civetweb.c 277 KB

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