civetweb.c 334 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928
  1. /* Copyright (c) 2013-2016 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. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  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. #if defined(_WIN64) || defined(__MINGW64__)
  229. #define SSL_LIB "ssleay64.dll"
  230. #define CRYPTO_LIB "libeay64.dll"
  231. #else
  232. #define SSL_LIB "ssleay32.dll"
  233. #define CRYPTO_LIB "libeay32.dll"
  234. #endif
  235. #define O_NONBLOCK (0)
  236. #ifndef W_OK
  237. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  238. #endif
  239. #if !defined(EWOULDBLOCK)
  240. #define EWOULDBLOCK WSAEWOULDBLOCK
  241. #endif /* !EWOULDBLOCK */
  242. #define _POSIX_
  243. #define INT64_FMT "I64d"
  244. #define UINT64_FMT "I64u"
  245. #define WINCDECL __cdecl
  246. #define SHUT_RD (0)
  247. #define SHUT_WR (1)
  248. #define SHUT_BOTH (2)
  249. #define vsnprintf_impl _vsnprintf
  250. #define access _access
  251. #define mg_sleep(x) (Sleep(x))
  252. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  253. #ifndef popen
  254. #define popen(x, y) (_popen(x, y))
  255. #endif
  256. #ifndef pclose
  257. #define pclose(x) (_pclose(x))
  258. #endif
  259. #define close(x) (_close(x))
  260. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  261. #define RTLD_LAZY (0)
  262. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)) == -1 ? -1 : 0)
  263. #define fdopen(x, y) (_fdopen((x), (y)))
  264. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  265. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  266. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  267. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  268. #define sleep(x) (Sleep((x)*1000))
  269. #define rmdir(x) (_rmdir(x))
  270. #define timegm(x) (_mkgmtime(x))
  271. #if !defined(fileno)
  272. #define fileno(x) (_fileno(x))
  273. #endif /* !fileno MINGW #defines fileno */
  274. typedef HANDLE pthread_mutex_t;
  275. typedef DWORD pthread_key_t;
  276. typedef HANDLE pthread_t;
  277. typedef struct {
  278. CRITICAL_SECTION threadIdSec;
  279. int waitingthreadcount; /* The number of threads queued. */
  280. pthread_t *waitingthreadhdls; /* The thread handles. */
  281. } pthread_cond_t;
  282. #ifndef __clockid_t_defined
  283. typedef DWORD clockid_t;
  284. #endif
  285. #ifndef CLOCK_MONOTONIC
  286. #define CLOCK_MONOTONIC (1)
  287. #endif
  288. #ifndef CLOCK_REALTIME
  289. #define CLOCK_REALTIME (2)
  290. #endif
  291. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  292. #define _TIMESPEC_DEFINED
  293. #endif
  294. #ifndef _TIMESPEC_DEFINED
  295. struct timespec {
  296. time_t tv_sec; /* seconds */
  297. long tv_nsec; /* nanoseconds */
  298. };
  299. #endif
  300. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  301. static int pthread_mutex_lock(pthread_mutex_t *);
  302. static int pthread_mutex_unlock(pthread_mutex_t *);
  303. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  304. struct file;
  305. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  306. #if defined(HAVE_STDINT)
  307. #include <stdint.h>
  308. #else
  309. typedef unsigned char uint8_t;
  310. typedef unsigned short uint16_t;
  311. typedef unsigned int uint32_t;
  312. typedef unsigned __int64 uint64_t;
  313. typedef __int64 int64_t;
  314. #define INT64_MAX (9223372036854775807)
  315. #endif /* HAVE_STDINT */
  316. /* POSIX dirent interface */
  317. struct dirent {
  318. char d_name[PATH_MAX];
  319. };
  320. typedef struct DIR {
  321. HANDLE handle;
  322. WIN32_FIND_DATAW info;
  323. struct dirent result;
  324. } DIR;
  325. #if defined(_WIN32) && !defined(POLLIN)
  326. #ifndef HAVE_POLL
  327. struct pollfd {
  328. SOCKET fd;
  329. short events;
  330. short revents;
  331. };
  332. #define POLLIN (0x0300)
  333. #endif
  334. #endif
  335. /* Mark required libraries */
  336. #if defined(_MSC_VER)
  337. #pragma comment(lib, "Ws2_32.lib")
  338. #endif
  339. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  340. block */
  341. #include <sys/wait.h>
  342. #include <sys/socket.h>
  343. #include <sys/poll.h>
  344. #include <netinet/in.h>
  345. #include <arpa/inet.h>
  346. #include <sys/time.h>
  347. #include <sys/utsname.h>
  348. #include <stdint.h>
  349. #include <inttypes.h>
  350. #include <netdb.h>
  351. #include <netinet/tcp.h>
  352. typedef const void *SOCK_OPT_TYPE;
  353. #if defined(ANDROID)
  354. typedef unsigned short int in_port_t;
  355. #endif
  356. #include <pwd.h>
  357. #include <unistd.h>
  358. #include <grp.h>
  359. #include <dirent.h>
  360. #define vsnprintf_impl vsnprintf
  361. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  362. #include <dlfcn.h>
  363. #endif
  364. #include <pthread.h>
  365. #if defined(__MACH__)
  366. #define SSL_LIB "libssl.dylib"
  367. #define CRYPTO_LIB "libcrypto.dylib"
  368. #else
  369. #if !defined(SSL_LIB)
  370. #define SSL_LIB "libssl.so"
  371. #endif
  372. #if !defined(CRYPTO_LIB)
  373. #define CRYPTO_LIB "libcrypto.so"
  374. #endif
  375. #endif
  376. #ifndef O_BINARY
  377. #define O_BINARY (0)
  378. #endif /* O_BINARY */
  379. #define closesocket(a) (close(a))
  380. #define mg_mkdir(x, y) (mkdir(x, y))
  381. #define mg_remove(x) (remove(x))
  382. #define mg_sleep(x) (usleep((x)*1000))
  383. #define ERRNO (errno)
  384. #define INVALID_SOCKET (-1)
  385. #define INT64_FMT PRId64
  386. #define UINT64_FMT PRIu64
  387. typedef int SOCKET;
  388. #define WINCDECL
  389. #if defined(__hpux)
  390. /* HPUX 11 does not have monotonic, fall back to realtime */
  391. #ifndef CLOCK_MONOTONIC
  392. #define CLOCK_MONOTONIC CLOCK_REALTIME
  393. #endif
  394. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  395. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  396. * the prototypes use int* rather than socklen_t* which matches the
  397. * actual library expectation. When called with the wrong size arg
  398. * accept() returns a zero client inet addr and check_acl() always
  399. * fails. Since socklen_t is widely used below, just force replace
  400. * their typedef with int. - DTL
  401. */
  402. #define socklen_t int
  403. #endif /* hpux */
  404. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - WINDOWS / UNIX include \
  405. block */
  406. /* va_copy should always be a macro, C99 and C++11 - DTL */
  407. #ifndef va_copy
  408. #define va_copy(x, y) ((x) = (y))
  409. #endif
  410. #ifdef _WIN32
  411. /* Create substitutes for POSIX functions in Win32. */
  412. #if defined(__MINGW32__)
  413. /* Show no warning in case system functions are not used. */
  414. #pragma GCC diagnostic push
  415. #pragma GCC diagnostic ignored "-Wunused-function"
  416. #endif
  417. static CRITICAL_SECTION global_log_file_lock;
  418. static DWORD
  419. pthread_self(void)
  420. {
  421. return GetCurrentThreadId();
  422. }
  423. static int
  424. pthread_key_create(
  425. pthread_key_t *key,
  426. void (*_ignored)(void *) /* destructor not supported for Windows */
  427. )
  428. {
  429. (void)_ignored;
  430. if ((key != 0)) {
  431. *key = TlsAlloc();
  432. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  433. }
  434. return -2;
  435. }
  436. static int
  437. pthread_key_delete(pthread_key_t key)
  438. {
  439. return TlsFree(key) ? 0 : 1;
  440. }
  441. static int
  442. pthread_setspecific(pthread_key_t key, void *value)
  443. {
  444. return TlsSetValue(key, value) ? 0 : 1;
  445. }
  446. static void *
  447. pthread_getspecific(pthread_key_t key)
  448. {
  449. return TlsGetValue(key);
  450. }
  451. #if defined(__MINGW32__)
  452. /* Enable unused function warning again */
  453. #pragma GCC diagnostic pop
  454. #endif
  455. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  456. #else
  457. static pthread_mutexattr_t pthread_mutex_attr;
  458. #endif /* _WIN32 */
  459. #include "civetweb.h"
  460. #define PASSWORDS_FILE_NAME ".htpasswd"
  461. #define CGI_ENVIRONMENT_SIZE (4096)
  462. #define MAX_CGI_ENVIR_VARS (256)
  463. #define MG_BUF_LEN (8192)
  464. #ifndef MAX_REQUEST_SIZE
  465. #define MAX_REQUEST_SIZE (16384)
  466. #endif
  467. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  468. "request size length must be a positive number");
  469. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  470. #if !defined(DEBUG_TRACE)
  471. #if defined(DEBUG)
  472. static void DEBUG_TRACE_FUNC(const char *func,
  473. unsigned line,
  474. PRINTF_FORMAT_STRING(const char *fmt),
  475. ...) PRINTF_ARGS(3, 4);
  476. static void
  477. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  478. {
  479. va_list args;
  480. flockfile(stdout);
  481. printf("*** %lu.%p.%s.%u: ",
  482. (unsigned long)time(NULL),
  483. (void *)pthread_self(),
  484. func,
  485. line);
  486. va_start(args, fmt);
  487. vprintf(fmt, args);
  488. va_end(args);
  489. putchar('\n');
  490. fflush(stdout);
  491. funlockfile(stdout);
  492. }
  493. #define DEBUG_TRACE(fmt, ...) \
  494. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  495. #else
  496. #define DEBUG_TRACE(fmt, ...) \
  497. do { \
  498. } while (0)
  499. #endif /* DEBUG */
  500. #endif /* DEBUG_TRACE */
  501. #if defined(MEMORY_DEBUGGING)
  502. unsigned long mg_memory_debug_blockCount = 0;
  503. unsigned long mg_memory_debug_totalMemUsed = 0;
  504. static void *
  505. mg_malloc_ex(size_t size, const char *file, unsigned line)
  506. {
  507. void *data = malloc(size + sizeof(size_t));
  508. void *memory = 0;
  509. char mallocStr[256];
  510. if (data) {
  511. *(size_t *)data = size;
  512. mg_memory_debug_totalMemUsed += size;
  513. mg_memory_debug_blockCount++;
  514. memory = (void *)(((char *)data) + sizeof(size_t));
  515. }
  516. sprintf(mallocStr,
  517. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  518. memory,
  519. (unsigned long)size,
  520. mg_memory_debug_totalMemUsed,
  521. mg_memory_debug_blockCount,
  522. file,
  523. line);
  524. #if defined(_WIN32)
  525. OutputDebugStringA(mallocStr);
  526. #else
  527. DEBUG_TRACE("%s", mallocStr);
  528. #endif
  529. return memory;
  530. }
  531. static void *
  532. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  533. {
  534. void *data = mg_malloc_ex(size * count, file, line);
  535. if (data) {
  536. memset(data, 0, size);
  537. }
  538. return data;
  539. }
  540. static void
  541. mg_free_ex(void *memory, const char *file, unsigned line)
  542. {
  543. char mallocStr[256];
  544. void *data = (void *)(((char *)memory) - sizeof(size_t));
  545. size_t size;
  546. if (memory) {
  547. size = *(size_t *)data;
  548. mg_memory_debug_totalMemUsed -= size;
  549. mg_memory_debug_blockCount--;
  550. sprintf(mallocStr,
  551. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  552. memory,
  553. (unsigned long)size,
  554. mg_memory_debug_totalMemUsed,
  555. mg_memory_debug_blockCount,
  556. file,
  557. line);
  558. #if defined(_WIN32)
  559. OutputDebugStringA(mallocStr);
  560. #else
  561. DEBUG_TRACE("%s", mallocStr);
  562. #endif
  563. free(data);
  564. }
  565. }
  566. static void *
  567. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  568. {
  569. char mallocStr[256];
  570. void *data;
  571. void *_realloc;
  572. size_t oldsize;
  573. if (newsize) {
  574. if (memory) {
  575. data = (void *)(((char *)memory) - sizeof(size_t));
  576. oldsize = *(size_t *)data;
  577. _realloc = realloc(data, newsize + sizeof(size_t));
  578. if (_realloc) {
  579. data = _realloc;
  580. mg_memory_debug_totalMemUsed -= oldsize;
  581. sprintf(mallocStr,
  582. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  583. memory,
  584. (unsigned long)oldsize,
  585. mg_memory_debug_totalMemUsed,
  586. mg_memory_debug_blockCount,
  587. file,
  588. line);
  589. #if defined(_WIN32)
  590. OutputDebugStringA(mallocStr);
  591. #else
  592. DEBUG_TRACE("%s", mallocStr);
  593. #endif
  594. mg_memory_debug_totalMemUsed += newsize;
  595. sprintf(mallocStr,
  596. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  597. memory,
  598. (unsigned long)newsize,
  599. mg_memory_debug_totalMemUsed,
  600. mg_memory_debug_blockCount,
  601. file,
  602. line);
  603. #if defined(_WIN32)
  604. OutputDebugStringA(mallocStr);
  605. #else
  606. DEBUG_TRACE("%s", mallocStr);
  607. #endif
  608. *(size_t *)data = newsize;
  609. data = (void *)(((char *)data) + sizeof(size_t));
  610. } else {
  611. #if defined(_WIN32)
  612. OutputDebugStringA("MEM: realloc failed\n");
  613. #else
  614. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  615. #endif
  616. return _realloc;
  617. }
  618. } else {
  619. data = mg_malloc_ex(newsize, file, line);
  620. }
  621. } else {
  622. data = 0;
  623. mg_free_ex(memory, file, line);
  624. }
  625. return data;
  626. }
  627. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  628. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  629. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  630. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  631. #else
  632. static __inline void *
  633. mg_malloc(size_t a)
  634. {
  635. return malloc(a);
  636. }
  637. static __inline void *
  638. mg_calloc(size_t a, size_t b)
  639. {
  640. return calloc(a, b);
  641. }
  642. static __inline void *
  643. mg_realloc(void *a, size_t b)
  644. {
  645. return realloc(a, b);
  646. }
  647. static __inline void
  648. mg_free(void *a)
  649. {
  650. free(a);
  651. }
  652. #endif
  653. static void mg_vsnprintf(const struct mg_connection *conn,
  654. int *truncated,
  655. char *buf,
  656. size_t buflen,
  657. const char *fmt,
  658. va_list ap);
  659. static void mg_snprintf(const struct mg_connection *conn,
  660. int *truncated,
  661. char *buf,
  662. size_t buflen,
  663. PRINTF_FORMAT_STRING(const char *fmt),
  664. ...) PRINTF_ARGS(5, 6);
  665. /* This following lines are just meant as a reminder to use the mg-functions
  666. * for memory management */
  667. #ifdef malloc
  668. #undef malloc
  669. #endif
  670. #ifdef calloc
  671. #undef calloc
  672. #endif
  673. #ifdef realloc
  674. #undef realloc
  675. #endif
  676. #ifdef free
  677. #undef free
  678. #endif
  679. #ifdef snprintf
  680. #undef snprintf
  681. #endif
  682. #ifdef vsnprintf
  683. #undef vsnprintf
  684. #endif
  685. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  686. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  687. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  688. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  689. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  690. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \
  691. * but this define only works well for Windows. */
  692. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  693. #endif
  694. #define MD5_STATIC static
  695. #include "md5.inl"
  696. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  697. #ifdef NO_SOCKLEN_T
  698. typedef int socklen_t;
  699. #endif /* NO_SOCKLEN_T */
  700. #define _DARWIN_UNLIMITED_SELECT
  701. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  702. #if !defined(MSG_NOSIGNAL)
  703. #define MSG_NOSIGNAL (0)
  704. #endif
  705. #if !defined(SOMAXCONN)
  706. #define SOMAXCONN (100)
  707. #endif
  708. /* Size of the accepted socket queue */
  709. #if !defined(MGSQLEN)
  710. #define MGSQLEN (20)
  711. #endif
  712. #if defined(NO_SSL_DL)
  713. #include <openssl/ssl.h>
  714. #include <openssl/err.h>
  715. #include <openssl/crypto.h>
  716. #include <openssl/x509.h>
  717. #include <openssl/pem.h>
  718. #else
  719. /* SSL loaded dynamically from DLL.
  720. * I put the prototypes here to be independent from OpenSSL source
  721. * installation. */
  722. typedef struct ssl_st SSL;
  723. typedef struct ssl_method_st SSL_METHOD;
  724. typedef struct ssl_ctx_st SSL_CTX;
  725. typedef struct x509_store_ctx_st X509_STORE_CTX;
  726. #define SSL_CTRL_OPTIONS (32)
  727. #define SSL_CTRL_CLEAR_OPTIONS (77)
  728. #define SSL_CTRL_SET_ECDH_AUTO (94)
  729. #define SSL_VERIFY_NONE (0)
  730. #define SSL_VERIFY_PEER (1)
  731. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  732. #define SSL_VERIFY_CLIENT_ONCE (4)
  733. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  734. #define SSL_OP_NO_SSLv2 (0x01000000L)
  735. #define SSL_OP_NO_SSLv3 (0x02000000L)
  736. #define SSL_OP_NO_TLSv1 (0x04000000L)
  737. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  738. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  739. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  740. struct ssl_func {
  741. const char *name; /* SSL function name */
  742. void (*ptr)(void); /* Function pointer */
  743. };
  744. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  745. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  746. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  747. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  748. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  749. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  750. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  751. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  752. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  753. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  754. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  755. #define SSL_CTX_use_PrivateKey_file \
  756. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  757. #define SSL_CTX_use_certificate_file \
  758. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  759. #define SSL_CTX_set_default_passwd_cb \
  760. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  761. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  762. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  763. #define SSL_CTX_use_certificate_chain_file \
  764. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  765. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  766. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  767. #define SSL_CTX_set_verify \
  768. (*(void (*)(SSL_CTX *, \
  769. int, \
  770. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  771. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  772. #define SSL_CTX_load_verify_locations \
  773. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  774. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  775. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  776. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  777. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  778. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  779. #define SSL_CIPHER_get_name \
  780. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  781. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  782. #define SSL_CTX_set_session_id_context \
  783. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  784. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  785. #define SSL_CTX_set_cipher_list \
  786. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  787. #define SSL_CTX_set_options(ctx, op) \
  788. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  789. #define SSL_CTX_clear_options(ctx, op) \
  790. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  791. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  792. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  793. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  794. #define CRYPTO_set_locking_callback \
  795. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  796. #define CRYPTO_set_id_callback \
  797. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  798. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  799. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  800. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  801. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  802. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  803. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  804. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  805. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  806. /* set_ssl_option() function updates this array.
  807. * It loads SSL library dynamically and changes NULLs to the actual addresses
  808. * of respective functions. The macros above (like SSL_connect()) are really
  809. * just calling these functions indirectly via the pointer. */
  810. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  811. {"SSL_accept", NULL},
  812. {"SSL_connect", NULL},
  813. {"SSL_read", NULL},
  814. {"SSL_write", NULL},
  815. {"SSL_get_error", NULL},
  816. {"SSL_set_fd", NULL},
  817. {"SSL_new", NULL},
  818. {"SSL_CTX_new", NULL},
  819. {"SSLv23_server_method", NULL},
  820. {"SSL_library_init", NULL},
  821. {"SSL_CTX_use_PrivateKey_file", NULL},
  822. {"SSL_CTX_use_certificate_file", NULL},
  823. {"SSL_CTX_set_default_passwd_cb", NULL},
  824. {"SSL_CTX_free", NULL},
  825. {"SSL_load_error_strings", NULL},
  826. {"SSL_CTX_use_certificate_chain_file", NULL},
  827. {"SSLv23_client_method", NULL},
  828. {"SSL_pending", NULL},
  829. {"SSL_CTX_set_verify", NULL},
  830. {"SSL_shutdown", NULL},
  831. {"SSL_CTX_load_verify_locations", NULL},
  832. {"SSL_CTX_set_default_verify_paths", NULL},
  833. {"SSL_CTX_set_verify_depth", NULL},
  834. {"SSL_get_peer_certificate", NULL},
  835. {"SSL_get_version", NULL},
  836. {"SSL_get_current_cipher", NULL},
  837. {"SSL_CIPHER_get_name", NULL},
  838. {"SSL_CTX_check_private_key", NULL},
  839. {"SSL_CTX_set_session_id_context", NULL},
  840. {"SSL_CTX_ctrl", NULL},
  841. {"SSL_CTX_set_cipher_list", NULL},
  842. {NULL, NULL}};
  843. /* Similar array as ssl_sw. These functions could be located in different
  844. * lib. */
  845. #if !defined(NO_SSL)
  846. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  847. {"CRYPTO_set_locking_callback", NULL},
  848. {"CRYPTO_set_id_callback", NULL},
  849. {"ERR_get_error", NULL},
  850. {"ERR_error_string", NULL},
  851. {"ERR_remove_state", NULL},
  852. {"ERR_free_strings", NULL},
  853. {"ENGINE_cleanup", NULL},
  854. {"CONF_modules_unload", NULL},
  855. {"CRYPTO_cleanup_all_ex_data", NULL},
  856. {"EVP_cleanup", NULL},
  857. {NULL, NULL}};
  858. #endif /* NO_SSL */
  859. #endif /* NO_SSL_DL */
  860. static const char *month_names[] = {"Jan",
  861. "Feb",
  862. "Mar",
  863. "Apr",
  864. "May",
  865. "Jun",
  866. "Jul",
  867. "Aug",
  868. "Sep",
  869. "Oct",
  870. "Nov",
  871. "Dec"};
  872. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  873. * union u. */
  874. union usa {
  875. struct sockaddr sa;
  876. struct sockaddr_in sin;
  877. #if defined(USE_IPV6)
  878. struct sockaddr_in6 sin6;
  879. #endif
  880. };
  881. /* Describes a string (chunk of memory). */
  882. struct vec {
  883. const char *ptr;
  884. size_t len;
  885. };
  886. struct file {
  887. uint64_t size;
  888. time_t last_modified;
  889. FILE *fp;
  890. const char *membuf; /* Non-NULL if file data is in memory */
  891. int is_directory;
  892. int gzipped; /* set to 1 if the content is gzipped
  893. * in which case we need a content-encoding: gzip header */
  894. };
  895. #define STRUCT_FILE_INITIALIZER \
  896. { \
  897. (uint64_t)0, (time_t)0, (FILE *)NULL, (const char *)NULL, 0, 0 \
  898. }
  899. /* Describes listening socket, or socket which was accept()-ed by the master
  900. * thread and queued for future handling by the worker thread. */
  901. struct socket {
  902. SOCKET sock; /* Listening socket */
  903. union usa lsa; /* Local socket address */
  904. union usa rsa; /* Remote socket address */
  905. unsigned char is_ssl; /* Is port SSL-ed */
  906. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  907. * port */
  908. };
  909. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  910. enum {
  911. CGI_EXTENSIONS,
  912. CGI_ENVIRONMENT,
  913. PUT_DELETE_PASSWORDS_FILE,
  914. CGI_INTERPRETER,
  915. PROTECT_URI,
  916. AUTHENTICATION_DOMAIN,
  917. SSI_EXTENSIONS,
  918. THROTTLE,
  919. ACCESS_LOG_FILE,
  920. ENABLE_DIRECTORY_LISTING,
  921. ERROR_LOG_FILE,
  922. GLOBAL_PASSWORDS_FILE,
  923. INDEX_FILES,
  924. ENABLE_KEEP_ALIVE,
  925. ACCESS_CONTROL_LIST,
  926. EXTRA_MIME_TYPES,
  927. LISTENING_PORTS,
  928. DOCUMENT_ROOT,
  929. SSL_CERTIFICATE,
  930. NUM_THREADS,
  931. RUN_AS_USER,
  932. REWRITE,
  933. HIDE_FILES,
  934. REQUEST_TIMEOUT,
  935. SSL_DO_VERIFY_PEER,
  936. SSL_CA_PATH,
  937. SSL_CA_FILE,
  938. SSL_VERIFY_DEPTH,
  939. SSL_DEFAULT_VERIFY_PATHS,
  940. SSL_CIPHER_LIST,
  941. SSL_PROTOCOL_VERSION,
  942. SSL_SHORT_TRUST,
  943. #if defined(USE_WEBSOCKET)
  944. WEBSOCKET_TIMEOUT,
  945. #endif
  946. DECODE_URL,
  947. #if defined(USE_LUA)
  948. LUA_PRELOAD_FILE,
  949. LUA_SCRIPT_EXTENSIONS,
  950. LUA_SERVER_PAGE_EXTENSIONS,
  951. #endif
  952. #if defined(USE_DUKTAPE)
  953. DUKTAPE_SCRIPT_EXTENSIONS,
  954. #endif
  955. #if defined(USE_WEBSOCKET)
  956. WEBSOCKET_ROOT,
  957. #endif
  958. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  959. LUA_WEBSOCKET_EXTENSIONS,
  960. #endif
  961. ACCESS_CONTROL_ALLOW_ORIGIN,
  962. ERROR_PAGES,
  963. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  964. * socket option typedef TCP_NODELAY. */
  965. STATIC_FILE_MAX_AGE,
  966. NUM_OPTIONS
  967. };
  968. /* Config option name, config types, default value */
  969. static struct mg_option config_options[] = {
  970. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  971. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  972. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  973. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  974. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  975. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  976. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  977. {"throttle", CONFIG_TYPE_STRING, NULL},
  978. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  979. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  980. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  981. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  982. {"index_files",
  983. CONFIG_TYPE_STRING,
  984. #ifdef USE_LUA
  985. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  986. "index.shtml,index.php"},
  987. #else
  988. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  989. #endif
  990. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  991. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  992. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  993. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  994. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  995. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  996. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  997. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  998. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  999. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1000. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1001. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1002. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1003. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1004. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1005. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1006. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1007. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1008. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1009. #if defined(USE_WEBSOCKET)
  1010. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1011. #endif
  1012. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1013. #if defined(USE_LUA)
  1014. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1015. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1016. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1017. #endif
  1018. #if defined(USE_DUKTAPE)
  1019. {"_experimental_duktape_script_pattern",
  1020. CONFIG_TYPE_EXT_PATTERN,
  1021. "**.ssjs$"}, /* TODO: redefine parameter */
  1022. #endif
  1023. #if defined(USE_WEBSOCKET)
  1024. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1025. #endif
  1026. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1027. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1028. #endif
  1029. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1030. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1031. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1032. {"_experimental_static_file_max_age",
  1033. CONFIG_TYPE_NUMBER,
  1034. "3600"}, /* TODO: redefine parameter */
  1035. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1036. /* Check if the config_options and the corresponding enum have compatible
  1037. * sizes. */
  1038. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1039. == (NUM_OPTIONS + 1),
  1040. "config_options and enum not sync");
  1041. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1042. struct mg_handler_info {
  1043. /* Name/Pattern of the URI. */
  1044. char *uri;
  1045. size_t uri_len;
  1046. /* handler type */
  1047. int handler_type;
  1048. /* Handler for http/https or authorization requests. */
  1049. mg_request_handler handler;
  1050. /* Handler for ws/wss (websocket) requests. */
  1051. mg_websocket_connect_handler connect_handler;
  1052. mg_websocket_ready_handler ready_handler;
  1053. mg_websocket_data_handler data_handler;
  1054. mg_websocket_close_handler close_handler;
  1055. /* Handler for authorization requests */
  1056. mg_authorization_handler auth_handler;
  1057. /* User supplied argument for the handler function. */
  1058. void *cbdata;
  1059. /* next handler in a linked list */
  1060. struct mg_handler_info *next;
  1061. };
  1062. struct mg_context {
  1063. volatile int stop_flag; /* Should we stop event loop */
  1064. SSL_CTX *ssl_ctx; /* SSL context */
  1065. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1066. struct mg_callbacks callbacks; /* User-defined callback function */
  1067. void *user_data; /* User-defined data */
  1068. int context_type; /* 1 = server context, 2 = client context */
  1069. struct socket *listening_sockets;
  1070. in_port_t *listening_ports;
  1071. unsigned int num_listening_sockets;
  1072. volatile int
  1073. running_worker_threads; /* Number of currently running worker threads */
  1074. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1075. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  1076. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1077. volatile int sq_head; /* Head of the socket queue */
  1078. volatile int sq_tail; /* Tail of the socket queue */
  1079. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1080. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1081. pthread_t masterthreadid; /* The master thread ID */
  1082. unsigned int
  1083. cfg_worker_threads; /* The number of configured worker threads. */
  1084. pthread_t *workerthreadids; /* The worker thread IDs */
  1085. time_t start_time; /* Server start time, used for authentication */
  1086. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1087. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1088. unsigned long nonce_count; /* Used nonces, used for authentication */
  1089. char *systemName; /* What operating system is running */
  1090. /* linked list of uri handlers */
  1091. struct mg_handler_info *handlers;
  1092. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1093. /* linked list of shared lua websockets */
  1094. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1095. #endif
  1096. #ifdef USE_TIMERS
  1097. struct ttimers *timers;
  1098. #endif
  1099. };
  1100. struct mg_connection {
  1101. struct mg_request_info request_info;
  1102. struct mg_context *ctx;
  1103. SSL *ssl; /* SSL descriptor */
  1104. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1105. struct socket client; /* Connected client */
  1106. time_t conn_birth_time; /* Time (wall clock) when connection was
  1107. * established */
  1108. struct timespec req_time; /* Time (since system start) when the request
  1109. * was received */
  1110. int64_t num_bytes_sent; /* Total bytes sent to client */
  1111. int64_t content_len; /* Content-Length header value */
  1112. int64_t consumed_content; /* How many bytes of content have been read */
  1113. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1114. * data available, 2: all data read */
  1115. size_t chunk_remainder; /* Unread data from the last chunk */
  1116. char *buf; /* Buffer for received data */
  1117. char *path_info; /* PATH_INFO part of the URL */
  1118. int must_close; /* 1 if connection must be closed */
  1119. int in_error_handler; /* 1 if in handler for user defined error
  1120. * pages */
  1121. int internal_error; /* 1 if an error occured while processing the
  1122. * request */
  1123. int buf_size; /* Buffer size */
  1124. int request_len; /* Size of the request + headers in a buffer */
  1125. int data_len; /* Total size of data in a buffer */
  1126. int status_code; /* HTTP reply status code, e.g. 200 */
  1127. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1128. * throttle */
  1129. time_t last_throttle_time; /* Last time throttled data was sent */
  1130. int64_t last_throttle_bytes; /* Bytes sent this second */
  1131. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1132. * atomic transmissions for websockets */
  1133. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1134. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1135. #endif
  1136. };
  1137. static pthread_key_t sTlsKey; /* Thread local storage index */
  1138. static int sTlsInit = 0;
  1139. static int thread_idx_max = 0;
  1140. struct mg_workerTLS {
  1141. int is_master;
  1142. unsigned long thread_idx;
  1143. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1144. HANDLE pthread_cond_helper_mutex;
  1145. #endif
  1146. };
  1147. /* Directory entry */
  1148. struct de {
  1149. struct mg_connection *conn;
  1150. char *file_name;
  1151. struct file file;
  1152. };
  1153. #if defined(USE_WEBSOCKET)
  1154. static int is_websocket_protocol(const struct mg_connection *conn);
  1155. #else
  1156. #define is_websocket_protocol(conn) (0)
  1157. #endif
  1158. static int
  1159. mg_atomic_inc(volatile int *addr)
  1160. {
  1161. int ret;
  1162. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1163. /* Depending on the SDK, this function uses either
  1164. * (volatile unsigned int *) or (volatile LONG *),
  1165. * so whatever you use, the other SDK is likely to raise a warning. */
  1166. ret = InterlockedIncrement((volatile long *)addr);
  1167. #elif defined(__GNUC__) \
  1168. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1169. ret = __sync_add_and_fetch(addr, 1);
  1170. #else
  1171. ret = (++(*addr));
  1172. #endif
  1173. return ret;
  1174. }
  1175. static int
  1176. mg_atomic_dec(volatile int *addr)
  1177. {
  1178. int ret;
  1179. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1180. /* Depending on the SDK, this function uses either
  1181. * (volatile unsigned int *) or (volatile LONG *),
  1182. * so whatever you use, the other SDK is likely to raise a warning. */
  1183. ret = InterlockedDecrement((volatile long *)addr);
  1184. #elif defined(__GNUC__) \
  1185. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1186. ret = __sync_sub_and_fetch(addr, 1);
  1187. #else
  1188. ret = (--(*addr));
  1189. #endif
  1190. return ret;
  1191. }
  1192. #if !defined(NO_THREAD_NAME)
  1193. #if defined(_WIN32) && defined(_MSC_VER)
  1194. /* Set the thread name for debugging purposes in Visual Studio
  1195. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1196. */
  1197. #pragma pack(push, 8)
  1198. typedef struct tagTHREADNAME_INFO {
  1199. DWORD dwType; /* Must be 0x1000. */
  1200. LPCSTR szName; /* Pointer to name (in user addr space). */
  1201. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1202. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1203. } THREADNAME_INFO;
  1204. #pragma pack(pop)
  1205. #elif defined(__linux__)
  1206. #include <sys/prctl.h>
  1207. #include <sys/sendfile.h>
  1208. #endif
  1209. static void
  1210. mg_set_thread_name(const char *name)
  1211. {
  1212. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1213. mg_snprintf(
  1214. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1215. #if defined(_WIN32)
  1216. #if defined(_MSC_VER)
  1217. /* Windows and Visual Studio Compiler */
  1218. __try
  1219. {
  1220. THREADNAME_INFO info;
  1221. info.dwType = 0x1000;
  1222. info.szName = threadName;
  1223. info.dwThreadID = ~0U;
  1224. info.dwFlags = 0;
  1225. RaiseException(0x406D1388,
  1226. 0,
  1227. sizeof(info) / sizeof(ULONG_PTR),
  1228. (ULONG_PTR *)&info);
  1229. }
  1230. __except(EXCEPTION_EXECUTE_HANDLER)
  1231. {
  1232. }
  1233. #elif defined(__MINGW32__)
  1234. /* No option known to set thread name for MinGW */
  1235. #endif
  1236. #elif defined(__GLIBC__) \
  1237. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1238. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1239. (void)pthread_setname_np(pthread_self(), threadName);
  1240. #elif defined(__linux__)
  1241. /* on linux we can use the old prctl function */
  1242. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1243. #endif
  1244. }
  1245. #else /* !defined(NO_THREAD_NAME) */
  1246. void
  1247. mg_set_thread_name(const char *threadName)
  1248. {
  1249. }
  1250. #endif
  1251. #if defined(MG_LEGACY_INTERFACE)
  1252. const char **
  1253. mg_get_valid_option_names(void)
  1254. {
  1255. /* This function is deprecated. Use mg_get_valid_options instead. */
  1256. static const char *
  1257. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1258. int i;
  1259. for (i = 0; config_options[i].name != NULL; i++) {
  1260. data[i * 2] = config_options[i].name;
  1261. data[i * 2 + 1] = config_options[i].default_value;
  1262. }
  1263. return data;
  1264. }
  1265. #endif
  1266. const struct mg_option *
  1267. mg_get_valid_options(void)
  1268. {
  1269. return config_options;
  1270. }
  1271. static int
  1272. is_file_in_memory(const struct mg_connection *conn,
  1273. const char *path,
  1274. struct file *filep)
  1275. {
  1276. size_t size = 0;
  1277. if (!conn || !filep) {
  1278. return 0;
  1279. }
  1280. if (conn->ctx->callbacks.open_file) {
  1281. filep->membuf = conn->ctx->callbacks.open_file(conn, path, &size);
  1282. if (filep->membuf != NULL) {
  1283. /* NOTE: override filep->size only on success. Otherwise, it might
  1284. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1285. filep->size = size;
  1286. }
  1287. }
  1288. return filep->membuf != NULL;
  1289. }
  1290. static int
  1291. is_file_opened(const struct file *filep)
  1292. {
  1293. if (!filep) {
  1294. return 0;
  1295. }
  1296. return filep->membuf != NULL || filep->fp != NULL;
  1297. }
  1298. static int
  1299. mg_fopen(const struct mg_connection *conn,
  1300. const char *path,
  1301. const char *mode,
  1302. struct file *filep)
  1303. {
  1304. struct stat st;
  1305. if (!filep) {
  1306. return 0;
  1307. }
  1308. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1309. * only get the file status. They should not work on different members of
  1310. * the same structure (bad cohesion). */
  1311. memset(filep, 0, sizeof(*filep));
  1312. if (stat(path, &st) == 0) {
  1313. filep->size = (uint64_t)(st.st_size);
  1314. }
  1315. if (!is_file_in_memory(conn, path, filep)) {
  1316. #ifdef _WIN32
  1317. wchar_t wbuf[PATH_MAX], wmode[20];
  1318. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1319. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1320. filep->fp = _wfopen(wbuf, wmode);
  1321. #else
  1322. /* Linux et al already use unicode. No need to convert. */
  1323. filep->fp = fopen(path, mode);
  1324. #endif
  1325. }
  1326. return is_file_opened(filep);
  1327. }
  1328. static void
  1329. mg_fclose(struct file *filep)
  1330. {
  1331. if (filep != NULL && filep->fp != NULL) {
  1332. fclose(filep->fp);
  1333. }
  1334. }
  1335. static void
  1336. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1337. {
  1338. for (; *src != '\0' && n > 1; n--) {
  1339. *dst++ = *src++;
  1340. }
  1341. *dst = '\0';
  1342. }
  1343. static int
  1344. lowercase(const char *s)
  1345. {
  1346. return tolower(*(const unsigned char *)s);
  1347. }
  1348. int
  1349. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1350. {
  1351. int diff = 0;
  1352. if (len > 0) {
  1353. do {
  1354. diff = lowercase(s1++) - lowercase(s2++);
  1355. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1356. }
  1357. return diff;
  1358. }
  1359. static int
  1360. mg_strcasecmp(const char *s1, const char *s2)
  1361. {
  1362. int diff;
  1363. do {
  1364. diff = lowercase(s1++) - lowercase(s2++);
  1365. } while (diff == 0 && s1[-1] != '\0');
  1366. return diff;
  1367. }
  1368. static char *
  1369. mg_strndup(const char *ptr, size_t len)
  1370. {
  1371. char *p;
  1372. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1373. mg_strlcpy(p, ptr, len + 1);
  1374. }
  1375. return p;
  1376. }
  1377. static char *
  1378. mg_strdup(const char *str)
  1379. {
  1380. return mg_strndup(str, strlen(str));
  1381. }
  1382. static const char *
  1383. mg_strcasestr(const char *big_str, const char *small_str)
  1384. {
  1385. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1386. if (big_len >= small_len) {
  1387. for (i = 0; i <= (big_len - small_len); i++) {
  1388. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1389. return big_str + i;
  1390. }
  1391. }
  1392. }
  1393. return NULL;
  1394. }
  1395. /* Return null terminated string of given maximum length.
  1396. * Report errors if length is exceeded. */
  1397. static void
  1398. mg_vsnprintf(const struct mg_connection *conn,
  1399. int *truncated,
  1400. char *buf,
  1401. size_t buflen,
  1402. const char *fmt,
  1403. va_list ap)
  1404. {
  1405. int n, ok;
  1406. if (buflen == 0) {
  1407. return;
  1408. }
  1409. #ifdef __clang__
  1410. #pragma clang diagnostic push
  1411. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1412. /* Using fmt as a non-literal is intended here, since it is mostly called
  1413. * indirectly by mg_snprintf */
  1414. #endif
  1415. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1416. ok = (n >= 0) && ((size_t)n < buflen);
  1417. #ifdef __clang__
  1418. #pragma clang diagnostic pop
  1419. #endif
  1420. if (ok) {
  1421. if (truncated) {
  1422. *truncated = 0;
  1423. }
  1424. } else {
  1425. if (truncated) {
  1426. *truncated = 1;
  1427. }
  1428. mg_cry(conn,
  1429. "truncating vsnprintf buffer: [%.*s]",
  1430. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1431. buf);
  1432. n = (int)buflen - 1;
  1433. }
  1434. buf[n] = '\0';
  1435. }
  1436. static void
  1437. mg_snprintf(const struct mg_connection *conn,
  1438. int *truncated,
  1439. char *buf,
  1440. size_t buflen,
  1441. const char *fmt,
  1442. ...)
  1443. {
  1444. va_list ap;
  1445. va_start(ap, fmt);
  1446. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1447. va_end(ap);
  1448. }
  1449. static int
  1450. get_option_index(const char *name)
  1451. {
  1452. int i;
  1453. for (i = 0; config_options[i].name != NULL; i++) {
  1454. if (strcmp(config_options[i].name, name) == 0) {
  1455. return i;
  1456. }
  1457. }
  1458. return -1;
  1459. }
  1460. const char *
  1461. mg_get_option(const struct mg_context *ctx, const char *name)
  1462. {
  1463. int i;
  1464. if ((i = get_option_index(name)) == -1) {
  1465. return NULL;
  1466. } else if (!ctx || ctx->config[i] == NULL) {
  1467. return "";
  1468. } else {
  1469. return ctx->config[i];
  1470. }
  1471. }
  1472. struct mg_context *
  1473. mg_get_context(const struct mg_connection *conn)
  1474. {
  1475. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1476. }
  1477. void *
  1478. mg_get_user_data(const struct mg_context *ctx)
  1479. {
  1480. return (ctx == NULL) ? NULL : ctx->user_data;
  1481. }
  1482. void
  1483. mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1484. {
  1485. if (conn != NULL) {
  1486. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1487. }
  1488. }
  1489. void *
  1490. mg_get_user_connection_data(const struct mg_connection *conn)
  1491. {
  1492. if (conn != NULL) {
  1493. return conn->request_info.conn_data;
  1494. }
  1495. return NULL;
  1496. }
  1497. size_t
  1498. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1499. {
  1500. size_t i;
  1501. if (!ctx) {
  1502. return 0;
  1503. }
  1504. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1505. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1506. ports[i] = ctx->listening_ports[i];
  1507. }
  1508. return i;
  1509. }
  1510. int
  1511. mg_get_server_ports(const struct mg_context *ctx,
  1512. int size,
  1513. struct mg_server_ports *ports)
  1514. {
  1515. int i, cnt = 0;
  1516. if (size <= 0) {
  1517. return -1;
  1518. }
  1519. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1520. if (!ctx) {
  1521. return -1;
  1522. }
  1523. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1524. return -1;
  1525. }
  1526. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1527. ports[cnt].port = ctx->listening_ports[i];
  1528. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1529. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1530. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1531. /* IPv4 */
  1532. ports[cnt].protocol = 1;
  1533. cnt++;
  1534. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1535. /* IPv6 */
  1536. ports[cnt].protocol = 3;
  1537. cnt++;
  1538. }
  1539. }
  1540. return cnt;
  1541. }
  1542. static void
  1543. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1544. {
  1545. buf[0] = '\0';
  1546. if (!usa) {
  1547. return;
  1548. }
  1549. if (usa->sa.sa_family == AF_INET) {
  1550. getnameinfo(&usa->sa,
  1551. sizeof(usa->sin),
  1552. buf,
  1553. (unsigned)len,
  1554. NULL,
  1555. 0,
  1556. NI_NUMERICHOST);
  1557. }
  1558. #if defined(USE_IPV6)
  1559. else if (usa->sa.sa_family == AF_INET6) {
  1560. getnameinfo(&usa->sa,
  1561. sizeof(usa->sin6),
  1562. buf,
  1563. (unsigned)len,
  1564. NULL,
  1565. 0,
  1566. NI_NUMERICHOST);
  1567. }
  1568. #endif
  1569. }
  1570. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1571. * included in all responses other than 100, 101, 5xx. */
  1572. static void
  1573. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1574. {
  1575. struct tm *tm;
  1576. tm = gmtime(t);
  1577. if (tm != NULL) {
  1578. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1579. } else {
  1580. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1581. buf[buf_len - 1] = '\0';
  1582. }
  1583. }
  1584. /* difftime for struct timespec. Return value is in seconds. */
  1585. static double
  1586. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1587. {
  1588. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1589. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1590. }
  1591. /* Print error message to the opened error log stream. */
  1592. void
  1593. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1594. {
  1595. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1596. va_list ap;
  1597. struct file fi;
  1598. time_t timestamp;
  1599. va_start(ap, fmt);
  1600. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1601. va_end(ap);
  1602. buf[sizeof(buf) - 1] = 0;
  1603. if (!conn) {
  1604. puts(buf);
  1605. return;
  1606. }
  1607. /* Do not lock when getting the callback value, here and below.
  1608. * I suppose this is fine, since function cannot disappear in the
  1609. * same way string option can. */
  1610. if ((conn->ctx->callbacks.log_message == NULL)
  1611. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1612. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1613. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1614. == 0) {
  1615. fi.fp = NULL;
  1616. }
  1617. } else {
  1618. fi.fp = NULL;
  1619. }
  1620. if (fi.fp != NULL) {
  1621. flockfile(fi.fp);
  1622. timestamp = time(NULL);
  1623. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1624. fprintf(fi.fp,
  1625. "[%010lu] [error] [client %s] ",
  1626. (unsigned long)timestamp,
  1627. src_addr);
  1628. if (conn->request_info.request_method != NULL) {
  1629. fprintf(fi.fp,
  1630. "%s %s: ",
  1631. conn->request_info.request_method,
  1632. conn->request_info.request_uri);
  1633. }
  1634. fprintf(fi.fp, "%s", buf);
  1635. fputc('\n', fi.fp);
  1636. fflush(fi.fp);
  1637. funlockfile(fi.fp);
  1638. mg_fclose(&fi);
  1639. }
  1640. }
  1641. }
  1642. /* Return fake connection structure. Used for logging, if connection
  1643. * is not applicable at the moment of logging. */
  1644. static struct mg_connection *
  1645. fc(struct mg_context *ctx)
  1646. {
  1647. static struct mg_connection fake_connection;
  1648. fake_connection.ctx = ctx;
  1649. return &fake_connection;
  1650. }
  1651. const char *
  1652. mg_version(void)
  1653. {
  1654. return CIVETWEB_VERSION;
  1655. }
  1656. const struct mg_request_info *
  1657. mg_get_request_info(const struct mg_connection *conn)
  1658. {
  1659. if (!conn) {
  1660. return NULL;
  1661. }
  1662. return &conn->request_info;
  1663. }
  1664. /* Skip the characters until one of the delimiters characters found.
  1665. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1666. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1667. * Delimiters can be quoted with quotechar. */
  1668. static char *
  1669. skip_quoted(char **buf,
  1670. const char *delimiters,
  1671. const char *whitespace,
  1672. char quotechar)
  1673. {
  1674. char *p, *begin_word, *end_word, *end_whitespace;
  1675. begin_word = *buf;
  1676. end_word = begin_word + strcspn(begin_word, delimiters);
  1677. /* Check for quotechar */
  1678. if (end_word > begin_word) {
  1679. p = end_word - 1;
  1680. while (*p == quotechar) {
  1681. /* While the delimiter is quoted, look for the next delimiter. */
  1682. /* This happens, e.g., in calls from parse_auth_header,
  1683. * if the user name contains a " character. */
  1684. /* If there is anything beyond end_word, copy it. */
  1685. if (*end_word != '\0') {
  1686. size_t end_off = strcspn(end_word + 1, delimiters);
  1687. memmove(p, end_word, end_off + 1);
  1688. p += end_off; /* p must correspond to end_word - 1 */
  1689. end_word += end_off + 1;
  1690. } else {
  1691. *p = '\0';
  1692. break;
  1693. }
  1694. }
  1695. for (p++; p < end_word; p++) {
  1696. *p = '\0';
  1697. }
  1698. }
  1699. if (*end_word == '\0') {
  1700. *buf = end_word;
  1701. } else {
  1702. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1703. for (p = end_word; p < end_whitespace; p++) {
  1704. *p = '\0';
  1705. }
  1706. *buf = end_whitespace;
  1707. }
  1708. return begin_word;
  1709. }
  1710. /* Simplified version of skip_quoted without quote char
  1711. * and whitespace == delimiters */
  1712. static char *
  1713. skip(char **buf, const char *delimiters)
  1714. {
  1715. return skip_quoted(buf, delimiters, delimiters, 0);
  1716. }
  1717. /* Return HTTP header value, or NULL if not found. */
  1718. static const char *
  1719. get_header(const struct mg_request_info *ri, const char *name)
  1720. {
  1721. int i;
  1722. if (ri) {
  1723. for (i = 0; i < ri->num_headers; i++) {
  1724. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1725. return ri->http_headers[i].value;
  1726. }
  1727. }
  1728. }
  1729. return NULL;
  1730. }
  1731. const char *
  1732. mg_get_header(const struct mg_connection *conn, const char *name)
  1733. {
  1734. if (!conn) {
  1735. return NULL;
  1736. }
  1737. return get_header(&conn->request_info, name);
  1738. }
  1739. /* A helper function for traversing a comma separated list of values.
  1740. * It returns a list pointer shifted to the next value, or NULL if the end
  1741. * of the list found.
  1742. * Value is stored in val vector. If value has form "x=y", then eq_val
  1743. * vector is initialized to point to the "y" part, and val vector length
  1744. * is adjusted to point only to "x". */
  1745. static const char *
  1746. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1747. {
  1748. int end;
  1749. reparse:
  1750. if (val == NULL || list == NULL || *list == '\0') {
  1751. /* End of the list */
  1752. list = NULL;
  1753. } else {
  1754. /* Skip over leading LWS */
  1755. while (*list == ' ' || *list == '\t')
  1756. list++;
  1757. val->ptr = list;
  1758. if ((list = strchr(val->ptr, ',')) != NULL) {
  1759. /* Comma found. Store length and shift the list ptr */
  1760. val->len = ((size_t)(list - val->ptr));
  1761. list++;
  1762. } else {
  1763. /* This value is the last one */
  1764. list = val->ptr + strlen(val->ptr);
  1765. val->len = ((size_t)(list - val->ptr));
  1766. }
  1767. /* Adjust length for trailing LWS */
  1768. end = (int)val->len - 1;
  1769. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1770. end--;
  1771. val->len = (size_t)(end + 1);
  1772. if (val->len == 0) {
  1773. /* Ignore any empty entries. */
  1774. goto reparse;
  1775. }
  1776. if (eq_val != NULL) {
  1777. /* Value has form "x=y", adjust pointers and lengths
  1778. * so that val points to "x", and eq_val points to "y". */
  1779. eq_val->len = 0;
  1780. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1781. if (eq_val->ptr != NULL) {
  1782. eq_val->ptr++; /* Skip over '=' character */
  1783. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1784. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1785. }
  1786. }
  1787. }
  1788. return list;
  1789. }
  1790. /* A helper function for checking if a comma separated list of values contains
  1791. * the given option (case insensitvely).
  1792. * 'header' can be NULL, in which case false is returned. */
  1793. static int header_has_option(const char *header, const char *option)
  1794. {
  1795. struct vec opt_vec;
  1796. struct vec eq_vec;
  1797. assert(option != NULL);
  1798. assert(option[0] != '\0');
  1799. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  1800. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  1801. return 1;
  1802. }
  1803. return 0;
  1804. }
  1805. /* Perform case-insensitive match of string against pattern */
  1806. static int
  1807. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1808. {
  1809. const char *or_str;
  1810. size_t i;
  1811. int j, len, res;
  1812. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1813. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1814. return res > 0 ? res : match_prefix(or_str + 1,
  1815. (size_t)((pattern + pattern_len)
  1816. - (or_str + 1)),
  1817. str);
  1818. }
  1819. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1820. if (pattern[i] == '?' && str[j] != '\0') {
  1821. continue;
  1822. } else if (pattern[i] == '$') {
  1823. return str[j] == '\0' ? j : -1;
  1824. } else if (pattern[i] == '*') {
  1825. i++;
  1826. if (pattern[i] == '*') {
  1827. i++;
  1828. len = (int)strlen(str + j);
  1829. } else {
  1830. len = (int)strcspn(str + j, "/");
  1831. }
  1832. if (i == pattern_len) {
  1833. return j + len;
  1834. }
  1835. do {
  1836. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1837. } while (res == -1 && len-- > 0);
  1838. return res == -1 ? -1 : j + res + len;
  1839. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1840. return -1;
  1841. }
  1842. }
  1843. return j;
  1844. }
  1845. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1846. * This function must tolerate situations when connection info is not
  1847. * set up, for example if request parsing failed. */
  1848. static int
  1849. should_keep_alive(const struct mg_connection *conn)
  1850. {
  1851. if (conn != NULL) {
  1852. const char *http_version = conn->request_info.http_version;
  1853. const char *header = mg_get_header(conn, "Connection");
  1854. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1855. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1856. || (header != NULL && !header_has_option(header, "keep-alive"))
  1857. || (header == NULL && http_version
  1858. && 0 != strcmp(http_version, "1.1"))) {
  1859. return 0;
  1860. }
  1861. return 1;
  1862. }
  1863. return 0;
  1864. }
  1865. static int
  1866. should_decode_url(const struct mg_connection *conn)
  1867. {
  1868. if (!conn || !conn->ctx) {
  1869. return 0;
  1870. }
  1871. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1872. }
  1873. static const char *
  1874. suggest_connection_header(const struct mg_connection *conn)
  1875. {
  1876. return should_keep_alive(conn) ? "keep-alive" : "close";
  1877. }
  1878. static int
  1879. send_no_cache_header(struct mg_connection *conn)
  1880. {
  1881. /* Send all current and obsolete cache opt-out directives. */
  1882. return mg_printf(conn,
  1883. "Cache-Control: no-cache, no-store, "
  1884. "must-revalidate, private, max-age=0\r\n"
  1885. "Pragma: no-cache\r\n"
  1886. "Expires: 0\r\n");
  1887. }
  1888. static int
  1889. send_static_cache_header(struct mg_connection *conn)
  1890. {
  1891. /* Read the server config to check how long a file may be cached.
  1892. * The configuration is in seconds. */
  1893. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  1894. if (max_age <= 0) {
  1895. /* 0 means "do not cache". All values <0 are reserved
  1896. * and may be used differently in the future. */
  1897. /* If a file should not be cached, do not only send
  1898. * max-age=0, but also pragmas and Expires headers. */
  1899. return send_no_cache_header(conn);
  1900. }
  1901. /* Use "Cache-Control: max-age" instead of "Expires" header.
  1902. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  1903. /* See also https://www.mnot.net/cache_docs/ */
  1904. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  1905. }
  1906. static void handle_file_based_request(struct mg_connection *conn,
  1907. const char *path,
  1908. struct file *filep);
  1909. static int
  1910. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1911. static const char *
  1912. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1913. {
  1914. /* See IANA HTTP status code assignment:
  1915. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  1916. */
  1917. switch (response_code) {
  1918. /* RFC2616 Section 10.1 - Informational 1xx */
  1919. case 100:
  1920. return "Continue"; /* RFC2616 Section 10.1.1 */
  1921. case 101:
  1922. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1923. case 102:
  1924. return "Processing"; /* RFC2518 Section 10.1 */
  1925. /* RFC2616 Section 10.2 - Successful 2xx */
  1926. case 200:
  1927. return "OK"; /* RFC2616 Section 10.2.1 */
  1928. case 201:
  1929. return "Created"; /* RFC2616 Section 10.2.2 */
  1930. case 202:
  1931. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1932. case 203:
  1933. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1934. case 204:
  1935. return "No Content"; /* RFC2616 Section 10.2.5 */
  1936. case 205:
  1937. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1938. case 206:
  1939. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1940. case 207:
  1941. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1942. case 208:
  1943. return "Already Reported"; /* RFC5842 Section 7.1 */
  1944. case 226:
  1945. return "IM used"; /* RFC3229 Section 10.4.1 */
  1946. /* RFC2616 Section 10.3 - Redirection 3xx */
  1947. case 300:
  1948. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1949. case 301:
  1950. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1951. case 302:
  1952. return "Found"; /* RFC2616 Section 10.3.3 */
  1953. case 303:
  1954. return "See Other"; /* RFC2616 Section 10.3.4 */
  1955. case 304:
  1956. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1957. case 305:
  1958. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1959. case 307:
  1960. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1961. case 308:
  1962. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1963. /* RFC2616 Section 10.4 - Client Error 4xx */
  1964. case 400:
  1965. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1966. case 401:
  1967. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1968. case 402:
  1969. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1970. case 403:
  1971. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1972. case 404:
  1973. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1974. case 405:
  1975. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1976. case 406:
  1977. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1978. case 407:
  1979. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1980. case 408:
  1981. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1982. case 409:
  1983. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1984. case 410:
  1985. return "Gone"; /* RFC2616 Section 10.4.11 */
  1986. case 411:
  1987. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1988. case 412:
  1989. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1990. case 413:
  1991. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1992. case 414:
  1993. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1994. case 415:
  1995. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1996. case 416:
  1997. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1998. case 417:
  1999. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2000. case 421:
  2001. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2002. case 422:
  2003. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2004. * Section 11.2 */
  2005. case 423:
  2006. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2007. case 424:
  2008. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2009. * Section 11.4 */
  2010. case 426:
  2011. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2012. case 428:
  2013. return "Precondition Required"; /* RFC 6585, Section 3 */
  2014. case 429:
  2015. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2016. case 431:
  2017. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2018. case 451:
  2019. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2020. * Section 3 */
  2021. /* RFC2616 Section 10.5 - Server Error 5xx */
  2022. case 500:
  2023. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2024. case 501:
  2025. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2026. case 502:
  2027. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2028. case 503:
  2029. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2030. case 504:
  2031. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2032. case 505:
  2033. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2034. case 506:
  2035. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2036. case 507:
  2037. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2038. * Section 11.5 */
  2039. case 508:
  2040. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2041. case 510:
  2042. return "Not Extended"; /* RFC 2774, Section 7 */
  2043. case 511:
  2044. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2045. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2046. * E.g., "de facto" standards due to common use, ... */
  2047. case 418:
  2048. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2049. case 419:
  2050. return "Authentication Timeout"; /* common use */
  2051. default:
  2052. /* This error code is unknown. This should not happen. */
  2053. if (conn) {
  2054. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2055. }
  2056. /* Return at least a category according to RFC 2616 Section 10. */
  2057. if (response_code >= 100 && response_code < 200) {
  2058. /* Unknown informational status code */
  2059. return "Information";
  2060. }
  2061. if (response_code >= 200 && response_code < 300) {
  2062. /* Unknown success code */
  2063. return "Success";
  2064. }
  2065. if (response_code >= 300 && response_code < 400) {
  2066. /* Unknown redirection code */
  2067. return "Redirection";
  2068. }
  2069. if (response_code >= 400 && response_code < 500) {
  2070. /* Unknown request error code */
  2071. return "Client Error";
  2072. }
  2073. if (response_code >= 500 && response_code < 600) {
  2074. /* Unknown server error code */
  2075. return "Server Error";
  2076. }
  2077. /* Response code not even within reasonable range */
  2078. return "";
  2079. }
  2080. }
  2081. static void send_http_error(struct mg_connection *,
  2082. int,
  2083. PRINTF_FORMAT_STRING(const char *fmt),
  2084. ...) PRINTF_ARGS(3, 4);
  2085. static void
  2086. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2087. {
  2088. char buf[MG_BUF_LEN];
  2089. va_list ap;
  2090. int len, i, page_handler_found, scope, truncated;
  2091. char date[64];
  2092. time_t curtime = time(NULL);
  2093. const char *error_handler = NULL;
  2094. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2095. const char *error_page_file_ext, *tstr;
  2096. const char *status_text = mg_get_response_code_text(status, conn);
  2097. if (conn == NULL) {
  2098. return;
  2099. }
  2100. conn->status_code = status;
  2101. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2102. || conn->ctx->callbacks.http_error(conn, status)) {
  2103. if (!conn->in_error_handler) {
  2104. /* Send user defined error pages, if defined */
  2105. error_handler = conn->ctx->config[ERROR_PAGES];
  2106. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2107. page_handler_found = 0;
  2108. if (error_handler != NULL) {
  2109. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2110. switch (scope) {
  2111. case 1: /* Handler for specific error, e.g. 404 error */
  2112. mg_snprintf(conn,
  2113. &truncated,
  2114. buf,
  2115. sizeof(buf) - 32,
  2116. "%serror%03u.",
  2117. error_handler,
  2118. status);
  2119. break;
  2120. case 2: /* Handler for error group, e.g., 5xx error handler
  2121. * for all server errors (500-599) */
  2122. mg_snprintf(conn,
  2123. &truncated,
  2124. buf,
  2125. sizeof(buf) - 32,
  2126. "%serror%01uxx.",
  2127. error_handler,
  2128. status / 100);
  2129. break;
  2130. default: /* Handler for all errors */
  2131. mg_snprintf(conn,
  2132. &truncated,
  2133. buf,
  2134. sizeof(buf) - 32,
  2135. "%serror.",
  2136. error_handler);
  2137. break;
  2138. }
  2139. /* String truncation in buf may only occur if error_handler
  2140. * is too long. This string is from the config, not from a
  2141. * client. */
  2142. (void)truncated;
  2143. len = (int)strlen(buf);
  2144. tstr = strchr(error_page_file_ext, '.');
  2145. while (tstr) {
  2146. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2147. i++)
  2148. buf[len + i - 1] = tstr[i];
  2149. buf[len + i - 1] = 0;
  2150. if (mg_stat(conn, buf, &error_page_file)) {
  2151. page_handler_found = 1;
  2152. break;
  2153. }
  2154. tstr = strchr(tstr + i, '.');
  2155. }
  2156. }
  2157. }
  2158. if (page_handler_found) {
  2159. conn->in_error_handler = 1;
  2160. handle_file_based_request(conn, buf, &error_page_file);
  2161. conn->in_error_handler = 0;
  2162. return;
  2163. }
  2164. }
  2165. /* No custom error page. Send default error page. */
  2166. gmt_time_string(date, sizeof(date), &curtime);
  2167. conn->must_close = 1;
  2168. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2169. send_no_cache_header(conn);
  2170. mg_printf(conn,
  2171. "Date: %s\r\n"
  2172. "Connection: close\r\n\r\n",
  2173. date);
  2174. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2175. if (status > 199 && status != 204 && status != 304) {
  2176. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2177. if (fmt != NULL) {
  2178. va_start(ap, fmt);
  2179. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2180. va_end(ap);
  2181. mg_write(conn, buf, strlen(buf));
  2182. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2183. }
  2184. } else {
  2185. /* No body allowed. Close the connection. */
  2186. DEBUG_TRACE("Error %i", status);
  2187. }
  2188. }
  2189. }
  2190. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2191. /* Create substitutes for POSIX functions in Win32. */
  2192. #if defined(__MINGW32__)
  2193. /* Show no warning in case system functions are not used. */
  2194. #pragma GCC diagnostic push
  2195. #pragma GCC diagnostic ignored "-Wunused-function"
  2196. #endif
  2197. static int
  2198. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2199. {
  2200. (void)unused;
  2201. *mutex = CreateMutex(NULL, FALSE, NULL);
  2202. return *mutex == NULL ? -1 : 0;
  2203. }
  2204. static int
  2205. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2206. {
  2207. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2208. }
  2209. static int
  2210. pthread_mutex_lock(pthread_mutex_t *mutex)
  2211. {
  2212. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2213. }
  2214. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2215. static int
  2216. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2217. {
  2218. switch (WaitForSingleObject(*mutex, 0)) {
  2219. case WAIT_OBJECT_0:
  2220. return 0;
  2221. case WAIT_TIMEOUT:
  2222. return -2; /* EBUSY */
  2223. }
  2224. return -1;
  2225. }
  2226. #endif
  2227. static int
  2228. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2229. {
  2230. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2231. }
  2232. #ifndef WIN_PTHREADS_TIME_H
  2233. static int
  2234. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2235. {
  2236. FILETIME ft;
  2237. ULARGE_INTEGER li;
  2238. BOOL ok = FALSE;
  2239. double d;
  2240. static double perfcnt_per_sec = 0.0;
  2241. if (tp) {
  2242. memset(tp, 0, sizeof(*tp));
  2243. if (clk_id == CLOCK_REALTIME) {
  2244. GetSystemTimeAsFileTime(&ft);
  2245. li.LowPart = ft.dwLowDateTime;
  2246. li.HighPart = ft.dwHighDateTime;
  2247. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2248. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2249. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2250. ok = TRUE;
  2251. } else if (clk_id == CLOCK_MONOTONIC) {
  2252. if (perfcnt_per_sec == 0.0) {
  2253. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2254. perfcnt_per_sec = 1.0 / li.QuadPart;
  2255. }
  2256. if (perfcnt_per_sec != 0.0) {
  2257. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2258. d = li.QuadPart * perfcnt_per_sec;
  2259. tp->tv_sec = (time_t)d;
  2260. d -= tp->tv_sec;
  2261. tp->tv_nsec = (long)(d * 1.0E9);
  2262. ok = TRUE;
  2263. }
  2264. }
  2265. }
  2266. return ok ? 0 : -1;
  2267. }
  2268. #endif
  2269. static int
  2270. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2271. {
  2272. (void)unused;
  2273. InitializeCriticalSection(&cv->threadIdSec);
  2274. cv->waitingthreadcount = 0;
  2275. cv->waitingthreadhdls =
  2276. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2277. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2278. }
  2279. static int
  2280. pthread_cond_timedwait(pthread_cond_t *cv,
  2281. pthread_mutex_t *mutex,
  2282. const struct timespec *abstime)
  2283. {
  2284. struct mg_workerTLS *tls =
  2285. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2286. int ok;
  2287. struct timespec tsnow;
  2288. int64_t nsnow, nswaitabs, nswaitrel;
  2289. DWORD mswaitrel;
  2290. EnterCriticalSection(&cv->threadIdSec);
  2291. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2292. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2293. tls->pthread_cond_helper_mutex;
  2294. cv->waitingthreadcount++;
  2295. LeaveCriticalSection(&cv->threadIdSec);
  2296. if (abstime) {
  2297. clock_gettime(CLOCK_REALTIME, &tsnow);
  2298. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2299. nswaitabs =
  2300. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2301. nswaitrel = nswaitabs - nsnow;
  2302. if (nswaitrel < 0) {
  2303. nswaitrel = 0;
  2304. }
  2305. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2306. } else {
  2307. mswaitrel = INFINITE;
  2308. }
  2309. pthread_mutex_unlock(mutex);
  2310. ok = (WAIT_OBJECT_0
  2311. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2312. pthread_mutex_lock(mutex);
  2313. return ok ? 0 : -1;
  2314. }
  2315. static int
  2316. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2317. {
  2318. return pthread_cond_timedwait(cv, mutex, NULL);
  2319. }
  2320. static int
  2321. pthread_cond_signal(pthread_cond_t *cv)
  2322. {
  2323. int i;
  2324. HANDLE wkup = NULL;
  2325. BOOL ok = FALSE;
  2326. EnterCriticalSection(&cv->threadIdSec);
  2327. if (cv->waitingthreadcount) {
  2328. wkup = cv->waitingthreadhdls[0];
  2329. ok = SetEvent(wkup);
  2330. for (i = 1; i < cv->waitingthreadcount; i++) {
  2331. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2332. }
  2333. cv->waitingthreadcount--;
  2334. assert(ok);
  2335. }
  2336. LeaveCriticalSection(&cv->threadIdSec);
  2337. return ok ? 0 : 1;
  2338. }
  2339. static int
  2340. pthread_cond_broadcast(pthread_cond_t *cv)
  2341. {
  2342. EnterCriticalSection(&cv->threadIdSec);
  2343. while (cv->waitingthreadcount) {
  2344. pthread_cond_signal(cv);
  2345. }
  2346. LeaveCriticalSection(&cv->threadIdSec);
  2347. return 0;
  2348. }
  2349. static int
  2350. pthread_cond_destroy(pthread_cond_t *cv)
  2351. {
  2352. EnterCriticalSection(&cv->threadIdSec);
  2353. assert(cv->waitingthreadcount == 0);
  2354. mg_free(cv->waitingthreadhdls);
  2355. cv->waitingthreadhdls = 0;
  2356. LeaveCriticalSection(&cv->threadIdSec);
  2357. DeleteCriticalSection(&cv->threadIdSec);
  2358. return 0;
  2359. }
  2360. #if defined(__MINGW32__)
  2361. /* Enable unused function warning again */
  2362. #pragma GCC diagnostic pop
  2363. #endif
  2364. /* For Windows, change all slashes to backslashes in path names. */
  2365. static void
  2366. change_slashes_to_backslashes(char *path)
  2367. {
  2368. int i;
  2369. for (i = 0; path[i] != '\0'; i++) {
  2370. if (path[i] == '/') {
  2371. path[i] = '\\';
  2372. }
  2373. /* remove double backslash (check i > 0 to preserve UNC paths,
  2374. * like \\server\file.txt) */
  2375. if ((path[i] == '\\') && (i > 0)) {
  2376. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2377. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2378. }
  2379. }
  2380. }
  2381. }
  2382. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2383. * wbuf and wbuf_len is a target buffer and its length. */
  2384. static void
  2385. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2386. {
  2387. char buf[PATH_MAX], buf2[PATH_MAX];
  2388. mg_strlcpy(buf, path, sizeof(buf));
  2389. change_slashes_to_backslashes(buf);
  2390. /* Convert to Unicode and back. If doubly-converted string does not
  2391. * match the original, something is fishy, reject. */
  2392. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2393. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2394. WideCharToMultiByte(
  2395. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2396. if (strcmp(buf, buf2) != 0) {
  2397. wbuf[0] = L'\0';
  2398. }
  2399. }
  2400. #if defined(_WIN32_WCE)
  2401. /* Create substitutes for POSIX functions in Win32. */
  2402. #if defined(__MINGW32__)
  2403. /* Show no warning in case system functions are not used. */
  2404. #pragma GCC diagnostic push
  2405. #pragma GCC diagnostic ignored "-Wunused-function"
  2406. #endif
  2407. static time_t
  2408. time(time_t *ptime)
  2409. {
  2410. time_t t;
  2411. SYSTEMTIME st;
  2412. FILETIME ft;
  2413. GetSystemTime(&st);
  2414. SystemTimeToFileTime(&st, &ft);
  2415. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2416. if (ptime != NULL) {
  2417. *ptime = t;
  2418. }
  2419. return t;
  2420. }
  2421. static struct tm *
  2422. localtime(const time_t *ptime, struct tm *ptm)
  2423. {
  2424. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2425. FILETIME ft, lft;
  2426. SYSTEMTIME st;
  2427. TIME_ZONE_INFORMATION tzinfo;
  2428. if (ptm == NULL) {
  2429. return NULL;
  2430. }
  2431. *(int64_t *)&ft = t;
  2432. FileTimeToLocalFileTime(&ft, &lft);
  2433. FileTimeToSystemTime(&lft, &st);
  2434. ptm->tm_year = st.wYear - 1900;
  2435. ptm->tm_mon = st.wMonth - 1;
  2436. ptm->tm_wday = st.wDayOfWeek;
  2437. ptm->tm_mday = st.wDay;
  2438. ptm->tm_hour = st.wHour;
  2439. ptm->tm_min = st.wMinute;
  2440. ptm->tm_sec = st.wSecond;
  2441. ptm->tm_yday = 0; /* hope nobody uses this */
  2442. ptm->tm_isdst =
  2443. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2444. return ptm;
  2445. }
  2446. static struct tm *
  2447. gmtime(const time_t *ptime, struct tm *ptm)
  2448. {
  2449. /* FIXME(lsm): fix this. */
  2450. return localtime(ptime, ptm);
  2451. }
  2452. static size_t
  2453. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2454. {
  2455. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2456. return 0;
  2457. }
  2458. #if defined(__MINGW32__)
  2459. /* Enable unused function warning again */
  2460. #pragma GCC diagnostic pop
  2461. #endif
  2462. #endif
  2463. /* Windows happily opens files with some garbage at the end of file name.
  2464. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2465. * "a.cgi", despite one would expect an error back.
  2466. * This function returns non-0 if path ends with some garbage. */
  2467. static int
  2468. path_cannot_disclose_cgi(const char *path)
  2469. {
  2470. static const char *allowed_last_characters = "_-";
  2471. int last = path[strlen(path) - 1];
  2472. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2473. }
  2474. static int
  2475. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2476. {
  2477. wchar_t wbuf[PATH_MAX];
  2478. WIN32_FILE_ATTRIBUTE_DATA info;
  2479. time_t creation_time;
  2480. if (!filep) {
  2481. return 0;
  2482. }
  2483. memset(filep, 0, sizeof(*filep));
  2484. if (conn && is_file_in_memory(conn, path, filep)) {
  2485. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2486. * memset */
  2487. filep->last_modified = time(NULL);
  2488. /* last_modified = now ... assumes the file may change during runtime,
  2489. * so every mg_fopen call may return different data */
  2490. /* last_modified = conn->ctx.start_time;
  2491. * May be used it the data does not change during runtime. This allows
  2492. * browser caching. Since we do not know, we have to assume the file
  2493. * in memory may change. */
  2494. return 1;
  2495. }
  2496. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2497. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2498. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2499. filep->last_modified =
  2500. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2501. info.ftLastWriteTime.dwHighDateTime);
  2502. /* On Windows, the file creation time can be higher than the
  2503. * modification time, e.g. when a file is copied.
  2504. * Since the Last-Modified timestamp is used for caching
  2505. * it should be based on the most recent timestamp. */
  2506. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2507. info.ftCreationTime.dwHighDateTime);
  2508. if (creation_time > filep->last_modified) {
  2509. filep->last_modified = creation_time;
  2510. }
  2511. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2512. /* If file name is fishy, reset the file structure and return
  2513. * error.
  2514. * Note it is important to reset, not just return the error, cause
  2515. * functions like is_file_opened() check the struct. */
  2516. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2517. memset(filep, 0, sizeof(*filep));
  2518. return 0;
  2519. }
  2520. return 1;
  2521. }
  2522. return 0;
  2523. }
  2524. static int
  2525. mg_remove(const char *path)
  2526. {
  2527. wchar_t wbuf[PATH_MAX];
  2528. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2529. return DeleteFileW(wbuf) ? 0 : -1;
  2530. }
  2531. static int
  2532. mg_mkdir(const char *path, int mode)
  2533. {
  2534. char buf[PATH_MAX];
  2535. wchar_t wbuf[PATH_MAX];
  2536. (void)mode;
  2537. mg_strlcpy(buf, path, sizeof(buf));
  2538. change_slashes_to_backslashes(buf);
  2539. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2540. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2541. }
  2542. /* Create substitutes for POSIX functions in Win32. */
  2543. #if defined(__MINGW32__)
  2544. /* Show no warning in case system functions are not used. */
  2545. #pragma GCC diagnostic push
  2546. #pragma GCC diagnostic ignored "-Wunused-function"
  2547. #endif
  2548. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2549. static DIR *
  2550. opendir(const char *name)
  2551. {
  2552. DIR *dir = NULL;
  2553. wchar_t wpath[PATH_MAX];
  2554. DWORD attrs;
  2555. if (name == NULL) {
  2556. SetLastError(ERROR_BAD_ARGUMENTS);
  2557. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2558. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2559. } else {
  2560. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2561. attrs = GetFileAttributesW(wpath);
  2562. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2563. == FILE_ATTRIBUTE_DIRECTORY)) {
  2564. (void)wcscat(wpath, L"\\*");
  2565. dir->handle = FindFirstFileW(wpath, &dir->info);
  2566. dir->result.d_name[0] = '\0';
  2567. } else {
  2568. mg_free(dir);
  2569. dir = NULL;
  2570. }
  2571. }
  2572. return dir;
  2573. }
  2574. static int
  2575. closedir(DIR *dir)
  2576. {
  2577. int result = 0;
  2578. if (dir != NULL) {
  2579. if (dir->handle != INVALID_HANDLE_VALUE)
  2580. result = FindClose(dir->handle) ? 0 : -1;
  2581. mg_free(dir);
  2582. } else {
  2583. result = -1;
  2584. SetLastError(ERROR_BAD_ARGUMENTS);
  2585. }
  2586. return result;
  2587. }
  2588. static struct dirent *
  2589. readdir(DIR *dir)
  2590. {
  2591. struct dirent *result = 0;
  2592. if (dir) {
  2593. if (dir->handle != INVALID_HANDLE_VALUE) {
  2594. result = &dir->result;
  2595. (void)WideCharToMultiByte(CP_UTF8,
  2596. 0,
  2597. dir->info.cFileName,
  2598. -1,
  2599. result->d_name,
  2600. sizeof(result->d_name),
  2601. NULL,
  2602. NULL);
  2603. if (!FindNextFileW(dir->handle, &dir->info)) {
  2604. (void)FindClose(dir->handle);
  2605. dir->handle = INVALID_HANDLE_VALUE;
  2606. }
  2607. } else {
  2608. SetLastError(ERROR_FILE_NOT_FOUND);
  2609. }
  2610. } else {
  2611. SetLastError(ERROR_BAD_ARGUMENTS);
  2612. }
  2613. return result;
  2614. }
  2615. #ifndef HAVE_POLL
  2616. static int
  2617. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2618. {
  2619. struct timeval tv;
  2620. fd_set set;
  2621. unsigned int i;
  2622. int result;
  2623. SOCKET maxfd = 0;
  2624. memset(&tv, 0, sizeof(tv));
  2625. tv.tv_sec = milliseconds / 1000;
  2626. tv.tv_usec = (milliseconds % 1000) * 1000;
  2627. FD_ZERO(&set);
  2628. for (i = 0; i < n; i++) {
  2629. FD_SET((SOCKET)pfd[i].fd, &set);
  2630. pfd[i].revents = 0;
  2631. if (pfd[i].fd > maxfd) {
  2632. maxfd = pfd[i].fd;
  2633. }
  2634. }
  2635. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2636. for (i = 0; i < n; i++) {
  2637. if (FD_ISSET(pfd[i].fd, &set)) {
  2638. pfd[i].revents = POLLIN;
  2639. }
  2640. }
  2641. }
  2642. return result;
  2643. }
  2644. #endif /* HAVE_POLL */
  2645. #if defined(__MINGW32__)
  2646. /* Enable unused function warning again */
  2647. #pragma GCC diagnostic pop
  2648. #endif
  2649. static void
  2650. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2651. {
  2652. (void)conn; /* Unused. */
  2653. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2654. }
  2655. int
  2656. mg_start_thread(mg_thread_func_t f, void *p)
  2657. {
  2658. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2659. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2660. */
  2661. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2662. == ((uintptr_t)(-1L)))
  2663. ? -1
  2664. : 0);
  2665. #else
  2666. return (
  2667. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2668. ? -1
  2669. : 0);
  2670. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2671. }
  2672. /* Start a thread storing the thread context. */
  2673. static int
  2674. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2675. void *p,
  2676. pthread_t *threadidptr)
  2677. {
  2678. uintptr_t uip;
  2679. HANDLE threadhandle;
  2680. int result = -1;
  2681. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2682. threadhandle = (HANDLE)uip;
  2683. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2684. *threadidptr = threadhandle;
  2685. result = 0;
  2686. }
  2687. return result;
  2688. }
  2689. /* Wait for a thread to finish. */
  2690. static int
  2691. mg_join_thread(pthread_t threadid)
  2692. {
  2693. int result;
  2694. DWORD dwevent;
  2695. result = -1;
  2696. dwevent = WaitForSingleObject(threadid, INFINITE);
  2697. if (dwevent == WAIT_FAILED) {
  2698. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2699. } else {
  2700. if (dwevent == WAIT_OBJECT_0) {
  2701. CloseHandle(threadid);
  2702. result = 0;
  2703. }
  2704. }
  2705. return result;
  2706. }
  2707. #if !defined(NO_SSL_DL)
  2708. /* Create substitutes for POSIX functions in Win32. */
  2709. #if defined(__MINGW32__)
  2710. /* Show no warning in case system functions are not used. */
  2711. #pragma GCC diagnostic push
  2712. #pragma GCC diagnostic ignored "-Wunused-function"
  2713. #endif
  2714. static HANDLE
  2715. dlopen(const char *dll_name, int flags)
  2716. {
  2717. wchar_t wbuf[PATH_MAX];
  2718. (void)flags;
  2719. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2720. return LoadLibraryW(wbuf);
  2721. }
  2722. static int
  2723. dlclose(void *handle)
  2724. {
  2725. int result;
  2726. if (FreeLibrary((HMODULE)handle) != 0) {
  2727. result = 0;
  2728. } else {
  2729. result = -1;
  2730. }
  2731. return result;
  2732. }
  2733. #if defined(__MINGW32__)
  2734. /* Enable unused function warning again */
  2735. #pragma GCC diagnostic pop
  2736. #endif
  2737. #endif
  2738. #if !defined(NO_CGI)
  2739. #define SIGKILL (0)
  2740. static int
  2741. kill(pid_t pid, int sig_num)
  2742. {
  2743. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2744. (void)CloseHandle((HANDLE)pid);
  2745. return 0;
  2746. }
  2747. static void
  2748. trim_trailing_whitespaces(char *s)
  2749. {
  2750. char *e = s + strlen(s) - 1;
  2751. while (e > s && isspace(*(unsigned char *)e)) {
  2752. *e-- = '\0';
  2753. }
  2754. }
  2755. static pid_t
  2756. spawn_process(struct mg_connection *conn,
  2757. const char *prog,
  2758. char *envblk,
  2759. char *envp[],
  2760. int fdin,
  2761. int fdout,
  2762. int fderr,
  2763. const char *dir)
  2764. {
  2765. HANDLE me;
  2766. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2767. cmdline[PATH_MAX], buf[PATH_MAX];
  2768. int truncated;
  2769. struct file file = STRUCT_FILE_INITIALIZER;
  2770. STARTUPINFOA si;
  2771. PROCESS_INFORMATION pi = {0};
  2772. (void)envp;
  2773. memset(&si, 0, sizeof(si));
  2774. si.cb = sizeof(si);
  2775. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2776. si.wShowWindow = SW_HIDE;
  2777. me = GetCurrentProcess();
  2778. DuplicateHandle(me,
  2779. (HANDLE)_get_osfhandle(fdin),
  2780. me,
  2781. &si.hStdInput,
  2782. 0,
  2783. TRUE,
  2784. DUPLICATE_SAME_ACCESS);
  2785. DuplicateHandle(me,
  2786. (HANDLE)_get_osfhandle(fdout),
  2787. me,
  2788. &si.hStdOutput,
  2789. 0,
  2790. TRUE,
  2791. DUPLICATE_SAME_ACCESS);
  2792. DuplicateHandle(me,
  2793. (HANDLE)_get_osfhandle(fderr),
  2794. me,
  2795. &si.hStdError,
  2796. 0,
  2797. TRUE,
  2798. DUPLICATE_SAME_ACCESS);
  2799. /* If CGI file is a script, try to read the interpreter line */
  2800. interp = conn->ctx->config[CGI_INTERPRETER];
  2801. if (interp == NULL) {
  2802. buf[0] = buf[1] = '\0';
  2803. /* Read the first line of the script into the buffer */
  2804. mg_snprintf(
  2805. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2806. if (truncated) {
  2807. pi.hProcess = (pid_t)-1;
  2808. goto spawn_cleanup;
  2809. }
  2810. if (mg_fopen(conn, cmdline, "r", &file)) {
  2811. p = (char *)file.membuf;
  2812. mg_fgets(buf, sizeof(buf), &file, &p);
  2813. mg_fclose(&file);
  2814. buf[sizeof(buf) - 1] = '\0';
  2815. }
  2816. if (buf[0] == '#' && buf[1] == '!') {
  2817. trim_trailing_whitespaces(buf + 2);
  2818. } else {
  2819. buf[2] = '\0';
  2820. }
  2821. interp = buf + 2;
  2822. }
  2823. if (interp[0] != '\0') {
  2824. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2825. interp = full_interp;
  2826. }
  2827. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2828. if (interp[0] != '\0') {
  2829. mg_snprintf(conn,
  2830. &truncated,
  2831. cmdline,
  2832. sizeof(cmdline),
  2833. "\"%s\" \"%s\\%s\"",
  2834. interp,
  2835. full_dir,
  2836. prog);
  2837. } else {
  2838. mg_snprintf(conn,
  2839. &truncated,
  2840. cmdline,
  2841. sizeof(cmdline),
  2842. "\"%s\\%s\"",
  2843. full_dir,
  2844. prog);
  2845. }
  2846. if (truncated) {
  2847. pi.hProcess = (pid_t)-1;
  2848. goto spawn_cleanup;
  2849. }
  2850. DEBUG_TRACE("Running [%s]", cmdline);
  2851. if (CreateProcessA(NULL,
  2852. cmdline,
  2853. NULL,
  2854. NULL,
  2855. TRUE,
  2856. CREATE_NEW_PROCESS_GROUP,
  2857. envblk,
  2858. NULL,
  2859. &si,
  2860. &pi) == 0) {
  2861. mg_cry(
  2862. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2863. pi.hProcess = (pid_t)-1;
  2864. /* goto spawn_cleanup; */
  2865. }
  2866. spawn_cleanup:
  2867. (void)CloseHandle(si.hStdOutput);
  2868. (void)CloseHandle(si.hStdError);
  2869. (void)CloseHandle(si.hStdInput);
  2870. if (pi.hThread != NULL) {
  2871. (void)CloseHandle(pi.hThread);
  2872. }
  2873. return (pid_t)pi.hProcess;
  2874. }
  2875. #endif /* !NO_CGI */
  2876. static int
  2877. set_non_blocking_mode(SOCKET sock)
  2878. {
  2879. unsigned long on = 1;
  2880. return ioctlsocket(sock, (long)FIONBIO, &on);
  2881. }
  2882. #else
  2883. static int
  2884. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2885. {
  2886. struct stat st;
  2887. if (!filep) {
  2888. return 0;
  2889. }
  2890. memset(filep, 0, sizeof(*filep));
  2891. if (conn && is_file_in_memory(conn, path, filep)) {
  2892. return 1;
  2893. }
  2894. if (0 == stat(path, &st)) {
  2895. filep->size = (uint64_t)(st.st_size);
  2896. filep->last_modified = st.st_mtime;
  2897. filep->is_directory = S_ISDIR(st.st_mode);
  2898. return 1;
  2899. }
  2900. return 0;
  2901. }
  2902. static void
  2903. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2904. {
  2905. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2906. if (conn) {
  2907. mg_cry(conn,
  2908. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2909. __func__,
  2910. strerror(ERRNO));
  2911. }
  2912. }
  2913. }
  2914. int
  2915. mg_start_thread(mg_thread_func_t func, void *param)
  2916. {
  2917. pthread_t thread_id;
  2918. pthread_attr_t attr;
  2919. int result;
  2920. (void)pthread_attr_init(&attr);
  2921. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2922. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2923. /* Compile-time option to control stack size,
  2924. * e.g. -DUSE_STACK_SIZE=16384 */
  2925. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2926. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2927. result = pthread_create(&thread_id, &attr, func, param);
  2928. pthread_attr_destroy(&attr);
  2929. return result;
  2930. }
  2931. /* Start a thread storing the thread context. */
  2932. static int
  2933. mg_start_thread_with_id(mg_thread_func_t func,
  2934. void *param,
  2935. pthread_t *threadidptr)
  2936. {
  2937. pthread_t thread_id;
  2938. pthread_attr_t attr;
  2939. int result;
  2940. (void)pthread_attr_init(&attr);
  2941. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2942. /* Compile-time option to control stack size,
  2943. * e.g. -DUSE_STACK_SIZE=16384 */
  2944. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2945. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2946. result = pthread_create(&thread_id, &attr, func, param);
  2947. pthread_attr_destroy(&attr);
  2948. if ((result == 0) && (threadidptr != NULL)) {
  2949. *threadidptr = thread_id;
  2950. }
  2951. return result;
  2952. }
  2953. /* Wait for a thread to finish. */
  2954. static int
  2955. mg_join_thread(pthread_t threadid)
  2956. {
  2957. int result;
  2958. result = pthread_join(threadid, NULL);
  2959. return result;
  2960. }
  2961. #ifndef NO_CGI
  2962. static pid_t
  2963. spawn_process(struct mg_connection *conn,
  2964. const char *prog,
  2965. char *envblk,
  2966. char *envp[],
  2967. int fdin,
  2968. int fdout,
  2969. int fderr,
  2970. const char *dir)
  2971. {
  2972. pid_t pid;
  2973. const char *interp;
  2974. (void)envblk;
  2975. if (conn == NULL) {
  2976. return 0;
  2977. }
  2978. if ((pid = fork()) == -1) {
  2979. /* Parent */
  2980. send_http_error(conn,
  2981. 500,
  2982. "Error: Creating CGI process\nfork(): %s",
  2983. strerror(ERRNO));
  2984. } else if (pid == 0) {
  2985. /* Child */
  2986. if (chdir(dir) != 0) {
  2987. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2988. } else if (dup2(fdin, 0) == -1) {
  2989. mg_cry(
  2990. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2991. } else if (dup2(fdout, 1) == -1) {
  2992. mg_cry(
  2993. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2994. } else if (dup2(fderr, 2) == -1) {
  2995. mg_cry(
  2996. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  2997. } else {
  2998. /* Keep stderr and stdout in two different pipes.
  2999. * Stdout will be sent back to the client,
  3000. * stderr should go into a server error log. */
  3001. (void)close(fdin);
  3002. (void)close(fdout);
  3003. (void)close(fderr);
  3004. /* After exec, all signal handlers are restored to their default
  3005. * values, with one exception of SIGCHLD. According to
  3006. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3007. * leave unchanged after exec if it was set to be ignored. Restore
  3008. * it to default action. */
  3009. signal(SIGCHLD, SIG_DFL);
  3010. interp = conn->ctx->config[CGI_INTERPRETER];
  3011. if (interp == NULL) {
  3012. (void)execle(prog, prog, NULL, envp);
  3013. mg_cry(conn,
  3014. "%s: execle(%s): %s",
  3015. __func__,
  3016. prog,
  3017. strerror(ERRNO));
  3018. } else {
  3019. (void)execle(interp, interp, prog, NULL, envp);
  3020. mg_cry(conn,
  3021. "%s: execle(%s %s): %s",
  3022. __func__,
  3023. interp,
  3024. prog,
  3025. strerror(ERRNO));
  3026. }
  3027. }
  3028. exit(EXIT_FAILURE);
  3029. }
  3030. return pid;
  3031. }
  3032. #endif /* !NO_CGI */
  3033. static int
  3034. set_non_blocking_mode(SOCKET sock)
  3035. {
  3036. int flags;
  3037. flags = fcntl(sock, F_GETFL, 0);
  3038. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3039. return 0;
  3040. }
  3041. #endif /* _WIN32 */
  3042. /* End of initial operating system specific define block. */
  3043. /* Get a random number (independent of C rand function) */
  3044. static uint64_t
  3045. get_random(void)
  3046. {
  3047. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3048. static uint64_t lcg = 0; /* Linear congruential generator */
  3049. struct timespec now;
  3050. memset(&now, 0, sizeof(now));
  3051. clock_gettime(CLOCK_MONOTONIC, &now);
  3052. if (lfsr == 0) {
  3053. /* lfsr will be only 0 if has not been initialized,
  3054. * so this code is called only once. */
  3055. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3056. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3057. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3058. + (uint64_t)(ptrdiff_t)&now;
  3059. } else {
  3060. /* Get the next step of both random number generators. */
  3061. lfsr = (lfsr >> 1)
  3062. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3063. << 63);
  3064. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3065. }
  3066. /* Combining two pseudo-random number generators and a high resolution part
  3067. * of the current server time will make it hard (impossible?) to guess the
  3068. * next number. */
  3069. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3070. }
  3071. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3072. * descriptor. Return number of bytes written. */
  3073. static int
  3074. push(struct mg_context *ctx,
  3075. FILE *fp,
  3076. SOCKET sock,
  3077. SSL *ssl,
  3078. const char *buf,
  3079. int len,
  3080. double timeout)
  3081. {
  3082. struct timespec start, now;
  3083. int n, err;
  3084. #ifdef _WIN32
  3085. typedef int len_t;
  3086. #else
  3087. typedef size_t len_t;
  3088. #endif
  3089. if (timeout > 0) {
  3090. memset(&start, 0, sizeof(start));
  3091. memset(&now, 0, sizeof(now));
  3092. clock_gettime(CLOCK_MONOTONIC, &start);
  3093. }
  3094. if (ctx == NULL) {
  3095. return -1;
  3096. }
  3097. #ifdef NO_SSL
  3098. if (ssl) {
  3099. return -1;
  3100. }
  3101. #endif
  3102. do {
  3103. #ifndef NO_SSL
  3104. if (ssl != NULL) {
  3105. n = SSL_write(ssl, buf, len);
  3106. if (n <= 0) {
  3107. err = SSL_get_error(ssl, n);
  3108. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3109. err = ERRNO;
  3110. } else {
  3111. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3112. return -1;
  3113. }
  3114. } else {
  3115. err = 0;
  3116. }
  3117. } else
  3118. #endif
  3119. if (fp != NULL) {
  3120. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3121. if (ferror(fp)) {
  3122. n = -1;
  3123. err = ERRNO;
  3124. } else {
  3125. err = 0;
  3126. }
  3127. } else {
  3128. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3129. err = (n < 0) ? ERRNO : 0;
  3130. }
  3131. if (ctx->stop_flag) {
  3132. return -1;
  3133. }
  3134. if ((n > 0) || (n == 0 && len == 0)) {
  3135. /* some data has been read, or no data was requested */
  3136. return n;
  3137. }
  3138. if (n == 0) {
  3139. /* shutdown of the socket at client side */
  3140. return -1;
  3141. }
  3142. if (n < 0) {
  3143. /* socket error - check errno */
  3144. DEBUG_TRACE("send() failed, error %d", err);
  3145. /* TODO: error handling depending on the error code.
  3146. * These codes are different between Windows and Linux.
  3147. */
  3148. return -1;
  3149. }
  3150. /* This code is not reached in the moment.
  3151. * ==> Fix the TODOs above first. */
  3152. if (timeout > 0) {
  3153. clock_gettime(CLOCK_MONOTONIC, &now);
  3154. }
  3155. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3156. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3157. used */
  3158. return -1;
  3159. }
  3160. static int64_t
  3161. push_all(struct mg_context *ctx,
  3162. FILE *fp,
  3163. SOCKET sock,
  3164. SSL *ssl,
  3165. const char *buf,
  3166. int64_t len)
  3167. {
  3168. double timeout = -1.0;
  3169. int64_t n, nwritten = 0;
  3170. if (ctx == NULL) {
  3171. return -1;
  3172. }
  3173. if (ctx->config[REQUEST_TIMEOUT]) {
  3174. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3175. }
  3176. while (len > 0 && ctx->stop_flag == 0) {
  3177. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3178. if (n < 0) {
  3179. if (nwritten == 0) {
  3180. nwritten = n; /* Propagate the error */
  3181. }
  3182. break;
  3183. } else if (n == 0) {
  3184. break; /* No more data to write */
  3185. } else {
  3186. nwritten += n;
  3187. len -= n;
  3188. }
  3189. }
  3190. return nwritten;
  3191. }
  3192. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3193. * Return negative value on error, or number of bytes read on success. */
  3194. static int
  3195. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3196. {
  3197. int nread, err;
  3198. struct timespec start, now;
  3199. #ifdef _WIN32
  3200. typedef int len_t;
  3201. #else
  3202. typedef size_t len_t;
  3203. #endif
  3204. if (timeout > 0) {
  3205. memset(&start, 0, sizeof(start));
  3206. memset(&now, 0, sizeof(now));
  3207. clock_gettime(CLOCK_MONOTONIC, &start);
  3208. }
  3209. do {
  3210. if (fp != NULL) {
  3211. /* Use read() instead of fread(), because if we're reading from the
  3212. * CGI pipe, fread() may block until IO buffer is filled up. We
  3213. * cannot afford to block and must pass all read bytes immediately
  3214. * to the client. */
  3215. nread = (int)read(fileno(fp), buf, (size_t)len);
  3216. err = (nread < 0) ? ERRNO : 0;
  3217. #ifndef NO_SSL
  3218. } else if (conn->ssl != NULL) {
  3219. nread = SSL_read(conn->ssl, buf, len);
  3220. if (nread <= 0) {
  3221. err = SSL_get_error(conn->ssl, nread);
  3222. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3223. err = ERRNO;
  3224. } else {
  3225. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3226. return -1;
  3227. }
  3228. } else {
  3229. err = 0;
  3230. }
  3231. #endif
  3232. } else {
  3233. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3234. err = (nread < 0) ? ERRNO : 0;
  3235. }
  3236. if (conn->ctx->stop_flag) {
  3237. return -1;
  3238. }
  3239. if ((nread > 0) || (nread == 0 && len == 0)) {
  3240. /* some data has been read, or no data was requested */
  3241. return nread;
  3242. }
  3243. if (nread == 0) {
  3244. /* shutdown of the socket at client side */
  3245. return -1;
  3246. }
  3247. if (nread < 0) {
  3248. /* socket error - check errno */
  3249. #ifdef _WIN32
  3250. if (err == WSAEWOULDBLOCK) {
  3251. /* standard case if called from close_socket_gracefully */
  3252. return -1;
  3253. } else if (err == WSAETIMEDOUT) {
  3254. /* timeout is handled by the while loop */
  3255. } else {
  3256. DEBUG_TRACE("recv() failed, error %d", err);
  3257. return -1;
  3258. }
  3259. #else
  3260. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3261. * if the timeout is reached and if the socket was set to non-
  3262. * blocking in close_socket_gracefully, so we can not distinguish
  3263. * here. We have to wait for the timeout in both cases for now.
  3264. */
  3265. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3266. /* EAGAIN/EWOULDBLOCK:
  3267. * standard case if called from close_socket_gracefully
  3268. * => should return -1 */
  3269. /* or timeout occured
  3270. * => the code must stay in the while loop */
  3271. /* EINTR can be generated on a socket with a timeout set even
  3272. * when SA_RESTART is effective for all relevant signals
  3273. * (see signal(7)).
  3274. * => stay in the while loop */
  3275. } else {
  3276. DEBUG_TRACE("recv() failed, error %d", err);
  3277. return -1;
  3278. }
  3279. #endif
  3280. }
  3281. if (timeout > 0) {
  3282. clock_gettime(CLOCK_MONOTONIC, &now);
  3283. }
  3284. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3285. /* Timeout occured, but no data available. */
  3286. return -1;
  3287. }
  3288. static int
  3289. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3290. {
  3291. int n, nread = 0;
  3292. double timeout = -1.0;
  3293. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3294. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3295. }
  3296. while (len > 0 && conn->ctx->stop_flag == 0) {
  3297. n = pull(fp, conn, buf + nread, len, timeout);
  3298. if (n < 0) {
  3299. if (nread == 0) {
  3300. nread = n; /* Propagate the error */
  3301. }
  3302. break;
  3303. } else if (n == 0) {
  3304. break; /* No more data to read */
  3305. } else {
  3306. conn->consumed_content += n;
  3307. nread += n;
  3308. len -= n;
  3309. }
  3310. }
  3311. return nread;
  3312. }
  3313. static void
  3314. discard_unread_request_data(struct mg_connection *conn)
  3315. {
  3316. char buf[MG_BUF_LEN];
  3317. size_t to_read;
  3318. int nread;
  3319. if (conn == NULL) {
  3320. return;
  3321. }
  3322. to_read = sizeof(buf);
  3323. if (conn->is_chunked) {
  3324. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3325. * completely */
  3326. while (conn->is_chunked == 1) {
  3327. nread = mg_read(conn, buf, to_read);
  3328. if (nread <= 0) {
  3329. break;
  3330. }
  3331. }
  3332. } else {
  3333. /* Not chunked: content length is known */
  3334. while (conn->consumed_content < conn->content_len) {
  3335. if (to_read
  3336. > (size_t)(conn->content_len - conn->consumed_content)) {
  3337. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3338. }
  3339. nread = mg_read(conn, buf, to_read);
  3340. if (nread <= 0) {
  3341. break;
  3342. }
  3343. }
  3344. }
  3345. }
  3346. static int
  3347. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3348. {
  3349. int64_t n, buffered_len, nread;
  3350. int64_t len64 =
  3351. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3352. * int, we may not read more
  3353. * bytes */
  3354. const char *body;
  3355. if (conn == NULL) {
  3356. return 0;
  3357. }
  3358. /* If Content-Length is not set for a PUT or POST request, read until
  3359. * socket is closed */
  3360. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3361. conn->content_len = INT64_MAX;
  3362. conn->must_close = 1;
  3363. }
  3364. nread = 0;
  3365. if (conn->consumed_content < conn->content_len) {
  3366. /* Adjust number of bytes to read. */
  3367. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3368. if (left_to_read < len64) {
  3369. /* Do not read more than the total content length of the request.
  3370. */
  3371. len64 = left_to_read;
  3372. }
  3373. /* Return buffered data */
  3374. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3375. - conn->consumed_content;
  3376. if (buffered_len > 0) {
  3377. if (len64 < buffered_len) {
  3378. buffered_len = len64;
  3379. }
  3380. body = conn->buf + conn->request_len + conn->consumed_content;
  3381. memcpy(buf, body, (size_t)buffered_len);
  3382. len64 -= buffered_len;
  3383. conn->consumed_content += buffered_len;
  3384. nread += buffered_len;
  3385. buf = (char *)buf + buffered_len;
  3386. }
  3387. /* We have returned all buffered data. Read new data from the remote
  3388. * socket.
  3389. */
  3390. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3391. nread += n;
  3392. } else {
  3393. nread = (nread > 0 ? nread : n);
  3394. }
  3395. }
  3396. return (int)nread;
  3397. }
  3398. static char
  3399. mg_getc(struct mg_connection *conn)
  3400. {
  3401. char c;
  3402. if (conn == NULL) {
  3403. return 0;
  3404. }
  3405. conn->content_len++;
  3406. if (mg_read_inner(conn, &c, 1) <= 0) {
  3407. return (char)0;
  3408. }
  3409. return c;
  3410. }
  3411. int
  3412. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3413. {
  3414. if (len > INT_MAX) {
  3415. len = INT_MAX;
  3416. }
  3417. if (conn == NULL) {
  3418. return 0;
  3419. }
  3420. if (conn->is_chunked) {
  3421. size_t all_read = 0;
  3422. while (len > 0) {
  3423. if (conn->chunk_remainder) {
  3424. /* copy from the remainder of the last received chunk */
  3425. long read_ret;
  3426. size_t read_now =
  3427. ((conn->chunk_remainder > len) ? (len)
  3428. : (conn->chunk_remainder));
  3429. conn->content_len += (int)read_now;
  3430. read_ret =
  3431. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3432. all_read += (size_t)read_ret;
  3433. conn->chunk_remainder -= read_now;
  3434. len -= read_now;
  3435. if (conn->chunk_remainder == 0) {
  3436. /* the rest of the data in the current chunk has been read
  3437. */
  3438. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3439. /* Protocol violation */
  3440. return -1;
  3441. }
  3442. }
  3443. } else {
  3444. /* fetch a new chunk */
  3445. int i = 0;
  3446. char lenbuf[64];
  3447. char *end = 0;
  3448. unsigned long chunkSize = 0;
  3449. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3450. lenbuf[i] = mg_getc(conn);
  3451. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3452. continue;
  3453. }
  3454. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3455. lenbuf[i + 1] = 0;
  3456. chunkSize = strtoul(lenbuf, &end, 16);
  3457. break;
  3458. }
  3459. if (!isalnum(lenbuf[i])) {
  3460. /* illegal character for chunk length */
  3461. return -1;
  3462. }
  3463. }
  3464. if ((end == NULL) || (*end != '\r')) {
  3465. /* chunksize not set correctly */
  3466. return -1;
  3467. }
  3468. conn->chunk_remainder = chunkSize;
  3469. if (chunkSize == 0) {
  3470. /* regular end of content */
  3471. conn->is_chunked = 2;
  3472. break;
  3473. }
  3474. }
  3475. }
  3476. return (int)all_read;
  3477. }
  3478. return mg_read_inner(conn, buf, len);
  3479. }
  3480. int
  3481. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3482. {
  3483. time_t now;
  3484. int64_t n, total, allowed;
  3485. if (conn == NULL) {
  3486. return 0;
  3487. }
  3488. if (conn->throttle > 0) {
  3489. if ((now = time(NULL)) != conn->last_throttle_time) {
  3490. conn->last_throttle_time = now;
  3491. conn->last_throttle_bytes = 0;
  3492. }
  3493. allowed = conn->throttle - conn->last_throttle_bytes;
  3494. if (allowed > (int64_t)len) {
  3495. allowed = (int64_t)len;
  3496. }
  3497. if ((total = push_all(conn->ctx,
  3498. NULL,
  3499. conn->client.sock,
  3500. conn->ssl,
  3501. (const char *)buf,
  3502. (int64_t)allowed)) == allowed) {
  3503. buf = (char *)buf + total;
  3504. conn->last_throttle_bytes += total;
  3505. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3506. allowed = conn->throttle > (int64_t)len - total
  3507. ? (int64_t)len - total
  3508. : conn->throttle;
  3509. if ((n = push_all(conn->ctx,
  3510. NULL,
  3511. conn->client.sock,
  3512. conn->ssl,
  3513. (const char *)buf,
  3514. (int64_t)allowed)) != allowed) {
  3515. break;
  3516. }
  3517. sleep(1);
  3518. conn->last_throttle_bytes = allowed;
  3519. conn->last_throttle_time = time(NULL);
  3520. buf = (char *)buf + n;
  3521. total += n;
  3522. }
  3523. }
  3524. } else {
  3525. total = push_all(conn->ctx,
  3526. NULL,
  3527. conn->client.sock,
  3528. conn->ssl,
  3529. (const char *)buf,
  3530. (int64_t)len);
  3531. }
  3532. return (int)total;
  3533. }
  3534. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3535. static int
  3536. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3537. {
  3538. va_list ap_copy;
  3539. size_t size = MG_BUF_LEN;
  3540. int len = -1;
  3541. *buf = NULL;
  3542. while (len < 0) {
  3543. if (*buf) {
  3544. mg_free(*buf);
  3545. }
  3546. *buf = (char *)mg_malloc(size *= 4);
  3547. if (!*buf) {
  3548. break;
  3549. }
  3550. va_copy(ap_copy, ap);
  3551. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3552. va_end(ap_copy);
  3553. *buf[size - 1] = 0;
  3554. }
  3555. return len;
  3556. }
  3557. /* Print message to buffer. If buffer is large enough to hold the message,
  3558. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3559. * and return allocated buffer. */
  3560. static int
  3561. alloc_vprintf(char **out_buf,
  3562. char *prealloc_buf,
  3563. size_t prealloc_size,
  3564. const char *fmt,
  3565. va_list ap)
  3566. {
  3567. va_list ap_copy;
  3568. int len;
  3569. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3570. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3571. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3572. * Therefore, we make two passes: on first pass, get required message
  3573. * length.
  3574. * On second pass, actually print the message. */
  3575. va_copy(ap_copy, ap);
  3576. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3577. va_end(ap_copy);
  3578. if (len < 0) {
  3579. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3580. * Switch to alternative code path that uses incremental allocations.
  3581. */
  3582. va_copy(ap_copy, ap);
  3583. len = alloc_vprintf2(out_buf, fmt, ap);
  3584. va_end(ap_copy);
  3585. } else if ((size_t)(len) >= prealloc_size) {
  3586. /* The pre-allocated buffer not large enough. */
  3587. /* Allocate a new buffer. */
  3588. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3589. if (!*out_buf) {
  3590. /* Allocation failed. Return -1 as "out of memory" error. */
  3591. return -1;
  3592. }
  3593. /* Buffer allocation successful. Store the string there. */
  3594. va_copy(ap_copy, ap);
  3595. IGNORE_UNUSED_RESULT(
  3596. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3597. va_end(ap_copy);
  3598. } else {
  3599. /* The pre-allocated buffer is large enough.
  3600. * Use it to store the string and return the address. */
  3601. va_copy(ap_copy, ap);
  3602. IGNORE_UNUSED_RESULT(
  3603. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3604. va_end(ap_copy);
  3605. *out_buf = prealloc_buf;
  3606. }
  3607. return len;
  3608. }
  3609. static int
  3610. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3611. {
  3612. char mem[MG_BUF_LEN];
  3613. char *buf = NULL;
  3614. int len;
  3615. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3616. len = mg_write(conn, buf, (size_t)len);
  3617. }
  3618. if (buf != mem && buf != NULL) {
  3619. mg_free(buf);
  3620. }
  3621. return len;
  3622. }
  3623. int
  3624. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3625. {
  3626. va_list ap;
  3627. int result;
  3628. va_start(ap, fmt);
  3629. result = mg_vprintf(conn, fmt, ap);
  3630. va_end(ap);
  3631. return result;
  3632. }
  3633. int
  3634. mg_url_decode(const char *src,
  3635. int src_len,
  3636. char *dst,
  3637. int dst_len,
  3638. int is_form_url_encoded)
  3639. {
  3640. int i, j, a, b;
  3641. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3642. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3643. if (i < src_len - 2 && src[i] == '%'
  3644. && isxdigit(*(const unsigned char *)(src + i + 1))
  3645. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3646. a = tolower(*(const unsigned char *)(src + i + 1));
  3647. b = tolower(*(const unsigned char *)(src + i + 2));
  3648. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3649. i += 2;
  3650. } else if (is_form_url_encoded && src[i] == '+') {
  3651. dst[j] = ' ';
  3652. } else {
  3653. dst[j] = src[i];
  3654. }
  3655. }
  3656. dst[j] = '\0'; /* Null-terminate the destination */
  3657. return i >= src_len ? j : -1;
  3658. }
  3659. int
  3660. mg_get_var(const char *data,
  3661. size_t data_len,
  3662. const char *name,
  3663. char *dst,
  3664. size_t dst_len)
  3665. {
  3666. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3667. }
  3668. int
  3669. mg_get_var2(const char *data,
  3670. size_t data_len,
  3671. const char *name,
  3672. char *dst,
  3673. size_t dst_len,
  3674. size_t occurrence)
  3675. {
  3676. const char *p, *e, *s;
  3677. size_t name_len;
  3678. int len;
  3679. if (dst == NULL || dst_len == 0) {
  3680. len = -2;
  3681. } else if (data == NULL || name == NULL || data_len == 0) {
  3682. len = -1;
  3683. dst[0] = '\0';
  3684. } else {
  3685. name_len = strlen(name);
  3686. e = data + data_len;
  3687. len = -1;
  3688. dst[0] = '\0';
  3689. /* data is "var1=val1&var2=val2...". Find variable first */
  3690. for (p = data; p + name_len < e; p++) {
  3691. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3692. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3693. /* Point p to variable value */
  3694. p += name_len + 1;
  3695. /* Point s to the end of the value */
  3696. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3697. if (s == NULL) {
  3698. s = e;
  3699. }
  3700. /* assert(s >= p); */
  3701. if (s < p) {
  3702. return -3;
  3703. }
  3704. /* Decode variable into destination buffer */
  3705. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3706. /* Redirect error code from -1 to -2 (destination buffer too
  3707. * small). */
  3708. if (len == -1) {
  3709. len = -2;
  3710. }
  3711. break;
  3712. }
  3713. }
  3714. }
  3715. return len;
  3716. }
  3717. int
  3718. mg_get_cookie(const char *cookie_header,
  3719. const char *var_name,
  3720. char *dst,
  3721. size_t dst_size)
  3722. {
  3723. const char *s, *p, *end;
  3724. int name_len, len = -1;
  3725. if (dst == NULL || dst_size == 0) {
  3726. len = -2;
  3727. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3728. len = -1;
  3729. dst[0] = '\0';
  3730. } else {
  3731. name_len = (int)strlen(var_name);
  3732. end = s + strlen(s);
  3733. dst[0] = '\0';
  3734. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3735. if (s[name_len] == '=') {
  3736. s += name_len + 1;
  3737. if ((p = strchr(s, ' ')) == NULL) {
  3738. p = end;
  3739. }
  3740. if (p[-1] == ';') {
  3741. p--;
  3742. }
  3743. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3744. s++;
  3745. p--;
  3746. }
  3747. if ((size_t)(p - s) < dst_size) {
  3748. len = (int)(p - s);
  3749. mg_strlcpy(dst, s, (size_t)len + 1);
  3750. } else {
  3751. len = -3;
  3752. }
  3753. break;
  3754. }
  3755. }
  3756. }
  3757. return len;
  3758. }
  3759. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3760. static void
  3761. base64_encode(const unsigned char *src, int src_len, char *dst)
  3762. {
  3763. static const char *b64 =
  3764. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3765. int i, j, a, b, c;
  3766. for (i = j = 0; i < src_len; i += 3) {
  3767. a = src[i];
  3768. b = i + 1 >= src_len ? 0 : src[i + 1];
  3769. c = i + 2 >= src_len ? 0 : src[i + 2];
  3770. dst[j++] = b64[a >> 2];
  3771. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3772. if (i + 1 < src_len) {
  3773. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3774. }
  3775. if (i + 2 < src_len) {
  3776. dst[j++] = b64[c & 63];
  3777. }
  3778. }
  3779. while (j % 4 != 0) {
  3780. dst[j++] = '=';
  3781. }
  3782. dst[j++] = '\0';
  3783. }
  3784. #endif
  3785. #if defined(USE_LUA)
  3786. static unsigned char
  3787. b64reverse(char letter)
  3788. {
  3789. if (letter >= 'A' && letter <= 'Z') {
  3790. return letter - 'A';
  3791. }
  3792. if (letter >= 'a' && letter <= 'z') {
  3793. return letter - 'a' + 26;
  3794. }
  3795. if (letter >= '0' && letter <= '9') {
  3796. return letter - '0' + 52;
  3797. }
  3798. if (letter == '+') {
  3799. return 62;
  3800. }
  3801. if (letter == '/') {
  3802. return 63;
  3803. }
  3804. if (letter == '=') {
  3805. return 255; /* normal end */
  3806. }
  3807. return 254; /* error */
  3808. }
  3809. static int
  3810. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3811. {
  3812. int i;
  3813. unsigned char a, b, c, d;
  3814. *dst_len = 0;
  3815. for (i = 0; i < src_len; i += 4) {
  3816. a = b64reverse(src[i]);
  3817. if (a >= 254) {
  3818. return i;
  3819. }
  3820. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3821. if (b >= 254) {
  3822. return i + 1;
  3823. }
  3824. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3825. if (c == 254) {
  3826. return i + 2;
  3827. }
  3828. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3829. if (d == 254) {
  3830. return i + 3;
  3831. }
  3832. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3833. if (c != 255) {
  3834. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3835. if (d != 255) {
  3836. dst[(*dst_len)++] = (c << 6) + d;
  3837. }
  3838. }
  3839. }
  3840. return -1;
  3841. }
  3842. #endif
  3843. static int
  3844. is_put_or_delete_method(const struct mg_connection *conn)
  3845. {
  3846. if (conn) {
  3847. const char *s = conn->request_info.request_method;
  3848. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3849. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3850. }
  3851. return 0;
  3852. }
  3853. static void
  3854. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3855. char *filename, /* out: filename */
  3856. size_t filename_buf_len, /* in: size of filename buffer */
  3857. struct file *filep, /* out: file structure */
  3858. int *is_found, /* out: file is found (directly) */
  3859. int *is_script_resource, /* out: handled by a script? */
  3860. int *is_websocket_request, /* out: websocket connetion? */
  3861. int *is_put_or_delete_request /* out: put/delete a file? */
  3862. )
  3863. {
  3864. /* TODO (high): Restructure this function */
  3865. #if !defined(NO_FILES)
  3866. const char *uri = conn->request_info.local_uri;
  3867. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3868. const char *rewrite;
  3869. struct vec a, b;
  3870. int match_len;
  3871. char gz_path[PATH_MAX];
  3872. char const *accept_encoding;
  3873. int truncated;
  3874. #if !defined(NO_CGI) || defined(USE_LUA)
  3875. char *p;
  3876. #endif
  3877. #else
  3878. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3879. #endif
  3880. memset(filep, 0, sizeof(*filep));
  3881. *filename = 0;
  3882. *is_found = 0;
  3883. *is_script_resource = 0;
  3884. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3885. #if defined(USE_WEBSOCKET)
  3886. *is_websocket_request = is_websocket_protocol(conn);
  3887. #if !defined(NO_FILES)
  3888. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3889. root = conn->ctx->config[WEBSOCKET_ROOT];
  3890. }
  3891. #endif /* !NO_FILES */
  3892. #else /* USE_WEBSOCKET */
  3893. *is_websocket_request = 0;
  3894. #endif /* USE_WEBSOCKET */
  3895. #if !defined(NO_FILES)
  3896. /* Note that root == NULL is a regular use case here. This occurs,
  3897. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3898. * config is not required. */
  3899. if (root == NULL) {
  3900. /* all file related outputs have already been set to 0, just return
  3901. */
  3902. return;
  3903. }
  3904. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3905. * of the path one byte on the right.
  3906. * If document_root is NULL, leave the file empty. */
  3907. mg_snprintf(
  3908. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  3909. if (truncated) {
  3910. goto interpret_cleanup;
  3911. }
  3912. rewrite = conn->ctx->config[REWRITE];
  3913. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3914. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3915. mg_snprintf(conn,
  3916. &truncated,
  3917. filename,
  3918. filename_buf_len - 1,
  3919. "%.*s%s",
  3920. (int)b.len,
  3921. b.ptr,
  3922. uri + match_len);
  3923. break;
  3924. }
  3925. }
  3926. if (truncated) {
  3927. goto interpret_cleanup;
  3928. }
  3929. /* Local file path and name, corresponding to requested URI
  3930. * is now stored in "filename" variable. */
  3931. if (mg_stat(conn, filename, filep)) {
  3932. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3933. /* File exists. Check if it is a script type. */
  3934. if (0
  3935. #if !defined(NO_CGI)
  3936. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3937. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3938. filename) > 0
  3939. #endif
  3940. #if defined(USE_LUA)
  3941. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3942. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3943. filename) > 0
  3944. #endif
  3945. #if defined(USE_DUKTAPE)
  3946. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3947. strlen(
  3948. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3949. filename) > 0
  3950. #endif
  3951. ) {
  3952. /* The request addresses a CGI script or a Lua script. The URI
  3953. * corresponds to the script itself (like /path/script.cgi),
  3954. * and there is no additional resource path
  3955. * (like /path/script.cgi/something).
  3956. * Requests that modify (replace or delete) a resource, like
  3957. * PUT and DELETE requests, should replace/delete the script
  3958. * file.
  3959. * Requests that read or write from/to a resource, like GET and
  3960. * POST requests, should call the script and return the
  3961. * generated response. */
  3962. *is_script_resource = !*is_put_or_delete_request;
  3963. }
  3964. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3965. *is_found = 1;
  3966. return;
  3967. }
  3968. /* If we can't find the actual file, look for the file
  3969. * with the same name but a .gz extension. If we find it,
  3970. * use that and set the gzipped flag in the file struct
  3971. * to indicate that the response need to have the content-
  3972. * encoding: gzip header.
  3973. * We can only do this if the browser declares support. */
  3974. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  3975. if (strstr(accept_encoding, "gzip") != NULL) {
  3976. mg_snprintf(
  3977. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  3978. if (truncated) {
  3979. goto interpret_cleanup;
  3980. }
  3981. if (mg_stat(conn, gz_path, filep)) {
  3982. if (filep) {
  3983. filep->gzipped = 1;
  3984. *is_found = 1;
  3985. }
  3986. /* Currently gz files can not be scripts. */
  3987. return;
  3988. }
  3989. }
  3990. }
  3991. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3992. /* Support PATH_INFO for CGI scripts. */
  3993. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3994. if (*p == '/') {
  3995. *p = '\0';
  3996. if ((0
  3997. #if !defined(NO_CGI)
  3998. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3999. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4000. filename) > 0
  4001. #endif
  4002. #if defined(USE_LUA)
  4003. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4004. strlen(
  4005. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4006. filename) > 0
  4007. #endif
  4008. #if defined(USE_DUKTAPE)
  4009. || match_prefix(
  4010. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4011. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4012. filename) > 0
  4013. #endif
  4014. ) && mg_stat(conn, filename, filep)) {
  4015. /* Shift PATH_INFO block one character right, e.g.
  4016. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4017. * conn->path_info is pointing to the local variable "path"
  4018. * declared in handle_request(), so PATH_INFO is not valid
  4019. * after handle_request returns. */
  4020. conn->path_info = p + 1;
  4021. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4022. * trailing \0 */
  4023. p[1] = '/';
  4024. *is_script_resource = 1;
  4025. break;
  4026. } else {
  4027. *p = '/';
  4028. }
  4029. }
  4030. }
  4031. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4032. #endif /* !defined(NO_FILES) */
  4033. return;
  4034. #if !defined(NO_FILES)
  4035. /* Reset all outputs */
  4036. interpret_cleanup:
  4037. memset(filep, 0, sizeof(*filep));
  4038. *filename = 0;
  4039. *is_found = 0;
  4040. *is_script_resource = 0;
  4041. *is_websocket_request = 0;
  4042. *is_put_or_delete_request = 0;
  4043. #endif /* !defined(NO_FILES) */
  4044. }
  4045. /* Check whether full request is buffered. Return:
  4046. * -1 if request is malformed
  4047. * 0 if request is not yet fully buffered
  4048. * >0 actual request length, including last \r\n\r\n */
  4049. static int
  4050. get_request_len(const char *buf, int buflen)
  4051. {
  4052. const char *s, *e;
  4053. int len = 0;
  4054. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4055. /* Control characters are not allowed but >=128 is. */
  4056. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4057. && *(const unsigned char *)s < 128) {
  4058. len = -1;
  4059. break; /* [i_a] abort scan as soon as one malformed character is
  4060. * found; */
  4061. /* don't let subsequent \r\n\r\n win us over anyhow */
  4062. } else if (s[0] == '\n' && s[1] == '\n') {
  4063. len = (int)(s - buf) + 2;
  4064. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4065. len = (int)(s - buf) + 3;
  4066. }
  4067. return len;
  4068. }
  4069. /* Convert month to the month number. Return -1 on error, or month number */
  4070. static int
  4071. get_month_index(const char *s)
  4072. {
  4073. size_t i;
  4074. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4075. if (!strcmp(s, month_names[i])) {
  4076. return (int)i;
  4077. }
  4078. }
  4079. return -1;
  4080. }
  4081. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4082. static time_t
  4083. parse_date_string(const char *datetime)
  4084. {
  4085. char month_str[32] = {0};
  4086. int second, minute, hour, day, month, year;
  4087. time_t result = (time_t)0;
  4088. struct tm tm;
  4089. if ((sscanf(datetime,
  4090. "%d/%3s/%d %d:%d:%d",
  4091. &day,
  4092. month_str,
  4093. &year,
  4094. &hour,
  4095. &minute,
  4096. &second) == 6) || (sscanf(datetime,
  4097. "%d %3s %d %d:%d:%d",
  4098. &day,
  4099. month_str,
  4100. &year,
  4101. &hour,
  4102. &minute,
  4103. &second) == 6)
  4104. || (sscanf(datetime,
  4105. "%*3s, %d %3s %d %d:%d:%d",
  4106. &day,
  4107. month_str,
  4108. &year,
  4109. &hour,
  4110. &minute,
  4111. &second) == 6) || (sscanf(datetime,
  4112. "%d-%3s-%d %d:%d:%d",
  4113. &day,
  4114. month_str,
  4115. &year,
  4116. &hour,
  4117. &minute,
  4118. &second) == 6)) {
  4119. month = get_month_index(month_str);
  4120. if ((month >= 0) && (year >= 1970)) {
  4121. memset(&tm, 0, sizeof(tm));
  4122. tm.tm_year = year - 1900;
  4123. tm.tm_mon = month;
  4124. tm.tm_mday = day;
  4125. tm.tm_hour = hour;
  4126. tm.tm_min = minute;
  4127. tm.tm_sec = second;
  4128. result = timegm(&tm);
  4129. }
  4130. }
  4131. return result;
  4132. }
  4133. /* Protect against directory disclosure attack by removing '..',
  4134. * excessive '/' and '\' characters */
  4135. static void
  4136. remove_double_dots_and_double_slashes(char *s)
  4137. {
  4138. char *p = s;
  4139. while (*s != '\0') {
  4140. *p++ = *s++;
  4141. if (s[-1] == '/' || s[-1] == '\\') {
  4142. /* Skip all following slashes, backslashes and double-dots */
  4143. while (s[0] != '\0') {
  4144. if (s[0] == '/' || s[0] == '\\') {
  4145. s++;
  4146. } else if (s[0] == '.' && s[1] == '.') {
  4147. s += 2;
  4148. } else {
  4149. break;
  4150. }
  4151. }
  4152. }
  4153. }
  4154. *p = '\0';
  4155. }
  4156. static const struct {
  4157. const char *extension;
  4158. size_t ext_len;
  4159. const char *mime_type;
  4160. } builtin_mime_types[] = {
  4161. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4162. * application types */
  4163. {".doc", 4, "application/msword"},
  4164. {".eps", 4, "application/postscript"},
  4165. {".exe", 4, "application/octet-stream"},
  4166. {".js", 3, "application/javascript"},
  4167. {".json", 5, "application/json"},
  4168. {".pdf", 4, "application/pdf"},
  4169. {".ps", 3, "application/postscript"},
  4170. {".rtf", 4, "application/rtf"},
  4171. {".xhtml", 6, "application/xhtml+xml"},
  4172. {".xsl", 4, "application/xml"},
  4173. {".xslt", 5, "application/xml"},
  4174. /* fonts */
  4175. {".ttf", 4, "application/font-sfnt"},
  4176. {".cff", 4, "application/font-sfnt"},
  4177. {".otf", 4, "application/font-sfnt"},
  4178. {".aat", 4, "application/font-sfnt"},
  4179. {".sil", 4, "application/font-sfnt"},
  4180. {".pfr", 4, "application/font-tdpfr"},
  4181. {".woff", 5, "application/font-woff"},
  4182. /* audio */
  4183. {".mp3", 4, "audio/mpeg"},
  4184. {".oga", 4, "audio/ogg"},
  4185. {".ogg", 4, "audio/ogg"},
  4186. /* image */
  4187. {".gif", 4, "image/gif"},
  4188. {".ief", 4, "image/ief"},
  4189. {".jpeg", 5, "image/jpeg"},
  4190. {".jpg", 4, "image/jpeg"},
  4191. {".jpm", 4, "image/jpm"},
  4192. {".jpx", 4, "image/jpx"},
  4193. {".png", 4, "image/png"},
  4194. {".svg", 4, "image/svg+xml"},
  4195. {".tif", 4, "image/tiff"},
  4196. {".tiff", 5, "image/tiff"},
  4197. /* model */
  4198. {".wrl", 4, "model/vrml"},
  4199. /* text */
  4200. {".css", 4, "text/css"},
  4201. {".csv", 4, "text/csv"},
  4202. {".htm", 4, "text/html"},
  4203. {".html", 5, "text/html"},
  4204. {".sgm", 4, "text/sgml"},
  4205. {".shtm", 5, "text/html"},
  4206. {".shtml", 6, "text/html"},
  4207. {".txt", 4, "text/plain"},
  4208. {".xml", 4, "text/xml"},
  4209. /* video */
  4210. {".mov", 4, "video/quicktime"},
  4211. {".mp4", 4, "video/mp4"},
  4212. {".mpeg", 5, "video/mpeg"},
  4213. {".mpg", 4, "video/mpeg"},
  4214. {".ogv", 4, "video/ogg"},
  4215. {".qt", 3, "video/quicktime"},
  4216. /* not registered types
  4217. * (http://reference.sitepoint.com/html/mime-types-full,
  4218. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4219. {".arj", 4, "application/x-arj-compressed"},
  4220. {".gz", 3, "application/x-gunzip"},
  4221. {".rar", 4, "application/x-arj-compressed"},
  4222. {".swf", 4, "application/x-shockwave-flash"},
  4223. {".tar", 4, "application/x-tar"},
  4224. {".tgz", 4, "application/x-tar-gz"},
  4225. {".torrent", 8, "application/x-bittorrent"},
  4226. {".ppt", 4, "application/x-mspowerpoint"},
  4227. {".xls", 4, "application/x-msexcel"},
  4228. {".zip", 4, "application/x-zip-compressed"},
  4229. {".aac",
  4230. 4,
  4231. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4232. {".aif", 4, "audio/x-aif"},
  4233. {".m3u", 4, "audio/x-mpegurl"},
  4234. {".mid", 4, "audio/x-midi"},
  4235. {".ra", 3, "audio/x-pn-realaudio"},
  4236. {".ram", 4, "audio/x-pn-realaudio"},
  4237. {".wav", 4, "audio/x-wav"},
  4238. {".bmp", 4, "image/bmp"},
  4239. {".ico", 4, "image/x-icon"},
  4240. {".pct", 4, "image/x-pct"},
  4241. {".pict", 5, "image/pict"},
  4242. {".rgb", 4, "image/x-rgb"},
  4243. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4244. {".asf", 4, "video/x-ms-asf"},
  4245. {".avi", 4, "video/x-msvideo"},
  4246. {".m4v", 4, "video/x-m4v"},
  4247. {NULL, 0, NULL}};
  4248. const char *
  4249. mg_get_builtin_mime_type(const char *path)
  4250. {
  4251. const char *ext;
  4252. size_t i, path_len;
  4253. path_len = strlen(path);
  4254. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4255. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4256. if (path_len > builtin_mime_types[i].ext_len
  4257. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4258. return builtin_mime_types[i].mime_type;
  4259. }
  4260. }
  4261. return "text/plain";
  4262. }
  4263. /* Look at the "path" extension and figure what mime type it has.
  4264. * Store mime type in the vector. */
  4265. static void
  4266. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4267. {
  4268. struct vec ext_vec, mime_vec;
  4269. const char *list, *ext;
  4270. size_t path_len;
  4271. path_len = strlen(path);
  4272. if (ctx == NULL || vec == NULL) {
  4273. return;
  4274. }
  4275. /* Scan user-defined mime types first, in case user wants to
  4276. * override default mime types. */
  4277. list = ctx->config[EXTRA_MIME_TYPES];
  4278. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4279. /* ext now points to the path suffix */
  4280. ext = path + path_len - ext_vec.len;
  4281. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4282. *vec = mime_vec;
  4283. return;
  4284. }
  4285. }
  4286. vec->ptr = mg_get_builtin_mime_type(path);
  4287. vec->len = strlen(vec->ptr);
  4288. }
  4289. /* Stringify binary data. Output buffer must be twice as big as input,
  4290. * because each byte takes 2 bytes in string representation */
  4291. static void
  4292. bin2str(char *to, const unsigned char *p, size_t len)
  4293. {
  4294. static const char *hex = "0123456789abcdef";
  4295. for (; len--; p++) {
  4296. *to++ = hex[p[0] >> 4];
  4297. *to++ = hex[p[0] & 0x0f];
  4298. }
  4299. *to = '\0';
  4300. }
  4301. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4302. char *
  4303. mg_md5(char buf[33], ...)
  4304. {
  4305. md5_byte_t hash[16];
  4306. const char *p;
  4307. va_list ap;
  4308. md5_state_t ctx;
  4309. md5_init(&ctx);
  4310. va_start(ap, buf);
  4311. while ((p = va_arg(ap, const char *)) != NULL) {
  4312. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4313. }
  4314. va_end(ap);
  4315. md5_finish(&ctx, hash);
  4316. bin2str(buf, hash, sizeof(hash));
  4317. return buf;
  4318. }
  4319. /* Check the user's password, return 1 if OK */
  4320. static int
  4321. check_password(const char *method,
  4322. const char *ha1,
  4323. const char *uri,
  4324. const char *nonce,
  4325. const char *nc,
  4326. const char *cnonce,
  4327. const char *qop,
  4328. const char *response)
  4329. {
  4330. char ha2[32 + 1], expected_response[32 + 1];
  4331. /* Some of the parameters may be NULL */
  4332. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4333. || qop == NULL
  4334. || response == NULL) {
  4335. return 0;
  4336. }
  4337. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4338. if (strlen(response) != 32) {
  4339. return 0;
  4340. }
  4341. mg_md5(ha2, method, ":", uri, NULL);
  4342. mg_md5(expected_response,
  4343. ha1,
  4344. ":",
  4345. nonce,
  4346. ":",
  4347. nc,
  4348. ":",
  4349. cnonce,
  4350. ":",
  4351. qop,
  4352. ":",
  4353. ha2,
  4354. NULL);
  4355. return mg_strcasecmp(response, expected_response) == 0;
  4356. }
  4357. /* Use the global passwords file, if specified by auth_gpass option,
  4358. * or search for .htpasswd in the requested directory. */
  4359. static void
  4360. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4361. {
  4362. if (conn != NULL && conn->ctx != NULL) {
  4363. char name[PATH_MAX];
  4364. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4365. struct file file = STRUCT_FILE_INITIALIZER;
  4366. int truncated;
  4367. if (gpass != NULL) {
  4368. /* Use global passwords file */
  4369. if (!mg_fopen(conn, gpass, "r", filep)) {
  4370. #ifdef DEBUG
  4371. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4372. #endif
  4373. }
  4374. /* Important: using local struct file to test path for is_directory
  4375. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4376. * was opened. */
  4377. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4378. mg_snprintf(conn,
  4379. &truncated,
  4380. name,
  4381. sizeof(name),
  4382. "%s/%s",
  4383. path,
  4384. PASSWORDS_FILE_NAME);
  4385. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4386. #ifdef DEBUG
  4387. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4388. #endif
  4389. }
  4390. } else {
  4391. /* Try to find .htpasswd in requested directory. */
  4392. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4393. if (e[0] == '/') {
  4394. break;
  4395. }
  4396. }
  4397. mg_snprintf(conn,
  4398. &truncated,
  4399. name,
  4400. sizeof(name),
  4401. "%.*s%s",
  4402. (int)(e - p),
  4403. p,
  4404. PASSWORDS_FILE_NAME);
  4405. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4406. #ifdef DEBUG
  4407. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4408. #endif
  4409. }
  4410. }
  4411. }
  4412. }
  4413. /* Parsed Authorization header */
  4414. struct ah {
  4415. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4416. };
  4417. /* Return 1 on success. Always initializes the ah structure. */
  4418. static int
  4419. parse_auth_header(struct mg_connection *conn,
  4420. char *buf,
  4421. size_t buf_size,
  4422. struct ah *ah)
  4423. {
  4424. char *name, *value, *s;
  4425. const char *auth_header;
  4426. uint64_t nonce;
  4427. if (!ah || !conn) {
  4428. return 0;
  4429. }
  4430. (void)memset(ah, 0, sizeof(*ah));
  4431. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4432. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4433. return 0;
  4434. }
  4435. /* Make modifiable copy of the auth header */
  4436. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4437. s = buf;
  4438. /* Parse authorization header */
  4439. for (;;) {
  4440. /* Gobble initial spaces */
  4441. while (isspace(*(unsigned char *)s)) {
  4442. s++;
  4443. }
  4444. name = skip_quoted(&s, "=", " ", 0);
  4445. /* Value is either quote-delimited, or ends at first comma or space. */
  4446. if (s[0] == '\"') {
  4447. s++;
  4448. value = skip_quoted(&s, "\"", " ", '\\');
  4449. if (s[0] == ',') {
  4450. s++;
  4451. }
  4452. } else {
  4453. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4454. * spaces */
  4455. }
  4456. if (*name == '\0') {
  4457. break;
  4458. }
  4459. if (!strcmp(name, "username")) {
  4460. ah->user = value;
  4461. } else if (!strcmp(name, "cnonce")) {
  4462. ah->cnonce = value;
  4463. } else if (!strcmp(name, "response")) {
  4464. ah->response = value;
  4465. } else if (!strcmp(name, "uri")) {
  4466. ah->uri = value;
  4467. } else if (!strcmp(name, "qop")) {
  4468. ah->qop = value;
  4469. } else if (!strcmp(name, "nc")) {
  4470. ah->nc = value;
  4471. } else if (!strcmp(name, "nonce")) {
  4472. ah->nonce = value;
  4473. }
  4474. }
  4475. #ifndef NO_NONCE_CHECK
  4476. /* Read the nonce from the response. */
  4477. if (ah->nonce == NULL) {
  4478. return 0;
  4479. }
  4480. s = NULL;
  4481. nonce = strtoull(ah->nonce, &s, 10);
  4482. if ((s == NULL) || (*s != 0)) {
  4483. return 0;
  4484. }
  4485. /* Convert the nonce from the client to a number. */
  4486. nonce ^= conn->ctx->auth_nonce_mask;
  4487. /* The converted number corresponds to the time the nounce has been
  4488. * created. This should not be earlier than the server start. */
  4489. /* Server side nonce check is valuable in all situations but one:
  4490. * if the server restarts frequently, but the client should not see
  4491. * that, so the server should accept nonces from previous starts. */
  4492. /* However, the reasonable default is to not accept a nonce from a
  4493. * previous start, so if anyone changed the access rights between
  4494. * two restarts, a new login is required. */
  4495. if (nonce < (uint64_t)conn->ctx->start_time) {
  4496. /* nonce is from a previous start of the server and no longer valid
  4497. * (replay attack?) */
  4498. return 0;
  4499. }
  4500. /* Check if the nonce is too high, so it has not (yet) been used by the
  4501. * server. */
  4502. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4503. return 0;
  4504. }
  4505. #endif
  4506. /* CGI needs it as REMOTE_USER */
  4507. if (ah->user != NULL) {
  4508. conn->request_info.remote_user = mg_strdup(ah->user);
  4509. } else {
  4510. return 0;
  4511. }
  4512. return 1;
  4513. }
  4514. static char *
  4515. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4516. {
  4517. char *eof;
  4518. size_t len;
  4519. char *memend;
  4520. if (!filep) {
  4521. return NULL;
  4522. }
  4523. if (filep->membuf != NULL && *p != NULL) {
  4524. memend = (char *)&filep->membuf[filep->size];
  4525. /* Search for \n from p till the end of stream */
  4526. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4527. if (eof != NULL) {
  4528. eof += 1; /* Include \n */
  4529. } else {
  4530. eof = memend; /* Copy remaining data */
  4531. }
  4532. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4533. memcpy(buf, *p, len);
  4534. buf[len] = '\0';
  4535. *p += len;
  4536. return len ? eof : NULL;
  4537. } else if (filep->fp != NULL) {
  4538. return fgets(buf, (int)size, filep->fp);
  4539. } else {
  4540. return NULL;
  4541. }
  4542. }
  4543. struct read_auth_file_struct {
  4544. struct mg_connection *conn;
  4545. struct ah ah;
  4546. char *domain;
  4547. char buf[256 + 256 + 40];
  4548. char *f_user;
  4549. char *f_domain;
  4550. char *f_ha1;
  4551. };
  4552. static int
  4553. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4554. {
  4555. char *p;
  4556. int is_authorized = 0;
  4557. struct file fp;
  4558. size_t l;
  4559. if (!filep || !workdata) {
  4560. return 0;
  4561. }
  4562. /* Loop over passwords file */
  4563. p = (char *)filep->membuf;
  4564. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4565. l = strlen(workdata->buf);
  4566. while (l > 0) {
  4567. if (isspace(workdata->buf[l - 1])
  4568. || iscntrl(workdata->buf[l - 1])) {
  4569. l--;
  4570. workdata->buf[l] = 0;
  4571. } else
  4572. break;
  4573. }
  4574. if (l < 1) {
  4575. continue;
  4576. }
  4577. workdata->f_user = workdata->buf;
  4578. if (workdata->f_user[0] == ':') {
  4579. /* user names may not contain a ':' and may not be empty,
  4580. * so lines starting with ':' may be used for a special purpose */
  4581. if (workdata->f_user[1] == '#') {
  4582. /* :# is a comment */
  4583. continue;
  4584. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4585. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4586. is_authorized = read_auth_file(&fp, workdata);
  4587. mg_fclose(&fp);
  4588. } else {
  4589. mg_cry(workdata->conn,
  4590. "%s: cannot open authorization file: %s",
  4591. __func__,
  4592. workdata->buf);
  4593. }
  4594. continue;
  4595. }
  4596. /* everything is invalid for the moment (might change in the
  4597. * future) */
  4598. mg_cry(workdata->conn,
  4599. "%s: syntax error in authorization file: %s",
  4600. __func__,
  4601. workdata->buf);
  4602. continue;
  4603. }
  4604. workdata->f_domain = strchr(workdata->f_user, ':');
  4605. if (workdata->f_domain == NULL) {
  4606. mg_cry(workdata->conn,
  4607. "%s: syntax error in authorization file: %s",
  4608. __func__,
  4609. workdata->buf);
  4610. continue;
  4611. }
  4612. *(workdata->f_domain) = 0;
  4613. (workdata->f_domain)++;
  4614. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4615. if (workdata->f_ha1 == NULL) {
  4616. mg_cry(workdata->conn,
  4617. "%s: syntax error in authorization file: %s",
  4618. __func__,
  4619. workdata->buf);
  4620. continue;
  4621. }
  4622. *(workdata->f_ha1) = 0;
  4623. (workdata->f_ha1)++;
  4624. if (!strcmp(workdata->ah.user, workdata->f_user)
  4625. && !strcmp(workdata->domain, workdata->f_domain)) {
  4626. return check_password(workdata->conn->request_info.request_method,
  4627. workdata->f_ha1,
  4628. workdata->ah.uri,
  4629. workdata->ah.nonce,
  4630. workdata->ah.nc,
  4631. workdata->ah.cnonce,
  4632. workdata->ah.qop,
  4633. workdata->ah.response);
  4634. }
  4635. }
  4636. return is_authorized;
  4637. }
  4638. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4639. static int
  4640. authorize(struct mg_connection *conn, struct file *filep)
  4641. {
  4642. struct read_auth_file_struct workdata;
  4643. char buf[MG_BUF_LEN];
  4644. if (!conn || !conn->ctx) {
  4645. return 0;
  4646. }
  4647. memset(&workdata, 0, sizeof(workdata));
  4648. workdata.conn = conn;
  4649. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4650. return 0;
  4651. }
  4652. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4653. return read_auth_file(filep, &workdata);
  4654. }
  4655. /* Return 1 if request is authorised, 0 otherwise. */
  4656. static int
  4657. check_authorization(struct mg_connection *conn, const char *path)
  4658. {
  4659. char fname[PATH_MAX];
  4660. struct vec uri_vec, filename_vec;
  4661. const char *list;
  4662. struct file file = STRUCT_FILE_INITIALIZER;
  4663. int authorized = 1, truncated;
  4664. if (!conn || !conn->ctx) {
  4665. return 0;
  4666. }
  4667. list = conn->ctx->config[PROTECT_URI];
  4668. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4669. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4670. mg_snprintf(conn,
  4671. &truncated,
  4672. fname,
  4673. sizeof(fname),
  4674. "%.*s",
  4675. (int)filename_vec.len,
  4676. filename_vec.ptr);
  4677. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4678. mg_cry(conn,
  4679. "%s: cannot open %s: %s",
  4680. __func__,
  4681. fname,
  4682. strerror(errno));
  4683. }
  4684. break;
  4685. }
  4686. }
  4687. if (!is_file_opened(&file)) {
  4688. open_auth_file(conn, path, &file);
  4689. }
  4690. if (is_file_opened(&file)) {
  4691. authorized = authorize(conn, &file);
  4692. mg_fclose(&file);
  4693. }
  4694. return authorized;
  4695. }
  4696. static void
  4697. send_authorization_request(struct mg_connection *conn)
  4698. {
  4699. char date[64];
  4700. time_t curtime = time(NULL);
  4701. if (conn && conn->ctx) {
  4702. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4703. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4704. nonce += conn->ctx->nonce_count;
  4705. ++conn->ctx->nonce_count;
  4706. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4707. nonce ^= conn->ctx->auth_nonce_mask;
  4708. conn->status_code = 401;
  4709. conn->must_close = 1;
  4710. gmt_time_string(date, sizeof(date), &curtime);
  4711. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4712. send_no_cache_header(conn);
  4713. mg_printf(conn,
  4714. "Date: %s\r\n"
  4715. "Connection: %s\r\n"
  4716. "Content-Length: 0\r\n"
  4717. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4718. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4719. date,
  4720. suggest_connection_header(conn),
  4721. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4722. nonce);
  4723. }
  4724. }
  4725. #if !defined(NO_FILES)
  4726. static int
  4727. is_authorized_for_put(struct mg_connection *conn)
  4728. {
  4729. if (conn) {
  4730. struct file file = STRUCT_FILE_INITIALIZER;
  4731. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4732. int ret = 0;
  4733. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4734. ret = authorize(conn, &file);
  4735. mg_fclose(&file);
  4736. }
  4737. return ret;
  4738. }
  4739. return 0;
  4740. }
  4741. #endif
  4742. int
  4743. mg_modify_passwords_file(const char *fname,
  4744. const char *domain,
  4745. const char *user,
  4746. const char *pass)
  4747. {
  4748. int found, i;
  4749. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4750. FILE *fp, *fp2;
  4751. found = 0;
  4752. fp = fp2 = NULL;
  4753. /* Regard empty password as no password - remove user record. */
  4754. if (pass != NULL && pass[0] == '\0') {
  4755. pass = NULL;
  4756. }
  4757. /* Other arguments must not be empty */
  4758. if (fname == NULL || domain == NULL || user == NULL) {
  4759. return 0;
  4760. }
  4761. /* Using the given file format, user name and domain must not contain ':'
  4762. */
  4763. if (strchr(user, ':') != NULL) {
  4764. return 0;
  4765. }
  4766. if (strchr(domain, ':') != NULL) {
  4767. return 0;
  4768. }
  4769. /* Do not allow control characters like newline in user name and domain.
  4770. * Do not allow excessively long names either. */
  4771. for (i = 0; i < 255 && user[i] != 0; i++) {
  4772. if (iscntrl(user[i])) {
  4773. return 0;
  4774. }
  4775. }
  4776. if (user[i]) {
  4777. return 0;
  4778. }
  4779. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4780. if (iscntrl(domain[i])) {
  4781. return 0;
  4782. }
  4783. }
  4784. if (domain[i]) {
  4785. return 0;
  4786. }
  4787. /* The maximum length of the path to the password file is limited */
  4788. if ((strlen(fname) + 4) >= PATH_MAX) {
  4789. return 0;
  4790. }
  4791. /* Create a temporary file name. Length has been checked before. */
  4792. strcpy(tmp, fname);
  4793. strcat(tmp, ".tmp");
  4794. /* Create the file if does not exist */
  4795. /* Use of fopen here is OK, since fname is only ASCII */
  4796. if ((fp = fopen(fname, "a+")) != NULL) {
  4797. (void)fclose(fp);
  4798. }
  4799. /* Open the given file and temporary file */
  4800. if ((fp = fopen(fname, "r")) == NULL) {
  4801. return 0;
  4802. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4803. fclose(fp);
  4804. return 0;
  4805. }
  4806. /* Copy the stuff to temporary file */
  4807. while (fgets(line, sizeof(line), fp) != NULL) {
  4808. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4809. continue;
  4810. }
  4811. u[255] = 0;
  4812. d[255] = 0;
  4813. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4814. found++;
  4815. if (pass != NULL) {
  4816. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4817. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4818. }
  4819. } else {
  4820. fprintf(fp2, "%s", line);
  4821. }
  4822. }
  4823. /* If new user, just add it */
  4824. if (!found && pass != NULL) {
  4825. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4826. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4827. }
  4828. /* Close files */
  4829. fclose(fp);
  4830. fclose(fp2);
  4831. /* Put the temp file in place of real file */
  4832. IGNORE_UNUSED_RESULT(remove(fname));
  4833. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4834. return 1;
  4835. }
  4836. static int
  4837. is_valid_port(unsigned long port)
  4838. {
  4839. return port < 0xffff;
  4840. }
  4841. static int
  4842. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4843. {
  4844. struct addrinfo hints, *res, *ressave;
  4845. int ret = 0;
  4846. memset(&hints, 0, sizeof(struct addrinfo));
  4847. hints.ai_family = af;
  4848. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4849. /* bad src string or bad address family */
  4850. return 0;
  4851. }
  4852. ressave = res;
  4853. while (res) {
  4854. if (dstlen >= res->ai_addrlen) {
  4855. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4856. ret = 1;
  4857. }
  4858. res = res->ai_next;
  4859. }
  4860. freeaddrinfo(ressave);
  4861. return ret;
  4862. }
  4863. static int
  4864. connect_socket(struct mg_context *ctx /* may be NULL */,
  4865. const char *host,
  4866. int port,
  4867. int use_ssl,
  4868. char *ebuf,
  4869. size_t ebuf_len,
  4870. SOCKET *sock /* output: socket, must not be NULL */,
  4871. union usa *sa /* output: socket address, must not be NULL */
  4872. )
  4873. {
  4874. int ip_ver = 0;
  4875. *sock = INVALID_SOCKET;
  4876. memset(sa, 0, sizeof(*sa));
  4877. if (ebuf_len > 0) {
  4878. *ebuf = 0;
  4879. }
  4880. if (host == NULL) {
  4881. mg_snprintf(NULL,
  4882. NULL, /* No truncation check for ebuf */
  4883. ebuf,
  4884. ebuf_len,
  4885. "%s",
  4886. "NULL host");
  4887. return 0;
  4888. }
  4889. if (port < 0 || !is_valid_port((unsigned)port)) {
  4890. mg_snprintf(NULL,
  4891. NULL, /* No truncation check for ebuf */
  4892. ebuf,
  4893. ebuf_len,
  4894. "%s",
  4895. "invalid port");
  4896. return 0;
  4897. }
  4898. if (use_ssl && (SSLv23_client_method == NULL)) {
  4899. mg_snprintf(NULL,
  4900. NULL, /* No truncation check for ebuf */
  4901. ebuf,
  4902. ebuf_len,
  4903. "%s",
  4904. "SSL is not initialized");
  4905. return 0;
  4906. }
  4907. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4908. sa->sin.sin_port = htons((uint16_t)port);
  4909. ip_ver = 4;
  4910. #ifdef USE_IPV6
  4911. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4912. sa->sin6.sin6_port = htons((uint16_t)port);
  4913. ip_ver = 6;
  4914. } else if (host[0] == '[') {
  4915. /* While getaddrinfo on Windows will work with [::1],
  4916. * getaddrinfo on Linux only works with ::1 (without []). */
  4917. size_t l = strlen(host + 1);
  4918. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4919. if (h) {
  4920. h[l - 1] = 0;
  4921. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4922. sa->sin6.sin6_port = htons((uint16_t)port);
  4923. ip_ver = 6;
  4924. }
  4925. mg_free(h);
  4926. }
  4927. #endif
  4928. }
  4929. if (ip_ver == 0) {
  4930. mg_snprintf(NULL,
  4931. NULL, /* No truncation check for ebuf */
  4932. ebuf,
  4933. ebuf_len,
  4934. "%s",
  4935. "host not found");
  4936. return 0;
  4937. }
  4938. if (ip_ver == 4) {
  4939. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4940. }
  4941. #ifdef USE_IPV6
  4942. else if (ip_ver == 6) {
  4943. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4944. }
  4945. #endif
  4946. if (*sock == INVALID_SOCKET) {
  4947. mg_snprintf(NULL,
  4948. NULL, /* No truncation check for ebuf */
  4949. ebuf,
  4950. ebuf_len,
  4951. "socket(): %s",
  4952. strerror(ERRNO));
  4953. return 0;
  4954. }
  4955. set_close_on_exec(*sock, fc(ctx));
  4956. if ((ip_ver == 4)
  4957. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  4958. == 0)) {
  4959. /* connected with IPv4 */
  4960. return 1;
  4961. }
  4962. #ifdef USE_IPV6
  4963. if ((ip_ver == 6)
  4964. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  4965. == 0)) {
  4966. /* connected with IPv6 */
  4967. return 1;
  4968. }
  4969. #endif
  4970. /* Not connected */
  4971. mg_snprintf(NULL,
  4972. NULL, /* No truncation check for ebuf */
  4973. ebuf,
  4974. ebuf_len,
  4975. "connect(%s:%d): %s",
  4976. host,
  4977. port,
  4978. strerror(ERRNO));
  4979. closesocket(*sock);
  4980. *sock = INVALID_SOCKET;
  4981. return 0;
  4982. }
  4983. int
  4984. mg_url_encode(const char *src, char *dst, size_t dst_len)
  4985. {
  4986. static const char *dont_escape = "._-$,;~()";
  4987. static const char *hex = "0123456789abcdef";
  4988. char *pos = dst;
  4989. const char *end = dst + dst_len - 1;
  4990. for (; *src != '\0' && pos < end; src++, pos++) {
  4991. if (isalnum(*(const unsigned char *)src)
  4992. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4993. *pos = *src;
  4994. } else if (pos + 2 < end) {
  4995. pos[0] = '%';
  4996. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4997. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4998. pos += 2;
  4999. } else {
  5000. break;
  5001. }
  5002. }
  5003. *pos = '\0';
  5004. return (*src == '\0') ? (int)(pos - dst) : -1;
  5005. }
  5006. static void
  5007. print_dir_entry(struct de *de)
  5008. {
  5009. char size[64], mod[64], href[PATH_MAX];
  5010. struct tm *tm;
  5011. if (de->file.is_directory) {
  5012. mg_snprintf(de->conn,
  5013. NULL, /* Buffer is big enough */
  5014. size,
  5015. sizeof(size),
  5016. "%s",
  5017. "[DIRECTORY]");
  5018. } else {
  5019. /* We use (signed) cast below because MSVC 6 compiler cannot
  5020. * convert unsigned __int64 to double. Sigh. */
  5021. if (de->file.size < 1024) {
  5022. mg_snprintf(de->conn,
  5023. NULL, /* Buffer is big enough */
  5024. size,
  5025. sizeof(size),
  5026. "%d",
  5027. (int)de->file.size);
  5028. } else if (de->file.size < 0x100000) {
  5029. mg_snprintf(de->conn,
  5030. NULL, /* Buffer is big enough */
  5031. size,
  5032. sizeof(size),
  5033. "%.1fk",
  5034. (double)de->file.size / 1024.0);
  5035. } else if (de->file.size < 0x40000000) {
  5036. mg_snprintf(de->conn,
  5037. NULL, /* Buffer is big enough */
  5038. size,
  5039. sizeof(size),
  5040. "%.1fM",
  5041. (double)de->file.size / 1048576);
  5042. } else {
  5043. mg_snprintf(de->conn,
  5044. NULL, /* Buffer is big enough */
  5045. size,
  5046. sizeof(size),
  5047. "%.1fG",
  5048. (double)de->file.size / 1073741824);
  5049. }
  5050. }
  5051. /* Note: mg_snprintf will not cause a buffer overflow above.
  5052. * So, string truncation checks are not required here. */
  5053. tm = localtime(&de->file.last_modified);
  5054. if (tm != NULL) {
  5055. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5056. } else {
  5057. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5058. mod[sizeof(mod) - 1] = '\0';
  5059. }
  5060. mg_url_encode(de->file_name, href, sizeof(href));
  5061. de->conn->num_bytes_sent +=
  5062. mg_printf(de->conn,
  5063. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5064. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5065. de->conn->request_info.local_uri,
  5066. href,
  5067. de->file.is_directory ? "/" : "",
  5068. de->file_name,
  5069. de->file.is_directory ? "/" : "",
  5070. mod,
  5071. size);
  5072. }
  5073. /* This function is called from send_directory() and used for
  5074. * sorting directory entries by size, or name, or modification time.
  5075. * On windows, __cdecl specification is needed in case if project is built
  5076. * with __stdcall convention. qsort always requires __cdels callback. */
  5077. static int WINCDECL
  5078. compare_dir_entries(const void *p1, const void *p2)
  5079. {
  5080. if (p1 && p2) {
  5081. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5082. const char *query_string = a->conn->request_info.query_string;
  5083. int cmp_result = 0;
  5084. if (query_string == NULL) {
  5085. query_string = "na";
  5086. }
  5087. if (a->file.is_directory && !b->file.is_directory) {
  5088. return -1; /* Always put directories on top */
  5089. } else if (!a->file.is_directory && b->file.is_directory) {
  5090. return 1; /* Always put directories on top */
  5091. } else if (*query_string == 'n') {
  5092. cmp_result = strcmp(a->file_name, b->file_name);
  5093. } else if (*query_string == 's') {
  5094. cmp_result = a->file.size == b->file.size
  5095. ? 0
  5096. : a->file.size > b->file.size ? 1 : -1;
  5097. } else if (*query_string == 'd') {
  5098. cmp_result =
  5099. (a->file.last_modified == b->file.last_modified)
  5100. ? 0
  5101. : ((a->file.last_modified > b->file.last_modified) ? 1
  5102. : -1);
  5103. }
  5104. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5105. }
  5106. return 0;
  5107. }
  5108. static int
  5109. must_hide_file(struct mg_connection *conn, const char *path)
  5110. {
  5111. if (conn && conn->ctx) {
  5112. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5113. const char *pattern = conn->ctx->config[HIDE_FILES];
  5114. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5115. || (pattern != NULL
  5116. && match_prefix(pattern, strlen(pattern), path) > 0);
  5117. }
  5118. return 0;
  5119. }
  5120. static int
  5121. scan_directory(struct mg_connection *conn,
  5122. const char *dir,
  5123. void *data,
  5124. void (*cb)(struct de *, void *))
  5125. {
  5126. char path[PATH_MAX];
  5127. struct dirent *dp;
  5128. DIR *dirp;
  5129. struct de de;
  5130. int truncated;
  5131. if ((dirp = opendir(dir)) == NULL) {
  5132. return 0;
  5133. } else {
  5134. de.conn = conn;
  5135. while ((dp = readdir(dirp)) != NULL) {
  5136. /* Do not show current dir and hidden files */
  5137. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5138. || must_hide_file(conn, dp->d_name)) {
  5139. continue;
  5140. }
  5141. mg_snprintf(
  5142. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5143. /* If we don't memset stat structure to zero, mtime will have
  5144. * garbage and strftime() will segfault later on in
  5145. * print_dir_entry(). memset is required only if mg_stat()
  5146. * fails. For more details, see
  5147. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5148. memset(&de.file, 0, sizeof(de.file));
  5149. if (truncated) {
  5150. /* If the path is not complete, skip processing. */
  5151. continue;
  5152. }
  5153. if (!mg_stat(conn, path, &de.file)) {
  5154. mg_cry(conn,
  5155. "%s: mg_stat(%s) failed: %s",
  5156. __func__,
  5157. path,
  5158. strerror(ERRNO));
  5159. }
  5160. de.file_name = dp->d_name;
  5161. cb(&de, data);
  5162. }
  5163. (void)closedir(dirp);
  5164. }
  5165. return 1;
  5166. }
  5167. #if !defined(NO_FILES)
  5168. static int
  5169. remove_directory(struct mg_connection *conn, const char *dir)
  5170. {
  5171. char path[PATH_MAX];
  5172. struct dirent *dp;
  5173. DIR *dirp;
  5174. struct de de;
  5175. int truncated;
  5176. int ok = 1;
  5177. if ((dirp = opendir(dir)) == NULL) {
  5178. return 0;
  5179. } else {
  5180. de.conn = conn;
  5181. while ((dp = readdir(dirp)) != NULL) {
  5182. /* Do not show current dir (but show hidden files as they will
  5183. * also be removed) */
  5184. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5185. continue;
  5186. }
  5187. mg_snprintf(
  5188. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5189. /* If we don't memset stat structure to zero, mtime will have
  5190. * garbage and strftime() will segfault later on in
  5191. * print_dir_entry(). memset is required only if mg_stat()
  5192. * fails. For more details, see
  5193. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5194. memset(&de.file, 0, sizeof(de.file));
  5195. if (truncated) {
  5196. /* Do not delete anything shorter */
  5197. ok = 0;
  5198. continue;
  5199. }
  5200. if (!mg_stat(conn, path, &de.file)) {
  5201. mg_cry(conn,
  5202. "%s: mg_stat(%s) failed: %s",
  5203. __func__,
  5204. path,
  5205. strerror(ERRNO));
  5206. ok = 0;
  5207. }
  5208. if (de.file.membuf == NULL) {
  5209. /* file is not in memory */
  5210. if (de.file.is_directory) {
  5211. if (remove_directory(conn, path) == 0) {
  5212. ok = 0;
  5213. }
  5214. } else {
  5215. if (mg_remove(path) == 0) {
  5216. ok = 0;
  5217. }
  5218. }
  5219. } else {
  5220. /* file is in memory. It can not be deleted. */
  5221. ok = 0;
  5222. }
  5223. }
  5224. (void)closedir(dirp);
  5225. IGNORE_UNUSED_RESULT(rmdir(dir));
  5226. }
  5227. return ok;
  5228. }
  5229. #endif
  5230. struct dir_scan_data {
  5231. struct de *entries;
  5232. unsigned int num_entries;
  5233. unsigned int arr_size;
  5234. };
  5235. /* Behaves like realloc(), but frees original pointer on failure */
  5236. static void *
  5237. realloc2(void *ptr, size_t size)
  5238. {
  5239. void *new_ptr = mg_realloc(ptr, size);
  5240. if (new_ptr == NULL) {
  5241. mg_free(ptr);
  5242. }
  5243. return new_ptr;
  5244. }
  5245. static void
  5246. dir_scan_callback(struct de *de, void *data)
  5247. {
  5248. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5249. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5250. dsd->arr_size *= 2;
  5251. dsd->entries =
  5252. (struct de *)realloc2(dsd->entries,
  5253. dsd->arr_size * sizeof(dsd->entries[0]));
  5254. }
  5255. if (dsd->entries == NULL) {
  5256. /* TODO(lsm, low): propagate an error to the caller */
  5257. dsd->num_entries = 0;
  5258. } else {
  5259. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5260. dsd->entries[dsd->num_entries].file = de->file;
  5261. dsd->entries[dsd->num_entries].conn = de->conn;
  5262. dsd->num_entries++;
  5263. }
  5264. }
  5265. static void
  5266. handle_directory_request(struct mg_connection *conn, const char *dir)
  5267. {
  5268. unsigned int i;
  5269. int sort_direction;
  5270. struct dir_scan_data data = {NULL, 0, 128};
  5271. char date[64];
  5272. time_t curtime = time(NULL);
  5273. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5274. send_http_error(conn,
  5275. 500,
  5276. "Error: Cannot open directory\nopendir(%s): %s",
  5277. dir,
  5278. strerror(ERRNO));
  5279. return;
  5280. }
  5281. gmt_time_string(date, sizeof(date), &curtime);
  5282. if (!conn) {
  5283. return;
  5284. }
  5285. sort_direction = conn->request_info.query_string != NULL
  5286. && conn->request_info.query_string[1] == 'd'
  5287. ? 'a'
  5288. : 'd';
  5289. conn->must_close = 1;
  5290. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5291. send_static_cache_header(conn);
  5292. mg_printf(conn,
  5293. "Date: %s\r\n"
  5294. "Connection: close\r\n"
  5295. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5296. date);
  5297. conn->num_bytes_sent +=
  5298. mg_printf(conn,
  5299. "<html><head><title>Index of %s</title>"
  5300. "<style>th {text-align: left;}</style></head>"
  5301. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5302. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5303. "<th><a href=\"?d%c\">Modified</a></th>"
  5304. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5305. "<tr><td colspan=\"3\"><hr></td></tr>",
  5306. conn->request_info.local_uri,
  5307. conn->request_info.local_uri,
  5308. sort_direction,
  5309. sort_direction,
  5310. sort_direction);
  5311. /* Print first entry - link to a parent directory */
  5312. conn->num_bytes_sent +=
  5313. mg_printf(conn,
  5314. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5315. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5316. conn->request_info.local_uri,
  5317. "..",
  5318. "Parent directory",
  5319. "-",
  5320. "-");
  5321. /* Sort and print directory entries */
  5322. if (data.entries != NULL) {
  5323. qsort(data.entries,
  5324. (size_t)data.num_entries,
  5325. sizeof(data.entries[0]),
  5326. compare_dir_entries);
  5327. for (i = 0; i < data.num_entries; i++) {
  5328. print_dir_entry(&data.entries[i]);
  5329. mg_free(data.entries[i].file_name);
  5330. }
  5331. mg_free(data.entries);
  5332. }
  5333. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5334. conn->status_code = 200;
  5335. }
  5336. /* Send len bytes from the opened file to the client. */
  5337. static void
  5338. send_file_data(struct mg_connection *conn,
  5339. struct file *filep,
  5340. int64_t offset,
  5341. int64_t len)
  5342. {
  5343. char buf[MG_BUF_LEN];
  5344. int to_read, num_read, num_written;
  5345. int64_t size;
  5346. if (!filep || !conn) {
  5347. return;
  5348. }
  5349. /* Sanity check the offset */
  5350. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5351. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5352. if (len > 0 && filep->membuf != NULL && size > 0) {
  5353. /* file stored in memory */
  5354. if (len > size - offset) {
  5355. len = size - offset;
  5356. }
  5357. mg_write(conn, filep->membuf + offset, (size_t)len);
  5358. } else if (len > 0 && filep->fp != NULL) {
  5359. /* file stored on disk */
  5360. #if defined(__linux__)
  5361. /* sendfile is only available for Linux */
  5362. if (conn->throttle == 0 && conn->ssl == 0) {
  5363. off_t sf_offs = (off_t)offset;
  5364. ssize_t sf_sent;
  5365. int sf_file = fileno(filep->fp);
  5366. int loop_cnt = 0;
  5367. do {
  5368. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5369. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5370. size_t sf_tosend =
  5371. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5372. sf_sent =
  5373. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5374. if (sf_sent > 0) {
  5375. conn->num_bytes_sent += sf_sent;
  5376. len -= sf_sent;
  5377. offset += sf_sent;
  5378. } else if (loop_cnt == 0) {
  5379. /* This file can not be sent using sendfile.
  5380. * This might be the case for pseudo-files in the
  5381. * /sys/ and /proc/ file system.
  5382. * Use the regular user mode copy code instead. */
  5383. break;
  5384. } else if (sf_sent == 0) {
  5385. /* No error, but 0 bytes sent. May be EOF? */
  5386. return;
  5387. }
  5388. loop_cnt++;
  5389. } while ((len > 0) && (sf_sent >= 0));
  5390. if (sf_sent > 0) {
  5391. return; /* OK */
  5392. }
  5393. /* sf_sent<0 means error, thus fall back to the classic way */
  5394. /* This is always the case, if sf_file is not a "normal" file,
  5395. * e.g., for sending data from the output of a CGI process. */
  5396. offset = (int64_t)sf_offs;
  5397. }
  5398. #endif
  5399. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5400. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5401. send_http_error(
  5402. conn,
  5403. 500,
  5404. "%s",
  5405. "Error: Unable to access file at requested position.");
  5406. } else {
  5407. while (len > 0) {
  5408. /* Calculate how much to read from the file in the buffer */
  5409. to_read = sizeof(buf);
  5410. if ((int64_t)to_read > len) {
  5411. to_read = (int)len;
  5412. }
  5413. /* Read from file, exit the loop on error */
  5414. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5415. <= 0) {
  5416. break;
  5417. }
  5418. /* Send read bytes to the client, exit the loop on error */
  5419. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5420. != num_read) {
  5421. break;
  5422. }
  5423. /* Both read and were successful, adjust counters */
  5424. conn->num_bytes_sent += num_written;
  5425. len -= num_written;
  5426. }
  5427. }
  5428. }
  5429. }
  5430. static int
  5431. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5432. {
  5433. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5434. }
  5435. static void
  5436. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5437. {
  5438. if (filep != NULL && buf != NULL) {
  5439. mg_snprintf(NULL,
  5440. NULL, /* All calls to construct_etag use 64 byte buffer */
  5441. buf,
  5442. buf_len,
  5443. "\"%lx.%" INT64_FMT "\"",
  5444. (unsigned long)filep->last_modified,
  5445. filep->size);
  5446. }
  5447. }
  5448. static void
  5449. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5450. {
  5451. if (filep != NULL && filep->fp != NULL) {
  5452. #ifdef _WIN32
  5453. (void)conn; /* Unused. */
  5454. #else
  5455. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5456. mg_cry(conn,
  5457. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5458. __func__,
  5459. strerror(ERRNO));
  5460. }
  5461. #endif
  5462. }
  5463. }
  5464. static void
  5465. handle_static_file_request(struct mg_connection *conn,
  5466. const char *path,
  5467. struct file *filep,
  5468. const char *mime_type)
  5469. {
  5470. char date[64], lm[64], etag[64];
  5471. char range[128]; /* large enough, so there will be no overflow */
  5472. const char *msg = "OK", *hdr;
  5473. time_t curtime = time(NULL);
  5474. int64_t cl, r1, r2;
  5475. struct vec mime_vec;
  5476. int n, truncated;
  5477. char gz_path[PATH_MAX];
  5478. const char *encoding = "";
  5479. const char *cors1, *cors2, *cors3;
  5480. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5481. return;
  5482. }
  5483. if (mime_type == NULL) {
  5484. get_mime_type(conn->ctx, path, &mime_vec);
  5485. } else {
  5486. mime_vec.ptr = mime_type;
  5487. mime_vec.len = strlen(mime_type);
  5488. }
  5489. if (filep->size > INT64_MAX) {
  5490. send_http_error(conn,
  5491. 500,
  5492. "Error: File size is too large to send\n%" INT64_FMT,
  5493. filep->size);
  5494. }
  5495. cl = (int64_t)filep->size;
  5496. conn->status_code = 200;
  5497. range[0] = '\0';
  5498. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5499. * it's important to rewrite the filename after resolving
  5500. * the mime type from it, to preserve the actual file's type */
  5501. if (filep->gzipped) {
  5502. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5503. if (truncated) {
  5504. send_http_error(conn,
  5505. 500,
  5506. "Error: Path of zipped file too long (%s)",
  5507. path);
  5508. return;
  5509. }
  5510. path = gz_path;
  5511. encoding = "Content-Encoding: gzip\r\n";
  5512. }
  5513. if (!mg_fopen(conn, path, "rb", filep)) {
  5514. send_http_error(conn,
  5515. 500,
  5516. "Error: Cannot open file\nfopen(%s): %s",
  5517. path,
  5518. strerror(ERRNO));
  5519. return;
  5520. }
  5521. fclose_on_exec(filep, conn);
  5522. /* If Range: header specified, act accordingly */
  5523. r1 = r2 = 0;
  5524. hdr = mg_get_header(conn, "Range");
  5525. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5526. && r2 >= 0) {
  5527. /* actually, range requests don't play well with a pre-gzipped
  5528. * file (since the range is specified in the uncompressed space) */
  5529. if (filep->gzipped) {
  5530. send_http_error(
  5531. conn,
  5532. 501,
  5533. "%s",
  5534. "Error: Range requests in gzipped files are not supported");
  5535. mg_fclose(filep);
  5536. return;
  5537. }
  5538. conn->status_code = 206;
  5539. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5540. mg_snprintf(conn,
  5541. NULL, /* range buffer is big enough */
  5542. range,
  5543. sizeof(range),
  5544. "Content-Range: bytes "
  5545. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5546. r1,
  5547. r1 + cl - 1,
  5548. filep->size);
  5549. msg = "Partial Content";
  5550. }
  5551. hdr = mg_get_header(conn, "Origin");
  5552. if (hdr) {
  5553. /* Cross-origin resource sharing (CORS), see
  5554. * http://www.html5rocks.com/en/tutorials/cors/,
  5555. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5556. * preflight is not supported for files. */
  5557. cors1 = "Access-Control-Allow-Origin: ";
  5558. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5559. cors3 = "\r\n";
  5560. } else {
  5561. cors1 = cors2 = cors3 = "";
  5562. }
  5563. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5564. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5565. gmt_time_string(date, sizeof(date), &curtime);
  5566. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5567. construct_etag(etag, sizeof(etag), filep);
  5568. (void)mg_printf(conn,
  5569. "HTTP/1.1 %d %s\r\n"
  5570. "%s%s%s"
  5571. "Date: %s\r\n",
  5572. conn->status_code,
  5573. msg,
  5574. cors1,
  5575. cors2,
  5576. cors3,
  5577. date);
  5578. send_static_cache_header(conn);
  5579. (void)mg_printf(conn,
  5580. "Last-Modified: %s\r\n"
  5581. "Etag: %s\r\n"
  5582. "Content-Type: %.*s\r\n"
  5583. "Content-Length: %" INT64_FMT "\r\n"
  5584. "Connection: %s\r\n"
  5585. "Accept-Ranges: bytes\r\n"
  5586. "%s%s\r\n",
  5587. lm,
  5588. etag,
  5589. (int)mime_vec.len,
  5590. mime_vec.ptr,
  5591. cl,
  5592. suggest_connection_header(conn),
  5593. range,
  5594. encoding);
  5595. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5596. send_file_data(conn, filep, r1, cl);
  5597. }
  5598. mg_fclose(filep);
  5599. }
  5600. void
  5601. mg_send_file(struct mg_connection *conn, const char *path)
  5602. {
  5603. mg_send_mime_file(conn, path, NULL);
  5604. }
  5605. void
  5606. mg_send_mime_file(struct mg_connection *conn,
  5607. const char *path,
  5608. const char *mime_type)
  5609. {
  5610. struct file file = STRUCT_FILE_INITIALIZER;
  5611. if (mg_stat(conn, path, &file)) {
  5612. if (file.is_directory) {
  5613. if (!conn) {
  5614. return;
  5615. }
  5616. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5617. "yes")) {
  5618. handle_directory_request(conn, path);
  5619. } else {
  5620. send_http_error(conn,
  5621. 403,
  5622. "%s",
  5623. "Error: Directory listing denied");
  5624. }
  5625. } else {
  5626. handle_static_file_request(conn, path, &file, mime_type);
  5627. }
  5628. } else {
  5629. send_http_error(conn, 404, "%s", "Error: File not found");
  5630. }
  5631. }
  5632. /* For a given PUT path, create all intermediate subdirectories.
  5633. * Return 0 if the path itself is a directory.
  5634. * Return 1 if the path leads to a file.
  5635. * Return -1 for if the path is too long.
  5636. * Return -2 if path can not be created.
  5637. */
  5638. static int
  5639. put_dir(struct mg_connection *conn, const char *path)
  5640. {
  5641. char buf[PATH_MAX];
  5642. const char *s, *p;
  5643. struct file file = STRUCT_FILE_INITIALIZER;
  5644. size_t len;
  5645. int res = 1;
  5646. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5647. len = (size_t)(p - path);
  5648. if (len >= sizeof(buf)) {
  5649. /* path too long */
  5650. res = -1;
  5651. break;
  5652. }
  5653. memcpy(buf, path, len);
  5654. buf[len] = '\0';
  5655. /* Try to create intermediate directory */
  5656. DEBUG_TRACE("mkdir(%s)", buf);
  5657. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5658. /* path does not exixt and can not be created */
  5659. res = -2;
  5660. break;
  5661. }
  5662. /* Is path itself a directory? */
  5663. if (p[1] == '\0') {
  5664. res = 0;
  5665. }
  5666. }
  5667. return res;
  5668. }
  5669. static void
  5670. remove_bad_file(const struct mg_connection *conn, const char *path)
  5671. {
  5672. int r = mg_remove(path);
  5673. if (r != 0) {
  5674. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  5675. }
  5676. }
  5677. long long
  5678. mg_store_body(struct mg_connection *conn, const char *path)
  5679. {
  5680. char buf[MG_BUF_LEN];
  5681. long long len = 0;
  5682. int ret, n;
  5683. struct file fi;
  5684. if (conn->consumed_content != 0) {
  5685. mg_cry(conn, "%s: Contents already consumed", __func__);
  5686. return -11;
  5687. }
  5688. ret = put_dir(conn, path);
  5689. if (ret < 0) {
  5690. /* -1 for path too long,
  5691. * -2 for path can not be created. */
  5692. return ret;
  5693. }
  5694. if (ret != 1) {
  5695. /* Return 0 means, path itself is a directory. */
  5696. return 0;
  5697. }
  5698. if (mg_fopen(conn, path, "w", &fi) == 0) {
  5699. return -12;
  5700. }
  5701. ret = mg_read(conn, buf, sizeof(buf));
  5702. while (ret > 0) {
  5703. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  5704. if (n != ret) {
  5705. fclose(fi.fp);
  5706. remove_bad_file(conn, path);
  5707. return -13;
  5708. }
  5709. ret = mg_read(conn, buf, sizeof(buf));
  5710. }
  5711. /* TODO: mg_fclose should return an error,
  5712. * and every caller should check and handle it. */
  5713. if (fclose(fi.fp) != 0) {
  5714. remove_bad_file(conn, path);
  5715. return -14;
  5716. }
  5717. return len;
  5718. }
  5719. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5720. * where parsing stopped. */
  5721. static void
  5722. parse_http_headers(char **buf, struct mg_request_info *ri)
  5723. {
  5724. int i;
  5725. if (!ri) {
  5726. return;
  5727. }
  5728. ri->num_headers = 0;
  5729. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5730. char *dp = *buf;
  5731. while ((*dp != ':') && (*dp != '\r') && (*dp != 0)) {
  5732. dp++;
  5733. }
  5734. if (!*dp) {
  5735. /* neither : nor \r\n. This is not a valid field. */
  5736. break;
  5737. }
  5738. if (*dp == '\r') {
  5739. if (dp[1] == '\n') {
  5740. /* \r\n */
  5741. ri->http_headers[i].name = *buf;
  5742. ri->http_headers[i].value = 0;
  5743. *buf = dp;
  5744. } else {
  5745. /* stray \r. This is not valid. */
  5746. break;
  5747. }
  5748. } else {
  5749. /* (*dp == ':') */
  5750. *dp = 0;
  5751. ri->http_headers[i].name = *buf;
  5752. do {
  5753. dp++;
  5754. } while (*dp == ' ');
  5755. ri->http_headers[i].value = dp;
  5756. *buf = strstr(dp, "\r\n");
  5757. }
  5758. ri->num_headers = i + 1;
  5759. if (*buf) {
  5760. (*buf)[0] = 0;
  5761. (*buf)[1] = 0;
  5762. *buf += 2;
  5763. } else {
  5764. *buf = dp;
  5765. break;
  5766. }
  5767. if (*buf[0] == '\r') {
  5768. /* This is the end of the header */
  5769. break;
  5770. }
  5771. }
  5772. }
  5773. static int
  5774. is_valid_http_method(const char *method)
  5775. {
  5776. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5777. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5778. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5779. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5780. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5781. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5782. /* TRACE method (RFC 2616) is not supported for security reasons */
  5783. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5784. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5785. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5786. /* Unsupported WEBDAV Methods: */
  5787. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5788. /* + 11 methods from RFC 3253 */
  5789. /* ORDERPATCH (RFC 3648) */
  5790. /* ACL (RFC 3744) */
  5791. /* SEARCH (RFC 5323) */
  5792. /* + MicroSoft extensions
  5793. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5794. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5795. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5796. }
  5797. /* Parse HTTP request, fill in mg_request_info structure.
  5798. * This function modifies the buffer by NUL-terminating
  5799. * HTTP request components, header names and header values. */
  5800. static int
  5801. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5802. {
  5803. int is_request, request_length;
  5804. if (!ri) {
  5805. return 0;
  5806. }
  5807. request_length = get_request_len(buf, len);
  5808. if (request_length > 0) {
  5809. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5810. * remote_port */
  5811. ri->remote_user = ri->request_method = ri->request_uri =
  5812. ri->http_version = NULL;
  5813. ri->num_headers = 0;
  5814. buf[request_length - 1] = '\0';
  5815. /* RFC says that all initial whitespaces should be ingored */
  5816. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5817. buf++;
  5818. }
  5819. ri->request_method = skip(&buf, " ");
  5820. ri->request_uri = skip(&buf, " ");
  5821. ri->http_version = skip(&buf, "\r\n");
  5822. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5823. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5824. is_request = is_valid_http_method(ri->request_method);
  5825. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5826. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5827. request_length = -1;
  5828. } else {
  5829. if (is_request) {
  5830. ri->http_version += 5;
  5831. }
  5832. parse_http_headers(&buf, ri);
  5833. }
  5834. }
  5835. return request_length;
  5836. }
  5837. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5838. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5839. * buffer (which marks the end of HTTP request). Buffer buf may already
  5840. * have some data. The length of the data is stored in nread.
  5841. * Upon every read operation, increase nread by the number of bytes read. */
  5842. static int
  5843. read_request(FILE *fp,
  5844. struct mg_connection *conn,
  5845. char *buf,
  5846. int bufsiz,
  5847. int *nread)
  5848. {
  5849. int request_len, n = 0;
  5850. struct timespec last_action_time;
  5851. double request_timeout;
  5852. if (!conn) {
  5853. return 0;
  5854. }
  5855. memset(&last_action_time, 0, sizeof(last_action_time));
  5856. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5857. /* value of request_timeout is in seconds, config in milliseconds */
  5858. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5859. } else {
  5860. request_timeout = -1.0;
  5861. }
  5862. request_len = get_request_len(buf, *nread);
  5863. /* first time reading from this connection */
  5864. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5865. while (
  5866. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5867. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5868. <= request_timeout) || (request_timeout < 0))
  5869. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5870. > 0)) {
  5871. *nread += n;
  5872. /* assert(*nread <= bufsiz); */
  5873. if (*nread > bufsiz) {
  5874. return -2;
  5875. }
  5876. request_len = get_request_len(buf, *nread);
  5877. if (request_timeout > 0.0) {
  5878. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5879. }
  5880. }
  5881. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5882. }
  5883. #if !defined(NO_FILES)
  5884. /* For given directory path, substitute it to valid index file.
  5885. * Return 1 if index file has been found, 0 if not found.
  5886. * If the file is found, it's stats is returned in stp. */
  5887. static int
  5888. substitute_index_file(struct mg_connection *conn,
  5889. char *path,
  5890. size_t path_len,
  5891. struct file *filep)
  5892. {
  5893. if (conn && conn->ctx) {
  5894. const char *list = conn->ctx->config[INDEX_FILES];
  5895. struct file file = STRUCT_FILE_INITIALIZER;
  5896. struct vec filename_vec;
  5897. size_t n = strlen(path);
  5898. int found = 0;
  5899. /* The 'path' given to us points to the directory. Remove all trailing
  5900. * directory separator characters from the end of the path, and
  5901. * then append single directory separator character. */
  5902. while (n > 0 && path[n - 1] == '/') {
  5903. n--;
  5904. }
  5905. path[n] = '/';
  5906. /* Traverse index files list. For each entry, append it to the given
  5907. * path and see if the file exists. If it exists, break the loop */
  5908. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5909. /* Ignore too long entries that may overflow path buffer */
  5910. if (filename_vec.len > path_len - (n + 2)) {
  5911. continue;
  5912. }
  5913. /* Prepare full path to the index file */
  5914. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5915. /* Does it exist? */
  5916. if (mg_stat(conn, path, &file)) {
  5917. /* Yes it does, break the loop */
  5918. *filep = file;
  5919. found = 1;
  5920. break;
  5921. }
  5922. }
  5923. /* If no index file exists, restore directory path */
  5924. if (!found) {
  5925. path[n] = '\0';
  5926. }
  5927. return found;
  5928. }
  5929. return 0;
  5930. }
  5931. #endif
  5932. /* Return True if we should reply 304 Not Modified. */
  5933. static int
  5934. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  5935. {
  5936. char etag[64];
  5937. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5938. const char *inm = mg_get_header(conn, "If-None-Match");
  5939. construct_etag(etag, sizeof(etag), filep);
  5940. if (!filep) {
  5941. return 0;
  5942. }
  5943. return (inm != NULL && !mg_strcasecmp(etag, inm))
  5944. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5945. }
  5946. #if !defined(NO_CGI) || !defined(NO_FILES)
  5947. static int
  5948. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5949. {
  5950. const char *expect, *body;
  5951. char buf[MG_BUF_LEN];
  5952. int to_read, nread, success = 0;
  5953. int64_t buffered_len;
  5954. double timeout = -1.0;
  5955. if (!conn) {
  5956. return 0;
  5957. }
  5958. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5959. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5960. }
  5961. expect = mg_get_header(conn, "Expect");
  5962. /* assert(fp != NULL); */
  5963. if (!fp) {
  5964. send_http_error(conn, 500, "%s", "Error: NULL File");
  5965. return 0;
  5966. }
  5967. if (conn->content_len == -1 && !conn->is_chunked) {
  5968. /* Content length is not specified by the client. */
  5969. send_http_error(conn,
  5970. 411,
  5971. "%s",
  5972. "Error: Client did not specify content length");
  5973. } else if ((expect != NULL)
  5974. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  5975. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5976. send_http_error(conn,
  5977. 417,
  5978. "Error: Can not fulfill expectation %s",
  5979. expect);
  5980. } else {
  5981. if (expect != NULL) {
  5982. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5983. conn->status_code = 100;
  5984. } else {
  5985. conn->status_code = 200;
  5986. }
  5987. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5988. - conn->consumed_content;
  5989. /* assert(buffered_len >= 0); */
  5990. /* assert(conn->consumed_content == 0); */
  5991. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5992. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  5993. return 0;
  5994. }
  5995. if (buffered_len > 0) {
  5996. if ((int64_t)buffered_len > conn->content_len) {
  5997. buffered_len = (int)conn->content_len;
  5998. }
  5999. body = conn->buf + conn->request_len + conn->consumed_content;
  6000. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6001. conn->consumed_content += buffered_len;
  6002. }
  6003. nread = 0;
  6004. while (conn->consumed_content < conn->content_len) {
  6005. to_read = sizeof(buf);
  6006. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6007. to_read = (int)(conn->content_len - conn->consumed_content);
  6008. }
  6009. nread = pull(NULL, conn, buf, to_read, timeout);
  6010. if (nread <= 0
  6011. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6012. break;
  6013. }
  6014. conn->consumed_content += nread;
  6015. }
  6016. if (conn->consumed_content == conn->content_len) {
  6017. success = (nread >= 0);
  6018. }
  6019. /* Each error code path in this function must send an error */
  6020. if (!success) {
  6021. /* NOTE: Maybe some data has already been sent. */
  6022. /* TODO (low): If some data has been sent, a correct error
  6023. * reply can no longer be sent, so just close the connection */
  6024. send_http_error(conn, 500, "%s", "");
  6025. }
  6026. }
  6027. return success;
  6028. }
  6029. #endif
  6030. #if !defined(NO_CGI)
  6031. /* This structure helps to create an environment for the spawned CGI program.
  6032. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6033. * last element must be NULL.
  6034. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6035. * strings must reside in a contiguous buffer. The end of the buffer is
  6036. * marked by two '\0' characters.
  6037. * We satisfy both worlds: we create an envp array (which is vars), all
  6038. * entries are actually pointers inside buf. */
  6039. struct cgi_environment {
  6040. struct mg_connection *conn;
  6041. /* Data block */
  6042. char *buf; /* Environment buffer */
  6043. size_t buflen; /* Space available in buf */
  6044. size_t bufused; /* Space taken in buf */
  6045. /* Index block */
  6046. char **var; /* char **envp */
  6047. size_t varlen; /* Number of variables available in var */
  6048. size_t varused; /* Number of variables stored in var */
  6049. };
  6050. static void addenv(struct cgi_environment *env,
  6051. PRINTF_FORMAT_STRING(const char *fmt),
  6052. ...) PRINTF_ARGS(2, 3);
  6053. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6054. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6055. static void
  6056. addenv(struct cgi_environment *env, const char *fmt, ...)
  6057. {
  6058. size_t n, space;
  6059. int truncated;
  6060. char *added;
  6061. va_list ap;
  6062. /* Calculate how much space is left in the buffer */
  6063. space = (env->buflen - env->bufused);
  6064. /* Calculate an estimate for the required space */
  6065. n = strlen(fmt) + 2 + 128;
  6066. do {
  6067. if (space <= n) {
  6068. /* Allocate new buffer */
  6069. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6070. added = (char *)mg_realloc(env->buf, n);
  6071. if (!added) {
  6072. /* Out of memory */
  6073. mg_cry(env->conn,
  6074. "%s: Cannot allocate memory for CGI variable [%s]",
  6075. __func__,
  6076. fmt);
  6077. return;
  6078. }
  6079. env->buf = added;
  6080. env->buflen = n;
  6081. space = (env->buflen - env->bufused);
  6082. }
  6083. /* Make a pointer to the free space int the buffer */
  6084. added = env->buf + env->bufused;
  6085. /* Copy VARIABLE=VALUE\0 string into the free space */
  6086. va_start(ap, fmt);
  6087. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6088. va_end(ap);
  6089. /* Do not add truncated strings to the environment */
  6090. if (truncated) {
  6091. /* Reallocate the buffer */
  6092. space = 0;
  6093. n = 1;
  6094. }
  6095. } while (truncated);
  6096. /* Calculate number of bytes added to the environment */
  6097. n = strlen(added) + 1;
  6098. env->bufused += n;
  6099. /* Now update the variable index */
  6100. space = (env->varlen - env->varused);
  6101. if (space < 2) {
  6102. mg_cry(env->conn,
  6103. "%s: Cannot register CGI variable [%s]",
  6104. __func__,
  6105. fmt);
  6106. return;
  6107. }
  6108. /* Append a pointer to the added string into the envp array */
  6109. env->var[env->varused] = added;
  6110. env->varused++;
  6111. }
  6112. static void
  6113. prepare_cgi_environment(struct mg_connection *conn,
  6114. const char *prog,
  6115. struct cgi_environment *env)
  6116. {
  6117. const char *s;
  6118. struct vec var_vec;
  6119. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6120. int i, truncated;
  6121. if (conn == NULL || prog == NULL || env == NULL) {
  6122. return;
  6123. }
  6124. env->conn = conn;
  6125. env->buflen = CGI_ENVIRONMENT_SIZE;
  6126. env->bufused = 0;
  6127. env->buf = (char *)mg_malloc(env->buflen);
  6128. env->varlen = MAX_CGI_ENVIR_VARS;
  6129. env->varused = 0;
  6130. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6131. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6132. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6133. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6134. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6135. /* Prepare the environment block */
  6136. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6137. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6138. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6139. #if defined(USE_IPV6)
  6140. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6141. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6142. } else
  6143. #endif
  6144. {
  6145. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6146. }
  6147. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6148. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6149. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6150. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6151. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6152. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6153. /* SCRIPT_NAME */
  6154. addenv(env,
  6155. "SCRIPT_NAME=%.*s",
  6156. (int)strlen(conn->request_info.local_uri)
  6157. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6158. conn->request_info.local_uri);
  6159. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6160. if (conn->path_info == NULL) {
  6161. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6162. } else {
  6163. addenv(env,
  6164. "PATH_TRANSLATED=%s%s",
  6165. conn->ctx->config[DOCUMENT_ROOT],
  6166. conn->path_info);
  6167. }
  6168. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  6169. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6170. addenv(env, "CONTENT_TYPE=%s", s);
  6171. }
  6172. if (conn->request_info.query_string != NULL) {
  6173. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6174. }
  6175. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6176. addenv(env, "CONTENT_LENGTH=%s", s);
  6177. }
  6178. if ((s = getenv("PATH")) != NULL) {
  6179. addenv(env, "PATH=%s", s);
  6180. }
  6181. if (conn->path_info != NULL) {
  6182. addenv(env, "PATH_INFO=%s", conn->path_info);
  6183. }
  6184. if (conn->status_code > 0) {
  6185. /* CGI error handler should show the status code */
  6186. addenv(env, "STATUS=%d", conn->status_code);
  6187. }
  6188. #if defined(_WIN32)
  6189. if ((s = getenv("COMSPEC")) != NULL) {
  6190. addenv(env, "COMSPEC=%s", s);
  6191. }
  6192. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6193. addenv(env, "SYSTEMROOT=%s", s);
  6194. }
  6195. if ((s = getenv("SystemDrive")) != NULL) {
  6196. addenv(env, "SystemDrive=%s", s);
  6197. }
  6198. if ((s = getenv("ProgramFiles")) != NULL) {
  6199. addenv(env, "ProgramFiles=%s", s);
  6200. }
  6201. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6202. addenv(env, "ProgramFiles(x86)=%s", s);
  6203. }
  6204. #else
  6205. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6206. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6207. }
  6208. #endif /* _WIN32 */
  6209. if ((s = getenv("PERLLIB")) != NULL) {
  6210. addenv(env, "PERLLIB=%s", s);
  6211. }
  6212. if (conn->request_info.remote_user != NULL) {
  6213. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6214. addenv(env, "%s", "AUTH_TYPE=Digest");
  6215. }
  6216. /* Add all headers as HTTP_* variables */
  6217. for (i = 0; i < conn->request_info.num_headers; i++) {
  6218. (void)mg_snprintf(conn,
  6219. &truncated,
  6220. http_var_name,
  6221. sizeof(http_var_name),
  6222. "HTTP_%s",
  6223. conn->request_info.http_headers[i].name);
  6224. if (truncated) {
  6225. mg_cry(conn,
  6226. "%s: HTTP header variable too long [%s]",
  6227. __func__,
  6228. conn->request_info.http_headers[i].name);
  6229. continue;
  6230. }
  6231. /* Convert variable name into uppercase, and change - to _ */
  6232. for (p = http_var_name; *p != '\0'; p++) {
  6233. if (*p == '-') {
  6234. *p = '_';
  6235. }
  6236. *p = (char)toupper(*(unsigned char *)p);
  6237. }
  6238. addenv(env,
  6239. "%s=%s",
  6240. http_var_name,
  6241. conn->request_info.http_headers[i].value);
  6242. }
  6243. /* Add user-specified variables */
  6244. s = conn->ctx->config[CGI_ENVIRONMENT];
  6245. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6246. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6247. }
  6248. env->var[env->varused] = NULL;
  6249. env->buf[env->bufused] = '\0';
  6250. }
  6251. static void
  6252. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6253. {
  6254. char *buf;
  6255. size_t buflen;
  6256. int headers_len, data_len, i, truncated;
  6257. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6258. const char *status, *status_text, *connection_state;
  6259. char *pbuf, dir[PATH_MAX], *p;
  6260. struct mg_request_info ri;
  6261. struct cgi_environment blk;
  6262. FILE *in = NULL, *out = NULL, *err = NULL;
  6263. struct file fout = STRUCT_FILE_INITIALIZER;
  6264. pid_t pid = (pid_t)-1;
  6265. if (conn == NULL) {
  6266. return;
  6267. }
  6268. buf = NULL;
  6269. buflen = 16384;
  6270. prepare_cgi_environment(conn, prog, &blk);
  6271. /* CGI must be executed in its own directory. 'dir' must point to the
  6272. * directory containing executable program, 'p' must point to the
  6273. * executable program name relative to 'dir'. */
  6274. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6275. if (truncated) {
  6276. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6277. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6278. goto done;
  6279. }
  6280. if ((p = strrchr(dir, '/')) != NULL) {
  6281. *p++ = '\0';
  6282. } else {
  6283. dir[0] = '.', dir[1] = '\0';
  6284. p = (char *)prog;
  6285. }
  6286. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6287. status = strerror(ERRNO);
  6288. mg_cry(conn,
  6289. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6290. prog,
  6291. status);
  6292. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6293. goto done;
  6294. }
  6295. pid = spawn_process(
  6296. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  6297. if (pid == (pid_t)-1) {
  6298. status = strerror(ERRNO);
  6299. mg_cry(conn,
  6300. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6301. prog,
  6302. status);
  6303. send_http_error(conn,
  6304. 500,
  6305. "Error: Cannot spawn CGI process [%s]: %s",
  6306. prog,
  6307. status);
  6308. goto done;
  6309. }
  6310. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6311. set_close_on_exec((SOCKET)fdin[0], conn);
  6312. set_close_on_exec((SOCKET)fdin[1], conn);
  6313. set_close_on_exec((SOCKET)fdout[0], conn);
  6314. set_close_on_exec((SOCKET)fdout[1], conn);
  6315. set_close_on_exec((SOCKET)fderr[0], conn);
  6316. set_close_on_exec((SOCKET)fderr[1], conn);
  6317. /* Parent closes only one side of the pipes.
  6318. * If we don't mark them as closed, close() attempt before
  6319. * return from this function throws an exception on Windows.
  6320. * Windows does not like when closed descriptor is closed again. */
  6321. (void)close(fdin[0]);
  6322. (void)close(fdout[1]);
  6323. (void)close(fderr[1]);
  6324. fdin[0] = fdout[1] = fderr[1] = -1;
  6325. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6326. status = strerror(ERRNO);
  6327. mg_cry(conn,
  6328. "Error: CGI program \"%s\": Can not open stdin: %s",
  6329. prog,
  6330. status);
  6331. send_http_error(conn,
  6332. 500,
  6333. "Error: CGI can not open fdin\nfopen: %s",
  6334. status);
  6335. goto done;
  6336. }
  6337. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6338. status = strerror(ERRNO);
  6339. mg_cry(conn,
  6340. "Error: CGI program \"%s\": Can not open stdout: %s",
  6341. prog,
  6342. status);
  6343. send_http_error(conn,
  6344. 500,
  6345. "Error: CGI can not open fdout\nfopen: %s",
  6346. status);
  6347. goto done;
  6348. }
  6349. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6350. status = strerror(ERRNO);
  6351. mg_cry(conn,
  6352. "Error: CGI program \"%s\": Can not open stderr: %s",
  6353. prog,
  6354. status);
  6355. send_http_error(conn,
  6356. 500,
  6357. "Error: CGI can not open fdout\nfopen: %s",
  6358. status);
  6359. goto done;
  6360. }
  6361. setbuf(in, NULL);
  6362. setbuf(out, NULL);
  6363. setbuf(err, NULL);
  6364. fout.fp = out;
  6365. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6366. /* This is a POST/PUT request, or another request with body data. */
  6367. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6368. /* Error sending the body data */
  6369. mg_cry(conn,
  6370. "Error: CGI program \"%s\": Forward body data failed",
  6371. prog);
  6372. goto done;
  6373. }
  6374. }
  6375. /* Close so child gets an EOF. */
  6376. fclose(in);
  6377. in = NULL;
  6378. fdin[1] = -1;
  6379. /* Now read CGI reply into a buffer. We need to set correct
  6380. * status code, thus we need to see all HTTP headers first.
  6381. * Do not send anything back to client, until we buffer in all
  6382. * HTTP headers. */
  6383. data_len = 0;
  6384. buf = (char *)mg_malloc(buflen);
  6385. if (buf == NULL) {
  6386. send_http_error(conn,
  6387. 500,
  6388. "Error: Not enough memory for CGI buffer (%u bytes)",
  6389. (unsigned int)buflen);
  6390. mg_cry(conn,
  6391. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6392. "bytes)",
  6393. prog,
  6394. (unsigned int)buflen);
  6395. goto done;
  6396. }
  6397. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6398. if (headers_len <= 0) {
  6399. /* Could not parse the CGI response. Check if some error message on
  6400. * stderr. */
  6401. i = pull_all(err, conn, buf, (int)buflen);
  6402. if (i > 0) {
  6403. mg_cry(conn,
  6404. "Error: CGI program \"%s\" sent error "
  6405. "message: [%.*s]",
  6406. prog,
  6407. i,
  6408. buf);
  6409. send_http_error(conn,
  6410. 500,
  6411. "Error: CGI program \"%s\" sent error "
  6412. "message: [%.*s]",
  6413. prog,
  6414. i,
  6415. buf);
  6416. } else {
  6417. mg_cry(conn,
  6418. "Error: CGI program sent malformed or too big "
  6419. "(>%u bytes) HTTP headers: [%.*s]",
  6420. (unsigned)buflen,
  6421. data_len,
  6422. buf);
  6423. send_http_error(conn,
  6424. 500,
  6425. "Error: CGI program sent malformed or too big "
  6426. "(>%u bytes) HTTP headers: [%.*s]",
  6427. (unsigned)buflen,
  6428. data_len,
  6429. buf);
  6430. }
  6431. goto done;
  6432. }
  6433. pbuf = buf;
  6434. buf[headers_len - 1] = '\0';
  6435. parse_http_headers(&pbuf, &ri);
  6436. /* Make up and send the status line */
  6437. status_text = "OK";
  6438. if ((status = get_header(&ri, "Status")) != NULL) {
  6439. conn->status_code = atoi(status);
  6440. status_text = status;
  6441. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  6442. status_text++;
  6443. }
  6444. } else if (get_header(&ri, "Location") != NULL) {
  6445. conn->status_code = 302;
  6446. } else {
  6447. conn->status_code = 200;
  6448. }
  6449. connection_state = get_header(&ri, "Connection");
  6450. if (!header_has_option(connection_state, "keep-alive")) {
  6451. conn->must_close = 1;
  6452. }
  6453. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6454. /* Send headers */
  6455. for (i = 0; i < ri.num_headers; i++) {
  6456. mg_printf(conn,
  6457. "%s: %s\r\n",
  6458. ri.http_headers[i].name,
  6459. ri.http_headers[i].value);
  6460. }
  6461. mg_write(conn, "\r\n", 2);
  6462. /* Send chunk of data that may have been read after the headers */
  6463. conn->num_bytes_sent +=
  6464. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6465. /* Read the rest of CGI output and send to the client */
  6466. send_file_data(conn, &fout, 0, INT64_MAX);
  6467. done:
  6468. mg_free(blk.var);
  6469. mg_free(blk.buf);
  6470. if (pid != (pid_t)-1) {
  6471. kill(pid, SIGKILL);
  6472. #if !defined(_WIN32)
  6473. {
  6474. int st;
  6475. while (waitpid(pid, &st, 0) != -1)
  6476. ; /* clean zombies */
  6477. }
  6478. #endif
  6479. }
  6480. if (fdin[0] != -1) {
  6481. close(fdin[0]);
  6482. }
  6483. if (fdout[1] != -1) {
  6484. close(fdout[1]);
  6485. }
  6486. if (in != NULL) {
  6487. fclose(in);
  6488. } else if (fdin[1] != -1) {
  6489. close(fdin[1]);
  6490. }
  6491. if (out != NULL) {
  6492. fclose(out);
  6493. } else if (fdout[0] != -1) {
  6494. close(fdout[0]);
  6495. }
  6496. if (err != NULL) {
  6497. fclose(err);
  6498. } else if (fderr[0] != -1) {
  6499. close(fderr[0]);
  6500. }
  6501. if (buf != NULL) {
  6502. mg_free(buf);
  6503. }
  6504. }
  6505. #endif /* !NO_CGI */
  6506. #if !defined(NO_FILES)
  6507. static void
  6508. mkcol(struct mg_connection *conn, const char *path)
  6509. {
  6510. int rc, body_len;
  6511. struct de de;
  6512. char date[64];
  6513. time_t curtime = time(NULL);
  6514. if (conn == NULL) {
  6515. return;
  6516. }
  6517. /* TODO (mid): Check the send_http_error situations in this function */
  6518. memset(&de.file, 0, sizeof(de.file));
  6519. if (!mg_stat(conn, path, &de.file)) {
  6520. mg_cry(conn,
  6521. "%s: mg_stat(%s) failed: %s",
  6522. __func__,
  6523. path,
  6524. strerror(ERRNO));
  6525. }
  6526. if (de.file.last_modified) {
  6527. /* TODO (high): This check does not seem to make any sense ! */
  6528. send_http_error(
  6529. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6530. return;
  6531. }
  6532. body_len = conn->data_len - conn->request_len;
  6533. if (body_len > 0) {
  6534. send_http_error(
  6535. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6536. return;
  6537. }
  6538. rc = mg_mkdir(path, 0755);
  6539. if (rc == 0) {
  6540. conn->status_code = 201;
  6541. gmt_time_string(date, sizeof(date), &curtime);
  6542. mg_printf(conn,
  6543. "HTTP/1.1 %d Created\r\n"
  6544. "Date: %s\r\n",
  6545. conn->status_code,
  6546. date);
  6547. send_static_cache_header(conn);
  6548. mg_printf(conn,
  6549. "Content-Length: 0\r\n"
  6550. "Connection: %s\r\n\r\n",
  6551. suggest_connection_header(conn));
  6552. } else if (rc == -1) {
  6553. if (errno == EEXIST) {
  6554. send_http_error(
  6555. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6556. } else if (errno == EACCES) {
  6557. send_http_error(
  6558. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6559. } else if (errno == ENOENT) {
  6560. send_http_error(
  6561. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6562. } else {
  6563. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6564. }
  6565. }
  6566. }
  6567. static void
  6568. put_file(struct mg_connection *conn, const char *path)
  6569. {
  6570. struct file file = STRUCT_FILE_INITIALIZER;
  6571. const char *range;
  6572. int64_t r1, r2;
  6573. int rc;
  6574. char date[64];
  6575. time_t curtime = time(NULL);
  6576. if (conn == NULL) {
  6577. return;
  6578. }
  6579. if (mg_stat(conn, path, &file)) {
  6580. /* File already exists */
  6581. conn->status_code = 200;
  6582. if (file.is_directory) {
  6583. /* This is an already existing directory,
  6584. * so there is nothing to do for the server. */
  6585. rc = 0;
  6586. } else {
  6587. /* File exists and is not a directory. */
  6588. /* Can it be replaced? */
  6589. if (file.membuf != NULL) {
  6590. /* This is an "in-memory" file, that can not be replaced */
  6591. send_http_error(
  6592. conn,
  6593. 405,
  6594. "Error: Put not possible\nReplacing %s is not supported",
  6595. path);
  6596. return;
  6597. }
  6598. /* Check if the server may write this file */
  6599. if (access(path, W_OK) == 0) {
  6600. /* Access granted */
  6601. conn->status_code = 200;
  6602. rc = 1;
  6603. } else {
  6604. send_http_error(
  6605. conn,
  6606. 403,
  6607. "Error: Put not possible\nReplacing %s is not allowed",
  6608. path);
  6609. return;
  6610. }
  6611. }
  6612. } else {
  6613. /* File should be created */
  6614. conn->status_code = 201;
  6615. rc = put_dir(conn, path);
  6616. }
  6617. if (rc == 0) {
  6618. /* put_dir returns 0 if path is a directory */
  6619. gmt_time_string(date, sizeof(date), &curtime);
  6620. mg_printf(conn,
  6621. "HTTP/1.1 %d %s\r\n",
  6622. conn->status_code,
  6623. mg_get_response_code_text(conn->status_code, NULL));
  6624. send_no_cache_header(conn);
  6625. mg_printf(conn,
  6626. "Date: %s\r\n"
  6627. "Content-Length: 0\r\n"
  6628. "Connection: %s\r\n\r\n",
  6629. date,
  6630. suggest_connection_header(conn));
  6631. /* Request to create a directory has been fulfilled successfully.
  6632. * No need to put a file. */
  6633. return;
  6634. }
  6635. if (rc == -1) {
  6636. /* put_dir returns -1 if the path is too long */
  6637. send_http_error(conn,
  6638. 414,
  6639. "Error: Path too long\nput_dir(%s): %s",
  6640. path,
  6641. strerror(ERRNO));
  6642. return;
  6643. }
  6644. if (rc == -2) {
  6645. /* put_dir returns -2 if the directory can not be created */
  6646. send_http_error(conn,
  6647. 500,
  6648. "Error: Can not create directory\nput_dir(%s): %s",
  6649. path,
  6650. strerror(ERRNO));
  6651. return;
  6652. }
  6653. /* A file should be created or overwritten. */
  6654. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6655. mg_fclose(&file);
  6656. send_http_error(conn,
  6657. 500,
  6658. "Error: Can not create file\nfopen(%s): %s",
  6659. path,
  6660. strerror(ERRNO));
  6661. return;
  6662. }
  6663. fclose_on_exec(&file, conn);
  6664. range = mg_get_header(conn, "Content-Range");
  6665. r1 = r2 = 0;
  6666. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6667. conn->status_code = 206; /* Partial content */
  6668. fseeko(file.fp, r1, SEEK_SET);
  6669. }
  6670. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6671. /* forward_body_data failed.
  6672. * The error code has already been sent to the client,
  6673. * and conn->status_code is already set. */
  6674. mg_fclose(&file);
  6675. return;
  6676. }
  6677. gmt_time_string(date, sizeof(date), &curtime);
  6678. mg_printf(conn,
  6679. "HTTP/1.1 %d %s\r\n",
  6680. conn->status_code,
  6681. mg_get_response_code_text(conn->status_code, NULL));
  6682. send_no_cache_header(conn);
  6683. mg_printf(conn,
  6684. "Date: %s\r\n"
  6685. "Content-Length: 0\r\n"
  6686. "Connection: %s\r\n\r\n",
  6687. date,
  6688. suggest_connection_header(conn));
  6689. mg_fclose(&file);
  6690. }
  6691. static void
  6692. delete_file(struct mg_connection *conn, const char *path)
  6693. {
  6694. struct de de;
  6695. memset(&de.file, 0, sizeof(de.file));
  6696. if (!mg_stat(conn, path, &de.file)) {
  6697. /* mg_stat returns 0 if the file does not exist */
  6698. send_http_error(conn,
  6699. 404,
  6700. "Error: Cannot delete file\nFile %s not found",
  6701. path);
  6702. return;
  6703. }
  6704. if (de.file.membuf != NULL) {
  6705. /* the file is cached in memory */
  6706. send_http_error(
  6707. conn,
  6708. 405,
  6709. "Error: Delete not possible\nDeleting %s is not supported",
  6710. path);
  6711. return;
  6712. }
  6713. if (de.file.is_directory) {
  6714. if (remove_directory(conn, path)) {
  6715. /* Delete is successful: Return 204 without content. */
  6716. send_http_error(conn, 204, "%s", "");
  6717. } else {
  6718. /* Delete is not successful: Return 500 (Server error). */
  6719. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6720. }
  6721. return;
  6722. }
  6723. /* This is an existing file (not a directory).
  6724. * Check if write permission is granted. */
  6725. if (access(path, W_OK) != 0) {
  6726. /* File is read only */
  6727. send_http_error(
  6728. conn,
  6729. 403,
  6730. "Error: Delete not possible\nDeleting %s is not allowed",
  6731. path);
  6732. return;
  6733. }
  6734. /* Try to delete it. */
  6735. if (mg_remove(path) == 0) {
  6736. /* Delete was successful: Return 204 without content. */
  6737. send_http_error(conn, 204, "%s", "");
  6738. } else {
  6739. /* Delete not successful (file locked). */
  6740. send_http_error(conn,
  6741. 423,
  6742. "Error: Cannot delete file\nremove(%s): %s",
  6743. path,
  6744. strerror(ERRNO));
  6745. }
  6746. }
  6747. #endif /* !NO_FILES */
  6748. static void
  6749. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6750. static void
  6751. do_ssi_include(struct mg_connection *conn,
  6752. const char *ssi,
  6753. char *tag,
  6754. int include_level)
  6755. {
  6756. char file_name[MG_BUF_LEN], path[512], *p;
  6757. struct file file = STRUCT_FILE_INITIALIZER;
  6758. size_t len;
  6759. int truncated = 0;
  6760. if (conn == NULL) {
  6761. return;
  6762. }
  6763. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6764. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6765. * always < MG_BUF_LEN. */
  6766. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6767. /* File name is relative to the webserver root */
  6768. file_name[511] = 0;
  6769. (void)mg_snprintf(conn,
  6770. &truncated,
  6771. path,
  6772. sizeof(path),
  6773. "%s/%s",
  6774. conn->ctx->config[DOCUMENT_ROOT],
  6775. file_name);
  6776. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6777. /* File name is relative to the webserver working directory
  6778. * or it is absolute system path */
  6779. file_name[511] = 0;
  6780. (void)
  6781. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6782. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6783. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6784. /* File name is relative to the currect document */
  6785. file_name[511] = 0;
  6786. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6787. if (!truncated) {
  6788. if ((p = strrchr(path, '/')) != NULL) {
  6789. p[1] = '\0';
  6790. }
  6791. len = strlen(path);
  6792. (void)mg_snprintf(conn,
  6793. &truncated,
  6794. path + len,
  6795. sizeof(path) - len,
  6796. "%s",
  6797. file_name);
  6798. }
  6799. } else {
  6800. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6801. return;
  6802. }
  6803. if (truncated) {
  6804. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6805. return;
  6806. }
  6807. if (!mg_fopen(conn, path, "rb", &file)) {
  6808. mg_cry(conn,
  6809. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6810. tag,
  6811. path,
  6812. strerror(ERRNO));
  6813. } else {
  6814. fclose_on_exec(&file, conn);
  6815. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6816. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6817. path) > 0) {
  6818. send_ssi_file(conn, path, &file, include_level + 1);
  6819. } else {
  6820. send_file_data(conn, &file, 0, INT64_MAX);
  6821. }
  6822. mg_fclose(&file);
  6823. }
  6824. }
  6825. #if !defined(NO_POPEN)
  6826. static void
  6827. do_ssi_exec(struct mg_connection *conn, char *tag)
  6828. {
  6829. char cmd[1024] = "";
  6830. struct file file = STRUCT_FILE_INITIALIZER;
  6831. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6832. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6833. } else {
  6834. cmd[1023] = 0;
  6835. if ((file.fp = popen(cmd, "r")) == NULL) {
  6836. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6837. } else {
  6838. send_file_data(conn, &file, 0, INT64_MAX);
  6839. pclose(file.fp);
  6840. }
  6841. }
  6842. }
  6843. #endif /* !NO_POPEN */
  6844. static int
  6845. mg_fgetc(struct file *filep, int offset)
  6846. {
  6847. if (filep == NULL) {
  6848. return EOF;
  6849. }
  6850. if (filep->membuf != NULL && offset >= 0
  6851. && ((unsigned int)(offset)) < filep->size) {
  6852. return ((unsigned char *)filep->membuf)[offset];
  6853. } else if (filep->fp != NULL) {
  6854. return fgetc(filep->fp);
  6855. } else {
  6856. return EOF;
  6857. }
  6858. }
  6859. static void
  6860. send_ssi_file(struct mg_connection *conn,
  6861. const char *path,
  6862. struct file *filep,
  6863. int include_level)
  6864. {
  6865. char buf[MG_BUF_LEN];
  6866. int ch, offset, len, in_ssi_tag;
  6867. if (include_level > 10) {
  6868. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6869. return;
  6870. }
  6871. in_ssi_tag = len = offset = 0;
  6872. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6873. if (in_ssi_tag && ch == '>') {
  6874. in_ssi_tag = 0;
  6875. buf[len++] = (char)ch;
  6876. buf[len] = '\0';
  6877. /* assert(len <= (int) sizeof(buf)); */
  6878. if (len > (int)sizeof(buf)) {
  6879. break;
  6880. }
  6881. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6882. /* Not an SSI tag, pass it */
  6883. (void)mg_write(conn, buf, (size_t)len);
  6884. } else {
  6885. if (!memcmp(buf + 5, "include", 7)) {
  6886. do_ssi_include(conn, path, buf + 12, include_level);
  6887. #if !defined(NO_POPEN)
  6888. } else if (!memcmp(buf + 5, "exec", 4)) {
  6889. do_ssi_exec(conn, buf + 9);
  6890. #endif /* !NO_POPEN */
  6891. } else {
  6892. mg_cry(conn,
  6893. "%s: unknown SSI "
  6894. "command: \"%s\"",
  6895. path,
  6896. buf);
  6897. }
  6898. }
  6899. len = 0;
  6900. } else if (in_ssi_tag) {
  6901. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6902. /* Not an SSI tag */
  6903. in_ssi_tag = 0;
  6904. } else if (len == (int)sizeof(buf) - 2) {
  6905. mg_cry(conn, "%s: SSI tag is too large", path);
  6906. len = 0;
  6907. }
  6908. buf[len++] = (char)(ch & 0xff);
  6909. } else if (ch == '<') {
  6910. in_ssi_tag = 1;
  6911. if (len > 0) {
  6912. mg_write(conn, buf, (size_t)len);
  6913. }
  6914. len = 0;
  6915. buf[len++] = (char)(ch & 0xff);
  6916. } else {
  6917. buf[len++] = (char)(ch & 0xff);
  6918. if (len == (int)sizeof(buf)) {
  6919. mg_write(conn, buf, (size_t)len);
  6920. len = 0;
  6921. }
  6922. }
  6923. }
  6924. /* Send the rest of buffered data */
  6925. if (len > 0) {
  6926. mg_write(conn, buf, (size_t)len);
  6927. }
  6928. }
  6929. static void
  6930. handle_ssi_file_request(struct mg_connection *conn,
  6931. const char *path,
  6932. struct file *filep)
  6933. {
  6934. char date[64];
  6935. time_t curtime = time(NULL);
  6936. const char *cors1, *cors2, *cors3;
  6937. if (conn == NULL || path == NULL || filep == NULL) {
  6938. return;
  6939. }
  6940. if (mg_get_header(conn, "Origin")) {
  6941. /* Cross-origin resource sharing (CORS). */
  6942. cors1 = "Access-Control-Allow-Origin: ";
  6943. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6944. cors3 = "\r\n";
  6945. } else {
  6946. cors1 = cors2 = cors3 = "";
  6947. }
  6948. if (!mg_fopen(conn, path, "rb", filep)) {
  6949. /* File exists (precondition for calling this function),
  6950. * but can not be opened by the server. */
  6951. send_http_error(conn,
  6952. 500,
  6953. "Error: Cannot read file\nfopen(%s): %s",
  6954. path,
  6955. strerror(ERRNO));
  6956. } else {
  6957. conn->must_close = 1;
  6958. gmt_time_string(date, sizeof(date), &curtime);
  6959. fclose_on_exec(filep, conn);
  6960. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6961. send_no_cache_header(conn);
  6962. mg_printf(conn,
  6963. "%s%s%s"
  6964. "Date: %s\r\n"
  6965. "Content-Type: text/html\r\n"
  6966. "Connection: %s\r\n\r\n",
  6967. cors1,
  6968. cors2,
  6969. cors3,
  6970. date,
  6971. suggest_connection_header(conn));
  6972. send_ssi_file(conn, path, filep, 0);
  6973. mg_fclose(filep);
  6974. }
  6975. }
  6976. #if !defined(NO_FILES)
  6977. static void
  6978. send_options(struct mg_connection *conn)
  6979. {
  6980. char date[64];
  6981. time_t curtime = time(NULL);
  6982. if (!conn) {
  6983. return;
  6984. }
  6985. conn->status_code = 200;
  6986. conn->must_close = 1;
  6987. gmt_time_string(date, sizeof(date), &curtime);
  6988. mg_printf(conn,
  6989. "HTTP/1.1 200 OK\r\n"
  6990. "Date: %s\r\n"
  6991. /* TODO: "Cache-Control" (?) */
  6992. "Connection: %s\r\n"
  6993. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  6994. "PROPFIND, MKCOL\r\n"
  6995. "DAV: 1\r\n\r\n",
  6996. date,
  6997. suggest_connection_header(conn));
  6998. }
  6999. /* Writes PROPFIND properties for a collection element */
  7000. static void
  7001. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7002. {
  7003. char mtime[64];
  7004. if (conn == NULL || uri == NULL || filep == NULL) {
  7005. return;
  7006. }
  7007. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7008. conn->num_bytes_sent +=
  7009. mg_printf(conn,
  7010. "<d:response>"
  7011. "<d:href>%s</d:href>"
  7012. "<d:propstat>"
  7013. "<d:prop>"
  7014. "<d:resourcetype>%s</d:resourcetype>"
  7015. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7016. "<d:getlastmodified>%s</d:getlastmodified>"
  7017. "</d:prop>"
  7018. "<d:status>HTTP/1.1 200 OK</d:status>"
  7019. "</d:propstat>"
  7020. "</d:response>\n",
  7021. uri,
  7022. filep->is_directory ? "<d:collection/>" : "",
  7023. filep->size,
  7024. mtime);
  7025. }
  7026. static void
  7027. print_dav_dir_entry(struct de *de, void *data)
  7028. {
  7029. char href[PATH_MAX];
  7030. char href_encoded[PATH_MAX];
  7031. int truncated;
  7032. struct mg_connection *conn = (struct mg_connection *)data;
  7033. if (!de || !conn) {
  7034. return;
  7035. }
  7036. mg_snprintf(conn,
  7037. &truncated,
  7038. href,
  7039. sizeof(href),
  7040. "%s%s",
  7041. conn->request_info.local_uri,
  7042. de->file_name);
  7043. if (!truncated) {
  7044. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  7045. print_props(conn, href_encoded, &de->file);
  7046. }
  7047. }
  7048. static void
  7049. handle_propfind(struct mg_connection *conn,
  7050. const char *path,
  7051. struct file *filep)
  7052. {
  7053. const char *depth = mg_get_header(conn, "Depth");
  7054. char date[64];
  7055. time_t curtime = time(NULL);
  7056. gmt_time_string(date, sizeof(date), &curtime);
  7057. if (!conn || !path || !filep || !conn->ctx) {
  7058. return;
  7059. }
  7060. conn->must_close = 1;
  7061. conn->status_code = 207;
  7062. mg_printf(conn,
  7063. "HTTP/1.1 207 Multi-Status\r\n"
  7064. "Date: %s\r\n",
  7065. date);
  7066. send_static_cache_header(conn);
  7067. mg_printf(conn,
  7068. "Connection: %s\r\n"
  7069. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7070. suggest_connection_header(conn));
  7071. conn->num_bytes_sent +=
  7072. mg_printf(conn,
  7073. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7074. "<d:multistatus xmlns:d='DAV:'>\n");
  7075. /* Print properties for the requested resource itself */
  7076. print_props(conn, conn->request_info.local_uri, filep);
  7077. /* If it is a directory, print directory entries too if Depth is not 0 */
  7078. if (filep && filep->is_directory
  7079. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7080. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7081. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7082. }
  7083. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7084. }
  7085. #endif
  7086. void
  7087. mg_lock_connection(struct mg_connection *conn)
  7088. {
  7089. if (conn) {
  7090. (void)pthread_mutex_lock(&conn->mutex);
  7091. }
  7092. }
  7093. void
  7094. mg_unlock_connection(struct mg_connection *conn)
  7095. {
  7096. if (conn) {
  7097. (void)pthread_mutex_unlock(&conn->mutex);
  7098. }
  7099. }
  7100. void
  7101. mg_lock_context(struct mg_context *ctx)
  7102. {
  7103. if (ctx) {
  7104. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7105. }
  7106. }
  7107. void
  7108. mg_unlock_context(struct mg_context *ctx)
  7109. {
  7110. if (ctx) {
  7111. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7112. }
  7113. }
  7114. #if defined(USE_TIMERS)
  7115. #include "timer.inl"
  7116. #endif /* USE_TIMERS */
  7117. #ifdef USE_LUA
  7118. #include "mod_lua.inl"
  7119. #endif /* USE_LUA */
  7120. #ifdef USE_DUKTAPE
  7121. #include "mod_duktape.inl"
  7122. #endif /* USE_DUKTAPE */
  7123. #if defined(USE_WEBSOCKET)
  7124. /* START OF SHA-1 code
  7125. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7126. #define SHA1HANDSOFF
  7127. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7128. *
  7129. * #if defined(__sun)
  7130. * #include "solarisfixes.h"
  7131. * #endif
  7132. */
  7133. static int
  7134. is_big_endian(void)
  7135. {
  7136. static const int n = 1;
  7137. return ((char *)&n)[0] == 0;
  7138. }
  7139. union char64long16 {
  7140. unsigned char c[64];
  7141. uint32_t l[16];
  7142. };
  7143. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7144. static uint32_t
  7145. blk0(union char64long16 *block, int i)
  7146. {
  7147. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7148. if (!is_big_endian()) {
  7149. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7150. | (rol(block->l[i], 8) & 0x00FF00FF);
  7151. }
  7152. return block->l[i];
  7153. }
  7154. #define blk(i) \
  7155. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7156. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7157. 1))
  7158. #define R0(v, w, x, y, z, i) \
  7159. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7160. w = rol(w, 30);
  7161. #define R1(v, w, x, y, z, i) \
  7162. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7163. w = rol(w, 30);
  7164. #define R2(v, w, x, y, z, i) \
  7165. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7166. w = rol(w, 30);
  7167. #define R3(v, w, x, y, z, i) \
  7168. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7169. w = rol(w, 30);
  7170. #define R4(v, w, x, y, z, i) \
  7171. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7172. w = rol(w, 30);
  7173. typedef struct {
  7174. uint32_t state[5];
  7175. uint32_t count[2];
  7176. unsigned char buffer[64];
  7177. } SHA1_CTX;
  7178. static void
  7179. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7180. {
  7181. uint32_t a, b, c, d, e;
  7182. union char64long16 block[1];
  7183. memcpy(block, buffer, 64);
  7184. a = state[0];
  7185. b = state[1];
  7186. c = state[2];
  7187. d = state[3];
  7188. e = state[4];
  7189. R0(a, b, c, d, e, 0);
  7190. R0(e, a, b, c, d, 1);
  7191. R0(d, e, a, b, c, 2);
  7192. R0(c, d, e, a, b, 3);
  7193. R0(b, c, d, e, a, 4);
  7194. R0(a, b, c, d, e, 5);
  7195. R0(e, a, b, c, d, 6);
  7196. R0(d, e, a, b, c, 7);
  7197. R0(c, d, e, a, b, 8);
  7198. R0(b, c, d, e, a, 9);
  7199. R0(a, b, c, d, e, 10);
  7200. R0(e, a, b, c, d, 11);
  7201. R0(d, e, a, b, c, 12);
  7202. R0(c, d, e, a, b, 13);
  7203. R0(b, c, d, e, a, 14);
  7204. R0(a, b, c, d, e, 15);
  7205. R1(e, a, b, c, d, 16);
  7206. R1(d, e, a, b, c, 17);
  7207. R1(c, d, e, a, b, 18);
  7208. R1(b, c, d, e, a, 19);
  7209. R2(a, b, c, d, e, 20);
  7210. R2(e, a, b, c, d, 21);
  7211. R2(d, e, a, b, c, 22);
  7212. R2(c, d, e, a, b, 23);
  7213. R2(b, c, d, e, a, 24);
  7214. R2(a, b, c, d, e, 25);
  7215. R2(e, a, b, c, d, 26);
  7216. R2(d, e, a, b, c, 27);
  7217. R2(c, d, e, a, b, 28);
  7218. R2(b, c, d, e, a, 29);
  7219. R2(a, b, c, d, e, 30);
  7220. R2(e, a, b, c, d, 31);
  7221. R2(d, e, a, b, c, 32);
  7222. R2(c, d, e, a, b, 33);
  7223. R2(b, c, d, e, a, 34);
  7224. R2(a, b, c, d, e, 35);
  7225. R2(e, a, b, c, d, 36);
  7226. R2(d, e, a, b, c, 37);
  7227. R2(c, d, e, a, b, 38);
  7228. R2(b, c, d, e, a, 39);
  7229. R3(a, b, c, d, e, 40);
  7230. R3(e, a, b, c, d, 41);
  7231. R3(d, e, a, b, c, 42);
  7232. R3(c, d, e, a, b, 43);
  7233. R3(b, c, d, e, a, 44);
  7234. R3(a, b, c, d, e, 45);
  7235. R3(e, a, b, c, d, 46);
  7236. R3(d, e, a, b, c, 47);
  7237. R3(c, d, e, a, b, 48);
  7238. R3(b, c, d, e, a, 49);
  7239. R3(a, b, c, d, e, 50);
  7240. R3(e, a, b, c, d, 51);
  7241. R3(d, e, a, b, c, 52);
  7242. R3(c, d, e, a, b, 53);
  7243. R3(b, c, d, e, a, 54);
  7244. R3(a, b, c, d, e, 55);
  7245. R3(e, a, b, c, d, 56);
  7246. R3(d, e, a, b, c, 57);
  7247. R3(c, d, e, a, b, 58);
  7248. R3(b, c, d, e, a, 59);
  7249. R4(a, b, c, d, e, 60);
  7250. R4(e, a, b, c, d, 61);
  7251. R4(d, e, a, b, c, 62);
  7252. R4(c, d, e, a, b, 63);
  7253. R4(b, c, d, e, a, 64);
  7254. R4(a, b, c, d, e, 65);
  7255. R4(e, a, b, c, d, 66);
  7256. R4(d, e, a, b, c, 67);
  7257. R4(c, d, e, a, b, 68);
  7258. R4(b, c, d, e, a, 69);
  7259. R4(a, b, c, d, e, 70);
  7260. R4(e, a, b, c, d, 71);
  7261. R4(d, e, a, b, c, 72);
  7262. R4(c, d, e, a, b, 73);
  7263. R4(b, c, d, e, a, 74);
  7264. R4(a, b, c, d, e, 75);
  7265. R4(e, a, b, c, d, 76);
  7266. R4(d, e, a, b, c, 77);
  7267. R4(c, d, e, a, b, 78);
  7268. R4(b, c, d, e, a, 79);
  7269. state[0] += a;
  7270. state[1] += b;
  7271. state[2] += c;
  7272. state[3] += d;
  7273. state[4] += e;
  7274. a = b = c = d = e = 0;
  7275. memset(block, '\0', sizeof(block));
  7276. }
  7277. static void
  7278. SHA1Init(SHA1_CTX *context)
  7279. {
  7280. context->state[0] = 0x67452301;
  7281. context->state[1] = 0xEFCDAB89;
  7282. context->state[2] = 0x98BADCFE;
  7283. context->state[3] = 0x10325476;
  7284. context->state[4] = 0xC3D2E1F0;
  7285. context->count[0] = context->count[1] = 0;
  7286. }
  7287. static void
  7288. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7289. {
  7290. uint32_t i, j;
  7291. j = context->count[0];
  7292. if ((context->count[0] += len << 3) < j) {
  7293. context->count[1]++;
  7294. }
  7295. context->count[1] += (len >> 29);
  7296. j = (j >> 3) & 63;
  7297. if ((j + len) > 63) {
  7298. memcpy(&context->buffer[j], data, (i = 64 - j));
  7299. SHA1Transform(context->state, context->buffer);
  7300. for (; i + 63 < len; i += 64) {
  7301. SHA1Transform(context->state, &data[i]);
  7302. }
  7303. j = 0;
  7304. } else
  7305. i = 0;
  7306. memcpy(&context->buffer[j], &data[i], len - i);
  7307. }
  7308. static void
  7309. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7310. {
  7311. unsigned i;
  7312. unsigned char finalcount[8], c;
  7313. for (i = 0; i < 8; i++) {
  7314. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7315. >> ((3 - (i & 3)) * 8)) & 255);
  7316. }
  7317. c = 0200;
  7318. SHA1Update(context, &c, 1);
  7319. while ((context->count[0] & 504) != 448) {
  7320. c = 0000;
  7321. SHA1Update(context, &c, 1);
  7322. }
  7323. SHA1Update(context, finalcount, 8);
  7324. for (i = 0; i < 20; i++) {
  7325. digest[i] = (unsigned char)((context->state[i >> 2]
  7326. >> ((3 - (i & 3)) * 8)) & 255);
  7327. }
  7328. memset(context, '\0', sizeof(*context));
  7329. memset(&finalcount, '\0', sizeof(finalcount));
  7330. }
  7331. /* END OF SHA1 CODE */
  7332. static int
  7333. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7334. {
  7335. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7336. const char *protocol = NULL;
  7337. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7338. SHA1_CTX sha_ctx;
  7339. int truncated;
  7340. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7341. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7342. if (truncated) {
  7343. conn->must_close = 1;
  7344. return 0;
  7345. }
  7346. SHA1Init(&sha_ctx);
  7347. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7348. SHA1Final((unsigned char *)sha, &sha_ctx);
  7349. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7350. mg_printf(conn,
  7351. "HTTP/1.1 101 Switching Protocols\r\n"
  7352. "Upgrade: websocket\r\n"
  7353. "Connection: Upgrade\r\n"
  7354. "Sec-WebSocket-Accept: %s\r\n",
  7355. b64_sha);
  7356. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7357. if (protocol) {
  7358. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7359. } else {
  7360. mg_printf(conn, "%s", "\r\n");
  7361. }
  7362. return 1;
  7363. }
  7364. static void
  7365. read_websocket(struct mg_connection *conn,
  7366. mg_websocket_data_handler ws_data_handler,
  7367. void *callback_data)
  7368. {
  7369. /* Pointer to the beginning of the portion of the incoming websocket
  7370. * message queue.
  7371. * The original websocket upgrade request is never removed, so the queue
  7372. * begins after it. */
  7373. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7374. int n, error, exit_by_callback;
  7375. /* body_len is the length of the entire queue in bytes
  7376. * len is the length of the current message
  7377. * data_len is the length of the current message's data payload
  7378. * header_len is the length of the current message's header */
  7379. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7380. /* "The masking key is a 32-bit value chosen at random by the client."
  7381. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7382. */
  7383. unsigned char mask[4];
  7384. /* data points to the place where the message is stored when passed to the
  7385. * websocket_data callback. This is either mem on the stack, or a
  7386. * dynamically allocated buffer if it is too large. */
  7387. char mem[4096];
  7388. char *data = mem;
  7389. unsigned char mop; /* mask flag and opcode */
  7390. double timeout = -1.0;
  7391. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7392. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7393. }
  7394. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7395. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7396. }
  7397. mg_set_thread_name("wsock");
  7398. /* Loop continuously, reading messages from the socket, invoking the
  7399. * callback, and waiting repeatedly until an error occurs. */
  7400. while (!conn->ctx->stop_flag) {
  7401. header_len = 0;
  7402. assert(conn->data_len >= conn->request_len);
  7403. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7404. len = buf[1] & 127;
  7405. mask_len = buf[1] & 128 ? 4 : 0;
  7406. if (len < 126 && body_len >= mask_len) {
  7407. data_len = len;
  7408. header_len = 2 + mask_len;
  7409. } else if (len == 126 && body_len >= 4 + mask_len) {
  7410. header_len = 4 + mask_len;
  7411. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7412. } else if (body_len >= 10 + mask_len) {
  7413. header_len = 10 + mask_len;
  7414. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7415. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7416. }
  7417. }
  7418. if (header_len > 0 && body_len >= header_len) {
  7419. /* Allocate space to hold websocket payload */
  7420. data = mem;
  7421. if (data_len > sizeof(mem)) {
  7422. data = (char *)mg_malloc(data_len);
  7423. if (data == NULL) {
  7424. /* Allocation failed, exit the loop and then close the
  7425. * connection */
  7426. mg_cry(conn, "websocket out of memory; closing connection");
  7427. break;
  7428. }
  7429. }
  7430. /* Copy the mask before we shift the queue and destroy it */
  7431. if (mask_len > 0) {
  7432. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7433. } else {
  7434. memset(mask, 0, sizeof(mask));
  7435. }
  7436. /* Read frame payload from the first message in the queue into
  7437. * data and advance the queue by moving the memory in place. */
  7438. assert(body_len >= header_len);
  7439. if (data_len + header_len > body_len) {
  7440. mop = buf[0]; /* current mask and opcode */
  7441. /* Overflow case */
  7442. len = body_len - header_len;
  7443. memcpy(data, buf + header_len, len);
  7444. error = 0;
  7445. while (len < data_len) {
  7446. n = pull(
  7447. NULL, conn, data + len, (int)(data_len - len), timeout);
  7448. if (n <= 0) {
  7449. error = 1;
  7450. break;
  7451. }
  7452. len += (size_t)n;
  7453. }
  7454. if (error) {
  7455. mg_cry(conn, "Websocket pull failed; closing connection");
  7456. break;
  7457. }
  7458. conn->data_len = conn->request_len;
  7459. } else {
  7460. mop = buf[0]; /* current mask and opcode, overwritten by
  7461. * memmove() */
  7462. /* Length of the message being read at the front of the
  7463. * queue */
  7464. len = data_len + header_len;
  7465. /* Copy the data payload into the data pointer for the
  7466. * callback */
  7467. memcpy(data, buf + header_len, data_len);
  7468. /* Move the queue forward len bytes */
  7469. memmove(buf, buf + len, body_len - len);
  7470. /* Mark the queue as advanced */
  7471. conn->data_len -= (int)len;
  7472. }
  7473. /* Apply mask if necessary */
  7474. if (mask_len > 0) {
  7475. for (i = 0; i < data_len; ++i) {
  7476. data[i] ^= mask[i & 3];
  7477. }
  7478. }
  7479. /* Exit the loop if callback signals to exit (server side),
  7480. * or "connection close" opcode received (client side). */
  7481. exit_by_callback = 0;
  7482. if ((ws_data_handler != NULL)
  7483. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7484. exit_by_callback = 1;
  7485. }
  7486. if (data != mem) {
  7487. mg_free(data);
  7488. }
  7489. if (exit_by_callback
  7490. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7491. /* Opcode == 8, connection close */
  7492. break;
  7493. }
  7494. /* Not breaking the loop, process next websocket frame. */
  7495. } else {
  7496. /* Read from the socket into the next available location in the
  7497. * message queue. */
  7498. if ((n = pull(NULL,
  7499. conn,
  7500. conn->buf + conn->data_len,
  7501. conn->buf_size - conn->data_len,
  7502. timeout)) <= 0) {
  7503. /* Error, no bytes read */
  7504. break;
  7505. }
  7506. conn->data_len += n;
  7507. }
  7508. }
  7509. mg_set_thread_name("worker");
  7510. }
  7511. static int
  7512. mg_websocket_write_exec(struct mg_connection *conn,
  7513. int opcode,
  7514. const char *data,
  7515. size_t dataLen,
  7516. uint32_t masking_key)
  7517. {
  7518. unsigned char header[14];
  7519. size_t headerLen = 1;
  7520. int retval = -1;
  7521. header[0] = 0x80 + (opcode & 0xF);
  7522. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7523. if (dataLen < 126) {
  7524. /* inline 7-bit length field */
  7525. header[1] = (unsigned char)dataLen;
  7526. headerLen = 2;
  7527. } else if (dataLen <= 0xFFFF) {
  7528. /* 16-bit length field */
  7529. header[1] = 126;
  7530. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7531. headerLen = 4;
  7532. } else {
  7533. /* 64-bit length field */
  7534. header[1] = 127;
  7535. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7536. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7537. headerLen = 10;
  7538. }
  7539. if (masking_key) {
  7540. /* add mask */
  7541. header[1] |= 0x80;
  7542. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7543. headerLen += 4;
  7544. }
  7545. /* Note that POSIX/Winsock's send() is threadsafe
  7546. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7547. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7548. * push(), although that is only a problem if the packet is large or
  7549. * outgoing buffer is full). */
  7550. (void)mg_lock_connection(conn);
  7551. retval = mg_write(conn, header, headerLen);
  7552. if (dataLen > 0) {
  7553. retval = mg_write(conn, data, dataLen);
  7554. }
  7555. mg_unlock_connection(conn);
  7556. return retval;
  7557. }
  7558. int
  7559. mg_websocket_write(struct mg_connection *conn,
  7560. int opcode,
  7561. const char *data,
  7562. size_t dataLen)
  7563. {
  7564. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7565. }
  7566. static void
  7567. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7568. {
  7569. size_t i = 0;
  7570. i = 0;
  7571. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7572. /* Convert in 32 bit words, if data is 4 byte aligned */
  7573. while (i < (in_len - 3)) {
  7574. *(uint32_t *)(void *)(out + i) =
  7575. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7576. i += 4;
  7577. }
  7578. }
  7579. if (i != in_len) {
  7580. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7581. while (i < in_len) {
  7582. *(uint8_t *)(void *)(out + i) =
  7583. *(uint8_t *)(void *)(in + i)
  7584. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7585. i++;
  7586. }
  7587. }
  7588. }
  7589. int
  7590. mg_websocket_client_write(struct mg_connection *conn,
  7591. int opcode,
  7592. const char *data,
  7593. size_t dataLen)
  7594. {
  7595. int retval = -1;
  7596. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7597. uint32_t masking_key = (uint32_t)get_random();
  7598. if (masked_data == NULL) {
  7599. /* Return -1 in an error case */
  7600. mg_cry(conn,
  7601. "Cannot allocate buffer for masked websocket response: "
  7602. "Out of memory");
  7603. return -1;
  7604. }
  7605. mask_data(data, dataLen, masking_key, masked_data);
  7606. retval = mg_websocket_write_exec(
  7607. conn, opcode, masked_data, dataLen, masking_key);
  7608. mg_free(masked_data);
  7609. return retval;
  7610. }
  7611. static void
  7612. handle_websocket_request(struct mg_connection *conn,
  7613. const char *path,
  7614. int is_callback_resource,
  7615. mg_websocket_connect_handler ws_connect_handler,
  7616. mg_websocket_ready_handler ws_ready_handler,
  7617. mg_websocket_data_handler ws_data_handler,
  7618. mg_websocket_close_handler ws_close_handler,
  7619. void *cbData)
  7620. {
  7621. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7622. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7623. int lua_websock = 0;
  7624. #if !defined(USE_LUA)
  7625. (void)path;
  7626. #endif
  7627. /* Step 1: Check websocket protocol version. */
  7628. /* Step 1.1: Check Sec-WebSocket-Key. */
  7629. if (!websock_key) {
  7630. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7631. * requires a Sec-WebSocket-Key header.
  7632. */
  7633. /* It could be the hixie draft version
  7634. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7635. */
  7636. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7637. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7638. char key3[8];
  7639. if ((key1 != NULL) && (key2 != NULL)) {
  7640. /* This version uses 8 byte body data in a GET request */
  7641. conn->content_len = 8;
  7642. if (8 == mg_read(conn, key3, 8)) {
  7643. /* This is the hixie version */
  7644. send_http_error(conn,
  7645. 426,
  7646. "%s",
  7647. "Protocol upgrade to RFC 6455 required");
  7648. return;
  7649. }
  7650. }
  7651. /* This is an unknown version */
  7652. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7653. return;
  7654. }
  7655. /* Step 1.2: Check websocket protocol version. */
  7656. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7657. if (version == NULL || strcmp(version, "13") != 0) {
  7658. /* Reject wrong versions */
  7659. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7660. return;
  7661. }
  7662. /* Step 1.3: Could check for "Host", but we do not really nead this
  7663. * value for anything, so just ignore it. */
  7664. /* Step 2: If a callback is responsible, call it. */
  7665. if (is_callback_resource) {
  7666. if (ws_connect_handler != NULL
  7667. && ws_connect_handler(conn, cbData) != 0) {
  7668. /* C callback has returned non-zero, do not proceed with
  7669. * handshake.
  7670. */
  7671. /* Note that C callbacks are no longer called when Lua is
  7672. * responsible, so C can no longer filter callbacks for Lua. */
  7673. return;
  7674. }
  7675. }
  7676. #if defined(USE_LUA)
  7677. /* Step 3: No callback. Check if Lua is responsible. */
  7678. else {
  7679. /* Step 3.1: Check if Lua is responsible. */
  7680. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7681. lua_websock =
  7682. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7683. strlen(
  7684. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7685. path);
  7686. }
  7687. if (lua_websock) {
  7688. /* Step 3.2: Lua is responsible: call it. */
  7689. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7690. if (!conn->lua_websocket_state) {
  7691. /* Lua rejected the new client */
  7692. return;
  7693. }
  7694. }
  7695. }
  7696. #endif
  7697. /* Step 4: Check if there is a responsible websocket handler. */
  7698. if (!is_callback_resource && !lua_websock) {
  7699. /* There is no callback, an Lua is not responsible either. */
  7700. /* Reply with a 404 Not Found or with nothing at all?
  7701. * TODO (mid): check the websocket standards, how to reply to
  7702. * requests to invalid websocket addresses. */
  7703. send_http_error(conn, 404, "%s", "Not found");
  7704. return;
  7705. }
  7706. /* Step 5: The websocket connection has been accepted */
  7707. if (!send_websocket_handshake(conn, websock_key)) {
  7708. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7709. return;
  7710. }
  7711. /* Step 6: Call the ready handler */
  7712. if (is_callback_resource) {
  7713. if (ws_ready_handler != NULL) {
  7714. ws_ready_handler(conn, cbData);
  7715. }
  7716. #if defined(USE_LUA)
  7717. } else if (lua_websock) {
  7718. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7719. /* the ready handler returned false */
  7720. return;
  7721. }
  7722. #endif
  7723. }
  7724. /* Step 7: Enter the read loop */
  7725. if (is_callback_resource) {
  7726. read_websocket(conn, ws_data_handler, cbData);
  7727. #if defined(USE_LUA)
  7728. } else if (lua_websock) {
  7729. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7730. #endif
  7731. }
  7732. /* Step 8: Call the close handler */
  7733. if (ws_close_handler) {
  7734. ws_close_handler(conn, cbData);
  7735. }
  7736. }
  7737. static int
  7738. is_websocket_protocol(const struct mg_connection *conn)
  7739. {
  7740. const char *upgrade, *connection;
  7741. /* A websocket protocoll has the following HTTP headers:
  7742. *
  7743. * Connection: Upgrade
  7744. * Upgrade: Websocket
  7745. */
  7746. upgrade = mg_get_header(conn, "Upgrade");
  7747. if (upgrade == NULL) {
  7748. return 0; /* fail early, don't waste time checking other header
  7749. * fields
  7750. */
  7751. }
  7752. if (!mg_strcasestr(upgrade, "websocket")) {
  7753. return 0;
  7754. }
  7755. connection = mg_get_header(conn, "Connection");
  7756. if (connection == NULL) {
  7757. return 0;
  7758. }
  7759. if (!mg_strcasestr(connection, "upgrade")) {
  7760. return 0;
  7761. }
  7762. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  7763. * "Sec-WebSocket-Version" are also required.
  7764. * Don't check them here, since even an unsupported websocket protocol
  7765. * request still IS a websocket request (in contrast to a standard HTTP
  7766. * request). It will fail later in handle_websocket_request.
  7767. */
  7768. return 1;
  7769. }
  7770. #endif /* !USE_WEBSOCKET */
  7771. static int
  7772. isbyte(int n)
  7773. {
  7774. return n >= 0 && n <= 255;
  7775. }
  7776. static int
  7777. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7778. {
  7779. int n, a, b, c, d, slash = 32, len = 0;
  7780. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7781. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7782. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7783. && slash < 33) {
  7784. len = n;
  7785. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7786. | (uint32_t)d;
  7787. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7788. }
  7789. return len;
  7790. }
  7791. static int
  7792. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7793. {
  7794. int throttle = 0;
  7795. struct vec vec, val;
  7796. uint32_t net, mask;
  7797. char mult;
  7798. double v;
  7799. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7800. mult = ',';
  7801. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7802. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7803. && mult != ',')) {
  7804. continue;
  7805. }
  7806. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7807. : 1;
  7808. if (vec.len == 1 && vec.ptr[0] == '*') {
  7809. throttle = (int)v;
  7810. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7811. if ((remote_ip & mask) == net) {
  7812. throttle = (int)v;
  7813. }
  7814. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7815. throttle = (int)v;
  7816. }
  7817. }
  7818. return throttle;
  7819. }
  7820. static uint32_t
  7821. get_remote_ip(const struct mg_connection *conn)
  7822. {
  7823. if (!conn) {
  7824. return 0;
  7825. }
  7826. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7827. }
  7828. /* Experimental replacement for mg_upload. */
  7829. #include "handle_form.inl"
  7830. /* Replacement for mg_upload (Note: mg_upload is deprecated) */
  7831. struct mg_upload_user_data {
  7832. struct mg_connection *conn;
  7833. const char *destination_dir;
  7834. int num_uploaded_files;
  7835. };
  7836. /* Helper function for deprecated mg_upload. */
  7837. static int
  7838. mg_upload_field_found(const char *key,
  7839. const char *filename,
  7840. char *path,
  7841. size_t pathlen,
  7842. void *user_data)
  7843. {
  7844. int truncated = 0;
  7845. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7846. (void)key;
  7847. if (!filename) {
  7848. mg_cry(fud->conn, "%s: No filename set", __func__);
  7849. return FORM_FIELD_STORAGE_ABORT;
  7850. }
  7851. mg_snprintf(fud->conn,
  7852. &truncated,
  7853. path,
  7854. pathlen - 1,
  7855. "%s/%s",
  7856. fud->destination_dir,
  7857. filename);
  7858. if (!truncated) {
  7859. mg_cry(fud->conn, "%s: File path too long", __func__);
  7860. return FORM_FIELD_STORAGE_ABORT;
  7861. }
  7862. return FORM_FIELD_STORAGE_STORE;
  7863. }
  7864. /* Helper function for deprecated mg_upload. */
  7865. static int
  7866. mg_upload_field_get(const char *key,
  7867. const char *value,
  7868. size_t value_size,
  7869. void *user_data)
  7870. {
  7871. /* Function should never be called */
  7872. (void)key;
  7873. (void)value;
  7874. (void)value_size;
  7875. (void)user_data;
  7876. return 0;
  7877. }
  7878. /* Helper function for deprecated mg_upload. */
  7879. static int
  7880. mg_upload_field_stored(const char *path, size_t file_size, void *user_data)
  7881. {
  7882. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7883. (void)file_size;
  7884. fud->num_uploaded_files++;
  7885. fud->conn->ctx->callbacks.upload(fud->conn, path);
  7886. return 0;
  7887. }
  7888. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  7889. int
  7890. mg_upload(struct mg_connection *conn, const char *destination_dir)
  7891. {
  7892. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  7893. struct mg_form_data_handler fdh = {mg_upload_field_found,
  7894. mg_upload_field_get,
  7895. mg_upload_field_stored,
  7896. 0};
  7897. int ret;
  7898. fdh.user_data = (void *)&fud;
  7899. ret = mg_handle_form_request(conn, &fdh);
  7900. if (ret < 0) {
  7901. mg_cry(conn, "%s: Error while parsing the request", __func__);
  7902. }
  7903. return fud.num_uploaded_files;
  7904. }
  7905. static int
  7906. get_first_ssl_listener_index(const struct mg_context *ctx)
  7907. {
  7908. unsigned int i;
  7909. int idx = -1;
  7910. if (ctx) {
  7911. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7912. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7913. }
  7914. }
  7915. return idx;
  7916. }
  7917. static void
  7918. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7919. {
  7920. char host[1025];
  7921. const char *host_header;
  7922. size_t hostlen;
  7923. host_header = mg_get_header(conn, "Host");
  7924. hostlen = sizeof(host);
  7925. if (host_header != NULL) {
  7926. char *pos;
  7927. mg_strlcpy(host, host_header, hostlen);
  7928. host[hostlen - 1] = '\0';
  7929. pos = strchr(host, ':');
  7930. if (pos != NULL) {
  7931. *pos = '\0';
  7932. }
  7933. } else {
  7934. /* Cannot get host from the Host: header.
  7935. * Fallback to our IP address. */
  7936. if (conn) {
  7937. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7938. }
  7939. }
  7940. /* Send host, port, uri and (if it exists) ?query_string */
  7941. if (conn) {
  7942. mg_printf(conn,
  7943. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7944. host,
  7945. (int)ntohs(
  7946. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7947. conn->request_info.local_uri,
  7948. (conn->request_info.query_string == NULL) ? "" : "?",
  7949. (conn->request_info.query_string == NULL)
  7950. ? ""
  7951. : conn->request_info.query_string);
  7952. }
  7953. }
  7954. static void
  7955. mg_set_handler_type(struct mg_context *ctx,
  7956. const char *uri,
  7957. int handler_type,
  7958. int is_delete_request,
  7959. mg_request_handler handler,
  7960. mg_websocket_connect_handler connect_handler,
  7961. mg_websocket_ready_handler ready_handler,
  7962. mg_websocket_data_handler data_handler,
  7963. mg_websocket_close_handler close_handler,
  7964. mg_authorization_handler auth_handler,
  7965. void *cbdata)
  7966. {
  7967. struct mg_handler_info *tmp_rh, **lastref;
  7968. size_t urilen = strlen(uri);
  7969. if (handler_type == WEBSOCKET_HANDLER) {
  7970. /* assert(handler == NULL); */
  7971. /* assert(is_delete_request || connect_handler!=NULL ||
  7972. * ready_handler!=NULL || data_handler!=NULL ||
  7973. * close_handler!=NULL);
  7974. */
  7975. /* assert(auth_handler == NULL); */
  7976. if (handler != NULL) {
  7977. return;
  7978. }
  7979. if (!is_delete_request && connect_handler == NULL
  7980. && ready_handler == NULL
  7981. && data_handler == NULL
  7982. && close_handler == NULL) {
  7983. return;
  7984. }
  7985. if (auth_handler != NULL) {
  7986. return;
  7987. }
  7988. } else if (handler_type == REQUEST_HANDLER) {
  7989. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7990. * data_handler==NULL && close_handler==NULL); */
  7991. /* assert(is_delete_request || (handler!=NULL));
  7992. */
  7993. /* assert(auth_handler == NULL); */
  7994. if (connect_handler != NULL || ready_handler != NULL
  7995. || data_handler != NULL
  7996. || close_handler != NULL) {
  7997. return;
  7998. }
  7999. if (!is_delete_request && (handler == NULL)) {
  8000. return;
  8001. }
  8002. if (auth_handler != NULL) {
  8003. return;
  8004. }
  8005. } else { /* AUTH_HANDLER */
  8006. /* assert(handler == NULL); */
  8007. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8008. * data_handler==NULL && close_handler==NULL); */
  8009. /* assert(auth_handler != NULL); */
  8010. if (handler != NULL) {
  8011. return;
  8012. }
  8013. if (connect_handler != NULL || ready_handler != NULL
  8014. || data_handler != NULL
  8015. || close_handler != NULL) {
  8016. return;
  8017. }
  8018. if (!is_delete_request && (auth_handler == NULL)) {
  8019. return;
  8020. }
  8021. }
  8022. if (!ctx) {
  8023. return;
  8024. }
  8025. mg_lock_context(ctx);
  8026. /* first try to find an existing handler */
  8027. lastref = &(ctx->handlers);
  8028. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8029. if (tmp_rh->handler_type == handler_type) {
  8030. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8031. if (!is_delete_request) {
  8032. /* update existing handler */
  8033. if (handler_type == REQUEST_HANDLER) {
  8034. tmp_rh->handler = handler;
  8035. } else if (handler_type == WEBSOCKET_HANDLER) {
  8036. tmp_rh->connect_handler = connect_handler;
  8037. tmp_rh->ready_handler = ready_handler;
  8038. tmp_rh->data_handler = data_handler;
  8039. tmp_rh->close_handler = close_handler;
  8040. } else { /* AUTH_HANDLER */
  8041. tmp_rh->auth_handler = auth_handler;
  8042. }
  8043. tmp_rh->cbdata = cbdata;
  8044. } else {
  8045. /* remove existing handler */
  8046. *lastref = tmp_rh->next;
  8047. mg_free(tmp_rh->uri);
  8048. mg_free(tmp_rh);
  8049. }
  8050. mg_unlock_context(ctx);
  8051. return;
  8052. }
  8053. }
  8054. lastref = &(tmp_rh->next);
  8055. }
  8056. if (is_delete_request) {
  8057. /* no handler to set, this was a remove request to a non-existing
  8058. * handler */
  8059. mg_unlock_context(ctx);
  8060. return;
  8061. }
  8062. tmp_rh =
  8063. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8064. if (tmp_rh == NULL) {
  8065. mg_unlock_context(ctx);
  8066. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8067. return;
  8068. }
  8069. tmp_rh->uri = mg_strdup(uri);
  8070. if (!tmp_rh->uri) {
  8071. mg_unlock_context(ctx);
  8072. mg_free(tmp_rh);
  8073. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8074. return;
  8075. }
  8076. tmp_rh->uri_len = urilen;
  8077. if (handler_type == REQUEST_HANDLER) {
  8078. tmp_rh->handler = handler;
  8079. } else if (handler_type == WEBSOCKET_HANDLER) {
  8080. tmp_rh->connect_handler = connect_handler;
  8081. tmp_rh->ready_handler = ready_handler;
  8082. tmp_rh->data_handler = data_handler;
  8083. tmp_rh->close_handler = close_handler;
  8084. } else { /* AUTH_HANDLER */
  8085. tmp_rh->auth_handler = auth_handler;
  8086. }
  8087. tmp_rh->cbdata = cbdata;
  8088. tmp_rh->handler_type = handler_type;
  8089. tmp_rh->next = NULL;
  8090. *lastref = tmp_rh;
  8091. mg_unlock_context(ctx);
  8092. }
  8093. void
  8094. mg_set_request_handler(struct mg_context *ctx,
  8095. const char *uri,
  8096. mg_request_handler handler,
  8097. void *cbdata)
  8098. {
  8099. mg_set_handler_type(ctx,
  8100. uri,
  8101. REQUEST_HANDLER,
  8102. handler == NULL,
  8103. handler,
  8104. NULL,
  8105. NULL,
  8106. NULL,
  8107. NULL,
  8108. NULL,
  8109. cbdata);
  8110. }
  8111. void
  8112. mg_set_websocket_handler(struct mg_context *ctx,
  8113. const char *uri,
  8114. mg_websocket_connect_handler connect_handler,
  8115. mg_websocket_ready_handler ready_handler,
  8116. mg_websocket_data_handler data_handler,
  8117. mg_websocket_close_handler close_handler,
  8118. void *cbdata)
  8119. {
  8120. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8121. && (data_handler == NULL)
  8122. && (close_handler == NULL);
  8123. mg_set_handler_type(ctx,
  8124. uri,
  8125. WEBSOCKET_HANDLER,
  8126. is_delete_request,
  8127. NULL,
  8128. connect_handler,
  8129. ready_handler,
  8130. data_handler,
  8131. close_handler,
  8132. NULL,
  8133. cbdata);
  8134. }
  8135. void
  8136. mg_set_auth_handler(struct mg_context *ctx,
  8137. const char *uri,
  8138. mg_request_handler handler,
  8139. void *cbdata)
  8140. {
  8141. mg_set_handler_type(ctx,
  8142. uri,
  8143. AUTH_HANDLER,
  8144. handler == NULL,
  8145. NULL,
  8146. NULL,
  8147. NULL,
  8148. NULL,
  8149. NULL,
  8150. handler,
  8151. cbdata);
  8152. }
  8153. static int
  8154. get_request_handler(struct mg_connection *conn,
  8155. int handler_type,
  8156. mg_request_handler *handler,
  8157. mg_websocket_connect_handler *connect_handler,
  8158. mg_websocket_ready_handler *ready_handler,
  8159. mg_websocket_data_handler *data_handler,
  8160. mg_websocket_close_handler *close_handler,
  8161. mg_authorization_handler *auth_handler,
  8162. void **cbdata)
  8163. {
  8164. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8165. if (request_info) {
  8166. const char *uri = request_info->local_uri;
  8167. size_t urilen = strlen(uri);
  8168. struct mg_handler_info *tmp_rh;
  8169. if (!conn || !conn->ctx) {
  8170. return 0;
  8171. }
  8172. mg_lock_context(conn->ctx);
  8173. /* first try for an exact match */
  8174. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8175. tmp_rh = tmp_rh->next) {
  8176. if (tmp_rh->handler_type == handler_type) {
  8177. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8178. if (handler_type == WEBSOCKET_HANDLER) {
  8179. *connect_handler = tmp_rh->connect_handler;
  8180. *ready_handler = tmp_rh->ready_handler;
  8181. *data_handler = tmp_rh->data_handler;
  8182. *close_handler = tmp_rh->close_handler;
  8183. } else if (handler_type == REQUEST_HANDLER) {
  8184. *handler = tmp_rh->handler;
  8185. } else { /* AUTH_HANDLER */
  8186. *auth_handler = tmp_rh->auth_handler;
  8187. }
  8188. *cbdata = tmp_rh->cbdata;
  8189. mg_unlock_context(conn->ctx);
  8190. return 1;
  8191. }
  8192. }
  8193. }
  8194. /* next try for a partial match, we will accept uri/something */
  8195. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8196. tmp_rh = tmp_rh->next) {
  8197. if (tmp_rh->handler_type == handler_type) {
  8198. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8199. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8200. if (handler_type == WEBSOCKET_HANDLER) {
  8201. *connect_handler = tmp_rh->connect_handler;
  8202. *ready_handler = tmp_rh->ready_handler;
  8203. *data_handler = tmp_rh->data_handler;
  8204. *close_handler = tmp_rh->close_handler;
  8205. } else if (handler_type == REQUEST_HANDLER) {
  8206. *handler = tmp_rh->handler;
  8207. } else { /* AUTH_HANDLER */
  8208. *auth_handler = tmp_rh->auth_handler;
  8209. }
  8210. *cbdata = tmp_rh->cbdata;
  8211. mg_unlock_context(conn->ctx);
  8212. return 1;
  8213. }
  8214. }
  8215. }
  8216. /* finally try for pattern match */
  8217. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8218. tmp_rh = tmp_rh->next) {
  8219. if (tmp_rh->handler_type == handler_type) {
  8220. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8221. if (handler_type == WEBSOCKET_HANDLER) {
  8222. *connect_handler = tmp_rh->connect_handler;
  8223. *ready_handler = tmp_rh->ready_handler;
  8224. *data_handler = tmp_rh->data_handler;
  8225. *close_handler = tmp_rh->close_handler;
  8226. } else if (handler_type == REQUEST_HANDLER) {
  8227. *handler = tmp_rh->handler;
  8228. } else { /* AUTH_HANDLER */
  8229. *auth_handler = tmp_rh->auth_handler;
  8230. }
  8231. *cbdata = tmp_rh->cbdata;
  8232. mg_unlock_context(conn->ctx);
  8233. return 1;
  8234. }
  8235. }
  8236. }
  8237. mg_unlock_context(conn->ctx);
  8238. }
  8239. return 0; /* none found */
  8240. }
  8241. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8242. static int
  8243. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8244. void *cbdata)
  8245. {
  8246. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8247. if (pcallbacks->websocket_connect) {
  8248. return pcallbacks->websocket_connect(conn);
  8249. }
  8250. /* No handler set - assume "OK" */
  8251. return 0;
  8252. }
  8253. static void
  8254. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8255. {
  8256. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8257. if (pcallbacks->websocket_ready) {
  8258. pcallbacks->websocket_ready(conn);
  8259. }
  8260. }
  8261. static int
  8262. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8263. int bits,
  8264. char *data,
  8265. size_t len,
  8266. void *cbdata)
  8267. {
  8268. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8269. if (pcallbacks->websocket_data) {
  8270. return pcallbacks->websocket_data(conn, bits, data, len);
  8271. }
  8272. /* No handler set - assume "OK" */
  8273. return 1;
  8274. }
  8275. #endif
  8276. /* This is the heart of the Civetweb's logic.
  8277. * This function is called when the request is read, parsed and validated,
  8278. * and Civetweb must decide what action to take: serve a file, or
  8279. * a directory, or call embedded function, etcetera. */
  8280. static void
  8281. handle_request(struct mg_connection *conn)
  8282. {
  8283. if (conn) {
  8284. struct mg_request_info *ri = &conn->request_info;
  8285. char path[PATH_MAX];
  8286. int uri_len, ssl_index;
  8287. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8288. is_put_or_delete_request = 0, is_callback_resource = 0;
  8289. int i;
  8290. struct file file = STRUCT_FILE_INITIALIZER;
  8291. mg_request_handler callback_handler = NULL;
  8292. mg_websocket_connect_handler ws_connect_handler = NULL;
  8293. mg_websocket_ready_handler ws_ready_handler = NULL;
  8294. mg_websocket_data_handler ws_data_handler = NULL;
  8295. mg_websocket_close_handler ws_close_handler = NULL;
  8296. void *callback_data = NULL;
  8297. mg_authorization_handler auth_handler = NULL;
  8298. void *auth_callback_data = NULL;
  8299. #if !defined(NO_FILES)
  8300. time_t curtime = time(NULL);
  8301. char date[64];
  8302. #endif
  8303. path[0] = 0;
  8304. if (!ri) {
  8305. return;
  8306. }
  8307. /* 1. get the request url */
  8308. /* 1.1. split into url and query string */
  8309. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8310. != NULL) {
  8311. *((char *)conn->request_info.query_string++) = '\0';
  8312. }
  8313. uri_len = (int)strlen(ri->local_uri);
  8314. /* 1.2. decode url (if config says so) */
  8315. if (should_decode_url(conn)) {
  8316. mg_url_decode(
  8317. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8318. }
  8319. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is
  8320. * not
  8321. * possible */
  8322. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8323. /* step 1. completed, the url is known now */
  8324. DEBUG_TRACE("URL: %s", ri->local_uri);
  8325. /* 2. do a https redirect, if required */
  8326. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8327. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8328. if (ssl_index >= 0) {
  8329. redirect_to_https_port(conn, ssl_index);
  8330. } else {
  8331. /* A http to https forward port has been specified,
  8332. * but no https port to forward to. */
  8333. send_http_error(conn,
  8334. 503,
  8335. "%s",
  8336. "Error: SSL forward not configured properly");
  8337. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8338. }
  8339. return;
  8340. }
  8341. /* 3. if this ip has limited speed, set it for this connection */
  8342. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8343. get_remote_ip(conn),
  8344. ri->local_uri);
  8345. /* 4. call a "handle everything" callback, if registered */
  8346. if (conn->ctx->callbacks.begin_request != NULL) {
  8347. /* Note that since V1.7 the "begin_request" function is called
  8348. * before an authorization check. If an authorization check is
  8349. * required, use a request_handler instead. */
  8350. i = conn->ctx->callbacks.begin_request(conn);
  8351. if (i > 0) {
  8352. /* callback already processed the request. Store the
  8353. return value as a status code for the access log. */
  8354. conn->status_code = i;
  8355. return;
  8356. } else if (i == 0) {
  8357. /* civetweb should process the request */
  8358. } else {
  8359. /* unspecified - may change with the next version */
  8360. return;
  8361. }
  8362. }
  8363. /* request not yet handled by a handler or redirect, so the request
  8364. * is processed here */
  8365. /* 5. interpret the url to find out how the request must be handled
  8366. */
  8367. /* 5.1. first test, if the request targets the regular http(s)://
  8368. * protocol namespace or the websocket ws(s):// protocol namespace.
  8369. */
  8370. is_websocket_request = is_websocket_protocol(conn);
  8371. /* 5.2. check if the request will be handled by a callback */
  8372. if (get_request_handler(conn,
  8373. is_websocket_request ? WEBSOCKET_HANDLER
  8374. : REQUEST_HANDLER,
  8375. &callback_handler,
  8376. &ws_connect_handler,
  8377. &ws_ready_handler,
  8378. &ws_data_handler,
  8379. &ws_close_handler,
  8380. NULL,
  8381. &callback_data)) {
  8382. /* 5.2.1. A callback will handle this request. All requests
  8383. * handled
  8384. * by a callback have to be considered as requests to a script
  8385. * resource. */
  8386. is_callback_resource = 1;
  8387. is_script_resource = 1;
  8388. is_put_or_delete_request = is_put_or_delete_method(conn);
  8389. } else {
  8390. no_callback_resource:
  8391. /* 5.2.2. No callback is responsible for this request. The URI
  8392. * addresses a file based resource (static content or Lua/cgi
  8393. * scripts in the file system). */
  8394. is_callback_resource = 0;
  8395. interpret_uri(conn,
  8396. path,
  8397. sizeof(path),
  8398. &file,
  8399. &is_found,
  8400. &is_script_resource,
  8401. &is_websocket_request,
  8402. &is_put_or_delete_request);
  8403. }
  8404. /* 6. authorization check */
  8405. /* 6.1. a custom authorization handler is installed */
  8406. if (get_request_handler(conn,
  8407. AUTH_HANDLER,
  8408. NULL,
  8409. NULL,
  8410. NULL,
  8411. NULL,
  8412. NULL,
  8413. &auth_handler,
  8414. &auth_callback_data)) {
  8415. if (!auth_handler(conn, auth_callback_data)) {
  8416. return;
  8417. }
  8418. } else if (is_put_or_delete_request && !is_script_resource
  8419. && !is_callback_resource) {
  8420. /* 6.2. this request is a PUT/DELETE to a real file */
  8421. /* 6.2.1. thus, the server must have real files */
  8422. #if defined(NO_FILES)
  8423. if (1) {
  8424. #else
  8425. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8426. #endif
  8427. /* This server does not have any real files, thus the
  8428. * PUT/DELETE methods are not valid. */
  8429. send_http_error(conn,
  8430. 405,
  8431. "%s method not allowed",
  8432. conn->request_info.request_method);
  8433. return;
  8434. }
  8435. #if !defined(NO_FILES)
  8436. /* 6.2.2. Check if put authorization for static files is available.
  8437. */
  8438. if (!is_authorized_for_put(conn)) {
  8439. send_authorization_request(conn);
  8440. return;
  8441. }
  8442. #endif
  8443. } else {
  8444. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8445. * or it is a PUT or DELETE request to a resource that does not
  8446. * correspond to a file. Check authorization. */
  8447. if (!check_authorization(conn, path)) {
  8448. send_authorization_request(conn);
  8449. return;
  8450. }
  8451. }
  8452. /* request is authorized or does not need authorization */
  8453. /* 7. check if there are request handlers for this uri */
  8454. if (is_callback_resource) {
  8455. if (!is_websocket_request) {
  8456. i = callback_handler(conn, callback_data);
  8457. if (i > 0) {
  8458. /* Do nothing, callback has served the request. Store
  8459. * the
  8460. * return value as status code for the log and discard
  8461. * all
  8462. * data from the client not used by the callback. */
  8463. conn->status_code = i;
  8464. discard_unread_request_data(conn);
  8465. } else {
  8466. /* TODO (high): what if the handler did NOT handle the
  8467. * request */
  8468. /* The last version did handle this as a file request,
  8469. * but
  8470. * since a file request is not always a script resource,
  8471. * the authorization check might be different */
  8472. interpret_uri(conn,
  8473. path,
  8474. sizeof(path),
  8475. &file,
  8476. &is_found,
  8477. &is_script_resource,
  8478. &is_websocket_request,
  8479. &is_put_or_delete_request);
  8480. callback_handler = NULL;
  8481. /* TODO (very low): goto is deprecated but for the
  8482. * moment,
  8483. * a goto is simpler than some curious loop. */
  8484. /* The situation "callback does not handle the request"
  8485. * needs to be reconsidered anyway. */
  8486. goto no_callback_resource;
  8487. }
  8488. } else {
  8489. #if defined(USE_WEBSOCKET)
  8490. handle_websocket_request(conn,
  8491. path,
  8492. is_callback_resource,
  8493. ws_connect_handler,
  8494. ws_ready_handler,
  8495. ws_data_handler,
  8496. ws_close_handler,
  8497. callback_data);
  8498. #endif
  8499. }
  8500. return;
  8501. }
  8502. /* 8. handle websocket requests */
  8503. #if defined(USE_WEBSOCKET)
  8504. if (is_websocket_request) {
  8505. if (is_script_resource) {
  8506. /* Websocket Lua script */
  8507. handle_websocket_request(conn,
  8508. path,
  8509. 0 /* Lua Script */,
  8510. NULL,
  8511. NULL,
  8512. NULL,
  8513. NULL,
  8514. &conn->ctx->callbacks);
  8515. } else {
  8516. #if defined(MG_LEGACY_INTERFACE)
  8517. handle_websocket_request(
  8518. conn,
  8519. path,
  8520. !is_script_resource /* could be deprecated global callback */,
  8521. deprecated_websocket_connect_wrapper,
  8522. deprecated_websocket_ready_wrapper,
  8523. deprecated_websocket_data_wrapper,
  8524. NULL,
  8525. &conn->ctx->callbacks);
  8526. #else
  8527. send_http_error(conn, 404, "%s", "Not found");
  8528. #endif
  8529. }
  8530. return;
  8531. } else
  8532. #endif
  8533. #if defined(NO_FILES)
  8534. /* 9a. In case the server uses only callbacks, this uri is
  8535. * unknown.
  8536. * Then, all request handling ends here. */
  8537. send_http_error(conn, 404, "%s", "Not Found");
  8538. #else
  8539. /* 9b. This request is either for a static file or resource handled
  8540. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8541. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8542. send_http_error(conn, 404, "%s", "Not Found");
  8543. return;
  8544. }
  8545. /* 10. File is handled by a script. */
  8546. if (is_script_resource) {
  8547. handle_file_based_request(conn, path, &file);
  8548. return;
  8549. }
  8550. /* 11. Handle put/delete/mkcol requests */
  8551. if (is_put_or_delete_request) {
  8552. /* 11.1. PUT method */
  8553. if (!strcmp(ri->request_method, "PUT")) {
  8554. put_file(conn, path);
  8555. return;
  8556. }
  8557. /* 11.2. DELETE method */
  8558. if (!strcmp(ri->request_method, "DELETE")) {
  8559. delete_file(conn, path);
  8560. return;
  8561. }
  8562. /* 11.3. MKCOL method */
  8563. if (!strcmp(ri->request_method, "MKCOL")) {
  8564. mkcol(conn, path);
  8565. return;
  8566. }
  8567. /* 11.4. PATCH method
  8568. * This method is not supported for static resources,
  8569. * only for scripts (Lua, CGI) and callbacks. */
  8570. send_http_error(conn,
  8571. 405,
  8572. "%s method not allowed",
  8573. conn->request_info.request_method);
  8574. return;
  8575. }
  8576. /* 11. File does not exist, or it was configured that it should be
  8577. * hidden */
  8578. if (!is_found || (must_hide_file(conn, path))) {
  8579. send_http_error(conn, 404, "%s", "Not found");
  8580. return;
  8581. }
  8582. /* 12. Directory uris should end with a slash */
  8583. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8584. gmt_time_string(date, sizeof(date), &curtime);
  8585. mg_printf(conn,
  8586. "HTTP/1.1 301 Moved Permanently\r\n"
  8587. "Location: %s/\r\n"
  8588. "Date: %s\r\n"
  8589. /* "Cache-Control: private\r\n" (= default) */
  8590. "Content-Length: 0\r\n"
  8591. "Connection: %s\r\n\r\n",
  8592. ri->request_uri,
  8593. date,
  8594. suggest_connection_header(conn));
  8595. return;
  8596. }
  8597. /* 13. Handle other methods than GET/HEAD */
  8598. /* 13.1. Handle PROPFIND */
  8599. if (!strcmp(ri->request_method, "PROPFIND")) {
  8600. handle_propfind(conn, path, &file);
  8601. return;
  8602. }
  8603. /* 13.2. Handle OPTIONS for files */
  8604. if (!strcmp(ri->request_method, "OPTIONS")) {
  8605. /* This standard handler is only used for real files.
  8606. * Scripts should support the OPTIONS method themselves, to allow a
  8607. * maximum flexibility.
  8608. * Lua and CGI scripts may fully support CORS this way (including
  8609. * preflights). */
  8610. send_options(conn);
  8611. return;
  8612. }
  8613. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8614. if (0 != strcmp(ri->request_method, "GET")
  8615. && 0 != strcmp(ri->request_method, "HEAD")) {
  8616. send_http_error(conn,
  8617. 405,
  8618. "%s method not allowed",
  8619. conn->request_info.request_method);
  8620. return;
  8621. }
  8622. /* 14. directories */
  8623. if (file.is_directory) {
  8624. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8625. /* 14.1. use a substitute file */
  8626. /* TODO (high): substitute index may be a script resource.
  8627. * define what should be possible in this case. */
  8628. } else {
  8629. /* 14.2. no substitute file */
  8630. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8631. "yes")) {
  8632. handle_directory_request(conn, path);
  8633. } else {
  8634. send_http_error(conn,
  8635. 403,
  8636. "%s",
  8637. "Error: Directory listing denied");
  8638. }
  8639. return;
  8640. }
  8641. }
  8642. handle_file_based_request(conn, path, &file);
  8643. #endif /* !defined(NO_FILES) */
  8644. #if 0
  8645. /* Perform redirect and auth checks before calling begin_request()
  8646. * handler.
  8647. * Otherwise, begin_request() would need to perform auth checks and
  8648. * redirects. */
  8649. #endif
  8650. }
  8651. return;
  8652. }
  8653. static void
  8654. handle_file_based_request(struct mg_connection *conn,
  8655. const char *path,
  8656. struct file *file)
  8657. {
  8658. if (!conn || !conn->ctx) {
  8659. return;
  8660. }
  8661. if (0) {
  8662. #ifdef USE_LUA
  8663. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8664. strlen(
  8665. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8666. path) > 0) {
  8667. /* Lua server page: an SSI like page containing mostly plain html
  8668. * code
  8669. * plus some tags with server generated contents. */
  8670. handle_lsp_request(conn, path, file, NULL);
  8671. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8672. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8673. path) > 0) {
  8674. /* Lua in-server module script: a CGI like script used to generate
  8675. * the
  8676. * entire reply. */
  8677. mg_exec_lua_script(conn, path, NULL);
  8678. #endif
  8679. #if defined(USE_DUKTAPE)
  8680. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8681. strlen(
  8682. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8683. path) > 0) {
  8684. /* Call duktape to generate the page */
  8685. mg_exec_duktape_script(conn, path);
  8686. #endif
  8687. #if !defined(NO_CGI)
  8688. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8689. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8690. path) > 0) {
  8691. /* CGI scripts may support all HTTP methods */
  8692. handle_cgi_request(conn, path);
  8693. #endif /* !NO_CGI */
  8694. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8695. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8696. path) > 0) {
  8697. handle_ssi_file_request(conn, path, file);
  8698. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8699. /* Send 304 "Not Modified" - this must not send any body data */
  8700. send_http_error(conn, 304, "%s", "");
  8701. } else {
  8702. handle_static_file_request(conn, path, file, NULL);
  8703. }
  8704. }
  8705. static void
  8706. close_all_listening_sockets(struct mg_context *ctx)
  8707. {
  8708. unsigned int i;
  8709. if (!ctx) {
  8710. return;
  8711. }
  8712. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8713. closesocket(ctx->listening_sockets[i].sock);
  8714. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8715. }
  8716. mg_free(ctx->listening_sockets);
  8717. ctx->listening_sockets = NULL;
  8718. mg_free(ctx->listening_ports);
  8719. ctx->listening_ports = NULL;
  8720. }
  8721. /* Valid listening port specification is: [ip_address:]port[s]
  8722. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8723. * Examples for IPv6: [::]:80, [::1]:80,
  8724. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8725. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8726. static int
  8727. parse_port_string(const struct vec *vec, struct socket *so)
  8728. {
  8729. unsigned int a, b, c, d, port;
  8730. int ch, len;
  8731. #if defined(USE_IPV6)
  8732. char buf[100] = {0};
  8733. #endif
  8734. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8735. * Also, all-zeroes in the socket address means binding to all addresses
  8736. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8737. memset(so, 0, sizeof(*so));
  8738. so->lsa.sin.sin_family = AF_INET;
  8739. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8740. == 5) {
  8741. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8742. so->lsa.sin.sin_addr.s_addr =
  8743. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8744. so->lsa.sin.sin_port = htons((uint16_t)port);
  8745. #if defined(USE_IPV6)
  8746. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8747. && mg_inet_pton(
  8748. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8749. /* IPv6 address, examples: see above */
  8750. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8751. */
  8752. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8753. #endif
  8754. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8755. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8756. so->lsa.sin.sin_port = htons((uint16_t)port);
  8757. } else {
  8758. /* Parsing failure. Make port invalid. */
  8759. port = 0;
  8760. len = 0;
  8761. }
  8762. /* sscanf and the option splitting code ensure the following condition
  8763. */
  8764. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8765. return 0;
  8766. }
  8767. ch = vec->ptr[len]; /* Next character after the port number */
  8768. so->is_ssl = (ch == 's');
  8769. so->ssl_redir = (ch == 'r');
  8770. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8771. return is_valid_port(port)
  8772. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8773. }
  8774. static int
  8775. set_ports_option(struct mg_context *ctx)
  8776. {
  8777. const char *list;
  8778. int on = 1;
  8779. #if defined(USE_IPV6)
  8780. int off = 0;
  8781. #endif
  8782. struct vec vec;
  8783. struct socket so, *ptr;
  8784. in_port_t *portPtr;
  8785. union usa usa;
  8786. socklen_t len;
  8787. int portsTotal = 0;
  8788. int portsOk = 0;
  8789. if (!ctx) {
  8790. return 0;
  8791. }
  8792. memset(&so, 0, sizeof(so));
  8793. memset(&usa, 0, sizeof(usa));
  8794. len = sizeof(usa);
  8795. list = ctx->config[LISTENING_PORTS];
  8796. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8797. portsTotal++;
  8798. if (!parse_port_string(&vec, &so)) {
  8799. mg_cry(fc(ctx),
  8800. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8801. (int)vec.len,
  8802. vec.ptr,
  8803. portsTotal,
  8804. "[IP_ADDRESS:]PORT[s|r]");
  8805. continue;
  8806. }
  8807. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8808. mg_cry(fc(ctx),
  8809. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8810. "option set?",
  8811. portsTotal);
  8812. continue;
  8813. }
  8814. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8815. == INVALID_SOCKET) {
  8816. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8817. continue;
  8818. }
  8819. #ifdef _WIN32
  8820. /* Windows SO_REUSEADDR lets many procs binds to a
  8821. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8822. * if someone already has the socket -- DTL */
  8823. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8824. * Windows might need a few seconds before
  8825. * the same port can be used again in the
  8826. * same process, so a short Sleep may be
  8827. * required between mg_stop and mg_start.
  8828. */
  8829. if (setsockopt(so.sock,
  8830. SOL_SOCKET,
  8831. SO_EXCLUSIVEADDRUSE,
  8832. (SOCK_OPT_TYPE)&on,
  8833. sizeof(on)) != 0) {
  8834. mg_cry(fc(ctx),
  8835. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8836. portsTotal);
  8837. }
  8838. #else
  8839. if (setsockopt(so.sock,
  8840. SOL_SOCKET,
  8841. SO_REUSEADDR,
  8842. (SOCK_OPT_TYPE)&on,
  8843. sizeof(on)) != 0) {
  8844. mg_cry(fc(ctx),
  8845. "cannot set socket option SO_REUSEADDR (entry %i)",
  8846. portsTotal);
  8847. }
  8848. #endif
  8849. #if defined(USE_IPV6)
  8850. if (so.lsa.sa.sa_family == AF_INET6
  8851. && setsockopt(so.sock,
  8852. IPPROTO_IPV6,
  8853. IPV6_V6ONLY,
  8854. (void *)&off,
  8855. sizeof(off)) != 0) {
  8856. mg_cry(fc(ctx),
  8857. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8858. portsTotal);
  8859. }
  8860. #endif
  8861. if (so.lsa.sa.sa_family == AF_INET) {
  8862. len = sizeof(so.lsa.sin);
  8863. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8864. mg_cry(fc(ctx),
  8865. "cannot bind to %.*s: %d (%s)",
  8866. (int)vec.len,
  8867. vec.ptr,
  8868. (int)ERRNO,
  8869. strerror(errno));
  8870. closesocket(so.sock);
  8871. so.sock = INVALID_SOCKET;
  8872. continue;
  8873. }
  8874. }
  8875. #if defined(USE_IPV6)
  8876. else if (so.lsa.sa.sa_family == AF_INET6) {
  8877. len = sizeof(so.lsa.sin6);
  8878. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8879. mg_cry(fc(ctx),
  8880. "cannot bind to IPv6 %.*s: %d (%s)",
  8881. (int)vec.len,
  8882. vec.ptr,
  8883. (int)ERRNO,
  8884. strerror(errno));
  8885. closesocket(so.sock);
  8886. so.sock = INVALID_SOCKET;
  8887. continue;
  8888. }
  8889. }
  8890. #endif
  8891. else {
  8892. mg_cry(fc(ctx),
  8893. "cannot bind: address family not supported (entry %i)",
  8894. portsTotal);
  8895. continue;
  8896. }
  8897. if (listen(so.sock, SOMAXCONN) != 0) {
  8898. mg_cry(fc(ctx),
  8899. "cannot listen to %.*s: %d (%s)",
  8900. (int)vec.len,
  8901. vec.ptr,
  8902. (int)ERRNO,
  8903. strerror(errno));
  8904. closesocket(so.sock);
  8905. so.sock = INVALID_SOCKET;
  8906. continue;
  8907. }
  8908. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8909. int err = (int)ERRNO;
  8910. mg_cry(fc(ctx),
  8911. "call to getsockname failed %.*s: %d (%s)",
  8912. (int)vec.len,
  8913. vec.ptr,
  8914. err,
  8915. strerror(errno));
  8916. closesocket(so.sock);
  8917. so.sock = INVALID_SOCKET;
  8918. continue;
  8919. }
  8920. if ((ptr = (struct socket *)
  8921. mg_realloc(ctx->listening_sockets,
  8922. (ctx->num_listening_sockets + 1)
  8923. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  8924. mg_cry(fc(ctx), "%s", "Out of memory");
  8925. closesocket(so.sock);
  8926. so.sock = INVALID_SOCKET;
  8927. continue;
  8928. }
  8929. if ((portPtr =
  8930. (in_port_t *)mg_realloc(ctx->listening_ports,
  8931. (ctx->num_listening_sockets + 1)
  8932. * sizeof(ctx->listening_ports[0])))
  8933. == NULL) {
  8934. mg_cry(fc(ctx), "%s", "Out of memory");
  8935. closesocket(so.sock);
  8936. so.sock = INVALID_SOCKET;
  8937. mg_free(ptr);
  8938. continue;
  8939. }
  8940. set_close_on_exec(so.sock, fc(ctx));
  8941. ctx->listening_sockets = ptr;
  8942. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8943. ctx->listening_ports = portPtr;
  8944. ctx->listening_ports[ctx->num_listening_sockets] =
  8945. ntohs(usa.sin.sin_port);
  8946. ctx->num_listening_sockets++;
  8947. portsOk++;
  8948. }
  8949. if (portsOk != portsTotal) {
  8950. close_all_listening_sockets(ctx);
  8951. portsOk = 0;
  8952. }
  8953. return portsOk;
  8954. }
  8955. static const char *
  8956. header_val(const struct mg_connection *conn, const char *header)
  8957. {
  8958. const char *header_value;
  8959. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8960. return "-";
  8961. } else {
  8962. return header_value;
  8963. }
  8964. }
  8965. static void
  8966. log_access(const struct mg_connection *conn)
  8967. {
  8968. const struct mg_request_info *ri;
  8969. struct file fi;
  8970. char date[64], src_addr[IP_ADDR_STR_LEN];
  8971. struct tm *tm;
  8972. const char *referer;
  8973. const char *user_agent;
  8974. char buf[4096];
  8975. if (!conn || !conn->ctx) {
  8976. return;
  8977. }
  8978. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  8979. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  8980. == 0) {
  8981. fi.fp = NULL;
  8982. }
  8983. } else {
  8984. fi.fp = NULL;
  8985. }
  8986. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8987. return;
  8988. }
  8989. tm = localtime(&conn->conn_birth_time);
  8990. if (tm != NULL) {
  8991. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8992. } else {
  8993. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  8994. date[sizeof(date) - 1] = '\0';
  8995. }
  8996. ri = &conn->request_info;
  8997. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8998. referer = header_val(conn, "Referer");
  8999. user_agent = header_val(conn, "User-Agent");
  9000. mg_snprintf(conn,
  9001. NULL, /* Ignore truncation in access log */
  9002. buf,
  9003. sizeof(buf),
  9004. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9005. src_addr,
  9006. ri->remote_user == NULL ? "-" : ri->remote_user,
  9007. date,
  9008. ri->request_method ? ri->request_method : "-",
  9009. ri->request_uri ? ri->request_uri : "-",
  9010. ri->query_string ? "?" : "",
  9011. ri->query_string ? ri->query_string : "",
  9012. ri->http_version,
  9013. conn->status_code,
  9014. conn->num_bytes_sent,
  9015. referer,
  9016. user_agent);
  9017. if (conn->ctx->callbacks.log_access) {
  9018. conn->ctx->callbacks.log_access(conn, buf);
  9019. }
  9020. if (fi.fp) {
  9021. flockfile(fi.fp);
  9022. fprintf(fi.fp, "%s\n", buf);
  9023. fflush(fi.fp);
  9024. funlockfile(fi.fp);
  9025. mg_fclose(&fi);
  9026. }
  9027. }
  9028. /* Verify given socket address against the ACL.
  9029. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9030. */
  9031. static int
  9032. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9033. {
  9034. int allowed, flag;
  9035. uint32_t net, mask;
  9036. struct vec vec;
  9037. if (ctx) {
  9038. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9039. /* If any ACL is set, deny by default */
  9040. allowed = list == NULL ? '+' : '-';
  9041. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9042. flag = vec.ptr[0];
  9043. if ((flag != '+' && flag != '-')
  9044. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9045. mg_cry(fc(ctx),
  9046. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9047. __func__);
  9048. return -1;
  9049. }
  9050. if (net == (remote_ip & mask)) {
  9051. allowed = flag;
  9052. }
  9053. }
  9054. return allowed == '+';
  9055. }
  9056. return -1;
  9057. }
  9058. #if !defined(_WIN32)
  9059. static int
  9060. set_uid_option(struct mg_context *ctx)
  9061. {
  9062. struct passwd *pw;
  9063. if (ctx) {
  9064. const char *uid = ctx->config[RUN_AS_USER];
  9065. int success = 0;
  9066. if (uid == NULL) {
  9067. success = 1;
  9068. } else {
  9069. if ((pw = getpwnam(uid)) == NULL) {
  9070. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9071. } else if (setgid(pw->pw_gid) == -1) {
  9072. mg_cry(fc(ctx),
  9073. "%s: setgid(%s): %s",
  9074. __func__,
  9075. uid,
  9076. strerror(errno));
  9077. } else if (setgroups(0, NULL)) {
  9078. mg_cry(fc(ctx),
  9079. "%s: setgroups(): %s",
  9080. __func__,
  9081. strerror(errno));
  9082. } else if (setuid(pw->pw_uid) == -1) {
  9083. mg_cry(fc(ctx),
  9084. "%s: setuid(%s): %s",
  9085. __func__,
  9086. uid,
  9087. strerror(errno));
  9088. } else {
  9089. success = 1;
  9090. }
  9091. }
  9092. return success;
  9093. }
  9094. return 0;
  9095. }
  9096. #endif /* !_WIN32 */
  9097. static void
  9098. tls_dtor(void *key)
  9099. {
  9100. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9101. /* key == pthread_getspecific(sTlsKey); */
  9102. if (tls) {
  9103. if (tls->is_master == 2) {
  9104. tls->is_master = -3; /* Mark memory as dead */
  9105. mg_free(tls);
  9106. }
  9107. }
  9108. pthread_setspecific(sTlsKey, NULL);
  9109. }
  9110. #if !defined(NO_SSL)
  9111. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9112. static unsigned long
  9113. ssl_id_callback(void)
  9114. {
  9115. #ifdef _WIN32
  9116. return GetCurrentThreadId();
  9117. #else
  9118. #ifdef __clang__
  9119. #pragma clang diagnostic push
  9120. #pragma clang diagnostic ignored "-Wunreachable-code"
  9121. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9122. * or not, so one of the two conditions will be unreachable by construction.
  9123. * Unfortunately the C standard does not define a way to check this at
  9124. * compile time, since the #if preprocessor conditions can not use the sizeof
  9125. * operator as an argument. */
  9126. #endif
  9127. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9128. /* This is the problematic case for CRYPTO_set_id_callback:
  9129. * The OS pthread_t can not be cast to unsigned long. */
  9130. struct mg_workerTLS *tls =
  9131. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9132. if (tls == NULL) {
  9133. /* SSL called from an unknown thread: Create some thread index.
  9134. */
  9135. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9136. tls->is_master = -2; /* -2 means "3rd party thread" */
  9137. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9138. pthread_setspecific(sTlsKey, tls);
  9139. }
  9140. return tls->thread_idx;
  9141. } else {
  9142. /* pthread_t may be any data type, so a simple cast to unsigned long
  9143. * can rise a warning/error, depending on the platform.
  9144. * Here memcpy is used as an anything-to-anything cast. */
  9145. unsigned long ret = 0;
  9146. pthread_t t = pthread_self();
  9147. memcpy(&ret, &t, sizeof(pthread_t));
  9148. return ret;
  9149. }
  9150. #ifdef __clang__
  9151. #pragma clang diagnostic pop
  9152. #endif
  9153. #endif
  9154. }
  9155. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9156. static const char * ssl_error(void);
  9157. static int
  9158. refresh_trust(struct mg_connection *conn)
  9159. {
  9160. static int reload_lock = 0;
  9161. static long int data_check = 0;
  9162. char *pem;
  9163. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9164. && conn->ctx->callbacks.init_ssl == NULL) {
  9165. return 0;
  9166. }
  9167. struct stat cert_buf;
  9168. long int t = data_check;
  9169. if (stat(pem, &cert_buf) != -1) {
  9170. t = (long int) cert_buf.st_mtime;
  9171. }
  9172. if (data_check != t) {
  9173. data_check = t;
  9174. int should_verify_peer =
  9175. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9176. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9177. if (should_verify_peer) {
  9178. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9179. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9180. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx, ca_file, ca_path)
  9181. != 1) {
  9182. mg_cry(fc(conn->ctx),
  9183. "SSL_CTX_load_verify_locations error: %s "
  9184. "ssl_verify_peer requires setting "
  9185. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9186. "present in "
  9187. "the .conf file?",
  9188. ssl_error());
  9189. return 0;
  9190. }
  9191. }
  9192. if (!reload_lock) {
  9193. reload_lock = 1;
  9194. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9195. return 0;
  9196. }
  9197. reload_lock = 0;
  9198. }
  9199. }
  9200. /* lock while cert is reloading */
  9201. while (reload_lock) {
  9202. sleep(1);
  9203. }
  9204. return 1;
  9205. }
  9206. static pthread_mutex_t *ssl_mutexes;
  9207. static int
  9208. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9209. {
  9210. int ret, err;
  9211. if (!conn) {
  9212. return 0;
  9213. }
  9214. int short_trust = !strcmp(conn->ctx->config[SSL_SHORT_TRUST], "yes");
  9215. if (short_trust) {
  9216. int trust_ret = refresh_trust(conn);
  9217. if (!trust_ret) {
  9218. return trust_ret;
  9219. }
  9220. }
  9221. conn->ssl = SSL_new(s);
  9222. if (conn->ssl == NULL) {
  9223. return 0;
  9224. }
  9225. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9226. if (ret != 1) {
  9227. err = SSL_get_error(conn->ssl, ret);
  9228. (void)err; /* TODO: set some error message */
  9229. SSL_free(conn->ssl);
  9230. conn->ssl = NULL;
  9231. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9232. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9233. ERR_remove_state(0);
  9234. return 0;
  9235. }
  9236. ret = func(conn->ssl);
  9237. if (ret != 1) {
  9238. err = SSL_get_error(conn->ssl, ret);
  9239. (void)err; /* TODO: set some error message */
  9240. SSL_free(conn->ssl);
  9241. conn->ssl = NULL;
  9242. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9243. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9244. ERR_remove_state(0);
  9245. return 0;
  9246. }
  9247. return 1;
  9248. }
  9249. /* Return OpenSSL error message (from CRYPTO lib) */
  9250. static const char *
  9251. ssl_error(void)
  9252. {
  9253. unsigned long err;
  9254. err = ERR_get_error();
  9255. return err == 0 ? "" : ERR_error_string(err, NULL);
  9256. }
  9257. static void
  9258. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9259. {
  9260. (void)line;
  9261. (void)file;
  9262. if (mode & 1) {
  9263. /* 1 is CRYPTO_LOCK */
  9264. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9265. } else {
  9266. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9267. }
  9268. }
  9269. #if !defined(NO_SSL_DL)
  9270. static void *
  9271. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9272. {
  9273. union {
  9274. void *p;
  9275. void (*fp)(void);
  9276. } u;
  9277. void *dll_handle;
  9278. struct ssl_func *fp;
  9279. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9280. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9281. return NULL;
  9282. }
  9283. for (fp = sw; fp->name != NULL; fp++) {
  9284. #ifdef _WIN32
  9285. /* GetProcAddress() returns pointer to function */
  9286. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9287. #else
  9288. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9289. * pointers to function pointers. We need to use a union to make a
  9290. * cast. */
  9291. u.p = dlsym(dll_handle, fp->name);
  9292. #endif /* _WIN32 */
  9293. if (u.fp == NULL) {
  9294. mg_cry(fc(ctx),
  9295. "%s: %s: cannot find %s",
  9296. __func__,
  9297. dll_name,
  9298. fp->name);
  9299. dlclose(dll_handle);
  9300. return NULL;
  9301. } else {
  9302. fp->ptr = u.fp;
  9303. }
  9304. }
  9305. return dll_handle;
  9306. }
  9307. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9308. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9309. #endif /* NO_SSL_DL */
  9310. #if defined(SSL_ALREADY_INITIALIZED)
  9311. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9312. #else
  9313. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9314. #endif
  9315. static int
  9316. initialize_ssl(struct mg_context *ctx)
  9317. {
  9318. int i;
  9319. size_t size;
  9320. #if !defined(NO_SSL_DL)
  9321. if (!cryptolib_dll_handle) {
  9322. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9323. if (!cryptolib_dll_handle) {
  9324. return 0;
  9325. }
  9326. }
  9327. #endif /* NO_SSL_DL */
  9328. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9329. return 1;
  9330. }
  9331. /* Initialize locking callbacks, needed for thread safety.
  9332. * http://www.openssl.org/support/faq.html#PROG1
  9333. */
  9334. i = CRYPTO_num_locks();
  9335. if (i < 0) {
  9336. i = 0;
  9337. }
  9338. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9339. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9340. mg_cry(fc(ctx),
  9341. "%s: cannot allocate mutexes: %s",
  9342. __func__,
  9343. ssl_error());
  9344. return 0;
  9345. }
  9346. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9347. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9348. }
  9349. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9350. CRYPTO_set_id_callback(&ssl_id_callback);
  9351. return 1;
  9352. }
  9353. static int
  9354. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9355. {
  9356. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9357. mg_cry(fc(ctx),
  9358. "%s: cannot open certificate file %s: %s",
  9359. __func__,
  9360. pem,
  9361. ssl_error());
  9362. return 0;
  9363. }
  9364. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9365. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9366. mg_cry(fc(ctx),
  9367. "%s: cannot open private key file %s: %s",
  9368. __func__,
  9369. pem,
  9370. ssl_error());
  9371. return 0;
  9372. }
  9373. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9374. mg_cry(fc(ctx),
  9375. "%s: certificate and private key do not match: %s",
  9376. __func__,
  9377. pem);
  9378. return 0;
  9379. }
  9380. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9381. mg_cry(fc(ctx),
  9382. "%s: cannot use certificate chain file %s: %s",
  9383. __func__,
  9384. pem,
  9385. ssl_error());
  9386. return 0;
  9387. }
  9388. return 1;
  9389. }
  9390. static long
  9391. ssl_get_protocol(int version_id)
  9392. {
  9393. long ret = SSL_OP_ALL;
  9394. if (version_id > 0)
  9395. ret |= SSL_OP_NO_SSLv2;
  9396. if (version_id > 1)
  9397. ret |= SSL_OP_NO_SSLv3;
  9398. if (version_id > 2)
  9399. ret |= SSL_OP_NO_TLSv1;
  9400. if (version_id > 3)
  9401. ret |= SSL_OP_NO_TLSv1_1;
  9402. return ret;
  9403. }
  9404. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9405. static int
  9406. set_ssl_option(struct mg_context *ctx)
  9407. {
  9408. const char *pem;
  9409. int callback_ret;
  9410. int should_verify_peer;
  9411. const char *ca_path;
  9412. const char *ca_file;
  9413. int use_default_verify_paths;
  9414. int verify_depth;
  9415. time_t now_rt = time(NULL);
  9416. struct timespec now_mt;
  9417. md5_byte_t ssl_context_id[16];
  9418. md5_state_t md5state;
  9419. int protocol_ver;
  9420. /* If PEM file is not specified and the init_ssl callback
  9421. * is not specified, skip SSL initialization. */
  9422. if (!ctx) {
  9423. return 0;
  9424. }
  9425. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9426. && ctx->callbacks.init_ssl == NULL) {
  9427. return 1;
  9428. }
  9429. if (!initialize_ssl(ctx)) {
  9430. return 0;
  9431. }
  9432. #if !defined(NO_SSL_DL)
  9433. if (!ssllib_dll_handle) {
  9434. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9435. if (!ssllib_dll_handle) {
  9436. return 0;
  9437. }
  9438. }
  9439. #endif /* NO_SSL_DL */
  9440. /* Initialize SSL library */
  9441. SSL_library_init();
  9442. SSL_load_error_strings();
  9443. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9444. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9445. return 0;
  9446. }
  9447. SSL_CTX_clear_options(ctx->ssl_ctx,
  9448. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9449. | SSL_OP_NO_TLSv1_1);
  9450. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9451. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9452. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9453. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9454. /* If a callback has been specified, call it. */
  9455. callback_ret =
  9456. (ctx->callbacks.init_ssl == NULL)
  9457. ? 0
  9458. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9459. /* If callback returns 0, civetweb sets up the SSL certificate.
  9460. * If it returns 1, civetweb assumes the calback already did this.
  9461. * If it returns -1, initializing ssl fails. */
  9462. if (callback_ret < 0) {
  9463. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9464. return 0;
  9465. }
  9466. if (callback_ret > 0) {
  9467. if (pem != NULL) {
  9468. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9469. }
  9470. return 1;
  9471. }
  9472. /* Use some UID as session context ID. */
  9473. md5_init(&md5state);
  9474. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9475. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9476. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9477. md5_append(&md5state,
  9478. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9479. strlen(ctx->config[LISTENING_PORTS]));
  9480. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9481. md5_finish(&md5state, ssl_context_id);
  9482. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9483. (const unsigned char *)&ssl_context_id,
  9484. sizeof(ssl_context_id));
  9485. if (pem != NULL) {
  9486. if (!ssl_use_pem_file(ctx, pem)) {
  9487. return 0;
  9488. }
  9489. }
  9490. should_verify_peer =
  9491. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9492. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9493. use_default_verify_paths =
  9494. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9495. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9496. if (should_verify_peer) {
  9497. ca_path = ctx->config[SSL_CA_PATH];
  9498. ca_file = ctx->config[SSL_CA_FILE];
  9499. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9500. != 1) {
  9501. mg_cry(fc(ctx),
  9502. "SSL_CTX_load_verify_locations error: %s "
  9503. "ssl_verify_peer requires setting "
  9504. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9505. "present in "
  9506. "the .conf file?",
  9507. ssl_error());
  9508. return 0;
  9509. }
  9510. SSL_CTX_set_verify(ctx->ssl_ctx,
  9511. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9512. NULL);
  9513. if (use_default_verify_paths
  9514. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9515. mg_cry(fc(ctx),
  9516. "SSL_CTX_set_default_verify_paths error: %s",
  9517. ssl_error());
  9518. return 0;
  9519. }
  9520. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9521. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9522. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9523. }
  9524. }
  9525. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9526. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9527. != 1) {
  9528. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9529. }
  9530. }
  9531. return 1;
  9532. }
  9533. static void
  9534. uninitialize_ssl(struct mg_context *ctx)
  9535. {
  9536. int i;
  9537. (void)ctx;
  9538. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9539. /* Shutdown according to
  9540. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9541. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9542. */
  9543. CRYPTO_set_locking_callback(NULL);
  9544. CRYPTO_set_id_callback(NULL);
  9545. ENGINE_cleanup();
  9546. CONF_modules_unload(1);
  9547. ERR_free_strings();
  9548. EVP_cleanup();
  9549. CRYPTO_cleanup_all_ex_data();
  9550. ERR_remove_state(0);
  9551. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9552. pthread_mutex_destroy(&ssl_mutexes[i]);
  9553. }
  9554. mg_free(ssl_mutexes);
  9555. ssl_mutexes = NULL;
  9556. }
  9557. }
  9558. #endif /* !NO_SSL */
  9559. static int
  9560. set_gpass_option(struct mg_context *ctx)
  9561. {
  9562. if (ctx) {
  9563. struct file file = STRUCT_FILE_INITIALIZER;
  9564. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9565. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9566. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9567. return 0;
  9568. }
  9569. return 1;
  9570. }
  9571. return 0;
  9572. }
  9573. static int
  9574. set_acl_option(struct mg_context *ctx)
  9575. {
  9576. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9577. }
  9578. static void
  9579. reset_per_request_attributes(struct mg_connection *conn)
  9580. {
  9581. if (!conn) {
  9582. return;
  9583. }
  9584. conn->path_info = NULL;
  9585. conn->num_bytes_sent = conn->consumed_content = 0;
  9586. conn->status_code = -1;
  9587. conn->is_chunked = 0;
  9588. conn->must_close = conn->request_len = conn->throttle = 0;
  9589. conn->request_info.content_length = -1;
  9590. conn->request_info.remote_user = NULL;
  9591. conn->request_info.request_method = NULL;
  9592. conn->request_info.request_uri = NULL;
  9593. conn->request_info.local_uri = NULL;
  9594. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9595. * local_uri and request_uri */
  9596. conn->request_info.http_version = NULL;
  9597. conn->request_info.num_headers = 0;
  9598. conn->data_len = 0;
  9599. conn->chunk_remainder = 0;
  9600. conn->internal_error = 0;
  9601. }
  9602. static int
  9603. set_sock_timeout(SOCKET sock, int milliseconds)
  9604. {
  9605. int r0 = 0, r1, r2;
  9606. #ifdef _WIN32
  9607. /* Windows specific */
  9608. DWORD tv = (DWORD)milliseconds;
  9609. #else
  9610. /* Linux, ... (not Windows) */
  9611. struct timeval tv;
  9612. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9613. * max. time waiting for the acknowledged of TCP data before the connection
  9614. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9615. * If this option is not set, the default timeout of 20-30 minutes is used.
  9616. */
  9617. /* #define TCP_USER_TIMEOUT (18) */
  9618. #if defined(TCP_USER_TIMEOUT)
  9619. unsigned int uto = (unsigned int)milliseconds;
  9620. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9621. #endif
  9622. memset(&tv, 0, sizeof(tv));
  9623. tv.tv_sec = milliseconds / 1000;
  9624. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9625. #endif /* _WIN32 */
  9626. r1 = setsockopt(
  9627. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9628. r2 = setsockopt(
  9629. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9630. return r0 || r1 || r2;
  9631. }
  9632. static int
  9633. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  9634. {
  9635. if (setsockopt(sock,
  9636. IPPROTO_TCP,
  9637. TCP_NODELAY,
  9638. (SOCK_OPT_TYPE)&nodelay_on,
  9639. sizeof(nodelay_on)) != 0) {
  9640. /* Error */
  9641. return 1;
  9642. }
  9643. /* OK */
  9644. return 0;
  9645. }
  9646. static void
  9647. close_socket_gracefully(struct mg_connection *conn)
  9648. {
  9649. #if defined(_WIN32)
  9650. char buf[MG_BUF_LEN];
  9651. int n;
  9652. #endif
  9653. struct linger linger;
  9654. if (!conn) {
  9655. return;
  9656. }
  9657. /* Set linger option to avoid socket hanging out after close. This
  9658. * prevent
  9659. * ephemeral port exhaust problem under high QPS. */
  9660. linger.l_onoff = 1;
  9661. linger.l_linger = 1;
  9662. if (setsockopt(conn->client.sock,
  9663. SOL_SOCKET,
  9664. SO_LINGER,
  9665. (char *)&linger,
  9666. sizeof(linger)) != 0) {
  9667. mg_cry(conn,
  9668. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9669. __func__,
  9670. strerror(ERRNO));
  9671. }
  9672. /* Send FIN to the client */
  9673. shutdown(conn->client.sock, SHUT_WR);
  9674. set_non_blocking_mode(conn->client.sock);
  9675. #if defined(_WIN32)
  9676. /* Read and discard pending incoming data. If we do not do that and
  9677. * close
  9678. * the socket, the data in the send buffer may be discarded. This
  9679. * behaviour is seen on Windows, when client keeps sending data
  9680. * when server decides to close the connection; then when client
  9681. * does recv() it gets no data back. */
  9682. do {
  9683. n = pull(
  9684. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9685. } while (n > 0);
  9686. #endif
  9687. /* Now we know that our FIN is ACK-ed, safe to close */
  9688. closesocket(conn->client.sock);
  9689. conn->client.sock = INVALID_SOCKET;
  9690. }
  9691. static void
  9692. close_connection(struct mg_connection *conn)
  9693. {
  9694. if (!conn || !conn->ctx) {
  9695. return;
  9696. }
  9697. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9698. if (conn->lua_websocket_state) {
  9699. lua_websocket_close(conn, conn->lua_websocket_state);
  9700. conn->lua_websocket_state = NULL;
  9701. }
  9702. #endif
  9703. /* call the connection_close callback if assigned */
  9704. if ((conn->ctx->callbacks.connection_close != NULL)
  9705. && (conn->ctx->context_type == 1)) {
  9706. conn->ctx->callbacks.connection_close(conn);
  9707. }
  9708. mg_lock_connection(conn);
  9709. conn->must_close = 1;
  9710. #ifndef NO_SSL
  9711. if (conn->ssl != NULL) {
  9712. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9713. */
  9714. SSL_shutdown(conn->ssl);
  9715. SSL_free(conn->ssl);
  9716. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9717. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9718. ERR_remove_state(0);
  9719. conn->ssl = NULL;
  9720. }
  9721. #endif
  9722. if (conn->client.sock != INVALID_SOCKET) {
  9723. close_socket_gracefully(conn);
  9724. conn->client.sock = INVALID_SOCKET;
  9725. }
  9726. mg_unlock_connection(conn);
  9727. }
  9728. void
  9729. mg_close_connection(struct mg_connection *conn)
  9730. {
  9731. struct mg_context *client_ctx = NULL;
  9732. unsigned int i;
  9733. if (conn == NULL) {
  9734. return;
  9735. }
  9736. if (conn->ctx->context_type == 2) {
  9737. client_ctx = conn->ctx;
  9738. /* client context: loops must end */
  9739. conn->ctx->stop_flag = 1;
  9740. }
  9741. #ifndef NO_SSL
  9742. if (conn->client_ssl_ctx != NULL) {
  9743. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9744. }
  9745. #endif
  9746. close_connection(conn);
  9747. if (client_ctx != NULL) {
  9748. /* join worker thread and free context */
  9749. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9750. if (client_ctx->workerthreadids[i] != 0) {
  9751. mg_join_thread(client_ctx->workerthreadids[i]);
  9752. }
  9753. }
  9754. mg_free(client_ctx->workerthreadids);
  9755. mg_free(client_ctx);
  9756. (void)pthread_mutex_destroy(&conn->mutex);
  9757. mg_free(conn);
  9758. }
  9759. }
  9760. static struct mg_connection *
  9761. mg_connect_client_impl(const struct mg_client_options *client_options,
  9762. int use_ssl,
  9763. char *ebuf,
  9764. size_t ebuf_len)
  9765. {
  9766. static struct mg_context fake_ctx;
  9767. struct mg_connection *conn = NULL;
  9768. SOCKET sock;
  9769. union usa sa;
  9770. if (!connect_socket(&fake_ctx,
  9771. client_options->host,
  9772. client_options->port,
  9773. use_ssl,
  9774. ebuf,
  9775. ebuf_len,
  9776. &sock,
  9777. &sa)) {
  9778. ;
  9779. } else if ((conn = (struct mg_connection *)
  9780. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9781. mg_snprintf(NULL,
  9782. NULL, /* No truncation check for ebuf */
  9783. ebuf,
  9784. ebuf_len,
  9785. "calloc(): %s",
  9786. strerror(ERRNO));
  9787. closesocket(sock);
  9788. #ifndef NO_SSL
  9789. } else if (use_ssl
  9790. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9791. == NULL) {
  9792. mg_snprintf(NULL,
  9793. NULL, /* No truncation check for ebuf */
  9794. ebuf,
  9795. ebuf_len,
  9796. "SSL_CTX_new error");
  9797. closesocket(sock);
  9798. mg_free(conn);
  9799. conn = NULL;
  9800. #endif /* NO_SSL */
  9801. } else {
  9802. #ifdef USE_IPV6
  9803. socklen_t len = (sa.sa.sa_family == AF_INET)
  9804. ? sizeof(conn->client.rsa.sin)
  9805. : sizeof(conn->client.rsa.sin6);
  9806. struct sockaddr *psa =
  9807. (sa.sa.sa_family == AF_INET)
  9808. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9809. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9810. #else
  9811. socklen_t len = sizeof(conn->client.rsa.sin);
  9812. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9813. #endif
  9814. conn->buf_size = MAX_REQUEST_SIZE;
  9815. conn->buf = (char *)(conn + 1);
  9816. conn->ctx = &fake_ctx;
  9817. conn->client.sock = sock;
  9818. conn->client.lsa = sa;
  9819. if (getsockname(sock, psa, &len) != 0) {
  9820. mg_cry(conn,
  9821. "%s: getsockname() failed: %s",
  9822. __func__,
  9823. strerror(ERRNO));
  9824. }
  9825. conn->client.is_ssl = use_ssl ? 1 : 0;
  9826. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9827. #ifndef NO_SSL
  9828. if (use_ssl) {
  9829. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9830. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9831. SSL_CTX_set_verify call is needed to switch off server
  9832. * certificate checking, which is off by default in OpenSSL and
  9833. on
  9834. * in yaSSL. */
  9835. // TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  9836. // SSL_VERIFY_PEER,
  9837. // verify_ssl_server);
  9838. if (client_options->client_cert) {
  9839. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9840. mg_snprintf(NULL,
  9841. NULL, /* No truncation check for ebuf */
  9842. ebuf,
  9843. ebuf_len,
  9844. "Can not use SSL client certificate");
  9845. SSL_CTX_free(conn->client_ssl_ctx);
  9846. closesocket(sock);
  9847. mg_free(conn);
  9848. conn = NULL;
  9849. }
  9850. }
  9851. if (client_options->server_cert) {
  9852. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9853. client_options->server_cert,
  9854. NULL);
  9855. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9856. } else {
  9857. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9858. }
  9859. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9860. mg_snprintf(NULL,
  9861. NULL, /* No truncation check for ebuf */
  9862. ebuf,
  9863. ebuf_len,
  9864. "SSL connection error");
  9865. SSL_CTX_free(conn->client_ssl_ctx);
  9866. closesocket(sock);
  9867. mg_free(conn);
  9868. conn = NULL;
  9869. }
  9870. }
  9871. #endif
  9872. }
  9873. return conn;
  9874. }
  9875. CIVETWEB_API struct mg_connection *
  9876. mg_connect_client_secure(const struct mg_client_options *client_options,
  9877. char *error_buffer,
  9878. size_t error_buffer_size)
  9879. {
  9880. return mg_connect_client_impl(client_options,
  9881. 1,
  9882. error_buffer,
  9883. error_buffer_size);
  9884. }
  9885. struct mg_connection *
  9886. mg_connect_client(const char *host,
  9887. int port,
  9888. int use_ssl,
  9889. char *error_buffer,
  9890. size_t error_buffer_size)
  9891. {
  9892. struct mg_client_options opts;
  9893. memset(&opts, 0, sizeof(opts));
  9894. opts.host = host;
  9895. opts.port = port;
  9896. return mg_connect_client_impl(&opts,
  9897. use_ssl,
  9898. error_buffer,
  9899. error_buffer_size);
  9900. }
  9901. static const struct {
  9902. const char *proto;
  9903. size_t proto_len;
  9904. unsigned default_port;
  9905. } abs_uri_protocols[] = {{"http://", 7, 80},
  9906. {"https://", 8, 443},
  9907. {"ws://", 5, 80},
  9908. {"wss://", 6, 443},
  9909. {NULL, 0, 0}};
  9910. /* Check if the uri is valid.
  9911. * return 0 for invalid uri,
  9912. * return 1 for *,
  9913. * return 2 for relative uri,
  9914. * return 3 for absolute uri without port,
  9915. * return 4 for absolute uri with port */
  9916. static int
  9917. get_uri_type(const char *uri)
  9918. {
  9919. int i;
  9920. char *hostend, *portbegin, *portend;
  9921. unsigned long port;
  9922. /* According to the HTTP standard
  9923. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  9924. * URI can be an asterisk (*) or should start with slash (relative uri),
  9925. * or it should start with the protocol (absolute uri). */
  9926. if (uri[0] == '*' && uri[1] == '\0') {
  9927. /* asterisk */
  9928. return 1;
  9929. }
  9930. if (uri[0] == '/') {
  9931. /* relative uri */
  9932. return 2;
  9933. }
  9934. /* It could be an absolute uri: */
  9935. /* This function only checks if the uri is valid, not if it is
  9936. * addressing the current server. So civetweb can also be used
  9937. * as a proxy server. */
  9938. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9939. if (mg_strncasecmp(uri,
  9940. abs_uri_protocols[i].proto,
  9941. abs_uri_protocols[i].proto_len) == 0) {
  9942. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9943. if (!hostend) {
  9944. return 0;
  9945. }
  9946. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9947. if (!portbegin) {
  9948. return 3;
  9949. }
  9950. port = strtoul(portbegin + 1, &portend, 10);
  9951. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9952. return 0;
  9953. }
  9954. return 4;
  9955. }
  9956. }
  9957. return 0;
  9958. }
  9959. /* Return NULL or the relative uri at the current server */
  9960. static const char *
  9961. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  9962. {
  9963. const char *server_domain;
  9964. size_t server_domain_len;
  9965. size_t request_domain_len = 0;
  9966. unsigned long port = 0;
  9967. int i;
  9968. const char *hostbegin = NULL;
  9969. const char *hostend = NULL;
  9970. const char *portbegin;
  9971. char *portend;
  9972. /* DNS is case insensitive, so use case insensitive string compare here
  9973. */
  9974. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  9975. if (!server_domain) {
  9976. return 0;
  9977. }
  9978. server_domain_len = strlen(server_domain);
  9979. if (!server_domain_len) {
  9980. return 0;
  9981. }
  9982. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9983. if (mg_strncasecmp(uri,
  9984. abs_uri_protocols[i].proto,
  9985. abs_uri_protocols[i].proto_len) == 0) {
  9986. hostbegin = uri + abs_uri_protocols[i].proto_len;
  9987. hostend = strchr(hostbegin, '/');
  9988. if (!hostend) {
  9989. return 0;
  9990. }
  9991. portbegin = strchr(hostbegin, ':');
  9992. if ((!portbegin) || (portbegin > hostend)) {
  9993. port = abs_uri_protocols[i].default_port;
  9994. request_domain_len = (size_t)(hostend - hostbegin);
  9995. } else {
  9996. port = strtoul(portbegin + 1, &portend, 10);
  9997. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9998. return 0;
  9999. }
  10000. request_domain_len = (size_t)(portbegin - hostbegin);
  10001. }
  10002. /* protocol found, port set */
  10003. break;
  10004. }
  10005. }
  10006. if (!port) {
  10007. /* port remains 0 if the protocol is not found */
  10008. return 0;
  10009. }
  10010. #if defined(USE_IPV6)
  10011. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10012. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10013. /* Request is directed to a different port */
  10014. return 0;
  10015. }
  10016. } else
  10017. #endif
  10018. {
  10019. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10020. /* Request is directed to a different port */
  10021. return 0;
  10022. }
  10023. }
  10024. if ((request_domain_len != server_domain_len)
  10025. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10026. /* Request is directed to another server */
  10027. return 0;
  10028. }
  10029. return hostend;
  10030. }
  10031. static int
  10032. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10033. {
  10034. const char *cl;
  10035. if (ebuf_len > 0) {
  10036. ebuf[0] = '\0';
  10037. }
  10038. *err = 0;
  10039. reset_per_request_attributes(conn);
  10040. if (!conn) {
  10041. mg_snprintf(conn,
  10042. NULL, /* No truncation check for ebuf */
  10043. ebuf,
  10044. ebuf_len,
  10045. "%s",
  10046. "Internal error");
  10047. *err = 500;
  10048. return 0;
  10049. }
  10050. /* Set the time the request was received. This value should be used for
  10051. * timeouts. */
  10052. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10053. conn->request_len =
  10054. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10055. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10056. */
  10057. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10058. mg_snprintf(conn,
  10059. NULL, /* No truncation check for ebuf */
  10060. ebuf,
  10061. ebuf_len,
  10062. "%s",
  10063. "Invalid request size");
  10064. *err = 500;
  10065. return 0;
  10066. }
  10067. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10068. mg_snprintf(conn,
  10069. NULL, /* No truncation check for ebuf */
  10070. ebuf,
  10071. ebuf_len,
  10072. "%s",
  10073. "Request Too Large");
  10074. *err = 413;
  10075. return 0;
  10076. } else if (conn->request_len <= 0) {
  10077. if (conn->data_len > 0) {
  10078. mg_snprintf(conn,
  10079. NULL, /* No truncation check for ebuf */
  10080. ebuf,
  10081. ebuf_len,
  10082. "%s",
  10083. "Client sent malformed request");
  10084. *err = 400;
  10085. } else {
  10086. /* Server did not send anything -> just close the connection */
  10087. conn->must_close = 1;
  10088. mg_snprintf(conn,
  10089. NULL, /* No truncation check for ebuf */
  10090. ebuf,
  10091. ebuf_len,
  10092. "%s",
  10093. "Client did not send a request");
  10094. *err = 0;
  10095. }
  10096. return 0;
  10097. } else if (parse_http_message(conn->buf,
  10098. conn->buf_size,
  10099. &conn->request_info) <= 0) {
  10100. mg_snprintf(conn,
  10101. NULL, /* No truncation check for ebuf */
  10102. ebuf,
  10103. ebuf_len,
  10104. "%s",
  10105. "Bad Request");
  10106. *err = 400;
  10107. return 0;
  10108. } else {
  10109. /* Message is a valid request or response */
  10110. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10111. /* Request/response has content length set */
  10112. char *endptr = NULL;
  10113. conn->content_len = strtoll(cl, &endptr, 10);
  10114. if (endptr == cl) {
  10115. mg_snprintf(conn,
  10116. NULL, /* No truncation check for ebuf */
  10117. ebuf,
  10118. ebuf_len,
  10119. "%s",
  10120. "Bad Request");
  10121. *err = 411;
  10122. return 0;
  10123. }
  10124. /* Publish the content length back to the request info. */
  10125. conn->request_info.content_length = conn->content_len;
  10126. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10127. != NULL
  10128. && strcmp(cl, "chunked") == 0) {
  10129. conn->is_chunked = 1;
  10130. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10131. || !mg_strcasecmp(conn->request_info.request_method,
  10132. "PUT")) {
  10133. /* POST or PUT request without content length set */
  10134. conn->content_len = -1;
  10135. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10136. "HTTP/",
  10137. 5)) {
  10138. /* Response without content length set */
  10139. conn->content_len = -1;
  10140. } else {
  10141. /* Other request */
  10142. conn->content_len = 0;
  10143. }
  10144. }
  10145. return 1;
  10146. }
  10147. int
  10148. mg_get_response(struct mg_connection *conn,
  10149. char *ebuf,
  10150. size_t ebuf_len,
  10151. int timeout)
  10152. {
  10153. if (conn) {
  10154. /* Implementation of API function for HTTP clients */
  10155. int err, ret;
  10156. struct mg_context *octx = conn->ctx;
  10157. struct mg_context rctx = *(conn->ctx);
  10158. char txt[32]; /* will not overflow */
  10159. if (timeout >= 0) {
  10160. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10161. rctx.config[REQUEST_TIMEOUT] = txt;
  10162. set_sock_timeout(conn->client.sock, timeout);
  10163. } else {
  10164. rctx.config[REQUEST_TIMEOUT] = NULL;
  10165. }
  10166. conn->ctx = &rctx;
  10167. ret = getreq(conn, ebuf, ebuf_len, &err);
  10168. conn->ctx = octx;
  10169. /* TODO: 1) uri is deprecated;
  10170. * 2) here, ri.uri is the http response code */
  10171. conn->request_info.uri = conn->request_info.request_uri;
  10172. /* TODO (mid): Define proper return values - maybe return length?
  10173. * For the first test use <0 for error and >0 for OK */
  10174. return (ret == 0) ? -1 : +1;
  10175. }
  10176. return -1;
  10177. }
  10178. struct mg_connection *
  10179. mg_download(const char *host,
  10180. int port,
  10181. int use_ssl,
  10182. char *ebuf,
  10183. size_t ebuf_len,
  10184. const char *fmt,
  10185. ...)
  10186. {
  10187. struct mg_connection *conn;
  10188. va_list ap;
  10189. int i;
  10190. int reqerr;
  10191. va_start(ap, fmt);
  10192. ebuf[0] = '\0';
  10193. /* open a connection */
  10194. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10195. if (conn != NULL) {
  10196. i = mg_vprintf(conn, fmt, ap);
  10197. if (i <= 0) {
  10198. mg_snprintf(conn,
  10199. NULL, /* No truncation check for ebuf */
  10200. ebuf,
  10201. ebuf_len,
  10202. "%s",
  10203. "Error sending request");
  10204. } else {
  10205. getreq(conn, ebuf, ebuf_len, &reqerr);
  10206. /* TODO: 1) uri is deprecated;
  10207. * 2) here, ri.uri is the http response code */
  10208. conn->request_info.uri = conn->request_info.request_uri;
  10209. }
  10210. }
  10211. /* if an error occured, close the connection */
  10212. if (ebuf[0] != '\0' && conn != NULL) {
  10213. mg_close_connection(conn);
  10214. conn = NULL;
  10215. }
  10216. va_end(ap);
  10217. return conn;
  10218. }
  10219. struct websocket_client_thread_data {
  10220. struct mg_connection *conn;
  10221. mg_websocket_data_handler data_handler;
  10222. mg_websocket_close_handler close_handler;
  10223. void *callback_data;
  10224. };
  10225. #if defined(USE_WEBSOCKET)
  10226. #ifdef _WIN32
  10227. static unsigned __stdcall websocket_client_thread(void *data)
  10228. #else
  10229. static void *
  10230. websocket_client_thread(void *data)
  10231. #endif
  10232. {
  10233. struct websocket_client_thread_data *cdata =
  10234. (struct websocket_client_thread_data *)data;
  10235. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10236. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10237. if (cdata->close_handler != NULL) {
  10238. cdata->close_handler(cdata->conn, cdata->callback_data);
  10239. }
  10240. mg_free((void *)cdata);
  10241. #ifdef _WIN32
  10242. return 0;
  10243. #else
  10244. return NULL;
  10245. #endif
  10246. }
  10247. #endif
  10248. struct mg_connection *
  10249. mg_connect_websocket_client(const char *host,
  10250. int port,
  10251. int use_ssl,
  10252. char *error_buffer,
  10253. size_t error_buffer_size,
  10254. const char *path,
  10255. const char *origin,
  10256. mg_websocket_data_handler data_func,
  10257. mg_websocket_close_handler close_func,
  10258. void *user_data)
  10259. {
  10260. struct mg_connection *conn = NULL;
  10261. #if defined(USE_WEBSOCKET)
  10262. struct mg_context *newctx = NULL;
  10263. struct websocket_client_thread_data *thread_data;
  10264. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10265. static const char *handshake_req;
  10266. if (origin != NULL) {
  10267. handshake_req = "GET %s HTTP/1.1\r\n"
  10268. "Host: %s\r\n"
  10269. "Upgrade: websocket\r\n"
  10270. "Connection: Upgrade\r\n"
  10271. "Sec-WebSocket-Key: %s\r\n"
  10272. "Sec-WebSocket-Version: 13\r\n"
  10273. "Origin: %s\r\n"
  10274. "\r\n";
  10275. } else {
  10276. handshake_req = "GET %s HTTP/1.1\r\n"
  10277. "Host: %s\r\n"
  10278. "Upgrade: websocket\r\n"
  10279. "Connection: Upgrade\r\n"
  10280. "Sec-WebSocket-Key: %s\r\n"
  10281. "Sec-WebSocket-Version: 13\r\n"
  10282. "\r\n";
  10283. }
  10284. /* Establish the client connection and request upgrade */
  10285. conn = mg_download(host,
  10286. port,
  10287. use_ssl,
  10288. error_buffer,
  10289. error_buffer_size,
  10290. handshake_req,
  10291. path,
  10292. host,
  10293. magic,
  10294. origin);
  10295. /* Connection object will be null if something goes wrong */
  10296. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10297. if (!*error_buffer) {
  10298. /* if there is a connection, but it did not return 101,
  10299. * error_buffer is not yet set */
  10300. mg_snprintf(conn,
  10301. NULL, /* No truncation check for ebuf */
  10302. error_buffer,
  10303. error_buffer_size,
  10304. "Unexpected server reply");
  10305. }
  10306. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10307. if (conn != NULL) {
  10308. mg_free(conn);
  10309. conn = NULL;
  10310. }
  10311. return conn;
  10312. }
  10313. /* For client connections, mg_context is fake. Since we need to set a
  10314. * callback function, we need to create a copy and modify it. */
  10315. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10316. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10317. newctx->user_data = user_data;
  10318. newctx->context_type = 2; /* client context type */
  10319. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10320. newctx->workerthreadids =
  10321. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10322. conn->ctx = newctx;
  10323. thread_data = (struct websocket_client_thread_data *)
  10324. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10325. thread_data->conn = conn;
  10326. thread_data->data_handler = data_func;
  10327. thread_data->close_handler = close_func;
  10328. thread_data->callback_data = NULL;
  10329. /* Start a thread to read the websocket client connection
  10330. * This thread will automatically stop when mg_disconnect is
  10331. * called on the client connection */
  10332. if (mg_start_thread_with_id(websocket_client_thread,
  10333. (void *)thread_data,
  10334. newctx->workerthreadids) != 0) {
  10335. mg_free((void *)thread_data);
  10336. mg_free((void *)newctx->workerthreadids);
  10337. mg_free((void *)newctx);
  10338. mg_free((void *)conn);
  10339. conn = NULL;
  10340. DEBUG_TRACE("%s",
  10341. "Websocket client connect thread could not be started\r\n");
  10342. }
  10343. #else
  10344. /* Appease "unused parameter" warnings */
  10345. (void)host;
  10346. (void)port;
  10347. (void)use_ssl;
  10348. (void)error_buffer;
  10349. (void)error_buffer_size;
  10350. (void)path;
  10351. (void)origin;
  10352. (void)user_data;
  10353. (void)data_func;
  10354. (void)close_func;
  10355. #endif
  10356. return conn;
  10357. }
  10358. static void
  10359. process_new_connection(struct mg_connection *conn)
  10360. {
  10361. if (conn && conn->ctx) {
  10362. struct mg_request_info *ri = &conn->request_info;
  10363. int keep_alive_enabled, keep_alive, discard_len;
  10364. char ebuf[100];
  10365. const char *hostend;
  10366. int reqerr, uri_type;
  10367. keep_alive_enabled =
  10368. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10369. /* Important: on new connection, reset the receiving buffer. Credit
  10370. * goes to crule42. */
  10371. conn->data_len = 0;
  10372. do {
  10373. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10374. /* The request sent by the client could not be understood by
  10375. * the server, or it was incomplete or a timeout. Send an
  10376. * error message and close the connection. */
  10377. if (reqerr > 0) {
  10378. /*assert(ebuf[0] != '\0');*/
  10379. send_http_error(conn, reqerr, "%s", ebuf);
  10380. }
  10381. } else if (strcmp(ri->http_version, "1.0")
  10382. && strcmp(ri->http_version, "1.1")) {
  10383. mg_snprintf(conn,
  10384. NULL, /* No truncation check for ebuf */
  10385. ebuf,
  10386. sizeof(ebuf),
  10387. "Bad HTTP version: [%s]",
  10388. ri->http_version);
  10389. send_http_error(conn, 505, "%s", ebuf);
  10390. }
  10391. if (ebuf[0] == '\0') {
  10392. uri_type = get_uri_type(conn->request_info.request_uri);
  10393. switch (uri_type) {
  10394. case 1:
  10395. /* Asterisk */
  10396. conn->request_info.local_uri = NULL;
  10397. break;
  10398. case 2:
  10399. /* relative uri */
  10400. conn->request_info.local_uri =
  10401. conn->request_info.request_uri;
  10402. break;
  10403. case 3:
  10404. case 4:
  10405. /* absolute uri (with/without port) */
  10406. hostend = get_rel_url_at_current_server(
  10407. conn->request_info.request_uri, conn);
  10408. if (hostend) {
  10409. conn->request_info.local_uri = hostend;
  10410. } else {
  10411. conn->request_info.local_uri = NULL;
  10412. }
  10413. break;
  10414. default:
  10415. mg_snprintf(conn,
  10416. NULL, /* No truncation check for ebuf */
  10417. ebuf,
  10418. sizeof(ebuf),
  10419. "Invalid URI: [%s]",
  10420. ri->request_uri);
  10421. send_http_error(conn, 400, "%s", ebuf);
  10422. break;
  10423. }
  10424. /* TODO: cleanup uri, local_uri and request_uri */
  10425. conn->request_info.uri = conn->request_info.local_uri;
  10426. }
  10427. if (ebuf[0] == '\0') {
  10428. if (conn->request_info.local_uri) {
  10429. /* handle request to local server */
  10430. handle_request(conn);
  10431. if (conn->ctx->callbacks.end_request != NULL) {
  10432. conn->ctx->callbacks.end_request(conn,
  10433. conn->status_code);
  10434. }
  10435. log_access(conn);
  10436. } else {
  10437. /* TODO: handle non-local request (PROXY) */
  10438. conn->must_close = 1;
  10439. }
  10440. } else {
  10441. conn->must_close = 1;
  10442. }
  10443. if (ri->remote_user != NULL) {
  10444. mg_free((void *)ri->remote_user);
  10445. /* Important! When having connections with and without auth
  10446. * would cause double free and then crash */
  10447. ri->remote_user = NULL;
  10448. }
  10449. /* NOTE(lsm): order is important here. should_keep_alive() call
  10450. * is
  10451. * using parsed request, which will be invalid after memmove's
  10452. * below.
  10453. * Therefore, memorize should_keep_alive() result now for later
  10454. * use
  10455. * in loop exit condition. */
  10456. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10457. && conn->content_len >= 0 && should_keep_alive(conn);
  10458. /* Discard all buffered data for this request */
  10459. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10460. && conn->request_len + conn->content_len
  10461. < (int64_t)conn->data_len
  10462. ? (int)(conn->request_len + conn->content_len)
  10463. : conn->data_len;
  10464. /*assert(discard_len >= 0);*/
  10465. if (discard_len < 0)
  10466. break;
  10467. conn->data_len -= discard_len;
  10468. if (conn->data_len > 0) {
  10469. memmove(conn->buf,
  10470. conn->buf + discard_len,
  10471. (size_t)conn->data_len);
  10472. }
  10473. /* assert(conn->data_len >= 0); */
  10474. /* assert(conn->data_len <= conn->buf_size); */
  10475. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10476. break;
  10477. }
  10478. } while (keep_alive);
  10479. }
  10480. }
  10481. /* Worker threads take accepted socket from the queue */
  10482. static int
  10483. consume_socket(struct mg_context *ctx, struct socket *sp)
  10484. {
  10485. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10486. if (!ctx) {
  10487. return 0;
  10488. }
  10489. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10490. DEBUG_TRACE("%s", "going idle");
  10491. /* If the queue is empty, wait. We're idle at this point. */
  10492. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10493. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10494. }
  10495. /* If we're stopping, sq_head may be equal to sq_tail. */
  10496. if (ctx->sq_head > ctx->sq_tail) {
  10497. /* Copy socket from the queue and increment tail */
  10498. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10499. ctx->sq_tail++;
  10500. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10501. /* Wrap pointers if needed */
  10502. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10503. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10504. ctx->sq_head -= QUEUE_SIZE(ctx);
  10505. }
  10506. }
  10507. (void)pthread_cond_signal(&ctx->sq_empty);
  10508. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10509. return !ctx->stop_flag;
  10510. #undef QUEUE_SIZE
  10511. }
  10512. static void *
  10513. worker_thread_run(void *thread_func_param)
  10514. {
  10515. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10516. struct mg_connection *conn;
  10517. struct mg_workerTLS tls;
  10518. #if defined(MG_LEGACY_INTERFACE)
  10519. uint32_t addr;
  10520. #endif
  10521. mg_set_thread_name("worker");
  10522. tls.is_master = 0;
  10523. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10524. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10525. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10526. #endif
  10527. conn =
  10528. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10529. if (conn == NULL) {
  10530. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10531. } else {
  10532. pthread_setspecific(sTlsKey, &tls);
  10533. conn->buf_size = MAX_REQUEST_SIZE;
  10534. conn->buf = (char *)(conn + 1);
  10535. conn->ctx = ctx;
  10536. conn->request_info.user_data = ctx->user_data;
  10537. /* Allocate a mutex for this connection to allow communication both
  10538. * within the request handler and from elsewhere in the application
  10539. */
  10540. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10541. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10542. * signal sq_empty condvar to wake up the master waiting in
  10543. * produce_socket() */
  10544. while (consume_socket(ctx, &conn->client)) {
  10545. conn->conn_birth_time = time(NULL);
  10546. /* Fill in IP, port info early so even if SSL setup below fails,
  10547. * error handler would have the corresponding info.
  10548. * Thanks to Johannes Winkelmann for the patch.
  10549. */
  10550. #if defined(USE_IPV6)
  10551. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10552. conn->request_info.remote_port =
  10553. ntohs(conn->client.rsa.sin6.sin6_port);
  10554. } else
  10555. #endif
  10556. {
  10557. conn->request_info.remote_port =
  10558. ntohs(conn->client.rsa.sin.sin_port);
  10559. }
  10560. sockaddr_to_string(conn->request_info.remote_addr,
  10561. sizeof(conn->request_info.remote_addr),
  10562. &conn->client.rsa);
  10563. #if defined(MG_LEGACY_INTERFACE)
  10564. /* This legacy interface only works for the IPv4 case */
  10565. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10566. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10567. #endif
  10568. conn->request_info.is_ssl = conn->client.is_ssl;
  10569. if (!conn->client.is_ssl
  10570. #ifndef NO_SSL
  10571. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10572. #endif
  10573. ) {
  10574. process_new_connection(conn);
  10575. }
  10576. close_connection(conn);
  10577. }
  10578. }
  10579. /* Signal master that we're done with connection and exiting */
  10580. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10581. ctx->running_worker_threads--;
  10582. (void)pthread_cond_signal(&ctx->thread_cond);
  10583. /* assert(ctx->running_worker_threads >= 0); */
  10584. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10585. pthread_setspecific(sTlsKey, NULL);
  10586. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10587. CloseHandle(tls.pthread_cond_helper_mutex);
  10588. #endif
  10589. pthread_mutex_destroy(&conn->mutex);
  10590. mg_free(conn);
  10591. DEBUG_TRACE("%s", "exiting");
  10592. return NULL;
  10593. }
  10594. /* Threads have different return types on Windows and Unix. */
  10595. #ifdef _WIN32
  10596. static unsigned __stdcall worker_thread(void *thread_func_param)
  10597. {
  10598. worker_thread_run(thread_func_param);
  10599. return 0;
  10600. }
  10601. #else
  10602. static void *
  10603. worker_thread(void *thread_func_param)
  10604. {
  10605. worker_thread_run(thread_func_param);
  10606. return NULL;
  10607. }
  10608. #endif /* _WIN32 */
  10609. /* Master thread adds accepted socket to a queue */
  10610. static void
  10611. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10612. {
  10613. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10614. if (!ctx) {
  10615. return;
  10616. }
  10617. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10618. /* If the queue is full, wait */
  10619. while (ctx->stop_flag == 0
  10620. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10621. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10622. }
  10623. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10624. /* Copy socket to the queue and increment head */
  10625. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10626. ctx->sq_head++;
  10627. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10628. }
  10629. (void)pthread_cond_signal(&ctx->sq_full);
  10630. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10631. #undef QUEUE_SIZE
  10632. }
  10633. static void
  10634. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10635. {
  10636. struct socket so;
  10637. char src_addr[IP_ADDR_STR_LEN];
  10638. socklen_t len = sizeof(so.rsa);
  10639. int on = 1;
  10640. int timeout;
  10641. if (!listener) {
  10642. return;
  10643. }
  10644. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10645. == INVALID_SOCKET) {
  10646. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10647. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10648. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10649. closesocket(so.sock);
  10650. so.sock = INVALID_SOCKET;
  10651. } else {
  10652. /* Put so socket structure into the queue */
  10653. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10654. set_close_on_exec(so.sock, fc(ctx));
  10655. so.is_ssl = listener->is_ssl;
  10656. so.ssl_redir = listener->ssl_redir;
  10657. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10658. mg_cry(fc(ctx),
  10659. "%s: getsockname() failed: %s",
  10660. __func__,
  10661. strerror(ERRNO));
  10662. }
  10663. /* Set TCP keep-alive. This is needed because if HTTP-level
  10664. * keep-alive
  10665. * is enabled, and client resets the connection, server won't get
  10666. * TCP FIN or RST and will keep the connection open forever. With
  10667. * TCP keep-alive, next keep-alive handshake will figure out that
  10668. * the client is down and will close the server end.
  10669. * Thanks to Igor Klopov who suggested the patch. */
  10670. if (setsockopt(so.sock,
  10671. SOL_SOCKET,
  10672. SO_KEEPALIVE,
  10673. (SOCK_OPT_TYPE)&on,
  10674. sizeof(on)) != 0) {
  10675. mg_cry(fc(ctx),
  10676. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10677. __func__,
  10678. strerror(ERRNO));
  10679. }
  10680. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  10681. * to effectively fill up the underlying IP packet payload and reduce
  10682. * the overhead of sending lots of small buffers. However this hurts
  10683. * the server's throughput (ie. operations per second) when HTTP 1.1
  10684. * persistent connections are used and the responses are relatively
  10685. * small (eg. less than 1400 bytes).
  10686. */
  10687. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  10688. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  10689. if (set_tcp_nodelay(so.sock, 1) != 0) {
  10690. mg_cry(fc(ctx),
  10691. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  10692. __func__,
  10693. strerror(ERRNO));
  10694. }
  10695. }
  10696. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10697. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10698. } else {
  10699. timeout = -1;
  10700. }
  10701. /* Set socket timeout to the given value, but not more than a
  10702. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10703. * so the server can exit after that time if requested. */
  10704. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10705. set_sock_timeout(so.sock, timeout);
  10706. } else {
  10707. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10708. }
  10709. produce_socket(ctx, &so);
  10710. }
  10711. }
  10712. static void
  10713. master_thread_run(void *thread_func_param)
  10714. {
  10715. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10716. struct mg_workerTLS tls;
  10717. struct pollfd *pfd;
  10718. unsigned int i;
  10719. unsigned int workerthreadcount;
  10720. if (!ctx) {
  10721. return;
  10722. }
  10723. mg_set_thread_name("master");
  10724. /* Increase priority of the master thread */
  10725. #if defined(_WIN32)
  10726. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10727. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10728. int min_prio = sched_get_priority_min(SCHED_RR);
  10729. int max_prio = sched_get_priority_max(SCHED_RR);
  10730. if ((min_prio >= 0) && (max_prio >= 0)
  10731. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10732. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10733. struct sched_param sched_param = {0};
  10734. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10735. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10736. }
  10737. #endif
  10738. /* Initialize thread local storage */
  10739. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10740. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10741. #endif
  10742. tls.is_master = 1;
  10743. pthread_setspecific(sTlsKey, &tls);
  10744. /* Server starts *now* */
  10745. ctx->start_time = time(NULL);
  10746. /* Allocate memory for the listening sockets, and start the server */
  10747. pfd =
  10748. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10749. while (pfd != NULL && ctx->stop_flag == 0) {
  10750. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10751. pfd[i].fd = ctx->listening_sockets[i].sock;
  10752. pfd[i].events = POLLIN;
  10753. }
  10754. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10755. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10756. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10757. * successful poll, and POLLIN is defined as
  10758. * (POLLRDNORM | POLLRDBAND)
  10759. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10760. * pfd[i].revents == POLLIN. */
  10761. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10762. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10763. }
  10764. }
  10765. }
  10766. }
  10767. mg_free(pfd);
  10768. DEBUG_TRACE("%s", "stopping workers");
  10769. /* Stop signal received: somebody called mg_stop. Quit. */
  10770. close_all_listening_sockets(ctx);
  10771. /* Wakeup workers that are waiting for connections to handle. */
  10772. pthread_cond_broadcast(&ctx->sq_full);
  10773. /* Wait until all threads finish */
  10774. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10775. while (ctx->running_worker_threads > 0) {
  10776. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10777. }
  10778. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10779. /* Join all worker threads to avoid leaking threads. */
  10780. workerthreadcount = ctx->cfg_worker_threads;
  10781. for (i = 0; i < workerthreadcount; i++) {
  10782. if (ctx->workerthreadids[i] != 0) {
  10783. mg_join_thread(ctx->workerthreadids[i]);
  10784. }
  10785. }
  10786. #if !defined(NO_SSL)
  10787. if (ctx->ssl_ctx != NULL) {
  10788. uninitialize_ssl(ctx);
  10789. }
  10790. #endif
  10791. DEBUG_TRACE("%s", "exiting");
  10792. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10793. CloseHandle(tls.pthread_cond_helper_mutex);
  10794. #endif
  10795. pthread_setspecific(sTlsKey, NULL);
  10796. /* Signal mg_stop() that we're done.
  10797. * WARNING: This must be the very last thing this
  10798. * thread does, as ctx becomes invalid after this line. */
  10799. ctx->stop_flag = 2;
  10800. }
  10801. /* Threads have different return types on Windows and Unix. */
  10802. #ifdef _WIN32
  10803. static unsigned __stdcall master_thread(void *thread_func_param)
  10804. {
  10805. master_thread_run(thread_func_param);
  10806. return 0;
  10807. }
  10808. #else
  10809. static void *
  10810. master_thread(void *thread_func_param)
  10811. {
  10812. master_thread_run(thread_func_param);
  10813. return NULL;
  10814. }
  10815. #endif /* _WIN32 */
  10816. static void
  10817. free_context(struct mg_context *ctx)
  10818. {
  10819. int i;
  10820. struct mg_handler_info *tmp_rh;
  10821. if (ctx == NULL) {
  10822. return;
  10823. }
  10824. if (ctx->callbacks.exit_context) {
  10825. ctx->callbacks.exit_context(ctx);
  10826. }
  10827. /* All threads exited, no sync is needed. Destroy thread mutex and
  10828. * condvars
  10829. */
  10830. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10831. (void)pthread_cond_destroy(&ctx->thread_cond);
  10832. (void)pthread_cond_destroy(&ctx->sq_empty);
  10833. (void)pthread_cond_destroy(&ctx->sq_full);
  10834. /* Destroy other context global data structures mutex */
  10835. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10836. #if defined(USE_TIMERS)
  10837. timers_exit(ctx);
  10838. #endif
  10839. /* Deallocate config parameters */
  10840. for (i = 0; i < NUM_OPTIONS; i++) {
  10841. if (ctx->config[i] != NULL) {
  10842. #if defined(_MSC_VER)
  10843. #pragma warning(suppress : 6001)
  10844. #endif
  10845. mg_free(ctx->config[i]);
  10846. }
  10847. }
  10848. /* Deallocate request handlers */
  10849. while (ctx->handlers) {
  10850. tmp_rh = ctx->handlers;
  10851. ctx->handlers = tmp_rh->next;
  10852. mg_free(tmp_rh->uri);
  10853. mg_free(tmp_rh);
  10854. }
  10855. #ifndef NO_SSL
  10856. /* Deallocate SSL context */
  10857. if (ctx->ssl_ctx != NULL) {
  10858. SSL_CTX_free(ctx->ssl_ctx);
  10859. }
  10860. #endif /* !NO_SSL */
  10861. /* Deallocate worker thread ID array */
  10862. if (ctx->workerthreadids != NULL) {
  10863. mg_free(ctx->workerthreadids);
  10864. }
  10865. /* Deallocate the tls variable */
  10866. if (mg_atomic_dec(&sTlsInit) == 0) {
  10867. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10868. DeleteCriticalSection(&global_log_file_lock);
  10869. #endif /* _WIN32 && !__SYMBIAN32__ */
  10870. #if !defined(_WIN32)
  10871. pthread_mutexattr_destroy(&pthread_mutex_attr);
  10872. #endif
  10873. pthread_key_delete(sTlsKey);
  10874. }
  10875. /* deallocate system name string */
  10876. mg_free(ctx->systemName);
  10877. /* Deallocate context itself */
  10878. mg_free(ctx);
  10879. }
  10880. void
  10881. mg_stop(struct mg_context *ctx)
  10882. {
  10883. pthread_t mt;
  10884. if (!ctx) {
  10885. return;
  10886. }
  10887. /* We don't use a lock here. Calling mg_stop with the same ctx from
  10888. * two threads is not allowed. */
  10889. mt = ctx->masterthreadid;
  10890. if (mt == 0) {
  10891. return;
  10892. }
  10893. ctx->masterthreadid = 0;
  10894. ctx->stop_flag = 1;
  10895. /* Wait until mg_fini() stops */
  10896. while (ctx->stop_flag != 2) {
  10897. (void)mg_sleep(10);
  10898. }
  10899. mg_join_thread(mt);
  10900. free_context(ctx);
  10901. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10902. (void)WSACleanup();
  10903. #endif /* _WIN32 && !__SYMBIAN32__ */
  10904. }
  10905. static void
  10906. get_system_name(char **sysName)
  10907. {
  10908. #if defined(_WIN32)
  10909. #if !defined(__SYMBIAN32__)
  10910. char name[128];
  10911. DWORD dwVersion = 0;
  10912. DWORD dwMajorVersion = 0;
  10913. DWORD dwMinorVersion = 0;
  10914. DWORD dwBuild = 0;
  10915. #ifdef _MSC_VER
  10916. #pragma warning(push)
  10917. // GetVersion was declared deprecated
  10918. #pragma warning(disable : 4996)
  10919. #endif
  10920. dwVersion = GetVersion();
  10921. #ifdef _MSC_VER
  10922. #pragma warning(pop)
  10923. #endif
  10924. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  10925. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  10926. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  10927. (void)dwBuild;
  10928. sprintf(name,
  10929. "Windows %u.%u",
  10930. (unsigned)dwMajorVersion,
  10931. (unsigned)dwMinorVersion);
  10932. *sysName = mg_strdup(name);
  10933. #else
  10934. *sysName = mg_strdup("Symbian");
  10935. #endif
  10936. #else
  10937. struct utsname name;
  10938. memset(&name, 0, sizeof(name));
  10939. uname(&name);
  10940. *sysName = mg_strdup(name.sysname);
  10941. #endif
  10942. }
  10943. struct mg_context *
  10944. mg_start(const struct mg_callbacks *callbacks,
  10945. void *user_data,
  10946. const char **options)
  10947. {
  10948. struct mg_context *ctx;
  10949. const char *name, *value, *default_value;
  10950. int idx, ok, workerthreadcount;
  10951. unsigned int i;
  10952. void (*exit_callback)(const struct mg_context *ctx) = 0;
  10953. struct mg_workerTLS tls;
  10954. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10955. WSADATA data;
  10956. WSAStartup(MAKEWORD(2, 2), &data);
  10957. #endif /* _WIN32 && !__SYMBIAN32__ */
  10958. /* Allocate context and initialize reasonable general case defaults. */
  10959. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  10960. return NULL;
  10961. }
  10962. /* Random number generator will initialize at the first call */
  10963. ctx->auth_nonce_mask =
  10964. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  10965. if (mg_atomic_inc(&sTlsInit) == 1) {
  10966. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10967. InitializeCriticalSection(&global_log_file_lock);
  10968. #endif /* _WIN32 && !__SYMBIAN32__ */
  10969. #if !defined(_WIN32)
  10970. pthread_mutexattr_init(&pthread_mutex_attr);
  10971. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  10972. #endif
  10973. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  10974. /* Fatal error - abort start. However, this situation should
  10975. * never
  10976. * occur in practice. */
  10977. mg_atomic_dec(&sTlsInit);
  10978. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  10979. mg_free(ctx);
  10980. return NULL;
  10981. }
  10982. } else {
  10983. /* TODO (low): istead of sleeping, check if sTlsKey is already
  10984. * initialized. */
  10985. mg_sleep(1);
  10986. }
  10987. tls.is_master = -1;
  10988. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10989. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10990. tls.pthread_cond_helper_mutex = NULL;
  10991. #endif
  10992. pthread_setspecific(sTlsKey, &tls);
  10993. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  10994. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  10995. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  10996. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  10997. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  10998. if (!ok) {
  10999. /* Fatal error - abort start. However, this situation should never
  11000. * occur in practice. */
  11001. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11002. mg_free(ctx);
  11003. pthread_setspecific(sTlsKey, NULL);
  11004. return NULL;
  11005. }
  11006. if (callbacks) {
  11007. ctx->callbacks = *callbacks;
  11008. exit_callback = callbacks->exit_context;
  11009. ctx->callbacks.exit_context = 0;
  11010. }
  11011. ctx->user_data = user_data;
  11012. ctx->handlers = NULL;
  11013. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11014. ctx->shared_lua_websockets = 0;
  11015. #endif
  11016. while (options && (name = *options++) != NULL) {
  11017. if ((idx = get_option_index(name)) == -1) {
  11018. mg_cry(fc(ctx), "Invalid option: %s", name);
  11019. free_context(ctx);
  11020. pthread_setspecific(sTlsKey, NULL);
  11021. return NULL;
  11022. } else if ((value = *options++) == NULL) {
  11023. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11024. free_context(ctx);
  11025. pthread_setspecific(sTlsKey, NULL);
  11026. return NULL;
  11027. }
  11028. if (ctx->config[idx] != NULL) {
  11029. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11030. mg_free(ctx->config[idx]);
  11031. }
  11032. ctx->config[idx] = mg_strdup(value);
  11033. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11034. }
  11035. /* Set default value if needed */
  11036. for (i = 0; config_options[i].name != NULL; i++) {
  11037. default_value = config_options[i].default_value;
  11038. if (ctx->config[i] == NULL && default_value != NULL) {
  11039. ctx->config[i] = mg_strdup(default_value);
  11040. }
  11041. }
  11042. #if defined(NO_FILES)
  11043. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11044. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11045. free_context(ctx);
  11046. pthread_setspecific(sTlsKey, NULL);
  11047. return NULL;
  11048. }
  11049. #endif
  11050. get_system_name(&ctx->systemName);
  11051. /* NOTE(lsm): order is important here. SSL certificates must
  11052. * be initialized before listening ports. UID must be set last. */
  11053. if (!set_gpass_option(ctx) ||
  11054. #if !defined(NO_SSL)
  11055. !set_ssl_option(ctx) ||
  11056. #endif
  11057. !set_ports_option(ctx) ||
  11058. #if !defined(_WIN32)
  11059. !set_uid_option(ctx) ||
  11060. #endif
  11061. !set_acl_option(ctx)) {
  11062. free_context(ctx);
  11063. pthread_setspecific(sTlsKey, NULL);
  11064. return NULL;
  11065. }
  11066. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11067. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11068. * won't kill the whole process. */
  11069. (void)signal(SIGPIPE, SIG_IGN);
  11070. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11071. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11072. if (workerthreadcount > MAX_WORKER_THREADS) {
  11073. mg_cry(fc(ctx), "Too many worker threads");
  11074. free_context(ctx);
  11075. pthread_setspecific(sTlsKey, NULL);
  11076. return NULL;
  11077. }
  11078. if (workerthreadcount > 0) {
  11079. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11080. ctx->workerthreadids =
  11081. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11082. if (ctx->workerthreadids == NULL) {
  11083. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11084. free_context(ctx);
  11085. pthread_setspecific(sTlsKey, NULL);
  11086. return NULL;
  11087. }
  11088. }
  11089. #if defined(USE_TIMERS)
  11090. if (timers_init(ctx) != 0) {
  11091. mg_cry(fc(ctx), "Error creating timers");
  11092. free_context(ctx);
  11093. pthread_setspecific(sTlsKey, NULL);
  11094. return NULL;
  11095. }
  11096. #endif
  11097. /* Context has been created - init user libraries */
  11098. if (ctx->callbacks.init_context) {
  11099. ctx->callbacks.init_context(ctx);
  11100. }
  11101. ctx->callbacks.exit_context = exit_callback;
  11102. ctx->context_type = 1; /* server context */
  11103. /* Start master (listening) thread */
  11104. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11105. /* Start worker threads */
  11106. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11107. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11108. ctx->running_worker_threads++;
  11109. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11110. if (mg_start_thread_with_id(worker_thread,
  11111. ctx,
  11112. &ctx->workerthreadids[i]) != 0) {
  11113. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11114. ctx->running_worker_threads--;
  11115. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11116. if (i > 0) {
  11117. mg_cry(fc(ctx),
  11118. "Cannot start worker thread %i: error %ld",
  11119. i + 1,
  11120. (long)ERRNO);
  11121. } else {
  11122. mg_cry(fc(ctx),
  11123. "Cannot create threads: error %ld",
  11124. (long)ERRNO);
  11125. free_context(ctx);
  11126. pthread_setspecific(sTlsKey, NULL);
  11127. return NULL;
  11128. }
  11129. break;
  11130. }
  11131. }
  11132. pthread_setspecific(sTlsKey, NULL);
  11133. return ctx;
  11134. }
  11135. /* Feature check API function */
  11136. unsigned
  11137. mg_check_feature(unsigned feature)
  11138. {
  11139. static const unsigned feature_set = 0
  11140. /* Set bits for available features according to API documentation.
  11141. * This bit mask is created at compile time, according to the active
  11142. * preprocessor defines. It is a single const value at runtime. */
  11143. #if !defined(NO_FILES)
  11144. | 1
  11145. #endif
  11146. #if !defined(NO_SSL)
  11147. | 2
  11148. #endif
  11149. #if !defined(NO_CGI)
  11150. | 4
  11151. #endif
  11152. #if defined(USE_IPV6)
  11153. | 8
  11154. #endif
  11155. #if defined(USE_WEBSOCKET)
  11156. | 16
  11157. #endif
  11158. #if defined(USE_LUA)
  11159. | 32
  11160. #endif
  11161. #if defined(USE_DUKTAPE)
  11162. | 64
  11163. #endif
  11164. /* Set some extra bits not defined in the API documentation.
  11165. * These bits may change without further notice. */
  11166. #if defined(MG_LEGACY_INTERFACE)
  11167. | 128
  11168. #endif
  11169. #if defined(MEMORY_DEBUGGING)
  11170. | 256
  11171. #endif
  11172. #if defined(USE_TIMERS)
  11173. | 512
  11174. #endif
  11175. #if !defined(NO_NONCE_CHECK)
  11176. | 1024
  11177. #endif
  11178. #if !defined(NO_POPEN)
  11179. | 2048
  11180. #endif
  11181. ;
  11182. return (feature & feature_set);
  11183. }