civetweb.c 291 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888
  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 (256)
  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. #if !defined(NO_FILES)
  2143. static int mg_remove(const char *path)
  2144. {
  2145. wchar_t wbuf[PATH_MAX];
  2146. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2147. return DeleteFileW(wbuf) ? 0 : -1;
  2148. }
  2149. static int mg_mkdir(const char *path, int mode)
  2150. {
  2151. char buf[PATH_MAX];
  2152. wchar_t wbuf[PATH_MAX];
  2153. (void)mode;
  2154. mg_strlcpy(buf, path, sizeof(buf));
  2155. change_slashes_to_backslashes(buf);
  2156. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2157. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2158. }
  2159. #endif
  2160. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2161. static DIR *opendir(const char *name)
  2162. {
  2163. DIR *dir = NULL;
  2164. wchar_t wpath[PATH_MAX];
  2165. DWORD attrs;
  2166. if (name == NULL) {
  2167. SetLastError(ERROR_BAD_ARGUMENTS);
  2168. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2169. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2170. } else {
  2171. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2172. attrs = GetFileAttributesW(wpath);
  2173. if (attrs != 0xFFFFFFFF &&
  2174. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  2175. (void)wcscat(wpath, L"\\*");
  2176. dir->handle = FindFirstFileW(wpath, &dir->info);
  2177. dir->result.d_name[0] = '\0';
  2178. } else {
  2179. mg_free(dir);
  2180. dir = NULL;
  2181. }
  2182. }
  2183. return dir;
  2184. }
  2185. static int closedir(DIR *dir)
  2186. {
  2187. int result = 0;
  2188. if (dir != NULL) {
  2189. if (dir->handle != INVALID_HANDLE_VALUE)
  2190. result = FindClose(dir->handle) ? 0 : -1;
  2191. mg_free(dir);
  2192. } else {
  2193. result = -1;
  2194. SetLastError(ERROR_BAD_ARGUMENTS);
  2195. }
  2196. return result;
  2197. }
  2198. static struct dirent *readdir(DIR *dir)
  2199. {
  2200. struct dirent *result = 0;
  2201. if (dir) {
  2202. if (dir->handle != INVALID_HANDLE_VALUE) {
  2203. result = &dir->result;
  2204. (void)WideCharToMultiByte(CP_UTF8,
  2205. 0,
  2206. dir->info.cFileName,
  2207. -1,
  2208. result->d_name,
  2209. sizeof(result->d_name),
  2210. NULL,
  2211. NULL);
  2212. if (!FindNextFileW(dir->handle, &dir->info)) {
  2213. (void)FindClose(dir->handle);
  2214. dir->handle = INVALID_HANDLE_VALUE;
  2215. }
  2216. } else {
  2217. SetLastError(ERROR_FILE_NOT_FOUND);
  2218. }
  2219. } else {
  2220. SetLastError(ERROR_BAD_ARGUMENTS);
  2221. }
  2222. return result;
  2223. }
  2224. #ifndef HAVE_POLL
  2225. static int poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2226. {
  2227. struct timeval tv;
  2228. fd_set set;
  2229. unsigned int i;
  2230. int result;
  2231. SOCKET maxfd = 0;
  2232. tv.tv_sec = milliseconds / 1000;
  2233. tv.tv_usec = (milliseconds % 1000) * 1000;
  2234. FD_ZERO(&set);
  2235. for (i = 0; i < n; i++) {
  2236. FD_SET((SOCKET)pfd[i].fd, &set);
  2237. pfd[i].revents = 0;
  2238. if (pfd[i].fd > maxfd) {
  2239. maxfd = pfd[i].fd;
  2240. }
  2241. }
  2242. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2243. for (i = 0; i < n; i++) {
  2244. if (FD_ISSET(pfd[i].fd, &set)) {
  2245. pfd[i].revents = POLLIN;
  2246. }
  2247. }
  2248. }
  2249. return result;
  2250. }
  2251. #endif /* HAVE_POLL */
  2252. static void set_close_on_exec(SOCKET sock,
  2253. struct mg_connection *conn /* may be null */)
  2254. {
  2255. (void)conn; /* Unused. */
  2256. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2257. }
  2258. int mg_start_thread(mg_thread_func_t f, void *p)
  2259. {
  2260. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2261. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2262. */
  2263. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p) ==
  2264. ((uintptr_t)(-1L)))
  2265. ? -1
  2266. : 0);
  2267. #else
  2268. return (
  2269. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2270. ? -1
  2271. : 0);
  2272. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2273. }
  2274. /* Start a thread storing the thread context. */
  2275. static int mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2276. void *p,
  2277. pthread_t *threadidptr)
  2278. {
  2279. uintptr_t uip;
  2280. HANDLE threadhandle;
  2281. int result = -1;
  2282. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2283. threadhandle = (HANDLE)uip;
  2284. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2285. *threadidptr = threadhandle;
  2286. result = 0;
  2287. }
  2288. return result;
  2289. }
  2290. /* Wait for a thread to finish. */
  2291. static int mg_join_thread(pthread_t threadid)
  2292. {
  2293. int result;
  2294. DWORD dwevent;
  2295. result = -1;
  2296. dwevent = WaitForSingleObject(threadid, INFINITE);
  2297. if (dwevent == WAIT_FAILED) {
  2298. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2299. } else {
  2300. if (dwevent == WAIT_OBJECT_0) {
  2301. CloseHandle(threadid);
  2302. result = 0;
  2303. }
  2304. }
  2305. return result;
  2306. }
  2307. #if !defined(NO_SSL_DL)
  2308. static HANDLE dlopen(const char *dll_name, int flags)
  2309. {
  2310. wchar_t wbuf[PATH_MAX];
  2311. (void)flags;
  2312. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2313. return LoadLibraryW(wbuf);
  2314. }
  2315. static int dlclose(void *handle)
  2316. {
  2317. int result;
  2318. if (FreeLibrary((HMODULE)handle) != 0) {
  2319. result = 0;
  2320. } else {
  2321. result = -1;
  2322. }
  2323. return result;
  2324. }
  2325. #endif
  2326. #if !defined(NO_CGI)
  2327. #define SIGKILL (0)
  2328. static int kill(pid_t pid, int sig_num)
  2329. {
  2330. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2331. (void)CloseHandle((HANDLE)pid);
  2332. return 0;
  2333. }
  2334. static void trim_trailing_whitespaces(char *s)
  2335. {
  2336. char *e = s + strlen(s) - 1;
  2337. while (e > s && isspace(*(unsigned char *)e)) {
  2338. *e-- = '\0';
  2339. }
  2340. }
  2341. static pid_t spawn_process(struct mg_connection *conn,
  2342. const char *prog,
  2343. char *envblk,
  2344. char *envp[],
  2345. int fdin,
  2346. int fdout,
  2347. const char *dir)
  2348. {
  2349. HANDLE me;
  2350. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2351. cmdline[PATH_MAX], buf[PATH_MAX];
  2352. int truncated;
  2353. struct file file = STRUCT_FILE_INITIALIZER;
  2354. STARTUPINFOA si;
  2355. PROCESS_INFORMATION pi = {0};
  2356. (void)envp;
  2357. memset(&si, 0, sizeof(si));
  2358. si.cb = sizeof(si);
  2359. /* TODO(lsm, mid): redirect CGI errors to the error log file */
  2360. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2361. si.wShowWindow = SW_HIDE;
  2362. me = GetCurrentProcess();
  2363. DuplicateHandle(me,
  2364. (HANDLE)_get_osfhandle(fdin),
  2365. me,
  2366. &si.hStdInput,
  2367. 0,
  2368. TRUE,
  2369. DUPLICATE_SAME_ACCESS);
  2370. DuplicateHandle(me,
  2371. (HANDLE)_get_osfhandle(fdout),
  2372. me,
  2373. &si.hStdOutput,
  2374. 0,
  2375. TRUE,
  2376. DUPLICATE_SAME_ACCESS);
  2377. /* If CGI file is a script, try to read the interpreter line */
  2378. interp = conn->ctx->config[CGI_INTERPRETER];
  2379. if (interp == NULL) {
  2380. buf[0] = buf[1] = '\0';
  2381. /* Read the first line of the script into the buffer */
  2382. mg_snprintf(
  2383. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2384. if (truncated) {
  2385. pi.hProcess = (pid_t)-1;
  2386. goto spawn_cleanup;
  2387. }
  2388. if (mg_fopen(conn, cmdline, "r", &file)) {
  2389. p = (char *)file.membuf;
  2390. mg_fgets(buf, sizeof(buf), &file, &p);
  2391. mg_fclose(&file);
  2392. buf[sizeof(buf) - 1] = '\0';
  2393. }
  2394. if (buf[0] == '#' && buf[1] == '!') {
  2395. trim_trailing_whitespaces(buf + 2);
  2396. } else {
  2397. buf[2] = '\0';
  2398. }
  2399. interp = buf + 2;
  2400. }
  2401. if (interp[0] != '\0') {
  2402. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2403. interp = full_interp;
  2404. }
  2405. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2406. if (interp[0] != '\0') {
  2407. mg_snprintf(conn,
  2408. &truncated,
  2409. cmdline,
  2410. sizeof(cmdline),
  2411. "\"%s\" \"%s\\%s\"",
  2412. interp,
  2413. full_dir,
  2414. prog);
  2415. } else {
  2416. mg_snprintf(conn,
  2417. &truncated,
  2418. cmdline,
  2419. sizeof(cmdline),
  2420. "\"%s\\%s\"",
  2421. full_dir,
  2422. prog);
  2423. }
  2424. if (truncated) {
  2425. pi.hProcess = (pid_t)-1;
  2426. goto spawn_cleanup;
  2427. }
  2428. DEBUG_TRACE("Running [%s]", cmdline);
  2429. if (CreateProcessA(NULL,
  2430. cmdline,
  2431. NULL,
  2432. NULL,
  2433. TRUE,
  2434. CREATE_NEW_PROCESS_GROUP,
  2435. envblk,
  2436. NULL,
  2437. &si,
  2438. &pi) == 0) {
  2439. mg_cry(
  2440. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2441. pi.hProcess = (pid_t)-1;
  2442. /* goto spawn_cleanup; */
  2443. }
  2444. spawn_cleanup:
  2445. (void)CloseHandle(si.hStdOutput);
  2446. (void)CloseHandle(si.hStdInput);
  2447. if (pi.hThread != NULL) {
  2448. (void)CloseHandle(pi.hThread);
  2449. }
  2450. return (pid_t)pi.hProcess;
  2451. }
  2452. #endif /* !NO_CGI */
  2453. static int set_non_blocking_mode(SOCKET sock)
  2454. {
  2455. unsigned long on = 1;
  2456. return ioctlsocket(sock, (long)FIONBIO, &on);
  2457. }
  2458. #else
  2459. static int
  2460. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2461. {
  2462. struct stat st;
  2463. if (!filep) {
  2464. return 0;
  2465. }
  2466. memset(filep, 0, sizeof(*filep));
  2467. if (conn && is_file_in_memory(conn, path, filep)) {
  2468. return 1;
  2469. }
  2470. if (0 == stat(path, &st)) {
  2471. filep->size = (uint64_t)(st.st_size);
  2472. filep->last_modified = st.st_mtime;
  2473. filep->is_directory = S_ISDIR(st.st_mode);
  2474. return 1;
  2475. }
  2476. return 0;
  2477. }
  2478. static void set_close_on_exec(SOCKET fd,
  2479. struct mg_connection *conn /* may be null */)
  2480. {
  2481. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2482. if (conn) {
  2483. mg_cry(conn,
  2484. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2485. __func__,
  2486. strerror(ERRNO));
  2487. }
  2488. }
  2489. }
  2490. int mg_start_thread(mg_thread_func_t func, void *param)
  2491. {
  2492. pthread_t thread_id;
  2493. pthread_attr_t attr;
  2494. int result;
  2495. (void)pthread_attr_init(&attr);
  2496. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2497. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2498. /* Compile-time option to control stack size,
  2499. * e.g. -DUSE_STACK_SIZE=16384 */
  2500. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2501. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2502. result = pthread_create(&thread_id, &attr, func, param);
  2503. pthread_attr_destroy(&attr);
  2504. return result;
  2505. }
  2506. /* Start a thread storing the thread context. */
  2507. static int mg_start_thread_with_id(mg_thread_func_t func,
  2508. void *param,
  2509. pthread_t *threadidptr)
  2510. {
  2511. pthread_t thread_id;
  2512. pthread_attr_t attr;
  2513. int result;
  2514. (void)pthread_attr_init(&attr);
  2515. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2516. /* Compile-time option to control stack size,
  2517. * e.g. -DUSE_STACK_SIZE=16384 */
  2518. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2519. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2520. result = pthread_create(&thread_id, &attr, func, param);
  2521. pthread_attr_destroy(&attr);
  2522. if ((result == 0) && (threadidptr != NULL)) {
  2523. *threadidptr = thread_id;
  2524. }
  2525. return result;
  2526. }
  2527. /* Wait for a thread to finish. */
  2528. static int mg_join_thread(pthread_t threadid)
  2529. {
  2530. int result;
  2531. result = pthread_join(threadid, NULL);
  2532. return result;
  2533. }
  2534. #ifndef NO_CGI
  2535. static pid_t spawn_process(struct mg_connection *conn,
  2536. const char *prog,
  2537. char *envblk,
  2538. char *envp[],
  2539. int fdin,
  2540. int fdout,
  2541. const char *dir)
  2542. {
  2543. pid_t pid;
  2544. const char *interp;
  2545. (void)envblk;
  2546. if (conn == NULL) {
  2547. return 0;
  2548. }
  2549. if ((pid = fork()) == -1) {
  2550. /* Parent */
  2551. send_http_error(conn,
  2552. 500,
  2553. "Error: Creating CGI process\nfork(): %s",
  2554. strerror(ERRNO));
  2555. } else if (pid == 0) {
  2556. /* Child */
  2557. if (chdir(dir) != 0) {
  2558. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2559. } else if (dup2(fdin, 0) == -1) {
  2560. mg_cry(
  2561. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2562. } else if (dup2(fdout, 1) == -1) {
  2563. mg_cry(
  2564. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2565. } else {
  2566. /* Not redirecting stderr to stdout, to avoid output being littered
  2567. * with the error messages. */
  2568. (void)close(fdin);
  2569. (void)close(fdout);
  2570. /* After exec, all signal handlers are restored to their default
  2571. * values, with one exception of SIGCHLD. According to
  2572. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2573. * leave unchanged after exec if it was set to be ignored. Restore
  2574. * it to default action. */
  2575. signal(SIGCHLD, SIG_DFL);
  2576. interp = conn->ctx->config[CGI_INTERPRETER];
  2577. if (interp == NULL) {
  2578. (void)execle(prog, prog, NULL, envp);
  2579. mg_cry(conn,
  2580. "%s: execle(%s): %s",
  2581. __func__,
  2582. prog,
  2583. strerror(ERRNO));
  2584. } else {
  2585. (void)execle(interp, interp, prog, NULL, envp);
  2586. mg_cry(conn,
  2587. "%s: execle(%s %s): %s",
  2588. __func__,
  2589. interp,
  2590. prog,
  2591. strerror(ERRNO));
  2592. }
  2593. }
  2594. exit(EXIT_FAILURE);
  2595. }
  2596. return pid;
  2597. }
  2598. #endif /* !NO_CGI */
  2599. static int set_non_blocking_mode(SOCKET sock)
  2600. {
  2601. int flags;
  2602. flags = fcntl(sock, F_GETFL, 0);
  2603. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2604. return 0;
  2605. }
  2606. #endif /* _WIN32 */
  2607. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2608. * descriptor. Return number of bytes written. */
  2609. static int push(struct mg_context *ctx,
  2610. FILE *fp,
  2611. SOCKET sock,
  2612. SSL *ssl,
  2613. const char *buf,
  2614. int len,
  2615. double timeout)
  2616. {
  2617. struct timespec start, now;
  2618. int n, err;
  2619. #ifdef _WIN32
  2620. typedef int len_t;
  2621. #else
  2622. typedef size_t len_t;
  2623. #endif
  2624. if (timeout > 0) {
  2625. memset(&start, 0, sizeof(start));
  2626. memset(&now, 0, sizeof(now));
  2627. clock_gettime(CLOCK_MONOTONIC, &start);
  2628. }
  2629. if (ctx == NULL) {
  2630. return -1;
  2631. }
  2632. #ifdef NO_SSL
  2633. if (ssl) {
  2634. return -1;
  2635. }
  2636. #endif
  2637. do {
  2638. #ifndef NO_SSL
  2639. if (ssl != NULL) {
  2640. n = SSL_write(ssl, buf, len);
  2641. if (n <= 0) {
  2642. err = SSL_get_error(ssl, n);
  2643. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  2644. err = ERRNO;
  2645. } else {
  2646. DEBUG_TRACE("SSL_write() failed, error %d", err);
  2647. return -1;
  2648. }
  2649. } else {
  2650. err = 0;
  2651. }
  2652. } else
  2653. #endif
  2654. if (fp != NULL) {
  2655. n = (int)fwrite(buf, 1, (size_t)len, fp);
  2656. if (ferror(fp)) {
  2657. n = -1;
  2658. err = ERRNO;
  2659. } else {
  2660. err = 0;
  2661. }
  2662. } else {
  2663. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  2664. err = (n < 0) ? ERRNO : 0;
  2665. }
  2666. if (ctx->stop_flag) {
  2667. return -1;
  2668. }
  2669. if ((n > 0) || (n == 0 && len == 0)) {
  2670. /* some data has been read, or no data was requested */
  2671. return n;
  2672. }
  2673. if (n == 0) {
  2674. /* shutdown of the socket at client side */
  2675. return -1;
  2676. }
  2677. if (n < 0) {
  2678. /* socket error - check errno */
  2679. DEBUG_TRACE("send() failed, error %d", err);
  2680. /* TODO: error handling depending on the error code.
  2681. * These codes are different between Windows and Linux.
  2682. */
  2683. return -1;
  2684. }
  2685. if (timeout > 0) {
  2686. clock_gettime(CLOCK_MONOTONIC, &now);
  2687. }
  2688. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2689. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  2690. used */
  2691. return -1;
  2692. }
  2693. static int64_t push_all(struct mg_context *ctx,
  2694. FILE *fp,
  2695. SOCKET sock,
  2696. SSL *ssl,
  2697. const char *buf,
  2698. int64_t len)
  2699. {
  2700. double timeout = -1.0;
  2701. int64_t n, nwritten = 0;
  2702. if (ctx == NULL) {
  2703. return -1;
  2704. }
  2705. if (ctx->config[REQUEST_TIMEOUT]) {
  2706. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2707. }
  2708. while (len > 0 && ctx->stop_flag == 0) {
  2709. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  2710. if (n < 0) {
  2711. if (nwritten == 0) {
  2712. nwritten = n; /* Propagate the error */
  2713. }
  2714. break;
  2715. } else if (n == 0) {
  2716. break; /* No more data to write */
  2717. } else {
  2718. nwritten += n;
  2719. len -= n;
  2720. }
  2721. }
  2722. return nwritten;
  2723. }
  2724. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  2725. * Return negative value on error, or number of bytes read on success. */
  2726. static int
  2727. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  2728. {
  2729. int nread, err;
  2730. struct timespec start, now;
  2731. #ifdef _WIN32
  2732. typedef int len_t;
  2733. #else
  2734. typedef size_t len_t;
  2735. #endif
  2736. if (timeout > 0) {
  2737. memset(&start, 0, sizeof(start));
  2738. memset(&now, 0, sizeof(now));
  2739. clock_gettime(CLOCK_MONOTONIC, &start);
  2740. }
  2741. do {
  2742. if (fp != NULL) {
  2743. /* Use read() instead of fread(), because if we're reading from the
  2744. * CGI pipe, fread() may block until IO buffer is filled up. We
  2745. * cannot afford to block and must pass all read bytes immediately
  2746. * to the client. */
  2747. nread = (int)read(fileno(fp), buf, (size_t)len);
  2748. err = (nread < 0) ? ERRNO : 0;
  2749. #ifndef NO_SSL
  2750. } else if (conn->ssl != NULL) {
  2751. nread = SSL_read(conn->ssl, buf, len);
  2752. if (nread <= 0) {
  2753. err = SSL_get_error(conn->ssl, nread);
  2754. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  2755. err = ERRNO;
  2756. } else {
  2757. DEBUG_TRACE("SSL_read() failed, error %d", err);
  2758. return -1;
  2759. }
  2760. } else {
  2761. err = 0;
  2762. }
  2763. #endif
  2764. } else {
  2765. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  2766. err = (nread < 0) ? ERRNO : 0;
  2767. }
  2768. if (conn->ctx->stop_flag) {
  2769. return -1;
  2770. }
  2771. if ((nread > 0) || (nread == 0 && len == 0)) {
  2772. /* some data has been read, or no data was requested */
  2773. return nread;
  2774. }
  2775. if (nread == 0) {
  2776. /* shutdown of the socket at client side */
  2777. return -1;
  2778. }
  2779. if (nread < 0) {
  2780. /* socket error - check errno */
  2781. #ifdef _WIN32
  2782. if (err == WSAEWOULDBLOCK) {
  2783. /* standard case if called from close_socket_gracefully */
  2784. return -1;
  2785. } else if (err == WSAETIMEDOUT) {
  2786. /* timeout is handled by the while loop */
  2787. } else {
  2788. DEBUG_TRACE("recv() failed, error %d", err);
  2789. return -1;
  2790. }
  2791. #else
  2792. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  2793. * if the timeout is reached and if the socket was set to non-
  2794. * blocking in close_socket_gracefully, so we can not distinguish
  2795. * here. We have to wait for the timeout in both cases for now.
  2796. */
  2797. if (err == EAGAIN || err == EWOULDBLOCK) {
  2798. /* standard case if called from close_socket_gracefully
  2799. * => should return -1 */
  2800. /* or timeout occured
  2801. * => the code must stay in the while loop */
  2802. } else {
  2803. DEBUG_TRACE("recv() failed, error %d", err);
  2804. return -1;
  2805. }
  2806. #endif
  2807. }
  2808. if (timeout > 0) {
  2809. clock_gettime(CLOCK_MONOTONIC, &now);
  2810. }
  2811. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2812. /* Timeout occured, but no data available. */
  2813. return -1;
  2814. }
  2815. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  2816. {
  2817. int n, nread = 0;
  2818. double timeout = -1.0;
  2819. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  2820. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2821. }
  2822. while (len > 0 && conn->ctx->stop_flag == 0) {
  2823. n = pull(fp, conn, buf + nread, len, timeout);
  2824. if (n < 0) {
  2825. if (nread == 0) {
  2826. nread = n; /* Propagate the error */
  2827. }
  2828. break;
  2829. } else if (n == 0) {
  2830. break; /* No more data to read */
  2831. } else {
  2832. conn->consumed_content += n;
  2833. nread += n;
  2834. len -= n;
  2835. }
  2836. }
  2837. return nread;
  2838. }
  2839. static void discard_unread_request_data(struct mg_connection *conn)
  2840. {
  2841. char buf[MG_BUF_LEN];
  2842. size_t to_read;
  2843. int nread;
  2844. if (conn == NULL) {
  2845. return;
  2846. }
  2847. to_read = sizeof(buf);
  2848. if (conn->is_chunked) {
  2849. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  2850. * completely */
  2851. while (conn->is_chunked == 1) {
  2852. nread = mg_read(conn, buf, to_read);
  2853. if (nread <= 0) {
  2854. break;
  2855. }
  2856. }
  2857. } else {
  2858. /* Not chunked: content length is known */
  2859. while (conn->consumed_content < conn->content_len) {
  2860. if (to_read >
  2861. (size_t)(conn->content_len - conn->consumed_content)) {
  2862. to_read = (size_t)(conn->content_len - conn->consumed_content);
  2863. }
  2864. nread = mg_read(conn, buf, to_read);
  2865. if (nread <= 0) {
  2866. break;
  2867. }
  2868. }
  2869. }
  2870. }
  2871. static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  2872. {
  2873. int64_t n, buffered_len, nread;
  2874. int64_t len64 =
  2875. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  2876. * int, we may not read more
  2877. * bytes */
  2878. const char *body;
  2879. if (conn == NULL) {
  2880. return 0;
  2881. }
  2882. /* If Content-Length is not set for a PUT or POST request, read until
  2883. * socket is closed */
  2884. if (conn->consumed_content == 0 && conn->content_len == -1) {
  2885. conn->content_len = INT64_MAX;
  2886. conn->must_close = 1;
  2887. }
  2888. nread = 0;
  2889. if (conn->consumed_content < conn->content_len) {
  2890. /* Adjust number of bytes to read. */
  2891. int64_t left_to_read = conn->content_len - conn->consumed_content;
  2892. if (left_to_read < len64) {
  2893. /* Do not reade more than the total content length of the request.
  2894. */
  2895. len64 = left_to_read;
  2896. }
  2897. /* Return buffered data */
  2898. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  2899. conn->consumed_content;
  2900. if (buffered_len > 0) {
  2901. if (len64 < buffered_len) {
  2902. buffered_len = len64;
  2903. }
  2904. body = conn->buf + conn->request_len + conn->consumed_content;
  2905. memcpy(buf, body, (size_t)buffered_len);
  2906. len64 -= buffered_len;
  2907. conn->consumed_content += buffered_len;
  2908. nread += buffered_len;
  2909. buf = (char *)buf + buffered_len;
  2910. }
  2911. /* We have returned all buffered data. Read new data from the remote
  2912. * socket.
  2913. */
  2914. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  2915. nread += n;
  2916. } else {
  2917. nread = (nread > 0 ? nread : n);
  2918. }
  2919. }
  2920. return (int)nread;
  2921. }
  2922. static char mg_getc(struct mg_connection *conn)
  2923. {
  2924. char c;
  2925. if (conn == NULL) {
  2926. return 0;
  2927. }
  2928. conn->content_len++;
  2929. if (mg_read_inner(conn, &c, 1) <= 0) {
  2930. return (char)0;
  2931. }
  2932. return c;
  2933. }
  2934. int mg_read(struct mg_connection *conn, void *buf, size_t len)
  2935. {
  2936. if (len > INT_MAX) {
  2937. len = INT_MAX;
  2938. }
  2939. if (conn == NULL) {
  2940. return 0;
  2941. }
  2942. if (conn->is_chunked) {
  2943. size_t all_read = 0;
  2944. while (len > 0) {
  2945. if (conn->chunk_remainder) {
  2946. /* copy from the remainder of the last received chunk */
  2947. long read_ret;
  2948. size_t read_now =
  2949. ((conn->chunk_remainder > len) ? (len)
  2950. : (conn->chunk_remainder));
  2951. conn->content_len += (int)read_now;
  2952. read_ret =
  2953. mg_read_inner(conn, (char *)buf + all_read, read_now);
  2954. all_read += (size_t)read_ret;
  2955. conn->chunk_remainder -= read_now;
  2956. len -= read_now;
  2957. if (conn->chunk_remainder == 0) {
  2958. /* the rest of the data in the current chunk has been read
  2959. */
  2960. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  2961. /* Protocol violation */
  2962. return -1;
  2963. }
  2964. }
  2965. } else {
  2966. /* fetch a new chunk */
  2967. int i = 0;
  2968. char lenbuf[64];
  2969. char *end = 0;
  2970. unsigned long chunkSize = 0;
  2971. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  2972. lenbuf[i] = mg_getc(conn);
  2973. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  2974. continue;
  2975. }
  2976. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  2977. lenbuf[i + 1] = 0;
  2978. chunkSize = strtoul(lenbuf, &end, 16);
  2979. break;
  2980. }
  2981. if (!isalnum(lenbuf[i])) {
  2982. /* illegal character for chunk length */
  2983. return -1;
  2984. }
  2985. }
  2986. if ((end == NULL) || (*end != '\r')) {
  2987. /* chunksize not set correctly */
  2988. return -1;
  2989. }
  2990. conn->chunk_remainder = chunkSize;
  2991. if (chunkSize == 0) {
  2992. /* regular end of content */
  2993. conn->is_chunked = 2;
  2994. break;
  2995. }
  2996. }
  2997. }
  2998. return (int)all_read;
  2999. }
  3000. return mg_read_inner(conn, buf, len);
  3001. }
  3002. int mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3003. {
  3004. time_t now;
  3005. int64_t n, total, allowed;
  3006. if (conn == NULL) {
  3007. return 0;
  3008. }
  3009. if (conn->throttle > 0) {
  3010. if ((now = time(NULL)) != conn->last_throttle_time) {
  3011. conn->last_throttle_time = now;
  3012. conn->last_throttle_bytes = 0;
  3013. }
  3014. allowed = conn->throttle - conn->last_throttle_bytes;
  3015. if (allowed > (int64_t)len) {
  3016. allowed = (int64_t)len;
  3017. }
  3018. if ((total = push_all(conn->ctx,
  3019. NULL,
  3020. conn->client.sock,
  3021. conn->ssl,
  3022. (const char *)buf,
  3023. (int64_t)allowed)) == allowed) {
  3024. buf = (char *)buf + total;
  3025. conn->last_throttle_bytes += total;
  3026. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3027. allowed = conn->throttle > (int64_t)len - total
  3028. ? (int64_t)len - total
  3029. : conn->throttle;
  3030. if ((n = push_all(conn->ctx,
  3031. NULL,
  3032. conn->client.sock,
  3033. conn->ssl,
  3034. (const char *)buf,
  3035. (int64_t)allowed)) != allowed) {
  3036. break;
  3037. }
  3038. sleep(1);
  3039. conn->last_throttle_bytes = allowed;
  3040. conn->last_throttle_time = time(NULL);
  3041. buf = (char *)buf + n;
  3042. total += n;
  3043. }
  3044. }
  3045. } else {
  3046. total = push_all(conn->ctx,
  3047. NULL,
  3048. conn->client.sock,
  3049. conn->ssl,
  3050. (const char *)buf,
  3051. (int64_t)len);
  3052. }
  3053. return (int)total;
  3054. }
  3055. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3056. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3057. {
  3058. va_list ap_copy;
  3059. size_t size = MG_BUF_LEN;
  3060. int len = -1;
  3061. *buf = NULL;
  3062. while (len < 0) {
  3063. if (*buf) {
  3064. mg_free(*buf);
  3065. }
  3066. *buf = (char *)mg_malloc(size *= 4);
  3067. if (!*buf) {
  3068. break;
  3069. }
  3070. va_copy(ap_copy, ap);
  3071. len = vsnprintf_impl(*buf, size, fmt, ap_copy);
  3072. va_end(ap_copy);
  3073. }
  3074. return len;
  3075. }
  3076. /* Print message to buffer. If buffer is large enough to hold the message,
  3077. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3078. * and return allocated buffer. */
  3079. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  3080. {
  3081. va_list ap_copy;
  3082. int len;
  3083. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3084. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3085. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3086. * Therefore, we make two passes: on first pass, get required message
  3087. * length.
  3088. * On second pass, actually print the message. */
  3089. va_copy(ap_copy, ap);
  3090. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3091. va_end(ap_copy);
  3092. if (len < 0) {
  3093. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3094. * Switch to alternative code path that uses incremental allocations.
  3095. */
  3096. va_copy(ap_copy, ap);
  3097. len = alloc_vprintf2(buf, fmt, ap);
  3098. va_end(ap_copy);
  3099. } else if ((size_t)(len) > size && (size = (size_t)(len) + 1) > 0 &&
  3100. (*buf = (char *)mg_malloc(size)) == NULL) {
  3101. len = -1; /* Allocation failed, mark failure */
  3102. } else {
  3103. va_copy(ap_copy, ap);
  3104. IGNORE_UNUSED_RESULT(vsnprintf_impl(*buf, size, fmt, ap_copy));
  3105. va_end(ap_copy);
  3106. }
  3107. return len;
  3108. }
  3109. static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3110. {
  3111. char mem[MG_BUF_LEN], *buf = mem;
  3112. int len;
  3113. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  3114. len = mg_write(conn, buf, (size_t)len);
  3115. }
  3116. if (buf != mem && buf != NULL) {
  3117. mg_free(buf);
  3118. }
  3119. return len;
  3120. }
  3121. int mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3122. {
  3123. va_list ap;
  3124. int result;
  3125. va_start(ap, fmt);
  3126. result = mg_vprintf(conn, fmt, ap);
  3127. va_end(ap);
  3128. return result;
  3129. }
  3130. int mg_url_decode(const char *src,
  3131. int src_len,
  3132. char *dst,
  3133. int dst_len,
  3134. int is_form_url_encoded)
  3135. {
  3136. int i, j, a, b;
  3137. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3138. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3139. if (i < src_len - 2 && src[i] == '%' &&
  3140. isxdigit(*(const unsigned char *)(src + i + 1)) &&
  3141. isxdigit(*(const unsigned char *)(src + i + 2))) {
  3142. a = tolower(*(const unsigned char *)(src + i + 1));
  3143. b = tolower(*(const unsigned char *)(src + i + 2));
  3144. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3145. i += 2;
  3146. } else if (is_form_url_encoded && src[i] == '+') {
  3147. dst[j] = ' ';
  3148. } else {
  3149. dst[j] = src[i];
  3150. }
  3151. }
  3152. dst[j] = '\0'; /* Null-terminate the destination */
  3153. return i >= src_len ? j : -1;
  3154. }
  3155. int mg_get_var(const char *data,
  3156. size_t data_len,
  3157. const char *name,
  3158. char *dst,
  3159. size_t dst_len)
  3160. {
  3161. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3162. }
  3163. int mg_get_var2(const char *data,
  3164. size_t data_len,
  3165. const char *name,
  3166. char *dst,
  3167. size_t dst_len,
  3168. size_t occurrence)
  3169. {
  3170. const char *p, *e, *s;
  3171. size_t name_len;
  3172. int len;
  3173. if (dst == NULL || dst_len == 0) {
  3174. len = -2;
  3175. } else if (data == NULL || name == NULL || data_len == 0) {
  3176. len = -1;
  3177. dst[0] = '\0';
  3178. } else {
  3179. name_len = strlen(name);
  3180. e = data + data_len;
  3181. len = -1;
  3182. dst[0] = '\0';
  3183. /* data is "var1=val1&var2=val2...". Find variable first */
  3184. for (p = data; p + name_len < e; p++) {
  3185. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  3186. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3187. /* Point p to variable value */
  3188. p += name_len + 1;
  3189. /* Point s to the end of the value */
  3190. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3191. if (s == NULL) {
  3192. s = e;
  3193. }
  3194. /* assert(s >= p); */
  3195. if (s < p) {
  3196. return -3;
  3197. }
  3198. /* Decode variable into destination buffer */
  3199. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3200. /* Redirect error code from -1 to -2 (destination buffer too
  3201. * small). */
  3202. if (len == -1) {
  3203. len = -2;
  3204. }
  3205. break;
  3206. }
  3207. }
  3208. }
  3209. return len;
  3210. }
  3211. int mg_get_cookie(const char *cookie_header,
  3212. const char *var_name,
  3213. char *dst,
  3214. size_t dst_size)
  3215. {
  3216. const char *s, *p, *end;
  3217. int name_len, len = -1;
  3218. if (dst == NULL || dst_size == 0) {
  3219. len = -2;
  3220. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3221. len = -1;
  3222. dst[0] = '\0';
  3223. } else {
  3224. name_len = (int)strlen(var_name);
  3225. end = s + strlen(s);
  3226. dst[0] = '\0';
  3227. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3228. if (s[name_len] == '=') {
  3229. s += name_len + 1;
  3230. if ((p = strchr(s, ' ')) == NULL) {
  3231. p = end;
  3232. }
  3233. if (p[-1] == ';') {
  3234. p--;
  3235. }
  3236. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3237. s++;
  3238. p--;
  3239. }
  3240. if ((size_t)(p - s) < dst_size) {
  3241. len = (int)(p - s);
  3242. mg_strlcpy(dst, s, (size_t)len + 1);
  3243. } else {
  3244. len = -3;
  3245. }
  3246. break;
  3247. }
  3248. }
  3249. }
  3250. return len;
  3251. }
  3252. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3253. static void base64_encode(const unsigned char *src, int src_len, char *dst)
  3254. {
  3255. static const char *b64 =
  3256. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3257. int i, j, a, b, c;
  3258. for (i = j = 0; i < src_len; i += 3) {
  3259. a = src[i];
  3260. b = i + 1 >= src_len ? 0 : src[i + 1];
  3261. c = i + 2 >= src_len ? 0 : src[i + 2];
  3262. dst[j++] = b64[a >> 2];
  3263. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3264. if (i + 1 < src_len) {
  3265. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3266. }
  3267. if (i + 2 < src_len) {
  3268. dst[j++] = b64[c & 63];
  3269. }
  3270. }
  3271. while (j % 4 != 0) {
  3272. dst[j++] = '=';
  3273. }
  3274. dst[j++] = '\0';
  3275. }
  3276. #endif
  3277. #if defined(USE_LUA)
  3278. static unsigned char b64reverse(char letter)
  3279. {
  3280. if (letter >= 'A' && letter <= 'Z') {
  3281. return letter - 'A';
  3282. }
  3283. if (letter >= 'a' && letter <= 'z') {
  3284. return letter - 'a' + 26;
  3285. }
  3286. if (letter >= '0' && letter <= '9') {
  3287. return letter - '0' + 52;
  3288. }
  3289. if (letter == '+') {
  3290. return 62;
  3291. }
  3292. if (letter == '/') {
  3293. return 63;
  3294. }
  3295. if (letter == '=') {
  3296. return 255; /* normal end */
  3297. }
  3298. return 254; /* error */
  3299. }
  3300. static int
  3301. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3302. {
  3303. int i;
  3304. unsigned char a, b, c, d;
  3305. *dst_len = 0;
  3306. for (i = 0; i < src_len; i += 4) {
  3307. a = b64reverse(src[i]);
  3308. if (a >= 254) {
  3309. return i;
  3310. }
  3311. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3312. if (b >= 254) {
  3313. return i + 1;
  3314. }
  3315. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3316. if (c == 254) {
  3317. return i + 2;
  3318. }
  3319. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3320. if (d == 254) {
  3321. return i + 3;
  3322. }
  3323. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3324. if (c != 255) {
  3325. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3326. if (d != 255) {
  3327. dst[(*dst_len)++] = (c << 6) + d;
  3328. }
  3329. }
  3330. }
  3331. return -1;
  3332. }
  3333. #endif
  3334. static int is_put_or_delete_method(const struct mg_connection *conn)
  3335. {
  3336. if (conn) {
  3337. const char *s = conn->request_info.request_method;
  3338. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  3339. !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3340. }
  3341. return 0;
  3342. }
  3343. static void
  3344. interpret_uri(struct mg_connection *conn, /* in: request */
  3345. char *filename, /* out: filename */
  3346. size_t filename_buf_len, /* in: size of filename buffer */
  3347. struct file *filep, /* out: file structure */
  3348. int *is_found, /* out: file is found (directly) */
  3349. int *is_script_ressource, /* out: handled by a script? */
  3350. int *is_websocket_request, /* out: websocket connetion? */
  3351. int *is_put_or_delete_request /* out: put/delete a file? */
  3352. )
  3353. {
  3354. /* TODO (high): Restructure this function */
  3355. if (conn && conn->ctx) {
  3356. #if !defined(NO_FILES)
  3357. const char *uri = conn->request_info.uri;
  3358. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3359. const char *rewrite;
  3360. struct vec a, b;
  3361. int match_len;
  3362. char gz_path[PATH_MAX];
  3363. char const *accept_encoding;
  3364. int truncated;
  3365. #if !defined(NO_CGI) || defined(USE_LUA)
  3366. char *p;
  3367. #endif
  3368. #else
  3369. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3370. #endif
  3371. memset(filep, 0, sizeof(*filep));
  3372. *filename = 0;
  3373. *is_found = 0;
  3374. *is_script_ressource = 0;
  3375. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3376. #if defined(USE_WEBSOCKET)
  3377. *is_websocket_request = is_websocket_protocol(conn);
  3378. #if !defined(NO_FILES)
  3379. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3380. root = conn->ctx->config[WEBSOCKET_ROOT];
  3381. }
  3382. #endif /* !NO_FILES */
  3383. #else /* USE_WEBSOCKET */
  3384. *is_websocket_request = 0;
  3385. #endif /* USE_WEBSOCKET */
  3386. #if !defined(NO_FILES)
  3387. /* Note that root == NULL is a regular use case here. This occurs,
  3388. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3389. * config is not required. */
  3390. if (root == NULL) {
  3391. /* all file related outputs have already been set to 0, just return
  3392. */
  3393. return;
  3394. }
  3395. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3396. * of the path one byte on the right.
  3397. * If document_root is NULL, leave the file empty. */
  3398. mg_snprintf(conn,
  3399. &truncated,
  3400. filename,
  3401. filename_buf_len - 1,
  3402. "%s%s",
  3403. root,
  3404. uri);
  3405. if (truncated) {
  3406. goto interpret_cleanup;
  3407. }
  3408. rewrite = conn->ctx->config[REWRITE];
  3409. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3410. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3411. mg_snprintf(conn,
  3412. &truncated,
  3413. filename,
  3414. filename_buf_len - 1,
  3415. "%.*s%s",
  3416. (int)b.len,
  3417. b.ptr,
  3418. uri + match_len);
  3419. break;
  3420. }
  3421. }
  3422. if (truncated) {
  3423. goto interpret_cleanup;
  3424. }
  3425. /* Local file path and name, corresponding to requested URI
  3426. * is now stored in "filename" variable. */
  3427. if (mg_stat(conn, filename, filep)) {
  3428. #if !defined(NO_CGI) || defined(USE_LUA)
  3429. /* File exists. Check if it is a script type. */
  3430. if (0
  3431. #if !defined(NO_CGI)
  3432. ||
  3433. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3434. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3435. filename) > 0
  3436. #endif
  3437. #if defined(USE_LUA)
  3438. ||
  3439. match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3440. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3441. filename) > 0
  3442. #endif
  3443. ) {
  3444. /* The request addresses a CGI script or a Lua script. The URI
  3445. * corresponds to the script itself (like /path/script.cgi),
  3446. * and there is no additional resource path
  3447. * (like /path/script.cgi/something).
  3448. * Requests that modify (replace or delete) a resource, like
  3449. * PUT and DELETE requests, should replace/delete the script
  3450. * file.
  3451. * Requests that read or write from/to a resource, like GET and
  3452. * POST requests, should call the script and return the
  3453. * generated response. */
  3454. *is_script_ressource = !*is_put_or_delete_request;
  3455. }
  3456. #endif /* !defined(NO_CGI) || defined(USE_LUA) */
  3457. *is_found = 1;
  3458. return;
  3459. }
  3460. /* If we can't find the actual file, look for the file
  3461. * with the same name but a .gz extension. If we find it,
  3462. * use that and set the gzipped flag in the file struct
  3463. * to indicate that the response need to have the content-
  3464. * encoding: gzip header.
  3465. * We can only do this if the browser declares support. */
  3466. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) !=
  3467. NULL) {
  3468. if (strstr(accept_encoding, "gzip") != NULL) {
  3469. mg_snprintf(conn,
  3470. &truncated,
  3471. gz_path,
  3472. sizeof(gz_path),
  3473. "%s.gz",
  3474. filename);
  3475. if (truncated) {
  3476. goto interpret_cleanup;
  3477. }
  3478. if (mg_stat(conn, gz_path, filep)) {
  3479. if (filep) {
  3480. filep->gzipped = 1;
  3481. *is_found = 1;
  3482. }
  3483. /* Currently gz files can not be scripts. */
  3484. return;
  3485. }
  3486. }
  3487. }
  3488. #if !defined(NO_CGI) || defined(USE_LUA)
  3489. /* Support PATH_INFO for CGI scripts. */
  3490. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3491. if (*p == '/') {
  3492. *p = '\0';
  3493. if ((0
  3494. #if !defined(NO_CGI)
  3495. ||
  3496. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3497. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3498. filename) > 0
  3499. #endif
  3500. #if defined(USE_LUA)
  3501. ||
  3502. match_prefix(
  3503. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3504. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3505. filename) > 0
  3506. #endif
  3507. ) &&
  3508. mg_stat(conn, filename, filep)) {
  3509. /* Shift PATH_INFO block one character right, e.g.
  3510. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3511. * conn->path_info is pointing to the local variable "path"
  3512. * declared in handle_request(), so PATH_INFO is not valid
  3513. * after handle_request returns. */
  3514. conn->path_info = p + 1;
  3515. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3516. * trailing \0 */
  3517. p[1] = '/';
  3518. *is_script_ressource = 1;
  3519. break;
  3520. } else {
  3521. *p = '/';
  3522. }
  3523. }
  3524. }
  3525. #endif /* !defined(NO_CGI) || defined(USE_LUA) */
  3526. #endif /* !defined(NO_FILES) */
  3527. }
  3528. return;
  3529. #if !defined(NO_FILES)
  3530. /* Reset all outputs */
  3531. interpret_cleanup:
  3532. memset(filep, 0, sizeof(*filep));
  3533. *filename = 0;
  3534. *is_found = 0;
  3535. *is_script_ressource = 0;
  3536. #endif
  3537. }
  3538. /* Check whether full request is buffered. Return:
  3539. * -1 if request is malformed
  3540. * 0 if request is not yet fully buffered
  3541. * >0 actual request length, including last \r\n\r\n */
  3542. static int get_request_len(const char *buf, int buflen)
  3543. {
  3544. const char *s, *e;
  3545. int len = 0;
  3546. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3547. /* Control characters are not allowed but >=128 is. */
  3548. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n' &&
  3549. *(const unsigned char *)s < 128) {
  3550. len = -1;
  3551. break; /* [i_a] abort scan as soon as one malformed character is
  3552. * found; */
  3553. /* don't let subsequent \r\n\r\n win us over anyhow */
  3554. } else if (s[0] == '\n' && s[1] == '\n') {
  3555. len = (int)(s - buf) + 2;
  3556. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3557. len = (int)(s - buf) + 3;
  3558. }
  3559. return len;
  3560. }
  3561. /* Convert month to the month number. Return -1 on error, or month number */
  3562. static int get_month_index(const char *s)
  3563. {
  3564. size_t i;
  3565. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  3566. if (!strcmp(s, month_names[i])) {
  3567. return (int)i;
  3568. }
  3569. }
  3570. return -1;
  3571. }
  3572. static int num_leap_years(int year)
  3573. {
  3574. return year / 4 - year / 100 + year / 400;
  3575. }
  3576. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3577. static time_t parse_date_string(const char *datetime)
  3578. {
  3579. static const unsigned short days_before_month[] = {
  3580. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3581. char month_str[32] = {0};
  3582. int second, minute, hour, day, month, year, leap_days, days;
  3583. time_t result = (time_t)0;
  3584. if ((sscanf(datetime,
  3585. "%d/%3s/%d %d:%d:%d",
  3586. &day,
  3587. month_str,
  3588. &year,
  3589. &hour,
  3590. &minute,
  3591. &second) == 6) ||
  3592. (sscanf(datetime,
  3593. "%d %3s %d %d:%d:%d",
  3594. &day,
  3595. month_str,
  3596. &year,
  3597. &hour,
  3598. &minute,
  3599. &second) == 6) ||
  3600. (sscanf(datetime,
  3601. "%*3s, %d %3s %d %d:%d:%d",
  3602. &day,
  3603. month_str,
  3604. &year,
  3605. &hour,
  3606. &minute,
  3607. &second) == 6) ||
  3608. (sscanf(datetime,
  3609. "%d-%3s-%d %d:%d:%d",
  3610. &day,
  3611. month_str,
  3612. &year,
  3613. &hour,
  3614. &minute,
  3615. &second) == 6)) {
  3616. month = get_month_index(month_str);
  3617. if ((month >= 0) && (year > 1970)) {
  3618. leap_days = num_leap_years(year) - num_leap_years(1970);
  3619. year -= 1970;
  3620. days =
  3621. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3622. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600 +
  3623. minute * 60 + second;
  3624. }
  3625. }
  3626. return result;
  3627. }
  3628. /* Protect against directory disclosure attack by removing '..',
  3629. * excessive '/' and '\' characters */
  3630. static void remove_double_dots_and_double_slashes(char *s)
  3631. {
  3632. char *p = s;
  3633. while (*s != '\0') {
  3634. *p++ = *s++;
  3635. if (s[-1] == '/' || s[-1] == '\\') {
  3636. /* Skip all following slashes, backslashes and double-dots */
  3637. while (s[0] != '\0') {
  3638. if (s[0] == '/' || s[0] == '\\') {
  3639. s++;
  3640. } else if (s[0] == '.' && s[1] == '.') {
  3641. s += 2;
  3642. } else {
  3643. break;
  3644. }
  3645. }
  3646. }
  3647. }
  3648. *p = '\0';
  3649. }
  3650. static const struct {
  3651. const char *extension;
  3652. size_t ext_len;
  3653. const char *mime_type;
  3654. } builtin_mime_types[] = {
  3655. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  3656. * application types */
  3657. {".doc", 4, "application/msword"},
  3658. {".eps", 4, "application/postscript"},
  3659. {".exe", 4, "application/octet-stream"},
  3660. {".js", 3, "application/javascript"},
  3661. {".json", 5, "application/json"},
  3662. {".pdf", 4, "application/pdf"},
  3663. {".ps", 3, "application/postscript"},
  3664. {".rtf", 4, "application/rtf"},
  3665. {".xhtml", 6, "application/xhtml+xml"},
  3666. {".xsl", 4, "application/xml"},
  3667. {".xslt", 5, "application/xml"},
  3668. /* audio */
  3669. {".mp3", 4, "audio/mpeg"},
  3670. {".oga", 4, "audio/ogg"},
  3671. {".ogg", 4, "audio/ogg"},
  3672. /* image */
  3673. {".gif", 4, "image/gif"},
  3674. {".ief", 4, "image/ief"},
  3675. {".jpeg", 5, "image/jpeg"},
  3676. {".jpg", 4, "image/jpeg"},
  3677. {".jpm", 4, "image/jpm"},
  3678. {".jpx", 4, "image/jpx"},
  3679. {".png", 4, "image/png"},
  3680. {".svg", 4, "image/svg+xml"},
  3681. {".tif", 4, "image/tiff"},
  3682. {".tiff", 5, "image/tiff"},
  3683. /* model */
  3684. {".wrl", 4, "model/vrml"},
  3685. /* text */
  3686. {".css", 4, "text/css"},
  3687. {".csv", 4, "text/csv"},
  3688. {".htm", 4, "text/html"},
  3689. {".html", 5, "text/html"},
  3690. {".sgm", 4, "text/sgml"},
  3691. {".shtm", 5, "text/html"},
  3692. {".shtml", 6, "text/html"},
  3693. {".txt", 4, "text/plain"},
  3694. {".xml", 4, "text/xml"},
  3695. /* video */
  3696. {".mov", 4, "video/quicktime"},
  3697. {".mp4", 4, "video/mp4"},
  3698. {".mpeg", 5, "video/mpeg"},
  3699. {".mpg", 4, "video/mpeg"},
  3700. {".ogv", 4, "video/ogg"},
  3701. {".qt", 3, "video/quicktime"},
  3702. /* not registered types
  3703. * (http://reference.sitepoint.com/html/mime-types-full,
  3704. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  3705. {".arj", 4, "application/x-arj-compressed"},
  3706. {".gz", 3, "application/x-gunzip"},
  3707. {".rar", 4, "application/x-arj-compressed"},
  3708. {".swf", 4, "application/x-shockwave-flash"},
  3709. {".tar", 4, "application/x-tar"},
  3710. {".tgz", 4, "application/x-tar-gz"},
  3711. {".torrent", 8, "application/x-bittorrent"},
  3712. {".ppt", 4, "application/x-mspowerpoint"},
  3713. {".xls", 4, "application/x-msexcel"},
  3714. {".zip", 4, "application/x-zip-compressed"},
  3715. {".aac",
  3716. 4,
  3717. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  3718. {".aif", 4, "audio/x-aif"},
  3719. {".m3u", 4, "audio/x-mpegurl"},
  3720. {".mid", 4, "audio/x-midi"},
  3721. {".ra", 3, "audio/x-pn-realaudio"},
  3722. {".ram", 4, "audio/x-pn-realaudio"},
  3723. {".wav", 4, "audio/x-wav"},
  3724. {".bmp", 4, "image/bmp"},
  3725. {".ico", 4, "image/x-icon"},
  3726. {".pct", 4, "image/x-pct"},
  3727. {".pict", 5, "image/pict"},
  3728. {".rgb", 4, "image/x-rgb"},
  3729. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  3730. {".asf", 4, "video/x-ms-asf"},
  3731. {".avi", 4, "video/x-msvideo"},
  3732. {".m4v", 4, "video/x-m4v"},
  3733. {NULL, 0, NULL}};
  3734. const char *mg_get_builtin_mime_type(const char *path)
  3735. {
  3736. const char *ext;
  3737. size_t i, path_len;
  3738. path_len = strlen(path);
  3739. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  3740. ext = path + (path_len - builtin_mime_types[i].ext_len);
  3741. if (path_len > builtin_mime_types[i].ext_len &&
  3742. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  3743. return builtin_mime_types[i].mime_type;
  3744. }
  3745. }
  3746. return "text/plain";
  3747. }
  3748. /* Look at the "path" extension and figure what mime type it has.
  3749. * Store mime type in the vector. */
  3750. static void
  3751. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  3752. {
  3753. struct vec ext_vec, mime_vec;
  3754. const char *list, *ext;
  3755. size_t path_len;
  3756. path_len = strlen(path);
  3757. if (ctx == NULL || vec == NULL) {
  3758. return;
  3759. }
  3760. /* Scan user-defined mime types first, in case user wants to
  3761. * override default mime types. */
  3762. list = ctx->config[EXTRA_MIME_TYPES];
  3763. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  3764. /* ext now points to the path suffix */
  3765. ext = path + path_len - ext_vec.len;
  3766. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  3767. *vec = mime_vec;
  3768. return;
  3769. }
  3770. }
  3771. vec->ptr = mg_get_builtin_mime_type(path);
  3772. vec->len = strlen(vec->ptr);
  3773. }
  3774. /* Stringify binary data. Output buffer must be twice as big as input,
  3775. * because each byte takes 2 bytes in string representation */
  3776. static void bin2str(char *to, const unsigned char *p, size_t len)
  3777. {
  3778. static const char *hex = "0123456789abcdef";
  3779. for (; len--; p++) {
  3780. *to++ = hex[p[0] >> 4];
  3781. *to++ = hex[p[0] & 0x0f];
  3782. }
  3783. *to = '\0';
  3784. }
  3785. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  3786. char *mg_md5(char buf[33], ...)
  3787. {
  3788. md5_byte_t hash[16];
  3789. const char *p;
  3790. va_list ap;
  3791. md5_state_t ctx;
  3792. md5_init(&ctx);
  3793. va_start(ap, buf);
  3794. while ((p = va_arg(ap, const char *)) != NULL) {
  3795. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  3796. }
  3797. va_end(ap);
  3798. md5_finish(&ctx, hash);
  3799. bin2str(buf, hash, sizeof(hash));
  3800. return buf;
  3801. }
  3802. /* Check the user's password, return 1 if OK */
  3803. static int check_password(const char *method,
  3804. const char *ha1,
  3805. const char *uri,
  3806. const char *nonce,
  3807. const char *nc,
  3808. const char *cnonce,
  3809. const char *qop,
  3810. const char *response)
  3811. {
  3812. char ha2[32 + 1], expected_response[32 + 1];
  3813. /* Some of the parameters may be NULL */
  3814. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  3815. qop == NULL || response == NULL) {
  3816. return 0;
  3817. }
  3818. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  3819. /* TODO(lsm): check for authentication timeout */
  3820. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  3821. strlen(response) != 32
  3822. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  3823. ) {
  3824. return 0;
  3825. }
  3826. mg_md5(ha2, method, ":", uri, NULL);
  3827. mg_md5(expected_response,
  3828. ha1,
  3829. ":",
  3830. nonce,
  3831. ":",
  3832. nc,
  3833. ":",
  3834. cnonce,
  3835. ":",
  3836. qop,
  3837. ":",
  3838. ha2,
  3839. NULL);
  3840. return mg_strcasecmp(response, expected_response) == 0;
  3841. }
  3842. /* Use the global passwords file, if specified by auth_gpass option,
  3843. * or search for .htpasswd in the requested directory. */
  3844. static void
  3845. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  3846. {
  3847. if (conn != NULL && conn->ctx != NULL) {
  3848. char name[PATH_MAX];
  3849. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  3850. struct file file = STRUCT_FILE_INITIALIZER;
  3851. int truncated;
  3852. if (gpass != NULL) {
  3853. /* Use global passwords file */
  3854. if (!mg_fopen(conn, gpass, "r", filep)) {
  3855. #ifdef DEBUG
  3856. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  3857. #endif
  3858. }
  3859. /* Important: using local struct file to test path for is_directory
  3860. * flag. If filep is used, mg_stat() makes it appear as if auth file
  3861. * was opened. */
  3862. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  3863. mg_snprintf(conn,
  3864. &truncated,
  3865. name,
  3866. sizeof(name),
  3867. "%s/%s",
  3868. path,
  3869. PASSWORDS_FILE_NAME);
  3870. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  3871. #ifdef DEBUG
  3872. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3873. #endif
  3874. }
  3875. } else {
  3876. /* Try to find .htpasswd in requested directory. */
  3877. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  3878. if (e[0] == '/') {
  3879. break;
  3880. }
  3881. }
  3882. mg_snprintf(conn,
  3883. &truncated,
  3884. name,
  3885. sizeof(name),
  3886. "%.*s%s",
  3887. (int)(e - p),
  3888. p,
  3889. PASSWORDS_FILE_NAME);
  3890. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  3891. #ifdef DEBUG
  3892. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3893. #endif
  3894. }
  3895. }
  3896. }
  3897. }
  3898. /* Parsed Authorization header */
  3899. struct ah {
  3900. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  3901. };
  3902. /* Return 1 on success. Always initializes the ah structure. */
  3903. static int parse_auth_header(struct mg_connection *conn,
  3904. char *buf,
  3905. size_t buf_size,
  3906. struct ah *ah)
  3907. {
  3908. char *name, *value, *s;
  3909. const char *auth_header;
  3910. unsigned long nonce;
  3911. if (!ah || !conn) {
  3912. return 0;
  3913. }
  3914. (void)memset(ah, 0, sizeof(*ah));
  3915. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  3916. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  3917. return 0;
  3918. }
  3919. /* Make modifiable copy of the auth header */
  3920. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  3921. s = buf;
  3922. /* Parse authorization header */
  3923. for (;;) {
  3924. /* Gobble initial spaces */
  3925. while (isspace(*(unsigned char *)s)) {
  3926. s++;
  3927. }
  3928. name = skip_quoted(&s, "=", " ", 0);
  3929. /* Value is either quote-delimited, or ends at first comma or space. */
  3930. if (s[0] == '\"') {
  3931. s++;
  3932. value = skip_quoted(&s, "\"", " ", '\\');
  3933. if (s[0] == ',') {
  3934. s++;
  3935. }
  3936. } else {
  3937. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  3938. * spaces */
  3939. }
  3940. if (*name == '\0') {
  3941. break;
  3942. }
  3943. if (!strcmp(name, "username")) {
  3944. ah->user = value;
  3945. } else if (!strcmp(name, "cnonce")) {
  3946. ah->cnonce = value;
  3947. } else if (!strcmp(name, "response")) {
  3948. ah->response = value;
  3949. } else if (!strcmp(name, "uri")) {
  3950. ah->uri = value;
  3951. } else if (!strcmp(name, "qop")) {
  3952. ah->qop = value;
  3953. } else if (!strcmp(name, "nc")) {
  3954. ah->nc = value;
  3955. } else if (!strcmp(name, "nonce")) {
  3956. ah->nonce = value;
  3957. }
  3958. }
  3959. #ifndef NO_NONCE_CHECK
  3960. /* Convert the nonce from the client to a number and check it. */
  3961. /* Server side nonce check is valuable in all situations but one: if the
  3962. * server restarts frequently,
  3963. * but the client should not see that, so the server should accept nonces
  3964. * from
  3965. * previous starts. */
  3966. if (ah->nonce == NULL) {
  3967. return 0;
  3968. }
  3969. s = NULL;
  3970. nonce = strtoul(ah->nonce, &s, 10);
  3971. if ((s == NULL) || (*s != 0)) {
  3972. return 0;
  3973. }
  3974. nonce ^= (uintptr_t)(conn->ctx);
  3975. if (nonce < conn->ctx->start_time) {
  3976. /* nonce is from a previous start of the server and no longer valid
  3977. * (replay attack?) */
  3978. return 0;
  3979. }
  3980. if (nonce >= conn->ctx->start_time + conn->ctx->nonce_count) {
  3981. return 0;
  3982. }
  3983. #endif
  3984. /* CGI needs it as REMOTE_USER */
  3985. if (ah->user != NULL) {
  3986. conn->request_info.remote_user = mg_strdup(ah->user);
  3987. } else {
  3988. return 0;
  3989. }
  3990. return 1;
  3991. }
  3992. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  3993. {
  3994. char *eof;
  3995. size_t len;
  3996. char *memend;
  3997. if (!filep) {
  3998. return NULL;
  3999. }
  4000. if (filep->membuf != NULL && *p != NULL) {
  4001. memend = (char *)&filep->membuf[filep->size];
  4002. /* Search for \n from p till the end of stream */
  4003. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4004. if (eof != NULL) {
  4005. eof += 1; /* Include \n */
  4006. } else {
  4007. eof = memend; /* Copy remaining data */
  4008. }
  4009. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4010. memcpy(buf, *p, len);
  4011. buf[len] = '\0';
  4012. *p += len;
  4013. return len ? eof : NULL;
  4014. } else if (filep->fp != NULL) {
  4015. return fgets(buf, (int)size, filep->fp);
  4016. } else {
  4017. return NULL;
  4018. }
  4019. }
  4020. struct read_auth_file_struct {
  4021. struct mg_connection *conn;
  4022. struct ah ah;
  4023. char *domain;
  4024. char buf[256 + 256 + 40];
  4025. char *f_user;
  4026. char *f_domain;
  4027. char *f_ha1;
  4028. };
  4029. static int read_auth_file(struct file *filep,
  4030. struct read_auth_file_struct *workdata)
  4031. {
  4032. char *p;
  4033. int is_authorized = 0;
  4034. struct file fp;
  4035. size_t l;
  4036. if (!filep || !workdata) {
  4037. return 0;
  4038. }
  4039. /* Loop over passwords file */
  4040. p = (char *)filep->membuf;
  4041. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4042. l = strlen(workdata->buf);
  4043. while (l > 0) {
  4044. if (isspace(workdata->buf[l - 1]) ||
  4045. iscntrl(workdata->buf[l - 1])) {
  4046. l--;
  4047. workdata->buf[l] = 0;
  4048. } else
  4049. break;
  4050. }
  4051. if (l < 1) {
  4052. continue;
  4053. }
  4054. workdata->f_user = workdata->buf;
  4055. if (workdata->f_user[0] == ':') {
  4056. /* user names may not contain a ':' and may not be empty,
  4057. * so lines starting with ':' may be used for a special purpose */
  4058. if (workdata->f_user[1] == '#') {
  4059. /* :# is a comment */
  4060. continue;
  4061. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4062. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4063. is_authorized = read_auth_file(&fp, workdata);
  4064. mg_fclose(&fp);
  4065. } else {
  4066. mg_cry(workdata->conn,
  4067. "%s: cannot open authorization file: %s",
  4068. __func__,
  4069. workdata->buf);
  4070. }
  4071. continue;
  4072. }
  4073. /* everything is invalid for the moment (might change in the
  4074. * future) */
  4075. mg_cry(workdata->conn,
  4076. "%s: syntax error in authorization file: %s",
  4077. __func__,
  4078. workdata->buf);
  4079. continue;
  4080. }
  4081. workdata->f_domain = strchr(workdata->f_user, ':');
  4082. if (workdata->f_domain == 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_domain) = 0;
  4090. (workdata->f_domain)++;
  4091. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4092. if (workdata->f_ha1 == NULL) {
  4093. mg_cry(workdata->conn,
  4094. "%s: syntax error in authorization file: %s",
  4095. __func__,
  4096. workdata->buf);
  4097. continue;
  4098. }
  4099. *(workdata->f_ha1) = 0;
  4100. (workdata->f_ha1)++;
  4101. if (!strcmp(workdata->ah.user, workdata->f_user) &&
  4102. !strcmp(workdata->domain, workdata->f_domain)) {
  4103. return check_password(workdata->conn->request_info.request_method,
  4104. workdata->f_ha1,
  4105. workdata->ah.uri,
  4106. workdata->ah.nonce,
  4107. workdata->ah.nc,
  4108. workdata->ah.cnonce,
  4109. workdata->ah.qop,
  4110. workdata->ah.response);
  4111. }
  4112. }
  4113. return is_authorized;
  4114. }
  4115. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4116. static int authorize(struct mg_connection *conn, struct file *filep)
  4117. {
  4118. struct read_auth_file_struct workdata;
  4119. char buf[MG_BUF_LEN];
  4120. if (!conn || !conn->ctx) {
  4121. return 0;
  4122. }
  4123. memset(&workdata, 0, sizeof(workdata));
  4124. workdata.conn = conn;
  4125. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4126. return 0;
  4127. }
  4128. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4129. return read_auth_file(filep, &workdata);
  4130. }
  4131. /* Return 1 if request is authorised, 0 otherwise. */
  4132. static int check_authorization(struct mg_connection *conn, const char *path)
  4133. {
  4134. char fname[PATH_MAX];
  4135. struct vec uri_vec, filename_vec;
  4136. const char *list;
  4137. struct file file = STRUCT_FILE_INITIALIZER;
  4138. int authorized = 1, truncated;
  4139. if (!conn || !conn->ctx) {
  4140. return 0;
  4141. }
  4142. list = conn->ctx->config[PROTECT_URI];
  4143. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4144. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  4145. mg_snprintf(conn,
  4146. &truncated,
  4147. fname,
  4148. sizeof(fname),
  4149. "%.*s",
  4150. (int)filename_vec.len,
  4151. filename_vec.ptr);
  4152. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4153. mg_cry(conn,
  4154. "%s: cannot open %s: %s",
  4155. __func__,
  4156. fname,
  4157. strerror(errno));
  4158. }
  4159. break;
  4160. }
  4161. }
  4162. if (!is_file_opened(&file)) {
  4163. open_auth_file(conn, path, &file);
  4164. }
  4165. if (is_file_opened(&file)) {
  4166. authorized = authorize(conn, &file);
  4167. mg_fclose(&file);
  4168. }
  4169. return authorized;
  4170. }
  4171. static void send_authorization_request(struct mg_connection *conn)
  4172. {
  4173. char date[64];
  4174. time_t curtime = time(NULL);
  4175. if (conn && conn->ctx) {
  4176. unsigned long nonce = (unsigned long)(conn->ctx->start_time);
  4177. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4178. nonce += conn->ctx->nonce_count;
  4179. ++conn->ctx->nonce_count;
  4180. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4181. nonce ^= (uintptr_t)(conn->ctx);
  4182. conn->status_code = 401;
  4183. conn->must_close = 1;
  4184. gmt_time_string(date, sizeof(date), &curtime);
  4185. mg_printf(conn,
  4186. "HTTP/1.1 401 Unauthorized\r\n"
  4187. "Date: %s\r\n"
  4188. "Connection: %s\r\n"
  4189. "Content-Length: 0\r\n"
  4190. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4191. "nonce=\"%lu\"\r\n\r\n",
  4192. date,
  4193. suggest_connection_header(conn),
  4194. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4195. nonce);
  4196. }
  4197. }
  4198. #if !defined(NO_FILES)
  4199. static int is_authorized_for_put(struct mg_connection *conn)
  4200. {
  4201. if (conn) {
  4202. struct file file = STRUCT_FILE_INITIALIZER;
  4203. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4204. int ret = 0;
  4205. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4206. ret = authorize(conn, &file);
  4207. mg_fclose(&file);
  4208. }
  4209. return ret;
  4210. }
  4211. return 0;
  4212. }
  4213. #endif
  4214. int mg_modify_passwords_file(const char *fname,
  4215. const char *domain,
  4216. const char *user,
  4217. const char *pass)
  4218. {
  4219. int found, i;
  4220. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4221. FILE *fp, *fp2;
  4222. found = 0;
  4223. fp = fp2 = NULL;
  4224. /* Regard empty password as no password - remove user record. */
  4225. if (pass != NULL && pass[0] == '\0') {
  4226. pass = NULL;
  4227. }
  4228. /* Other arguments must not be empty */
  4229. if (fname == NULL || domain == NULL || user == NULL) {
  4230. return 0;
  4231. }
  4232. /* Using the given file format, user name and domain must not contain ':'
  4233. */
  4234. if (strchr(user, ':') != NULL) {
  4235. return 0;
  4236. }
  4237. if (strchr(domain, ':') != NULL) {
  4238. return 0;
  4239. }
  4240. /* Do not allow control characters like newline in user name and domain.
  4241. * Do not allow excessively long names either. */
  4242. for (i = 0; i < 255 && user[i] != 0; i++) {
  4243. if (iscntrl(user[i])) {
  4244. return 0;
  4245. }
  4246. }
  4247. if (user[i]) {
  4248. return 0;
  4249. }
  4250. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4251. if (iscntrl(domain[i])) {
  4252. return 0;
  4253. }
  4254. }
  4255. if (domain[i]) {
  4256. return 0;
  4257. }
  4258. /* The maximum length of the path to the password file is limited */
  4259. if ((strlen(fname) + 4) >= PATH_MAX) {
  4260. return 0;
  4261. }
  4262. /* Create a temporary file name. Length has been checked before. */
  4263. strcpy(tmp, fname);
  4264. strcat(tmp, ".tmp");
  4265. /* Create the file if does not exist */
  4266. if ((fp = fopen(fname, "a+")) != NULL) {
  4267. (void)fclose(fp);
  4268. }
  4269. /* Open the given file and temporary file */
  4270. if ((fp = fopen(fname, "r")) == NULL) {
  4271. return 0;
  4272. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4273. fclose(fp);
  4274. return 0;
  4275. }
  4276. /* Copy the stuff to temporary file */
  4277. while (fgets(line, sizeof(line), fp) != NULL) {
  4278. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4279. continue;
  4280. }
  4281. u[255] = 0;
  4282. d[255] = 0;
  4283. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4284. found++;
  4285. if (pass != NULL) {
  4286. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4287. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4288. }
  4289. } else {
  4290. fprintf(fp2, "%s", line);
  4291. }
  4292. }
  4293. /* If new user, just add it */
  4294. if (!found && pass != NULL) {
  4295. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4296. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4297. }
  4298. /* Close files */
  4299. fclose(fp);
  4300. fclose(fp2);
  4301. /* Put the temp file in place of real file */
  4302. IGNORE_UNUSED_RESULT(remove(fname));
  4303. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4304. return 1;
  4305. }
  4306. static int is_valid_port(unsigned int port) { return port < 0xffff; }
  4307. static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4308. {
  4309. struct addrinfo hints, *res, *ressave;
  4310. int ret = 0;
  4311. memset(&hints, 0, sizeof(struct addrinfo));
  4312. hints.ai_family = af;
  4313. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4314. /* bad src string or bad address family */
  4315. return 0;
  4316. }
  4317. ressave = res;
  4318. while (res) {
  4319. if (dstlen >= res->ai_addrlen) {
  4320. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4321. ret = 1;
  4322. }
  4323. res = res->ai_next;
  4324. }
  4325. freeaddrinfo(ressave);
  4326. return ret;
  4327. }
  4328. static int connect_socket(struct mg_context *ctx /* may be null */,
  4329. const char *host,
  4330. int port,
  4331. int use_ssl,
  4332. char *ebuf,
  4333. size_t ebuf_len,
  4334. SOCKET *sock /* output: socket */,
  4335. union usa *sa /* output: socket address */
  4336. )
  4337. {
  4338. int ip_ver = 0;
  4339. *sock = INVALID_SOCKET;
  4340. memset(sa, 0, sizeof(*sa));
  4341. if (ebuf_len > 0) {
  4342. *ebuf = 0;
  4343. }
  4344. if (host == NULL) {
  4345. mg_snprintf(NULL,
  4346. NULL, /* No truncation check for ebuf */
  4347. ebuf,
  4348. ebuf_len,
  4349. "%s",
  4350. "NULL host");
  4351. return 0;
  4352. }
  4353. if (port < 0 || !is_valid_port((unsigned)port)) {
  4354. mg_snprintf(NULL,
  4355. NULL, /* No truncation check for ebuf */
  4356. ebuf,
  4357. ebuf_len,
  4358. "%s",
  4359. "invalid port");
  4360. return 0;
  4361. }
  4362. if (use_ssl && (SSLv23_client_method == NULL)) {
  4363. mg_snprintf(NULL,
  4364. NULL, /* No truncation check for ebuf */
  4365. ebuf,
  4366. ebuf_len,
  4367. "%s",
  4368. "SSL is not initialized");
  4369. return 0;
  4370. }
  4371. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4372. sa->sin.sin_port = htons((uint16_t)port);
  4373. ip_ver = 4;
  4374. #ifdef USE_IPV6
  4375. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4376. sa->sin6.sin6_port = htons((uint16_t)port);
  4377. ip_ver = 6;
  4378. } else if (host[0] == '[') {
  4379. /* While getaddrinfo on Windows will work with [::1],
  4380. * getaddrinfo on Linux only works with ::1 (without []). */
  4381. size_t l = strlen(host + 1);
  4382. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4383. if (h) {
  4384. h[l - 1] = 0;
  4385. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4386. sa->sin6.sin6_port = htons((uint16_t)port);
  4387. ip_ver = 6;
  4388. }
  4389. mg_free(h);
  4390. }
  4391. #endif
  4392. }
  4393. if (ip_ver == 0) {
  4394. mg_snprintf(NULL,
  4395. NULL, /* No truncation check for ebuf */
  4396. ebuf,
  4397. ebuf_len,
  4398. "%s",
  4399. "host not found");
  4400. return 0;
  4401. }
  4402. if (ip_ver == 4) {
  4403. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4404. }
  4405. #ifdef USE_IPV6
  4406. else if (ip_ver == 6) {
  4407. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4408. }
  4409. #endif
  4410. if (*sock == INVALID_SOCKET) {
  4411. mg_snprintf(NULL,
  4412. NULL, /* No truncation check for ebuf */
  4413. ebuf,
  4414. ebuf_len,
  4415. "socket(): %s",
  4416. strerror(ERRNO));
  4417. return 0;
  4418. }
  4419. set_close_on_exec(*sock, fc(ctx));
  4420. if ((ip_ver == 4) &&
  4421. (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin)) == 0)) {
  4422. /* connected with IPv4 */
  4423. return 1;
  4424. }
  4425. #ifdef USE_IPV6
  4426. if ((ip_ver == 6) &&
  4427. (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6)) == 0)) {
  4428. /* connected with IPv6 */
  4429. return 1;
  4430. }
  4431. #endif
  4432. /* Not connected */
  4433. mg_snprintf(NULL,
  4434. NULL, /* No truncation check for ebuf */
  4435. ebuf,
  4436. ebuf_len,
  4437. "connect(%s:%d): %s",
  4438. host,
  4439. port,
  4440. strerror(ERRNO));
  4441. closesocket(*sock);
  4442. *sock = INVALID_SOCKET;
  4443. return 0;
  4444. }
  4445. int mg_url_encode(const char *src, char *dst, size_t dst_len)
  4446. {
  4447. static const char *dont_escape = "._-$,;~()";
  4448. static const char *hex = "0123456789abcdef";
  4449. char *pos = dst;
  4450. const char *end = dst + dst_len - 1;
  4451. for (; *src != '\0' && pos < end; src++, pos++) {
  4452. if (isalnum(*(const unsigned char *)src) ||
  4453. strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4454. *pos = *src;
  4455. } else if (pos + 2 < end) {
  4456. pos[0] = '%';
  4457. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4458. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4459. pos += 2;
  4460. } else {
  4461. break;
  4462. }
  4463. }
  4464. *pos = '\0';
  4465. return (*src == '\0') ? (int)(pos - dst) : -1;
  4466. }
  4467. static void print_dir_entry(struct de *de)
  4468. {
  4469. char size[64], mod[64], href[PATH_MAX];
  4470. struct tm *tm;
  4471. if (de->file.is_directory) {
  4472. mg_snprintf(de->conn,
  4473. NULL, /* Buffer is big enough */
  4474. size,
  4475. sizeof(size),
  4476. "%s",
  4477. "[DIRECTORY]");
  4478. } else {
  4479. /* We use (signed) cast below because MSVC 6 compiler cannot
  4480. * convert unsigned __int64 to double. Sigh. */
  4481. if (de->file.size < 1024) {
  4482. mg_snprintf(de->conn,
  4483. NULL, /* Buffer is big enough */
  4484. size,
  4485. sizeof(size),
  4486. "%d",
  4487. (int)de->file.size);
  4488. } else if (de->file.size < 0x100000) {
  4489. mg_snprintf(de->conn,
  4490. NULL, /* Buffer is big enough */
  4491. size,
  4492. sizeof(size),
  4493. "%.1fk",
  4494. (double)de->file.size / 1024.0);
  4495. } else if (de->file.size < 0x40000000) {
  4496. mg_snprintf(de->conn,
  4497. NULL, /* Buffer is big enough */
  4498. size,
  4499. sizeof(size),
  4500. "%.1fM",
  4501. (double)de->file.size / 1048576);
  4502. } else {
  4503. mg_snprintf(de->conn,
  4504. NULL, /* Buffer is big enough */
  4505. size,
  4506. sizeof(size),
  4507. "%.1fG",
  4508. (double)de->file.size / 1073741824);
  4509. }
  4510. }
  4511. /* Note: mg_snprintf will not cause a buffer overflow above.
  4512. * So, string truncation checks are not required here. */
  4513. tm = localtime(&de->file.last_modified);
  4514. if (tm != NULL) {
  4515. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4516. } else {
  4517. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4518. mod[sizeof(mod) - 1] = '\0';
  4519. }
  4520. mg_url_encode(de->file_name, href, sizeof(href));
  4521. de->conn->num_bytes_sent +=
  4522. mg_printf(de->conn,
  4523. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4524. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4525. de->conn->request_info.uri,
  4526. href,
  4527. de->file.is_directory ? "/" : "",
  4528. de->file_name,
  4529. de->file.is_directory ? "/" : "",
  4530. mod,
  4531. size);
  4532. }
  4533. /* This function is called from send_directory() and used for
  4534. * sorting directory entries by size, or name, or modification time.
  4535. * On windows, __cdecl specification is needed in case if project is built
  4536. * with __stdcall convention. qsort always requires __cdels callback. */
  4537. static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
  4538. {
  4539. if (p1 && p2) {
  4540. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4541. const char *query_string = a->conn->request_info.query_string;
  4542. int cmp_result = 0;
  4543. if (query_string == NULL) {
  4544. query_string = "na";
  4545. }
  4546. if (a->file.is_directory && !b->file.is_directory) {
  4547. return -1; /* Always put directories on top */
  4548. } else if (!a->file.is_directory && b->file.is_directory) {
  4549. return 1; /* Always put directories on top */
  4550. } else if (*query_string == 'n') {
  4551. cmp_result = strcmp(a->file_name, b->file_name);
  4552. } else if (*query_string == 's') {
  4553. cmp_result = a->file.size == b->file.size
  4554. ? 0
  4555. : a->file.size > b->file.size ? 1 : -1;
  4556. } else if (*query_string == 'd') {
  4557. cmp_result =
  4558. (a->file.last_modified == b->file.last_modified)
  4559. ? 0
  4560. : ((a->file.last_modified > b->file.last_modified) ? 1
  4561. : -1);
  4562. }
  4563. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  4564. }
  4565. return 0;
  4566. }
  4567. static int must_hide_file(struct mg_connection *conn, const char *path)
  4568. {
  4569. if (conn && conn->ctx) {
  4570. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  4571. const char *pattern = conn->ctx->config[HIDE_FILES];
  4572. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  4573. (pattern != NULL &&
  4574. match_prefix(pattern, strlen(pattern), path) > 0);
  4575. }
  4576. return 0;
  4577. }
  4578. static int scan_directory(struct mg_connection *conn,
  4579. const char *dir,
  4580. void *data,
  4581. void (*cb)(struct de *, void *))
  4582. {
  4583. char path[PATH_MAX];
  4584. struct dirent *dp;
  4585. DIR *dirp;
  4586. struct de de;
  4587. int truncated;
  4588. if ((dirp = opendir(dir)) == NULL) {
  4589. return 0;
  4590. } else {
  4591. de.conn = conn;
  4592. while ((dp = readdir(dirp)) != NULL) {
  4593. /* Do not show current dir and hidden files */
  4594. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") ||
  4595. must_hide_file(conn, dp->d_name)) {
  4596. continue;
  4597. }
  4598. mg_snprintf(
  4599. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  4600. /* If we don't memset stat structure to zero, mtime will have
  4601. * garbage and strftime() will segfault later on in
  4602. * print_dir_entry(). memset is required only if mg_stat()
  4603. * fails. For more details, see
  4604. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4605. memset(&de.file, 0, sizeof(de.file));
  4606. if (truncated) {
  4607. /* If the path is not complete, skip processing. */
  4608. continue;
  4609. }
  4610. if (!mg_stat(conn, path, &de.file)) {
  4611. mg_cry(conn,
  4612. "%s: mg_stat(%s) failed: %s",
  4613. __func__,
  4614. path,
  4615. strerror(ERRNO));
  4616. }
  4617. de.file_name = dp->d_name;
  4618. cb(&de, data);
  4619. }
  4620. (void)closedir(dirp);
  4621. }
  4622. return 1;
  4623. }
  4624. #if !defined(NO_FILES)
  4625. static int remove_directory(struct mg_connection *conn, const char *dir)
  4626. {
  4627. char path[PATH_MAX];
  4628. struct dirent *dp;
  4629. DIR *dirp;
  4630. struct de de;
  4631. int truncated;
  4632. int ok = 1;
  4633. if ((dirp = opendir(dir)) == NULL) {
  4634. return 0;
  4635. } else {
  4636. de.conn = conn;
  4637. while ((dp = readdir(dirp)) != NULL) {
  4638. /* Do not show current dir (but show hidden files as they will
  4639. * also be removed) */
  4640. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  4641. continue;
  4642. }
  4643. mg_snprintf(
  4644. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  4645. /* If we don't memset stat structure to zero, mtime will have
  4646. * garbage and strftime() will segfault later on in
  4647. * print_dir_entry(). memset is required only if mg_stat()
  4648. * fails. For more details, see
  4649. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4650. memset(&de.file, 0, sizeof(de.file));
  4651. if (truncated) {
  4652. /* Do not delete anything shorter */
  4653. continue;
  4654. }
  4655. if (!mg_stat(conn, path, &de.file)) {
  4656. mg_cry(conn,
  4657. "%s: mg_stat(%s) failed: %s",
  4658. __func__,
  4659. path,
  4660. strerror(ERRNO));
  4661. }
  4662. if (de.file.membuf == NULL) {
  4663. /* file is not in memory */
  4664. if (de.file.is_directory) {
  4665. if (remove_directory(conn, path) == 0) {
  4666. ok = 0;
  4667. }
  4668. } else {
  4669. if (mg_remove(path) == 0) {
  4670. ok = 0;
  4671. }
  4672. }
  4673. }
  4674. }
  4675. (void)closedir(dirp);
  4676. IGNORE_UNUSED_RESULT(rmdir(dir));
  4677. }
  4678. return ok;
  4679. }
  4680. #endif
  4681. struct dir_scan_data {
  4682. struct de *entries;
  4683. unsigned int num_entries;
  4684. unsigned int arr_size;
  4685. };
  4686. /* Behaves like realloc(), but frees original pointer on failure */
  4687. static void *realloc2(void *ptr, size_t size)
  4688. {
  4689. void *new_ptr = mg_realloc(ptr, size);
  4690. if (new_ptr == NULL) {
  4691. mg_free(ptr);
  4692. }
  4693. return new_ptr;
  4694. }
  4695. static void dir_scan_callback(struct de *de, void *data)
  4696. {
  4697. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  4698. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  4699. dsd->arr_size *= 2;
  4700. dsd->entries = (struct de *)realloc2(
  4701. dsd->entries, dsd->arr_size * sizeof(dsd->entries[0]));
  4702. }
  4703. if (dsd->entries == NULL) {
  4704. /* TODO(lsm, low): propagate an error to the caller */
  4705. dsd->num_entries = 0;
  4706. } else {
  4707. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  4708. dsd->entries[dsd->num_entries].file = de->file;
  4709. dsd->entries[dsd->num_entries].conn = de->conn;
  4710. dsd->num_entries++;
  4711. }
  4712. }
  4713. static void handle_directory_request(struct mg_connection *conn,
  4714. const char *dir)
  4715. {
  4716. unsigned int i;
  4717. int sort_direction;
  4718. struct dir_scan_data data = {NULL, 0, 128};
  4719. char date[64];
  4720. time_t curtime = time(NULL);
  4721. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  4722. send_http_error(conn,
  4723. 500,
  4724. "Error: Cannot open directory\nopendir(%s): %s",
  4725. dir,
  4726. strerror(ERRNO));
  4727. return;
  4728. }
  4729. gmt_time_string(date, sizeof(date), &curtime);
  4730. if (!conn) {
  4731. return;
  4732. }
  4733. sort_direction = conn->request_info.query_string != NULL &&
  4734. conn->request_info.query_string[1] == 'd'
  4735. ? 'a'
  4736. : 'd';
  4737. conn->must_close = 1;
  4738. mg_printf(conn,
  4739. "HTTP/1.1 200 OK\r\n"
  4740. "Date: %s\r\n"
  4741. "Connection: close\r\n"
  4742. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  4743. date);
  4744. conn->num_bytes_sent +=
  4745. mg_printf(conn,
  4746. "<html><head><title>Index of %s</title>"
  4747. "<style>th {text-align: left;}</style></head>"
  4748. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  4749. "<tr><th><a href=\"?n%c\">Name</a></th>"
  4750. "<th><a href=\"?d%c\">Modified</a></th>"
  4751. "<th><a href=\"?s%c\">Size</a></th></tr>"
  4752. "<tr><td colspan=\"3\"><hr></td></tr>",
  4753. conn->request_info.uri,
  4754. conn->request_info.uri,
  4755. sort_direction,
  4756. sort_direction,
  4757. sort_direction);
  4758. /* Print first entry - link to a parent directory */
  4759. conn->num_bytes_sent +=
  4760. mg_printf(conn,
  4761. "<tr><td><a href=\"%s%s\">%s</a></td>"
  4762. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4763. conn->request_info.uri,
  4764. "..",
  4765. "Parent directory",
  4766. "-",
  4767. "-");
  4768. /* Sort and print directory entries */
  4769. if (data.entries != NULL) {
  4770. qsort(data.entries,
  4771. (size_t)data.num_entries,
  4772. sizeof(data.entries[0]),
  4773. compare_dir_entries);
  4774. for (i = 0; i < data.num_entries; i++) {
  4775. print_dir_entry(&data.entries[i]);
  4776. mg_free(data.entries[i].file_name);
  4777. }
  4778. mg_free(data.entries);
  4779. }
  4780. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  4781. conn->status_code = 200;
  4782. }
  4783. /* Send len bytes from the opened file to the client. */
  4784. static void send_file_data(struct mg_connection *conn,
  4785. struct file *filep,
  4786. int64_t offset,
  4787. int64_t len)
  4788. {
  4789. char buf[MG_BUF_LEN];
  4790. int to_read, num_read, num_written;
  4791. int64_t size;
  4792. if (!filep || !conn) {
  4793. return;
  4794. }
  4795. /* Sanity check the offset */
  4796. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  4797. offset = offset < 0 ? 0 : offset > size ? size : offset;
  4798. if (len > 0 && filep->membuf != NULL && size > 0) {
  4799. /* file stored in memory */
  4800. if (len > size - offset) {
  4801. len = size - offset;
  4802. }
  4803. mg_write(conn, filep->membuf + offset, (size_t)len);
  4804. } else if (len > 0 && filep->fp != NULL) {
  4805. /* file stored on disk */
  4806. #if defined(__linux__)
  4807. /* TODO (high): Test sendfile for Linux */
  4808. if (conn->throttle == 0 && conn->ssl == 0) {
  4809. off_t sf_offs = (off_t)offset;
  4810. ssize_t sf_sent;
  4811. int sf_file = fileno(filep->fp);
  4812. int loop_cnt = 0;
  4813. do {
  4814. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  4815. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  4816. size_t sf_tosend =
  4817. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  4818. sf_sent =
  4819. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  4820. if (sf_sent > 0) {
  4821. conn->num_bytes_sent += sf_sent;
  4822. len -= sf_sent;
  4823. offset += sf_sent;
  4824. } else if (loop_cnt == 0) {
  4825. /* This file can not be sent using sendfile.
  4826. * This might be the case for pseudo-files in the
  4827. * /sys/ and /proc/ file system.
  4828. * Use the regular user mode copy code instead. */
  4829. break;
  4830. } else if (sf_sent == 0) {
  4831. /* No error, but 0 bytes sent. May be EOF? */
  4832. mg_sleep(1);
  4833. loop_cnt = -1;
  4834. /* TODO(high): Maybe just return here. --> Test required */
  4835. }
  4836. loop_cnt++;
  4837. } while ((len > 0) && (sf_sent >= 0));
  4838. if (sf_sent > 0) {
  4839. return; /* OK */
  4840. }
  4841. /* sf_sent<0 means error, thus fall back to the classic way */
  4842. mg_cry(conn,
  4843. "%s: sendfile() failed: %s (now trying read+write)",
  4844. __func__,
  4845. strerror(ERRNO));
  4846. offset = (int64_t)sf_offs;
  4847. }
  4848. #endif
  4849. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  4850. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  4851. send_http_error(
  4852. conn,
  4853. 500,
  4854. "%s",
  4855. "Error: Unable to access file at requested position.");
  4856. } else {
  4857. while (len > 0) {
  4858. /* Calculate how much to read from the file in the buffer */
  4859. to_read = sizeof(buf);
  4860. if ((int64_t)to_read > len) {
  4861. to_read = (int)len;
  4862. }
  4863. /* Read from file, exit the loop on error */
  4864. if ((num_read =
  4865. (int)fread(buf, 1, (size_t)to_read, filep->fp)) <= 0) {
  4866. break;
  4867. }
  4868. /* Send read bytes to the client, exit the loop on error */
  4869. if ((num_written = mg_write(conn, buf, (size_t)num_read)) !=
  4870. num_read) {
  4871. break;
  4872. }
  4873. /* Both read and were successful, adjust counters */
  4874. conn->num_bytes_sent += num_written;
  4875. len -= num_written;
  4876. }
  4877. }
  4878. }
  4879. }
  4880. static int parse_range_header(const char *header, int64_t *a, int64_t *b)
  4881. {
  4882. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  4883. }
  4884. static void construct_etag(char *buf, size_t buf_len, const struct file *filep)
  4885. {
  4886. if (filep != NULL && buf != NULL) {
  4887. mg_snprintf(NULL,
  4888. NULL, /* All calls to construct_etag use 64 byte buffer */
  4889. buf,
  4890. buf_len,
  4891. "\"%lx.%" INT64_FMT "\"",
  4892. (unsigned long)filep->last_modified,
  4893. filep->size);
  4894. }
  4895. }
  4896. static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
  4897. {
  4898. if (filep != NULL && filep->fp != NULL) {
  4899. #ifdef _WIN32
  4900. (void)conn; /* Unused. */
  4901. #else
  4902. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  4903. mg_cry(conn,
  4904. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4905. __func__,
  4906. strerror(ERRNO));
  4907. }
  4908. #endif
  4909. }
  4910. }
  4911. static void handle_static_file_request(struct mg_connection *conn,
  4912. const char *path,
  4913. struct file *filep)
  4914. {
  4915. char date[64], lm[64], etag[64];
  4916. char range[128]; /* large enough, so there will be no overflow */
  4917. const char *msg = "OK", *hdr;
  4918. time_t curtime = time(NULL);
  4919. int64_t cl, r1, r2;
  4920. struct vec mime_vec;
  4921. int n, truncated;
  4922. char gz_path[PATH_MAX];
  4923. const char *encoding = "";
  4924. const char *cors1, *cors2, *cors3;
  4925. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  4926. return;
  4927. }
  4928. get_mime_type(conn->ctx, path, &mime_vec);
  4929. if (filep->size > INT64_MAX) {
  4930. send_http_error(conn,
  4931. 500,
  4932. "Error: File size is too large to send\n%" INT64_FMT,
  4933. filep->size);
  4934. }
  4935. cl = (int64_t)filep->size;
  4936. conn->status_code = 200;
  4937. range[0] = '\0';
  4938. /* if this file is in fact a pre-gzipped file, rewrite its filename
  4939. * it's important to rewrite the filename after resolving
  4940. * the mime type from it, to preserve the actual file's type */
  4941. if (filep->gzipped) {
  4942. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  4943. if (truncated) {
  4944. send_http_error(
  4945. conn, 500, "Error: Path of zipped file too long (%s)", path);
  4946. return;
  4947. }
  4948. path = gz_path;
  4949. encoding = "Content-Encoding: gzip\r\n";
  4950. }
  4951. if (!mg_fopen(conn, path, "rb", filep)) {
  4952. send_http_error(conn,
  4953. 500,
  4954. "Error: Cannot open file\nfopen(%s): %s",
  4955. path,
  4956. strerror(ERRNO));
  4957. return;
  4958. }
  4959. fclose_on_exec(filep, conn);
  4960. /* If Range: header specified, act accordingly */
  4961. r1 = r2 = 0;
  4962. hdr = mg_get_header(conn, "Range");
  4963. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  4964. r2 >= 0) {
  4965. /* actually, range requests don't play well with a pre-gzipped
  4966. * file (since the range is specified in the uncompressed space) */
  4967. if (filep->gzipped) {
  4968. send_http_error(
  4969. conn,
  4970. 501,
  4971. "%s",
  4972. "Error: Range requests in gzipped files are not supported");
  4973. mg_fclose(filep);
  4974. return;
  4975. }
  4976. conn->status_code = 206;
  4977. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  4978. mg_snprintf(conn,
  4979. NULL, /* range buffer is big enough */
  4980. range,
  4981. sizeof(range),
  4982. "Content-Range: bytes "
  4983. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  4984. r1,
  4985. r1 + cl - 1,
  4986. filep->size);
  4987. msg = "Partial Content";
  4988. }
  4989. hdr = mg_get_header(conn, "Origin");
  4990. if (hdr) {
  4991. /* Cross-origin resource sharing (CORS), see
  4992. * http://www.html5rocks.com/en/tutorials/cors/,
  4993. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  4994. * preflight is not supported for files. */
  4995. cors1 = "Access-Control-Allow-Origin: ";
  4996. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  4997. cors3 = "\r\n";
  4998. } else {
  4999. cors1 = cors2 = cors3 = "";
  5000. }
  5001. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5002. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5003. gmt_time_string(date, sizeof(date), &curtime);
  5004. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5005. construct_etag(etag, sizeof(etag), filep);
  5006. (void)mg_printf(conn,
  5007. "HTTP/1.1 %d %s\r\n"
  5008. "%s%s%s"
  5009. "Date: %s\r\n"
  5010. "Last-Modified: %s\r\n"
  5011. "Etag: %s\r\n"
  5012. "Content-Type: %.*s\r\n"
  5013. "Content-Length: %" INT64_FMT "\r\n"
  5014. "Connection: %s\r\n"
  5015. "Accept-Ranges: bytes\r\n"
  5016. "%s%s\r\n",
  5017. conn->status_code,
  5018. msg,
  5019. cors1,
  5020. cors2,
  5021. cors3,
  5022. date,
  5023. lm,
  5024. etag,
  5025. (int)mime_vec.len,
  5026. mime_vec.ptr,
  5027. cl,
  5028. suggest_connection_header(conn),
  5029. range,
  5030. encoding);
  5031. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5032. send_file_data(conn, filep, r1, cl);
  5033. }
  5034. mg_fclose(filep);
  5035. }
  5036. void mg_send_file(struct mg_connection *conn, const char *path)
  5037. {
  5038. struct file file = STRUCT_FILE_INITIALIZER;
  5039. if (mg_stat(conn, path, &file)) {
  5040. if (file.is_directory) {
  5041. if (!conn) {
  5042. return;
  5043. }
  5044. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5045. "yes")) {
  5046. handle_directory_request(conn, path);
  5047. } else {
  5048. send_http_error(
  5049. conn, 403, "%s", "Error: Directory listing denied");
  5050. }
  5051. } else {
  5052. handle_static_file_request(conn, path, &file);
  5053. }
  5054. } else {
  5055. send_http_error(conn, 404, "%s", "Error: File not found");
  5056. }
  5057. }
  5058. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5059. * where parsing stopped. */
  5060. static void parse_http_headers(char **buf, struct mg_request_info *ri)
  5061. {
  5062. int i;
  5063. if (!ri) {
  5064. return;
  5065. }
  5066. ri->num_headers = 0;
  5067. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5068. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  5069. ri->http_headers[i].value = skip(buf, "\r\n");
  5070. if (ri->http_headers[i].name[0] == '\0') {
  5071. break;
  5072. }
  5073. ri->num_headers = i + 1;
  5074. }
  5075. }
  5076. static int is_valid_http_method(const char *method)
  5077. {
  5078. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  5079. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  5080. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  5081. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND") ||
  5082. !strcmp(method, "MKCOL") || !strcmp(method, "PATCH");
  5083. /* TRACE method is not supported for security reasons */
  5084. /* PATCH method (RFC 5789) only allowed for CGI/Lua/LSP and callbacks. */
  5085. }
  5086. /* Parse HTTP request, fill in mg_request_info structure.
  5087. * This function modifies the buffer by NUL-terminating
  5088. * HTTP request components, header names and header values. */
  5089. static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5090. {
  5091. int is_request, request_length;
  5092. if (!ri) {
  5093. return 0;
  5094. }
  5095. request_length = get_request_len(buf, len);
  5096. if (request_length > 0) {
  5097. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5098. * remote_port */
  5099. ri->remote_user = ri->request_method = ri->uri = ri->http_version =
  5100. NULL;
  5101. ri->num_headers = 0;
  5102. buf[request_length - 1] = '\0';
  5103. /* RFC says that all initial whitespaces should be ingored */
  5104. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5105. buf++;
  5106. }
  5107. ri->request_method = skip(&buf, " ");
  5108. ri->uri = skip(&buf, " ");
  5109. ri->http_version = skip(&buf, "\r\n");
  5110. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5111. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5112. is_request = is_valid_http_method(ri->request_method);
  5113. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  5114. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5115. request_length = -1;
  5116. } else {
  5117. if (is_request) {
  5118. ri->http_version += 5;
  5119. }
  5120. parse_http_headers(&buf, ri);
  5121. }
  5122. }
  5123. return request_length;
  5124. }
  5125. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5126. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5127. * buffer (which marks the end of HTTP request). Buffer buf may already
  5128. * have some data. The length of the data is stored in nread.
  5129. * Upon every read operation, increase nread by the number of bytes read. */
  5130. static int read_request(
  5131. FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread)
  5132. {
  5133. int request_len, n = 0;
  5134. struct timespec last_action_time = {0, 0};
  5135. double request_timeout;
  5136. if (!conn) {
  5137. return 0;
  5138. }
  5139. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5140. /* value of request_timeout is in seconds, config in milliseconds */
  5141. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5142. } else {
  5143. request_timeout = -1.0;
  5144. }
  5145. request_len = get_request_len(buf, *nread);
  5146. while (
  5147. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) &&
  5148. (request_len == 0) &&
  5149. ((mg_difftimespec(&last_action_time, &(conn->req_time)) <=
  5150. request_timeout) ||
  5151. (request_timeout < 0)) &&
  5152. ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout)) >
  5153. 0)) {
  5154. *nread += n;
  5155. /* assert(*nread <= bufsiz); */
  5156. if (*nread > bufsiz) {
  5157. return -2;
  5158. }
  5159. request_len = get_request_len(buf, *nread);
  5160. if (request_timeout > 0.0) {
  5161. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5162. }
  5163. }
  5164. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5165. }
  5166. #if !defined(NO_FILES)
  5167. /* For given directory path, substitute it to valid index file.
  5168. * Return 1 if index file has been found, 0 if not found.
  5169. * If the file is found, it's stats is returned in stp. */
  5170. static int substitute_index_file(struct mg_connection *conn,
  5171. char *path,
  5172. size_t path_len,
  5173. struct file *filep)
  5174. {
  5175. if (conn && conn->ctx) {
  5176. const char *list = conn->ctx->config[INDEX_FILES];
  5177. struct file file = STRUCT_FILE_INITIALIZER;
  5178. struct vec filename_vec;
  5179. size_t n = strlen(path);
  5180. int found = 0;
  5181. /* The 'path' given to us points to the directory. Remove all trailing
  5182. * directory separator characters from the end of the path, and
  5183. * then append single directory separator character. */
  5184. while (n > 0 && path[n - 1] == '/') {
  5185. n--;
  5186. }
  5187. path[n] = '/';
  5188. /* Traverse index files list. For each entry, append it to the given
  5189. * path and see if the file exists. If it exists, break the loop */
  5190. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5191. /* Ignore too long entries that may overflow path buffer */
  5192. if (filename_vec.len > path_len - (n + 2)) {
  5193. continue;
  5194. }
  5195. /* Prepare full path to the index file */
  5196. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5197. /* Does it exist? */
  5198. if (mg_stat(conn, path, &file)) {
  5199. /* Yes it does, break the loop */
  5200. *filep = file;
  5201. found = 1;
  5202. break;
  5203. }
  5204. }
  5205. /* If no index file exists, restore directory path */
  5206. if (!found) {
  5207. path[n] = '\0';
  5208. }
  5209. return found;
  5210. }
  5211. return 0;
  5212. }
  5213. #endif
  5214. /* Return True if we should reply 304 Not Modified. */
  5215. static int is_not_modified(const struct mg_connection *conn,
  5216. const struct file *filep)
  5217. {
  5218. char etag[64];
  5219. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5220. const char *inm = mg_get_header(conn, "If-None-Match");
  5221. construct_etag(etag, sizeof(etag), filep);
  5222. if (!filep) {
  5223. return 0;
  5224. }
  5225. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  5226. (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5227. }
  5228. #if !defined(NO_CGI) || !defined(NO_FILES)
  5229. static int
  5230. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5231. {
  5232. const char *expect, *body;
  5233. char buf[MG_BUF_LEN];
  5234. int to_read, nread, success = 0;
  5235. int64_t buffered_len;
  5236. double timeout = -1.0;
  5237. if (!conn) {
  5238. return 0;
  5239. }
  5240. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5241. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5242. }
  5243. expect = mg_get_header(conn, "Expect");
  5244. /* assert(fp != NULL); */
  5245. if (!fp) {
  5246. send_http_error(conn, 500, "%s", "Error: NULL File");
  5247. return 0;
  5248. }
  5249. if (conn->content_len == -1 && !conn->is_chunked) {
  5250. /* Content length is not specified by the client. */
  5251. send_http_error(
  5252. conn, 411, "%s", "Error: Client did not specify content length");
  5253. } else if ((expect != NULL) &&
  5254. (mg_strcasecmp(expect, "100-continue") != 0)) {
  5255. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5256. send_http_error(
  5257. conn, 417, "Error: Can not fulfill expectation %s", expect);
  5258. } else {
  5259. if (expect != NULL) {
  5260. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5261. conn->status_code = 100;
  5262. } else {
  5263. conn->status_code = 200;
  5264. }
  5265. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  5266. conn->consumed_content;
  5267. /* assert(buffered_len >= 0); */
  5268. /* assert(conn->consumed_content == 0); */
  5269. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5270. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5271. return 0;
  5272. }
  5273. if (buffered_len > 0) {
  5274. if ((int64_t)buffered_len > conn->content_len) {
  5275. buffered_len = (int)conn->content_len;
  5276. }
  5277. body = conn->buf + conn->request_len + conn->consumed_content;
  5278. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5279. conn->consumed_content += buffered_len;
  5280. }
  5281. nread = 0;
  5282. while (conn->consumed_content < conn->content_len) {
  5283. to_read = sizeof(buf);
  5284. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5285. to_read = (int)(conn->content_len - conn->consumed_content);
  5286. }
  5287. nread = pull(NULL, conn, buf, to_read, timeout);
  5288. if (nread <= 0 ||
  5289. push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5290. break;
  5291. }
  5292. conn->consumed_content += nread;
  5293. }
  5294. if (conn->consumed_content == conn->content_len) {
  5295. success = nread >= 0;
  5296. }
  5297. /* Each error code path in this function must send an error */
  5298. if (!success) {
  5299. /* NOTE: Maybe some data has already been sent. */
  5300. /* TODO (low): If some data has been sent, a correct error
  5301. * reply can no longer be sent, so just close the connection */
  5302. send_http_error(conn, 500, "%s", "");
  5303. }
  5304. }
  5305. return success;
  5306. }
  5307. #endif
  5308. #if !defined(NO_CGI)
  5309. /* This structure helps to create an environment for the spawned CGI program.
  5310. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5311. * last element must be NULL.
  5312. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5313. * strings must reside in a contiguous buffer. The end of the buffer is
  5314. * marked by two '\0' characters.
  5315. * We satisfy both worlds: we create an envp array (which is vars), all
  5316. * entries are actually pointers inside buf. */
  5317. struct cgi_environment {
  5318. struct mg_connection *conn;
  5319. /* Data block */
  5320. char *buf; /* Environment buffer */
  5321. size_t buflen; /* Space available in buf */
  5322. size_t bufused; /* Space taken in buf */
  5323. /* Index block */
  5324. char **var; /* char **envp */
  5325. size_t varlen; /* Number of variables available in var */
  5326. size_t varused; /* Number of variables stored in var */
  5327. };
  5328. static void addenv(struct cgi_environment *env,
  5329. PRINTF_FORMAT_STRING(const char *fmt),
  5330. ...) PRINTF_ARGS(2, 3);
  5331. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  5332. * pointer into the vars array. Assumes block != NULL and fmt != NULL. */
  5333. static void addenv(struct cgi_environment *env, const char *fmt, ...)
  5334. {
  5335. size_t n, space;
  5336. int truncated;
  5337. char *added;
  5338. va_list ap;
  5339. /* Calculate how much space is left in the buffer */
  5340. space = (env->buflen - env->bufused);
  5341. /* Calculate an estimate for the required space */
  5342. n = strlen(fmt) + 2 + 128;
  5343. do {
  5344. if (space <= n) {
  5345. /* Allocate new buffer */
  5346. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  5347. added = (char *)mg_realloc(env->buf, n);
  5348. if (!added) {
  5349. /* Out of memory */
  5350. mg_cry(env->conn,
  5351. "%s: Cannot allocate memory for CGI variable [%s]",
  5352. __func__,
  5353. fmt);
  5354. return;
  5355. }
  5356. env->buf = added;
  5357. env->buflen = n;
  5358. space = (env->buflen - env->bufused);
  5359. }
  5360. /* Make a pointer to the free space int the buffer */
  5361. added = env->buf + env->bufused;
  5362. /* Copy VARIABLE=VALUE\0 string into the free space */
  5363. va_start(ap, fmt);
  5364. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  5365. va_end(ap);
  5366. /* Do not add truncated strings to the environment */
  5367. if (truncated) {
  5368. /* Reallocate the buffer */
  5369. space = 0;
  5370. n = 1;
  5371. }
  5372. } while (truncated);
  5373. /* Calculate number of bytes added to the environment */
  5374. n = strlen(added) + 1;
  5375. env->bufused += n;
  5376. /* Now update the variable index */
  5377. space = (env->varlen - env->varused);
  5378. if (space < 2) {
  5379. mg_cry(
  5380. env->conn, "%s: Cannot register CGI variable [%s]", __func__, fmt);
  5381. return;
  5382. }
  5383. /* Append a pointer to the added string into the envp array */
  5384. env->var[env->varused] = added;
  5385. env->varused++;
  5386. }
  5387. static void prepare_cgi_environment(struct mg_connection *conn,
  5388. const char *prog,
  5389. struct cgi_environment *env)
  5390. {
  5391. const char *s;
  5392. struct vec var_vec;
  5393. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  5394. int i, truncated;
  5395. if (conn == NULL || prog == NULL || env == NULL) {
  5396. return;
  5397. }
  5398. env->conn = conn;
  5399. env->buflen = CGI_ENVIRONMENT_SIZE;
  5400. env->bufused = 0;
  5401. env->buf = (char *)mg_malloc(env->buflen);
  5402. env->varlen = MAX_CGI_ENVIR_VARS;
  5403. env->varused = 0;
  5404. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  5405. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  5406. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5407. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5408. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  5409. /* Prepare the environment block */
  5410. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  5411. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  5412. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  5413. #if defined(USE_IPV6)
  5414. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  5415. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  5416. } else
  5417. #endif
  5418. {
  5419. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  5420. }
  5421. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5422. addenv(env, "REMOTE_ADDR=%s", src_addr);
  5423. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  5424. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5425. addenv(env, "REQUEST_URI=%s", conn->request_info.uri);
  5426. /* SCRIPT_NAME */
  5427. addenv(env,
  5428. "SCRIPT_NAME=%.*s",
  5429. (int)strlen(conn->request_info.uri) -
  5430. ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5431. conn->request_info.uri);
  5432. addenv(env, "SCRIPT_FILENAME=%s", prog);
  5433. if (conn->path_info == NULL) {
  5434. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5435. } else {
  5436. addenv(env,
  5437. "PATH_TRANSLATED=%s%s",
  5438. conn->ctx->config[DOCUMENT_ROOT],
  5439. conn->path_info);
  5440. }
  5441. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5442. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  5443. addenv(env, "CONTENT_TYPE=%s", s);
  5444. }
  5445. if (conn->request_info.query_string != NULL) {
  5446. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  5447. }
  5448. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  5449. addenv(env, "CONTENT_LENGTH=%s", s);
  5450. }
  5451. if ((s = getenv("PATH")) != NULL) {
  5452. addenv(env, "PATH=%s", s);
  5453. }
  5454. if (conn->path_info != NULL) {
  5455. addenv(env, "PATH_INFO=%s", conn->path_info);
  5456. }
  5457. if (conn->status_code > 0) {
  5458. /* CGI error handler should show the status code */
  5459. addenv(env, "STATUS=%d", conn->status_code);
  5460. }
  5461. #if defined(_WIN32)
  5462. if ((s = getenv("COMSPEC")) != NULL) {
  5463. addenv(env, "COMSPEC=%s", s);
  5464. }
  5465. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5466. addenv(env, "SYSTEMROOT=%s", s);
  5467. }
  5468. if ((s = getenv("SystemDrive")) != NULL) {
  5469. addenv(env, "SystemDrive=%s", s);
  5470. }
  5471. if ((s = getenv("ProgramFiles")) != NULL) {
  5472. addenv(env, "ProgramFiles=%s", s);
  5473. }
  5474. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5475. addenv(env, "ProgramFiles(x86)=%s", s);
  5476. }
  5477. #else
  5478. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  5479. addenv(env, "LD_LIBRARY_PATH=%s", s);
  5480. }
  5481. #endif /* _WIN32 */
  5482. if ((s = getenv("PERLLIB")) != NULL) {
  5483. addenv(env, "PERLLIB=%s", s);
  5484. }
  5485. if (conn->request_info.remote_user != NULL) {
  5486. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  5487. addenv(env, "%s", "AUTH_TYPE=Digest");
  5488. }
  5489. /* Add all headers as HTTP_* variables */
  5490. for (i = 0; i < conn->request_info.num_headers; i++) {
  5491. (void)mg_snprintf(conn,
  5492. &truncated,
  5493. http_var_name,
  5494. sizeof(http_var_name),
  5495. "HTTP_%s",
  5496. conn->request_info.http_headers[i].name);
  5497. if (truncated) {
  5498. mg_cry(conn,
  5499. "%s: HTTP header variable too long [%s]",
  5500. __func__,
  5501. conn->request_info.http_headers[i].name);
  5502. continue;
  5503. }
  5504. /* Convert variable name into uppercase, and change - to _ */
  5505. for (p = http_var_name; *p != '\0'; p++) {
  5506. if (*p == '-') {
  5507. *p = '_';
  5508. }
  5509. *p = (char)toupper(*(unsigned char *)p);
  5510. }
  5511. addenv(env,
  5512. "%s=%s",
  5513. http_var_name,
  5514. conn->request_info.http_headers[i].value);
  5515. }
  5516. /* Add user-specified variables */
  5517. s = conn->ctx->config[CGI_ENVIRONMENT];
  5518. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  5519. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  5520. }
  5521. env->var[env->varused] = NULL;
  5522. env->buf[env->bufused] = '\0';
  5523. }
  5524. static void handle_cgi_request(struct mg_connection *conn, const char *prog)
  5525. {
  5526. char *buf;
  5527. size_t buflen;
  5528. int headers_len, data_len, i, truncated;
  5529. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1};
  5530. const char *status, *status_text, *connection_state;
  5531. char *pbuf, dir[PATH_MAX], *p;
  5532. struct mg_request_info ri;
  5533. struct cgi_environment blk;
  5534. FILE *in = NULL, *out = NULL;
  5535. struct file fout = STRUCT_FILE_INITIALIZER;
  5536. pid_t pid = (pid_t)-1;
  5537. if (conn == NULL) {
  5538. return;
  5539. }
  5540. buf = NULL;
  5541. buflen = 16384;
  5542. prepare_cgi_environment(conn, prog, &blk);
  5543. /* CGI must be executed in its own directory. 'dir' must point to the
  5544. * directory containing executable program, 'p' must point to the
  5545. * executable program name relative to 'dir'. */
  5546. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  5547. if (truncated) {
  5548. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  5549. goto done;
  5550. }
  5551. if ((p = strrchr(dir, '/')) != NULL) {
  5552. *p++ = '\0';
  5553. } else {
  5554. dir[0] = '.', dir[1] = '\0';
  5555. p = (char *)prog;
  5556. }
  5557. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  5558. send_http_error(
  5559. conn, 500, "Error: Cannot create CGI pipe: %s", strerror(ERRNO));
  5560. goto done;
  5561. }
  5562. pid = spawn_process(conn, p, blk.buf, blk.var, fdin[0], fdout[1], dir);
  5563. if (pid == (pid_t)-1) {
  5564. send_http_error(conn,
  5565. 500,
  5566. "Error: Cannot spawn CGI process [%s]: %s",
  5567. prog,
  5568. strerror(ERRNO));
  5569. goto done;
  5570. }
  5571. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  5572. set_close_on_exec((SOCKET)fdin[0], conn);
  5573. set_close_on_exec((SOCKET)fdin[1], conn);
  5574. set_close_on_exec((SOCKET)fdout[0], conn);
  5575. set_close_on_exec((SOCKET)fdout[1], conn);
  5576. /* Parent closes only one side of the pipes.
  5577. * If we don't mark them as closed, close() attempt before
  5578. * return from this function throws an exception on Windows.
  5579. * Windows does not like when closed descriptor is closed again. */
  5580. (void)close(fdin[0]);
  5581. (void)close(fdout[1]);
  5582. fdin[0] = fdout[1] = -1;
  5583. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  5584. send_http_error(conn,
  5585. 500,
  5586. "Error: CGI can not open fdin\nfopen: %s",
  5587. strerror(ERRNO));
  5588. goto done;
  5589. }
  5590. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  5591. send_http_error(conn,
  5592. 500,
  5593. "Error: CGI can not open fdout\nfopen: %s",
  5594. strerror(ERRNO));
  5595. goto done;
  5596. }
  5597. setbuf(in, NULL);
  5598. setbuf(out, NULL);
  5599. fout.fp = out;
  5600. /* Send POST or PUT data to the CGI process if needed */
  5601. if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  5602. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  5603. /* This is a POST/PUT request */
  5604. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  5605. /* Error sending the body data */
  5606. goto done;
  5607. }
  5608. }
  5609. /* Close so child gets an EOF. */
  5610. fclose(in);
  5611. in = NULL;
  5612. fdin[1] = -1;
  5613. /* Now read CGI reply into a buffer. We need to set correct
  5614. * status code, thus we need to see all HTTP headers first.
  5615. * Do not send anything back to client, until we buffer in all
  5616. * HTTP headers. */
  5617. data_len = 0;
  5618. buf = (char *)mg_malloc(buflen);
  5619. if (buf == NULL) {
  5620. send_http_error(conn,
  5621. 500,
  5622. "Error: Not enough memory for CGI buffer (%u bytes)",
  5623. (unsigned int)buflen);
  5624. goto done;
  5625. }
  5626. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  5627. if (headers_len <= 0) {
  5628. send_http_error(conn,
  5629. 500,
  5630. "Error: CGI program sent malformed or too big "
  5631. "(>%u bytes) HTTP headers: [%.*s]",
  5632. (unsigned)buflen,
  5633. data_len,
  5634. buf);
  5635. goto done;
  5636. }
  5637. pbuf = buf;
  5638. buf[headers_len - 1] = '\0';
  5639. parse_http_headers(&pbuf, &ri);
  5640. /* Make up and send the status line */
  5641. status_text = "OK";
  5642. if ((status = get_header(&ri, "Status")) != NULL) {
  5643. conn->status_code = atoi(status);
  5644. status_text = status;
  5645. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  5646. status_text++;
  5647. }
  5648. } else if (get_header(&ri, "Location") != NULL) {
  5649. conn->status_code = 302;
  5650. } else {
  5651. conn->status_code = 200;
  5652. }
  5653. connection_state = get_header(&ri, "Connection");
  5654. if (connection_state == NULL ||
  5655. mg_strcasecmp(connection_state, "keep-alive")) {
  5656. conn->must_close = 1;
  5657. }
  5658. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  5659. /* Send headers */
  5660. for (i = 0; i < ri.num_headers; i++) {
  5661. mg_printf(conn,
  5662. "%s: %s\r\n",
  5663. ri.http_headers[i].name,
  5664. ri.http_headers[i].value);
  5665. }
  5666. mg_write(conn, "\r\n", 2);
  5667. /* Send chunk of data that may have been read after the headers */
  5668. conn->num_bytes_sent +=
  5669. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  5670. /* Read the rest of CGI output and send to the client */
  5671. send_file_data(conn, &fout, 0, INT64_MAX);
  5672. done:
  5673. mg_free(blk.var);
  5674. mg_free(blk.buf);
  5675. if (pid != (pid_t)-1) {
  5676. kill(pid, SIGKILL);
  5677. #if !defined(_WIN32)
  5678. {
  5679. int st;
  5680. while (waitpid(pid, &st, 0) != -1)
  5681. ; /* clean zombies */
  5682. }
  5683. #endif
  5684. }
  5685. if (fdin[0] != -1) {
  5686. close(fdin[0]);
  5687. }
  5688. if (fdout[1] != -1) {
  5689. close(fdout[1]);
  5690. }
  5691. if (in != NULL) {
  5692. fclose(in);
  5693. } else if (fdin[1] != -1) {
  5694. close(fdin[1]);
  5695. }
  5696. if (out != NULL) {
  5697. fclose(out);
  5698. } else if (fdout[0] != -1) {
  5699. close(fdout[0]);
  5700. }
  5701. if (buf != NULL) {
  5702. mg_free(buf);
  5703. }
  5704. }
  5705. #endif /* !NO_CGI */
  5706. #if !defined(NO_FILES)
  5707. /* For a given PUT path, create all intermediate subdirectories.
  5708. * Return 0 if the path itself is a directory.
  5709. * Return 1 if the path leads to a file.
  5710. * Return -1 for if the path is too long.
  5711. * Return -2 if path can not be created.
  5712. */
  5713. static int put_dir(struct mg_connection *conn, const char *path)
  5714. {
  5715. char buf[PATH_MAX];
  5716. const char *s, *p;
  5717. struct file file = STRUCT_FILE_INITIALIZER;
  5718. size_t len;
  5719. int res = 1;
  5720. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5721. len = (size_t)(p - path);
  5722. if (len >= sizeof(buf)) {
  5723. /* path too long */
  5724. res = -1;
  5725. break;
  5726. }
  5727. memcpy(buf, path, len);
  5728. buf[len] = '\0';
  5729. /* Try to create intermediate directory */
  5730. DEBUG_TRACE("mkdir(%s)", buf);
  5731. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5732. /* path does not exixt and can not be created */
  5733. res = -2;
  5734. break;
  5735. }
  5736. /* Is path itself a directory? */
  5737. if (p[1] == '\0') {
  5738. res = 0;
  5739. }
  5740. }
  5741. return res;
  5742. }
  5743. static void mkcol(struct mg_connection *conn, const char *path)
  5744. {
  5745. int rc, body_len;
  5746. struct de de;
  5747. char date[64];
  5748. time_t curtime = time(NULL);
  5749. if (conn == NULL) {
  5750. return;
  5751. }
  5752. /* TODO (mid): Check the send_http_error situations in this function */
  5753. memset(&de.file, 0, sizeof(de.file));
  5754. if (!mg_stat(conn, path, &de.file)) {
  5755. mg_cry(conn,
  5756. "%s: mg_stat(%s) failed: %s",
  5757. __func__,
  5758. path,
  5759. strerror(ERRNO));
  5760. }
  5761. if (de.file.last_modified) {
  5762. /* TODO (high): This check does not seem to make any sense ! */
  5763. send_http_error(
  5764. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5765. return;
  5766. }
  5767. body_len = conn->data_len - conn->request_len;
  5768. if (body_len > 0) {
  5769. send_http_error(
  5770. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5771. return;
  5772. }
  5773. rc = mg_mkdir(path, 0755);
  5774. if (rc == 0) {
  5775. conn->status_code = 201;
  5776. gmt_time_string(date, sizeof(date), &curtime);
  5777. mg_printf(conn,
  5778. "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: "
  5779. "0\r\nConnection: %s\r\n\r\n",
  5780. conn->status_code,
  5781. date,
  5782. suggest_connection_header(conn));
  5783. } else if (rc == -1) {
  5784. if (errno == EEXIST) {
  5785. send_http_error(
  5786. conn, 405, "Error:mkcol(%s): %s", path, strerror(ERRNO));
  5787. } else if (errno == EACCES) {
  5788. send_http_error(
  5789. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5790. } else if (errno == ENOENT) {
  5791. send_http_error(
  5792. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5793. } else {
  5794. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  5795. }
  5796. }
  5797. }
  5798. static void put_file(struct mg_connection *conn, const char *path)
  5799. {
  5800. struct file file = STRUCT_FILE_INITIALIZER;
  5801. const char *range;
  5802. int64_t r1, r2;
  5803. int rc;
  5804. char date[64];
  5805. time_t curtime = time(NULL);
  5806. if (conn == NULL) {
  5807. return;
  5808. }
  5809. if (mg_stat(conn, path, &file)) {
  5810. /* File already exists */
  5811. conn->status_code = 200;
  5812. if (file.is_directory) {
  5813. /* This is an already existing directory,
  5814. * so there is nothing to do for the server. */
  5815. rc = 0;
  5816. } else {
  5817. /* File exists and is not a directory. */
  5818. /* Can it be replaced? */
  5819. if (file.membuf != NULL) {
  5820. /* This is an "in-memory" file, that can not be replaced */
  5821. send_http_error(
  5822. conn,
  5823. 405,
  5824. "Error: Put not possible\nReplacing %s is not supported",
  5825. path);
  5826. return;
  5827. }
  5828. /* Check if the server may write this file */
  5829. if (access(path, W_OK) == 0) {
  5830. /* Access granted */
  5831. conn->status_code = 200;
  5832. rc = 1;
  5833. } else {
  5834. send_http_error(
  5835. conn,
  5836. 403,
  5837. "Error: Put not possible\nReplacing %s is not allowed",
  5838. path);
  5839. return;
  5840. }
  5841. }
  5842. } else {
  5843. /* File should be created */
  5844. conn->status_code = 201;
  5845. rc = put_dir(conn, path);
  5846. }
  5847. if (rc == 0) {
  5848. /* put_dir returns 0 if path is a directory */
  5849. gmt_time_string(date, sizeof(date), &curtime);
  5850. mg_printf(conn,
  5851. "HTTP/1.1 %d %s\r\n"
  5852. "Date: %s\r\n"
  5853. "Content-Length: 0\r\n"
  5854. "Connection: %s\r\n\r\n",
  5855. conn->status_code,
  5856. mg_get_response_code_text(conn->status_code, NULL),
  5857. date,
  5858. suggest_connection_header(conn));
  5859. /* Request to create a directory has been fulfilled successfully.
  5860. * No need to put a file. */
  5861. return;
  5862. }
  5863. if (rc == -1) {
  5864. /* put_dir returns -1 if the path is too long */
  5865. send_http_error(conn,
  5866. 414,
  5867. "Error: Path too long\nput_dir(%s): %s",
  5868. path,
  5869. strerror(ERRNO));
  5870. return;
  5871. }
  5872. if (rc == -2) {
  5873. /* put_dir returns -2 if the directory can not be created */
  5874. send_http_error(conn,
  5875. 500,
  5876. "Error: Can not create directory\nput_dir(%s): %s",
  5877. path,
  5878. strerror(ERRNO));
  5879. return;
  5880. }
  5881. /* A file should be created or overwritten. */
  5882. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  5883. mg_fclose(&file);
  5884. send_http_error(conn,
  5885. 500,
  5886. "Error: Can not create file\nfopen(%s): %s",
  5887. path,
  5888. strerror(ERRNO));
  5889. return;
  5890. }
  5891. fclose_on_exec(&file, conn);
  5892. range = mg_get_header(conn, "Content-Range");
  5893. r1 = r2 = 0;
  5894. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  5895. conn->status_code = 206; /* Partial content */
  5896. fseeko(file.fp, r1, SEEK_SET);
  5897. }
  5898. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  5899. /* forward_body_data failed.
  5900. * The error code has already been sent to the client,
  5901. * and conn->status_code is already set. */
  5902. return;
  5903. }
  5904. gmt_time_string(date, sizeof(date), &curtime);
  5905. mg_printf(conn,
  5906. "HTTP/1.1 %d %s\r\n"
  5907. "Date: %s\r\n"
  5908. "Content-Length: 0\r\n"
  5909. "Connection: %s\r\n\r\n",
  5910. conn->status_code,
  5911. mg_get_response_code_text(conn->status_code, NULL),
  5912. date,
  5913. suggest_connection_header(conn));
  5914. mg_fclose(&file);
  5915. }
  5916. static void delete_file(struct mg_connection *conn, const char *path)
  5917. {
  5918. struct de de;
  5919. memset(&de.file, 0, sizeof(de.file));
  5920. if (!mg_stat(conn, path, &de.file)) {
  5921. /* mg_stat returns 0 if the file does not exist */
  5922. send_http_error(
  5923. conn, 404, "Error: Cannot delete file\nFile %s not found", path);
  5924. return;
  5925. }
  5926. if (de.file.membuf != NULL) {
  5927. /* the file is cached in memory */
  5928. send_http_error(
  5929. conn,
  5930. 405,
  5931. "Error: Delete not possible\nDeleting %s is not supported",
  5932. path);
  5933. return;
  5934. }
  5935. if (de.file.is_directory) {
  5936. remove_directory(conn, path);
  5937. /* TODO (mid): remove_dir does not return success of the operation */
  5938. /* Assume delete is successful: Return 204 without content. */
  5939. send_http_error(conn, 204, "%s", "");
  5940. return;
  5941. }
  5942. /* This is an existing file (not a directory).
  5943. * Check if write permission is granted. */
  5944. if (access(path, W_OK) != 0) {
  5945. /* File is read only */
  5946. send_http_error(
  5947. conn,
  5948. 403,
  5949. "Error: Delete not possible\nDeleting %s is not allowed",
  5950. path);
  5951. return;
  5952. }
  5953. /* Try to delete it. */
  5954. if (mg_remove(path) == 0) {
  5955. /* Delete was successful: Return 204 without content. */
  5956. send_http_error(conn, 204, "%s", "");
  5957. } else {
  5958. /* Delete not successful (file locked). */
  5959. send_http_error(conn,
  5960. 423,
  5961. "Error: Cannot delete file\nremove(%s): %s",
  5962. path,
  5963. strerror(ERRNO));
  5964. }
  5965. }
  5966. #endif /* !NO_FILES */
  5967. static void
  5968. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  5969. static void do_ssi_include(struct mg_connection *conn,
  5970. const char *ssi,
  5971. char *tag,
  5972. int include_level)
  5973. {
  5974. char file_name[MG_BUF_LEN], path[512], *p;
  5975. struct file file = STRUCT_FILE_INITIALIZER;
  5976. size_t len;
  5977. int truncated = 0;
  5978. if (conn == NULL) {
  5979. return;
  5980. }
  5981. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  5982. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  5983. * always < MG_BUF_LEN. */
  5984. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  5985. /* File name is relative to the webserver root */
  5986. file_name[511] = 0;
  5987. (void)mg_snprintf(conn,
  5988. &truncated,
  5989. path,
  5990. sizeof(path),
  5991. "%s/%s",
  5992. conn->ctx->config[DOCUMENT_ROOT],
  5993. file_name);
  5994. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  5995. /* File name is relative to the webserver working directory
  5996. * or it is absolute system path */
  5997. file_name[511] = 0;
  5998. (void)mg_snprintf(
  5999. conn, &truncated, path, sizeof(path), "%s", file_name);
  6000. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1 ||
  6001. sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6002. /* File name is relative to the currect document */
  6003. file_name[511] = 0;
  6004. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6005. if (!truncated) {
  6006. if ((p = strrchr(path, '/')) != NULL) {
  6007. p[1] = '\0';
  6008. }
  6009. len = strlen(path);
  6010. (void)mg_snprintf(conn,
  6011. &truncated,
  6012. path + len,
  6013. sizeof(path) - len,
  6014. "%s",
  6015. file_name);
  6016. }
  6017. } else {
  6018. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6019. return;
  6020. }
  6021. if (truncated) {
  6022. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6023. return;
  6024. }
  6025. if (!mg_fopen(conn, path, "rb", &file)) {
  6026. mg_cry(conn,
  6027. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6028. tag,
  6029. path,
  6030. strerror(ERRNO));
  6031. } else {
  6032. fclose_on_exec(&file, conn);
  6033. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6034. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6035. path) > 0) {
  6036. send_ssi_file(conn, path, &file, include_level + 1);
  6037. } else {
  6038. send_file_data(conn, &file, 0, INT64_MAX);
  6039. }
  6040. mg_fclose(&file);
  6041. }
  6042. }
  6043. #if !defined(NO_POPEN)
  6044. static void do_ssi_exec(struct mg_connection *conn, char *tag)
  6045. {
  6046. char cmd[1024] = "";
  6047. struct file file = STRUCT_FILE_INITIALIZER;
  6048. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6049. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6050. } else {
  6051. cmd[1023] = 0;
  6052. if ((file.fp = popen(cmd, "r")) == NULL) {
  6053. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6054. } else {
  6055. send_file_data(conn, &file, 0, INT64_MAX);
  6056. pclose(file.fp);
  6057. }
  6058. }
  6059. }
  6060. #endif /* !NO_POPEN */
  6061. static int mg_fgetc(struct file *filep, int offset)
  6062. {
  6063. if (filep == NULL) {
  6064. return EOF;
  6065. }
  6066. if (filep->membuf != NULL && offset >= 0 &&
  6067. ((unsigned int)(offset)) < filep->size) {
  6068. return ((unsigned char *)filep->membuf)[offset];
  6069. } else if (filep->fp != NULL) {
  6070. return fgetc(filep->fp);
  6071. } else {
  6072. return EOF;
  6073. }
  6074. }
  6075. static void send_ssi_file(struct mg_connection *conn,
  6076. const char *path,
  6077. struct file *filep,
  6078. int include_level)
  6079. {
  6080. char buf[MG_BUF_LEN];
  6081. int ch, offset, len, in_ssi_tag;
  6082. if (include_level > 10) {
  6083. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6084. return;
  6085. }
  6086. in_ssi_tag = len = offset = 0;
  6087. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6088. if (in_ssi_tag && ch == '>') {
  6089. in_ssi_tag = 0;
  6090. buf[len++] = (char)ch;
  6091. buf[len] = '\0';
  6092. /* assert(len <= (int) sizeof(buf)); */
  6093. if (len > (int)sizeof(buf)) {
  6094. break;
  6095. }
  6096. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6097. /* Not an SSI tag, pass it */
  6098. (void)mg_write(conn, buf, (size_t)len);
  6099. } else {
  6100. if (!memcmp(buf + 5, "include", 7)) {
  6101. do_ssi_include(conn, path, buf + 12, include_level);
  6102. #if !defined(NO_POPEN)
  6103. } else if (!memcmp(buf + 5, "exec", 4)) {
  6104. do_ssi_exec(conn, buf + 9);
  6105. #endif /* !NO_POPEN */
  6106. } else {
  6107. mg_cry(conn,
  6108. "%s: unknown SSI "
  6109. "command: \"%s\"",
  6110. path,
  6111. buf);
  6112. }
  6113. }
  6114. len = 0;
  6115. } else if (in_ssi_tag) {
  6116. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6117. /* Not an SSI tag */
  6118. in_ssi_tag = 0;
  6119. } else if (len == (int)sizeof(buf) - 2) {
  6120. mg_cry(conn, "%s: SSI tag is too large", path);
  6121. len = 0;
  6122. }
  6123. buf[len++] = (char)(ch & 0xff);
  6124. } else if (ch == '<') {
  6125. in_ssi_tag = 1;
  6126. if (len > 0) {
  6127. mg_write(conn, buf, (size_t)len);
  6128. }
  6129. len = 0;
  6130. buf[len++] = (char)(ch & 0xff);
  6131. } else {
  6132. buf[len++] = (char)(ch & 0xff);
  6133. if (len == (int)sizeof(buf)) {
  6134. mg_write(conn, buf, (size_t)len);
  6135. len = 0;
  6136. }
  6137. }
  6138. }
  6139. /* Send the rest of buffered data */
  6140. if (len > 0) {
  6141. mg_write(conn, buf, (size_t)len);
  6142. }
  6143. }
  6144. static void handle_ssi_file_request(struct mg_connection *conn,
  6145. const char *path,
  6146. struct file *filep)
  6147. {
  6148. char date[64];
  6149. time_t curtime = time(NULL);
  6150. const char *cors1, *cors2, *cors3;
  6151. if (conn == NULL || path == NULL || filep == NULL) {
  6152. return;
  6153. }
  6154. if (mg_get_header(conn, "Origin")) {
  6155. /* Cross-origin resource sharing (CORS). */
  6156. cors1 = "Access-Control-Allow-Origin: ";
  6157. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6158. cors3 = "\r\n";
  6159. } else {
  6160. cors1 = cors2 = cors3 = "";
  6161. }
  6162. if (!mg_fopen(conn, path, "rb", filep)) {
  6163. /* File exists (precondition for calling this function),
  6164. * but can not be opened by the server. */
  6165. send_http_error(conn,
  6166. 500,
  6167. "Error: Cannot read file\nfopen(%s): %s",
  6168. path,
  6169. strerror(ERRNO));
  6170. } else {
  6171. conn->must_close = 1;
  6172. gmt_time_string(date, sizeof(date), &curtime);
  6173. fclose_on_exec(filep, conn);
  6174. mg_printf(conn,
  6175. "HTTP/1.1 200 OK\r\n"
  6176. "%s%s%s"
  6177. "Date: %s\r\n"
  6178. "Content-Type: text/html\r\n"
  6179. "Connection: %s\r\n\r\n",
  6180. cors1,
  6181. cors2,
  6182. cors3,
  6183. date,
  6184. suggest_connection_header(conn));
  6185. send_ssi_file(conn, path, filep, 0);
  6186. mg_fclose(filep);
  6187. }
  6188. }
  6189. #if !defined(NO_FILES)
  6190. static void send_options(struct mg_connection *conn)
  6191. {
  6192. char date[64];
  6193. time_t curtime = time(NULL);
  6194. if (!conn) {
  6195. return;
  6196. }
  6197. conn->status_code = 200;
  6198. conn->must_close = 1;
  6199. gmt_time_string(date, sizeof(date), &curtime);
  6200. mg_printf(conn,
  6201. "HTTP/1.1 200 OK\r\n"
  6202. "Date: %s\r\n"
  6203. "Connection: %s\r\n"
  6204. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6205. "PROPFIND, MKCOL\r\n"
  6206. "DAV: 1\r\n\r\n",
  6207. date,
  6208. suggest_connection_header(conn));
  6209. }
  6210. /* Writes PROPFIND properties for a collection element */
  6211. static void
  6212. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  6213. {
  6214. char mtime[64];
  6215. if (conn == NULL || uri == NULL || filep == NULL) {
  6216. return;
  6217. }
  6218. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  6219. conn->num_bytes_sent +=
  6220. mg_printf(conn,
  6221. "<d:response>"
  6222. "<d:href>%s</d:href>"
  6223. "<d:propstat>"
  6224. "<d:prop>"
  6225. "<d:resourcetype>%s</d:resourcetype>"
  6226. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  6227. "<d:getlastmodified>%s</d:getlastmodified>"
  6228. "</d:prop>"
  6229. "<d:status>HTTP/1.1 200 OK</d:status>"
  6230. "</d:propstat>"
  6231. "</d:response>\n",
  6232. uri,
  6233. filep->is_directory ? "<d:collection/>" : "",
  6234. filep->size,
  6235. mtime);
  6236. }
  6237. static void print_dav_dir_entry(struct de *de, void *data)
  6238. {
  6239. char href[PATH_MAX];
  6240. char href_encoded[PATH_MAX];
  6241. int truncated;
  6242. struct mg_connection *conn = (struct mg_connection *)data;
  6243. if (!de || !conn) {
  6244. return;
  6245. }
  6246. mg_snprintf(conn,
  6247. &truncated,
  6248. href,
  6249. sizeof(href),
  6250. "%s%s",
  6251. conn->request_info.uri,
  6252. de->file_name);
  6253. if (!truncated) {
  6254. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  6255. print_props(conn, href_encoded, &de->file);
  6256. }
  6257. }
  6258. static void handle_propfind(struct mg_connection *conn,
  6259. const char *path,
  6260. struct file *filep)
  6261. {
  6262. const char *depth = mg_get_header(conn, "Depth");
  6263. char date[64];
  6264. time_t curtime = time(NULL);
  6265. gmt_time_string(date, sizeof(date), &curtime);
  6266. if (!conn || !path || !filep) {
  6267. return;
  6268. }
  6269. conn->must_close = 1;
  6270. conn->status_code = 207;
  6271. mg_printf(conn,
  6272. "HTTP/1.1 207 Multi-Status\r\n"
  6273. "Date: %s\r\n"
  6274. "Connection: %s\r\n"
  6275. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  6276. date,
  6277. suggest_connection_header(conn));
  6278. conn->num_bytes_sent +=
  6279. mg_printf(conn,
  6280. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  6281. "<d:multistatus xmlns:d='DAV:'>\n");
  6282. /* Print properties for the requested resource itself */
  6283. print_props(conn, conn->request_info.uri, filep);
  6284. /* If it is a directory, print directory entries too if Depth is not 0 */
  6285. if (filep && conn->ctx && filep->is_directory &&
  6286. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  6287. (depth == NULL || strcmp(depth, "0") != 0)) {
  6288. scan_directory(conn, path, conn, &print_dav_dir_entry);
  6289. }
  6290. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  6291. }
  6292. #endif
  6293. void mg_lock_connection(struct mg_connection *conn)
  6294. {
  6295. if (conn) {
  6296. (void)pthread_mutex_lock(&conn->mutex);
  6297. }
  6298. }
  6299. void mg_unlock_connection(struct mg_connection *conn)
  6300. {
  6301. if (conn) {
  6302. (void)pthread_mutex_unlock(&conn->mutex);
  6303. }
  6304. }
  6305. void mg_lock_context(struct mg_context *ctx)
  6306. {
  6307. if (ctx) {
  6308. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  6309. }
  6310. }
  6311. void mg_unlock_context(struct mg_context *ctx)
  6312. {
  6313. if (ctx) {
  6314. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  6315. }
  6316. }
  6317. #if defined(USE_TIMERS)
  6318. #include "timer.inl"
  6319. #endif /* USE_TIMERS */
  6320. #ifdef USE_LUA
  6321. #include "mod_lua.inl"
  6322. #endif /* USE_LUA */
  6323. #if defined(USE_WEBSOCKET)
  6324. /* START OF SHA-1 code
  6325. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  6326. #define SHA1HANDSOFF
  6327. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  6328. *
  6329. * #if defined(__sun)
  6330. * #include "solarisfixes.h"
  6331. * #endif
  6332. */
  6333. static int is_big_endian(void)
  6334. {
  6335. static const int n = 1;
  6336. return ((char *)&n)[0] == 0;
  6337. }
  6338. union char64long16 {
  6339. unsigned char c[64];
  6340. uint32_t l[16];
  6341. };
  6342. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6343. static uint32_t blk0(union char64long16 *block, int i)
  6344. {
  6345. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  6346. if (!is_big_endian()) {
  6347. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  6348. (rol(block->l[i], 8) & 0x00FF00FF);
  6349. }
  6350. return block->l[i];
  6351. }
  6352. #define blk(i) \
  6353. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  6354. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6355. 1))
  6356. #define R0(v, w, x, y, z, i) \
  6357. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6358. w = rol(w, 30);
  6359. #define R1(v, w, x, y, z, i) \
  6360. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6361. w = rol(w, 30);
  6362. #define R2(v, w, x, y, z, i) \
  6363. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6364. w = rol(w, 30);
  6365. #define R3(v, w, x, y, z, i) \
  6366. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6367. w = rol(w, 30);
  6368. #define R4(v, w, x, y, z, i) \
  6369. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6370. w = rol(w, 30);
  6371. typedef struct {
  6372. uint32_t state[5];
  6373. uint32_t count[2];
  6374. unsigned char buffer[64];
  6375. } SHA1_CTX;
  6376. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  6377. {
  6378. uint32_t a, b, c, d, e;
  6379. union char64long16 block[1];
  6380. memcpy(block, buffer, 64);
  6381. a = state[0];
  6382. b = state[1];
  6383. c = state[2];
  6384. d = state[3];
  6385. e = state[4];
  6386. R0(a, b, c, d, e, 0);
  6387. R0(e, a, b, c, d, 1);
  6388. R0(d, e, a, b, c, 2);
  6389. R0(c, d, e, a, b, 3);
  6390. R0(b, c, d, e, a, 4);
  6391. R0(a, b, c, d, e, 5);
  6392. R0(e, a, b, c, d, 6);
  6393. R0(d, e, a, b, c, 7);
  6394. R0(c, d, e, a, b, 8);
  6395. R0(b, c, d, e, a, 9);
  6396. R0(a, b, c, d, e, 10);
  6397. R0(e, a, b, c, d, 11);
  6398. R0(d, e, a, b, c, 12);
  6399. R0(c, d, e, a, b, 13);
  6400. R0(b, c, d, e, a, 14);
  6401. R0(a, b, c, d, e, 15);
  6402. R1(e, a, b, c, d, 16);
  6403. R1(d, e, a, b, c, 17);
  6404. R1(c, d, e, a, b, 18);
  6405. R1(b, c, d, e, a, 19);
  6406. R2(a, b, c, d, e, 20);
  6407. R2(e, a, b, c, d, 21);
  6408. R2(d, e, a, b, c, 22);
  6409. R2(c, d, e, a, b, 23);
  6410. R2(b, c, d, e, a, 24);
  6411. R2(a, b, c, d, e, 25);
  6412. R2(e, a, b, c, d, 26);
  6413. R2(d, e, a, b, c, 27);
  6414. R2(c, d, e, a, b, 28);
  6415. R2(b, c, d, e, a, 29);
  6416. R2(a, b, c, d, e, 30);
  6417. R2(e, a, b, c, d, 31);
  6418. R2(d, e, a, b, c, 32);
  6419. R2(c, d, e, a, b, 33);
  6420. R2(b, c, d, e, a, 34);
  6421. R2(a, b, c, d, e, 35);
  6422. R2(e, a, b, c, d, 36);
  6423. R2(d, e, a, b, c, 37);
  6424. R2(c, d, e, a, b, 38);
  6425. R2(b, c, d, e, a, 39);
  6426. R3(a, b, c, d, e, 40);
  6427. R3(e, a, b, c, d, 41);
  6428. R3(d, e, a, b, c, 42);
  6429. R3(c, d, e, a, b, 43);
  6430. R3(b, c, d, e, a, 44);
  6431. R3(a, b, c, d, e, 45);
  6432. R3(e, a, b, c, d, 46);
  6433. R3(d, e, a, b, c, 47);
  6434. R3(c, d, e, a, b, 48);
  6435. R3(b, c, d, e, a, 49);
  6436. R3(a, b, c, d, e, 50);
  6437. R3(e, a, b, c, d, 51);
  6438. R3(d, e, a, b, c, 52);
  6439. R3(c, d, e, a, b, 53);
  6440. R3(b, c, d, e, a, 54);
  6441. R3(a, b, c, d, e, 55);
  6442. R3(e, a, b, c, d, 56);
  6443. R3(d, e, a, b, c, 57);
  6444. R3(c, d, e, a, b, 58);
  6445. R3(b, c, d, e, a, 59);
  6446. R4(a, b, c, d, e, 60);
  6447. R4(e, a, b, c, d, 61);
  6448. R4(d, e, a, b, c, 62);
  6449. R4(c, d, e, a, b, 63);
  6450. R4(b, c, d, e, a, 64);
  6451. R4(a, b, c, d, e, 65);
  6452. R4(e, a, b, c, d, 66);
  6453. R4(d, e, a, b, c, 67);
  6454. R4(c, d, e, a, b, 68);
  6455. R4(b, c, d, e, a, 69);
  6456. R4(a, b, c, d, e, 70);
  6457. R4(e, a, b, c, d, 71);
  6458. R4(d, e, a, b, c, 72);
  6459. R4(c, d, e, a, b, 73);
  6460. R4(b, c, d, e, a, 74);
  6461. R4(a, b, c, d, e, 75);
  6462. R4(e, a, b, c, d, 76);
  6463. R4(d, e, a, b, c, 77);
  6464. R4(c, d, e, a, b, 78);
  6465. R4(b, c, d, e, a, 79);
  6466. state[0] += a;
  6467. state[1] += b;
  6468. state[2] += c;
  6469. state[3] += d;
  6470. state[4] += e;
  6471. a = b = c = d = e = 0;
  6472. memset(block, '\0', sizeof(block));
  6473. }
  6474. static void SHA1Init(SHA1_CTX *context)
  6475. {
  6476. context->state[0] = 0x67452301;
  6477. context->state[1] = 0xEFCDAB89;
  6478. context->state[2] = 0x98BADCFE;
  6479. context->state[3] = 0x10325476;
  6480. context->state[4] = 0xC3D2E1F0;
  6481. context->count[0] = context->count[1] = 0;
  6482. }
  6483. static void
  6484. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  6485. {
  6486. uint32_t i, j;
  6487. j = context->count[0];
  6488. if ((context->count[0] += len << 3) < j) {
  6489. context->count[1]++;
  6490. }
  6491. context->count[1] += (len >> 29);
  6492. j = (j >> 3) & 63;
  6493. if ((j + len) > 63) {
  6494. memcpy(&context->buffer[j], data, (i = 64 - j));
  6495. SHA1Transform(context->state, context->buffer);
  6496. for (; i + 63 < len; i += 64) {
  6497. SHA1Transform(context->state, &data[i]);
  6498. }
  6499. j = 0;
  6500. } else
  6501. i = 0;
  6502. memcpy(&context->buffer[j], &data[i], len - i);
  6503. }
  6504. static void SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  6505. {
  6506. unsigned i;
  6507. unsigned char finalcount[8], c;
  6508. for (i = 0; i < 8; i++) {
  6509. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >>
  6510. ((3 - (i & 3)) * 8)) &
  6511. 255);
  6512. }
  6513. c = 0200;
  6514. SHA1Update(context, &c, 1);
  6515. while ((context->count[0] & 504) != 448) {
  6516. c = 0000;
  6517. SHA1Update(context, &c, 1);
  6518. }
  6519. SHA1Update(context, finalcount, 8);
  6520. for (i = 0; i < 20; i++) {
  6521. digest[i] =
  6522. (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) &
  6523. 255);
  6524. }
  6525. memset(context, '\0', sizeof(*context));
  6526. memset(&finalcount, '\0', sizeof(finalcount));
  6527. }
  6528. /* END OF SHA1 CODE */
  6529. static int send_websocket_handshake(struct mg_connection *conn)
  6530. {
  6531. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  6532. const char *protocol = NULL;
  6533. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  6534. SHA1_CTX sha_ctx;
  6535. int truncated;
  6536. mg_snprintf(conn,
  6537. &truncated,
  6538. buf,
  6539. sizeof(buf),
  6540. "%s%s",
  6541. mg_get_header(conn, "Sec-WebSocket-Key"),
  6542. magic);
  6543. if (truncated) {
  6544. conn->must_close = 1;
  6545. return 0;
  6546. }
  6547. SHA1Init(&sha_ctx);
  6548. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  6549. SHA1Final((unsigned char *)sha, &sha_ctx);
  6550. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  6551. mg_printf(conn,
  6552. "HTTP/1.1 101 Switching Protocols\r\n"
  6553. "Upgrade: websocket\r\n"
  6554. "Connection: Upgrade\r\n"
  6555. "Sec-WebSocket-Accept: %s\r\n",
  6556. b64_sha);
  6557. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  6558. if (protocol) {
  6559. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  6560. } else {
  6561. mg_printf(conn, "%s", "\r\n");
  6562. }
  6563. return 1;
  6564. }
  6565. static void read_websocket(struct mg_connection *conn,
  6566. mg_websocket_data_handler ws_data_handler,
  6567. void *callback_data)
  6568. {
  6569. /* Pointer to the beginning of the portion of the incoming websocket
  6570. * message queue.
  6571. * The original websocket upgrade request is never removed, so the queue
  6572. * begins after it. */
  6573. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  6574. int n, error, exit_by_callback;
  6575. /* body_len is the length of the entire queue in bytes
  6576. * len is the length of the current message
  6577. * data_len is the length of the current message's data payload
  6578. * header_len is the length of the current message's header */
  6579. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  6580. /* "The masking key is a 32-bit value chosen at random by the client."
  6581. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  6582. */
  6583. unsigned char mask[4];
  6584. /* data points to the place where the message is stored when passed to the
  6585. * websocket_data callback. This is either mem on the stack, or a
  6586. * dynamically allocated buffer if it is too large. */
  6587. char mem[4096];
  6588. char *data = mem;
  6589. unsigned char mop; /* mask flag and opcode */
  6590. double timeout = -1.0;
  6591. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  6592. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  6593. }
  6594. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  6595. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6596. }
  6597. mg_set_thread_name("wsock");
  6598. /* Loop continuously, reading messages from the socket, invoking the
  6599. * callback, and waiting repeatedly until an error occurs. */
  6600. while (!conn->ctx->stop_flag) {
  6601. header_len = 0;
  6602. assert(conn->data_len >= conn->request_len);
  6603. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  6604. len = buf[1] & 127;
  6605. mask_len = buf[1] & 128 ? 4 : 0;
  6606. if (len < 126 && body_len >= mask_len) {
  6607. data_len = len;
  6608. header_len = 2 + mask_len;
  6609. } else if (len == 126 && body_len >= 4 + mask_len) {
  6610. header_len = 4 + mask_len;
  6611. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  6612. } else if (body_len >= 10 + mask_len) {
  6613. header_len = 10 + mask_len;
  6614. data_len =
  6615. (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2])) << 32) +
  6616. ntohl(*(uint32_t *)(void *)&buf[6]);
  6617. }
  6618. }
  6619. if (header_len > 0 && body_len >= header_len) {
  6620. /* Allocate space to hold websocket payload */
  6621. data = mem;
  6622. if (data_len > sizeof(mem)) {
  6623. data = (char *)mg_malloc(data_len);
  6624. if (data == NULL) {
  6625. /* Allocation failed, exit the loop and then close the
  6626. * connection */
  6627. mg_cry(conn, "websocket out of memory; closing connection");
  6628. break;
  6629. }
  6630. }
  6631. /* Copy the mask before we shift the queue and destroy it */
  6632. if (mask_len > 0) {
  6633. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  6634. } else {
  6635. memset(mask, 0, sizeof(mask));
  6636. }
  6637. /* Read frame payload from the first message in the queue into
  6638. * data and advance the queue by moving the memory in place. */
  6639. assert(body_len >= header_len);
  6640. if (data_len + header_len > body_len) {
  6641. mop = buf[0]; /* current mask and opcode */
  6642. /* Overflow case */
  6643. len = body_len - header_len;
  6644. memcpy(data, buf + header_len, len);
  6645. error = 0;
  6646. while (len < data_len) {
  6647. n = pull(
  6648. NULL, conn, data + len, (int)(data_len - len), timeout);
  6649. if (n <= 0) {
  6650. error = 1;
  6651. break;
  6652. }
  6653. len += (size_t)n;
  6654. }
  6655. if (error) {
  6656. mg_cry(conn, "Websocket pull failed; closing connection");
  6657. break;
  6658. }
  6659. conn->data_len = conn->request_len;
  6660. } else {
  6661. mop = buf[0]; /* current mask and opcode, overwritten by
  6662. * memmove() */
  6663. /* Length of the message being read at the front of the
  6664. * queue */
  6665. len = data_len + header_len;
  6666. /* Copy the data payload into the data pointer for the
  6667. * callback */
  6668. memcpy(data, buf + header_len, data_len);
  6669. /* Move the queue forward len bytes */
  6670. memmove(buf, buf + len, body_len - len);
  6671. /* Mark the queue as advanced */
  6672. conn->data_len -= (int)len;
  6673. }
  6674. /* Apply mask if necessary */
  6675. if (mask_len > 0) {
  6676. for (i = 0; i < data_len; ++i) {
  6677. data[i] ^= mask[i & 3];
  6678. }
  6679. }
  6680. /* Exit the loop if callback signals to exit (server side),
  6681. * or "connection close" opcode received (client side). */
  6682. exit_by_callback = 0;
  6683. if ((ws_data_handler != NULL) &&
  6684. !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  6685. exit_by_callback = 1;
  6686. }
  6687. if (data != mem) {
  6688. mg_free(data);
  6689. }
  6690. if (exit_by_callback ||
  6691. ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  6692. /* Opcode == 8, connection close */
  6693. break;
  6694. }
  6695. /* Not breaking the loop, process next websocket frame. */
  6696. } else {
  6697. /* Read from the socket into the next available location in the
  6698. * message queue. */
  6699. if ((n = pull(NULL,
  6700. conn,
  6701. conn->buf + conn->data_len,
  6702. conn->buf_size - conn->data_len,
  6703. timeout)) <= 0) {
  6704. /* Error, no bytes read */
  6705. break;
  6706. }
  6707. conn->data_len += n;
  6708. }
  6709. }
  6710. mg_set_thread_name("worker");
  6711. }
  6712. int mg_websocket_write(struct mg_connection *conn,
  6713. int opcode,
  6714. const char *data,
  6715. size_t dataLen)
  6716. {
  6717. unsigned char header[10];
  6718. size_t headerLen = 1;
  6719. int retval = -1;
  6720. header[0] = 0x80 + (opcode & 0xF);
  6721. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  6722. if (dataLen < 126) {
  6723. /* inline 7-bit length field */
  6724. header[1] = (unsigned char)dataLen;
  6725. headerLen = 2;
  6726. } else if (dataLen <= 0xFFFF) {
  6727. /* 16-bit length field */
  6728. header[1] = 126;
  6729. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  6730. headerLen = 4;
  6731. } else {
  6732. /* 64-bit length field */
  6733. header[1] = 127;
  6734. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  6735. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  6736. headerLen = 10;
  6737. }
  6738. /* Note that POSIX/Winsock's send() is threadsafe
  6739. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  6740. * but mongoose's mg_printf/mg_write is not (because of the loop in
  6741. * push(), although that is only a problem if the packet is large or
  6742. * outgoing buffer is full). */
  6743. (void)mg_lock_connection(conn);
  6744. retval = mg_write(conn, header, headerLen);
  6745. retval = mg_write(conn, data, dataLen);
  6746. mg_unlock_connection(conn);
  6747. return retval;
  6748. }
  6749. static void
  6750. handle_websocket_request(struct mg_connection *conn,
  6751. const char *path,
  6752. int is_callback_resource,
  6753. mg_websocket_connect_handler ws_connect_handler,
  6754. mg_websocket_ready_handler ws_ready_handler,
  6755. mg_websocket_data_handler ws_data_handler,
  6756. mg_websocket_close_handler ws_close_handler,
  6757. void *cbData)
  6758. {
  6759. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  6760. int lua_websock = 0;
  6761. #if !defined(USE_LUA)
  6762. (void)path;
  6763. #endif
  6764. /* Step 1: Check websocket protocol version. */
  6765. if (version == NULL || strcmp(version, "13") != 0) {
  6766. /* Reject wrong versions */
  6767. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  6768. return;
  6769. }
  6770. /* Step 2: If a callback is responsible, call it. */
  6771. if (is_callback_resource) {
  6772. if (ws_connect_handler != NULL &&
  6773. ws_connect_handler(conn, cbData) != 0) {
  6774. /* C callback has returned non-zero, do not proceed with handshake.
  6775. */
  6776. /* Note that C callbacks are no longer called when Lua is
  6777. * responsible, so C can no longer filter callbacks for Lua. */
  6778. return;
  6779. }
  6780. }
  6781. #if defined(USE_LUA)
  6782. /* Step 3: No callback. Check if Lua is responsible. */
  6783. else {
  6784. /* Step 3.1: Check if Lua is responsible. */
  6785. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  6786. lua_websock = match_prefix(
  6787. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  6788. strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  6789. path);
  6790. }
  6791. if (lua_websock) {
  6792. /* Step 3.2: Lua is responsible: call it. */
  6793. conn->lua_websocket_state = lua_websocket_new(path, conn);
  6794. if (!conn->lua_websocket_state) {
  6795. /* Lua rejected the new client */
  6796. return;
  6797. }
  6798. }
  6799. }
  6800. #endif
  6801. /* Step 4: Check if there is a responsible websocket handler. */
  6802. if (!is_callback_resource && !lua_websock) {
  6803. /* There is no callback, an Lua is not responsible either. */
  6804. /* Reply with a 404 Not Found or with nothing at all?
  6805. * TODO (mid): check the websocket standards, how to reply to
  6806. * requests to invalid websocket addresses. */
  6807. send_http_error(conn, 404, "%s", "Not found");
  6808. return;
  6809. }
  6810. /* Step 5: The websocket connection has been accepted */
  6811. if (!send_websocket_handshake(conn)) {
  6812. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  6813. return;
  6814. }
  6815. /* Step 6: Call the ready handler */
  6816. if (is_callback_resource) {
  6817. if (ws_ready_handler != NULL) {
  6818. ws_ready_handler(conn, cbData);
  6819. }
  6820. #if defined(USE_LUA)
  6821. } else if (lua_websock) {
  6822. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  6823. /* the ready handler returned false */
  6824. return;
  6825. }
  6826. #endif
  6827. }
  6828. /* Step 7: Enter the read loop */
  6829. if (is_callback_resource) {
  6830. read_websocket(conn, ws_data_handler, cbData);
  6831. #if defined(USE_LUA)
  6832. } else if (lua_websock) {
  6833. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  6834. #endif
  6835. }
  6836. /* Step 8: Call the close handler */
  6837. if (ws_close_handler) {
  6838. ws_close_handler(conn, cbData);
  6839. }
  6840. }
  6841. static int is_websocket_protocol(const struct mg_connection *conn)
  6842. {
  6843. const char *host, *upgrade, *connection, *version, *key;
  6844. upgrade = mg_get_header(conn, "Upgrade");
  6845. if (upgrade == NULL) {
  6846. return 0; /* fail early, don't waste time checking other header fields
  6847. */
  6848. }
  6849. if (!mg_strcasestr(upgrade, "websocket")) {
  6850. return 0;
  6851. }
  6852. connection = mg_get_header(conn, "Connection");
  6853. if (connection == NULL) {
  6854. return 0;
  6855. }
  6856. if (!mg_strcasestr(connection, "upgrade")) {
  6857. return 0;
  6858. }
  6859. host = mg_get_header(conn, "Host");
  6860. key = mg_get_header(conn, "Sec-WebSocket-Key");
  6861. version = mg_get_header(conn, "Sec-WebSocket-Version");
  6862. return (host != NULL && key != NULL && version != NULL);
  6863. }
  6864. #endif /* !USE_WEBSOCKET */
  6865. static int isbyte(int n) { return n >= 0 && n <= 255; }
  6866. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  6867. {
  6868. int n, a, b, c, d, slash = 32, len = 0;
  6869. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  6870. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  6871. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  6872. slash < 33) {
  6873. len = n;
  6874. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) |
  6875. (uint32_t)d;
  6876. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  6877. }
  6878. return len;
  6879. }
  6880. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  6881. {
  6882. int throttle = 0;
  6883. struct vec vec, val;
  6884. uint32_t net, mask;
  6885. char mult;
  6886. double v;
  6887. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  6888. mult = ',';
  6889. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  6890. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' &&
  6891. mult != ',')) {
  6892. continue;
  6893. }
  6894. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  6895. : 1;
  6896. if (vec.len == 1 && vec.ptr[0] == '*') {
  6897. throttle = (int)v;
  6898. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  6899. if ((remote_ip & mask) == net) {
  6900. throttle = (int)v;
  6901. }
  6902. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  6903. throttle = (int)v;
  6904. }
  6905. }
  6906. return throttle;
  6907. }
  6908. static uint32_t get_remote_ip(const struct mg_connection *conn)
  6909. {
  6910. if (!conn) {
  6911. return 0;
  6912. }
  6913. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  6914. }
  6915. int mg_upload(struct mg_connection *conn, const char *destination_dir)
  6916. {
  6917. /* TODO (high): completely rewrite this function. See issue #180. */
  6918. /* TODO (mid): set a timeout */
  6919. const char *content_type_header, *boundary_start, *sc;
  6920. char *s;
  6921. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX];
  6922. char fname[1024], boundary[100];
  6923. FILE *fp;
  6924. int bl, n, i, headers_len, boundary_len, eof, truncated;
  6925. int len = 0, num_uploaded_files = 0;
  6926. struct mg_request_info part_request_info;
  6927. /* Request looks like this:
  6928. *
  6929. * POST /upload HTTP/1.1
  6930. * Host: 127.0.0.1:8080
  6931. * Content-Length: 244894
  6932. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  6933. *
  6934. * ------WebKitFormBoundaryRVr
  6935. * Content-Disposition: form-data; name="file"; filename="accum.png"
  6936. * Content-Type: image/png
  6937. *
  6938. * <89>PNG
  6939. * <PNG DATA>
  6940. * ------WebKitFormBoundaryRVr */
  6941. /* Extract boundary string from the Content-Type header */
  6942. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  6943. (boundary_start = mg_strcasestr(content_type_header, "boundary=")) ==
  6944. NULL ||
  6945. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  6946. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  6947. boundary[0] == '\0') {
  6948. return num_uploaded_files;
  6949. }
  6950. boundary[99] = 0;
  6951. boundary_len = (int)strlen(boundary);
  6952. bl = boundary_len + 4; /* \r\n--<boundary> */
  6953. for (;;) {
  6954. /* Pull in headers */
  6955. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  6956. if ((len < 0) || (len > (int)sizeof(buf))) {
  6957. break;
  6958. }
  6959. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  6960. len += n;
  6961. /* assert(len <= (int) sizeof(buf)); */
  6962. if (len > (int)sizeof(buf)) {
  6963. break;
  6964. }
  6965. }
  6966. if ((headers_len = get_request_len(buf, len)) <= 0) {
  6967. break;
  6968. }
  6969. /* terminate header */
  6970. buf[headers_len - 1] = 0;
  6971. /* Scan for the boundary string and skip it */
  6972. if (buf[0] == '-' && buf[1] == '-' &&
  6973. !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  6974. s = &buf[bl];
  6975. } else {
  6976. s = &buf[2];
  6977. }
  6978. /* Get headers for this part of the multipart message */
  6979. memset(&part_request_info, 0, sizeof(part_request_info));
  6980. parse_http_headers(&s, &part_request_info);
  6981. /* assert(&buf[headers_len-1] == s); */
  6982. if (&buf[headers_len - 1] != s) {
  6983. break;
  6984. }
  6985. /* Fetch file name. */
  6986. sc = get_header(&part_request_info, "Content-Disposition");
  6987. if (!sc) {
  6988. /* invalid part of a multipart message */
  6989. break;
  6990. }
  6991. sc = strstr(sc, "filename");
  6992. if (!sc) {
  6993. /* no filename set */
  6994. break;
  6995. }
  6996. sc += 8; /* skip "filename" */
  6997. fname[0] = '\0';
  6998. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  6999. fname[1023] = 0;
  7000. /* Give up if the headers are not what we expect */
  7001. if (fname[0] == '\0') {
  7002. break;
  7003. }
  7004. /* Construct destination file name. Do not allow paths to have
  7005. * slashes. */
  7006. if ((s = strrchr(fname, '/')) == NULL &&
  7007. (s = strrchr(fname, '\\')) == NULL) {
  7008. s = fname;
  7009. } else {
  7010. s++;
  7011. }
  7012. /* There data is written to a temporary file first. */
  7013. /* Different users should use a different destination_dir. */
  7014. mg_snprintf(conn,
  7015. &truncated,
  7016. path,
  7017. sizeof(path) - 1,
  7018. "%s/%s",
  7019. destination_dir,
  7020. s);
  7021. /* TODO(high): kick client on buffer overflow */
  7022. strcpy(tmp_path, path);
  7023. strcat(tmp_path, "~");
  7024. /* We open the file with exclusive lock held. This guarantee us
  7025. * there is no other thread can save into the same file
  7026. * simultaneously. */
  7027. fp = NULL;
  7028. /* Open file in binary mode. */
  7029. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  7030. break;
  7031. }
  7032. /* Move data to the beginning of the buffer */
  7033. /* part_request_info is no longer valid after this operation */
  7034. /* assert(len >= headers_len); */
  7035. if (len < headers_len) {
  7036. break;
  7037. }
  7038. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  7039. len -= headers_len;
  7040. /* Read POST data, write into file until boundary is found. */
  7041. eof = n = 0;
  7042. do {
  7043. len += n;
  7044. for (i = 0; i < len - bl; i++) {
  7045. if (!memcmp(&buf[i], "\r\n--", 4) &&
  7046. !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  7047. /* Found boundary, that's the end of file data. */
  7048. fwrite(buf, 1, (size_t)i, fp);
  7049. eof = 1;
  7050. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  7051. len -= i + bl;
  7052. break;
  7053. }
  7054. }
  7055. if (!eof && len > bl) {
  7056. fwrite(buf, 1, (size_t)(len - bl), fp);
  7057. memmove(buf, &buf[len - bl], (size_t)bl);
  7058. len = bl;
  7059. }
  7060. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  7061. } while (!eof && (n > 0));
  7062. fclose(fp);
  7063. if (eof) {
  7064. remove(path);
  7065. rename(tmp_path, path);
  7066. num_uploaded_files++;
  7067. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  7068. conn->ctx->callbacks.upload(conn, path);
  7069. }
  7070. } else {
  7071. remove(tmp_path);
  7072. }
  7073. }
  7074. return num_uploaded_files;
  7075. }
  7076. static int get_first_ssl_listener_index(const struct mg_context *ctx)
  7077. {
  7078. unsigned int i;
  7079. int idx = -1;
  7080. if (ctx) {
  7081. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7082. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7083. }
  7084. }
  7085. return idx;
  7086. }
  7087. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7088. {
  7089. char host[1025];
  7090. const char *host_header;
  7091. size_t hostlen;
  7092. host_header = mg_get_header(conn, "Host");
  7093. hostlen = sizeof(host);
  7094. if (host_header != NULL) {
  7095. char *pos;
  7096. mg_strlcpy(host, host_header, hostlen);
  7097. host[hostlen - 1] = '\0';
  7098. pos = strchr(host, ':');
  7099. if (pos != NULL) {
  7100. *pos = '\0';
  7101. }
  7102. } else {
  7103. /* Cannot get host from the Host: header.
  7104. * Fallback to our IP address. */
  7105. if (conn) {
  7106. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7107. }
  7108. }
  7109. /* Send host, port, uri and (if it exists) ?query_string */
  7110. if (conn) {
  7111. mg_printf(conn,
  7112. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7113. host,
  7114. (int)ntohs(
  7115. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7116. conn->request_info.uri,
  7117. (conn->request_info.query_string == NULL) ? "" : "?",
  7118. (conn->request_info.query_string == NULL)
  7119. ? ""
  7120. : conn->request_info.query_string);
  7121. }
  7122. }
  7123. static void
  7124. mg_set_request_handler_type(struct mg_context *ctx,
  7125. const char *uri,
  7126. int is_websocket_handler,
  7127. int is_delete_request,
  7128. mg_request_handler handler,
  7129. mg_websocket_connect_handler connect_handler,
  7130. mg_websocket_ready_handler ready_handler,
  7131. mg_websocket_data_handler data_handler,
  7132. mg_websocket_close_handler close_handler,
  7133. void *cbdata)
  7134. {
  7135. struct mg_request_handler_info *tmp_rh, **lastref;
  7136. size_t urilen = strlen(uri);
  7137. if (is_websocket_handler) {
  7138. /* assert(handler == NULL); */
  7139. /* assert(is_delete_request || connect_handler!=NULL ||
  7140. * ready_handler!=NULL || data_handler!=NULL ||
  7141. * close_handler!=NULL);
  7142. */
  7143. if (handler != NULL) {
  7144. return;
  7145. }
  7146. if (!is_delete_request && connect_handler == NULL &&
  7147. ready_handler == NULL && data_handler == NULL &&
  7148. close_handler == NULL) {
  7149. return;
  7150. }
  7151. } else {
  7152. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7153. * data_handler==NULL && close_handler==NULL); */
  7154. /* assert(is_delete_request || (handler!=NULL));
  7155. */
  7156. if (connect_handler != NULL || ready_handler != NULL ||
  7157. data_handler != NULL || close_handler != NULL) {
  7158. return;
  7159. }
  7160. if (!is_delete_request && (handler == NULL)) {
  7161. return;
  7162. }
  7163. }
  7164. if (!ctx) {
  7165. return;
  7166. }
  7167. mg_lock_context(ctx);
  7168. /* first try to find an existing handler */
  7169. lastref = &(ctx->request_handlers);
  7170. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  7171. tmp_rh = tmp_rh->next) {
  7172. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  7173. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7174. if (!is_delete_request) {
  7175. /* update existing handler */
  7176. if (!is_websocket_handler) {
  7177. tmp_rh->handler = handler;
  7178. } else {
  7179. tmp_rh->connect_handler = connect_handler;
  7180. tmp_rh->ready_handler = ready_handler;
  7181. tmp_rh->data_handler = data_handler;
  7182. tmp_rh->close_handler = close_handler;
  7183. }
  7184. tmp_rh->cbdata = cbdata;
  7185. } else {
  7186. /* remove existing handler */
  7187. *lastref = tmp_rh->next;
  7188. mg_free(tmp_rh->uri);
  7189. mg_free(tmp_rh);
  7190. }
  7191. mg_unlock_context(ctx);
  7192. return;
  7193. }
  7194. }
  7195. lastref = &(tmp_rh->next);
  7196. }
  7197. if (is_delete_request) {
  7198. /* no handler to set, this was a remove request to a non-existing
  7199. * handler */
  7200. mg_unlock_context(ctx);
  7201. return;
  7202. }
  7203. tmp_rh = (struct mg_request_handler_info *)mg_calloc(
  7204. sizeof(struct mg_request_handler_info), 1);
  7205. if (tmp_rh == NULL) {
  7206. mg_unlock_context(ctx);
  7207. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7208. return;
  7209. }
  7210. tmp_rh->uri = mg_strdup(uri);
  7211. if (!tmp_rh->uri) {
  7212. mg_unlock_context(ctx);
  7213. mg_free(tmp_rh);
  7214. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7215. return;
  7216. }
  7217. tmp_rh->uri_len = urilen;
  7218. if (!is_websocket_handler) {
  7219. tmp_rh->handler = handler;
  7220. } else {
  7221. tmp_rh->connect_handler = connect_handler;
  7222. tmp_rh->ready_handler = ready_handler;
  7223. tmp_rh->data_handler = data_handler;
  7224. tmp_rh->close_handler = close_handler;
  7225. }
  7226. tmp_rh->cbdata = cbdata;
  7227. tmp_rh->is_websocket_handler = is_websocket_handler;
  7228. tmp_rh->next = NULL;
  7229. *lastref = tmp_rh;
  7230. mg_unlock_context(ctx);
  7231. }
  7232. void mg_set_request_handler(struct mg_context *ctx,
  7233. const char *uri,
  7234. mg_request_handler handler,
  7235. void *cbdata)
  7236. {
  7237. mg_set_request_handler_type(
  7238. ctx, uri, 0, handler == NULL, handler, NULL, NULL, NULL, NULL, cbdata);
  7239. }
  7240. void mg_set_websocket_handler(struct mg_context *ctx,
  7241. const char *uri,
  7242. mg_websocket_connect_handler connect_handler,
  7243. mg_websocket_ready_handler ready_handler,
  7244. mg_websocket_data_handler data_handler,
  7245. mg_websocket_close_handler close_handler,
  7246. void *cbdata)
  7247. {
  7248. int is_delete_request = (connect_handler == NULL) &&
  7249. (ready_handler == NULL) && (data_handler == NULL) &&
  7250. (close_handler == NULL);
  7251. mg_set_request_handler_type(ctx,
  7252. uri,
  7253. 1,
  7254. is_delete_request,
  7255. NULL,
  7256. connect_handler,
  7257. ready_handler,
  7258. data_handler,
  7259. close_handler,
  7260. cbdata);
  7261. }
  7262. static int get_request_handler(struct mg_connection *conn,
  7263. int is_websocket_request,
  7264. mg_request_handler *handler,
  7265. mg_websocket_connect_handler *connect_handler,
  7266. mg_websocket_ready_handler *ready_handler,
  7267. mg_websocket_data_handler *data_handler,
  7268. mg_websocket_close_handler *close_handler,
  7269. void **cbdata)
  7270. {
  7271. const struct mg_request_info *request_info = mg_get_request_info(conn);
  7272. if (request_info) {
  7273. const char *uri = request_info->uri;
  7274. size_t urilen = strlen(uri);
  7275. struct mg_request_handler_info *tmp_rh;
  7276. if (!conn || !conn->ctx) {
  7277. return 0;
  7278. }
  7279. mg_lock_context(conn->ctx);
  7280. /* first try for an exact match */
  7281. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7282. tmp_rh = tmp_rh->next) {
  7283. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7284. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7285. if (is_websocket_request) {
  7286. *connect_handler = tmp_rh->connect_handler;
  7287. *ready_handler = tmp_rh->ready_handler;
  7288. *data_handler = tmp_rh->data_handler;
  7289. *close_handler = tmp_rh->close_handler;
  7290. } else {
  7291. *handler = tmp_rh->handler;
  7292. }
  7293. *cbdata = tmp_rh->cbdata;
  7294. mg_unlock_context(conn->ctx);
  7295. return 1;
  7296. }
  7297. }
  7298. }
  7299. /* next try for a partial match, we will accept uri/something */
  7300. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7301. tmp_rh = tmp_rh->next) {
  7302. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7303. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/' &&
  7304. memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  7305. if (is_websocket_request) {
  7306. *connect_handler = tmp_rh->connect_handler;
  7307. *ready_handler = tmp_rh->ready_handler;
  7308. *data_handler = tmp_rh->data_handler;
  7309. *close_handler = tmp_rh->close_handler;
  7310. } else {
  7311. *handler = tmp_rh->handler;
  7312. }
  7313. *cbdata = tmp_rh->cbdata;
  7314. mg_unlock_context(conn->ctx);
  7315. return 1;
  7316. }
  7317. }
  7318. }
  7319. /* finally try for pattern match */
  7320. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7321. tmp_rh = tmp_rh->next) {
  7322. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7323. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  7324. if (is_websocket_request) {
  7325. *connect_handler = tmp_rh->connect_handler;
  7326. *ready_handler = tmp_rh->ready_handler;
  7327. *data_handler = tmp_rh->data_handler;
  7328. *close_handler = tmp_rh->close_handler;
  7329. } else {
  7330. *handler = tmp_rh->handler;
  7331. }
  7332. *cbdata = tmp_rh->cbdata;
  7333. mg_unlock_context(conn->ctx);
  7334. return 1;
  7335. }
  7336. }
  7337. }
  7338. mg_unlock_context(conn->ctx);
  7339. }
  7340. return 0; /* none found */
  7341. }
  7342. #if defined(USE_WEBSOCKET)
  7343. static int
  7344. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  7345. void *cbdata)
  7346. {
  7347. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7348. if (pcallbacks->websocket_connect) {
  7349. return pcallbacks->websocket_connect(conn);
  7350. }
  7351. /* No handler set - assume "OK" */
  7352. return 0;
  7353. }
  7354. static void deprecated_websocket_ready_wrapper(struct mg_connection *conn,
  7355. void *cbdata)
  7356. {
  7357. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7358. if (pcallbacks->websocket_ready) {
  7359. pcallbacks->websocket_ready(conn);
  7360. }
  7361. }
  7362. static int deprecated_websocket_data_wrapper(
  7363. struct mg_connection *conn, int bits, char *data, size_t len, void *cbdata)
  7364. {
  7365. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7366. if (pcallbacks->websocket_data) {
  7367. return pcallbacks->websocket_data(conn, bits, data, len);
  7368. }
  7369. /* No handler set - assume "OK" */
  7370. return 1;
  7371. }
  7372. #endif
  7373. /* This is the heart of the Civetweb's logic.
  7374. * This function is called when the request is read, parsed and validated,
  7375. * and Civetweb must decide what action to take: serve a file, or
  7376. * a directory, or call embedded function, etcetera. */
  7377. static void handle_request(struct mg_connection *conn)
  7378. {
  7379. if (conn) {
  7380. struct mg_request_info *ri = &conn->request_info;
  7381. char path[PATH_MAX];
  7382. int uri_len, ssl_index;
  7383. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  7384. is_put_or_delete_request = 0, is_callback_resource = 0;
  7385. int i;
  7386. struct file file = STRUCT_FILE_INITIALIZER;
  7387. mg_request_handler callback_handler = NULL;
  7388. mg_websocket_connect_handler ws_connect_handler = NULL;
  7389. mg_websocket_ready_handler ws_ready_handler = NULL;
  7390. mg_websocket_data_handler ws_data_handler = NULL;
  7391. mg_websocket_close_handler ws_close_handler = NULL;
  7392. void *callback_data = NULL;
  7393. #if !defined(NO_FILES)
  7394. time_t curtime = time(NULL);
  7395. char date[64];
  7396. #endif
  7397. path[0] = 0;
  7398. if (!ri) {
  7399. return;
  7400. }
  7401. /* 1. get the request url */
  7402. /* 1.1. split into url and query string */
  7403. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  7404. *((char *)conn->request_info.query_string++) = '\0';
  7405. }
  7406. uri_len = (int)strlen(ri->uri);
  7407. /* 1.2. decode url (if config says so) */
  7408. if (should_decode_url(conn)) {
  7409. mg_url_decode(ri->uri, uri_len, (char *)ri->uri, uri_len + 1, 0);
  7410. }
  7411. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  7412. * possible */
  7413. remove_double_dots_and_double_slashes((char *)ri->uri);
  7414. /* step 1. completed, the url is known now */
  7415. DEBUG_TRACE("URL: %s", ri->uri);
  7416. /* 2. do a https redirect, if required */
  7417. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  7418. ssl_index = get_first_ssl_listener_index(conn->ctx);
  7419. if (ssl_index >= 0) {
  7420. redirect_to_https_port(conn, ssl_index);
  7421. } else {
  7422. /* A http to https forward port has been specified,
  7423. * but no https port to forward to. */
  7424. send_http_error(conn,
  7425. 503,
  7426. "%s",
  7427. "Error: SSL forward not configured properly");
  7428. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  7429. }
  7430. return;
  7431. }
  7432. /* 3. if this ip has limited speed, set it for this connection */
  7433. conn->throttle = set_throttle(
  7434. conn->ctx->config[THROTTLE], get_remote_ip(conn), ri->uri);
  7435. /* 4. call a "handle everything" callback, if registered */
  7436. if (conn->ctx->callbacks.begin_request != NULL) {
  7437. /* Note that since V1.7 the "begin_request" function is called
  7438. * before an authorization check. If an authorization check is
  7439. * required, use a request_handler instead. */
  7440. i = conn->ctx->callbacks.begin_request(conn);
  7441. if (i > 0) {
  7442. /* callback already processed the request. Store the
  7443. return value as a status code for the access log. */
  7444. conn->status_code = i;
  7445. return;
  7446. } else if (i == 0) {
  7447. /* civetweb should process the request */
  7448. } else {
  7449. /* unspecified - may change with the next version */
  7450. return;
  7451. }
  7452. }
  7453. /* request not yet handled by a handler or redirect, so the request
  7454. * is processed here */
  7455. /* 5. interpret the url to find out how the request must be handled */
  7456. /* 5.1. first test, if the request targets the regular http(s)://
  7457. * protocol namespace or the websocket ws(s):// protocol namespace. */
  7458. is_websocket_request = is_websocket_protocol(conn);
  7459. /* 5.2. check if the request will be handled by a callback */
  7460. if (get_request_handler(conn,
  7461. is_websocket_request,
  7462. &callback_handler,
  7463. &ws_connect_handler,
  7464. &ws_ready_handler,
  7465. &ws_data_handler,
  7466. &ws_close_handler,
  7467. &callback_data)) {
  7468. /* 5.2.1. A callback will handle this request. All requests handled
  7469. * by a callback have to be considered as requests to a script
  7470. * resource. */
  7471. is_callback_resource = 1;
  7472. is_script_resource = 1;
  7473. is_put_or_delete_request = is_put_or_delete_method(conn);
  7474. } else {
  7475. no_callback_resource:
  7476. /* 5.2.2. No callback is responsible for this request. The URI
  7477. * addresses a file based resource (static content or Lua/cgi
  7478. * scripts in the file system). */
  7479. is_callback_resource = 0;
  7480. interpret_uri(conn,
  7481. path,
  7482. sizeof(path),
  7483. &file,
  7484. &is_found,
  7485. &is_script_resource,
  7486. &is_websocket_request,
  7487. &is_put_or_delete_request);
  7488. }
  7489. /* 6. authorization check */
  7490. if (is_put_or_delete_request && !is_script_resource &&
  7491. !is_callback_resource) {
  7492. /* 6.1. this request is a PUT/DELETE to a real file */
  7493. /* 6.1.1. thus, the server must have real files */
  7494. #if defined(NO_FILES)
  7495. if (1) {
  7496. #else
  7497. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7498. #endif
  7499. /* This server does not have any real files, thus the
  7500. * PUT/DELETE methods are not valid. */
  7501. send_http_error(conn,
  7502. 405,
  7503. "%s method not allowed",
  7504. conn->request_info.request_method);
  7505. return;
  7506. }
  7507. #if !defined(NO_FILES)
  7508. /* 6.1.2. Check if put authorization for static files is available.
  7509. */
  7510. if (!is_authorized_for_put(conn)) {
  7511. send_authorization_request(conn);
  7512. return;
  7513. }
  7514. #endif
  7515. } else {
  7516. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  7517. * or it is a PUT or DELETE request to a resource that does not
  7518. * correspond to a file. Check authorization. */
  7519. if (!check_authorization(conn, path)) {
  7520. send_authorization_request(conn);
  7521. return;
  7522. }
  7523. }
  7524. /* request is authorized or does not need authorization */
  7525. /* 7. check if there are request handlers for this uri */
  7526. if (is_callback_resource) {
  7527. if (!is_websocket_request) {
  7528. i = callback_handler(conn, callback_data);
  7529. if (i > 0) {
  7530. /* Do nothing, callback has served the request. Store the
  7531. * return value as status code for the log and discard all
  7532. * data from the client not used by the callback. */
  7533. conn->status_code = i;
  7534. discard_unread_request_data(conn);
  7535. } else {
  7536. /* TODO (high): what if the handler did NOT handle the
  7537. * request */
  7538. /* The last version did handle this as a file request, but
  7539. * since a file request is not always a script resource,
  7540. * the authorization check might be different */
  7541. interpret_uri(conn,
  7542. path,
  7543. sizeof(path),
  7544. &file,
  7545. &is_found,
  7546. &is_script_resource,
  7547. &is_websocket_request,
  7548. &is_put_or_delete_request);
  7549. callback_handler = NULL;
  7550. /* TODO (very low): goto is deprecatedm but for the moment,
  7551. * a goto is
  7552. * simpler than some curious loop. */
  7553. /* The situation "callback does not handle the request"
  7554. * needs to be reconsidered anyway. */
  7555. goto no_callback_resource;
  7556. }
  7557. } else {
  7558. #if defined(USE_WEBSOCKET)
  7559. handle_websocket_request(conn,
  7560. path,
  7561. is_callback_resource,
  7562. ws_connect_handler,
  7563. ws_ready_handler,
  7564. ws_data_handler,
  7565. ws_close_handler,
  7566. callback_data);
  7567. #endif
  7568. }
  7569. return;
  7570. }
  7571. /* 8. handle websocket requests */
  7572. #if defined(USE_WEBSOCKET)
  7573. if (is_websocket_request) {
  7574. handle_websocket_request(
  7575. conn,
  7576. path,
  7577. !is_script_resource /* could be deprecated global callback */,
  7578. deprecated_websocket_connect_wrapper,
  7579. deprecated_websocket_ready_wrapper,
  7580. deprecated_websocket_data_wrapper,
  7581. NULL,
  7582. &conn->ctx->callbacks);
  7583. return;
  7584. } else
  7585. #endif
  7586. #if defined(NO_FILES)
  7587. /* 9a. In case the server uses only callbacks, this uri is unknown.
  7588. * Then, all request handling ends here. */
  7589. send_http_error(conn, 404, "%s", "Not Found");
  7590. #else
  7591. /* 9b. This request is either for a static file or resource handled
  7592. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  7593. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7594. send_http_error(conn, 404, "%s", "Not Found");
  7595. return;
  7596. }
  7597. /* 10. File is handled by a script. */
  7598. if (is_script_resource) {
  7599. handle_file_based_request(conn, path, &file);
  7600. return;
  7601. }
  7602. /* 11. Handle put/delete/mkcol requests */
  7603. if (is_put_or_delete_request) {
  7604. /* 11.1. PUT method */
  7605. if (!strcmp(ri->request_method, "PUT")) {
  7606. put_file(conn, path);
  7607. return;
  7608. }
  7609. /* 11.2. DELETE method */
  7610. if (!strcmp(ri->request_method, "DELETE")) {
  7611. delete_file(conn, path);
  7612. return;
  7613. }
  7614. /* 11.3. MKCOL method */
  7615. if (!strcmp(ri->request_method, "MKCOL")) {
  7616. mkcol(conn, path);
  7617. return;
  7618. }
  7619. /* 11.4. PATCH method
  7620. * This method is not supported for static resources,
  7621. * only for scripts (Lua, CGI) and callbacks. */
  7622. send_http_error(conn,
  7623. 405,
  7624. "%s method not allowed",
  7625. conn->request_info.request_method);
  7626. return;
  7627. }
  7628. /* 11. File does not exist, or it was configured that it should be
  7629. * hidden */
  7630. if (!is_found || (must_hide_file(conn, path))) {
  7631. send_http_error(conn, 404, "%s", "Not found");
  7632. return;
  7633. }
  7634. /* 12. Directories uris should end with a slash */
  7635. if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  7636. gmt_time_string(date, sizeof(date), &curtime);
  7637. mg_printf(conn,
  7638. "HTTP/1.1 301 Moved Permanently\r\n"
  7639. "Location: %s/\r\n"
  7640. "Date: %s\r\n"
  7641. "Content-Length: 0\r\n"
  7642. "Connection: %s\r\n\r\n",
  7643. ri->uri,
  7644. date,
  7645. suggest_connection_header(conn));
  7646. return;
  7647. }
  7648. /* 13. Handle other methods than GET/HEAD */
  7649. /* 13.1. Handle PROPFIND */
  7650. if (!strcmp(ri->request_method, "PROPFIND")) {
  7651. handle_propfind(conn, path, &file);
  7652. return;
  7653. }
  7654. /* 13.2. Handle OPTIONS for files */
  7655. if (!strcmp(ri->request_method, "OPTIONS")) {
  7656. /* This standard handler is only used for real files.
  7657. * Scripts should support the OPTIONS method themselves, to allow a
  7658. * maximum flexibility.
  7659. * Lua and CGI scripts may fully support CORS this way (including
  7660. * preflights). */
  7661. send_options(conn);
  7662. return;
  7663. }
  7664. /* 13.3. everything but GET and HEAD (e.g. POST) */
  7665. if (0 != strcmp(ri->request_method, "GET") &&
  7666. 0 != strcmp(ri->request_method, "HEAD")) {
  7667. send_http_error(conn,
  7668. 405,
  7669. "%s method not allowed",
  7670. conn->request_info.request_method);
  7671. return;
  7672. }
  7673. /* 14. directories */
  7674. if (file.is_directory) {
  7675. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  7676. /* 14.1. use a substitute file */
  7677. /* TODO (high): substitute index may be a script resource.
  7678. * define what should be possible in this case. */
  7679. } else {
  7680. /* 14.2. no substitute file */
  7681. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7682. "yes")) {
  7683. handle_directory_request(conn, path);
  7684. } else {
  7685. send_http_error(
  7686. conn, 403, "%s", "Error: Directory listing denied");
  7687. }
  7688. return;
  7689. }
  7690. }
  7691. handle_file_based_request(conn, path, &file);
  7692. #endif /* !defined(NO_FILES) */
  7693. #if 0
  7694. /* Perform redirect and auth checks before calling begin_request()
  7695. * handler.
  7696. * Otherwise, begin_request() would need to perform auth checks and
  7697. * redirects. */
  7698. #endif
  7699. }
  7700. return;
  7701. }
  7702. static void handle_file_based_request(struct mg_connection *conn,
  7703. const char *path,
  7704. struct file *file)
  7705. {
  7706. if (!conn || !conn->ctx) {
  7707. return;
  7708. }
  7709. if (0) {
  7710. #ifdef USE_LUA
  7711. } else if (match_prefix(
  7712. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  7713. strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  7714. path) > 0) {
  7715. /* Lua server page: an SSI like page containing mostly plain html code
  7716. * plus some tags with server generated contents. */
  7717. handle_lsp_request(conn, path, file, NULL);
  7718. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  7719. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  7720. path) > 0) {
  7721. /* Lua in-server module script: a CGI like script used to generate the
  7722. * entire reply. */
  7723. mg_exec_lua_script(conn, path, NULL);
  7724. #endif
  7725. #if !defined(NO_CGI)
  7726. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  7727. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  7728. path) > 0) {
  7729. /* CGI scripts may support all HTTP methods */
  7730. handle_cgi_request(conn, path);
  7731. #endif /* !NO_CGI */
  7732. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7733. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7734. path) > 0) {
  7735. handle_ssi_file_request(conn, path, file);
  7736. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  7737. /* Send 304 "Not Modified" - this must not send any body data */
  7738. send_http_error(conn, 304, "%s", "");
  7739. } else {
  7740. handle_static_file_request(conn, path, file);
  7741. }
  7742. }
  7743. static void close_all_listening_sockets(struct mg_context *ctx)
  7744. {
  7745. unsigned int i;
  7746. if (!ctx) {
  7747. return;
  7748. }
  7749. for (i = 0; i < ctx->num_listening_sockets; i++) {
  7750. closesocket(ctx->listening_sockets[i].sock);
  7751. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  7752. }
  7753. mg_free(ctx->listening_sockets);
  7754. ctx->listening_sockets = NULL;
  7755. mg_free(ctx->listening_ports);
  7756. ctx->listening_ports = NULL;
  7757. }
  7758. /* Valid listening port specification is: [ip_address:]port[s]
  7759. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  7760. * Examples for IPv6: [::]:80, [::1]:80,
  7761. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  7762. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  7763. static int parse_port_string(const struct vec *vec, struct socket *so)
  7764. {
  7765. unsigned int a, b, c, d, port;
  7766. int ch, len;
  7767. #if defined(USE_IPV6)
  7768. char buf[100] = {0};
  7769. #endif
  7770. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  7771. * Also, all-zeroes in the socket address means binding to all addresses
  7772. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  7773. memset(so, 0, sizeof(*so));
  7774. so->lsa.sin.sin_family = AF_INET;
  7775. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) ==
  7776. 5) {
  7777. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  7778. so->lsa.sin.sin_addr.s_addr =
  7779. htonl((a << 24) | (b << 16) | (c << 8) | d);
  7780. so->lsa.sin.sin_port = htons((uint16_t)port);
  7781. #if defined(USE_IPV6)
  7782. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
  7783. mg_inet_pton(
  7784. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  7785. /* IPv6 address, examples: see above */
  7786. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */
  7787. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  7788. #endif
  7789. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  7790. /* If only port is specified, bind to IPv4, INADDR_ANY */
  7791. so->lsa.sin.sin_port = htons((uint16_t)port);
  7792. } else {
  7793. /* Parsing failure. Make port invalid. */
  7794. port = 0;
  7795. len = 0;
  7796. }
  7797. /* sscanf and the option splitting code ensure the following condition */
  7798. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  7799. return 0;
  7800. }
  7801. ch = vec->ptr[len]; /* Next character after the port number */
  7802. so->is_ssl = (ch == 's');
  7803. so->ssl_redir = (ch == 'r');
  7804. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  7805. return is_valid_port(port) &&
  7806. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  7807. }
  7808. static int set_ports_option(struct mg_context *ctx)
  7809. {
  7810. const char *list;
  7811. int on = 1;
  7812. #if defined(USE_IPV6)
  7813. int off = 0;
  7814. #endif
  7815. struct vec vec;
  7816. struct socket so, *ptr;
  7817. in_port_t *portPtr;
  7818. union usa usa;
  7819. socklen_t len;
  7820. int portsTotal = 0;
  7821. int portsOk = 0;
  7822. if (!ctx) {
  7823. return 0;
  7824. }
  7825. memset(&so, 0, sizeof(so));
  7826. memset(&usa, 0, sizeof(usa));
  7827. len = sizeof(usa);
  7828. list = ctx->config[LISTENING_PORTS];
  7829. while ((list = next_option(list, &vec, NULL)) != NULL) {
  7830. portsTotal++;
  7831. if (!parse_port_string(&vec, &so)) {
  7832. mg_cry(fc(ctx),
  7833. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  7834. (int)vec.len,
  7835. vec.ptr,
  7836. portsTotal,
  7837. "[IP_ADDRESS:]PORT[s|r]");
  7838. continue;
  7839. }
  7840. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  7841. mg_cry(fc(ctx),
  7842. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  7843. "option set?",
  7844. portsTotal);
  7845. continue;
  7846. }
  7847. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  7848. INVALID_SOCKET) {
  7849. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  7850. continue;
  7851. }
  7852. #ifdef _WIN32
  7853. /* Windows SO_REUSEADDR lets many procs binds to a
  7854. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  7855. * if someone already has the socket -- DTL */
  7856. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  7857. * Windows might need a few seconds before
  7858. * the same port can be used again in the
  7859. * same process, so a short Sleep may be
  7860. * required between mg_stop and mg_start.
  7861. */
  7862. if (setsockopt(so.sock,
  7863. SOL_SOCKET,
  7864. SO_EXCLUSIVEADDRUSE,
  7865. (SOCK_OPT_TYPE)&on,
  7866. sizeof(on)) != 0) {
  7867. mg_cry(fc(ctx),
  7868. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  7869. portsTotal);
  7870. }
  7871. #else
  7872. if (setsockopt(so.sock,
  7873. SOL_SOCKET,
  7874. SO_REUSEADDR,
  7875. (SOCK_OPT_TYPE)&on,
  7876. sizeof(on)) != 0) {
  7877. mg_cry(fc(ctx),
  7878. "cannot set socket option SO_REUSEADDR (entry %i)",
  7879. portsTotal);
  7880. }
  7881. #endif
  7882. #if defined(USE_IPV6)
  7883. if (so.lsa.sa.sa_family == AF_INET6 &&
  7884. setsockopt(so.sock,
  7885. IPPROTO_IPV6,
  7886. IPV6_V6ONLY,
  7887. (void *)&off,
  7888. sizeof(off)) != 0) {
  7889. mg_cry(fc(ctx),
  7890. "cannot set socket option IPV6_V6ONLY (entry %i)",
  7891. portsTotal);
  7892. }
  7893. #endif
  7894. if (so.lsa.sa.sa_family == AF_INET) {
  7895. len = sizeof(so.lsa.sin);
  7896. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  7897. mg_cry(fc(ctx),
  7898. "cannot bind to %.*s: %d (%s)",
  7899. (int)vec.len,
  7900. vec.ptr,
  7901. (int)ERRNO,
  7902. strerror(errno));
  7903. closesocket(so.sock);
  7904. so.sock = INVALID_SOCKET;
  7905. continue;
  7906. }
  7907. }
  7908. #if defined(USE_IPV6)
  7909. else if (so.lsa.sa.sa_family == AF_INET6) {
  7910. len = sizeof(so.lsa.sin6);
  7911. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  7912. mg_cry(fc(ctx),
  7913. "cannot bind to IPv6 %.*s: %d (%s)",
  7914. (int)vec.len,
  7915. vec.ptr,
  7916. (int)ERRNO,
  7917. strerror(errno));
  7918. closesocket(so.sock);
  7919. so.sock = INVALID_SOCKET;
  7920. continue;
  7921. }
  7922. }
  7923. #endif
  7924. else {
  7925. mg_cry(fc(ctx),
  7926. "cannot bind: address family not supported (entry %i)",
  7927. portsTotal);
  7928. continue;
  7929. }
  7930. if (listen(so.sock, SOMAXCONN) != 0) {
  7931. mg_cry(fc(ctx),
  7932. "cannot listen to %.*s: %d (%s)",
  7933. (int)vec.len,
  7934. vec.ptr,
  7935. (int)ERRNO,
  7936. strerror(errno));
  7937. closesocket(so.sock);
  7938. so.sock = INVALID_SOCKET;
  7939. continue;
  7940. }
  7941. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  7942. int err = (int)ERRNO;
  7943. mg_cry(fc(ctx),
  7944. "call to getsockname failed %.*s: %d (%s)",
  7945. (int)vec.len,
  7946. vec.ptr,
  7947. err,
  7948. strerror(errno));
  7949. closesocket(so.sock);
  7950. so.sock = INVALID_SOCKET;
  7951. continue;
  7952. }
  7953. if ((ptr = (struct socket *)mg_realloc(
  7954. ctx->listening_sockets,
  7955. (ctx->num_listening_sockets + 1) *
  7956. sizeof(ctx->listening_sockets[0]))) == NULL) {
  7957. mg_cry(fc(ctx), "%s", "Out of memory");
  7958. closesocket(so.sock);
  7959. so.sock = INVALID_SOCKET;
  7960. continue;
  7961. }
  7962. if ((portPtr = (in_port_t *)mg_realloc(
  7963. ctx->listening_ports,
  7964. (ctx->num_listening_sockets + 1) *
  7965. sizeof(ctx->listening_ports[0]))) == NULL) {
  7966. mg_cry(fc(ctx), "%s", "Out of memory");
  7967. closesocket(so.sock);
  7968. so.sock = INVALID_SOCKET;
  7969. mg_free(ptr);
  7970. continue;
  7971. }
  7972. set_close_on_exec(so.sock, fc(ctx));
  7973. ctx->listening_sockets = ptr;
  7974. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  7975. ctx->listening_ports = portPtr;
  7976. ctx->listening_ports[ctx->num_listening_sockets] =
  7977. ntohs(usa.sin.sin_port);
  7978. ctx->num_listening_sockets++;
  7979. portsOk++;
  7980. }
  7981. if (portsOk != portsTotal) {
  7982. close_all_listening_sockets(ctx);
  7983. portsOk = 0;
  7984. }
  7985. return portsOk;
  7986. }
  7987. static const char *header_val(const struct mg_connection *conn,
  7988. const char *header)
  7989. {
  7990. const char *header_value;
  7991. if ((header_value = mg_get_header(conn, header)) == NULL) {
  7992. return "-";
  7993. } else {
  7994. return header_value;
  7995. }
  7996. }
  7997. static void log_access(const struct mg_connection *conn)
  7998. {
  7999. const struct mg_request_info *ri;
  8000. FILE *fp;
  8001. char date[64], src_addr[IP_ADDR_STR_LEN];
  8002. struct tm *tm;
  8003. const char *referer;
  8004. const char *user_agent;
  8005. char buf[4096];
  8006. if (!conn || !conn->ctx) {
  8007. return;
  8008. }
  8009. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  8010. ? NULL
  8011. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  8012. if (fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8013. return;
  8014. }
  8015. tm = localtime(&conn->conn_birth_time);
  8016. if (tm != NULL) {
  8017. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8018. } else {
  8019. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8020. date[sizeof(date) - 1] = '\0';
  8021. }
  8022. ri = &conn->request_info;
  8023. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8024. referer = header_val(conn, "Referer");
  8025. user_agent = header_val(conn, "User-Agent");
  8026. mg_snprintf(conn,
  8027. NULL, /* Ignore truncation in access log */
  8028. buf,
  8029. sizeof(buf),
  8030. "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT " %s %s",
  8031. src_addr,
  8032. ri->remote_user == NULL ? "-" : ri->remote_user,
  8033. date,
  8034. ri->request_method ? ri->request_method : "-",
  8035. ri->uri ? ri->uri : "-",
  8036. ri->http_version,
  8037. conn->status_code,
  8038. conn->num_bytes_sent,
  8039. referer,
  8040. user_agent);
  8041. if (conn->ctx->callbacks.log_access) {
  8042. conn->ctx->callbacks.log_access(conn, buf);
  8043. }
  8044. if (fp) {
  8045. flockfile(fp);
  8046. fprintf(fp, "%s", buf);
  8047. fputc('\n', fp);
  8048. fflush(fp);
  8049. funlockfile(fp);
  8050. fclose(fp);
  8051. }
  8052. }
  8053. /* Verify given socket address against the ACL.
  8054. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  8055. static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
  8056. {
  8057. int allowed, flag;
  8058. uint32_t net, mask;
  8059. struct vec vec;
  8060. if (ctx) {
  8061. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  8062. /* If any ACL is set, deny by default */
  8063. allowed = list == NULL ? '+' : '-';
  8064. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8065. flag = vec.ptr[0];
  8066. if ((flag != '+' && flag != '-') ||
  8067. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  8068. mg_cry(
  8069. fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  8070. return -1;
  8071. }
  8072. if (net == (remote_ip & mask)) {
  8073. allowed = flag;
  8074. }
  8075. }
  8076. return allowed == '+';
  8077. }
  8078. return -1;
  8079. }
  8080. #if !defined(_WIN32)
  8081. static int set_uid_option(struct mg_context *ctx)
  8082. {
  8083. struct passwd *pw;
  8084. if (ctx) {
  8085. const char *uid = ctx->config[RUN_AS_USER];
  8086. int success = 0;
  8087. if (uid == NULL) {
  8088. success = 1;
  8089. } else {
  8090. if ((pw = getpwnam(uid)) == NULL) {
  8091. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  8092. } else if (setgid(pw->pw_gid) == -1) {
  8093. mg_cry(fc(ctx),
  8094. "%s: setgid(%s): %s",
  8095. __func__,
  8096. uid,
  8097. strerror(errno));
  8098. } else if (setgroups(0, NULL)) {
  8099. mg_cry(
  8100. fc(ctx), "%s: setgroups(): %s", __func__, strerror(errno));
  8101. } else if (setuid(pw->pw_uid) == -1) {
  8102. mg_cry(fc(ctx),
  8103. "%s: setuid(%s): %s",
  8104. __func__,
  8105. uid,
  8106. strerror(errno));
  8107. } else {
  8108. success = 1;
  8109. }
  8110. }
  8111. return success;
  8112. }
  8113. return 0;
  8114. }
  8115. #endif /* !_WIN32 */
  8116. #if !defined(NO_SSL)
  8117. static pthread_mutex_t *ssl_mutexes;
  8118. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  8119. {
  8120. if (!conn) {
  8121. return 0;
  8122. }
  8123. return (conn->ssl = SSL_new(s)) != NULL &&
  8124. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  8125. func(conn->ssl) == 1;
  8126. }
  8127. /* Return OpenSSL error message (from CRYPTO lib) */
  8128. static const char *ssl_error(void)
  8129. {
  8130. unsigned long err;
  8131. err = ERR_get_error();
  8132. return err == 0 ? "" : ERR_error_string(err, NULL);
  8133. }
  8134. static void
  8135. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  8136. {
  8137. (void)line;
  8138. (void)file;
  8139. if (mode & 1) {
  8140. /* 1 is CRYPTO_LOCK */
  8141. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  8142. } else {
  8143. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  8144. }
  8145. }
  8146. static unsigned long ssl_id_callback(void)
  8147. {
  8148. return (unsigned long)pthread_self();
  8149. }
  8150. #if !defined(NO_SSL_DL)
  8151. static void *
  8152. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  8153. {
  8154. union {
  8155. void *p;
  8156. void (*fp)(void);
  8157. } u;
  8158. void *dll_handle;
  8159. struct ssl_func *fp;
  8160. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  8161. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  8162. return NULL;
  8163. }
  8164. for (fp = sw; fp->name != NULL; fp++) {
  8165. #ifdef _WIN32
  8166. /* GetProcAddress() returns pointer to function */
  8167. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  8168. #else
  8169. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  8170. * pointers to function pointers. We need to use a union to make a
  8171. * cast. */
  8172. u.p = dlsym(dll_handle, fp->name);
  8173. #endif /* _WIN32 */
  8174. if (u.fp == NULL) {
  8175. mg_cry(fc(ctx),
  8176. "%s: %s: cannot find %s",
  8177. __func__,
  8178. dll_name,
  8179. fp->name);
  8180. dlclose(dll_handle);
  8181. return NULL;
  8182. } else {
  8183. fp->ptr = u.fp;
  8184. }
  8185. }
  8186. return dll_handle;
  8187. }
  8188. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  8189. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  8190. #endif /* NO_SSL_DL */
  8191. #if defined(SSL_ALREADY_INITIALIZED)
  8192. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  8193. #else
  8194. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  8195. #endif
  8196. static int initialize_ssl(struct mg_context *ctx)
  8197. {
  8198. int i;
  8199. size_t size;
  8200. #if !defined(NO_SSL_DL)
  8201. if (!cryptolib_dll_handle) {
  8202. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  8203. if (!cryptolib_dll_handle) {
  8204. return 0;
  8205. }
  8206. }
  8207. #endif /* NO_SSL_DL */
  8208. if (mg_atomic_inc(&cryptolib_users) > 1) {
  8209. return 1;
  8210. }
  8211. /* Initialize locking callbacks, needed for thread safety.
  8212. * http://www.openssl.org/support/faq.html#PROG1
  8213. */
  8214. i = CRYPTO_num_locks();
  8215. if (i < 0) {
  8216. i = 0;
  8217. }
  8218. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  8219. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  8220. mg_cry(
  8221. fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  8222. return 0;
  8223. }
  8224. for (i = 0; i < CRYPTO_num_locks(); i++) {
  8225. pthread_mutex_init(&ssl_mutexes[i], NULL);
  8226. }
  8227. CRYPTO_set_locking_callback(&ssl_locking_callback);
  8228. CRYPTO_set_id_callback(&ssl_id_callback);
  8229. return 1;
  8230. }
  8231. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  8232. static int set_ssl_option(struct mg_context *ctx)
  8233. {
  8234. const char *pem;
  8235. int callback_ret;
  8236. /* If PEM file is not specified and the init_ssl callback
  8237. * is not specified, skip SSL initialization. */
  8238. if (!ctx) {
  8239. return 0;
  8240. }
  8241. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  8242. ctx->callbacks.init_ssl == NULL) {
  8243. return 1;
  8244. }
  8245. if (!initialize_ssl(ctx)) {
  8246. return 0;
  8247. }
  8248. #if !defined(NO_SSL_DL)
  8249. if (!ssllib_dll_handle) {
  8250. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  8251. if (!ssllib_dll_handle) {
  8252. return 0;
  8253. }
  8254. }
  8255. #endif /* NO_SSL_DL */
  8256. /* Initialize SSL library */
  8257. SSL_library_init();
  8258. SSL_load_error_strings();
  8259. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  8260. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  8261. return 0;
  8262. }
  8263. /* If a callback has been specified, call it. */
  8264. callback_ret =
  8265. (ctx->callbacks.init_ssl == NULL)
  8266. ? 0
  8267. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  8268. /* If callback returns 0, civetweb sets up the SSL certificate.
  8269. * If it returns 1, civetweb assumes the calback already did this.
  8270. * If it returns -1, initializing ssl fails. */
  8271. if (callback_ret < 0) {
  8272. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  8273. return 0;
  8274. }
  8275. if (callback_ret == 0) {
  8276. if (pem != NULL) {
  8277. if ((SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) ||
  8278. (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  8279. mg_cry(fc(ctx),
  8280. "%s: cannot open %s: %s",
  8281. __func__,
  8282. pem,
  8283. ssl_error());
  8284. return 0;
  8285. }
  8286. }
  8287. }
  8288. if (pem != NULL) {
  8289. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  8290. }
  8291. return 1;
  8292. }
  8293. static void uninitialize_ssl(struct mg_context *ctx)
  8294. {
  8295. int i;
  8296. (void)ctx;
  8297. if (mg_atomic_dec(&cryptolib_users) == 0) {
  8298. CRYPTO_set_locking_callback(NULL);
  8299. for (i = 0; i < CRYPTO_num_locks(); i++) {
  8300. pthread_mutex_destroy(&ssl_mutexes[i]);
  8301. }
  8302. CRYPTO_set_locking_callback(NULL);
  8303. CRYPTO_set_id_callback(NULL);
  8304. }
  8305. }
  8306. #endif /* !NO_SSL */
  8307. static int set_gpass_option(struct mg_context *ctx)
  8308. {
  8309. if (ctx) {
  8310. struct file file = STRUCT_FILE_INITIALIZER;
  8311. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  8312. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  8313. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  8314. return 0;
  8315. }
  8316. return 1;
  8317. }
  8318. return 0;
  8319. }
  8320. static int set_acl_option(struct mg_context *ctx)
  8321. {
  8322. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  8323. }
  8324. static void reset_per_request_attributes(struct mg_connection *conn)
  8325. {
  8326. if (!conn) {
  8327. return;
  8328. }
  8329. conn->path_info = NULL;
  8330. conn->num_bytes_sent = conn->consumed_content = 0;
  8331. conn->status_code = -1;
  8332. conn->is_chunked = 0;
  8333. conn->must_close = conn->request_len = conn->throttle = 0;
  8334. conn->request_info.content_length = -1;
  8335. conn->request_info.remote_user = NULL;
  8336. conn->request_info.request_method = NULL;
  8337. conn->request_info.uri = NULL;
  8338. conn->request_info.http_version = NULL;
  8339. conn->request_info.num_headers = 0;
  8340. conn->data_len = 0;
  8341. conn->chunk_remainder = 0;
  8342. conn->internal_error = 0;
  8343. }
  8344. static int set_sock_timeout(SOCKET sock, int milliseconds)
  8345. {
  8346. int r1, r2;
  8347. #ifdef _WIN32
  8348. DWORD t = (DWORD)milliseconds;
  8349. #else
  8350. #if defined(TCP_USER_TIMEOUT)
  8351. unsigned int uto = (unsigned int)milliseconds;
  8352. #endif
  8353. struct timeval t;
  8354. t.tv_sec = milliseconds / 1000;
  8355. t.tv_usec = (milliseconds * 1000) % 1000000;
  8356. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  8357. * max. time waiting for the acknowledged of TCP data before the connection
  8358. * will be forcefully closed and ETIMEDOUT is returned to the application.
  8359. * If this option is not set, the default timeout of 20-30 minutes is used.
  8360. */
  8361. /* #define TCP_USER_TIMEOUT (18) */
  8362. #if defined(TCP_USER_TIMEOUT)
  8363. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  8364. #endif
  8365. #endif
  8366. r1 =
  8367. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  8368. r2 =
  8369. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  8370. return r1 || r2;
  8371. }
  8372. static void close_socket_gracefully(struct mg_connection *conn)
  8373. {
  8374. #if defined(_WIN32)
  8375. char buf[MG_BUF_LEN];
  8376. int n;
  8377. #endif
  8378. struct linger linger;
  8379. if (!conn) {
  8380. return;
  8381. }
  8382. /* Set linger option to avoid socket hanging out after close. This prevent
  8383. * ephemeral port exhaust problem under high QPS. */
  8384. linger.l_onoff = 1;
  8385. linger.l_linger = 1;
  8386. if (setsockopt(conn->client.sock,
  8387. SOL_SOCKET,
  8388. SO_LINGER,
  8389. (char *)&linger,
  8390. sizeof(linger)) != 0) {
  8391. mg_cry(conn,
  8392. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  8393. __func__,
  8394. strerror(ERRNO));
  8395. }
  8396. /* Send FIN to the client */
  8397. shutdown(conn->client.sock, SHUT_WR);
  8398. set_non_blocking_mode(conn->client.sock);
  8399. #if defined(_WIN32)
  8400. /* Read and discard pending incoming data. If we do not do that and close
  8401. * the socket, the data in the send buffer may be discarded. This
  8402. * behaviour is seen on Windows, when client keeps sending data
  8403. * when server decides to close the connection; then when client
  8404. * does recv() it gets no data back. */
  8405. do {
  8406. n = pull(
  8407. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  8408. } while (n > 0);
  8409. #endif
  8410. /* Now we know that our FIN is ACK-ed, safe to close */
  8411. closesocket(conn->client.sock);
  8412. conn->client.sock = INVALID_SOCKET;
  8413. }
  8414. static void close_connection(struct mg_connection *conn)
  8415. {
  8416. if (!conn || !conn->ctx) {
  8417. return;
  8418. }
  8419. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  8420. if (conn->lua_websocket_state) {
  8421. lua_websocket_close(conn, conn->lua_websocket_state);
  8422. conn->lua_websocket_state = NULL;
  8423. }
  8424. #endif
  8425. /* call the connection_close callback if assigned */
  8426. if ((conn->ctx->callbacks.connection_close != NULL) &&
  8427. (conn->ctx->context_type == 1)) {
  8428. conn->ctx->callbacks.connection_close(conn);
  8429. }
  8430. mg_lock_connection(conn);
  8431. conn->must_close = 1;
  8432. #ifndef NO_SSL
  8433. if (conn->ssl != NULL) {
  8434. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  8435. SSL_shutdown(conn->ssl);
  8436. SSL_free(conn->ssl);
  8437. conn->ssl = NULL;
  8438. }
  8439. #endif
  8440. if (conn->client.sock != INVALID_SOCKET) {
  8441. close_socket_gracefully(conn);
  8442. conn->client.sock = INVALID_SOCKET;
  8443. }
  8444. mg_unlock_connection(conn);
  8445. }
  8446. void mg_close_connection(struct mg_connection *conn)
  8447. {
  8448. struct mg_context *client_ctx = NULL;
  8449. unsigned int i;
  8450. if (conn == NULL) {
  8451. return;
  8452. }
  8453. if (conn->ctx->context_type == 2) {
  8454. client_ctx = conn->ctx;
  8455. /* client context: loops must end */
  8456. conn->ctx->stop_flag = 1;
  8457. }
  8458. #ifndef NO_SSL
  8459. if (conn->client_ssl_ctx != NULL) {
  8460. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  8461. }
  8462. #endif
  8463. close_connection(conn);
  8464. if (client_ctx != NULL) {
  8465. /* join worker thread and free context */
  8466. for (i = 0; i < client_ctx->workerthreadcount; i++) {
  8467. if (client_ctx->workerthreadids[i] != 0) {
  8468. mg_join_thread(client_ctx->workerthreadids[i]);
  8469. }
  8470. }
  8471. mg_free(client_ctx->workerthreadids);
  8472. mg_free(client_ctx);
  8473. }
  8474. (void)pthread_mutex_destroy(&conn->mutex);
  8475. mg_free(conn);
  8476. }
  8477. struct mg_connection *mg_connect_client(
  8478. const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len)
  8479. {
  8480. static struct mg_context fake_ctx;
  8481. struct mg_connection *conn = NULL;
  8482. SOCKET sock;
  8483. union usa sa;
  8484. if (!connect_socket(
  8485. &fake_ctx, host, port, use_ssl, ebuf, ebuf_len, &sock, &sa)) {
  8486. ;
  8487. } else if ((conn = (struct mg_connection *)mg_calloc(
  8488. 1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  8489. mg_snprintf(NULL,
  8490. NULL, /* No truncation check for ebuf */
  8491. ebuf,
  8492. ebuf_len,
  8493. "calloc(): %s",
  8494. strerror(ERRNO));
  8495. closesocket(sock);
  8496. #ifndef NO_SSL
  8497. } else if (use_ssl &&
  8498. (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method())) ==
  8499. NULL) {
  8500. mg_snprintf(NULL,
  8501. NULL, /* No truncation check for ebuf */
  8502. ebuf,
  8503. ebuf_len,
  8504. "SSL_CTX_new error");
  8505. closesocket(sock);
  8506. mg_free(conn);
  8507. conn = NULL;
  8508. #endif /* NO_SSL */
  8509. } else {
  8510. #ifdef USE_IPV6
  8511. socklen_t len = (sa.sa.sa_family == AF_INET)
  8512. ? sizeof(conn->client.rsa.sin)
  8513. : sizeof(conn->client.rsa.sin6);
  8514. struct sockaddr *psa =
  8515. (sa.sa.sa_family == AF_INET)
  8516. ? (struct sockaddr *)&(conn->client.rsa.sin)
  8517. : (struct sockaddr *)&(conn->client.rsa.sin6);
  8518. #else
  8519. socklen_t len = sizeof(conn->client.rsa.sin);
  8520. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  8521. #endif
  8522. conn->buf_size = MAX_REQUEST_SIZE;
  8523. conn->buf = (char *)(conn + 1);
  8524. conn->ctx = &fake_ctx;
  8525. conn->client.sock = sock;
  8526. conn->client.lsa = sa;
  8527. if (getsockname(sock, psa, &len) != 0) {
  8528. mg_cry(conn,
  8529. "%s: getsockname() failed: %s",
  8530. __func__,
  8531. strerror(ERRNO));
  8532. }
  8533. conn->client.is_ssl = use_ssl ? 1 : 0;
  8534. (void)pthread_mutex_init(&conn->mutex, NULL);
  8535. #ifndef NO_SSL
  8536. if (use_ssl) {
  8537. /* SSL_CTX_set_verify call is needed to switch off server
  8538. * certificate checking, which is off by default in OpenSSL and on
  8539. * in yaSSL. */
  8540. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  8541. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  8542. }
  8543. #endif
  8544. }
  8545. return conn;
  8546. }
  8547. static int is_valid_uri(const char *uri)
  8548. {
  8549. /* Conform to
  8550. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  8551. * URI can be an asterisk (*) or should start with slash. */
  8552. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  8553. }
  8554. static int
  8555. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  8556. {
  8557. const char *cl;
  8558. if (ebuf_len > 0) {
  8559. ebuf[0] = '\0';
  8560. }
  8561. *err = 0;
  8562. reset_per_request_attributes(conn);
  8563. if (!conn) {
  8564. mg_snprintf(conn,
  8565. NULL, /* No truncation check for ebuf */
  8566. ebuf,
  8567. ebuf_len,
  8568. "%s",
  8569. "Internal error");
  8570. *err = 500;
  8571. return 0;
  8572. }
  8573. /* Set the time the request was received. This value should be used for
  8574. * timeouts. */
  8575. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  8576. conn->request_len =
  8577. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  8578. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  8579. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  8580. mg_snprintf(conn,
  8581. NULL, /* No truncation check for ebuf */
  8582. ebuf,
  8583. ebuf_len,
  8584. "%s",
  8585. "Invalid request size");
  8586. *err = 500;
  8587. return 0;
  8588. }
  8589. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  8590. mg_snprintf(conn,
  8591. NULL, /* No truncation check for ebuf */
  8592. ebuf,
  8593. ebuf_len,
  8594. "%s",
  8595. "Request Too Large");
  8596. *err = 413;
  8597. return 0;
  8598. } else if (conn->request_len <= 0) {
  8599. if (conn->data_len > 0) {
  8600. mg_snprintf(conn,
  8601. NULL, /* No truncation check for ebuf */
  8602. ebuf,
  8603. ebuf_len,
  8604. "%s",
  8605. "Client sent malformed request");
  8606. *err = 400;
  8607. } else {
  8608. /* Server did not send anything -> just close the connection */
  8609. conn->must_close = 1;
  8610. mg_snprintf(conn,
  8611. NULL, /* No truncation check for ebuf */
  8612. ebuf,
  8613. ebuf_len,
  8614. "%s",
  8615. "Client did not send a request");
  8616. *err = 0;
  8617. }
  8618. return 0;
  8619. } else if (parse_http_message(
  8620. conn->buf, conn->buf_size, &conn->request_info) <= 0) {
  8621. mg_snprintf(conn,
  8622. NULL, /* No truncation check for ebuf */
  8623. ebuf,
  8624. ebuf_len,
  8625. "%s",
  8626. "Bad Request");
  8627. *err = 400;
  8628. return 0;
  8629. } else {
  8630. /* Message is a valid request or response */
  8631. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  8632. /* Request/response has content length set */
  8633. char *endptr = NULL;
  8634. conn->content_len = strtoll(cl, &endptr, 10);
  8635. if (endptr == cl) {
  8636. mg_snprintf(conn,
  8637. NULL, /* No truncation check for ebuf */
  8638. ebuf,
  8639. ebuf_len,
  8640. "%s",
  8641. "Bad Request");
  8642. *err = 411;
  8643. return 0;
  8644. }
  8645. /* Publish the content length back to the request info. */
  8646. conn->request_info.content_length = conn->content_len;
  8647. } else if ((cl = get_header(&conn->request_info,
  8648. "Transfer-Encoding")) != NULL &&
  8649. strcmp(cl, "chunked") == 0) {
  8650. conn->is_chunked = 1;
  8651. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  8652. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  8653. /* POST or PUT request without content length set */
  8654. conn->content_len = -1;
  8655. } else if (!mg_strncasecmp(
  8656. conn->request_info.request_method, "HTTP/", 5)) {
  8657. /* Response without content length set */
  8658. conn->content_len = -1;
  8659. } else {
  8660. /* Other request */
  8661. conn->content_len = 0;
  8662. }
  8663. }
  8664. return 1;
  8665. }
  8666. int mg_get_response(struct mg_connection *conn,
  8667. char *ebuf,
  8668. size_t ebuf_len,
  8669. int timeout)
  8670. {
  8671. if (conn) {
  8672. /* Implementation of API function for HTTP clients */
  8673. int err, ret;
  8674. struct mg_context *octx = conn->ctx;
  8675. struct mg_context rctx = *(conn->ctx);
  8676. char txt[32]; /* will not overflow */
  8677. if (timeout >= 0) {
  8678. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  8679. rctx.config[REQUEST_TIMEOUT] = txt;
  8680. set_sock_timeout(conn->client.sock, timeout);
  8681. } else {
  8682. rctx.config[REQUEST_TIMEOUT] = NULL;
  8683. }
  8684. conn->ctx = &rctx;
  8685. ret = getreq(conn, ebuf, ebuf_len, &err);
  8686. conn->ctx = octx;
  8687. /* TODO (mid): Define proper return values - maybe return length?
  8688. * For the first test use <0 for error and >0 for OK */
  8689. return (ret == 0) ? -1 : +1;
  8690. }
  8691. return -1;
  8692. }
  8693. struct mg_connection *mg_download(const char *host,
  8694. int port,
  8695. int use_ssl,
  8696. char *ebuf,
  8697. size_t ebuf_len,
  8698. const char *fmt,
  8699. ...)
  8700. {
  8701. struct mg_connection *conn;
  8702. va_list ap;
  8703. int i;
  8704. int reqerr;
  8705. va_start(ap, fmt);
  8706. ebuf[0] = '\0';
  8707. /* open a connection */
  8708. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  8709. if (conn != NULL) {
  8710. i = mg_vprintf(conn, fmt, ap);
  8711. if (i <= 0) {
  8712. mg_snprintf(conn,
  8713. NULL, /* No truncation check for ebuf */
  8714. ebuf,
  8715. ebuf_len,
  8716. "%s",
  8717. "Error sending request");
  8718. } else {
  8719. getreq(conn, ebuf, ebuf_len, &reqerr);
  8720. }
  8721. }
  8722. /* if an error occured, close the connection */
  8723. if (ebuf[0] != '\0' && conn != NULL) {
  8724. mg_close_connection(conn);
  8725. conn = NULL;
  8726. }
  8727. va_end(ap);
  8728. return conn;
  8729. }
  8730. struct websocket_client_thread_data {
  8731. struct mg_connection *conn;
  8732. mg_websocket_data_handler data_handler;
  8733. mg_websocket_close_handler close_handler;
  8734. void *callback_data;
  8735. };
  8736. #if defined(USE_WEBSOCKET)
  8737. #ifdef _WIN32
  8738. static unsigned __stdcall websocket_client_thread(void *data)
  8739. #else
  8740. static void *websocket_client_thread(void *data)
  8741. #endif
  8742. {
  8743. struct websocket_client_thread_data *cdata =
  8744. (struct websocket_client_thread_data *)data;
  8745. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  8746. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  8747. if (cdata->close_handler != NULL) {
  8748. cdata->close_handler(cdata->conn, cdata->callback_data);
  8749. }
  8750. mg_free((void *)cdata);
  8751. #ifdef _WIN32
  8752. return 0;
  8753. #else
  8754. return NULL;
  8755. #endif
  8756. }
  8757. #endif
  8758. struct mg_connection *
  8759. mg_connect_websocket_client(const char *host,
  8760. int port,
  8761. int use_ssl,
  8762. char *error_buffer,
  8763. size_t error_buffer_size,
  8764. const char *path,
  8765. const char *origin,
  8766. mg_websocket_data_handler data_func,
  8767. mg_websocket_close_handler close_func,
  8768. void *user_data)
  8769. {
  8770. struct mg_connection *conn = NULL;
  8771. #if defined(USE_WEBSOCKET)
  8772. struct mg_context *newctx = NULL;
  8773. struct websocket_client_thread_data *thread_data;
  8774. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  8775. static const char *handshake_req;
  8776. if (origin != NULL) {
  8777. handshake_req = "GET %s HTTP/1.1\r\n"
  8778. "Host: %s\r\n"
  8779. "Upgrade: websocket\r\n"
  8780. "Connection: Upgrade\r\n"
  8781. "Sec-WebSocket-Key: %s\r\n"
  8782. "Sec-WebSocket-Version: 13\r\n"
  8783. "Origin: %s\r\n"
  8784. "\r\n";
  8785. } else {
  8786. handshake_req = "GET %s HTTP/1.1\r\n"
  8787. "Host: %s\r\n"
  8788. "Upgrade: websocket\r\n"
  8789. "Connection: Upgrade\r\n"
  8790. "Sec-WebSocket-Key: %s\r\n"
  8791. "Sec-WebSocket-Version: 13\r\n"
  8792. "\r\n";
  8793. }
  8794. /* Establish the client connection and request upgrade */
  8795. conn = mg_download(host,
  8796. port,
  8797. use_ssl,
  8798. error_buffer,
  8799. error_buffer_size,
  8800. handshake_req,
  8801. path,
  8802. host,
  8803. magic,
  8804. origin);
  8805. /* Connection object will be null if something goes wrong */
  8806. if (conn == NULL || (strcmp(conn->request_info.uri, "101") != 0)) {
  8807. if (!*error_buffer) {
  8808. /* if there is a connection, but it did not return 101,
  8809. * error_buffer is not yet set */
  8810. mg_snprintf(conn,
  8811. NULL, /* No truncation check for ebuf */
  8812. error_buffer,
  8813. error_buffer_size,
  8814. "Unexpected server reply");
  8815. }
  8816. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  8817. if (conn != NULL) {
  8818. mg_free(conn);
  8819. conn = NULL;
  8820. }
  8821. return conn;
  8822. }
  8823. /* For client connections, mg_context is fake. Since we need to set a
  8824. * callback function, we need to create a copy and modify it. */
  8825. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  8826. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  8827. newctx->user_data = user_data;
  8828. newctx->context_type = 2; /* client context type */
  8829. newctx->workerthreadcount = 1; /* one worker thread will be created */
  8830. newctx->workerthreadids =
  8831. (pthread_t *)mg_calloc(newctx->workerthreadcount, sizeof(pthread_t));
  8832. conn->ctx = newctx;
  8833. thread_data = (struct websocket_client_thread_data *)mg_calloc(
  8834. sizeof(struct websocket_client_thread_data), 1);
  8835. thread_data->conn = conn;
  8836. thread_data->data_handler = data_func;
  8837. thread_data->close_handler = close_func;
  8838. thread_data->callback_data = NULL;
  8839. /* Start a thread to read the websocket client connection
  8840. * This thread will automatically stop when mg_disconnect is
  8841. * called on the client connection */
  8842. if (mg_start_thread_with_id(websocket_client_thread,
  8843. (void *)thread_data,
  8844. newctx->workerthreadids) != 0) {
  8845. mg_free((void *)thread_data);
  8846. mg_free((void *)newctx->workerthreadids);
  8847. mg_free((void *)newctx);
  8848. mg_free((void *)conn);
  8849. conn = NULL;
  8850. DEBUG_TRACE("%s",
  8851. "Websocket client connect thread could not be started\r\n");
  8852. }
  8853. #else
  8854. /* Appease "unused parameter" warnings */
  8855. (void)host;
  8856. (void)port;
  8857. (void)use_ssl;
  8858. (void)error_buffer;
  8859. (void)error_buffer_size;
  8860. (void)path;
  8861. (void)origin;
  8862. (void)user_data;
  8863. (void)data_func;
  8864. (void)close_func;
  8865. #endif
  8866. return conn;
  8867. }
  8868. static void process_new_connection(struct mg_connection *conn)
  8869. {
  8870. if (conn && conn->ctx) {
  8871. struct mg_request_info *ri = &conn->request_info;
  8872. int keep_alive_enabled, keep_alive, discard_len;
  8873. char ebuf[100];
  8874. int reqerr;
  8875. keep_alive_enabled =
  8876. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  8877. /* Important: on new connection, reset the receiving buffer. Credit
  8878. * goes to crule42. */
  8879. conn->data_len = 0;
  8880. do {
  8881. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  8882. /* The request sent by the client could not be understood by
  8883. * the server, or it was incomplete or a timeout. Send an
  8884. * error message and close the connection. */
  8885. if (reqerr > 0) {
  8886. /*assert(ebuf[0] != '\0');*/
  8887. send_http_error(conn, reqerr, "%s", ebuf);
  8888. }
  8889. } else if (!is_valid_uri(conn->request_info.uri)) {
  8890. mg_snprintf(conn,
  8891. NULL, /* No truncation check for ebuf */
  8892. ebuf,
  8893. sizeof(ebuf),
  8894. "Invalid URI: [%s]",
  8895. ri->uri);
  8896. send_http_error(conn, 400, "%s", ebuf);
  8897. } else if (strcmp(ri->http_version, "1.0") &&
  8898. strcmp(ri->http_version, "1.1")) {
  8899. mg_snprintf(conn,
  8900. NULL, /* No truncation check for ebuf */
  8901. ebuf,
  8902. sizeof(ebuf),
  8903. "Bad HTTP version: [%s]",
  8904. ri->http_version);
  8905. send_http_error(conn, 505, "%s", ebuf);
  8906. }
  8907. if (ebuf[0] == '\0') {
  8908. handle_request(conn);
  8909. if (conn->ctx->callbacks.end_request != NULL) {
  8910. conn->ctx->callbacks.end_request(conn, conn->status_code);
  8911. }
  8912. log_access(conn);
  8913. } else {
  8914. conn->must_close = 1;
  8915. }
  8916. if (ri->remote_user != NULL) {
  8917. mg_free((void *)ri->remote_user);
  8918. /* Important! When having connections with and without auth
  8919. * would cause double free and then crash */
  8920. ri->remote_user = NULL;
  8921. }
  8922. /* NOTE(lsm): order is important here. should_keep_alive() call is
  8923. * using parsed request, which will be invalid after memmove's
  8924. * below.
  8925. * Therefore, memorize should_keep_alive() result now for later use
  8926. * in loop exit condition. */
  8927. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  8928. conn->content_len >= 0 && should_keep_alive(conn);
  8929. /* Discard all buffered data for this request */
  8930. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  8931. conn->request_len + conn->content_len <
  8932. (int64_t)conn->data_len
  8933. ? (int)(conn->request_len + conn->content_len)
  8934. : conn->data_len;
  8935. /*assert(discard_len >= 0);*/
  8936. if (discard_len < 0)
  8937. break;
  8938. conn->data_len -= discard_len;
  8939. if (conn->data_len > 0) {
  8940. memmove(
  8941. conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  8942. }
  8943. /* assert(conn->data_len >= 0); */
  8944. /* assert(conn->data_len <= conn->buf_size); */
  8945. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  8946. break;
  8947. }
  8948. } while (keep_alive);
  8949. }
  8950. }
  8951. /* Worker threads take accepted socket from the queue */
  8952. static int consume_socket(struct mg_context *ctx, struct socket *sp)
  8953. {
  8954. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  8955. if (!ctx) {
  8956. return 0;
  8957. }
  8958. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8959. DEBUG_TRACE("%s", "going idle");
  8960. /* If the queue is empty, wait. We're idle at this point. */
  8961. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  8962. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  8963. }
  8964. /* If we're stopping, sq_head may be equal to sq_tail. */
  8965. if (ctx->sq_head > ctx->sq_tail) {
  8966. /* Copy socket from the queue and increment tail */
  8967. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  8968. ctx->sq_tail++;
  8969. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  8970. /* Wrap pointers if needed */
  8971. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  8972. ctx->sq_tail -= QUEUE_SIZE(ctx);
  8973. ctx->sq_head -= QUEUE_SIZE(ctx);
  8974. }
  8975. }
  8976. (void)pthread_cond_signal(&ctx->sq_empty);
  8977. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8978. return !ctx->stop_flag;
  8979. #undef QUEUE_SIZE
  8980. }
  8981. static void *worker_thread_run(void *thread_func_param)
  8982. {
  8983. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  8984. struct mg_connection *conn;
  8985. struct mg_workerTLS tls;
  8986. uint32_t addr;
  8987. mg_set_thread_name("worker");
  8988. tls.is_master = 0;
  8989. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8990. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  8991. #endif
  8992. conn =
  8993. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  8994. if (conn == NULL) {
  8995. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  8996. } else {
  8997. pthread_setspecific(sTlsKey, &tls);
  8998. conn->buf_size = MAX_REQUEST_SIZE;
  8999. conn->buf = (char *)(conn + 1);
  9000. conn->ctx = ctx;
  9001. conn->request_info.user_data = ctx->user_data;
  9002. /* Allocate a mutex for this connection to allow communication both
  9003. * within the request handler and from elsewhere in the application */
  9004. (void)pthread_mutex_init(&conn->mutex, NULL);
  9005. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  9006. * signal sq_empty condvar to wake up the master waiting in
  9007. * produce_socket() */
  9008. while (consume_socket(ctx, &conn->client)) {
  9009. conn->conn_birth_time = time(NULL);
  9010. /* Fill in IP, port info early so even if SSL setup below fails,
  9011. * error handler would have the corresponding info.
  9012. * Thanks to Johannes Winkelmann for the patch.
  9013. * TODO(lsm, high): Fix IPv6 case */
  9014. conn->request_info.remote_port =
  9015. ntohs(conn->client.rsa.sin.sin_port);
  9016. sockaddr_to_string(conn->request_info.remote_addr,
  9017. sizeof(conn->request_info.remote_addr),
  9018. &conn->client.rsa);
  9019. /* TODO: #if defined(MG_LEGACY_INTERFACE) */
  9020. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  9021. memcpy(&conn->request_info.remote_ip, &addr, 4);
  9022. /* #endif */
  9023. conn->request_info.is_ssl = conn->client.is_ssl;
  9024. if (!conn->client.is_ssl
  9025. #ifndef NO_SSL
  9026. ||
  9027. sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  9028. #endif
  9029. ) {
  9030. process_new_connection(conn);
  9031. }
  9032. close_connection(conn);
  9033. }
  9034. }
  9035. /* Signal master that we're done with connection and exiting */
  9036. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9037. ctx->num_threads--;
  9038. (void)pthread_cond_signal(&ctx->thread_cond);
  9039. /* assert(ctx->num_threads >= 0); */
  9040. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9041. pthread_setspecific(sTlsKey, NULL);
  9042. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9043. CloseHandle(tls.pthread_cond_helper_mutex);
  9044. #endif
  9045. mg_free(conn);
  9046. DEBUG_TRACE("%s", "exiting");
  9047. return NULL;
  9048. }
  9049. /* Threads have different return types on Windows and Unix. */
  9050. #ifdef _WIN32
  9051. static unsigned __stdcall worker_thread(void *thread_func_param)
  9052. {
  9053. worker_thread_run(thread_func_param);
  9054. return 0;
  9055. }
  9056. #else
  9057. static void *worker_thread(void *thread_func_param)
  9058. {
  9059. worker_thread_run(thread_func_param);
  9060. return NULL;
  9061. }
  9062. #endif /* _WIN32 */
  9063. /* Master thread adds accepted socket to a queue */
  9064. static void produce_socket(struct mg_context *ctx, const struct socket *sp)
  9065. {
  9066. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  9067. if (!ctx) {
  9068. return;
  9069. }
  9070. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9071. /* If the queue is full, wait */
  9072. while (ctx->stop_flag == 0 &&
  9073. ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  9074. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  9075. }
  9076. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  9077. /* Copy socket to the queue and increment head */
  9078. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  9079. ctx->sq_head++;
  9080. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  9081. }
  9082. (void)pthread_cond_signal(&ctx->sq_full);
  9083. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9084. #undef QUEUE_SIZE
  9085. }
  9086. static void accept_new_connection(const struct socket *listener,
  9087. struct mg_context *ctx)
  9088. {
  9089. struct socket so;
  9090. char src_addr[IP_ADDR_STR_LEN];
  9091. socklen_t len = sizeof(so.rsa);
  9092. int on = 1;
  9093. int timeout;
  9094. if (!listener) {
  9095. return;
  9096. }
  9097. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) ==
  9098. INVALID_SOCKET) {
  9099. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  9100. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  9101. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  9102. closesocket(so.sock);
  9103. so.sock = INVALID_SOCKET;
  9104. } else {
  9105. /* Put so socket structure into the queue */
  9106. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  9107. set_close_on_exec(so.sock, fc(ctx));
  9108. so.is_ssl = listener->is_ssl;
  9109. so.ssl_redir = listener->ssl_redir;
  9110. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  9111. mg_cry(fc(ctx),
  9112. "%s: getsockname() failed: %s",
  9113. __func__,
  9114. strerror(ERRNO));
  9115. }
  9116. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  9117. * is enabled, and client resets the connection, server won't get
  9118. * TCP FIN or RST and will keep the connection open forever. With TCP
  9119. * keep-alive, next keep-alive handshake will figure out that the
  9120. * client is down and will close the server end.
  9121. * Thanks to Igor Klopov who suggested the patch. */
  9122. if (setsockopt(so.sock,
  9123. SOL_SOCKET,
  9124. SO_KEEPALIVE,
  9125. (SOCK_OPT_TYPE)&on,
  9126. sizeof(on)) != 0) {
  9127. mg_cry(fc(ctx),
  9128. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  9129. __func__,
  9130. strerror(ERRNO));
  9131. }
  9132. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  9133. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  9134. } else {
  9135. timeout = -1;
  9136. }
  9137. /* Set socket timeout to the given value, but not more than a
  9138. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  9139. * so the server can exit after that time if requested. */
  9140. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  9141. set_sock_timeout(so.sock, timeout);
  9142. } else {
  9143. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  9144. }
  9145. produce_socket(ctx, &so);
  9146. }
  9147. }
  9148. static void master_thread_run(void *thread_func_param)
  9149. {
  9150. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  9151. struct mg_workerTLS tls;
  9152. struct pollfd *pfd;
  9153. unsigned int i;
  9154. unsigned int workerthreadcount;
  9155. if (!ctx) {
  9156. return;
  9157. }
  9158. mg_set_thread_name("master");
  9159. /* Increase priority of the master thread */
  9160. #if defined(_WIN32)
  9161. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  9162. #elif defined(USE_MASTER_THREAD_PRIORITY)
  9163. int min_prio = sched_get_priority_min(SCHED_RR);
  9164. int max_prio = sched_get_priority_max(SCHED_RR);
  9165. if ((min_prio >= 0) && (max_prio >= 0) &&
  9166. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  9167. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  9168. struct sched_param sched_param = {0};
  9169. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  9170. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  9171. }
  9172. #endif
  9173. /* Initialize thread local storage */
  9174. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9175. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  9176. #endif
  9177. tls.is_master = 1;
  9178. pthread_setspecific(sTlsKey, &tls);
  9179. /* Server starts *now* */
  9180. ctx->start_time = (unsigned long)time(NULL);
  9181. /* Allocate memory for the listening sockets, and start the server */
  9182. pfd =
  9183. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  9184. while (pfd != NULL && ctx->stop_flag == 0) {
  9185. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9186. pfd[i].fd = ctx->listening_sockets[i].sock;
  9187. pfd[i].events = POLLIN;
  9188. }
  9189. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  9190. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9191. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  9192. * successful poll, and POLLIN is defined as
  9193. * (POLLRDNORM | POLLRDBAND)
  9194. * Therefore, we're checking pfd[i].revents & POLLIN, not
  9195. * pfd[i].revents == POLLIN. */
  9196. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  9197. accept_new_connection(&ctx->listening_sockets[i], ctx);
  9198. }
  9199. }
  9200. }
  9201. }
  9202. mg_free(pfd);
  9203. DEBUG_TRACE("%s", "stopping workers");
  9204. /* Stop signal received: somebody called mg_stop. Quit. */
  9205. close_all_listening_sockets(ctx);
  9206. /* Wakeup workers that are waiting for connections to handle. */
  9207. pthread_cond_broadcast(&ctx->sq_full);
  9208. /* Wait until all threads finish */
  9209. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9210. while (ctx->num_threads > 0) {
  9211. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  9212. }
  9213. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9214. /* Join all worker threads to avoid leaking threads. */
  9215. workerthreadcount = ctx->workerthreadcount;
  9216. for (i = 0; i < workerthreadcount; i++) {
  9217. if (ctx->workerthreadids[i] != 0) {
  9218. mg_join_thread(ctx->workerthreadids[i]);
  9219. }
  9220. }
  9221. #if !defined(NO_SSL)
  9222. if (ctx->ssl_ctx != NULL) {
  9223. uninitialize_ssl(ctx);
  9224. }
  9225. #endif
  9226. DEBUG_TRACE("%s", "exiting");
  9227. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9228. CloseHandle(tls.pthread_cond_helper_mutex);
  9229. #endif
  9230. pthread_setspecific(sTlsKey, NULL);
  9231. /* Signal mg_stop() that we're done.
  9232. * WARNING: This must be the very last thing this
  9233. * thread does, as ctx becomes invalid after this line. */
  9234. ctx->stop_flag = 2;
  9235. }
  9236. /* Threads have different return types on Windows and Unix. */
  9237. #ifdef _WIN32
  9238. static unsigned __stdcall master_thread(void *thread_func_param)
  9239. {
  9240. master_thread_run(thread_func_param);
  9241. return 0;
  9242. }
  9243. #else
  9244. static void *master_thread(void *thread_func_param)
  9245. {
  9246. master_thread_run(thread_func_param);
  9247. return NULL;
  9248. }
  9249. #endif /* _WIN32 */
  9250. static void free_context(struct mg_context *ctx)
  9251. {
  9252. int i;
  9253. struct mg_request_handler_info *tmp_rh;
  9254. if (ctx == NULL) {
  9255. return;
  9256. }
  9257. if (ctx->callbacks.exit_context) {
  9258. ctx->callbacks.exit_context(ctx);
  9259. }
  9260. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  9261. */
  9262. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  9263. (void)pthread_cond_destroy(&ctx->thread_cond);
  9264. (void)pthread_cond_destroy(&ctx->sq_empty);
  9265. (void)pthread_cond_destroy(&ctx->sq_full);
  9266. /* Destroy other context global data structures mutex */
  9267. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  9268. #if defined(USE_TIMERS)
  9269. timers_exit(ctx);
  9270. #endif
  9271. /* Deallocate config parameters */
  9272. for (i = 0; i < NUM_OPTIONS; i++) {
  9273. if (ctx->config[i] != NULL) {
  9274. #if defined(_MSC_VER)
  9275. #pragma warning(suppress : 6001)
  9276. #endif
  9277. mg_free(ctx->config[i]);
  9278. }
  9279. }
  9280. /* Deallocate request handlers */
  9281. while (ctx->request_handlers) {
  9282. tmp_rh = ctx->request_handlers;
  9283. ctx->request_handlers = tmp_rh->next;
  9284. mg_free(tmp_rh->uri);
  9285. mg_free(tmp_rh);
  9286. }
  9287. #ifndef NO_SSL
  9288. /* Deallocate SSL context */
  9289. if (ctx->ssl_ctx != NULL) {
  9290. SSL_CTX_free(ctx->ssl_ctx);
  9291. }
  9292. if (ssl_mutexes != NULL) {
  9293. mg_free(ssl_mutexes);
  9294. ssl_mutexes = NULL;
  9295. }
  9296. #endif /* !NO_SSL */
  9297. /* Deallocate worker thread ID array */
  9298. if (ctx->workerthreadids != NULL) {
  9299. mg_free(ctx->workerthreadids);
  9300. }
  9301. /* Deallocate the tls variable */
  9302. if (mg_atomic_dec(&sTlsInit) == 0) {
  9303. pthread_key_delete(sTlsKey);
  9304. }
  9305. /* deallocate system name string */
  9306. mg_free(ctx->systemName);
  9307. /* Deallocate context itself */
  9308. mg_free(ctx);
  9309. }
  9310. void mg_stop(struct mg_context *ctx)
  9311. {
  9312. pthread_t mt;
  9313. if (!ctx) {
  9314. return;
  9315. }
  9316. /* We don't use a lock here. Calling mg_stop with the same ctx from
  9317. * two threads is not allowed. */
  9318. mt = ctx->masterthreadid;
  9319. if (mt == 0) {
  9320. return;
  9321. }
  9322. ctx->masterthreadid = 0;
  9323. ctx->stop_flag = 1;
  9324. /* Wait until mg_fini() stops */
  9325. while (ctx->stop_flag != 2) {
  9326. (void)mg_sleep(10);
  9327. }
  9328. mg_join_thread(mt);
  9329. free_context(ctx);
  9330. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9331. (void)WSACleanup();
  9332. #endif /* _WIN32 && !__SYMBIAN32__ */
  9333. }
  9334. static void get_system_name(char **sysName)
  9335. {
  9336. #if defined(_WIN32)
  9337. #if !defined(__SYMBIAN32__)
  9338. char name[128];
  9339. DWORD dwVersion = 0;
  9340. DWORD dwMajorVersion = 0;
  9341. DWORD dwMinorVersion = 0;
  9342. DWORD dwBuild = 0;
  9343. #ifdef _MSC_VER
  9344. #pragma warning(push)
  9345. // GetVersion was declared deprecated
  9346. #pragma warning(disable : 4996)
  9347. #endif
  9348. dwVersion = GetVersion();
  9349. #ifdef _MSC_VER
  9350. #pragma warning(pop)
  9351. #endif
  9352. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  9353. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  9354. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  9355. (void)dwBuild;
  9356. sprintf(name,
  9357. "Windows %u.%u",
  9358. (unsigned)dwMajorVersion,
  9359. (unsigned)dwMinorVersion);
  9360. *sysName = mg_strdup(name);
  9361. #else
  9362. *sysName = mg_strdup("Symbian");
  9363. #endif
  9364. #else
  9365. struct utsname name;
  9366. memset(&name, 0, sizeof(name));
  9367. uname(&name);
  9368. *sysName = mg_strdup(name.sysname);
  9369. #endif
  9370. }
  9371. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  9372. void *user_data,
  9373. const char **options)
  9374. {
  9375. struct mg_context *ctx;
  9376. const char *name, *value, *default_value;
  9377. int idx, ok, workerthreadcount;
  9378. unsigned int i;
  9379. void (*exit_callback)(const struct mg_context *ctx) = 0;
  9380. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  9381. WSADATA data;
  9382. WSAStartup(MAKEWORD(2, 2), &data);
  9383. #if defined(_MSC_VER)
  9384. #pragma warning(suppress : 28125)
  9385. #endif
  9386. if (!sTlsInit) {
  9387. InitializeCriticalSection(&global_log_file_lock);
  9388. }
  9389. #endif /* _WIN32 && !__SYMBIAN32__ */
  9390. /* Allocate context and initialize reasonable general case defaults. */
  9391. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  9392. return NULL;
  9393. }
  9394. if (mg_atomic_inc(&sTlsInit) == 1) {
  9395. if (0 != pthread_key_create(&sTlsKey, NULL)) {
  9396. /* Fatal error - abort start. However, this situation should never
  9397. * occur in practice. */
  9398. mg_atomic_dec(&sTlsInit);
  9399. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  9400. mg_free(ctx);
  9401. return NULL;
  9402. }
  9403. } else {
  9404. /* TODO (low): istead of sleeping, check if sTlsKey is already
  9405. * initialized. */
  9406. mg_sleep(1);
  9407. }
  9408. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, NULL);
  9409. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  9410. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  9411. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  9412. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, NULL);
  9413. if (!ok) {
  9414. /* Fatal error - abort start. However, this situation should never
  9415. * occur in practice. */
  9416. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  9417. mg_free(ctx);
  9418. return NULL;
  9419. }
  9420. if (callbacks) {
  9421. ctx->callbacks = *callbacks;
  9422. exit_callback = callbacks->exit_context;
  9423. ctx->callbacks.exit_context = 0;
  9424. }
  9425. ctx->user_data = user_data;
  9426. ctx->request_handlers = NULL;
  9427. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9428. ctx->shared_lua_websockets = 0;
  9429. #endif
  9430. while (options && (name = *options++) != NULL) {
  9431. if ((idx = get_option_index(name)) == -1) {
  9432. mg_cry(fc(ctx), "Invalid option: %s", name);
  9433. free_context(ctx);
  9434. return NULL;
  9435. } else if ((value = *options++) == NULL) {
  9436. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  9437. free_context(ctx);
  9438. return NULL;
  9439. }
  9440. if (ctx->config[idx] != NULL) {
  9441. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  9442. mg_free(ctx->config[idx]);
  9443. }
  9444. ctx->config[idx] = mg_strdup(value);
  9445. DEBUG_TRACE("[%s] -> [%s]", name, value);
  9446. }
  9447. /* Set default value if needed */
  9448. for (i = 0; config_options[i].name != NULL; i++) {
  9449. default_value = config_options[i].default_value;
  9450. if (ctx->config[i] == NULL && default_value != NULL) {
  9451. ctx->config[i] = mg_strdup(default_value);
  9452. }
  9453. }
  9454. #if defined(NO_FILES)
  9455. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  9456. mg_cry(fc(ctx), "%s", "Document root must not be set");
  9457. free_context(ctx);
  9458. return NULL;
  9459. }
  9460. #endif
  9461. get_system_name(&ctx->systemName);
  9462. /* NOTE(lsm): order is important here. SSL certificates must
  9463. * be initialized before listening ports. UID must be set last. */
  9464. if (!set_gpass_option(ctx) ||
  9465. #if !defined(NO_SSL)
  9466. !set_ssl_option(ctx) ||
  9467. #endif
  9468. !set_ports_option(ctx) ||
  9469. #if !defined(_WIN32)
  9470. !set_uid_option(ctx) ||
  9471. #endif
  9472. !set_acl_option(ctx)) {
  9473. free_context(ctx);
  9474. return NULL;
  9475. }
  9476. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  9477. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  9478. * won't kill the whole process. */
  9479. (void)signal(SIGPIPE, SIG_IGN);
  9480. #endif /* !_WIN32 && !__SYMBIAN32__ */
  9481. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  9482. if (workerthreadcount > MAX_WORKER_THREADS) {
  9483. mg_cry(fc(ctx), "Too many worker threads");
  9484. free_context(ctx);
  9485. return NULL;
  9486. }
  9487. if (workerthreadcount > 0) {
  9488. ctx->workerthreadcount = ((unsigned int)(workerthreadcount));
  9489. ctx->workerthreadids =
  9490. (pthread_t *)mg_calloc(ctx->workerthreadcount, sizeof(pthread_t));
  9491. if (ctx->workerthreadids == NULL) {
  9492. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  9493. free_context(ctx);
  9494. return NULL;
  9495. }
  9496. }
  9497. #if defined(USE_TIMERS)
  9498. if (timers_init(ctx) != 0) {
  9499. mg_cry(fc(ctx), "Error creating timers");
  9500. free_context(ctx);
  9501. return NULL;
  9502. }
  9503. #endif
  9504. /* Context has been created - init user libraries */
  9505. if (ctx->callbacks.init_context) {
  9506. ctx->callbacks.init_context(ctx);
  9507. }
  9508. ctx->callbacks.exit_context = exit_callback;
  9509. ctx->context_type = 1; /* server context */
  9510. /* Start master (listening) thread */
  9511. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  9512. /* Start worker threads */
  9513. for (i = 0; i < ctx->workerthreadcount; i++) {
  9514. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9515. ctx->num_threads++;
  9516. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9517. if (mg_start_thread_with_id(
  9518. worker_thread, ctx, &ctx->workerthreadids[i]) != 0) {
  9519. (void)pthread_mutex_lock(&ctx->thread_mutex);
  9520. ctx->num_threads--;
  9521. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  9522. if (i > 0) {
  9523. mg_cry(fc(ctx),
  9524. "Cannot start worker thread %i: error %ld",
  9525. i + 1,
  9526. (long)ERRNO);
  9527. } else {
  9528. mg_cry(
  9529. fc(ctx), "Cannot create threads: error %ld", (long)ERRNO);
  9530. free_context(ctx);
  9531. return NULL;
  9532. }
  9533. break;
  9534. }
  9535. }
  9536. return ctx;
  9537. }
  9538. /* Feature check API function */
  9539. unsigned mg_check_feature(unsigned feature)
  9540. {
  9541. static const unsigned feature_set = 0
  9542. /* Set bits for available features according to API documentation. */
  9543. #if !defined(NO_FILES)
  9544. | 1
  9545. #endif
  9546. #if !defined(NO_SSL)
  9547. | 2
  9548. #endif
  9549. #if !defined(NO_CGI)
  9550. | 4
  9551. #endif
  9552. #if defined(USE_IPV6)
  9553. | 8
  9554. #endif
  9555. #if defined(USE_WEBSOCKET)
  9556. | 16
  9557. #endif
  9558. #if defined(USE_LUA)
  9559. | 32
  9560. #endif
  9561. /* Set some extra bits not defined in the API documentation.
  9562. * These bits may change without further notice. */
  9563. #if !defined(NO_POPEN)
  9564. | 64
  9565. #endif
  9566. #if defined(MG_LEGACY_INTERFACE)
  9567. | 128
  9568. #endif
  9569. #if defined(MEMORY_DEBUGGING)
  9570. | 256
  9571. #endif
  9572. #if defined(USE_TIMERS)
  9573. | 512
  9574. #endif
  9575. #if !defined(NO_NONCE_CHECK)
  9576. | 1024
  9577. #endif
  9578. ;
  9579. return (feature & feature_set);
  9580. }