civetweb.c 318 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139
  1. /* Copyright (c) 2013-2015 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #ifdef __linux__
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  92. * type size check"); */
  93. /* DTL -- including winsock2.h works better if lean and mean */
  94. #ifndef WIN32_LEAN_AND_MEAN
  95. #define WIN32_LEAN_AND_MEAN
  96. #endif
  97. #if defined(__SYMBIAN32__)
  98. #define NO_SSL /* SSL is not supported */
  99. #define NO_CGI /* CGI is not supported */
  100. #define PATH_MAX FILENAME_MAX
  101. #endif /* __SYMBIAN32__ */
  102. #ifndef IGNORE_UNUSED_RESULT
  103. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  104. #endif
  105. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  106. #include <sys/types.h>
  107. #include <sys/stat.h>
  108. #include <errno.h>
  109. #include <signal.h>
  110. #include <fcntl.h>
  111. #endif /* !_WIN32_WCE */
  112. #ifdef __MACH__
  113. #define CLOCK_MONOTONIC (1)
  114. #define CLOCK_REALTIME (2)
  115. #include <sys/time.h>
  116. #include <mach/clock.h>
  117. #include <mach/mach.h>
  118. #include <mach/mach_time.h>
  119. #include <assert.h>
  120. /* clock_gettime is not implemented on OSX */
  121. int clock_gettime(int clk_id, struct timespec *t);
  122. int
  123. clock_gettime(int clk_id, struct timespec *t)
  124. {
  125. memset(t, 0, sizeof(*t));
  126. if (clk_id == CLOCK_REALTIME) {
  127. struct timeval now;
  128. int rv = gettimeofday(&now, NULL);
  129. if (rv) {
  130. return rv;
  131. }
  132. t->tv_sec = now.tv_sec;
  133. t->tv_nsec = now.tv_usec * 1000;
  134. return 0;
  135. } else if (clk_id == CLOCK_MONOTONIC) {
  136. static uint64_t clock_start_time = 0;
  137. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  138. uint64_t now = mach_absolute_time();
  139. if (clock_start_time == 0) {
  140. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  141. #if defined(DEBUG)
  142. assert(mach_status == KERN_SUCCESS);
  143. #else
  144. /* appease "unused variable" warning for release builds */
  145. (void)mach_status;
  146. #endif
  147. clock_start_time = now;
  148. }
  149. now = (uint64_t)((double)(now - clock_start_time)
  150. * (double)timebase_ifo.numer
  151. / (double)timebase_ifo.denom);
  152. t->tv_sec = now / 1000000000;
  153. t->tv_nsec = now % 1000000000;
  154. return 0;
  155. }
  156. return -1; /* EINVAL - Clock ID is unknown */
  157. }
  158. #endif
  159. #include <time.h>
  160. #include <stdlib.h>
  161. #include <stdarg.h>
  162. #include <assert.h>
  163. #include <string.h>
  164. #include <ctype.h>
  165. #include <limits.h>
  166. #include <stddef.h>
  167. #include <stdio.h>
  168. #ifndef MAX_WORKER_THREADS
  169. #define MAX_WORKER_THREADS (1024 * 64)
  170. #endif
  171. #ifndef SOCKET_TIMEOUT_QUANTUM
  172. #define SOCKET_TIMEOUT_QUANTUM (10000)
  173. #endif
  174. mg_static_assert(MAX_WORKER_THREADS >= 1,
  175. "worker threads must be a positive number");
  176. #if defined(_WIN32) \
  177. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  178. #include <windows.h>
  179. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  180. #include <ws2tcpip.h>
  181. typedef const char *SOCK_OPT_TYPE;
  182. #if !defined(PATH_MAX)
  183. #define PATH_MAX (MAX_PATH)
  184. #endif
  185. #if !defined(PATH_MAX)
  186. #define PATH_MAX (4096)
  187. #endif
  188. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  189. #ifndef _IN_PORT_T
  190. #ifndef in_port_t
  191. #define in_port_t u_short
  192. #endif
  193. #endif
  194. #ifndef _WIN32_WCE
  195. #include <process.h>
  196. #include <direct.h>
  197. #include <io.h>
  198. #else /* _WIN32_WCE */
  199. #define NO_CGI /* WinCE has no pipes */
  200. typedef long off_t;
  201. #define errno ((int)(GetLastError()))
  202. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  203. #endif /* _WIN32_WCE */
  204. #define MAKEUQUAD(lo, hi) \
  205. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  206. #define RATE_DIFF (10000000) /* 100 nsecs */
  207. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  208. #define SYS2UNIX_TIME(lo, hi) \
  209. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  210. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  211. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  212. * Also use _strtoui64 on modern M$ compilers */
  213. #if defined(_MSC_VER)
  214. #if (_MSC_VER < 1300)
  215. #define STRX(x) #x
  216. #define STR(x) STRX(x)
  217. #define __func__ __FILE__ ":" STR(__LINE__)
  218. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  219. #define strtoll(x, y, z) (_atoi64(x))
  220. #else
  221. #define __func__ __FUNCTION__
  222. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  223. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  224. #endif
  225. #endif /* _MSC_VER */
  226. #define ERRNO ((int)(GetLastError()))
  227. #define NO_SOCKLEN_T
  228. #define SSL_LIB "ssleay32.dll"
  229. #define CRYPTO_LIB "libeay32.dll"
  230. #define O_NONBLOCK (0)
  231. #ifndef W_OK
  232. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  233. #endif
  234. #if !defined(EWOULDBLOCK)
  235. #define EWOULDBLOCK WSAEWOULDBLOCK
  236. #endif /* !EWOULDBLOCK */
  237. #define _POSIX_
  238. #define INT64_FMT "I64d"
  239. #define UINT64_FMT "I64u"
  240. #define WINCDECL __cdecl
  241. #define SHUT_RD (0)
  242. #define SHUT_WR (1)
  243. #define SHUT_BOTH (2)
  244. #define vsnprintf_impl _vsnprintf
  245. #define access _access
  246. #define mg_sleep(x) (Sleep(x))
  247. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  248. #ifndef popen
  249. #define popen(x, y) (_popen(x, y))
  250. #endif
  251. #ifndef pclose
  252. #define pclose(x) (_pclose(x))
  253. #endif
  254. #define close(x) (_close(x))
  255. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  256. #define RTLD_LAZY (0)
  257. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  258. #define fdopen(x, y) (_fdopen((x), (y)))
  259. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  260. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  261. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  262. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  263. #define sleep(x) (Sleep((x)*1000))
  264. #define rmdir(x) (_rmdir(x))
  265. #if !defined(fileno)
  266. #define fileno(x) (_fileno(x))
  267. #endif /* !fileno MINGW #defines fileno */
  268. typedef HANDLE pthread_mutex_t;
  269. typedef DWORD pthread_key_t;
  270. typedef HANDLE pthread_t;
  271. typedef struct {
  272. CRITICAL_SECTION threadIdSec;
  273. int waitingthreadcount; /* The number of threads queued. */
  274. pthread_t *waitingthreadhdls; /* The thread handles. */
  275. } pthread_cond_t;
  276. #ifndef __clockid_t_defined
  277. typedef DWORD clockid_t;
  278. #endif
  279. #ifndef CLOCK_MONOTONIC
  280. #define CLOCK_MONOTONIC (1)
  281. #endif
  282. #ifndef CLOCK_REALTIME
  283. #define CLOCK_REALTIME (2)
  284. #endif
  285. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  286. #define _TIMESPEC_DEFINED
  287. #endif
  288. #ifndef _TIMESPEC_DEFINED
  289. struct timespec {
  290. time_t tv_sec; /* seconds */
  291. long tv_nsec; /* nanoseconds */
  292. };
  293. #endif
  294. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  295. static int pthread_mutex_lock(pthread_mutex_t *);
  296. static int pthread_mutex_unlock(pthread_mutex_t *);
  297. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  298. struct file;
  299. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  300. #if defined(HAVE_STDINT)
  301. #include <stdint.h>
  302. #else
  303. typedef unsigned char uint8_t;
  304. typedef unsigned short uint16_t;
  305. typedef unsigned int uint32_t;
  306. typedef unsigned __int64 uint64_t;
  307. typedef __int64 int64_t;
  308. #define INT64_MAX (9223372036854775807)
  309. #endif /* HAVE_STDINT */
  310. /* POSIX dirent interface */
  311. struct dirent {
  312. char d_name[PATH_MAX];
  313. };
  314. typedef struct DIR {
  315. HANDLE handle;
  316. WIN32_FIND_DATAW info;
  317. struct dirent result;
  318. } DIR;
  319. #if defined(_WIN32) && !defined(POLLIN)
  320. #ifndef HAVE_POLL
  321. struct pollfd {
  322. SOCKET fd;
  323. short events;
  324. short revents;
  325. };
  326. #define POLLIN (0x0300)
  327. #endif
  328. #endif
  329. /* Mark required libraries */
  330. #if defined(_MSC_VER)
  331. #pragma comment(lib, "Ws2_32.lib")
  332. #endif
  333. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  334. block */
  335. #include <sys/wait.h>
  336. #include <sys/socket.h>
  337. #include <sys/poll.h>
  338. #include <netinet/in.h>
  339. #include <arpa/inet.h>
  340. #include <sys/time.h>
  341. #include <sys/utsname.h>
  342. #include <stdint.h>
  343. #include <inttypes.h>
  344. #include <netdb.h>
  345. typedef const void *SOCK_OPT_TYPE;
  346. #if defined(ANDROID)
  347. typedef unsigned short int in_port_t;
  348. #endif
  349. #include <pwd.h>
  350. #include <unistd.h>
  351. #include <grp.h>
  352. #include <dirent.h>
  353. #define vsnprintf_impl vsnprintf
  354. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  355. #include <dlfcn.h>
  356. #endif
  357. #include <pthread.h>
  358. #if defined(__MACH__)
  359. #define SSL_LIB "libssl.dylib"
  360. #define CRYPTO_LIB "libcrypto.dylib"
  361. #else
  362. #if !defined(SSL_LIB)
  363. #define SSL_LIB "libssl.so"
  364. #endif
  365. #if !defined(CRYPTO_LIB)
  366. #define CRYPTO_LIB "libcrypto.so"
  367. #endif
  368. #endif
  369. #ifndef O_BINARY
  370. #define O_BINARY (0)
  371. #endif /* O_BINARY */
  372. #define closesocket(a) (close(a))
  373. #define mg_mkdir(x, y) (mkdir(x, y))
  374. #define mg_remove(x) (remove(x))
  375. #define mg_sleep(x) (usleep((x)*1000))
  376. #define ERRNO (errno)
  377. #define INVALID_SOCKET (-1)
  378. #define INT64_FMT PRId64
  379. #define UINT64_FMT PRIu64
  380. typedef int SOCKET;
  381. #define WINCDECL
  382. #if defined(__hpux)
  383. /* HPUX 11 does not have monotonic, fall back to realtime */
  384. #ifndef CLOCK_MONOTONIC
  385. #define CLOCK_MONOTONIC CLOCK_REALTIME
  386. #endif
  387. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  388. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  389. * the prototypes use int* rather than socklen_t* which matches the
  390. * actual library expectation. When called with the wrong size arg
  391. * accept() returns a zero client inet addr and check_acl() always
  392. * fails. Since socklen_t is widely used below, just force replace
  393. * their typedef with int. - DTL
  394. */
  395. #define socklen_t int
  396. #endif /* hpux */
  397. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  398. block */
  399. /* va_copy should always be a macro, C99 and C++11 - DTL */
  400. #ifndef va_copy
  401. #define va_copy(x, y) ((x) = (y))
  402. #endif
  403. #ifdef _WIN32
  404. /* Create substitutes for POSIX functions in Win32. */
  405. #if defined(__MINGW32__)
  406. /* Show no warning in case system functions are not used. */
  407. #pragma GCC diagnostic push
  408. #pragma GCC diagnostic ignored "-Wunused-function"
  409. #endif
  410. static CRITICAL_SECTION global_log_file_lock;
  411. static DWORD
  412. pthread_self(void)
  413. {
  414. return GetCurrentThreadId();
  415. }
  416. static int
  417. pthread_key_create(
  418. pthread_key_t *key,
  419. void (*_ignored)(void *) /* destructor not supported for Windows */
  420. )
  421. {
  422. (void)_ignored;
  423. if ((key != 0)) {
  424. *key = TlsAlloc();
  425. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  426. }
  427. return -2;
  428. }
  429. static int
  430. pthread_key_delete(pthread_key_t key)
  431. {
  432. return TlsFree(key) ? 0 : 1;
  433. }
  434. static int
  435. pthread_setspecific(pthread_key_t key, void *value)
  436. {
  437. return TlsSetValue(key, value) ? 0 : 1;
  438. }
  439. static void *
  440. pthread_getspecific(pthread_key_t key)
  441. {
  442. return TlsGetValue(key);
  443. }
  444. #if defined(__MINGW32__)
  445. /* Enable unused function warning again */
  446. #pragma GCC diagnostic pop
  447. #endif
  448. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  449. #else
  450. static pthread_mutexattr_t pthread_mutex_attr;
  451. #endif /* _WIN32 */
  452. #include "civetweb.h"
  453. #define PASSWORDS_FILE_NAME ".htpasswd"
  454. #define CGI_ENVIRONMENT_SIZE (4096)
  455. #define MAX_CGI_ENVIR_VARS (256)
  456. #define MG_BUF_LEN (8192)
  457. #ifndef MAX_REQUEST_SIZE
  458. #define MAX_REQUEST_SIZE (16384)
  459. #endif
  460. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  461. "request size length must be a positive number");
  462. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  463. #if !defined(DEBUG_TRACE)
  464. #if defined(DEBUG)
  465. static void DEBUG_TRACE_FUNC(const char *func,
  466. unsigned line,
  467. PRINTF_FORMAT_STRING(const char *fmt),
  468. ...) PRINTF_ARGS(3, 4);
  469. static void
  470. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  471. {
  472. va_list args;
  473. flockfile(stdout);
  474. printf("*** %lu.%p.%s.%u: ",
  475. (unsigned long)time(NULL),
  476. (void *)pthread_self(),
  477. func,
  478. line);
  479. va_start(args, fmt);
  480. vprintf(fmt, args);
  481. va_end(args);
  482. putchar('\n');
  483. fflush(stdout);
  484. funlockfile(stdout);
  485. }
  486. #define DEBUG_TRACE(fmt, ...) \
  487. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  488. #else
  489. #define DEBUG_TRACE(fmt, ...) \
  490. do { \
  491. } while (0)
  492. #endif /* DEBUG */
  493. #endif /* DEBUG_TRACE */
  494. #if defined(MEMORY_DEBUGGING)
  495. unsigned long mg_memory_debug_blockCount = 0;
  496. unsigned long mg_memory_debug_totalMemUsed = 0;
  497. static void *
  498. mg_malloc_ex(size_t size, const char *file, unsigned line)
  499. {
  500. void *data = malloc(size + sizeof(size_t));
  501. void *memory = 0;
  502. char mallocStr[256];
  503. if (data) {
  504. *(size_t *)data = size;
  505. mg_memory_debug_totalMemUsed += size;
  506. mg_memory_debug_blockCount++;
  507. memory = (void *)(((char *)data) + sizeof(size_t));
  508. }
  509. sprintf(mallocStr,
  510. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  511. memory,
  512. (unsigned long)size,
  513. mg_memory_debug_totalMemUsed,
  514. mg_memory_debug_blockCount,
  515. file,
  516. line);
  517. #if defined(_WIN32)
  518. OutputDebugStringA(mallocStr);
  519. #else
  520. DEBUG_TRACE("%s", mallocStr);
  521. #endif
  522. return memory;
  523. }
  524. static void *
  525. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  526. {
  527. void *data = mg_malloc_ex(size * count, file, line);
  528. if (data) {
  529. memset(data, 0, size);
  530. }
  531. return data;
  532. }
  533. static void
  534. mg_free_ex(void *memory, const char *file, unsigned line)
  535. {
  536. char mallocStr[256];
  537. void *data = (void *)(((char *)memory) - sizeof(size_t));
  538. size_t size;
  539. if (memory) {
  540. size = *(size_t *)data;
  541. mg_memory_debug_totalMemUsed -= size;
  542. mg_memory_debug_blockCount--;
  543. sprintf(mallocStr,
  544. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  545. memory,
  546. (unsigned long)size,
  547. mg_memory_debug_totalMemUsed,
  548. mg_memory_debug_blockCount,
  549. file,
  550. line);
  551. #if defined(_WIN32)
  552. OutputDebugStringA(mallocStr);
  553. #else
  554. DEBUG_TRACE("%s", mallocStr);
  555. #endif
  556. free(data);
  557. }
  558. }
  559. static void *
  560. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  561. {
  562. char mallocStr[256];
  563. void *data;
  564. void *_realloc;
  565. size_t oldsize;
  566. if (newsize) {
  567. if (memory) {
  568. data = (void *)(((char *)memory) - sizeof(size_t));
  569. oldsize = *(size_t *)data;
  570. _realloc = realloc(data, newsize + sizeof(size_t));
  571. if (_realloc) {
  572. data = _realloc;
  573. mg_memory_debug_totalMemUsed -= oldsize;
  574. sprintf(mallocStr,
  575. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  576. memory,
  577. (unsigned long)oldsize,
  578. mg_memory_debug_totalMemUsed,
  579. mg_memory_debug_blockCount,
  580. file,
  581. line);
  582. #if defined(_WIN32)
  583. OutputDebugStringA(mallocStr);
  584. #else
  585. DEBUG_TRACE("%s", mallocStr);
  586. #endif
  587. mg_memory_debug_totalMemUsed += newsize;
  588. sprintf(mallocStr,
  589. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  590. memory,
  591. (unsigned long)newsize,
  592. mg_memory_debug_totalMemUsed,
  593. mg_memory_debug_blockCount,
  594. file,
  595. line);
  596. #if defined(_WIN32)
  597. OutputDebugStringA(mallocStr);
  598. #else
  599. DEBUG_TRACE("%s", mallocStr);
  600. #endif
  601. *(size_t *)data = newsize;
  602. data = (void *)(((char *)data) + sizeof(size_t));
  603. } else {
  604. #if defined(_WIN32)
  605. OutputDebugStringA("MEM: realloc failed\n");
  606. #else
  607. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  608. #endif
  609. return _realloc;
  610. }
  611. } else {
  612. data = mg_malloc_ex(newsize, file, line);
  613. }
  614. } else {
  615. data = 0;
  616. mg_free_ex(memory, file, line);
  617. }
  618. return data;
  619. }
  620. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  621. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  622. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  623. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  624. #else
  625. static __inline void *
  626. mg_malloc(size_t a)
  627. {
  628. return malloc(a);
  629. }
  630. static __inline void *
  631. mg_calloc(size_t a, size_t b)
  632. {
  633. return calloc(a, b);
  634. }
  635. static __inline void *
  636. mg_realloc(void *a, size_t b)
  637. {
  638. return realloc(a, b);
  639. }
  640. static __inline void
  641. mg_free(void *a)
  642. {
  643. free(a);
  644. }
  645. #endif
  646. static void mg_vsnprintf(const struct mg_connection *conn,
  647. int *truncated,
  648. char *buf,
  649. size_t buflen,
  650. const char *fmt,
  651. va_list ap);
  652. static void mg_snprintf(const struct mg_connection *conn,
  653. int *truncated,
  654. char *buf,
  655. size_t buflen,
  656. PRINTF_FORMAT_STRING(const char *fmt),
  657. ...) PRINTF_ARGS(5, 6);
  658. /* This following lines are just meant as a reminder to use the mg-functions
  659. * for memory management */
  660. #ifdef malloc
  661. #undef malloc
  662. #endif
  663. #ifdef calloc
  664. #undef calloc
  665. #endif
  666. #ifdef realloc
  667. #undef realloc
  668. #endif
  669. #ifdef free
  670. #undef free
  671. #endif
  672. #ifdef snprintf
  673. #undef snprintf
  674. #endif
  675. #ifdef vsnprintf
  676. #undef vsnprintf
  677. #endif
  678. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  679. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  680. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  681. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  682. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  683. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  684. * but this define only works well for Windows. */
  685. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  686. #endif
  687. #define MD5_STATIC static
  688. #include "md5.inl"
  689. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  690. #ifdef NO_SOCKLEN_T
  691. typedef int socklen_t;
  692. #endif /* NO_SOCKLEN_T */
  693. #define _DARWIN_UNLIMITED_SELECT
  694. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  695. #if !defined(MSG_NOSIGNAL)
  696. #define MSG_NOSIGNAL (0)
  697. #endif
  698. #if !defined(SOMAXCONN)
  699. #define SOMAXCONN (100)
  700. #endif
  701. /* Size of the accepted socket queue */
  702. #if !defined(MGSQLEN)
  703. #define MGSQLEN (20)
  704. #endif
  705. #if defined(NO_SSL_DL)
  706. #include <openssl/ssl.h>
  707. #include <openssl/err.h>
  708. #include <openssl/crypto.h>
  709. #include <openssl/x509.h>
  710. #include <openssl/pem.h>
  711. #else
  712. /* SSL loaded dynamically from DLL.
  713. * I put the prototypes here to be independent from OpenSSL source
  714. * installation. */
  715. typedef struct ssl_st SSL;
  716. typedef struct ssl_method_st SSL_METHOD;
  717. typedef struct ssl_ctx_st SSL_CTX;
  718. typedef struct x509_store_ctx_st X509_STORE_CTX;
  719. #define SSL_VERIFY_NONE (0)
  720. #define SSL_VERIFY_PEER (1)
  721. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  722. #define SSL_VERIFY_CLIENT_ONCE (4)
  723. struct ssl_func {
  724. const char *name; /* SSL function name */
  725. void (*ptr)(void); /* Function pointer */
  726. };
  727. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  728. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  729. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  730. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  731. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  732. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  733. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  734. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  735. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  736. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  737. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  738. #define SSL_CTX_use_PrivateKey_file \
  739. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  740. #define SSL_CTX_use_certificate_file \
  741. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  742. #define SSL_CTX_set_default_passwd_cb \
  743. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  744. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  745. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  746. #define SSL_CTX_use_certificate_chain_file \
  747. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  748. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  749. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  750. #define SSL_CTX_set_verify \
  751. (*(void (*)(SSL_CTX *, \
  752. int, \
  753. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  754. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  755. #define SSL_CTX_load_verify_locations \
  756. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  757. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  758. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  759. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  760. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  761. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  762. #define SSL_CIPHER_get_name \
  763. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  764. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  765. #define SSL_CTX_set_session_id_context \
  766. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  767. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  768. #define CRYPTO_set_locking_callback \
  769. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  770. #define CRYPTO_set_id_callback \
  771. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  772. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  773. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  774. /* set_ssl_option() function updates this array.
  775. * It loads SSL library dynamically and changes NULLs to the actual addresses
  776. * of respective functions. The macros above (like SSL_connect()) are really
  777. * just calling these functions indirectly via the pointer. */
  778. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  779. {"SSL_accept", NULL},
  780. {"SSL_connect", NULL},
  781. {"SSL_read", NULL},
  782. {"SSL_write", NULL},
  783. {"SSL_get_error", NULL},
  784. {"SSL_set_fd", NULL},
  785. {"SSL_new", NULL},
  786. {"SSL_CTX_new", NULL},
  787. {"SSLv23_server_method", NULL},
  788. {"SSL_library_init", NULL},
  789. {"SSL_CTX_use_PrivateKey_file", NULL},
  790. {"SSL_CTX_use_certificate_file", NULL},
  791. {"SSL_CTX_set_default_passwd_cb", NULL},
  792. {"SSL_CTX_free", NULL},
  793. {"SSL_load_error_strings", NULL},
  794. {"SSL_CTX_use_certificate_chain_file", NULL},
  795. {"SSLv23_client_method", NULL},
  796. {"SSL_pending", NULL},
  797. {"SSL_CTX_set_verify", NULL},
  798. {"SSL_shutdown", NULL},
  799. {"SSL_CTX_load_verify_locations", NULL},
  800. {"SSL_CTX_set_default_verify_paths", NULL},
  801. {"SSL_CTX_set_verify_depth", NULL},
  802. {"SSL_get_peer_certificate", NULL},
  803. {"SSL_get_version", NULL},
  804. {"SSL_get_current_cipher", NULL},
  805. {"SSL_CIPHER_get_name", NULL},
  806. {"SSL_CTX_check_private_key", NULL},
  807. {"SSL_CTX_set_session_id_context", NULL},
  808. {NULL, NULL}};
  809. /* Similar array as ssl_sw. These functions could be located in different
  810. * lib. */
  811. #if !defined(NO_SSL)
  812. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  813. {"CRYPTO_set_locking_callback", NULL},
  814. {"CRYPTO_set_id_callback", NULL},
  815. {"ERR_get_error", NULL},
  816. {"ERR_error_string", NULL},
  817. {NULL, NULL}};
  818. #endif /* NO_SSL */
  819. #endif /* NO_SSL_DL */
  820. static const char *month_names[] = {"Jan",
  821. "Feb",
  822. "Mar",
  823. "Apr",
  824. "May",
  825. "Jun",
  826. "Jul",
  827. "Aug",
  828. "Sep",
  829. "Oct",
  830. "Nov",
  831. "Dec"};
  832. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  833. * union u. */
  834. union usa {
  835. struct sockaddr sa;
  836. struct sockaddr_in sin;
  837. #if defined(USE_IPV6)
  838. struct sockaddr_in6 sin6;
  839. #endif
  840. };
  841. /* Describes a string (chunk of memory). */
  842. struct vec {
  843. const char *ptr;
  844. size_t len;
  845. };
  846. struct file {
  847. uint64_t size;
  848. time_t last_modified;
  849. FILE *fp;
  850. const char *membuf; /* Non-NULL if file data is in memory */
  851. int is_directory;
  852. int gzipped; /* set to 1 if the content is gzipped
  853. * in which case we need a content-encoding: gzip header */
  854. };
  855. #define STRUCT_FILE_INITIALIZER \
  856. { \
  857. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  858. }
  859. /* Describes listening socket, or socket which was accept()-ed by the master
  860. * thread and queued for future handling by the worker thread. */
  861. struct socket {
  862. SOCKET sock; /* Listening socket */
  863. union usa lsa; /* Local socket address */
  864. union usa rsa; /* Remote socket address */
  865. unsigned char is_ssl; /* Is port SSL-ed */
  866. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  867. * port */
  868. };
  869. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  870. enum {
  871. CGI_EXTENSIONS,
  872. CGI_ENVIRONMENT,
  873. PUT_DELETE_PASSWORDS_FILE,
  874. CGI_INTERPRETER,
  875. PROTECT_URI,
  876. AUTHENTICATION_DOMAIN,
  877. SSI_EXTENSIONS,
  878. THROTTLE,
  879. ACCESS_LOG_FILE,
  880. ENABLE_DIRECTORY_LISTING,
  881. ERROR_LOG_FILE,
  882. GLOBAL_PASSWORDS_FILE,
  883. INDEX_FILES,
  884. ENABLE_KEEP_ALIVE,
  885. ACCESS_CONTROL_LIST,
  886. EXTRA_MIME_TYPES,
  887. LISTENING_PORTS,
  888. DOCUMENT_ROOT,
  889. SSL_CERTIFICATE,
  890. NUM_THREADS,
  891. RUN_AS_USER,
  892. REWRITE,
  893. HIDE_FILES,
  894. REQUEST_TIMEOUT,
  895. SSL_DO_VERIFY_PEER,
  896. SSL_CA_PATH,
  897. SSL_CA_FILE,
  898. SSL_VERIFY_DEPTH,
  899. SSL_DEFAULT_VERIFY_PATHS,
  900. SSL_FORWARD_SECRECY,
  901. #if defined(USE_WEBSOCKET)
  902. WEBSOCKET_TIMEOUT,
  903. #endif
  904. DECODE_URL,
  905. #if defined(USE_LUA)
  906. LUA_PRELOAD_FILE,
  907. LUA_SCRIPT_EXTENSIONS,
  908. LUA_SERVER_PAGE_EXTENSIONS,
  909. #endif
  910. #if defined(USE_DUKTAPE)
  911. DUKTAPE_SCRIPT_EXTENSIONS,
  912. #endif
  913. #if defined(USE_WEBSOCKET)
  914. WEBSOCKET_ROOT,
  915. #endif
  916. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  917. LUA_WEBSOCKET_EXTENSIONS,
  918. #endif
  919. ACCESS_CONTROL_ALLOW_ORIGIN,
  920. ERROR_PAGES,
  921. NUM_OPTIONS
  922. };
  923. /* Config option name, config types, default value */
  924. static struct mg_option config_options[] = {
  925. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  926. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  927. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  928. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  929. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  930. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  931. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  932. {"throttle", CONFIG_TYPE_STRING, NULL},
  933. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  934. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  935. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  936. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  937. {"index_files",
  938. CONFIG_TYPE_STRING,
  939. #ifdef USE_LUA
  940. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  941. "index.shtml,index.php"},
  942. #else
  943. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  944. #endif
  945. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  946. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  947. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  948. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  949. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  950. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  951. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  952. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  953. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  954. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  955. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  956. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  957. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  958. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  959. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  960. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  961. {"ssl_forward_secrecy", CONFIG_TYPE_BOOLEAN, "yes"},
  962. #if defined(USE_WEBSOCKET)
  963. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  964. #endif
  965. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  966. #if defined(USE_LUA)
  967. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  968. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  969. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  970. #endif
  971. #if defined(USE_DUKTAPE)
  972. {"_experimental_duktape_script_pattern",
  973. CONFIG_TYPE_EXT_PATTERN,
  974. "**.ssjs$"}, /* TODO: redefine parameter */
  975. #endif
  976. #if defined(USE_WEBSOCKET)
  977. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  978. #endif
  979. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  980. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  981. #endif
  982. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  983. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  984. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  985. /* Check if the config_options and the corresponding enum have compatible
  986. * sizes. */
  987. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  988. == (NUM_OPTIONS + 1),
  989. "config_options and enum not sync");
  990. struct mg_request_handler_info {
  991. /* Name/Pattern of the URI. */
  992. char *uri;
  993. size_t uri_len;
  994. /* URI type: ws/wss (websocket) or http/https (web page). */
  995. int is_websocket_handler;
  996. /* Handler for http/https requests. */
  997. mg_request_handler handler;
  998. /* Handler for ws/wss (websocket) requests. */
  999. mg_websocket_connect_handler connect_handler;
  1000. mg_websocket_ready_handler ready_handler;
  1001. mg_websocket_data_handler data_handler;
  1002. mg_websocket_close_handler close_handler;
  1003. /* User supplied argument for the handler function. */
  1004. void *cbdata;
  1005. /* next request handler in a linked list */
  1006. struct mg_request_handler_info *next;
  1007. };
  1008. struct mg_context {
  1009. volatile int stop_flag; /* Should we stop event loop */
  1010. SSL_CTX *ssl_ctx; /* SSL context */
  1011. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1012. struct mg_callbacks callbacks; /* User-defined callback function */
  1013. void *user_data; /* User-defined data */
  1014. int context_type; /* 1 = server context, 2 = client context */
  1015. struct socket *listening_sockets;
  1016. in_port_t *listening_ports;
  1017. unsigned int num_listening_sockets;
  1018. volatile int
  1019. running_worker_threads; /* Number of currently running worker threads */
  1020. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1021. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1022. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1023. volatile int sq_head; /* Head of the socket queue */
  1024. volatile int sq_tail; /* Tail of the socket queue */
  1025. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1026. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1027. pthread_t masterthreadid; /* The master thread ID */
  1028. unsigned int
  1029. cfg_worker_threads; /* The number of configured worker threads. */
  1030. pthread_t *workerthreadids; /* The worker thread IDs */
  1031. time_t start_time; /* Server start time, used for authentication */
  1032. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1033. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1034. unsigned long nonce_count; /* Used nonces, used for authentication */
  1035. char *systemName; /* What operating system is running */
  1036. /* linked list of uri handlers */
  1037. struct mg_request_handler_info *request_handlers;
  1038. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1039. /* linked list of shared lua websockets */
  1040. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1041. #endif
  1042. #ifdef USE_TIMERS
  1043. struct ttimers *timers;
  1044. #endif
  1045. };
  1046. struct mg_connection {
  1047. struct mg_request_info request_info;
  1048. struct mg_context *ctx;
  1049. SSL *ssl; /* SSL descriptor */
  1050. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1051. struct socket client; /* Connected client */
  1052. time_t conn_birth_time; /* Time (wall clock) when connection was
  1053. * established */
  1054. struct timespec req_time; /* Time (since system start) when the request
  1055. * was received */
  1056. int64_t num_bytes_sent; /* Total bytes sent to client */
  1057. int64_t content_len; /* Content-Length header value */
  1058. int64_t consumed_content; /* How many bytes of content have been read */
  1059. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1060. * data available, 2: all data read */
  1061. size_t chunk_remainder; /* Unread data from the last chunk */
  1062. char *buf; /* Buffer for received data */
  1063. char *path_info; /* PATH_INFO part of the URL */
  1064. int must_close; /* 1 if connection must be closed */
  1065. int in_error_handler; /* 1 if in handler for user defined error
  1066. * pages */
  1067. int internal_error; /* 1 if an error occured while processing the
  1068. * request */
  1069. int buf_size; /* Buffer size */
  1070. int request_len; /* Size of the request + headers in a buffer */
  1071. int data_len; /* Total size of data in a buffer */
  1072. int status_code; /* HTTP reply status code, e.g. 200 */
  1073. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1074. * throttle */
  1075. time_t last_throttle_time; /* Last time throttled data was sent */
  1076. int64_t last_throttle_bytes; /* Bytes sent this second */
  1077. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1078. * atomic transmissions for websockets */
  1079. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1080. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1081. #endif
  1082. };
  1083. static pthread_key_t sTlsKey; /* Thread local storage index */
  1084. static int sTlsInit = 0;
  1085. static int thread_idx_max = 0;
  1086. struct mg_workerTLS {
  1087. int is_master;
  1088. unsigned long thread_idx;
  1089. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1090. HANDLE pthread_cond_helper_mutex;
  1091. #endif
  1092. };
  1093. /* Directory entry */
  1094. struct de {
  1095. struct mg_connection *conn;
  1096. char *file_name;
  1097. struct file file;
  1098. };
  1099. #if defined(USE_WEBSOCKET)
  1100. static int is_websocket_protocol(const struct mg_connection *conn);
  1101. #else
  1102. #define is_websocket_protocol(conn) (0)
  1103. #endif
  1104. static int
  1105. mg_atomic_inc(volatile int *addr)
  1106. {
  1107. int ret;
  1108. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1109. /* Depending on the SDK, this function uses either
  1110. * (volatile unsigned int *) or (volatile LONG *),
  1111. * so whatever you use, the other SDK is likely to raise a warning. */
  1112. ret = InterlockedIncrement((volatile long *)addr);
  1113. #elif defined(__GNUC__) \
  1114. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1115. ret = __sync_add_and_fetch(addr, 1);
  1116. #else
  1117. ret = (++(*addr));
  1118. #endif
  1119. return ret;
  1120. }
  1121. static int
  1122. mg_atomic_dec(volatile int *addr)
  1123. {
  1124. int ret;
  1125. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1126. /* Depending on the SDK, this function uses either
  1127. * (volatile unsigned int *) or (volatile LONG *),
  1128. * so whatever you use, the other SDK is likely to raise a warning. */
  1129. ret = InterlockedDecrement((volatile long *)addr);
  1130. #elif defined(__GNUC__) \
  1131. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1132. ret = __sync_sub_and_fetch(addr, 1);
  1133. #else
  1134. ret = (--(*addr));
  1135. #endif
  1136. return ret;
  1137. }
  1138. #if !defined(NO_THREAD_NAME)
  1139. #if defined(_WIN32) && defined(_MSC_VER)
  1140. /* Set the thread name for debugging purposes in Visual Studio
  1141. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1142. */
  1143. #pragma pack(push, 8)
  1144. typedef struct tagTHREADNAME_INFO {
  1145. DWORD dwType; /* Must be 0x1000. */
  1146. LPCSTR szName; /* Pointer to name (in user addr space). */
  1147. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1148. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1149. } THREADNAME_INFO;
  1150. #pragma pack(pop)
  1151. #elif defined(__linux__)
  1152. #include <sys/prctl.h>
  1153. #include <sys/sendfile.h>
  1154. #endif
  1155. static void
  1156. mg_set_thread_name(const char *name)
  1157. {
  1158. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1159. mg_snprintf(
  1160. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1161. #if defined(_WIN32)
  1162. #if defined(_MSC_VER)
  1163. /* Windows and Visual Studio Compiler */
  1164. __try
  1165. {
  1166. THREADNAME_INFO info;
  1167. info.dwType = 0x1000;
  1168. info.szName = threadName;
  1169. info.dwThreadID = ~0U;
  1170. info.dwFlags = 0;
  1171. RaiseException(0x406D1388,
  1172. 0,
  1173. sizeof(info) / sizeof(ULONG_PTR),
  1174. (ULONG_PTR *)&info);
  1175. }
  1176. __except(EXCEPTION_EXECUTE_HANDLER)
  1177. {
  1178. }
  1179. #elif defined(__MINGW32__)
  1180. /* No option known to set thread name for MinGW */
  1181. #endif
  1182. #elif defined(__GLIBC__) \
  1183. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1184. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1185. (void)pthread_setname_np(pthread_self(), threadName);
  1186. #elif defined(__linux__)
  1187. /* on linux we can use the old prctl function */
  1188. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1189. #endif
  1190. }
  1191. #else /* !defined(NO_THREAD_NAME) */
  1192. void
  1193. mg_set_thread_name(const char *threadName)
  1194. {
  1195. }
  1196. #endif
  1197. #if defined(MG_LEGACY_INTERFACE)
  1198. const char **
  1199. mg_get_valid_option_names(void)
  1200. {
  1201. /* This function is deprecated. Use mg_get_valid_options instead. */
  1202. static const char *
  1203. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1204. int i;
  1205. for (i = 0; config_options[i].name != NULL; i++) {
  1206. data[i * 2] = config_options[i].name;
  1207. data[i * 2 + 1] = config_options[i].default_value;
  1208. }
  1209. return data;
  1210. }
  1211. #endif
  1212. const struct mg_option *
  1213. mg_get_valid_options(void)
  1214. {
  1215. return config_options;
  1216. }
  1217. static int
  1218. is_file_in_memory(struct mg_connection *conn,
  1219. const char *path,
  1220. struct file *filep)
  1221. {
  1222. size_t size = 0;
  1223. if (!conn || !filep) {
  1224. return 0;
  1225. }
  1226. if (conn->ctx->callbacks.open_file) {
  1227. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1228. if (filep->membuf != NULL) {
  1229. /* NOTE: override filep->size only on success. Otherwise, it might
  1230. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1231. filep->size = size;
  1232. }
  1233. }
  1234. return filep->membuf != NULL;
  1235. }
  1236. static int
  1237. is_file_opened(const struct file *filep)
  1238. {
  1239. if (!filep) {
  1240. return 0;
  1241. }
  1242. return filep->membuf != NULL || filep->fp != NULL;
  1243. }
  1244. static int
  1245. mg_fopen(struct mg_connection *conn,
  1246. const char *path,
  1247. const char *mode,
  1248. struct file *filep)
  1249. {
  1250. if (!filep) {
  1251. return 0;
  1252. }
  1253. memset(filep, 0, sizeof(*filep));
  1254. if (!is_file_in_memory(conn, path, filep)) {
  1255. #ifdef _WIN32
  1256. wchar_t wbuf[PATH_MAX], wmode[20];
  1257. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1258. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1259. filep->fp = _wfopen(wbuf, wmode);
  1260. #else
  1261. filep->fp = fopen(path, mode);
  1262. #endif
  1263. }
  1264. return is_file_opened(filep);
  1265. }
  1266. static void
  1267. mg_fclose(struct file *filep)
  1268. {
  1269. if (filep != NULL && filep->fp != NULL) {
  1270. fclose(filep->fp);
  1271. }
  1272. }
  1273. static void
  1274. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1275. {
  1276. for (; *src != '\0' && n > 1; n--) {
  1277. *dst++ = *src++;
  1278. }
  1279. *dst = '\0';
  1280. }
  1281. static int
  1282. lowercase(const char *s)
  1283. {
  1284. return tolower(*(const unsigned char *)s);
  1285. }
  1286. int
  1287. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1288. {
  1289. int diff = 0;
  1290. if (len > 0) {
  1291. do {
  1292. diff = lowercase(s1++) - lowercase(s2++);
  1293. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1294. }
  1295. return diff;
  1296. }
  1297. static int
  1298. mg_strcasecmp(const char *s1, const char *s2)
  1299. {
  1300. int diff;
  1301. do {
  1302. diff = lowercase(s1++) - lowercase(s2++);
  1303. } while (diff == 0 && s1[-1] != '\0');
  1304. return diff;
  1305. }
  1306. static char *
  1307. mg_strndup(const char *ptr, size_t len)
  1308. {
  1309. char *p;
  1310. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1311. mg_strlcpy(p, ptr, len + 1);
  1312. }
  1313. return p;
  1314. }
  1315. static char *
  1316. mg_strdup(const char *str)
  1317. {
  1318. return mg_strndup(str, strlen(str));
  1319. }
  1320. static const char *
  1321. mg_strcasestr(const char *big_str, const char *small_str)
  1322. {
  1323. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1324. if (big_len >= small_len) {
  1325. for (i = 0; i <= (big_len - small_len); i++) {
  1326. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1327. return big_str + i;
  1328. }
  1329. }
  1330. }
  1331. return NULL;
  1332. }
  1333. /* Return null terminated string of given maximum length.
  1334. * Report errors if length is exceeded. */
  1335. static void
  1336. mg_vsnprintf(const struct mg_connection *conn,
  1337. int *truncated,
  1338. char *buf,
  1339. size_t buflen,
  1340. const char *fmt,
  1341. va_list ap)
  1342. {
  1343. int n, ok;
  1344. if (buflen == 0) {
  1345. return;
  1346. }
  1347. #ifdef __clang__
  1348. #pragma clang diagnostic push
  1349. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1350. /* Using fmt as a non-literal is intended here, since it is mostly called
  1351. * indirectly by mg_snprintf */
  1352. #endif
  1353. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1354. ok = (n >= 0) && ((size_t)n < buflen);
  1355. #ifdef __clang__
  1356. #pragma clang diagnostic pop
  1357. #endif
  1358. if (ok) {
  1359. if (truncated) {
  1360. *truncated = 0;
  1361. }
  1362. } else {
  1363. if (truncated) {
  1364. *truncated = 1;
  1365. }
  1366. mg_cry(conn,
  1367. "truncating vsnprintf buffer: [%.*s]",
  1368. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1369. buf);
  1370. n = (int)buflen - 1;
  1371. }
  1372. buf[n] = '\0';
  1373. }
  1374. static void
  1375. mg_snprintf(const struct mg_connection *conn,
  1376. int *truncated,
  1377. char *buf,
  1378. size_t buflen,
  1379. const char *fmt,
  1380. ...)
  1381. {
  1382. va_list ap;
  1383. va_start(ap, fmt);
  1384. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1385. va_end(ap);
  1386. }
  1387. static int
  1388. get_option_index(const char *name)
  1389. {
  1390. int i;
  1391. for (i = 0; config_options[i].name != NULL; i++) {
  1392. if (strcmp(config_options[i].name, name) == 0) {
  1393. return i;
  1394. }
  1395. }
  1396. return -1;
  1397. }
  1398. const char *
  1399. mg_get_option(const struct mg_context *ctx, const char *name)
  1400. {
  1401. int i;
  1402. if ((i = get_option_index(name)) == -1) {
  1403. return NULL;
  1404. } else if (!ctx || ctx->config[i] == NULL) {
  1405. return "";
  1406. } else {
  1407. return ctx->config[i];
  1408. }
  1409. }
  1410. struct mg_context *
  1411. mg_get_context(const struct mg_connection *conn)
  1412. {
  1413. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1414. }
  1415. void *
  1416. mg_get_user_data(const struct mg_context *ctx)
  1417. {
  1418. return (ctx == NULL) ? NULL : ctx->user_data;
  1419. }
  1420. void
  1421. mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1422. {
  1423. if (conn != NULL) {
  1424. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1425. }
  1426. }
  1427. void *
  1428. mg_get_user_connection_data(const struct mg_connection *conn)
  1429. {
  1430. if (conn != NULL) {
  1431. return conn->request_info.conn_data;
  1432. }
  1433. return NULL;
  1434. }
  1435. size_t
  1436. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1437. {
  1438. size_t i;
  1439. if (!ctx) {
  1440. return 0;
  1441. }
  1442. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1443. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1444. ports[i] = ctx->listening_ports[i];
  1445. }
  1446. return i;
  1447. }
  1448. int
  1449. mg_get_server_ports(const struct mg_context *ctx,
  1450. int size,
  1451. struct mg_server_ports *ports)
  1452. {
  1453. int i, cnt = 0;
  1454. if (size <= 0) {
  1455. return -1;
  1456. }
  1457. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1458. if (!ctx) {
  1459. return -1;
  1460. }
  1461. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1462. return -1;
  1463. }
  1464. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1465. ports[cnt].port = ctx->listening_ports[i];
  1466. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1467. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1468. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1469. /* IPv4 */
  1470. ports[cnt].protocol = 1;
  1471. cnt++;
  1472. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1473. /* IPv6 */
  1474. ports[cnt].protocol = 3;
  1475. cnt++;
  1476. }
  1477. }
  1478. return cnt;
  1479. }
  1480. static void
  1481. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1482. {
  1483. buf[0] = '\0';
  1484. if (!usa) {
  1485. return;
  1486. }
  1487. if (usa->sa.sa_family == AF_INET) {
  1488. getnameinfo(&usa->sa,
  1489. sizeof(usa->sin),
  1490. buf,
  1491. (unsigned)len,
  1492. NULL,
  1493. 0,
  1494. NI_NUMERICHOST);
  1495. }
  1496. #if defined(USE_IPV6)
  1497. else if (usa->sa.sa_family == AF_INET6) {
  1498. getnameinfo(&usa->sa,
  1499. sizeof(usa->sin6),
  1500. buf,
  1501. (unsigned)len,
  1502. NULL,
  1503. 0,
  1504. NI_NUMERICHOST);
  1505. }
  1506. #endif
  1507. }
  1508. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1509. * included in all responses other than 100, 101, 5xx. */
  1510. static void
  1511. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1512. {
  1513. struct tm *tm;
  1514. tm = gmtime(t);
  1515. if (tm != NULL) {
  1516. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1517. } else {
  1518. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1519. buf[buf_len - 1] = '\0';
  1520. }
  1521. }
  1522. /* difftime for struct timespec. Return value is in seconds. */
  1523. static double
  1524. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1525. {
  1526. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1527. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1528. }
  1529. /* Print error message to the opened error log stream. */
  1530. void
  1531. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1532. {
  1533. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1534. va_list ap;
  1535. FILE *fp;
  1536. time_t timestamp;
  1537. va_start(ap, fmt);
  1538. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1539. va_end(ap);
  1540. buf[sizeof(buf) - 1] = 0;
  1541. /* Do not lock when getting the callback value, here and below.
  1542. * I suppose this is fine, since function cannot disappear in the
  1543. * same way string option can. */
  1544. if (conn && (conn->ctx->callbacks.log_message == NULL
  1545. || conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1546. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1547. ? NULL
  1548. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1549. if (fp != NULL) {
  1550. flockfile(fp);
  1551. timestamp = time(NULL);
  1552. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1553. fprintf(fp,
  1554. "[%010lu] [error] [client %s] ",
  1555. (unsigned long)timestamp,
  1556. src_addr);
  1557. if (conn->request_info.request_method != NULL) {
  1558. fprintf(fp,
  1559. "%s %s: ",
  1560. conn->request_info.request_method,
  1561. conn->request_info.request_uri);
  1562. }
  1563. fprintf(fp, "%s", buf);
  1564. fputc('\n', fp);
  1565. funlockfile(fp);
  1566. fclose(fp);
  1567. }
  1568. }
  1569. }
  1570. /* Return fake connection structure. Used for logging, if connection
  1571. * is not applicable at the moment of logging. */
  1572. static struct mg_connection *
  1573. fc(struct mg_context *ctx)
  1574. {
  1575. static struct mg_connection fake_connection;
  1576. fake_connection.ctx = ctx;
  1577. return &fake_connection;
  1578. }
  1579. const char *
  1580. mg_version(void)
  1581. {
  1582. return CIVETWEB_VERSION;
  1583. }
  1584. const struct mg_request_info *
  1585. mg_get_request_info(const struct mg_connection *conn)
  1586. {
  1587. if (!conn) {
  1588. return NULL;
  1589. }
  1590. return &conn->request_info;
  1591. }
  1592. /* Skip the characters until one of the delimiters characters found.
  1593. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1594. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1595. * Delimiters can be quoted with quotechar. */
  1596. static char *
  1597. skip_quoted(char **buf,
  1598. const char *delimiters,
  1599. const char *whitespace,
  1600. char quotechar)
  1601. {
  1602. char *p, *begin_word, *end_word, *end_whitespace;
  1603. begin_word = *buf;
  1604. end_word = begin_word + strcspn(begin_word, delimiters);
  1605. /* Check for quotechar */
  1606. if (end_word > begin_word) {
  1607. p = end_word - 1;
  1608. while (*p == quotechar) {
  1609. /* While the delimiter is quoted, look for the next delimiter. */
  1610. /* This happens, e.g., in calls from parse_auth_header,
  1611. * if the user name contains a " character. */
  1612. /* If there is anything beyond end_word, copy it. */
  1613. if (*end_word != '\0') {
  1614. size_t end_off = strcspn(end_word + 1, delimiters);
  1615. memmove(p, end_word, end_off + 1);
  1616. p += end_off; /* p must correspond to end_word - 1 */
  1617. end_word += end_off + 1;
  1618. } else {
  1619. *p = '\0';
  1620. break;
  1621. }
  1622. }
  1623. for (p++; p < end_word; p++) {
  1624. *p = '\0';
  1625. }
  1626. }
  1627. if (*end_word == '\0') {
  1628. *buf = end_word;
  1629. } else {
  1630. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1631. for (p = end_word; p < end_whitespace; p++) {
  1632. *p = '\0';
  1633. }
  1634. *buf = end_whitespace;
  1635. }
  1636. return begin_word;
  1637. }
  1638. /* Simplified version of skip_quoted without quote char
  1639. * and whitespace == delimiters */
  1640. static char *
  1641. skip(char **buf, const char *delimiters)
  1642. {
  1643. return skip_quoted(buf, delimiters, delimiters, 0);
  1644. }
  1645. /* Return HTTP header value, or NULL if not found. */
  1646. static const char *
  1647. get_header(const struct mg_request_info *ri, const char *name)
  1648. {
  1649. int i;
  1650. if (ri) {
  1651. for (i = 0; i < ri->num_headers; i++) {
  1652. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1653. return ri->http_headers[i].value;
  1654. }
  1655. }
  1656. }
  1657. return NULL;
  1658. }
  1659. const char *
  1660. mg_get_header(const struct mg_connection *conn, const char *name)
  1661. {
  1662. if (!conn) {
  1663. return NULL;
  1664. }
  1665. return get_header(&conn->request_info, name);
  1666. }
  1667. /* A helper function for traversing a comma separated list of values.
  1668. * It returns a list pointer shifted to the next value, or NULL if the end
  1669. * of the list found.
  1670. * Value is stored in val vector. If value has form "x=y", then eq_val
  1671. * vector is initialized to point to the "y" part, and val vector length
  1672. * is adjusted to point only to "x". */
  1673. static const char *
  1674. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1675. {
  1676. if (val == NULL || list == NULL || *list == '\0') {
  1677. /* End of the list */
  1678. list = NULL;
  1679. } else {
  1680. val->ptr = list;
  1681. if ((list = strchr(val->ptr, ',')) != NULL) {
  1682. /* Comma found. Store length and shift the list ptr */
  1683. val->len = ((size_t)(list - val->ptr));
  1684. list++;
  1685. } else {
  1686. /* This value is the last one */
  1687. list = val->ptr + strlen(val->ptr);
  1688. val->len = ((size_t)(list - val->ptr));
  1689. }
  1690. if (eq_val != NULL) {
  1691. /* Value has form "x=y", adjust pointers and lengths
  1692. * so that val points to "x", and eq_val points to "y". */
  1693. eq_val->len = 0;
  1694. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1695. if (eq_val->ptr != NULL) {
  1696. eq_val->ptr++; /* Skip over '=' character */
  1697. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1698. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1699. }
  1700. }
  1701. }
  1702. return list;
  1703. }
  1704. /* Perform case-insensitive match of string against pattern */
  1705. static int
  1706. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1707. {
  1708. const char *or_str;
  1709. size_t i;
  1710. int j, len, res;
  1711. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1712. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1713. return res > 0 ? res : match_prefix(or_str + 1,
  1714. (size_t)((pattern + pattern_len)
  1715. - (or_str + 1)),
  1716. str);
  1717. }
  1718. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1719. if (pattern[i] == '?' && str[j] != '\0') {
  1720. continue;
  1721. } else if (pattern[i] == '$') {
  1722. return str[j] == '\0' ? j : -1;
  1723. } else if (pattern[i] == '*') {
  1724. i++;
  1725. if (pattern[i] == '*') {
  1726. i++;
  1727. len = (int)strlen(str + j);
  1728. } else {
  1729. len = (int)strcspn(str + j, "/");
  1730. }
  1731. if (i == pattern_len) {
  1732. return j + len;
  1733. }
  1734. do {
  1735. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1736. } while (res == -1 && len-- > 0);
  1737. return res == -1 ? -1 : j + res + len;
  1738. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1739. return -1;
  1740. }
  1741. }
  1742. return j;
  1743. }
  1744. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1745. * This function must tolerate situations when connection info is not
  1746. * set up, for example if request parsing failed. */
  1747. static int
  1748. should_keep_alive(const struct mg_connection *conn)
  1749. {
  1750. if (conn != NULL) {
  1751. const char *http_version = conn->request_info.http_version;
  1752. const char *header = mg_get_header(conn, "Connection");
  1753. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1754. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1755. || (header != NULL && mg_strcasecmp(header, "keep-alive") != 0)
  1756. || (header == NULL && http_version
  1757. && 0 != strcmp(http_version, "1.1"))) {
  1758. return 0;
  1759. }
  1760. return 1;
  1761. }
  1762. return 0;
  1763. }
  1764. static int
  1765. should_decode_url(const struct mg_connection *conn)
  1766. {
  1767. if (!conn || !conn->ctx) {
  1768. return 0;
  1769. }
  1770. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1771. }
  1772. static const char *
  1773. suggest_connection_header(const struct mg_connection *conn)
  1774. {
  1775. return should_keep_alive(conn) ? "keep-alive" : "close";
  1776. }
  1777. static void handle_file_based_request(struct mg_connection *conn,
  1778. const char *path,
  1779. struct file *filep);
  1780. static int
  1781. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1782. static const char *
  1783. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1784. {
  1785. switch (response_code) {
  1786. /* RFC2616 Section 10.1 - Informational 1xx */
  1787. case 100:
  1788. return "Continue"; /* RFC2616 Section 10.1.1 */
  1789. case 101:
  1790. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1791. case 102:
  1792. return "Processing"; /* RFC2518 Section 10.1 */
  1793. /* RFC2616 Section 10.2 - Successful 2xx */
  1794. case 200:
  1795. return "OK"; /* RFC2616 Section 10.2.1 */
  1796. case 201:
  1797. return "Created"; /* RFC2616 Section 10.2.2 */
  1798. case 202:
  1799. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1800. case 203:
  1801. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1802. case 204:
  1803. return "No Content"; /* RFC2616 Section 10.2.5 */
  1804. case 205:
  1805. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1806. case 206:
  1807. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1808. case 207:
  1809. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1810. /* RFC2616 Section 10.3 - Redirection 3xx */
  1811. case 300:
  1812. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1813. case 301:
  1814. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1815. case 302:
  1816. return "Found"; /* RFC2616 Section 10.3.3 */
  1817. case 303:
  1818. return "See Other"; /* RFC2616 Section 10.3.4 */
  1819. case 304:
  1820. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1821. case 305:
  1822. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1823. case 307:
  1824. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1825. /* RFC2616 Section 10.4 - Client Error 4xx */
  1826. case 400:
  1827. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1828. case 401:
  1829. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1830. case 402:
  1831. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1832. case 403:
  1833. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1834. case 404:
  1835. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1836. case 405:
  1837. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1838. case 406:
  1839. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1840. case 407:
  1841. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1842. case 408:
  1843. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1844. case 409:
  1845. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1846. case 410:
  1847. return "Gone"; /* RFC2616 Section 10.4.11 */
  1848. case 411:
  1849. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1850. case 412:
  1851. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1852. case 413:
  1853. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1854. case 414:
  1855. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1856. case 415:
  1857. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1858. case 416:
  1859. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1860. case 417:
  1861. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1862. case 422:
  1863. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1864. * Section 11.2 */
  1865. case 423:
  1866. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1867. case 424:
  1868. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1869. * Section 11.4 */
  1870. case 428:
  1871. return "Precondition Required"; /* RFC 6585, Section 3 */
  1872. case 429:
  1873. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1874. case 431:
  1875. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1876. /* RFC2616 Section 10.5 - Server Error 5xx */
  1877. case 500:
  1878. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1879. case 501:
  1880. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1881. case 502:
  1882. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1883. case 503:
  1884. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1885. case 504:
  1886. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1887. case 505:
  1888. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1889. case 507:
  1890. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  1891. * Section 11.5 */
  1892. case 511:
  1893. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1894. /* Other RFCs */
  1895. case 426:
  1896. return "Upgrade Required"; /* RFC 2817 */
  1897. /* Return codes from non normative RFCs: */
  1898. /* Informative and experimental RFCs, "de facto" standards due to common
  1899. * use, ... */
  1900. case 208:
  1901. return "Already Reported"; /* RFC5842 Section 7.1 */
  1902. case 226:
  1903. return "IM used"; /* RFC3229 Section 10.4.1 */
  1904. case 308:
  1905. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1906. case 418:
  1907. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1908. case 419:
  1909. return "Authentication Timeout"; /* common use */
  1910. case 451:
  1911. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1912. * Section 3 */
  1913. case 506:
  1914. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1915. case 508:
  1916. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1917. case 510:
  1918. return "Not Extended"; /* RFC 2774, Section 7 */
  1919. default:
  1920. /* This error code is unknown. This should not happen. */
  1921. if (conn) {
  1922. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1923. }
  1924. /* Return at least a category according to RFC 2616 Section 10. */
  1925. if (response_code >= 100 && response_code < 200) {
  1926. /* Unknown informational status code */
  1927. return "Information";
  1928. }
  1929. if (response_code >= 200 && response_code < 300) {
  1930. /* Unknown success code */
  1931. return "Success";
  1932. }
  1933. if (response_code >= 300 && response_code < 400) {
  1934. /* Unknown redirection code */
  1935. return "Redirection";
  1936. }
  1937. if (response_code >= 400 && response_code < 500) {
  1938. /* Unknown request error code */
  1939. return "Client Error";
  1940. }
  1941. if (response_code >= 500 && response_code < 600) {
  1942. /* Unknown server error code */
  1943. return "Server Error";
  1944. }
  1945. /* Response code not even within reasonable range */
  1946. return "";
  1947. }
  1948. }
  1949. static void send_http_error(struct mg_connection *,
  1950. int,
  1951. PRINTF_FORMAT_STRING(const char *fmt),
  1952. ...) PRINTF_ARGS(3, 4);
  1953. static void
  1954. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  1955. {
  1956. char buf[MG_BUF_LEN];
  1957. va_list ap;
  1958. int len, i, page_handler_found, scope, truncated;
  1959. char date[64];
  1960. time_t curtime = time(NULL);
  1961. const char *error_handler = NULL;
  1962. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1963. const char *error_page_file_ext, *tstr;
  1964. const char *status_text = mg_get_response_code_text(status, conn);
  1965. if (conn == NULL) {
  1966. return;
  1967. }
  1968. conn->status_code = status;
  1969. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  1970. || conn->ctx->callbacks.http_error(conn, status)) {
  1971. if (!conn->in_error_handler) {
  1972. /* Send user defined error pages, if defined */
  1973. error_handler = conn->ctx->config[ERROR_PAGES];
  1974. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1975. page_handler_found = 0;
  1976. if (error_handler != NULL) {
  1977. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  1978. switch (scope) {
  1979. case 1: /* Handler for specific error, e.g. 404 error */
  1980. mg_snprintf(conn,
  1981. &truncated,
  1982. buf,
  1983. sizeof(buf) - 32,
  1984. "%serror%03u.",
  1985. error_handler,
  1986. status);
  1987. break;
  1988. case 2: /* Handler for error group, e.g., 5xx error handler
  1989. * for all server errors (500-599) */
  1990. mg_snprintf(conn,
  1991. &truncated,
  1992. buf,
  1993. sizeof(buf) - 32,
  1994. "%serror%01uxx.",
  1995. error_handler,
  1996. status / 100);
  1997. break;
  1998. default: /* Handler for all errors */
  1999. mg_snprintf(conn,
  2000. &truncated,
  2001. buf,
  2002. sizeof(buf) - 32,
  2003. "%serror.",
  2004. error_handler);
  2005. break;
  2006. }
  2007. /* String truncation in buf may only occur if error_handler
  2008. * is too long. This string is from the config, not from a
  2009. * client. */
  2010. (void)truncated;
  2011. len = (int)strlen(buf);
  2012. tstr = strchr(error_page_file_ext, '.');
  2013. while (tstr) {
  2014. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2015. i++)
  2016. buf[len + i - 1] = tstr[i];
  2017. buf[len + i - 1] = 0;
  2018. if (mg_stat(conn, buf, &error_page_file)) {
  2019. page_handler_found = 1;
  2020. break;
  2021. }
  2022. tstr = strchr(tstr + i, '.');
  2023. }
  2024. }
  2025. }
  2026. if (page_handler_found) {
  2027. conn->in_error_handler = 1;
  2028. handle_file_based_request(conn, buf, &error_page_file);
  2029. conn->in_error_handler = 0;
  2030. return;
  2031. }
  2032. }
  2033. /* No custom error page. Send default error page. */
  2034. gmt_time_string(date, sizeof(date), &curtime);
  2035. conn->must_close = 1;
  2036. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2037. mg_printf(conn,
  2038. "Date: %s\r\n"
  2039. "Connection: close\r\n\r\n",
  2040. date);
  2041. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2042. if (status > 199 && status != 204 && status != 304) {
  2043. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2044. if (fmt != NULL) {
  2045. va_start(ap, fmt);
  2046. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2047. va_end(ap);
  2048. mg_write(conn, buf, strlen(buf));
  2049. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2050. }
  2051. } else {
  2052. /* No body allowed. Close the connection. */
  2053. DEBUG_TRACE("Error %i", status);
  2054. }
  2055. }
  2056. }
  2057. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2058. /* Create substitutes for POSIX functions in Win32. */
  2059. #if defined(__MINGW32__)
  2060. /* Show no warning in case system functions are not used. */
  2061. #pragma GCC diagnostic push
  2062. #pragma GCC diagnostic ignored "-Wunused-function"
  2063. #endif
  2064. static int
  2065. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2066. {
  2067. (void)unused;
  2068. *mutex = CreateMutex(NULL, FALSE, NULL);
  2069. return *mutex == NULL ? -1 : 0;
  2070. }
  2071. static int
  2072. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2073. {
  2074. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2075. }
  2076. static int
  2077. pthread_mutex_lock(pthread_mutex_t *mutex)
  2078. {
  2079. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2080. }
  2081. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2082. static int
  2083. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2084. {
  2085. switch (WaitForSingleObject(*mutex, 0)) {
  2086. case WAIT_OBJECT_0:
  2087. return 0;
  2088. case WAIT_TIMEOUT:
  2089. return -2; /* EBUSY */
  2090. }
  2091. return -1;
  2092. }
  2093. #endif
  2094. static int
  2095. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2096. {
  2097. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2098. }
  2099. #ifndef WIN_PTHREADS_TIME_H
  2100. static int
  2101. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2102. {
  2103. FILETIME ft;
  2104. ULARGE_INTEGER li;
  2105. BOOL ok = FALSE;
  2106. double d;
  2107. static double perfcnt_per_sec = 0.0;
  2108. if (tp) {
  2109. memset(tp, 0, sizeof(*tp));
  2110. if (clk_id == CLOCK_REALTIME) {
  2111. GetSystemTimeAsFileTime(&ft);
  2112. li.LowPart = ft.dwLowDateTime;
  2113. li.HighPart = ft.dwHighDateTime;
  2114. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2115. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2116. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2117. ok = TRUE;
  2118. } else if (clk_id == CLOCK_MONOTONIC) {
  2119. if (perfcnt_per_sec == 0.0) {
  2120. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2121. perfcnt_per_sec = 1.0 / li.QuadPart;
  2122. }
  2123. if (perfcnt_per_sec != 0.0) {
  2124. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2125. d = li.QuadPart * perfcnt_per_sec;
  2126. tp->tv_sec = (time_t)d;
  2127. d -= tp->tv_sec;
  2128. tp->tv_nsec = (long)(d * 1.0E9);
  2129. ok = TRUE;
  2130. }
  2131. }
  2132. }
  2133. return ok ? 0 : -1;
  2134. }
  2135. #endif
  2136. static int
  2137. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2138. {
  2139. (void)unused;
  2140. InitializeCriticalSection(&cv->threadIdSec);
  2141. cv->waitingthreadcount = 0;
  2142. cv->waitingthreadhdls =
  2143. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2144. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2145. }
  2146. static int
  2147. pthread_cond_timedwait(pthread_cond_t *cv,
  2148. pthread_mutex_t *mutex,
  2149. const struct timespec *abstime)
  2150. {
  2151. struct mg_workerTLS *tls =
  2152. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2153. int ok;
  2154. struct timespec tsnow;
  2155. int64_t nsnow, nswaitabs, nswaitrel;
  2156. DWORD mswaitrel;
  2157. EnterCriticalSection(&cv->threadIdSec);
  2158. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2159. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2160. tls->pthread_cond_helper_mutex;
  2161. cv->waitingthreadcount++;
  2162. LeaveCriticalSection(&cv->threadIdSec);
  2163. if (abstime) {
  2164. clock_gettime(CLOCK_REALTIME, &tsnow);
  2165. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2166. nswaitabs =
  2167. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2168. nswaitrel = nswaitabs - nsnow;
  2169. if (nswaitrel < 0) {
  2170. nswaitrel = 0;
  2171. }
  2172. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2173. } else {
  2174. mswaitrel = INFINITE;
  2175. }
  2176. pthread_mutex_unlock(mutex);
  2177. ok = (WAIT_OBJECT_0
  2178. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2179. pthread_mutex_lock(mutex);
  2180. return ok ? 0 : -1;
  2181. }
  2182. static int
  2183. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2184. {
  2185. return pthread_cond_timedwait(cv, mutex, NULL);
  2186. }
  2187. static int
  2188. pthread_cond_signal(pthread_cond_t *cv)
  2189. {
  2190. int i;
  2191. HANDLE wkup = NULL;
  2192. BOOL ok = FALSE;
  2193. EnterCriticalSection(&cv->threadIdSec);
  2194. if (cv->waitingthreadcount) {
  2195. wkup = cv->waitingthreadhdls[0];
  2196. ok = SetEvent(wkup);
  2197. for (i = 1; i < cv->waitingthreadcount; i++) {
  2198. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2199. }
  2200. cv->waitingthreadcount--;
  2201. assert(ok);
  2202. }
  2203. LeaveCriticalSection(&cv->threadIdSec);
  2204. return ok ? 0 : 1;
  2205. }
  2206. static int
  2207. pthread_cond_broadcast(pthread_cond_t *cv)
  2208. {
  2209. EnterCriticalSection(&cv->threadIdSec);
  2210. while (cv->waitingthreadcount) {
  2211. pthread_cond_signal(cv);
  2212. }
  2213. LeaveCriticalSection(&cv->threadIdSec);
  2214. return 0;
  2215. }
  2216. static int
  2217. pthread_cond_destroy(pthread_cond_t *cv)
  2218. {
  2219. EnterCriticalSection(&cv->threadIdSec);
  2220. assert(cv->waitingthreadcount == 0);
  2221. mg_free(cv->waitingthreadhdls);
  2222. cv->waitingthreadhdls = 0;
  2223. LeaveCriticalSection(&cv->threadIdSec);
  2224. DeleteCriticalSection(&cv->threadIdSec);
  2225. return 0;
  2226. }
  2227. #if defined(__MINGW32__)
  2228. /* Enable unused function warning again */
  2229. #pragma GCC diagnostic pop
  2230. #endif
  2231. /* For Windows, change all slashes to backslashes in path names. */
  2232. static void
  2233. change_slashes_to_backslashes(char *path)
  2234. {
  2235. int i;
  2236. for (i = 0; path[i] != '\0'; i++) {
  2237. if (path[i] == '/') {
  2238. path[i] = '\\';
  2239. }
  2240. /* remove double backslash (check i > 0 to preserve UNC paths,
  2241. * like \\server\file.txt) */
  2242. if ((path[i] == '\\') && (i > 0)) {
  2243. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2244. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2245. }
  2246. }
  2247. }
  2248. }
  2249. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2250. * wbuf and wbuf_len is a target buffer and its length. */
  2251. static void
  2252. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2253. {
  2254. char buf[PATH_MAX], buf2[PATH_MAX];
  2255. mg_strlcpy(buf, path, sizeof(buf));
  2256. change_slashes_to_backslashes(buf);
  2257. /* Convert to Unicode and back. If doubly-converted string does not
  2258. * match the original, something is fishy, reject. */
  2259. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2260. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2261. WideCharToMultiByte(
  2262. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2263. if (strcmp(buf, buf2) != 0) {
  2264. wbuf[0] = L'\0';
  2265. }
  2266. }
  2267. #if defined(_WIN32_WCE)
  2268. /* Create substitutes for POSIX functions in Win32. */
  2269. #if defined(__MINGW32__)
  2270. /* Show no warning in case system functions are not used. */
  2271. #pragma GCC diagnostic push
  2272. #pragma GCC diagnostic ignored "-Wunused-function"
  2273. #endif
  2274. static time_t
  2275. time(time_t *ptime)
  2276. {
  2277. time_t t;
  2278. SYSTEMTIME st;
  2279. FILETIME ft;
  2280. GetSystemTime(&st);
  2281. SystemTimeToFileTime(&st, &ft);
  2282. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2283. if (ptime != NULL) {
  2284. *ptime = t;
  2285. }
  2286. return t;
  2287. }
  2288. static struct tm *
  2289. localtime(const time_t *ptime, struct tm *ptm)
  2290. {
  2291. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2292. FILETIME ft, lft;
  2293. SYSTEMTIME st;
  2294. TIME_ZONE_INFORMATION tzinfo;
  2295. if (ptm == NULL) {
  2296. return NULL;
  2297. }
  2298. *(int64_t *)&ft = t;
  2299. FileTimeToLocalFileTime(&ft, &lft);
  2300. FileTimeToSystemTime(&lft, &st);
  2301. ptm->tm_year = st.wYear - 1900;
  2302. ptm->tm_mon = st.wMonth - 1;
  2303. ptm->tm_wday = st.wDayOfWeek;
  2304. ptm->tm_mday = st.wDay;
  2305. ptm->tm_hour = st.wHour;
  2306. ptm->tm_min = st.wMinute;
  2307. ptm->tm_sec = st.wSecond;
  2308. ptm->tm_yday = 0; /* hope nobody uses this */
  2309. ptm->tm_isdst =
  2310. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2311. return ptm;
  2312. }
  2313. static struct tm *
  2314. gmtime(const time_t *ptime, struct tm *ptm)
  2315. {
  2316. /* FIXME(lsm): fix this. */
  2317. return localtime(ptime, ptm);
  2318. }
  2319. static size_t
  2320. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2321. {
  2322. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2323. return 0;
  2324. }
  2325. #if defined(__MINGW32__)
  2326. /* Enable unused function warning again */
  2327. #pragma GCC diagnostic pop
  2328. #endif
  2329. #endif
  2330. /* Windows happily opens files with some garbage at the end of file name.
  2331. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2332. * "a.cgi", despite one would expect an error back.
  2333. * This function returns non-0 if path ends with some garbage. */
  2334. static int
  2335. path_cannot_disclose_cgi(const char *path)
  2336. {
  2337. static const char *allowed_last_characters = "_-";
  2338. int last = path[strlen(path) - 1];
  2339. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2340. }
  2341. static int
  2342. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2343. {
  2344. wchar_t wbuf[PATH_MAX];
  2345. WIN32_FILE_ATTRIBUTE_DATA info;
  2346. time_t creation_time;
  2347. if (!filep) {
  2348. return 0;
  2349. }
  2350. memset(filep, 0, sizeof(*filep));
  2351. if (conn && is_file_in_memory(conn, path, filep)) {
  2352. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2353. * memset */
  2354. filep->last_modified = time(NULL);
  2355. /* last_modified = now ... assumes the file may change during runtime,
  2356. * so every mg_fopen call may return different data */
  2357. /* last_modified = conn->ctx.start_time;
  2358. * May be used it the data does not change during runtime. This allows
  2359. * browser caching. Since we do not know, we have to assume the file
  2360. * in memory may change. */
  2361. return 1;
  2362. }
  2363. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2364. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2365. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2366. filep->last_modified =
  2367. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2368. info.ftLastWriteTime.dwHighDateTime);
  2369. /* On Windows, the file creation time can be higher than the
  2370. * modification time, e.g. when a file is copied.
  2371. * Since the Last-Modified timestamp is used for caching
  2372. * it should be based on the most recent timestamp. */
  2373. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2374. info.ftCreationTime.dwHighDateTime);
  2375. if (creation_time > filep->last_modified) {
  2376. filep->last_modified = creation_time;
  2377. }
  2378. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2379. /* If file name is fishy, reset the file structure and return
  2380. * error.
  2381. * Note it is important to reset, not just return the error, cause
  2382. * functions like is_file_opened() check the struct. */
  2383. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2384. memset(filep, 0, sizeof(*filep));
  2385. return 0;
  2386. }
  2387. return 1;
  2388. }
  2389. return 0;
  2390. }
  2391. #if !defined(NO_FILES)
  2392. static int
  2393. mg_remove(const char *path)
  2394. {
  2395. wchar_t wbuf[PATH_MAX];
  2396. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2397. return DeleteFileW(wbuf) ? 0 : -1;
  2398. }
  2399. static int
  2400. mg_mkdir(const char *path, int mode)
  2401. {
  2402. char buf[PATH_MAX];
  2403. wchar_t wbuf[PATH_MAX];
  2404. (void)mode;
  2405. mg_strlcpy(buf, path, sizeof(buf));
  2406. change_slashes_to_backslashes(buf);
  2407. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2408. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2409. }
  2410. #endif
  2411. /* Create substitutes for POSIX functions in Win32. */
  2412. #if defined(__MINGW32__)
  2413. /* Show no warning in case system functions are not used. */
  2414. #pragma GCC diagnostic push
  2415. #pragma GCC diagnostic ignored "-Wunused-function"
  2416. #endif
  2417. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2418. static DIR *
  2419. opendir(const char *name)
  2420. {
  2421. DIR *dir = NULL;
  2422. wchar_t wpath[PATH_MAX];
  2423. DWORD attrs;
  2424. if (name == NULL) {
  2425. SetLastError(ERROR_BAD_ARGUMENTS);
  2426. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2427. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2428. } else {
  2429. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2430. attrs = GetFileAttributesW(wpath);
  2431. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2432. == FILE_ATTRIBUTE_DIRECTORY)) {
  2433. (void)wcscat(wpath, L"\\*");
  2434. dir->handle = FindFirstFileW(wpath, &dir->info);
  2435. dir->result.d_name[0] = '\0';
  2436. } else {
  2437. mg_free(dir);
  2438. dir = NULL;
  2439. }
  2440. }
  2441. return dir;
  2442. }
  2443. static int
  2444. closedir(DIR *dir)
  2445. {
  2446. int result = 0;
  2447. if (dir != NULL) {
  2448. if (dir->handle != INVALID_HANDLE_VALUE)
  2449. result = FindClose(dir->handle) ? 0 : -1;
  2450. mg_free(dir);
  2451. } else {
  2452. result = -1;
  2453. SetLastError(ERROR_BAD_ARGUMENTS);
  2454. }
  2455. return result;
  2456. }
  2457. static struct dirent *
  2458. readdir(DIR *dir)
  2459. {
  2460. struct dirent *result = 0;
  2461. if (dir) {
  2462. if (dir->handle != INVALID_HANDLE_VALUE) {
  2463. result = &dir->result;
  2464. (void)WideCharToMultiByte(CP_UTF8,
  2465. 0,
  2466. dir->info.cFileName,
  2467. -1,
  2468. result->d_name,
  2469. sizeof(result->d_name),
  2470. NULL,
  2471. NULL);
  2472. if (!FindNextFileW(dir->handle, &dir->info)) {
  2473. (void)FindClose(dir->handle);
  2474. dir->handle = INVALID_HANDLE_VALUE;
  2475. }
  2476. } else {
  2477. SetLastError(ERROR_FILE_NOT_FOUND);
  2478. }
  2479. } else {
  2480. SetLastError(ERROR_BAD_ARGUMENTS);
  2481. }
  2482. return result;
  2483. }
  2484. #ifndef HAVE_POLL
  2485. static int
  2486. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2487. {
  2488. struct timeval tv;
  2489. fd_set set;
  2490. unsigned int i;
  2491. int result;
  2492. SOCKET maxfd = 0;
  2493. memset(&tv, 0, sizeof(tv));
  2494. tv.tv_sec = milliseconds / 1000;
  2495. tv.tv_usec = (milliseconds % 1000) * 1000;
  2496. FD_ZERO(&set);
  2497. for (i = 0; i < n; i++) {
  2498. FD_SET((SOCKET)pfd[i].fd, &set);
  2499. pfd[i].revents = 0;
  2500. if (pfd[i].fd > maxfd) {
  2501. maxfd = pfd[i].fd;
  2502. }
  2503. }
  2504. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2505. for (i = 0; i < n; i++) {
  2506. if (FD_ISSET(pfd[i].fd, &set)) {
  2507. pfd[i].revents = POLLIN;
  2508. }
  2509. }
  2510. }
  2511. return result;
  2512. }
  2513. #endif /* HAVE_POLL */
  2514. #if defined(__MINGW32__)
  2515. /* Enable unused function warning again */
  2516. #pragma GCC diagnostic pop
  2517. #endif
  2518. static void
  2519. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2520. {
  2521. (void)conn; /* Unused. */
  2522. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2523. }
  2524. int
  2525. mg_start_thread(mg_thread_func_t f, void *p)
  2526. {
  2527. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2528. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2529. */
  2530. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2531. == ((uintptr_t)(-1L)))
  2532. ? -1
  2533. : 0);
  2534. #else
  2535. return (
  2536. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2537. ? -1
  2538. : 0);
  2539. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2540. }
  2541. /* Start a thread storing the thread context. */
  2542. static int
  2543. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2544. void *p,
  2545. pthread_t *threadidptr)
  2546. {
  2547. uintptr_t uip;
  2548. HANDLE threadhandle;
  2549. int result = -1;
  2550. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2551. threadhandle = (HANDLE)uip;
  2552. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2553. *threadidptr = threadhandle;
  2554. result = 0;
  2555. }
  2556. return result;
  2557. }
  2558. /* Wait for a thread to finish. */
  2559. static int
  2560. mg_join_thread(pthread_t threadid)
  2561. {
  2562. int result;
  2563. DWORD dwevent;
  2564. result = -1;
  2565. dwevent = WaitForSingleObject(threadid, INFINITE);
  2566. if (dwevent == WAIT_FAILED) {
  2567. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2568. } else {
  2569. if (dwevent == WAIT_OBJECT_0) {
  2570. CloseHandle(threadid);
  2571. result = 0;
  2572. }
  2573. }
  2574. return result;
  2575. }
  2576. #if !defined(NO_SSL_DL)
  2577. /* Create substitutes for POSIX functions in Win32. */
  2578. #if defined(__MINGW32__)
  2579. /* Show no warning in case system functions are not used. */
  2580. #pragma GCC diagnostic push
  2581. #pragma GCC diagnostic ignored "-Wunused-function"
  2582. #endif
  2583. static HANDLE
  2584. dlopen(const char *dll_name, int flags)
  2585. {
  2586. wchar_t wbuf[PATH_MAX];
  2587. (void)flags;
  2588. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2589. return LoadLibraryW(wbuf);
  2590. }
  2591. static int
  2592. dlclose(void *handle)
  2593. {
  2594. int result;
  2595. if (FreeLibrary((HMODULE)handle) != 0) {
  2596. result = 0;
  2597. } else {
  2598. result = -1;
  2599. }
  2600. return result;
  2601. }
  2602. #if defined(__MINGW32__)
  2603. /* Enable unused function warning again */
  2604. #pragma GCC diagnostic pop
  2605. #endif
  2606. #endif
  2607. #if !defined(NO_CGI)
  2608. #define SIGKILL (0)
  2609. static int
  2610. kill(pid_t pid, int sig_num)
  2611. {
  2612. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2613. (void)CloseHandle((HANDLE)pid);
  2614. return 0;
  2615. }
  2616. static void
  2617. trim_trailing_whitespaces(char *s)
  2618. {
  2619. char *e = s + strlen(s) - 1;
  2620. while (e > s && isspace(*(unsigned char *)e)) {
  2621. *e-- = '\0';
  2622. }
  2623. }
  2624. static pid_t
  2625. spawn_process(struct mg_connection *conn,
  2626. const char *prog,
  2627. char *envblk,
  2628. char *envp[],
  2629. int fdin,
  2630. int fdout,
  2631. int fderr,
  2632. const char *dir)
  2633. {
  2634. HANDLE me;
  2635. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2636. cmdline[PATH_MAX], buf[PATH_MAX];
  2637. int truncated;
  2638. struct file file = STRUCT_FILE_INITIALIZER;
  2639. STARTUPINFOA si;
  2640. PROCESS_INFORMATION pi = {0};
  2641. (void)envp;
  2642. memset(&si, 0, sizeof(si));
  2643. si.cb = sizeof(si);
  2644. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2645. si.wShowWindow = SW_HIDE;
  2646. me = GetCurrentProcess();
  2647. DuplicateHandle(me,
  2648. (HANDLE)_get_osfhandle(fdin),
  2649. me,
  2650. &si.hStdInput,
  2651. 0,
  2652. TRUE,
  2653. DUPLICATE_SAME_ACCESS);
  2654. DuplicateHandle(me,
  2655. (HANDLE)_get_osfhandle(fdout),
  2656. me,
  2657. &si.hStdOutput,
  2658. 0,
  2659. TRUE,
  2660. DUPLICATE_SAME_ACCESS);
  2661. DuplicateHandle(me,
  2662. (HANDLE)_get_osfhandle(fderr),
  2663. me,
  2664. &si.hStdError,
  2665. 0,
  2666. TRUE,
  2667. DUPLICATE_SAME_ACCESS);
  2668. /* If CGI file is a script, try to read the interpreter line */
  2669. interp = conn->ctx->config[CGI_INTERPRETER];
  2670. if (interp == NULL) {
  2671. buf[0] = buf[1] = '\0';
  2672. /* Read the first line of the script into the buffer */
  2673. mg_snprintf(
  2674. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2675. if (truncated) {
  2676. pi.hProcess = (pid_t)-1;
  2677. goto spawn_cleanup;
  2678. }
  2679. if (mg_fopen(conn, cmdline, "r", &file)) {
  2680. p = (char *)file.membuf;
  2681. mg_fgets(buf, sizeof(buf), &file, &p);
  2682. mg_fclose(&file);
  2683. buf[sizeof(buf) - 1] = '\0';
  2684. }
  2685. if (buf[0] == '#' && buf[1] == '!') {
  2686. trim_trailing_whitespaces(buf + 2);
  2687. } else {
  2688. buf[2] = '\0';
  2689. }
  2690. interp = buf + 2;
  2691. }
  2692. if (interp[0] != '\0') {
  2693. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2694. interp = full_interp;
  2695. }
  2696. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2697. if (interp[0] != '\0') {
  2698. mg_snprintf(conn,
  2699. &truncated,
  2700. cmdline,
  2701. sizeof(cmdline),
  2702. "\"%s\" \"%s\\%s\"",
  2703. interp,
  2704. full_dir,
  2705. prog);
  2706. } else {
  2707. mg_snprintf(conn,
  2708. &truncated,
  2709. cmdline,
  2710. sizeof(cmdline),
  2711. "\"%s\\%s\"",
  2712. full_dir,
  2713. prog);
  2714. }
  2715. if (truncated) {
  2716. pi.hProcess = (pid_t)-1;
  2717. goto spawn_cleanup;
  2718. }
  2719. DEBUG_TRACE("Running [%s]", cmdline);
  2720. if (CreateProcessA(NULL,
  2721. cmdline,
  2722. NULL,
  2723. NULL,
  2724. TRUE,
  2725. CREATE_NEW_PROCESS_GROUP,
  2726. envblk,
  2727. NULL,
  2728. &si,
  2729. &pi) == 0) {
  2730. mg_cry(
  2731. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2732. pi.hProcess = (pid_t)-1;
  2733. /* goto spawn_cleanup; */
  2734. }
  2735. spawn_cleanup:
  2736. (void)CloseHandle(si.hStdOutput);
  2737. (void)CloseHandle(si.hStdError);
  2738. (void)CloseHandle(si.hStdInput);
  2739. if (pi.hThread != NULL) {
  2740. (void)CloseHandle(pi.hThread);
  2741. }
  2742. return (pid_t)pi.hProcess;
  2743. }
  2744. #endif /* !NO_CGI */
  2745. static int
  2746. set_non_blocking_mode(SOCKET sock)
  2747. {
  2748. unsigned long on = 1;
  2749. return ioctlsocket(sock, (long)FIONBIO, &on);
  2750. }
  2751. #else
  2752. static int
  2753. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2754. {
  2755. struct stat st;
  2756. if (!filep) {
  2757. return 0;
  2758. }
  2759. memset(filep, 0, sizeof(*filep));
  2760. if (conn && is_file_in_memory(conn, path, filep)) {
  2761. return 1;
  2762. }
  2763. if (0 == stat(path, &st)) {
  2764. filep->size = (uint64_t)(st.st_size);
  2765. filep->last_modified = st.st_mtime;
  2766. filep->is_directory = S_ISDIR(st.st_mode);
  2767. return 1;
  2768. }
  2769. return 0;
  2770. }
  2771. static void
  2772. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2773. {
  2774. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2775. if (conn) {
  2776. mg_cry(conn,
  2777. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2778. __func__,
  2779. strerror(ERRNO));
  2780. }
  2781. }
  2782. }
  2783. int
  2784. mg_start_thread(mg_thread_func_t func, void *param)
  2785. {
  2786. pthread_t thread_id;
  2787. pthread_attr_t attr;
  2788. int result;
  2789. (void)pthread_attr_init(&attr);
  2790. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2791. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2792. /* Compile-time option to control stack size,
  2793. * e.g. -DUSE_STACK_SIZE=16384 */
  2794. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2795. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2796. result = pthread_create(&thread_id, &attr, func, param);
  2797. pthread_attr_destroy(&attr);
  2798. return result;
  2799. }
  2800. /* Start a thread storing the thread context. */
  2801. static int
  2802. mg_start_thread_with_id(mg_thread_func_t func,
  2803. void *param,
  2804. pthread_t *threadidptr)
  2805. {
  2806. pthread_t thread_id;
  2807. pthread_attr_t attr;
  2808. int result;
  2809. (void)pthread_attr_init(&attr);
  2810. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2811. /* Compile-time option to control stack size,
  2812. * e.g. -DUSE_STACK_SIZE=16384 */
  2813. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2814. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2815. result = pthread_create(&thread_id, &attr, func, param);
  2816. pthread_attr_destroy(&attr);
  2817. if ((result == 0) && (threadidptr != NULL)) {
  2818. *threadidptr = thread_id;
  2819. }
  2820. return result;
  2821. }
  2822. /* Wait for a thread to finish. */
  2823. static int
  2824. mg_join_thread(pthread_t threadid)
  2825. {
  2826. int result;
  2827. result = pthread_join(threadid, NULL);
  2828. return result;
  2829. }
  2830. #ifndef NO_CGI
  2831. static pid_t
  2832. spawn_process(struct mg_connection *conn,
  2833. const char *prog,
  2834. char *envblk,
  2835. char *envp[],
  2836. int fdin,
  2837. int fdout,
  2838. int fderr,
  2839. const char *dir)
  2840. {
  2841. pid_t pid;
  2842. const char *interp;
  2843. (void)envblk;
  2844. if (conn == NULL) {
  2845. return 0;
  2846. }
  2847. if ((pid = fork()) == -1) {
  2848. /* Parent */
  2849. send_http_error(conn,
  2850. 500,
  2851. "Error: Creating CGI process\nfork(): %s",
  2852. strerror(ERRNO));
  2853. } else if (pid == 0) {
  2854. /* Child */
  2855. if (chdir(dir) != 0) {
  2856. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2857. } else if (dup2(fdin, 0) == -1) {
  2858. mg_cry(
  2859. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2860. } else if (dup2(fdout, 1) == -1) {
  2861. mg_cry(
  2862. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2863. } else if (dup2(fderr, 2) == -1) {
  2864. mg_cry(
  2865. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  2866. } else {
  2867. /* Keep stderr and stdout in two different pipes.
  2868. * Stdout will be sent back to the client,
  2869. * stderr should go into a server error log. */
  2870. (void)close(fdin);
  2871. (void)close(fdout);
  2872. (void)close(fderr);
  2873. /* After exec, all signal handlers are restored to their default
  2874. * values, with one exception of SIGCHLD. According to
  2875. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2876. * leave unchanged after exec if it was set to be ignored. Restore
  2877. * it to default action. */
  2878. signal(SIGCHLD, SIG_DFL);
  2879. interp = conn->ctx->config[CGI_INTERPRETER];
  2880. if (interp == NULL) {
  2881. (void)execle(prog, prog, NULL, envp);
  2882. mg_cry(conn,
  2883. "%s: execle(%s): %s",
  2884. __func__,
  2885. prog,
  2886. strerror(ERRNO));
  2887. } else {
  2888. (void)execle(interp, interp, prog, NULL, envp);
  2889. mg_cry(conn,
  2890. "%s: execle(%s %s): %s",
  2891. __func__,
  2892. interp,
  2893. prog,
  2894. strerror(ERRNO));
  2895. }
  2896. }
  2897. exit(EXIT_FAILURE);
  2898. }
  2899. return pid;
  2900. }
  2901. #endif /* !NO_CGI */
  2902. static int
  2903. set_non_blocking_mode(SOCKET sock)
  2904. {
  2905. int flags;
  2906. flags = fcntl(sock, F_GETFL, 0);
  2907. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2908. return 0;
  2909. }
  2910. #endif /* _WIN32 */
  2911. /* End of initial operating system specific define block. */
  2912. /* Get a random number (independent of C rand function) */
  2913. static uint64_t
  2914. get_random(void)
  2915. {
  2916. static uint64_t lfsr = 0; /* Linear feedback shift register */
  2917. static uint64_t lcg = 0; /* Linear congruential generator */
  2918. struct timespec now;
  2919. memset(&now, 0, sizeof(now));
  2920. clock_gettime(CLOCK_MONOTONIC, &now);
  2921. if (lfsr == 0) {
  2922. /* lfsr will be only 0 if has not been initialized,
  2923. * so this code is called only once. */
  2924. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  2925. ^ ((uint64_t)(ptrdiff_t)&now) ^ ((uint64_t)pthread_self())
  2926. ^ (((uint64_t)time(NULL)) << 33);
  2927. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  2928. + (uint64_t)(ptrdiff_t)&now;
  2929. } else {
  2930. /* Get the next step of both random number generators. */
  2931. lfsr = (lfsr >> 1)
  2932. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  2933. << 63);
  2934. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  2935. }
  2936. /* Combining two pseudo-random number generators and a high resolution part
  2937. * of the current server time will make it hard (impossible?) to guess the
  2938. * next number. */
  2939. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  2940. }
  2941. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2942. * descriptor. Return number of bytes written. */
  2943. static int
  2944. push(struct mg_context *ctx,
  2945. FILE *fp,
  2946. SOCKET sock,
  2947. SSL *ssl,
  2948. const char *buf,
  2949. int len,
  2950. double timeout)
  2951. {
  2952. struct timespec start, now;
  2953. int n, err;
  2954. #ifdef _WIN32
  2955. typedef int len_t;
  2956. #else
  2957. typedef size_t len_t;
  2958. #endif
  2959. if (timeout > 0) {
  2960. memset(&start, 0, sizeof(start));
  2961. memset(&now, 0, sizeof(now));
  2962. clock_gettime(CLOCK_MONOTONIC, &start);
  2963. }
  2964. if (ctx == NULL) {
  2965. return -1;
  2966. }
  2967. #ifdef NO_SSL
  2968. if (ssl) {
  2969. return -1;
  2970. }
  2971. #endif
  2972. do {
  2973. #ifndef NO_SSL
  2974. if (ssl != NULL) {
  2975. n = SSL_write(ssl, buf, len);
  2976. if (n <= 0) {
  2977. err = SSL_get_error(ssl, n);
  2978. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  2979. err = ERRNO;
  2980. } else {
  2981. DEBUG_TRACE("SSL_write() failed, error %d", err);
  2982. return -1;
  2983. }
  2984. } else {
  2985. err = 0;
  2986. }
  2987. } else
  2988. #endif
  2989. if (fp != NULL) {
  2990. n = (int)fwrite(buf, 1, (size_t)len, fp);
  2991. if (ferror(fp)) {
  2992. n = -1;
  2993. err = ERRNO;
  2994. } else {
  2995. err = 0;
  2996. }
  2997. } else {
  2998. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  2999. err = (n < 0) ? ERRNO : 0;
  3000. }
  3001. if (ctx->stop_flag) {
  3002. return -1;
  3003. }
  3004. if ((n > 0) || (n == 0 && len == 0)) {
  3005. /* some data has been read, or no data was requested */
  3006. return n;
  3007. }
  3008. if (n == 0) {
  3009. /* shutdown of the socket at client side */
  3010. return -1;
  3011. }
  3012. if (n < 0) {
  3013. /* socket error - check errno */
  3014. DEBUG_TRACE("send() failed, error %d", err);
  3015. /* TODO: error handling depending on the error code.
  3016. * These codes are different between Windows and Linux.
  3017. */
  3018. return -1;
  3019. }
  3020. if (timeout > 0) {
  3021. clock_gettime(CLOCK_MONOTONIC, &now);
  3022. }
  3023. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3024. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3025. used */
  3026. return -1;
  3027. }
  3028. static int64_t
  3029. push_all(struct mg_context *ctx,
  3030. FILE *fp,
  3031. SOCKET sock,
  3032. SSL *ssl,
  3033. const char *buf,
  3034. int64_t len)
  3035. {
  3036. double timeout = -1.0;
  3037. int64_t n, nwritten = 0;
  3038. if (ctx == NULL) {
  3039. return -1;
  3040. }
  3041. if (ctx->config[REQUEST_TIMEOUT]) {
  3042. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3043. }
  3044. while (len > 0 && ctx->stop_flag == 0) {
  3045. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3046. if (n < 0) {
  3047. if (nwritten == 0) {
  3048. nwritten = n; /* Propagate the error */
  3049. }
  3050. break;
  3051. } else if (n == 0) {
  3052. break; /* No more data to write */
  3053. } else {
  3054. nwritten += n;
  3055. len -= n;
  3056. }
  3057. }
  3058. return nwritten;
  3059. }
  3060. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3061. * Return negative value on error, or number of bytes read on success. */
  3062. static int
  3063. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3064. {
  3065. int nread, err;
  3066. struct timespec start, now;
  3067. #ifdef _WIN32
  3068. typedef int len_t;
  3069. #else
  3070. typedef size_t len_t;
  3071. #endif
  3072. if (timeout > 0) {
  3073. memset(&start, 0, sizeof(start));
  3074. memset(&now, 0, sizeof(now));
  3075. clock_gettime(CLOCK_MONOTONIC, &start);
  3076. }
  3077. do {
  3078. if (fp != NULL) {
  3079. /* Use read() instead of fread(), because if we're reading from the
  3080. * CGI pipe, fread() may block until IO buffer is filled up. We
  3081. * cannot afford to block and must pass all read bytes immediately
  3082. * to the client. */
  3083. nread = (int)read(fileno(fp), buf, (size_t)len);
  3084. err = (nread < 0) ? ERRNO : 0;
  3085. #ifndef NO_SSL
  3086. } else if (conn->ssl != NULL) {
  3087. nread = SSL_read(conn->ssl, buf, len);
  3088. if (nread <= 0) {
  3089. err = SSL_get_error(conn->ssl, nread);
  3090. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3091. err = ERRNO;
  3092. } else {
  3093. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3094. return -1;
  3095. }
  3096. } else {
  3097. err = 0;
  3098. }
  3099. #endif
  3100. } else {
  3101. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3102. err = (nread < 0) ? ERRNO : 0;
  3103. }
  3104. if (conn->ctx->stop_flag) {
  3105. return -1;
  3106. }
  3107. if ((nread > 0) || (nread == 0 && len == 0)) {
  3108. /* some data has been read, or no data was requested */
  3109. return nread;
  3110. }
  3111. if (nread == 0) {
  3112. /* shutdown of the socket at client side */
  3113. return -1;
  3114. }
  3115. if (nread < 0) {
  3116. /* socket error - check errno */
  3117. #ifdef _WIN32
  3118. if (err == WSAEWOULDBLOCK) {
  3119. /* standard case if called from close_socket_gracefully */
  3120. return -1;
  3121. } else if (err == WSAETIMEDOUT) {
  3122. /* timeout is handled by the while loop */
  3123. } else {
  3124. DEBUG_TRACE("recv() failed, error %d", err);
  3125. return -1;
  3126. }
  3127. #else
  3128. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3129. * if the timeout is reached and if the socket was set to non-
  3130. * blocking in close_socket_gracefully, so we can not distinguish
  3131. * here. We have to wait for the timeout in both cases for now.
  3132. */
  3133. if (err == EAGAIN || err == EWOULDBLOCK) {
  3134. /* standard case if called from close_socket_gracefully
  3135. * => should return -1 */
  3136. /* or timeout occured
  3137. * => the code must stay in the while loop */
  3138. } else {
  3139. DEBUG_TRACE("recv() failed, error %d", err);
  3140. return -1;
  3141. }
  3142. #endif
  3143. }
  3144. if (timeout > 0) {
  3145. clock_gettime(CLOCK_MONOTONIC, &now);
  3146. }
  3147. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3148. /* Timeout occured, but no data available. */
  3149. return -1;
  3150. }
  3151. static int
  3152. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3153. {
  3154. int n, nread = 0;
  3155. double timeout = -1.0;
  3156. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3157. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3158. }
  3159. while (len > 0 && conn->ctx->stop_flag == 0) {
  3160. n = pull(fp, conn, buf + nread, len, timeout);
  3161. if (n < 0) {
  3162. if (nread == 0) {
  3163. nread = n; /* Propagate the error */
  3164. }
  3165. break;
  3166. } else if (n == 0) {
  3167. break; /* No more data to read */
  3168. } else {
  3169. conn->consumed_content += n;
  3170. nread += n;
  3171. len -= n;
  3172. }
  3173. }
  3174. return nread;
  3175. }
  3176. static void
  3177. discard_unread_request_data(struct mg_connection *conn)
  3178. {
  3179. char buf[MG_BUF_LEN];
  3180. size_t to_read;
  3181. int nread;
  3182. if (conn == NULL) {
  3183. return;
  3184. }
  3185. to_read = sizeof(buf);
  3186. if (conn->is_chunked) {
  3187. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3188. * completely */
  3189. while (conn->is_chunked == 1) {
  3190. nread = mg_read(conn, buf, to_read);
  3191. if (nread <= 0) {
  3192. break;
  3193. }
  3194. }
  3195. } else {
  3196. /* Not chunked: content length is known */
  3197. while (conn->consumed_content < conn->content_len) {
  3198. if (to_read
  3199. > (size_t)(conn->content_len - conn->consumed_content)) {
  3200. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3201. }
  3202. nread = mg_read(conn, buf, to_read);
  3203. if (nread <= 0) {
  3204. break;
  3205. }
  3206. }
  3207. }
  3208. }
  3209. static int
  3210. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3211. {
  3212. int64_t n, buffered_len, nread;
  3213. int64_t len64 =
  3214. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3215. * int, we may not read more
  3216. * bytes */
  3217. const char *body;
  3218. if (conn == NULL) {
  3219. return 0;
  3220. }
  3221. /* If Content-Length is not set for a PUT or POST request, read until
  3222. * socket is closed */
  3223. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3224. conn->content_len = INT64_MAX;
  3225. conn->must_close = 1;
  3226. }
  3227. nread = 0;
  3228. if (conn->consumed_content < conn->content_len) {
  3229. /* Adjust number of bytes to read. */
  3230. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3231. if (left_to_read < len64) {
  3232. /* Do not read more than the total content length of the request.
  3233. */
  3234. len64 = left_to_read;
  3235. }
  3236. /* Return buffered data */
  3237. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3238. - conn->consumed_content;
  3239. if (buffered_len > 0) {
  3240. if (len64 < buffered_len) {
  3241. buffered_len = len64;
  3242. }
  3243. body = conn->buf + conn->request_len + conn->consumed_content;
  3244. memcpy(buf, body, (size_t)buffered_len);
  3245. len64 -= buffered_len;
  3246. conn->consumed_content += buffered_len;
  3247. nread += buffered_len;
  3248. buf = (char *)buf + buffered_len;
  3249. }
  3250. /* We have returned all buffered data. Read new data from the remote
  3251. * socket.
  3252. */
  3253. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3254. nread += n;
  3255. } else {
  3256. nread = (nread > 0 ? nread : n);
  3257. }
  3258. }
  3259. return (int)nread;
  3260. }
  3261. static char
  3262. mg_getc(struct mg_connection *conn)
  3263. {
  3264. char c;
  3265. if (conn == NULL) {
  3266. return 0;
  3267. }
  3268. conn->content_len++;
  3269. if (mg_read_inner(conn, &c, 1) <= 0) {
  3270. return (char)0;
  3271. }
  3272. return c;
  3273. }
  3274. int
  3275. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3276. {
  3277. if (len > INT_MAX) {
  3278. len = INT_MAX;
  3279. }
  3280. if (conn == NULL) {
  3281. return 0;
  3282. }
  3283. if (conn->is_chunked) {
  3284. size_t all_read = 0;
  3285. while (len > 0) {
  3286. if (conn->chunk_remainder) {
  3287. /* copy from the remainder of the last received chunk */
  3288. long read_ret;
  3289. size_t read_now =
  3290. ((conn->chunk_remainder > len) ? (len)
  3291. : (conn->chunk_remainder));
  3292. conn->content_len += (int)read_now;
  3293. read_ret =
  3294. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3295. all_read += (size_t)read_ret;
  3296. conn->chunk_remainder -= read_now;
  3297. len -= read_now;
  3298. if (conn->chunk_remainder == 0) {
  3299. /* the rest of the data in the current chunk has been read
  3300. */
  3301. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3302. /* Protocol violation */
  3303. return -1;
  3304. }
  3305. }
  3306. } else {
  3307. /* fetch a new chunk */
  3308. int i = 0;
  3309. char lenbuf[64];
  3310. char *end = 0;
  3311. unsigned long chunkSize = 0;
  3312. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3313. lenbuf[i] = mg_getc(conn);
  3314. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3315. continue;
  3316. }
  3317. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3318. lenbuf[i + 1] = 0;
  3319. chunkSize = strtoul(lenbuf, &end, 16);
  3320. break;
  3321. }
  3322. if (!isalnum(lenbuf[i])) {
  3323. /* illegal character for chunk length */
  3324. return -1;
  3325. }
  3326. }
  3327. if ((end == NULL) || (*end != '\r')) {
  3328. /* chunksize not set correctly */
  3329. return -1;
  3330. }
  3331. conn->chunk_remainder = chunkSize;
  3332. if (chunkSize == 0) {
  3333. /* regular end of content */
  3334. conn->is_chunked = 2;
  3335. break;
  3336. }
  3337. }
  3338. }
  3339. return (int)all_read;
  3340. }
  3341. return mg_read_inner(conn, buf, len);
  3342. }
  3343. int
  3344. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3345. {
  3346. time_t now;
  3347. int64_t n, total, allowed;
  3348. if (conn == NULL) {
  3349. return 0;
  3350. }
  3351. if (conn->throttle > 0) {
  3352. if ((now = time(NULL)) != conn->last_throttle_time) {
  3353. conn->last_throttle_time = now;
  3354. conn->last_throttle_bytes = 0;
  3355. }
  3356. allowed = conn->throttle - conn->last_throttle_bytes;
  3357. if (allowed > (int64_t)len) {
  3358. allowed = (int64_t)len;
  3359. }
  3360. if ((total = push_all(conn->ctx,
  3361. NULL,
  3362. conn->client.sock,
  3363. conn->ssl,
  3364. (const char *)buf,
  3365. (int64_t)allowed)) == allowed) {
  3366. buf = (char *)buf + total;
  3367. conn->last_throttle_bytes += total;
  3368. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3369. allowed = conn->throttle > (int64_t)len - total
  3370. ? (int64_t)len - total
  3371. : conn->throttle;
  3372. if ((n = push_all(conn->ctx,
  3373. NULL,
  3374. conn->client.sock,
  3375. conn->ssl,
  3376. (const char *)buf,
  3377. (int64_t)allowed)) != allowed) {
  3378. break;
  3379. }
  3380. sleep(1);
  3381. conn->last_throttle_bytes = allowed;
  3382. conn->last_throttle_time = time(NULL);
  3383. buf = (char *)buf + n;
  3384. total += n;
  3385. }
  3386. }
  3387. } else {
  3388. total = push_all(conn->ctx,
  3389. NULL,
  3390. conn->client.sock,
  3391. conn->ssl,
  3392. (const char *)buf,
  3393. (int64_t)len);
  3394. }
  3395. return (int)total;
  3396. }
  3397. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3398. static int
  3399. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3400. {
  3401. va_list ap_copy;
  3402. size_t size = MG_BUF_LEN;
  3403. int len = -1;
  3404. *buf = NULL;
  3405. while (len < 0) {
  3406. if (*buf) {
  3407. mg_free(*buf);
  3408. }
  3409. *buf = (char *)mg_malloc(size *= 4);
  3410. if (!*buf) {
  3411. break;
  3412. }
  3413. va_copy(ap_copy, ap);
  3414. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3415. va_end(ap_copy);
  3416. *buf[size - 1] = 0;
  3417. }
  3418. return len;
  3419. }
  3420. /* Print message to buffer. If buffer is large enough to hold the message,
  3421. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3422. * and return allocated buffer. */
  3423. static int
  3424. alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  3425. {
  3426. va_list ap_copy;
  3427. int len;
  3428. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3429. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3430. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3431. * Therefore, we make two passes: on first pass, get required message
  3432. * length.
  3433. * On second pass, actually print the message. */
  3434. va_copy(ap_copy, ap);
  3435. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3436. va_end(ap_copy);
  3437. if (len < 0) {
  3438. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3439. * Switch to alternative code path that uses incremental allocations.
  3440. */
  3441. va_copy(ap_copy, ap);
  3442. len = alloc_vprintf2(buf, fmt, ap);
  3443. va_end(ap_copy);
  3444. } else if ((size_t)(len) > size && (size = (size_t)(len) + 1) > 0
  3445. && (*buf = (char *)mg_malloc(size)) == NULL) {
  3446. len = -1; /* Allocation failed, mark failure */
  3447. } else {
  3448. va_copy(ap_copy, ap);
  3449. IGNORE_UNUSED_RESULT(vsnprintf_impl(*buf, size, fmt, ap_copy));
  3450. va_end(ap_copy);
  3451. }
  3452. return len;
  3453. }
  3454. static int
  3455. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3456. {
  3457. char mem[MG_BUF_LEN], *buf = mem;
  3458. int len;
  3459. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  3460. len = mg_write(conn, buf, (size_t)len);
  3461. }
  3462. if (buf != mem && buf != NULL) {
  3463. mg_free(buf);
  3464. }
  3465. return len;
  3466. }
  3467. int
  3468. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3469. {
  3470. va_list ap;
  3471. int result;
  3472. va_start(ap, fmt);
  3473. result = mg_vprintf(conn, fmt, ap);
  3474. va_end(ap);
  3475. return result;
  3476. }
  3477. int
  3478. mg_url_decode(const char *src,
  3479. int src_len,
  3480. char *dst,
  3481. int dst_len,
  3482. int is_form_url_encoded)
  3483. {
  3484. int i, j, a, b;
  3485. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3486. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3487. if (i < src_len - 2 && src[i] == '%'
  3488. && isxdigit(*(const unsigned char *)(src + i + 1))
  3489. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3490. a = tolower(*(const unsigned char *)(src + i + 1));
  3491. b = tolower(*(const unsigned char *)(src + i + 2));
  3492. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3493. i += 2;
  3494. } else if (is_form_url_encoded && src[i] == '+') {
  3495. dst[j] = ' ';
  3496. } else {
  3497. dst[j] = src[i];
  3498. }
  3499. }
  3500. dst[j] = '\0'; /* Null-terminate the destination */
  3501. return i >= src_len ? j : -1;
  3502. }
  3503. int
  3504. mg_get_var(const char *data,
  3505. size_t data_len,
  3506. const char *name,
  3507. char *dst,
  3508. size_t dst_len)
  3509. {
  3510. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3511. }
  3512. int
  3513. mg_get_var2(const char *data,
  3514. size_t data_len,
  3515. const char *name,
  3516. char *dst,
  3517. size_t dst_len,
  3518. size_t occurrence)
  3519. {
  3520. const char *p, *e, *s;
  3521. size_t name_len;
  3522. int len;
  3523. if (dst == NULL || dst_len == 0) {
  3524. len = -2;
  3525. } else if (data == NULL || name == NULL || data_len == 0) {
  3526. len = -1;
  3527. dst[0] = '\0';
  3528. } else {
  3529. name_len = strlen(name);
  3530. e = data + data_len;
  3531. len = -1;
  3532. dst[0] = '\0';
  3533. /* data is "var1=val1&var2=val2...". Find variable first */
  3534. for (p = data; p + name_len < e; p++) {
  3535. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3536. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3537. /* Point p to variable value */
  3538. p += name_len + 1;
  3539. /* Point s to the end of the value */
  3540. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3541. if (s == NULL) {
  3542. s = e;
  3543. }
  3544. /* assert(s >= p); */
  3545. if (s < p) {
  3546. return -3;
  3547. }
  3548. /* Decode variable into destination buffer */
  3549. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3550. /* Redirect error code from -1 to -2 (destination buffer too
  3551. * small). */
  3552. if (len == -1) {
  3553. len = -2;
  3554. }
  3555. break;
  3556. }
  3557. }
  3558. }
  3559. return len;
  3560. }
  3561. int
  3562. mg_get_cookie(const char *cookie_header,
  3563. const char *var_name,
  3564. char *dst,
  3565. size_t dst_size)
  3566. {
  3567. const char *s, *p, *end;
  3568. int name_len, len = -1;
  3569. if (dst == NULL || dst_size == 0) {
  3570. len = -2;
  3571. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3572. len = -1;
  3573. dst[0] = '\0';
  3574. } else {
  3575. name_len = (int)strlen(var_name);
  3576. end = s + strlen(s);
  3577. dst[0] = '\0';
  3578. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3579. if (s[name_len] == '=') {
  3580. s += name_len + 1;
  3581. if ((p = strchr(s, ' ')) == NULL) {
  3582. p = end;
  3583. }
  3584. if (p[-1] == ';') {
  3585. p--;
  3586. }
  3587. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3588. s++;
  3589. p--;
  3590. }
  3591. if ((size_t)(p - s) < dst_size) {
  3592. len = (int)(p - s);
  3593. mg_strlcpy(dst, s, (size_t)len + 1);
  3594. } else {
  3595. len = -3;
  3596. }
  3597. break;
  3598. }
  3599. }
  3600. }
  3601. return len;
  3602. }
  3603. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3604. static void
  3605. base64_encode(const unsigned char *src, int src_len, char *dst)
  3606. {
  3607. static const char *b64 =
  3608. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3609. int i, j, a, b, c;
  3610. for (i = j = 0; i < src_len; i += 3) {
  3611. a = src[i];
  3612. b = i + 1 >= src_len ? 0 : src[i + 1];
  3613. c = i + 2 >= src_len ? 0 : src[i + 2];
  3614. dst[j++] = b64[a >> 2];
  3615. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3616. if (i + 1 < src_len) {
  3617. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3618. }
  3619. if (i + 2 < src_len) {
  3620. dst[j++] = b64[c & 63];
  3621. }
  3622. }
  3623. while (j % 4 != 0) {
  3624. dst[j++] = '=';
  3625. }
  3626. dst[j++] = '\0';
  3627. }
  3628. #endif
  3629. #if defined(USE_LUA)
  3630. static unsigned char
  3631. b64reverse(char letter)
  3632. {
  3633. if (letter >= 'A' && letter <= 'Z') {
  3634. return letter - 'A';
  3635. }
  3636. if (letter >= 'a' && letter <= 'z') {
  3637. return letter - 'a' + 26;
  3638. }
  3639. if (letter >= '0' && letter <= '9') {
  3640. return letter - '0' + 52;
  3641. }
  3642. if (letter == '+') {
  3643. return 62;
  3644. }
  3645. if (letter == '/') {
  3646. return 63;
  3647. }
  3648. if (letter == '=') {
  3649. return 255; /* normal end */
  3650. }
  3651. return 254; /* error */
  3652. }
  3653. static int
  3654. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3655. {
  3656. int i;
  3657. unsigned char a, b, c, d;
  3658. *dst_len = 0;
  3659. for (i = 0; i < src_len; i += 4) {
  3660. a = b64reverse(src[i]);
  3661. if (a >= 254) {
  3662. return i;
  3663. }
  3664. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3665. if (b >= 254) {
  3666. return i + 1;
  3667. }
  3668. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3669. if (c == 254) {
  3670. return i + 2;
  3671. }
  3672. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3673. if (d == 254) {
  3674. return i + 3;
  3675. }
  3676. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3677. if (c != 255) {
  3678. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3679. if (d != 255) {
  3680. dst[(*dst_len)++] = (c << 6) + d;
  3681. }
  3682. }
  3683. }
  3684. return -1;
  3685. }
  3686. #endif
  3687. static int
  3688. is_put_or_delete_method(const struct mg_connection *conn)
  3689. {
  3690. if (conn) {
  3691. const char *s = conn->request_info.request_method;
  3692. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3693. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3694. }
  3695. return 0;
  3696. }
  3697. static void
  3698. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3699. char *filename, /* out: filename */
  3700. size_t filename_buf_len, /* in: size of filename buffer */
  3701. struct file *filep, /* out: file structure */
  3702. int *is_found, /* out: file is found (directly) */
  3703. int *is_script_resource, /* out: handled by a script? */
  3704. int *is_websocket_request, /* out: websocket connetion? */
  3705. int *is_put_or_delete_request /* out: put/delete a file? */
  3706. )
  3707. {
  3708. /* TODO (high): Restructure this function */
  3709. #if !defined(NO_FILES)
  3710. const char *uri = conn->request_info.local_uri;
  3711. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3712. const char *rewrite;
  3713. struct vec a, b;
  3714. int match_len;
  3715. char gz_path[PATH_MAX];
  3716. char const *accept_encoding;
  3717. int truncated;
  3718. #if !defined(NO_CGI) || defined(USE_LUA)
  3719. char *p;
  3720. #endif
  3721. #else
  3722. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3723. #endif
  3724. memset(filep, 0, sizeof(*filep));
  3725. *filename = 0;
  3726. *is_found = 0;
  3727. *is_script_resource = 0;
  3728. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3729. #if defined(USE_WEBSOCKET)
  3730. *is_websocket_request = is_websocket_protocol(conn);
  3731. #if !defined(NO_FILES)
  3732. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3733. root = conn->ctx->config[WEBSOCKET_ROOT];
  3734. }
  3735. #endif /* !NO_FILES */
  3736. #else /* USE_WEBSOCKET */
  3737. *is_websocket_request = 0;
  3738. #endif /* USE_WEBSOCKET */
  3739. #if !defined(NO_FILES)
  3740. /* Note that root == NULL is a regular use case here. This occurs,
  3741. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3742. * config is not required. */
  3743. if (root == NULL) {
  3744. /* all file related outputs have already been set to 0, just return
  3745. */
  3746. return;
  3747. }
  3748. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3749. * of the path one byte on the right.
  3750. * If document_root is NULL, leave the file empty. */
  3751. mg_snprintf(
  3752. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  3753. if (truncated) {
  3754. goto interpret_cleanup;
  3755. }
  3756. rewrite = conn->ctx->config[REWRITE];
  3757. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3758. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3759. mg_snprintf(conn,
  3760. &truncated,
  3761. filename,
  3762. filename_buf_len - 1,
  3763. "%.*s%s",
  3764. (int)b.len,
  3765. b.ptr,
  3766. uri + match_len);
  3767. break;
  3768. }
  3769. }
  3770. if (truncated) {
  3771. goto interpret_cleanup;
  3772. }
  3773. /* Local file path and name, corresponding to requested URI
  3774. * is now stored in "filename" variable. */
  3775. if (mg_stat(conn, filename, filep)) {
  3776. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3777. /* File exists. Check if it is a script type. */
  3778. if (0
  3779. #if !defined(NO_CGI)
  3780. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3781. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3782. filename) > 0
  3783. #endif
  3784. #if defined(USE_LUA)
  3785. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3786. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3787. filename) > 0
  3788. #endif
  3789. #if defined(USE_DUKTAPE)
  3790. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3791. strlen(
  3792. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3793. filename) > 0
  3794. #endif
  3795. ) {
  3796. /* The request addresses a CGI script or a Lua script. The URI
  3797. * corresponds to the script itself (like /path/script.cgi),
  3798. * and there is no additional resource path
  3799. * (like /path/script.cgi/something).
  3800. * Requests that modify (replace or delete) a resource, like
  3801. * PUT and DELETE requests, should replace/delete the script
  3802. * file.
  3803. * Requests that read or write from/to a resource, like GET and
  3804. * POST requests, should call the script and return the
  3805. * generated response. */
  3806. *is_script_resource = !*is_put_or_delete_request;
  3807. }
  3808. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3809. *is_found = 1;
  3810. return;
  3811. }
  3812. /* If we can't find the actual file, look for the file
  3813. * with the same name but a .gz extension. If we find it,
  3814. * use that and set the gzipped flag in the file struct
  3815. * to indicate that the response need to have the content-
  3816. * encoding: gzip header.
  3817. * We can only do this if the browser declares support. */
  3818. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  3819. if (strstr(accept_encoding, "gzip") != NULL) {
  3820. mg_snprintf(
  3821. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  3822. if (truncated) {
  3823. goto interpret_cleanup;
  3824. }
  3825. if (mg_stat(conn, gz_path, filep)) {
  3826. if (filep) {
  3827. filep->gzipped = 1;
  3828. *is_found = 1;
  3829. }
  3830. /* Currently gz files can not be scripts. */
  3831. return;
  3832. }
  3833. }
  3834. }
  3835. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3836. /* Support PATH_INFO for CGI scripts. */
  3837. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3838. if (*p == '/') {
  3839. *p = '\0';
  3840. if ((0
  3841. #if !defined(NO_CGI)
  3842. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3843. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3844. filename) > 0
  3845. #endif
  3846. #if defined(USE_LUA)
  3847. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3848. strlen(
  3849. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3850. filename) > 0
  3851. #endif
  3852. #if defined(USE_DUKTAPE)
  3853. || match_prefix(
  3854. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3855. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3856. filename) > 0
  3857. #endif
  3858. ) && mg_stat(conn, filename, filep)) {
  3859. /* Shift PATH_INFO block one character right, e.g.
  3860. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3861. * conn->path_info is pointing to the local variable "path"
  3862. * declared in handle_request(), so PATH_INFO is not valid
  3863. * after handle_request returns. */
  3864. conn->path_info = p + 1;
  3865. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3866. * trailing \0 */
  3867. p[1] = '/';
  3868. *is_script_resource = 1;
  3869. break;
  3870. } else {
  3871. *p = '/';
  3872. }
  3873. }
  3874. }
  3875. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3876. #endif /* !defined(NO_FILES) */
  3877. return;
  3878. #if !defined(NO_FILES)
  3879. /* Reset all outputs */
  3880. interpret_cleanup:
  3881. memset(filep, 0, sizeof(*filep));
  3882. *filename = 0;
  3883. *is_found = 0;
  3884. *is_script_resource = 0;
  3885. *is_websocket_request = 0;
  3886. *is_put_or_delete_request = 0;
  3887. #endif /* !defined(NO_FILES) */
  3888. }
  3889. /* Check whether full request is buffered. Return:
  3890. * -1 if request is malformed
  3891. * 0 if request is not yet fully buffered
  3892. * >0 actual request length, including last \r\n\r\n */
  3893. static int
  3894. get_request_len(const char *buf, int buflen)
  3895. {
  3896. const char *s, *e;
  3897. int len = 0;
  3898. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3899. /* Control characters are not allowed but >=128 is. */
  3900. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  3901. && *(const unsigned char *)s < 128) {
  3902. len = -1;
  3903. break; /* [i_a] abort scan as soon as one malformed character is
  3904. * found; */
  3905. /* don't let subsequent \r\n\r\n win us over anyhow */
  3906. } else if (s[0] == '\n' && s[1] == '\n') {
  3907. len = (int)(s - buf) + 2;
  3908. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3909. len = (int)(s - buf) + 3;
  3910. }
  3911. return len;
  3912. }
  3913. /* Convert month to the month number. Return -1 on error, or month number */
  3914. static int
  3915. get_month_index(const char *s)
  3916. {
  3917. size_t i;
  3918. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  3919. if (!strcmp(s, month_names[i])) {
  3920. return (int)i;
  3921. }
  3922. }
  3923. return -1;
  3924. }
  3925. static int
  3926. num_leap_years(int year)
  3927. {
  3928. return year / 4 - year / 100 + year / 400;
  3929. }
  3930. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3931. static time_t
  3932. parse_date_string(const char *datetime)
  3933. {
  3934. static const unsigned short days_before_month[] = {
  3935. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3936. char month_str[32] = {0};
  3937. int second, minute, hour, day, month, year, leap_days, days;
  3938. time_t result = (time_t)0;
  3939. if ((sscanf(datetime,
  3940. "%d/%3s/%d %d:%d:%d",
  3941. &day,
  3942. month_str,
  3943. &year,
  3944. &hour,
  3945. &minute,
  3946. &second) == 6) || (sscanf(datetime,
  3947. "%d %3s %d %d:%d:%d",
  3948. &day,
  3949. month_str,
  3950. &year,
  3951. &hour,
  3952. &minute,
  3953. &second) == 6)
  3954. || (sscanf(datetime,
  3955. "%*3s, %d %3s %d %d:%d:%d",
  3956. &day,
  3957. month_str,
  3958. &year,
  3959. &hour,
  3960. &minute,
  3961. &second) == 6) || (sscanf(datetime,
  3962. "%d-%3s-%d %d:%d:%d",
  3963. &day,
  3964. month_str,
  3965. &year,
  3966. &hour,
  3967. &minute,
  3968. &second) == 6)) {
  3969. month = get_month_index(month_str);
  3970. if ((month >= 0) && (year > 1970)) {
  3971. leap_days = num_leap_years(year) - num_leap_years(1970);
  3972. year -= 1970;
  3973. days =
  3974. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3975. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600
  3976. + minute * 60 + second;
  3977. }
  3978. }
  3979. return result;
  3980. }
  3981. /* Protect against directory disclosure attack by removing '..',
  3982. * excessive '/' and '\' characters */
  3983. static void
  3984. remove_double_dots_and_double_slashes(char *s)
  3985. {
  3986. char *p = s;
  3987. while (*s != '\0') {
  3988. *p++ = *s++;
  3989. if (s[-1] == '/' || s[-1] == '\\') {
  3990. /* Skip all following slashes, backslashes and double-dots */
  3991. while (s[0] != '\0') {
  3992. if (s[0] == '/' || s[0] == '\\') {
  3993. s++;
  3994. } else if (s[0] == '.' && s[1] == '.') {
  3995. s += 2;
  3996. } else {
  3997. break;
  3998. }
  3999. }
  4000. }
  4001. }
  4002. *p = '\0';
  4003. }
  4004. static const struct {
  4005. const char *extension;
  4006. size_t ext_len;
  4007. const char *mime_type;
  4008. } builtin_mime_types[] = {
  4009. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4010. * application types */
  4011. {".doc", 4, "application/msword"},
  4012. {".eps", 4, "application/postscript"},
  4013. {".exe", 4, "application/octet-stream"},
  4014. {".js", 3, "application/javascript"},
  4015. {".json", 5, "application/json"},
  4016. {".pdf", 4, "application/pdf"},
  4017. {".ps", 3, "application/postscript"},
  4018. {".rtf", 4, "application/rtf"},
  4019. {".xhtml", 6, "application/xhtml+xml"},
  4020. {".xsl", 4, "application/xml"},
  4021. {".xslt", 5, "application/xml"},
  4022. /* audio */
  4023. {".mp3", 4, "audio/mpeg"},
  4024. {".oga", 4, "audio/ogg"},
  4025. {".ogg", 4, "audio/ogg"},
  4026. /* image */
  4027. {".gif", 4, "image/gif"},
  4028. {".ief", 4, "image/ief"},
  4029. {".jpeg", 5, "image/jpeg"},
  4030. {".jpg", 4, "image/jpeg"},
  4031. {".jpm", 4, "image/jpm"},
  4032. {".jpx", 4, "image/jpx"},
  4033. {".png", 4, "image/png"},
  4034. {".svg", 4, "image/svg+xml"},
  4035. {".tif", 4, "image/tiff"},
  4036. {".tiff", 5, "image/tiff"},
  4037. /* model */
  4038. {".wrl", 4, "model/vrml"},
  4039. /* text */
  4040. {".css", 4, "text/css"},
  4041. {".csv", 4, "text/csv"},
  4042. {".htm", 4, "text/html"},
  4043. {".html", 5, "text/html"},
  4044. {".sgm", 4, "text/sgml"},
  4045. {".shtm", 5, "text/html"},
  4046. {".shtml", 6, "text/html"},
  4047. {".txt", 4, "text/plain"},
  4048. {".xml", 4, "text/xml"},
  4049. /* video */
  4050. {".mov", 4, "video/quicktime"},
  4051. {".mp4", 4, "video/mp4"},
  4052. {".mpeg", 5, "video/mpeg"},
  4053. {".mpg", 4, "video/mpeg"},
  4054. {".ogv", 4, "video/ogg"},
  4055. {".qt", 3, "video/quicktime"},
  4056. /* not registered types
  4057. * (http://reference.sitepoint.com/html/mime-types-full,
  4058. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4059. {".arj", 4, "application/x-arj-compressed"},
  4060. {".gz", 3, "application/x-gunzip"},
  4061. {".rar", 4, "application/x-arj-compressed"},
  4062. {".swf", 4, "application/x-shockwave-flash"},
  4063. {".tar", 4, "application/x-tar"},
  4064. {".tgz", 4, "application/x-tar-gz"},
  4065. {".torrent", 8, "application/x-bittorrent"},
  4066. {".ppt", 4, "application/x-mspowerpoint"},
  4067. {".xls", 4, "application/x-msexcel"},
  4068. {".zip", 4, "application/x-zip-compressed"},
  4069. {".aac",
  4070. 4,
  4071. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4072. {".aif", 4, "audio/x-aif"},
  4073. {".m3u", 4, "audio/x-mpegurl"},
  4074. {".mid", 4, "audio/x-midi"},
  4075. {".ra", 3, "audio/x-pn-realaudio"},
  4076. {".ram", 4, "audio/x-pn-realaudio"},
  4077. {".wav", 4, "audio/x-wav"},
  4078. {".bmp", 4, "image/bmp"},
  4079. {".ico", 4, "image/x-icon"},
  4080. {".pct", 4, "image/x-pct"},
  4081. {".pict", 5, "image/pict"},
  4082. {".rgb", 4, "image/x-rgb"},
  4083. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4084. {".asf", 4, "video/x-ms-asf"},
  4085. {".avi", 4, "video/x-msvideo"},
  4086. {".m4v", 4, "video/x-m4v"},
  4087. {NULL, 0, NULL}};
  4088. const char *
  4089. mg_get_builtin_mime_type(const char *path)
  4090. {
  4091. const char *ext;
  4092. size_t i, path_len;
  4093. path_len = strlen(path);
  4094. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4095. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4096. if (path_len > builtin_mime_types[i].ext_len
  4097. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4098. return builtin_mime_types[i].mime_type;
  4099. }
  4100. }
  4101. return "text/plain";
  4102. }
  4103. /* Look at the "path" extension and figure what mime type it has.
  4104. * Store mime type in the vector. */
  4105. static void
  4106. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4107. {
  4108. struct vec ext_vec, mime_vec;
  4109. const char *list, *ext;
  4110. size_t path_len;
  4111. path_len = strlen(path);
  4112. if (ctx == NULL || vec == NULL) {
  4113. return;
  4114. }
  4115. /* Scan user-defined mime types first, in case user wants to
  4116. * override default mime types. */
  4117. list = ctx->config[EXTRA_MIME_TYPES];
  4118. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4119. /* ext now points to the path suffix */
  4120. ext = path + path_len - ext_vec.len;
  4121. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4122. *vec = mime_vec;
  4123. return;
  4124. }
  4125. }
  4126. vec->ptr = mg_get_builtin_mime_type(path);
  4127. vec->len = strlen(vec->ptr);
  4128. }
  4129. /* Stringify binary data. Output buffer must be twice as big as input,
  4130. * because each byte takes 2 bytes in string representation */
  4131. static void
  4132. bin2str(char *to, const unsigned char *p, size_t len)
  4133. {
  4134. static const char *hex = "0123456789abcdef";
  4135. for (; len--; p++) {
  4136. *to++ = hex[p[0] >> 4];
  4137. *to++ = hex[p[0] & 0x0f];
  4138. }
  4139. *to = '\0';
  4140. }
  4141. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4142. char *
  4143. mg_md5(char buf[33], ...)
  4144. {
  4145. md5_byte_t hash[16];
  4146. const char *p;
  4147. va_list ap;
  4148. md5_state_t ctx;
  4149. md5_init(&ctx);
  4150. va_start(ap, buf);
  4151. while ((p = va_arg(ap, const char *)) != NULL) {
  4152. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4153. }
  4154. va_end(ap);
  4155. md5_finish(&ctx, hash);
  4156. bin2str(buf, hash, sizeof(hash));
  4157. return buf;
  4158. }
  4159. /* Check the user's password, return 1 if OK */
  4160. static int
  4161. check_password(const char *method,
  4162. const char *ha1,
  4163. const char *uri,
  4164. const char *nonce,
  4165. const char *nc,
  4166. const char *cnonce,
  4167. const char *qop,
  4168. const char *response)
  4169. {
  4170. char ha2[32 + 1], expected_response[32 + 1];
  4171. /* Some of the parameters may be NULL */
  4172. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4173. || qop == NULL
  4174. || response == NULL) {
  4175. return 0;
  4176. }
  4177. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4178. if (strlen(response) != 32) {
  4179. return 0;
  4180. }
  4181. mg_md5(ha2, method, ":", uri, NULL);
  4182. mg_md5(expected_response,
  4183. ha1,
  4184. ":",
  4185. nonce,
  4186. ":",
  4187. nc,
  4188. ":",
  4189. cnonce,
  4190. ":",
  4191. qop,
  4192. ":",
  4193. ha2,
  4194. NULL);
  4195. return mg_strcasecmp(response, expected_response) == 0;
  4196. }
  4197. /* Use the global passwords file, if specified by auth_gpass option,
  4198. * or search for .htpasswd in the requested directory. */
  4199. static void
  4200. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4201. {
  4202. if (conn != NULL && conn->ctx != NULL) {
  4203. char name[PATH_MAX];
  4204. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4205. struct file file = STRUCT_FILE_INITIALIZER;
  4206. int truncated;
  4207. if (gpass != NULL) {
  4208. /* Use global passwords file */
  4209. if (!mg_fopen(conn, gpass, "r", filep)) {
  4210. #ifdef DEBUG
  4211. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4212. #endif
  4213. }
  4214. /* Important: using local struct file to test path for is_directory
  4215. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4216. * was opened. */
  4217. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4218. mg_snprintf(conn,
  4219. &truncated,
  4220. name,
  4221. sizeof(name),
  4222. "%s/%s",
  4223. path,
  4224. PASSWORDS_FILE_NAME);
  4225. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4226. #ifdef DEBUG
  4227. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4228. #endif
  4229. }
  4230. } else {
  4231. /* Try to find .htpasswd in requested directory. */
  4232. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4233. if (e[0] == '/') {
  4234. break;
  4235. }
  4236. }
  4237. mg_snprintf(conn,
  4238. &truncated,
  4239. name,
  4240. sizeof(name),
  4241. "%.*s%s",
  4242. (int)(e - p),
  4243. p,
  4244. PASSWORDS_FILE_NAME);
  4245. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4246. #ifdef DEBUG
  4247. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4248. #endif
  4249. }
  4250. }
  4251. }
  4252. }
  4253. /* Parsed Authorization header */
  4254. struct ah {
  4255. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4256. };
  4257. /* Return 1 on success. Always initializes the ah structure. */
  4258. static int
  4259. parse_auth_header(struct mg_connection *conn,
  4260. char *buf,
  4261. size_t buf_size,
  4262. struct ah *ah)
  4263. {
  4264. char *name, *value, *s;
  4265. const char *auth_header;
  4266. uint64_t nonce;
  4267. if (!ah || !conn) {
  4268. return 0;
  4269. }
  4270. (void)memset(ah, 0, sizeof(*ah));
  4271. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4272. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4273. return 0;
  4274. }
  4275. /* Make modifiable copy of the auth header */
  4276. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4277. s = buf;
  4278. /* Parse authorization header */
  4279. for (;;) {
  4280. /* Gobble initial spaces */
  4281. while (isspace(*(unsigned char *)s)) {
  4282. s++;
  4283. }
  4284. name = skip_quoted(&s, "=", " ", 0);
  4285. /* Value is either quote-delimited, or ends at first comma or space. */
  4286. if (s[0] == '\"') {
  4287. s++;
  4288. value = skip_quoted(&s, "\"", " ", '\\');
  4289. if (s[0] == ',') {
  4290. s++;
  4291. }
  4292. } else {
  4293. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4294. * spaces */
  4295. }
  4296. if (*name == '\0') {
  4297. break;
  4298. }
  4299. if (!strcmp(name, "username")) {
  4300. ah->user = value;
  4301. } else if (!strcmp(name, "cnonce")) {
  4302. ah->cnonce = value;
  4303. } else if (!strcmp(name, "response")) {
  4304. ah->response = value;
  4305. } else if (!strcmp(name, "uri")) {
  4306. ah->uri = value;
  4307. } else if (!strcmp(name, "qop")) {
  4308. ah->qop = value;
  4309. } else if (!strcmp(name, "nc")) {
  4310. ah->nc = value;
  4311. } else if (!strcmp(name, "nonce")) {
  4312. ah->nonce = value;
  4313. }
  4314. }
  4315. #ifndef NO_NONCE_CHECK
  4316. /* Read the nonce from the response. */
  4317. if (ah->nonce == NULL) {
  4318. return 0;
  4319. }
  4320. s = NULL;
  4321. nonce = strtoull(ah->nonce, &s, 10);
  4322. if ((s == NULL) || (*s != 0)) {
  4323. return 0;
  4324. }
  4325. /* Convert the nonce from the client to a number. */
  4326. nonce ^= conn->ctx->auth_nonce_mask;
  4327. /* The converted number corresponds to the time the nounce has been
  4328. * created. This should not be earlier than the server start. */
  4329. /* Server side nonce check is valuable in all situations but one:
  4330. * if the server restarts frequently, but the client should not see
  4331. * that, so the server should accept nonces from previous starts. */
  4332. /* However, the reasonable default is to not accept a nonce from a
  4333. * previous start, so if anyone changed the access rights between
  4334. * two restarts, a new login is required. */
  4335. if (nonce < (uint64_t)conn->ctx->start_time) {
  4336. /* nonce is from a previous start of the server and no longer valid
  4337. * (replay attack?) */
  4338. return 0;
  4339. }
  4340. /* Check if the nonce is too high, so it has not (yet) been used by the
  4341. * server. */
  4342. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4343. return 0;
  4344. }
  4345. #endif
  4346. /* CGI needs it as REMOTE_USER */
  4347. if (ah->user != NULL) {
  4348. conn->request_info.remote_user = mg_strdup(ah->user);
  4349. } else {
  4350. return 0;
  4351. }
  4352. return 1;
  4353. }
  4354. static char *
  4355. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4356. {
  4357. char *eof;
  4358. size_t len;
  4359. char *memend;
  4360. if (!filep) {
  4361. return NULL;
  4362. }
  4363. if (filep->membuf != NULL && *p != NULL) {
  4364. memend = (char *)&filep->membuf[filep->size];
  4365. /* Search for \n from p till the end of stream */
  4366. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4367. if (eof != NULL) {
  4368. eof += 1; /* Include \n */
  4369. } else {
  4370. eof = memend; /* Copy remaining data */
  4371. }
  4372. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4373. memcpy(buf, *p, len);
  4374. buf[len] = '\0';
  4375. *p += len;
  4376. return len ? eof : NULL;
  4377. } else if (filep->fp != NULL) {
  4378. return fgets(buf, (int)size, filep->fp);
  4379. } else {
  4380. return NULL;
  4381. }
  4382. }
  4383. struct read_auth_file_struct {
  4384. struct mg_connection *conn;
  4385. struct ah ah;
  4386. char *domain;
  4387. char buf[256 + 256 + 40];
  4388. char *f_user;
  4389. char *f_domain;
  4390. char *f_ha1;
  4391. };
  4392. static int
  4393. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4394. {
  4395. char *p;
  4396. int is_authorized = 0;
  4397. struct file fp;
  4398. size_t l;
  4399. if (!filep || !workdata) {
  4400. return 0;
  4401. }
  4402. /* Loop over passwords file */
  4403. p = (char *)filep->membuf;
  4404. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4405. l = strlen(workdata->buf);
  4406. while (l > 0) {
  4407. if (isspace(workdata->buf[l - 1])
  4408. || iscntrl(workdata->buf[l - 1])) {
  4409. l--;
  4410. workdata->buf[l] = 0;
  4411. } else
  4412. break;
  4413. }
  4414. if (l < 1) {
  4415. continue;
  4416. }
  4417. workdata->f_user = workdata->buf;
  4418. if (workdata->f_user[0] == ':') {
  4419. /* user names may not contain a ':' and may not be empty,
  4420. * so lines starting with ':' may be used for a special purpose */
  4421. if (workdata->f_user[1] == '#') {
  4422. /* :# is a comment */
  4423. continue;
  4424. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4425. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4426. is_authorized = read_auth_file(&fp, workdata);
  4427. mg_fclose(&fp);
  4428. } else {
  4429. mg_cry(workdata->conn,
  4430. "%s: cannot open authorization file: %s",
  4431. __func__,
  4432. workdata->buf);
  4433. }
  4434. continue;
  4435. }
  4436. /* everything is invalid for the moment (might change in the
  4437. * future) */
  4438. mg_cry(workdata->conn,
  4439. "%s: syntax error in authorization file: %s",
  4440. __func__,
  4441. workdata->buf);
  4442. continue;
  4443. }
  4444. workdata->f_domain = strchr(workdata->f_user, ':');
  4445. if (workdata->f_domain == NULL) {
  4446. mg_cry(workdata->conn,
  4447. "%s: syntax error in authorization file: %s",
  4448. __func__,
  4449. workdata->buf);
  4450. continue;
  4451. }
  4452. *(workdata->f_domain) = 0;
  4453. (workdata->f_domain)++;
  4454. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4455. if (workdata->f_ha1 == NULL) {
  4456. mg_cry(workdata->conn,
  4457. "%s: syntax error in authorization file: %s",
  4458. __func__,
  4459. workdata->buf);
  4460. continue;
  4461. }
  4462. *(workdata->f_ha1) = 0;
  4463. (workdata->f_ha1)++;
  4464. if (!strcmp(workdata->ah.user, workdata->f_user)
  4465. && !strcmp(workdata->domain, workdata->f_domain)) {
  4466. return check_password(workdata->conn->request_info.request_method,
  4467. workdata->f_ha1,
  4468. workdata->ah.uri,
  4469. workdata->ah.nonce,
  4470. workdata->ah.nc,
  4471. workdata->ah.cnonce,
  4472. workdata->ah.qop,
  4473. workdata->ah.response);
  4474. }
  4475. }
  4476. return is_authorized;
  4477. }
  4478. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4479. static int
  4480. authorize(struct mg_connection *conn, struct file *filep)
  4481. {
  4482. struct read_auth_file_struct workdata;
  4483. char buf[MG_BUF_LEN];
  4484. if (!conn || !conn->ctx) {
  4485. return 0;
  4486. }
  4487. memset(&workdata, 0, sizeof(workdata));
  4488. workdata.conn = conn;
  4489. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4490. return 0;
  4491. }
  4492. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4493. return read_auth_file(filep, &workdata);
  4494. }
  4495. /* Return 1 if request is authorised, 0 otherwise. */
  4496. static int
  4497. check_authorization(struct mg_connection *conn, const char *path)
  4498. {
  4499. char fname[PATH_MAX];
  4500. struct vec uri_vec, filename_vec;
  4501. const char *list;
  4502. struct file file = STRUCT_FILE_INITIALIZER;
  4503. int authorized = 1, truncated;
  4504. if (!conn || !conn->ctx) {
  4505. return 0;
  4506. }
  4507. list = conn->ctx->config[PROTECT_URI];
  4508. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4509. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4510. mg_snprintf(conn,
  4511. &truncated,
  4512. fname,
  4513. sizeof(fname),
  4514. "%.*s",
  4515. (int)filename_vec.len,
  4516. filename_vec.ptr);
  4517. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4518. mg_cry(conn,
  4519. "%s: cannot open %s: %s",
  4520. __func__,
  4521. fname,
  4522. strerror(errno));
  4523. }
  4524. break;
  4525. }
  4526. }
  4527. if (!is_file_opened(&file)) {
  4528. open_auth_file(conn, path, &file);
  4529. }
  4530. if (is_file_opened(&file)) {
  4531. authorized = authorize(conn, &file);
  4532. mg_fclose(&file);
  4533. }
  4534. return authorized;
  4535. }
  4536. static void
  4537. send_authorization_request(struct mg_connection *conn)
  4538. {
  4539. char date[64];
  4540. time_t curtime = time(NULL);
  4541. if (conn && conn->ctx) {
  4542. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4543. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4544. nonce += conn->ctx->nonce_count;
  4545. ++conn->ctx->nonce_count;
  4546. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4547. nonce ^= conn->ctx->auth_nonce_mask;
  4548. conn->status_code = 401;
  4549. conn->must_close = 1;
  4550. gmt_time_string(date, sizeof(date), &curtime);
  4551. mg_printf(conn,
  4552. "HTTP/1.1 401 Unauthorized\r\n"
  4553. "Date: %s\r\n"
  4554. "Connection: %s\r\n"
  4555. "Content-Length: 0\r\n"
  4556. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4557. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4558. date,
  4559. suggest_connection_header(conn),
  4560. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4561. nonce);
  4562. }
  4563. }
  4564. #if !defined(NO_FILES)
  4565. static int
  4566. is_authorized_for_put(struct mg_connection *conn)
  4567. {
  4568. if (conn) {
  4569. struct file file = STRUCT_FILE_INITIALIZER;
  4570. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4571. int ret = 0;
  4572. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4573. ret = authorize(conn, &file);
  4574. mg_fclose(&file);
  4575. }
  4576. return ret;
  4577. }
  4578. return 0;
  4579. }
  4580. #endif
  4581. int
  4582. mg_modify_passwords_file(const char *fname,
  4583. const char *domain,
  4584. const char *user,
  4585. const char *pass)
  4586. {
  4587. int found, i;
  4588. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4589. FILE *fp, *fp2;
  4590. found = 0;
  4591. fp = fp2 = NULL;
  4592. /* Regard empty password as no password - remove user record. */
  4593. if (pass != NULL && pass[0] == '\0') {
  4594. pass = NULL;
  4595. }
  4596. /* Other arguments must not be empty */
  4597. if (fname == NULL || domain == NULL || user == NULL) {
  4598. return 0;
  4599. }
  4600. /* Using the given file format, user name and domain must not contain ':'
  4601. */
  4602. if (strchr(user, ':') != NULL) {
  4603. return 0;
  4604. }
  4605. if (strchr(domain, ':') != NULL) {
  4606. return 0;
  4607. }
  4608. /* Do not allow control characters like newline in user name and domain.
  4609. * Do not allow excessively long names either. */
  4610. for (i = 0; i < 255 && user[i] != 0; i++) {
  4611. if (iscntrl(user[i])) {
  4612. return 0;
  4613. }
  4614. }
  4615. if (user[i]) {
  4616. return 0;
  4617. }
  4618. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4619. if (iscntrl(domain[i])) {
  4620. return 0;
  4621. }
  4622. }
  4623. if (domain[i]) {
  4624. return 0;
  4625. }
  4626. /* The maximum length of the path to the password file is limited */
  4627. if ((strlen(fname) + 4) >= PATH_MAX) {
  4628. return 0;
  4629. }
  4630. /* Create a temporary file name. Length has been checked before. */
  4631. strcpy(tmp, fname);
  4632. strcat(tmp, ".tmp");
  4633. /* Create the file if does not exist */
  4634. if ((fp = fopen(fname, "a+")) != NULL) {
  4635. (void)fclose(fp);
  4636. }
  4637. /* Open the given file and temporary file */
  4638. if ((fp = fopen(fname, "r")) == NULL) {
  4639. return 0;
  4640. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4641. fclose(fp);
  4642. return 0;
  4643. }
  4644. /* Copy the stuff to temporary file */
  4645. while (fgets(line, sizeof(line), fp) != NULL) {
  4646. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4647. continue;
  4648. }
  4649. u[255] = 0;
  4650. d[255] = 0;
  4651. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4652. found++;
  4653. if (pass != NULL) {
  4654. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4655. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4656. }
  4657. } else {
  4658. fprintf(fp2, "%s", line);
  4659. }
  4660. }
  4661. /* If new user, just add it */
  4662. if (!found && pass != NULL) {
  4663. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4664. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4665. }
  4666. /* Close files */
  4667. fclose(fp);
  4668. fclose(fp2);
  4669. /* Put the temp file in place of real file */
  4670. IGNORE_UNUSED_RESULT(remove(fname));
  4671. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4672. return 1;
  4673. }
  4674. static int
  4675. is_valid_port(unsigned long port)
  4676. {
  4677. return port < 0xffff;
  4678. }
  4679. static int
  4680. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4681. {
  4682. struct addrinfo hints, *res, *ressave;
  4683. int ret = 0;
  4684. memset(&hints, 0, sizeof(struct addrinfo));
  4685. hints.ai_family = af;
  4686. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4687. /* bad src string or bad address family */
  4688. return 0;
  4689. }
  4690. ressave = res;
  4691. while (res) {
  4692. if (dstlen >= res->ai_addrlen) {
  4693. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4694. ret = 1;
  4695. }
  4696. res = res->ai_next;
  4697. }
  4698. freeaddrinfo(ressave);
  4699. return ret;
  4700. }
  4701. static int
  4702. connect_socket(struct mg_context *ctx /* may be NULL */,
  4703. const char *host,
  4704. int port,
  4705. int use_ssl,
  4706. char *ebuf,
  4707. size_t ebuf_len,
  4708. SOCKET *sock /* output: socket, must not be NULL */,
  4709. union usa *sa /* output: socket address, must not be NULL */
  4710. )
  4711. {
  4712. int ip_ver = 0;
  4713. *sock = INVALID_SOCKET;
  4714. memset(sa, 0, sizeof(*sa));
  4715. if (ebuf_len > 0) {
  4716. *ebuf = 0;
  4717. }
  4718. if (host == NULL) {
  4719. mg_snprintf(NULL,
  4720. NULL, /* No truncation check for ebuf */
  4721. ebuf,
  4722. ebuf_len,
  4723. "%s",
  4724. "NULL host");
  4725. return 0;
  4726. }
  4727. if (port < 0 || !is_valid_port((unsigned)port)) {
  4728. mg_snprintf(NULL,
  4729. NULL, /* No truncation check for ebuf */
  4730. ebuf,
  4731. ebuf_len,
  4732. "%s",
  4733. "invalid port");
  4734. return 0;
  4735. }
  4736. if (use_ssl && (SSLv23_client_method == NULL)) {
  4737. mg_snprintf(NULL,
  4738. NULL, /* No truncation check for ebuf */
  4739. ebuf,
  4740. ebuf_len,
  4741. "%s",
  4742. "SSL is not initialized");
  4743. return 0;
  4744. }
  4745. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4746. sa->sin.sin_port = htons((uint16_t)port);
  4747. ip_ver = 4;
  4748. #ifdef USE_IPV6
  4749. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4750. sa->sin6.sin6_port = htons((uint16_t)port);
  4751. ip_ver = 6;
  4752. } else if (host[0] == '[') {
  4753. /* While getaddrinfo on Windows will work with [::1],
  4754. * getaddrinfo on Linux only works with ::1 (without []). */
  4755. size_t l = strlen(host + 1);
  4756. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4757. if (h) {
  4758. h[l - 1] = 0;
  4759. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4760. sa->sin6.sin6_port = htons((uint16_t)port);
  4761. ip_ver = 6;
  4762. }
  4763. mg_free(h);
  4764. }
  4765. #endif
  4766. }
  4767. if (ip_ver == 0) {
  4768. mg_snprintf(NULL,
  4769. NULL, /* No truncation check for ebuf */
  4770. ebuf,
  4771. ebuf_len,
  4772. "%s",
  4773. "host not found");
  4774. return 0;
  4775. }
  4776. if (ip_ver == 4) {
  4777. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4778. }
  4779. #ifdef USE_IPV6
  4780. else if (ip_ver == 6) {
  4781. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4782. }
  4783. #endif
  4784. if (*sock == INVALID_SOCKET) {
  4785. mg_snprintf(NULL,
  4786. NULL, /* No truncation check for ebuf */
  4787. ebuf,
  4788. ebuf_len,
  4789. "socket(): %s",
  4790. strerror(ERRNO));
  4791. return 0;
  4792. }
  4793. set_close_on_exec(*sock, fc(ctx));
  4794. if ((ip_ver == 4)
  4795. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  4796. == 0)) {
  4797. /* connected with IPv4 */
  4798. return 1;
  4799. }
  4800. #ifdef USE_IPV6
  4801. if ((ip_ver == 6)
  4802. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  4803. == 0)) {
  4804. /* connected with IPv6 */
  4805. return 1;
  4806. }
  4807. #endif
  4808. /* Not connected */
  4809. mg_snprintf(NULL,
  4810. NULL, /* No truncation check for ebuf */
  4811. ebuf,
  4812. ebuf_len,
  4813. "connect(%s:%d): %s",
  4814. host,
  4815. port,
  4816. strerror(ERRNO));
  4817. closesocket(*sock);
  4818. *sock = INVALID_SOCKET;
  4819. return 0;
  4820. }
  4821. int
  4822. mg_url_encode(const char *src, char *dst, size_t dst_len)
  4823. {
  4824. static const char *dont_escape = "._-$,;~()";
  4825. static const char *hex = "0123456789abcdef";
  4826. char *pos = dst;
  4827. const char *end = dst + dst_len - 1;
  4828. for (; *src != '\0' && pos < end; src++, pos++) {
  4829. if (isalnum(*(const unsigned char *)src)
  4830. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4831. *pos = *src;
  4832. } else if (pos + 2 < end) {
  4833. pos[0] = '%';
  4834. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4835. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4836. pos += 2;
  4837. } else {
  4838. break;
  4839. }
  4840. }
  4841. *pos = '\0';
  4842. return (*src == '\0') ? (int)(pos - dst) : -1;
  4843. }
  4844. static void
  4845. print_dir_entry(struct de *de)
  4846. {
  4847. char size[64], mod[64], href[PATH_MAX];
  4848. struct tm *tm;
  4849. if (de->file.is_directory) {
  4850. mg_snprintf(de->conn,
  4851. NULL, /* Buffer is big enough */
  4852. size,
  4853. sizeof(size),
  4854. "%s",
  4855. "[DIRECTORY]");
  4856. } else {
  4857. /* We use (signed) cast below because MSVC 6 compiler cannot
  4858. * convert unsigned __int64 to double. Sigh. */
  4859. if (de->file.size < 1024) {
  4860. mg_snprintf(de->conn,
  4861. NULL, /* Buffer is big enough */
  4862. size,
  4863. sizeof(size),
  4864. "%d",
  4865. (int)de->file.size);
  4866. } else if (de->file.size < 0x100000) {
  4867. mg_snprintf(de->conn,
  4868. NULL, /* Buffer is big enough */
  4869. size,
  4870. sizeof(size),
  4871. "%.1fk",
  4872. (double)de->file.size / 1024.0);
  4873. } else if (de->file.size < 0x40000000) {
  4874. mg_snprintf(de->conn,
  4875. NULL, /* Buffer is big enough */
  4876. size,
  4877. sizeof(size),
  4878. "%.1fM",
  4879. (double)de->file.size / 1048576);
  4880. } else {
  4881. mg_snprintf(de->conn,
  4882. NULL, /* Buffer is big enough */
  4883. size,
  4884. sizeof(size),
  4885. "%.1fG",
  4886. (double)de->file.size / 1073741824);
  4887. }
  4888. }
  4889. /* Note: mg_snprintf will not cause a buffer overflow above.
  4890. * So, string truncation checks are not required here. */
  4891. tm = localtime(&de->file.last_modified);
  4892. if (tm != NULL) {
  4893. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4894. } else {
  4895. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4896. mod[sizeof(mod) - 1] = '\0';
  4897. }
  4898. mg_url_encode(de->file_name, href, sizeof(href));
  4899. de->conn->num_bytes_sent +=
  4900. mg_printf(de->conn,
  4901. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4902. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4903. de->conn->request_info.local_uri,
  4904. href,
  4905. de->file.is_directory ? "/" : "",
  4906. de->file_name,
  4907. de->file.is_directory ? "/" : "",
  4908. mod,
  4909. size);
  4910. }
  4911. /* This function is called from send_directory() and used for
  4912. * sorting directory entries by size, or name, or modification time.
  4913. * On windows, __cdecl specification is needed in case if project is built
  4914. * with __stdcall convention. qsort always requires __cdels callback. */
  4915. static int WINCDECL
  4916. compare_dir_entries(const void *p1, const void *p2)
  4917. {
  4918. if (p1 && p2) {
  4919. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4920. const char *query_string = a->conn->request_info.query_string;
  4921. int cmp_result = 0;
  4922. if (query_string == NULL) {
  4923. query_string = "na";
  4924. }
  4925. if (a->file.is_directory && !b->file.is_directory) {
  4926. return -1; /* Always put directories on top */
  4927. } else if (!a->file.is_directory && b->file.is_directory) {
  4928. return 1; /* Always put directories on top */
  4929. } else if (*query_string == 'n') {
  4930. cmp_result = strcmp(a->file_name, b->file_name);
  4931. } else if (*query_string == 's') {
  4932. cmp_result = a->file.size == b->file.size
  4933. ? 0
  4934. : a->file.size > b->file.size ? 1 : -1;
  4935. } else if (*query_string == 'd') {
  4936. cmp_result =
  4937. (a->file.last_modified == b->file.last_modified)
  4938. ? 0
  4939. : ((a->file.last_modified > b->file.last_modified) ? 1
  4940. : -1);
  4941. }
  4942. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  4943. }
  4944. return 0;
  4945. }
  4946. static int
  4947. must_hide_file(struct mg_connection *conn, const char *path)
  4948. {
  4949. if (conn && conn->ctx) {
  4950. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  4951. const char *pattern = conn->ctx->config[HIDE_FILES];
  4952. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  4953. || (pattern != NULL
  4954. && match_prefix(pattern, strlen(pattern), path) > 0);
  4955. }
  4956. return 0;
  4957. }
  4958. static int
  4959. scan_directory(struct mg_connection *conn,
  4960. const char *dir,
  4961. void *data,
  4962. void (*cb)(struct de *, void *))
  4963. {
  4964. char path[PATH_MAX];
  4965. struct dirent *dp;
  4966. DIR *dirp;
  4967. struct de de;
  4968. int truncated;
  4969. if ((dirp = opendir(dir)) == NULL) {
  4970. return 0;
  4971. } else {
  4972. de.conn = conn;
  4973. while ((dp = readdir(dirp)) != NULL) {
  4974. /* Do not show current dir and hidden files */
  4975. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  4976. || must_hide_file(conn, dp->d_name)) {
  4977. continue;
  4978. }
  4979. mg_snprintf(
  4980. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  4981. /* If we don't memset stat structure to zero, mtime will have
  4982. * garbage and strftime() will segfault later on in
  4983. * print_dir_entry(). memset is required only if mg_stat()
  4984. * fails. For more details, see
  4985. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4986. memset(&de.file, 0, sizeof(de.file));
  4987. if (truncated) {
  4988. /* If the path is not complete, skip processing. */
  4989. continue;
  4990. }
  4991. if (!mg_stat(conn, path, &de.file)) {
  4992. mg_cry(conn,
  4993. "%s: mg_stat(%s) failed: %s",
  4994. __func__,
  4995. path,
  4996. strerror(ERRNO));
  4997. }
  4998. de.file_name = dp->d_name;
  4999. cb(&de, data);
  5000. }
  5001. (void)closedir(dirp);
  5002. }
  5003. return 1;
  5004. }
  5005. #if !defined(NO_FILES)
  5006. static int
  5007. remove_directory(struct mg_connection *conn, const char *dir)
  5008. {
  5009. char path[PATH_MAX];
  5010. struct dirent *dp;
  5011. DIR *dirp;
  5012. struct de de;
  5013. int truncated;
  5014. int ok = 1;
  5015. if ((dirp = opendir(dir)) == NULL) {
  5016. return 0;
  5017. } else {
  5018. de.conn = conn;
  5019. while ((dp = readdir(dirp)) != NULL) {
  5020. /* Do not show current dir (but show hidden files as they will
  5021. * also be removed) */
  5022. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5023. continue;
  5024. }
  5025. mg_snprintf(
  5026. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5027. /* If we don't memset stat structure to zero, mtime will have
  5028. * garbage and strftime() will segfault later on in
  5029. * print_dir_entry(). memset is required only if mg_stat()
  5030. * fails. For more details, see
  5031. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5032. memset(&de.file, 0, sizeof(de.file));
  5033. if (truncated) {
  5034. /* Do not delete anything shorter */
  5035. ok = 0;
  5036. continue;
  5037. }
  5038. if (!mg_stat(conn, path, &de.file)) {
  5039. mg_cry(conn,
  5040. "%s: mg_stat(%s) failed: %s",
  5041. __func__,
  5042. path,
  5043. strerror(ERRNO));
  5044. ok = 0;
  5045. }
  5046. if (de.file.membuf == NULL) {
  5047. /* file is not in memory */
  5048. if (de.file.is_directory) {
  5049. if (remove_directory(conn, path) == 0) {
  5050. ok = 0;
  5051. }
  5052. } else {
  5053. if (mg_remove(path) == 0) {
  5054. ok = 0;
  5055. }
  5056. }
  5057. } else {
  5058. /* file is in memory. It can not be deleted. */
  5059. ok = 0;
  5060. }
  5061. }
  5062. (void)closedir(dirp);
  5063. IGNORE_UNUSED_RESULT(rmdir(dir));
  5064. }
  5065. return ok;
  5066. }
  5067. #endif
  5068. struct dir_scan_data {
  5069. struct de *entries;
  5070. unsigned int num_entries;
  5071. unsigned int arr_size;
  5072. };
  5073. /* Behaves like realloc(), but frees original pointer on failure */
  5074. static void *
  5075. realloc2(void *ptr, size_t size)
  5076. {
  5077. void *new_ptr = mg_realloc(ptr, size);
  5078. if (new_ptr == NULL) {
  5079. mg_free(ptr);
  5080. }
  5081. return new_ptr;
  5082. }
  5083. static void
  5084. dir_scan_callback(struct de *de, void *data)
  5085. {
  5086. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5087. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5088. dsd->arr_size *= 2;
  5089. dsd->entries =
  5090. (struct de *)realloc2(dsd->entries,
  5091. dsd->arr_size * sizeof(dsd->entries[0]));
  5092. }
  5093. if (dsd->entries == NULL) {
  5094. /* TODO(lsm, low): propagate an error to the caller */
  5095. dsd->num_entries = 0;
  5096. } else {
  5097. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5098. dsd->entries[dsd->num_entries].file = de->file;
  5099. dsd->entries[dsd->num_entries].conn = de->conn;
  5100. dsd->num_entries++;
  5101. }
  5102. }
  5103. static void
  5104. handle_directory_request(struct mg_connection *conn, const char *dir)
  5105. {
  5106. unsigned int i;
  5107. int sort_direction;
  5108. struct dir_scan_data data = {NULL, 0, 128};
  5109. char date[64];
  5110. time_t curtime = time(NULL);
  5111. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5112. send_http_error(conn,
  5113. 500,
  5114. "Error: Cannot open directory\nopendir(%s): %s",
  5115. dir,
  5116. strerror(ERRNO));
  5117. return;
  5118. }
  5119. gmt_time_string(date, sizeof(date), &curtime);
  5120. if (!conn) {
  5121. return;
  5122. }
  5123. sort_direction = conn->request_info.query_string != NULL
  5124. && conn->request_info.query_string[1] == 'd'
  5125. ? 'a'
  5126. : 'd';
  5127. conn->must_close = 1;
  5128. mg_printf(conn,
  5129. "HTTP/1.1 200 OK\r\n"
  5130. "Date: %s\r\n"
  5131. "Connection: close\r\n"
  5132. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5133. date);
  5134. conn->num_bytes_sent +=
  5135. mg_printf(conn,
  5136. "<html><head><title>Index of %s</title>"
  5137. "<style>th {text-align: left;}</style></head>"
  5138. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5139. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5140. "<th><a href=\"?d%c\">Modified</a></th>"
  5141. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5142. "<tr><td colspan=\"3\"><hr></td></tr>",
  5143. conn->request_info.local_uri,
  5144. conn->request_info.local_uri,
  5145. sort_direction,
  5146. sort_direction,
  5147. sort_direction);
  5148. /* Print first entry - link to a parent directory */
  5149. conn->num_bytes_sent +=
  5150. mg_printf(conn,
  5151. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5152. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5153. conn->request_info.local_uri,
  5154. "..",
  5155. "Parent directory",
  5156. "-",
  5157. "-");
  5158. /* Sort and print directory entries */
  5159. if (data.entries != NULL) {
  5160. qsort(data.entries,
  5161. (size_t)data.num_entries,
  5162. sizeof(data.entries[0]),
  5163. compare_dir_entries);
  5164. for (i = 0; i < data.num_entries; i++) {
  5165. print_dir_entry(&data.entries[i]);
  5166. mg_free(data.entries[i].file_name);
  5167. }
  5168. mg_free(data.entries);
  5169. }
  5170. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5171. conn->status_code = 200;
  5172. }
  5173. /* Send len bytes from the opened file to the client. */
  5174. static void
  5175. send_file_data(struct mg_connection *conn,
  5176. struct file *filep,
  5177. int64_t offset,
  5178. int64_t len)
  5179. {
  5180. char buf[MG_BUF_LEN];
  5181. int to_read, num_read, num_written;
  5182. int64_t size;
  5183. if (!filep || !conn) {
  5184. return;
  5185. }
  5186. /* Sanity check the offset */
  5187. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5188. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5189. if (len > 0 && filep->membuf != NULL && size > 0) {
  5190. /* file stored in memory */
  5191. if (len > size - offset) {
  5192. len = size - offset;
  5193. }
  5194. mg_write(conn, filep->membuf + offset, (size_t)len);
  5195. } else if (len > 0 && filep->fp != NULL) {
  5196. /* file stored on disk */
  5197. #if defined(__linux__)
  5198. /* sendfile is only available for Linux */
  5199. if (conn->throttle == 0 && conn->ssl == 0) {
  5200. off_t sf_offs = (off_t)offset;
  5201. ssize_t sf_sent;
  5202. int sf_file = fileno(filep->fp);
  5203. int loop_cnt = 0;
  5204. do {
  5205. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5206. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5207. size_t sf_tosend =
  5208. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5209. sf_sent =
  5210. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5211. if (sf_sent > 0) {
  5212. conn->num_bytes_sent += sf_sent;
  5213. len -= sf_sent;
  5214. offset += sf_sent;
  5215. } else if (loop_cnt == 0) {
  5216. /* This file can not be sent using sendfile.
  5217. * This might be the case for pseudo-files in the
  5218. * /sys/ and /proc/ file system.
  5219. * Use the regular user mode copy code instead. */
  5220. break;
  5221. } else if (sf_sent == 0) {
  5222. /* No error, but 0 bytes sent. May be EOF? */
  5223. return;
  5224. }
  5225. loop_cnt++;
  5226. } while ((len > 0) && (sf_sent >= 0));
  5227. if (sf_sent > 0) {
  5228. return; /* OK */
  5229. }
  5230. /* sf_sent<0 means error, thus fall back to the classic way */
  5231. /* This is always the case, if sf_file is not a "normal" file,
  5232. * e.g., for sending data from the output of a CGI process. */
  5233. offset = (int64_t)sf_offs;
  5234. }
  5235. #endif
  5236. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5237. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5238. send_http_error(
  5239. conn,
  5240. 500,
  5241. "%s",
  5242. "Error: Unable to access file at requested position.");
  5243. } else {
  5244. while (len > 0) {
  5245. /* Calculate how much to read from the file in the buffer */
  5246. to_read = sizeof(buf);
  5247. if ((int64_t)to_read > len) {
  5248. to_read = (int)len;
  5249. }
  5250. /* Read from file, exit the loop on error */
  5251. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5252. <= 0) {
  5253. break;
  5254. }
  5255. /* Send read bytes to the client, exit the loop on error */
  5256. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5257. != num_read) {
  5258. break;
  5259. }
  5260. /* Both read and were successful, adjust counters */
  5261. conn->num_bytes_sent += num_written;
  5262. len -= num_written;
  5263. }
  5264. }
  5265. }
  5266. }
  5267. static int
  5268. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5269. {
  5270. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5271. }
  5272. static void
  5273. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5274. {
  5275. if (filep != NULL && buf != NULL) {
  5276. mg_snprintf(NULL,
  5277. NULL, /* All calls to construct_etag use 64 byte buffer */
  5278. buf,
  5279. buf_len,
  5280. "\"%lx.%" INT64_FMT "\"",
  5281. (unsigned long)filep->last_modified,
  5282. filep->size);
  5283. }
  5284. }
  5285. static void
  5286. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5287. {
  5288. if (filep != NULL && filep->fp != NULL) {
  5289. #ifdef _WIN32
  5290. (void)conn; /* Unused. */
  5291. #else
  5292. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5293. mg_cry(conn,
  5294. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5295. __func__,
  5296. strerror(ERRNO));
  5297. }
  5298. #endif
  5299. }
  5300. }
  5301. static void
  5302. handle_static_file_request(struct mg_connection *conn,
  5303. const char *path,
  5304. struct file *filep)
  5305. {
  5306. char date[64], lm[64], etag[64];
  5307. char range[128]; /* large enough, so there will be no overflow */
  5308. const char *msg = "OK", *hdr;
  5309. time_t curtime = time(NULL);
  5310. int64_t cl, r1, r2;
  5311. struct vec mime_vec;
  5312. int n, truncated;
  5313. char gz_path[PATH_MAX];
  5314. const char *encoding = "";
  5315. const char *cors1, *cors2, *cors3;
  5316. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5317. return;
  5318. }
  5319. get_mime_type(conn->ctx, path, &mime_vec);
  5320. if (filep->size > INT64_MAX) {
  5321. send_http_error(conn,
  5322. 500,
  5323. "Error: File size is too large to send\n%" INT64_FMT,
  5324. filep->size);
  5325. }
  5326. cl = (int64_t)filep->size;
  5327. conn->status_code = 200;
  5328. range[0] = '\0';
  5329. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5330. * it's important to rewrite the filename after resolving
  5331. * the mime type from it, to preserve the actual file's type */
  5332. if (filep->gzipped) {
  5333. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5334. if (truncated) {
  5335. send_http_error(conn,
  5336. 500,
  5337. "Error: Path of zipped file too long (%s)",
  5338. path);
  5339. return;
  5340. }
  5341. path = gz_path;
  5342. encoding = "Content-Encoding: gzip\r\n";
  5343. }
  5344. if (!mg_fopen(conn, path, "rb", filep)) {
  5345. send_http_error(conn,
  5346. 500,
  5347. "Error: Cannot open file\nfopen(%s): %s",
  5348. path,
  5349. strerror(ERRNO));
  5350. return;
  5351. }
  5352. fclose_on_exec(filep, conn);
  5353. /* If Range: header specified, act accordingly */
  5354. r1 = r2 = 0;
  5355. hdr = mg_get_header(conn, "Range");
  5356. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5357. && r2 >= 0) {
  5358. /* actually, range requests don't play well with a pre-gzipped
  5359. * file (since the range is specified in the uncompressed space) */
  5360. if (filep->gzipped) {
  5361. send_http_error(
  5362. conn,
  5363. 501,
  5364. "%s",
  5365. "Error: Range requests in gzipped files are not supported");
  5366. mg_fclose(filep);
  5367. return;
  5368. }
  5369. conn->status_code = 206;
  5370. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5371. mg_snprintf(conn,
  5372. NULL, /* range buffer is big enough */
  5373. range,
  5374. sizeof(range),
  5375. "Content-Range: bytes "
  5376. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5377. r1,
  5378. r1 + cl - 1,
  5379. filep->size);
  5380. msg = "Partial Content";
  5381. }
  5382. hdr = mg_get_header(conn, "Origin");
  5383. if (hdr) {
  5384. /* Cross-origin resource sharing (CORS), see
  5385. * http://www.html5rocks.com/en/tutorials/cors/,
  5386. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5387. * preflight is not supported for files. */
  5388. cors1 = "Access-Control-Allow-Origin: ";
  5389. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5390. cors3 = "\r\n";
  5391. } else {
  5392. cors1 = cors2 = cors3 = "";
  5393. }
  5394. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5395. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5396. gmt_time_string(date, sizeof(date), &curtime);
  5397. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5398. construct_etag(etag, sizeof(etag), filep);
  5399. (void)mg_printf(conn,
  5400. "HTTP/1.1 %d %s\r\n"
  5401. "%s%s%s"
  5402. "Date: %s\r\n"
  5403. "Last-Modified: %s\r\n"
  5404. "Etag: %s\r\n"
  5405. "Content-Type: %.*s\r\n"
  5406. "Content-Length: %" INT64_FMT "\r\n"
  5407. "Connection: %s\r\n"
  5408. "Accept-Ranges: bytes\r\n"
  5409. "%s%s\r\n",
  5410. conn->status_code,
  5411. msg,
  5412. cors1,
  5413. cors2,
  5414. cors3,
  5415. date,
  5416. lm,
  5417. etag,
  5418. (int)mime_vec.len,
  5419. mime_vec.ptr,
  5420. cl,
  5421. suggest_connection_header(conn),
  5422. range,
  5423. encoding);
  5424. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5425. send_file_data(conn, filep, r1, cl);
  5426. }
  5427. mg_fclose(filep);
  5428. }
  5429. void
  5430. mg_send_file(struct mg_connection *conn, const char *path)
  5431. {
  5432. struct file file = STRUCT_FILE_INITIALIZER;
  5433. if (mg_stat(conn, path, &file)) {
  5434. if (file.is_directory) {
  5435. if (!conn) {
  5436. return;
  5437. }
  5438. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5439. "yes")) {
  5440. handle_directory_request(conn, path);
  5441. } else {
  5442. send_http_error(conn,
  5443. 403,
  5444. "%s",
  5445. "Error: Directory listing denied");
  5446. }
  5447. } else {
  5448. handle_static_file_request(conn, path, &file);
  5449. }
  5450. } else {
  5451. send_http_error(conn, 404, "%s", "Error: File not found");
  5452. }
  5453. }
  5454. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5455. * where parsing stopped. */
  5456. static void
  5457. parse_http_headers(char **buf, struct mg_request_info *ri)
  5458. {
  5459. int i;
  5460. if (!ri) {
  5461. return;
  5462. }
  5463. ri->num_headers = 0;
  5464. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5465. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  5466. ri->http_headers[i].value = skip(buf, "\r\n");
  5467. if (ri->http_headers[i].name[0] == '\0') {
  5468. break;
  5469. }
  5470. ri->num_headers = i + 1;
  5471. }
  5472. }
  5473. static int
  5474. is_valid_http_method(const char *method)
  5475. {
  5476. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5477. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5478. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5479. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5480. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5481. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5482. /* TRACE method (RFC 2616) is not supported for security reasons */
  5483. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5484. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5485. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5486. /* Unsupported WEBDAV Methods: */
  5487. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5488. /* + 11 methods from RFC 3253 */
  5489. /* ORDERPATCH (RFC 3648) */
  5490. /* ACL (RFC 3744) */
  5491. /* SEARCH (RFC 5323) */
  5492. /* + MicroSoft extensions
  5493. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5494. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5495. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5496. }
  5497. /* Parse HTTP request, fill in mg_request_info structure.
  5498. * This function modifies the buffer by NUL-terminating
  5499. * HTTP request components, header names and header values. */
  5500. static int
  5501. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5502. {
  5503. int is_request, request_length;
  5504. if (!ri) {
  5505. return 0;
  5506. }
  5507. request_length = get_request_len(buf, len);
  5508. if (request_length > 0) {
  5509. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5510. * remote_port */
  5511. ri->remote_user = ri->request_method = ri->request_uri =
  5512. ri->http_version = NULL;
  5513. ri->num_headers = 0;
  5514. buf[request_length - 1] = '\0';
  5515. /* RFC says that all initial whitespaces should be ingored */
  5516. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5517. buf++;
  5518. }
  5519. ri->request_method = skip(&buf, " ");
  5520. ri->request_uri = skip(&buf, " ");
  5521. ri->http_version = skip(&buf, "\r\n");
  5522. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5523. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5524. is_request = is_valid_http_method(ri->request_method);
  5525. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5526. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5527. request_length = -1;
  5528. } else {
  5529. if (is_request) {
  5530. ri->http_version += 5;
  5531. }
  5532. parse_http_headers(&buf, ri);
  5533. }
  5534. }
  5535. return request_length;
  5536. }
  5537. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5538. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5539. * buffer (which marks the end of HTTP request). Buffer buf may already
  5540. * have some data. The length of the data is stored in nread.
  5541. * Upon every read operation, increase nread by the number of bytes read. */
  5542. static int
  5543. read_request(FILE *fp,
  5544. struct mg_connection *conn,
  5545. char *buf,
  5546. int bufsiz,
  5547. int *nread)
  5548. {
  5549. int request_len, n = 0;
  5550. struct timespec last_action_time;
  5551. double request_timeout;
  5552. if (!conn) {
  5553. return 0;
  5554. }
  5555. memset(&last_action_time, 0, sizeof(last_action_time));
  5556. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5557. /* value of request_timeout is in seconds, config in milliseconds */
  5558. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5559. } else {
  5560. request_timeout = -1.0;
  5561. }
  5562. request_len = get_request_len(buf, *nread);
  5563. while (
  5564. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5565. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5566. <= request_timeout) || (request_timeout < 0))
  5567. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5568. > 0)) {
  5569. *nread += n;
  5570. /* assert(*nread <= bufsiz); */
  5571. if (*nread > bufsiz) {
  5572. return -2;
  5573. }
  5574. request_len = get_request_len(buf, *nread);
  5575. if (request_timeout > 0.0) {
  5576. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5577. }
  5578. }
  5579. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5580. }
  5581. #if !defined(NO_FILES)
  5582. /* For given directory path, substitute it to valid index file.
  5583. * Return 1 if index file has been found, 0 if not found.
  5584. * If the file is found, it's stats is returned in stp. */
  5585. static int
  5586. substitute_index_file(struct mg_connection *conn,
  5587. char *path,
  5588. size_t path_len,
  5589. struct file *filep)
  5590. {
  5591. if (conn && conn->ctx) {
  5592. const char *list = conn->ctx->config[INDEX_FILES];
  5593. struct file file = STRUCT_FILE_INITIALIZER;
  5594. struct vec filename_vec;
  5595. size_t n = strlen(path);
  5596. int found = 0;
  5597. /* The 'path' given to us points to the directory. Remove all trailing
  5598. * directory separator characters from the end of the path, and
  5599. * then append single directory separator character. */
  5600. while (n > 0 && path[n - 1] == '/') {
  5601. n--;
  5602. }
  5603. path[n] = '/';
  5604. /* Traverse index files list. For each entry, append it to the given
  5605. * path and see if the file exists. If it exists, break the loop */
  5606. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5607. /* Ignore too long entries that may overflow path buffer */
  5608. if (filename_vec.len > path_len - (n + 2)) {
  5609. continue;
  5610. }
  5611. /* Prepare full path to the index file */
  5612. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5613. /* Does it exist? */
  5614. if (mg_stat(conn, path, &file)) {
  5615. /* Yes it does, break the loop */
  5616. *filep = file;
  5617. found = 1;
  5618. break;
  5619. }
  5620. }
  5621. /* If no index file exists, restore directory path */
  5622. if (!found) {
  5623. path[n] = '\0';
  5624. }
  5625. return found;
  5626. }
  5627. return 0;
  5628. }
  5629. #endif
  5630. /* Return True if we should reply 304 Not Modified. */
  5631. static int
  5632. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  5633. {
  5634. char etag[64];
  5635. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5636. const char *inm = mg_get_header(conn, "If-None-Match");
  5637. construct_etag(etag, sizeof(etag), filep);
  5638. if (!filep) {
  5639. return 0;
  5640. }
  5641. return (inm != NULL && !mg_strcasecmp(etag, inm))
  5642. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5643. }
  5644. #if !defined(NO_CGI) || !defined(NO_FILES)
  5645. static int
  5646. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5647. {
  5648. const char *expect, *body;
  5649. char buf[MG_BUF_LEN];
  5650. int to_read, nread, success = 0;
  5651. int64_t buffered_len;
  5652. double timeout = -1.0;
  5653. if (!conn) {
  5654. return 0;
  5655. }
  5656. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5657. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5658. }
  5659. expect = mg_get_header(conn, "Expect");
  5660. /* assert(fp != NULL); */
  5661. if (!fp) {
  5662. send_http_error(conn, 500, "%s", "Error: NULL File");
  5663. return 0;
  5664. }
  5665. if (conn->content_len == -1 && !conn->is_chunked) {
  5666. /* Content length is not specified by the client. */
  5667. send_http_error(conn,
  5668. 411,
  5669. "%s",
  5670. "Error: Client did not specify content length");
  5671. } else if ((expect != NULL)
  5672. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  5673. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5674. send_http_error(conn,
  5675. 417,
  5676. "Error: Can not fulfill expectation %s",
  5677. expect);
  5678. } else {
  5679. if (expect != NULL) {
  5680. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5681. conn->status_code = 100;
  5682. } else {
  5683. conn->status_code = 200;
  5684. }
  5685. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5686. - conn->consumed_content;
  5687. /* assert(buffered_len >= 0); */
  5688. /* assert(conn->consumed_content == 0); */
  5689. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5690. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5691. return 0;
  5692. }
  5693. if (buffered_len > 0) {
  5694. if ((int64_t)buffered_len > conn->content_len) {
  5695. buffered_len = (int)conn->content_len;
  5696. }
  5697. body = conn->buf + conn->request_len + conn->consumed_content;
  5698. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  5699. conn->consumed_content += buffered_len;
  5700. }
  5701. nread = 0;
  5702. while (conn->consumed_content < conn->content_len) {
  5703. to_read = sizeof(buf);
  5704. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  5705. to_read = (int)(conn->content_len - conn->consumed_content);
  5706. }
  5707. nread = pull(NULL, conn, buf, to_read, timeout);
  5708. if (nread <= 0
  5709. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  5710. break;
  5711. }
  5712. conn->consumed_content += nread;
  5713. }
  5714. if (conn->consumed_content == conn->content_len) {
  5715. success = nread >= 0;
  5716. }
  5717. /* Each error code path in this function must send an error */
  5718. if (!success) {
  5719. /* NOTE: Maybe some data has already been sent. */
  5720. /* TODO (low): If some data has been sent, a correct error
  5721. * reply can no longer be sent, so just close the connection */
  5722. send_http_error(conn, 500, "%s", "");
  5723. }
  5724. }
  5725. return success;
  5726. }
  5727. #endif
  5728. #if !defined(NO_CGI)
  5729. /* This structure helps to create an environment for the spawned CGI program.
  5730. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  5731. * last element must be NULL.
  5732. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  5733. * strings must reside in a contiguous buffer. The end of the buffer is
  5734. * marked by two '\0' characters.
  5735. * We satisfy both worlds: we create an envp array (which is vars), all
  5736. * entries are actually pointers inside buf. */
  5737. struct cgi_environment {
  5738. struct mg_connection *conn;
  5739. /* Data block */
  5740. char *buf; /* Environment buffer */
  5741. size_t buflen; /* Space available in buf */
  5742. size_t bufused; /* Space taken in buf */
  5743. /* Index block */
  5744. char **var; /* char **envp */
  5745. size_t varlen; /* Number of variables available in var */
  5746. size_t varused; /* Number of variables stored in var */
  5747. };
  5748. static void addenv(struct cgi_environment *env,
  5749. PRINTF_FORMAT_STRING(const char *fmt),
  5750. ...) PRINTF_ARGS(2, 3);
  5751. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  5752. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  5753. static void
  5754. addenv(struct cgi_environment *env, const char *fmt, ...)
  5755. {
  5756. size_t n, space;
  5757. int truncated;
  5758. char *added;
  5759. va_list ap;
  5760. /* Calculate how much space is left in the buffer */
  5761. space = (env->buflen - env->bufused);
  5762. /* Calculate an estimate for the required space */
  5763. n = strlen(fmt) + 2 + 128;
  5764. do {
  5765. if (space <= n) {
  5766. /* Allocate new buffer */
  5767. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  5768. added = (char *)mg_realloc(env->buf, n);
  5769. if (!added) {
  5770. /* Out of memory */
  5771. mg_cry(env->conn,
  5772. "%s: Cannot allocate memory for CGI variable [%s]",
  5773. __func__,
  5774. fmt);
  5775. return;
  5776. }
  5777. env->buf = added;
  5778. env->buflen = n;
  5779. space = (env->buflen - env->bufused);
  5780. }
  5781. /* Make a pointer to the free space int the buffer */
  5782. added = env->buf + env->bufused;
  5783. /* Copy VARIABLE=VALUE\0 string into the free space */
  5784. va_start(ap, fmt);
  5785. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  5786. va_end(ap);
  5787. /* Do not add truncated strings to the environment */
  5788. if (truncated) {
  5789. /* Reallocate the buffer */
  5790. space = 0;
  5791. n = 1;
  5792. }
  5793. } while (truncated);
  5794. /* Calculate number of bytes added to the environment */
  5795. n = strlen(added) + 1;
  5796. env->bufused += n;
  5797. /* Now update the variable index */
  5798. space = (env->varlen - env->varused);
  5799. if (space < 2) {
  5800. mg_cry(env->conn,
  5801. "%s: Cannot register CGI variable [%s]",
  5802. __func__,
  5803. fmt);
  5804. return;
  5805. }
  5806. /* Append a pointer to the added string into the envp array */
  5807. env->var[env->varused] = added;
  5808. env->varused++;
  5809. }
  5810. static void
  5811. prepare_cgi_environment(struct mg_connection *conn,
  5812. const char *prog,
  5813. struct cgi_environment *env)
  5814. {
  5815. const char *s;
  5816. struct vec var_vec;
  5817. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  5818. int i, truncated;
  5819. if (conn == NULL || prog == NULL || env == NULL) {
  5820. return;
  5821. }
  5822. env->conn = conn;
  5823. env->buflen = CGI_ENVIRONMENT_SIZE;
  5824. env->bufused = 0;
  5825. env->buf = (char *)mg_malloc(env->buflen);
  5826. env->varlen = MAX_CGI_ENVIR_VARS;
  5827. env->varused = 0;
  5828. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  5829. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  5830. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5831. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5832. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  5833. /* Prepare the environment block */
  5834. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  5835. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  5836. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  5837. #if defined(USE_IPV6)
  5838. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  5839. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  5840. } else
  5841. #endif
  5842. {
  5843. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  5844. }
  5845. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  5846. addenv(env, "REMOTE_ADDR=%s", src_addr);
  5847. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  5848. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5849. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  5850. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  5851. /* SCRIPT_NAME */
  5852. addenv(env,
  5853. "SCRIPT_NAME=%.*s",
  5854. (int)strlen(conn->request_info.local_uri)
  5855. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5856. conn->request_info.local_uri);
  5857. addenv(env, "SCRIPT_FILENAME=%s", prog);
  5858. if (conn->path_info == NULL) {
  5859. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5860. } else {
  5861. addenv(env,
  5862. "PATH_TRANSLATED=%s%s",
  5863. conn->ctx->config[DOCUMENT_ROOT],
  5864. conn->path_info);
  5865. }
  5866. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5867. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  5868. addenv(env, "CONTENT_TYPE=%s", s);
  5869. }
  5870. if (conn->request_info.query_string != NULL) {
  5871. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  5872. }
  5873. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  5874. addenv(env, "CONTENT_LENGTH=%s", s);
  5875. }
  5876. if ((s = getenv("PATH")) != NULL) {
  5877. addenv(env, "PATH=%s", s);
  5878. }
  5879. if (conn->path_info != NULL) {
  5880. addenv(env, "PATH_INFO=%s", conn->path_info);
  5881. }
  5882. if (conn->status_code > 0) {
  5883. /* CGI error handler should show the status code */
  5884. addenv(env, "STATUS=%d", conn->status_code);
  5885. }
  5886. #if defined(_WIN32)
  5887. if ((s = getenv("COMSPEC")) != NULL) {
  5888. addenv(env, "COMSPEC=%s", s);
  5889. }
  5890. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5891. addenv(env, "SYSTEMROOT=%s", s);
  5892. }
  5893. if ((s = getenv("SystemDrive")) != NULL) {
  5894. addenv(env, "SystemDrive=%s", s);
  5895. }
  5896. if ((s = getenv("ProgramFiles")) != NULL) {
  5897. addenv(env, "ProgramFiles=%s", s);
  5898. }
  5899. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5900. addenv(env, "ProgramFiles(x86)=%s", s);
  5901. }
  5902. #else
  5903. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  5904. addenv(env, "LD_LIBRARY_PATH=%s", s);
  5905. }
  5906. #endif /* _WIN32 */
  5907. if ((s = getenv("PERLLIB")) != NULL) {
  5908. addenv(env, "PERLLIB=%s", s);
  5909. }
  5910. if (conn->request_info.remote_user != NULL) {
  5911. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  5912. addenv(env, "%s", "AUTH_TYPE=Digest");
  5913. }
  5914. /* Add all headers as HTTP_* variables */
  5915. for (i = 0; i < conn->request_info.num_headers; i++) {
  5916. (void)mg_snprintf(conn,
  5917. &truncated,
  5918. http_var_name,
  5919. sizeof(http_var_name),
  5920. "HTTP_%s",
  5921. conn->request_info.http_headers[i].name);
  5922. if (truncated) {
  5923. mg_cry(conn,
  5924. "%s: HTTP header variable too long [%s]",
  5925. __func__,
  5926. conn->request_info.http_headers[i].name);
  5927. continue;
  5928. }
  5929. /* Convert variable name into uppercase, and change - to _ */
  5930. for (p = http_var_name; *p != '\0'; p++) {
  5931. if (*p == '-') {
  5932. *p = '_';
  5933. }
  5934. *p = (char)toupper(*(unsigned char *)p);
  5935. }
  5936. addenv(env,
  5937. "%s=%s",
  5938. http_var_name,
  5939. conn->request_info.http_headers[i].value);
  5940. }
  5941. /* Add user-specified variables */
  5942. s = conn->ctx->config[CGI_ENVIRONMENT];
  5943. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  5944. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  5945. }
  5946. env->var[env->varused] = NULL;
  5947. env->buf[env->bufused] = '\0';
  5948. }
  5949. static void
  5950. handle_cgi_request(struct mg_connection *conn, const char *prog)
  5951. {
  5952. char *buf;
  5953. size_t buflen;
  5954. int headers_len, data_len, i, truncated;
  5955. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  5956. const char *status, *status_text, *connection_state;
  5957. char *pbuf, dir[PATH_MAX], *p;
  5958. struct mg_request_info ri;
  5959. struct cgi_environment blk;
  5960. FILE *in = NULL, *out = NULL, *err = NULL;
  5961. struct file fout = STRUCT_FILE_INITIALIZER;
  5962. pid_t pid = (pid_t)-1;
  5963. if (conn == NULL) {
  5964. return;
  5965. }
  5966. buf = NULL;
  5967. buflen = 16384;
  5968. prepare_cgi_environment(conn, prog, &blk);
  5969. /* CGI must be executed in its own directory. 'dir' must point to the
  5970. * directory containing executable program, 'p' must point to the
  5971. * executable program name relative to 'dir'. */
  5972. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  5973. if (truncated) {
  5974. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  5975. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  5976. goto done;
  5977. }
  5978. if ((p = strrchr(dir, '/')) != NULL) {
  5979. *p++ = '\0';
  5980. } else {
  5981. dir[0] = '.', dir[1] = '\0';
  5982. p = (char *)prog;
  5983. }
  5984. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  5985. status = strerror(ERRNO);
  5986. mg_cry(conn,
  5987. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  5988. prog,
  5989. status);
  5990. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  5991. goto done;
  5992. }
  5993. pid = spawn_process(
  5994. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  5995. if (pid == (pid_t)-1) {
  5996. status = strerror(ERRNO);
  5997. mg_cry(conn,
  5998. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  5999. prog,
  6000. status);
  6001. send_http_error(conn,
  6002. 500,
  6003. "Error: Cannot spawn CGI process [%s]: %s",
  6004. prog,
  6005. status);
  6006. goto done;
  6007. }
  6008. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6009. set_close_on_exec((SOCKET)fdin[0], conn);
  6010. set_close_on_exec((SOCKET)fdin[1], conn);
  6011. set_close_on_exec((SOCKET)fdout[0], conn);
  6012. set_close_on_exec((SOCKET)fdout[1], conn);
  6013. set_close_on_exec((SOCKET)fderr[0], conn);
  6014. set_close_on_exec((SOCKET)fderr[1], conn);
  6015. /* Parent closes only one side of the pipes.
  6016. * If we don't mark them as closed, close() attempt before
  6017. * return from this function throws an exception on Windows.
  6018. * Windows does not like when closed descriptor is closed again. */
  6019. (void)close(fdin[0]);
  6020. (void)close(fdout[1]);
  6021. (void)close(fderr[1]);
  6022. fdin[0] = fdout[1] = fderr[1] = -1;
  6023. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6024. status = strerror(ERRNO);
  6025. mg_cry(conn,
  6026. "Error: CGI program \"%s\": Can not open stdin: %s",
  6027. prog,
  6028. status);
  6029. send_http_error(conn,
  6030. 500,
  6031. "Error: CGI can not open fdin\nfopen: %s",
  6032. status);
  6033. goto done;
  6034. }
  6035. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6036. status = strerror(ERRNO);
  6037. mg_cry(conn,
  6038. "Error: CGI program \"%s\": Can not open stdout: %s",
  6039. prog,
  6040. status);
  6041. send_http_error(conn,
  6042. 500,
  6043. "Error: CGI can not open fdout\nfopen: %s",
  6044. status);
  6045. goto done;
  6046. }
  6047. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6048. status = strerror(ERRNO);
  6049. mg_cry(conn,
  6050. "Error: CGI program \"%s\": Can not open stderr: %s",
  6051. prog,
  6052. status);
  6053. send_http_error(conn,
  6054. 500,
  6055. "Error: CGI can not open fdout\nfopen: %s",
  6056. status);
  6057. goto done;
  6058. }
  6059. setbuf(in, NULL);
  6060. setbuf(out, NULL);
  6061. setbuf(err, NULL);
  6062. fout.fp = out;
  6063. /* Send POST or PUT data to the CGI process if needed */
  6064. /* TODO(high): Methods like PATCH, MKCOL, ... also have body data. */
  6065. if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  6066. || !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  6067. /* This is a POST/PUT request */
  6068. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6069. /* Error sending the body data */
  6070. mg_cry(conn,
  6071. "Error: CGI program \"%s\": Forward body data failed",
  6072. prog);
  6073. goto done;
  6074. }
  6075. }
  6076. /* Close so child gets an EOF. */
  6077. fclose(in);
  6078. in = NULL;
  6079. fdin[1] = -1;
  6080. /* Now read CGI reply into a buffer. We need to set correct
  6081. * status code, thus we need to see all HTTP headers first.
  6082. * Do not send anything back to client, until we buffer in all
  6083. * HTTP headers. */
  6084. data_len = 0;
  6085. buf = (char *)mg_malloc(buflen);
  6086. if (buf == NULL) {
  6087. send_http_error(conn,
  6088. 500,
  6089. "Error: Not enough memory for CGI buffer (%u bytes)",
  6090. (unsigned int)buflen);
  6091. mg_cry(conn,
  6092. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6093. "bytes)",
  6094. prog,
  6095. (unsigned int)buflen);
  6096. goto done;
  6097. }
  6098. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6099. if (headers_len <= 0) {
  6100. /* Could not parse the CGI response. Check if some error message on
  6101. * stderr. */
  6102. i = pull_all(err, conn, buf, (int)buflen);
  6103. if (i > 0) {
  6104. mg_cry(conn,
  6105. "Error: CGI program \"%s\" sent error "
  6106. "message: [%.*s]",
  6107. prog,
  6108. i,
  6109. buf);
  6110. send_http_error(conn,
  6111. 500,
  6112. "Error: CGI program \"%s\" sent error "
  6113. "message: [%.*s]",
  6114. prog,
  6115. i,
  6116. buf);
  6117. } else {
  6118. mg_cry(conn,
  6119. "Error: CGI program sent malformed or too big "
  6120. "(>%u bytes) HTTP headers: [%.*s]",
  6121. (unsigned)buflen,
  6122. data_len,
  6123. buf);
  6124. send_http_error(conn,
  6125. 500,
  6126. "Error: CGI program sent malformed or too big "
  6127. "(>%u bytes) HTTP headers: [%.*s]",
  6128. (unsigned)buflen,
  6129. data_len,
  6130. buf);
  6131. }
  6132. goto done;
  6133. }
  6134. pbuf = buf;
  6135. buf[headers_len - 1] = '\0';
  6136. parse_http_headers(&pbuf, &ri);
  6137. /* Make up and send the status line */
  6138. status_text = "OK";
  6139. if ((status = get_header(&ri, "Status")) != NULL) {
  6140. conn->status_code = atoi(status);
  6141. status_text = status;
  6142. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  6143. status_text++;
  6144. }
  6145. } else if (get_header(&ri, "Location") != NULL) {
  6146. conn->status_code = 302;
  6147. } else {
  6148. conn->status_code = 200;
  6149. }
  6150. connection_state = get_header(&ri, "Connection");
  6151. if (connection_state == NULL
  6152. || mg_strcasecmp(connection_state, "keep-alive")) {
  6153. conn->must_close = 1;
  6154. }
  6155. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6156. /* Send headers */
  6157. for (i = 0; i < ri.num_headers; i++) {
  6158. mg_printf(conn,
  6159. "%s: %s\r\n",
  6160. ri.http_headers[i].name,
  6161. ri.http_headers[i].value);
  6162. }
  6163. mg_write(conn, "\r\n", 2);
  6164. /* Send chunk of data that may have been read after the headers */
  6165. conn->num_bytes_sent +=
  6166. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6167. /* Read the rest of CGI output and send to the client */
  6168. send_file_data(conn, &fout, 0, INT64_MAX);
  6169. done:
  6170. mg_free(blk.var);
  6171. mg_free(blk.buf);
  6172. if (pid != (pid_t)-1) {
  6173. kill(pid, SIGKILL);
  6174. #if !defined(_WIN32)
  6175. {
  6176. int st;
  6177. while (waitpid(pid, &st, 0) != -1)
  6178. ; /* clean zombies */
  6179. }
  6180. #endif
  6181. }
  6182. if (fdin[0] != -1) {
  6183. close(fdin[0]);
  6184. }
  6185. if (fdout[1] != -1) {
  6186. close(fdout[1]);
  6187. }
  6188. if (in != NULL) {
  6189. fclose(in);
  6190. } else if (fdin[1] != -1) {
  6191. close(fdin[1]);
  6192. }
  6193. if (out != NULL) {
  6194. fclose(out);
  6195. } else if (fdout[0] != -1) {
  6196. close(fdout[0]);
  6197. }
  6198. if (err != NULL) {
  6199. fclose(err);
  6200. } else if (fderr[0] != -1) {
  6201. close(fderr[0]);
  6202. }
  6203. if (buf != NULL) {
  6204. mg_free(buf);
  6205. }
  6206. }
  6207. #endif /* !NO_CGI */
  6208. #if !defined(NO_FILES)
  6209. /* For a given PUT path, create all intermediate subdirectories.
  6210. * Return 0 if the path itself is a directory.
  6211. * Return 1 if the path leads to a file.
  6212. * Return -1 for if the path is too long.
  6213. * Return -2 if path can not be created.
  6214. */
  6215. static int
  6216. put_dir(struct mg_connection *conn, const char *path)
  6217. {
  6218. char buf[PATH_MAX];
  6219. const char *s, *p;
  6220. struct file file = STRUCT_FILE_INITIALIZER;
  6221. size_t len;
  6222. int res = 1;
  6223. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6224. len = (size_t)(p - path);
  6225. if (len >= sizeof(buf)) {
  6226. /* path too long */
  6227. res = -1;
  6228. break;
  6229. }
  6230. memcpy(buf, path, len);
  6231. buf[len] = '\0';
  6232. /* Try to create intermediate directory */
  6233. DEBUG_TRACE("mkdir(%s)", buf);
  6234. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  6235. /* path does not exixt and can not be created */
  6236. res = -2;
  6237. break;
  6238. }
  6239. /* Is path itself a directory? */
  6240. if (p[1] == '\0') {
  6241. res = 0;
  6242. }
  6243. }
  6244. return res;
  6245. }
  6246. static void
  6247. mkcol(struct mg_connection *conn, const char *path)
  6248. {
  6249. int rc, body_len;
  6250. struct de de;
  6251. char date[64];
  6252. time_t curtime = time(NULL);
  6253. if (conn == NULL) {
  6254. return;
  6255. }
  6256. /* TODO (mid): Check the send_http_error situations in this function */
  6257. memset(&de.file, 0, sizeof(de.file));
  6258. if (!mg_stat(conn, path, &de.file)) {
  6259. mg_cry(conn,
  6260. "%s: mg_stat(%s) failed: %s",
  6261. __func__,
  6262. path,
  6263. strerror(ERRNO));
  6264. }
  6265. if (de.file.last_modified) {
  6266. /* TODO (high): This check does not seem to make any sense ! */
  6267. send_http_error(
  6268. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6269. return;
  6270. }
  6271. body_len = conn->data_len - conn->request_len;
  6272. if (body_len > 0) {
  6273. send_http_error(
  6274. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6275. return;
  6276. }
  6277. rc = mg_mkdir(path, 0755);
  6278. if (rc == 0) {
  6279. conn->status_code = 201;
  6280. gmt_time_string(date, sizeof(date), &curtime);
  6281. mg_printf(conn,
  6282. "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: "
  6283. "0\r\nConnection: %s\r\n\r\n",
  6284. conn->status_code,
  6285. date,
  6286. suggest_connection_header(conn));
  6287. } else if (rc == -1) {
  6288. if (errno == EEXIST) {
  6289. send_http_error(
  6290. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6291. } else if (errno == EACCES) {
  6292. send_http_error(
  6293. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6294. } else if (errno == ENOENT) {
  6295. send_http_error(
  6296. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6297. } else {
  6298. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6299. }
  6300. }
  6301. }
  6302. static void
  6303. put_file(struct mg_connection *conn, const char *path)
  6304. {
  6305. struct file file = STRUCT_FILE_INITIALIZER;
  6306. const char *range;
  6307. int64_t r1, r2;
  6308. int rc;
  6309. char date[64];
  6310. time_t curtime = time(NULL);
  6311. if (conn == NULL) {
  6312. return;
  6313. }
  6314. if (mg_stat(conn, path, &file)) {
  6315. /* File already exists */
  6316. conn->status_code = 200;
  6317. if (file.is_directory) {
  6318. /* This is an already existing directory,
  6319. * so there is nothing to do for the server. */
  6320. rc = 0;
  6321. } else {
  6322. /* File exists and is not a directory. */
  6323. /* Can it be replaced? */
  6324. if (file.membuf != NULL) {
  6325. /* This is an "in-memory" file, that can not be replaced */
  6326. send_http_error(
  6327. conn,
  6328. 405,
  6329. "Error: Put not possible\nReplacing %s is not supported",
  6330. path);
  6331. return;
  6332. }
  6333. /* Check if the server may write this file */
  6334. if (access(path, W_OK) == 0) {
  6335. /* Access granted */
  6336. conn->status_code = 200;
  6337. rc = 1;
  6338. } else {
  6339. send_http_error(
  6340. conn,
  6341. 403,
  6342. "Error: Put not possible\nReplacing %s is not allowed",
  6343. path);
  6344. return;
  6345. }
  6346. }
  6347. } else {
  6348. /* File should be created */
  6349. conn->status_code = 201;
  6350. rc = put_dir(conn, path);
  6351. }
  6352. if (rc == 0) {
  6353. /* put_dir returns 0 if path is a directory */
  6354. gmt_time_string(date, sizeof(date), &curtime);
  6355. mg_printf(conn,
  6356. "HTTP/1.1 %d %s\r\n"
  6357. "Date: %s\r\n"
  6358. "Content-Length: 0\r\n"
  6359. "Connection: %s\r\n\r\n",
  6360. conn->status_code,
  6361. mg_get_response_code_text(conn->status_code, NULL),
  6362. date,
  6363. suggest_connection_header(conn));
  6364. /* Request to create a directory has been fulfilled successfully.
  6365. * No need to put a file. */
  6366. return;
  6367. }
  6368. if (rc == -1) {
  6369. /* put_dir returns -1 if the path is too long */
  6370. send_http_error(conn,
  6371. 414,
  6372. "Error: Path too long\nput_dir(%s): %s",
  6373. path,
  6374. strerror(ERRNO));
  6375. return;
  6376. }
  6377. if (rc == -2) {
  6378. /* put_dir returns -2 if the directory can not be created */
  6379. send_http_error(conn,
  6380. 500,
  6381. "Error: Can not create directory\nput_dir(%s): %s",
  6382. path,
  6383. strerror(ERRNO));
  6384. return;
  6385. }
  6386. /* A file should be created or overwritten. */
  6387. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6388. mg_fclose(&file);
  6389. send_http_error(conn,
  6390. 500,
  6391. "Error: Can not create file\nfopen(%s): %s",
  6392. path,
  6393. strerror(ERRNO));
  6394. return;
  6395. }
  6396. fclose_on_exec(&file, conn);
  6397. range = mg_get_header(conn, "Content-Range");
  6398. r1 = r2 = 0;
  6399. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6400. conn->status_code = 206; /* Partial content */
  6401. fseeko(file.fp, r1, SEEK_SET);
  6402. }
  6403. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6404. /* forward_body_data failed.
  6405. * The error code has already been sent to the client,
  6406. * and conn->status_code is already set. */
  6407. return;
  6408. }
  6409. gmt_time_string(date, sizeof(date), &curtime);
  6410. mg_printf(conn,
  6411. "HTTP/1.1 %d %s\r\n"
  6412. "Date: %s\r\n"
  6413. "Content-Length: 0\r\n"
  6414. "Connection: %s\r\n\r\n",
  6415. conn->status_code,
  6416. mg_get_response_code_text(conn->status_code, NULL),
  6417. date,
  6418. suggest_connection_header(conn));
  6419. mg_fclose(&file);
  6420. }
  6421. static void
  6422. delete_file(struct mg_connection *conn, const char *path)
  6423. {
  6424. struct de de;
  6425. memset(&de.file, 0, sizeof(de.file));
  6426. if (!mg_stat(conn, path, &de.file)) {
  6427. /* mg_stat returns 0 if the file does not exist */
  6428. send_http_error(conn,
  6429. 404,
  6430. "Error: Cannot delete file\nFile %s not found",
  6431. path);
  6432. return;
  6433. }
  6434. if (de.file.membuf != NULL) {
  6435. /* the file is cached in memory */
  6436. send_http_error(
  6437. conn,
  6438. 405,
  6439. "Error: Delete not possible\nDeleting %s is not supported",
  6440. path);
  6441. return;
  6442. }
  6443. if (de.file.is_directory) {
  6444. if (remove_directory(conn, path)) {
  6445. /* Delete is successful: Return 204 without content. */
  6446. send_http_error(conn, 204, "%s", "");
  6447. } else {
  6448. /* Delete is not successful: Return 500 (Server error). */
  6449. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6450. }
  6451. return;
  6452. }
  6453. /* This is an existing file (not a directory).
  6454. * Check if write permission is granted. */
  6455. if (access(path, W_OK) != 0) {
  6456. /* File is read only */
  6457. send_http_error(
  6458. conn,
  6459. 403,
  6460. "Error: Delete not possible\nDeleting %s is not allowed",
  6461. path);
  6462. return;
  6463. }
  6464. /* Try to delete it. */
  6465. if (mg_remove(path) == 0) {
  6466. /* Delete was successful: Return 204 without content. */
  6467. send_http_error(conn, 204, "%s", "");
  6468. } else {
  6469. /* Delete not successful (file locked). */
  6470. send_http_error(conn,
  6471. 423,
  6472. "Error: Cannot delete file\nremove(%s): %s",
  6473. path,
  6474. strerror(ERRNO));
  6475. }
  6476. }
  6477. #endif /* !NO_FILES */
  6478. static void
  6479. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6480. static void
  6481. do_ssi_include(struct mg_connection *conn,
  6482. const char *ssi,
  6483. char *tag,
  6484. int include_level)
  6485. {
  6486. char file_name[MG_BUF_LEN], path[512], *p;
  6487. struct file file = STRUCT_FILE_INITIALIZER;
  6488. size_t len;
  6489. int truncated = 0;
  6490. if (conn == NULL) {
  6491. return;
  6492. }
  6493. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6494. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6495. * always < MG_BUF_LEN. */
  6496. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6497. /* File name is relative to the webserver root */
  6498. file_name[511] = 0;
  6499. (void)mg_snprintf(conn,
  6500. &truncated,
  6501. path,
  6502. sizeof(path),
  6503. "%s/%s",
  6504. conn->ctx->config[DOCUMENT_ROOT],
  6505. file_name);
  6506. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6507. /* File name is relative to the webserver working directory
  6508. * or it is absolute system path */
  6509. file_name[511] = 0;
  6510. (void)
  6511. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6512. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6513. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6514. /* File name is relative to the currect document */
  6515. file_name[511] = 0;
  6516. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6517. if (!truncated) {
  6518. if ((p = strrchr(path, '/')) != NULL) {
  6519. p[1] = '\0';
  6520. }
  6521. len = strlen(path);
  6522. (void)mg_snprintf(conn,
  6523. &truncated,
  6524. path + len,
  6525. sizeof(path) - len,
  6526. "%s",
  6527. file_name);
  6528. }
  6529. } else {
  6530. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6531. return;
  6532. }
  6533. if (truncated) {
  6534. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6535. return;
  6536. }
  6537. if (!mg_fopen(conn, path, "rb", &file)) {
  6538. mg_cry(conn,
  6539. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6540. tag,
  6541. path,
  6542. strerror(ERRNO));
  6543. } else {
  6544. fclose_on_exec(&file, conn);
  6545. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6546. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6547. path) > 0) {
  6548. send_ssi_file(conn, path, &file, include_level + 1);
  6549. } else {
  6550. send_file_data(conn, &file, 0, INT64_MAX);
  6551. }
  6552. mg_fclose(&file);
  6553. }
  6554. }
  6555. #if !defined(NO_POPEN)
  6556. static void
  6557. do_ssi_exec(struct mg_connection *conn, char *tag)
  6558. {
  6559. char cmd[1024] = "";
  6560. struct file file = STRUCT_FILE_INITIALIZER;
  6561. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6562. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6563. } else {
  6564. cmd[1023] = 0;
  6565. if ((file.fp = popen(cmd, "r")) == NULL) {
  6566. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6567. } else {
  6568. send_file_data(conn, &file, 0, INT64_MAX);
  6569. pclose(file.fp);
  6570. }
  6571. }
  6572. }
  6573. #endif /* !NO_POPEN */
  6574. static int
  6575. mg_fgetc(struct file *filep, int offset)
  6576. {
  6577. if (filep == NULL) {
  6578. return EOF;
  6579. }
  6580. if (filep->membuf != NULL && offset >= 0
  6581. && ((unsigned int)(offset)) < filep->size) {
  6582. return ((unsigned char *)filep->membuf)[offset];
  6583. } else if (filep->fp != NULL) {
  6584. return fgetc(filep->fp);
  6585. } else {
  6586. return EOF;
  6587. }
  6588. }
  6589. static void
  6590. send_ssi_file(struct mg_connection *conn,
  6591. const char *path,
  6592. struct file *filep,
  6593. int include_level)
  6594. {
  6595. char buf[MG_BUF_LEN];
  6596. int ch, offset, len, in_ssi_tag;
  6597. if (include_level > 10) {
  6598. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6599. return;
  6600. }
  6601. in_ssi_tag = len = offset = 0;
  6602. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6603. if (in_ssi_tag && ch == '>') {
  6604. in_ssi_tag = 0;
  6605. buf[len++] = (char)ch;
  6606. buf[len] = '\0';
  6607. /* assert(len <= (int) sizeof(buf)); */
  6608. if (len > (int)sizeof(buf)) {
  6609. break;
  6610. }
  6611. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6612. /* Not an SSI tag, pass it */
  6613. (void)mg_write(conn, buf, (size_t)len);
  6614. } else {
  6615. if (!memcmp(buf + 5, "include", 7)) {
  6616. do_ssi_include(conn, path, buf + 12, include_level);
  6617. #if !defined(NO_POPEN)
  6618. } else if (!memcmp(buf + 5, "exec", 4)) {
  6619. do_ssi_exec(conn, buf + 9);
  6620. #endif /* !NO_POPEN */
  6621. } else {
  6622. mg_cry(conn,
  6623. "%s: unknown SSI "
  6624. "command: \"%s\"",
  6625. path,
  6626. buf);
  6627. }
  6628. }
  6629. len = 0;
  6630. } else if (in_ssi_tag) {
  6631. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6632. /* Not an SSI tag */
  6633. in_ssi_tag = 0;
  6634. } else if (len == (int)sizeof(buf) - 2) {
  6635. mg_cry(conn, "%s: SSI tag is too large", path);
  6636. len = 0;
  6637. }
  6638. buf[len++] = (char)(ch & 0xff);
  6639. } else if (ch == '<') {
  6640. in_ssi_tag = 1;
  6641. if (len > 0) {
  6642. mg_write(conn, buf, (size_t)len);
  6643. }
  6644. len = 0;
  6645. buf[len++] = (char)(ch & 0xff);
  6646. } else {
  6647. buf[len++] = (char)(ch & 0xff);
  6648. if (len == (int)sizeof(buf)) {
  6649. mg_write(conn, buf, (size_t)len);
  6650. len = 0;
  6651. }
  6652. }
  6653. }
  6654. /* Send the rest of buffered data */
  6655. if (len > 0) {
  6656. mg_write(conn, buf, (size_t)len);
  6657. }
  6658. }
  6659. static void
  6660. handle_ssi_file_request(struct mg_connection *conn,
  6661. const char *path,
  6662. struct file *filep)
  6663. {
  6664. char date[64];
  6665. time_t curtime = time(NULL);
  6666. const char *cors1, *cors2, *cors3;
  6667. if (conn == NULL || path == NULL || filep == NULL) {
  6668. return;
  6669. }
  6670. if (mg_get_header(conn, "Origin")) {
  6671. /* Cross-origin resource sharing (CORS). */
  6672. cors1 = "Access-Control-Allow-Origin: ";
  6673. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6674. cors3 = "\r\n";
  6675. } else {
  6676. cors1 = cors2 = cors3 = "";
  6677. }
  6678. if (!mg_fopen(conn, path, "rb", filep)) {
  6679. /* File exists (precondition for calling this function),
  6680. * but can not be opened by the server. */
  6681. send_http_error(conn,
  6682. 500,
  6683. "Error: Cannot read file\nfopen(%s): %s",
  6684. path,
  6685. strerror(ERRNO));
  6686. } else {
  6687. conn->must_close = 1;
  6688. gmt_time_string(date, sizeof(date), &curtime);
  6689. fclose_on_exec(filep, conn);
  6690. mg_printf(conn,
  6691. "HTTP/1.1 200 OK\r\n"
  6692. "%s%s%s"
  6693. "Date: %s\r\n"
  6694. "Content-Type: text/html\r\n"
  6695. "Connection: %s\r\n\r\n",
  6696. cors1,
  6697. cors2,
  6698. cors3,
  6699. date,
  6700. suggest_connection_header(conn));
  6701. send_ssi_file(conn, path, filep, 0);
  6702. mg_fclose(filep);
  6703. }
  6704. }
  6705. #if !defined(NO_FILES)
  6706. static void
  6707. send_options(struct mg_connection *conn)
  6708. {
  6709. char date[64];
  6710. time_t curtime = time(NULL);
  6711. if (!conn) {
  6712. return;
  6713. }
  6714. conn->status_code = 200;
  6715. conn->must_close = 1;
  6716. gmt_time_string(date, sizeof(date), &curtime);
  6717. mg_printf(conn,
  6718. "HTTP/1.1 200 OK\r\n"
  6719. "Date: %s\r\n"
  6720. "Connection: %s\r\n"
  6721. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6722. "PROPFIND, MKCOL\r\n"
  6723. "DAV: 1\r\n\r\n",
  6724. date,
  6725. suggest_connection_header(conn));
  6726. }
  6727. /* Writes PROPFIND properties for a collection element */
  6728. static void
  6729. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  6730. {
  6731. char mtime[64];
  6732. if (conn == NULL || uri == NULL || filep == NULL) {
  6733. return;
  6734. }
  6735. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  6736. conn->num_bytes_sent +=
  6737. mg_printf(conn,
  6738. "<d:response>"
  6739. "<d:href>%s</d:href>"
  6740. "<d:propstat>"
  6741. "<d:prop>"
  6742. "<d:resourcetype>%s</d:resourcetype>"
  6743. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  6744. "<d:getlastmodified>%s</d:getlastmodified>"
  6745. "</d:prop>"
  6746. "<d:status>HTTP/1.1 200 OK</d:status>"
  6747. "</d:propstat>"
  6748. "</d:response>\n",
  6749. uri,
  6750. filep->is_directory ? "<d:collection/>" : "",
  6751. filep->size,
  6752. mtime);
  6753. }
  6754. static void
  6755. print_dav_dir_entry(struct de *de, void *data)
  6756. {
  6757. char href[PATH_MAX];
  6758. char href_encoded[PATH_MAX];
  6759. int truncated;
  6760. struct mg_connection *conn = (struct mg_connection *)data;
  6761. if (!de || !conn) {
  6762. return;
  6763. }
  6764. mg_snprintf(conn,
  6765. &truncated,
  6766. href,
  6767. sizeof(href),
  6768. "%s%s",
  6769. conn->request_info.local_uri,
  6770. de->file_name);
  6771. if (!truncated) {
  6772. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  6773. print_props(conn, href_encoded, &de->file);
  6774. }
  6775. }
  6776. static void
  6777. handle_propfind(struct mg_connection *conn,
  6778. const char *path,
  6779. struct file *filep)
  6780. {
  6781. const char *depth = mg_get_header(conn, "Depth");
  6782. char date[64];
  6783. time_t curtime = time(NULL);
  6784. gmt_time_string(date, sizeof(date), &curtime);
  6785. if (!conn || !path || !filep) {
  6786. return;
  6787. }
  6788. conn->must_close = 1;
  6789. conn->status_code = 207;
  6790. mg_printf(conn,
  6791. "HTTP/1.1 207 Multi-Status\r\n"
  6792. "Date: %s\r\n"
  6793. "Connection: %s\r\n"
  6794. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  6795. date,
  6796. suggest_connection_header(conn));
  6797. conn->num_bytes_sent +=
  6798. mg_printf(conn,
  6799. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  6800. "<d:multistatus xmlns:d='DAV:'>\n");
  6801. /* Print properties for the requested resource itself */
  6802. print_props(conn, conn->request_info.local_uri, filep);
  6803. /* If it is a directory, print directory entries too if Depth is not 0 */
  6804. if (filep && conn->ctx && filep->is_directory
  6805. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  6806. && (depth == NULL || strcmp(depth, "0") != 0)) {
  6807. scan_directory(conn, path, conn, &print_dav_dir_entry);
  6808. }
  6809. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  6810. }
  6811. #endif
  6812. void
  6813. mg_lock_connection(struct mg_connection *conn)
  6814. {
  6815. if (conn) {
  6816. (void)pthread_mutex_lock(&conn->mutex);
  6817. }
  6818. }
  6819. void
  6820. mg_unlock_connection(struct mg_connection *conn)
  6821. {
  6822. if (conn) {
  6823. (void)pthread_mutex_unlock(&conn->mutex);
  6824. }
  6825. }
  6826. void
  6827. mg_lock_context(struct mg_context *ctx)
  6828. {
  6829. if (ctx) {
  6830. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  6831. }
  6832. }
  6833. void
  6834. mg_unlock_context(struct mg_context *ctx)
  6835. {
  6836. if (ctx) {
  6837. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  6838. }
  6839. }
  6840. #if defined(USE_TIMERS)
  6841. #include "timer.inl"
  6842. #endif /* USE_TIMERS */
  6843. #ifdef USE_LUA
  6844. #include "mod_lua.inl"
  6845. #endif /* USE_LUA */
  6846. #ifdef USE_DUKTAPE
  6847. #include "mod_duktape.inl"
  6848. #endif /* USE_DUKTAPE */
  6849. #if defined(USE_WEBSOCKET)
  6850. /* START OF SHA-1 code
  6851. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  6852. #define SHA1HANDSOFF
  6853. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  6854. *
  6855. * #if defined(__sun)
  6856. * #include "solarisfixes.h"
  6857. * #endif
  6858. */
  6859. static int
  6860. is_big_endian(void)
  6861. {
  6862. static const int n = 1;
  6863. return ((char *)&n)[0] == 0;
  6864. }
  6865. union char64long16 {
  6866. unsigned char c[64];
  6867. uint32_t l[16];
  6868. };
  6869. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6870. static uint32_t
  6871. blk0(union char64long16 *block, int i)
  6872. {
  6873. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  6874. if (!is_big_endian()) {
  6875. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  6876. | (rol(block->l[i], 8) & 0x00FF00FF);
  6877. }
  6878. return block->l[i];
  6879. }
  6880. #define blk(i) \
  6881. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  6882. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6883. 1))
  6884. #define R0(v, w, x, y, z, i) \
  6885. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6886. w = rol(w, 30);
  6887. #define R1(v, w, x, y, z, i) \
  6888. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6889. w = rol(w, 30);
  6890. #define R2(v, w, x, y, z, i) \
  6891. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6892. w = rol(w, 30);
  6893. #define R3(v, w, x, y, z, i) \
  6894. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6895. w = rol(w, 30);
  6896. #define R4(v, w, x, y, z, i) \
  6897. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6898. w = rol(w, 30);
  6899. typedef struct {
  6900. uint32_t state[5];
  6901. uint32_t count[2];
  6902. unsigned char buffer[64];
  6903. } SHA1_CTX;
  6904. static void
  6905. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  6906. {
  6907. uint32_t a, b, c, d, e;
  6908. union char64long16 block[1];
  6909. memcpy(block, buffer, 64);
  6910. a = state[0];
  6911. b = state[1];
  6912. c = state[2];
  6913. d = state[3];
  6914. e = state[4];
  6915. R0(a, b, c, d, e, 0);
  6916. R0(e, a, b, c, d, 1);
  6917. R0(d, e, a, b, c, 2);
  6918. R0(c, d, e, a, b, 3);
  6919. R0(b, c, d, e, a, 4);
  6920. R0(a, b, c, d, e, 5);
  6921. R0(e, a, b, c, d, 6);
  6922. R0(d, e, a, b, c, 7);
  6923. R0(c, d, e, a, b, 8);
  6924. R0(b, c, d, e, a, 9);
  6925. R0(a, b, c, d, e, 10);
  6926. R0(e, a, b, c, d, 11);
  6927. R0(d, e, a, b, c, 12);
  6928. R0(c, d, e, a, b, 13);
  6929. R0(b, c, d, e, a, 14);
  6930. R0(a, b, c, d, e, 15);
  6931. R1(e, a, b, c, d, 16);
  6932. R1(d, e, a, b, c, 17);
  6933. R1(c, d, e, a, b, 18);
  6934. R1(b, c, d, e, a, 19);
  6935. R2(a, b, c, d, e, 20);
  6936. R2(e, a, b, c, d, 21);
  6937. R2(d, e, a, b, c, 22);
  6938. R2(c, d, e, a, b, 23);
  6939. R2(b, c, d, e, a, 24);
  6940. R2(a, b, c, d, e, 25);
  6941. R2(e, a, b, c, d, 26);
  6942. R2(d, e, a, b, c, 27);
  6943. R2(c, d, e, a, b, 28);
  6944. R2(b, c, d, e, a, 29);
  6945. R2(a, b, c, d, e, 30);
  6946. R2(e, a, b, c, d, 31);
  6947. R2(d, e, a, b, c, 32);
  6948. R2(c, d, e, a, b, 33);
  6949. R2(b, c, d, e, a, 34);
  6950. R2(a, b, c, d, e, 35);
  6951. R2(e, a, b, c, d, 36);
  6952. R2(d, e, a, b, c, 37);
  6953. R2(c, d, e, a, b, 38);
  6954. R2(b, c, d, e, a, 39);
  6955. R3(a, b, c, d, e, 40);
  6956. R3(e, a, b, c, d, 41);
  6957. R3(d, e, a, b, c, 42);
  6958. R3(c, d, e, a, b, 43);
  6959. R3(b, c, d, e, a, 44);
  6960. R3(a, b, c, d, e, 45);
  6961. R3(e, a, b, c, d, 46);
  6962. R3(d, e, a, b, c, 47);
  6963. R3(c, d, e, a, b, 48);
  6964. R3(b, c, d, e, a, 49);
  6965. R3(a, b, c, d, e, 50);
  6966. R3(e, a, b, c, d, 51);
  6967. R3(d, e, a, b, c, 52);
  6968. R3(c, d, e, a, b, 53);
  6969. R3(b, c, d, e, a, 54);
  6970. R3(a, b, c, d, e, 55);
  6971. R3(e, a, b, c, d, 56);
  6972. R3(d, e, a, b, c, 57);
  6973. R3(c, d, e, a, b, 58);
  6974. R3(b, c, d, e, a, 59);
  6975. R4(a, b, c, d, e, 60);
  6976. R4(e, a, b, c, d, 61);
  6977. R4(d, e, a, b, c, 62);
  6978. R4(c, d, e, a, b, 63);
  6979. R4(b, c, d, e, a, 64);
  6980. R4(a, b, c, d, e, 65);
  6981. R4(e, a, b, c, d, 66);
  6982. R4(d, e, a, b, c, 67);
  6983. R4(c, d, e, a, b, 68);
  6984. R4(b, c, d, e, a, 69);
  6985. R4(a, b, c, d, e, 70);
  6986. R4(e, a, b, c, d, 71);
  6987. R4(d, e, a, b, c, 72);
  6988. R4(c, d, e, a, b, 73);
  6989. R4(b, c, d, e, a, 74);
  6990. R4(a, b, c, d, e, 75);
  6991. R4(e, a, b, c, d, 76);
  6992. R4(d, e, a, b, c, 77);
  6993. R4(c, d, e, a, b, 78);
  6994. R4(b, c, d, e, a, 79);
  6995. state[0] += a;
  6996. state[1] += b;
  6997. state[2] += c;
  6998. state[3] += d;
  6999. state[4] += e;
  7000. a = b = c = d = e = 0;
  7001. memset(block, '\0', sizeof(block));
  7002. }
  7003. static void
  7004. SHA1Init(SHA1_CTX *context)
  7005. {
  7006. context->state[0] = 0x67452301;
  7007. context->state[1] = 0xEFCDAB89;
  7008. context->state[2] = 0x98BADCFE;
  7009. context->state[3] = 0x10325476;
  7010. context->state[4] = 0xC3D2E1F0;
  7011. context->count[0] = context->count[1] = 0;
  7012. }
  7013. static void
  7014. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7015. {
  7016. uint32_t i, j;
  7017. j = context->count[0];
  7018. if ((context->count[0] += len << 3) < j) {
  7019. context->count[1]++;
  7020. }
  7021. context->count[1] += (len >> 29);
  7022. j = (j >> 3) & 63;
  7023. if ((j + len) > 63) {
  7024. memcpy(&context->buffer[j], data, (i = 64 - j));
  7025. SHA1Transform(context->state, context->buffer);
  7026. for (; i + 63 < len; i += 64) {
  7027. SHA1Transform(context->state, &data[i]);
  7028. }
  7029. j = 0;
  7030. } else
  7031. i = 0;
  7032. memcpy(&context->buffer[j], &data[i], len - i);
  7033. }
  7034. static void
  7035. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7036. {
  7037. unsigned i;
  7038. unsigned char finalcount[8], c;
  7039. for (i = 0; i < 8; i++) {
  7040. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7041. >> ((3 - (i & 3)) * 8)) & 255);
  7042. }
  7043. c = 0200;
  7044. SHA1Update(context, &c, 1);
  7045. while ((context->count[0] & 504) != 448) {
  7046. c = 0000;
  7047. SHA1Update(context, &c, 1);
  7048. }
  7049. SHA1Update(context, finalcount, 8);
  7050. for (i = 0; i < 20; i++) {
  7051. digest[i] = (unsigned char)((context->state[i >> 2]
  7052. >> ((3 - (i & 3)) * 8)) & 255);
  7053. }
  7054. memset(context, '\0', sizeof(*context));
  7055. memset(&finalcount, '\0', sizeof(finalcount));
  7056. }
  7057. /* END OF SHA1 CODE */
  7058. static int
  7059. send_websocket_handshake(struct mg_connection *conn)
  7060. {
  7061. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7062. const char *protocol = NULL;
  7063. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7064. SHA1_CTX sha_ctx;
  7065. int truncated;
  7066. mg_snprintf(conn,
  7067. &truncated,
  7068. buf,
  7069. sizeof(buf),
  7070. "%s%s",
  7071. mg_get_header(conn, "Sec-WebSocket-Key"),
  7072. magic);
  7073. if (truncated) {
  7074. conn->must_close = 1;
  7075. return 0;
  7076. }
  7077. SHA1Init(&sha_ctx);
  7078. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7079. SHA1Final((unsigned char *)sha, &sha_ctx);
  7080. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7081. mg_printf(conn,
  7082. "HTTP/1.1 101 Switching Protocols\r\n"
  7083. "Upgrade: websocket\r\n"
  7084. "Connection: Upgrade\r\n"
  7085. "Sec-WebSocket-Accept: %s\r\n",
  7086. b64_sha);
  7087. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7088. if (protocol) {
  7089. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7090. } else {
  7091. mg_printf(conn, "%s", "\r\n");
  7092. }
  7093. return 1;
  7094. }
  7095. static void
  7096. read_websocket(struct mg_connection *conn,
  7097. mg_websocket_data_handler ws_data_handler,
  7098. void *callback_data)
  7099. {
  7100. /* Pointer to the beginning of the portion of the incoming websocket
  7101. * message queue.
  7102. * The original websocket upgrade request is never removed, so the queue
  7103. * begins after it. */
  7104. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7105. int n, error, exit_by_callback;
  7106. /* body_len is the length of the entire queue in bytes
  7107. * len is the length of the current message
  7108. * data_len is the length of the current message's data payload
  7109. * header_len is the length of the current message's header */
  7110. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7111. /* "The masking key is a 32-bit value chosen at random by the client."
  7112. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7113. */
  7114. unsigned char mask[4];
  7115. /* data points to the place where the message is stored when passed to the
  7116. * websocket_data callback. This is either mem on the stack, or a
  7117. * dynamically allocated buffer if it is too large. */
  7118. char mem[4096];
  7119. char *data = mem;
  7120. unsigned char mop; /* mask flag and opcode */
  7121. double timeout = -1.0;
  7122. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7123. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7124. }
  7125. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7126. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7127. }
  7128. mg_set_thread_name("wsock");
  7129. /* Loop continuously, reading messages from the socket, invoking the
  7130. * callback, and waiting repeatedly until an error occurs. */
  7131. while (!conn->ctx->stop_flag) {
  7132. header_len = 0;
  7133. assert(conn->data_len >= conn->request_len);
  7134. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7135. len = buf[1] & 127;
  7136. mask_len = buf[1] & 128 ? 4 : 0;
  7137. if (len < 126 && body_len >= mask_len) {
  7138. data_len = len;
  7139. header_len = 2 + mask_len;
  7140. } else if (len == 126 && body_len >= 4 + mask_len) {
  7141. header_len = 4 + mask_len;
  7142. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7143. } else if (body_len >= 10 + mask_len) {
  7144. header_len = 10 + mask_len;
  7145. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7146. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7147. }
  7148. }
  7149. if (header_len > 0 && body_len >= header_len) {
  7150. /* Allocate space to hold websocket payload */
  7151. data = mem;
  7152. if (data_len > sizeof(mem)) {
  7153. data = (char *)mg_malloc(data_len);
  7154. if (data == NULL) {
  7155. /* Allocation failed, exit the loop and then close the
  7156. * connection */
  7157. mg_cry(conn, "websocket out of memory; closing connection");
  7158. break;
  7159. }
  7160. }
  7161. /* Copy the mask before we shift the queue and destroy it */
  7162. if (mask_len > 0) {
  7163. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7164. } else {
  7165. memset(mask, 0, sizeof(mask));
  7166. }
  7167. /* Read frame payload from the first message in the queue into
  7168. * data and advance the queue by moving the memory in place. */
  7169. assert(body_len >= header_len);
  7170. if (data_len + header_len > body_len) {
  7171. mop = buf[0]; /* current mask and opcode */
  7172. /* Overflow case */
  7173. len = body_len - header_len;
  7174. memcpy(data, buf + header_len, len);
  7175. error = 0;
  7176. while (len < data_len) {
  7177. n = pull(
  7178. NULL, conn, data + len, (int)(data_len - len), timeout);
  7179. if (n <= 0) {
  7180. error = 1;
  7181. break;
  7182. }
  7183. len += (size_t)n;
  7184. }
  7185. if (error) {
  7186. mg_cry(conn, "Websocket pull failed; closing connection");
  7187. break;
  7188. }
  7189. conn->data_len = conn->request_len;
  7190. } else {
  7191. mop = buf[0]; /* current mask and opcode, overwritten by
  7192. * memmove() */
  7193. /* Length of the message being read at the front of the
  7194. * queue */
  7195. len = data_len + header_len;
  7196. /* Copy the data payload into the data pointer for the
  7197. * callback */
  7198. memcpy(data, buf + header_len, data_len);
  7199. /* Move the queue forward len bytes */
  7200. memmove(buf, buf + len, body_len - len);
  7201. /* Mark the queue as advanced */
  7202. conn->data_len -= (int)len;
  7203. }
  7204. /* Apply mask if necessary */
  7205. if (mask_len > 0) {
  7206. for (i = 0; i < data_len; ++i) {
  7207. data[i] ^= mask[i & 3];
  7208. }
  7209. }
  7210. /* Exit the loop if callback signals to exit (server side),
  7211. * or "connection close" opcode received (client side). */
  7212. exit_by_callback = 0;
  7213. if ((ws_data_handler != NULL)
  7214. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7215. exit_by_callback = 1;
  7216. }
  7217. if (data != mem) {
  7218. mg_free(data);
  7219. }
  7220. if (exit_by_callback
  7221. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7222. /* Opcode == 8, connection close */
  7223. break;
  7224. }
  7225. /* Not breaking the loop, process next websocket frame. */
  7226. } else {
  7227. /* Read from the socket into the next available location in the
  7228. * message queue. */
  7229. if ((n = pull(NULL,
  7230. conn,
  7231. conn->buf + conn->data_len,
  7232. conn->buf_size - conn->data_len,
  7233. timeout)) <= 0) {
  7234. /* Error, no bytes read */
  7235. break;
  7236. }
  7237. conn->data_len += n;
  7238. }
  7239. }
  7240. mg_set_thread_name("worker");
  7241. }
  7242. static int
  7243. mg_websocket_write_exec(struct mg_connection *conn,
  7244. int opcode,
  7245. const char *data,
  7246. size_t dataLen,
  7247. uint32_t masking_key)
  7248. {
  7249. unsigned char header[14];
  7250. size_t headerLen = 1;
  7251. int retval = -1;
  7252. header[0] = 0x80 + (opcode & 0xF);
  7253. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7254. if (dataLen < 126) {
  7255. /* inline 7-bit length field */
  7256. header[1] = (unsigned char)dataLen;
  7257. headerLen = 2;
  7258. } else if (dataLen <= 0xFFFF) {
  7259. /* 16-bit length field */
  7260. header[1] = 126;
  7261. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7262. headerLen = 4;
  7263. } else {
  7264. /* 64-bit length field */
  7265. header[1] = 127;
  7266. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7267. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7268. headerLen = 10;
  7269. }
  7270. if (masking_key) {
  7271. /* add mask */
  7272. header[1] |= 0x80;
  7273. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7274. headerLen += 4;
  7275. }
  7276. /* Note that POSIX/Winsock's send() is threadsafe
  7277. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7278. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7279. * push(), although that is only a problem if the packet is large or
  7280. * outgoing buffer is full). */
  7281. (void)mg_lock_connection(conn);
  7282. retval = mg_write(conn, header, headerLen);
  7283. if (dataLen > 0) {
  7284. retval = mg_write(conn, data, dataLen);
  7285. }
  7286. mg_unlock_connection(conn);
  7287. return retval;
  7288. }
  7289. int
  7290. mg_websocket_write(struct mg_connection *conn,
  7291. int opcode,
  7292. const char *data,
  7293. size_t dataLen)
  7294. {
  7295. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7296. }
  7297. static void
  7298. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7299. {
  7300. size_t i = 0;
  7301. i = 0;
  7302. if (((ptrdiff_t)in % 4) == 0) {
  7303. /* Convert in 32 bit words, if data is 4 byte aligned */
  7304. while (i < (in_len - 3)) {
  7305. *(uint32_t *)(void *)(out + i) =
  7306. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7307. i += 4;
  7308. }
  7309. }
  7310. if (i != in_len) {
  7311. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7312. while (i < in_len) {
  7313. *(uint8_t *)(void *)(out + i) =
  7314. *(uint8_t *)(void *)(in + i)
  7315. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7316. i++;
  7317. }
  7318. }
  7319. }
  7320. int
  7321. mg_websocket_client_write(struct mg_connection *conn,
  7322. int opcode,
  7323. const char *data,
  7324. size_t dataLen)
  7325. {
  7326. int retval = -1;
  7327. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7328. uint32_t masking_key = (uint32_t)get_random();
  7329. if (masked_data == NULL) {
  7330. /* Return -1 in an error case */
  7331. mg_cry(conn,
  7332. "Cannot allocate buffer for masked websocket response: "
  7333. "Out of memory");
  7334. return -1;
  7335. }
  7336. mask_data(data, dataLen, masking_key, masked_data);
  7337. retval = mg_websocket_write_exec(
  7338. conn, opcode, masked_data, dataLen, masking_key);
  7339. mg_free(masked_data);
  7340. return retval;
  7341. }
  7342. static void
  7343. handle_websocket_request(struct mg_connection *conn,
  7344. const char *path,
  7345. int is_callback_resource,
  7346. mg_websocket_connect_handler ws_connect_handler,
  7347. mg_websocket_ready_handler ws_ready_handler,
  7348. mg_websocket_data_handler ws_data_handler,
  7349. mg_websocket_close_handler ws_close_handler,
  7350. void *cbData)
  7351. {
  7352. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7353. int lua_websock = 0;
  7354. #if !defined(USE_LUA)
  7355. (void)path;
  7356. #endif
  7357. /* Step 1: Check websocket protocol version. */
  7358. if (version == NULL || strcmp(version, "13") != 0) {
  7359. /* Reject wrong versions */
  7360. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7361. return;
  7362. }
  7363. /* Step 2: If a callback is responsible, call it. */
  7364. if (is_callback_resource) {
  7365. if (ws_connect_handler != NULL
  7366. && ws_connect_handler(conn, cbData) != 0) {
  7367. /* C callback has returned non-zero, do not proceed with handshake.
  7368. */
  7369. /* Note that C callbacks are no longer called when Lua is
  7370. * responsible, so C can no longer filter callbacks for Lua. */
  7371. return;
  7372. }
  7373. }
  7374. #if defined(USE_LUA)
  7375. /* Step 3: No callback. Check if Lua is responsible. */
  7376. else {
  7377. /* Step 3.1: Check if Lua is responsible. */
  7378. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7379. lua_websock =
  7380. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7381. strlen(
  7382. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7383. path);
  7384. }
  7385. if (lua_websock) {
  7386. /* Step 3.2: Lua is responsible: call it. */
  7387. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7388. if (!conn->lua_websocket_state) {
  7389. /* Lua rejected the new client */
  7390. return;
  7391. }
  7392. }
  7393. }
  7394. #endif
  7395. /* Step 4: Check if there is a responsible websocket handler. */
  7396. if (!is_callback_resource && !lua_websock) {
  7397. /* There is no callback, an Lua is not responsible either. */
  7398. /* Reply with a 404 Not Found or with nothing at all?
  7399. * TODO (mid): check the websocket standards, how to reply to
  7400. * requests to invalid websocket addresses. */
  7401. send_http_error(conn, 404, "%s", "Not found");
  7402. return;
  7403. }
  7404. /* Step 5: The websocket connection has been accepted */
  7405. if (!send_websocket_handshake(conn)) {
  7406. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7407. return;
  7408. }
  7409. /* Step 6: Call the ready handler */
  7410. if (is_callback_resource) {
  7411. if (ws_ready_handler != NULL) {
  7412. ws_ready_handler(conn, cbData);
  7413. }
  7414. #if defined(USE_LUA)
  7415. } else if (lua_websock) {
  7416. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7417. /* the ready handler returned false */
  7418. return;
  7419. }
  7420. #endif
  7421. }
  7422. /* Step 7: Enter the read loop */
  7423. if (is_callback_resource) {
  7424. read_websocket(conn, ws_data_handler, cbData);
  7425. #if defined(USE_LUA)
  7426. } else if (lua_websock) {
  7427. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7428. #endif
  7429. }
  7430. /* Step 8: Call the close handler */
  7431. if (ws_close_handler) {
  7432. ws_close_handler(conn, cbData);
  7433. }
  7434. }
  7435. static int
  7436. is_websocket_protocol(const struct mg_connection *conn)
  7437. {
  7438. const char *host, *upgrade, *connection, *version, *key;
  7439. upgrade = mg_get_header(conn, "Upgrade");
  7440. if (upgrade == NULL) {
  7441. return 0; /* fail early, don't waste time checking other header fields
  7442. */
  7443. }
  7444. if (!mg_strcasestr(upgrade, "websocket")) {
  7445. return 0;
  7446. }
  7447. connection = mg_get_header(conn, "Connection");
  7448. if (connection == NULL) {
  7449. return 0;
  7450. }
  7451. if (!mg_strcasestr(connection, "upgrade")) {
  7452. return 0;
  7453. }
  7454. host = mg_get_header(conn, "Host");
  7455. key = mg_get_header(conn, "Sec-WebSocket-Key");
  7456. version = mg_get_header(conn, "Sec-WebSocket-Version");
  7457. return (host != NULL && key != NULL && version != NULL);
  7458. }
  7459. #endif /* !USE_WEBSOCKET */
  7460. static int
  7461. isbyte(int n)
  7462. {
  7463. return n >= 0 && n <= 255;
  7464. }
  7465. static int
  7466. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7467. {
  7468. int n, a, b, c, d, slash = 32, len = 0;
  7469. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7470. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7471. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7472. && slash < 33) {
  7473. len = n;
  7474. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7475. | (uint32_t)d;
  7476. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7477. }
  7478. return len;
  7479. }
  7480. static int
  7481. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7482. {
  7483. int throttle = 0;
  7484. struct vec vec, val;
  7485. uint32_t net, mask;
  7486. char mult;
  7487. double v;
  7488. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7489. mult = ',';
  7490. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7491. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7492. && mult != ',')) {
  7493. continue;
  7494. }
  7495. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7496. : 1;
  7497. if (vec.len == 1 && vec.ptr[0] == '*') {
  7498. throttle = (int)v;
  7499. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7500. if ((remote_ip & mask) == net) {
  7501. throttle = (int)v;
  7502. }
  7503. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7504. throttle = (int)v;
  7505. }
  7506. }
  7507. return throttle;
  7508. }
  7509. static uint32_t
  7510. get_remote_ip(const struct mg_connection *conn)
  7511. {
  7512. if (!conn) {
  7513. return 0;
  7514. }
  7515. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7516. }
  7517. int
  7518. mg_upload(struct mg_connection *conn, const char *destination_dir)
  7519. {
  7520. /* TODO (high): completely rewrite this function. See issue #180. */
  7521. /* TODO (mid): set a timeout */
  7522. const char *content_type_header, *boundary_start, *sc;
  7523. char *s;
  7524. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX];
  7525. char fname[1024], boundary[100];
  7526. FILE *fp;
  7527. int bl, n, i, headers_len, boundary_len, eof, truncated;
  7528. int len = 0, num_uploaded_files = 0;
  7529. struct mg_request_info part_request_info;
  7530. /* Request looks like this:
  7531. *
  7532. * POST /upload HTTP/1.1
  7533. * Host: 127.0.0.1:8080
  7534. * Content-Length: 244894
  7535. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  7536. *
  7537. * ------WebKitFormBoundaryRVr
  7538. * Content-Disposition: form-data; name="file"; filename="accum.png"
  7539. * Content-Type: image/png
  7540. *
  7541. * <89>PNG
  7542. * <PNG DATA>
  7543. * ------WebKitFormBoundaryRVr */
  7544. /* Extract boundary string from the Content-Type header */
  7545. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL
  7546. || (boundary_start = mg_strcasestr(content_type_header, "boundary="))
  7547. == NULL
  7548. || (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0
  7549. && sscanf(boundary_start, "boundary=%99s", boundary) == 0)
  7550. || boundary[0] == '\0') {
  7551. return num_uploaded_files;
  7552. }
  7553. boundary[99] = 0;
  7554. boundary_len = (int)strlen(boundary);
  7555. bl = boundary_len + 4; /* \r\n--<boundary> */
  7556. for (;;) {
  7557. /* Pull in headers */
  7558. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  7559. if ((len < 0) || (len > (int)sizeof(buf))) {
  7560. break;
  7561. }
  7562. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  7563. len += n;
  7564. /* assert(len <= (int) sizeof(buf)); */
  7565. if (len > (int)sizeof(buf)) {
  7566. break;
  7567. }
  7568. }
  7569. if ((headers_len = get_request_len(buf, len)) <= 0) {
  7570. break;
  7571. }
  7572. /* terminate header */
  7573. buf[headers_len - 1] = 0;
  7574. /* Scan for the boundary string and skip it */
  7575. if (buf[0] == '-' && buf[1] == '-'
  7576. && !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  7577. s = &buf[bl];
  7578. } else {
  7579. s = &buf[2];
  7580. }
  7581. /* Get headers for this part of the multipart message */
  7582. memset(&part_request_info, 0, sizeof(part_request_info));
  7583. parse_http_headers(&s, &part_request_info);
  7584. /* assert(&buf[headers_len-1] == s); */
  7585. if (&buf[headers_len - 1] != s) {
  7586. break;
  7587. }
  7588. /* Fetch file name. */
  7589. sc = get_header(&part_request_info, "Content-Disposition");
  7590. if (!sc) {
  7591. /* invalid part of a multipart message */
  7592. break;
  7593. }
  7594. sc = strstr(sc, "filename");
  7595. if (!sc) {
  7596. /* no filename set */
  7597. break;
  7598. }
  7599. sc += 8; /* skip "filename" */
  7600. fname[0] = '\0';
  7601. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  7602. fname[1023] = 0;
  7603. /* Give up if the headers are not what we expect */
  7604. if (fname[0] == '\0') {
  7605. break;
  7606. }
  7607. /* Construct destination file name. Do not allow paths to have
  7608. * slashes. */
  7609. if ((s = strrchr(fname, '/')) == NULL
  7610. && (s = strrchr(fname, '\\')) == NULL) {
  7611. s = fname;
  7612. } else {
  7613. s++;
  7614. }
  7615. /* There data is written to a temporary file first. */
  7616. /* Different users should use a different destination_dir. */
  7617. mg_snprintf(conn,
  7618. &truncated,
  7619. path,
  7620. sizeof(path) - 1,
  7621. "%s/%s",
  7622. destination_dir,
  7623. s);
  7624. /* TODO(high): kick client on buffer overflow */
  7625. strcpy(tmp_path, path);
  7626. strcat(tmp_path, "~");
  7627. /* We open the file with exclusive lock held. This guarantee us
  7628. * there is no other thread can save into the same file
  7629. * simultaneously. */
  7630. fp = NULL;
  7631. /* Open file in binary mode. */
  7632. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  7633. break;
  7634. }
  7635. /* Move data to the beginning of the buffer */
  7636. /* part_request_info is no longer valid after this operation */
  7637. /* assert(len >= headers_len); */
  7638. if (len < headers_len) {
  7639. break;
  7640. }
  7641. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  7642. len -= headers_len;
  7643. /* Read POST data, write into file until boundary is found. */
  7644. eof = n = 0;
  7645. do {
  7646. len += n;
  7647. for (i = 0; i < len - bl; i++) {
  7648. if (!memcmp(&buf[i], "\r\n--", 4)
  7649. && !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  7650. /* Found boundary, that's the end of file data. */
  7651. fwrite(buf, 1, (size_t)i, fp);
  7652. eof = 1;
  7653. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  7654. len -= i + bl;
  7655. break;
  7656. }
  7657. }
  7658. if (!eof && len > bl) {
  7659. fwrite(buf, 1, (size_t)(len - bl), fp);
  7660. memmove(buf, &buf[len - bl], (size_t)bl);
  7661. len = bl;
  7662. }
  7663. if (!eof) {
  7664. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  7665. }
  7666. } while (!eof && (n > 0));
  7667. fclose(fp);
  7668. if (eof) {
  7669. remove(path);
  7670. rename(tmp_path, path);
  7671. num_uploaded_files++;
  7672. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  7673. conn->ctx->callbacks.upload(conn, path);
  7674. }
  7675. } else {
  7676. remove(tmp_path);
  7677. }
  7678. }
  7679. return num_uploaded_files;
  7680. }
  7681. static int
  7682. get_first_ssl_listener_index(const struct mg_context *ctx)
  7683. {
  7684. unsigned int i;
  7685. int idx = -1;
  7686. if (ctx) {
  7687. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7688. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7689. }
  7690. }
  7691. return idx;
  7692. }
  7693. static void
  7694. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7695. {
  7696. char host[1025];
  7697. const char *host_header;
  7698. size_t hostlen;
  7699. host_header = mg_get_header(conn, "Host");
  7700. hostlen = sizeof(host);
  7701. if (host_header != NULL) {
  7702. char *pos;
  7703. mg_strlcpy(host, host_header, hostlen);
  7704. host[hostlen - 1] = '\0';
  7705. pos = strchr(host, ':');
  7706. if (pos != NULL) {
  7707. *pos = '\0';
  7708. }
  7709. } else {
  7710. /* Cannot get host from the Host: header.
  7711. * Fallback to our IP address. */
  7712. if (conn) {
  7713. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7714. }
  7715. }
  7716. /* Send host, port, uri and (if it exists) ?query_string */
  7717. if (conn) {
  7718. mg_printf(conn,
  7719. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7720. host,
  7721. (int)ntohs(
  7722. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7723. conn->request_info.local_uri,
  7724. (conn->request_info.query_string == NULL) ? "" : "?",
  7725. (conn->request_info.query_string == NULL)
  7726. ? ""
  7727. : conn->request_info.query_string);
  7728. }
  7729. }
  7730. static void
  7731. mg_set_request_handler_type(struct mg_context *ctx,
  7732. const char *uri,
  7733. int is_websocket_handler,
  7734. int is_delete_request,
  7735. mg_request_handler handler,
  7736. mg_websocket_connect_handler connect_handler,
  7737. mg_websocket_ready_handler ready_handler,
  7738. mg_websocket_data_handler data_handler,
  7739. mg_websocket_close_handler close_handler,
  7740. void *cbdata)
  7741. {
  7742. struct mg_request_handler_info *tmp_rh, **lastref;
  7743. size_t urilen = strlen(uri);
  7744. if (is_websocket_handler) {
  7745. /* assert(handler == NULL); */
  7746. /* assert(is_delete_request || connect_handler!=NULL ||
  7747. * ready_handler!=NULL || data_handler!=NULL ||
  7748. * close_handler!=NULL);
  7749. */
  7750. if (handler != NULL) {
  7751. return;
  7752. }
  7753. if (!is_delete_request && connect_handler == NULL
  7754. && ready_handler == NULL
  7755. && data_handler == NULL
  7756. && close_handler == NULL) {
  7757. return;
  7758. }
  7759. } else {
  7760. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7761. * data_handler==NULL && close_handler==NULL); */
  7762. /* assert(is_delete_request || (handler!=NULL));
  7763. */
  7764. if (connect_handler != NULL || ready_handler != NULL
  7765. || data_handler != NULL
  7766. || close_handler != NULL) {
  7767. return;
  7768. }
  7769. if (!is_delete_request && (handler == NULL)) {
  7770. return;
  7771. }
  7772. }
  7773. if (!ctx) {
  7774. return;
  7775. }
  7776. mg_lock_context(ctx);
  7777. /* first try to find an existing handler */
  7778. lastref = &(ctx->request_handlers);
  7779. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  7780. tmp_rh = tmp_rh->next) {
  7781. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  7782. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7783. if (!is_delete_request) {
  7784. /* update existing handler */
  7785. if (!is_websocket_handler) {
  7786. tmp_rh->handler = handler;
  7787. } else {
  7788. tmp_rh->connect_handler = connect_handler;
  7789. tmp_rh->ready_handler = ready_handler;
  7790. tmp_rh->data_handler = data_handler;
  7791. tmp_rh->close_handler = close_handler;
  7792. }
  7793. tmp_rh->cbdata = cbdata;
  7794. } else {
  7795. /* remove existing handler */
  7796. *lastref = tmp_rh->next;
  7797. mg_free(tmp_rh->uri);
  7798. mg_free(tmp_rh);
  7799. }
  7800. mg_unlock_context(ctx);
  7801. return;
  7802. }
  7803. }
  7804. lastref = &(tmp_rh->next);
  7805. }
  7806. if (is_delete_request) {
  7807. /* no handler to set, this was a remove request to a non-existing
  7808. * handler */
  7809. mg_unlock_context(ctx);
  7810. return;
  7811. }
  7812. tmp_rh = (struct mg_request_handler_info *)
  7813. mg_calloc(sizeof(struct mg_request_handler_info), 1);
  7814. if (tmp_rh == NULL) {
  7815. mg_unlock_context(ctx);
  7816. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7817. return;
  7818. }
  7819. tmp_rh->uri = mg_strdup(uri);
  7820. if (!tmp_rh->uri) {
  7821. mg_unlock_context(ctx);
  7822. mg_free(tmp_rh);
  7823. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  7824. return;
  7825. }
  7826. tmp_rh->uri_len = urilen;
  7827. if (!is_websocket_handler) {
  7828. tmp_rh->handler = handler;
  7829. } else {
  7830. tmp_rh->connect_handler = connect_handler;
  7831. tmp_rh->ready_handler = ready_handler;
  7832. tmp_rh->data_handler = data_handler;
  7833. tmp_rh->close_handler = close_handler;
  7834. }
  7835. tmp_rh->cbdata = cbdata;
  7836. tmp_rh->is_websocket_handler = is_websocket_handler;
  7837. tmp_rh->next = NULL;
  7838. *lastref = tmp_rh;
  7839. mg_unlock_context(ctx);
  7840. }
  7841. void
  7842. mg_set_request_handler(struct mg_context *ctx,
  7843. const char *uri,
  7844. mg_request_handler handler,
  7845. void *cbdata)
  7846. {
  7847. mg_set_request_handler_type(
  7848. ctx, uri, 0, handler == NULL, handler, NULL, NULL, NULL, NULL, cbdata);
  7849. }
  7850. void
  7851. mg_set_websocket_handler(struct mg_context *ctx,
  7852. const char *uri,
  7853. mg_websocket_connect_handler connect_handler,
  7854. mg_websocket_ready_handler ready_handler,
  7855. mg_websocket_data_handler data_handler,
  7856. mg_websocket_close_handler close_handler,
  7857. void *cbdata)
  7858. {
  7859. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  7860. && (data_handler == NULL)
  7861. && (close_handler == NULL);
  7862. mg_set_request_handler_type(ctx,
  7863. uri,
  7864. 1,
  7865. is_delete_request,
  7866. NULL,
  7867. connect_handler,
  7868. ready_handler,
  7869. data_handler,
  7870. close_handler,
  7871. cbdata);
  7872. }
  7873. static int
  7874. get_request_handler(struct mg_connection *conn,
  7875. int is_websocket_request,
  7876. mg_request_handler *handler,
  7877. mg_websocket_connect_handler *connect_handler,
  7878. mg_websocket_ready_handler *ready_handler,
  7879. mg_websocket_data_handler *data_handler,
  7880. mg_websocket_close_handler *close_handler,
  7881. void **cbdata)
  7882. {
  7883. const struct mg_request_info *request_info = mg_get_request_info(conn);
  7884. if (request_info) {
  7885. const char *uri = request_info->local_uri;
  7886. size_t urilen = strlen(uri);
  7887. struct mg_request_handler_info *tmp_rh;
  7888. if (!conn || !conn->ctx) {
  7889. return 0;
  7890. }
  7891. mg_lock_context(conn->ctx);
  7892. /* first try for an exact match */
  7893. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7894. tmp_rh = tmp_rh->next) {
  7895. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7896. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  7897. if (is_websocket_request) {
  7898. *connect_handler = tmp_rh->connect_handler;
  7899. *ready_handler = tmp_rh->ready_handler;
  7900. *data_handler = tmp_rh->data_handler;
  7901. *close_handler = tmp_rh->close_handler;
  7902. } else {
  7903. *handler = tmp_rh->handler;
  7904. }
  7905. *cbdata = tmp_rh->cbdata;
  7906. mg_unlock_context(conn->ctx);
  7907. return 1;
  7908. }
  7909. }
  7910. }
  7911. /* next try for a partial match, we will accept uri/something */
  7912. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7913. tmp_rh = tmp_rh->next) {
  7914. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7915. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  7916. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  7917. if (is_websocket_request) {
  7918. *connect_handler = tmp_rh->connect_handler;
  7919. *ready_handler = tmp_rh->ready_handler;
  7920. *data_handler = tmp_rh->data_handler;
  7921. *close_handler = tmp_rh->close_handler;
  7922. } else {
  7923. *handler = tmp_rh->handler;
  7924. }
  7925. *cbdata = tmp_rh->cbdata;
  7926. mg_unlock_context(conn->ctx);
  7927. return 1;
  7928. }
  7929. }
  7930. }
  7931. /* finally try for pattern match */
  7932. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  7933. tmp_rh = tmp_rh->next) {
  7934. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  7935. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  7936. if (is_websocket_request) {
  7937. *connect_handler = tmp_rh->connect_handler;
  7938. *ready_handler = tmp_rh->ready_handler;
  7939. *data_handler = tmp_rh->data_handler;
  7940. *close_handler = tmp_rh->close_handler;
  7941. } else {
  7942. *handler = tmp_rh->handler;
  7943. }
  7944. *cbdata = tmp_rh->cbdata;
  7945. mg_unlock_context(conn->ctx);
  7946. return 1;
  7947. }
  7948. }
  7949. }
  7950. mg_unlock_context(conn->ctx);
  7951. }
  7952. return 0; /* none found */
  7953. }
  7954. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  7955. static int
  7956. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  7957. void *cbdata)
  7958. {
  7959. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7960. if (pcallbacks->websocket_connect) {
  7961. return pcallbacks->websocket_connect(conn);
  7962. }
  7963. /* No handler set - assume "OK" */
  7964. return 0;
  7965. }
  7966. static void
  7967. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  7968. {
  7969. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7970. if (pcallbacks->websocket_ready) {
  7971. pcallbacks->websocket_ready(conn);
  7972. }
  7973. }
  7974. static int
  7975. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  7976. int bits,
  7977. char *data,
  7978. size_t len,
  7979. void *cbdata)
  7980. {
  7981. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  7982. if (pcallbacks->websocket_data) {
  7983. return pcallbacks->websocket_data(conn, bits, data, len);
  7984. }
  7985. /* No handler set - assume "OK" */
  7986. return 1;
  7987. }
  7988. #endif
  7989. /* This is the heart of the Civetweb's logic.
  7990. * This function is called when the request is read, parsed and validated,
  7991. * and Civetweb must decide what action to take: serve a file, or
  7992. * a directory, or call embedded function, etcetera. */
  7993. static void
  7994. handle_request(struct mg_connection *conn)
  7995. {
  7996. if (conn) {
  7997. struct mg_request_info *ri = &conn->request_info;
  7998. char path[PATH_MAX];
  7999. int uri_len, ssl_index;
  8000. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8001. is_put_or_delete_request = 0, is_callback_resource = 0;
  8002. int i;
  8003. struct file file = STRUCT_FILE_INITIALIZER;
  8004. mg_request_handler callback_handler = NULL;
  8005. mg_websocket_connect_handler ws_connect_handler = NULL;
  8006. mg_websocket_ready_handler ws_ready_handler = NULL;
  8007. mg_websocket_data_handler ws_data_handler = NULL;
  8008. mg_websocket_close_handler ws_close_handler = NULL;
  8009. void *callback_data = NULL;
  8010. #if !defined(NO_FILES)
  8011. time_t curtime = time(NULL);
  8012. char date[64];
  8013. #endif
  8014. path[0] = 0;
  8015. if (!ri) {
  8016. return;
  8017. }
  8018. /* 1. get the request url */
  8019. /* 1.1. split into url and query string */
  8020. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8021. != NULL) {
  8022. *((char *)conn->request_info.query_string++) = '\0';
  8023. }
  8024. uri_len = (int)strlen(ri->local_uri);
  8025. /* 1.2. decode url (if config says so) */
  8026. if (should_decode_url(conn)) {
  8027. mg_url_decode(
  8028. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8029. }
  8030. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  8031. * possible */
  8032. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8033. /* step 1. completed, the url is known now */
  8034. DEBUG_TRACE("URL: %s", ri->local_uri);
  8035. /* 2. do a https redirect, if required */
  8036. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8037. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8038. if (ssl_index >= 0) {
  8039. redirect_to_https_port(conn, ssl_index);
  8040. } else {
  8041. /* A http to https forward port has been specified,
  8042. * but no https port to forward to. */
  8043. send_http_error(conn,
  8044. 503,
  8045. "%s",
  8046. "Error: SSL forward not configured properly");
  8047. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8048. }
  8049. return;
  8050. }
  8051. /* 3. if this ip has limited speed, set it for this connection */
  8052. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8053. get_remote_ip(conn),
  8054. ri->local_uri);
  8055. /* 4. call a "handle everything" callback, if registered */
  8056. if (conn->ctx->callbacks.begin_request != NULL) {
  8057. /* Note that since V1.7 the "begin_request" function is called
  8058. * before an authorization check. If an authorization check is
  8059. * required, use a request_handler instead. */
  8060. i = conn->ctx->callbacks.begin_request(conn);
  8061. if (i > 0) {
  8062. /* callback already processed the request. Store the
  8063. return value as a status code for the access log. */
  8064. conn->status_code = i;
  8065. return;
  8066. } else if (i == 0) {
  8067. /* civetweb should process the request */
  8068. } else {
  8069. /* unspecified - may change with the next version */
  8070. return;
  8071. }
  8072. }
  8073. /* request not yet handled by a handler or redirect, so the request
  8074. * is processed here */
  8075. /* 5. interpret the url to find out how the request must be handled */
  8076. /* 5.1. first test, if the request targets the regular http(s)://
  8077. * protocol namespace or the websocket ws(s):// protocol namespace. */
  8078. is_websocket_request = is_websocket_protocol(conn);
  8079. /* 5.2. check if the request will be handled by a callback */
  8080. if (get_request_handler(conn,
  8081. is_websocket_request,
  8082. &callback_handler,
  8083. &ws_connect_handler,
  8084. &ws_ready_handler,
  8085. &ws_data_handler,
  8086. &ws_close_handler,
  8087. &callback_data)) {
  8088. /* 5.2.1. A callback will handle this request. All requests handled
  8089. * by a callback have to be considered as requests to a script
  8090. * resource. */
  8091. is_callback_resource = 1;
  8092. is_script_resource = 1;
  8093. is_put_or_delete_request = is_put_or_delete_method(conn);
  8094. } else {
  8095. no_callback_resource:
  8096. /* 5.2.2. No callback is responsible for this request. The URI
  8097. * addresses a file based resource (static content or Lua/cgi
  8098. * scripts in the file system). */
  8099. is_callback_resource = 0;
  8100. interpret_uri(conn,
  8101. path,
  8102. sizeof(path),
  8103. &file,
  8104. &is_found,
  8105. &is_script_resource,
  8106. &is_websocket_request,
  8107. &is_put_or_delete_request);
  8108. }
  8109. /* 6. authorization check */
  8110. if (is_put_or_delete_request && !is_script_resource
  8111. && !is_callback_resource) {
  8112. /* 6.1. this request is a PUT/DELETE to a real file */
  8113. /* 6.1.1. thus, the server must have real files */
  8114. #if defined(NO_FILES)
  8115. if (1) {
  8116. #else
  8117. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8118. #endif
  8119. /* This server does not have any real files, thus the
  8120. * PUT/DELETE methods are not valid. */
  8121. send_http_error(conn,
  8122. 405,
  8123. "%s method not allowed",
  8124. conn->request_info.request_method);
  8125. return;
  8126. }
  8127. #if !defined(NO_FILES)
  8128. /* 6.1.2. Check if put authorization for static files is available.
  8129. */
  8130. if (!is_authorized_for_put(conn)) {
  8131. send_authorization_request(conn);
  8132. return;
  8133. }
  8134. #endif
  8135. } else {
  8136. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  8137. * or it is a PUT or DELETE request to a resource that does not
  8138. * correspond to a file. Check authorization. */
  8139. if (!check_authorization(conn, path)) {
  8140. send_authorization_request(conn);
  8141. return;
  8142. }
  8143. }
  8144. /* request is authorized or does not need authorization */
  8145. /* 7. check if there are request handlers for this uri */
  8146. if (is_callback_resource) {
  8147. if (!is_websocket_request) {
  8148. i = callback_handler(conn, callback_data);
  8149. if (i > 0) {
  8150. /* Do nothing, callback has served the request. Store the
  8151. * return value as status code for the log and discard all
  8152. * data from the client not used by the callback. */
  8153. conn->status_code = i;
  8154. discard_unread_request_data(conn);
  8155. } else {
  8156. /* TODO (high): what if the handler did NOT handle the
  8157. * request */
  8158. /* The last version did handle this as a file request, but
  8159. * since a file request is not always a script resource,
  8160. * the authorization check might be different */
  8161. interpret_uri(conn,
  8162. path,
  8163. sizeof(path),
  8164. &file,
  8165. &is_found,
  8166. &is_script_resource,
  8167. &is_websocket_request,
  8168. &is_put_or_delete_request);
  8169. callback_handler = NULL;
  8170. /* TODO (very low): goto is deprecated but for the moment,
  8171. * a goto is simpler than some curious loop. */
  8172. /* The situation "callback does not handle the request"
  8173. * needs to be reconsidered anyway. */
  8174. goto no_callback_resource;
  8175. }
  8176. } else {
  8177. #if defined(USE_WEBSOCKET)
  8178. handle_websocket_request(conn,
  8179. path,
  8180. is_callback_resource,
  8181. ws_connect_handler,
  8182. ws_ready_handler,
  8183. ws_data_handler,
  8184. ws_close_handler,
  8185. callback_data);
  8186. #endif
  8187. }
  8188. return;
  8189. }
  8190. /* 8. handle websocket requests */
  8191. #if defined(USE_WEBSOCKET)
  8192. if (is_websocket_request) {
  8193. if (is_script_resource) {
  8194. /* Websocket Lua script */
  8195. handle_websocket_request(conn,
  8196. path,
  8197. 0 /* Lua Script */,
  8198. NULL,
  8199. NULL,
  8200. NULL,
  8201. NULL,
  8202. &conn->ctx->callbacks);
  8203. } else {
  8204. #if defined(MG_LEGACY_INTERFACE)
  8205. handle_websocket_request(
  8206. conn,
  8207. path,
  8208. !is_script_resource /* could be deprecated global callback */,
  8209. deprecated_websocket_connect_wrapper,
  8210. deprecated_websocket_ready_wrapper,
  8211. deprecated_websocket_data_wrapper,
  8212. NULL,
  8213. &conn->ctx->callbacks);
  8214. #else
  8215. send_http_error(conn, 404, "%s", "Not found");
  8216. #endif
  8217. }
  8218. return;
  8219. } else
  8220. #endif
  8221. #if defined(NO_FILES)
  8222. /* 9a. In case the server uses only callbacks, this uri is unknown.
  8223. * Then, all request handling ends here. */
  8224. send_http_error(conn, 404, "%s", "Not Found");
  8225. #else
  8226. /* 9b. This request is either for a static file or resource handled
  8227. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8228. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8229. send_http_error(conn, 404, "%s", "Not Found");
  8230. return;
  8231. }
  8232. /* 10. File is handled by a script. */
  8233. if (is_script_resource) {
  8234. handle_file_based_request(conn, path, &file);
  8235. return;
  8236. }
  8237. /* 11. Handle put/delete/mkcol requests */
  8238. if (is_put_or_delete_request) {
  8239. /* 11.1. PUT method */
  8240. if (!strcmp(ri->request_method, "PUT")) {
  8241. put_file(conn, path);
  8242. return;
  8243. }
  8244. /* 11.2. DELETE method */
  8245. if (!strcmp(ri->request_method, "DELETE")) {
  8246. delete_file(conn, path);
  8247. return;
  8248. }
  8249. /* 11.3. MKCOL method */
  8250. if (!strcmp(ri->request_method, "MKCOL")) {
  8251. mkcol(conn, path);
  8252. return;
  8253. }
  8254. /* 11.4. PATCH method
  8255. * This method is not supported for static resources,
  8256. * only for scripts (Lua, CGI) and callbacks. */
  8257. send_http_error(conn,
  8258. 405,
  8259. "%s method not allowed",
  8260. conn->request_info.request_method);
  8261. return;
  8262. }
  8263. /* 11. File does not exist, or it was configured that it should be
  8264. * hidden */
  8265. if (!is_found || (must_hide_file(conn, path))) {
  8266. send_http_error(conn, 404, "%s", "Not found");
  8267. return;
  8268. }
  8269. /* 12. Directories uris should end with a slash */
  8270. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8271. gmt_time_string(date, sizeof(date), &curtime);
  8272. mg_printf(conn,
  8273. "HTTP/1.1 301 Moved Permanently\r\n"
  8274. "Location: %s/\r\n"
  8275. "Date: %s\r\n"
  8276. "Content-Length: 0\r\n"
  8277. "Connection: %s\r\n\r\n",
  8278. ri->request_uri,
  8279. date,
  8280. suggest_connection_header(conn));
  8281. return;
  8282. }
  8283. /* 13. Handle other methods than GET/HEAD */
  8284. /* 13.1. Handle PROPFIND */
  8285. if (!strcmp(ri->request_method, "PROPFIND")) {
  8286. handle_propfind(conn, path, &file);
  8287. return;
  8288. }
  8289. /* 13.2. Handle OPTIONS for files */
  8290. if (!strcmp(ri->request_method, "OPTIONS")) {
  8291. /* This standard handler is only used for real files.
  8292. * Scripts should support the OPTIONS method themselves, to allow a
  8293. * maximum flexibility.
  8294. * Lua and CGI scripts may fully support CORS this way (including
  8295. * preflights). */
  8296. send_options(conn);
  8297. return;
  8298. }
  8299. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8300. if (0 != strcmp(ri->request_method, "GET")
  8301. && 0 != strcmp(ri->request_method, "HEAD")) {
  8302. send_http_error(conn,
  8303. 405,
  8304. "%s method not allowed",
  8305. conn->request_info.request_method);
  8306. return;
  8307. }
  8308. /* 14. directories */
  8309. if (file.is_directory) {
  8310. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8311. /* 14.1. use a substitute file */
  8312. /* TODO (high): substitute index may be a script resource.
  8313. * define what should be possible in this case. */
  8314. } else {
  8315. /* 14.2. no substitute file */
  8316. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8317. "yes")) {
  8318. handle_directory_request(conn, path);
  8319. } else {
  8320. send_http_error(conn,
  8321. 403,
  8322. "%s",
  8323. "Error: Directory listing denied");
  8324. }
  8325. return;
  8326. }
  8327. }
  8328. handle_file_based_request(conn, path, &file);
  8329. #endif /* !defined(NO_FILES) */
  8330. #if 0
  8331. /* Perform redirect and auth checks before calling begin_request()
  8332. * handler.
  8333. * Otherwise, begin_request() would need to perform auth checks and
  8334. * redirects. */
  8335. #endif
  8336. }
  8337. return;
  8338. }
  8339. static void
  8340. handle_file_based_request(struct mg_connection *conn,
  8341. const char *path,
  8342. struct file *file)
  8343. {
  8344. if (!conn || !conn->ctx) {
  8345. return;
  8346. }
  8347. if (0) {
  8348. #ifdef USE_LUA
  8349. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8350. strlen(
  8351. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8352. path) > 0) {
  8353. /* Lua server page: an SSI like page containing mostly plain html code
  8354. * plus some tags with server generated contents. */
  8355. handle_lsp_request(conn, path, file, NULL);
  8356. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8357. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8358. path) > 0) {
  8359. /* Lua in-server module script: a CGI like script used to generate the
  8360. * entire reply. */
  8361. mg_exec_lua_script(conn, path, NULL);
  8362. #endif
  8363. #if defined(USE_DUKTAPE)
  8364. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8365. strlen(
  8366. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8367. path) > 0) {
  8368. /* Call duktape to generate the page */
  8369. mg_exec_duktape_script(conn, path);
  8370. #endif
  8371. #if !defined(NO_CGI)
  8372. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8373. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8374. path) > 0) {
  8375. /* CGI scripts may support all HTTP methods */
  8376. handle_cgi_request(conn, path);
  8377. #endif /* !NO_CGI */
  8378. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8379. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8380. path) > 0) {
  8381. handle_ssi_file_request(conn, path, file);
  8382. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8383. /* Send 304 "Not Modified" - this must not send any body data */
  8384. send_http_error(conn, 304, "%s", "");
  8385. } else {
  8386. handle_static_file_request(conn, path, file);
  8387. }
  8388. }
  8389. static void
  8390. close_all_listening_sockets(struct mg_context *ctx)
  8391. {
  8392. unsigned int i;
  8393. if (!ctx) {
  8394. return;
  8395. }
  8396. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8397. closesocket(ctx->listening_sockets[i].sock);
  8398. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8399. }
  8400. mg_free(ctx->listening_sockets);
  8401. ctx->listening_sockets = NULL;
  8402. mg_free(ctx->listening_ports);
  8403. ctx->listening_ports = NULL;
  8404. }
  8405. /* Valid listening port specification is: [ip_address:]port[s]
  8406. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8407. * Examples for IPv6: [::]:80, [::1]:80,
  8408. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8409. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8410. static int
  8411. parse_port_string(const struct vec *vec, struct socket *so)
  8412. {
  8413. unsigned int a, b, c, d, port;
  8414. int ch, len;
  8415. #if defined(USE_IPV6)
  8416. char buf[100] = {0};
  8417. #endif
  8418. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8419. * Also, all-zeroes in the socket address means binding to all addresses
  8420. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8421. memset(so, 0, sizeof(*so));
  8422. so->lsa.sin.sin_family = AF_INET;
  8423. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8424. == 5) {
  8425. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8426. so->lsa.sin.sin_addr.s_addr =
  8427. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8428. so->lsa.sin.sin_port = htons((uint16_t)port);
  8429. #if defined(USE_IPV6)
  8430. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8431. && mg_inet_pton(
  8432. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8433. /* IPv6 address, examples: see above */
  8434. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */
  8435. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8436. #endif
  8437. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8438. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8439. so->lsa.sin.sin_port = htons((uint16_t)port);
  8440. } else {
  8441. /* Parsing failure. Make port invalid. */
  8442. port = 0;
  8443. len = 0;
  8444. }
  8445. /* sscanf and the option splitting code ensure the following condition */
  8446. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8447. return 0;
  8448. }
  8449. ch = vec->ptr[len]; /* Next character after the port number */
  8450. so->is_ssl = (ch == 's');
  8451. so->ssl_redir = (ch == 'r');
  8452. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8453. return is_valid_port(port)
  8454. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8455. }
  8456. static int
  8457. set_ports_option(struct mg_context *ctx)
  8458. {
  8459. const char *list;
  8460. int on = 1;
  8461. #if defined(USE_IPV6)
  8462. int off = 0;
  8463. #endif
  8464. struct vec vec;
  8465. struct socket so, *ptr;
  8466. in_port_t *portPtr;
  8467. union usa usa;
  8468. socklen_t len;
  8469. int portsTotal = 0;
  8470. int portsOk = 0;
  8471. if (!ctx) {
  8472. return 0;
  8473. }
  8474. memset(&so, 0, sizeof(so));
  8475. memset(&usa, 0, sizeof(usa));
  8476. len = sizeof(usa);
  8477. list = ctx->config[LISTENING_PORTS];
  8478. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8479. portsTotal++;
  8480. if (!parse_port_string(&vec, &so)) {
  8481. mg_cry(fc(ctx),
  8482. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8483. (int)vec.len,
  8484. vec.ptr,
  8485. portsTotal,
  8486. "[IP_ADDRESS:]PORT[s|r]");
  8487. continue;
  8488. }
  8489. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8490. mg_cry(fc(ctx),
  8491. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8492. "option set?",
  8493. portsTotal);
  8494. continue;
  8495. }
  8496. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8497. == INVALID_SOCKET) {
  8498. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8499. continue;
  8500. }
  8501. #ifdef _WIN32
  8502. /* Windows SO_REUSEADDR lets many procs binds to a
  8503. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8504. * if someone already has the socket -- DTL */
  8505. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8506. * Windows might need a few seconds before
  8507. * the same port can be used again in the
  8508. * same process, so a short Sleep may be
  8509. * required between mg_stop and mg_start.
  8510. */
  8511. if (setsockopt(so.sock,
  8512. SOL_SOCKET,
  8513. SO_EXCLUSIVEADDRUSE,
  8514. (SOCK_OPT_TYPE)&on,
  8515. sizeof(on)) != 0) {
  8516. mg_cry(fc(ctx),
  8517. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8518. portsTotal);
  8519. }
  8520. #else
  8521. if (setsockopt(so.sock,
  8522. SOL_SOCKET,
  8523. SO_REUSEADDR,
  8524. (SOCK_OPT_TYPE)&on,
  8525. sizeof(on)) != 0) {
  8526. mg_cry(fc(ctx),
  8527. "cannot set socket option SO_REUSEADDR (entry %i)",
  8528. portsTotal);
  8529. }
  8530. #endif
  8531. #if defined(USE_IPV6)
  8532. if (so.lsa.sa.sa_family == AF_INET6
  8533. && setsockopt(so.sock,
  8534. IPPROTO_IPV6,
  8535. IPV6_V6ONLY,
  8536. (void *)&off,
  8537. sizeof(off)) != 0) {
  8538. mg_cry(fc(ctx),
  8539. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8540. portsTotal);
  8541. }
  8542. #endif
  8543. if (so.lsa.sa.sa_family == AF_INET) {
  8544. len = sizeof(so.lsa.sin);
  8545. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8546. mg_cry(fc(ctx),
  8547. "cannot bind to %.*s: %d (%s)",
  8548. (int)vec.len,
  8549. vec.ptr,
  8550. (int)ERRNO,
  8551. strerror(errno));
  8552. closesocket(so.sock);
  8553. so.sock = INVALID_SOCKET;
  8554. continue;
  8555. }
  8556. }
  8557. #if defined(USE_IPV6)
  8558. else if (so.lsa.sa.sa_family == AF_INET6) {
  8559. len = sizeof(so.lsa.sin6);
  8560. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8561. mg_cry(fc(ctx),
  8562. "cannot bind to IPv6 %.*s: %d (%s)",
  8563. (int)vec.len,
  8564. vec.ptr,
  8565. (int)ERRNO,
  8566. strerror(errno));
  8567. closesocket(so.sock);
  8568. so.sock = INVALID_SOCKET;
  8569. continue;
  8570. }
  8571. }
  8572. #endif
  8573. else {
  8574. mg_cry(fc(ctx),
  8575. "cannot bind: address family not supported (entry %i)",
  8576. portsTotal);
  8577. continue;
  8578. }
  8579. if (listen(so.sock, SOMAXCONN) != 0) {
  8580. mg_cry(fc(ctx),
  8581. "cannot listen to %.*s: %d (%s)",
  8582. (int)vec.len,
  8583. vec.ptr,
  8584. (int)ERRNO,
  8585. strerror(errno));
  8586. closesocket(so.sock);
  8587. so.sock = INVALID_SOCKET;
  8588. continue;
  8589. }
  8590. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8591. int err = (int)ERRNO;
  8592. mg_cry(fc(ctx),
  8593. "call to getsockname failed %.*s: %d (%s)",
  8594. (int)vec.len,
  8595. vec.ptr,
  8596. err,
  8597. strerror(errno));
  8598. closesocket(so.sock);
  8599. so.sock = INVALID_SOCKET;
  8600. continue;
  8601. }
  8602. if ((ptr = (struct socket *)
  8603. mg_realloc(ctx->listening_sockets,
  8604. (ctx->num_listening_sockets + 1)
  8605. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  8606. mg_cry(fc(ctx), "%s", "Out of memory");
  8607. closesocket(so.sock);
  8608. so.sock = INVALID_SOCKET;
  8609. continue;
  8610. }
  8611. if ((portPtr =
  8612. (in_port_t *)mg_realloc(ctx->listening_ports,
  8613. (ctx->num_listening_sockets + 1)
  8614. * sizeof(ctx->listening_ports[0])))
  8615. == NULL) {
  8616. mg_cry(fc(ctx), "%s", "Out of memory");
  8617. closesocket(so.sock);
  8618. so.sock = INVALID_SOCKET;
  8619. mg_free(ptr);
  8620. continue;
  8621. }
  8622. set_close_on_exec(so.sock, fc(ctx));
  8623. ctx->listening_sockets = ptr;
  8624. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8625. ctx->listening_ports = portPtr;
  8626. ctx->listening_ports[ctx->num_listening_sockets] =
  8627. ntohs(usa.sin.sin_port);
  8628. ctx->num_listening_sockets++;
  8629. portsOk++;
  8630. }
  8631. if (portsOk != portsTotal) {
  8632. close_all_listening_sockets(ctx);
  8633. portsOk = 0;
  8634. }
  8635. return portsOk;
  8636. }
  8637. static const char *
  8638. header_val(const struct mg_connection *conn, const char *header)
  8639. {
  8640. const char *header_value;
  8641. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8642. return "-";
  8643. } else {
  8644. return header_value;
  8645. }
  8646. }
  8647. static void
  8648. log_access(const struct mg_connection *conn)
  8649. {
  8650. const struct mg_request_info *ri;
  8651. FILE *fp;
  8652. char date[64], src_addr[IP_ADDR_STR_LEN];
  8653. struct tm *tm;
  8654. const char *referer;
  8655. const char *user_agent;
  8656. char buf[4096];
  8657. if (!conn || !conn->ctx) {
  8658. return;
  8659. }
  8660. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  8661. ? NULL
  8662. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  8663. if (fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8664. return;
  8665. }
  8666. tm = localtime(&conn->conn_birth_time);
  8667. if (tm != NULL) {
  8668. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8669. } else {
  8670. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8671. date[sizeof(date) - 1] = '\0';
  8672. }
  8673. ri = &conn->request_info;
  8674. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8675. referer = header_val(conn, "Referer");
  8676. user_agent = header_val(conn, "User-Agent");
  8677. mg_snprintf(conn,
  8678. NULL, /* Ignore truncation in access log */
  8679. buf,
  8680. sizeof(buf),
  8681. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  8682. src_addr,
  8683. ri->remote_user == NULL ? "-" : ri->remote_user,
  8684. date,
  8685. ri->request_method ? ri->request_method : "-",
  8686. ri->request_uri ? ri->request_uri : "-",
  8687. ri->query_string ? "?" : "",
  8688. ri->query_string ? ri->query_string : "",
  8689. ri->http_version,
  8690. conn->status_code,
  8691. conn->num_bytes_sent,
  8692. referer,
  8693. user_agent);
  8694. if (conn->ctx->callbacks.log_access) {
  8695. conn->ctx->callbacks.log_access(conn, buf);
  8696. }
  8697. if (fp) {
  8698. flockfile(fp);
  8699. fprintf(fp, "%s", buf);
  8700. fputc('\n', fp);
  8701. fflush(fp);
  8702. funlockfile(fp);
  8703. fclose(fp);
  8704. }
  8705. }
  8706. /* Verify given socket address against the ACL.
  8707. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  8708. static int
  8709. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  8710. {
  8711. int allowed, flag;
  8712. uint32_t net, mask;
  8713. struct vec vec;
  8714. if (ctx) {
  8715. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  8716. /* If any ACL is set, deny by default */
  8717. allowed = list == NULL ? '+' : '-';
  8718. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8719. flag = vec.ptr[0];
  8720. if ((flag != '+' && flag != '-')
  8721. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  8722. mg_cry(fc(ctx),
  8723. "%s: subnet must be [+|-]x.x.x.x[/x]",
  8724. __func__);
  8725. return -1;
  8726. }
  8727. if (net == (remote_ip & mask)) {
  8728. allowed = flag;
  8729. }
  8730. }
  8731. return allowed == '+';
  8732. }
  8733. return -1;
  8734. }
  8735. #if !defined(_WIN32)
  8736. static int
  8737. set_uid_option(struct mg_context *ctx)
  8738. {
  8739. struct passwd *pw;
  8740. if (ctx) {
  8741. const char *uid = ctx->config[RUN_AS_USER];
  8742. int success = 0;
  8743. if (uid == NULL) {
  8744. success = 1;
  8745. } else {
  8746. if ((pw = getpwnam(uid)) == NULL) {
  8747. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  8748. } else if (setgid(pw->pw_gid) == -1) {
  8749. mg_cry(fc(ctx),
  8750. "%s: setgid(%s): %s",
  8751. __func__,
  8752. uid,
  8753. strerror(errno));
  8754. } else if (setgroups(0, NULL)) {
  8755. mg_cry(fc(ctx),
  8756. "%s: setgroups(): %s",
  8757. __func__,
  8758. strerror(errno));
  8759. } else if (setuid(pw->pw_uid) == -1) {
  8760. mg_cry(fc(ctx),
  8761. "%s: setuid(%s): %s",
  8762. __func__,
  8763. uid,
  8764. strerror(errno));
  8765. } else {
  8766. success = 1;
  8767. }
  8768. }
  8769. return success;
  8770. }
  8771. return 0;
  8772. }
  8773. #endif /* !_WIN32 */
  8774. static void
  8775. tls_dtor(void *key)
  8776. {
  8777. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  8778. /* key == pthread_getspecific(sTlsKey); */
  8779. if (tls) {
  8780. if (tls->is_master == 2) {
  8781. tls->is_master = -3; /* Mark memory as dead */
  8782. mg_free(tls);
  8783. }
  8784. }
  8785. pthread_setspecific(sTlsKey, NULL);
  8786. }
  8787. #if !defined(NO_SSL)
  8788. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  8789. static unsigned long
  8790. ssl_id_callback(void)
  8791. {
  8792. #ifdef _WIN32
  8793. return GetCurrentThreadId();
  8794. #else
  8795. #ifdef __clang__
  8796. #pragma clang diagnostic push
  8797. #pragma clang diagnostic ignored "-Wunreachable-code"
  8798. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  8799. * or not, so one of the two conditions will be unreachable by construction.
  8800. * Unfortunately the C standard does not define a way to check this at
  8801. * compile time, since the #if preprocessor conditions can not use the sizeof
  8802. * operator as an argument. */
  8803. #endif
  8804. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  8805. /* This is the problematic case for CRYPTO_set_id_callback:
  8806. * The OS pthread_t can not be cast to unsigned long. */
  8807. struct mg_workerTLS *tls =
  8808. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  8809. if (tls == NULL) {
  8810. /* SSL called from an unknown thread: Create some thread index. */
  8811. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  8812. tls->is_master = -2; /* -2 means "3rd party thread" */
  8813. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  8814. pthread_setspecific(sTlsKey, tls);
  8815. }
  8816. return tls->thread_idx;
  8817. } else {
  8818. return (unsigned long)pthread_self();
  8819. }
  8820. #ifdef __clang__
  8821. #pragma clang diagnostic pop
  8822. #endif
  8823. #endif
  8824. }
  8825. static pthread_mutex_t *ssl_mutexes;
  8826. static int
  8827. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  8828. {
  8829. int ret, err;
  8830. if (!conn) {
  8831. return 0;
  8832. }
  8833. conn->ssl = SSL_new(s);
  8834. if (conn->ssl == NULL) {
  8835. return 0;
  8836. }
  8837. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  8838. if (ret != 1) {
  8839. err = SSL_get_error(conn->ssl, ret);
  8840. (void)err; /* TODO: set some error message */
  8841. SSL_free(conn->ssl);
  8842. conn->ssl = NULL;
  8843. return 0;
  8844. }
  8845. ret = func(conn->ssl);
  8846. if (ret != 1) {
  8847. err = SSL_get_error(conn->ssl, ret);
  8848. (void)err; /* TODO: set some error message */
  8849. SSL_free(conn->ssl);
  8850. conn->ssl = NULL;
  8851. return 0;
  8852. }
  8853. return 1;
  8854. }
  8855. /* Return OpenSSL error message (from CRYPTO lib) */
  8856. static const char *
  8857. ssl_error(void)
  8858. {
  8859. unsigned long err;
  8860. err = ERR_get_error();
  8861. return err == 0 ? "" : ERR_error_string(err, NULL);
  8862. }
  8863. static void
  8864. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  8865. {
  8866. (void)line;
  8867. (void)file;
  8868. if (mode & 1) {
  8869. /* 1 is CRYPTO_LOCK */
  8870. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  8871. } else {
  8872. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  8873. }
  8874. }
  8875. #if !defined(NO_SSL_DL)
  8876. static void *
  8877. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  8878. {
  8879. union {
  8880. void *p;
  8881. void (*fp)(void);
  8882. } u;
  8883. void *dll_handle;
  8884. struct ssl_func *fp;
  8885. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  8886. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  8887. return NULL;
  8888. }
  8889. for (fp = sw; fp->name != NULL; fp++) {
  8890. #ifdef _WIN32
  8891. /* GetProcAddress() returns pointer to function */
  8892. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  8893. #else
  8894. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  8895. * pointers to function pointers. We need to use a union to make a
  8896. * cast. */
  8897. u.p = dlsym(dll_handle, fp->name);
  8898. #endif /* _WIN32 */
  8899. if (u.fp == NULL) {
  8900. mg_cry(fc(ctx),
  8901. "%s: %s: cannot find %s",
  8902. __func__,
  8903. dll_name,
  8904. fp->name);
  8905. dlclose(dll_handle);
  8906. return NULL;
  8907. } else {
  8908. fp->ptr = u.fp;
  8909. }
  8910. }
  8911. return dll_handle;
  8912. }
  8913. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  8914. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  8915. #endif /* NO_SSL_DL */
  8916. #if defined(SSL_ALREADY_INITIALIZED)
  8917. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  8918. #else
  8919. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  8920. #endif
  8921. static int
  8922. initialize_ssl(struct mg_context *ctx)
  8923. {
  8924. int i;
  8925. size_t size;
  8926. #if !defined(NO_SSL_DL)
  8927. if (!cryptolib_dll_handle) {
  8928. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  8929. if (!cryptolib_dll_handle) {
  8930. return 0;
  8931. }
  8932. }
  8933. #endif /* NO_SSL_DL */
  8934. if (mg_atomic_inc(&cryptolib_users) > 1) {
  8935. return 1;
  8936. }
  8937. /* Initialize locking callbacks, needed for thread safety.
  8938. * http://www.openssl.org/support/faq.html#PROG1
  8939. */
  8940. i = CRYPTO_num_locks();
  8941. if (i < 0) {
  8942. i = 0;
  8943. }
  8944. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  8945. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  8946. mg_cry(fc(ctx),
  8947. "%s: cannot allocate mutexes: %s",
  8948. __func__,
  8949. ssl_error());
  8950. return 0;
  8951. }
  8952. for (i = 0; i < CRYPTO_num_locks(); i++) {
  8953. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  8954. }
  8955. CRYPTO_set_locking_callback(&ssl_locking_callback);
  8956. CRYPTO_set_id_callback(&ssl_id_callback);
  8957. return 1;
  8958. }
  8959. static int
  8960. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  8961. {
  8962. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  8963. mg_cry(fc(ctx),
  8964. "%s: cannot open certificate file %s: %s",
  8965. __func__,
  8966. pem,
  8967. ssl_error());
  8968. return 0;
  8969. }
  8970. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  8971. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  8972. mg_cry(fc(ctx),
  8973. "%s: cannot open private key file %s: %s",
  8974. __func__,
  8975. pem,
  8976. ssl_error());
  8977. return 0;
  8978. }
  8979. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  8980. mg_cry(fc(ctx),
  8981. "%s: certificate and private key do not match: %s",
  8982. __func__,
  8983. pem);
  8984. return 0;
  8985. }
  8986. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  8987. mg_cry(fc(ctx),
  8988. "%s: cannot use certificate chain file %s: %s",
  8989. __func__,
  8990. pem,
  8991. ssl_error());
  8992. return 0;
  8993. }
  8994. return 1;
  8995. }
  8996. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  8997. static int
  8998. set_ssl_option(struct mg_context *ctx)
  8999. {
  9000. const char *pem;
  9001. int callback_ret;
  9002. int should_verify_peer;
  9003. const char *ca_path;
  9004. const char *ca_file;
  9005. int use_default_verify_paths;
  9006. int verify_depth;
  9007. time_t now_rt = time(NULL);
  9008. struct timespec now_mt;
  9009. md5_byte_t ssl_context_id[16];
  9010. md5_state_t md5state;
  9011. /* If PEM file is not specified and the init_ssl callback
  9012. * is not specified, skip SSL initialization. */
  9013. if (!ctx) {
  9014. return 0;
  9015. }
  9016. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9017. && ctx->callbacks.init_ssl == NULL) {
  9018. return 1;
  9019. }
  9020. if (!initialize_ssl(ctx)) {
  9021. return 0;
  9022. }
  9023. #if !defined(NO_SSL_DL)
  9024. if (!ssllib_dll_handle) {
  9025. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9026. if (!ssllib_dll_handle) {
  9027. return 0;
  9028. }
  9029. }
  9030. #endif /* NO_SSL_DL */
  9031. /* Initialize SSL library */
  9032. SSL_library_init();
  9033. SSL_load_error_strings();
  9034. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9035. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9036. return 0;
  9037. }
  9038. /* If a callback has been specified, call it. */
  9039. callback_ret =
  9040. (ctx->callbacks.init_ssl == NULL)
  9041. ? 0
  9042. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9043. /* If callback returns 0, civetweb sets up the SSL certificate.
  9044. * If it returns 1, civetweb assumes the calback already did this.
  9045. * If it returns -1, initializing ssl fails. */
  9046. if (callback_ret < 0) {
  9047. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9048. return 0;
  9049. }
  9050. if (callback_ret > 0) {
  9051. if (pem != NULL) {
  9052. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9053. }
  9054. return 1;
  9055. }
  9056. /* Use some UID as session context ID. */
  9057. md5_init(&md5state);
  9058. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9059. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9060. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9061. md5_append(&md5state,
  9062. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9063. strlen(ctx->config[LISTENING_PORTS]));
  9064. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9065. md5_finish(&md5state, ssl_context_id);
  9066. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9067. (const unsigned char *)&ssl_context_id,
  9068. sizeof(ssl_context_id));
  9069. if (pem != NULL) {
  9070. if (!ssl_use_pem_file(ctx, pem)) {
  9071. return 0;
  9072. }
  9073. }
  9074. should_verify_peer =
  9075. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9076. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9077. use_default_verify_paths =
  9078. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9079. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9080. if (should_verify_peer) {
  9081. ca_path = ctx->config[SSL_CA_PATH];
  9082. ca_file = ctx->config[SSL_CA_FILE];
  9083. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9084. != 1) {
  9085. mg_cry(
  9086. fc(ctx),
  9087. "SSL_CTX_load_verify_locations error: %s "
  9088. "ssl_verify_peer requires setting "
  9089. "either ssl_ca_path or ssl_ca_file. Is any of them present in "
  9090. "the .conf file?",
  9091. ssl_error());
  9092. return 0;
  9093. }
  9094. SSL_CTX_set_verify(ctx->ssl_ctx,
  9095. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9096. NULL);
  9097. if (use_default_verify_paths
  9098. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9099. mg_cry(fc(ctx),
  9100. "SSL_CTX_set_default_verify_paths error: %s",
  9101. ssl_error());
  9102. return 0;
  9103. }
  9104. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9105. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9106. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9107. }
  9108. }
  9109. /* TODO: could set use SSL_CTX_set_cipher_list if set */
  9110. return 1;
  9111. }
  9112. static void
  9113. uninitialize_ssl(struct mg_context *ctx)
  9114. {
  9115. int i;
  9116. (void)ctx;
  9117. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9118. CRYPTO_set_locking_callback(NULL);
  9119. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9120. pthread_mutex_destroy(&ssl_mutexes[i]);
  9121. }
  9122. CRYPTO_set_locking_callback(NULL);
  9123. CRYPTO_set_id_callback(NULL);
  9124. }
  9125. }
  9126. #endif /* !NO_SSL */
  9127. static int
  9128. set_gpass_option(struct mg_context *ctx)
  9129. {
  9130. if (ctx) {
  9131. struct file file = STRUCT_FILE_INITIALIZER;
  9132. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9133. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9134. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9135. return 0;
  9136. }
  9137. return 1;
  9138. }
  9139. return 0;
  9140. }
  9141. static int
  9142. set_acl_option(struct mg_context *ctx)
  9143. {
  9144. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9145. }
  9146. static void
  9147. reset_per_request_attributes(struct mg_connection *conn)
  9148. {
  9149. if (!conn) {
  9150. return;
  9151. }
  9152. conn->path_info = NULL;
  9153. conn->num_bytes_sent = conn->consumed_content = 0;
  9154. conn->status_code = -1;
  9155. conn->is_chunked = 0;
  9156. conn->must_close = conn->request_len = conn->throttle = 0;
  9157. conn->request_info.content_length = -1;
  9158. conn->request_info.remote_user = NULL;
  9159. conn->request_info.request_method = NULL;
  9160. conn->request_info.request_uri = NULL;
  9161. conn->request_info.local_uri = NULL;
  9162. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9163. * local_uri and request_uri */
  9164. conn->request_info.http_version = NULL;
  9165. conn->request_info.num_headers = 0;
  9166. conn->data_len = 0;
  9167. conn->chunk_remainder = 0;
  9168. conn->internal_error = 0;
  9169. }
  9170. static int
  9171. set_sock_timeout(SOCKET sock, int milliseconds)
  9172. {
  9173. int r1, r2;
  9174. #ifdef _WIN32
  9175. /* Windows specific */
  9176. DWORD tv = (DWORD)milliseconds;
  9177. #else
  9178. /* Linux, ... (not Windows) */
  9179. struct timeval tv;
  9180. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9181. * max. time waiting for the acknowledged of TCP data before the connection
  9182. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9183. * If this option is not set, the default timeout of 20-30 minutes is used.
  9184. */
  9185. /* #define TCP_USER_TIMEOUT (18) */
  9186. #if defined(TCP_USER_TIMEOUT)
  9187. unsigned int uto = (unsigned int)milliseconds;
  9188. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9189. #endif
  9190. memset(&tv, 0, sizeof(tv));
  9191. tv.tv_sec = milliseconds / 1000;
  9192. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9193. #endif /* _WIN32 */
  9194. r1 = setsockopt(
  9195. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9196. r2 = setsockopt(
  9197. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9198. return r1 || r2;
  9199. }
  9200. static void
  9201. close_socket_gracefully(struct mg_connection *conn)
  9202. {
  9203. #if defined(_WIN32)
  9204. char buf[MG_BUF_LEN];
  9205. int n;
  9206. #endif
  9207. struct linger linger;
  9208. if (!conn) {
  9209. return;
  9210. }
  9211. /* Set linger option to avoid socket hanging out after close. This prevent
  9212. * ephemeral port exhaust problem under high QPS. */
  9213. linger.l_onoff = 1;
  9214. linger.l_linger = 1;
  9215. if (setsockopt(conn->client.sock,
  9216. SOL_SOCKET,
  9217. SO_LINGER,
  9218. (char *)&linger,
  9219. sizeof(linger)) != 0) {
  9220. mg_cry(conn,
  9221. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9222. __func__,
  9223. strerror(ERRNO));
  9224. }
  9225. /* Send FIN to the client */
  9226. shutdown(conn->client.sock, SHUT_WR);
  9227. set_non_blocking_mode(conn->client.sock);
  9228. #if defined(_WIN32)
  9229. /* Read and discard pending incoming data. If we do not do that and close
  9230. * the socket, the data in the send buffer may be discarded. This
  9231. * behaviour is seen on Windows, when client keeps sending data
  9232. * when server decides to close the connection; then when client
  9233. * does recv() it gets no data back. */
  9234. do {
  9235. n = pull(
  9236. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9237. } while (n > 0);
  9238. #endif
  9239. /* Now we know that our FIN is ACK-ed, safe to close */
  9240. closesocket(conn->client.sock);
  9241. conn->client.sock = INVALID_SOCKET;
  9242. }
  9243. static void
  9244. close_connection(struct mg_connection *conn)
  9245. {
  9246. if (!conn || !conn->ctx) {
  9247. return;
  9248. }
  9249. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9250. if (conn->lua_websocket_state) {
  9251. lua_websocket_close(conn, conn->lua_websocket_state);
  9252. conn->lua_websocket_state = NULL;
  9253. }
  9254. #endif
  9255. /* call the connection_close callback if assigned */
  9256. if ((conn->ctx->callbacks.connection_close != NULL)
  9257. && (conn->ctx->context_type == 1)) {
  9258. conn->ctx->callbacks.connection_close(conn);
  9259. }
  9260. mg_lock_connection(conn);
  9261. conn->must_close = 1;
  9262. #ifndef NO_SSL
  9263. if (conn->ssl != NULL) {
  9264. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  9265. SSL_shutdown(conn->ssl);
  9266. SSL_free(conn->ssl);
  9267. conn->ssl = NULL;
  9268. }
  9269. #endif
  9270. if (conn->client.sock != INVALID_SOCKET) {
  9271. close_socket_gracefully(conn);
  9272. conn->client.sock = INVALID_SOCKET;
  9273. }
  9274. mg_unlock_connection(conn);
  9275. }
  9276. void
  9277. mg_close_connection(struct mg_connection *conn)
  9278. {
  9279. struct mg_context *client_ctx = NULL;
  9280. unsigned int i;
  9281. if (conn == NULL) {
  9282. return;
  9283. }
  9284. if (conn->ctx->context_type == 2) {
  9285. client_ctx = conn->ctx;
  9286. /* client context: loops must end */
  9287. conn->ctx->stop_flag = 1;
  9288. }
  9289. #ifndef NO_SSL
  9290. if (conn->client_ssl_ctx != NULL) {
  9291. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9292. }
  9293. #endif
  9294. close_connection(conn);
  9295. if (client_ctx != NULL) {
  9296. /* join worker thread and free context */
  9297. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9298. if (client_ctx->workerthreadids[i] != 0) {
  9299. mg_join_thread(client_ctx->workerthreadids[i]);
  9300. }
  9301. }
  9302. mg_free(client_ctx->workerthreadids);
  9303. mg_free(client_ctx);
  9304. }
  9305. (void)pthread_mutex_destroy(&conn->mutex);
  9306. mg_free(conn);
  9307. }
  9308. static struct mg_connection *
  9309. mg_connect_client_impl(const struct mg_client_options *client_options,
  9310. int use_ssl,
  9311. char *ebuf,
  9312. size_t ebuf_len)
  9313. {
  9314. static struct mg_context fake_ctx;
  9315. struct mg_connection *conn = NULL;
  9316. SOCKET sock;
  9317. union usa sa;
  9318. if (!connect_socket(&fake_ctx,
  9319. client_options->host,
  9320. client_options->port,
  9321. use_ssl,
  9322. ebuf,
  9323. ebuf_len,
  9324. &sock,
  9325. &sa)) {
  9326. ;
  9327. } else if ((conn = (struct mg_connection *)
  9328. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9329. mg_snprintf(NULL,
  9330. NULL, /* No truncation check for ebuf */
  9331. ebuf,
  9332. ebuf_len,
  9333. "calloc(): %s",
  9334. strerror(ERRNO));
  9335. closesocket(sock);
  9336. #ifndef NO_SSL
  9337. } else if (use_ssl
  9338. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9339. == NULL) {
  9340. mg_snprintf(NULL,
  9341. NULL, /* No truncation check for ebuf */
  9342. ebuf,
  9343. ebuf_len,
  9344. "SSL_CTX_new error");
  9345. closesocket(sock);
  9346. mg_free(conn);
  9347. conn = NULL;
  9348. #endif /* NO_SSL */
  9349. } else {
  9350. #ifdef USE_IPV6
  9351. socklen_t len = (sa.sa.sa_family == AF_INET)
  9352. ? sizeof(conn->client.rsa.sin)
  9353. : sizeof(conn->client.rsa.sin6);
  9354. struct sockaddr *psa =
  9355. (sa.sa.sa_family == AF_INET)
  9356. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9357. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9358. #else
  9359. socklen_t len = sizeof(conn->client.rsa.sin);
  9360. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9361. #endif
  9362. conn->buf_size = MAX_REQUEST_SIZE;
  9363. conn->buf = (char *)(conn + 1);
  9364. conn->ctx = &fake_ctx;
  9365. conn->client.sock = sock;
  9366. conn->client.lsa = sa;
  9367. if (getsockname(sock, psa, &len) != 0) {
  9368. mg_cry(conn,
  9369. "%s: getsockname() failed: %s",
  9370. __func__,
  9371. strerror(ERRNO));
  9372. }
  9373. conn->client.is_ssl = use_ssl ? 1 : 0;
  9374. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9375. #ifndef NO_SSL
  9376. if (use_ssl) {
  9377. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9378. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9379. SSL_CTX_set_verify call is needed to switch off server
  9380. * certificate checking, which is off by default in OpenSSL and on
  9381. * in yaSSL. */
  9382. // TODO: SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER,
  9383. // verify_ssl_server);
  9384. if (client_options->client_cert) {
  9385. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9386. mg_snprintf(NULL,
  9387. NULL, /* No truncation check for ebuf */
  9388. ebuf,
  9389. ebuf_len,
  9390. "Can not use SSL client certificate");
  9391. SSL_CTX_free(conn->client_ssl_ctx);
  9392. closesocket(sock);
  9393. mg_free(conn);
  9394. conn = NULL;
  9395. }
  9396. }
  9397. if (client_options->server_cert) {
  9398. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9399. client_options->server_cert,
  9400. NULL);
  9401. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9402. } else {
  9403. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9404. }
  9405. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9406. mg_snprintf(NULL,
  9407. NULL, /* No truncation check for ebuf */
  9408. ebuf,
  9409. ebuf_len,
  9410. "SSL connection error");
  9411. SSL_CTX_free(conn->client_ssl_ctx);
  9412. closesocket(sock);
  9413. mg_free(conn);
  9414. conn = NULL;
  9415. }
  9416. }
  9417. #endif
  9418. }
  9419. return conn;
  9420. }
  9421. CIVETWEB_API struct mg_connection *
  9422. mg_connect_client_secure(const struct mg_client_options *client_options,
  9423. char *error_buffer,
  9424. size_t error_buffer_size)
  9425. {
  9426. return mg_connect_client_impl(client_options,
  9427. 1,
  9428. error_buffer,
  9429. error_buffer_size);
  9430. }
  9431. struct mg_connection *
  9432. mg_connect_client(const char *host,
  9433. int port,
  9434. int use_ssl,
  9435. char *error_buffer,
  9436. size_t error_buffer_size)
  9437. {
  9438. struct mg_client_options opts;
  9439. memset(&opts, 0, sizeof(opts));
  9440. opts.host = host;
  9441. opts.port = port;
  9442. return mg_connect_client_impl(&opts,
  9443. use_ssl,
  9444. error_buffer,
  9445. error_buffer_size);
  9446. }
  9447. static const struct {
  9448. const char *proto;
  9449. size_t proto_len;
  9450. unsigned default_port;
  9451. } abs_uri_protocols[] = {{"http://", 7, 80},
  9452. {"https://", 8, 443},
  9453. {"ws://", 5, 80},
  9454. {"wss://", 6, 443},
  9455. {NULL, 0, 0}};
  9456. /* Check if the uri is valid.
  9457. * return 0 for invalid uri,
  9458. * return 1 for *,
  9459. * return 2 for relative uri,
  9460. * return 3 for absolute uri without port,
  9461. * return 4 for absolute uri with port */
  9462. static int
  9463. get_uri_type(const char *uri)
  9464. {
  9465. int i;
  9466. char *hostend, *portbegin, *portend;
  9467. unsigned long port;
  9468. /* According to the HTTP standard
  9469. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  9470. * URI can be an asterisk (*) or should start with slash (relative uri),
  9471. * or it should start with the protocol (absolute uri). */
  9472. if (uri[0] == '*' && uri[1] == '\0') {
  9473. /* asterisk */
  9474. return 1;
  9475. }
  9476. if (uri[0] == '/') {
  9477. /* relative uri */
  9478. return 2;
  9479. }
  9480. /* It could be an absolute uri: */
  9481. /* This function only checks if the uri is valid, not if it is
  9482. * addressing the current server. So civetweb can also be used
  9483. * as a proxy server. */
  9484. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9485. if (mg_strncasecmp(uri,
  9486. abs_uri_protocols[i].proto,
  9487. abs_uri_protocols[i].proto_len) == 0) {
  9488. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9489. if (!hostend) {
  9490. return 0;
  9491. }
  9492. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9493. if (!portbegin) {
  9494. return 3;
  9495. }
  9496. port = strtoul(portbegin + 1, &portend, 10);
  9497. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9498. return 0;
  9499. }
  9500. return 4;
  9501. }
  9502. }
  9503. return 0;
  9504. }
  9505. /* Return NULL or the relative uri at the current server */
  9506. static const char *
  9507. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  9508. {
  9509. const char *domain;
  9510. size_t domain_len;
  9511. unsigned long port = 0;
  9512. int i;
  9513. char *hostend = NULL;
  9514. char *portbegin, *portend;
  9515. /* DNS is case insensitive, so use case insensitive string compare here */
  9516. domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  9517. if (!domain) {
  9518. return 0;
  9519. }
  9520. domain_len = strlen(domain);
  9521. if (!domain_len) {
  9522. return 0;
  9523. }
  9524. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9525. if (mg_strncasecmp(uri,
  9526. abs_uri_protocols[i].proto,
  9527. abs_uri_protocols[i].proto_len) == 0) {
  9528. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9529. if (!hostend) {
  9530. return 0;
  9531. }
  9532. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9533. if (!portbegin) {
  9534. port = abs_uri_protocols[i].default_port;
  9535. } else {
  9536. port = strtoul(portbegin + 1, &portend, 10);
  9537. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9538. return 0;
  9539. }
  9540. }
  9541. /* protocol found, port set */
  9542. break;
  9543. }
  9544. }
  9545. if (!port) {
  9546. /* port remains 0 if the protocol is not found */
  9547. return 0;
  9548. }
  9549. #if defined(USE_IPV6)
  9550. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9551. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  9552. return 0;
  9553. }
  9554. } else
  9555. #endif
  9556. {
  9557. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  9558. return 0;
  9559. }
  9560. }
  9561. return hostend;
  9562. }
  9563. static int
  9564. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  9565. {
  9566. const char *cl;
  9567. if (ebuf_len > 0) {
  9568. ebuf[0] = '\0';
  9569. }
  9570. *err = 0;
  9571. reset_per_request_attributes(conn);
  9572. if (!conn) {
  9573. mg_snprintf(conn,
  9574. NULL, /* No truncation check for ebuf */
  9575. ebuf,
  9576. ebuf_len,
  9577. "%s",
  9578. "Internal error");
  9579. *err = 500;
  9580. return 0;
  9581. }
  9582. /* Set the time the request was received. This value should be used for
  9583. * timeouts. */
  9584. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  9585. conn->request_len =
  9586. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  9587. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  9588. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  9589. mg_snprintf(conn,
  9590. NULL, /* No truncation check for ebuf */
  9591. ebuf,
  9592. ebuf_len,
  9593. "%s",
  9594. "Invalid request size");
  9595. *err = 500;
  9596. return 0;
  9597. }
  9598. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  9599. mg_snprintf(conn,
  9600. NULL, /* No truncation check for ebuf */
  9601. ebuf,
  9602. ebuf_len,
  9603. "%s",
  9604. "Request Too Large");
  9605. *err = 413;
  9606. return 0;
  9607. } else if (conn->request_len <= 0) {
  9608. if (conn->data_len > 0) {
  9609. mg_snprintf(conn,
  9610. NULL, /* No truncation check for ebuf */
  9611. ebuf,
  9612. ebuf_len,
  9613. "%s",
  9614. "Client sent malformed request");
  9615. *err = 400;
  9616. } else {
  9617. /* Server did not send anything -> just close the connection */
  9618. conn->must_close = 1;
  9619. mg_snprintf(conn,
  9620. NULL, /* No truncation check for ebuf */
  9621. ebuf,
  9622. ebuf_len,
  9623. "%s",
  9624. "Client did not send a request");
  9625. *err = 0;
  9626. }
  9627. return 0;
  9628. } else if (parse_http_message(conn->buf,
  9629. conn->buf_size,
  9630. &conn->request_info) <= 0) {
  9631. mg_snprintf(conn,
  9632. NULL, /* No truncation check for ebuf */
  9633. ebuf,
  9634. ebuf_len,
  9635. "%s",
  9636. "Bad Request");
  9637. *err = 400;
  9638. return 0;
  9639. } else {
  9640. /* Message is a valid request or response */
  9641. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  9642. /* Request/response has content length set */
  9643. char *endptr = NULL;
  9644. conn->content_len = strtoll(cl, &endptr, 10);
  9645. if (endptr == cl) {
  9646. mg_snprintf(conn,
  9647. NULL, /* No truncation check for ebuf */
  9648. ebuf,
  9649. ebuf_len,
  9650. "%s",
  9651. "Bad Request");
  9652. *err = 411;
  9653. return 0;
  9654. }
  9655. /* Publish the content length back to the request info. */
  9656. conn->request_info.content_length = conn->content_len;
  9657. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  9658. != NULL
  9659. && strcmp(cl, "chunked") == 0) {
  9660. conn->is_chunked = 1;
  9661. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  9662. || !mg_strcasecmp(conn->request_info.request_method,
  9663. "PUT")) {
  9664. /* POST or PUT request without content length set */
  9665. conn->content_len = -1;
  9666. } else if (!mg_strncasecmp(conn->request_info.request_method,
  9667. "HTTP/",
  9668. 5)) {
  9669. /* Response without content length set */
  9670. conn->content_len = -1;
  9671. } else {
  9672. /* Other request */
  9673. conn->content_len = 0;
  9674. }
  9675. }
  9676. return 1;
  9677. }
  9678. int
  9679. mg_get_response(struct mg_connection *conn,
  9680. char *ebuf,
  9681. size_t ebuf_len,
  9682. int timeout)
  9683. {
  9684. if (conn) {
  9685. /* Implementation of API function for HTTP clients */
  9686. int err, ret;
  9687. struct mg_context *octx = conn->ctx;
  9688. struct mg_context rctx = *(conn->ctx);
  9689. char txt[32]; /* will not overflow */
  9690. if (timeout >= 0) {
  9691. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  9692. rctx.config[REQUEST_TIMEOUT] = txt;
  9693. set_sock_timeout(conn->client.sock, timeout);
  9694. } else {
  9695. rctx.config[REQUEST_TIMEOUT] = NULL;
  9696. }
  9697. conn->ctx = &rctx;
  9698. ret = getreq(conn, ebuf, ebuf_len, &err);
  9699. conn->ctx = octx;
  9700. /* TODO: 1) uri is deprecated;
  9701. * 2) here, ri.uri is the http response code */
  9702. conn->request_info.uri = conn->request_info.request_uri;
  9703. /* TODO (mid): Define proper return values - maybe return length?
  9704. * For the first test use <0 for error and >0 for OK */
  9705. return (ret == 0) ? -1 : +1;
  9706. }
  9707. return -1;
  9708. }
  9709. struct mg_connection *
  9710. mg_download(const char *host,
  9711. int port,
  9712. int use_ssl,
  9713. char *ebuf,
  9714. size_t ebuf_len,
  9715. const char *fmt,
  9716. ...)
  9717. {
  9718. struct mg_connection *conn;
  9719. va_list ap;
  9720. int i;
  9721. int reqerr;
  9722. va_start(ap, fmt);
  9723. ebuf[0] = '\0';
  9724. /* open a connection */
  9725. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  9726. if (conn != NULL) {
  9727. i = mg_vprintf(conn, fmt, ap);
  9728. if (i <= 0) {
  9729. mg_snprintf(conn,
  9730. NULL, /* No truncation check for ebuf */
  9731. ebuf,
  9732. ebuf_len,
  9733. "%s",
  9734. "Error sending request");
  9735. } else {
  9736. getreq(conn, ebuf, ebuf_len, &reqerr);
  9737. /* TODO: 1) uri is deprecated;
  9738. * 2) here, ri.uri is the http response code */
  9739. conn->request_info.uri = conn->request_info.request_uri;
  9740. }
  9741. }
  9742. /* if an error occured, close the connection */
  9743. if (ebuf[0] != '\0' && conn != NULL) {
  9744. mg_close_connection(conn);
  9745. conn = NULL;
  9746. }
  9747. va_end(ap);
  9748. return conn;
  9749. }
  9750. struct websocket_client_thread_data {
  9751. struct mg_connection *conn;
  9752. mg_websocket_data_handler data_handler;
  9753. mg_websocket_close_handler close_handler;
  9754. void *callback_data;
  9755. };
  9756. #if defined(USE_WEBSOCKET)
  9757. #ifdef _WIN32
  9758. static unsigned __stdcall websocket_client_thread(void *data)
  9759. #else
  9760. static void *
  9761. websocket_client_thread(void *data)
  9762. #endif
  9763. {
  9764. struct websocket_client_thread_data *cdata =
  9765. (struct websocket_client_thread_data *)data;
  9766. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  9767. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  9768. if (cdata->close_handler != NULL) {
  9769. cdata->close_handler(cdata->conn, cdata->callback_data);
  9770. }
  9771. mg_free((void *)cdata);
  9772. #ifdef _WIN32
  9773. return 0;
  9774. #else
  9775. return NULL;
  9776. #endif
  9777. }
  9778. #endif
  9779. struct mg_connection *
  9780. mg_connect_websocket_client(const char *host,
  9781. int port,
  9782. int use_ssl,
  9783. char *error_buffer,
  9784. size_t error_buffer_size,
  9785. const char *path,
  9786. const char *origin,
  9787. mg_websocket_data_handler data_func,
  9788. mg_websocket_close_handler close_func,
  9789. void *user_data)
  9790. {
  9791. struct mg_connection *conn = NULL;
  9792. #if defined(USE_WEBSOCKET)
  9793. struct mg_context *newctx = NULL;
  9794. struct websocket_client_thread_data *thread_data;
  9795. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  9796. static const char *handshake_req;
  9797. if (origin != NULL) {
  9798. handshake_req = "GET %s HTTP/1.1\r\n"
  9799. "Host: %s\r\n"
  9800. "Upgrade: websocket\r\n"
  9801. "Connection: Upgrade\r\n"
  9802. "Sec-WebSocket-Key: %s\r\n"
  9803. "Sec-WebSocket-Version: 13\r\n"
  9804. "Origin: %s\r\n"
  9805. "\r\n";
  9806. } else {
  9807. handshake_req = "GET %s HTTP/1.1\r\n"
  9808. "Host: %s\r\n"
  9809. "Upgrade: websocket\r\n"
  9810. "Connection: Upgrade\r\n"
  9811. "Sec-WebSocket-Key: %s\r\n"
  9812. "Sec-WebSocket-Version: 13\r\n"
  9813. "\r\n";
  9814. }
  9815. /* Establish the client connection and request upgrade */
  9816. conn = mg_download(host,
  9817. port,
  9818. use_ssl,
  9819. error_buffer,
  9820. error_buffer_size,
  9821. handshake_req,
  9822. path,
  9823. host,
  9824. magic,
  9825. origin);
  9826. /* Connection object will be null if something goes wrong */
  9827. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  9828. if (!*error_buffer) {
  9829. /* if there is a connection, but it did not return 101,
  9830. * error_buffer is not yet set */
  9831. mg_snprintf(conn,
  9832. NULL, /* No truncation check for ebuf */
  9833. error_buffer,
  9834. error_buffer_size,
  9835. "Unexpected server reply");
  9836. }
  9837. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  9838. if (conn != NULL) {
  9839. mg_free(conn);
  9840. conn = NULL;
  9841. }
  9842. return conn;
  9843. }
  9844. /* For client connections, mg_context is fake. Since we need to set a
  9845. * callback function, we need to create a copy and modify it. */
  9846. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  9847. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  9848. newctx->user_data = user_data;
  9849. newctx->context_type = 2; /* client context type */
  9850. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  9851. newctx->workerthreadids =
  9852. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  9853. conn->ctx = newctx;
  9854. thread_data = (struct websocket_client_thread_data *)
  9855. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  9856. thread_data->conn = conn;
  9857. thread_data->data_handler = data_func;
  9858. thread_data->close_handler = close_func;
  9859. thread_data->callback_data = NULL;
  9860. /* Start a thread to read the websocket client connection
  9861. * This thread will automatically stop when mg_disconnect is
  9862. * called on the client connection */
  9863. if (mg_start_thread_with_id(websocket_client_thread,
  9864. (void *)thread_data,
  9865. newctx->workerthreadids) != 0) {
  9866. mg_free((void *)thread_data);
  9867. mg_free((void *)newctx->workerthreadids);
  9868. mg_free((void *)newctx);
  9869. mg_free((void *)conn);
  9870. conn = NULL;
  9871. DEBUG_TRACE("%s",
  9872. "Websocket client connect thread could not be started\r\n");
  9873. }
  9874. #else
  9875. /* Appease "unused parameter" warnings */
  9876. (void)host;
  9877. (void)port;
  9878. (void)use_ssl;
  9879. (void)error_buffer;
  9880. (void)error_buffer_size;
  9881. (void)path;
  9882. (void)origin;
  9883. (void)user_data;
  9884. (void)data_func;
  9885. (void)close_func;
  9886. #endif
  9887. return conn;
  9888. }
  9889. static void
  9890. process_new_connection(struct mg_connection *conn)
  9891. {
  9892. if (conn && conn->ctx) {
  9893. struct mg_request_info *ri = &conn->request_info;
  9894. int keep_alive_enabled, keep_alive, discard_len;
  9895. char ebuf[100];
  9896. const char *hostend;
  9897. int reqerr, uri_type;
  9898. keep_alive_enabled =
  9899. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  9900. /* Important: on new connection, reset the receiving buffer. Credit
  9901. * goes to crule42. */
  9902. conn->data_len = 0;
  9903. do {
  9904. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  9905. /* The request sent by the client could not be understood by
  9906. * the server, or it was incomplete or a timeout. Send an
  9907. * error message and close the connection. */
  9908. if (reqerr > 0) {
  9909. /*assert(ebuf[0] != '\0');*/
  9910. send_http_error(conn, reqerr, "%s", ebuf);
  9911. }
  9912. } else if (strcmp(ri->http_version, "1.0")
  9913. && strcmp(ri->http_version, "1.1")) {
  9914. mg_snprintf(conn,
  9915. NULL, /* No truncation check for ebuf */
  9916. ebuf,
  9917. sizeof(ebuf),
  9918. "Bad HTTP version: [%s]",
  9919. ri->http_version);
  9920. send_http_error(conn, 505, "%s", ebuf);
  9921. }
  9922. if (ebuf[0] == '\0') {
  9923. uri_type = get_uri_type(conn->request_info.request_uri);
  9924. switch (uri_type) {
  9925. case 1:
  9926. /* Asterisk */
  9927. conn->request_info.local_uri = NULL;
  9928. break;
  9929. case 2:
  9930. /* relative uri */
  9931. conn->request_info.local_uri =
  9932. conn->request_info.request_uri;
  9933. break;
  9934. case 3:
  9935. case 4:
  9936. /* absolute uri (with/without port) */
  9937. hostend = get_rel_url_at_current_server(
  9938. conn->request_info.request_uri, conn);
  9939. if (hostend) {
  9940. conn->request_info.local_uri = hostend;
  9941. } else {
  9942. conn->request_info.local_uri = NULL;
  9943. }
  9944. break;
  9945. default:
  9946. mg_snprintf(conn,
  9947. NULL, /* No truncation check for ebuf */
  9948. ebuf,
  9949. sizeof(ebuf),
  9950. "Invalid URI: [%s]",
  9951. ri->request_uri);
  9952. send_http_error(conn, 400, "%s", ebuf);
  9953. break;
  9954. }
  9955. /* TODO: cleanup uri, local_uri and request_uri */
  9956. conn->request_info.uri = conn->request_info.local_uri;
  9957. }
  9958. if (ebuf[0] == '\0') {
  9959. handle_request(conn);
  9960. if (conn->ctx->callbacks.end_request != NULL) {
  9961. conn->ctx->callbacks.end_request(conn, conn->status_code);
  9962. }
  9963. log_access(conn);
  9964. } else {
  9965. conn->must_close = 1;
  9966. }
  9967. if (ri->remote_user != NULL) {
  9968. mg_free((void *)ri->remote_user);
  9969. /* Important! When having connections with and without auth
  9970. * would cause double free and then crash */
  9971. ri->remote_user = NULL;
  9972. }
  9973. /* NOTE(lsm): order is important here. should_keep_alive() call is
  9974. * using parsed request, which will be invalid after memmove's
  9975. * below.
  9976. * Therefore, memorize should_keep_alive() result now for later use
  9977. * in loop exit condition. */
  9978. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  9979. && conn->content_len >= 0 && should_keep_alive(conn);
  9980. /* Discard all buffered data for this request */
  9981. discard_len = conn->content_len >= 0 && conn->request_len > 0
  9982. && conn->request_len + conn->content_len
  9983. < (int64_t)conn->data_len
  9984. ? (int)(conn->request_len + conn->content_len)
  9985. : conn->data_len;
  9986. /*assert(discard_len >= 0);*/
  9987. if (discard_len < 0)
  9988. break;
  9989. conn->data_len -= discard_len;
  9990. if (conn->data_len > 0) {
  9991. memmove(conn->buf,
  9992. conn->buf + discard_len,
  9993. (size_t)conn->data_len);
  9994. }
  9995. /* assert(conn->data_len >= 0); */
  9996. /* assert(conn->data_len <= conn->buf_size); */
  9997. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  9998. break;
  9999. }
  10000. } while (keep_alive);
  10001. }
  10002. }
  10003. /* Worker threads take accepted socket from the queue */
  10004. static int
  10005. consume_socket(struct mg_context *ctx, struct socket *sp)
  10006. {
  10007. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10008. if (!ctx) {
  10009. return 0;
  10010. }
  10011. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10012. DEBUG_TRACE("%s", "going idle");
  10013. /* If the queue is empty, wait. We're idle at this point. */
  10014. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10015. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10016. }
  10017. /* If we're stopping, sq_head may be equal to sq_tail. */
  10018. if (ctx->sq_head > ctx->sq_tail) {
  10019. /* Copy socket from the queue and increment tail */
  10020. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10021. ctx->sq_tail++;
  10022. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10023. /* Wrap pointers if needed */
  10024. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10025. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10026. ctx->sq_head -= QUEUE_SIZE(ctx);
  10027. }
  10028. }
  10029. (void)pthread_cond_signal(&ctx->sq_empty);
  10030. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10031. return !ctx->stop_flag;
  10032. #undef QUEUE_SIZE
  10033. }
  10034. static void *
  10035. worker_thread_run(void *thread_func_param)
  10036. {
  10037. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10038. struct mg_connection *conn;
  10039. struct mg_workerTLS tls;
  10040. #if defined(MG_LEGACY_INTERFACE)
  10041. uint32_t addr;
  10042. #endif
  10043. mg_set_thread_name("worker");
  10044. tls.is_master = 0;
  10045. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10046. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10047. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10048. #endif
  10049. conn =
  10050. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10051. if (conn == NULL) {
  10052. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10053. } else {
  10054. pthread_setspecific(sTlsKey, &tls);
  10055. conn->buf_size = MAX_REQUEST_SIZE;
  10056. conn->buf = (char *)(conn + 1);
  10057. conn->ctx = ctx;
  10058. conn->request_info.user_data = ctx->user_data;
  10059. /* Allocate a mutex for this connection to allow communication both
  10060. * within the request handler and from elsewhere in the application */
  10061. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10062. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10063. * signal sq_empty condvar to wake up the master waiting in
  10064. * produce_socket() */
  10065. while (consume_socket(ctx, &conn->client)) {
  10066. conn->conn_birth_time = time(NULL);
  10067. /* Fill in IP, port info early so even if SSL setup below fails,
  10068. * error handler would have the corresponding info.
  10069. * Thanks to Johannes Winkelmann for the patch.
  10070. */
  10071. #if defined(USE_IPV6)
  10072. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10073. conn->request_info.remote_port =
  10074. ntohs(conn->client.rsa.sin6.sin6_port);
  10075. } else
  10076. #endif
  10077. {
  10078. conn->request_info.remote_port =
  10079. ntohs(conn->client.rsa.sin.sin_port);
  10080. }
  10081. sockaddr_to_string(conn->request_info.remote_addr,
  10082. sizeof(conn->request_info.remote_addr),
  10083. &conn->client.rsa);
  10084. #if defined(MG_LEGACY_INTERFACE)
  10085. /* This legacy interface only works for the IPv4 case */
  10086. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10087. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10088. #endif
  10089. conn->request_info.is_ssl = conn->client.is_ssl;
  10090. if (!conn->client.is_ssl
  10091. #ifndef NO_SSL
  10092. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10093. #endif
  10094. ) {
  10095. process_new_connection(conn);
  10096. }
  10097. close_connection(conn);
  10098. }
  10099. }
  10100. /* Signal master that we're done with connection and exiting */
  10101. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10102. ctx->running_worker_threads--;
  10103. (void)pthread_cond_signal(&ctx->thread_cond);
  10104. /* assert(ctx->running_worker_threads >= 0); */
  10105. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10106. pthread_setspecific(sTlsKey, NULL);
  10107. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10108. CloseHandle(tls.pthread_cond_helper_mutex);
  10109. #endif
  10110. mg_free(conn);
  10111. DEBUG_TRACE("%s", "exiting");
  10112. return NULL;
  10113. }
  10114. /* Threads have different return types on Windows and Unix. */
  10115. #ifdef _WIN32
  10116. static unsigned __stdcall worker_thread(void *thread_func_param)
  10117. {
  10118. worker_thread_run(thread_func_param);
  10119. return 0;
  10120. }
  10121. #else
  10122. static void *
  10123. worker_thread(void *thread_func_param)
  10124. {
  10125. worker_thread_run(thread_func_param);
  10126. return NULL;
  10127. }
  10128. #endif /* _WIN32 */
  10129. /* Master thread adds accepted socket to a queue */
  10130. static void
  10131. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10132. {
  10133. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10134. if (!ctx) {
  10135. return;
  10136. }
  10137. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10138. /* If the queue is full, wait */
  10139. while (ctx->stop_flag == 0
  10140. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10141. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10142. }
  10143. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10144. /* Copy socket to the queue and increment head */
  10145. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10146. ctx->sq_head++;
  10147. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10148. }
  10149. (void)pthread_cond_signal(&ctx->sq_full);
  10150. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10151. #undef QUEUE_SIZE
  10152. }
  10153. static void
  10154. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10155. {
  10156. struct socket so;
  10157. char src_addr[IP_ADDR_STR_LEN];
  10158. socklen_t len = sizeof(so.rsa);
  10159. int on = 1;
  10160. int timeout;
  10161. if (!listener) {
  10162. return;
  10163. }
  10164. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10165. == INVALID_SOCKET) {
  10166. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10167. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10168. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10169. closesocket(so.sock);
  10170. so.sock = INVALID_SOCKET;
  10171. } else {
  10172. /* Put so socket structure into the queue */
  10173. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10174. set_close_on_exec(so.sock, fc(ctx));
  10175. so.is_ssl = listener->is_ssl;
  10176. so.ssl_redir = listener->ssl_redir;
  10177. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10178. mg_cry(fc(ctx),
  10179. "%s: getsockname() failed: %s",
  10180. __func__,
  10181. strerror(ERRNO));
  10182. }
  10183. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  10184. * is enabled, and client resets the connection, server won't get
  10185. * TCP FIN or RST and will keep the connection open forever. With TCP
  10186. * keep-alive, next keep-alive handshake will figure out that the
  10187. * client is down and will close the server end.
  10188. * Thanks to Igor Klopov who suggested the patch. */
  10189. if (setsockopt(so.sock,
  10190. SOL_SOCKET,
  10191. SO_KEEPALIVE,
  10192. (SOCK_OPT_TYPE)&on,
  10193. sizeof(on)) != 0) {
  10194. mg_cry(fc(ctx),
  10195. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10196. __func__,
  10197. strerror(ERRNO));
  10198. }
  10199. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10200. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10201. } else {
  10202. timeout = -1;
  10203. }
  10204. /* Set socket timeout to the given value, but not more than a
  10205. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10206. * so the server can exit after that time if requested. */
  10207. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10208. set_sock_timeout(so.sock, timeout);
  10209. } else {
  10210. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10211. }
  10212. produce_socket(ctx, &so);
  10213. }
  10214. }
  10215. static void
  10216. master_thread_run(void *thread_func_param)
  10217. {
  10218. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10219. struct mg_workerTLS tls;
  10220. struct pollfd *pfd;
  10221. unsigned int i;
  10222. unsigned int workerthreadcount;
  10223. if (!ctx) {
  10224. return;
  10225. }
  10226. mg_set_thread_name("master");
  10227. /* Increase priority of the master thread */
  10228. #if defined(_WIN32)
  10229. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10230. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10231. int min_prio = sched_get_priority_min(SCHED_RR);
  10232. int max_prio = sched_get_priority_max(SCHED_RR);
  10233. if ((min_prio >= 0) && (max_prio >= 0)
  10234. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10235. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10236. struct sched_param sched_param = {0};
  10237. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10238. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10239. }
  10240. #endif
  10241. /* Initialize thread local storage */
  10242. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10243. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10244. #endif
  10245. tls.is_master = 1;
  10246. pthread_setspecific(sTlsKey, &tls);
  10247. /* Server starts *now* */
  10248. ctx->start_time = time(NULL);
  10249. /* Allocate memory for the listening sockets, and start the server */
  10250. pfd =
  10251. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10252. while (pfd != NULL && ctx->stop_flag == 0) {
  10253. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10254. pfd[i].fd = ctx->listening_sockets[i].sock;
  10255. pfd[i].events = POLLIN;
  10256. }
  10257. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10258. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10259. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10260. * successful poll, and POLLIN is defined as
  10261. * (POLLRDNORM | POLLRDBAND)
  10262. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10263. * pfd[i].revents == POLLIN. */
  10264. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10265. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10266. }
  10267. }
  10268. }
  10269. }
  10270. mg_free(pfd);
  10271. DEBUG_TRACE("%s", "stopping workers");
  10272. /* Stop signal received: somebody called mg_stop. Quit. */
  10273. close_all_listening_sockets(ctx);
  10274. /* Wakeup workers that are waiting for connections to handle. */
  10275. pthread_cond_broadcast(&ctx->sq_full);
  10276. /* Wait until all threads finish */
  10277. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10278. while (ctx->running_worker_threads > 0) {
  10279. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10280. }
  10281. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10282. /* Join all worker threads to avoid leaking threads. */
  10283. workerthreadcount = ctx->cfg_worker_threads;
  10284. for (i = 0; i < workerthreadcount; i++) {
  10285. if (ctx->workerthreadids[i] != 0) {
  10286. mg_join_thread(ctx->workerthreadids[i]);
  10287. }
  10288. }
  10289. #if !defined(NO_SSL)
  10290. if (ctx->ssl_ctx != NULL) {
  10291. uninitialize_ssl(ctx);
  10292. }
  10293. #endif
  10294. DEBUG_TRACE("%s", "exiting");
  10295. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10296. CloseHandle(tls.pthread_cond_helper_mutex);
  10297. #endif
  10298. pthread_setspecific(sTlsKey, NULL);
  10299. /* Signal mg_stop() that we're done.
  10300. * WARNING: This must be the very last thing this
  10301. * thread does, as ctx becomes invalid after this line. */
  10302. ctx->stop_flag = 2;
  10303. }
  10304. /* Threads have different return types on Windows and Unix. */
  10305. #ifdef _WIN32
  10306. static unsigned __stdcall master_thread(void *thread_func_param)
  10307. {
  10308. master_thread_run(thread_func_param);
  10309. return 0;
  10310. }
  10311. #else
  10312. static void *
  10313. master_thread(void *thread_func_param)
  10314. {
  10315. master_thread_run(thread_func_param);
  10316. return NULL;
  10317. }
  10318. #endif /* _WIN32 */
  10319. static void
  10320. free_context(struct mg_context *ctx)
  10321. {
  10322. int i;
  10323. struct mg_request_handler_info *tmp_rh;
  10324. if (ctx == NULL) {
  10325. return;
  10326. }
  10327. if (ctx->callbacks.exit_context) {
  10328. ctx->callbacks.exit_context(ctx);
  10329. }
  10330. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  10331. */
  10332. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10333. (void)pthread_cond_destroy(&ctx->thread_cond);
  10334. (void)pthread_cond_destroy(&ctx->sq_empty);
  10335. (void)pthread_cond_destroy(&ctx->sq_full);
  10336. /* Destroy other context global data structures mutex */
  10337. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10338. #if defined(USE_TIMERS)
  10339. timers_exit(ctx);
  10340. #endif
  10341. /* Deallocate config parameters */
  10342. for (i = 0; i < NUM_OPTIONS; i++) {
  10343. if (ctx->config[i] != NULL) {
  10344. #if defined(_MSC_VER)
  10345. #pragma warning(suppress : 6001)
  10346. #endif
  10347. mg_free(ctx->config[i]);
  10348. }
  10349. }
  10350. /* Deallocate request handlers */
  10351. while (ctx->request_handlers) {
  10352. tmp_rh = ctx->request_handlers;
  10353. ctx->request_handlers = tmp_rh->next;
  10354. mg_free(tmp_rh->uri);
  10355. mg_free(tmp_rh);
  10356. }
  10357. #ifndef NO_SSL
  10358. /* Deallocate SSL context */
  10359. if (ctx->ssl_ctx != NULL) {
  10360. SSL_CTX_free(ctx->ssl_ctx);
  10361. }
  10362. if (ssl_mutexes != NULL) {
  10363. mg_free(ssl_mutexes);
  10364. ssl_mutexes = NULL;
  10365. }
  10366. #endif /* !NO_SSL */
  10367. /* Deallocate worker thread ID array */
  10368. if (ctx->workerthreadids != NULL) {
  10369. mg_free(ctx->workerthreadids);
  10370. }
  10371. /* Deallocate the tls variable */
  10372. if (mg_atomic_dec(&sTlsInit) == 0) {
  10373. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10374. DeleteCriticalSection(&global_log_file_lock);
  10375. #endif /* _WIN32 && !__SYMBIAN32__ */
  10376. #if !defined(_WIN32)
  10377. pthread_mutexattr_destroy(&pthread_mutex_attr);
  10378. #endif
  10379. pthread_key_delete(sTlsKey);
  10380. }
  10381. /* deallocate system name string */
  10382. mg_free(ctx->systemName);
  10383. /* Deallocate context itself */
  10384. mg_free(ctx);
  10385. }
  10386. void
  10387. mg_stop(struct mg_context *ctx)
  10388. {
  10389. pthread_t mt;
  10390. if (!ctx) {
  10391. return;
  10392. }
  10393. /* We don't use a lock here. Calling mg_stop with the same ctx from
  10394. * two threads is not allowed. */
  10395. mt = ctx->masterthreadid;
  10396. if (mt == 0) {
  10397. return;
  10398. }
  10399. ctx->masterthreadid = 0;
  10400. ctx->stop_flag = 1;
  10401. /* Wait until mg_fini() stops */
  10402. while (ctx->stop_flag != 2) {
  10403. (void)mg_sleep(10);
  10404. }
  10405. mg_join_thread(mt);
  10406. free_context(ctx);
  10407. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10408. (void)WSACleanup();
  10409. #endif /* _WIN32 && !__SYMBIAN32__ */
  10410. }
  10411. static void
  10412. get_system_name(char **sysName)
  10413. {
  10414. #if defined(_WIN32)
  10415. #if !defined(__SYMBIAN32__)
  10416. char name[128];
  10417. DWORD dwVersion = 0;
  10418. DWORD dwMajorVersion = 0;
  10419. DWORD dwMinorVersion = 0;
  10420. DWORD dwBuild = 0;
  10421. #ifdef _MSC_VER
  10422. #pragma warning(push)
  10423. // GetVersion was declared deprecated
  10424. #pragma warning(disable : 4996)
  10425. #endif
  10426. dwVersion = GetVersion();
  10427. #ifdef _MSC_VER
  10428. #pragma warning(pop)
  10429. #endif
  10430. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  10431. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  10432. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  10433. (void)dwBuild;
  10434. sprintf(name,
  10435. "Windows %u.%u",
  10436. (unsigned)dwMajorVersion,
  10437. (unsigned)dwMinorVersion);
  10438. *sysName = mg_strdup(name);
  10439. #else
  10440. *sysName = mg_strdup("Symbian");
  10441. #endif
  10442. #else
  10443. struct utsname name;
  10444. memset(&name, 0, sizeof(name));
  10445. uname(&name);
  10446. *sysName = mg_strdup(name.sysname);
  10447. #endif
  10448. }
  10449. struct mg_context *
  10450. mg_start(const struct mg_callbacks *callbacks,
  10451. void *user_data,
  10452. const char **options)
  10453. {
  10454. struct mg_context *ctx;
  10455. const char *name, *value, *default_value;
  10456. int idx, ok, workerthreadcount;
  10457. unsigned int i;
  10458. void (*exit_callback)(const struct mg_context *ctx) = 0;
  10459. struct mg_workerTLS tls;
  10460. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10461. WSADATA data;
  10462. WSAStartup(MAKEWORD(2, 2), &data);
  10463. #endif /* _WIN32 && !__SYMBIAN32__ */
  10464. /* Allocate context and initialize reasonable general case defaults. */
  10465. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  10466. return NULL;
  10467. }
  10468. /* Random number generator will initialize at the first call */
  10469. ctx->auth_nonce_mask =
  10470. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  10471. if (mg_atomic_inc(&sTlsInit) == 1) {
  10472. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10473. InitializeCriticalSection(&global_log_file_lock);
  10474. #endif /* _WIN32 && !__SYMBIAN32__ */
  10475. #if !defined(_WIN32)
  10476. pthread_mutexattr_init(&pthread_mutex_attr);
  10477. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  10478. #endif
  10479. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  10480. /* Fatal error - abort start. However, this situation should never
  10481. * occur in practice. */
  10482. mg_atomic_dec(&sTlsInit);
  10483. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  10484. mg_free(ctx);
  10485. return NULL;
  10486. }
  10487. } else {
  10488. /* TODO (low): istead of sleeping, check if sTlsKey is already
  10489. * initialized. */
  10490. mg_sleep(1);
  10491. }
  10492. tls.is_master = -1;
  10493. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10494. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10495. tls.pthread_cond_helper_mutex = NULL;
  10496. #endif
  10497. pthread_setspecific(sTlsKey, &tls);
  10498. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  10499. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  10500. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  10501. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  10502. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  10503. if (!ok) {
  10504. /* Fatal error - abort start. However, this situation should never
  10505. * occur in practice. */
  10506. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  10507. mg_free(ctx);
  10508. pthread_setspecific(sTlsKey, NULL);
  10509. return NULL;
  10510. }
  10511. if (callbacks) {
  10512. ctx->callbacks = *callbacks;
  10513. exit_callback = callbacks->exit_context;
  10514. ctx->callbacks.exit_context = 0;
  10515. }
  10516. ctx->user_data = user_data;
  10517. ctx->request_handlers = NULL;
  10518. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10519. ctx->shared_lua_websockets = 0;
  10520. #endif
  10521. while (options && (name = *options++) != NULL) {
  10522. if ((idx = get_option_index(name)) == -1) {
  10523. mg_cry(fc(ctx), "Invalid option: %s", name);
  10524. free_context(ctx);
  10525. pthread_setspecific(sTlsKey, NULL);
  10526. return NULL;
  10527. } else if ((value = *options++) == NULL) {
  10528. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  10529. free_context(ctx);
  10530. pthread_setspecific(sTlsKey, NULL);
  10531. return NULL;
  10532. }
  10533. if (ctx->config[idx] != NULL) {
  10534. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  10535. mg_free(ctx->config[idx]);
  10536. }
  10537. ctx->config[idx] = mg_strdup(value);
  10538. DEBUG_TRACE("[%s] -> [%s]", name, value);
  10539. }
  10540. /* Set default value if needed */
  10541. for (i = 0; config_options[i].name != NULL; i++) {
  10542. default_value = config_options[i].default_value;
  10543. if (ctx->config[i] == NULL && default_value != NULL) {
  10544. ctx->config[i] = mg_strdup(default_value);
  10545. }
  10546. }
  10547. #if defined(NO_FILES)
  10548. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  10549. mg_cry(fc(ctx), "%s", "Document root must not be set");
  10550. free_context(ctx);
  10551. pthread_setspecific(sTlsKey, NULL);
  10552. return NULL;
  10553. }
  10554. #endif
  10555. get_system_name(&ctx->systemName);
  10556. /* NOTE(lsm): order is important here. SSL certificates must
  10557. * be initialized before listening ports. UID must be set last. */
  10558. if (!set_gpass_option(ctx) ||
  10559. #if !defined(NO_SSL)
  10560. !set_ssl_option(ctx) ||
  10561. #endif
  10562. !set_ports_option(ctx) ||
  10563. #if !defined(_WIN32)
  10564. !set_uid_option(ctx) ||
  10565. #endif
  10566. !set_acl_option(ctx)) {
  10567. free_context(ctx);
  10568. pthread_setspecific(sTlsKey, NULL);
  10569. return NULL;
  10570. }
  10571. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  10572. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  10573. * won't kill the whole process. */
  10574. (void)signal(SIGPIPE, SIG_IGN);
  10575. #endif /* !_WIN32 && !__SYMBIAN32__ */
  10576. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  10577. if (workerthreadcount > MAX_WORKER_THREADS) {
  10578. mg_cry(fc(ctx), "Too many worker threads");
  10579. free_context(ctx);
  10580. pthread_setspecific(sTlsKey, NULL);
  10581. return NULL;
  10582. }
  10583. if (workerthreadcount > 0) {
  10584. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  10585. ctx->workerthreadids =
  10586. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  10587. if (ctx->workerthreadids == NULL) {
  10588. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  10589. free_context(ctx);
  10590. pthread_setspecific(sTlsKey, NULL);
  10591. return NULL;
  10592. }
  10593. }
  10594. #if defined(USE_TIMERS)
  10595. if (timers_init(ctx) != 0) {
  10596. mg_cry(fc(ctx), "Error creating timers");
  10597. free_context(ctx);
  10598. pthread_setspecific(sTlsKey, NULL);
  10599. return NULL;
  10600. }
  10601. #endif
  10602. /* Context has been created - init user libraries */
  10603. if (ctx->callbacks.init_context) {
  10604. ctx->callbacks.init_context(ctx);
  10605. }
  10606. ctx->callbacks.exit_context = exit_callback;
  10607. ctx->context_type = 1; /* server context */
  10608. /* Start master (listening) thread */
  10609. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  10610. /* Start worker threads */
  10611. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  10612. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10613. ctx->running_worker_threads++;
  10614. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10615. if (mg_start_thread_with_id(worker_thread,
  10616. ctx,
  10617. &ctx->workerthreadids[i]) != 0) {
  10618. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10619. ctx->running_worker_threads--;
  10620. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10621. if (i > 0) {
  10622. mg_cry(fc(ctx),
  10623. "Cannot start worker thread %i: error %ld",
  10624. i + 1,
  10625. (long)ERRNO);
  10626. } else {
  10627. mg_cry(fc(ctx),
  10628. "Cannot create threads: error %ld",
  10629. (long)ERRNO);
  10630. free_context(ctx);
  10631. pthread_setspecific(sTlsKey, NULL);
  10632. return NULL;
  10633. }
  10634. break;
  10635. }
  10636. }
  10637. pthread_setspecific(sTlsKey, NULL);
  10638. return ctx;
  10639. }
  10640. /* Feature check API function */
  10641. unsigned
  10642. mg_check_feature(unsigned feature)
  10643. {
  10644. static const unsigned feature_set = 0
  10645. /* Set bits for available features according to API documentation.
  10646. * This bit mask is created at compile time, according to the active
  10647. * preprocessor defines. It is a single const value at runtime. */
  10648. #if !defined(NO_FILES)
  10649. | 1
  10650. #endif
  10651. #if !defined(NO_SSL)
  10652. | 2
  10653. #endif
  10654. #if !defined(NO_CGI)
  10655. | 4
  10656. #endif
  10657. #if defined(USE_IPV6)
  10658. | 8
  10659. #endif
  10660. #if defined(USE_WEBSOCKET)
  10661. | 16
  10662. #endif
  10663. #if defined(USE_LUA)
  10664. | 32
  10665. #endif
  10666. #if defined(USE_DUKTAPE)
  10667. | 64
  10668. #endif
  10669. /* Set some extra bits not defined in the API documentation.
  10670. * These bits may change without further notice. */
  10671. #if defined(MG_LEGACY_INTERFACE)
  10672. | 128
  10673. #endif
  10674. #if defined(MEMORY_DEBUGGING)
  10675. | 256
  10676. #endif
  10677. #if defined(USE_TIMERS)
  10678. | 512
  10679. #endif
  10680. #if !defined(NO_NONCE_CHECK)
  10681. | 1024
  10682. #endif
  10683. #if !defined(NO_POPEN)
  10684. | 2048
  10685. #endif
  10686. ;
  10687. return (feature & feature_set);
  10688. }