civetweb.c 289 KB

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