civetweb.c 315 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049
  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(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. #ifndef IGNORE_UNUSED_RESULT
  103. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  104. #endif
  105. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <errno.h>
  109. #include <signal.h>
  110. #include <fcntl.h>
  111. #endif /* !_WIN32_WCE */
  112. #ifdef __MACH__
  113. #define CLOCK_MONOTONIC (1)
  114. #define CLOCK_REALTIME (2)
  115. #include <sys/time.h>
  116. #include <mach/clock.h>
  117. #include <mach/mach.h>
  118. #include <mach/mach_time.h>
  119. #include <assert.h>
  120. /* clock_gettime is not implemented on OSX */
  121. int clock_gettime(int clk_id, struct timespec *t);
  122. int
  123. clock_gettime(int clk_id, struct timespec *t)
  124. {
  125. memset(t, 0, sizeof(*t);
  126. if (clk_id == CLOCK_REALTIME) {
  127. struct timeval now;
  128. int rv = gettimeofday(&now, NULL);
  129. if (rv) {
  130. return rv;
  131. }
  132. t->tv_sec = now.tv_sec;
  133. t->tv_nsec = now.tv_usec * 1000;
  134. return 0;
  135. } else if (clk_id == CLOCK_MONOTONIC) {
  136. static uint64_t start_time = 0;
  137. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  138. uint64_t now = mach_absolute_time();
  139. if (start_time == 0) {
  140. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  141. #if defined(DEBUG)
  142. assert(mach_status == KERN_SUCCESS);
  143. #else
  144. /* appease "unused variable" warning for release builds */
  145. (void)mach_status;
  146. #endif
  147. start_time = now;
  148. }
  149. now = (uint64_t)((double)(now - start_time) * (double)timebase_ifo.numer
  150. / (double)timebase_ifo.denom);
  151. t->tv_sec = now / 1000000000;
  152. t->tv_nsec = now % 1000000000;
  153. return 0;
  154. }
  155. return -1; /* EINVAL - Clock ID is unknown */
  156. }
  157. #endif
  158. #include <time.h>
  159. #include <stdlib.h>
  160. #include <stdarg.h>
  161. #include <assert.h>
  162. #include <string.h>
  163. #include <ctype.h>
  164. #include <limits.h>
  165. #include <stddef.h>
  166. #include <stdio.h>
  167. #ifndef MAX_WORKER_THREADS
  168. #define MAX_WORKER_THREADS (1024 * 64)
  169. #endif
  170. #ifndef SOCKET_TIMEOUT_QUANTUM
  171. #define SOCKET_TIMEOUT_QUANTUM (10000)
  172. #endif
  173. mg_static_assert(MAX_WORKER_THREADS >= 1,
  174. "worker threads must be a positive number");
  175. #if defined(_WIN32) \
  176. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  177. #include <windows.h>
  178. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  179. #include <ws2tcpip.h>
  180. typedef const char *SOCK_OPT_TYPE;
  181. #if !defined(PATH_MAX)
  182. #define PATH_MAX (MAX_PATH)
  183. #endif
  184. #if !defined(PATH_MAX)
  185. #define PATH_MAX (4096)
  186. #endif
  187. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  188. #ifndef _IN_PORT_T
  189. #ifndef in_port_t
  190. #define in_port_t u_short
  191. #endif
  192. #endif
  193. #ifndef _WIN32_WCE
  194. #include <process.h>
  195. #include <direct.h>
  196. #include <io.h>
  197. #else /* _WIN32_WCE */
  198. #define NO_CGI /* WinCE has no pipes */
  199. typedef long off_t;
  200. #define errno ((int)(GetLastError()))
  201. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  202. #endif /* _WIN32_WCE */
  203. #define MAKEUQUAD(lo, hi) \
  204. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  205. #define RATE_DIFF (10000000) /* 100 nsecs */
  206. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  207. #define SYS2UNIX_TIME(lo, hi) \
  208. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  209. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  210. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  211. * Also use _strtoui64 on modern M$ compilers */
  212. #if defined(_MSC_VER)
  213. #if (_MSC_VER < 1300)
  214. #define STRX(x) #x
  215. #define STR(x) STRX(x)
  216. #define __func__ __FILE__ ":" STR(__LINE__)
  217. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  218. #define strtoll(x, y, z) (_atoi64(x))
  219. #else
  220. #define __func__ __FUNCTION__
  221. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  222. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  223. #endif
  224. #endif /* _MSC_VER */
  225. #define ERRNO ((int)(GetLastError()))
  226. #define NO_SOCKLEN_T
  227. #define SSL_LIB "ssleay32.dll"
  228. #define CRYPTO_LIB "libeay32.dll"
  229. #define O_NONBLOCK (0)
  230. #ifndef W_OK
  231. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  232. #endif
  233. #if !defined(EWOULDBLOCK)
  234. #define EWOULDBLOCK WSAEWOULDBLOCK
  235. #endif /* !EWOULDBLOCK */
  236. #define _POSIX_
  237. #define INT64_FMT "I64d"
  238. #define WINCDECL __cdecl
  239. #define SHUT_RD (0)
  240. #define SHUT_WR (1)
  241. #define SHUT_BOTH (2)
  242. #define vsnprintf_impl _vsnprintf
  243. #define access _access
  244. #define mg_sleep(x) (Sleep(x))
  245. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  246. #ifndef popen
  247. #define popen(x, y) (_popen(x, y))
  248. #endif
  249. #ifndef pclose
  250. #define pclose(x) (_pclose(x))
  251. #endif
  252. #define close(x) (_close(x))
  253. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  254. #define RTLD_LAZY (0)
  255. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  256. #define fdopen(x, y) (_fdopen((x), (y)))
  257. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  258. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  259. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  260. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  261. #define sleep(x) (Sleep((x)*1000))
  262. #define rmdir(x) (_rmdir(x))
  263. #if !defined(fileno)
  264. #define fileno(x) (_fileno(x))
  265. #endif /* !fileno MINGW #defines fileno */
  266. typedef HANDLE pthread_mutex_t;
  267. typedef DWORD pthread_key_t;
  268. typedef HANDLE pthread_t;
  269. typedef struct {
  270. CRITICAL_SECTION threadIdSec;
  271. int waitingthreadcount; /* The number of threads queued. */
  272. pthread_t *waitingthreadhdls; /* The thread handles. */
  273. } pthread_cond_t;
  274. #ifndef __clockid_t_defined
  275. typedef DWORD clockid_t;
  276. #endif
  277. #ifndef CLOCK_MONOTONIC
  278. #define CLOCK_MONOTONIC (1)
  279. #endif
  280. #ifndef CLOCK_REALTIME
  281. #define CLOCK_REALTIME (2)
  282. #endif
  283. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  284. #define _TIMESPEC_DEFINED
  285. #endif
  286. #ifndef _TIMESPEC_DEFINED
  287. struct timespec {
  288. time_t tv_sec; /* seconds */
  289. long tv_nsec; /* nanoseconds */
  290. };
  291. #endif
  292. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  293. static int pthread_mutex_lock(pthread_mutex_t *);
  294. static int pthread_mutex_unlock(pthread_mutex_t *);
  295. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  296. struct file;
  297. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  298. #if defined(HAVE_STDINT)
  299. #include <stdint.h>
  300. #else
  301. typedef unsigned char uint8_t;
  302. typedef unsigned short uint16_t;
  303. typedef unsigned int uint32_t;
  304. typedef unsigned __int64 uint64_t;
  305. typedef __int64 int64_t;
  306. #define INT64_MAX (9223372036854775807)
  307. #endif /* HAVE_STDINT */
  308. /* POSIX dirent interface */
  309. struct dirent {
  310. char d_name[PATH_MAX];
  311. };
  312. typedef struct DIR {
  313. HANDLE handle;
  314. WIN32_FIND_DATAW info;
  315. struct dirent result;
  316. } DIR;
  317. #if defined(_WIN32) && !defined(POLLIN)
  318. #ifndef HAVE_POLL
  319. struct pollfd {
  320. SOCKET fd;
  321. short events;
  322. short revents;
  323. };
  324. #define POLLIN (0x0300)
  325. #endif
  326. #endif
  327. /* Mark required libraries */
  328. #if defined(_MSC_VER)
  329. #pragma comment(lib, "Ws2_32.lib")
  330. #endif
  331. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  332. block */
  333. #include <sys/wait.h>
  334. #include <sys/socket.h>
  335. #include <sys/poll.h>
  336. #include <netinet/in.h>
  337. #include <arpa/inet.h>
  338. #include <sys/time.h>
  339. #include <sys/utsname.h>
  340. #include <stdint.h>
  341. #include <inttypes.h>
  342. #include <netdb.h>
  343. typedef const void *SOCK_OPT_TYPE;
  344. #if defined(ANDROID)
  345. typedef unsigned short int in_port_t;
  346. #endif
  347. #include <pwd.h>
  348. #include <unistd.h>
  349. #include <grp.h>
  350. #include <dirent.h>
  351. #define vsnprintf_impl vsnprintf
  352. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  353. #include <dlfcn.h>
  354. #endif
  355. #include <pthread.h>
  356. #if defined(__MACH__)
  357. #define SSL_LIB "libssl.dylib"
  358. #define CRYPTO_LIB "libcrypto.dylib"
  359. #else
  360. #if !defined(SSL_LIB)
  361. #define SSL_LIB "libssl.so"
  362. #endif
  363. #if !defined(CRYPTO_LIB)
  364. #define CRYPTO_LIB "libcrypto.so"
  365. #endif
  366. #endif
  367. #ifndef O_BINARY
  368. #define O_BINARY (0)
  369. #endif /* O_BINARY */
  370. #define closesocket(a) (close(a))
  371. #define mg_mkdir(x, y) (mkdir(x, y))
  372. #define mg_remove(x) (remove(x))
  373. #define mg_sleep(x) (usleep((x)*1000))
  374. #define ERRNO (errno)
  375. #define INVALID_SOCKET (-1)
  376. #define INT64_FMT PRId64
  377. typedef int SOCKET;
  378. #define WINCDECL
  379. #if defined(__hpux)
  380. /* HPUX 11 does not have monotonic, fall back to realtime */
  381. #ifndef CLOCK_MONOTONIC
  382. #define CLOCK_MONOTONIC CLOCK_REALTIME
  383. #endif
  384. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  385. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  386. * the prototypes use int* rather than socklen_t* which matches the
  387. * actual library expectation. When called with the wrong size arg
  388. * accept() returns a zero client inet addr and check_acl() always
  389. * fails. Since socklen_t is widely used below, just force replace
  390. * their typedef with int. - DTL
  391. */
  392. #define socklen_t int
  393. #endif /* hpux */
  394. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  395. block */
  396. /* va_copy should always be a macro, C99 and C++11 - DTL */
  397. #ifndef va_copy
  398. #define va_copy(x, y) ((x) = (y))
  399. #endif
  400. #ifdef _WIN32
  401. /* Create substitutes for POSIX functions in Win32. */
  402. #if defined(__MINGW32__)
  403. /* Show no warning in case system functions are not used. */
  404. #pragma GCC diagnostic push
  405. #pragma GCC diagnostic ignored "-Wunused-function"
  406. #endif
  407. static CRITICAL_SECTION global_log_file_lock;
  408. static DWORD
  409. pthread_self(void)
  410. {
  411. return GetCurrentThreadId();
  412. }
  413. static int
  414. pthread_key_create(
  415. pthread_key_t *key,
  416. void (*_ignored)(void *) /* destructor not supported for Windows */
  417. )
  418. {
  419. (void)_ignored;
  420. if ((key != 0)) {
  421. *key = TlsAlloc();
  422. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  423. }
  424. return -2;
  425. }
  426. static int
  427. pthread_key_delete(pthread_key_t key)
  428. {
  429. return TlsFree(key) ? 0 : 1;
  430. }
  431. static int
  432. pthread_setspecific(pthread_key_t key, void *value)
  433. {
  434. return TlsSetValue(key, value) ? 0 : 1;
  435. }
  436. static void *
  437. pthread_getspecific(pthread_key_t key)
  438. {
  439. return TlsGetValue(key);
  440. }
  441. #if defined(__MINGW32__)
  442. /* Enable unused function warning again */
  443. #pragma GCC diagnostic pop
  444. #endif
  445. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  446. #else
  447. static pthread_mutexattr_t pthread_mutex_attr;
  448. #endif /* _WIN32 */
  449. #include "civetweb.h"
  450. #define PASSWORDS_FILE_NAME ".htpasswd"
  451. #define CGI_ENVIRONMENT_SIZE (4096)
  452. #define MAX_CGI_ENVIR_VARS (256)
  453. #define MG_BUF_LEN (8192)
  454. #ifndef MAX_REQUEST_SIZE
  455. #define MAX_REQUEST_SIZE (16384)
  456. #endif
  457. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  458. "request size length must be a positive number");
  459. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  460. #if !defined(DEBUG_TRACE)
  461. #if defined(DEBUG)
  462. static void DEBUG_TRACE_FUNC(const char *func,
  463. unsigned line,
  464. PRINTF_FORMAT_STRING(const char *fmt),
  465. ...) PRINTF_ARGS(3, 4);
  466. static void
  467. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  468. {
  469. va_list args;
  470. flockfile(stdout);
  471. printf("*** %lu.%p.%s.%u: ",
  472. (unsigned long)time(NULL),
  473. (void *)pthread_self(),
  474. func,
  475. line);
  476. va_start(args, fmt);
  477. vprintf(fmt, args);
  478. va_end(args);
  479. putchar('\n');
  480. fflush(stdout);
  481. funlockfile(stdout);
  482. }
  483. #define DEBUG_TRACE(fmt, ...) \
  484. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  485. #else
  486. #define DEBUG_TRACE(fmt, ...) \
  487. do { \
  488. } while (0)
  489. #endif /* DEBUG */
  490. #endif /* DEBUG_TRACE */
  491. #if defined(MEMORY_DEBUGGING)
  492. unsigned long mg_memory_debug_blockCount = 0;
  493. unsigned long mg_memory_debug_totalMemUsed = 0;
  494. static void *
  495. mg_malloc_ex(size_t size, const char *file, unsigned line)
  496. {
  497. void *data = malloc(size + sizeof(size_t));
  498. void *memory = 0;
  499. char mallocStr[256];
  500. if (data) {
  501. *(size_t *)data = size;
  502. mg_memory_debug_totalMemUsed += size;
  503. mg_memory_debug_blockCount++;
  504. memory = (void *)(((char *)data) + sizeof(size_t));
  505. }
  506. sprintf(mallocStr,
  507. "MEM: %p %5lu alloc %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. return memory;
  520. }
  521. static void *
  522. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  523. {
  524. void *data = mg_malloc_ex(size * count, file, line);
  525. if (data) {
  526. memset(data, 0, size);
  527. }
  528. return data;
  529. }
  530. static void
  531. mg_free_ex(void *memory, const char *file, unsigned line)
  532. {
  533. char mallocStr[256];
  534. void *data = (void *)(((char *)memory) - sizeof(size_t));
  535. size_t size;
  536. if (memory) {
  537. size = *(size_t *)data;
  538. mg_memory_debug_totalMemUsed -= size;
  539. mg_memory_debug_blockCount--;
  540. sprintf(mallocStr,
  541. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  542. memory,
  543. (unsigned long)size,
  544. mg_memory_debug_totalMemUsed,
  545. mg_memory_debug_blockCount,
  546. file,
  547. line);
  548. #if defined(_WIN32)
  549. OutputDebugStringA(mallocStr);
  550. #else
  551. DEBUG_TRACE("%s", mallocStr);
  552. #endif
  553. free(data);
  554. }
  555. }
  556. static void *
  557. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  558. {
  559. char mallocStr[256];
  560. void *data;
  561. void *_realloc;
  562. size_t oldsize;
  563. if (newsize) {
  564. if (memory) {
  565. data = (void *)(((char *)memory) - sizeof(size_t));
  566. oldsize = *(size_t *)data;
  567. _realloc = realloc(data, newsize + sizeof(size_t));
  568. if (_realloc) {
  569. data = _realloc;
  570. mg_memory_debug_totalMemUsed -= oldsize;
  571. sprintf(mallocStr,
  572. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  573. memory,
  574. (unsigned long)oldsize,
  575. mg_memory_debug_totalMemUsed,
  576. mg_memory_debug_blockCount,
  577. file,
  578. line);
  579. #if defined(_WIN32)
  580. OutputDebugStringA(mallocStr);
  581. #else
  582. DEBUG_TRACE("%s", mallocStr);
  583. #endif
  584. mg_memory_debug_totalMemUsed += newsize;
  585. sprintf(mallocStr,
  586. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  587. memory,
  588. (unsigned long)newsize,
  589. mg_memory_debug_totalMemUsed,
  590. mg_memory_debug_blockCount,
  591. file,
  592. line);
  593. #if defined(_WIN32)
  594. OutputDebugStringA(mallocStr);
  595. #else
  596. DEBUG_TRACE("%s", mallocStr);
  597. #endif
  598. *(size_t *)data = newsize;
  599. data = (void *)(((char *)data) + sizeof(size_t));
  600. } else {
  601. #if defined(_WIN32)
  602. OutputDebugStringA("MEM: realloc failed\n");
  603. #else
  604. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  605. #endif
  606. return _realloc;
  607. }
  608. } else {
  609. data = mg_malloc_ex(newsize, file, line);
  610. }
  611. } else {
  612. data = 0;
  613. mg_free_ex(memory, file, line);
  614. }
  615. return data;
  616. }
  617. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  618. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  619. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  620. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  621. #else
  622. static __inline void *
  623. mg_malloc(size_t a)
  624. {
  625. return malloc(a);
  626. }
  627. static __inline void *
  628. mg_calloc(size_t a, size_t b)
  629. {
  630. return calloc(a, b);
  631. }
  632. static __inline void *
  633. mg_realloc(void *a, size_t b)
  634. {
  635. return realloc(a, b);
  636. }
  637. static __inline void
  638. mg_free(void *a)
  639. {
  640. free(a);
  641. }
  642. #endif
  643. static void mg_vsnprintf(const struct mg_connection *conn,
  644. int *truncated,
  645. char *buf,
  646. size_t buflen,
  647. const char *fmt,
  648. va_list ap);
  649. static void mg_snprintf(const struct mg_connection *conn,
  650. int *truncated,
  651. char *buf,
  652. size_t buflen,
  653. PRINTF_FORMAT_STRING(const char *fmt),
  654. ...) PRINTF_ARGS(5, 6);
  655. /* This following lines are just meant as a reminder to use the mg-functions
  656. * for memory management */
  657. #ifdef malloc
  658. #undef malloc
  659. #endif
  660. #ifdef calloc
  661. #undef calloc
  662. #endif
  663. #ifdef realloc
  664. #undef realloc
  665. #endif
  666. #ifdef free
  667. #undef free
  668. #endif
  669. #ifdef snprintf
  670. #undef snprintf
  671. #endif
  672. #ifdef vsnprintf
  673. #undef vsnprintf
  674. #endif
  675. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  676. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  677. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  678. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  679. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  680. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  681. * but this define only works well for Windows. */
  682. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  683. #endif
  684. #define MD5_STATIC static
  685. #include "md5.inl"
  686. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  687. #ifdef NO_SOCKLEN_T
  688. typedef int socklen_t;
  689. #endif /* NO_SOCKLEN_T */
  690. #define _DARWIN_UNLIMITED_SELECT
  691. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  692. #if !defined(MSG_NOSIGNAL)
  693. #define MSG_NOSIGNAL (0)
  694. #endif
  695. #if !defined(SOMAXCONN)
  696. #define SOMAXCONN (100)
  697. #endif
  698. /* Size of the accepted socket queue */
  699. #if !defined(MGSQLEN)
  700. #define MGSQLEN (20)
  701. #endif
  702. #if defined(NO_SSL_DL)
  703. #include <openssl/ssl.h>
  704. #include <openssl/err.h>
  705. #include <openssl/crypto.h>
  706. #include <openssl/x509.h>
  707. #include <openssl/pem.h>
  708. #else
  709. /* SSL loaded dynamically from DLL.
  710. * I put the prototypes here to be independent from OpenSSL source
  711. * installation. */
  712. typedef struct ssl_st SSL;
  713. typedef struct ssl_method_st SSL_METHOD;
  714. typedef struct ssl_ctx_st SSL_CTX;
  715. typedef struct x509_store_ctx_st X509_STORE_CTX;
  716. #define SSL_VERIFY_NONE (0)
  717. #define SSL_VERIFY_PEER (1)
  718. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  719. #define SSL_VERIFY_CLIENT_ONCE (4)
  720. struct ssl_func {
  721. const char *name; /* SSL function name */
  722. void (*ptr)(void); /* Function pointer */
  723. };
  724. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  725. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  726. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  727. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  728. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  729. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  730. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  731. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  732. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  733. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  734. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  735. #define SSL_CTX_use_PrivateKey_file \
  736. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  737. #define SSL_CTX_use_certificate_file \
  738. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  739. #define SSL_CTX_set_default_passwd_cb \
  740. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  741. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  742. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  743. #define SSL_CTX_use_certificate_chain_file \
  744. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  745. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  746. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  747. #define SSL_CTX_set_verify \
  748. (*(void (*)(SSL_CTX *, \
  749. int, \
  750. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  751. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  752. #define SSL_CTX_load_verify_locations \
  753. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  754. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  755. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  756. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  757. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  758. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  759. #define SSL_CIPHER_get_name \
  760. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  761. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  762. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  763. #define CRYPTO_set_locking_callback \
  764. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  765. #define CRYPTO_set_id_callback \
  766. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  767. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  768. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  769. /* set_ssl_option() function updates this array.
  770. * It loads SSL library dynamically and changes NULLs to the actual addresses
  771. * of respective functions. The macros above (like SSL_connect()) are really
  772. * just calling these functions indirectly via the pointer. */
  773. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  774. {"SSL_accept", NULL},
  775. {"SSL_connect", NULL},
  776. {"SSL_read", NULL},
  777. {"SSL_write", NULL},
  778. {"SSL_get_error", NULL},
  779. {"SSL_set_fd", NULL},
  780. {"SSL_new", NULL},
  781. {"SSL_CTX_new", NULL},
  782. {"SSLv23_server_method", NULL},
  783. {"SSL_library_init", NULL},
  784. {"SSL_CTX_use_PrivateKey_file", NULL},
  785. {"SSL_CTX_use_certificate_file", NULL},
  786. {"SSL_CTX_set_default_passwd_cb", NULL},
  787. {"SSL_CTX_free", NULL},
  788. {"SSL_load_error_strings", NULL},
  789. {"SSL_CTX_use_certificate_chain_file", NULL},
  790. {"SSLv23_client_method", NULL},
  791. {"SSL_pending", NULL},
  792. {"SSL_CTX_set_verify", NULL},
  793. {"SSL_shutdown", NULL},
  794. {"SSL_CTX_load_verify_locations", NULL},
  795. {"SSL_CTX_set_default_verify_paths", NULL},
  796. {"SSL_CTX_set_verify_depth", NULL},
  797. {"SSL_get_peer_certificate", NULL},
  798. {"SSL_get_version", NULL},
  799. {"SSL_get_current_cipher", NULL},
  800. {"SSL_CIPHER_get_name", NULL},
  801. {"SSL_CTX_check_private_key", NULL},
  802. {NULL, NULL}};
  803. /* Similar array as ssl_sw. These functions could be located in different
  804. * lib. */
  805. #if !defined(NO_SSL)
  806. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  807. {"CRYPTO_set_locking_callback", NULL},
  808. {"CRYPTO_set_id_callback", NULL},
  809. {"ERR_get_error", NULL},
  810. {"ERR_error_string", NULL},
  811. {NULL, NULL}};
  812. #endif /* NO_SSL */
  813. #endif /* NO_SSL_DL */
  814. static const char *month_names[] = {"Jan",
  815. "Feb",
  816. "Mar",
  817. "Apr",
  818. "May",
  819. "Jun",
  820. "Jul",
  821. "Aug",
  822. "Sep",
  823. "Oct",
  824. "Nov",
  825. "Dec"};
  826. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  827. * union u. */
  828. union usa {
  829. struct sockaddr sa;
  830. struct sockaddr_in sin;
  831. #if defined(USE_IPV6)
  832. struct sockaddr_in6 sin6;
  833. #endif
  834. };
  835. /* Describes a string (chunk of memory). */
  836. struct vec {
  837. const char *ptr;
  838. size_t len;
  839. };
  840. struct file {
  841. uint64_t size;
  842. time_t last_modified;
  843. FILE *fp;
  844. const char *membuf; /* Non-NULL if file data is in memory */
  845. int is_directory;
  846. int gzipped; /* set to 1 if the content is gzipped
  847. * in which case we need a content-encoding: gzip header */
  848. };
  849. #define STRUCT_FILE_INITIALIZER \
  850. { \
  851. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  852. }
  853. /* Describes listening socket, or socket which was accept()-ed by the master
  854. * thread and queued for future handling by the worker thread. */
  855. struct socket {
  856. SOCKET sock; /* Listening socket */
  857. union usa lsa; /* Local socket address */
  858. union usa rsa; /* Remote socket address */
  859. unsigned char is_ssl; /* Is port SSL-ed */
  860. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  861. * port */
  862. };
  863. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  864. enum {
  865. CGI_EXTENSIONS,
  866. CGI_ENVIRONMENT,
  867. PUT_DELETE_PASSWORDS_FILE,
  868. CGI_INTERPRETER,
  869. PROTECT_URI,
  870. AUTHENTICATION_DOMAIN,
  871. SSI_EXTENSIONS,
  872. THROTTLE,
  873. ACCESS_LOG_FILE,
  874. ENABLE_DIRECTORY_LISTING,
  875. ERROR_LOG_FILE,
  876. GLOBAL_PASSWORDS_FILE,
  877. INDEX_FILES,
  878. ENABLE_KEEP_ALIVE,
  879. ACCESS_CONTROL_LIST,
  880. EXTRA_MIME_TYPES,
  881. LISTENING_PORTS,
  882. DOCUMENT_ROOT,
  883. SSL_CERTIFICATE,
  884. NUM_THREADS,
  885. RUN_AS_USER,
  886. REWRITE,
  887. HIDE_FILES,
  888. REQUEST_TIMEOUT,
  889. SSL_DO_VERIFY_PEER,
  890. SSL_CA_PATH,
  891. SSL_CA_FILE,
  892. SSL_VERIFY_DEPTH,
  893. SSL_DEFAULT_VERIFY_PATHS,
  894. SSL_FORWARD_SECRECY,
  895. #if defined(USE_WEBSOCKET)
  896. WEBSOCKET_TIMEOUT,
  897. #endif
  898. DECODE_URL,
  899. #if defined(USE_LUA)
  900. LUA_PRELOAD_FILE,
  901. LUA_SCRIPT_EXTENSIONS,
  902. LUA_SERVER_PAGE_EXTENSIONS,
  903. #endif
  904. #if defined(USE_DUKTAPE)
  905. DUKTAPE_SCRIPT_EXTENSIONS,
  906. #endif
  907. #if defined(USE_WEBSOCKET)
  908. WEBSOCKET_ROOT,
  909. #endif
  910. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  911. LUA_WEBSOCKET_EXTENSIONS,
  912. #endif
  913. ACCESS_CONTROL_ALLOW_ORIGIN,
  914. ERROR_PAGES,
  915. NUM_OPTIONS
  916. };
  917. /* Config option name, config types, default value */
  918. static struct mg_option config_options[] = {
  919. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  920. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  921. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  922. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  923. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  924. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  925. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  926. {"throttle", CONFIG_TYPE_STRING, NULL},
  927. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  928. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  929. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  930. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  931. {"index_files",
  932. CONFIG_TYPE_STRING,
  933. #ifdef USE_LUA
  934. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  935. "index.shtml,index.php"},
  936. #else
  937. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  938. #endif
  939. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  940. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  941. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  942. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  943. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  944. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  945. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  946. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  947. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  948. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  949. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  950. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  951. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  952. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  953. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  954. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  955. {"ssl_forward_secrecy", CONFIG_TYPE_BOOLEAN, "yes"},
  956. #if defined(USE_WEBSOCKET)
  957. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  958. #endif
  959. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  960. #if defined(USE_LUA)
  961. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  962. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  963. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  964. #endif
  965. #if defined(USE_DUKTAPE)
  966. {"_experimental_duktape_script_pattern",
  967. CONFIG_TYPE_EXT_PATTERN,
  968. "**.ssjs$"}, /* TODO: redefine parameter */
  969. #endif
  970. #if defined(USE_WEBSOCKET)
  971. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  972. #endif
  973. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  974. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  975. #endif
  976. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  977. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  978. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  979. /* Check if the config_options and the corresponding enum have compatible
  980. * sizes. */
  981. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  982. == (NUM_OPTIONS + 1),
  983. "config_options and enum not sync");
  984. struct mg_request_handler_info {
  985. /* Name/Pattern of the URI. */
  986. char *uri;
  987. size_t uri_len;
  988. /* URI type: ws/wss (websocket) or http/https (web page). */
  989. int is_websocket_handler;
  990. /* Handler for http/https requests. */
  991. mg_request_handler handler;
  992. /* Handler for ws/wss (websocket) requests. */
  993. mg_websocket_connect_handler connect_handler;
  994. mg_websocket_ready_handler ready_handler;
  995. mg_websocket_data_handler data_handler;
  996. mg_websocket_close_handler close_handler;
  997. /* User supplied argument for the handler function. */
  998. void *cbdata;
  999. /* next request handler in a linked list */
  1000. struct mg_request_handler_info *next;
  1001. };
  1002. struct mg_context {
  1003. volatile int stop_flag; /* Should we stop event loop */
  1004. SSL_CTX *ssl_ctx; /* SSL context */
  1005. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1006. struct mg_callbacks callbacks; /* User-defined callback function */
  1007. void *user_data; /* User-defined data */
  1008. int context_type; /* 1 = server context, 2 = client context */
  1009. struct socket *listening_sockets;
  1010. in_port_t *listening_ports;
  1011. unsigned int num_listening_sockets;
  1012. volatile int
  1013. running_worker_threads; /* Number of currently running worker threads */
  1014. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1015. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1016. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1017. volatile int sq_head; /* Head of the socket queue */
  1018. volatile int sq_tail; /* Tail of the socket queue */
  1019. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1020. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1021. pthread_t masterthreadid; /* The master thread ID */
  1022. unsigned int
  1023. cfg_worker_threads; /* The number of configured worker threads. */
  1024. pthread_t *workerthreadids; /* The worker thread IDs */
  1025. unsigned long start_time; /* Server start time, used for authentication */
  1026. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1027. unsigned long nonce_count; /* Used nonces, used for authentication */
  1028. char *systemName; /* What operating system is running */
  1029. /* linked list of uri handlers */
  1030. struct mg_request_handler_info *request_handlers;
  1031. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1032. /* linked list of shared lua websockets */
  1033. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1034. #endif
  1035. #ifdef USE_TIMERS
  1036. struct ttimers *timers;
  1037. #endif
  1038. };
  1039. struct mg_connection {
  1040. struct mg_request_info request_info;
  1041. struct mg_context *ctx;
  1042. SSL *ssl; /* SSL descriptor */
  1043. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1044. struct socket client; /* Connected client */
  1045. time_t conn_birth_time; /* Time (wall clock) when connection was
  1046. * established */
  1047. struct timespec req_time; /* Time (since system start) when the request
  1048. * was received */
  1049. int64_t num_bytes_sent; /* Total bytes sent to client */
  1050. int64_t content_len; /* Content-Length header value */
  1051. int64_t consumed_content; /* How many bytes of content have been read */
  1052. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1053. * data available, 2: all data read */
  1054. size_t chunk_remainder; /* Unread data from the last chunk */
  1055. char *buf; /* Buffer for received data */
  1056. char *path_info; /* PATH_INFO part of the URL */
  1057. int must_close; /* 1 if connection must be closed */
  1058. int in_error_handler; /* 1 if in handler for user defined error
  1059. * pages */
  1060. int internal_error; /* 1 if an error occured while processing the
  1061. * request */
  1062. int buf_size; /* Buffer size */
  1063. int request_len; /* Size of the request + headers in a buffer */
  1064. int data_len; /* Total size of data in a buffer */
  1065. int status_code; /* HTTP reply status code, e.g. 200 */
  1066. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1067. * throttle */
  1068. time_t last_throttle_time; /* Last time throttled data was sent */
  1069. int64_t last_throttle_bytes; /* Bytes sent this second */
  1070. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1071. * atomic transmissions for websockets */
  1072. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1073. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1074. #endif
  1075. };
  1076. static pthread_key_t sTlsKey; /* Thread local storage index */
  1077. static int sTlsInit = 0;
  1078. static int thread_idx_max = 0;
  1079. struct mg_workerTLS {
  1080. int is_master;
  1081. unsigned long thread_idx;
  1082. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1083. HANDLE pthread_cond_helper_mutex;
  1084. #endif
  1085. };
  1086. /* Directory entry */
  1087. struct de {
  1088. struct mg_connection *conn;
  1089. char *file_name;
  1090. struct file file;
  1091. };
  1092. #if defined(USE_WEBSOCKET)
  1093. static int is_websocket_protocol(const struct mg_connection *conn);
  1094. #else
  1095. #define is_websocket_protocol(conn) (0)
  1096. #endif
  1097. static int
  1098. mg_atomic_inc(volatile int *addr)
  1099. {
  1100. int ret;
  1101. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1102. /* Depending on the SDK, this function uses either
  1103. * (volatile unsigned int *) or (volatile LONG *),
  1104. * so whatever you use, the other SDK is likely to raise a warning. */
  1105. ret = InterlockedIncrement((volatile long *)addr);
  1106. #elif defined(__GNUC__)
  1107. ret = __sync_add_and_fetch(addr, 1);
  1108. #else
  1109. ret = (++(*addr));
  1110. #endif
  1111. return ret;
  1112. }
  1113. static int
  1114. mg_atomic_dec(volatile int *addr)
  1115. {
  1116. int ret;
  1117. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1118. /* Depending on the SDK, this function uses either
  1119. * (volatile unsigned int *) or (volatile LONG *),
  1120. * so whatever you use, the other SDK is likely to raise a warning. */
  1121. ret = InterlockedDecrement((volatile long *)addr);
  1122. #elif defined(__GNUC__)
  1123. ret = __sync_sub_and_fetch(addr, 1);
  1124. #else
  1125. ret = (--(*addr));
  1126. #endif
  1127. return ret;
  1128. }
  1129. #if !defined(NO_THREAD_NAME)
  1130. #if defined(_WIN32) && defined(_MSC_VER)
  1131. /* Set the thread name for debugging purposes in Visual Studio
  1132. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1133. */
  1134. #pragma pack(push, 8)
  1135. typedef struct tagTHREADNAME_INFO {
  1136. DWORD dwType; /* Must be 0x1000. */
  1137. LPCSTR szName; /* Pointer to name (in user addr space). */
  1138. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1139. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1140. } THREADNAME_INFO;
  1141. #pragma pack(pop)
  1142. #elif defined(__linux__)
  1143. #include <sys/prctl.h>
  1144. #include <sys/sendfile.h>
  1145. #endif
  1146. static void
  1147. mg_set_thread_name(const char *name)
  1148. {
  1149. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1150. mg_snprintf(
  1151. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1152. #if defined(_WIN32)
  1153. #if defined(_MSC_VER)
  1154. /* Windows and Visual Studio Compiler */
  1155. __try
  1156. {
  1157. THREADNAME_INFO info;
  1158. info.dwType = 0x1000;
  1159. info.szName = threadName;
  1160. info.dwThreadID = ~0U;
  1161. info.dwFlags = 0;
  1162. RaiseException(0x406D1388,
  1163. 0,
  1164. sizeof(info) / sizeof(ULONG_PTR),
  1165. (ULONG_PTR *)&info);
  1166. }
  1167. __except(EXCEPTION_EXECUTE_HANDLER)
  1168. {
  1169. }
  1170. #elif defined(__MINGW32__)
  1171. /* No option known to set thread name for MinGW */
  1172. #endif
  1173. #elif defined(__GLIBC__) \
  1174. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1175. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1176. (void)pthread_setname_np(pthread_self(), threadName);
  1177. #elif defined(__linux__)
  1178. /* on linux we can use the old prctl function */
  1179. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1180. #endif
  1181. }
  1182. #else /* !defined(NO_THREAD_NAME) */
  1183. void
  1184. mg_set_thread_name(const char *threadName)
  1185. {
  1186. }
  1187. #endif
  1188. #if defined(MG_LEGACY_INTERFACE)
  1189. const char **
  1190. mg_get_valid_option_names(void)
  1191. {
  1192. /* This function is deprecated. Use mg_get_valid_options instead. */
  1193. static const char *
  1194. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1195. int i;
  1196. for (i = 0; config_options[i].name != NULL; i++) {
  1197. data[i * 2] = config_options[i].name;
  1198. data[i * 2 + 1] = config_options[i].default_value;
  1199. }
  1200. return data;
  1201. }
  1202. #endif
  1203. const struct mg_option *
  1204. mg_get_valid_options(void)
  1205. {
  1206. return config_options;
  1207. }
  1208. static int
  1209. is_file_in_memory(struct mg_connection *conn,
  1210. const char *path,
  1211. struct file *filep)
  1212. {
  1213. size_t size = 0;
  1214. if (!conn || !filep) {
  1215. return 0;
  1216. }
  1217. if (conn->ctx->callbacks.open_file) {
  1218. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1219. if (filep->membuf != NULL) {
  1220. /* NOTE: override filep->size only on success. Otherwise, it might
  1221. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1222. filep->size = size;
  1223. }
  1224. }
  1225. return filep->membuf != NULL;
  1226. }
  1227. static int
  1228. is_file_opened(const struct file *filep)
  1229. {
  1230. if (!filep) {
  1231. return 0;
  1232. }
  1233. return filep->membuf != NULL || filep->fp != NULL;
  1234. }
  1235. static int
  1236. mg_fopen(struct mg_connection *conn,
  1237. const char *path,
  1238. const char *mode,
  1239. struct file *filep)
  1240. {
  1241. if (!filep) {
  1242. return 0;
  1243. }
  1244. memset(filep, 0, sizeof(*filep));
  1245. if (!is_file_in_memory(conn, path, filep)) {
  1246. #ifdef _WIN32
  1247. wchar_t wbuf[PATH_MAX], wmode[20];
  1248. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1249. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1250. filep->fp = _wfopen(wbuf, wmode);
  1251. #else
  1252. filep->fp = fopen(path, mode);
  1253. #endif
  1254. }
  1255. return is_file_opened(filep);
  1256. }
  1257. static void
  1258. mg_fclose(struct file *filep)
  1259. {
  1260. if (filep != NULL && filep->fp != NULL) {
  1261. fclose(filep->fp);
  1262. }
  1263. }
  1264. static void
  1265. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1266. {
  1267. for (; *src != '\0' && n > 1; n--) {
  1268. *dst++ = *src++;
  1269. }
  1270. *dst = '\0';
  1271. }
  1272. static int
  1273. lowercase(const char *s)
  1274. {
  1275. return tolower(*(const unsigned char *)s);
  1276. }
  1277. int
  1278. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1279. {
  1280. int diff = 0;
  1281. if (len > 0) {
  1282. do {
  1283. diff = lowercase(s1++) - lowercase(s2++);
  1284. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1285. }
  1286. return diff;
  1287. }
  1288. static int
  1289. mg_strcasecmp(const char *s1, const char *s2)
  1290. {
  1291. int diff;
  1292. do {
  1293. diff = lowercase(s1++) - lowercase(s2++);
  1294. } while (diff == 0 && s1[-1] != '\0');
  1295. return diff;
  1296. }
  1297. static char *
  1298. mg_strndup(const char *ptr, size_t len)
  1299. {
  1300. char *p;
  1301. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1302. mg_strlcpy(p, ptr, len + 1);
  1303. }
  1304. return p;
  1305. }
  1306. static char *
  1307. mg_strdup(const char *str)
  1308. {
  1309. return mg_strndup(str, strlen(str));
  1310. }
  1311. static const char *
  1312. mg_strcasestr(const char *big_str, const char *small_str)
  1313. {
  1314. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1315. if (big_len >= small_len) {
  1316. for (i = 0; i <= (big_len - small_len); i++) {
  1317. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1318. return big_str + i;
  1319. }
  1320. }
  1321. }
  1322. return NULL;
  1323. }
  1324. /* Return null terminated string of given maximum length.
  1325. * Report errors if length is exceeded. */
  1326. static void
  1327. mg_vsnprintf(const struct mg_connection *conn,
  1328. int *truncated,
  1329. char *buf,
  1330. size_t buflen,
  1331. const char *fmt,
  1332. va_list ap)
  1333. {
  1334. int n, ok;
  1335. if (buflen == 0) {
  1336. return;
  1337. }
  1338. #ifdef __clang__
  1339. #pragma clang diagnostic push
  1340. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1341. /* Using fmt as a non-literal is intended here, since it is mostly called
  1342. * indirectly by mg_snprintf */
  1343. #endif
  1344. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1345. ok = (n >= 0) && ((size_t)n < buflen);
  1346. #ifdef __clang__
  1347. #pragma clang diagnostic pop
  1348. #endif
  1349. if (ok) {
  1350. if (truncated) {
  1351. *truncated = 0;
  1352. }
  1353. } else {
  1354. if (truncated) {
  1355. *truncated = 1;
  1356. }
  1357. mg_cry(conn,
  1358. "truncating vsnprintf buffer: [%.*s]",
  1359. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1360. buf);
  1361. n = (int)buflen - 1;
  1362. }
  1363. buf[n] = '\0';
  1364. }
  1365. static void
  1366. mg_snprintf(const struct mg_connection *conn,
  1367. int *truncated,
  1368. char *buf,
  1369. size_t buflen,
  1370. const char *fmt,
  1371. ...)
  1372. {
  1373. va_list ap;
  1374. va_start(ap, fmt);
  1375. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1376. va_end(ap);
  1377. }
  1378. static int
  1379. get_option_index(const char *name)
  1380. {
  1381. int i;
  1382. for (i = 0; config_options[i].name != NULL; i++) {
  1383. if (strcmp(config_options[i].name, name) == 0) {
  1384. return i;
  1385. }
  1386. }
  1387. return -1;
  1388. }
  1389. const char *
  1390. mg_get_option(const struct mg_context *ctx, const char *name)
  1391. {
  1392. int i;
  1393. if ((i = get_option_index(name)) == -1) {
  1394. return NULL;
  1395. } else if (!ctx || ctx->config[i] == NULL) {
  1396. return "";
  1397. } else {
  1398. return ctx->config[i];
  1399. }
  1400. }
  1401. struct mg_context *
  1402. mg_get_context(const struct mg_connection *conn)
  1403. {
  1404. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1405. }
  1406. void *
  1407. mg_get_user_data(const struct mg_context *ctx)
  1408. {
  1409. return (ctx == NULL) ? NULL : ctx->user_data;
  1410. }
  1411. void
  1412. mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1413. {
  1414. if (conn != NULL) {
  1415. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1416. }
  1417. }
  1418. void *
  1419. mg_get_user_connection_data(const struct mg_connection *conn)
  1420. {
  1421. if (conn != NULL) {
  1422. return conn->request_info.conn_data;
  1423. }
  1424. return NULL;
  1425. }
  1426. size_t
  1427. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1428. {
  1429. size_t i;
  1430. if (!ctx) {
  1431. return 0;
  1432. }
  1433. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1434. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1435. ports[i] = ctx->listening_ports[i];
  1436. }
  1437. return i;
  1438. }
  1439. int
  1440. mg_get_server_ports(const struct mg_context *ctx,
  1441. int size,
  1442. struct mg_server_ports *ports)
  1443. {
  1444. int i, cnt = 0;
  1445. if (size <= 0) {
  1446. return -1;
  1447. }
  1448. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1449. if (!ctx) {
  1450. return -1;
  1451. }
  1452. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1453. return -1;
  1454. }
  1455. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1456. ports[cnt].port = ctx->listening_ports[i];
  1457. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1458. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1459. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1460. /* IPv4 */
  1461. ports[cnt].protocol = 1;
  1462. cnt++;
  1463. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1464. /* IPv6 */
  1465. ports[cnt].protocol = 3;
  1466. cnt++;
  1467. }
  1468. }
  1469. return cnt;
  1470. }
  1471. static void
  1472. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1473. {
  1474. buf[0] = '\0';
  1475. if (!usa) {
  1476. return;
  1477. }
  1478. if (usa->sa.sa_family == AF_INET) {
  1479. getnameinfo(&usa->sa,
  1480. sizeof(usa->sin),
  1481. buf,
  1482. (unsigned)len,
  1483. NULL,
  1484. 0,
  1485. NI_NUMERICHOST);
  1486. }
  1487. #if defined(USE_IPV6)
  1488. else if (usa->sa.sa_family == AF_INET6) {
  1489. getnameinfo(&usa->sa,
  1490. sizeof(usa->sin6),
  1491. buf,
  1492. (unsigned)len,
  1493. NULL,
  1494. 0,
  1495. NI_NUMERICHOST);
  1496. }
  1497. #endif
  1498. }
  1499. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1500. * included in all responses other than 100, 101, 5xx. */
  1501. static void
  1502. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1503. {
  1504. struct tm *tm;
  1505. tm = gmtime(t);
  1506. if (tm != NULL) {
  1507. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1508. } else {
  1509. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1510. buf[buf_len - 1] = '\0';
  1511. }
  1512. }
  1513. /* difftime for struct timespec. Return value is in seconds. */
  1514. static double
  1515. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1516. {
  1517. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1518. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1519. }
  1520. /* Print error message to the opened error log stream. */
  1521. void
  1522. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1523. {
  1524. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1525. va_list ap;
  1526. FILE *fp;
  1527. time_t timestamp;
  1528. va_start(ap, fmt);
  1529. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1530. va_end(ap);
  1531. buf[sizeof(buf) - 1] = 0;
  1532. /* Do not lock when getting the callback value, here and below.
  1533. * I suppose this is fine, since function cannot disappear in the
  1534. * same way string option can. */
  1535. if (conn && (conn->ctx->callbacks.log_message == NULL
  1536. || conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1537. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1538. ? NULL
  1539. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1540. if (fp != NULL) {
  1541. flockfile(fp);
  1542. timestamp = time(NULL);
  1543. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1544. fprintf(fp,
  1545. "[%010lu] [error] [client %s] ",
  1546. (unsigned long)timestamp,
  1547. src_addr);
  1548. if (conn->request_info.request_method != NULL) {
  1549. fprintf(fp,
  1550. "%s %s: ",
  1551. conn->request_info.request_method,
  1552. conn->request_info.request_uri);
  1553. }
  1554. fprintf(fp, "%s", buf);
  1555. fputc('\n', fp);
  1556. funlockfile(fp);
  1557. fclose(fp);
  1558. }
  1559. }
  1560. }
  1561. /* Return fake connection structure. Used for logging, if connection
  1562. * is not applicable at the moment of logging. */
  1563. static struct mg_connection *
  1564. fc(struct mg_context *ctx)
  1565. {
  1566. static struct mg_connection fake_connection;
  1567. fake_connection.ctx = ctx;
  1568. return &fake_connection;
  1569. }
  1570. const char *
  1571. mg_version(void)
  1572. {
  1573. return CIVETWEB_VERSION;
  1574. }
  1575. const struct mg_request_info *
  1576. mg_get_request_info(const struct mg_connection *conn)
  1577. {
  1578. if (!conn) {
  1579. return NULL;
  1580. }
  1581. return &conn->request_info;
  1582. }
  1583. /* Skip the characters until one of the delimiters characters found.
  1584. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1585. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1586. * Delimiters can be quoted with quotechar. */
  1587. static char *
  1588. skip_quoted(char **buf,
  1589. const char *delimiters,
  1590. const char *whitespace,
  1591. char quotechar)
  1592. {
  1593. char *p, *begin_word, *end_word, *end_whitespace;
  1594. begin_word = *buf;
  1595. end_word = begin_word + strcspn(begin_word, delimiters);
  1596. /* Check for quotechar */
  1597. if (end_word > begin_word) {
  1598. p = end_word - 1;
  1599. while (*p == quotechar) {
  1600. /* TODO (bel, low): it seems this code is never reached, so
  1601. * quotechar is actually not needed - check if this code may be
  1602. * droped */
  1603. /* If there is anything beyond end_word, copy it */
  1604. if (*end_word == '\0') {
  1605. *p = '\0';
  1606. break;
  1607. } else {
  1608. size_t end_off = strcspn(end_word + 1, delimiters);
  1609. memmove(p, end_word, end_off + 1);
  1610. p += end_off; /* p must correspond to end_word - 1 */
  1611. end_word += end_off + 1;
  1612. }
  1613. }
  1614. for (p++; p < end_word; p++) {
  1615. *p = '\0';
  1616. }
  1617. }
  1618. if (*end_word == '\0') {
  1619. *buf = end_word;
  1620. } else {
  1621. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1622. for (p = end_word; p < end_whitespace; p++) {
  1623. *p = '\0';
  1624. }
  1625. *buf = end_whitespace;
  1626. }
  1627. return begin_word;
  1628. }
  1629. /* Simplified version of skip_quoted without quote char
  1630. * and whitespace == delimiters */
  1631. static char *
  1632. skip(char **buf, const char *delimiters)
  1633. {
  1634. return skip_quoted(buf, delimiters, delimiters, 0);
  1635. }
  1636. /* Return HTTP header value, or NULL if not found. */
  1637. static const char *
  1638. get_header(const struct mg_request_info *ri, const char *name)
  1639. {
  1640. int i;
  1641. if (ri) {
  1642. for (i = 0; i < ri->num_headers; i++) {
  1643. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1644. return ri->http_headers[i].value;
  1645. }
  1646. }
  1647. }
  1648. return NULL;
  1649. }
  1650. const char *
  1651. mg_get_header(const struct mg_connection *conn, const char *name)
  1652. {
  1653. if (!conn) {
  1654. return NULL;
  1655. }
  1656. return get_header(&conn->request_info, name);
  1657. }
  1658. /* A helper function for traversing a comma separated list of values.
  1659. * It returns a list pointer shifted to the next value, or NULL if the end
  1660. * of the list found.
  1661. * Value is stored in val vector. If value has form "x=y", then eq_val
  1662. * vector is initialized to point to the "y" part, and val vector length
  1663. * is adjusted to point only to "x". */
  1664. static const char *
  1665. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1666. {
  1667. if (val == NULL || list == NULL || *list == '\0') {
  1668. /* End of the list */
  1669. list = NULL;
  1670. } else {
  1671. val->ptr = list;
  1672. if ((list = strchr(val->ptr, ',')) != NULL) {
  1673. /* Comma found. Store length and shift the list ptr */
  1674. val->len = ((size_t)(list - val->ptr));
  1675. list++;
  1676. } else {
  1677. /* This value is the last one */
  1678. list = val->ptr + strlen(val->ptr);
  1679. val->len = ((size_t)(list - val->ptr));
  1680. }
  1681. if (eq_val != NULL) {
  1682. /* Value has form "x=y", adjust pointers and lengths
  1683. * so that val points to "x", and eq_val points to "y". */
  1684. eq_val->len = 0;
  1685. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1686. if (eq_val->ptr != NULL) {
  1687. eq_val->ptr++; /* Skip over '=' character */
  1688. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1689. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1690. }
  1691. }
  1692. }
  1693. return list;
  1694. }
  1695. /* Perform case-insensitive match of string against pattern */
  1696. static int
  1697. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1698. {
  1699. const char *or_str;
  1700. size_t i;
  1701. int j, len, res;
  1702. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1703. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1704. return res > 0 ? res : match_prefix(or_str + 1,
  1705. (size_t)((pattern + pattern_len)
  1706. - (or_str + 1)),
  1707. str);
  1708. }
  1709. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1710. if (pattern[i] == '?' && str[j] != '\0') {
  1711. continue;
  1712. } else if (pattern[i] == '$') {
  1713. return str[j] == '\0' ? j : -1;
  1714. } else if (pattern[i] == '*') {
  1715. i++;
  1716. if (pattern[i] == '*') {
  1717. i++;
  1718. len = (int)strlen(str + j);
  1719. } else {
  1720. len = (int)strcspn(str + j, "/");
  1721. }
  1722. if (i == pattern_len) {
  1723. return j + len;
  1724. }
  1725. do {
  1726. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1727. } while (res == -1 && len-- > 0);
  1728. return res == -1 ? -1 : j + res + len;
  1729. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1730. return -1;
  1731. }
  1732. }
  1733. return j;
  1734. }
  1735. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1736. * This function must tolerate situations when connection info is not
  1737. * set up, for example if request parsing failed. */
  1738. static int
  1739. should_keep_alive(const struct mg_connection *conn)
  1740. {
  1741. if (conn != NULL) {
  1742. const char *http_version = conn->request_info.http_version;
  1743. const char *header = mg_get_header(conn, "Connection");
  1744. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1745. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1746. || (header != NULL && mg_strcasecmp(header, "keep-alive") != 0)
  1747. || (header == NULL && http_version
  1748. && 0 != strcmp(http_version, "1.1"))) {
  1749. return 0;
  1750. }
  1751. return 1;
  1752. }
  1753. return 0;
  1754. }
  1755. static int
  1756. should_decode_url(const struct mg_connection *conn)
  1757. {
  1758. if (!conn || !conn->ctx) {
  1759. return 0;
  1760. }
  1761. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1762. }
  1763. static const char *
  1764. suggest_connection_header(const struct mg_connection *conn)
  1765. {
  1766. return should_keep_alive(conn) ? "keep-alive" : "close";
  1767. }
  1768. static void handle_file_based_request(struct mg_connection *conn,
  1769. const char *path,
  1770. struct file *filep);
  1771. static int
  1772. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1773. static const char *
  1774. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1775. {
  1776. switch (response_code) {
  1777. /* RFC2616 Section 10.1 - Informational 1xx */
  1778. case 100:
  1779. return "Continue"; /* RFC2616 Section 10.1.1 */
  1780. case 101:
  1781. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1782. case 102:
  1783. return "Processing"; /* RFC2518 Section 10.1 */
  1784. /* RFC2616 Section 10.2 - Successful 2xx */
  1785. case 200:
  1786. return "OK"; /* RFC2616 Section 10.2.1 */
  1787. case 201:
  1788. return "Created"; /* RFC2616 Section 10.2.2 */
  1789. case 202:
  1790. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1791. case 203:
  1792. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1793. case 204:
  1794. return "No Content"; /* RFC2616 Section 10.2.5 */
  1795. case 205:
  1796. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1797. case 206:
  1798. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1799. case 207:
  1800. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1801. /* RFC2616 Section 10.3 - Redirection 3xx */
  1802. case 300:
  1803. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1804. case 301:
  1805. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1806. case 302:
  1807. return "Found"; /* RFC2616 Section 10.3.3 */
  1808. case 303:
  1809. return "See Other"; /* RFC2616 Section 10.3.4 */
  1810. case 304:
  1811. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1812. case 305:
  1813. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1814. case 307:
  1815. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1816. /* RFC2616 Section 10.4 - Client Error 4xx */
  1817. case 400:
  1818. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1819. case 401:
  1820. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1821. case 402:
  1822. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1823. case 403:
  1824. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1825. case 404:
  1826. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1827. case 405:
  1828. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1829. case 406:
  1830. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1831. case 407:
  1832. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1833. case 408:
  1834. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1835. case 409:
  1836. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1837. case 410:
  1838. return "Gone"; /* RFC2616 Section 10.4.11 */
  1839. case 411:
  1840. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1841. case 412:
  1842. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1843. case 413:
  1844. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1845. case 414:
  1846. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1847. case 415:
  1848. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1849. case 416:
  1850. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1851. case 417:
  1852. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1853. case 422:
  1854. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1855. * Section 11.2 */
  1856. case 423:
  1857. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1858. case 424:
  1859. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1860. * Section 11.4 */
  1861. case 428:
  1862. return "Precondition Required"; /* RFC 6585, Section 3 */
  1863. case 429:
  1864. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1865. case 431:
  1866. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1867. /* RFC2616 Section 10.5 - Server Error 5xx */
  1868. case 500:
  1869. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1870. case 501:
  1871. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1872. case 502:
  1873. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1874. case 503:
  1875. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1876. case 504:
  1877. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1878. case 505:
  1879. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1880. case 507:
  1881. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  1882. * Section 11.5 */
  1883. case 511:
  1884. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1885. /* Other RFCs */
  1886. case 426:
  1887. return "Upgrade Required"; /* RFC 2817 */
  1888. /* Return codes from non normative RFCs: */
  1889. /* Informative and experimental RFCs, "de facto" standards due to common
  1890. * use, ... */
  1891. case 208:
  1892. return "Already Reported"; /* RFC5842 Section 7.1 */
  1893. case 226:
  1894. return "IM used"; /* RFC3229 Section 10.4.1 */
  1895. case 308:
  1896. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1897. case 418:
  1898. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1899. case 419:
  1900. return "Authentication Timeout"; /* common use */
  1901. case 451:
  1902. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1903. * Section 3 */
  1904. case 506:
  1905. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1906. case 508:
  1907. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1908. case 510:
  1909. return "Not Extended"; /* RFC 2774, Section 7 */
  1910. default:
  1911. /* This error code is unknown. This should not happen. */
  1912. if (conn) {
  1913. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1914. }
  1915. /* Return at least a category according to RFC 2616 Section 10. */
  1916. if (response_code >= 100 && response_code < 200) {
  1917. /* Unknown informational status code */
  1918. return "Information";
  1919. }
  1920. if (response_code >= 200 && response_code < 300) {
  1921. /* Unknown success code */
  1922. return "Success";
  1923. }
  1924. if (response_code >= 300 && response_code < 400) {
  1925. /* Unknown redirection code */
  1926. return "Redirection";
  1927. }
  1928. if (response_code >= 400 && response_code < 500) {
  1929. /* Unknown request error code */
  1930. return "Client Error";
  1931. }
  1932. if (response_code >= 500 && response_code < 600) {
  1933. /* Unknown server error code */
  1934. return "Server Error";
  1935. }
  1936. /* Response code not even within reasonable range */
  1937. return "";
  1938. }
  1939. }
  1940. static void send_http_error(struct mg_connection *,
  1941. int,
  1942. PRINTF_FORMAT_STRING(const char *fmt),
  1943. ...) PRINTF_ARGS(3, 4);
  1944. static void
  1945. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  1946. {
  1947. char buf[MG_BUF_LEN];
  1948. va_list ap;
  1949. int len, i, page_handler_found, scope, truncated;
  1950. char date[64];
  1951. time_t curtime = time(NULL);
  1952. const char *error_handler = NULL;
  1953. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1954. const char *error_page_file_ext, *tstr;
  1955. const char *status_text = mg_get_response_code_text(status, conn);
  1956. if (conn == NULL) {
  1957. return;
  1958. }
  1959. conn->status_code = status;
  1960. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  1961. || conn->ctx->callbacks.http_error(conn, status)) {
  1962. if (!conn->in_error_handler) {
  1963. /* Send user defined error pages, if defined */
  1964. error_handler = conn->ctx->config[ERROR_PAGES];
  1965. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1966. page_handler_found = 0;
  1967. if (error_handler != NULL) {
  1968. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  1969. switch (scope) {
  1970. case 1: /* Handler for specific error, e.g. 404 error */
  1971. mg_snprintf(conn,
  1972. &truncated,
  1973. buf,
  1974. sizeof(buf) - 32,
  1975. "%serror%03u.",
  1976. error_handler,
  1977. status);
  1978. break;
  1979. case 2: /* Handler for error group, e.g., 5xx error handler
  1980. * for all server errors (500-599) */
  1981. mg_snprintf(conn,
  1982. &truncated,
  1983. buf,
  1984. sizeof(buf) - 32,
  1985. "%serror%01uxx.",
  1986. error_handler,
  1987. status / 100);
  1988. break;
  1989. default: /* Handler for all errors */
  1990. mg_snprintf(conn,
  1991. &truncated,
  1992. buf,
  1993. sizeof(buf) - 32,
  1994. "%serror.",
  1995. error_handler);
  1996. break;
  1997. }
  1998. /* String truncation in buf may only occur if error_handler
  1999. * is too long. This string is from the config, not from a
  2000. * client. */
  2001. (void)truncated;
  2002. len = (int)strlen(buf);
  2003. tstr = strchr(error_page_file_ext, '.');
  2004. while (tstr) {
  2005. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2006. i++)
  2007. buf[len + i - 1] = tstr[i];
  2008. buf[len + i - 1] = 0;
  2009. if (mg_stat(conn, buf, &error_page_file)) {
  2010. page_handler_found = 1;
  2011. break;
  2012. }
  2013. tstr = strchr(tstr + i, '.');
  2014. }
  2015. }
  2016. }
  2017. if (page_handler_found) {
  2018. conn->in_error_handler = 1;
  2019. handle_file_based_request(conn, buf, &error_page_file);
  2020. conn->in_error_handler = 0;
  2021. return;
  2022. }
  2023. }
  2024. /* No custom error page. Send default error page. */
  2025. gmt_time_string(date, sizeof(date), &curtime);
  2026. conn->must_close = 1;
  2027. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2028. mg_printf(conn,
  2029. "Date: %s\r\n"
  2030. "Connection: close\r\n\r\n",
  2031. date);
  2032. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2033. if (status > 199 && status != 204 && status != 304) {
  2034. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2035. if (fmt != NULL) {
  2036. va_start(ap, fmt);
  2037. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2038. va_end(ap);
  2039. mg_write(conn, buf, strlen(buf));
  2040. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2041. }
  2042. } else {
  2043. /* No body allowed. Close the connection. */
  2044. DEBUG_TRACE("Error %i", status);
  2045. }
  2046. }
  2047. }
  2048. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2049. /* Create substitutes for POSIX functions in Win32. */
  2050. #if defined(__MINGW32__)
  2051. /* Show no warning in case system functions are not used. */
  2052. #pragma GCC diagnostic push
  2053. #pragma GCC diagnostic ignored "-Wunused-function"
  2054. #endif
  2055. static int
  2056. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2057. {
  2058. (void)unused;
  2059. *mutex = CreateMutex(NULL, FALSE, NULL);
  2060. return *mutex == NULL ? -1 : 0;
  2061. }
  2062. static int
  2063. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2064. {
  2065. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2066. }
  2067. static int
  2068. pthread_mutex_lock(pthread_mutex_t *mutex)
  2069. {
  2070. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2071. }
  2072. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2073. static int
  2074. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2075. {
  2076. switch (WaitForSingleObject(*mutex, 0)) {
  2077. case WAIT_OBJECT_0:
  2078. return 0;
  2079. case WAIT_TIMEOUT:
  2080. return -2; /* EBUSY */
  2081. }
  2082. return -1;
  2083. }
  2084. #endif
  2085. static int
  2086. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2087. {
  2088. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2089. }
  2090. #ifndef WIN_PTHREADS_TIME_H
  2091. static int
  2092. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2093. {
  2094. FILETIME ft;
  2095. ULARGE_INTEGER li;
  2096. BOOL ok = FALSE;
  2097. double d;
  2098. static double perfcnt_per_sec = 0.0;
  2099. if (tp) {
  2100. memset(tp, 0, sizeof(*tp));
  2101. if (clk_id == CLOCK_REALTIME) {
  2102. GetSystemTimeAsFileTime(&ft);
  2103. li.LowPart = ft.dwLowDateTime;
  2104. li.HighPart = ft.dwHighDateTime;
  2105. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2106. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2107. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2108. ok = TRUE;
  2109. } else if (clk_id == CLOCK_MONOTONIC) {
  2110. if (perfcnt_per_sec == 0.0) {
  2111. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2112. perfcnt_per_sec = 1.0 / li.QuadPart;
  2113. }
  2114. if (perfcnt_per_sec != 0.0) {
  2115. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2116. d = li.QuadPart * perfcnt_per_sec;
  2117. tp->tv_sec = (time_t)d;
  2118. d -= tp->tv_sec;
  2119. tp->tv_nsec = (long)(d * 1.0E9);
  2120. ok = TRUE;
  2121. }
  2122. }
  2123. }
  2124. return ok ? 0 : -1;
  2125. }
  2126. #endif
  2127. static int
  2128. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2129. {
  2130. (void)unused;
  2131. InitializeCriticalSection(&cv->threadIdSec);
  2132. cv->waitingthreadcount = 0;
  2133. cv->waitingthreadhdls =
  2134. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2135. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2136. }
  2137. static int
  2138. pthread_cond_timedwait(pthread_cond_t *cv,
  2139. pthread_mutex_t *mutex,
  2140. const struct timespec *abstime)
  2141. {
  2142. struct mg_workerTLS *tls =
  2143. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2144. int ok;
  2145. struct timespec tsnow;
  2146. int64_t nsnow, nswaitabs, nswaitrel;
  2147. DWORD mswaitrel;
  2148. EnterCriticalSection(&cv->threadIdSec);
  2149. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2150. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2151. tls->pthread_cond_helper_mutex;
  2152. cv->waitingthreadcount++;
  2153. LeaveCriticalSection(&cv->threadIdSec);
  2154. if (abstime) {
  2155. clock_gettime(CLOCK_REALTIME, &tsnow);
  2156. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2157. nswaitabs =
  2158. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2159. nswaitrel = nswaitabs - nsnow;
  2160. if (nswaitrel < 0) {
  2161. nswaitrel = 0;
  2162. }
  2163. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2164. } else {
  2165. mswaitrel = INFINITE;
  2166. }
  2167. pthread_mutex_unlock(mutex);
  2168. ok = (WAIT_OBJECT_0
  2169. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2170. pthread_mutex_lock(mutex);
  2171. return ok ? 0 : -1;
  2172. }
  2173. static int
  2174. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2175. {
  2176. return pthread_cond_timedwait(cv, mutex, NULL);
  2177. }
  2178. static int
  2179. pthread_cond_signal(pthread_cond_t *cv)
  2180. {
  2181. int i;
  2182. HANDLE wkup = NULL;
  2183. BOOL ok = FALSE;
  2184. EnterCriticalSection(&cv->threadIdSec);
  2185. if (cv->waitingthreadcount) {
  2186. wkup = cv->waitingthreadhdls[0];
  2187. ok = SetEvent(wkup);
  2188. for (i = 1; i < cv->waitingthreadcount; i++) {
  2189. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2190. }
  2191. cv->waitingthreadcount--;
  2192. assert(ok);
  2193. }
  2194. LeaveCriticalSection(&cv->threadIdSec);
  2195. return ok ? 0 : 1;
  2196. }
  2197. static int
  2198. pthread_cond_broadcast(pthread_cond_t *cv)
  2199. {
  2200. EnterCriticalSection(&cv->threadIdSec);
  2201. while (cv->waitingthreadcount) {
  2202. pthread_cond_signal(cv);
  2203. }
  2204. LeaveCriticalSection(&cv->threadIdSec);
  2205. return 0;
  2206. }
  2207. static int
  2208. pthread_cond_destroy(pthread_cond_t *cv)
  2209. {
  2210. EnterCriticalSection(&cv->threadIdSec);
  2211. assert(cv->waitingthreadcount == 0);
  2212. mg_free(cv->waitingthreadhdls);
  2213. cv->waitingthreadhdls = 0;
  2214. LeaveCriticalSection(&cv->threadIdSec);
  2215. DeleteCriticalSection(&cv->threadIdSec);
  2216. return 0;
  2217. }
  2218. #if defined(__MINGW32__)
  2219. /* Enable unused function warning again */
  2220. #pragma GCC diagnostic pop
  2221. #endif
  2222. /* For Windows, change all slashes to backslashes in path names. */
  2223. static void
  2224. change_slashes_to_backslashes(char *path)
  2225. {
  2226. int i;
  2227. for (i = 0; path[i] != '\0'; i++) {
  2228. if (path[i] == '/') {
  2229. path[i] = '\\';
  2230. }
  2231. /* remove double backslash (check i > 0 to preserve UNC paths,
  2232. * like \\server\file.txt) */
  2233. if ((path[i] == '\\') && (i > 0)) {
  2234. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2235. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2236. }
  2237. }
  2238. }
  2239. }
  2240. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2241. * wbuf and wbuf_len is a target buffer and its length. */
  2242. static void
  2243. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2244. {
  2245. char buf[PATH_MAX], buf2[PATH_MAX];
  2246. mg_strlcpy(buf, path, sizeof(buf));
  2247. change_slashes_to_backslashes(buf);
  2248. /* Convert to Unicode and back. If doubly-converted string does not
  2249. * match the original, something is fishy, reject. */
  2250. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2251. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2252. WideCharToMultiByte(
  2253. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2254. if (strcmp(buf, buf2) != 0) {
  2255. wbuf[0] = L'\0';
  2256. }
  2257. }
  2258. #if defined(_WIN32_WCE)
  2259. /* Create substitutes for POSIX functions in Win32. */
  2260. #if defined(__MINGW32__)
  2261. /* Show no warning in case system functions are not used. */
  2262. #pragma GCC diagnostic push
  2263. #pragma GCC diagnostic ignored "-Wunused-function"
  2264. #endif
  2265. static time_t
  2266. time(time_t *ptime)
  2267. {
  2268. time_t t;
  2269. SYSTEMTIME st;
  2270. FILETIME ft;
  2271. GetSystemTime(&st);
  2272. SystemTimeToFileTime(&st, &ft);
  2273. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2274. if (ptime != NULL) {
  2275. *ptime = t;
  2276. }
  2277. return t;
  2278. }
  2279. static struct tm *
  2280. localtime(const time_t *ptime, struct tm *ptm)
  2281. {
  2282. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2283. FILETIME ft, lft;
  2284. SYSTEMTIME st;
  2285. TIME_ZONE_INFORMATION tzinfo;
  2286. if (ptm == NULL) {
  2287. return NULL;
  2288. }
  2289. *(int64_t *)&ft = t;
  2290. FileTimeToLocalFileTime(&ft, &lft);
  2291. FileTimeToSystemTime(&lft, &st);
  2292. ptm->tm_year = st.wYear - 1900;
  2293. ptm->tm_mon = st.wMonth - 1;
  2294. ptm->tm_wday = st.wDayOfWeek;
  2295. ptm->tm_mday = st.wDay;
  2296. ptm->tm_hour = st.wHour;
  2297. ptm->tm_min = st.wMinute;
  2298. ptm->tm_sec = st.wSecond;
  2299. ptm->tm_yday = 0; /* hope nobody uses this */
  2300. ptm->tm_isdst =
  2301. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2302. return ptm;
  2303. }
  2304. static struct tm *
  2305. gmtime(const time_t *ptime, struct tm *ptm)
  2306. {
  2307. /* FIXME(lsm): fix this. */
  2308. return localtime(ptime, ptm);
  2309. }
  2310. static size_t
  2311. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2312. {
  2313. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2314. return 0;
  2315. }
  2316. #if defined(__MINGW32__)
  2317. /* Enable unused function warning again */
  2318. #pragma GCC diagnostic pop
  2319. #endif
  2320. #endif
  2321. /* Windows happily opens files with some garbage at the end of file name.
  2322. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2323. * "a.cgi", despite one would expect an error back.
  2324. * This function returns non-0 if path ends with some garbage. */
  2325. static int
  2326. path_cannot_disclose_cgi(const char *path)
  2327. {
  2328. static const char *allowed_last_characters = "_-";
  2329. int last = path[strlen(path) - 1];
  2330. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2331. }
  2332. static int
  2333. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2334. {
  2335. wchar_t wbuf[PATH_MAX];
  2336. WIN32_FILE_ATTRIBUTE_DATA info;
  2337. time_t creation_time;
  2338. if (!filep) {
  2339. return 0;
  2340. }
  2341. memset(filep, 0, sizeof(*filep));
  2342. if (conn && is_file_in_memory(conn, path, filep)) {
  2343. return 1;
  2344. }
  2345. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2346. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2347. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2348. filep->last_modified =
  2349. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2350. info.ftLastWriteTime.dwHighDateTime);
  2351. /* On Windows, the file creation time can be higher than the
  2352. * modification time, e.g. when a file is copied.
  2353. * Since the Last-Modified timestamp is used for caching
  2354. * it should be based on the most recent timestamp. */
  2355. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2356. info.ftCreationTime.dwHighDateTime);
  2357. if (creation_time > filep->last_modified) {
  2358. filep->last_modified = creation_time;
  2359. }
  2360. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2361. /* If file name is fishy, reset the file structure and return
  2362. * error.
  2363. * Note it is important to reset, not just return the error, cause
  2364. * functions like is_file_opened() check the struct. */
  2365. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2366. memset(filep, 0, sizeof(*filep));
  2367. return 0;
  2368. }
  2369. return 1;
  2370. }
  2371. return 0;
  2372. }
  2373. #if !defined(NO_FILES)
  2374. static int
  2375. mg_remove(const char *path)
  2376. {
  2377. wchar_t wbuf[PATH_MAX];
  2378. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2379. return DeleteFileW(wbuf) ? 0 : -1;
  2380. }
  2381. static int
  2382. mg_mkdir(const char *path, int mode)
  2383. {
  2384. char buf[PATH_MAX];
  2385. wchar_t wbuf[PATH_MAX];
  2386. (void)mode;
  2387. mg_strlcpy(buf, path, sizeof(buf));
  2388. change_slashes_to_backslashes(buf);
  2389. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2390. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2391. }
  2392. #endif
  2393. /* Create substitutes for POSIX functions in Win32. */
  2394. #if defined(__MINGW32__)
  2395. /* Show no warning in case system functions are not used. */
  2396. #pragma GCC diagnostic push
  2397. #pragma GCC diagnostic ignored "-Wunused-function"
  2398. #endif
  2399. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2400. static DIR *
  2401. opendir(const char *name)
  2402. {
  2403. DIR *dir = NULL;
  2404. wchar_t wpath[PATH_MAX];
  2405. DWORD attrs;
  2406. if (name == NULL) {
  2407. SetLastError(ERROR_BAD_ARGUMENTS);
  2408. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2409. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2410. } else {
  2411. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2412. attrs = GetFileAttributesW(wpath);
  2413. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2414. == FILE_ATTRIBUTE_DIRECTORY)) {
  2415. (void)wcscat(wpath, L"\\*");
  2416. dir->handle = FindFirstFileW(wpath, &dir->info);
  2417. dir->result.d_name[0] = '\0';
  2418. } else {
  2419. mg_free(dir);
  2420. dir = NULL;
  2421. }
  2422. }
  2423. return dir;
  2424. }
  2425. static int
  2426. closedir(DIR *dir)
  2427. {
  2428. int result = 0;
  2429. if (dir != NULL) {
  2430. if (dir->handle != INVALID_HANDLE_VALUE)
  2431. result = FindClose(dir->handle) ? 0 : -1;
  2432. mg_free(dir);
  2433. } else {
  2434. result = -1;
  2435. SetLastError(ERROR_BAD_ARGUMENTS);
  2436. }
  2437. return result;
  2438. }
  2439. static struct dirent *
  2440. readdir(DIR *dir)
  2441. {
  2442. struct dirent *result = 0;
  2443. if (dir) {
  2444. if (dir->handle != INVALID_HANDLE_VALUE) {
  2445. result = &dir->result;
  2446. (void)WideCharToMultiByte(CP_UTF8,
  2447. 0,
  2448. dir->info.cFileName,
  2449. -1,
  2450. result->d_name,
  2451. sizeof(result->d_name),
  2452. NULL,
  2453. NULL);
  2454. if (!FindNextFileW(dir->handle, &dir->info)) {
  2455. (void)FindClose(dir->handle);
  2456. dir->handle = INVALID_HANDLE_VALUE;
  2457. }
  2458. } else {
  2459. SetLastError(ERROR_FILE_NOT_FOUND);
  2460. }
  2461. } else {
  2462. SetLastError(ERROR_BAD_ARGUMENTS);
  2463. }
  2464. return result;
  2465. }
  2466. #ifndef HAVE_POLL
  2467. static int
  2468. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2469. {
  2470. struct timeval tv;
  2471. fd_set set;
  2472. unsigned int i;
  2473. int result;
  2474. SOCKET maxfd = 0;
  2475. memset(&tv, 0, sizeof(tv));
  2476. tv.tv_sec = milliseconds / 1000;
  2477. tv.tv_usec = (milliseconds % 1000) * 1000;
  2478. FD_ZERO(&set);
  2479. for (i = 0; i < n; i++) {
  2480. FD_SET((SOCKET)pfd[i].fd, &set);
  2481. pfd[i].revents = 0;
  2482. if (pfd[i].fd > maxfd) {
  2483. maxfd = pfd[i].fd;
  2484. }
  2485. }
  2486. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2487. for (i = 0; i < n; i++) {
  2488. if (FD_ISSET(pfd[i].fd, &set)) {
  2489. pfd[i].revents = POLLIN;
  2490. }
  2491. }
  2492. }
  2493. return result;
  2494. }
  2495. #endif /* HAVE_POLL */
  2496. #if defined(__MINGW32__)
  2497. /* Enable unused function warning again */
  2498. #pragma GCC diagnostic pop
  2499. #endif
  2500. static void
  2501. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2502. {
  2503. (void)conn; /* Unused. */
  2504. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2505. }
  2506. int
  2507. mg_start_thread(mg_thread_func_t f, void *p)
  2508. {
  2509. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2510. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2511. */
  2512. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2513. == ((uintptr_t)(-1L)))
  2514. ? -1
  2515. : 0);
  2516. #else
  2517. return (
  2518. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2519. ? -1
  2520. : 0);
  2521. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2522. }
  2523. /* Start a thread storing the thread context. */
  2524. static int
  2525. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2526. void *p,
  2527. pthread_t *threadidptr)
  2528. {
  2529. uintptr_t uip;
  2530. HANDLE threadhandle;
  2531. int result = -1;
  2532. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2533. threadhandle = (HANDLE)uip;
  2534. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2535. *threadidptr = threadhandle;
  2536. result = 0;
  2537. }
  2538. return result;
  2539. }
  2540. /* Wait for a thread to finish. */
  2541. static int
  2542. mg_join_thread(pthread_t threadid)
  2543. {
  2544. int result;
  2545. DWORD dwevent;
  2546. result = -1;
  2547. dwevent = WaitForSingleObject(threadid, INFINITE);
  2548. if (dwevent == WAIT_FAILED) {
  2549. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2550. } else {
  2551. if (dwevent == WAIT_OBJECT_0) {
  2552. CloseHandle(threadid);
  2553. result = 0;
  2554. }
  2555. }
  2556. return result;
  2557. }
  2558. #if !defined(NO_SSL_DL)
  2559. /* Create substitutes for POSIX functions in Win32. */
  2560. #if defined(__MINGW32__)
  2561. /* Show no warning in case system functions are not used. */
  2562. #pragma GCC diagnostic push
  2563. #pragma GCC diagnostic ignored "-Wunused-function"
  2564. #endif
  2565. static HANDLE
  2566. dlopen(const char *dll_name, int flags)
  2567. {
  2568. wchar_t wbuf[PATH_MAX];
  2569. (void)flags;
  2570. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2571. return LoadLibraryW(wbuf);
  2572. }
  2573. static int
  2574. dlclose(void *handle)
  2575. {
  2576. int result;
  2577. if (FreeLibrary((HMODULE)handle) != 0) {
  2578. result = 0;
  2579. } else {
  2580. result = -1;
  2581. }
  2582. return result;
  2583. }
  2584. #if defined(__MINGW32__)
  2585. /* Enable unused function warning again */
  2586. #pragma GCC diagnostic pop
  2587. #endif
  2588. #endif
  2589. #if !defined(NO_CGI)
  2590. #define SIGKILL (0)
  2591. static int
  2592. kill(pid_t pid, int sig_num)
  2593. {
  2594. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2595. (void)CloseHandle((HANDLE)pid);
  2596. return 0;
  2597. }
  2598. static void
  2599. trim_trailing_whitespaces(char *s)
  2600. {
  2601. char *e = s + strlen(s) - 1;
  2602. while (e > s && isspace(*(unsigned char *)e)) {
  2603. *e-- = '\0';
  2604. }
  2605. }
  2606. static pid_t
  2607. spawn_process(struct mg_connection *conn,
  2608. const char *prog,
  2609. char *envblk,
  2610. char *envp[],
  2611. int fdin,
  2612. int fdout,
  2613. int fderr,
  2614. const char *dir)
  2615. {
  2616. HANDLE me;
  2617. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2618. cmdline[PATH_MAX], buf[PATH_MAX];
  2619. int truncated;
  2620. struct file file = STRUCT_FILE_INITIALIZER;
  2621. STARTUPINFOA si;
  2622. PROCESS_INFORMATION pi = {0};
  2623. (void)envp;
  2624. memset(&si, 0, sizeof(si));
  2625. si.cb = sizeof(si);
  2626. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2627. si.wShowWindow = SW_HIDE;
  2628. me = GetCurrentProcess();
  2629. DuplicateHandle(me,
  2630. (HANDLE)_get_osfhandle(fdin),
  2631. me,
  2632. &si.hStdInput,
  2633. 0,
  2634. TRUE,
  2635. DUPLICATE_SAME_ACCESS);
  2636. DuplicateHandle(me,
  2637. (HANDLE)_get_osfhandle(fdout),
  2638. me,
  2639. &si.hStdOutput,
  2640. 0,
  2641. TRUE,
  2642. DUPLICATE_SAME_ACCESS);
  2643. DuplicateHandle(me,
  2644. (HANDLE)_get_osfhandle(fderr),
  2645. me,
  2646. &si.hStdError,
  2647. 0,
  2648. TRUE,
  2649. DUPLICATE_SAME_ACCESS);
  2650. /* If CGI file is a script, try to read the interpreter line */
  2651. interp = conn->ctx->config[CGI_INTERPRETER];
  2652. if (interp == NULL) {
  2653. buf[0] = buf[1] = '\0';
  2654. /* Read the first line of the script into the buffer */
  2655. mg_snprintf(
  2656. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2657. if (truncated) {
  2658. pi.hProcess = (pid_t)-1;
  2659. goto spawn_cleanup;
  2660. }
  2661. if (mg_fopen(conn, cmdline, "r", &file)) {
  2662. p = (char *)file.membuf;
  2663. mg_fgets(buf, sizeof(buf), &file, &p);
  2664. mg_fclose(&file);
  2665. buf[sizeof(buf) - 1] = '\0';
  2666. }
  2667. if (buf[0] == '#' && buf[1] == '!') {
  2668. trim_trailing_whitespaces(buf + 2);
  2669. } else {
  2670. buf[2] = '\0';
  2671. }
  2672. interp = buf + 2;
  2673. }
  2674. if (interp[0] != '\0') {
  2675. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2676. interp = full_interp;
  2677. }
  2678. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2679. if (interp[0] != '\0') {
  2680. mg_snprintf(conn,
  2681. &truncated,
  2682. cmdline,
  2683. sizeof(cmdline),
  2684. "\"%s\" \"%s\\%s\"",
  2685. interp,
  2686. full_dir,
  2687. prog);
  2688. } else {
  2689. mg_snprintf(conn,
  2690. &truncated,
  2691. cmdline,
  2692. sizeof(cmdline),
  2693. "\"%s\\%s\"",
  2694. full_dir,
  2695. prog);
  2696. }
  2697. if (truncated) {
  2698. pi.hProcess = (pid_t)-1;
  2699. goto spawn_cleanup;
  2700. }
  2701. DEBUG_TRACE("Running [%s]", cmdline);
  2702. if (CreateProcessA(NULL,
  2703. cmdline,
  2704. NULL,
  2705. NULL,
  2706. TRUE,
  2707. CREATE_NEW_PROCESS_GROUP,
  2708. envblk,
  2709. NULL,
  2710. &si,
  2711. &pi) == 0) {
  2712. mg_cry(
  2713. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2714. pi.hProcess = (pid_t)-1;
  2715. /* goto spawn_cleanup; */
  2716. }
  2717. spawn_cleanup:
  2718. (void)CloseHandle(si.hStdOutput);
  2719. (void)CloseHandle(si.hStdError);
  2720. (void)CloseHandle(si.hStdInput);
  2721. if (pi.hThread != NULL) {
  2722. (void)CloseHandle(pi.hThread);
  2723. }
  2724. return (pid_t)pi.hProcess;
  2725. }
  2726. #endif /* !NO_CGI */
  2727. static int
  2728. set_non_blocking_mode(SOCKET sock)
  2729. {
  2730. unsigned long on = 1;
  2731. return ioctlsocket(sock, (long)FIONBIO, &on);
  2732. }
  2733. #else
  2734. static int
  2735. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2736. {
  2737. struct stat st;
  2738. if (!filep) {
  2739. return 0;
  2740. }
  2741. memset(filep, 0, sizeof(*filep));
  2742. if (conn && is_file_in_memory(conn, path, filep)) {
  2743. return 1;
  2744. }
  2745. if (0 == stat(path, &st)) {
  2746. filep->size = (uint64_t)(st.st_size);
  2747. filep->last_modified = st.st_mtime;
  2748. filep->is_directory = S_ISDIR(st.st_mode);
  2749. return 1;
  2750. }
  2751. return 0;
  2752. }
  2753. static void
  2754. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2755. {
  2756. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2757. if (conn) {
  2758. mg_cry(conn,
  2759. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2760. __func__,
  2761. strerror(ERRNO));
  2762. }
  2763. }
  2764. }
  2765. int
  2766. mg_start_thread(mg_thread_func_t func, void *param)
  2767. {
  2768. pthread_t thread_id;
  2769. pthread_attr_t attr;
  2770. int result;
  2771. (void)pthread_attr_init(&attr);
  2772. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2773. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2774. /* Compile-time option to control stack size,
  2775. * e.g. -DUSE_STACK_SIZE=16384 */
  2776. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2777. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2778. result = pthread_create(&thread_id, &attr, func, param);
  2779. pthread_attr_destroy(&attr);
  2780. return result;
  2781. }
  2782. /* Start a thread storing the thread context. */
  2783. static int
  2784. mg_start_thread_with_id(mg_thread_func_t func,
  2785. void *param,
  2786. pthread_t *threadidptr)
  2787. {
  2788. pthread_t thread_id;
  2789. pthread_attr_t attr;
  2790. int result;
  2791. (void)pthread_attr_init(&attr);
  2792. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2793. /* Compile-time option to control stack size,
  2794. * e.g. -DUSE_STACK_SIZE=16384 */
  2795. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2796. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2797. result = pthread_create(&thread_id, &attr, func, param);
  2798. pthread_attr_destroy(&attr);
  2799. if ((result == 0) && (threadidptr != NULL)) {
  2800. *threadidptr = thread_id;
  2801. }
  2802. return result;
  2803. }
  2804. /* Wait for a thread to finish. */
  2805. static int
  2806. mg_join_thread(pthread_t threadid)
  2807. {
  2808. int result;
  2809. result = pthread_join(threadid, NULL);
  2810. return result;
  2811. }
  2812. #ifndef NO_CGI
  2813. static pid_t
  2814. spawn_process(struct mg_connection *conn,
  2815. const char *prog,
  2816. char *envblk,
  2817. char *envp[],
  2818. int fdin,
  2819. int fdout,
  2820. int fderr,
  2821. const char *dir)
  2822. {
  2823. pid_t pid;
  2824. const char *interp;
  2825. (void)envblk;
  2826. if (conn == NULL) {
  2827. return 0;
  2828. }
  2829. if ((pid = fork()) == -1) {
  2830. /* Parent */
  2831. send_http_error(conn,
  2832. 500,
  2833. "Error: Creating CGI process\nfork(): %s",
  2834. strerror(ERRNO));
  2835. } else if (pid == 0) {
  2836. /* Child */
  2837. if (chdir(dir) != 0) {
  2838. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2839. } else if (dup2(fdin, 0) == -1) {
  2840. mg_cry(
  2841. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2842. } else if (dup2(fdout, 1) == -1) {
  2843. mg_cry(
  2844. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2845. } else if (dup2(fderr, 2) == -1) {
  2846. mg_cry(
  2847. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  2848. } else {
  2849. /* Keep stderr and stdout in two different pipes.
  2850. * Stdout will be sent back to the client,
  2851. * stderr should go into a server error log. */
  2852. (void)close(fdin);
  2853. (void)close(fdout);
  2854. (void)close(fderr);
  2855. /* After exec, all signal handlers are restored to their default
  2856. * values, with one exception of SIGCHLD. According to
  2857. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2858. * leave unchanged after exec if it was set to be ignored. Restore
  2859. * it to default action. */
  2860. signal(SIGCHLD, SIG_DFL);
  2861. interp = conn->ctx->config[CGI_INTERPRETER];
  2862. if (interp == NULL) {
  2863. (void)execle(prog, prog, NULL, envp);
  2864. mg_cry(conn,
  2865. "%s: execle(%s): %s",
  2866. __func__,
  2867. prog,
  2868. strerror(ERRNO));
  2869. } else {
  2870. (void)execle(interp, interp, prog, NULL, envp);
  2871. mg_cry(conn,
  2872. "%s: execle(%s %s): %s",
  2873. __func__,
  2874. interp,
  2875. prog,
  2876. strerror(ERRNO));
  2877. }
  2878. }
  2879. exit(EXIT_FAILURE);
  2880. }
  2881. return pid;
  2882. }
  2883. #endif /* !NO_CGI */
  2884. static int
  2885. set_non_blocking_mode(SOCKET sock)
  2886. {
  2887. int flags;
  2888. flags = fcntl(sock, F_GETFL, 0);
  2889. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2890. return 0;
  2891. }
  2892. #endif /* _WIN32 */
  2893. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2894. * descriptor. Return number of bytes written. */
  2895. static int
  2896. push(struct mg_context *ctx,
  2897. FILE *fp,
  2898. SOCKET sock,
  2899. SSL *ssl,
  2900. const char *buf,
  2901. int len,
  2902. double timeout)
  2903. {
  2904. struct timespec start, now;
  2905. int n, err;
  2906. #ifdef _WIN32
  2907. typedef int len_t;
  2908. #else
  2909. typedef size_t len_t;
  2910. #endif
  2911. if (timeout > 0) {
  2912. memset(&start, 0, sizeof(start));
  2913. memset(&now, 0, sizeof(now));
  2914. clock_gettime(CLOCK_MONOTONIC, &start);
  2915. }
  2916. if (ctx == NULL) {
  2917. return -1;
  2918. }
  2919. #ifdef NO_SSL
  2920. if (ssl) {
  2921. return -1;
  2922. }
  2923. #endif
  2924. do {
  2925. #ifndef NO_SSL
  2926. if (ssl != NULL) {
  2927. n = SSL_write(ssl, buf, len);
  2928. if (n <= 0) {
  2929. err = SSL_get_error(ssl, n);
  2930. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  2931. err = ERRNO;
  2932. } else {
  2933. DEBUG_TRACE("SSL_write() failed, error %d", err);
  2934. return -1;
  2935. }
  2936. } else {
  2937. err = 0;
  2938. }
  2939. } else
  2940. #endif
  2941. if (fp != NULL) {
  2942. n = (int)fwrite(buf, 1, (size_t)len, fp);
  2943. if (ferror(fp)) {
  2944. n = -1;
  2945. err = ERRNO;
  2946. } else {
  2947. err = 0;
  2948. }
  2949. } else {
  2950. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  2951. err = (n < 0) ? ERRNO : 0;
  2952. }
  2953. if (ctx->stop_flag) {
  2954. return -1;
  2955. }
  2956. if ((n > 0) || (n == 0 && len == 0)) {
  2957. /* some data has been read, or no data was requested */
  2958. return n;
  2959. }
  2960. if (n == 0) {
  2961. /* shutdown of the socket at client side */
  2962. return -1;
  2963. }
  2964. if (n < 0) {
  2965. /* socket error - check errno */
  2966. DEBUG_TRACE("send() failed, error %d", err);
  2967. /* TODO: error handling depending on the error code.
  2968. * These codes are different between Windows and Linux.
  2969. */
  2970. return -1;
  2971. }
  2972. if (timeout > 0) {
  2973. clock_gettime(CLOCK_MONOTONIC, &now);
  2974. }
  2975. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2976. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  2977. used */
  2978. return -1;
  2979. }
  2980. static int64_t
  2981. push_all(struct mg_context *ctx,
  2982. FILE *fp,
  2983. SOCKET sock,
  2984. SSL *ssl,
  2985. const char *buf,
  2986. int64_t len)
  2987. {
  2988. double timeout = -1.0;
  2989. int64_t n, nwritten = 0;
  2990. if (ctx == NULL) {
  2991. return -1;
  2992. }
  2993. if (ctx->config[REQUEST_TIMEOUT]) {
  2994. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2995. }
  2996. while (len > 0 && ctx->stop_flag == 0) {
  2997. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  2998. if (n < 0) {
  2999. if (nwritten == 0) {
  3000. nwritten = n; /* Propagate the error */
  3001. }
  3002. break;
  3003. } else if (n == 0) {
  3004. break; /* No more data to write */
  3005. } else {
  3006. nwritten += n;
  3007. len -= n;
  3008. }
  3009. }
  3010. return nwritten;
  3011. }
  3012. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3013. * Return negative value on error, or number of bytes read on success. */
  3014. static int
  3015. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3016. {
  3017. int nread, err;
  3018. struct timespec start, now;
  3019. #ifdef _WIN32
  3020. typedef int len_t;
  3021. #else
  3022. typedef size_t len_t;
  3023. #endif
  3024. if (timeout > 0) {
  3025. memset(&start, 0, sizeof(start));
  3026. memset(&now, 0, sizeof(now));
  3027. clock_gettime(CLOCK_MONOTONIC, &start);
  3028. }
  3029. do {
  3030. if (fp != NULL) {
  3031. /* Use read() instead of fread(), because if we're reading from the
  3032. * CGI pipe, fread() may block until IO buffer is filled up. We
  3033. * cannot afford to block and must pass all read bytes immediately
  3034. * to the client. */
  3035. nread = (int)read(fileno(fp), buf, (size_t)len);
  3036. err = (nread < 0) ? ERRNO : 0;
  3037. #ifndef NO_SSL
  3038. } else if (conn->ssl != NULL) {
  3039. nread = SSL_read(conn->ssl, buf, len);
  3040. if (nread <= 0) {
  3041. err = SSL_get_error(conn->ssl, nread);
  3042. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3043. err = ERRNO;
  3044. } else {
  3045. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3046. return -1;
  3047. }
  3048. } else {
  3049. err = 0;
  3050. }
  3051. #endif
  3052. } else {
  3053. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3054. err = (nread < 0) ? ERRNO : 0;
  3055. }
  3056. if (conn->ctx->stop_flag) {
  3057. return -1;
  3058. }
  3059. if ((nread > 0) || (nread == 0 && len == 0)) {
  3060. /* some data has been read, or no data was requested */
  3061. return nread;
  3062. }
  3063. if (nread == 0) {
  3064. /* shutdown of the socket at client side */
  3065. return -1;
  3066. }
  3067. if (nread < 0) {
  3068. /* socket error - check errno */
  3069. #ifdef _WIN32
  3070. if (err == WSAEWOULDBLOCK) {
  3071. /* standard case if called from close_socket_gracefully */
  3072. return -1;
  3073. } else if (err == WSAETIMEDOUT) {
  3074. /* timeout is handled by the while loop */
  3075. } else {
  3076. DEBUG_TRACE("recv() failed, error %d", err);
  3077. return -1;
  3078. }
  3079. #else
  3080. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3081. * if the timeout is reached and if the socket was set to non-
  3082. * blocking in close_socket_gracefully, so we can not distinguish
  3083. * here. We have to wait for the timeout in both cases for now.
  3084. */
  3085. if (err == EAGAIN || err == EWOULDBLOCK) {
  3086. /* standard case if called from close_socket_gracefully
  3087. * => should return -1 */
  3088. /* or timeout occured
  3089. * => the code must stay in the while loop */
  3090. } else {
  3091. DEBUG_TRACE("recv() failed, error %d", err);
  3092. return -1;
  3093. }
  3094. #endif
  3095. }
  3096. if (timeout > 0) {
  3097. clock_gettime(CLOCK_MONOTONIC, &now);
  3098. }
  3099. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3100. /* Timeout occured, but no data available. */
  3101. return -1;
  3102. }
  3103. static int
  3104. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3105. {
  3106. int n, nread = 0;
  3107. double timeout = -1.0;
  3108. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3109. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3110. }
  3111. while (len > 0 && conn->ctx->stop_flag == 0) {
  3112. n = pull(fp, conn, buf + nread, len, timeout);
  3113. if (n < 0) {
  3114. if (nread == 0) {
  3115. nread = n; /* Propagate the error */
  3116. }
  3117. break;
  3118. } else if (n == 0) {
  3119. break; /* No more data to read */
  3120. } else {
  3121. conn->consumed_content += n;
  3122. nread += n;
  3123. len -= n;
  3124. }
  3125. }
  3126. return nread;
  3127. }
  3128. static void
  3129. discard_unread_request_data(struct mg_connection *conn)
  3130. {
  3131. char buf[MG_BUF_LEN];
  3132. size_t to_read;
  3133. int nread;
  3134. if (conn == NULL) {
  3135. return;
  3136. }
  3137. to_read = sizeof(buf);
  3138. if (conn->is_chunked) {
  3139. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3140. * completely */
  3141. while (conn->is_chunked == 1) {
  3142. nread = mg_read(conn, buf, to_read);
  3143. if (nread <= 0) {
  3144. break;
  3145. }
  3146. }
  3147. } else {
  3148. /* Not chunked: content length is known */
  3149. while (conn->consumed_content < conn->content_len) {
  3150. if (to_read
  3151. > (size_t)(conn->content_len - conn->consumed_content)) {
  3152. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3153. }
  3154. nread = mg_read(conn, buf, to_read);
  3155. if (nread <= 0) {
  3156. break;
  3157. }
  3158. }
  3159. }
  3160. }
  3161. static int
  3162. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3163. {
  3164. int64_t n, buffered_len, nread;
  3165. int64_t len64 =
  3166. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3167. * int, we may not read more
  3168. * bytes */
  3169. const char *body;
  3170. if (conn == NULL) {
  3171. return 0;
  3172. }
  3173. /* If Content-Length is not set for a PUT or POST request, read until
  3174. * socket is closed */
  3175. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3176. conn->content_len = INT64_MAX;
  3177. conn->must_close = 1;
  3178. }
  3179. nread = 0;
  3180. if (conn->consumed_content < conn->content_len) {
  3181. /* Adjust number of bytes to read. */
  3182. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3183. if (left_to_read < len64) {
  3184. /* Do not read more than the total content length of the request.
  3185. */
  3186. len64 = left_to_read;
  3187. }
  3188. /* Return buffered data */
  3189. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3190. - conn->consumed_content;
  3191. if (buffered_len > 0) {
  3192. if (len64 < buffered_len) {
  3193. buffered_len = len64;
  3194. }
  3195. body = conn->buf + conn->request_len + conn->consumed_content;
  3196. memcpy(buf, body, (size_t)buffered_len);
  3197. len64 -= buffered_len;
  3198. conn->consumed_content += buffered_len;
  3199. nread += buffered_len;
  3200. buf = (char *)buf + buffered_len;
  3201. }
  3202. /* We have returned all buffered data. Read new data from the remote
  3203. * socket.
  3204. */
  3205. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3206. nread += n;
  3207. } else {
  3208. nread = (nread > 0 ? nread : n);
  3209. }
  3210. }
  3211. return (int)nread;
  3212. }
  3213. static char
  3214. mg_getc(struct mg_connection *conn)
  3215. {
  3216. char c;
  3217. if (conn == NULL) {
  3218. return 0;
  3219. }
  3220. conn->content_len++;
  3221. if (mg_read_inner(conn, &c, 1) <= 0) {
  3222. return (char)0;
  3223. }
  3224. return c;
  3225. }
  3226. int
  3227. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3228. {
  3229. if (len > INT_MAX) {
  3230. len = INT_MAX;
  3231. }
  3232. if (conn == NULL) {
  3233. return 0;
  3234. }
  3235. if (conn->is_chunked) {
  3236. size_t all_read = 0;
  3237. while (len > 0) {
  3238. if (conn->chunk_remainder) {
  3239. /* copy from the remainder of the last received chunk */
  3240. long read_ret;
  3241. size_t read_now =
  3242. ((conn->chunk_remainder > len) ? (len)
  3243. : (conn->chunk_remainder));
  3244. conn->content_len += (int)read_now;
  3245. read_ret =
  3246. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3247. all_read += (size_t)read_ret;
  3248. conn->chunk_remainder -= read_now;
  3249. len -= read_now;
  3250. if (conn->chunk_remainder == 0) {
  3251. /* the rest of the data in the current chunk has been read
  3252. */
  3253. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3254. /* Protocol violation */
  3255. return -1;
  3256. }
  3257. }
  3258. } else {
  3259. /* fetch a new chunk */
  3260. int i = 0;
  3261. char lenbuf[64];
  3262. char *end = 0;
  3263. unsigned long chunkSize = 0;
  3264. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3265. lenbuf[i] = mg_getc(conn);
  3266. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3267. continue;
  3268. }
  3269. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3270. lenbuf[i + 1] = 0;
  3271. chunkSize = strtoul(lenbuf, &end, 16);
  3272. break;
  3273. }
  3274. if (!isalnum(lenbuf[i])) {
  3275. /* illegal character for chunk length */
  3276. return -1;
  3277. }
  3278. }
  3279. if ((end == NULL) || (*end != '\r')) {
  3280. /* chunksize not set correctly */
  3281. return -1;
  3282. }
  3283. conn->chunk_remainder = chunkSize;
  3284. if (chunkSize == 0) {
  3285. /* regular end of content */
  3286. conn->is_chunked = 2;
  3287. break;
  3288. }
  3289. }
  3290. }
  3291. return (int)all_read;
  3292. }
  3293. return mg_read_inner(conn, buf, len);
  3294. }
  3295. int
  3296. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3297. {
  3298. time_t now;
  3299. int64_t n, total, allowed;
  3300. if (conn == NULL) {
  3301. return 0;
  3302. }
  3303. if (conn->throttle > 0) {
  3304. if ((now = time(NULL)) != conn->last_throttle_time) {
  3305. conn->last_throttle_time = now;
  3306. conn->last_throttle_bytes = 0;
  3307. }
  3308. allowed = conn->throttle - conn->last_throttle_bytes;
  3309. if (allowed > (int64_t)len) {
  3310. allowed = (int64_t)len;
  3311. }
  3312. if ((total = push_all(conn->ctx,
  3313. NULL,
  3314. conn->client.sock,
  3315. conn->ssl,
  3316. (const char *)buf,
  3317. (int64_t)allowed)) == allowed) {
  3318. buf = (char *)buf + total;
  3319. conn->last_throttle_bytes += total;
  3320. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3321. allowed = conn->throttle > (int64_t)len - total
  3322. ? (int64_t)len - total
  3323. : conn->throttle;
  3324. if ((n = push_all(conn->ctx,
  3325. NULL,
  3326. conn->client.sock,
  3327. conn->ssl,
  3328. (const char *)buf,
  3329. (int64_t)allowed)) != allowed) {
  3330. break;
  3331. }
  3332. sleep(1);
  3333. conn->last_throttle_bytes = allowed;
  3334. conn->last_throttle_time = time(NULL);
  3335. buf = (char *)buf + n;
  3336. total += n;
  3337. }
  3338. }
  3339. } else {
  3340. total = push_all(conn->ctx,
  3341. NULL,
  3342. conn->client.sock,
  3343. conn->ssl,
  3344. (const char *)buf,
  3345. (int64_t)len);
  3346. }
  3347. return (int)total;
  3348. }
  3349. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3350. static int
  3351. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3352. {
  3353. va_list ap_copy;
  3354. size_t size = MG_BUF_LEN;
  3355. int len = -1;
  3356. *buf = NULL;
  3357. while (len < 0) {
  3358. if (*buf) {
  3359. mg_free(*buf);
  3360. }
  3361. *buf = (char *)mg_malloc(size *= 4);
  3362. if (!*buf) {
  3363. break;
  3364. }
  3365. va_copy(ap_copy, ap);
  3366. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3367. va_end(ap_copy);
  3368. *buf[size - 1] = 0;
  3369. }
  3370. return len;
  3371. }
  3372. /* Print message to buffer. If buffer is large enough to hold the message,
  3373. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3374. * and return allocated buffer. */
  3375. static int
  3376. alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  3377. {
  3378. va_list ap_copy;
  3379. int len;
  3380. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3381. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3382. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3383. * Therefore, we make two passes: on first pass, get required message
  3384. * length.
  3385. * On second pass, actually print the message. */
  3386. va_copy(ap_copy, ap);
  3387. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3388. va_end(ap_copy);
  3389. if (len < 0) {
  3390. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3391. * Switch to alternative code path that uses incremental allocations.
  3392. */
  3393. va_copy(ap_copy, ap);
  3394. len = alloc_vprintf2(buf, fmt, ap);
  3395. va_end(ap_copy);
  3396. } else if ((size_t)(len) > size && (size = (size_t)(len) + 1) > 0
  3397. && (*buf = (char *)mg_malloc(size)) == NULL) {
  3398. len = -1; /* Allocation failed, mark failure */
  3399. } else {
  3400. va_copy(ap_copy, ap);
  3401. IGNORE_UNUSED_RESULT(vsnprintf_impl(*buf, size, fmt, ap_copy));
  3402. va_end(ap_copy);
  3403. }
  3404. return len;
  3405. }
  3406. static int
  3407. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3408. {
  3409. char mem[MG_BUF_LEN], *buf = mem;
  3410. int len;
  3411. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  3412. len = mg_write(conn, buf, (size_t)len);
  3413. }
  3414. if (buf != mem && buf != NULL) {
  3415. mg_free(buf);
  3416. }
  3417. return len;
  3418. }
  3419. int
  3420. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3421. {
  3422. va_list ap;
  3423. int result;
  3424. va_start(ap, fmt);
  3425. result = mg_vprintf(conn, fmt, ap);
  3426. va_end(ap);
  3427. return result;
  3428. }
  3429. int
  3430. mg_url_decode(const char *src,
  3431. int src_len,
  3432. char *dst,
  3433. int dst_len,
  3434. int is_form_url_encoded)
  3435. {
  3436. int i, j, a, b;
  3437. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3438. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3439. if (i < src_len - 2 && src[i] == '%'
  3440. && isxdigit(*(const unsigned char *)(src + i + 1))
  3441. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3442. a = tolower(*(const unsigned char *)(src + i + 1));
  3443. b = tolower(*(const unsigned char *)(src + i + 2));
  3444. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3445. i += 2;
  3446. } else if (is_form_url_encoded && src[i] == '+') {
  3447. dst[j] = ' ';
  3448. } else {
  3449. dst[j] = src[i];
  3450. }
  3451. }
  3452. dst[j] = '\0'; /* Null-terminate the destination */
  3453. return i >= src_len ? j : -1;
  3454. }
  3455. int
  3456. mg_get_var(const char *data,
  3457. size_t data_len,
  3458. const char *name,
  3459. char *dst,
  3460. size_t dst_len)
  3461. {
  3462. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3463. }
  3464. int
  3465. mg_get_var2(const char *data,
  3466. size_t data_len,
  3467. const char *name,
  3468. char *dst,
  3469. size_t dst_len,
  3470. size_t occurrence)
  3471. {
  3472. const char *p, *e, *s;
  3473. size_t name_len;
  3474. int len;
  3475. if (dst == NULL || dst_len == 0) {
  3476. len = -2;
  3477. } else if (data == NULL || name == NULL || data_len == 0) {
  3478. len = -1;
  3479. dst[0] = '\0';
  3480. } else {
  3481. name_len = strlen(name);
  3482. e = data + data_len;
  3483. len = -1;
  3484. dst[0] = '\0';
  3485. /* data is "var1=val1&var2=val2...". Find variable first */
  3486. for (p = data; p + name_len < e; p++) {
  3487. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3488. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3489. /* Point p to variable value */
  3490. p += name_len + 1;
  3491. /* Point s to the end of the value */
  3492. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3493. if (s == NULL) {
  3494. s = e;
  3495. }
  3496. /* assert(s >= p); */
  3497. if (s < p) {
  3498. return -3;
  3499. }
  3500. /* Decode variable into destination buffer */
  3501. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3502. /* Redirect error code from -1 to -2 (destination buffer too
  3503. * small). */
  3504. if (len == -1) {
  3505. len = -2;
  3506. }
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. return len;
  3512. }
  3513. int
  3514. mg_get_cookie(const char *cookie_header,
  3515. const char *var_name,
  3516. char *dst,
  3517. size_t dst_size)
  3518. {
  3519. const char *s, *p, *end;
  3520. int name_len, len = -1;
  3521. if (dst == NULL || dst_size == 0) {
  3522. len = -2;
  3523. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3524. len = -1;
  3525. dst[0] = '\0';
  3526. } else {
  3527. name_len = (int)strlen(var_name);
  3528. end = s + strlen(s);
  3529. dst[0] = '\0';
  3530. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3531. if (s[name_len] == '=') {
  3532. s += name_len + 1;
  3533. if ((p = strchr(s, ' ')) == NULL) {
  3534. p = end;
  3535. }
  3536. if (p[-1] == ';') {
  3537. p--;
  3538. }
  3539. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3540. s++;
  3541. p--;
  3542. }
  3543. if ((size_t)(p - s) < dst_size) {
  3544. len = (int)(p - s);
  3545. mg_strlcpy(dst, s, (size_t)len + 1);
  3546. } else {
  3547. len = -3;
  3548. }
  3549. break;
  3550. }
  3551. }
  3552. }
  3553. return len;
  3554. }
  3555. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3556. static void
  3557. base64_encode(const unsigned char *src, int src_len, char *dst)
  3558. {
  3559. static const char *b64 =
  3560. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3561. int i, j, a, b, c;
  3562. for (i = j = 0; i < src_len; i += 3) {
  3563. a = src[i];
  3564. b = i + 1 >= src_len ? 0 : src[i + 1];
  3565. c = i + 2 >= src_len ? 0 : src[i + 2];
  3566. dst[j++] = b64[a >> 2];
  3567. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3568. if (i + 1 < src_len) {
  3569. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3570. }
  3571. if (i + 2 < src_len) {
  3572. dst[j++] = b64[c & 63];
  3573. }
  3574. }
  3575. while (j % 4 != 0) {
  3576. dst[j++] = '=';
  3577. }
  3578. dst[j++] = '\0';
  3579. }
  3580. #endif
  3581. #if defined(USE_LUA)
  3582. static unsigned char
  3583. b64reverse(char letter)
  3584. {
  3585. if (letter >= 'A' && letter <= 'Z') {
  3586. return letter - 'A';
  3587. }
  3588. if (letter >= 'a' && letter <= 'z') {
  3589. return letter - 'a' + 26;
  3590. }
  3591. if (letter >= '0' && letter <= '9') {
  3592. return letter - '0' + 52;
  3593. }
  3594. if (letter == '+') {
  3595. return 62;
  3596. }
  3597. if (letter == '/') {
  3598. return 63;
  3599. }
  3600. if (letter == '=') {
  3601. return 255; /* normal end */
  3602. }
  3603. return 254; /* error */
  3604. }
  3605. static int
  3606. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3607. {
  3608. int i;
  3609. unsigned char a, b, c, d;
  3610. *dst_len = 0;
  3611. for (i = 0; i < src_len; i += 4) {
  3612. a = b64reverse(src[i]);
  3613. if (a >= 254) {
  3614. return i;
  3615. }
  3616. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3617. if (b >= 254) {
  3618. return i + 1;
  3619. }
  3620. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3621. if (c == 254) {
  3622. return i + 2;
  3623. }
  3624. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3625. if (d == 254) {
  3626. return i + 3;
  3627. }
  3628. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3629. if (c != 255) {
  3630. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3631. if (d != 255) {
  3632. dst[(*dst_len)++] = (c << 6) + d;
  3633. }
  3634. }
  3635. }
  3636. return -1;
  3637. }
  3638. #endif
  3639. static int
  3640. is_put_or_delete_method(const struct mg_connection *conn)
  3641. {
  3642. if (conn) {
  3643. const char *s = conn->request_info.request_method;
  3644. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3645. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3646. }
  3647. return 0;
  3648. }
  3649. static void
  3650. interpret_uri(struct mg_connection *conn, /* in: request */
  3651. char *filename, /* out: filename */
  3652. size_t filename_buf_len, /* in: size of filename buffer */
  3653. struct file *filep, /* out: file structure */
  3654. int *is_found, /* out: file is found (directly) */
  3655. int *is_script_resource, /* out: handled by a script? */
  3656. int *is_websocket_request, /* out: websocket connetion? */
  3657. int *is_put_or_delete_request /* out: put/delete a file? */
  3658. )
  3659. {
  3660. /* TODO (high): Restructure this function */
  3661. if (conn && conn->ctx) {
  3662. #if !defined(NO_FILES)
  3663. const char *uri = conn->request_info.local_uri;
  3664. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3665. const char *rewrite;
  3666. struct vec a, b;
  3667. int match_len;
  3668. char gz_path[PATH_MAX];
  3669. char const *accept_encoding;
  3670. int truncated;
  3671. #if !defined(NO_CGI) || defined(USE_LUA)
  3672. char *p;
  3673. #endif
  3674. #else
  3675. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3676. #endif
  3677. memset(filep, 0, sizeof(*filep));
  3678. *filename = 0;
  3679. *is_found = 0;
  3680. *is_script_resource = 0;
  3681. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3682. #if defined(USE_WEBSOCKET)
  3683. *is_websocket_request = is_websocket_protocol(conn);
  3684. #if !defined(NO_FILES)
  3685. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3686. root = conn->ctx->config[WEBSOCKET_ROOT];
  3687. }
  3688. #endif /* !NO_FILES */
  3689. #else /* USE_WEBSOCKET */
  3690. *is_websocket_request = 0;
  3691. #endif /* USE_WEBSOCKET */
  3692. #if !defined(NO_FILES)
  3693. /* Note that root == NULL is a regular use case here. This occurs,
  3694. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3695. * config is not required. */
  3696. if (root == NULL) {
  3697. /* all file related outputs have already been set to 0, just return
  3698. */
  3699. return;
  3700. }
  3701. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3702. * of the path one byte on the right.
  3703. * If document_root is NULL, leave the file empty. */
  3704. mg_snprintf(conn,
  3705. &truncated,
  3706. filename,
  3707. filename_buf_len - 1,
  3708. "%s%s",
  3709. root,
  3710. uri);
  3711. if (truncated) {
  3712. goto interpret_cleanup;
  3713. }
  3714. rewrite = conn->ctx->config[REWRITE];
  3715. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3716. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3717. mg_snprintf(conn,
  3718. &truncated,
  3719. filename,
  3720. filename_buf_len - 1,
  3721. "%.*s%s",
  3722. (int)b.len,
  3723. b.ptr,
  3724. uri + match_len);
  3725. break;
  3726. }
  3727. }
  3728. if (truncated) {
  3729. goto interpret_cleanup;
  3730. }
  3731. /* Local file path and name, corresponding to requested URI
  3732. * is now stored in "filename" variable. */
  3733. if (mg_stat(conn, filename, filep)) {
  3734. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3735. /* File exists. Check if it is a script type. */
  3736. if (0
  3737. #if !defined(NO_CGI)
  3738. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3739. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3740. filename) > 0
  3741. #endif
  3742. #if defined(USE_LUA)
  3743. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3744. strlen(
  3745. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3746. filename) > 0
  3747. #endif
  3748. #if defined(USE_DUKTAPE)
  3749. || match_prefix(
  3750. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3751. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3752. filename) > 0
  3753. #endif
  3754. ) {
  3755. /* The request addresses a CGI script or a Lua script. The URI
  3756. * corresponds to the script itself (like /path/script.cgi),
  3757. * and there is no additional resource path
  3758. * (like /path/script.cgi/something).
  3759. * Requests that modify (replace or delete) a resource, like
  3760. * PUT and DELETE requests, should replace/delete the script
  3761. * file.
  3762. * Requests that read or write from/to a resource, like GET and
  3763. * POST requests, should call the script and return the
  3764. * generated response. */
  3765. *is_script_resource = !*is_put_or_delete_request;
  3766. }
  3767. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3768. *is_found = 1;
  3769. return;
  3770. }
  3771. /* If we can't find the actual file, look for the file
  3772. * with the same name but a .gz extension. If we find it,
  3773. * use that and set the gzipped flag in the file struct
  3774. * to indicate that the response need to have the content-
  3775. * encoding: gzip header.
  3776. * We can only do this if the browser declares support. */
  3777. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding"))
  3778. != NULL) {
  3779. if (strstr(accept_encoding, "gzip") != NULL) {
  3780. mg_snprintf(conn,
  3781. &truncated,
  3782. gz_path,
  3783. sizeof(gz_path),
  3784. "%s.gz",
  3785. filename);
  3786. if (truncated) {
  3787. goto interpret_cleanup;
  3788. }
  3789. if (mg_stat(conn, gz_path, filep)) {
  3790. if (filep) {
  3791. filep->gzipped = 1;
  3792. *is_found = 1;
  3793. }
  3794. /* Currently gz files can not be scripts. */
  3795. return;
  3796. }
  3797. }
  3798. }
  3799. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3800. /* Support PATH_INFO for CGI scripts. */
  3801. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3802. if (*p == '/') {
  3803. *p = '\0';
  3804. if ((0
  3805. #if !defined(NO_CGI)
  3806. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3807. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3808. filename) > 0
  3809. #endif
  3810. #if defined(USE_LUA)
  3811. || match_prefix(
  3812. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3813. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3814. filename) > 0
  3815. #endif
  3816. #if defined(USE_DUKTAPE)
  3817. || match_prefix(
  3818. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3819. strlen(
  3820. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3821. filename) > 0
  3822. #endif
  3823. ) && mg_stat(conn, filename, filep)) {
  3824. /* Shift PATH_INFO block one character right, e.g.
  3825. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3826. * conn->path_info is pointing to the local variable "path"
  3827. * declared in handle_request(), so PATH_INFO is not valid
  3828. * after handle_request returns. */
  3829. conn->path_info = p + 1;
  3830. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3831. * trailing \0 */
  3832. p[1] = '/';
  3833. *is_script_resource = 1;
  3834. break;
  3835. } else {
  3836. *p = '/';
  3837. }
  3838. }
  3839. }
  3840. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3841. #endif /* !defined(NO_FILES) */
  3842. }
  3843. return;
  3844. #if !defined(NO_FILES)
  3845. /* Reset all outputs */
  3846. interpret_cleanup:
  3847. memset(filep, 0, sizeof(*filep));
  3848. *filename = 0;
  3849. *is_found = 0;
  3850. *is_script_resource = 0;
  3851. #endif
  3852. }
  3853. /* Check whether full request is buffered. Return:
  3854. * -1 if request is malformed
  3855. * 0 if request is not yet fully buffered
  3856. * >0 actual request length, including last \r\n\r\n */
  3857. static int
  3858. get_request_len(const char *buf, int buflen)
  3859. {
  3860. const char *s, *e;
  3861. int len = 0;
  3862. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3863. /* Control characters are not allowed but >=128 is. */
  3864. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  3865. && *(const unsigned char *)s < 128) {
  3866. len = -1;
  3867. break; /* [i_a] abort scan as soon as one malformed character is
  3868. * found; */
  3869. /* don't let subsequent \r\n\r\n win us over anyhow */
  3870. } else if (s[0] == '\n' && s[1] == '\n') {
  3871. len = (int)(s - buf) + 2;
  3872. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3873. len = (int)(s - buf) + 3;
  3874. }
  3875. return len;
  3876. }
  3877. /* Convert month to the month number. Return -1 on error, or month number */
  3878. static int
  3879. get_month_index(const char *s)
  3880. {
  3881. size_t i;
  3882. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  3883. if (!strcmp(s, month_names[i])) {
  3884. return (int)i;
  3885. }
  3886. }
  3887. return -1;
  3888. }
  3889. static int
  3890. num_leap_years(int year)
  3891. {
  3892. return year / 4 - year / 100 + year / 400;
  3893. }
  3894. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3895. static time_t
  3896. parse_date_string(const char *datetime)
  3897. {
  3898. static const unsigned short days_before_month[] = {
  3899. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3900. char month_str[32] = {0};
  3901. int second, minute, hour, day, month, year, leap_days, days;
  3902. time_t result = (time_t)0;
  3903. if ((sscanf(datetime,
  3904. "%d/%3s/%d %d:%d:%d",
  3905. &day,
  3906. month_str,
  3907. &year,
  3908. &hour,
  3909. &minute,
  3910. &second) == 6) || (sscanf(datetime,
  3911. "%d %3s %d %d:%d:%d",
  3912. &day,
  3913. month_str,
  3914. &year,
  3915. &hour,
  3916. &minute,
  3917. &second) == 6)
  3918. || (sscanf(datetime,
  3919. "%*3s, %d %3s %d %d:%d:%d",
  3920. &day,
  3921. month_str,
  3922. &year,
  3923. &hour,
  3924. &minute,
  3925. &second) == 6) || (sscanf(datetime,
  3926. "%d-%3s-%d %d:%d:%d",
  3927. &day,
  3928. month_str,
  3929. &year,
  3930. &hour,
  3931. &minute,
  3932. &second) == 6)) {
  3933. month = get_month_index(month_str);
  3934. if ((month >= 0) && (year > 1970)) {
  3935. leap_days = num_leap_years(year) - num_leap_years(1970);
  3936. year -= 1970;
  3937. days =
  3938. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3939. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600
  3940. + minute * 60 + second;
  3941. }
  3942. }
  3943. return result;
  3944. }
  3945. /* Protect against directory disclosure attack by removing '..',
  3946. * excessive '/' and '\' characters */
  3947. static void
  3948. remove_double_dots_and_double_slashes(char *s)
  3949. {
  3950. char *p = s;
  3951. while (*s != '\0') {
  3952. *p++ = *s++;
  3953. if (s[-1] == '/' || s[-1] == '\\') {
  3954. /* Skip all following slashes, backslashes and double-dots */
  3955. while (s[0] != '\0') {
  3956. if (s[0] == '/' || s[0] == '\\') {
  3957. s++;
  3958. } else if (s[0] == '.' && s[1] == '.') {
  3959. s += 2;
  3960. } else {
  3961. break;
  3962. }
  3963. }
  3964. }
  3965. }
  3966. *p = '\0';
  3967. }
  3968. static const struct {
  3969. const char *extension;
  3970. size_t ext_len;
  3971. const char *mime_type;
  3972. } builtin_mime_types[] = {
  3973. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  3974. * application types */
  3975. {".doc", 4, "application/msword"},
  3976. {".eps", 4, "application/postscript"},
  3977. {".exe", 4, "application/octet-stream"},
  3978. {".js", 3, "application/javascript"},
  3979. {".json", 5, "application/json"},
  3980. {".pdf", 4, "application/pdf"},
  3981. {".ps", 3, "application/postscript"},
  3982. {".rtf", 4, "application/rtf"},
  3983. {".xhtml", 6, "application/xhtml+xml"},
  3984. {".xsl", 4, "application/xml"},
  3985. {".xslt", 5, "application/xml"},
  3986. /* audio */
  3987. {".mp3", 4, "audio/mpeg"},
  3988. {".oga", 4, "audio/ogg"},
  3989. {".ogg", 4, "audio/ogg"},
  3990. /* image */
  3991. {".gif", 4, "image/gif"},
  3992. {".ief", 4, "image/ief"},
  3993. {".jpeg", 5, "image/jpeg"},
  3994. {".jpg", 4, "image/jpeg"},
  3995. {".jpm", 4, "image/jpm"},
  3996. {".jpx", 4, "image/jpx"},
  3997. {".png", 4, "image/png"},
  3998. {".svg", 4, "image/svg+xml"},
  3999. {".tif", 4, "image/tiff"},
  4000. {".tiff", 5, "image/tiff"},
  4001. /* model */
  4002. {".wrl", 4, "model/vrml"},
  4003. /* text */
  4004. {".css", 4, "text/css"},
  4005. {".csv", 4, "text/csv"},
  4006. {".htm", 4, "text/html"},
  4007. {".html", 5, "text/html"},
  4008. {".sgm", 4, "text/sgml"},
  4009. {".shtm", 5, "text/html"},
  4010. {".shtml", 6, "text/html"},
  4011. {".txt", 4, "text/plain"},
  4012. {".xml", 4, "text/xml"},
  4013. /* video */
  4014. {".mov", 4, "video/quicktime"},
  4015. {".mp4", 4, "video/mp4"},
  4016. {".mpeg", 5, "video/mpeg"},
  4017. {".mpg", 4, "video/mpeg"},
  4018. {".ogv", 4, "video/ogg"},
  4019. {".qt", 3, "video/quicktime"},
  4020. /* not registered types
  4021. * (http://reference.sitepoint.com/html/mime-types-full,
  4022. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4023. {".arj", 4, "application/x-arj-compressed"},
  4024. {".gz", 3, "application/x-gunzip"},
  4025. {".rar", 4, "application/x-arj-compressed"},
  4026. {".swf", 4, "application/x-shockwave-flash"},
  4027. {".tar", 4, "application/x-tar"},
  4028. {".tgz", 4, "application/x-tar-gz"},
  4029. {".torrent", 8, "application/x-bittorrent"},
  4030. {".ppt", 4, "application/x-mspowerpoint"},
  4031. {".xls", 4, "application/x-msexcel"},
  4032. {".zip", 4, "application/x-zip-compressed"},
  4033. {".aac",
  4034. 4,
  4035. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4036. {".aif", 4, "audio/x-aif"},
  4037. {".m3u", 4, "audio/x-mpegurl"},
  4038. {".mid", 4, "audio/x-midi"},
  4039. {".ra", 3, "audio/x-pn-realaudio"},
  4040. {".ram", 4, "audio/x-pn-realaudio"},
  4041. {".wav", 4, "audio/x-wav"},
  4042. {".bmp", 4, "image/bmp"},
  4043. {".ico", 4, "image/x-icon"},
  4044. {".pct", 4, "image/x-pct"},
  4045. {".pict", 5, "image/pict"},
  4046. {".rgb", 4, "image/x-rgb"},
  4047. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4048. {".asf", 4, "video/x-ms-asf"},
  4049. {".avi", 4, "video/x-msvideo"},
  4050. {".m4v", 4, "video/x-m4v"},
  4051. {NULL, 0, NULL}};
  4052. const char *
  4053. mg_get_builtin_mime_type(const char *path)
  4054. {
  4055. const char *ext;
  4056. size_t i, path_len;
  4057. path_len = strlen(path);
  4058. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4059. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4060. if (path_len > builtin_mime_types[i].ext_len
  4061. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4062. return builtin_mime_types[i].mime_type;
  4063. }
  4064. }
  4065. return "text/plain";
  4066. }
  4067. /* Look at the "path" extension and figure what mime type it has.
  4068. * Store mime type in the vector. */
  4069. static void
  4070. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4071. {
  4072. struct vec ext_vec, mime_vec;
  4073. const char *list, *ext;
  4074. size_t path_len;
  4075. path_len = strlen(path);
  4076. if (ctx == NULL || vec == NULL) {
  4077. return;
  4078. }
  4079. /* Scan user-defined mime types first, in case user wants to
  4080. * override default mime types. */
  4081. list = ctx->config[EXTRA_MIME_TYPES];
  4082. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4083. /* ext now points to the path suffix */
  4084. ext = path + path_len - ext_vec.len;
  4085. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4086. *vec = mime_vec;
  4087. return;
  4088. }
  4089. }
  4090. vec->ptr = mg_get_builtin_mime_type(path);
  4091. vec->len = strlen(vec->ptr);
  4092. }
  4093. /* Stringify binary data. Output buffer must be twice as big as input,
  4094. * because each byte takes 2 bytes in string representation */
  4095. static void
  4096. bin2str(char *to, const unsigned char *p, size_t len)
  4097. {
  4098. static const char *hex = "0123456789abcdef";
  4099. for (; len--; p++) {
  4100. *to++ = hex[p[0] >> 4];
  4101. *to++ = hex[p[0] & 0x0f];
  4102. }
  4103. *to = '\0';
  4104. }
  4105. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4106. char *
  4107. mg_md5(char buf[33], ...)
  4108. {
  4109. md5_byte_t hash[16];
  4110. const char *p;
  4111. va_list ap;
  4112. md5_state_t ctx;
  4113. md5_init(&ctx);
  4114. va_start(ap, buf);
  4115. while ((p = va_arg(ap, const char *)) != NULL) {
  4116. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4117. }
  4118. va_end(ap);
  4119. md5_finish(&ctx, hash);
  4120. bin2str(buf, hash, sizeof(hash));
  4121. return buf;
  4122. }
  4123. /* Check the user's password, return 1 if OK */
  4124. static int
  4125. check_password(const char *method,
  4126. const char *ha1,
  4127. const char *uri,
  4128. const char *nonce,
  4129. const char *nc,
  4130. const char *cnonce,
  4131. const char *qop,
  4132. const char *response)
  4133. {
  4134. char ha2[32 + 1], expected_response[32 + 1];
  4135. /* Some of the parameters may be NULL */
  4136. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4137. || qop == NULL
  4138. || response == NULL) {
  4139. return 0;
  4140. }
  4141. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4142. /* TODO(lsm): check for authentication timeout */
  4143. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  4144. strlen(response) != 32
  4145. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  4146. ) {
  4147. return 0;
  4148. }
  4149. mg_md5(ha2, method, ":", uri, NULL);
  4150. mg_md5(expected_response,
  4151. ha1,
  4152. ":",
  4153. nonce,
  4154. ":",
  4155. nc,
  4156. ":",
  4157. cnonce,
  4158. ":",
  4159. qop,
  4160. ":",
  4161. ha2,
  4162. NULL);
  4163. return mg_strcasecmp(response, expected_response) == 0;
  4164. }
  4165. /* Use the global passwords file, if specified by auth_gpass option,
  4166. * or search for .htpasswd in the requested directory. */
  4167. static void
  4168. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4169. {
  4170. if (conn != NULL && conn->ctx != NULL) {
  4171. char name[PATH_MAX];
  4172. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4173. struct file file = STRUCT_FILE_INITIALIZER;
  4174. int truncated;
  4175. if (gpass != NULL) {
  4176. /* Use global passwords file */
  4177. if (!mg_fopen(conn, gpass, "r", filep)) {
  4178. #ifdef DEBUG
  4179. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4180. #endif
  4181. }
  4182. /* Important: using local struct file to test path for is_directory
  4183. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4184. * was opened. */
  4185. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4186. mg_snprintf(conn,
  4187. &truncated,
  4188. name,
  4189. sizeof(name),
  4190. "%s/%s",
  4191. path,
  4192. PASSWORDS_FILE_NAME);
  4193. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4194. #ifdef DEBUG
  4195. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4196. #endif
  4197. }
  4198. } else {
  4199. /* Try to find .htpasswd in requested directory. */
  4200. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4201. if (e[0] == '/') {
  4202. break;
  4203. }
  4204. }
  4205. mg_snprintf(conn,
  4206. &truncated,
  4207. name,
  4208. sizeof(name),
  4209. "%.*s%s",
  4210. (int)(e - p),
  4211. p,
  4212. PASSWORDS_FILE_NAME);
  4213. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4214. #ifdef DEBUG
  4215. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4216. #endif
  4217. }
  4218. }
  4219. }
  4220. }
  4221. /* Parsed Authorization header */
  4222. struct ah {
  4223. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4224. };
  4225. /* Return 1 on success. Always initializes the ah structure. */
  4226. static int
  4227. parse_auth_header(struct mg_connection *conn,
  4228. char *buf,
  4229. size_t buf_size,
  4230. struct ah *ah)
  4231. {
  4232. char *name, *value, *s;
  4233. const char *auth_header;
  4234. unsigned long nonce;
  4235. if (!ah || !conn) {
  4236. return 0;
  4237. }
  4238. (void)memset(ah, 0, sizeof(*ah));
  4239. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4240. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4241. return 0;
  4242. }
  4243. /* Make modifiable copy of the auth header */
  4244. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4245. s = buf;
  4246. /* Parse authorization header */
  4247. for (;;) {
  4248. /* Gobble initial spaces */
  4249. while (isspace(*(unsigned char *)s)) {
  4250. s++;
  4251. }
  4252. name = skip_quoted(&s, "=", " ", 0);
  4253. /* Value is either quote-delimited, or ends at first comma or space. */
  4254. if (s[0] == '\"') {
  4255. s++;
  4256. value = skip_quoted(&s, "\"", " ", '\\');
  4257. if (s[0] == ',') {
  4258. s++;
  4259. }
  4260. } else {
  4261. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4262. * spaces */
  4263. }
  4264. if (*name == '\0') {
  4265. break;
  4266. }
  4267. if (!strcmp(name, "username")) {
  4268. ah->user = value;
  4269. } else if (!strcmp(name, "cnonce")) {
  4270. ah->cnonce = value;
  4271. } else if (!strcmp(name, "response")) {
  4272. ah->response = value;
  4273. } else if (!strcmp(name, "uri")) {
  4274. ah->uri = value;
  4275. } else if (!strcmp(name, "qop")) {
  4276. ah->qop = value;
  4277. } else if (!strcmp(name, "nc")) {
  4278. ah->nc = value;
  4279. } else if (!strcmp(name, "nonce")) {
  4280. ah->nonce = value;
  4281. }
  4282. }
  4283. #ifndef NO_NONCE_CHECK
  4284. /* Convert the nonce from the client to a number and check it. */
  4285. /* Server side nonce check is valuable in all situations but one: if the
  4286. * server restarts frequently,
  4287. * but the client should not see that, so the server should accept nonces
  4288. * from
  4289. * previous starts. */
  4290. if (ah->nonce == NULL) {
  4291. return 0;
  4292. }
  4293. s = NULL;
  4294. nonce = strtoul(ah->nonce, &s, 10);
  4295. if ((s == NULL) || (*s != 0)) {
  4296. return 0;
  4297. }
  4298. nonce ^= (uintptr_t)(conn->ctx);
  4299. if (nonce < conn->ctx->start_time) {
  4300. /* nonce is from a previous start of the server and no longer valid
  4301. * (replay attack?) */
  4302. return 0;
  4303. }
  4304. if (nonce >= conn->ctx->start_time + conn->ctx->nonce_count) {
  4305. return 0;
  4306. }
  4307. #endif
  4308. /* CGI needs it as REMOTE_USER */
  4309. if (ah->user != NULL) {
  4310. conn->request_info.remote_user = mg_strdup(ah->user);
  4311. } else {
  4312. return 0;
  4313. }
  4314. return 1;
  4315. }
  4316. static char *
  4317. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4318. {
  4319. char *eof;
  4320. size_t len;
  4321. char *memend;
  4322. if (!filep) {
  4323. return NULL;
  4324. }
  4325. if (filep->membuf != NULL && *p != NULL) {
  4326. memend = (char *)&filep->membuf[filep->size];
  4327. /* Search for \n from p till the end of stream */
  4328. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4329. if (eof != NULL) {
  4330. eof += 1; /* Include \n */
  4331. } else {
  4332. eof = memend; /* Copy remaining data */
  4333. }
  4334. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4335. memcpy(buf, *p, len);
  4336. buf[len] = '\0';
  4337. *p += len;
  4338. return len ? eof : NULL;
  4339. } else if (filep->fp != NULL) {
  4340. return fgets(buf, (int)size, filep->fp);
  4341. } else {
  4342. return NULL;
  4343. }
  4344. }
  4345. struct read_auth_file_struct {
  4346. struct mg_connection *conn;
  4347. struct ah ah;
  4348. char *domain;
  4349. char buf[256 + 256 + 40];
  4350. char *f_user;
  4351. char *f_domain;
  4352. char *f_ha1;
  4353. };
  4354. static int
  4355. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4356. {
  4357. char *p;
  4358. int is_authorized = 0;
  4359. struct file fp;
  4360. size_t l;
  4361. if (!filep || !workdata) {
  4362. return 0;
  4363. }
  4364. /* Loop over passwords file */
  4365. p = (char *)filep->membuf;
  4366. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4367. l = strlen(workdata->buf);
  4368. while (l > 0) {
  4369. if (isspace(workdata->buf[l - 1])
  4370. || iscntrl(workdata->buf[l - 1])) {
  4371. l--;
  4372. workdata->buf[l] = 0;
  4373. } else
  4374. break;
  4375. }
  4376. if (l < 1) {
  4377. continue;
  4378. }
  4379. workdata->f_user = workdata->buf;
  4380. if (workdata->f_user[0] == ':') {
  4381. /* user names may not contain a ':' and may not be empty,
  4382. * so lines starting with ':' may be used for a special purpose */
  4383. if (workdata->f_user[1] == '#') {
  4384. /* :# is a comment */
  4385. continue;
  4386. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4387. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4388. is_authorized = read_auth_file(&fp, workdata);
  4389. mg_fclose(&fp);
  4390. } else {
  4391. mg_cry(workdata->conn,
  4392. "%s: cannot open authorization file: %s",
  4393. __func__,
  4394. workdata->buf);
  4395. }
  4396. continue;
  4397. }
  4398. /* everything is invalid for the moment (might change in the
  4399. * future) */
  4400. mg_cry(workdata->conn,
  4401. "%s: syntax error in authorization file: %s",
  4402. __func__,
  4403. workdata->buf);
  4404. continue;
  4405. }
  4406. workdata->f_domain = strchr(workdata->f_user, ':');
  4407. if (workdata->f_domain == NULL) {
  4408. mg_cry(workdata->conn,
  4409. "%s: syntax error in authorization file: %s",
  4410. __func__,
  4411. workdata->buf);
  4412. continue;
  4413. }
  4414. *(workdata->f_domain) = 0;
  4415. (workdata->f_domain)++;
  4416. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4417. if (workdata->f_ha1 == NULL) {
  4418. mg_cry(workdata->conn,
  4419. "%s: syntax error in authorization file: %s",
  4420. __func__,
  4421. workdata->buf);
  4422. continue;
  4423. }
  4424. *(workdata->f_ha1) = 0;
  4425. (workdata->f_ha1)++;
  4426. if (!strcmp(workdata->ah.user, workdata->f_user)
  4427. && !strcmp(workdata->domain, workdata->f_domain)) {
  4428. return check_password(workdata->conn->request_info.request_method,
  4429. workdata->f_ha1,
  4430. workdata->ah.uri,
  4431. workdata->ah.nonce,
  4432. workdata->ah.nc,
  4433. workdata->ah.cnonce,
  4434. workdata->ah.qop,
  4435. workdata->ah.response);
  4436. }
  4437. }
  4438. return is_authorized;
  4439. }
  4440. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4441. static int
  4442. authorize(struct mg_connection *conn, struct file *filep)
  4443. {
  4444. struct read_auth_file_struct workdata;
  4445. char buf[MG_BUF_LEN];
  4446. if (!conn || !conn->ctx) {
  4447. return 0;
  4448. }
  4449. memset(&workdata, 0, sizeof(workdata));
  4450. workdata.conn = conn;
  4451. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4452. return 0;
  4453. }
  4454. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4455. return read_auth_file(filep, &workdata);
  4456. }
  4457. /* Return 1 if request is authorised, 0 otherwise. */
  4458. static int
  4459. check_authorization(struct mg_connection *conn, const char *path)
  4460. {
  4461. char fname[PATH_MAX];
  4462. struct vec uri_vec, filename_vec;
  4463. const char *list;
  4464. struct file file = STRUCT_FILE_INITIALIZER;
  4465. int authorized = 1, truncated;
  4466. if (!conn || !conn->ctx) {
  4467. return 0;
  4468. }
  4469. list = conn->ctx->config[PROTECT_URI];
  4470. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4471. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4472. mg_snprintf(conn,
  4473. &truncated,
  4474. fname,
  4475. sizeof(fname),
  4476. "%.*s",
  4477. (int)filename_vec.len,
  4478. filename_vec.ptr);
  4479. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4480. mg_cry(conn,
  4481. "%s: cannot open %s: %s",
  4482. __func__,
  4483. fname,
  4484. strerror(errno));
  4485. }
  4486. break;
  4487. }
  4488. }
  4489. if (!is_file_opened(&file)) {
  4490. open_auth_file(conn, path, &file);
  4491. }
  4492. if (is_file_opened(&file)) {
  4493. authorized = authorize(conn, &file);
  4494. mg_fclose(&file);
  4495. }
  4496. return authorized;
  4497. }
  4498. static void
  4499. send_authorization_request(struct mg_connection *conn)
  4500. {
  4501. char date[64];
  4502. time_t curtime = time(NULL);
  4503. if (conn && conn->ctx) {
  4504. unsigned long nonce = (unsigned long)(conn->ctx->start_time);
  4505. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4506. nonce += conn->ctx->nonce_count;
  4507. ++conn->ctx->nonce_count;
  4508. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4509. nonce ^= (uintptr_t)(conn->ctx);
  4510. conn->status_code = 401;
  4511. conn->must_close = 1;
  4512. gmt_time_string(date, sizeof(date), &curtime);
  4513. mg_printf(conn,
  4514. "HTTP/1.1 401 Unauthorized\r\n"
  4515. "Date: %s\r\n"
  4516. "Connection: %s\r\n"
  4517. "Content-Length: 0\r\n"
  4518. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4519. "nonce=\"%lu\"\r\n\r\n",
  4520. date,
  4521. suggest_connection_header(conn),
  4522. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4523. nonce);
  4524. }
  4525. }
  4526. #if !defined(NO_FILES)
  4527. static int
  4528. is_authorized_for_put(struct mg_connection *conn)
  4529. {
  4530. if (conn) {
  4531. struct file file = STRUCT_FILE_INITIALIZER;
  4532. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4533. int ret = 0;
  4534. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4535. ret = authorize(conn, &file);
  4536. mg_fclose(&file);
  4537. }
  4538. return ret;
  4539. }
  4540. return 0;
  4541. }
  4542. #endif
  4543. int
  4544. mg_modify_passwords_file(const char *fname,
  4545. const char *domain,
  4546. const char *user,
  4547. const char *pass)
  4548. {
  4549. int found, i;
  4550. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4551. FILE *fp, *fp2;
  4552. found = 0;
  4553. fp = fp2 = NULL;
  4554. /* Regard empty password as no password - remove user record. */
  4555. if (pass != NULL && pass[0] == '\0') {
  4556. pass = NULL;
  4557. }
  4558. /* Other arguments must not be empty */
  4559. if (fname == NULL || domain == NULL || user == NULL) {
  4560. return 0;
  4561. }
  4562. /* Using the given file format, user name and domain must not contain ':'
  4563. */
  4564. if (strchr(user, ':') != NULL) {
  4565. return 0;
  4566. }
  4567. if (strchr(domain, ':') != NULL) {
  4568. return 0;
  4569. }
  4570. /* Do not allow control characters like newline in user name and domain.
  4571. * Do not allow excessively long names either. */
  4572. for (i = 0; i < 255 && user[i] != 0; i++) {
  4573. if (iscntrl(user[i])) {
  4574. return 0;
  4575. }
  4576. }
  4577. if (user[i]) {
  4578. return 0;
  4579. }
  4580. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4581. if (iscntrl(domain[i])) {
  4582. return 0;
  4583. }
  4584. }
  4585. if (domain[i]) {
  4586. return 0;
  4587. }
  4588. /* The maximum length of the path to the password file is limited */
  4589. if ((strlen(fname) + 4) >= PATH_MAX) {
  4590. return 0;
  4591. }
  4592. /* Create a temporary file name. Length has been checked before. */
  4593. strcpy(tmp, fname);
  4594. strcat(tmp, ".tmp");
  4595. /* Create the file if does not exist */
  4596. if ((fp = fopen(fname, "a+")) != NULL) {
  4597. (void)fclose(fp);
  4598. }
  4599. /* Open the given file and temporary file */
  4600. if ((fp = fopen(fname, "r")) == NULL) {
  4601. return 0;
  4602. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4603. fclose(fp);
  4604. return 0;
  4605. }
  4606. /* Copy the stuff to temporary file */
  4607. while (fgets(line, sizeof(line), fp) != NULL) {
  4608. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4609. continue;
  4610. }
  4611. u[255] = 0;
  4612. d[255] = 0;
  4613. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4614. found++;
  4615. if (pass != NULL) {
  4616. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4617. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4618. }
  4619. } else {
  4620. fprintf(fp2, "%s", line);
  4621. }
  4622. }
  4623. /* If new user, just add it */
  4624. if (!found && pass != NULL) {
  4625. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4626. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4627. }
  4628. /* Close files */
  4629. fclose(fp);
  4630. fclose(fp2);
  4631. /* Put the temp file in place of real file */
  4632. IGNORE_UNUSED_RESULT(remove(fname));
  4633. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4634. return 1;
  4635. }
  4636. static int
  4637. is_valid_port(unsigned long port)
  4638. {
  4639. return port < 0xffff;
  4640. }
  4641. static int
  4642. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4643. {
  4644. struct addrinfo hints, *res, *ressave;
  4645. int ret = 0;
  4646. memset(&hints, 0, sizeof(struct addrinfo));
  4647. hints.ai_family = af;
  4648. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4649. /* bad src string or bad address family */
  4650. return 0;
  4651. }
  4652. ressave = res;
  4653. while (res) {
  4654. if (dstlen >= res->ai_addrlen) {
  4655. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4656. ret = 1;
  4657. }
  4658. res = res->ai_next;
  4659. }
  4660. freeaddrinfo(ressave);
  4661. return ret;
  4662. }
  4663. static int
  4664. connect_socket(struct mg_context *ctx /* may be NULL */,
  4665. const char *host,
  4666. int port,
  4667. int use_ssl,
  4668. char *ebuf,
  4669. size_t ebuf_len,
  4670. SOCKET *sock /* output: socket, must not be NULL */,
  4671. union usa *sa /* output: socket address, must not be NULL */
  4672. )
  4673. {
  4674. int ip_ver = 0;
  4675. *sock = INVALID_SOCKET;
  4676. memset(sa, 0, sizeof(*sa));
  4677. if (ebuf_len > 0) {
  4678. *ebuf = 0;
  4679. }
  4680. if (host == NULL) {
  4681. mg_snprintf(NULL,
  4682. NULL, /* No truncation check for ebuf */
  4683. ebuf,
  4684. ebuf_len,
  4685. "%s",
  4686. "NULL host");
  4687. return 0;
  4688. }
  4689. if (port < 0 || !is_valid_port((unsigned)port)) {
  4690. mg_snprintf(NULL,
  4691. NULL, /* No truncation check for ebuf */
  4692. ebuf,
  4693. ebuf_len,
  4694. "%s",
  4695. "invalid port");
  4696. return 0;
  4697. }
  4698. if (use_ssl && (SSLv23_client_method == NULL)) {
  4699. mg_snprintf(NULL,
  4700. NULL, /* No truncation check for ebuf */
  4701. ebuf,
  4702. ebuf_len,
  4703. "%s",
  4704. "SSL is not initialized");
  4705. return 0;
  4706. }
  4707. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4708. sa->sin.sin_port = htons((uint16_t)port);
  4709. ip_ver = 4;
  4710. #ifdef USE_IPV6
  4711. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4712. sa->sin6.sin6_port = htons((uint16_t)port);
  4713. ip_ver = 6;
  4714. } else if (host[0] == '[') {
  4715. /* While getaddrinfo on Windows will work with [::1],
  4716. * getaddrinfo on Linux only works with ::1 (without []). */
  4717. size_t l = strlen(host + 1);
  4718. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4719. if (h) {
  4720. h[l - 1] = 0;
  4721. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4722. sa->sin6.sin6_port = htons((uint16_t)port);
  4723. ip_ver = 6;
  4724. }
  4725. mg_free(h);
  4726. }
  4727. #endif
  4728. }
  4729. if (ip_ver == 0) {
  4730. mg_snprintf(NULL,
  4731. NULL, /* No truncation check for ebuf */
  4732. ebuf,
  4733. ebuf_len,
  4734. "%s",
  4735. "host not found");
  4736. return 0;
  4737. }
  4738. if (ip_ver == 4) {
  4739. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4740. }
  4741. #ifdef USE_IPV6
  4742. else if (ip_ver == 6) {
  4743. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4744. }
  4745. #endif
  4746. if (*sock == INVALID_SOCKET) {
  4747. mg_snprintf(NULL,
  4748. NULL, /* No truncation check for ebuf */
  4749. ebuf,
  4750. ebuf_len,
  4751. "socket(): %s",
  4752. strerror(ERRNO));
  4753. return 0;
  4754. }
  4755. set_close_on_exec(*sock, fc(ctx));
  4756. if ((ip_ver == 4)
  4757. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  4758. == 0)) {
  4759. /* connected with IPv4 */
  4760. return 1;
  4761. }
  4762. #ifdef USE_IPV6
  4763. if ((ip_ver == 6)
  4764. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  4765. == 0)) {
  4766. /* connected with IPv6 */
  4767. return 1;
  4768. }
  4769. #endif
  4770. /* Not connected */
  4771. mg_snprintf(NULL,
  4772. NULL, /* No truncation check for ebuf */
  4773. ebuf,
  4774. ebuf_len,
  4775. "connect(%s:%d): %s",
  4776. host,
  4777. port,
  4778. strerror(ERRNO));
  4779. closesocket(*sock);
  4780. *sock = INVALID_SOCKET;
  4781. return 0;
  4782. }
  4783. int
  4784. mg_url_encode(const char *src, char *dst, size_t dst_len)
  4785. {
  4786. static const char *dont_escape = "._-$,;~()";
  4787. static const char *hex = "0123456789abcdef";
  4788. char *pos = dst;
  4789. const char *end = dst + dst_len - 1;
  4790. for (; *src != '\0' && pos < end; src++, pos++) {
  4791. if (isalnum(*(const unsigned char *)src)
  4792. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4793. *pos = *src;
  4794. } else if (pos + 2 < end) {
  4795. pos[0] = '%';
  4796. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4797. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4798. pos += 2;
  4799. } else {
  4800. break;
  4801. }
  4802. }
  4803. *pos = '\0';
  4804. return (*src == '\0') ? (int)(pos - dst) : -1;
  4805. }
  4806. static void
  4807. print_dir_entry(struct de *de)
  4808. {
  4809. char size[64], mod[64], href[PATH_MAX];
  4810. struct tm *tm;
  4811. if (de->file.is_directory) {
  4812. mg_snprintf(de->conn,
  4813. NULL, /* Buffer is big enough */
  4814. size,
  4815. sizeof(size),
  4816. "%s",
  4817. "[DIRECTORY]");
  4818. } else {
  4819. /* We use (signed) cast below because MSVC 6 compiler cannot
  4820. * convert unsigned __int64 to double. Sigh. */
  4821. if (de->file.size < 1024) {
  4822. mg_snprintf(de->conn,
  4823. NULL, /* Buffer is big enough */
  4824. size,
  4825. sizeof(size),
  4826. "%d",
  4827. (int)de->file.size);
  4828. } else if (de->file.size < 0x100000) {
  4829. mg_snprintf(de->conn,
  4830. NULL, /* Buffer is big enough */
  4831. size,
  4832. sizeof(size),
  4833. "%.1fk",
  4834. (double)de->file.size / 1024.0);
  4835. } else if (de->file.size < 0x40000000) {
  4836. mg_snprintf(de->conn,
  4837. NULL, /* Buffer is big enough */
  4838. size,
  4839. sizeof(size),
  4840. "%.1fM",
  4841. (double)de->file.size / 1048576);
  4842. } else {
  4843. mg_snprintf(de->conn,
  4844. NULL, /* Buffer is big enough */
  4845. size,
  4846. sizeof(size),
  4847. "%.1fG",
  4848. (double)de->file.size / 1073741824);
  4849. }
  4850. }
  4851. /* Note: mg_snprintf will not cause a buffer overflow above.
  4852. * So, string truncation checks are not required here. */
  4853. tm = localtime(&de->file.last_modified);
  4854. if (tm != NULL) {
  4855. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4856. } else {
  4857. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4858. mod[sizeof(mod) - 1] = '\0';
  4859. }
  4860. mg_url_encode(de->file_name, href, sizeof(href));
  4861. de->conn->num_bytes_sent +=
  4862. mg_printf(de->conn,
  4863. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4864. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4865. de->conn->request_info.local_uri,
  4866. href,
  4867. de->file.is_directory ? "/" : "",
  4868. de->file_name,
  4869. de->file.is_directory ? "/" : "",
  4870. mod,
  4871. size);
  4872. }
  4873. /* This function is called from send_directory() and used for
  4874. * sorting directory entries by size, or name, or modification time.
  4875. * On windows, __cdecl specification is needed in case if project is built
  4876. * with __stdcall convention. qsort always requires __cdels callback. */
  4877. static int WINCDECL
  4878. compare_dir_entries(const void *p1, const void *p2)
  4879. {
  4880. if (p1 && p2) {
  4881. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4882. const char *query_string = a->conn->request_info.query_string;
  4883. int cmp_result = 0;
  4884. if (query_string == NULL) {
  4885. query_string = "na";
  4886. }
  4887. if (a->file.is_directory && !b->file.is_directory) {
  4888. return -1; /* Always put directories on top */
  4889. } else if (!a->file.is_directory && b->file.is_directory) {
  4890. return 1; /* Always put directories on top */
  4891. } else if (*query_string == 'n') {
  4892. cmp_result = strcmp(a->file_name, b->file_name);
  4893. } else if (*query_string == 's') {
  4894. cmp_result = a->file.size == b->file.size
  4895. ? 0
  4896. : a->file.size > b->file.size ? 1 : -1;
  4897. } else if (*query_string == 'd') {
  4898. cmp_result =
  4899. (a->file.last_modified == b->file.last_modified)
  4900. ? 0
  4901. : ((a->file.last_modified > b->file.last_modified) ? 1
  4902. : -1);
  4903. }
  4904. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  4905. }
  4906. return 0;
  4907. }
  4908. static int
  4909. must_hide_file(struct mg_connection *conn, const char *path)
  4910. {
  4911. if (conn && conn->ctx) {
  4912. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  4913. const char *pattern = conn->ctx->config[HIDE_FILES];
  4914. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  4915. || (pattern != NULL
  4916. && match_prefix(pattern, strlen(pattern), path) > 0);
  4917. }
  4918. return 0;
  4919. }
  4920. static int
  4921. scan_directory(struct mg_connection *conn,
  4922. const char *dir,
  4923. void *data,
  4924. void (*cb)(struct de *, void *))
  4925. {
  4926. char path[PATH_MAX];
  4927. struct dirent *dp;
  4928. DIR *dirp;
  4929. struct de de;
  4930. int truncated;
  4931. if ((dirp = opendir(dir)) == NULL) {
  4932. return 0;
  4933. } else {
  4934. de.conn = conn;
  4935. while ((dp = readdir(dirp)) != NULL) {
  4936. /* Do not show current dir and hidden files */
  4937. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  4938. || must_hide_file(conn, dp->d_name)) {
  4939. continue;
  4940. }
  4941. mg_snprintf(
  4942. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  4943. /* If we don't memset stat structure to zero, mtime will have
  4944. * garbage and strftime() will segfault later on in
  4945. * print_dir_entry(). memset is required only if mg_stat()
  4946. * fails. For more details, see
  4947. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4948. memset(&de.file, 0, sizeof(de.file));
  4949. if (truncated) {
  4950. /* If the path is not complete, skip processing. */
  4951. continue;
  4952. }
  4953. if (!mg_stat(conn, path, &de.file)) {
  4954. mg_cry(conn,
  4955. "%s: mg_stat(%s) failed: %s",
  4956. __func__,
  4957. path,
  4958. strerror(ERRNO));
  4959. }
  4960. de.file_name = dp->d_name;
  4961. cb(&de, data);
  4962. }
  4963. (void)closedir(dirp);
  4964. }
  4965. return 1;
  4966. }
  4967. #if !defined(NO_FILES)
  4968. static int
  4969. remove_directory(struct mg_connection *conn, const char *dir)
  4970. {
  4971. char path[PATH_MAX];
  4972. struct dirent *dp;
  4973. DIR *dirp;
  4974. struct de de;
  4975. int truncated;
  4976. int ok = 1;
  4977. if ((dirp = opendir(dir)) == NULL) {
  4978. return 0;
  4979. } else {
  4980. de.conn = conn;
  4981. while ((dp = readdir(dirp)) != NULL) {
  4982. /* Do not show current dir (but show hidden files as they will
  4983. * also be removed) */
  4984. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  4985. continue;
  4986. }
  4987. mg_snprintf(
  4988. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  4989. /* If we don't memset stat structure to zero, mtime will have
  4990. * garbage and strftime() will segfault later on in
  4991. * print_dir_entry(). memset is required only if mg_stat()
  4992. * fails. For more details, see
  4993. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4994. memset(&de.file, 0, sizeof(de.file));
  4995. if (truncated) {
  4996. /* Do not delete anything shorter */
  4997. continue;
  4998. }
  4999. if (!mg_stat(conn, path, &de.file)) {
  5000. mg_cry(conn,
  5001. "%s: mg_stat(%s) failed: %s",
  5002. __func__,
  5003. path,
  5004. strerror(ERRNO));
  5005. }
  5006. if (de.file.membuf == NULL) {
  5007. /* file is not in memory */
  5008. if (de.file.is_directory) {
  5009. if (remove_directory(conn, path) == 0) {
  5010. ok = 0;
  5011. }
  5012. } else {
  5013. if (mg_remove(path) == 0) {
  5014. ok = 0;
  5015. }
  5016. }
  5017. }
  5018. }
  5019. (void)closedir(dirp);
  5020. IGNORE_UNUSED_RESULT(rmdir(dir));
  5021. }
  5022. return ok;
  5023. }
  5024. #endif
  5025. struct dir_scan_data {
  5026. struct de *entries;
  5027. unsigned int num_entries;
  5028. unsigned int arr_size;
  5029. };
  5030. /* Behaves like realloc(), but frees original pointer on failure */
  5031. static void *
  5032. realloc2(void *ptr, size_t size)
  5033. {
  5034. void *new_ptr = mg_realloc(ptr, size);
  5035. if (new_ptr == NULL) {
  5036. mg_free(ptr);
  5037. }
  5038. return new_ptr;
  5039. }
  5040. static void
  5041. dir_scan_callback(struct de *de, void *data)
  5042. {
  5043. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5044. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5045. dsd->arr_size *= 2;
  5046. dsd->entries =
  5047. (struct de *)realloc2(dsd->entries,
  5048. dsd->arr_size * sizeof(dsd->entries[0]));
  5049. }
  5050. if (dsd->entries == NULL) {
  5051. /* TODO(lsm, low): propagate an error to the caller */
  5052. dsd->num_entries = 0;
  5053. } else {
  5054. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5055. dsd->entries[dsd->num_entries].file = de->file;
  5056. dsd->entries[dsd->num_entries].conn = de->conn;
  5057. dsd->num_entries++;
  5058. }
  5059. }
  5060. static void
  5061. handle_directory_request(struct mg_connection *conn, const char *dir)
  5062. {
  5063. unsigned int i;
  5064. int sort_direction;
  5065. struct dir_scan_data data = {NULL, 0, 128};
  5066. char date[64];
  5067. time_t curtime = time(NULL);
  5068. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5069. send_http_error(conn,
  5070. 500,
  5071. "Error: Cannot open directory\nopendir(%s): %s",
  5072. dir,
  5073. strerror(ERRNO));
  5074. return;
  5075. }
  5076. gmt_time_string(date, sizeof(date), &curtime);
  5077. if (!conn) {
  5078. return;
  5079. }
  5080. sort_direction = conn->request_info.query_string != NULL
  5081. && conn->request_info.query_string[1] == 'd'
  5082. ? 'a'
  5083. : 'd';
  5084. conn->must_close = 1;
  5085. mg_printf(conn,
  5086. "HTTP/1.1 200 OK\r\n"
  5087. "Date: %s\r\n"
  5088. "Connection: close\r\n"
  5089. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5090. date);
  5091. conn->num_bytes_sent +=
  5092. mg_printf(conn,
  5093. "<html><head><title>Index of %s</title>"
  5094. "<style>th {text-align: left;}</style></head>"
  5095. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5096. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5097. "<th><a href=\"?d%c\">Modified</a></th>"
  5098. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5099. "<tr><td colspan=\"3\"><hr></td></tr>",
  5100. conn->request_info.local_uri,
  5101. conn->request_info.local_uri,
  5102. sort_direction,
  5103. sort_direction,
  5104. sort_direction);
  5105. /* Print first entry - link to a parent directory */
  5106. conn->num_bytes_sent +=
  5107. mg_printf(conn,
  5108. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5109. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5110. conn->request_info.local_uri,
  5111. "..",
  5112. "Parent directory",
  5113. "-",
  5114. "-");
  5115. /* Sort and print directory entries */
  5116. if (data.entries != NULL) {
  5117. qsort(data.entries,
  5118. (size_t)data.num_entries,
  5119. sizeof(data.entries[0]),
  5120. compare_dir_entries);
  5121. for (i = 0; i < data.num_entries; i++) {
  5122. print_dir_entry(&data.entries[i]);
  5123. mg_free(data.entries[i].file_name);
  5124. }
  5125. mg_free(data.entries);
  5126. }
  5127. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5128. conn->status_code = 200;
  5129. }
  5130. /* Send len bytes from the opened file to the client. */
  5131. static void
  5132. send_file_data(struct mg_connection *conn,
  5133. struct file *filep,
  5134. int64_t offset,
  5135. int64_t len)
  5136. {
  5137. char buf[MG_BUF_LEN];
  5138. int to_read, num_read, num_written;
  5139. int64_t size;
  5140. if (!filep || !conn) {
  5141. return;
  5142. }
  5143. /* Sanity check the offset */
  5144. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5145. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5146. if (len > 0 && filep->membuf != NULL && size > 0) {
  5147. /* file stored in memory */
  5148. if (len > size - offset) {
  5149. len = size - offset;
  5150. }
  5151. mg_write(conn, filep->membuf + offset, (size_t)len);
  5152. } else if (len > 0 && filep->fp != NULL) {
  5153. /* file stored on disk */
  5154. #if defined(__linux__)
  5155. /* sendfile is only available for Linux */
  5156. if (conn->throttle == 0 && conn->ssl == 0) {
  5157. off_t sf_offs = (off_t)offset;
  5158. ssize_t sf_sent;
  5159. int sf_file = fileno(filep->fp);
  5160. int loop_cnt = 0;
  5161. do {
  5162. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5163. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5164. size_t sf_tosend =
  5165. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5166. sf_sent =
  5167. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5168. if (sf_sent > 0) {
  5169. conn->num_bytes_sent += sf_sent;
  5170. len -= sf_sent;
  5171. offset += sf_sent;
  5172. } else if (loop_cnt == 0) {
  5173. /* This file can not be sent using sendfile.
  5174. * This might be the case for pseudo-files in the
  5175. * /sys/ and /proc/ file system.
  5176. * Use the regular user mode copy code instead. */
  5177. break;
  5178. } else if (sf_sent == 0) {
  5179. /* No error, but 0 bytes sent. May be EOF? */
  5180. return;
  5181. }
  5182. loop_cnt++;
  5183. } while ((len > 0) && (sf_sent >= 0));
  5184. if (sf_sent > 0) {
  5185. return; /* OK */
  5186. }
  5187. /* sf_sent<0 means error, thus fall back to the classic way */
  5188. /* This is always the case, if sf_file is not a "normal" file,
  5189. * e.g., for sending data from the output of a CGI process. */
  5190. offset = (int64_t)sf_offs;
  5191. }
  5192. #endif
  5193. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5194. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5195. send_http_error(
  5196. conn,
  5197. 500,
  5198. "%s",
  5199. "Error: Unable to access file at requested position.");
  5200. } else {
  5201. while (len > 0) {
  5202. /* Calculate how much to read from the file in the buffer */
  5203. to_read = sizeof(buf);
  5204. if ((int64_t)to_read > len) {
  5205. to_read = (int)len;
  5206. }
  5207. /* Read from file, exit the loop on error */
  5208. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5209. <= 0) {
  5210. break;
  5211. }
  5212. /* Send read bytes to the client, exit the loop on error */
  5213. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5214. != num_read) {
  5215. break;
  5216. }
  5217. /* Both read and were successful, adjust counters */
  5218. conn->num_bytes_sent += num_written;
  5219. len -= num_written;
  5220. }
  5221. }
  5222. }
  5223. }
  5224. static int
  5225. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5226. {
  5227. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5228. }
  5229. static void
  5230. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5231. {
  5232. if (filep != NULL && buf != NULL) {
  5233. mg_snprintf(NULL,
  5234. NULL, /* All calls to construct_etag use 64 byte buffer */
  5235. buf,
  5236. buf_len,
  5237. "\"%lx.%" INT64_FMT "\"",
  5238. (unsigned long)filep->last_modified,
  5239. filep->size);
  5240. }
  5241. }
  5242. static void
  5243. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5244. {
  5245. if (filep != NULL && filep->fp != NULL) {
  5246. #ifdef _WIN32
  5247. (void)conn; /* Unused. */
  5248. #else
  5249. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5250. mg_cry(conn,
  5251. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5252. __func__,
  5253. strerror(ERRNO));
  5254. }
  5255. #endif
  5256. }
  5257. }
  5258. static void
  5259. handle_static_file_request(struct mg_connection *conn,
  5260. const char *path,
  5261. struct file *filep)
  5262. {
  5263. char date[64], lm[64], etag[64];
  5264. char range[128]; /* large enough, so there will be no overflow */
  5265. const char *msg = "OK", *hdr;
  5266. time_t curtime = time(NULL);
  5267. int64_t cl, r1, r2;
  5268. struct vec mime_vec;
  5269. int n, truncated;
  5270. char gz_path[PATH_MAX];
  5271. const char *encoding = "";
  5272. const char *cors1, *cors2, *cors3;
  5273. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5274. return;
  5275. }
  5276. get_mime_type(conn->ctx, path, &mime_vec);
  5277. if (filep->size > INT64_MAX) {
  5278. send_http_error(conn,
  5279. 500,
  5280. "Error: File size is too large to send\n%" INT64_FMT,
  5281. filep->size);
  5282. }
  5283. cl = (int64_t)filep->size;
  5284. conn->status_code = 200;
  5285. range[0] = '\0';
  5286. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5287. * it's important to rewrite the filename after resolving
  5288. * the mime type from it, to preserve the actual file's type */
  5289. if (filep->gzipped) {
  5290. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5291. if (truncated) {
  5292. send_http_error(conn,
  5293. 500,
  5294. "Error: Path of zipped file too long (%s)",
  5295. path);
  5296. return;
  5297. }
  5298. path = gz_path;
  5299. encoding = "Content-Encoding: gzip\r\n";
  5300. }
  5301. if (!mg_fopen(conn, path, "rb", filep)) {
  5302. send_http_error(conn,
  5303. 500,
  5304. "Error: Cannot open file\nfopen(%s): %s",
  5305. path,
  5306. strerror(ERRNO));
  5307. return;
  5308. }
  5309. fclose_on_exec(filep, conn);
  5310. /* If Range: header specified, act accordingly */
  5311. r1 = r2 = 0;
  5312. hdr = mg_get_header(conn, "Range");
  5313. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5314. && r2 >= 0) {
  5315. /* actually, range requests don't play well with a pre-gzipped
  5316. * file (since the range is specified in the uncompressed space) */
  5317. if (filep->gzipped) {
  5318. send_http_error(
  5319. conn,
  5320. 501,
  5321. "%s",
  5322. "Error: Range requests in gzipped files are not supported");
  5323. mg_fclose(filep);
  5324. return;
  5325. }
  5326. conn->status_code = 206;
  5327. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5328. mg_snprintf(conn,
  5329. NULL, /* range buffer is big enough */
  5330. range,
  5331. sizeof(range),
  5332. "Content-Range: bytes "
  5333. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5334. r1,
  5335. r1 + cl - 1,
  5336. filep->size);
  5337. msg = "Partial Content";
  5338. }
  5339. hdr = mg_get_header(conn, "Origin");
  5340. if (hdr) {
  5341. /* Cross-origin resource sharing (CORS), see
  5342. * http://www.html5rocks.com/en/tutorials/cors/,
  5343. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5344. * preflight is not supported for files. */
  5345. cors1 = "Access-Control-Allow-Origin: ";
  5346. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5347. cors3 = "\r\n";
  5348. } else {
  5349. cors1 = cors2 = cors3 = "";
  5350. }
  5351. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5352. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5353. gmt_time_string(date, sizeof(date), &curtime);
  5354. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5355. construct_etag(etag, sizeof(etag), filep);
  5356. (void)mg_printf(conn,
  5357. "HTTP/1.1 %d %s\r\n"
  5358. "%s%s%s"
  5359. "Date: %s\r\n"
  5360. "Last-Modified: %s\r\n"
  5361. "Etag: %s\r\n"
  5362. "Content-Type: %.*s\r\n"
  5363. "Content-Length: %" INT64_FMT "\r\n"
  5364. "Connection: %s\r\n"
  5365. "Accept-Ranges: bytes\r\n"
  5366. "%s%s\r\n",
  5367. conn->status_code,
  5368. msg,
  5369. cors1,
  5370. cors2,
  5371. cors3,
  5372. date,
  5373. lm,
  5374. etag,
  5375. (int)mime_vec.len,
  5376. mime_vec.ptr,
  5377. cl,
  5378. suggest_connection_header(conn),
  5379. range,
  5380. encoding);
  5381. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5382. send_file_data(conn, filep, r1, cl);
  5383. }
  5384. mg_fclose(filep);
  5385. }
  5386. void
  5387. mg_send_file(struct mg_connection *conn, const char *path)
  5388. {
  5389. struct file file = STRUCT_FILE_INITIALIZER;
  5390. if (mg_stat(conn, path, &file)) {
  5391. if (file.is_directory) {
  5392. if (!conn) {
  5393. return;
  5394. }
  5395. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5396. "yes")) {
  5397. handle_directory_request(conn, path);
  5398. } else {
  5399. send_http_error(conn,
  5400. 403,
  5401. "%s",
  5402. "Error: Directory listing denied");
  5403. }
  5404. } else {
  5405. handle_static_file_request(conn, path, &file);
  5406. }
  5407. } else {
  5408. send_http_error(conn, 404, "%s", "Error: File not found");
  5409. }
  5410. }
  5411. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5412. * where parsing stopped. */
  5413. static void
  5414. parse_http_headers(char **buf, struct mg_request_info *ri)
  5415. {
  5416. int i;
  5417. if (!ri) {
  5418. return;
  5419. }
  5420. ri->num_headers = 0;
  5421. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5422. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  5423. ri->http_headers[i].value = skip(buf, "\r\n");
  5424. if (ri->http_headers[i].name[0] == '\0') {
  5425. break;
  5426. }
  5427. ri->num_headers = i + 1;
  5428. }
  5429. }
  5430. static int
  5431. is_valid_http_method(const char *method)
  5432. {
  5433. return !strcmp(method, "GET") || !strcmp(method, "POST")
  5434. || !strcmp(method, "HEAD") || !strcmp(method, "CONNECT")
  5435. || !strcmp(method, "PUT") || !strcmp(method, "DELETE")
  5436. || !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
  5437. || !strcmp(method, "MKCOL") || !strcmp(method, "PATCH");
  5438. /* TRACE method is not supported for security reasons */
  5439. /* PATCH method (RFC 5789) only allowed for CGI/Lua/LSP and callbacks. */
  5440. }
  5441. /* Parse HTTP request, fill in mg_request_info structure.
  5442. * This function modifies the buffer by NUL-terminating
  5443. * HTTP request components, header names and header values. */
  5444. static int
  5445. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5446. {
  5447. int is_request, request_length;
  5448. if (!ri) {
  5449. return 0;
  5450. }
  5451. request_length = get_request_len(buf, len);
  5452. if (request_length > 0) {
  5453. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5454. * remote_port */
  5455. ri->remote_user = ri->request_method = ri->request_uri =
  5456. ri->http_version = NULL;
  5457. ri->num_headers = 0;
  5458. buf[request_length - 1] = '\0';
  5459. /* RFC says that all initial whitespaces should be ingored */
  5460. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5461. buf++;
  5462. }
  5463. ri->request_method = skip(&buf, " ");
  5464. ri->request_uri = skip(&buf, " ");
  5465. ri->http_version = skip(&buf, "\r\n");
  5466. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5467. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5468. is_request = is_valid_http_method(ri->request_method);
  5469. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5470. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5471. request_length = -1;
  5472. } else {
  5473. if (is_request) {
  5474. ri->http_version += 5;
  5475. }
  5476. parse_http_headers(&buf, ri);
  5477. }
  5478. }
  5479. return request_length;
  5480. }
  5481. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5482. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5483. * buffer (which marks the end of HTTP request). Buffer buf may already
  5484. * have some data. The length of the data is stored in nread.
  5485. * Upon every read operation, increase nread by the number of bytes read. */
  5486. static int
  5487. read_request(FILE *fp,
  5488. struct mg_connection *conn,
  5489. char *buf,
  5490. int bufsiz,
  5491. int *nread)
  5492. {
  5493. int request_len, n = 0;
  5494. struct timespec last_action_time;
  5495. double request_timeout;
  5496. if (!conn) {
  5497. return 0;
  5498. }
  5499. memset(&last_action_time, 0, sizeof(last_action_time));
  5500. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5501. /* value of request_timeout is in seconds, config in milliseconds */
  5502. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5503. } else {
  5504. request_timeout = -1.0;
  5505. }
  5506. request_len = get_request_len(buf, *nread);
  5507. while (
  5508. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5509. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5510. <= request_timeout) || (request_timeout < 0))
  5511. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5512. > 0)) {
  5513. *nread += n;
  5514. /* assert(*nread <= bufsiz); */
  5515. if (*nread > bufsiz) {
  5516. return -2;
  5517. }
  5518. request_len = get_request_len(buf, *nread);
  5519. if (request_timeout > 0.0) {
  5520. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5521. }
  5522. }
  5523. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5524. }
  5525. #if !defined(NO_FILES)
  5526. /* For given directory path, substitute it to valid index file.
  5527. * Return 1 if index file has been found, 0 if not found.
  5528. * If the file is found, it's stats is returned in stp. */
  5529. static int
  5530. substitute_index_file(struct mg_connection *conn,
  5531. char *path,
  5532. size_t path_len,
  5533. struct file *filep)
  5534. {
  5535. if (conn && conn->ctx) {
  5536. const char *list = conn->ctx->config[INDEX_FILES];
  5537. struct file file = STRUCT_FILE_INITIALIZER;
  5538. struct vec filename_vec;
  5539. size_t n = strlen(path);
  5540. int found = 0;
  5541. /* The 'path' given to us points to the directory. Remove all trailing
  5542. * directory separator characters from the end of the path, and
  5543. * then append single directory separator character. */
  5544. while (n > 0 && path[n - 1] == '/') {
  5545. n--;
  5546. }
  5547. path[n] = '/';
  5548. /* Traverse index files list. For each entry, append it to the given
  5549. * path and see if the file exists. If it exists, break the loop */
  5550. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5551. /* Ignore too long entries that may overflow path buffer */
  5552. if (filename_vec.len > path_len - (n + 2)) {
  5553. continue;
  5554. }
  5555. /* Prepare full path to the index file */
  5556. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5557. /* Does it exist? */
  5558. if (mg_stat(conn, path, &file)) {
  5559. /* Yes it does, break the loop */
  5560. *filep = file;
  5561. found = 1;
  5562. break;
  5563. }
  5564. }
  5565. /* If no index file exists, restore directory path */
  5566. if (!found) {
  5567. path[n] = '\0';
  5568. }
  5569. return found;
  5570. }
  5571. return 0;
  5572. }
  5573. #endif
  5574. /* Return True if we should reply 304 Not Modified. */
  5575. static int
  5576. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  5577. {
  5578. char etag[64];
  5579. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5580. const char *inm = mg_get_header(conn, "If-None-Match");
  5581. construct_etag(etag, sizeof(etag), filep);
  5582. if (!filep) {
  5583. return 0;
  5584. }
  5585. return (inm != NULL && !mg_strcasecmp(etag, inm))
  5586. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5587. }
  5588. #if !defined(NO_CGI) || !defined(NO_FILES)
  5589. static int
  5590. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5591. {
  5592. const char *expect, *body;
  5593. char buf[MG_BUF_LEN];
  5594. int to_read, nread, success = 0;
  5595. int64_t buffered_len;
  5596. double timeout = -1.0;
  5597. if (!conn) {
  5598. return 0;
  5599. }
  5600. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5601. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5602. }
  5603. expect = mg_get_header(conn, "Expect");
  5604. /* assert(fp != NULL); */
  5605. if (!fp) {
  5606. send_http_error(conn, 500, "%s", "Error: NULL File");
  5607. return 0;
  5608. }
  5609. if (conn->content_len == -1 && !conn->is_chunked) {
  5610. /* Content length is not specified by the client. */
  5611. send_http_error(conn,
  5612. 411,
  5613. "%s",
  5614. "Error: Client did not specify content length");
  5615. } else if ((expect != NULL)
  5616. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  5617. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5618. send_http_error(conn,
  5619. 417,
  5620. "Error: Can not fulfill expectation %s",
  5621. expect);
  5622. } else {
  5623. if (expect != NULL) {
  5624. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5625. conn->status_code = 100;
  5626. } else {
  5627. conn->status_code = 200;
  5628. }
  5629. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5630. - conn->consumed_content;
  5631. /* assert(buffered_len >= 0); */
  5632. /* assert(conn->consumed_content == 0); */
  5633. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5634. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5635. return 0;
  5636. }
  5637. if (buffered_len > 0) {
  5638. if ((int64_t)buffered_len > conn->content_len) {
  5639. buffered_len = (int)conn->content_len;
  5640. }
  5641. body = conn->buf + conn->request_len + conn->consumed_content;
  5642. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5643. conn->consumed_content += buffered_len;
  5644. }
  5645. nread = 0;
  5646. while (conn->consumed_content < conn->content_len) {
  5647. to_read = sizeof(buf);
  5648. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5649. to_read = (int)(conn->content_len - conn->consumed_content);
  5650. }
  5651. nread = pull(NULL, conn, buf, to_read, timeout);
  5652. if (nread <= 0
  5653. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5654. break;
  5655. }
  5656. conn->consumed_content += nread;
  5657. }
  5658. if (conn->consumed_content == conn->content_len) {
  5659. success = nread >= 0;
  5660. }
  5661. /* Each error code path in this function must send an error */
  5662. if (!success) {
  5663. /* NOTE: Maybe some data has already been sent. */
  5664. /* TODO (low): If some data has been sent, a correct error
  5665. * reply can no longer be sent, so just close the connection */
  5666. send_http_error(conn, 500, "%s", "");
  5667. }
  5668. }
  5669. return success;
  5670. }
  5671. #endif
  5672. #if !defined(NO_CGI)
  5673. /* This structure helps to create an environment for the spawned CGI program.
  5674. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5675. * last element must be NULL.
  5676. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5677. * strings must reside in a contiguous buffer. The end of the buffer is
  5678. * marked by two '\0' characters.
  5679. * We satisfy both worlds: we create an envp array (which is vars), all
  5680. * entries are actually pointers inside buf. */
  5681. struct cgi_environment {
  5682. struct mg_connection *conn;
  5683. /* Data block */
  5684. char *buf; /* Environment buffer */
  5685. size_t buflen; /* Space available in buf */
  5686. size_t bufused; /* Space taken in buf */
  5687. /* Index block */
  5688. char **var; /* char **envp */
  5689. size_t varlen; /* Number of variables available in var */
  5690. size_t varused; /* Number of variables stored in var */
  5691. };
  5692. static void addenv(struct cgi_environment *env,
  5693. PRINTF_FORMAT_STRING(const char *fmt),
  5694. ...) PRINTF_ARGS(2, 3);
  5695. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  5696. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  5697. static void
  5698. addenv(struct cgi_environment *env, const char *fmt, ...)
  5699. {
  5700. size_t n, space;
  5701. int truncated;
  5702. char *added;
  5703. va_list ap;
  5704. /* Calculate how much space is left in the buffer */
  5705. space = (env->buflen - env->bufused);
  5706. /* Calculate an estimate for the required space */
  5707. n = strlen(fmt) + 2 + 128;
  5708. do {
  5709. if (space <= n) {
  5710. /* Allocate new buffer */
  5711. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  5712. added = (char *)mg_realloc(env->buf, n);
  5713. if (!added) {
  5714. /* Out of memory */
  5715. mg_cry(env->conn,
  5716. "%s: Cannot allocate memory for CGI variable [%s]",
  5717. __func__,
  5718. fmt);
  5719. return;
  5720. }
  5721. env->buf = added;
  5722. env->buflen = n;
  5723. space = (env->buflen - env->bufused);
  5724. }
  5725. /* Make a pointer to the free space int the buffer */
  5726. added = env->buf + env->bufused;
  5727. /* Copy VARIABLE=VALUE\0 string into the free space */
  5728. va_start(ap, fmt);
  5729. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  5730. va_end(ap);
  5731. /* Do not add truncated strings to the environment */
  5732. if (truncated) {
  5733. /* Reallocate the buffer */
  5734. space = 0;
  5735. n = 1;
  5736. }
  5737. } while (truncated);
  5738. /* Calculate number of bytes added to the environment */
  5739. n = strlen(added) + 1;
  5740. env->bufused += n;
  5741. /* Now update the variable index */
  5742. space = (env->varlen - env->varused);
  5743. if (space < 2) {
  5744. mg_cry(env->conn,
  5745. "%s: Cannot register CGI variable [%s]",
  5746. __func__,
  5747. fmt);
  5748. return;
  5749. }
  5750. /* Append a pointer to the added string into the envp array */
  5751. env->var[env->varused] = added;
  5752. env->varused++;
  5753. }
  5754. static void
  5755. prepare_cgi_environment(struct mg_connection *conn,
  5756. const char *prog,
  5757. struct cgi_environment *env)
  5758. {
  5759. const char *s;
  5760. struct vec var_vec;
  5761. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  5762. int i, truncated;
  5763. if (conn == NULL || prog == NULL || env == NULL) {
  5764. return;
  5765. }
  5766. env->conn = conn;
  5767. env->buflen = CGI_ENVIRONMENT_SIZE;
  5768. env->bufused = 0;
  5769. env->buf = (char *)mg_malloc(env->buflen);
  5770. env->varlen = MAX_CGI_ENVIR_VARS;
  5771. env->varused = 0;
  5772. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  5773. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  5774. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5775. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5776. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  5777. /* Prepare the environment block */
  5778. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  5779. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  5780. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  5781. #if defined(USE_IPV6)
  5782. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  5783. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  5784. } else
  5785. #endif
  5786. {
  5787. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  5788. }
  5789. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5790. addenv(env, "REMOTE_ADDR=%s", src_addr);
  5791. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  5792. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5793. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  5794. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  5795. /* SCRIPT_NAME */
  5796. addenv(env,
  5797. "SCRIPT_NAME=%.*s",
  5798. (int)strlen(conn->request_info.local_uri)
  5799. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5800. conn->request_info.local_uri);
  5801. addenv(env, "SCRIPT_FILENAME=%s", prog);
  5802. if (conn->path_info == NULL) {
  5803. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5804. } else {
  5805. addenv(env,
  5806. "PATH_TRANSLATED=%s%s",
  5807. conn->ctx->config[DOCUMENT_ROOT],
  5808. conn->path_info);
  5809. }
  5810. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5811. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  5812. addenv(env, "CONTENT_TYPE=%s", s);
  5813. }
  5814. if (conn->request_info.query_string != NULL) {
  5815. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  5816. }
  5817. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  5818. addenv(env, "CONTENT_LENGTH=%s", s);
  5819. }
  5820. if ((s = getenv("PATH")) != NULL) {
  5821. addenv(env, "PATH=%s", s);
  5822. }
  5823. if (conn->path_info != NULL) {
  5824. addenv(env, "PATH_INFO=%s", conn->path_info);
  5825. }
  5826. if (conn->status_code > 0) {
  5827. /* CGI error handler should show the status code */
  5828. addenv(env, "STATUS=%d", conn->status_code);
  5829. }
  5830. #if defined(_WIN32)
  5831. if ((s = getenv("COMSPEC")) != NULL) {
  5832. addenv(env, "COMSPEC=%s", s);
  5833. }
  5834. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5835. addenv(env, "SYSTEMROOT=%s", s);
  5836. }
  5837. if ((s = getenv("SystemDrive")) != NULL) {
  5838. addenv(env, "SystemDrive=%s", s);
  5839. }
  5840. if ((s = getenv("ProgramFiles")) != NULL) {
  5841. addenv(env, "ProgramFiles=%s", s);
  5842. }
  5843. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5844. addenv(env, "ProgramFiles(x86)=%s", s);
  5845. }
  5846. #else
  5847. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  5848. addenv(env, "LD_LIBRARY_PATH=%s", s);
  5849. }
  5850. #endif /* _WIN32 */
  5851. if ((s = getenv("PERLLIB")) != NULL) {
  5852. addenv(env, "PERLLIB=%s", s);
  5853. }
  5854. if (conn->request_info.remote_user != NULL) {
  5855. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  5856. addenv(env, "%s", "AUTH_TYPE=Digest");
  5857. }
  5858. /* Add all headers as HTTP_* variables */
  5859. for (i = 0; i < conn->request_info.num_headers; i++) {
  5860. (void)mg_snprintf(conn,
  5861. &truncated,
  5862. http_var_name,
  5863. sizeof(http_var_name),
  5864. "HTTP_%s",
  5865. conn->request_info.http_headers[i].name);
  5866. if (truncated) {
  5867. mg_cry(conn,
  5868. "%s: HTTP header variable too long [%s]",
  5869. __func__,
  5870. conn->request_info.http_headers[i].name);
  5871. continue;
  5872. }
  5873. /* Convert variable name into uppercase, and change - to _ */
  5874. for (p = http_var_name; *p != '\0'; p++) {
  5875. if (*p == '-') {
  5876. *p = '_';
  5877. }
  5878. *p = (char)toupper(*(unsigned char *)p);
  5879. }
  5880. addenv(env,
  5881. "%s=%s",
  5882. http_var_name,
  5883. conn->request_info.http_headers[i].value);
  5884. }
  5885. /* Add user-specified variables */
  5886. s = conn->ctx->config[CGI_ENVIRONMENT];
  5887. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  5888. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  5889. }
  5890. env->var[env->varused] = NULL;
  5891. env->buf[env->bufused] = '\0';
  5892. }
  5893. static void
  5894. handle_cgi_request(struct mg_connection *conn, const char *prog)
  5895. {
  5896. char *buf;
  5897. size_t buflen;
  5898. int headers_len, data_len, i, truncated;
  5899. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  5900. const char *status, *status_text, *connection_state;
  5901. char *pbuf, dir[PATH_MAX], *p;
  5902. struct mg_request_info ri;
  5903. struct cgi_environment blk;
  5904. FILE *in = NULL, *out = NULL, *err = NULL;
  5905. struct file fout = STRUCT_FILE_INITIALIZER;
  5906. pid_t pid = (pid_t)-1;
  5907. if (conn == NULL) {
  5908. return;
  5909. }
  5910. buf = NULL;
  5911. buflen = 16384;
  5912. prepare_cgi_environment(conn, prog, &blk);
  5913. /* CGI must be executed in its own directory. 'dir' must point to the
  5914. * directory containing executable program, 'p' must point to the
  5915. * executable program name relative to 'dir'. */
  5916. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  5917. if (truncated) {
  5918. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  5919. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  5920. goto done;
  5921. }
  5922. if ((p = strrchr(dir, '/')) != NULL) {
  5923. *p++ = '\0';
  5924. } else {
  5925. dir[0] = '.', dir[1] = '\0';
  5926. p = (char *)prog;
  5927. }
  5928. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  5929. status = strerror(ERRNO);
  5930. mg_cry(conn,
  5931. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  5932. prog,
  5933. status);
  5934. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  5935. goto done;
  5936. }
  5937. pid = spawn_process(
  5938. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  5939. if (pid == (pid_t)-1) {
  5940. status = strerror(ERRNO);
  5941. mg_cry(conn,
  5942. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  5943. prog,
  5944. status);
  5945. send_http_error(conn,
  5946. 500,
  5947. "Error: Cannot spawn CGI process [%s]: %s",
  5948. prog,
  5949. status);
  5950. goto done;
  5951. }
  5952. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  5953. set_close_on_exec((SOCKET)fdin[0], conn);
  5954. set_close_on_exec((SOCKET)fdin[1], conn);
  5955. set_close_on_exec((SOCKET)fdout[0], conn);
  5956. set_close_on_exec((SOCKET)fdout[1], conn);
  5957. set_close_on_exec((SOCKET)fderr[0], conn);
  5958. set_close_on_exec((SOCKET)fderr[1], conn);
  5959. /* Parent closes only one side of the pipes.
  5960. * If we don't mark them as closed, close() attempt before
  5961. * return from this function throws an exception on Windows.
  5962. * Windows does not like when closed descriptor is closed again. */
  5963. (void)close(fdin[0]);
  5964. (void)close(fdout[1]);
  5965. (void)close(fderr[1]);
  5966. fdin[0] = fdout[1] = fderr[1] = -1;
  5967. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  5968. status = strerror(ERRNO);
  5969. mg_cry(conn,
  5970. "Error: CGI program \"%s\": Can not open stdin: %s",
  5971. prog,
  5972. status);
  5973. send_http_error(conn,
  5974. 500,
  5975. "Error: CGI can not open fdin\nfopen: %s",
  5976. status);
  5977. goto done;
  5978. }
  5979. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  5980. status = strerror(ERRNO);
  5981. mg_cry(conn,
  5982. "Error: CGI program \"%s\": Can not open stdout: %s",
  5983. prog,
  5984. status);
  5985. send_http_error(conn,
  5986. 500,
  5987. "Error: CGI can not open fdout\nfopen: %s",
  5988. status);
  5989. goto done;
  5990. }
  5991. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  5992. status = strerror(ERRNO);
  5993. mg_cry(conn,
  5994. "Error: CGI program \"%s\": Can not open stderr: %s",
  5995. prog,
  5996. status);
  5997. send_http_error(conn,
  5998. 500,
  5999. "Error: CGI can not open fdout\nfopen: %s",
  6000. status);
  6001. goto done;
  6002. }
  6003. setbuf(in, NULL);
  6004. setbuf(out, NULL);
  6005. setbuf(err, NULL);
  6006. fout.fp = out;
  6007. /* Send POST or PUT data to the CGI process if needed */
  6008. /* TODO(high): Methods like PATCH, MKCOL, ... also have body data. */
  6009. if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  6010. || !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  6011. /* This is a POST/PUT request */
  6012. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6013. /* Error sending the body data */
  6014. mg_cry(conn,
  6015. "Error: CGI program \"%s\": Forward body data failed",
  6016. prog);
  6017. goto done;
  6018. }
  6019. }
  6020. /* Close so child gets an EOF. */
  6021. fclose(in);
  6022. in = NULL;
  6023. fdin[1] = -1;
  6024. /* Now read CGI reply into a buffer. We need to set correct
  6025. * status code, thus we need to see all HTTP headers first.
  6026. * Do not send anything back to client, until we buffer in all
  6027. * HTTP headers. */
  6028. data_len = 0;
  6029. buf = (char *)mg_malloc(buflen);
  6030. if (buf == NULL) {
  6031. send_http_error(conn,
  6032. 500,
  6033. "Error: Not enough memory for CGI buffer (%u bytes)",
  6034. (unsigned int)buflen);
  6035. mg_cry(conn,
  6036. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6037. "bytes)",
  6038. prog,
  6039. (unsigned int)buflen);
  6040. goto done;
  6041. }
  6042. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6043. if (headers_len <= 0) {
  6044. /* Could not parse the CGI response. Check if some error message on
  6045. * stderr. */
  6046. i = pull_all(err, conn, buf, (int)buflen);
  6047. if (i > 0) {
  6048. mg_cry(conn,
  6049. "Error: CGI program \"%s\" sent error "
  6050. "message: [%.*s]",
  6051. prog,
  6052. i,
  6053. buf);
  6054. send_http_error(conn,
  6055. 500,
  6056. "Error: CGI program \"%s\" sent error "
  6057. "message: [%.*s]",
  6058. prog,
  6059. i,
  6060. buf);
  6061. } else {
  6062. mg_cry(conn,
  6063. "Error: CGI program sent malformed or too big "
  6064. "(>%u bytes) HTTP headers: [%.*s]",
  6065. (unsigned)buflen,
  6066. data_len,
  6067. buf);
  6068. send_http_error(conn,
  6069. 500,
  6070. "Error: CGI program sent malformed or too big "
  6071. "(>%u bytes) HTTP headers: [%.*s]",
  6072. (unsigned)buflen,
  6073. data_len,
  6074. buf);
  6075. }
  6076. goto done;
  6077. }
  6078. pbuf = buf;
  6079. buf[headers_len - 1] = '\0';
  6080. parse_http_headers(&pbuf, &ri);
  6081. /* Make up and send the status line */
  6082. status_text = "OK";
  6083. if ((status = get_header(&ri, "Status")) != NULL) {
  6084. conn->status_code = atoi(status);
  6085. status_text = status;
  6086. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  6087. status_text++;
  6088. }
  6089. } else if (get_header(&ri, "Location") != NULL) {
  6090. conn->status_code = 302;
  6091. } else {
  6092. conn->status_code = 200;
  6093. }
  6094. connection_state = get_header(&ri, "Connection");
  6095. if (connection_state == NULL
  6096. || mg_strcasecmp(connection_state, "keep-alive")) {
  6097. conn->must_close = 1;
  6098. }
  6099. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6100. /* Send headers */
  6101. for (i = 0; i < ri.num_headers; i++) {
  6102. mg_printf(conn,
  6103. "%s: %s\r\n",
  6104. ri.http_headers[i].name,
  6105. ri.http_headers[i].value);
  6106. }
  6107. mg_write(conn, "\r\n", 2);
  6108. /* Send chunk of data that may have been read after the headers */
  6109. conn->num_bytes_sent +=
  6110. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6111. /* Read the rest of CGI output and send to the client */
  6112. send_file_data(conn, &fout, 0, INT64_MAX);
  6113. done:
  6114. mg_free(blk.var);
  6115. mg_free(blk.buf);
  6116. if (pid != (pid_t)-1) {
  6117. kill(pid, SIGKILL);
  6118. #if !defined(_WIN32)
  6119. {
  6120. int st;
  6121. while (waitpid(pid, &st, 0) != -1)
  6122. ; /* clean zombies */
  6123. }
  6124. #endif
  6125. }
  6126. if (fdin[0] != -1) {
  6127. close(fdin[0]);
  6128. }
  6129. if (fdout[1] != -1) {
  6130. close(fdout[1]);
  6131. }
  6132. if (in != NULL) {
  6133. fclose(in);
  6134. } else if (fdin[1] != -1) {
  6135. close(fdin[1]);
  6136. }
  6137. if (out != NULL) {
  6138. fclose(out);
  6139. } else if (fdout[0] != -1) {
  6140. close(fdout[0]);
  6141. }
  6142. if (err != NULL) {
  6143. fclose(err);
  6144. } else if (fderr[0] != -1) {
  6145. close(fderr[0]);
  6146. }
  6147. if (buf != NULL) {
  6148. mg_free(buf);
  6149. }
  6150. }
  6151. #endif /* !NO_CGI */
  6152. #if !defined(NO_FILES)
  6153. /* For a given PUT path, create all intermediate subdirectories.
  6154. * Return 0 if the path itself is a directory.
  6155. * Return 1 if the path leads to a file.
  6156. * Return -1 for if the path is too long.
  6157. * Return -2 if path can not be created.
  6158. */
  6159. static int
  6160. put_dir(struct mg_connection *conn, const char *path)
  6161. {
  6162. char buf[PATH_MAX];
  6163. const char *s, *p;
  6164. struct file file = STRUCT_FILE_INITIALIZER;
  6165. size_t len;
  6166. int res = 1;
  6167. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6168. len = (size_t)(p - path);
  6169. if (len >= sizeof(buf)) {
  6170. /* path too long */
  6171. res = -1;
  6172. break;
  6173. }
  6174. memcpy(buf, path, len);
  6175. buf[len] = '\0';
  6176. /* Try to create intermediate directory */
  6177. DEBUG_TRACE("mkdir(%s)", buf);
  6178. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  6179. /* path does not exixt and can not be created */
  6180. res = -2;
  6181. break;
  6182. }
  6183. /* Is path itself a directory? */
  6184. if (p[1] == '\0') {
  6185. res = 0;
  6186. }
  6187. }
  6188. return res;
  6189. }
  6190. static void
  6191. mkcol(struct mg_connection *conn, const char *path)
  6192. {
  6193. int rc, body_len;
  6194. struct de de;
  6195. char date[64];
  6196. time_t curtime = time(NULL);
  6197. if (conn == NULL) {
  6198. return;
  6199. }
  6200. /* TODO (mid): Check the send_http_error situations in this function */
  6201. memset(&de.file, 0, sizeof(de.file));
  6202. if (!mg_stat(conn, path, &de.file)) {
  6203. mg_cry(conn,
  6204. "%s: mg_stat(%s) failed: %s",
  6205. __func__,
  6206. path,
  6207. strerror(ERRNO));
  6208. }
  6209. if (de.file.last_modified) {
  6210. /* TODO (high): This check does not seem to make any sense ! */
  6211. send_http_error(
  6212. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6213. return;
  6214. }
  6215. body_len = conn->data_len - conn->request_len;
  6216. if (body_len > 0) {
  6217. send_http_error(
  6218. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6219. return;
  6220. }
  6221. rc = mg_mkdir(path, 0755);
  6222. if (rc == 0) {
  6223. conn->status_code = 201;
  6224. gmt_time_string(date, sizeof(date), &curtime);
  6225. mg_printf(conn,
  6226. "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: "
  6227. "0\r\nConnection: %s\r\n\r\n",
  6228. conn->status_code,
  6229. date,
  6230. suggest_connection_header(conn));
  6231. } else if (rc == -1) {
  6232. if (errno == EEXIST) {
  6233. send_http_error(
  6234. conn, 405, "Error:mkcol(%s): %s", path, strerror(ERRNO));
  6235. } else if (errno == EACCES) {
  6236. send_http_error(
  6237. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6238. } else if (errno == ENOENT) {
  6239. send_http_error(
  6240. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6241. } else {
  6242. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6243. }
  6244. }
  6245. }
  6246. static void
  6247. put_file(struct mg_connection *conn, const char *path)
  6248. {
  6249. struct file file = STRUCT_FILE_INITIALIZER;
  6250. const char *range;
  6251. int64_t r1, r2;
  6252. int rc;
  6253. char date[64];
  6254. time_t curtime = time(NULL);
  6255. if (conn == NULL) {
  6256. return;
  6257. }
  6258. if (mg_stat(conn, path, &file)) {
  6259. /* File already exists */
  6260. conn->status_code = 200;
  6261. if (file.is_directory) {
  6262. /* This is an already existing directory,
  6263. * so there is nothing to do for the server. */
  6264. rc = 0;
  6265. } else {
  6266. /* File exists and is not a directory. */
  6267. /* Can it be replaced? */
  6268. if (file.membuf != NULL) {
  6269. /* This is an "in-memory" file, that can not be replaced */
  6270. send_http_error(
  6271. conn,
  6272. 405,
  6273. "Error: Put not possible\nReplacing %s is not supported",
  6274. path);
  6275. return;
  6276. }
  6277. /* Check if the server may write this file */
  6278. if (access(path, W_OK) == 0) {
  6279. /* Access granted */
  6280. conn->status_code = 200;
  6281. rc = 1;
  6282. } else {
  6283. send_http_error(
  6284. conn,
  6285. 403,
  6286. "Error: Put not possible\nReplacing %s is not allowed",
  6287. path);
  6288. return;
  6289. }
  6290. }
  6291. } else {
  6292. /* File should be created */
  6293. conn->status_code = 201;
  6294. rc = put_dir(conn, path);
  6295. }
  6296. if (rc == 0) {
  6297. /* put_dir returns 0 if path is a directory */
  6298. gmt_time_string(date, sizeof(date), &curtime);
  6299. mg_printf(conn,
  6300. "HTTP/1.1 %d %s\r\n"
  6301. "Date: %s\r\n"
  6302. "Content-Length: 0\r\n"
  6303. "Connection: %s\r\n\r\n",
  6304. conn->status_code,
  6305. mg_get_response_code_text(conn->status_code, NULL),
  6306. date,
  6307. suggest_connection_header(conn));
  6308. /* Request to create a directory has been fulfilled successfully.
  6309. * No need to put a file. */
  6310. return;
  6311. }
  6312. if (rc == -1) {
  6313. /* put_dir returns -1 if the path is too long */
  6314. send_http_error(conn,
  6315. 414,
  6316. "Error: Path too long\nput_dir(%s): %s",
  6317. path,
  6318. strerror(ERRNO));
  6319. return;
  6320. }
  6321. if (rc == -2) {
  6322. /* put_dir returns -2 if the directory can not be created */
  6323. send_http_error(conn,
  6324. 500,
  6325. "Error: Can not create directory\nput_dir(%s): %s",
  6326. path,
  6327. strerror(ERRNO));
  6328. return;
  6329. }
  6330. /* A file should be created or overwritten. */
  6331. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6332. mg_fclose(&file);
  6333. send_http_error(conn,
  6334. 500,
  6335. "Error: Can not create file\nfopen(%s): %s",
  6336. path,
  6337. strerror(ERRNO));
  6338. return;
  6339. }
  6340. fclose_on_exec(&file, conn);
  6341. range = mg_get_header(conn, "Content-Range");
  6342. r1 = r2 = 0;
  6343. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6344. conn->status_code = 206; /* Partial content */
  6345. fseeko(file.fp, r1, SEEK_SET);
  6346. }
  6347. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6348. /* forward_body_data failed.
  6349. * The error code has already been sent to the client,
  6350. * and conn->status_code is already set. */
  6351. return;
  6352. }
  6353. gmt_time_string(date, sizeof(date), &curtime);
  6354. mg_printf(conn,
  6355. "HTTP/1.1 %d %s\r\n"
  6356. "Date: %s\r\n"
  6357. "Content-Length: 0\r\n"
  6358. "Connection: %s\r\n\r\n",
  6359. conn->status_code,
  6360. mg_get_response_code_text(conn->status_code, NULL),
  6361. date,
  6362. suggest_connection_header(conn));
  6363. mg_fclose(&file);
  6364. }
  6365. static void
  6366. delete_file(struct mg_connection *conn, const char *path)
  6367. {
  6368. struct de de;
  6369. memset(&de.file, 0, sizeof(de.file));
  6370. if (!mg_stat(conn, path, &de.file)) {
  6371. /* mg_stat returns 0 if the file does not exist */
  6372. send_http_error(conn,
  6373. 404,
  6374. "Error: Cannot delete file\nFile %s not found",
  6375. path);
  6376. return;
  6377. }
  6378. if (de.file.membuf != NULL) {
  6379. /* the file is cached in memory */
  6380. send_http_error(
  6381. conn,
  6382. 405,
  6383. "Error: Delete not possible\nDeleting %s is not supported",
  6384. path);
  6385. return;
  6386. }
  6387. if (de.file.is_directory) {
  6388. remove_directory(conn, path);
  6389. /* TODO (mid): remove_dir does not return success of the operation */
  6390. /* Assume delete is successful: Return 204 without content. */
  6391. send_http_error(conn, 204, "%s", "");
  6392. return;
  6393. }
  6394. /* This is an existing file (not a directory).
  6395. * Check if write permission is granted. */
  6396. if (access(path, W_OK) != 0) {
  6397. /* File is read only */
  6398. send_http_error(
  6399. conn,
  6400. 403,
  6401. "Error: Delete not possible\nDeleting %s is not allowed",
  6402. path);
  6403. return;
  6404. }
  6405. /* Try to delete it. */
  6406. if (mg_remove(path) == 0) {
  6407. /* Delete was successful: Return 204 without content. */
  6408. send_http_error(conn, 204, "%s", "");
  6409. } else {
  6410. /* Delete not successful (file locked). */
  6411. send_http_error(conn,
  6412. 423,
  6413. "Error: Cannot delete file\nremove(%s): %s",
  6414. path,
  6415. strerror(ERRNO));
  6416. }
  6417. }
  6418. #endif /* !NO_FILES */
  6419. static void
  6420. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6421. static void
  6422. do_ssi_include(struct mg_connection *conn,
  6423. const char *ssi,
  6424. char *tag,
  6425. int include_level)
  6426. {
  6427. char file_name[MG_BUF_LEN], path[512], *p;
  6428. struct file file = STRUCT_FILE_INITIALIZER;
  6429. size_t len;
  6430. int truncated = 0;
  6431. if (conn == NULL) {
  6432. return;
  6433. }
  6434. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6435. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6436. * always < MG_BUF_LEN. */
  6437. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6438. /* File name is relative to the webserver root */
  6439. file_name[511] = 0;
  6440. (void)mg_snprintf(conn,
  6441. &truncated,
  6442. path,
  6443. sizeof(path),
  6444. "%s/%s",
  6445. conn->ctx->config[DOCUMENT_ROOT],
  6446. file_name);
  6447. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6448. /* File name is relative to the webserver working directory
  6449. * or it is absolute system path */
  6450. file_name[511] = 0;
  6451. (void)
  6452. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6453. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6454. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6455. /* File name is relative to the currect document */
  6456. file_name[511] = 0;
  6457. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6458. if (!truncated) {
  6459. if ((p = strrchr(path, '/')) != NULL) {
  6460. p[1] = '\0';
  6461. }
  6462. len = strlen(path);
  6463. (void)mg_snprintf(conn,
  6464. &truncated,
  6465. path + len,
  6466. sizeof(path) - len,
  6467. "%s",
  6468. file_name);
  6469. }
  6470. } else {
  6471. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6472. return;
  6473. }
  6474. if (truncated) {
  6475. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6476. return;
  6477. }
  6478. if (!mg_fopen(conn, path, "rb", &file)) {
  6479. mg_cry(conn,
  6480. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6481. tag,
  6482. path,
  6483. strerror(ERRNO));
  6484. } else {
  6485. fclose_on_exec(&file, conn);
  6486. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6487. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6488. path) > 0) {
  6489. send_ssi_file(conn, path, &file, include_level + 1);
  6490. } else {
  6491. send_file_data(conn, &file, 0, INT64_MAX);
  6492. }
  6493. mg_fclose(&file);
  6494. }
  6495. }
  6496. #if !defined(NO_POPEN)
  6497. static void
  6498. do_ssi_exec(struct mg_connection *conn, char *tag)
  6499. {
  6500. char cmd[1024] = "";
  6501. struct file file = STRUCT_FILE_INITIALIZER;
  6502. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6503. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6504. } else {
  6505. cmd[1023] = 0;
  6506. if ((file.fp = popen(cmd, "r")) == NULL) {
  6507. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6508. } else {
  6509. send_file_data(conn, &file, 0, INT64_MAX);
  6510. pclose(file.fp);
  6511. }
  6512. }
  6513. }
  6514. #endif /* !NO_POPEN */
  6515. static int
  6516. mg_fgetc(struct file *filep, int offset)
  6517. {
  6518. if (filep == NULL) {
  6519. return EOF;
  6520. }
  6521. if (filep->membuf != NULL && offset >= 0
  6522. && ((unsigned int)(offset)) < filep->size) {
  6523. return ((unsigned char *)filep->membuf)[offset];
  6524. } else if (filep->fp != NULL) {
  6525. return fgetc(filep->fp);
  6526. } else {
  6527. return EOF;
  6528. }
  6529. }
  6530. static void
  6531. send_ssi_file(struct mg_connection *conn,
  6532. const char *path,
  6533. struct file *filep,
  6534. int include_level)
  6535. {
  6536. char buf[MG_BUF_LEN];
  6537. int ch, offset, len, in_ssi_tag;
  6538. if (include_level > 10) {
  6539. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6540. return;
  6541. }
  6542. in_ssi_tag = len = offset = 0;
  6543. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6544. if (in_ssi_tag && ch == '>') {
  6545. in_ssi_tag = 0;
  6546. buf[len++] = (char)ch;
  6547. buf[len] = '\0';
  6548. /* assert(len <= (int) sizeof(buf)); */
  6549. if (len > (int)sizeof(buf)) {
  6550. break;
  6551. }
  6552. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6553. /* Not an SSI tag, pass it */
  6554. (void)mg_write(conn, buf, (size_t)len);
  6555. } else {
  6556. if (!memcmp(buf + 5, "include", 7)) {
  6557. do_ssi_include(conn, path, buf + 12, include_level);
  6558. #if !defined(NO_POPEN)
  6559. } else if (!memcmp(buf + 5, "exec", 4)) {
  6560. do_ssi_exec(conn, buf + 9);
  6561. #endif /* !NO_POPEN */
  6562. } else {
  6563. mg_cry(conn,
  6564. "%s: unknown SSI "
  6565. "command: \"%s\"",
  6566. path,
  6567. buf);
  6568. }
  6569. }
  6570. len = 0;
  6571. } else if (in_ssi_tag) {
  6572. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6573. /* Not an SSI tag */
  6574. in_ssi_tag = 0;
  6575. } else if (len == (int)sizeof(buf) - 2) {
  6576. mg_cry(conn, "%s: SSI tag is too large", path);
  6577. len = 0;
  6578. }
  6579. buf[len++] = (char)(ch & 0xff);
  6580. } else if (ch == '<') {
  6581. in_ssi_tag = 1;
  6582. if (len > 0) {
  6583. mg_write(conn, buf, (size_t)len);
  6584. }
  6585. len = 0;
  6586. buf[len++] = (char)(ch & 0xff);
  6587. } else {
  6588. buf[len++] = (char)(ch & 0xff);
  6589. if (len == (int)sizeof(buf)) {
  6590. mg_write(conn, buf, (size_t)len);
  6591. len = 0;
  6592. }
  6593. }
  6594. }
  6595. /* Send the rest of buffered data */
  6596. if (len > 0) {
  6597. mg_write(conn, buf, (size_t)len);
  6598. }
  6599. }
  6600. static void
  6601. handle_ssi_file_request(struct mg_connection *conn,
  6602. const char *path,
  6603. struct file *filep)
  6604. {
  6605. char date[64];
  6606. time_t curtime = time(NULL);
  6607. const char *cors1, *cors2, *cors3;
  6608. if (conn == NULL || path == NULL || filep == NULL) {
  6609. return;
  6610. }
  6611. if (mg_get_header(conn, "Origin")) {
  6612. /* Cross-origin resource sharing (CORS). */
  6613. cors1 = "Access-Control-Allow-Origin: ";
  6614. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6615. cors3 = "\r\n";
  6616. } else {
  6617. cors1 = cors2 = cors3 = "";
  6618. }
  6619. if (!mg_fopen(conn, path, "rb", filep)) {
  6620. /* File exists (precondition for calling this function),
  6621. * but can not be opened by the server. */
  6622. send_http_error(conn,
  6623. 500,
  6624. "Error: Cannot read file\nfopen(%s): %s",
  6625. path,
  6626. strerror(ERRNO));
  6627. } else {
  6628. conn->must_close = 1;
  6629. gmt_time_string(date, sizeof(date), &curtime);
  6630. fclose_on_exec(filep, conn);
  6631. mg_printf(conn,
  6632. "HTTP/1.1 200 OK\r\n"
  6633. "%s%s%s"
  6634. "Date: %s\r\n"
  6635. "Content-Type: text/html\r\n"
  6636. "Connection: %s\r\n\r\n",
  6637. cors1,
  6638. cors2,
  6639. cors3,
  6640. date,
  6641. suggest_connection_header(conn));
  6642. send_ssi_file(conn, path, filep, 0);
  6643. mg_fclose(filep);
  6644. }
  6645. }
  6646. #if !defined(NO_FILES)
  6647. static void
  6648. send_options(struct mg_connection *conn)
  6649. {
  6650. char date[64];
  6651. time_t curtime = time(NULL);
  6652. if (!conn) {
  6653. return;
  6654. }
  6655. conn->status_code = 200;
  6656. conn->must_close = 1;
  6657. gmt_time_string(date, sizeof(date), &curtime);
  6658. mg_printf(conn,
  6659. "HTTP/1.1 200 OK\r\n"
  6660. "Date: %s\r\n"
  6661. "Connection: %s\r\n"
  6662. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6663. "PROPFIND, MKCOL\r\n"
  6664. "DAV: 1\r\n\r\n",
  6665. date,
  6666. suggest_connection_header(conn));
  6667. }
  6668. /* Writes PROPFIND properties for a collection element */
  6669. static void
  6670. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  6671. {
  6672. char mtime[64];
  6673. if (conn == NULL || uri == NULL || filep == NULL) {
  6674. return;
  6675. }
  6676. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  6677. conn->num_bytes_sent +=
  6678. mg_printf(conn,
  6679. "<d:response>"
  6680. "<d:href>%s</d:href>"
  6681. "<d:propstat>"
  6682. "<d:prop>"
  6683. "<d:resourcetype>%s</d:resourcetype>"
  6684. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  6685. "<d:getlastmodified>%s</d:getlastmodified>"
  6686. "</d:prop>"
  6687. "<d:status>HTTP/1.1 200 OK</d:status>"
  6688. "</d:propstat>"
  6689. "</d:response>\n",
  6690. uri,
  6691. filep->is_directory ? "<d:collection/>" : "",
  6692. filep->size,
  6693. mtime);
  6694. }
  6695. static void
  6696. print_dav_dir_entry(struct de *de, void *data)
  6697. {
  6698. char href[PATH_MAX];
  6699. char href_encoded[PATH_MAX];
  6700. int truncated;
  6701. struct mg_connection *conn = (struct mg_connection *)data;
  6702. if (!de || !conn) {
  6703. return;
  6704. }
  6705. mg_snprintf(conn,
  6706. &truncated,
  6707. href,
  6708. sizeof(href),
  6709. "%s%s",
  6710. conn->request_info.local_uri,
  6711. de->file_name);
  6712. if (!truncated) {
  6713. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  6714. print_props(conn, href_encoded, &de->file);
  6715. }
  6716. }
  6717. static void
  6718. handle_propfind(struct mg_connection *conn,
  6719. const char *path,
  6720. struct file *filep)
  6721. {
  6722. const char *depth = mg_get_header(conn, "Depth");
  6723. char date[64];
  6724. time_t curtime = time(NULL);
  6725. gmt_time_string(date, sizeof(date), &curtime);
  6726. if (!conn || !path || !filep) {
  6727. return;
  6728. }
  6729. conn->must_close = 1;
  6730. conn->status_code = 207;
  6731. mg_printf(conn,
  6732. "HTTP/1.1 207 Multi-Status\r\n"
  6733. "Date: %s\r\n"
  6734. "Connection: %s\r\n"
  6735. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  6736. date,
  6737. suggest_connection_header(conn));
  6738. conn->num_bytes_sent +=
  6739. mg_printf(conn,
  6740. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  6741. "<d:multistatus xmlns:d='DAV:'>\n");
  6742. /* Print properties for the requested resource itself */
  6743. print_props(conn, conn->request_info.local_uri, filep);
  6744. /* If it is a directory, print directory entries too if Depth is not 0 */
  6745. if (filep && conn->ctx && filep->is_directory
  6746. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  6747. && (depth == NULL || strcmp(depth, "0") != 0)) {
  6748. scan_directory(conn, path, conn, &print_dav_dir_entry);
  6749. }
  6750. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  6751. }
  6752. #endif
  6753. void
  6754. mg_lock_connection(struct mg_connection *conn)
  6755. {
  6756. if (conn) {
  6757. (void)pthread_mutex_lock(&conn->mutex);
  6758. }
  6759. }
  6760. void
  6761. mg_unlock_connection(struct mg_connection *conn)
  6762. {
  6763. if (conn) {
  6764. (void)pthread_mutex_unlock(&conn->mutex);
  6765. }
  6766. }
  6767. void
  6768. mg_lock_context(struct mg_context *ctx)
  6769. {
  6770. if (ctx) {
  6771. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  6772. }
  6773. }
  6774. void
  6775. mg_unlock_context(struct mg_context *ctx)
  6776. {
  6777. if (ctx) {
  6778. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  6779. }
  6780. }
  6781. #if defined(USE_TIMERS)
  6782. #include "timer.inl"
  6783. #endif /* USE_TIMERS */
  6784. #ifdef USE_LUA
  6785. #include "mod_lua.inl"
  6786. #endif /* USE_LUA */
  6787. #ifdef USE_DUKTAPE
  6788. #include "mod_duktape.inl"
  6789. #endif /* USE_DUKTAPE */
  6790. #if defined(USE_WEBSOCKET)
  6791. /* START OF SHA-1 code
  6792. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  6793. #define SHA1HANDSOFF
  6794. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  6795. *
  6796. * #if defined(__sun)
  6797. * #include "solarisfixes.h"
  6798. * #endif
  6799. */
  6800. static int
  6801. is_big_endian(void)
  6802. {
  6803. static const int n = 1;
  6804. return ((char *)&n)[0] == 0;
  6805. }
  6806. union char64long16 {
  6807. unsigned char c[64];
  6808. uint32_t l[16];
  6809. };
  6810. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6811. static uint32_t
  6812. blk0(union char64long16 *block, int i)
  6813. {
  6814. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  6815. if (!is_big_endian()) {
  6816. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  6817. | (rol(block->l[i], 8) & 0x00FF00FF);
  6818. }
  6819. return block->l[i];
  6820. }
  6821. #define blk(i) \
  6822. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  6823. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6824. 1))
  6825. #define R0(v, w, x, y, z, i) \
  6826. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6827. w = rol(w, 30);
  6828. #define R1(v, w, x, y, z, i) \
  6829. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6830. w = rol(w, 30);
  6831. #define R2(v, w, x, y, z, i) \
  6832. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6833. w = rol(w, 30);
  6834. #define R3(v, w, x, y, z, i) \
  6835. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6836. w = rol(w, 30);
  6837. #define R4(v, w, x, y, z, i) \
  6838. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6839. w = rol(w, 30);
  6840. typedef struct {
  6841. uint32_t state[5];
  6842. uint32_t count[2];
  6843. unsigned char buffer[64];
  6844. } SHA1_CTX;
  6845. static void
  6846. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  6847. {
  6848. uint32_t a, b, c, d, e;
  6849. union char64long16 block[1];
  6850. memcpy(block, buffer, 64);
  6851. a = state[0];
  6852. b = state[1];
  6853. c = state[2];
  6854. d = state[3];
  6855. e = state[4];
  6856. R0(a, b, c, d, e, 0);
  6857. R0(e, a, b, c, d, 1);
  6858. R0(d, e, a, b, c, 2);
  6859. R0(c, d, e, a, b, 3);
  6860. R0(b, c, d, e, a, 4);
  6861. R0(a, b, c, d, e, 5);
  6862. R0(e, a, b, c, d, 6);
  6863. R0(d, e, a, b, c, 7);
  6864. R0(c, d, e, a, b, 8);
  6865. R0(b, c, d, e, a, 9);
  6866. R0(a, b, c, d, e, 10);
  6867. R0(e, a, b, c, d, 11);
  6868. R0(d, e, a, b, c, 12);
  6869. R0(c, d, e, a, b, 13);
  6870. R0(b, c, d, e, a, 14);
  6871. R0(a, b, c, d, e, 15);
  6872. R1(e, a, b, c, d, 16);
  6873. R1(d, e, a, b, c, 17);
  6874. R1(c, d, e, a, b, 18);
  6875. R1(b, c, d, e, a, 19);
  6876. R2(a, b, c, d, e, 20);
  6877. R2(e, a, b, c, d, 21);
  6878. R2(d, e, a, b, c, 22);
  6879. R2(c, d, e, a, b, 23);
  6880. R2(b, c, d, e, a, 24);
  6881. R2(a, b, c, d, e, 25);
  6882. R2(e, a, b, c, d, 26);
  6883. R2(d, e, a, b, c, 27);
  6884. R2(c, d, e, a, b, 28);
  6885. R2(b, c, d, e, a, 29);
  6886. R2(a, b, c, d, e, 30);
  6887. R2(e, a, b, c, d, 31);
  6888. R2(d, e, a, b, c, 32);
  6889. R2(c, d, e, a, b, 33);
  6890. R2(b, c, d, e, a, 34);
  6891. R2(a, b, c, d, e, 35);
  6892. R2(e, a, b, c, d, 36);
  6893. R2(d, e, a, b, c, 37);
  6894. R2(c, d, e, a, b, 38);
  6895. R2(b, c, d, e, a, 39);
  6896. R3(a, b, c, d, e, 40);
  6897. R3(e, a, b, c, d, 41);
  6898. R3(d, e, a, b, c, 42);
  6899. R3(c, d, e, a, b, 43);
  6900. R3(b, c, d, e, a, 44);
  6901. R3(a, b, c, d, e, 45);
  6902. R3(e, a, b, c, d, 46);
  6903. R3(d, e, a, b, c, 47);
  6904. R3(c, d, e, a, b, 48);
  6905. R3(b, c, d, e, a, 49);
  6906. R3(a, b, c, d, e, 50);
  6907. R3(e, a, b, c, d, 51);
  6908. R3(d, e, a, b, c, 52);
  6909. R3(c, d, e, a, b, 53);
  6910. R3(b, c, d, e, a, 54);
  6911. R3(a, b, c, d, e, 55);
  6912. R3(e, a, b, c, d, 56);
  6913. R3(d, e, a, b, c, 57);
  6914. R3(c, d, e, a, b, 58);
  6915. R3(b, c, d, e, a, 59);
  6916. R4(a, b, c, d, e, 60);
  6917. R4(e, a, b, c, d, 61);
  6918. R4(d, e, a, b, c, 62);
  6919. R4(c, d, e, a, b, 63);
  6920. R4(b, c, d, e, a, 64);
  6921. R4(a, b, c, d, e, 65);
  6922. R4(e, a, b, c, d, 66);
  6923. R4(d, e, a, b, c, 67);
  6924. R4(c, d, e, a, b, 68);
  6925. R4(b, c, d, e, a, 69);
  6926. R4(a, b, c, d, e, 70);
  6927. R4(e, a, b, c, d, 71);
  6928. R4(d, e, a, b, c, 72);
  6929. R4(c, d, e, a, b, 73);
  6930. R4(b, c, d, e, a, 74);
  6931. R4(a, b, c, d, e, 75);
  6932. R4(e, a, b, c, d, 76);
  6933. R4(d, e, a, b, c, 77);
  6934. R4(c, d, e, a, b, 78);
  6935. R4(b, c, d, e, a, 79);
  6936. state[0] += a;
  6937. state[1] += b;
  6938. state[2] += c;
  6939. state[3] += d;
  6940. state[4] += e;
  6941. a = b = c = d = e = 0;
  6942. memset(block, '\0', sizeof(block));
  6943. }
  6944. static void
  6945. SHA1Init(SHA1_CTX *context)
  6946. {
  6947. context->state[0] = 0x67452301;
  6948. context->state[1] = 0xEFCDAB89;
  6949. context->state[2] = 0x98BADCFE;
  6950. context->state[3] = 0x10325476;
  6951. context->state[4] = 0xC3D2E1F0;
  6952. context->count[0] = context->count[1] = 0;
  6953. }
  6954. static void
  6955. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  6956. {
  6957. uint32_t i, j;
  6958. j = context->count[0];
  6959. if ((context->count[0] += len << 3) < j) {
  6960. context->count[1]++;
  6961. }
  6962. context->count[1] += (len >> 29);
  6963. j = (j >> 3) & 63;
  6964. if ((j + len) > 63) {
  6965. memcpy(&context->buffer[j], data, (i = 64 - j));
  6966. SHA1Transform(context->state, context->buffer);
  6967. for (; i + 63 < len; i += 64) {
  6968. SHA1Transform(context->state, &data[i]);
  6969. }
  6970. j = 0;
  6971. } else
  6972. i = 0;
  6973. memcpy(&context->buffer[j], &data[i], len - i);
  6974. }
  6975. static void
  6976. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  6977. {
  6978. unsigned i;
  6979. unsigned char finalcount[8], c;
  6980. for (i = 0; i < 8; i++) {
  6981. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  6982. >> ((3 - (i & 3)) * 8)) & 255);
  6983. }
  6984. c = 0200;
  6985. SHA1Update(context, &c, 1);
  6986. while ((context->count[0] & 504) != 448) {
  6987. c = 0000;
  6988. SHA1Update(context, &c, 1);
  6989. }
  6990. SHA1Update(context, finalcount, 8);
  6991. for (i = 0; i < 20; i++) {
  6992. digest[i] = (unsigned char)((context->state[i >> 2]
  6993. >> ((3 - (i & 3)) * 8)) & 255);
  6994. }
  6995. memset(context, '\0', sizeof(*context));
  6996. memset(&finalcount, '\0', sizeof(finalcount));
  6997. }
  6998. /* END OF SHA1 CODE */
  6999. static int
  7000. send_websocket_handshake(struct mg_connection *conn)
  7001. {
  7002. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7003. const char *protocol = NULL;
  7004. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7005. SHA1_CTX sha_ctx;
  7006. int truncated;
  7007. mg_snprintf(conn,
  7008. &truncated,
  7009. buf,
  7010. sizeof(buf),
  7011. "%s%s",
  7012. mg_get_header(conn, "Sec-WebSocket-Key"),
  7013. magic);
  7014. if (truncated) {
  7015. conn->must_close = 1;
  7016. return 0;
  7017. }
  7018. SHA1Init(&sha_ctx);
  7019. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7020. SHA1Final((unsigned char *)sha, &sha_ctx);
  7021. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7022. mg_printf(conn,
  7023. "HTTP/1.1 101 Switching Protocols\r\n"
  7024. "Upgrade: websocket\r\n"
  7025. "Connection: Upgrade\r\n"
  7026. "Sec-WebSocket-Accept: %s\r\n",
  7027. b64_sha);
  7028. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7029. if (protocol) {
  7030. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7031. } else {
  7032. mg_printf(conn, "%s", "\r\n");
  7033. }
  7034. return 1;
  7035. }
  7036. static void
  7037. read_websocket(struct mg_connection *conn,
  7038. mg_websocket_data_handler ws_data_handler,
  7039. void *callback_data)
  7040. {
  7041. /* Pointer to the beginning of the portion of the incoming websocket
  7042. * message queue.
  7043. * The original websocket upgrade request is never removed, so the queue
  7044. * begins after it. */
  7045. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7046. int n, error, exit_by_callback;
  7047. /* body_len is the length of the entire queue in bytes
  7048. * len is the length of the current message
  7049. * data_len is the length of the current message's data payload
  7050. * header_len is the length of the current message's header */
  7051. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7052. /* "The masking key is a 32-bit value chosen at random by the client."
  7053. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7054. */
  7055. unsigned char mask[4];
  7056. /* data points to the place where the message is stored when passed to the
  7057. * websocket_data callback. This is either mem on the stack, or a
  7058. * dynamically allocated buffer if it is too large. */
  7059. char mem[4096];
  7060. char *data = mem;
  7061. unsigned char mop; /* mask flag and opcode */
  7062. double timeout = -1.0;
  7063. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7064. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7065. }
  7066. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7067. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7068. }
  7069. mg_set_thread_name("wsock");
  7070. /* Loop continuously, reading messages from the socket, invoking the
  7071. * callback, and waiting repeatedly until an error occurs. */
  7072. while (!conn->ctx->stop_flag) {
  7073. header_len = 0;
  7074. assert(conn->data_len >= conn->request_len);
  7075. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7076. len = buf[1] & 127;
  7077. mask_len = buf[1] & 128 ? 4 : 0;
  7078. if (len < 126 && body_len >= mask_len) {
  7079. data_len = len;
  7080. header_len = 2 + mask_len;
  7081. } else if (len == 126 && body_len >= 4 + mask_len) {
  7082. header_len = 4 + mask_len;
  7083. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7084. } else if (body_len >= 10 + mask_len) {
  7085. header_len = 10 + mask_len;
  7086. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7087. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7088. }
  7089. }
  7090. if (header_len > 0 && body_len >= header_len) {
  7091. /* Allocate space to hold websocket payload */
  7092. data = mem;
  7093. if (data_len > sizeof(mem)) {
  7094. data = (char *)mg_malloc(data_len);
  7095. if (data == NULL) {
  7096. /* Allocation failed, exit the loop and then close the
  7097. * connection */
  7098. mg_cry(conn, "websocket out of memory; closing connection");
  7099. break;
  7100. }
  7101. }
  7102. /* Copy the mask before we shift the queue and destroy it */
  7103. if (mask_len > 0) {
  7104. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7105. } else {
  7106. memset(mask, 0, sizeof(mask));
  7107. }
  7108. /* Read frame payload from the first message in the queue into
  7109. * data and advance the queue by moving the memory in place. */
  7110. assert(body_len >= header_len);
  7111. if (data_len + header_len > body_len) {
  7112. mop = buf[0]; /* current mask and opcode */
  7113. /* Overflow case */
  7114. len = body_len - header_len;
  7115. memcpy(data, buf + header_len, len);
  7116. error = 0;
  7117. while (len < data_len) {
  7118. n = pull(
  7119. NULL, conn, data + len, (int)(data_len - len), timeout);
  7120. if (n <= 0) {
  7121. error = 1;
  7122. break;
  7123. }
  7124. len += (size_t)n;
  7125. }
  7126. if (error) {
  7127. mg_cry(conn, "Websocket pull failed; closing connection");
  7128. break;
  7129. }
  7130. conn->data_len = conn->request_len;
  7131. } else {
  7132. mop = buf[0]; /* current mask and opcode, overwritten by
  7133. * memmove() */
  7134. /* Length of the message being read at the front of the
  7135. * queue */
  7136. len = data_len + header_len;
  7137. /* Copy the data payload into the data pointer for the
  7138. * callback */
  7139. memcpy(data, buf + header_len, data_len);
  7140. /* Move the queue forward len bytes */
  7141. memmove(buf, buf + len, body_len - len);
  7142. /* Mark the queue as advanced */
  7143. conn->data_len -= (int)len;
  7144. }
  7145. /* Apply mask if necessary */
  7146. if (mask_len > 0) {
  7147. for (i = 0; i < data_len; ++i) {
  7148. data[i] ^= mask[i & 3];
  7149. }
  7150. }
  7151. /* Exit the loop if callback signals to exit (server side),
  7152. * or "connection close" opcode received (client side). */
  7153. exit_by_callback = 0;
  7154. if ((ws_data_handler != NULL)
  7155. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7156. exit_by_callback = 1;
  7157. }
  7158. if (data != mem) {
  7159. mg_free(data);
  7160. }
  7161. if (exit_by_callback
  7162. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7163. /* Opcode == 8, connection close */
  7164. break;
  7165. }
  7166. /* Not breaking the loop, process next websocket frame. */
  7167. } else {
  7168. /* Read from the socket into the next available location in the
  7169. * message queue. */
  7170. if ((n = pull(NULL,
  7171. conn,
  7172. conn->buf + conn->data_len,
  7173. conn->buf_size - conn->data_len,
  7174. timeout)) <= 0) {
  7175. /* Error, no bytes read */
  7176. break;
  7177. }
  7178. conn->data_len += n;
  7179. }
  7180. }
  7181. mg_set_thread_name("worker");
  7182. }
  7183. static int
  7184. mg_websocket_write_exec(struct mg_connection *conn,
  7185. int opcode,
  7186. const char *data,
  7187. size_t dataLen,
  7188. uint32_t masking_key)
  7189. {
  7190. unsigned char header[14];
  7191. size_t headerLen = 1;
  7192. int retval = -1;
  7193. header[0] = 0x80 + (opcode & 0xF);
  7194. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7195. if (dataLen < 126) {
  7196. /* inline 7-bit length field */
  7197. header[1] = (unsigned char)dataLen;
  7198. headerLen = 2;
  7199. } else if (dataLen <= 0xFFFF) {
  7200. /* 16-bit length field */
  7201. header[1] = 126;
  7202. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7203. headerLen = 4;
  7204. } else {
  7205. /* 64-bit length field */
  7206. header[1] = 127;
  7207. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7208. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7209. headerLen = 10;
  7210. }
  7211. if (masking_key) {
  7212. /* add mask */
  7213. header[1] |= 0x80;
  7214. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7215. headerLen += 4;
  7216. }
  7217. /* Note that POSIX/Winsock's send() is threadsafe
  7218. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7219. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7220. * push(), although that is only a problem if the packet is large or
  7221. * outgoing buffer is full). */
  7222. (void)mg_lock_connection(conn);
  7223. retval = mg_write(conn, header, headerLen);
  7224. if (dataLen > 0) {
  7225. retval = mg_write(conn, data, dataLen);
  7226. }
  7227. mg_unlock_connection(conn);
  7228. return retval;
  7229. }
  7230. int
  7231. mg_websocket_write(struct mg_connection *conn,
  7232. int opcode,
  7233. const char *data,
  7234. size_t dataLen)
  7235. {
  7236. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7237. }
  7238. int
  7239. mg_websocket_client_write(struct mg_connection *conn,
  7240. int opcode,
  7241. const char *data,
  7242. size_t dataLen)
  7243. {
  7244. int retval = -1;
  7245. size_t i = 0;
  7246. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7247. uint32_t masking_key;
  7248. static uint64_t lfsr = 0;
  7249. static uint64_t lcg = 0;
  7250. struct timespec now;
  7251. memset(&now, 0, sizeof(now));
  7252. clock_gettime(CLOCK_MONOTONIC, &now);
  7253. if (lfsr == 0) {
  7254. lfsr = (((uint64_t)now.tv_sec) << 21) ^ (uint64_t)now.tv_nsec
  7255. ^ (uint64_t)&dataLen;
  7256. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  7257. + (uint64_t)data;
  7258. } else {
  7259. lfsr = (lfsr >> 1)
  7260. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  7261. << 63);
  7262. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  7263. }
  7264. masking_key = (uint32_t)lfsr ^ (uint32_t)lcg ^ (uint32_t)now.tv_nsec;
  7265. if (masked_data == NULL) {
  7266. /* Return -1 in an error case */
  7267. mg_cry(conn,
  7268. "Cannot allocate buffer for masked websocket response: "
  7269. "Out of memory");
  7270. return -1;
  7271. }
  7272. i = 0;
  7273. if (((ptrdiff_t)data % 4) == 0) {
  7274. /* Convert in 32 bit words, if data is 4 byte aligned */
  7275. while (i < (dataLen - 3)) {
  7276. *(uint32_t *)(void *)(masked_data + i) =
  7277. *(uint32_t *)(void *)(data + i) ^ masking_key;
  7278. i += 4;
  7279. }
  7280. }
  7281. if (i != dataLen) {
  7282. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7283. i -= 4;
  7284. while (i < dataLen) {
  7285. *(uint8_t *)(void *)(masked_data + i) =
  7286. *(uint8_t *)(void *)(data + i)
  7287. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7288. i++;
  7289. }
  7290. }
  7291. /* TODO (high): Deal with ((dataLen % 4) != 0) and misalignment */
  7292. retval = mg_websocket_write_exec(
  7293. conn, opcode, masked_data, dataLen, masking_key);
  7294. mg_free(masked_data);
  7295. return retval;
  7296. }
  7297. static void
  7298. handle_websocket_request(struct mg_connection *conn,
  7299. const char *path,
  7300. int is_callback_resource,
  7301. mg_websocket_connect_handler ws_connect_handler,
  7302. mg_websocket_ready_handler ws_ready_handler,
  7303. mg_websocket_data_handler ws_data_handler,
  7304. mg_websocket_close_handler ws_close_handler,
  7305. void *cbData)
  7306. {
  7307. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7308. int lua_websock = 0;
  7309. #if !defined(USE_LUA)
  7310. (void)path;
  7311. #endif
  7312. /* Step 1: Check websocket protocol version. */
  7313. if (version == NULL || strcmp(version, "13") != 0) {
  7314. /* Reject wrong versions */
  7315. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7316. return;
  7317. }
  7318. /* Step 2: If a callback is responsible, call it. */
  7319. if (is_callback_resource) {
  7320. if (ws_connect_handler != NULL
  7321. && ws_connect_handler(conn, cbData) != 0) {
  7322. /* C callback has returned non-zero, do not proceed with handshake.
  7323. */
  7324. /* Note that C callbacks are no longer called when Lua is
  7325. * responsible, so C can no longer filter callbacks for Lua. */
  7326. return;
  7327. }
  7328. }
  7329. #if defined(USE_LUA)
  7330. /* Step 3: No callback. Check if Lua is responsible. */
  7331. else {
  7332. /* Step 3.1: Check if Lua is responsible. */
  7333. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7334. lua_websock =
  7335. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7336. strlen(
  7337. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7338. path);
  7339. }
  7340. if (lua_websock) {
  7341. /* Step 3.2: Lua is responsible: call it. */
  7342. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7343. if (!conn->lua_websocket_state) {
  7344. /* Lua rejected the new client */
  7345. return;
  7346. }
  7347. }
  7348. }
  7349. #endif
  7350. /* Step 4: Check if there is a responsible websocket handler. */
  7351. if (!is_callback_resource && !lua_websock) {
  7352. /* There is no callback, an Lua is not responsible either. */
  7353. /* Reply with a 404 Not Found or with nothing at all?
  7354. * TODO (mid): check the websocket standards, how to reply to
  7355. * requests to invalid websocket addresses. */
  7356. send_http_error(conn, 404, "%s", "Not found");
  7357. return;
  7358. }
  7359. /* Step 5: The websocket connection has been accepted */
  7360. if (!send_websocket_handshake(conn)) {
  7361. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7362. return;
  7363. }
  7364. /* Step 6: Call the ready handler */
  7365. if (is_callback_resource) {
  7366. if (ws_ready_handler != NULL) {
  7367. ws_ready_handler(conn, cbData);
  7368. }
  7369. #if defined(USE_LUA)
  7370. } else if (lua_websock) {
  7371. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7372. /* the ready handler returned false */
  7373. return;
  7374. }
  7375. #endif
  7376. }
  7377. /* Step 7: Enter the read loop */
  7378. if (is_callback_resource) {
  7379. read_websocket(conn, ws_data_handler, cbData);
  7380. #if defined(USE_LUA)
  7381. } else if (lua_websock) {
  7382. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7383. #endif
  7384. }
  7385. /* Step 8: Call the close handler */
  7386. if (ws_close_handler) {
  7387. ws_close_handler(conn, cbData);
  7388. }
  7389. }
  7390. static int
  7391. is_websocket_protocol(const struct mg_connection *conn)
  7392. {
  7393. const char *host, *upgrade, *connection, *version, *key;
  7394. upgrade = mg_get_header(conn, "Upgrade");
  7395. if (upgrade == NULL) {
  7396. return 0; /* fail early, don't waste time checking other header fields
  7397. */
  7398. }
  7399. if (!mg_strcasestr(upgrade, "websocket")) {
  7400. return 0;
  7401. }
  7402. connection = mg_get_header(conn, "Connection");
  7403. if (connection == NULL) {
  7404. return 0;
  7405. }
  7406. if (!mg_strcasestr(connection, "upgrade")) {
  7407. return 0;
  7408. }
  7409. host = mg_get_header(conn, "Host");
  7410. key = mg_get_header(conn, "Sec-WebSocket-Key");
  7411. version = mg_get_header(conn, "Sec-WebSocket-Version");
  7412. return (host != NULL && key != NULL && version != NULL);
  7413. }
  7414. #endif /* !USE_WEBSOCKET */
  7415. static int
  7416. isbyte(int n)
  7417. {
  7418. return n >= 0 && n <= 255;
  7419. }
  7420. static int
  7421. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7422. {
  7423. int n, a, b, c, d, slash = 32, len = 0;
  7424. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7425. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7426. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7427. && slash < 33) {
  7428. len = n;
  7429. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7430. | (uint32_t)d;
  7431. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7432. }
  7433. return len;
  7434. }
  7435. static int
  7436. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7437. {
  7438. int throttle = 0;
  7439. struct vec vec, val;
  7440. uint32_t net, mask;
  7441. char mult;
  7442. double v;
  7443. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7444. mult = ',';
  7445. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7446. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7447. && mult != ',')) {
  7448. continue;
  7449. }
  7450. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7451. : 1;
  7452. if (vec.len == 1 && vec.ptr[0] == '*') {
  7453. throttle = (int)v;
  7454. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7455. if ((remote_ip & mask) == net) {
  7456. throttle = (int)v;
  7457. }
  7458. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7459. throttle = (int)v;
  7460. }
  7461. }
  7462. return throttle;
  7463. }
  7464. static uint32_t
  7465. get_remote_ip(const struct mg_connection *conn)
  7466. {
  7467. if (!conn) {
  7468. return 0;
  7469. }
  7470. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7471. }
  7472. int
  7473. mg_upload(struct mg_connection *conn, const char *destination_dir)
  7474. {
  7475. /* TODO (high): completely rewrite this function. See issue #180. */
  7476. /* TODO (mid): set a timeout */
  7477. const char *content_type_header, *boundary_start, *sc;
  7478. char *s;
  7479. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX];
  7480. char fname[1024], boundary[100];
  7481. FILE *fp;
  7482. int bl, n, i, headers_len, boundary_len, eof, truncated;
  7483. int len = 0, num_uploaded_files = 0;
  7484. struct mg_request_info part_request_info;
  7485. /* Request looks like this:
  7486. *
  7487. * POST /upload HTTP/1.1
  7488. * Host: 127.0.0.1:8080
  7489. * Content-Length: 244894
  7490. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  7491. *
  7492. * ------WebKitFormBoundaryRVr
  7493. * Content-Disposition: form-data; name="file"; filename="accum.png"
  7494. * Content-Type: image/png
  7495. *
  7496. * <89>PNG
  7497. * <PNG DATA>
  7498. * ------WebKitFormBoundaryRVr */
  7499. /* Extract boundary string from the Content-Type header */
  7500. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL
  7501. || (boundary_start = mg_strcasestr(content_type_header, "boundary="))
  7502. == NULL
  7503. || (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0
  7504. && sscanf(boundary_start, "boundary=%99s", boundary) == 0)
  7505. || boundary[0] == '\0') {
  7506. return num_uploaded_files;
  7507. }
  7508. boundary[99] = 0;
  7509. boundary_len = (int)strlen(boundary);
  7510. bl = boundary_len + 4; /* \r\n--<boundary> */
  7511. for (;;) {
  7512. /* Pull in headers */
  7513. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  7514. if ((len < 0) || (len > (int)sizeof(buf))) {
  7515. break;
  7516. }
  7517. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  7518. len += n;
  7519. /* assert(len <= (int) sizeof(buf)); */
  7520. if (len > (int)sizeof(buf)) {
  7521. break;
  7522. }
  7523. }
  7524. if ((headers_len = get_request_len(buf, len)) <= 0) {
  7525. break;
  7526. }
  7527. /* terminate header */
  7528. buf[headers_len - 1] = 0;
  7529. /* Scan for the boundary string and skip it */
  7530. if (buf[0] == '-' && buf[1] == '-'
  7531. && !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  7532. s = &buf[bl];
  7533. } else {
  7534. s = &buf[2];
  7535. }
  7536. /* Get headers for this part of the multipart message */
  7537. memset(&part_request_info, 0, sizeof(part_request_info));
  7538. parse_http_headers(&s, &part_request_info);
  7539. /* assert(&buf[headers_len-1] == s); */
  7540. if (&buf[headers_len - 1] != s) {
  7541. break;
  7542. }
  7543. /* Fetch file name. */
  7544. sc = get_header(&part_request_info, "Content-Disposition");
  7545. if (!sc) {
  7546. /* invalid part of a multipart message */
  7547. break;
  7548. }
  7549. sc = strstr(sc, "filename");
  7550. if (!sc) {
  7551. /* no filename set */
  7552. break;
  7553. }
  7554. sc += 8; /* skip "filename" */
  7555. fname[0] = '\0';
  7556. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  7557. fname[1023] = 0;
  7558. /* Give up if the headers are not what we expect */
  7559. if (fname[0] == '\0') {
  7560. break;
  7561. }
  7562. /* Construct destination file name. Do not allow paths to have
  7563. * slashes. */
  7564. if ((s = strrchr(fname, '/')) == NULL
  7565. && (s = strrchr(fname, '\\')) == NULL) {
  7566. s = fname;
  7567. } else {
  7568. s++;
  7569. }
  7570. /* There data is written to a temporary file first. */
  7571. /* Different users should use a different destination_dir. */
  7572. mg_snprintf(conn,
  7573. &truncated,
  7574. path,
  7575. sizeof(path) - 1,
  7576. "%s/%s",
  7577. destination_dir,
  7578. s);
  7579. /* TODO(high): kick client on buffer overflow */
  7580. strcpy(tmp_path, path);
  7581. strcat(tmp_path, "~");
  7582. /* We open the file with exclusive lock held. This guarantee us
  7583. * there is no other thread can save into the same file
  7584. * simultaneously. */
  7585. fp = NULL;
  7586. /* Open file in binary mode. */
  7587. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  7588. break;
  7589. }
  7590. /* Move data to the beginning of the buffer */
  7591. /* part_request_info is no longer valid after this operation */
  7592. /* assert(len >= headers_len); */
  7593. if (len < headers_len) {
  7594. break;
  7595. }
  7596. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  7597. len -= headers_len;
  7598. /* Read POST data, write into file until boundary is found. */
  7599. eof = n = 0;
  7600. do {
  7601. len += n;
  7602. for (i = 0; i < len - bl; i++) {
  7603. if (!memcmp(&buf[i], "\r\n--", 4)
  7604. && !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  7605. /* Found boundary, that's the end of file data. */
  7606. fwrite(buf, 1, (size_t)i, fp);
  7607. eof = 1;
  7608. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  7609. len -= i + bl;
  7610. break;
  7611. }
  7612. }
  7613. if (!eof && len > bl) {
  7614. fwrite(buf, 1, (size_t)(len - bl), fp);
  7615. memmove(buf, &buf[len - bl], (size_t)bl);
  7616. len = bl;
  7617. }
  7618. if (!eof) {
  7619. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  7620. }
  7621. } while (!eof && (n > 0));
  7622. fclose(fp);
  7623. if (eof) {
  7624. remove(path);
  7625. rename(tmp_path, path);
  7626. num_uploaded_files++;
  7627. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  7628. conn->ctx->callbacks.upload(conn, path);
  7629. }
  7630. } else {
  7631. remove(tmp_path);
  7632. }
  7633. }
  7634. return num_uploaded_files;
  7635. }
  7636. static int
  7637. get_first_ssl_listener_index(const struct mg_context *ctx)
  7638. {
  7639. unsigned int i;
  7640. int idx = -1;
  7641. if (ctx) {
  7642. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7643. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7644. }
  7645. }
  7646. return idx;
  7647. }
  7648. static void
  7649. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7650. {
  7651. char host[1025];
  7652. const char *host_header;
  7653. size_t hostlen;
  7654. host_header = mg_get_header(conn, "Host");
  7655. hostlen = sizeof(host);
  7656. if (host_header != NULL) {
  7657. char *pos;
  7658. mg_strlcpy(host, host_header, hostlen);
  7659. host[hostlen - 1] = '\0';
  7660. pos = strchr(host, ':');
  7661. if (pos != NULL) {
  7662. *pos = '\0';
  7663. }
  7664. } else {
  7665. /* Cannot get host from the Host: header.
  7666. * Fallback to our IP address. */
  7667. if (conn) {
  7668. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7669. }
  7670. }
  7671. /* Send host, port, uri and (if it exists) ?query_string */
  7672. if (conn) {
  7673. mg_printf(conn,
  7674. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7675. host,
  7676. (int)ntohs(
  7677. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7678. conn->request_info.local_uri,
  7679. (conn->request_info.query_string == NULL) ? "" : "?",
  7680. (conn->request_info.query_string == NULL)
  7681. ? ""
  7682. : conn->request_info.query_string);
  7683. }
  7684. }
  7685. static void
  7686. mg_set_request_handler_type(struct mg_context *ctx,
  7687. const char *uri,
  7688. int is_websocket_handler,
  7689. int is_delete_request,
  7690. mg_request_handler handler,
  7691. mg_websocket_connect_handler connect_handler,
  7692. mg_websocket_ready_handler ready_handler,
  7693. mg_websocket_data_handler data_handler,
  7694. mg_websocket_close_handler close_handler,
  7695. void *cbdata)
  7696. {
  7697. struct mg_request_handler_info *tmp_rh, **lastref;
  7698. size_t urilen = strlen(uri);
  7699. if (is_websocket_handler) {
  7700. /* assert(handler == NULL); */
  7701. /* assert(is_delete_request || connect_handler!=NULL ||
  7702. * ready_handler!=NULL || data_handler!=NULL ||
  7703. * close_handler!=NULL);
  7704. */
  7705. if (handler != NULL) {
  7706. return;
  7707. }
  7708. if (!is_delete_request && connect_handler == NULL
  7709. && ready_handler == NULL
  7710. && data_handler == NULL
  7711. && close_handler == NULL) {
  7712. return;
  7713. }
  7714. } else {
  7715. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7716. * data_handler==NULL && close_handler==NULL); */
  7717. /* assert(is_delete_request || (handler!=NULL));
  7718. */
  7719. if (connect_handler != NULL || ready_handler != NULL
  7720. || data_handler != NULL
  7721. || close_handler != NULL) {
  7722. return;
  7723. }
  7724. if (!is_delete_request && (handler == NULL)) {
  7725. return;
  7726. }
  7727. }
  7728. if (!ctx) {
  7729. return;
  7730. }
  7731. mg_lock_context(ctx);
  7732. /* first try to find an existing handler */
  7733. lastref = &(ctx->request_handlers);
  7734. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  7735. tmp_rh = tmp_rh->next) {
  7736. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  7737. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7738. if (!is_delete_request) {
  7739. /* update existing handler */
  7740. if (!is_websocket_handler) {
  7741. tmp_rh->handler = handler;
  7742. } else {
  7743. tmp_rh->connect_handler = connect_handler;
  7744. tmp_rh->ready_handler = ready_handler;
  7745. tmp_rh->data_handler = data_handler;
  7746. tmp_rh->close_handler = close_handler;
  7747. }
  7748. tmp_rh->cbdata = cbdata;
  7749. } else {
  7750. /* remove existing handler */
  7751. *lastref = tmp_rh->next;
  7752. mg_free(tmp_rh->uri);
  7753. mg_free(tmp_rh);
  7754. }
  7755. mg_unlock_context(ctx);
  7756. return;
  7757. }
  7758. }
  7759. lastref = &(tmp_rh->next);
  7760. }
  7761. if (is_delete_request) {
  7762. /* no handler to set, this was a remove request to a non-existing
  7763. * handler */
  7764. mg_unlock_context(ctx);
  7765. return;
  7766. }
  7767. tmp_rh = (struct mg_request_handler_info *)
  7768. mg_calloc(sizeof(struct mg_request_handler_info), 1);
  7769. if (tmp_rh == NULL) {
  7770. mg_unlock_context(ctx);
  7771. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7772. return;
  7773. }
  7774. tmp_rh->uri = mg_strdup(uri);
  7775. if (!tmp_rh->uri) {
  7776. mg_unlock_context(ctx);
  7777. mg_free(tmp_rh);
  7778. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7779. return;
  7780. }
  7781. tmp_rh->uri_len = urilen;
  7782. if (!is_websocket_handler) {
  7783. tmp_rh->handler = handler;
  7784. } else {
  7785. tmp_rh->connect_handler = connect_handler;
  7786. tmp_rh->ready_handler = ready_handler;
  7787. tmp_rh->data_handler = data_handler;
  7788. tmp_rh->close_handler = close_handler;
  7789. }
  7790. tmp_rh->cbdata = cbdata;
  7791. tmp_rh->is_websocket_handler = is_websocket_handler;
  7792. tmp_rh->next = NULL;
  7793. *lastref = tmp_rh;
  7794. mg_unlock_context(ctx);
  7795. }
  7796. void
  7797. mg_set_request_handler(struct mg_context *ctx,
  7798. const char *uri,
  7799. mg_request_handler handler,
  7800. void *cbdata)
  7801. {
  7802. mg_set_request_handler_type(
  7803. ctx, uri, 0, handler == NULL, handler, NULL, NULL, NULL, NULL, cbdata);
  7804. }
  7805. void
  7806. mg_set_websocket_handler(struct mg_context *ctx,
  7807. const char *uri,
  7808. mg_websocket_connect_handler connect_handler,
  7809. mg_websocket_ready_handler ready_handler,
  7810. mg_websocket_data_handler data_handler,
  7811. mg_websocket_close_handler close_handler,
  7812. void *cbdata)
  7813. {
  7814. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  7815. && (data_handler == NULL)
  7816. && (close_handler == NULL);
  7817. mg_set_request_handler_type(ctx,
  7818. uri,
  7819. 1,
  7820. is_delete_request,
  7821. NULL,
  7822. connect_handler,
  7823. ready_handler,
  7824. data_handler,
  7825. close_handler,
  7826. cbdata);
  7827. }
  7828. static int
  7829. get_request_handler(struct mg_connection *conn,
  7830. int is_websocket_request,
  7831. mg_request_handler *handler,
  7832. mg_websocket_connect_handler *connect_handler,
  7833. mg_websocket_ready_handler *ready_handler,
  7834. mg_websocket_data_handler *data_handler,
  7835. mg_websocket_close_handler *close_handler,
  7836. void **cbdata)
  7837. {
  7838. const struct mg_request_info *request_info = mg_get_request_info(conn);
  7839. if (request_info) {
  7840. const char *uri = request_info->local_uri;
  7841. size_t urilen = strlen(uri);
  7842. struct mg_request_handler_info *tmp_rh;
  7843. if (!conn || !conn->ctx) {
  7844. return 0;
  7845. }
  7846. mg_lock_context(conn->ctx);
  7847. /* first try for an exact match */
  7848. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7849. tmp_rh = tmp_rh->next) {
  7850. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7851. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7852. if (is_websocket_request) {
  7853. *connect_handler = tmp_rh->connect_handler;
  7854. *ready_handler = tmp_rh->ready_handler;
  7855. *data_handler = tmp_rh->data_handler;
  7856. *close_handler = tmp_rh->close_handler;
  7857. } else {
  7858. *handler = tmp_rh->handler;
  7859. }
  7860. *cbdata = tmp_rh->cbdata;
  7861. mg_unlock_context(conn->ctx);
  7862. return 1;
  7863. }
  7864. }
  7865. }
  7866. /* next try for a partial match, we will accept uri/something */
  7867. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7868. tmp_rh = tmp_rh->next) {
  7869. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7870. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  7871. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  7872. if (is_websocket_request) {
  7873. *connect_handler = tmp_rh->connect_handler;
  7874. *ready_handler = tmp_rh->ready_handler;
  7875. *data_handler = tmp_rh->data_handler;
  7876. *close_handler = tmp_rh->close_handler;
  7877. } else {
  7878. *handler = tmp_rh->handler;
  7879. }
  7880. *cbdata = tmp_rh->cbdata;
  7881. mg_unlock_context(conn->ctx);
  7882. return 1;
  7883. }
  7884. }
  7885. }
  7886. /* finally try for pattern match */
  7887. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7888. tmp_rh = tmp_rh->next) {
  7889. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7890. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  7891. if (is_websocket_request) {
  7892. *connect_handler = tmp_rh->connect_handler;
  7893. *ready_handler = tmp_rh->ready_handler;
  7894. *data_handler = tmp_rh->data_handler;
  7895. *close_handler = tmp_rh->close_handler;
  7896. } else {
  7897. *handler = tmp_rh->handler;
  7898. }
  7899. *cbdata = tmp_rh->cbdata;
  7900. mg_unlock_context(conn->ctx);
  7901. return 1;
  7902. }
  7903. }
  7904. }
  7905. mg_unlock_context(conn->ctx);
  7906. }
  7907. return 0; /* none found */
  7908. }
  7909. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  7910. static int
  7911. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  7912. void *cbdata)
  7913. {
  7914. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7915. if (pcallbacks->websocket_connect) {
  7916. return pcallbacks->websocket_connect(conn);
  7917. }
  7918. /* No handler set - assume "OK" */
  7919. return 0;
  7920. }
  7921. static void
  7922. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  7923. {
  7924. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7925. if (pcallbacks->websocket_ready) {
  7926. pcallbacks->websocket_ready(conn);
  7927. }
  7928. }
  7929. static int
  7930. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  7931. int bits,
  7932. char *data,
  7933. size_t len,
  7934. void *cbdata)
  7935. {
  7936. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7937. if (pcallbacks->websocket_data) {
  7938. return pcallbacks->websocket_data(conn, bits, data, len);
  7939. }
  7940. /* No handler set - assume "OK" */
  7941. return 1;
  7942. }
  7943. #endif
  7944. /* This is the heart of the Civetweb's logic.
  7945. * This function is called when the request is read, parsed and validated,
  7946. * and Civetweb must decide what action to take: serve a file, or
  7947. * a directory, or call embedded function, etcetera. */
  7948. static void
  7949. handle_request(struct mg_connection *conn)
  7950. {
  7951. if (conn) {
  7952. struct mg_request_info *ri = &conn->request_info;
  7953. char path[PATH_MAX];
  7954. int uri_len, ssl_index;
  7955. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  7956. is_put_or_delete_request = 0, is_callback_resource = 0;
  7957. int i;
  7958. struct file file = STRUCT_FILE_INITIALIZER;
  7959. mg_request_handler callback_handler = NULL;
  7960. mg_websocket_connect_handler ws_connect_handler = NULL;
  7961. mg_websocket_ready_handler ws_ready_handler = NULL;
  7962. mg_websocket_data_handler ws_data_handler = NULL;
  7963. mg_websocket_close_handler ws_close_handler = NULL;
  7964. void *callback_data = NULL;
  7965. #if !defined(NO_FILES)
  7966. time_t curtime = time(NULL);
  7967. char date[64];
  7968. #endif
  7969. path[0] = 0;
  7970. if (!ri) {
  7971. return;
  7972. }
  7973. /* 1. get the request url */
  7974. /* 1.1. split into url and query string */
  7975. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  7976. != NULL) {
  7977. *((char *)conn->request_info.query_string++) = '\0';
  7978. }
  7979. uri_len = (int)strlen(ri->local_uri);
  7980. /* 1.2. decode url (if config says so) */
  7981. if (should_decode_url(conn)) {
  7982. mg_url_decode(
  7983. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  7984. }
  7985. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  7986. * possible */
  7987. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  7988. /* step 1. completed, the url is known now */
  7989. DEBUG_TRACE("URL: %s", ri->local_uri);
  7990. /* 2. do a https redirect, if required */
  7991. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  7992. ssl_index = get_first_ssl_listener_index(conn->ctx);
  7993. if (ssl_index >= 0) {
  7994. redirect_to_https_port(conn, ssl_index);
  7995. } else {
  7996. /* A http to https forward port has been specified,
  7997. * but no https port to forward to. */
  7998. send_http_error(conn,
  7999. 503,
  8000. "%s",
  8001. "Error: SSL forward not configured properly");
  8002. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8003. }
  8004. return;
  8005. }
  8006. /* 3. if this ip has limited speed, set it for this connection */
  8007. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8008. get_remote_ip(conn),
  8009. ri->local_uri);
  8010. /* 4. call a "handle everything" callback, if registered */
  8011. if (conn->ctx->callbacks.begin_request != NULL) {
  8012. /* Note that since V1.7 the "begin_request" function is called
  8013. * before an authorization check. If an authorization check is
  8014. * required, use a request_handler instead. */
  8015. i = conn->ctx->callbacks.begin_request(conn);
  8016. if (i > 0) {
  8017. /* callback already processed the request. Store the
  8018. return value as a status code for the access log. */
  8019. conn->status_code = i;
  8020. return;
  8021. } else if (i == 0) {
  8022. /* civetweb should process the request */
  8023. } else {
  8024. /* unspecified - may change with the next version */
  8025. return;
  8026. }
  8027. }
  8028. /* request not yet handled by a handler or redirect, so the request
  8029. * is processed here */
  8030. /* 5. interpret the url to find out how the request must be handled */
  8031. /* 5.1. first test, if the request targets the regular http(s)://
  8032. * protocol namespace or the websocket ws(s):// protocol namespace. */
  8033. is_websocket_request = is_websocket_protocol(conn);
  8034. /* 5.2. check if the request will be handled by a callback */
  8035. if (get_request_handler(conn,
  8036. is_websocket_request,
  8037. &callback_handler,
  8038. &ws_connect_handler,
  8039. &ws_ready_handler,
  8040. &ws_data_handler,
  8041. &ws_close_handler,
  8042. &callback_data)) {
  8043. /* 5.2.1. A callback will handle this request. All requests handled
  8044. * by a callback have to be considered as requests to a script
  8045. * resource. */
  8046. is_callback_resource = 1;
  8047. is_script_resource = 1;
  8048. is_put_or_delete_request = is_put_or_delete_method(conn);
  8049. } else {
  8050. no_callback_resource:
  8051. /* 5.2.2. No callback is responsible for this request. The URI
  8052. * addresses a file based resource (static content or Lua/cgi
  8053. * scripts in the file system). */
  8054. is_callback_resource = 0;
  8055. interpret_uri(conn,
  8056. path,
  8057. sizeof(path),
  8058. &file,
  8059. &is_found,
  8060. &is_script_resource,
  8061. &is_websocket_request,
  8062. &is_put_or_delete_request);
  8063. }
  8064. /* 6. authorization check */
  8065. if (is_put_or_delete_request && !is_script_resource
  8066. && !is_callback_resource) {
  8067. /* 6.1. this request is a PUT/DELETE to a real file */
  8068. /* 6.1.1. thus, the server must have real files */
  8069. #if defined(NO_FILES)
  8070. if (1) {
  8071. #else
  8072. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8073. #endif
  8074. /* This server does not have any real files, thus the
  8075. * PUT/DELETE methods are not valid. */
  8076. send_http_error(conn,
  8077. 405,
  8078. "%s method not allowed",
  8079. conn->request_info.request_method);
  8080. return;
  8081. }
  8082. #if !defined(NO_FILES)
  8083. /* 6.1.2. Check if put authorization for static files is available.
  8084. */
  8085. if (!is_authorized_for_put(conn)) {
  8086. send_authorization_request(conn);
  8087. return;
  8088. }
  8089. #endif
  8090. } else {
  8091. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  8092. * or it is a PUT or DELETE request to a resource that does not
  8093. * correspond to a file. Check authorization. */
  8094. if (!check_authorization(conn, path)) {
  8095. send_authorization_request(conn);
  8096. return;
  8097. }
  8098. }
  8099. /* request is authorized or does not need authorization */
  8100. /* 7. check if there are request handlers for this uri */
  8101. if (is_callback_resource) {
  8102. if (!is_websocket_request) {
  8103. i = callback_handler(conn, callback_data);
  8104. if (i > 0) {
  8105. /* Do nothing, callback has served the request. Store the
  8106. * return value as status code for the log and discard all
  8107. * data from the client not used by the callback. */
  8108. conn->status_code = i;
  8109. discard_unread_request_data(conn);
  8110. } else {
  8111. /* TODO (high): what if the handler did NOT handle the
  8112. * request */
  8113. /* The last version did handle this as a file request, but
  8114. * since a file request is not always a script resource,
  8115. * the authorization check might be different */
  8116. interpret_uri(conn,
  8117. path,
  8118. sizeof(path),
  8119. &file,
  8120. &is_found,
  8121. &is_script_resource,
  8122. &is_websocket_request,
  8123. &is_put_or_delete_request);
  8124. callback_handler = NULL;
  8125. /* TODO (very low): goto is deprecated but for the moment,
  8126. * a goto is simpler than some curious loop. */
  8127. /* The situation "callback does not handle the request"
  8128. * needs to be reconsidered anyway. */
  8129. goto no_callback_resource;
  8130. }
  8131. } else {
  8132. #if defined(USE_WEBSOCKET)
  8133. handle_websocket_request(conn,
  8134. path,
  8135. is_callback_resource,
  8136. ws_connect_handler,
  8137. ws_ready_handler,
  8138. ws_data_handler,
  8139. ws_close_handler,
  8140. callback_data);
  8141. #endif
  8142. }
  8143. return;
  8144. }
  8145. /* 8. handle websocket requests */
  8146. #if defined(USE_WEBSOCKET)
  8147. if (is_websocket_request) {
  8148. if (is_script_resource) {
  8149. /* Websocket Lua script */
  8150. handle_websocket_request(conn,
  8151. path,
  8152. 0 /* Lua Script */,
  8153. NULL,
  8154. NULL,
  8155. NULL,
  8156. NULL,
  8157. &conn->ctx->callbacks);
  8158. } else {
  8159. #if defined(MG_LEGACY_INTERFACE)
  8160. handle_websocket_request(
  8161. conn,
  8162. path,
  8163. !is_script_resource /* could be deprecated global callback */,
  8164. deprecated_websocket_connect_wrapper,
  8165. deprecated_websocket_ready_wrapper,
  8166. deprecated_websocket_data_wrapper,
  8167. NULL,
  8168. &conn->ctx->callbacks);
  8169. #else
  8170. send_http_error(conn, 404, "%s", "Not found");
  8171. #endif
  8172. }
  8173. return;
  8174. } else
  8175. #endif
  8176. #if defined(NO_FILES)
  8177. /* 9a. In case the server uses only callbacks, this uri is unknown.
  8178. * Then, all request handling ends here. */
  8179. send_http_error(conn, 404, "%s", "Not Found");
  8180. #else
  8181. /* 9b. This request is either for a static file or resource handled
  8182. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8183. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8184. send_http_error(conn, 404, "%s", "Not Found");
  8185. return;
  8186. }
  8187. /* 10. File is handled by a script. */
  8188. if (is_script_resource) {
  8189. handle_file_based_request(conn, path, &file);
  8190. return;
  8191. }
  8192. /* 11. Handle put/delete/mkcol requests */
  8193. if (is_put_or_delete_request) {
  8194. /* 11.1. PUT method */
  8195. if (!strcmp(ri->request_method, "PUT")) {
  8196. put_file(conn, path);
  8197. return;
  8198. }
  8199. /* 11.2. DELETE method */
  8200. if (!strcmp(ri->request_method, "DELETE")) {
  8201. delete_file(conn, path);
  8202. return;
  8203. }
  8204. /* 11.3. MKCOL method */
  8205. if (!strcmp(ri->request_method, "MKCOL")) {
  8206. mkcol(conn, path);
  8207. return;
  8208. }
  8209. /* 11.4. PATCH method
  8210. * This method is not supported for static resources,
  8211. * only for scripts (Lua, CGI) and callbacks. */
  8212. send_http_error(conn,
  8213. 405,
  8214. "%s method not allowed",
  8215. conn->request_info.request_method);
  8216. return;
  8217. }
  8218. /* 11. File does not exist, or it was configured that it should be
  8219. * hidden */
  8220. if (!is_found || (must_hide_file(conn, path))) {
  8221. send_http_error(conn, 404, "%s", "Not found");
  8222. return;
  8223. }
  8224. /* 12. Directories uris should end with a slash */
  8225. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8226. gmt_time_string(date, sizeof(date), &curtime);
  8227. mg_printf(conn,
  8228. "HTTP/1.1 301 Moved Permanently\r\n"
  8229. "Location: %s/\r\n"
  8230. "Date: %s\r\n"
  8231. "Content-Length: 0\r\n"
  8232. "Connection: %s\r\n\r\n",
  8233. ri->request_uri,
  8234. date,
  8235. suggest_connection_header(conn));
  8236. return;
  8237. }
  8238. /* 13. Handle other methods than GET/HEAD */
  8239. /* 13.1. Handle PROPFIND */
  8240. if (!strcmp(ri->request_method, "PROPFIND")) {
  8241. handle_propfind(conn, path, &file);
  8242. return;
  8243. }
  8244. /* 13.2. Handle OPTIONS for files */
  8245. if (!strcmp(ri->request_method, "OPTIONS")) {
  8246. /* This standard handler is only used for real files.
  8247. * Scripts should support the OPTIONS method themselves, to allow a
  8248. * maximum flexibility.
  8249. * Lua and CGI scripts may fully support CORS this way (including
  8250. * preflights). */
  8251. send_options(conn);
  8252. return;
  8253. }
  8254. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8255. if (0 != strcmp(ri->request_method, "GET")
  8256. && 0 != strcmp(ri->request_method, "HEAD")) {
  8257. send_http_error(conn,
  8258. 405,
  8259. "%s method not allowed",
  8260. conn->request_info.request_method);
  8261. return;
  8262. }
  8263. /* 14. directories */
  8264. if (file.is_directory) {
  8265. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8266. /* 14.1. use a substitute file */
  8267. /* TODO (high): substitute index may be a script resource.
  8268. * define what should be possible in this case. */
  8269. } else {
  8270. /* 14.2. no substitute file */
  8271. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8272. "yes")) {
  8273. handle_directory_request(conn, path);
  8274. } else {
  8275. send_http_error(conn,
  8276. 403,
  8277. "%s",
  8278. "Error: Directory listing denied");
  8279. }
  8280. return;
  8281. }
  8282. }
  8283. handle_file_based_request(conn, path, &file);
  8284. #endif /* !defined(NO_FILES) */
  8285. #if 0
  8286. /* Perform redirect and auth checks before calling begin_request()
  8287. * handler.
  8288. * Otherwise, begin_request() would need to perform auth checks and
  8289. * redirects. */
  8290. #endif
  8291. }
  8292. return;
  8293. }
  8294. static void
  8295. handle_file_based_request(struct mg_connection *conn,
  8296. const char *path,
  8297. struct file *file)
  8298. {
  8299. if (!conn || !conn->ctx) {
  8300. return;
  8301. }
  8302. if (0) {
  8303. #ifdef USE_LUA
  8304. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8305. strlen(
  8306. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8307. path) > 0) {
  8308. /* Lua server page: an SSI like page containing mostly plain html code
  8309. * plus some tags with server generated contents. */
  8310. handle_lsp_request(conn, path, file, NULL);
  8311. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8312. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8313. path) > 0) {
  8314. /* Lua in-server module script: a CGI like script used to generate the
  8315. * entire reply. */
  8316. mg_exec_lua_script(conn, path, NULL);
  8317. #endif
  8318. #if defined(USE_DUKTAPE)
  8319. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8320. strlen(
  8321. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8322. path) > 0) {
  8323. /* Call duktape to generate the page */
  8324. mg_exec_duktape_script(conn, path);
  8325. #endif
  8326. #if !defined(NO_CGI)
  8327. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8328. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8329. path) > 0) {
  8330. /* CGI scripts may support all HTTP methods */
  8331. handle_cgi_request(conn, path);
  8332. #endif /* !NO_CGI */
  8333. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8334. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8335. path) > 0) {
  8336. handle_ssi_file_request(conn, path, file);
  8337. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8338. /* Send 304 "Not Modified" - this must not send any body data */
  8339. send_http_error(conn, 304, "%s", "");
  8340. } else {
  8341. handle_static_file_request(conn, path, file);
  8342. }
  8343. }
  8344. static void
  8345. close_all_listening_sockets(struct mg_context *ctx)
  8346. {
  8347. unsigned int i;
  8348. if (!ctx) {
  8349. return;
  8350. }
  8351. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8352. closesocket(ctx->listening_sockets[i].sock);
  8353. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8354. }
  8355. mg_free(ctx->listening_sockets);
  8356. ctx->listening_sockets = NULL;
  8357. mg_free(ctx->listening_ports);
  8358. ctx->listening_ports = NULL;
  8359. }
  8360. /* Valid listening port specification is: [ip_address:]port[s]
  8361. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8362. * Examples for IPv6: [::]:80, [::1]:80,
  8363. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8364. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8365. static int
  8366. parse_port_string(const struct vec *vec, struct socket *so)
  8367. {
  8368. unsigned int a, b, c, d, port;
  8369. int ch, len;
  8370. #if defined(USE_IPV6)
  8371. char buf[100] = {0};
  8372. #endif
  8373. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8374. * Also, all-zeroes in the socket address means binding to all addresses
  8375. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8376. memset(so, 0, sizeof(*so));
  8377. so->lsa.sin.sin_family = AF_INET;
  8378. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8379. == 5) {
  8380. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8381. so->lsa.sin.sin_addr.s_addr =
  8382. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8383. so->lsa.sin.sin_port = htons((uint16_t)port);
  8384. #if defined(USE_IPV6)
  8385. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8386. && mg_inet_pton(
  8387. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8388. /* IPv6 address, examples: see above */
  8389. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */
  8390. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8391. #endif
  8392. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8393. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8394. so->lsa.sin.sin_port = htons((uint16_t)port);
  8395. } else {
  8396. /* Parsing failure. Make port invalid. */
  8397. port = 0;
  8398. len = 0;
  8399. }
  8400. /* sscanf and the option splitting code ensure the following condition */
  8401. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8402. return 0;
  8403. }
  8404. ch = vec->ptr[len]; /* Next character after the port number */
  8405. so->is_ssl = (ch == 's');
  8406. so->ssl_redir = (ch == 'r');
  8407. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8408. return is_valid_port(port)
  8409. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8410. }
  8411. static int
  8412. set_ports_option(struct mg_context *ctx)
  8413. {
  8414. const char *list;
  8415. int on = 1;
  8416. #if defined(USE_IPV6)
  8417. int off = 0;
  8418. #endif
  8419. struct vec vec;
  8420. struct socket so, *ptr;
  8421. in_port_t *portPtr;
  8422. union usa usa;
  8423. socklen_t len;
  8424. int portsTotal = 0;
  8425. int portsOk = 0;
  8426. if (!ctx) {
  8427. return 0;
  8428. }
  8429. memset(&so, 0, sizeof(so));
  8430. memset(&usa, 0, sizeof(usa));
  8431. len = sizeof(usa);
  8432. list = ctx->config[LISTENING_PORTS];
  8433. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8434. portsTotal++;
  8435. if (!parse_port_string(&vec, &so)) {
  8436. mg_cry(fc(ctx),
  8437. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8438. (int)vec.len,
  8439. vec.ptr,
  8440. portsTotal,
  8441. "[IP_ADDRESS:]PORT[s|r]");
  8442. continue;
  8443. }
  8444. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8445. mg_cry(fc(ctx),
  8446. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8447. "option set?",
  8448. portsTotal);
  8449. continue;
  8450. }
  8451. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8452. == INVALID_SOCKET) {
  8453. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8454. continue;
  8455. }
  8456. #ifdef _WIN32
  8457. /* Windows SO_REUSEADDR lets many procs binds to a
  8458. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8459. * if someone already has the socket -- DTL */
  8460. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8461. * Windows might need a few seconds before
  8462. * the same port can be used again in the
  8463. * same process, so a short Sleep may be
  8464. * required between mg_stop and mg_start.
  8465. */
  8466. if (setsockopt(so.sock,
  8467. SOL_SOCKET,
  8468. SO_EXCLUSIVEADDRUSE,
  8469. (SOCK_OPT_TYPE)&on,
  8470. sizeof(on)) != 0) {
  8471. mg_cry(fc(ctx),
  8472. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8473. portsTotal);
  8474. }
  8475. #else
  8476. if (setsockopt(so.sock,
  8477. SOL_SOCKET,
  8478. SO_REUSEADDR,
  8479. (SOCK_OPT_TYPE)&on,
  8480. sizeof(on)) != 0) {
  8481. mg_cry(fc(ctx),
  8482. "cannot set socket option SO_REUSEADDR (entry %i)",
  8483. portsTotal);
  8484. }
  8485. #endif
  8486. #if defined(USE_IPV6)
  8487. if (so.lsa.sa.sa_family == AF_INET6
  8488. && setsockopt(so.sock,
  8489. IPPROTO_IPV6,
  8490. IPV6_V6ONLY,
  8491. (void *)&off,
  8492. sizeof(off)) != 0) {
  8493. mg_cry(fc(ctx),
  8494. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8495. portsTotal);
  8496. }
  8497. #endif
  8498. if (so.lsa.sa.sa_family == AF_INET) {
  8499. len = sizeof(so.lsa.sin);
  8500. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8501. mg_cry(fc(ctx),
  8502. "cannot bind to %.*s: %d (%s)",
  8503. (int)vec.len,
  8504. vec.ptr,
  8505. (int)ERRNO,
  8506. strerror(errno));
  8507. closesocket(so.sock);
  8508. so.sock = INVALID_SOCKET;
  8509. continue;
  8510. }
  8511. }
  8512. #if defined(USE_IPV6)
  8513. else if (so.lsa.sa.sa_family == AF_INET6) {
  8514. len = sizeof(so.lsa.sin6);
  8515. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8516. mg_cry(fc(ctx),
  8517. "cannot bind to IPv6 %.*s: %d (%s)",
  8518. (int)vec.len,
  8519. vec.ptr,
  8520. (int)ERRNO,
  8521. strerror(errno));
  8522. closesocket(so.sock);
  8523. so.sock = INVALID_SOCKET;
  8524. continue;
  8525. }
  8526. }
  8527. #endif
  8528. else {
  8529. mg_cry(fc(ctx),
  8530. "cannot bind: address family not supported (entry %i)",
  8531. portsTotal);
  8532. continue;
  8533. }
  8534. if (listen(so.sock, SOMAXCONN) != 0) {
  8535. mg_cry(fc(ctx),
  8536. "cannot listen to %.*s: %d (%s)",
  8537. (int)vec.len,
  8538. vec.ptr,
  8539. (int)ERRNO,
  8540. strerror(errno));
  8541. closesocket(so.sock);
  8542. so.sock = INVALID_SOCKET;
  8543. continue;
  8544. }
  8545. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8546. int err = (int)ERRNO;
  8547. mg_cry(fc(ctx),
  8548. "call to getsockname failed %.*s: %d (%s)",
  8549. (int)vec.len,
  8550. vec.ptr,
  8551. err,
  8552. strerror(errno));
  8553. closesocket(so.sock);
  8554. so.sock = INVALID_SOCKET;
  8555. continue;
  8556. }
  8557. if ((ptr = (struct socket *)
  8558. mg_realloc(ctx->listening_sockets,
  8559. (ctx->num_listening_sockets + 1)
  8560. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  8561. mg_cry(fc(ctx), "%s", "Out of memory");
  8562. closesocket(so.sock);
  8563. so.sock = INVALID_SOCKET;
  8564. continue;
  8565. }
  8566. if ((portPtr =
  8567. (in_port_t *)mg_realloc(ctx->listening_ports,
  8568. (ctx->num_listening_sockets + 1)
  8569. * sizeof(ctx->listening_ports[0])))
  8570. == NULL) {
  8571. mg_cry(fc(ctx), "%s", "Out of memory");
  8572. closesocket(so.sock);
  8573. so.sock = INVALID_SOCKET;
  8574. mg_free(ptr);
  8575. continue;
  8576. }
  8577. set_close_on_exec(so.sock, fc(ctx));
  8578. ctx->listening_sockets = ptr;
  8579. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8580. ctx->listening_ports = portPtr;
  8581. ctx->listening_ports[ctx->num_listening_sockets] =
  8582. ntohs(usa.sin.sin_port);
  8583. ctx->num_listening_sockets++;
  8584. portsOk++;
  8585. }
  8586. if (portsOk != portsTotal) {
  8587. close_all_listening_sockets(ctx);
  8588. portsOk = 0;
  8589. }
  8590. return portsOk;
  8591. }
  8592. static const char *
  8593. header_val(const struct mg_connection *conn, const char *header)
  8594. {
  8595. const char *header_value;
  8596. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8597. return "-";
  8598. } else {
  8599. return header_value;
  8600. }
  8601. }
  8602. static void
  8603. log_access(const struct mg_connection *conn)
  8604. {
  8605. const struct mg_request_info *ri;
  8606. FILE *fp;
  8607. char date[64], src_addr[IP_ADDR_STR_LEN];
  8608. struct tm *tm;
  8609. const char *referer;
  8610. const char *user_agent;
  8611. char buf[4096];
  8612. if (!conn || !conn->ctx) {
  8613. return;
  8614. }
  8615. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  8616. ? NULL
  8617. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  8618. if (fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8619. return;
  8620. }
  8621. tm = localtime(&conn->conn_birth_time);
  8622. if (tm != NULL) {
  8623. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8624. } else {
  8625. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8626. date[sizeof(date) - 1] = '\0';
  8627. }
  8628. ri = &conn->request_info;
  8629. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8630. referer = header_val(conn, "Referer");
  8631. user_agent = header_val(conn, "User-Agent");
  8632. mg_snprintf(conn,
  8633. NULL, /* Ignore truncation in access log */
  8634. buf,
  8635. sizeof(buf),
  8636. "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT " %s %s",
  8637. src_addr,
  8638. ri->remote_user == NULL ? "-" : ri->remote_user,
  8639. date,
  8640. ri->request_method ? ri->request_method : "-",
  8641. ri->request_uri ? ri->request_uri : "-",
  8642. ri->http_version,
  8643. conn->status_code,
  8644. conn->num_bytes_sent,
  8645. referer,
  8646. user_agent);
  8647. if (conn->ctx->callbacks.log_access) {
  8648. conn->ctx->callbacks.log_access(conn, buf);
  8649. }
  8650. if (fp) {
  8651. flockfile(fp);
  8652. fprintf(fp, "%s", buf);
  8653. fputc('\n', fp);
  8654. fflush(fp);
  8655. funlockfile(fp);
  8656. fclose(fp);
  8657. }
  8658. }
  8659. /* Verify given socket address against the ACL.
  8660. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  8661. static int
  8662. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  8663. {
  8664. int allowed, flag;
  8665. uint32_t net, mask;
  8666. struct vec vec;
  8667. if (ctx) {
  8668. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  8669. /* If any ACL is set, deny by default */
  8670. allowed = list == NULL ? '+' : '-';
  8671. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8672. flag = vec.ptr[0];
  8673. if ((flag != '+' && flag != '-')
  8674. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  8675. mg_cry(fc(ctx),
  8676. "%s: subnet must be [+|-]x.x.x.x[/x]",
  8677. __func__);
  8678. return -1;
  8679. }
  8680. if (net == (remote_ip & mask)) {
  8681. allowed = flag;
  8682. }
  8683. }
  8684. return allowed == '+';
  8685. }
  8686. return -1;
  8687. }
  8688. #if !defined(_WIN32)
  8689. static int
  8690. set_uid_option(struct mg_context *ctx)
  8691. {
  8692. struct passwd *pw;
  8693. if (ctx) {
  8694. const char *uid = ctx->config[RUN_AS_USER];
  8695. int success = 0;
  8696. if (uid == NULL) {
  8697. success = 1;
  8698. } else {
  8699. if ((pw = getpwnam(uid)) == NULL) {
  8700. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  8701. } else if (setgid(pw->pw_gid) == -1) {
  8702. mg_cry(fc(ctx),
  8703. "%s: setgid(%s): %s",
  8704. __func__,
  8705. uid,
  8706. strerror(errno));
  8707. } else if (setgroups(0, NULL)) {
  8708. mg_cry(fc(ctx),
  8709. "%s: setgroups(): %s",
  8710. __func__,
  8711. strerror(errno));
  8712. } else if (setuid(pw->pw_uid) == -1) {
  8713. mg_cry(fc(ctx),
  8714. "%s: setuid(%s): %s",
  8715. __func__,
  8716. uid,
  8717. strerror(errno));
  8718. } else {
  8719. success = 1;
  8720. }
  8721. }
  8722. return success;
  8723. }
  8724. return 0;
  8725. }
  8726. #endif /* !_WIN32 */
  8727. static void
  8728. tls_dtor(void *key)
  8729. {
  8730. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  8731. /* key == pthread_getspecific(sTlsKey); */
  8732. if (tls) {
  8733. if (tls->is_master == 2) {
  8734. tls->is_master = -3; /* Mark memory as dead */
  8735. mg_free(tls);
  8736. }
  8737. }
  8738. pthread_setspecific(sTlsKey, NULL);
  8739. }
  8740. #if !defined(NO_SSL)
  8741. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  8742. static unsigned long
  8743. ssl_id_callback(void)
  8744. {
  8745. #ifdef _WIN32
  8746. return GetCurrentThreadId();
  8747. #else
  8748. #ifdef __clang__
  8749. #pragma clang diagnostic push
  8750. #pragma clang diagnostic ignored "-Wunreachable-code"
  8751. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  8752. * or not, so one of the two conditions will be unreachable by construction.
  8753. * Unfortunately the C standard does not define a way to check this at
  8754. * compile time, since the #if preprocessor conditions can not use the sizeof
  8755. * operator as an argument. */
  8756. #endif
  8757. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  8758. /* This is the problematic case for CRYPTO_set_id_callback:
  8759. * The OS pthread_t can not be cast to unsigned long. */
  8760. struct mg_workerTLS *tls =
  8761. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  8762. if (tls == NULL) {
  8763. /* SSL called from an unknown thread: Create some thread index. */
  8764. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  8765. tls->is_master = -2; /* -2 means "3rd party thread" */
  8766. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  8767. pthread_setspecific(sTlsKey, tls);
  8768. }
  8769. return tls->thread_idx;
  8770. } else {
  8771. return (unsigned long)pthread_self();
  8772. }
  8773. #ifdef __clang__
  8774. #pragma clang diagnostic pop
  8775. #endif
  8776. #endif
  8777. }
  8778. static pthread_mutex_t *ssl_mutexes;
  8779. static int
  8780. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  8781. {
  8782. int ret, err;
  8783. if (!conn) {
  8784. return 0;
  8785. }
  8786. conn->ssl = SSL_new(s);
  8787. if (conn->ssl == NULL) {
  8788. return 0;
  8789. }
  8790. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  8791. if (ret != 1) {
  8792. err = SSL_get_error(conn->ssl, ret);
  8793. (void)err; /* TODO: set some error message */
  8794. SSL_free(conn->ssl);
  8795. conn->ssl = NULL;
  8796. return 0;
  8797. }
  8798. ret = func(conn->ssl);
  8799. if (ret != 1) {
  8800. err = SSL_get_error(conn->ssl, ret);
  8801. (void)err; /* TODO: set some error message */
  8802. SSL_free(conn->ssl);
  8803. conn->ssl = NULL;
  8804. return 0;
  8805. }
  8806. return 1;
  8807. }
  8808. /* Return OpenSSL error message (from CRYPTO lib) */
  8809. static const char *
  8810. ssl_error(void)
  8811. {
  8812. unsigned long err;
  8813. err = ERR_get_error();
  8814. return err == 0 ? "" : ERR_error_string(err, NULL);
  8815. }
  8816. static void
  8817. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  8818. {
  8819. (void)line;
  8820. (void)file;
  8821. if (mode & 1) {
  8822. /* 1 is CRYPTO_LOCK */
  8823. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  8824. } else {
  8825. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  8826. }
  8827. }
  8828. #if !defined(NO_SSL_DL)
  8829. static void *
  8830. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  8831. {
  8832. union {
  8833. void *p;
  8834. void (*fp)(void);
  8835. } u;
  8836. void *dll_handle;
  8837. struct ssl_func *fp;
  8838. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  8839. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  8840. return NULL;
  8841. }
  8842. for (fp = sw; fp->name != NULL; fp++) {
  8843. #ifdef _WIN32
  8844. /* GetProcAddress() returns pointer to function */
  8845. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  8846. #else
  8847. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  8848. * pointers to function pointers. We need to use a union to make a
  8849. * cast. */
  8850. u.p = dlsym(dll_handle, fp->name);
  8851. #endif /* _WIN32 */
  8852. if (u.fp == NULL) {
  8853. mg_cry(fc(ctx),
  8854. "%s: %s: cannot find %s",
  8855. __func__,
  8856. dll_name,
  8857. fp->name);
  8858. dlclose(dll_handle);
  8859. return NULL;
  8860. } else {
  8861. fp->ptr = u.fp;
  8862. }
  8863. }
  8864. return dll_handle;
  8865. }
  8866. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  8867. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  8868. #endif /* NO_SSL_DL */
  8869. #if defined(SSL_ALREADY_INITIALIZED)
  8870. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  8871. #else
  8872. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  8873. #endif
  8874. static int
  8875. initialize_ssl(struct mg_context *ctx)
  8876. {
  8877. int i;
  8878. size_t size;
  8879. #if !defined(NO_SSL_DL)
  8880. if (!cryptolib_dll_handle) {
  8881. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  8882. if (!cryptolib_dll_handle) {
  8883. return 0;
  8884. }
  8885. }
  8886. #endif /* NO_SSL_DL */
  8887. if (mg_atomic_inc(&cryptolib_users) > 1) {
  8888. return 1;
  8889. }
  8890. /* Initialize locking callbacks, needed for thread safety.
  8891. * http://www.openssl.org/support/faq.html#PROG1
  8892. */
  8893. i = CRYPTO_num_locks();
  8894. if (i < 0) {
  8895. i = 0;
  8896. }
  8897. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  8898. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  8899. mg_cry(fc(ctx),
  8900. "%s: cannot allocate mutexes: %s",
  8901. __func__,
  8902. ssl_error());
  8903. return 0;
  8904. }
  8905. for (i = 0; i < CRYPTO_num_locks(); i++) {
  8906. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  8907. }
  8908. CRYPTO_set_locking_callback(&ssl_locking_callback);
  8909. CRYPTO_set_id_callback(&ssl_id_callback);
  8910. return 1;
  8911. }
  8912. #if 0 /* TODO: check if this function is required at all */
  8913. static int
  8914. verify_ssl_client(int preverify_ok, X509_STORE_CTX *x509_ctx)
  8915. {
  8916. int ret = preverify_ok;
  8917. /*
  8918. TODO: store rejected connection attempts
  8919. char buf[256];
  8920. struct X509 *err_cert;
  8921. int err, depth;
  8922. SSL *ssl;
  8923. */
  8924. /* Ignore pre-verification - only accept clients we know locally */
  8925. (void)preverify_ok;
  8926. /*
  8927. err_cert = X509_STORE_CTX_get_current_cert(x509_st);
  8928. err = X509_STORE_CTX_get_error(x509_st);
  8929. depth = X509_STORE_CTX_get_error_depth(x509_st);
  8930. */
  8931. return ret;
  8932. }
  8933. #endif
  8934. static int
  8935. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  8936. {
  8937. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  8938. mg_cry(fc(ctx),
  8939. "%s: cannot open certificate file %s: %s",
  8940. __func__,
  8941. pem,
  8942. ssl_error());
  8943. return 0;
  8944. }
  8945. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  8946. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  8947. mg_cry(fc(ctx),
  8948. "%s: cannot open private key file %s: %s",
  8949. __func__,
  8950. pem,
  8951. ssl_error());
  8952. return 0;
  8953. }
  8954. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  8955. mg_cry(fc(ctx),
  8956. "%s: certificate and private key do not match: %s",
  8957. __func__,
  8958. pem);
  8959. return 0;
  8960. }
  8961. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  8962. mg_cry(fc(ctx),
  8963. "%s: cannot use certificate chain file %s: %s",
  8964. __func__,
  8965. pem,
  8966. ssl_error());
  8967. return 0;
  8968. }
  8969. return 1;
  8970. }
  8971. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  8972. static int
  8973. set_ssl_option(struct mg_context *ctx)
  8974. {
  8975. const char *pem;
  8976. int callback_ret;
  8977. int should_verify_peer;
  8978. const char *ca_path;
  8979. const char *ca_file;
  8980. int use_default_verify_paths;
  8981. int verify_depth;
  8982. /* If PEM file is not specified and the init_ssl callback
  8983. * is not specified, skip SSL initialization. */
  8984. if (!ctx) {
  8985. return 0;
  8986. }
  8987. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  8988. && ctx->callbacks.init_ssl == NULL) {
  8989. return 1;
  8990. }
  8991. if (!initialize_ssl(ctx)) {
  8992. return 0;
  8993. }
  8994. #if !defined(NO_SSL_DL)
  8995. if (!ssllib_dll_handle) {
  8996. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  8997. if (!ssllib_dll_handle) {
  8998. return 0;
  8999. }
  9000. }
  9001. #endif /* NO_SSL_DL */
  9002. /* Initialize SSL library */
  9003. SSL_library_init();
  9004. SSL_load_error_strings();
  9005. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9006. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9007. return 0;
  9008. }
  9009. /* If a callback has been specified, call it. */
  9010. callback_ret =
  9011. (ctx->callbacks.init_ssl == NULL)
  9012. ? 0
  9013. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9014. /* If callback returns 0, civetweb sets up the SSL certificate.
  9015. * If it returns 1, civetweb assumes the calback already did this.
  9016. * If it returns -1, initializing ssl fails. */
  9017. if (callback_ret < 0) {
  9018. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9019. return 0;
  9020. }
  9021. if (callback_ret > 0) {
  9022. if (pem != NULL) {
  9023. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9024. }
  9025. return 1;
  9026. }
  9027. if (pem != NULL) {
  9028. if (!ssl_use_pem_file(ctx, pem)) {
  9029. return 0;
  9030. }
  9031. }
  9032. should_verify_peer =
  9033. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9034. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9035. use_default_verify_paths =
  9036. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9037. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9038. if (should_verify_peer) {
  9039. ca_path = ctx->config[SSL_CA_PATH];
  9040. ca_file = ctx->config[SSL_CA_FILE];
  9041. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9042. != 1) {
  9043. mg_cry(
  9044. fc(ctx),
  9045. "SSL_CTX_load_verify_locations error: %s "
  9046. "ssl_verify_peer requires setting "
  9047. "either ssl_ca_path or ssl_ca_file. Is any of them present in "
  9048. "the .conf file?",
  9049. ssl_error());
  9050. return 0;
  9051. }
  9052. SSL_CTX_set_verify(ctx->ssl_ctx,
  9053. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9054. NULL);
  9055. if (use_default_verify_paths
  9056. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9057. mg_cry(fc(ctx),
  9058. "SSL_CTX_set_default_verify_paths error: %s",
  9059. ssl_error());
  9060. return 0;
  9061. }
  9062. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9063. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9064. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9065. }
  9066. }
  9067. /* TODO: could set use SSL_CTX_set_cipher_list if set */
  9068. return 1;
  9069. }
  9070. static void
  9071. uninitialize_ssl(struct mg_context *ctx)
  9072. {
  9073. int i;
  9074. (void)ctx;
  9075. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9076. CRYPTO_set_locking_callback(NULL);
  9077. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9078. pthread_mutex_destroy(&ssl_mutexes[i]);
  9079. }
  9080. CRYPTO_set_locking_callback(NULL);
  9081. CRYPTO_set_id_callback(NULL);
  9082. }
  9083. }
  9084. #endif /* !NO_SSL */
  9085. static int
  9086. set_gpass_option(struct mg_context *ctx)
  9087. {
  9088. if (ctx) {
  9089. struct file file = STRUCT_FILE_INITIALIZER;
  9090. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9091. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9092. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9093. return 0;
  9094. }
  9095. return 1;
  9096. }
  9097. return 0;
  9098. }
  9099. static int
  9100. set_acl_option(struct mg_context *ctx)
  9101. {
  9102. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9103. }
  9104. static void
  9105. reset_per_request_attributes(struct mg_connection *conn)
  9106. {
  9107. if (!conn) {
  9108. return;
  9109. }
  9110. conn->path_info = NULL;
  9111. conn->num_bytes_sent = conn->consumed_content = 0;
  9112. conn->status_code = -1;
  9113. conn->is_chunked = 0;
  9114. conn->must_close = conn->request_len = conn->throttle = 0;
  9115. conn->request_info.content_length = -1;
  9116. conn->request_info.remote_user = NULL;
  9117. conn->request_info.request_method = NULL;
  9118. conn->request_info.request_uri = NULL;
  9119. conn->request_info.local_uri = NULL;
  9120. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9121. * local_uri and request_uri */
  9122. conn->request_info.http_version = NULL;
  9123. conn->request_info.num_headers = 0;
  9124. conn->data_len = 0;
  9125. conn->chunk_remainder = 0;
  9126. conn->internal_error = 0;
  9127. }
  9128. static int
  9129. set_sock_timeout(SOCKET sock, int milliseconds)
  9130. {
  9131. int r1, r2;
  9132. struct timeval tv;
  9133. #ifdef _WIN32
  9134. DWORD t = (DWORD)milliseconds;
  9135. #else
  9136. #if defined(TCP_USER_TIMEOUT)
  9137. unsigned int uto = (unsigned int)milliseconds;
  9138. #endif
  9139. memset(&tv, 0, sizeof(tv));
  9140. tv.tv_sec = milliseconds / 1000;
  9141. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9142. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9143. * max. time waiting for the acknowledged of TCP data before the connection
  9144. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9145. * If this option is not set, the default timeout of 20-30 minutes is used.
  9146. */
  9147. /* #define TCP_USER_TIMEOUT (18) */
  9148. #if defined(TCP_USER_TIMEOUT)
  9149. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9150. #endif
  9151. #endif
  9152. r1 = setsockopt(
  9153. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9154. r2 = setsockopt(
  9155. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9156. return r1 || r2;
  9157. }
  9158. static void
  9159. close_socket_gracefully(struct mg_connection *conn)
  9160. {
  9161. #if defined(_WIN32)
  9162. char buf[MG_BUF_LEN];
  9163. int n;
  9164. #endif
  9165. struct linger linger;
  9166. if (!conn) {
  9167. return;
  9168. }
  9169. /* Set linger option to avoid socket hanging out after close. This prevent
  9170. * ephemeral port exhaust problem under high QPS. */
  9171. linger.l_onoff = 1;
  9172. linger.l_linger = 1;
  9173. if (setsockopt(conn->client.sock,
  9174. SOL_SOCKET,
  9175. SO_LINGER,
  9176. (char *)&linger,
  9177. sizeof(linger)) != 0) {
  9178. mg_cry(conn,
  9179. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9180. __func__,
  9181. strerror(ERRNO));
  9182. }
  9183. /* Send FIN to the client */
  9184. shutdown(conn->client.sock, SHUT_WR);
  9185. set_non_blocking_mode(conn->client.sock);
  9186. #if defined(_WIN32)
  9187. /* Read and discard pending incoming data. If we do not do that and close
  9188. * the socket, the data in the send buffer may be discarded. This
  9189. * behaviour is seen on Windows, when client keeps sending data
  9190. * when server decides to close the connection; then when client
  9191. * does recv() it gets no data back. */
  9192. do {
  9193. n = pull(
  9194. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9195. } while (n > 0);
  9196. #endif
  9197. /* Now we know that our FIN is ACK-ed, safe to close */
  9198. closesocket(conn->client.sock);
  9199. conn->client.sock = INVALID_SOCKET;
  9200. }
  9201. static void
  9202. close_connection(struct mg_connection *conn)
  9203. {
  9204. if (!conn || !conn->ctx) {
  9205. return;
  9206. }
  9207. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9208. if (conn->lua_websocket_state) {
  9209. lua_websocket_close(conn, conn->lua_websocket_state);
  9210. conn->lua_websocket_state = NULL;
  9211. }
  9212. #endif
  9213. /* call the connection_close callback if assigned */
  9214. if ((conn->ctx->callbacks.connection_close != NULL)
  9215. && (conn->ctx->context_type == 1)) {
  9216. conn->ctx->callbacks.connection_close(conn);
  9217. }
  9218. mg_lock_connection(conn);
  9219. conn->must_close = 1;
  9220. #ifndef NO_SSL
  9221. if (conn->ssl != NULL) {
  9222. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  9223. SSL_shutdown(conn->ssl);
  9224. SSL_free(conn->ssl);
  9225. conn->ssl = NULL;
  9226. }
  9227. #endif
  9228. if (conn->client.sock != INVALID_SOCKET) {
  9229. close_socket_gracefully(conn);
  9230. conn->client.sock = INVALID_SOCKET;
  9231. }
  9232. mg_unlock_connection(conn);
  9233. }
  9234. void
  9235. mg_close_connection(struct mg_connection *conn)
  9236. {
  9237. struct mg_context *client_ctx = NULL;
  9238. unsigned int i;
  9239. if (conn == NULL) {
  9240. return;
  9241. }
  9242. if (conn->ctx->context_type == 2) {
  9243. client_ctx = conn->ctx;
  9244. /* client context: loops must end */
  9245. conn->ctx->stop_flag = 1;
  9246. }
  9247. #ifndef NO_SSL
  9248. if (conn->client_ssl_ctx != NULL) {
  9249. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9250. }
  9251. #endif
  9252. close_connection(conn);
  9253. if (client_ctx != NULL) {
  9254. /* join worker thread and free context */
  9255. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9256. if (client_ctx->workerthreadids[i] != 0) {
  9257. mg_join_thread(client_ctx->workerthreadids[i]);
  9258. }
  9259. }
  9260. mg_free(client_ctx->workerthreadids);
  9261. mg_free(client_ctx);
  9262. }
  9263. (void)pthread_mutex_destroy(&conn->mutex);
  9264. mg_free(conn);
  9265. }
  9266. static struct mg_connection *
  9267. mg_connect_client_impl(const struct mg_client_options *client_options,
  9268. int use_ssl,
  9269. char *ebuf,
  9270. size_t ebuf_len)
  9271. {
  9272. static struct mg_context fake_ctx;
  9273. struct mg_connection *conn = NULL;
  9274. SOCKET sock;
  9275. union usa sa;
  9276. if (!connect_socket(&fake_ctx,
  9277. client_options->host,
  9278. client_options->port,
  9279. use_ssl,
  9280. ebuf,
  9281. ebuf_len,
  9282. &sock,
  9283. &sa)) {
  9284. ;
  9285. } else if ((conn = (struct mg_connection *)
  9286. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9287. mg_snprintf(NULL,
  9288. NULL, /* No truncation check for ebuf */
  9289. ebuf,
  9290. ebuf_len,
  9291. "calloc(): %s",
  9292. strerror(ERRNO));
  9293. closesocket(sock);
  9294. #ifndef NO_SSL
  9295. } else if (use_ssl
  9296. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9297. == NULL) {
  9298. mg_snprintf(NULL,
  9299. NULL, /* No truncation check for ebuf */
  9300. ebuf,
  9301. ebuf_len,
  9302. "SSL_CTX_new error");
  9303. closesocket(sock);
  9304. mg_free(conn);
  9305. conn = NULL;
  9306. #endif /* NO_SSL */
  9307. } else {
  9308. #ifdef USE_IPV6
  9309. socklen_t len = (sa.sa.sa_family == AF_INET)
  9310. ? sizeof(conn->client.rsa.sin)
  9311. : sizeof(conn->client.rsa.sin6);
  9312. struct sockaddr *psa =
  9313. (sa.sa.sa_family == AF_INET)
  9314. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9315. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9316. #else
  9317. socklen_t len = sizeof(conn->client.rsa.sin);
  9318. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9319. #endif
  9320. conn->buf_size = MAX_REQUEST_SIZE;
  9321. conn->buf = (char *)(conn + 1);
  9322. conn->ctx = &fake_ctx;
  9323. conn->client.sock = sock;
  9324. conn->client.lsa = sa;
  9325. if (getsockname(sock, psa, &len) != 0) {
  9326. mg_cry(conn,
  9327. "%s: getsockname() failed: %s",
  9328. __func__,
  9329. strerror(ERRNO));
  9330. }
  9331. conn->client.is_ssl = use_ssl ? 1 : 0;
  9332. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9333. #ifndef NO_SSL
  9334. if (use_ssl) {
  9335. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9336. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9337. SSL_CTX_set_verify call is needed to switch off server
  9338. * certificate checking, which is off by default in OpenSSL and on
  9339. * in yaSSL. */
  9340. // TODO: SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER,
  9341. // verify_ssl_server);
  9342. if (client_options->client_cert) {
  9343. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9344. mg_snprintf(NULL,
  9345. NULL, /* No truncation check for ebuf */
  9346. ebuf,
  9347. ebuf_len,
  9348. "Can not use SSL client certificate");
  9349. SSL_CTX_free(conn->client_ssl_ctx);
  9350. closesocket(sock);
  9351. mg_free(conn);
  9352. conn = NULL;
  9353. }
  9354. }
  9355. if (client_options->server_cert) {
  9356. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9357. client_options->server_cert,
  9358. NULL);
  9359. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9360. } else {
  9361. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9362. }
  9363. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9364. mg_snprintf(NULL,
  9365. NULL, /* No truncation check for ebuf */
  9366. ebuf,
  9367. ebuf_len,
  9368. "SSL connection error");
  9369. SSL_CTX_free(conn->client_ssl_ctx);
  9370. closesocket(sock);
  9371. mg_free(conn);
  9372. conn = NULL;
  9373. }
  9374. }
  9375. #endif
  9376. }
  9377. return conn;
  9378. }
  9379. CIVETWEB_API struct mg_connection *
  9380. mg_connect_client_secure(const struct mg_client_options *client_options,
  9381. char *error_buffer,
  9382. size_t error_buffer_size)
  9383. {
  9384. return mg_connect_client_impl(client_options,
  9385. 1,
  9386. error_buffer,
  9387. error_buffer_size);
  9388. }
  9389. struct mg_connection *
  9390. mg_connect_client(const char *host,
  9391. int port,
  9392. int use_ssl,
  9393. char *error_buffer,
  9394. size_t error_buffer_size)
  9395. {
  9396. struct mg_client_options opts;
  9397. memset(&opts, 0, sizeof(opts));
  9398. opts.host = host;
  9399. opts.port = port;
  9400. return mg_connect_client_impl(&opts,
  9401. use_ssl,
  9402. error_buffer,
  9403. error_buffer_size);
  9404. }
  9405. static const struct {
  9406. const char *proto;
  9407. size_t proto_len;
  9408. unsigned default_port;
  9409. } abs_uri_protocols[] = {{"http://", 7, 80},
  9410. {"https://", 8, 443},
  9411. {"ws://", 5, 80},
  9412. {"wss://", 6, 443},
  9413. {NULL, 0, 0}};
  9414. /* Check if the uri is valid.
  9415. * return 0 for invalid uri,
  9416. * return 1 for *,
  9417. * return 2 for relative uri,
  9418. * return 3 for absolute uri without port,
  9419. * return 4 for absolute uri with port */
  9420. static int
  9421. get_uri_type(const char *uri)
  9422. {
  9423. int i;
  9424. char *hostend, *portbegin, *portend;
  9425. unsigned long port;
  9426. /* According to the HTTP standard
  9427. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  9428. * URI can be an asterisk (*) or should start with slash (relative uri),
  9429. * or it should start with the protocol (absolute uri). */
  9430. if (uri[0] == '*' && uri[1] == '\0') {
  9431. /* asterisk */
  9432. return 1;
  9433. }
  9434. if (uri[0] == '/') {
  9435. /* relative uri */
  9436. return 2;
  9437. }
  9438. /* It could be an absolute uri: */
  9439. /* This function only checks if the uri is valid, not if it is
  9440. * addressing the current server. So civetweb can also be used
  9441. * as a proxy server. */
  9442. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9443. if (mg_strncasecmp(uri,
  9444. abs_uri_protocols[i].proto,
  9445. abs_uri_protocols[i].proto_len) == 0) {
  9446. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9447. if (!hostend) {
  9448. return 0;
  9449. }
  9450. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9451. if (!portbegin) {
  9452. return 3;
  9453. }
  9454. port = strtoul(portbegin + 1, &portend, 10);
  9455. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9456. return 0;
  9457. }
  9458. return 4;
  9459. }
  9460. }
  9461. return 0;
  9462. }
  9463. /* Return NULL or the relative uri at the current server */
  9464. static const char *
  9465. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  9466. {
  9467. const char *domain;
  9468. size_t domain_len;
  9469. unsigned long port = 0;
  9470. int i;
  9471. char *hostend = NULL;
  9472. char *portbegin, *portend;
  9473. /* DNS is case insensitive, so use case insensitive string compare here */
  9474. domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  9475. if (!domain) {
  9476. return 0;
  9477. }
  9478. domain_len = strlen(domain);
  9479. if (!domain_len) {
  9480. return 0;
  9481. }
  9482. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9483. if (mg_strncasecmp(uri,
  9484. abs_uri_protocols[i].proto,
  9485. abs_uri_protocols[i].proto_len) == 0) {
  9486. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9487. if (!hostend) {
  9488. return 0;
  9489. }
  9490. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9491. if (!portbegin) {
  9492. port = abs_uri_protocols[i].default_port;
  9493. } else {
  9494. port = strtoul(portbegin + 1, &portend, 10);
  9495. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9496. return 0;
  9497. }
  9498. }
  9499. /* protocol found, port set */
  9500. break;
  9501. }
  9502. }
  9503. if (!port) {
  9504. /* port remains 0 if the protocol is not found */
  9505. return 0;
  9506. }
  9507. #if defined(USE_IPV6)
  9508. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9509. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  9510. return 0;
  9511. }
  9512. } else
  9513. #endif
  9514. {
  9515. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  9516. return 0;
  9517. }
  9518. }
  9519. return hostend;
  9520. }
  9521. static int
  9522. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  9523. {
  9524. const char *cl;
  9525. if (ebuf_len > 0) {
  9526. ebuf[0] = '\0';
  9527. }
  9528. *err = 0;
  9529. reset_per_request_attributes(conn);
  9530. if (!conn) {
  9531. mg_snprintf(conn,
  9532. NULL, /* No truncation check for ebuf */
  9533. ebuf,
  9534. ebuf_len,
  9535. "%s",
  9536. "Internal error");
  9537. *err = 500;
  9538. return 0;
  9539. }
  9540. /* Set the time the request was received. This value should be used for
  9541. * timeouts. */
  9542. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  9543. conn->request_len =
  9544. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  9545. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  9546. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  9547. mg_snprintf(conn,
  9548. NULL, /* No truncation check for ebuf */
  9549. ebuf,
  9550. ebuf_len,
  9551. "%s",
  9552. "Invalid request size");
  9553. *err = 500;
  9554. return 0;
  9555. }
  9556. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  9557. mg_snprintf(conn,
  9558. NULL, /* No truncation check for ebuf */
  9559. ebuf,
  9560. ebuf_len,
  9561. "%s",
  9562. "Request Too Large");
  9563. *err = 413;
  9564. return 0;
  9565. } else if (conn->request_len <= 0) {
  9566. if (conn->data_len > 0) {
  9567. mg_snprintf(conn,
  9568. NULL, /* No truncation check for ebuf */
  9569. ebuf,
  9570. ebuf_len,
  9571. "%s",
  9572. "Client sent malformed request");
  9573. *err = 400;
  9574. } else {
  9575. /* Server did not send anything -> just close the connection */
  9576. conn->must_close = 1;
  9577. mg_snprintf(conn,
  9578. NULL, /* No truncation check for ebuf */
  9579. ebuf,
  9580. ebuf_len,
  9581. "%s",
  9582. "Client did not send a request");
  9583. *err = 0;
  9584. }
  9585. return 0;
  9586. } else if (parse_http_message(conn->buf,
  9587. conn->buf_size,
  9588. &conn->request_info) <= 0) {
  9589. mg_snprintf(conn,
  9590. NULL, /* No truncation check for ebuf */
  9591. ebuf,
  9592. ebuf_len,
  9593. "%s",
  9594. "Bad Request");
  9595. *err = 400;
  9596. return 0;
  9597. } else {
  9598. /* Message is a valid request or response */
  9599. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  9600. /* Request/response has content length set */
  9601. char *endptr = NULL;
  9602. conn->content_len = strtoll(cl, &endptr, 10);
  9603. if (endptr == cl) {
  9604. mg_snprintf(conn,
  9605. NULL, /* No truncation check for ebuf */
  9606. ebuf,
  9607. ebuf_len,
  9608. "%s",
  9609. "Bad Request");
  9610. *err = 411;
  9611. return 0;
  9612. }
  9613. /* Publish the content length back to the request info. */
  9614. conn->request_info.content_length = conn->content_len;
  9615. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  9616. != NULL
  9617. && strcmp(cl, "chunked") == 0) {
  9618. conn->is_chunked = 1;
  9619. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  9620. || !mg_strcasecmp(conn->request_info.request_method,
  9621. "PUT")) {
  9622. /* POST or PUT request without content length set */
  9623. conn->content_len = -1;
  9624. } else if (!mg_strncasecmp(conn->request_info.request_method,
  9625. "HTTP/",
  9626. 5)) {
  9627. /* Response without content length set */
  9628. conn->content_len = -1;
  9629. } else {
  9630. /* Other request */
  9631. conn->content_len = 0;
  9632. }
  9633. }
  9634. return 1;
  9635. }
  9636. int
  9637. mg_get_response(struct mg_connection *conn,
  9638. char *ebuf,
  9639. size_t ebuf_len,
  9640. int timeout)
  9641. {
  9642. if (conn) {
  9643. /* Implementation of API function for HTTP clients */
  9644. int err, ret;
  9645. struct mg_context *octx = conn->ctx;
  9646. struct mg_context rctx = *(conn->ctx);
  9647. char txt[32]; /* will not overflow */
  9648. if (timeout >= 0) {
  9649. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  9650. rctx.config[REQUEST_TIMEOUT] = txt;
  9651. set_sock_timeout(conn->client.sock, timeout);
  9652. } else {
  9653. rctx.config[REQUEST_TIMEOUT] = NULL;
  9654. }
  9655. conn->ctx = &rctx;
  9656. ret = getreq(conn, ebuf, ebuf_len, &err);
  9657. conn->ctx = octx;
  9658. /* TODO: 1) uri is deprecated;
  9659. * 2) here, ri.uri is the http response code */
  9660. conn->request_info.uri = conn->request_info.request_uri;
  9661. /* TODO (mid): Define proper return values - maybe return length?
  9662. * For the first test use <0 for error and >0 for OK */
  9663. return (ret == 0) ? -1 : +1;
  9664. }
  9665. return -1;
  9666. }
  9667. struct mg_connection *
  9668. mg_download(const char *host,
  9669. int port,
  9670. int use_ssl,
  9671. char *ebuf,
  9672. size_t ebuf_len,
  9673. const char *fmt,
  9674. ...)
  9675. {
  9676. struct mg_connection *conn;
  9677. va_list ap;
  9678. int i;
  9679. int reqerr;
  9680. va_start(ap, fmt);
  9681. ebuf[0] = '\0';
  9682. /* open a connection */
  9683. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  9684. if (conn != NULL) {
  9685. i = mg_vprintf(conn, fmt, ap);
  9686. if (i <= 0) {
  9687. mg_snprintf(conn,
  9688. NULL, /* No truncation check for ebuf */
  9689. ebuf,
  9690. ebuf_len,
  9691. "%s",
  9692. "Error sending request");
  9693. } else {
  9694. getreq(conn, ebuf, ebuf_len, &reqerr);
  9695. /* TODO: 1) uri is deprecated;
  9696. * 2) here, ri.uri is the http response code */
  9697. conn->request_info.uri = conn->request_info.request_uri;
  9698. }
  9699. }
  9700. /* if an error occured, close the connection */
  9701. if (ebuf[0] != '\0' && conn != NULL) {
  9702. mg_close_connection(conn);
  9703. conn = NULL;
  9704. }
  9705. va_end(ap);
  9706. return conn;
  9707. }
  9708. struct websocket_client_thread_data {
  9709. struct mg_connection *conn;
  9710. mg_websocket_data_handler data_handler;
  9711. mg_websocket_close_handler close_handler;
  9712. void *callback_data;
  9713. };
  9714. #if defined(USE_WEBSOCKET)
  9715. #ifdef _WIN32
  9716. static unsigned __stdcall websocket_client_thread(void *data)
  9717. #else
  9718. static void *
  9719. websocket_client_thread(void *data)
  9720. #endif
  9721. {
  9722. struct websocket_client_thread_data *cdata =
  9723. (struct websocket_client_thread_data *)data;
  9724. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  9725. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  9726. if (cdata->close_handler != NULL) {
  9727. cdata->close_handler(cdata->conn, cdata->callback_data);
  9728. }
  9729. mg_free((void *)cdata);
  9730. #ifdef _WIN32
  9731. return 0;
  9732. #else
  9733. return NULL;
  9734. #endif
  9735. }
  9736. #endif
  9737. struct mg_connection *
  9738. mg_connect_websocket_client(const char *host,
  9739. int port,
  9740. int use_ssl,
  9741. char *error_buffer,
  9742. size_t error_buffer_size,
  9743. const char *path,
  9744. const char *origin,
  9745. mg_websocket_data_handler data_func,
  9746. mg_websocket_close_handler close_func,
  9747. void *user_data)
  9748. {
  9749. struct mg_connection *conn = NULL;
  9750. #if defined(USE_WEBSOCKET)
  9751. struct mg_context *newctx = NULL;
  9752. struct websocket_client_thread_data *thread_data;
  9753. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  9754. static const char *handshake_req;
  9755. if (origin != NULL) {
  9756. handshake_req = "GET %s HTTP/1.1\r\n"
  9757. "Host: %s\r\n"
  9758. "Upgrade: websocket\r\n"
  9759. "Connection: Upgrade\r\n"
  9760. "Sec-WebSocket-Key: %s\r\n"
  9761. "Sec-WebSocket-Version: 13\r\n"
  9762. "Origin: %s\r\n"
  9763. "\r\n";
  9764. } else {
  9765. handshake_req = "GET %s HTTP/1.1\r\n"
  9766. "Host: %s\r\n"
  9767. "Upgrade: websocket\r\n"
  9768. "Connection: Upgrade\r\n"
  9769. "Sec-WebSocket-Key: %s\r\n"
  9770. "Sec-WebSocket-Version: 13\r\n"
  9771. "\r\n";
  9772. }
  9773. /* Establish the client connection and request upgrade */
  9774. conn = mg_download(host,
  9775. port,
  9776. use_ssl,
  9777. error_buffer,
  9778. error_buffer_size,
  9779. handshake_req,
  9780. path,
  9781. host,
  9782. magic,
  9783. origin);
  9784. /* Connection object will be null if something goes wrong */
  9785. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  9786. if (!*error_buffer) {
  9787. /* if there is a connection, but it did not return 101,
  9788. * error_buffer is not yet set */
  9789. mg_snprintf(conn,
  9790. NULL, /* No truncation check for ebuf */
  9791. error_buffer,
  9792. error_buffer_size,
  9793. "Unexpected server reply");
  9794. }
  9795. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  9796. if (conn != NULL) {
  9797. mg_free(conn);
  9798. conn = NULL;
  9799. }
  9800. return conn;
  9801. }
  9802. /* For client connections, mg_context is fake. Since we need to set a
  9803. * callback function, we need to create a copy and modify it. */
  9804. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  9805. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  9806. newctx->user_data = user_data;
  9807. newctx->context_type = 2; /* client context type */
  9808. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  9809. newctx->workerthreadids =
  9810. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  9811. conn->ctx = newctx;
  9812. thread_data = (struct websocket_client_thread_data *)
  9813. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  9814. thread_data->conn = conn;
  9815. thread_data->data_handler = data_func;
  9816. thread_data->close_handler = close_func;
  9817. thread_data->callback_data = NULL;
  9818. /* Start a thread to read the websocket client connection
  9819. * This thread will automatically stop when mg_disconnect is
  9820. * called on the client connection */
  9821. if (mg_start_thread_with_id(websocket_client_thread,
  9822. (void *)thread_data,
  9823. newctx->workerthreadids) != 0) {
  9824. mg_free((void *)thread_data);
  9825. mg_free((void *)newctx->workerthreadids);
  9826. mg_free((void *)newctx);
  9827. mg_free((void *)conn);
  9828. conn = NULL;
  9829. DEBUG_TRACE("%s",
  9830. "Websocket client connect thread could not be started\r\n");
  9831. }
  9832. #else
  9833. /* Appease "unused parameter" warnings */
  9834. (void)host;
  9835. (void)port;
  9836. (void)use_ssl;
  9837. (void)error_buffer;
  9838. (void)error_buffer_size;
  9839. (void)path;
  9840. (void)origin;
  9841. (void)user_data;
  9842. (void)data_func;
  9843. (void)close_func;
  9844. #endif
  9845. return conn;
  9846. }
  9847. static void
  9848. process_new_connection(struct mg_connection *conn)
  9849. {
  9850. if (conn && conn->ctx) {
  9851. struct mg_request_info *ri = &conn->request_info;
  9852. int keep_alive_enabled, keep_alive, discard_len;
  9853. char ebuf[100];
  9854. const char *hostend;
  9855. int reqerr, uri_type;
  9856. keep_alive_enabled =
  9857. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  9858. /* Important: on new connection, reset the receiving buffer. Credit
  9859. * goes to crule42. */
  9860. conn->data_len = 0;
  9861. do {
  9862. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  9863. /* The request sent by the client could not be understood by
  9864. * the server, or it was incomplete or a timeout. Send an
  9865. * error message and close the connection. */
  9866. if (reqerr > 0) {
  9867. /*assert(ebuf[0] != '\0');*/
  9868. send_http_error(conn, reqerr, "%s", ebuf);
  9869. }
  9870. } else if (strcmp(ri->http_version, "1.0")
  9871. && strcmp(ri->http_version, "1.1")) {
  9872. mg_snprintf(conn,
  9873. NULL, /* No truncation check for ebuf */
  9874. ebuf,
  9875. sizeof(ebuf),
  9876. "Bad HTTP version: [%s]",
  9877. ri->http_version);
  9878. send_http_error(conn, 505, "%s", ebuf);
  9879. }
  9880. if (ebuf[0] == '\0') {
  9881. uri_type = get_uri_type(conn->request_info.request_uri);
  9882. switch (uri_type) {
  9883. case 1:
  9884. /* Asterisk */
  9885. conn->request_info.local_uri = NULL;
  9886. break;
  9887. case 2:
  9888. /* relative uri */
  9889. conn->request_info.local_uri =
  9890. conn->request_info.request_uri;
  9891. break;
  9892. case 3:
  9893. case 4:
  9894. /* absolute uri (with/without port) */
  9895. hostend = get_rel_url_at_current_server(
  9896. conn->request_info.request_uri, conn);
  9897. if (hostend) {
  9898. conn->request_info.local_uri = hostend;
  9899. } else {
  9900. conn->request_info.local_uri = NULL;
  9901. }
  9902. break;
  9903. default:
  9904. mg_snprintf(conn,
  9905. NULL, /* No truncation check for ebuf */
  9906. ebuf,
  9907. sizeof(ebuf),
  9908. "Invalid URI: [%s]",
  9909. ri->request_uri);
  9910. send_http_error(conn, 400, "%s", ebuf);
  9911. break;
  9912. }
  9913. /* TODO: cleanup uri, local_uri and request_uri */
  9914. conn->request_info.uri = conn->request_info.local_uri;
  9915. }
  9916. if (ebuf[0] == '\0') {
  9917. handle_request(conn);
  9918. if (conn->ctx->callbacks.end_request != NULL) {
  9919. conn->ctx->callbacks.end_request(conn, conn->status_code);
  9920. }
  9921. log_access(conn);
  9922. } else {
  9923. conn->must_close = 1;
  9924. }
  9925. if (ri->remote_user != NULL) {
  9926. mg_free((void *)ri->remote_user);
  9927. /* Important! When having connections with and without auth
  9928. * would cause double free and then crash */
  9929. ri->remote_user = NULL;
  9930. }
  9931. /* NOTE(lsm): order is important here. should_keep_alive() call is
  9932. * using parsed request, which will be invalid after memmove's
  9933. * below.
  9934. * Therefore, memorize should_keep_alive() result now for later use
  9935. * in loop exit condition. */
  9936. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  9937. && conn->content_len >= 0 && should_keep_alive(conn);
  9938. /* Discard all buffered data for this request */
  9939. discard_len = conn->content_len >= 0 && conn->request_len > 0
  9940. && conn->request_len + conn->content_len
  9941. < (int64_t)conn->data_len
  9942. ? (int)(conn->request_len + conn->content_len)
  9943. : conn->data_len;
  9944. /*assert(discard_len >= 0);*/
  9945. if (discard_len < 0)
  9946. break;
  9947. conn->data_len -= discard_len;
  9948. if (conn->data_len > 0) {
  9949. memmove(conn->buf,
  9950. conn->buf + discard_len,
  9951. (size_t)conn->data_len);
  9952. }
  9953. /* assert(conn->data_len >= 0); */
  9954. /* assert(conn->data_len <= conn->buf_size); */
  9955. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  9956. break;
  9957. }
  9958. } while (keep_alive);
  9959. }
  9960. }
  9961. /* Worker threads take accepted socket from the queue */
  9962. static int
  9963. consume_socket(struct mg_context *ctx, struct socket *sp)
  9964. {
  9965. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  9966. if (!ctx) {
  9967. return 0;
  9968. }
  9969. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9970. DEBUG_TRACE("%s", "going idle");
  9971. /* If the queue is empty, wait. We're idle at this point. */
  9972. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  9973. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  9974. }
  9975. /* If we're stopping, sq_head may be equal to sq_tail. */
  9976. if (ctx->sq_head > ctx->sq_tail) {
  9977. /* Copy socket from the queue and increment tail */
  9978. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  9979. ctx->sq_tail++;
  9980. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  9981. /* Wrap pointers if needed */
  9982. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  9983. ctx->sq_tail -= QUEUE_SIZE(ctx);
  9984. ctx->sq_head -= QUEUE_SIZE(ctx);
  9985. }
  9986. }
  9987. (void)pthread_cond_signal(&ctx->sq_empty);
  9988. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9989. return !ctx->stop_flag;
  9990. #undef QUEUE_SIZE
  9991. }
  9992. static void *
  9993. worker_thread_run(void *thread_func_param)
  9994. {
  9995. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  9996. struct mg_connection *conn;
  9997. struct mg_workerTLS tls;
  9998. #if defined(MG_LEGACY_INTERFACE)
  9999. uint32_t addr;
  10000. #endif
  10001. mg_set_thread_name("worker");
  10002. tls.is_master = 0;
  10003. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10004. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10005. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10006. #endif
  10007. conn =
  10008. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10009. if (conn == NULL) {
  10010. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10011. } else {
  10012. pthread_setspecific(sTlsKey, &tls);
  10013. conn->buf_size = MAX_REQUEST_SIZE;
  10014. conn->buf = (char *)(conn + 1);
  10015. conn->ctx = ctx;
  10016. conn->request_info.user_data = ctx->user_data;
  10017. /* Allocate a mutex for this connection to allow communication both
  10018. * within the request handler and from elsewhere in the application */
  10019. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10020. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10021. * signal sq_empty condvar to wake up the master waiting in
  10022. * produce_socket() */
  10023. while (consume_socket(ctx, &conn->client)) {
  10024. conn->conn_birth_time = time(NULL);
  10025. /* Fill in IP, port info early so even if SSL setup below fails,
  10026. * error handler would have the corresponding info.
  10027. * Thanks to Johannes Winkelmann for the patch.
  10028. */
  10029. #if defined(USE_IPV6)
  10030. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10031. conn->request_info.remote_port =
  10032. ntohs(conn->client.rsa.sin6.sin6_port);
  10033. } else
  10034. #endif
  10035. {
  10036. conn->request_info.remote_port =
  10037. ntohs(conn->client.rsa.sin.sin_port);
  10038. }
  10039. sockaddr_to_string(conn->request_info.remote_addr,
  10040. sizeof(conn->request_info.remote_addr),
  10041. &conn->client.rsa);
  10042. #if defined(MG_LEGACY_INTERFACE)
  10043. /* This legacy interface only works for the IPv4 case */
  10044. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10045. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10046. #endif
  10047. conn->request_info.is_ssl = conn->client.is_ssl;
  10048. if (!conn->client.is_ssl
  10049. #ifndef NO_SSL
  10050. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10051. #endif
  10052. ) {
  10053. process_new_connection(conn);
  10054. }
  10055. close_connection(conn);
  10056. }
  10057. }
  10058. /* Signal master that we're done with connection and exiting */
  10059. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10060. ctx->running_worker_threads--;
  10061. (void)pthread_cond_signal(&ctx->thread_cond);
  10062. /* assert(ctx->running_worker_threads >= 0); */
  10063. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10064. pthread_setspecific(sTlsKey, NULL);
  10065. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10066. CloseHandle(tls.pthread_cond_helper_mutex);
  10067. #endif
  10068. mg_free(conn);
  10069. DEBUG_TRACE("%s", "exiting");
  10070. return NULL;
  10071. }
  10072. /* Threads have different return types on Windows and Unix. */
  10073. #ifdef _WIN32
  10074. static unsigned __stdcall worker_thread(void *thread_func_param)
  10075. {
  10076. worker_thread_run(thread_func_param);
  10077. return 0;
  10078. }
  10079. #else
  10080. static void *
  10081. worker_thread(void *thread_func_param)
  10082. {
  10083. worker_thread_run(thread_func_param);
  10084. return NULL;
  10085. }
  10086. #endif /* _WIN32 */
  10087. /* Master thread adds accepted socket to a queue */
  10088. static void
  10089. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10090. {
  10091. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10092. if (!ctx) {
  10093. return;
  10094. }
  10095. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10096. /* If the queue is full, wait */
  10097. while (ctx->stop_flag == 0
  10098. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10099. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10100. }
  10101. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10102. /* Copy socket to the queue and increment head */
  10103. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10104. ctx->sq_head++;
  10105. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10106. }
  10107. (void)pthread_cond_signal(&ctx->sq_full);
  10108. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10109. #undef QUEUE_SIZE
  10110. }
  10111. static void
  10112. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10113. {
  10114. struct socket so;
  10115. char src_addr[IP_ADDR_STR_LEN];
  10116. socklen_t len = sizeof(so.rsa);
  10117. int on = 1;
  10118. int timeout;
  10119. if (!listener) {
  10120. return;
  10121. }
  10122. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10123. == INVALID_SOCKET) {
  10124. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10125. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10126. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10127. closesocket(so.sock);
  10128. so.sock = INVALID_SOCKET;
  10129. } else {
  10130. /* Put so socket structure into the queue */
  10131. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10132. set_close_on_exec(so.sock, fc(ctx));
  10133. so.is_ssl = listener->is_ssl;
  10134. so.ssl_redir = listener->ssl_redir;
  10135. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10136. mg_cry(fc(ctx),
  10137. "%s: getsockname() failed: %s",
  10138. __func__,
  10139. strerror(ERRNO));
  10140. }
  10141. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  10142. * is enabled, and client resets the connection, server won't get
  10143. * TCP FIN or RST and will keep the connection open forever. With TCP
  10144. * keep-alive, next keep-alive handshake will figure out that the
  10145. * client is down and will close the server end.
  10146. * Thanks to Igor Klopov who suggested the patch. */
  10147. if (setsockopt(so.sock,
  10148. SOL_SOCKET,
  10149. SO_KEEPALIVE,
  10150. (SOCK_OPT_TYPE)&on,
  10151. sizeof(on)) != 0) {
  10152. mg_cry(fc(ctx),
  10153. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10154. __func__,
  10155. strerror(ERRNO));
  10156. }
  10157. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10158. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10159. } else {
  10160. timeout = -1;
  10161. }
  10162. /* Set socket timeout to the given value, but not more than a
  10163. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10164. * so the server can exit after that time if requested. */
  10165. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10166. set_sock_timeout(so.sock, timeout);
  10167. } else {
  10168. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10169. }
  10170. produce_socket(ctx, &so);
  10171. }
  10172. }
  10173. static void
  10174. master_thread_run(void *thread_func_param)
  10175. {
  10176. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10177. struct mg_workerTLS tls;
  10178. struct pollfd *pfd;
  10179. unsigned int i;
  10180. unsigned int workerthreadcount;
  10181. if (!ctx) {
  10182. return;
  10183. }
  10184. mg_set_thread_name("master");
  10185. /* Increase priority of the master thread */
  10186. #if defined(_WIN32)
  10187. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10188. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10189. int min_prio = sched_get_priority_min(SCHED_RR);
  10190. int max_prio = sched_get_priority_max(SCHED_RR);
  10191. if ((min_prio >= 0) && (max_prio >= 0)
  10192. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10193. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10194. struct sched_param sched_param = {0};
  10195. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10196. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10197. }
  10198. #endif
  10199. /* Initialize thread local storage */
  10200. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10201. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10202. #endif
  10203. tls.is_master = 1;
  10204. pthread_setspecific(sTlsKey, &tls);
  10205. /* Server starts *now* */
  10206. ctx->start_time = (unsigned long)time(NULL);
  10207. /* Allocate memory for the listening sockets, and start the server */
  10208. pfd =
  10209. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10210. while (pfd != NULL && ctx->stop_flag == 0) {
  10211. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10212. pfd[i].fd = ctx->listening_sockets[i].sock;
  10213. pfd[i].events = POLLIN;
  10214. }
  10215. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10216. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10217. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10218. * successful poll, and POLLIN is defined as
  10219. * (POLLRDNORM | POLLRDBAND)
  10220. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10221. * pfd[i].revents == POLLIN. */
  10222. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10223. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10224. }
  10225. }
  10226. }
  10227. }
  10228. mg_free(pfd);
  10229. DEBUG_TRACE("%s", "stopping workers");
  10230. /* Stop signal received: somebody called mg_stop. Quit. */
  10231. close_all_listening_sockets(ctx);
  10232. /* Wakeup workers that are waiting for connections to handle. */
  10233. pthread_cond_broadcast(&ctx->sq_full);
  10234. /* Wait until all threads finish */
  10235. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10236. while (ctx->running_worker_threads > 0) {
  10237. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10238. }
  10239. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10240. /* Join all worker threads to avoid leaking threads. */
  10241. workerthreadcount = ctx->cfg_worker_threads;
  10242. for (i = 0; i < workerthreadcount; i++) {
  10243. if (ctx->workerthreadids[i] != 0) {
  10244. mg_join_thread(ctx->workerthreadids[i]);
  10245. }
  10246. }
  10247. #if !defined(NO_SSL)
  10248. if (ctx->ssl_ctx != NULL) {
  10249. uninitialize_ssl(ctx);
  10250. }
  10251. #endif
  10252. DEBUG_TRACE("%s", "exiting");
  10253. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10254. CloseHandle(tls.pthread_cond_helper_mutex);
  10255. #endif
  10256. pthread_setspecific(sTlsKey, NULL);
  10257. /* Signal mg_stop() that we're done.
  10258. * WARNING: This must be the very last thing this
  10259. * thread does, as ctx becomes invalid after this line. */
  10260. ctx->stop_flag = 2;
  10261. }
  10262. /* Threads have different return types on Windows and Unix. */
  10263. #ifdef _WIN32
  10264. static unsigned __stdcall master_thread(void *thread_func_param)
  10265. {
  10266. master_thread_run(thread_func_param);
  10267. return 0;
  10268. }
  10269. #else
  10270. static void *
  10271. master_thread(void *thread_func_param)
  10272. {
  10273. master_thread_run(thread_func_param);
  10274. return NULL;
  10275. }
  10276. #endif /* _WIN32 */
  10277. static void
  10278. free_context(struct mg_context *ctx)
  10279. {
  10280. int i;
  10281. struct mg_request_handler_info *tmp_rh;
  10282. if (ctx == NULL) {
  10283. return;
  10284. }
  10285. if (ctx->callbacks.exit_context) {
  10286. ctx->callbacks.exit_context(ctx);
  10287. }
  10288. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  10289. */
  10290. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10291. (void)pthread_cond_destroy(&ctx->thread_cond);
  10292. (void)pthread_cond_destroy(&ctx->sq_empty);
  10293. (void)pthread_cond_destroy(&ctx->sq_full);
  10294. /* Destroy other context global data structures mutex */
  10295. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10296. #if defined(USE_TIMERS)
  10297. timers_exit(ctx);
  10298. #endif
  10299. /* Deallocate config parameters */
  10300. for (i = 0; i < NUM_OPTIONS; i++) {
  10301. if (ctx->config[i] != NULL) {
  10302. #if defined(_MSC_VER)
  10303. #pragma warning(suppress : 6001)
  10304. #endif
  10305. mg_free(ctx->config[i]);
  10306. }
  10307. }
  10308. /* Deallocate request handlers */
  10309. while (ctx->request_handlers) {
  10310. tmp_rh = ctx->request_handlers;
  10311. ctx->request_handlers = tmp_rh->next;
  10312. mg_free(tmp_rh->uri);
  10313. mg_free(tmp_rh);
  10314. }
  10315. #ifndef NO_SSL
  10316. /* Deallocate SSL context */
  10317. if (ctx->ssl_ctx != NULL) {
  10318. SSL_CTX_free(ctx->ssl_ctx);
  10319. }
  10320. if (ssl_mutexes != NULL) {
  10321. mg_free(ssl_mutexes);
  10322. ssl_mutexes = NULL;
  10323. }
  10324. #endif /* !NO_SSL */
  10325. /* Deallocate worker thread ID array */
  10326. if (ctx->workerthreadids != NULL) {
  10327. mg_free(ctx->workerthreadids);
  10328. }
  10329. /* Deallocate the tls variable */
  10330. if (mg_atomic_dec(&sTlsInit) == 0) {
  10331. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10332. DeleteCriticalSection(&global_log_file_lock);
  10333. #endif /* _WIN32 && !__SYMBIAN32__ */
  10334. #if !defined(_WIN32)
  10335. pthread_mutexattr_destroy(&pthread_mutex_attr);
  10336. #endif
  10337. pthread_key_delete(sTlsKey);
  10338. }
  10339. /* deallocate system name string */
  10340. mg_free(ctx->systemName);
  10341. /* Deallocate context itself */
  10342. mg_free(ctx);
  10343. }
  10344. void
  10345. mg_stop(struct mg_context *ctx)
  10346. {
  10347. pthread_t mt;
  10348. if (!ctx) {
  10349. return;
  10350. }
  10351. /* We don't use a lock here. Calling mg_stop with the same ctx from
  10352. * two threads is not allowed. */
  10353. mt = ctx->masterthreadid;
  10354. if (mt == 0) {
  10355. return;
  10356. }
  10357. ctx->masterthreadid = 0;
  10358. ctx->stop_flag = 1;
  10359. /* Wait until mg_fini() stops */
  10360. while (ctx->stop_flag != 2) {
  10361. (void)mg_sleep(10);
  10362. }
  10363. mg_join_thread(mt);
  10364. free_context(ctx);
  10365. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10366. (void)WSACleanup();
  10367. #endif /* _WIN32 && !__SYMBIAN32__ */
  10368. }
  10369. static void
  10370. get_system_name(char **sysName)
  10371. {
  10372. #if defined(_WIN32)
  10373. #if !defined(__SYMBIAN32__)
  10374. char name[128];
  10375. DWORD dwVersion = 0;
  10376. DWORD dwMajorVersion = 0;
  10377. DWORD dwMinorVersion = 0;
  10378. DWORD dwBuild = 0;
  10379. #ifdef _MSC_VER
  10380. #pragma warning(push)
  10381. // GetVersion was declared deprecated
  10382. #pragma warning(disable : 4996)
  10383. #endif
  10384. dwVersion = GetVersion();
  10385. #ifdef _MSC_VER
  10386. #pragma warning(pop)
  10387. #endif
  10388. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  10389. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  10390. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  10391. (void)dwBuild;
  10392. sprintf(name,
  10393. "Windows %u.%u",
  10394. (unsigned)dwMajorVersion,
  10395. (unsigned)dwMinorVersion);
  10396. *sysName = mg_strdup(name);
  10397. #else
  10398. *sysName = mg_strdup("Symbian");
  10399. #endif
  10400. #else
  10401. struct utsname name;
  10402. memset(&name, 0, sizeof(name));
  10403. uname(&name);
  10404. *sysName = mg_strdup(name.sysname);
  10405. #endif
  10406. }
  10407. struct mg_context *
  10408. mg_start(const struct mg_callbacks *callbacks,
  10409. void *user_data,
  10410. const char **options)
  10411. {
  10412. struct mg_context *ctx;
  10413. const char *name, *value, *default_value;
  10414. int idx, ok, workerthreadcount;
  10415. unsigned int i;
  10416. void (*exit_callback)(const struct mg_context *ctx) = 0;
  10417. struct mg_workerTLS tls;
  10418. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10419. WSADATA data;
  10420. WSAStartup(MAKEWORD(2, 2), &data);
  10421. #endif /* _WIN32 && !__SYMBIAN32__ */
  10422. /* Allocate context and initialize reasonable general case defaults. */
  10423. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  10424. return NULL;
  10425. }
  10426. if (mg_atomic_inc(&sTlsInit) == 1) {
  10427. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10428. InitializeCriticalSection(&global_log_file_lock);
  10429. #endif /* _WIN32 && !__SYMBIAN32__ */
  10430. #if !defined(_WIN32)
  10431. pthread_mutexattr_init(&pthread_mutex_attr);
  10432. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  10433. #endif
  10434. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  10435. /* Fatal error - abort start. However, this situation should never
  10436. * occur in practice. */
  10437. mg_atomic_dec(&sTlsInit);
  10438. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  10439. mg_free(ctx);
  10440. return NULL;
  10441. }
  10442. } else {
  10443. /* TODO (low): istead of sleeping, check if sTlsKey is already
  10444. * initialized. */
  10445. mg_sleep(1);
  10446. }
  10447. tls.is_master = -1;
  10448. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10449. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10450. tls.pthread_cond_helper_mutex = NULL;
  10451. #endif
  10452. pthread_setspecific(sTlsKey, &tls);
  10453. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  10454. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  10455. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  10456. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  10457. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  10458. if (!ok) {
  10459. /* Fatal error - abort start. However, this situation should never
  10460. * occur in practice. */
  10461. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  10462. mg_free(ctx);
  10463. pthread_setspecific(sTlsKey, NULL);
  10464. return NULL;
  10465. }
  10466. if (callbacks) {
  10467. ctx->callbacks = *callbacks;
  10468. exit_callback = callbacks->exit_context;
  10469. ctx->callbacks.exit_context = 0;
  10470. }
  10471. ctx->user_data = user_data;
  10472. ctx->request_handlers = NULL;
  10473. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10474. ctx->shared_lua_websockets = 0;
  10475. #endif
  10476. while (options && (name = *options++) != NULL) {
  10477. if ((idx = get_option_index(name)) == -1) {
  10478. mg_cry(fc(ctx), "Invalid option: %s", name);
  10479. free_context(ctx);
  10480. pthread_setspecific(sTlsKey, NULL);
  10481. return NULL;
  10482. } else if ((value = *options++) == NULL) {
  10483. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  10484. free_context(ctx);
  10485. pthread_setspecific(sTlsKey, NULL);
  10486. return NULL;
  10487. }
  10488. if (ctx->config[idx] != NULL) {
  10489. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  10490. mg_free(ctx->config[idx]);
  10491. }
  10492. ctx->config[idx] = mg_strdup(value);
  10493. DEBUG_TRACE("[%s] -> [%s]", name, value);
  10494. }
  10495. /* Set default value if needed */
  10496. for (i = 0; config_options[i].name != NULL; i++) {
  10497. default_value = config_options[i].default_value;
  10498. if (ctx->config[i] == NULL && default_value != NULL) {
  10499. ctx->config[i] = mg_strdup(default_value);
  10500. }
  10501. }
  10502. #if defined(NO_FILES)
  10503. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  10504. mg_cry(fc(ctx), "%s", "Document root must not be set");
  10505. free_context(ctx);
  10506. pthread_setspecific(sTlsKey, NULL);
  10507. return NULL;
  10508. }
  10509. #endif
  10510. get_system_name(&ctx->systemName);
  10511. /* NOTE(lsm): order is important here. SSL certificates must
  10512. * be initialized before listening ports. UID must be set last. */
  10513. if (!set_gpass_option(ctx) ||
  10514. #if !defined(NO_SSL)
  10515. !set_ssl_option(ctx) ||
  10516. #endif
  10517. !set_ports_option(ctx) ||
  10518. #if !defined(_WIN32)
  10519. !set_uid_option(ctx) ||
  10520. #endif
  10521. !set_acl_option(ctx)) {
  10522. free_context(ctx);
  10523. pthread_setspecific(sTlsKey, NULL);
  10524. return NULL;
  10525. }
  10526. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  10527. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  10528. * won't kill the whole process. */
  10529. (void)signal(SIGPIPE, SIG_IGN);
  10530. #endif /* !_WIN32 && !__SYMBIAN32__ */
  10531. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  10532. if (workerthreadcount > MAX_WORKER_THREADS) {
  10533. mg_cry(fc(ctx), "Too many worker threads");
  10534. free_context(ctx);
  10535. pthread_setspecific(sTlsKey, NULL);
  10536. return NULL;
  10537. }
  10538. if (workerthreadcount > 0) {
  10539. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  10540. ctx->workerthreadids =
  10541. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  10542. if (ctx->workerthreadids == NULL) {
  10543. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  10544. free_context(ctx);
  10545. pthread_setspecific(sTlsKey, NULL);
  10546. return NULL;
  10547. }
  10548. }
  10549. #if defined(USE_TIMERS)
  10550. if (timers_init(ctx) != 0) {
  10551. mg_cry(fc(ctx), "Error creating timers");
  10552. free_context(ctx);
  10553. pthread_setspecific(sTlsKey, NULL);
  10554. return NULL;
  10555. }
  10556. #endif
  10557. /* Context has been created - init user libraries */
  10558. if (ctx->callbacks.init_context) {
  10559. ctx->callbacks.init_context(ctx);
  10560. }
  10561. ctx->callbacks.exit_context = exit_callback;
  10562. ctx->context_type = 1; /* server context */
  10563. /* Start master (listening) thread */
  10564. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  10565. /* Start worker threads */
  10566. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10567. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10568. ctx->running_worker_threads++;
  10569. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10570. if (mg_start_thread_with_id(worker_thread,
  10571. ctx,
  10572. &ctx->workerthreadids[i]) != 0) {
  10573. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10574. ctx->running_worker_threads--;
  10575. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10576. if (i > 0) {
  10577. mg_cry(fc(ctx),
  10578. "Cannot start worker thread %i: error %ld",
  10579. i + 1,
  10580. (long)ERRNO);
  10581. } else {
  10582. mg_cry(fc(ctx),
  10583. "Cannot create threads: error %ld",
  10584. (long)ERRNO);
  10585. free_context(ctx);
  10586. pthread_setspecific(sTlsKey, NULL);
  10587. return NULL;
  10588. }
  10589. break;
  10590. }
  10591. }
  10592. pthread_setspecific(sTlsKey, NULL);
  10593. return ctx;
  10594. }
  10595. /* Feature check API function */
  10596. unsigned
  10597. mg_check_feature(unsigned feature)
  10598. {
  10599. static const unsigned feature_set = 0
  10600. /* Set bits for available features according to API documentation.
  10601. * This bit mask is created at compile time, according to the active
  10602. * preprocessor defines. It is a single const value at runtime. */
  10603. #if !defined(NO_FILES)
  10604. | 1
  10605. #endif
  10606. #if !defined(NO_SSL)
  10607. | 2
  10608. #endif
  10609. #if !defined(NO_CGI)
  10610. | 4
  10611. #endif
  10612. #if defined(USE_IPV6)
  10613. | 8
  10614. #endif
  10615. #if defined(USE_WEBSOCKET)
  10616. | 16
  10617. #endif
  10618. #if defined(USE_LUA)
  10619. | 32
  10620. #endif
  10621. #if defined(USE_DUKTAPE)
  10622. | 64
  10623. #endif
  10624. /* Set some extra bits not defined in the API documentation.
  10625. * These bits may change without further notice. */
  10626. #if defined(MG_LEGACY_INTERFACE)
  10627. | 128
  10628. #endif
  10629. #if defined(MEMORY_DEBUGGING)
  10630. | 256
  10631. #endif
  10632. #if defined(USE_TIMERS)
  10633. | 512
  10634. #endif
  10635. #if !defined(NO_NONCE_CHECK)
  10636. | 1024
  10637. #endif
  10638. #if !defined(NO_POPEN)
  10639. | 2048
  10640. #endif
  10641. ;
  10642. return (feature & feature_set);
  10643. }