civetweb.c 335 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955
  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. /* mg_fopen will open a file either in memory or on the disk.
  1299. * The input parameter path is a string in UTF-8 encoding.
  1300. * The input parameter mode is the same as for fopen.
  1301. * Either fp or membuf will be set in the output struct filep.
  1302. * The function returns 1 on success, 0 on error. */
  1303. static int
  1304. mg_fopen(const struct mg_connection *conn,
  1305. const char *path,
  1306. const char *mode,
  1307. struct file *filep)
  1308. {
  1309. struct stat st;
  1310. if (!filep) {
  1311. return 0;
  1312. }
  1313. /* TODO (high): mg_fopen should only open a file, while mg_stat should
  1314. * only get the file status. They should not work on different members of
  1315. * the same structure (bad cohesion). */
  1316. memset(filep, 0, sizeof(*filep));
  1317. if (stat(path, &st) == 0) {
  1318. filep->size = (uint64_t)(st.st_size);
  1319. }
  1320. if (!is_file_in_memory(conn, path, filep)) {
  1321. #ifdef _WIN32
  1322. wchar_t wbuf[PATH_MAX], wmode[20];
  1323. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1324. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1325. filep->fp = _wfopen(wbuf, wmode);
  1326. #else
  1327. /* Linux et al already use unicode. No need to convert. */
  1328. filep->fp = fopen(path, mode);
  1329. #endif
  1330. }
  1331. return is_file_opened(filep);
  1332. }
  1333. static void
  1334. mg_fclose(struct file *filep)
  1335. {
  1336. if (filep != NULL && filep->fp != NULL) {
  1337. fclose(filep->fp);
  1338. }
  1339. }
  1340. static void
  1341. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1342. {
  1343. for (; *src != '\0' && n > 1; n--) {
  1344. *dst++ = *src++;
  1345. }
  1346. *dst = '\0';
  1347. }
  1348. static int
  1349. lowercase(const char *s)
  1350. {
  1351. return tolower(*(const unsigned char *)s);
  1352. }
  1353. int
  1354. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1355. {
  1356. int diff = 0;
  1357. if (len > 0) {
  1358. do {
  1359. diff = lowercase(s1++) - lowercase(s2++);
  1360. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1361. }
  1362. return diff;
  1363. }
  1364. static int
  1365. mg_strcasecmp(const char *s1, const char *s2)
  1366. {
  1367. int diff;
  1368. do {
  1369. diff = lowercase(s1++) - lowercase(s2++);
  1370. } while (diff == 0 && s1[-1] != '\0');
  1371. return diff;
  1372. }
  1373. static char *
  1374. mg_strndup(const char *ptr, size_t len)
  1375. {
  1376. char *p;
  1377. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1378. mg_strlcpy(p, ptr, len + 1);
  1379. }
  1380. return p;
  1381. }
  1382. static char *
  1383. mg_strdup(const char *str)
  1384. {
  1385. return mg_strndup(str, strlen(str));
  1386. }
  1387. static const char *
  1388. mg_strcasestr(const char *big_str, const char *small_str)
  1389. {
  1390. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1391. if (big_len >= small_len) {
  1392. for (i = 0; i <= (big_len - small_len); i++) {
  1393. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1394. return big_str + i;
  1395. }
  1396. }
  1397. }
  1398. return NULL;
  1399. }
  1400. /* Return null terminated string of given maximum length.
  1401. * Report errors if length is exceeded. */
  1402. static void
  1403. mg_vsnprintf(const struct mg_connection *conn,
  1404. int *truncated,
  1405. char *buf,
  1406. size_t buflen,
  1407. const char *fmt,
  1408. va_list ap)
  1409. {
  1410. int n, ok;
  1411. if (buflen == 0) {
  1412. return;
  1413. }
  1414. #ifdef __clang__
  1415. #pragma clang diagnostic push
  1416. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1417. /* Using fmt as a non-literal is intended here, since it is mostly called
  1418. * indirectly by mg_snprintf */
  1419. #endif
  1420. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1421. ok = (n >= 0) && ((size_t)n < buflen);
  1422. #ifdef __clang__
  1423. #pragma clang diagnostic pop
  1424. #endif
  1425. if (ok) {
  1426. if (truncated) {
  1427. *truncated = 0;
  1428. }
  1429. } else {
  1430. if (truncated) {
  1431. *truncated = 1;
  1432. }
  1433. mg_cry(conn,
  1434. "truncating vsnprintf buffer: [%.*s]",
  1435. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1436. buf);
  1437. n = (int)buflen - 1;
  1438. }
  1439. buf[n] = '\0';
  1440. }
  1441. static void
  1442. mg_snprintf(const struct mg_connection *conn,
  1443. int *truncated,
  1444. char *buf,
  1445. size_t buflen,
  1446. const char *fmt,
  1447. ...)
  1448. {
  1449. va_list ap;
  1450. va_start(ap, fmt);
  1451. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  1452. va_end(ap);
  1453. }
  1454. static int
  1455. get_option_index(const char *name)
  1456. {
  1457. int i;
  1458. for (i = 0; config_options[i].name != NULL; i++) {
  1459. if (strcmp(config_options[i].name, name) == 0) {
  1460. return i;
  1461. }
  1462. }
  1463. return -1;
  1464. }
  1465. const char *
  1466. mg_get_option(const struct mg_context *ctx, const char *name)
  1467. {
  1468. int i;
  1469. if ((i = get_option_index(name)) == -1) {
  1470. return NULL;
  1471. } else if (!ctx || ctx->config[i] == NULL) {
  1472. return "";
  1473. } else {
  1474. return ctx->config[i];
  1475. }
  1476. }
  1477. struct mg_context *
  1478. mg_get_context(const struct mg_connection *conn)
  1479. {
  1480. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1481. }
  1482. void *
  1483. mg_get_user_data(const struct mg_context *ctx)
  1484. {
  1485. return (ctx == NULL) ? NULL : ctx->user_data;
  1486. }
  1487. void
  1488. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  1489. {
  1490. if (conn != NULL) {
  1491. conn->request_info.conn_data = data;
  1492. }
  1493. }
  1494. void *
  1495. mg_get_user_connection_data(const struct mg_connection *conn)
  1496. {
  1497. if (conn != NULL) {
  1498. return conn->request_info.conn_data;
  1499. }
  1500. return NULL;
  1501. }
  1502. size_t
  1503. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1504. {
  1505. size_t i;
  1506. if (!ctx) {
  1507. return 0;
  1508. }
  1509. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1510. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1511. ports[i] = ctx->listening_ports[i];
  1512. }
  1513. return i;
  1514. }
  1515. int
  1516. mg_get_server_ports(const struct mg_context *ctx,
  1517. int size,
  1518. struct mg_server_ports *ports)
  1519. {
  1520. int i, cnt = 0;
  1521. if (size <= 0) {
  1522. return -1;
  1523. }
  1524. memset(ports, 0, sizeof(*ports) * (size_t)size);
  1525. if (!ctx) {
  1526. return -1;
  1527. }
  1528. if (!ctx->listening_sockets || !ctx->listening_ports) {
  1529. return -1;
  1530. }
  1531. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  1532. ports[cnt].port = ctx->listening_ports[i];
  1533. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  1534. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  1535. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  1536. /* IPv4 */
  1537. ports[cnt].protocol = 1;
  1538. cnt++;
  1539. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  1540. /* IPv6 */
  1541. ports[cnt].protocol = 3;
  1542. cnt++;
  1543. }
  1544. }
  1545. return cnt;
  1546. }
  1547. static void
  1548. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1549. {
  1550. buf[0] = '\0';
  1551. if (!usa) {
  1552. return;
  1553. }
  1554. if (usa->sa.sa_family == AF_INET) {
  1555. getnameinfo(&usa->sa,
  1556. sizeof(usa->sin),
  1557. buf,
  1558. (unsigned)len,
  1559. NULL,
  1560. 0,
  1561. NI_NUMERICHOST);
  1562. }
  1563. #if defined(USE_IPV6)
  1564. else if (usa->sa.sa_family == AF_INET6) {
  1565. getnameinfo(&usa->sa,
  1566. sizeof(usa->sin6),
  1567. buf,
  1568. (unsigned)len,
  1569. NULL,
  1570. 0,
  1571. NI_NUMERICHOST);
  1572. }
  1573. #endif
  1574. }
  1575. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1576. * included in all responses other than 100, 101, 5xx. */
  1577. static void
  1578. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1579. {
  1580. struct tm *tm;
  1581. tm = gmtime(t);
  1582. if (tm != NULL) {
  1583. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1584. } else {
  1585. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1586. buf[buf_len - 1] = '\0';
  1587. }
  1588. }
  1589. /* difftime for struct timespec. Return value is in seconds. */
  1590. static double
  1591. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  1592. {
  1593. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  1594. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  1595. }
  1596. /* Print error message to the opened error log stream. */
  1597. void
  1598. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1599. {
  1600. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1601. va_list ap;
  1602. struct file fi;
  1603. time_t timestamp;
  1604. va_start(ap, fmt);
  1605. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  1606. va_end(ap);
  1607. buf[sizeof(buf) - 1] = 0;
  1608. if (!conn) {
  1609. puts(buf);
  1610. return;
  1611. }
  1612. /* Do not lock when getting the callback value, here and below.
  1613. * I suppose this is fine, since function cannot disappear in the
  1614. * same way string option can. */
  1615. if ((conn->ctx->callbacks.log_message == NULL)
  1616. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1617. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  1618. if (mg_fopen(conn, conn->ctx->config[ERROR_LOG_FILE], "a+", &fi)
  1619. == 0) {
  1620. fi.fp = NULL;
  1621. }
  1622. } else {
  1623. fi.fp = NULL;
  1624. }
  1625. if (fi.fp != NULL) {
  1626. flockfile(fi.fp);
  1627. timestamp = time(NULL);
  1628. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1629. fprintf(fi.fp,
  1630. "[%010lu] [error] [client %s] ",
  1631. (unsigned long)timestamp,
  1632. src_addr);
  1633. if (conn->request_info.request_method != NULL) {
  1634. fprintf(fi.fp,
  1635. "%s %s: ",
  1636. conn->request_info.request_method,
  1637. conn->request_info.request_uri);
  1638. }
  1639. fprintf(fi.fp, "%s", buf);
  1640. fputc('\n', fi.fp);
  1641. fflush(fi.fp);
  1642. funlockfile(fi.fp);
  1643. mg_fclose(&fi);
  1644. }
  1645. }
  1646. }
  1647. /* Return fake connection structure. Used for logging, if connection
  1648. * is not applicable at the moment of logging. */
  1649. static struct mg_connection *
  1650. fc(struct mg_context *ctx)
  1651. {
  1652. static struct mg_connection fake_connection;
  1653. fake_connection.ctx = ctx;
  1654. return &fake_connection;
  1655. }
  1656. const char *
  1657. mg_version(void)
  1658. {
  1659. return CIVETWEB_VERSION;
  1660. }
  1661. const struct mg_request_info *
  1662. mg_get_request_info(const struct mg_connection *conn)
  1663. {
  1664. if (!conn) {
  1665. return NULL;
  1666. }
  1667. return &conn->request_info;
  1668. }
  1669. /* Skip the characters until one of the delimiters characters found.
  1670. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1671. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1672. * Delimiters can be quoted with quotechar. */
  1673. static char *
  1674. skip_quoted(char **buf,
  1675. const char *delimiters,
  1676. const char *whitespace,
  1677. char quotechar)
  1678. {
  1679. char *p, *begin_word, *end_word, *end_whitespace;
  1680. begin_word = *buf;
  1681. end_word = begin_word + strcspn(begin_word, delimiters);
  1682. /* Check for quotechar */
  1683. if (end_word > begin_word) {
  1684. p = end_word - 1;
  1685. while (*p == quotechar) {
  1686. /* While the delimiter is quoted, look for the next delimiter. */
  1687. /* This happens, e.g., in calls from parse_auth_header,
  1688. * if the user name contains a " character. */
  1689. /* If there is anything beyond end_word, copy it. */
  1690. if (*end_word != '\0') {
  1691. size_t end_off = strcspn(end_word + 1, delimiters);
  1692. memmove(p, end_word, end_off + 1);
  1693. p += end_off; /* p must correspond to end_word - 1 */
  1694. end_word += end_off + 1;
  1695. } else {
  1696. *p = '\0';
  1697. break;
  1698. }
  1699. }
  1700. for (p++; p < end_word; p++) {
  1701. *p = '\0';
  1702. }
  1703. }
  1704. if (*end_word == '\0') {
  1705. *buf = end_word;
  1706. } else {
  1707. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1708. for (p = end_word; p < end_whitespace; p++) {
  1709. *p = '\0';
  1710. }
  1711. *buf = end_whitespace;
  1712. }
  1713. return begin_word;
  1714. }
  1715. /* Simplified version of skip_quoted without quote char
  1716. * and whitespace == delimiters */
  1717. static char *
  1718. skip(char **buf, const char *delimiters)
  1719. {
  1720. return skip_quoted(buf, delimiters, delimiters, 0);
  1721. }
  1722. /* Return HTTP header value, or NULL if not found. */
  1723. static const char *
  1724. get_header(const struct mg_request_info *ri, const char *name)
  1725. {
  1726. int i;
  1727. if (ri) {
  1728. for (i = 0; i < ri->num_headers; i++) {
  1729. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1730. return ri->http_headers[i].value;
  1731. }
  1732. }
  1733. }
  1734. return NULL;
  1735. }
  1736. const char *
  1737. mg_get_header(const struct mg_connection *conn, const char *name)
  1738. {
  1739. if (!conn) {
  1740. return NULL;
  1741. }
  1742. return get_header(&conn->request_info, name);
  1743. }
  1744. /* A helper function for traversing a comma separated list of values.
  1745. * It returns a list pointer shifted to the next value, or NULL if the end
  1746. * of the list found.
  1747. * Value is stored in val vector. If value has form "x=y", then eq_val
  1748. * vector is initialized to point to the "y" part, and val vector length
  1749. * is adjusted to point only to "x". */
  1750. static const char *
  1751. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1752. {
  1753. int end;
  1754. reparse:
  1755. if (val == NULL || list == NULL || *list == '\0') {
  1756. /* End of the list */
  1757. list = NULL;
  1758. } else {
  1759. /* Skip over leading LWS */
  1760. while (*list == ' ' || *list == '\t')
  1761. list++;
  1762. val->ptr = list;
  1763. if ((list = strchr(val->ptr, ',')) != NULL) {
  1764. /* Comma found. Store length and shift the list ptr */
  1765. val->len = ((size_t)(list - val->ptr));
  1766. list++;
  1767. } else {
  1768. /* This value is the last one */
  1769. list = val->ptr + strlen(val->ptr);
  1770. val->len = ((size_t)(list - val->ptr));
  1771. }
  1772. /* Adjust length for trailing LWS */
  1773. end = (int)val->len - 1;
  1774. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  1775. end--;
  1776. val->len = (size_t)(end + 1);
  1777. if (val->len == 0) {
  1778. /* Ignore any empty entries. */
  1779. goto reparse;
  1780. }
  1781. if (eq_val != NULL) {
  1782. /* Value has form "x=y", adjust pointers and lengths
  1783. * so that val points to "x", and eq_val points to "y". */
  1784. eq_val->len = 0;
  1785. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1786. if (eq_val->ptr != NULL) {
  1787. eq_val->ptr++; /* Skip over '=' character */
  1788. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1789. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1790. }
  1791. }
  1792. }
  1793. return list;
  1794. }
  1795. /* A helper function for checking if a comma separated list of values contains
  1796. * the given option (case insensitvely).
  1797. * 'header' can be NULL, in which case false is returned. */
  1798. static int
  1799. header_has_option(const char *header, const char *option)
  1800. {
  1801. struct vec opt_vec;
  1802. struct vec eq_vec;
  1803. assert(option != NULL);
  1804. assert(option[0] != '\0');
  1805. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  1806. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  1807. return 1;
  1808. }
  1809. return 0;
  1810. }
  1811. /* Perform case-insensitive match of string against pattern */
  1812. static int
  1813. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1814. {
  1815. const char *or_str;
  1816. size_t i;
  1817. int j, len, res;
  1818. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1819. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1820. return res > 0 ? res : match_prefix(or_str + 1,
  1821. (size_t)((pattern + pattern_len)
  1822. - (or_str + 1)),
  1823. str);
  1824. }
  1825. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1826. if (pattern[i] == '?' && str[j] != '\0') {
  1827. continue;
  1828. } else if (pattern[i] == '$') {
  1829. return str[j] == '\0' ? j : -1;
  1830. } else if (pattern[i] == '*') {
  1831. i++;
  1832. if (pattern[i] == '*') {
  1833. i++;
  1834. len = (int)strlen(str + j);
  1835. } else {
  1836. len = (int)strcspn(str + j, "/");
  1837. }
  1838. if (i == pattern_len) {
  1839. return j + len;
  1840. }
  1841. do {
  1842. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1843. } while (res == -1 && len-- > 0);
  1844. return res == -1 ? -1 : j + res + len;
  1845. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1846. return -1;
  1847. }
  1848. }
  1849. return j;
  1850. }
  1851. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1852. * This function must tolerate situations when connection info is not
  1853. * set up, for example if request parsing failed. */
  1854. static int
  1855. should_keep_alive(const struct mg_connection *conn)
  1856. {
  1857. if (conn != NULL) {
  1858. const char *http_version = conn->request_info.http_version;
  1859. const char *header = mg_get_header(conn, "Connection");
  1860. if (conn->must_close || conn->internal_error || conn->status_code == 401
  1861. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  1862. || (header != NULL && !header_has_option(header, "keep-alive"))
  1863. || (header == NULL && http_version
  1864. && 0 != strcmp(http_version, "1.1"))) {
  1865. return 0;
  1866. }
  1867. return 1;
  1868. }
  1869. return 0;
  1870. }
  1871. static int
  1872. should_decode_url(const struct mg_connection *conn)
  1873. {
  1874. if (!conn || !conn->ctx) {
  1875. return 0;
  1876. }
  1877. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1878. }
  1879. static const char *
  1880. suggest_connection_header(const struct mg_connection *conn)
  1881. {
  1882. return should_keep_alive(conn) ? "keep-alive" : "close";
  1883. }
  1884. static int
  1885. send_no_cache_header(struct mg_connection *conn)
  1886. {
  1887. /* Send all current and obsolete cache opt-out directives. */
  1888. return mg_printf(conn,
  1889. "Cache-Control: no-cache, no-store, "
  1890. "must-revalidate, private, max-age=0\r\n"
  1891. "Pragma: no-cache\r\n"
  1892. "Expires: 0\r\n");
  1893. }
  1894. static int
  1895. send_static_cache_header(struct mg_connection *conn)
  1896. {
  1897. /* Read the server config to check how long a file may be cached.
  1898. * The configuration is in seconds. */
  1899. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  1900. if (max_age <= 0) {
  1901. /* 0 means "do not cache". All values <0 are reserved
  1902. * and may be used differently in the future. */
  1903. /* If a file should not be cached, do not only send
  1904. * max-age=0, but also pragmas and Expires headers. */
  1905. return send_no_cache_header(conn);
  1906. }
  1907. /* Use "Cache-Control: max-age" instead of "Expires" header.
  1908. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  1909. /* See also https://www.mnot.net/cache_docs/ */
  1910. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  1911. }
  1912. static void handle_file_based_request(struct mg_connection *conn,
  1913. const char *path,
  1914. struct file *filep);
  1915. static int
  1916. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1917. static const char *
  1918. mg_get_response_code_text(int response_code, struct mg_connection *conn)
  1919. {
  1920. /* See IANA HTTP status code assignment:
  1921. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  1922. */
  1923. switch (response_code) {
  1924. /* RFC2616 Section 10.1 - Informational 1xx */
  1925. case 100:
  1926. return "Continue"; /* RFC2616 Section 10.1.1 */
  1927. case 101:
  1928. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1929. case 102:
  1930. return "Processing"; /* RFC2518 Section 10.1 */
  1931. /* RFC2616 Section 10.2 - Successful 2xx */
  1932. case 200:
  1933. return "OK"; /* RFC2616 Section 10.2.1 */
  1934. case 201:
  1935. return "Created"; /* RFC2616 Section 10.2.2 */
  1936. case 202:
  1937. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1938. case 203:
  1939. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1940. case 204:
  1941. return "No Content"; /* RFC2616 Section 10.2.5 */
  1942. case 205:
  1943. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1944. case 206:
  1945. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1946. case 207:
  1947. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1948. case 208:
  1949. return "Already Reported"; /* RFC5842 Section 7.1 */
  1950. case 226:
  1951. return "IM used"; /* RFC3229 Section 10.4.1 */
  1952. /* RFC2616 Section 10.3 - Redirection 3xx */
  1953. case 300:
  1954. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1955. case 301:
  1956. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1957. case 302:
  1958. return "Found"; /* RFC2616 Section 10.3.3 */
  1959. case 303:
  1960. return "See Other"; /* RFC2616 Section 10.3.4 */
  1961. case 304:
  1962. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1963. case 305:
  1964. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1965. case 307:
  1966. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1967. case 308:
  1968. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1969. /* RFC2616 Section 10.4 - Client Error 4xx */
  1970. case 400:
  1971. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1972. case 401:
  1973. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1974. case 402:
  1975. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1976. case 403:
  1977. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1978. case 404:
  1979. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1980. case 405:
  1981. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1982. case 406:
  1983. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1984. case 407:
  1985. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1986. case 408:
  1987. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1988. case 409:
  1989. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1990. case 410:
  1991. return "Gone"; /* RFC2616 Section 10.4.11 */
  1992. case 411:
  1993. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1994. case 412:
  1995. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1996. case 413:
  1997. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1998. case 414:
  1999. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2000. case 415:
  2001. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2002. case 416:
  2003. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2004. case 417:
  2005. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2006. case 421:
  2007. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2008. case 422:
  2009. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2010. * Section 11.2 */
  2011. case 423:
  2012. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2013. case 424:
  2014. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2015. * Section 11.4 */
  2016. case 426:
  2017. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2018. case 428:
  2019. return "Precondition Required"; /* RFC 6585, Section 3 */
  2020. case 429:
  2021. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2022. case 431:
  2023. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2024. case 451:
  2025. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2026. * Section 3 */
  2027. /* RFC2616 Section 10.5 - Server Error 5xx */
  2028. case 500:
  2029. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2030. case 501:
  2031. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2032. case 502:
  2033. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2034. case 503:
  2035. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2036. case 504:
  2037. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2038. case 505:
  2039. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2040. case 506:
  2041. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2042. case 507:
  2043. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2044. * Section 11.5 */
  2045. case 508:
  2046. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2047. case 510:
  2048. return "Not Extended"; /* RFC 2774, Section 7 */
  2049. case 511:
  2050. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2051. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2052. * E.g., "de facto" standards due to common use, ... */
  2053. case 418:
  2054. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2055. case 419:
  2056. return "Authentication Timeout"; /* common use */
  2057. default:
  2058. /* This error code is unknown. This should not happen. */
  2059. if (conn) {
  2060. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2061. }
  2062. /* Return at least a category according to RFC 2616 Section 10. */
  2063. if (response_code >= 100 && response_code < 200) {
  2064. /* Unknown informational status code */
  2065. return "Information";
  2066. }
  2067. if (response_code >= 200 && response_code < 300) {
  2068. /* Unknown success code */
  2069. return "Success";
  2070. }
  2071. if (response_code >= 300 && response_code < 400) {
  2072. /* Unknown redirection code */
  2073. return "Redirection";
  2074. }
  2075. if (response_code >= 400 && response_code < 500) {
  2076. /* Unknown request error code */
  2077. return "Client Error";
  2078. }
  2079. if (response_code >= 500 && response_code < 600) {
  2080. /* Unknown server error code */
  2081. return "Server Error";
  2082. }
  2083. /* Response code not even within reasonable range */
  2084. return "";
  2085. }
  2086. }
  2087. static void send_http_error(struct mg_connection *,
  2088. int,
  2089. PRINTF_FORMAT_STRING(const char *fmt),
  2090. ...) PRINTF_ARGS(3, 4);
  2091. static void
  2092. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2093. {
  2094. char buf[MG_BUF_LEN];
  2095. va_list ap;
  2096. int len, i, page_handler_found, scope, truncated;
  2097. char date[64];
  2098. time_t curtime = time(NULL);
  2099. const char *error_handler = NULL;
  2100. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  2101. const char *error_page_file_ext, *tstr;
  2102. const char *status_text = mg_get_response_code_text(status, conn);
  2103. if (conn == NULL) {
  2104. return;
  2105. }
  2106. conn->status_code = status;
  2107. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2108. || conn->ctx->callbacks.http_error(conn, status)) {
  2109. if (!conn->in_error_handler) {
  2110. /* Send user defined error pages, if defined */
  2111. error_handler = conn->ctx->config[ERROR_PAGES];
  2112. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2113. page_handler_found = 0;
  2114. if (error_handler != NULL) {
  2115. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2116. switch (scope) {
  2117. case 1: /* Handler for specific error, e.g. 404 error */
  2118. mg_snprintf(conn,
  2119. &truncated,
  2120. buf,
  2121. sizeof(buf) - 32,
  2122. "%serror%03u.",
  2123. error_handler,
  2124. status);
  2125. break;
  2126. case 2: /* Handler for error group, e.g., 5xx error handler
  2127. * for all server errors (500-599) */
  2128. mg_snprintf(conn,
  2129. &truncated,
  2130. buf,
  2131. sizeof(buf) - 32,
  2132. "%serror%01uxx.",
  2133. error_handler,
  2134. status / 100);
  2135. break;
  2136. default: /* Handler for all errors */
  2137. mg_snprintf(conn,
  2138. &truncated,
  2139. buf,
  2140. sizeof(buf) - 32,
  2141. "%serror.",
  2142. error_handler);
  2143. break;
  2144. }
  2145. /* String truncation in buf may only occur if error_handler
  2146. * is too long. This string is from the config, not from a
  2147. * client. */
  2148. (void)truncated;
  2149. len = (int)strlen(buf);
  2150. tstr = strchr(error_page_file_ext, '.');
  2151. while (tstr) {
  2152. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2153. i++)
  2154. buf[len + i - 1] = tstr[i];
  2155. buf[len + i - 1] = 0;
  2156. if (mg_stat(conn, buf, &error_page_file)) {
  2157. page_handler_found = 1;
  2158. break;
  2159. }
  2160. tstr = strchr(tstr + i, '.');
  2161. }
  2162. }
  2163. }
  2164. if (page_handler_found) {
  2165. conn->in_error_handler = 1;
  2166. handle_file_based_request(conn, buf, &error_page_file);
  2167. conn->in_error_handler = 0;
  2168. return;
  2169. }
  2170. }
  2171. /* No custom error page. Send default error page. */
  2172. gmt_time_string(date, sizeof(date), &curtime);
  2173. conn->must_close = 1;
  2174. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2175. send_no_cache_header(conn);
  2176. mg_printf(conn,
  2177. "Date: %s\r\n"
  2178. "Connection: close\r\n\r\n",
  2179. date);
  2180. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2181. if (status > 199 && status != 204 && status != 304) {
  2182. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2183. if (fmt != NULL) {
  2184. va_start(ap, fmt);
  2185. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2186. va_end(ap);
  2187. mg_write(conn, buf, strlen(buf));
  2188. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2189. }
  2190. } else {
  2191. /* No body allowed. Close the connection. */
  2192. DEBUG_TRACE("Error %i", status);
  2193. }
  2194. }
  2195. }
  2196. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2197. /* Create substitutes for POSIX functions in Win32. */
  2198. #if defined(__MINGW32__)
  2199. /* Show no warning in case system functions are not used. */
  2200. #pragma GCC diagnostic push
  2201. #pragma GCC diagnostic ignored "-Wunused-function"
  2202. #endif
  2203. static int
  2204. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2205. {
  2206. (void)unused;
  2207. *mutex = CreateMutex(NULL, FALSE, NULL);
  2208. return *mutex == NULL ? -1 : 0;
  2209. }
  2210. static int
  2211. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2212. {
  2213. return CloseHandle(*mutex) == 0 ? -1 : 0;
  2214. }
  2215. static int
  2216. pthread_mutex_lock(pthread_mutex_t *mutex)
  2217. {
  2218. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  2219. }
  2220. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2221. static int
  2222. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2223. {
  2224. switch (WaitForSingleObject(*mutex, 0)) {
  2225. case WAIT_OBJECT_0:
  2226. return 0;
  2227. case WAIT_TIMEOUT:
  2228. return -2; /* EBUSY */
  2229. }
  2230. return -1;
  2231. }
  2232. #endif
  2233. static int
  2234. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2235. {
  2236. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  2237. }
  2238. #ifndef WIN_PTHREADS_TIME_H
  2239. static int
  2240. clock_gettime(clockid_t clk_id, struct timespec *tp)
  2241. {
  2242. FILETIME ft;
  2243. ULARGE_INTEGER li;
  2244. BOOL ok = FALSE;
  2245. double d;
  2246. static double perfcnt_per_sec = 0.0;
  2247. if (tp) {
  2248. memset(tp, 0, sizeof(*tp));
  2249. if (clk_id == CLOCK_REALTIME) {
  2250. GetSystemTimeAsFileTime(&ft);
  2251. li.LowPart = ft.dwLowDateTime;
  2252. li.HighPart = ft.dwHighDateTime;
  2253. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  2254. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  2255. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  2256. ok = TRUE;
  2257. } else if (clk_id == CLOCK_MONOTONIC) {
  2258. if (perfcnt_per_sec == 0.0) {
  2259. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  2260. perfcnt_per_sec = 1.0 / li.QuadPart;
  2261. }
  2262. if (perfcnt_per_sec != 0.0) {
  2263. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  2264. d = li.QuadPart * perfcnt_per_sec;
  2265. tp->tv_sec = (time_t)d;
  2266. d -= tp->tv_sec;
  2267. tp->tv_nsec = (long)(d * 1.0E9);
  2268. ok = TRUE;
  2269. }
  2270. }
  2271. }
  2272. return ok ? 0 : -1;
  2273. }
  2274. #endif
  2275. static int
  2276. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2277. {
  2278. (void)unused;
  2279. InitializeCriticalSection(&cv->threadIdSec);
  2280. cv->waitingthreadcount = 0;
  2281. cv->waitingthreadhdls =
  2282. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  2283. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  2284. }
  2285. static int
  2286. pthread_cond_timedwait(pthread_cond_t *cv,
  2287. pthread_mutex_t *mutex,
  2288. const struct timespec *abstime)
  2289. {
  2290. struct mg_workerTLS *tls =
  2291. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2292. int ok;
  2293. struct timespec tsnow;
  2294. int64_t nsnow, nswaitabs, nswaitrel;
  2295. DWORD mswaitrel;
  2296. EnterCriticalSection(&cv->threadIdSec);
  2297. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  2298. cv->waitingthreadhdls[cv->waitingthreadcount] =
  2299. tls->pthread_cond_helper_mutex;
  2300. cv->waitingthreadcount++;
  2301. LeaveCriticalSection(&cv->threadIdSec);
  2302. if (abstime) {
  2303. clock_gettime(CLOCK_REALTIME, &tsnow);
  2304. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2305. nswaitabs =
  2306. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2307. nswaitrel = nswaitabs - nsnow;
  2308. if (nswaitrel < 0) {
  2309. nswaitrel = 0;
  2310. }
  2311. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2312. } else {
  2313. mswaitrel = INFINITE;
  2314. }
  2315. pthread_mutex_unlock(mutex);
  2316. ok = (WAIT_OBJECT_0
  2317. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2318. pthread_mutex_lock(mutex);
  2319. return ok ? 0 : -1;
  2320. }
  2321. static int
  2322. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2323. {
  2324. return pthread_cond_timedwait(cv, mutex, NULL);
  2325. }
  2326. static int
  2327. pthread_cond_signal(pthread_cond_t *cv)
  2328. {
  2329. int i;
  2330. HANDLE wkup = NULL;
  2331. BOOL ok = FALSE;
  2332. EnterCriticalSection(&cv->threadIdSec);
  2333. if (cv->waitingthreadcount) {
  2334. wkup = cv->waitingthreadhdls[0];
  2335. ok = SetEvent(wkup);
  2336. for (i = 1; i < cv->waitingthreadcount; i++) {
  2337. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  2338. }
  2339. cv->waitingthreadcount--;
  2340. assert(ok);
  2341. }
  2342. LeaveCriticalSection(&cv->threadIdSec);
  2343. return ok ? 0 : 1;
  2344. }
  2345. static int
  2346. pthread_cond_broadcast(pthread_cond_t *cv)
  2347. {
  2348. EnterCriticalSection(&cv->threadIdSec);
  2349. while (cv->waitingthreadcount) {
  2350. pthread_cond_signal(cv);
  2351. }
  2352. LeaveCriticalSection(&cv->threadIdSec);
  2353. return 0;
  2354. }
  2355. static int
  2356. pthread_cond_destroy(pthread_cond_t *cv)
  2357. {
  2358. EnterCriticalSection(&cv->threadIdSec);
  2359. assert(cv->waitingthreadcount == 0);
  2360. mg_free(cv->waitingthreadhdls);
  2361. cv->waitingthreadhdls = 0;
  2362. LeaveCriticalSection(&cv->threadIdSec);
  2363. DeleteCriticalSection(&cv->threadIdSec);
  2364. return 0;
  2365. }
  2366. #if defined(__MINGW32__)
  2367. /* Enable unused function warning again */
  2368. #pragma GCC diagnostic pop
  2369. #endif
  2370. /* For Windows, change all slashes to backslashes in path names. */
  2371. static void
  2372. change_slashes_to_backslashes(char *path)
  2373. {
  2374. int i;
  2375. for (i = 0; path[i] != '\0'; i++) {
  2376. if (path[i] == '/') {
  2377. path[i] = '\\';
  2378. }
  2379. /* remove double backslash (check i > 0 to preserve UNC paths,
  2380. * like \\server\file.txt) */
  2381. if ((path[i] == '\\') && (i > 0)) {
  2382. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2383. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2384. }
  2385. }
  2386. }
  2387. }
  2388. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2389. * wbuf and wbuf_len is a target buffer and its length. */
  2390. static void
  2391. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2392. {
  2393. char buf[PATH_MAX], buf2[PATH_MAX];
  2394. mg_strlcpy(buf, path, sizeof(buf));
  2395. change_slashes_to_backslashes(buf);
  2396. /* Convert to Unicode and back. If doubly-converted string does not
  2397. * match the original, something is fishy, reject. */
  2398. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2399. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2400. WideCharToMultiByte(
  2401. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2402. if (strcmp(buf, buf2) != 0) {
  2403. wbuf[0] = L'\0';
  2404. }
  2405. }
  2406. #if defined(_WIN32_WCE)
  2407. /* Create substitutes for POSIX functions in Win32. */
  2408. #if defined(__MINGW32__)
  2409. /* Show no warning in case system functions are not used. */
  2410. #pragma GCC diagnostic push
  2411. #pragma GCC diagnostic ignored "-Wunused-function"
  2412. #endif
  2413. static time_t
  2414. time(time_t *ptime)
  2415. {
  2416. time_t t;
  2417. SYSTEMTIME st;
  2418. FILETIME ft;
  2419. GetSystemTime(&st);
  2420. SystemTimeToFileTime(&st, &ft);
  2421. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2422. if (ptime != NULL) {
  2423. *ptime = t;
  2424. }
  2425. return t;
  2426. }
  2427. static struct tm *
  2428. localtime(const time_t *ptime, struct tm *ptm)
  2429. {
  2430. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2431. FILETIME ft, lft;
  2432. SYSTEMTIME st;
  2433. TIME_ZONE_INFORMATION tzinfo;
  2434. if (ptm == NULL) {
  2435. return NULL;
  2436. }
  2437. *(int64_t *)&ft = t;
  2438. FileTimeToLocalFileTime(&ft, &lft);
  2439. FileTimeToSystemTime(&lft, &st);
  2440. ptm->tm_year = st.wYear - 1900;
  2441. ptm->tm_mon = st.wMonth - 1;
  2442. ptm->tm_wday = st.wDayOfWeek;
  2443. ptm->tm_mday = st.wDay;
  2444. ptm->tm_hour = st.wHour;
  2445. ptm->tm_min = st.wMinute;
  2446. ptm->tm_sec = st.wSecond;
  2447. ptm->tm_yday = 0; /* hope nobody uses this */
  2448. ptm->tm_isdst =
  2449. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2450. return ptm;
  2451. }
  2452. static struct tm *
  2453. gmtime(const time_t *ptime, struct tm *ptm)
  2454. {
  2455. /* FIXME(lsm): fix this. */
  2456. return localtime(ptime, ptm);
  2457. }
  2458. static size_t
  2459. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2460. {
  2461. (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() for WinCE");
  2462. return 0;
  2463. }
  2464. #if defined(__MINGW32__)
  2465. /* Enable unused function warning again */
  2466. #pragma GCC diagnostic pop
  2467. #endif
  2468. #endif
  2469. /* Windows happily opens files with some garbage at the end of file name.
  2470. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2471. * "a.cgi", despite one would expect an error back.
  2472. * This function returns non-0 if path ends with some garbage. */
  2473. static int
  2474. path_cannot_disclose_cgi(const char *path)
  2475. {
  2476. static const char *allowed_last_characters = "_-";
  2477. int last = path[strlen(path) - 1];
  2478. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2479. }
  2480. static int
  2481. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2482. {
  2483. wchar_t wbuf[PATH_MAX];
  2484. WIN32_FILE_ATTRIBUTE_DATA info;
  2485. time_t creation_time;
  2486. if (!filep) {
  2487. return 0;
  2488. }
  2489. memset(filep, 0, sizeof(*filep));
  2490. if (conn && is_file_in_memory(conn, path, filep)) {
  2491. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  2492. * memset */
  2493. filep->last_modified = time(NULL);
  2494. /* last_modified = now ... assumes the file may change during runtime,
  2495. * so every mg_fopen call may return different data */
  2496. /* last_modified = conn->ctx.start_time;
  2497. * May be used it the data does not change during runtime. This allows
  2498. * browser caching. Since we do not know, we have to assume the file
  2499. * in memory may change. */
  2500. return 1;
  2501. }
  2502. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2503. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2504. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2505. filep->last_modified =
  2506. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2507. info.ftLastWriteTime.dwHighDateTime);
  2508. /* On Windows, the file creation time can be higher than the
  2509. * modification time, e.g. when a file is copied.
  2510. * Since the Last-Modified timestamp is used for caching
  2511. * it should be based on the most recent timestamp. */
  2512. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  2513. info.ftCreationTime.dwHighDateTime);
  2514. if (creation_time > filep->last_modified) {
  2515. filep->last_modified = creation_time;
  2516. }
  2517. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2518. /* If file name is fishy, reset the file structure and return
  2519. * error.
  2520. * Note it is important to reset, not just return the error, cause
  2521. * functions like is_file_opened() check the struct. */
  2522. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2523. memset(filep, 0, sizeof(*filep));
  2524. return 0;
  2525. }
  2526. return 1;
  2527. }
  2528. return 0;
  2529. }
  2530. static int
  2531. mg_remove(const char *path)
  2532. {
  2533. wchar_t wbuf[PATH_MAX];
  2534. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2535. return DeleteFileW(wbuf) ? 0 : -1;
  2536. }
  2537. static int
  2538. mg_mkdir(const char *path, int mode)
  2539. {
  2540. char buf[PATH_MAX];
  2541. wchar_t wbuf[PATH_MAX];
  2542. (void)mode;
  2543. mg_strlcpy(buf, path, sizeof(buf));
  2544. change_slashes_to_backslashes(buf);
  2545. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2546. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2547. }
  2548. /* Create substitutes for POSIX functions in Win32. */
  2549. #if defined(__MINGW32__)
  2550. /* Show no warning in case system functions are not used. */
  2551. #pragma GCC diagnostic push
  2552. #pragma GCC diagnostic ignored "-Wunused-function"
  2553. #endif
  2554. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2555. static DIR *
  2556. opendir(const char *name)
  2557. {
  2558. DIR *dir = NULL;
  2559. wchar_t wpath[PATH_MAX];
  2560. DWORD attrs;
  2561. if (name == NULL) {
  2562. SetLastError(ERROR_BAD_ARGUMENTS);
  2563. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2564. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2565. } else {
  2566. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2567. attrs = GetFileAttributesW(wpath);
  2568. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  2569. == FILE_ATTRIBUTE_DIRECTORY)) {
  2570. (void)wcscat(wpath, L"\\*");
  2571. dir->handle = FindFirstFileW(wpath, &dir->info);
  2572. dir->result.d_name[0] = '\0';
  2573. } else {
  2574. mg_free(dir);
  2575. dir = NULL;
  2576. }
  2577. }
  2578. return dir;
  2579. }
  2580. static int
  2581. closedir(DIR *dir)
  2582. {
  2583. int result = 0;
  2584. if (dir != NULL) {
  2585. if (dir->handle != INVALID_HANDLE_VALUE)
  2586. result = FindClose(dir->handle) ? 0 : -1;
  2587. mg_free(dir);
  2588. } else {
  2589. result = -1;
  2590. SetLastError(ERROR_BAD_ARGUMENTS);
  2591. }
  2592. return result;
  2593. }
  2594. static struct dirent *
  2595. readdir(DIR *dir)
  2596. {
  2597. struct dirent *result = 0;
  2598. if (dir) {
  2599. if (dir->handle != INVALID_HANDLE_VALUE) {
  2600. result = &dir->result;
  2601. (void)WideCharToMultiByte(CP_UTF8,
  2602. 0,
  2603. dir->info.cFileName,
  2604. -1,
  2605. result->d_name,
  2606. sizeof(result->d_name),
  2607. NULL,
  2608. NULL);
  2609. if (!FindNextFileW(dir->handle, &dir->info)) {
  2610. (void)FindClose(dir->handle);
  2611. dir->handle = INVALID_HANDLE_VALUE;
  2612. }
  2613. } else {
  2614. SetLastError(ERROR_FILE_NOT_FOUND);
  2615. }
  2616. } else {
  2617. SetLastError(ERROR_BAD_ARGUMENTS);
  2618. }
  2619. return result;
  2620. }
  2621. #ifndef HAVE_POLL
  2622. static int
  2623. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2624. {
  2625. struct timeval tv;
  2626. fd_set set;
  2627. unsigned int i;
  2628. int result;
  2629. SOCKET maxfd = 0;
  2630. memset(&tv, 0, sizeof(tv));
  2631. tv.tv_sec = milliseconds / 1000;
  2632. tv.tv_usec = (milliseconds % 1000) * 1000;
  2633. FD_ZERO(&set);
  2634. for (i = 0; i < n; i++) {
  2635. FD_SET((SOCKET)pfd[i].fd, &set);
  2636. pfd[i].revents = 0;
  2637. if (pfd[i].fd > maxfd) {
  2638. maxfd = pfd[i].fd;
  2639. }
  2640. }
  2641. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2642. for (i = 0; i < n; i++) {
  2643. if (FD_ISSET(pfd[i].fd, &set)) {
  2644. pfd[i].revents = POLLIN;
  2645. }
  2646. }
  2647. }
  2648. return result;
  2649. }
  2650. #endif /* HAVE_POLL */
  2651. #if defined(__MINGW32__)
  2652. /* Enable unused function warning again */
  2653. #pragma GCC diagnostic pop
  2654. #endif
  2655. static void
  2656. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  2657. {
  2658. (void)conn; /* Unused. */
  2659. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2660. }
  2661. int
  2662. mg_start_thread(mg_thread_func_t f, void *p)
  2663. {
  2664. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2665. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2666. */
  2667. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  2668. == ((uintptr_t)(-1L)))
  2669. ? -1
  2670. : 0);
  2671. #else
  2672. return (
  2673. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2674. ? -1
  2675. : 0);
  2676. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2677. }
  2678. /* Start a thread storing the thread context. */
  2679. static int
  2680. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2681. void *p,
  2682. pthread_t *threadidptr)
  2683. {
  2684. uintptr_t uip;
  2685. HANDLE threadhandle;
  2686. int result = -1;
  2687. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2688. threadhandle = (HANDLE)uip;
  2689. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2690. *threadidptr = threadhandle;
  2691. result = 0;
  2692. }
  2693. return result;
  2694. }
  2695. /* Wait for a thread to finish. */
  2696. static int
  2697. mg_join_thread(pthread_t threadid)
  2698. {
  2699. int result;
  2700. DWORD dwevent;
  2701. result = -1;
  2702. dwevent = WaitForSingleObject(threadid, INFINITE);
  2703. if (dwevent == WAIT_FAILED) {
  2704. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2705. } else {
  2706. if (dwevent == WAIT_OBJECT_0) {
  2707. CloseHandle(threadid);
  2708. result = 0;
  2709. }
  2710. }
  2711. return result;
  2712. }
  2713. #if !defined(NO_SSL_DL)
  2714. /* Create substitutes for POSIX functions in Win32. */
  2715. #if defined(__MINGW32__)
  2716. /* Show no warning in case system functions are not used. */
  2717. #pragma GCC diagnostic push
  2718. #pragma GCC diagnostic ignored "-Wunused-function"
  2719. #endif
  2720. static HANDLE
  2721. dlopen(const char *dll_name, int flags)
  2722. {
  2723. wchar_t wbuf[PATH_MAX];
  2724. (void)flags;
  2725. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2726. return LoadLibraryW(wbuf);
  2727. }
  2728. static int
  2729. dlclose(void *handle)
  2730. {
  2731. int result;
  2732. if (FreeLibrary((HMODULE)handle) != 0) {
  2733. result = 0;
  2734. } else {
  2735. result = -1;
  2736. }
  2737. return result;
  2738. }
  2739. #if defined(__MINGW32__)
  2740. /* Enable unused function warning again */
  2741. #pragma GCC diagnostic pop
  2742. #endif
  2743. #endif
  2744. #if !defined(NO_CGI)
  2745. #define SIGKILL (0)
  2746. static int
  2747. kill(pid_t pid, int sig_num)
  2748. {
  2749. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2750. (void)CloseHandle((HANDLE)pid);
  2751. return 0;
  2752. }
  2753. static void
  2754. trim_trailing_whitespaces(char *s)
  2755. {
  2756. char *e = s + strlen(s) - 1;
  2757. while (e > s && isspace(*(unsigned char *)e)) {
  2758. *e-- = '\0';
  2759. }
  2760. }
  2761. static pid_t
  2762. spawn_process(struct mg_connection *conn,
  2763. const char *prog,
  2764. char *envblk,
  2765. char *envp[],
  2766. int fdin,
  2767. int fdout,
  2768. int fderr,
  2769. const char *dir)
  2770. {
  2771. HANDLE me;
  2772. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2773. cmdline[PATH_MAX], buf[PATH_MAX];
  2774. int truncated;
  2775. struct file file = STRUCT_FILE_INITIALIZER;
  2776. STARTUPINFOA si;
  2777. PROCESS_INFORMATION pi = {0};
  2778. (void)envp;
  2779. memset(&si, 0, sizeof(si));
  2780. si.cb = sizeof(si);
  2781. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2782. si.wShowWindow = SW_HIDE;
  2783. me = GetCurrentProcess();
  2784. DuplicateHandle(me,
  2785. (HANDLE)_get_osfhandle(fdin),
  2786. me,
  2787. &si.hStdInput,
  2788. 0,
  2789. TRUE,
  2790. DUPLICATE_SAME_ACCESS);
  2791. DuplicateHandle(me,
  2792. (HANDLE)_get_osfhandle(fdout),
  2793. me,
  2794. &si.hStdOutput,
  2795. 0,
  2796. TRUE,
  2797. DUPLICATE_SAME_ACCESS);
  2798. DuplicateHandle(me,
  2799. (HANDLE)_get_osfhandle(fderr),
  2800. me,
  2801. &si.hStdError,
  2802. 0,
  2803. TRUE,
  2804. DUPLICATE_SAME_ACCESS);
  2805. /* If CGI file is a script, try to read the interpreter line */
  2806. interp = conn->ctx->config[CGI_INTERPRETER];
  2807. if (interp == NULL) {
  2808. buf[0] = buf[1] = '\0';
  2809. /* Read the first line of the script into the buffer */
  2810. mg_snprintf(
  2811. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  2812. if (truncated) {
  2813. pi.hProcess = (pid_t)-1;
  2814. goto spawn_cleanup;
  2815. }
  2816. if (mg_fopen(conn, cmdline, "r", &file)) {
  2817. p = (char *)file.membuf;
  2818. mg_fgets(buf, sizeof(buf), &file, &p);
  2819. mg_fclose(&file);
  2820. buf[sizeof(buf) - 1] = '\0';
  2821. }
  2822. if (buf[0] == '#' && buf[1] == '!') {
  2823. trim_trailing_whitespaces(buf + 2);
  2824. } else {
  2825. buf[2] = '\0';
  2826. }
  2827. interp = buf + 2;
  2828. }
  2829. if (interp[0] != '\0') {
  2830. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2831. interp = full_interp;
  2832. }
  2833. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2834. if (interp[0] != '\0') {
  2835. mg_snprintf(conn,
  2836. &truncated,
  2837. cmdline,
  2838. sizeof(cmdline),
  2839. "\"%s\" \"%s\\%s\"",
  2840. interp,
  2841. full_dir,
  2842. prog);
  2843. } else {
  2844. mg_snprintf(conn,
  2845. &truncated,
  2846. cmdline,
  2847. sizeof(cmdline),
  2848. "\"%s\\%s\"",
  2849. full_dir,
  2850. prog);
  2851. }
  2852. if (truncated) {
  2853. pi.hProcess = (pid_t)-1;
  2854. goto spawn_cleanup;
  2855. }
  2856. DEBUG_TRACE("Running [%s]", cmdline);
  2857. if (CreateProcessA(NULL,
  2858. cmdline,
  2859. NULL,
  2860. NULL,
  2861. TRUE,
  2862. CREATE_NEW_PROCESS_GROUP,
  2863. envblk,
  2864. NULL,
  2865. &si,
  2866. &pi) == 0) {
  2867. mg_cry(
  2868. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  2869. pi.hProcess = (pid_t)-1;
  2870. /* goto spawn_cleanup; */
  2871. }
  2872. spawn_cleanup:
  2873. (void)CloseHandle(si.hStdOutput);
  2874. (void)CloseHandle(si.hStdError);
  2875. (void)CloseHandle(si.hStdInput);
  2876. if (pi.hThread != NULL) {
  2877. (void)CloseHandle(pi.hThread);
  2878. }
  2879. return (pid_t)pi.hProcess;
  2880. }
  2881. #endif /* !NO_CGI */
  2882. static int
  2883. set_non_blocking_mode(SOCKET sock)
  2884. {
  2885. unsigned long on = 1;
  2886. return ioctlsocket(sock, (long)FIONBIO, &on);
  2887. }
  2888. #else
  2889. static int
  2890. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2891. {
  2892. struct stat st;
  2893. if (!filep) {
  2894. return 0;
  2895. }
  2896. memset(filep, 0, sizeof(*filep));
  2897. if (conn && is_file_in_memory(conn, path, filep)) {
  2898. return 1;
  2899. }
  2900. if (0 == stat(path, &st)) {
  2901. filep->size = (uint64_t)(st.st_size);
  2902. filep->last_modified = st.st_mtime;
  2903. filep->is_directory = S_ISDIR(st.st_mode);
  2904. return 1;
  2905. }
  2906. return 0;
  2907. }
  2908. static void
  2909. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  2910. {
  2911. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2912. if (conn) {
  2913. mg_cry(conn,
  2914. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2915. __func__,
  2916. strerror(ERRNO));
  2917. }
  2918. }
  2919. }
  2920. int
  2921. mg_start_thread(mg_thread_func_t func, void *param)
  2922. {
  2923. pthread_t thread_id;
  2924. pthread_attr_t attr;
  2925. int result;
  2926. (void)pthread_attr_init(&attr);
  2927. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2928. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2929. /* Compile-time option to control stack size,
  2930. * e.g. -DUSE_STACK_SIZE=16384 */
  2931. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2932. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2933. result = pthread_create(&thread_id, &attr, func, param);
  2934. pthread_attr_destroy(&attr);
  2935. return result;
  2936. }
  2937. /* Start a thread storing the thread context. */
  2938. static int
  2939. mg_start_thread_with_id(mg_thread_func_t func,
  2940. void *param,
  2941. pthread_t *threadidptr)
  2942. {
  2943. pthread_t thread_id;
  2944. pthread_attr_t attr;
  2945. int result;
  2946. (void)pthread_attr_init(&attr);
  2947. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2948. /* Compile-time option to control stack size,
  2949. * e.g. -DUSE_STACK_SIZE=16384 */
  2950. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2951. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2952. result = pthread_create(&thread_id, &attr, func, param);
  2953. pthread_attr_destroy(&attr);
  2954. if ((result == 0) && (threadidptr != NULL)) {
  2955. *threadidptr = thread_id;
  2956. }
  2957. return result;
  2958. }
  2959. /* Wait for a thread to finish. */
  2960. static int
  2961. mg_join_thread(pthread_t threadid)
  2962. {
  2963. int result;
  2964. result = pthread_join(threadid, NULL);
  2965. return result;
  2966. }
  2967. #ifndef NO_CGI
  2968. static pid_t
  2969. spawn_process(struct mg_connection *conn,
  2970. const char *prog,
  2971. char *envblk,
  2972. char *envp[],
  2973. int fdin,
  2974. int fdout,
  2975. int fderr,
  2976. const char *dir)
  2977. {
  2978. pid_t pid;
  2979. const char *interp;
  2980. (void)envblk;
  2981. if (conn == NULL) {
  2982. return 0;
  2983. }
  2984. if ((pid = fork()) == -1) {
  2985. /* Parent */
  2986. send_http_error(conn,
  2987. 500,
  2988. "Error: Creating CGI process\nfork(): %s",
  2989. strerror(ERRNO));
  2990. } else if (pid == 0) {
  2991. /* Child */
  2992. if (chdir(dir) != 0) {
  2993. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2994. } else if (dup2(fdin, 0) == -1) {
  2995. mg_cry(
  2996. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2997. } else if (dup2(fdout, 1) == -1) {
  2998. mg_cry(
  2999. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  3000. } else if (dup2(fderr, 2) == -1) {
  3001. mg_cry(
  3002. conn, "%s: dup2(%d, 2): %s", __func__, fderr, strerror(ERRNO));
  3003. } else {
  3004. /* Keep stderr and stdout in two different pipes.
  3005. * Stdout will be sent back to the client,
  3006. * stderr should go into a server error log. */
  3007. (void)close(fdin);
  3008. (void)close(fdout);
  3009. (void)close(fderr);
  3010. /* After exec, all signal handlers are restored to their default
  3011. * values, with one exception of SIGCHLD. According to
  3012. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3013. * leave unchanged after exec if it was set to be ignored. Restore
  3014. * it to default action. */
  3015. signal(SIGCHLD, SIG_DFL);
  3016. interp = conn->ctx->config[CGI_INTERPRETER];
  3017. if (interp == NULL) {
  3018. (void)execle(prog, prog, NULL, envp);
  3019. mg_cry(conn,
  3020. "%s: execle(%s): %s",
  3021. __func__,
  3022. prog,
  3023. strerror(ERRNO));
  3024. } else {
  3025. (void)execle(interp, interp, prog, NULL, envp);
  3026. mg_cry(conn,
  3027. "%s: execle(%s %s): %s",
  3028. __func__,
  3029. interp,
  3030. prog,
  3031. strerror(ERRNO));
  3032. }
  3033. }
  3034. exit(EXIT_FAILURE);
  3035. }
  3036. return pid;
  3037. }
  3038. #endif /* !NO_CGI */
  3039. static int
  3040. set_non_blocking_mode(SOCKET sock)
  3041. {
  3042. int flags;
  3043. flags = fcntl(sock, F_GETFL, 0);
  3044. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3045. return 0;
  3046. }
  3047. #endif /* _WIN32 */
  3048. /* End of initial operating system specific define block. */
  3049. /* Get a random number (independent of C rand function) */
  3050. static uint64_t
  3051. get_random(void)
  3052. {
  3053. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3054. static uint64_t lcg = 0; /* Linear congruential generator */
  3055. struct timespec now;
  3056. memset(&now, 0, sizeof(now));
  3057. clock_gettime(CLOCK_MONOTONIC, &now);
  3058. if (lfsr == 0) {
  3059. /* lfsr will be only 0 if has not been initialized,
  3060. * so this code is called only once. */
  3061. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3062. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3063. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3064. + (uint64_t)(ptrdiff_t)&now;
  3065. } else {
  3066. /* Get the next step of both random number generators. */
  3067. lfsr = (lfsr >> 1)
  3068. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3069. << 63);
  3070. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3071. }
  3072. /* Combining two pseudo-random number generators and a high resolution part
  3073. * of the current server time will make it hard (impossible?) to guess the
  3074. * next number. */
  3075. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3076. }
  3077. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3078. * descriptor. Return number of bytes written. */
  3079. static int
  3080. push(struct mg_context *ctx,
  3081. FILE *fp,
  3082. SOCKET sock,
  3083. SSL *ssl,
  3084. const char *buf,
  3085. int len,
  3086. double timeout)
  3087. {
  3088. struct timespec start, now;
  3089. int n, err;
  3090. #ifdef _WIN32
  3091. typedef int len_t;
  3092. #else
  3093. typedef size_t len_t;
  3094. #endif
  3095. if (timeout > 0) {
  3096. memset(&start, 0, sizeof(start));
  3097. memset(&now, 0, sizeof(now));
  3098. clock_gettime(CLOCK_MONOTONIC, &start);
  3099. }
  3100. if (ctx == NULL) {
  3101. return -1;
  3102. }
  3103. #ifdef NO_SSL
  3104. if (ssl) {
  3105. return -1;
  3106. }
  3107. #endif
  3108. do {
  3109. #ifndef NO_SSL
  3110. if (ssl != NULL) {
  3111. n = SSL_write(ssl, buf, len);
  3112. if (n <= 0) {
  3113. err = SSL_get_error(ssl, n);
  3114. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (n == -1)) {
  3115. err = ERRNO;
  3116. } else {
  3117. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3118. return -1;
  3119. }
  3120. } else {
  3121. err = 0;
  3122. }
  3123. } else
  3124. #endif
  3125. if (fp != NULL) {
  3126. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3127. if (ferror(fp)) {
  3128. n = -1;
  3129. err = ERRNO;
  3130. } else {
  3131. err = 0;
  3132. }
  3133. } else {
  3134. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3135. err = (n < 0) ? ERRNO : 0;
  3136. }
  3137. if (ctx->stop_flag) {
  3138. return -1;
  3139. }
  3140. if ((n > 0) || (n == 0 && len == 0)) {
  3141. /* some data has been read, or no data was requested */
  3142. return n;
  3143. }
  3144. if (n == 0) {
  3145. /* shutdown of the socket at client side */
  3146. return -1;
  3147. }
  3148. if (n < 0) {
  3149. /* socket error - check errno */
  3150. DEBUG_TRACE("send() failed, error %d", err);
  3151. /* TODO: error handling depending on the error code.
  3152. * These codes are different between Windows and Linux.
  3153. */
  3154. return -1;
  3155. }
  3156. /* This code is not reached in the moment.
  3157. * ==> Fix the TODOs above first. */
  3158. if (timeout > 0) {
  3159. clock_gettime(CLOCK_MONOTONIC, &now);
  3160. }
  3161. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3162. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3163. used */
  3164. return -1;
  3165. }
  3166. static int64_t
  3167. push_all(struct mg_context *ctx,
  3168. FILE *fp,
  3169. SOCKET sock,
  3170. SSL *ssl,
  3171. const char *buf,
  3172. int64_t len)
  3173. {
  3174. double timeout = -1.0;
  3175. int64_t n, nwritten = 0;
  3176. if (ctx == NULL) {
  3177. return -1;
  3178. }
  3179. if (ctx->config[REQUEST_TIMEOUT]) {
  3180. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3181. }
  3182. while (len > 0 && ctx->stop_flag == 0) {
  3183. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3184. if (n < 0) {
  3185. if (nwritten == 0) {
  3186. nwritten = n; /* Propagate the error */
  3187. }
  3188. break;
  3189. } else if (n == 0) {
  3190. break; /* No more data to write */
  3191. } else {
  3192. nwritten += n;
  3193. len -= n;
  3194. }
  3195. }
  3196. return nwritten;
  3197. }
  3198. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3199. * Return negative value on error, or number of bytes read on success. */
  3200. static int
  3201. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3202. {
  3203. int nread, err;
  3204. struct timespec start, now;
  3205. #ifdef _WIN32
  3206. typedef int len_t;
  3207. #else
  3208. typedef size_t len_t;
  3209. #endif
  3210. if (timeout > 0) {
  3211. memset(&start, 0, sizeof(start));
  3212. memset(&now, 0, sizeof(now));
  3213. clock_gettime(CLOCK_MONOTONIC, &start);
  3214. }
  3215. do {
  3216. if (fp != NULL) {
  3217. /* Use read() instead of fread(), because if we're reading from the
  3218. * CGI pipe, fread() may block until IO buffer is filled up. We
  3219. * cannot afford to block and must pass all read bytes immediately
  3220. * to the client. */
  3221. nread = (int)read(fileno(fp), buf, (size_t)len);
  3222. err = (nread < 0) ? ERRNO : 0;
  3223. #ifndef NO_SSL
  3224. } else if (conn->ssl != NULL) {
  3225. nread = SSL_read(conn->ssl, buf, len);
  3226. if (nread <= 0) {
  3227. err = SSL_get_error(conn->ssl, nread);
  3228. if ((err == 5 /* SSL_ERROR_SYSCALL */) && (nread == -1)) {
  3229. err = ERRNO;
  3230. } else {
  3231. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3232. return -1;
  3233. }
  3234. } else {
  3235. err = 0;
  3236. }
  3237. #endif
  3238. } else {
  3239. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3240. err = (nread < 0) ? ERRNO : 0;
  3241. }
  3242. if (conn->ctx->stop_flag) {
  3243. return -1;
  3244. }
  3245. if ((nread > 0) || (nread == 0 && len == 0)) {
  3246. /* some data has been read, or no data was requested */
  3247. return nread;
  3248. }
  3249. if (nread == 0) {
  3250. /* shutdown of the socket at client side */
  3251. return -1;
  3252. }
  3253. if (nread < 0) {
  3254. /* socket error - check errno */
  3255. #ifdef _WIN32
  3256. if (err == WSAEWOULDBLOCK) {
  3257. /* standard case if called from close_socket_gracefully */
  3258. return -1;
  3259. } else if (err == WSAETIMEDOUT) {
  3260. /* timeout is handled by the while loop */
  3261. } else {
  3262. DEBUG_TRACE("recv() failed, error %d", err);
  3263. return -1;
  3264. }
  3265. #else
  3266. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3267. * if the timeout is reached and if the socket was set to non-
  3268. * blocking in close_socket_gracefully, so we can not distinguish
  3269. * here. We have to wait for the timeout in both cases for now.
  3270. */
  3271. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3272. /* EAGAIN/EWOULDBLOCK:
  3273. * standard case if called from close_socket_gracefully
  3274. * => should return -1 */
  3275. /* or timeout occured
  3276. * => the code must stay in the while loop */
  3277. /* EINTR can be generated on a socket with a timeout set even
  3278. * when SA_RESTART is effective for all relevant signals
  3279. * (see signal(7)).
  3280. * => stay in the while loop */
  3281. } else {
  3282. DEBUG_TRACE("recv() failed, error %d", err);
  3283. return -1;
  3284. }
  3285. #endif
  3286. }
  3287. if (timeout > 0) {
  3288. clock_gettime(CLOCK_MONOTONIC, &now);
  3289. }
  3290. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3291. /* Timeout occured, but no data available. */
  3292. return -1;
  3293. }
  3294. static int
  3295. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  3296. {
  3297. int n, nread = 0;
  3298. double timeout = -1.0;
  3299. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  3300. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3301. }
  3302. while (len > 0 && conn->ctx->stop_flag == 0) {
  3303. n = pull(fp, conn, buf + nread, len, timeout);
  3304. if (n < 0) {
  3305. if (nread == 0) {
  3306. nread = n; /* Propagate the error */
  3307. }
  3308. break;
  3309. } else if (n == 0) {
  3310. break; /* No more data to read */
  3311. } else {
  3312. conn->consumed_content += n;
  3313. nread += n;
  3314. len -= n;
  3315. }
  3316. }
  3317. return nread;
  3318. }
  3319. static void
  3320. discard_unread_request_data(struct mg_connection *conn)
  3321. {
  3322. char buf[MG_BUF_LEN];
  3323. size_t to_read;
  3324. int nread;
  3325. if (conn == NULL) {
  3326. return;
  3327. }
  3328. to_read = sizeof(buf);
  3329. if (conn->is_chunked) {
  3330. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  3331. * completely */
  3332. while (conn->is_chunked == 1) {
  3333. nread = mg_read(conn, buf, to_read);
  3334. if (nread <= 0) {
  3335. break;
  3336. }
  3337. }
  3338. } else {
  3339. /* Not chunked: content length is known */
  3340. while (conn->consumed_content < conn->content_len) {
  3341. if (to_read
  3342. > (size_t)(conn->content_len - conn->consumed_content)) {
  3343. to_read = (size_t)(conn->content_len - conn->consumed_content);
  3344. }
  3345. nread = mg_read(conn, buf, to_read);
  3346. if (nread <= 0) {
  3347. break;
  3348. }
  3349. }
  3350. }
  3351. }
  3352. static int
  3353. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  3354. {
  3355. int64_t n, buffered_len, nread;
  3356. int64_t len64 =
  3357. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  3358. * int, we may not read more
  3359. * bytes */
  3360. const char *body;
  3361. if (conn == NULL) {
  3362. return 0;
  3363. }
  3364. /* If Content-Length is not set for a PUT or POST request, read until
  3365. * socket is closed */
  3366. if (conn->consumed_content == 0 && conn->content_len == -1) {
  3367. conn->content_len = INT64_MAX;
  3368. conn->must_close = 1;
  3369. }
  3370. nread = 0;
  3371. if (conn->consumed_content < conn->content_len) {
  3372. /* Adjust number of bytes to read. */
  3373. int64_t left_to_read = conn->content_len - conn->consumed_content;
  3374. if (left_to_read < len64) {
  3375. /* Do not read more than the total content length of the request.
  3376. */
  3377. len64 = left_to_read;
  3378. }
  3379. /* Return buffered data */
  3380. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  3381. - conn->consumed_content;
  3382. if (buffered_len > 0) {
  3383. if (len64 < buffered_len) {
  3384. buffered_len = len64;
  3385. }
  3386. body = conn->buf + conn->request_len + conn->consumed_content;
  3387. memcpy(buf, body, (size_t)buffered_len);
  3388. len64 -= buffered_len;
  3389. conn->consumed_content += buffered_len;
  3390. nread += buffered_len;
  3391. buf = (char *)buf + buffered_len;
  3392. }
  3393. /* We have returned all buffered data. Read new data from the remote
  3394. * socket.
  3395. */
  3396. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  3397. nread += n;
  3398. } else {
  3399. nread = (nread > 0 ? nread : n);
  3400. }
  3401. }
  3402. return (int)nread;
  3403. }
  3404. static char
  3405. mg_getc(struct mg_connection *conn)
  3406. {
  3407. char c;
  3408. if (conn == NULL) {
  3409. return 0;
  3410. }
  3411. conn->content_len++;
  3412. if (mg_read_inner(conn, &c, 1) <= 0) {
  3413. return (char)0;
  3414. }
  3415. return c;
  3416. }
  3417. int
  3418. mg_read(struct mg_connection *conn, void *buf, size_t len)
  3419. {
  3420. if (len > INT_MAX) {
  3421. len = INT_MAX;
  3422. }
  3423. if (conn == NULL) {
  3424. return 0;
  3425. }
  3426. if (conn->is_chunked) {
  3427. size_t all_read = 0;
  3428. while (len > 0) {
  3429. if (conn->chunk_remainder) {
  3430. /* copy from the remainder of the last received chunk */
  3431. long read_ret;
  3432. size_t read_now =
  3433. ((conn->chunk_remainder > len) ? (len)
  3434. : (conn->chunk_remainder));
  3435. conn->content_len += (int)read_now;
  3436. read_ret =
  3437. mg_read_inner(conn, (char *)buf + all_read, read_now);
  3438. all_read += (size_t)read_ret;
  3439. conn->chunk_remainder -= read_now;
  3440. len -= read_now;
  3441. if (conn->chunk_remainder == 0) {
  3442. /* the rest of the data in the current chunk has been read
  3443. */
  3444. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  3445. /* Protocol violation */
  3446. return -1;
  3447. }
  3448. }
  3449. } else {
  3450. /* fetch a new chunk */
  3451. int i = 0;
  3452. char lenbuf[64];
  3453. char *end = 0;
  3454. unsigned long chunkSize = 0;
  3455. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  3456. lenbuf[i] = mg_getc(conn);
  3457. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  3458. continue;
  3459. }
  3460. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  3461. lenbuf[i + 1] = 0;
  3462. chunkSize = strtoul(lenbuf, &end, 16);
  3463. break;
  3464. }
  3465. if (!isalnum(lenbuf[i])) {
  3466. /* illegal character for chunk length */
  3467. return -1;
  3468. }
  3469. }
  3470. if ((end == NULL) || (*end != '\r')) {
  3471. /* chunksize not set correctly */
  3472. return -1;
  3473. }
  3474. conn->chunk_remainder = chunkSize;
  3475. if (chunkSize == 0) {
  3476. /* regular end of content */
  3477. conn->is_chunked = 2;
  3478. break;
  3479. }
  3480. }
  3481. }
  3482. return (int)all_read;
  3483. }
  3484. return mg_read_inner(conn, buf, len);
  3485. }
  3486. int
  3487. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  3488. {
  3489. time_t now;
  3490. int64_t n, total, allowed;
  3491. if (conn == NULL) {
  3492. return 0;
  3493. }
  3494. if (conn->throttle > 0) {
  3495. if ((now = time(NULL)) != conn->last_throttle_time) {
  3496. conn->last_throttle_time = now;
  3497. conn->last_throttle_bytes = 0;
  3498. }
  3499. allowed = conn->throttle - conn->last_throttle_bytes;
  3500. if (allowed > (int64_t)len) {
  3501. allowed = (int64_t)len;
  3502. }
  3503. if ((total = push_all(conn->ctx,
  3504. NULL,
  3505. conn->client.sock,
  3506. conn->ssl,
  3507. (const char *)buf,
  3508. (int64_t)allowed)) == allowed) {
  3509. buf = (char *)buf + total;
  3510. conn->last_throttle_bytes += total;
  3511. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  3512. allowed = conn->throttle > (int64_t)len - total
  3513. ? (int64_t)len - total
  3514. : conn->throttle;
  3515. if ((n = push_all(conn->ctx,
  3516. NULL,
  3517. conn->client.sock,
  3518. conn->ssl,
  3519. (const char *)buf,
  3520. (int64_t)allowed)) != allowed) {
  3521. break;
  3522. }
  3523. sleep(1);
  3524. conn->last_throttle_bytes = allowed;
  3525. conn->last_throttle_time = time(NULL);
  3526. buf = (char *)buf + n;
  3527. total += n;
  3528. }
  3529. }
  3530. } else {
  3531. total = push_all(conn->ctx,
  3532. NULL,
  3533. conn->client.sock,
  3534. conn->ssl,
  3535. (const char *)buf,
  3536. (int64_t)len);
  3537. }
  3538. return (int)total;
  3539. }
  3540. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  3541. static int
  3542. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  3543. {
  3544. va_list ap_copy;
  3545. size_t size = MG_BUF_LEN / 4;
  3546. int len = -1;
  3547. *buf = NULL;
  3548. while (len < 0) {
  3549. if (*buf) {
  3550. mg_free(*buf);
  3551. }
  3552. size *= 4;
  3553. *buf = (char *)mg_malloc(size);
  3554. if (!*buf) {
  3555. break;
  3556. }
  3557. va_copy(ap_copy, ap);
  3558. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  3559. va_end(ap_copy);
  3560. (*buf)[size - 1] = 0;
  3561. }
  3562. return len;
  3563. }
  3564. /* Print message to buffer. If buffer is large enough to hold the message,
  3565. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  3566. * and return allocated buffer. */
  3567. static int
  3568. alloc_vprintf(char **out_buf,
  3569. char *prealloc_buf,
  3570. size_t prealloc_size,
  3571. const char *fmt,
  3572. va_list ap)
  3573. {
  3574. va_list ap_copy;
  3575. int len;
  3576. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  3577. * buffer is too small. Also, older versions of msvcrt.dll do not have
  3578. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  3579. * Therefore, we make two passes: on first pass, get required message
  3580. * length.
  3581. * On second pass, actually print the message. */
  3582. va_copy(ap_copy, ap);
  3583. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  3584. va_end(ap_copy);
  3585. if (len < 0) {
  3586. /* C runtime is not standard compliant, vsnprintf() returned -1.
  3587. * Switch to alternative code path that uses incremental allocations.
  3588. */
  3589. va_copy(ap_copy, ap);
  3590. len = alloc_vprintf2(out_buf, fmt, ap);
  3591. va_end(ap_copy);
  3592. } else if ((size_t)(len) >= prealloc_size) {
  3593. /* The pre-allocated buffer not large enough. */
  3594. /* Allocate a new buffer. */
  3595. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  3596. if (!*out_buf) {
  3597. /* Allocation failed. Return -1 as "out of memory" error. */
  3598. return -1;
  3599. }
  3600. /* Buffer allocation successful. Store the string there. */
  3601. va_copy(ap_copy, ap);
  3602. IGNORE_UNUSED_RESULT(
  3603. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  3604. va_end(ap_copy);
  3605. } else {
  3606. /* The pre-allocated buffer is large enough.
  3607. * Use it to store the string and return the address. */
  3608. va_copy(ap_copy, ap);
  3609. IGNORE_UNUSED_RESULT(
  3610. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  3611. va_end(ap_copy);
  3612. *out_buf = prealloc_buf;
  3613. }
  3614. return len;
  3615. }
  3616. static int
  3617. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  3618. {
  3619. char mem[MG_BUF_LEN];
  3620. char *buf = NULL;
  3621. int len;
  3622. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  3623. len = mg_write(conn, buf, (size_t)len);
  3624. }
  3625. if (buf != mem && buf != NULL) {
  3626. mg_free(buf);
  3627. }
  3628. return len;
  3629. }
  3630. int
  3631. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  3632. {
  3633. va_list ap;
  3634. int result;
  3635. va_start(ap, fmt);
  3636. result = mg_vprintf(conn, fmt, ap);
  3637. va_end(ap);
  3638. return result;
  3639. }
  3640. int
  3641. mg_url_decode(const char *src,
  3642. int src_len,
  3643. char *dst,
  3644. int dst_len,
  3645. int is_form_url_encoded)
  3646. {
  3647. int i, j, a, b;
  3648. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3649. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3650. if (i < src_len - 2 && src[i] == '%'
  3651. && isxdigit(*(const unsigned char *)(src + i + 1))
  3652. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  3653. a = tolower(*(const unsigned char *)(src + i + 1));
  3654. b = tolower(*(const unsigned char *)(src + i + 2));
  3655. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3656. i += 2;
  3657. } else if (is_form_url_encoded && src[i] == '+') {
  3658. dst[j] = ' ';
  3659. } else {
  3660. dst[j] = src[i];
  3661. }
  3662. }
  3663. dst[j] = '\0'; /* Null-terminate the destination */
  3664. return i >= src_len ? j : -1;
  3665. }
  3666. int
  3667. mg_get_var(const char *data,
  3668. size_t data_len,
  3669. const char *name,
  3670. char *dst,
  3671. size_t dst_len)
  3672. {
  3673. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3674. }
  3675. int
  3676. mg_get_var2(const char *data,
  3677. size_t data_len,
  3678. const char *name,
  3679. char *dst,
  3680. size_t dst_len,
  3681. size_t occurrence)
  3682. {
  3683. const char *p, *e, *s;
  3684. size_t name_len;
  3685. int len;
  3686. if (dst == NULL || dst_len == 0) {
  3687. len = -2;
  3688. } else if (data == NULL || name == NULL || data_len == 0) {
  3689. len = -1;
  3690. dst[0] = '\0';
  3691. } else {
  3692. name_len = strlen(name);
  3693. e = data + data_len;
  3694. len = -1;
  3695. dst[0] = '\0';
  3696. /* data is "var1=val1&var2=val2...". Find variable first */
  3697. for (p = data; p + name_len < e; p++) {
  3698. if ((p == data || p[-1] == '&') && p[name_len] == '='
  3699. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3700. /* Point p to variable value */
  3701. p += name_len + 1;
  3702. /* Point s to the end of the value */
  3703. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3704. if (s == NULL) {
  3705. s = e;
  3706. }
  3707. /* assert(s >= p); */
  3708. if (s < p) {
  3709. return -3;
  3710. }
  3711. /* Decode variable into destination buffer */
  3712. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3713. /* Redirect error code from -1 to -2 (destination buffer too
  3714. * small). */
  3715. if (len == -1) {
  3716. len = -2;
  3717. }
  3718. break;
  3719. }
  3720. }
  3721. }
  3722. return len;
  3723. }
  3724. int
  3725. mg_get_cookie(const char *cookie_header,
  3726. const char *var_name,
  3727. char *dst,
  3728. size_t dst_size)
  3729. {
  3730. const char *s, *p, *end;
  3731. int name_len, len = -1;
  3732. if (dst == NULL || dst_size == 0) {
  3733. len = -2;
  3734. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3735. len = -1;
  3736. dst[0] = '\0';
  3737. } else {
  3738. name_len = (int)strlen(var_name);
  3739. end = s + strlen(s);
  3740. dst[0] = '\0';
  3741. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3742. if (s[name_len] == '=') {
  3743. s += name_len + 1;
  3744. if ((p = strchr(s, ' ')) == NULL) {
  3745. p = end;
  3746. }
  3747. if (p[-1] == ';') {
  3748. p--;
  3749. }
  3750. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3751. s++;
  3752. p--;
  3753. }
  3754. if ((size_t)(p - s) < dst_size) {
  3755. len = (int)(p - s);
  3756. mg_strlcpy(dst, s, (size_t)len + 1);
  3757. } else {
  3758. len = -3;
  3759. }
  3760. break;
  3761. }
  3762. }
  3763. }
  3764. return len;
  3765. }
  3766. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3767. static void
  3768. base64_encode(const unsigned char *src, int src_len, char *dst)
  3769. {
  3770. static const char *b64 =
  3771. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3772. int i, j, a, b, c;
  3773. for (i = j = 0; i < src_len; i += 3) {
  3774. a = src[i];
  3775. b = i + 1 >= src_len ? 0 : src[i + 1];
  3776. c = i + 2 >= src_len ? 0 : src[i + 2];
  3777. dst[j++] = b64[a >> 2];
  3778. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3779. if (i + 1 < src_len) {
  3780. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3781. }
  3782. if (i + 2 < src_len) {
  3783. dst[j++] = b64[c & 63];
  3784. }
  3785. }
  3786. while (j % 4 != 0) {
  3787. dst[j++] = '=';
  3788. }
  3789. dst[j++] = '\0';
  3790. }
  3791. #endif
  3792. #if defined(USE_LUA)
  3793. static unsigned char
  3794. b64reverse(char letter)
  3795. {
  3796. if (letter >= 'A' && letter <= 'Z') {
  3797. return letter - 'A';
  3798. }
  3799. if (letter >= 'a' && letter <= 'z') {
  3800. return letter - 'a' + 26;
  3801. }
  3802. if (letter >= '0' && letter <= '9') {
  3803. return letter - '0' + 52;
  3804. }
  3805. if (letter == '+') {
  3806. return 62;
  3807. }
  3808. if (letter == '/') {
  3809. return 63;
  3810. }
  3811. if (letter == '=') {
  3812. return 255; /* normal end */
  3813. }
  3814. return 254; /* error */
  3815. }
  3816. static int
  3817. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3818. {
  3819. int i;
  3820. unsigned char a, b, c, d;
  3821. *dst_len = 0;
  3822. for (i = 0; i < src_len; i += 4) {
  3823. a = b64reverse(src[i]);
  3824. if (a >= 254) {
  3825. return i;
  3826. }
  3827. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3828. if (b >= 254) {
  3829. return i + 1;
  3830. }
  3831. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3832. if (c == 254) {
  3833. return i + 2;
  3834. }
  3835. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3836. if (d == 254) {
  3837. return i + 3;
  3838. }
  3839. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3840. if (c != 255) {
  3841. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3842. if (d != 255) {
  3843. dst[(*dst_len)++] = (c << 6) + d;
  3844. }
  3845. }
  3846. }
  3847. return -1;
  3848. }
  3849. #endif
  3850. static int
  3851. is_put_or_delete_method(const struct mg_connection *conn)
  3852. {
  3853. if (conn) {
  3854. const char *s = conn->request_info.request_method;
  3855. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  3856. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  3857. }
  3858. return 0;
  3859. }
  3860. static void
  3861. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  3862. char *filename, /* out: filename */
  3863. size_t filename_buf_len, /* in: size of filename buffer */
  3864. struct file *filep, /* out: file structure */
  3865. int *is_found, /* out: file is found (directly) */
  3866. int *is_script_resource, /* out: handled by a script? */
  3867. int *is_websocket_request, /* out: websocket connetion? */
  3868. int *is_put_or_delete_request /* out: put/delete a file? */
  3869. )
  3870. {
  3871. /* TODO (high): Restructure this function */
  3872. #if !defined(NO_FILES)
  3873. const char *uri = conn->request_info.local_uri;
  3874. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3875. const char *rewrite;
  3876. struct vec a, b;
  3877. int match_len;
  3878. char gz_path[PATH_MAX];
  3879. char const *accept_encoding;
  3880. int truncated;
  3881. #if !defined(NO_CGI) || defined(USE_LUA)
  3882. char *p;
  3883. #endif
  3884. #else
  3885. (void)filename_buf_len; /* unused if NO_FILES is defined */
  3886. #endif
  3887. memset(filep, 0, sizeof(*filep));
  3888. *filename = 0;
  3889. *is_found = 0;
  3890. *is_script_resource = 0;
  3891. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3892. #if defined(USE_WEBSOCKET)
  3893. *is_websocket_request = is_websocket_protocol(conn);
  3894. #if !defined(NO_FILES)
  3895. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3896. root = conn->ctx->config[WEBSOCKET_ROOT];
  3897. }
  3898. #endif /* !NO_FILES */
  3899. #else /* USE_WEBSOCKET */
  3900. *is_websocket_request = 0;
  3901. #endif /* USE_WEBSOCKET */
  3902. #if !defined(NO_FILES)
  3903. /* Note that root == NULL is a regular use case here. This occurs,
  3904. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3905. * config is not required. */
  3906. if (root == NULL) {
  3907. /* all file related outputs have already been set to 0, just return
  3908. */
  3909. return;
  3910. }
  3911. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3912. * of the path one byte on the right.
  3913. * If document_root is NULL, leave the file empty. */
  3914. mg_snprintf(
  3915. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  3916. if (truncated) {
  3917. goto interpret_cleanup;
  3918. }
  3919. rewrite = conn->ctx->config[REWRITE];
  3920. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3921. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3922. mg_snprintf(conn,
  3923. &truncated,
  3924. filename,
  3925. filename_buf_len - 1,
  3926. "%.*s%s",
  3927. (int)b.len,
  3928. b.ptr,
  3929. uri + match_len);
  3930. break;
  3931. }
  3932. }
  3933. if (truncated) {
  3934. goto interpret_cleanup;
  3935. }
  3936. /* Local file path and name, corresponding to requested URI
  3937. * is now stored in "filename" variable. */
  3938. if (mg_stat(conn, filename, filep)) {
  3939. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3940. /* File exists. Check if it is a script type. */
  3941. if (0
  3942. #if !defined(NO_CGI)
  3943. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3944. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3945. filename) > 0
  3946. #endif
  3947. #if defined(USE_LUA)
  3948. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3949. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3950. filename) > 0
  3951. #endif
  3952. #if defined(USE_DUKTAPE)
  3953. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  3954. strlen(
  3955. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  3956. filename) > 0
  3957. #endif
  3958. ) {
  3959. /* The request addresses a CGI script or a Lua script. The URI
  3960. * corresponds to the script itself (like /path/script.cgi),
  3961. * and there is no additional resource path
  3962. * (like /path/script.cgi/something).
  3963. * Requests that modify (replace or delete) a resource, like
  3964. * PUT and DELETE requests, should replace/delete the script
  3965. * file.
  3966. * Requests that read or write from/to a resource, like GET and
  3967. * POST requests, should call the script and return the
  3968. * generated response. */
  3969. *is_script_resource = !*is_put_or_delete_request;
  3970. }
  3971. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  3972. *is_found = 1;
  3973. return;
  3974. }
  3975. /* If we can't find the actual file, look for the file
  3976. * with the same name but a .gz extension. If we find it,
  3977. * use that and set the gzipped flag in the file struct
  3978. * to indicate that the response need to have the content-
  3979. * encoding: gzip header.
  3980. * We can only do this if the browser declares support. */
  3981. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  3982. if (strstr(accept_encoding, "gzip") != NULL) {
  3983. mg_snprintf(
  3984. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  3985. if (truncated) {
  3986. goto interpret_cleanup;
  3987. }
  3988. if (mg_stat(conn, gz_path, filep)) {
  3989. if (filep) {
  3990. filep->gzipped = 1;
  3991. *is_found = 1;
  3992. }
  3993. /* Currently gz files can not be scripts. */
  3994. return;
  3995. }
  3996. }
  3997. }
  3998. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  3999. /* Support PATH_INFO for CGI scripts. */
  4000. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4001. if (*p == '/') {
  4002. *p = '\0';
  4003. if ((0
  4004. #if !defined(NO_CGI)
  4005. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4006. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4007. filename) > 0
  4008. #endif
  4009. #if defined(USE_LUA)
  4010. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4011. strlen(
  4012. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4013. filename) > 0
  4014. #endif
  4015. #if defined(USE_DUKTAPE)
  4016. || match_prefix(
  4017. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4018. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4019. filename) > 0
  4020. #endif
  4021. ) && mg_stat(conn, filename, filep)) {
  4022. /* Shift PATH_INFO block one character right, e.g.
  4023. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4024. * conn->path_info is pointing to the local variable "path"
  4025. * declared in handle_request(), so PATH_INFO is not valid
  4026. * after handle_request returns. */
  4027. conn->path_info = p + 1;
  4028. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4029. * trailing \0 */
  4030. p[1] = '/';
  4031. *is_script_resource = 1;
  4032. break;
  4033. } else {
  4034. *p = '/';
  4035. }
  4036. }
  4037. }
  4038. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4039. #endif /* !defined(NO_FILES) */
  4040. return;
  4041. #if !defined(NO_FILES)
  4042. /* Reset all outputs */
  4043. interpret_cleanup:
  4044. memset(filep, 0, sizeof(*filep));
  4045. *filename = 0;
  4046. *is_found = 0;
  4047. *is_script_resource = 0;
  4048. *is_websocket_request = 0;
  4049. *is_put_or_delete_request = 0;
  4050. #endif /* !defined(NO_FILES) */
  4051. }
  4052. /* Check whether full request is buffered. Return:
  4053. * -1 if request is malformed
  4054. * 0 if request is not yet fully buffered
  4055. * >0 actual request length, including last \r\n\r\n */
  4056. static int
  4057. get_request_len(const char *buf, int buflen)
  4058. {
  4059. const char *s, *e;
  4060. int len = 0;
  4061. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4062. /* Control characters are not allowed but >=128 is. */
  4063. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4064. && *(const unsigned char *)s < 128) {
  4065. len = -1;
  4066. break; /* [i_a] abort scan as soon as one malformed character is
  4067. * found; */
  4068. /* don't let subsequent \r\n\r\n win us over anyhow */
  4069. } else if (s[0] == '\n' && s[1] == '\n') {
  4070. len = (int)(s - buf) + 2;
  4071. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4072. len = (int)(s - buf) + 3;
  4073. }
  4074. return len;
  4075. }
  4076. /* Convert month to the month number. Return -1 on error, or month number */
  4077. static int
  4078. get_month_index(const char *s)
  4079. {
  4080. size_t i;
  4081. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4082. if (!strcmp(s, month_names[i])) {
  4083. return (int)i;
  4084. }
  4085. }
  4086. return -1;
  4087. }
  4088. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4089. static time_t
  4090. parse_date_string(const char *datetime)
  4091. {
  4092. char month_str[32] = {0};
  4093. int second, minute, hour, day, month, year;
  4094. time_t result = (time_t)0;
  4095. struct tm tm;
  4096. if ((sscanf(datetime,
  4097. "%d/%3s/%d %d:%d:%d",
  4098. &day,
  4099. month_str,
  4100. &year,
  4101. &hour,
  4102. &minute,
  4103. &second) == 6) || (sscanf(datetime,
  4104. "%d %3s %d %d:%d:%d",
  4105. &day,
  4106. month_str,
  4107. &year,
  4108. &hour,
  4109. &minute,
  4110. &second) == 6)
  4111. || (sscanf(datetime,
  4112. "%*3s, %d %3s %d %d:%d:%d",
  4113. &day,
  4114. month_str,
  4115. &year,
  4116. &hour,
  4117. &minute,
  4118. &second) == 6) || (sscanf(datetime,
  4119. "%d-%3s-%d %d:%d:%d",
  4120. &day,
  4121. month_str,
  4122. &year,
  4123. &hour,
  4124. &minute,
  4125. &second) == 6)) {
  4126. month = get_month_index(month_str);
  4127. if ((month >= 0) && (year >= 1970)) {
  4128. memset(&tm, 0, sizeof(tm));
  4129. tm.tm_year = year - 1900;
  4130. tm.tm_mon = month;
  4131. tm.tm_mday = day;
  4132. tm.tm_hour = hour;
  4133. tm.tm_min = minute;
  4134. tm.tm_sec = second;
  4135. result = timegm(&tm);
  4136. }
  4137. }
  4138. return result;
  4139. }
  4140. /* Protect against directory disclosure attack by removing '..',
  4141. * excessive '/' and '\' characters */
  4142. static void
  4143. remove_double_dots_and_double_slashes(char *s)
  4144. {
  4145. char *p = s;
  4146. while (*s != '\0') {
  4147. *p++ = *s++;
  4148. if (s[-1] == '/' || s[-1] == '\\') {
  4149. /* Skip all following slashes, backslashes and double-dots */
  4150. while (s[0] != '\0') {
  4151. if (s[0] == '/' || s[0] == '\\') {
  4152. s++;
  4153. } else if (s[0] == '.' && s[1] == '.') {
  4154. s += 2;
  4155. } else {
  4156. break;
  4157. }
  4158. }
  4159. }
  4160. }
  4161. *p = '\0';
  4162. }
  4163. static const struct {
  4164. const char *extension;
  4165. size_t ext_len;
  4166. const char *mime_type;
  4167. } builtin_mime_types[] = {
  4168. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4169. * application types */
  4170. {".doc", 4, "application/msword"},
  4171. {".eps", 4, "application/postscript"},
  4172. {".exe", 4, "application/octet-stream"},
  4173. {".js", 3, "application/javascript"},
  4174. {".json", 5, "application/json"},
  4175. {".pdf", 4, "application/pdf"},
  4176. {".ps", 3, "application/postscript"},
  4177. {".rtf", 4, "application/rtf"},
  4178. {".xhtml", 6, "application/xhtml+xml"},
  4179. {".xsl", 4, "application/xml"},
  4180. {".xslt", 5, "application/xml"},
  4181. /* fonts */
  4182. {".ttf", 4, "application/font-sfnt"},
  4183. {".cff", 4, "application/font-sfnt"},
  4184. {".otf", 4, "application/font-sfnt"},
  4185. {".aat", 4, "application/font-sfnt"},
  4186. {".sil", 4, "application/font-sfnt"},
  4187. {".pfr", 4, "application/font-tdpfr"},
  4188. {".woff", 5, "application/font-woff"},
  4189. /* audio */
  4190. {".mp3", 4, "audio/mpeg"},
  4191. {".oga", 4, "audio/ogg"},
  4192. {".ogg", 4, "audio/ogg"},
  4193. /* image */
  4194. {".gif", 4, "image/gif"},
  4195. {".ief", 4, "image/ief"},
  4196. {".jpeg", 5, "image/jpeg"},
  4197. {".jpg", 4, "image/jpeg"},
  4198. {".jpm", 4, "image/jpm"},
  4199. {".jpx", 4, "image/jpx"},
  4200. {".png", 4, "image/png"},
  4201. {".svg", 4, "image/svg+xml"},
  4202. {".tif", 4, "image/tiff"},
  4203. {".tiff", 5, "image/tiff"},
  4204. /* model */
  4205. {".wrl", 4, "model/vrml"},
  4206. /* text */
  4207. {".css", 4, "text/css"},
  4208. {".csv", 4, "text/csv"},
  4209. {".htm", 4, "text/html"},
  4210. {".html", 5, "text/html"},
  4211. {".sgm", 4, "text/sgml"},
  4212. {".shtm", 5, "text/html"},
  4213. {".shtml", 6, "text/html"},
  4214. {".txt", 4, "text/plain"},
  4215. {".xml", 4, "text/xml"},
  4216. /* video */
  4217. {".mov", 4, "video/quicktime"},
  4218. {".mp4", 4, "video/mp4"},
  4219. {".mpeg", 5, "video/mpeg"},
  4220. {".mpg", 4, "video/mpeg"},
  4221. {".ogv", 4, "video/ogg"},
  4222. {".qt", 3, "video/quicktime"},
  4223. /* not registered types
  4224. * (http://reference.sitepoint.com/html/mime-types-full,
  4225. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4226. {".arj", 4, "application/x-arj-compressed"},
  4227. {".gz", 3, "application/x-gunzip"},
  4228. {".rar", 4, "application/x-arj-compressed"},
  4229. {".swf", 4, "application/x-shockwave-flash"},
  4230. {".tar", 4, "application/x-tar"},
  4231. {".tgz", 4, "application/x-tar-gz"},
  4232. {".torrent", 8, "application/x-bittorrent"},
  4233. {".ppt", 4, "application/x-mspowerpoint"},
  4234. {".xls", 4, "application/x-msexcel"},
  4235. {".zip", 4, "application/x-zip-compressed"},
  4236. {".aac",
  4237. 4,
  4238. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4239. {".aif", 4, "audio/x-aif"},
  4240. {".m3u", 4, "audio/x-mpegurl"},
  4241. {".mid", 4, "audio/x-midi"},
  4242. {".ra", 3, "audio/x-pn-realaudio"},
  4243. {".ram", 4, "audio/x-pn-realaudio"},
  4244. {".wav", 4, "audio/x-wav"},
  4245. {".bmp", 4, "image/bmp"},
  4246. {".ico", 4, "image/x-icon"},
  4247. {".pct", 4, "image/x-pct"},
  4248. {".pict", 5, "image/pict"},
  4249. {".rgb", 4, "image/x-rgb"},
  4250. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4251. {".asf", 4, "video/x-ms-asf"},
  4252. {".avi", 4, "video/x-msvideo"},
  4253. {".m4v", 4, "video/x-m4v"},
  4254. {NULL, 0, NULL}};
  4255. const char *
  4256. mg_get_builtin_mime_type(const char *path)
  4257. {
  4258. const char *ext;
  4259. size_t i, path_len;
  4260. path_len = strlen(path);
  4261. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4262. ext = path + (path_len - builtin_mime_types[i].ext_len);
  4263. if (path_len > builtin_mime_types[i].ext_len
  4264. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  4265. return builtin_mime_types[i].mime_type;
  4266. }
  4267. }
  4268. return "text/plain";
  4269. }
  4270. /* Look at the "path" extension and figure what mime type it has.
  4271. * Store mime type in the vector. */
  4272. static void
  4273. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  4274. {
  4275. struct vec ext_vec, mime_vec;
  4276. const char *list, *ext;
  4277. size_t path_len;
  4278. path_len = strlen(path);
  4279. if (ctx == NULL || vec == NULL) {
  4280. return;
  4281. }
  4282. /* Scan user-defined mime types first, in case user wants to
  4283. * override default mime types. */
  4284. list = ctx->config[EXTRA_MIME_TYPES];
  4285. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  4286. /* ext now points to the path suffix */
  4287. ext = path + path_len - ext_vec.len;
  4288. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  4289. *vec = mime_vec;
  4290. return;
  4291. }
  4292. }
  4293. vec->ptr = mg_get_builtin_mime_type(path);
  4294. vec->len = strlen(vec->ptr);
  4295. }
  4296. /* Stringify binary data. Output buffer must be twice as big as input,
  4297. * because each byte takes 2 bytes in string representation */
  4298. static void
  4299. bin2str(char *to, const unsigned char *p, size_t len)
  4300. {
  4301. static const char *hex = "0123456789abcdef";
  4302. for (; len--; p++) {
  4303. *to++ = hex[p[0] >> 4];
  4304. *to++ = hex[p[0] & 0x0f];
  4305. }
  4306. *to = '\0';
  4307. }
  4308. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  4309. char *
  4310. mg_md5(char buf[33], ...)
  4311. {
  4312. md5_byte_t hash[16];
  4313. const char *p;
  4314. va_list ap;
  4315. md5_state_t ctx;
  4316. md5_init(&ctx);
  4317. va_start(ap, buf);
  4318. while ((p = va_arg(ap, const char *)) != NULL) {
  4319. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  4320. }
  4321. va_end(ap);
  4322. md5_finish(&ctx, hash);
  4323. bin2str(buf, hash, sizeof(hash));
  4324. return buf;
  4325. }
  4326. /* Check the user's password, return 1 if OK */
  4327. static int
  4328. check_password(const char *method,
  4329. const char *ha1,
  4330. const char *uri,
  4331. const char *nonce,
  4332. const char *nc,
  4333. const char *cnonce,
  4334. const char *qop,
  4335. const char *response)
  4336. {
  4337. char ha2[32 + 1], expected_response[32 + 1];
  4338. /* Some of the parameters may be NULL */
  4339. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  4340. || qop == NULL
  4341. || response == NULL) {
  4342. return 0;
  4343. }
  4344. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  4345. if (strlen(response) != 32) {
  4346. return 0;
  4347. }
  4348. mg_md5(ha2, method, ":", uri, NULL);
  4349. mg_md5(expected_response,
  4350. ha1,
  4351. ":",
  4352. nonce,
  4353. ":",
  4354. nc,
  4355. ":",
  4356. cnonce,
  4357. ":",
  4358. qop,
  4359. ":",
  4360. ha2,
  4361. NULL);
  4362. return mg_strcasecmp(response, expected_response) == 0;
  4363. }
  4364. /* Use the global passwords file, if specified by auth_gpass option,
  4365. * or search for .htpasswd in the requested directory. */
  4366. static void
  4367. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  4368. {
  4369. if (conn != NULL && conn->ctx != NULL) {
  4370. char name[PATH_MAX];
  4371. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  4372. struct file file = STRUCT_FILE_INITIALIZER;
  4373. int truncated;
  4374. if (gpass != NULL) {
  4375. /* Use global passwords file */
  4376. if (!mg_fopen(conn, gpass, "r", filep)) {
  4377. #ifdef DEBUG
  4378. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  4379. #endif
  4380. }
  4381. /* Important: using local struct file to test path for is_directory
  4382. * flag. If filep is used, mg_stat() makes it appear as if auth file
  4383. * was opened. */
  4384. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  4385. mg_snprintf(conn,
  4386. &truncated,
  4387. name,
  4388. sizeof(name),
  4389. "%s/%s",
  4390. path,
  4391. PASSWORDS_FILE_NAME);
  4392. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4393. #ifdef DEBUG
  4394. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4395. #endif
  4396. }
  4397. } else {
  4398. /* Try to find .htpasswd in requested directory. */
  4399. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  4400. if (e[0] == '/') {
  4401. break;
  4402. }
  4403. }
  4404. mg_snprintf(conn,
  4405. &truncated,
  4406. name,
  4407. sizeof(name),
  4408. "%.*s%s",
  4409. (int)(e - p),
  4410. p,
  4411. PASSWORDS_FILE_NAME);
  4412. if (truncated || !mg_fopen(conn, name, "r", filep)) {
  4413. #ifdef DEBUG
  4414. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  4415. #endif
  4416. }
  4417. }
  4418. }
  4419. }
  4420. /* Parsed Authorization header */
  4421. struct ah {
  4422. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  4423. };
  4424. /* Return 1 on success. Always initializes the ah structure. */
  4425. static int
  4426. parse_auth_header(struct mg_connection *conn,
  4427. char *buf,
  4428. size_t buf_size,
  4429. struct ah *ah)
  4430. {
  4431. char *name, *value, *s;
  4432. const char *auth_header;
  4433. uint64_t nonce;
  4434. if (!ah || !conn) {
  4435. return 0;
  4436. }
  4437. (void)memset(ah, 0, sizeof(*ah));
  4438. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  4439. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  4440. return 0;
  4441. }
  4442. /* Make modifiable copy of the auth header */
  4443. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  4444. s = buf;
  4445. /* Parse authorization header */
  4446. for (;;) {
  4447. /* Gobble initial spaces */
  4448. while (isspace(*(unsigned char *)s)) {
  4449. s++;
  4450. }
  4451. name = skip_quoted(&s, "=", " ", 0);
  4452. /* Value is either quote-delimited, or ends at first comma or space. */
  4453. if (s[0] == '\"') {
  4454. s++;
  4455. value = skip_quoted(&s, "\"", " ", '\\');
  4456. if (s[0] == ',') {
  4457. s++;
  4458. }
  4459. } else {
  4460. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  4461. * spaces */
  4462. }
  4463. if (*name == '\0') {
  4464. break;
  4465. }
  4466. if (!strcmp(name, "username")) {
  4467. ah->user = value;
  4468. } else if (!strcmp(name, "cnonce")) {
  4469. ah->cnonce = value;
  4470. } else if (!strcmp(name, "response")) {
  4471. ah->response = value;
  4472. } else if (!strcmp(name, "uri")) {
  4473. ah->uri = value;
  4474. } else if (!strcmp(name, "qop")) {
  4475. ah->qop = value;
  4476. } else if (!strcmp(name, "nc")) {
  4477. ah->nc = value;
  4478. } else if (!strcmp(name, "nonce")) {
  4479. ah->nonce = value;
  4480. }
  4481. }
  4482. #ifndef NO_NONCE_CHECK
  4483. /* Read the nonce from the response. */
  4484. if (ah->nonce == NULL) {
  4485. return 0;
  4486. }
  4487. s = NULL;
  4488. nonce = strtoull(ah->nonce, &s, 10);
  4489. if ((s == NULL) || (*s != 0)) {
  4490. return 0;
  4491. }
  4492. /* Convert the nonce from the client to a number. */
  4493. nonce ^= conn->ctx->auth_nonce_mask;
  4494. /* The converted number corresponds to the time the nounce has been
  4495. * created. This should not be earlier than the server start. */
  4496. /* Server side nonce check is valuable in all situations but one:
  4497. * if the server restarts frequently, but the client should not see
  4498. * that, so the server should accept nonces from previous starts. */
  4499. /* However, the reasonable default is to not accept a nonce from a
  4500. * previous start, so if anyone changed the access rights between
  4501. * two restarts, a new login is required. */
  4502. if (nonce < (uint64_t)conn->ctx->start_time) {
  4503. /* nonce is from a previous start of the server and no longer valid
  4504. * (replay attack?) */
  4505. return 0;
  4506. }
  4507. /* Check if the nonce is too high, so it has not (yet) been used by the
  4508. * server. */
  4509. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  4510. return 0;
  4511. }
  4512. #endif
  4513. /* CGI needs it as REMOTE_USER */
  4514. if (ah->user != NULL) {
  4515. conn->request_info.remote_user = mg_strdup(ah->user);
  4516. } else {
  4517. return 0;
  4518. }
  4519. return 1;
  4520. }
  4521. static char *
  4522. mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  4523. {
  4524. char *eof;
  4525. size_t len;
  4526. char *memend;
  4527. if (!filep) {
  4528. return NULL;
  4529. }
  4530. if (filep->membuf != NULL && *p != NULL) {
  4531. memend = (char *)&filep->membuf[filep->size];
  4532. /* Search for \n from p till the end of stream */
  4533. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  4534. if (eof != NULL) {
  4535. eof += 1; /* Include \n */
  4536. } else {
  4537. eof = memend; /* Copy remaining data */
  4538. }
  4539. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  4540. memcpy(buf, *p, len);
  4541. buf[len] = '\0';
  4542. *p += len;
  4543. return len ? eof : NULL;
  4544. } else if (filep->fp != NULL) {
  4545. return fgets(buf, (int)size, filep->fp);
  4546. } else {
  4547. return NULL;
  4548. }
  4549. }
  4550. struct read_auth_file_struct {
  4551. struct mg_connection *conn;
  4552. struct ah ah;
  4553. char *domain;
  4554. char buf[256 + 256 + 40];
  4555. char *f_user;
  4556. char *f_domain;
  4557. char *f_ha1;
  4558. };
  4559. static int
  4560. read_auth_file(struct file *filep, struct read_auth_file_struct *workdata)
  4561. {
  4562. char *p;
  4563. int is_authorized = 0;
  4564. struct file fp;
  4565. size_t l;
  4566. if (!filep || !workdata) {
  4567. return 0;
  4568. }
  4569. /* Loop over passwords file */
  4570. p = (char *)filep->membuf;
  4571. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  4572. l = strlen(workdata->buf);
  4573. while (l > 0) {
  4574. if (isspace(workdata->buf[l - 1])
  4575. || iscntrl(workdata->buf[l - 1])) {
  4576. l--;
  4577. workdata->buf[l] = 0;
  4578. } else
  4579. break;
  4580. }
  4581. if (l < 1) {
  4582. continue;
  4583. }
  4584. workdata->f_user = workdata->buf;
  4585. if (workdata->f_user[0] == ':') {
  4586. /* user names may not contain a ':' and may not be empty,
  4587. * so lines starting with ':' may be used for a special purpose */
  4588. if (workdata->f_user[1] == '#') {
  4589. /* :# is a comment */
  4590. continue;
  4591. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  4592. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  4593. is_authorized = read_auth_file(&fp, workdata);
  4594. mg_fclose(&fp);
  4595. } else {
  4596. mg_cry(workdata->conn,
  4597. "%s: cannot open authorization file: %s",
  4598. __func__,
  4599. workdata->buf);
  4600. }
  4601. continue;
  4602. }
  4603. /* everything is invalid for the moment (might change in the
  4604. * future) */
  4605. mg_cry(workdata->conn,
  4606. "%s: syntax error in authorization file: %s",
  4607. __func__,
  4608. workdata->buf);
  4609. continue;
  4610. }
  4611. workdata->f_domain = strchr(workdata->f_user, ':');
  4612. if (workdata->f_domain == NULL) {
  4613. mg_cry(workdata->conn,
  4614. "%s: syntax error in authorization file: %s",
  4615. __func__,
  4616. workdata->buf);
  4617. continue;
  4618. }
  4619. *(workdata->f_domain) = 0;
  4620. (workdata->f_domain)++;
  4621. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  4622. if (workdata->f_ha1 == NULL) {
  4623. mg_cry(workdata->conn,
  4624. "%s: syntax error in authorization file: %s",
  4625. __func__,
  4626. workdata->buf);
  4627. continue;
  4628. }
  4629. *(workdata->f_ha1) = 0;
  4630. (workdata->f_ha1)++;
  4631. if (!strcmp(workdata->ah.user, workdata->f_user)
  4632. && !strcmp(workdata->domain, workdata->f_domain)) {
  4633. return check_password(workdata->conn->request_info.request_method,
  4634. workdata->f_ha1,
  4635. workdata->ah.uri,
  4636. workdata->ah.nonce,
  4637. workdata->ah.nc,
  4638. workdata->ah.cnonce,
  4639. workdata->ah.qop,
  4640. workdata->ah.response);
  4641. }
  4642. }
  4643. return is_authorized;
  4644. }
  4645. /* Authorize against the opened passwords file. Return 1 if authorized. */
  4646. static int
  4647. authorize(struct mg_connection *conn, struct file *filep)
  4648. {
  4649. struct read_auth_file_struct workdata;
  4650. char buf[MG_BUF_LEN];
  4651. if (!conn || !conn->ctx) {
  4652. return 0;
  4653. }
  4654. memset(&workdata, 0, sizeof(workdata));
  4655. workdata.conn = conn;
  4656. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  4657. return 0;
  4658. }
  4659. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  4660. return read_auth_file(filep, &workdata);
  4661. }
  4662. /* Return 1 if request is authorised, 0 otherwise. */
  4663. static int
  4664. check_authorization(struct mg_connection *conn, const char *path)
  4665. {
  4666. char fname[PATH_MAX];
  4667. struct vec uri_vec, filename_vec;
  4668. const char *list;
  4669. struct file file = STRUCT_FILE_INITIALIZER;
  4670. int authorized = 1, truncated;
  4671. if (!conn || !conn->ctx) {
  4672. return 0;
  4673. }
  4674. list = conn->ctx->config[PROTECT_URI];
  4675. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  4676. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  4677. mg_snprintf(conn,
  4678. &truncated,
  4679. fname,
  4680. sizeof(fname),
  4681. "%.*s",
  4682. (int)filename_vec.len,
  4683. filename_vec.ptr);
  4684. if (truncated || !mg_fopen(conn, fname, "r", &file)) {
  4685. mg_cry(conn,
  4686. "%s: cannot open %s: %s",
  4687. __func__,
  4688. fname,
  4689. strerror(errno));
  4690. }
  4691. break;
  4692. }
  4693. }
  4694. if (!is_file_opened(&file)) {
  4695. open_auth_file(conn, path, &file);
  4696. }
  4697. if (is_file_opened(&file)) {
  4698. authorized = authorize(conn, &file);
  4699. mg_fclose(&file);
  4700. }
  4701. return authorized;
  4702. }
  4703. static void
  4704. send_authorization_request(struct mg_connection *conn)
  4705. {
  4706. char date[64];
  4707. time_t curtime = time(NULL);
  4708. if (conn && conn->ctx) {
  4709. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  4710. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  4711. nonce += conn->ctx->nonce_count;
  4712. ++conn->ctx->nonce_count;
  4713. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  4714. nonce ^= conn->ctx->auth_nonce_mask;
  4715. conn->status_code = 401;
  4716. conn->must_close = 1;
  4717. gmt_time_string(date, sizeof(date), &curtime);
  4718. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  4719. send_no_cache_header(conn);
  4720. mg_printf(conn,
  4721. "Date: %s\r\n"
  4722. "Connection: %s\r\n"
  4723. "Content-Length: 0\r\n"
  4724. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  4725. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  4726. date,
  4727. suggest_connection_header(conn),
  4728. conn->ctx->config[AUTHENTICATION_DOMAIN],
  4729. nonce);
  4730. }
  4731. }
  4732. #if !defined(NO_FILES)
  4733. static int
  4734. is_authorized_for_put(struct mg_connection *conn)
  4735. {
  4736. if (conn) {
  4737. struct file file = STRUCT_FILE_INITIALIZER;
  4738. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4739. int ret = 0;
  4740. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4741. ret = authorize(conn, &file);
  4742. mg_fclose(&file);
  4743. }
  4744. return ret;
  4745. }
  4746. return 0;
  4747. }
  4748. #endif
  4749. int
  4750. mg_modify_passwords_file(const char *fname,
  4751. const char *domain,
  4752. const char *user,
  4753. const char *pass)
  4754. {
  4755. int found, i;
  4756. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4757. FILE *fp, *fp2;
  4758. found = 0;
  4759. fp = fp2 = NULL;
  4760. /* Regard empty password as no password - remove user record. */
  4761. if (pass != NULL && pass[0] == '\0') {
  4762. pass = NULL;
  4763. }
  4764. /* Other arguments must not be empty */
  4765. if (fname == NULL || domain == NULL || user == NULL) {
  4766. return 0;
  4767. }
  4768. /* Using the given file format, user name and domain must not contain ':'
  4769. */
  4770. if (strchr(user, ':') != NULL) {
  4771. return 0;
  4772. }
  4773. if (strchr(domain, ':') != NULL) {
  4774. return 0;
  4775. }
  4776. /* Do not allow control characters like newline in user name and domain.
  4777. * Do not allow excessively long names either. */
  4778. for (i = 0; i < 255 && user[i] != 0; i++) {
  4779. if (iscntrl(user[i])) {
  4780. return 0;
  4781. }
  4782. }
  4783. if (user[i]) {
  4784. return 0;
  4785. }
  4786. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4787. if (iscntrl(domain[i])) {
  4788. return 0;
  4789. }
  4790. }
  4791. if (domain[i]) {
  4792. return 0;
  4793. }
  4794. /* The maximum length of the path to the password file is limited */
  4795. if ((strlen(fname) + 4) >= PATH_MAX) {
  4796. return 0;
  4797. }
  4798. /* Create a temporary file name. Length has been checked before. */
  4799. strcpy(tmp, fname);
  4800. strcat(tmp, ".tmp");
  4801. /* Create the file if does not exist */
  4802. /* Use of fopen here is OK, since fname is only ASCII */
  4803. if ((fp = fopen(fname, "a+")) != NULL) {
  4804. (void)fclose(fp);
  4805. }
  4806. /* Open the given file and temporary file */
  4807. if ((fp = fopen(fname, "r")) == NULL) {
  4808. return 0;
  4809. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4810. fclose(fp);
  4811. return 0;
  4812. }
  4813. /* Copy the stuff to temporary file */
  4814. while (fgets(line, sizeof(line), fp) != NULL) {
  4815. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4816. continue;
  4817. }
  4818. u[255] = 0;
  4819. d[255] = 0;
  4820. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4821. found++;
  4822. if (pass != NULL) {
  4823. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4824. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4825. }
  4826. } else {
  4827. fprintf(fp2, "%s", line);
  4828. }
  4829. }
  4830. /* If new user, just add it */
  4831. if (!found && pass != NULL) {
  4832. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4833. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4834. }
  4835. /* Close files */
  4836. fclose(fp);
  4837. fclose(fp2);
  4838. /* Put the temp file in place of real file */
  4839. IGNORE_UNUSED_RESULT(remove(fname));
  4840. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4841. return 1;
  4842. }
  4843. static int
  4844. is_valid_port(unsigned long port)
  4845. {
  4846. return port < 0xffff;
  4847. }
  4848. static int
  4849. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4850. {
  4851. struct addrinfo hints, *res, *ressave;
  4852. int ret = 0;
  4853. memset(&hints, 0, sizeof(struct addrinfo));
  4854. hints.ai_family = af;
  4855. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4856. /* bad src string or bad address family */
  4857. return 0;
  4858. }
  4859. ressave = res;
  4860. while (res) {
  4861. if (dstlen >= res->ai_addrlen) {
  4862. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4863. ret = 1;
  4864. }
  4865. res = res->ai_next;
  4866. }
  4867. freeaddrinfo(ressave);
  4868. return ret;
  4869. }
  4870. static int
  4871. connect_socket(struct mg_context *ctx /* may be NULL */,
  4872. const char *host,
  4873. int port,
  4874. int use_ssl,
  4875. char *ebuf,
  4876. size_t ebuf_len,
  4877. SOCKET *sock /* output: socket, must not be NULL */,
  4878. union usa *sa /* output: socket address, must not be NULL */
  4879. )
  4880. {
  4881. int ip_ver = 0;
  4882. *sock = INVALID_SOCKET;
  4883. memset(sa, 0, sizeof(*sa));
  4884. if (ebuf_len > 0) {
  4885. *ebuf = 0;
  4886. }
  4887. if (host == NULL) {
  4888. mg_snprintf(NULL,
  4889. NULL, /* No truncation check for ebuf */
  4890. ebuf,
  4891. ebuf_len,
  4892. "%s",
  4893. "NULL host");
  4894. return 0;
  4895. }
  4896. if (port < 0 || !is_valid_port((unsigned)port)) {
  4897. mg_snprintf(NULL,
  4898. NULL, /* No truncation check for ebuf */
  4899. ebuf,
  4900. ebuf_len,
  4901. "%s",
  4902. "invalid port");
  4903. return 0;
  4904. }
  4905. if (use_ssl && (SSLv23_client_method == NULL)) {
  4906. mg_snprintf(NULL,
  4907. NULL, /* No truncation check for ebuf */
  4908. ebuf,
  4909. ebuf_len,
  4910. "%s",
  4911. "SSL is not initialized");
  4912. return 0;
  4913. }
  4914. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  4915. sa->sin.sin_port = htons((uint16_t)port);
  4916. ip_ver = 4;
  4917. #ifdef USE_IPV6
  4918. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  4919. sa->sin6.sin6_port = htons((uint16_t)port);
  4920. ip_ver = 6;
  4921. } else if (host[0] == '[') {
  4922. /* While getaddrinfo on Windows will work with [::1],
  4923. * getaddrinfo on Linux only works with ::1 (without []). */
  4924. size_t l = strlen(host + 1);
  4925. char *h = l > 1 ? mg_strdup(host + 1) : NULL;
  4926. if (h) {
  4927. h[l - 1] = 0;
  4928. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  4929. sa->sin6.sin6_port = htons((uint16_t)port);
  4930. ip_ver = 6;
  4931. }
  4932. mg_free(h);
  4933. }
  4934. #endif
  4935. }
  4936. if (ip_ver == 0) {
  4937. mg_snprintf(NULL,
  4938. NULL, /* No truncation check for ebuf */
  4939. ebuf,
  4940. ebuf_len,
  4941. "%s",
  4942. "host not found");
  4943. return 0;
  4944. }
  4945. if (ip_ver == 4) {
  4946. *sock = socket(PF_INET, SOCK_STREAM, 0);
  4947. }
  4948. #ifdef USE_IPV6
  4949. else if (ip_ver == 6) {
  4950. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  4951. }
  4952. #endif
  4953. if (*sock == INVALID_SOCKET) {
  4954. mg_snprintf(NULL,
  4955. NULL, /* No truncation check for ebuf */
  4956. ebuf,
  4957. ebuf_len,
  4958. "socket(): %s",
  4959. strerror(ERRNO));
  4960. return 0;
  4961. }
  4962. set_close_on_exec(*sock, fc(ctx));
  4963. if ((ip_ver == 4)
  4964. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  4965. == 0)) {
  4966. /* connected with IPv4 */
  4967. return 1;
  4968. }
  4969. #ifdef USE_IPV6
  4970. if ((ip_ver == 6)
  4971. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  4972. == 0)) {
  4973. /* connected with IPv6 */
  4974. return 1;
  4975. }
  4976. #endif
  4977. /* Not connected */
  4978. mg_snprintf(NULL,
  4979. NULL, /* No truncation check for ebuf */
  4980. ebuf,
  4981. ebuf_len,
  4982. "connect(%s:%d): %s",
  4983. host,
  4984. port,
  4985. strerror(ERRNO));
  4986. closesocket(*sock);
  4987. *sock = INVALID_SOCKET;
  4988. return 0;
  4989. }
  4990. int
  4991. mg_url_encode(const char *src, char *dst, size_t dst_len)
  4992. {
  4993. static const char *dont_escape = "._-$,;~()";
  4994. static const char *hex = "0123456789abcdef";
  4995. char *pos = dst;
  4996. const char *end = dst + dst_len - 1;
  4997. for (; *src != '\0' && pos < end; src++, pos++) {
  4998. if (isalnum(*(const unsigned char *)src)
  4999. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5000. *pos = *src;
  5001. } else if (pos + 2 < end) {
  5002. pos[0] = '%';
  5003. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5004. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5005. pos += 2;
  5006. } else {
  5007. break;
  5008. }
  5009. }
  5010. *pos = '\0';
  5011. return (*src == '\0') ? (int)(pos - dst) : -1;
  5012. }
  5013. static void
  5014. print_dir_entry(struct de *de)
  5015. {
  5016. char size[64], mod[64], href[PATH_MAX];
  5017. struct tm *tm;
  5018. if (de->file.is_directory) {
  5019. mg_snprintf(de->conn,
  5020. NULL, /* Buffer is big enough */
  5021. size,
  5022. sizeof(size),
  5023. "%s",
  5024. "[DIRECTORY]");
  5025. } else {
  5026. /* We use (signed) cast below because MSVC 6 compiler cannot
  5027. * convert unsigned __int64 to double. Sigh. */
  5028. if (de->file.size < 1024) {
  5029. mg_snprintf(de->conn,
  5030. NULL, /* Buffer is big enough */
  5031. size,
  5032. sizeof(size),
  5033. "%d",
  5034. (int)de->file.size);
  5035. } else if (de->file.size < 0x100000) {
  5036. mg_snprintf(de->conn,
  5037. NULL, /* Buffer is big enough */
  5038. size,
  5039. sizeof(size),
  5040. "%.1fk",
  5041. (double)de->file.size / 1024.0);
  5042. } else if (de->file.size < 0x40000000) {
  5043. mg_snprintf(de->conn,
  5044. NULL, /* Buffer is big enough */
  5045. size,
  5046. sizeof(size),
  5047. "%.1fM",
  5048. (double)de->file.size / 1048576);
  5049. } else {
  5050. mg_snprintf(de->conn,
  5051. NULL, /* Buffer is big enough */
  5052. size,
  5053. sizeof(size),
  5054. "%.1fG",
  5055. (double)de->file.size / 1073741824);
  5056. }
  5057. }
  5058. /* Note: mg_snprintf will not cause a buffer overflow above.
  5059. * So, string truncation checks are not required here. */
  5060. tm = localtime(&de->file.last_modified);
  5061. if (tm != NULL) {
  5062. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5063. } else {
  5064. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5065. mod[sizeof(mod) - 1] = '\0';
  5066. }
  5067. mg_url_encode(de->file_name, href, sizeof(href));
  5068. de->conn->num_bytes_sent +=
  5069. mg_printf(de->conn,
  5070. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5071. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5072. de->conn->request_info.local_uri,
  5073. href,
  5074. de->file.is_directory ? "/" : "",
  5075. de->file_name,
  5076. de->file.is_directory ? "/" : "",
  5077. mod,
  5078. size);
  5079. }
  5080. /* This function is called from send_directory() and used for
  5081. * sorting directory entries by size, or name, or modification time.
  5082. * On windows, __cdecl specification is needed in case if project is built
  5083. * with __stdcall convention. qsort always requires __cdels callback. */
  5084. static int WINCDECL
  5085. compare_dir_entries(const void *p1, const void *p2)
  5086. {
  5087. if (p1 && p2) {
  5088. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5089. const char *query_string = a->conn->request_info.query_string;
  5090. int cmp_result = 0;
  5091. if (query_string == NULL) {
  5092. query_string = "na";
  5093. }
  5094. if (a->file.is_directory && !b->file.is_directory) {
  5095. return -1; /* Always put directories on top */
  5096. } else if (!a->file.is_directory && b->file.is_directory) {
  5097. return 1; /* Always put directories on top */
  5098. } else if (*query_string == 'n') {
  5099. cmp_result = strcmp(a->file_name, b->file_name);
  5100. } else if (*query_string == 's') {
  5101. cmp_result = a->file.size == b->file.size
  5102. ? 0
  5103. : a->file.size > b->file.size ? 1 : -1;
  5104. } else if (*query_string == 'd') {
  5105. cmp_result =
  5106. (a->file.last_modified == b->file.last_modified)
  5107. ? 0
  5108. : ((a->file.last_modified > b->file.last_modified) ? 1
  5109. : -1);
  5110. }
  5111. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  5112. }
  5113. return 0;
  5114. }
  5115. static int
  5116. must_hide_file(struct mg_connection *conn, const char *path)
  5117. {
  5118. if (conn && conn->ctx) {
  5119. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5120. const char *pattern = conn->ctx->config[HIDE_FILES];
  5121. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5122. || (pattern != NULL
  5123. && match_prefix(pattern, strlen(pattern), path) > 0);
  5124. }
  5125. return 0;
  5126. }
  5127. static int
  5128. scan_directory(struct mg_connection *conn,
  5129. const char *dir,
  5130. void *data,
  5131. void (*cb)(struct de *, void *))
  5132. {
  5133. char path[PATH_MAX];
  5134. struct dirent *dp;
  5135. DIR *dirp;
  5136. struct de de;
  5137. int truncated;
  5138. if ((dirp = opendir(dir)) == NULL) {
  5139. return 0;
  5140. } else {
  5141. de.conn = conn;
  5142. while ((dp = readdir(dirp)) != NULL) {
  5143. /* Do not show current dir and hidden files */
  5144. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5145. || must_hide_file(conn, dp->d_name)) {
  5146. continue;
  5147. }
  5148. mg_snprintf(
  5149. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5150. /* If we don't memset stat structure to zero, mtime will have
  5151. * garbage and strftime() will segfault later on in
  5152. * print_dir_entry(). memset is required only if mg_stat()
  5153. * fails. For more details, see
  5154. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5155. memset(&de.file, 0, sizeof(de.file));
  5156. if (truncated) {
  5157. /* If the path is not complete, skip processing. */
  5158. continue;
  5159. }
  5160. if (!mg_stat(conn, path, &de.file)) {
  5161. mg_cry(conn,
  5162. "%s: mg_stat(%s) failed: %s",
  5163. __func__,
  5164. path,
  5165. strerror(ERRNO));
  5166. }
  5167. de.file_name = dp->d_name;
  5168. cb(&de, data);
  5169. }
  5170. (void)closedir(dirp);
  5171. }
  5172. return 1;
  5173. }
  5174. #if !defined(NO_FILES)
  5175. static int
  5176. remove_directory(struct mg_connection *conn, const char *dir)
  5177. {
  5178. char path[PATH_MAX];
  5179. struct dirent *dp;
  5180. DIR *dirp;
  5181. struct de de;
  5182. int truncated;
  5183. int ok = 1;
  5184. if ((dirp = opendir(dir)) == NULL) {
  5185. return 0;
  5186. } else {
  5187. de.conn = conn;
  5188. while ((dp = readdir(dirp)) != NULL) {
  5189. /* Do not show current dir (but show hidden files as they will
  5190. * also be removed) */
  5191. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5192. continue;
  5193. }
  5194. mg_snprintf(
  5195. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5196. /* If we don't memset stat structure to zero, mtime will have
  5197. * garbage and strftime() will segfault later on in
  5198. * print_dir_entry(). memset is required only if mg_stat()
  5199. * fails. For more details, see
  5200. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5201. memset(&de.file, 0, sizeof(de.file));
  5202. if (truncated) {
  5203. /* Do not delete anything shorter */
  5204. ok = 0;
  5205. continue;
  5206. }
  5207. if (!mg_stat(conn, path, &de.file)) {
  5208. mg_cry(conn,
  5209. "%s: mg_stat(%s) failed: %s",
  5210. __func__,
  5211. path,
  5212. strerror(ERRNO));
  5213. ok = 0;
  5214. }
  5215. if (de.file.membuf == NULL) {
  5216. /* file is not in memory */
  5217. if (de.file.is_directory) {
  5218. if (remove_directory(conn, path) == 0) {
  5219. ok = 0;
  5220. }
  5221. } else {
  5222. if (mg_remove(path) == 0) {
  5223. ok = 0;
  5224. }
  5225. }
  5226. } else {
  5227. /* file is in memory. It can not be deleted. */
  5228. ok = 0;
  5229. }
  5230. }
  5231. (void)closedir(dirp);
  5232. IGNORE_UNUSED_RESULT(rmdir(dir));
  5233. }
  5234. return ok;
  5235. }
  5236. #endif
  5237. struct dir_scan_data {
  5238. struct de *entries;
  5239. unsigned int num_entries;
  5240. unsigned int arr_size;
  5241. };
  5242. /* Behaves like realloc(), but frees original pointer on failure */
  5243. static void *
  5244. realloc2(void *ptr, size_t size)
  5245. {
  5246. void *new_ptr = mg_realloc(ptr, size);
  5247. if (new_ptr == NULL) {
  5248. mg_free(ptr);
  5249. }
  5250. return new_ptr;
  5251. }
  5252. static void
  5253. dir_scan_callback(struct de *de, void *data)
  5254. {
  5255. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  5256. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  5257. dsd->arr_size *= 2;
  5258. dsd->entries =
  5259. (struct de *)realloc2(dsd->entries,
  5260. dsd->arr_size * sizeof(dsd->entries[0]));
  5261. }
  5262. if (dsd->entries == NULL) {
  5263. /* TODO(lsm, low): propagate an error to the caller */
  5264. dsd->num_entries = 0;
  5265. } else {
  5266. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  5267. dsd->entries[dsd->num_entries].file = de->file;
  5268. dsd->entries[dsd->num_entries].conn = de->conn;
  5269. dsd->num_entries++;
  5270. }
  5271. }
  5272. static void
  5273. handle_directory_request(struct mg_connection *conn, const char *dir)
  5274. {
  5275. unsigned int i;
  5276. int sort_direction;
  5277. struct dir_scan_data data = {NULL, 0, 128};
  5278. char date[64];
  5279. time_t curtime = time(NULL);
  5280. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  5281. send_http_error(conn,
  5282. 500,
  5283. "Error: Cannot open directory\nopendir(%s): %s",
  5284. dir,
  5285. strerror(ERRNO));
  5286. return;
  5287. }
  5288. gmt_time_string(date, sizeof(date), &curtime);
  5289. if (!conn) {
  5290. return;
  5291. }
  5292. sort_direction = conn->request_info.query_string != NULL
  5293. && conn->request_info.query_string[1] == 'd'
  5294. ? 'a'
  5295. : 'd';
  5296. conn->must_close = 1;
  5297. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  5298. send_static_cache_header(conn);
  5299. mg_printf(conn,
  5300. "Date: %s\r\n"
  5301. "Connection: close\r\n"
  5302. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  5303. date);
  5304. conn->num_bytes_sent +=
  5305. mg_printf(conn,
  5306. "<html><head><title>Index of %s</title>"
  5307. "<style>th {text-align: left;}</style></head>"
  5308. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  5309. "<tr><th><a href=\"?n%c\">Name</a></th>"
  5310. "<th><a href=\"?d%c\">Modified</a></th>"
  5311. "<th><a href=\"?s%c\">Size</a></th></tr>"
  5312. "<tr><td colspan=\"3\"><hr></td></tr>",
  5313. conn->request_info.local_uri,
  5314. conn->request_info.local_uri,
  5315. sort_direction,
  5316. sort_direction,
  5317. sort_direction);
  5318. /* Print first entry - link to a parent directory */
  5319. conn->num_bytes_sent +=
  5320. mg_printf(conn,
  5321. "<tr><td><a href=\"%s%s\">%s</a></td>"
  5322. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5323. conn->request_info.local_uri,
  5324. "..",
  5325. "Parent directory",
  5326. "-",
  5327. "-");
  5328. /* Sort and print directory entries */
  5329. if (data.entries != NULL) {
  5330. qsort(data.entries,
  5331. (size_t)data.num_entries,
  5332. sizeof(data.entries[0]),
  5333. compare_dir_entries);
  5334. for (i = 0; i < data.num_entries; i++) {
  5335. print_dir_entry(&data.entries[i]);
  5336. mg_free(data.entries[i].file_name);
  5337. }
  5338. mg_free(data.entries);
  5339. }
  5340. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  5341. conn->status_code = 200;
  5342. }
  5343. /* Send len bytes from the opened file to the client. */
  5344. static void
  5345. send_file_data(struct mg_connection *conn,
  5346. struct file *filep,
  5347. int64_t offset,
  5348. int64_t len)
  5349. {
  5350. char buf[MG_BUF_LEN];
  5351. int to_read, num_read, num_written;
  5352. int64_t size;
  5353. if (!filep || !conn) {
  5354. return;
  5355. }
  5356. /* Sanity check the offset */
  5357. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  5358. offset = offset < 0 ? 0 : offset > size ? size : offset;
  5359. if (len > 0 && filep->membuf != NULL && size > 0) {
  5360. /* file stored in memory */
  5361. if (len > size - offset) {
  5362. len = size - offset;
  5363. }
  5364. mg_write(conn, filep->membuf + offset, (size_t)len);
  5365. } else if (len > 0 && filep->fp != NULL) {
  5366. /* file stored on disk */
  5367. #if defined(__linux__)
  5368. /* sendfile is only available for Linux */
  5369. if (conn->throttle == 0 && conn->ssl == 0) {
  5370. off_t sf_offs = (off_t)offset;
  5371. ssize_t sf_sent;
  5372. int sf_file = fileno(filep->fp);
  5373. int loop_cnt = 0;
  5374. do {
  5375. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  5376. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  5377. size_t sf_tosend =
  5378. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  5379. sf_sent =
  5380. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  5381. if (sf_sent > 0) {
  5382. conn->num_bytes_sent += sf_sent;
  5383. len -= sf_sent;
  5384. offset += sf_sent;
  5385. } else if (loop_cnt == 0) {
  5386. /* This file can not be sent using sendfile.
  5387. * This might be the case for pseudo-files in the
  5388. * /sys/ and /proc/ file system.
  5389. * Use the regular user mode copy code instead. */
  5390. break;
  5391. } else if (sf_sent == 0) {
  5392. /* No error, but 0 bytes sent. May be EOF? */
  5393. return;
  5394. }
  5395. loop_cnt++;
  5396. } while ((len > 0) && (sf_sent >= 0));
  5397. if (sf_sent > 0) {
  5398. return; /* OK */
  5399. }
  5400. /* sf_sent<0 means error, thus fall back to the classic way */
  5401. /* This is always the case, if sf_file is not a "normal" file,
  5402. * e.g., for sending data from the output of a CGI process. */
  5403. offset = (int64_t)sf_offs;
  5404. }
  5405. #endif
  5406. if ((offset > 0) && (fseeko(filep->fp, offset, SEEK_SET) != 0)) {
  5407. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  5408. send_http_error(
  5409. conn,
  5410. 500,
  5411. "%s",
  5412. "Error: Unable to access file at requested position.");
  5413. } else {
  5414. while (len > 0) {
  5415. /* Calculate how much to read from the file in the buffer */
  5416. to_read = sizeof(buf);
  5417. if ((int64_t)to_read > len) {
  5418. to_read = (int)len;
  5419. }
  5420. /* Read from file, exit the loop on error */
  5421. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp))
  5422. <= 0) {
  5423. break;
  5424. }
  5425. /* Send read bytes to the client, exit the loop on error */
  5426. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  5427. != num_read) {
  5428. break;
  5429. }
  5430. /* Both read and were successful, adjust counters */
  5431. conn->num_bytes_sent += num_written;
  5432. len -= num_written;
  5433. }
  5434. }
  5435. }
  5436. }
  5437. static int
  5438. parse_range_header(const char *header, int64_t *a, int64_t *b)
  5439. {
  5440. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5441. }
  5442. static void
  5443. construct_etag(char *buf, size_t buf_len, const struct file *filep)
  5444. {
  5445. if (filep != NULL && buf != NULL) {
  5446. mg_snprintf(NULL,
  5447. NULL, /* All calls to construct_etag use 64 byte buffer */
  5448. buf,
  5449. buf_len,
  5450. "\"%lx.%" INT64_FMT "\"",
  5451. (unsigned long)filep->last_modified,
  5452. filep->size);
  5453. }
  5454. }
  5455. static void
  5456. fclose_on_exec(struct file *filep, struct mg_connection *conn)
  5457. {
  5458. if (filep != NULL && filep->fp != NULL) {
  5459. #ifdef _WIN32
  5460. (void)conn; /* Unused. */
  5461. #else
  5462. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  5463. mg_cry(conn,
  5464. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5465. __func__,
  5466. strerror(ERRNO));
  5467. }
  5468. #endif
  5469. }
  5470. }
  5471. static void
  5472. handle_static_file_request(struct mg_connection *conn,
  5473. const char *path,
  5474. struct file *filep,
  5475. const char *mime_type)
  5476. {
  5477. char date[64], lm[64], etag[64];
  5478. char range[128]; /* large enough, so there will be no overflow */
  5479. const char *msg = "OK", *hdr;
  5480. time_t curtime = time(NULL);
  5481. int64_t cl, r1, r2;
  5482. struct vec mime_vec;
  5483. int n, truncated;
  5484. char gz_path[PATH_MAX];
  5485. const char *encoding = "";
  5486. const char *cors1, *cors2, *cors3;
  5487. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  5488. return;
  5489. }
  5490. if (mime_type == NULL) {
  5491. get_mime_type(conn->ctx, path, &mime_vec);
  5492. } else {
  5493. mime_vec.ptr = mime_type;
  5494. mime_vec.len = strlen(mime_type);
  5495. }
  5496. if (filep->size > INT64_MAX) {
  5497. send_http_error(conn,
  5498. 500,
  5499. "Error: File size is too large to send\n%" INT64_FMT,
  5500. filep->size);
  5501. }
  5502. cl = (int64_t)filep->size;
  5503. conn->status_code = 200;
  5504. range[0] = '\0';
  5505. /* if this file is in fact a pre-gzipped file, rewrite its filename
  5506. * it's important to rewrite the filename after resolving
  5507. * the mime type from it, to preserve the actual file's type */
  5508. if (filep->gzipped) {
  5509. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  5510. if (truncated) {
  5511. send_http_error(conn,
  5512. 500,
  5513. "Error: Path of zipped file too long (%s)",
  5514. path);
  5515. return;
  5516. }
  5517. path = gz_path;
  5518. encoding = "Content-Encoding: gzip\r\n";
  5519. }
  5520. if (!mg_fopen(conn, path, "rb", filep)) {
  5521. send_http_error(conn,
  5522. 500,
  5523. "Error: Cannot open file\nfopen(%s): %s",
  5524. path,
  5525. strerror(ERRNO));
  5526. return;
  5527. }
  5528. fclose_on_exec(filep, conn);
  5529. /* If Range: header specified, act accordingly */
  5530. r1 = r2 = 0;
  5531. hdr = mg_get_header(conn, "Range");
  5532. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  5533. && r2 >= 0) {
  5534. /* actually, range requests don't play well with a pre-gzipped
  5535. * file (since the range is specified in the uncompressed space) */
  5536. if (filep->gzipped) {
  5537. send_http_error(
  5538. conn,
  5539. 501,
  5540. "%s",
  5541. "Error: Range requests in gzipped files are not supported");
  5542. mg_fclose(filep);
  5543. return;
  5544. }
  5545. conn->status_code = 206;
  5546. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  5547. mg_snprintf(conn,
  5548. NULL, /* range buffer is big enough */
  5549. range,
  5550. sizeof(range),
  5551. "Content-Range: bytes "
  5552. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5553. r1,
  5554. r1 + cl - 1,
  5555. filep->size);
  5556. msg = "Partial Content";
  5557. }
  5558. hdr = mg_get_header(conn, "Origin");
  5559. if (hdr) {
  5560. /* Cross-origin resource sharing (CORS), see
  5561. * http://www.html5rocks.com/en/tutorials/cors/,
  5562. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  5563. * preflight is not supported for files. */
  5564. cors1 = "Access-Control-Allow-Origin: ";
  5565. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5566. cors3 = "\r\n";
  5567. } else {
  5568. cors1 = cors2 = cors3 = "";
  5569. }
  5570. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  5571. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  5572. gmt_time_string(date, sizeof(date), &curtime);
  5573. gmt_time_string(lm, sizeof(lm), &filep->last_modified);
  5574. construct_etag(etag, sizeof(etag), filep);
  5575. (void)mg_printf(conn,
  5576. "HTTP/1.1 %d %s\r\n"
  5577. "%s%s%s"
  5578. "Date: %s\r\n",
  5579. conn->status_code,
  5580. msg,
  5581. cors1,
  5582. cors2,
  5583. cors3,
  5584. date);
  5585. send_static_cache_header(conn);
  5586. (void)mg_printf(conn,
  5587. "Last-Modified: %s\r\n"
  5588. "Etag: %s\r\n"
  5589. "Content-Type: %.*s\r\n"
  5590. "Content-Length: %" INT64_FMT "\r\n"
  5591. "Connection: %s\r\n"
  5592. "Accept-Ranges: bytes\r\n"
  5593. "%s%s\r\n",
  5594. lm,
  5595. etag,
  5596. (int)mime_vec.len,
  5597. mime_vec.ptr,
  5598. cl,
  5599. suggest_connection_header(conn),
  5600. range,
  5601. encoding);
  5602. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  5603. send_file_data(conn, filep, r1, cl);
  5604. }
  5605. mg_fclose(filep);
  5606. }
  5607. void
  5608. mg_send_file(struct mg_connection *conn, const char *path)
  5609. {
  5610. mg_send_mime_file(conn, path, NULL);
  5611. }
  5612. void
  5613. mg_send_mime_file(struct mg_connection *conn,
  5614. const char *path,
  5615. const char *mime_type)
  5616. {
  5617. struct file file = STRUCT_FILE_INITIALIZER;
  5618. if (mg_stat(conn, path, &file)) {
  5619. if (file.is_directory) {
  5620. if (!conn) {
  5621. return;
  5622. }
  5623. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  5624. "yes")) {
  5625. handle_directory_request(conn, path);
  5626. } else {
  5627. send_http_error(conn,
  5628. 403,
  5629. "%s",
  5630. "Error: Directory listing denied");
  5631. }
  5632. } else {
  5633. handle_static_file_request(conn, path, &file, mime_type);
  5634. }
  5635. } else {
  5636. send_http_error(conn, 404, "%s", "Error: File not found");
  5637. }
  5638. }
  5639. /* For a given PUT path, create all intermediate subdirectories.
  5640. * Return 0 if the path itself is a directory.
  5641. * Return 1 if the path leads to a file.
  5642. * Return -1 for if the path is too long.
  5643. * Return -2 if path can not be created.
  5644. */
  5645. static int
  5646. put_dir(struct mg_connection *conn, const char *path)
  5647. {
  5648. char buf[PATH_MAX];
  5649. const char *s, *p;
  5650. struct file file = STRUCT_FILE_INITIALIZER;
  5651. size_t len;
  5652. int res = 1;
  5653. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5654. len = (size_t)(p - path);
  5655. if (len >= sizeof(buf)) {
  5656. /* path too long */
  5657. res = -1;
  5658. break;
  5659. }
  5660. memcpy(buf, path, len);
  5661. buf[len] = '\0';
  5662. /* Try to create intermediate directory */
  5663. DEBUG_TRACE("mkdir(%s)", buf);
  5664. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5665. /* path does not exixt and can not be created */
  5666. res = -2;
  5667. break;
  5668. }
  5669. /* Is path itself a directory? */
  5670. if (p[1] == '\0') {
  5671. res = 0;
  5672. }
  5673. }
  5674. return res;
  5675. }
  5676. static void
  5677. remove_bad_file(const struct mg_connection *conn, const char *path)
  5678. {
  5679. int r = mg_remove(path);
  5680. if (r != 0) {
  5681. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  5682. }
  5683. }
  5684. long long
  5685. mg_store_body(struct mg_connection *conn, const char *path)
  5686. {
  5687. char buf[MG_BUF_LEN];
  5688. long long len = 0;
  5689. int ret, n;
  5690. struct file fi;
  5691. if (conn->consumed_content != 0) {
  5692. mg_cry(conn, "%s: Contents already consumed", __func__);
  5693. return -11;
  5694. }
  5695. ret = put_dir(conn, path);
  5696. if (ret < 0) {
  5697. /* -1 for path too long,
  5698. * -2 for path can not be created. */
  5699. return ret;
  5700. }
  5701. if (ret != 1) {
  5702. /* Return 0 means, path itself is a directory. */
  5703. return 0;
  5704. }
  5705. if (mg_fopen(conn, path, "w", &fi) == 0) {
  5706. return -12;
  5707. }
  5708. ret = mg_read(conn, buf, sizeof(buf));
  5709. while (ret > 0) {
  5710. n = (int)fwrite(buf, 1, (size_t)ret, fi.fp);
  5711. if (n != ret) {
  5712. mg_fclose(&fi);
  5713. remove_bad_file(conn, path);
  5714. return -13;
  5715. }
  5716. ret = mg_read(conn, buf, sizeof(buf));
  5717. }
  5718. /* TODO: mg_fclose should return an error,
  5719. * and every caller should check and handle it. */
  5720. if (fclose(fi.fp) != 0) {
  5721. remove_bad_file(conn, path);
  5722. return -14;
  5723. }
  5724. return len;
  5725. }
  5726. /* Parse HTTP headers from the given buffer, advance buffer to the point
  5727. * where parsing stopped. */
  5728. static void
  5729. parse_http_headers(char **buf, struct mg_request_info *ri)
  5730. {
  5731. int i;
  5732. if (!ri) {
  5733. return;
  5734. }
  5735. ri->num_headers = 0;
  5736. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  5737. char *dp = *buf;
  5738. while ((*dp != ':') && (*dp != '\r') && (*dp != 0)) {
  5739. dp++;
  5740. }
  5741. if (!*dp) {
  5742. /* neither : nor \r\n. This is not a valid field. */
  5743. break;
  5744. }
  5745. if (*dp == '\r') {
  5746. if (dp[1] == '\n') {
  5747. /* \r\n */
  5748. ri->http_headers[i].name = *buf;
  5749. ri->http_headers[i].value = 0;
  5750. *buf = dp;
  5751. } else {
  5752. /* stray \r. This is not valid. */
  5753. break;
  5754. }
  5755. } else {
  5756. /* (*dp == ':') */
  5757. *dp = 0;
  5758. ri->http_headers[i].name = *buf;
  5759. do {
  5760. dp++;
  5761. } while (*dp == ' ');
  5762. ri->http_headers[i].value = dp;
  5763. *buf = strstr(dp, "\r\n");
  5764. }
  5765. ri->num_headers = i + 1;
  5766. if (*buf) {
  5767. (*buf)[0] = 0;
  5768. (*buf)[1] = 0;
  5769. *buf += 2;
  5770. } else {
  5771. *buf = dp;
  5772. break;
  5773. }
  5774. if (*buf[0] == '\r') {
  5775. /* This is the end of the header */
  5776. break;
  5777. }
  5778. }
  5779. }
  5780. static int
  5781. is_valid_http_method(const char *method)
  5782. {
  5783. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  5784. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  5785. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  5786. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  5787. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  5788. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  5789. /* TRACE method (RFC 2616) is not supported for security reasons */
  5790. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  5791. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  5792. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  5793. /* Unsupported WEBDAV Methods: */
  5794. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  5795. /* + 11 methods from RFC 3253 */
  5796. /* ORDERPATCH (RFC 3648) */
  5797. /* ACL (RFC 3744) */
  5798. /* SEARCH (RFC 5323) */
  5799. /* + MicroSoft extensions
  5800. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  5801. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  5802. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  5803. }
  5804. /* Parse HTTP request, fill in mg_request_info structure.
  5805. * This function modifies the buffer by NUL-terminating
  5806. * HTTP request components, header names and header values. */
  5807. static int
  5808. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  5809. {
  5810. int is_request, request_length;
  5811. if (!ri) {
  5812. return 0;
  5813. }
  5814. request_length = get_request_len(buf, len);
  5815. if (request_length > 0) {
  5816. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  5817. * remote_port */
  5818. ri->remote_user = ri->request_method = ri->request_uri =
  5819. ri->http_version = NULL;
  5820. ri->num_headers = 0;
  5821. buf[request_length - 1] = '\0';
  5822. /* RFC says that all initial whitespaces should be ingored */
  5823. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  5824. buf++;
  5825. }
  5826. ri->request_method = skip(&buf, " ");
  5827. ri->request_uri = skip(&buf, " ");
  5828. ri->http_version = skip(&buf, "\r\n");
  5829. /* HTTP message could be either HTTP request or HTTP response, e.g.
  5830. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  5831. is_request = is_valid_http_method(ri->request_method);
  5832. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  5833. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  5834. request_length = -1;
  5835. } else {
  5836. if (is_request) {
  5837. ri->http_version += 5;
  5838. }
  5839. parse_http_headers(&buf, ri);
  5840. }
  5841. }
  5842. return request_length;
  5843. }
  5844. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  5845. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  5846. * buffer (which marks the end of HTTP request). Buffer buf may already
  5847. * have some data. The length of the data is stored in nread.
  5848. * Upon every read operation, increase nread by the number of bytes read. */
  5849. static int
  5850. read_request(FILE *fp,
  5851. struct mg_connection *conn,
  5852. char *buf,
  5853. int bufsiz,
  5854. int *nread)
  5855. {
  5856. int request_len, n = 0;
  5857. struct timespec last_action_time;
  5858. double request_timeout;
  5859. if (!conn) {
  5860. return 0;
  5861. }
  5862. memset(&last_action_time, 0, sizeof(last_action_time));
  5863. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5864. /* value of request_timeout is in seconds, config in milliseconds */
  5865. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5866. } else {
  5867. request_timeout = -1.0;
  5868. }
  5869. request_len = get_request_len(buf, *nread);
  5870. /* first time reading from this connection */
  5871. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5872. while (
  5873. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) && (request_len == 0)
  5874. && ((mg_difftimespec(&last_action_time, &(conn->req_time))
  5875. <= request_timeout) || (request_timeout < 0))
  5876. && ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout))
  5877. > 0)) {
  5878. *nread += n;
  5879. /* assert(*nread <= bufsiz); */
  5880. if (*nread > bufsiz) {
  5881. return -2;
  5882. }
  5883. request_len = get_request_len(buf, *nread);
  5884. if (request_timeout > 0.0) {
  5885. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  5886. }
  5887. }
  5888. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  5889. }
  5890. #if !defined(NO_FILES)
  5891. /* For given directory path, substitute it to valid index file.
  5892. * Return 1 if index file has been found, 0 if not found.
  5893. * If the file is found, it's stats is returned in stp. */
  5894. static int
  5895. substitute_index_file(struct mg_connection *conn,
  5896. char *path,
  5897. size_t path_len,
  5898. struct file *filep)
  5899. {
  5900. if (conn && conn->ctx) {
  5901. const char *list = conn->ctx->config[INDEX_FILES];
  5902. struct file file = STRUCT_FILE_INITIALIZER;
  5903. struct vec filename_vec;
  5904. size_t n = strlen(path);
  5905. int found = 0;
  5906. /* The 'path' given to us points to the directory. Remove all trailing
  5907. * directory separator characters from the end of the path, and
  5908. * then append single directory separator character. */
  5909. while (n > 0 && path[n - 1] == '/') {
  5910. n--;
  5911. }
  5912. path[n] = '/';
  5913. /* Traverse index files list. For each entry, append it to the given
  5914. * path and see if the file exists. If it exists, break the loop */
  5915. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5916. /* Ignore too long entries that may overflow path buffer */
  5917. if (filename_vec.len > path_len - (n + 2)) {
  5918. continue;
  5919. }
  5920. /* Prepare full path to the index file */
  5921. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5922. /* Does it exist? */
  5923. if (mg_stat(conn, path, &file)) {
  5924. /* Yes it does, break the loop */
  5925. *filep = file;
  5926. found = 1;
  5927. break;
  5928. }
  5929. }
  5930. /* If no index file exists, restore directory path */
  5931. if (!found) {
  5932. path[n] = '\0';
  5933. }
  5934. return found;
  5935. }
  5936. return 0;
  5937. }
  5938. #endif
  5939. /* Return True if we should reply 304 Not Modified. */
  5940. static int
  5941. is_not_modified(const struct mg_connection *conn, const struct file *filep)
  5942. {
  5943. char etag[64];
  5944. const char *ims = mg_get_header(conn, "If-Modified-Since");
  5945. const char *inm = mg_get_header(conn, "If-None-Match");
  5946. construct_etag(etag, sizeof(etag), filep);
  5947. if (!filep) {
  5948. return 0;
  5949. }
  5950. return (inm != NULL && !mg_strcasecmp(etag, inm))
  5951. || (ims != NULL && (filep->last_modified <= parse_date_string(ims)));
  5952. }
  5953. #if !defined(NO_CGI) || !defined(NO_FILES)
  5954. static int
  5955. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  5956. {
  5957. const char *expect, *body;
  5958. char buf[MG_BUF_LEN];
  5959. int to_read, nread, success = 0;
  5960. int64_t buffered_len;
  5961. double timeout = -1.0;
  5962. if (!conn) {
  5963. return 0;
  5964. }
  5965. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  5966. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5967. }
  5968. expect = mg_get_header(conn, "Expect");
  5969. /* assert(fp != NULL); */
  5970. if (!fp) {
  5971. send_http_error(conn, 500, "%s", "Error: NULL File");
  5972. return 0;
  5973. }
  5974. if (conn->content_len == -1 && !conn->is_chunked) {
  5975. /* Content length is not specified by the client. */
  5976. send_http_error(conn,
  5977. 411,
  5978. "%s",
  5979. "Error: Client did not specify content length");
  5980. } else if ((expect != NULL)
  5981. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  5982. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  5983. send_http_error(conn,
  5984. 417,
  5985. "Error: Can not fulfill expectation %s",
  5986. expect);
  5987. } else {
  5988. if (expect != NULL) {
  5989. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  5990. conn->status_code = 100;
  5991. } else {
  5992. conn->status_code = 200;
  5993. }
  5994. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5995. - conn->consumed_content;
  5996. /* assert(buffered_len >= 0); */
  5997. /* assert(conn->consumed_content == 0); */
  5998. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  5999. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6000. return 0;
  6001. }
  6002. if (buffered_len > 0) {
  6003. if ((int64_t)buffered_len > conn->content_len) {
  6004. buffered_len = (int)conn->content_len;
  6005. }
  6006. body = conn->buf + conn->request_len + conn->consumed_content;
  6007. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6008. conn->consumed_content += buffered_len;
  6009. }
  6010. nread = 0;
  6011. while (conn->consumed_content < conn->content_len) {
  6012. to_read = sizeof(buf);
  6013. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6014. to_read = (int)(conn->content_len - conn->consumed_content);
  6015. }
  6016. nread = pull(NULL, conn, buf, to_read, timeout);
  6017. if (nread <= 0
  6018. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6019. break;
  6020. }
  6021. conn->consumed_content += nread;
  6022. }
  6023. if (conn->consumed_content == conn->content_len) {
  6024. success = (nread >= 0);
  6025. }
  6026. /* Each error code path in this function must send an error */
  6027. if (!success) {
  6028. /* NOTE: Maybe some data has already been sent. */
  6029. /* TODO (low): If some data has been sent, a correct error
  6030. * reply can no longer be sent, so just close the connection */
  6031. send_http_error(conn, 500, "%s", "");
  6032. }
  6033. }
  6034. return success;
  6035. }
  6036. #endif
  6037. #if !defined(NO_CGI)
  6038. /* This structure helps to create an environment for the spawned CGI program.
  6039. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6040. * last element must be NULL.
  6041. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6042. * strings must reside in a contiguous buffer. The end of the buffer is
  6043. * marked by two '\0' characters.
  6044. * We satisfy both worlds: we create an envp array (which is vars), all
  6045. * entries are actually pointers inside buf. */
  6046. struct cgi_environment {
  6047. struct mg_connection *conn;
  6048. /* Data block */
  6049. char *buf; /* Environment buffer */
  6050. size_t buflen; /* Space available in buf */
  6051. size_t bufused; /* Space taken in buf */
  6052. /* Index block */
  6053. char **var; /* char **envp */
  6054. size_t varlen; /* Number of variables available in var */
  6055. size_t varused; /* Number of variables stored in var */
  6056. };
  6057. static void addenv(struct cgi_environment *env,
  6058. PRINTF_FORMAT_STRING(const char *fmt),
  6059. ...) PRINTF_ARGS(2, 3);
  6060. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6061. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6062. static void
  6063. addenv(struct cgi_environment *env, const char *fmt, ...)
  6064. {
  6065. size_t n, space;
  6066. int truncated;
  6067. char *added;
  6068. va_list ap;
  6069. /* Calculate how much space is left in the buffer */
  6070. space = (env->buflen - env->bufused);
  6071. /* Calculate an estimate for the required space */
  6072. n = strlen(fmt) + 2 + 128;
  6073. do {
  6074. if (space <= n) {
  6075. /* Allocate new buffer */
  6076. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6077. added = (char *)mg_realloc(env->buf, n);
  6078. if (!added) {
  6079. /* Out of memory */
  6080. mg_cry(env->conn,
  6081. "%s: Cannot allocate memory for CGI variable [%s]",
  6082. __func__,
  6083. fmt);
  6084. return;
  6085. }
  6086. env->buf = added;
  6087. env->buflen = n;
  6088. space = (env->buflen - env->bufused);
  6089. }
  6090. /* Make a pointer to the free space int the buffer */
  6091. added = env->buf + env->bufused;
  6092. /* Copy VARIABLE=VALUE\0 string into the free space */
  6093. va_start(ap, fmt);
  6094. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6095. va_end(ap);
  6096. /* Do not add truncated strings to the environment */
  6097. if (truncated) {
  6098. /* Reallocate the buffer */
  6099. space = 0;
  6100. n = 1;
  6101. }
  6102. } while (truncated);
  6103. /* Calculate number of bytes added to the environment */
  6104. n = strlen(added) + 1;
  6105. env->bufused += n;
  6106. /* Now update the variable index */
  6107. space = (env->varlen - env->varused);
  6108. if (space < 2) {
  6109. mg_cry(env->conn,
  6110. "%s: Cannot register CGI variable [%s]",
  6111. __func__,
  6112. fmt);
  6113. return;
  6114. }
  6115. /* Append a pointer to the added string into the envp array */
  6116. env->var[env->varused] = added;
  6117. env->varused++;
  6118. }
  6119. static void
  6120. prepare_cgi_environment(struct mg_connection *conn,
  6121. const char *prog,
  6122. struct cgi_environment *env)
  6123. {
  6124. const char *s;
  6125. struct vec var_vec;
  6126. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6127. int i, truncated;
  6128. if (conn == NULL || prog == NULL || env == NULL) {
  6129. return;
  6130. }
  6131. env->conn = conn;
  6132. env->buflen = CGI_ENVIRONMENT_SIZE;
  6133. env->bufused = 0;
  6134. env->buf = (char *)mg_malloc(env->buflen);
  6135. env->varlen = MAX_CGI_ENVIR_VARS;
  6136. env->varused = 0;
  6137. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  6138. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  6139. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6140. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6141. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  6142. /* Prepare the environment block */
  6143. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  6144. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  6145. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  6146. #if defined(USE_IPV6)
  6147. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  6148. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  6149. } else
  6150. #endif
  6151. {
  6152. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  6153. }
  6154. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  6155. addenv(env, "REMOTE_ADDR=%s", src_addr);
  6156. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  6157. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  6158. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  6159. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  6160. /* SCRIPT_NAME */
  6161. addenv(env,
  6162. "SCRIPT_NAME=%.*s",
  6163. (int)strlen(conn->request_info.local_uri)
  6164. - ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  6165. conn->request_info.local_uri);
  6166. addenv(env, "SCRIPT_FILENAME=%s", prog);
  6167. if (conn->path_info == NULL) {
  6168. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  6169. } else {
  6170. addenv(env,
  6171. "PATH_TRANSLATED=%s%s",
  6172. conn->ctx->config[DOCUMENT_ROOT],
  6173. conn->path_info);
  6174. }
  6175. addenv(env, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  6176. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  6177. addenv(env, "CONTENT_TYPE=%s", s);
  6178. }
  6179. if (conn->request_info.query_string != NULL) {
  6180. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  6181. }
  6182. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  6183. addenv(env, "CONTENT_LENGTH=%s", s);
  6184. }
  6185. if ((s = getenv("PATH")) != NULL) {
  6186. addenv(env, "PATH=%s", s);
  6187. }
  6188. if (conn->path_info != NULL) {
  6189. addenv(env, "PATH_INFO=%s", conn->path_info);
  6190. }
  6191. if (conn->status_code > 0) {
  6192. /* CGI error handler should show the status code */
  6193. addenv(env, "STATUS=%d", conn->status_code);
  6194. }
  6195. #if defined(_WIN32)
  6196. if ((s = getenv("COMSPEC")) != NULL) {
  6197. addenv(env, "COMSPEC=%s", s);
  6198. }
  6199. if ((s = getenv("SYSTEMROOT")) != NULL) {
  6200. addenv(env, "SYSTEMROOT=%s", s);
  6201. }
  6202. if ((s = getenv("SystemDrive")) != NULL) {
  6203. addenv(env, "SystemDrive=%s", s);
  6204. }
  6205. if ((s = getenv("ProgramFiles")) != NULL) {
  6206. addenv(env, "ProgramFiles=%s", s);
  6207. }
  6208. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  6209. addenv(env, "ProgramFiles(x86)=%s", s);
  6210. }
  6211. #else
  6212. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  6213. addenv(env, "LD_LIBRARY_PATH=%s", s);
  6214. }
  6215. #endif /* _WIN32 */
  6216. if ((s = getenv("PERLLIB")) != NULL) {
  6217. addenv(env, "PERLLIB=%s", s);
  6218. }
  6219. if (conn->request_info.remote_user != NULL) {
  6220. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  6221. addenv(env, "%s", "AUTH_TYPE=Digest");
  6222. }
  6223. /* Add all headers as HTTP_* variables */
  6224. for (i = 0; i < conn->request_info.num_headers; i++) {
  6225. (void)mg_snprintf(conn,
  6226. &truncated,
  6227. http_var_name,
  6228. sizeof(http_var_name),
  6229. "HTTP_%s",
  6230. conn->request_info.http_headers[i].name);
  6231. if (truncated) {
  6232. mg_cry(conn,
  6233. "%s: HTTP header variable too long [%s]",
  6234. __func__,
  6235. conn->request_info.http_headers[i].name);
  6236. continue;
  6237. }
  6238. /* Convert variable name into uppercase, and change - to _ */
  6239. for (p = http_var_name; *p != '\0'; p++) {
  6240. if (*p == '-') {
  6241. *p = '_';
  6242. }
  6243. *p = (char)toupper(*(unsigned char *)p);
  6244. }
  6245. addenv(env,
  6246. "%s=%s",
  6247. http_var_name,
  6248. conn->request_info.http_headers[i].value);
  6249. }
  6250. /* Add user-specified variables */
  6251. s = conn->ctx->config[CGI_ENVIRONMENT];
  6252. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  6253. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  6254. }
  6255. env->var[env->varused] = NULL;
  6256. env->buf[env->bufused] = '\0';
  6257. }
  6258. static void
  6259. handle_cgi_request(struct mg_connection *conn, const char *prog)
  6260. {
  6261. char *buf;
  6262. size_t buflen;
  6263. int headers_len, data_len, i, truncated;
  6264. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  6265. const char *status, *status_text, *connection_state;
  6266. char *pbuf, dir[PATH_MAX], *p;
  6267. struct mg_request_info ri;
  6268. struct cgi_environment blk;
  6269. FILE *in = NULL, *out = NULL, *err = NULL;
  6270. struct file fout = STRUCT_FILE_INITIALIZER;
  6271. pid_t pid = (pid_t)-1;
  6272. if (conn == NULL) {
  6273. return;
  6274. }
  6275. buf = NULL;
  6276. buflen = 16384;
  6277. prepare_cgi_environment(conn, prog, &blk);
  6278. /* CGI must be executed in its own directory. 'dir' must point to the
  6279. * directory containing executable program, 'p' must point to the
  6280. * executable program name relative to 'dir'. */
  6281. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  6282. if (truncated) {
  6283. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  6284. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  6285. goto done;
  6286. }
  6287. if ((p = strrchr(dir, '/')) != NULL) {
  6288. *p++ = '\0';
  6289. } else {
  6290. dir[0] = '.', dir[1] = '\0';
  6291. p = (char *)prog;
  6292. }
  6293. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  6294. status = strerror(ERRNO);
  6295. mg_cry(conn,
  6296. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  6297. prog,
  6298. status);
  6299. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  6300. goto done;
  6301. }
  6302. pid = spawn_process(
  6303. conn, p, blk.buf, blk.var, fdin[0], fdout[1], fderr[1], dir);
  6304. if (pid == (pid_t)-1) {
  6305. status = strerror(ERRNO);
  6306. mg_cry(conn,
  6307. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  6308. prog,
  6309. status);
  6310. send_http_error(conn,
  6311. 500,
  6312. "Error: Cannot spawn CGI process [%s]: %s",
  6313. prog,
  6314. status);
  6315. goto done;
  6316. }
  6317. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  6318. set_close_on_exec((SOCKET)fdin[0], conn);
  6319. set_close_on_exec((SOCKET)fdin[1], conn);
  6320. set_close_on_exec((SOCKET)fdout[0], conn);
  6321. set_close_on_exec((SOCKET)fdout[1], conn);
  6322. set_close_on_exec((SOCKET)fderr[0], conn);
  6323. set_close_on_exec((SOCKET)fderr[1], conn);
  6324. /* Parent closes only one side of the pipes.
  6325. * If we don't mark them as closed, close() attempt before
  6326. * return from this function throws an exception on Windows.
  6327. * Windows does not like when closed descriptor is closed again. */
  6328. (void)close(fdin[0]);
  6329. (void)close(fdout[1]);
  6330. (void)close(fderr[1]);
  6331. fdin[0] = fdout[1] = fderr[1] = -1;
  6332. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  6333. status = strerror(ERRNO);
  6334. mg_cry(conn,
  6335. "Error: CGI program \"%s\": Can not open stdin: %s",
  6336. prog,
  6337. status);
  6338. send_http_error(conn,
  6339. 500,
  6340. "Error: CGI can not open fdin\nfopen: %s",
  6341. status);
  6342. goto done;
  6343. }
  6344. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  6345. status = strerror(ERRNO);
  6346. mg_cry(conn,
  6347. "Error: CGI program \"%s\": Can not open stdout: %s",
  6348. prog,
  6349. status);
  6350. send_http_error(conn,
  6351. 500,
  6352. "Error: CGI can not open fdout\nfopen: %s",
  6353. status);
  6354. goto done;
  6355. }
  6356. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  6357. status = strerror(ERRNO);
  6358. mg_cry(conn,
  6359. "Error: CGI program \"%s\": Can not open stderr: %s",
  6360. prog,
  6361. status);
  6362. send_http_error(conn,
  6363. 500,
  6364. "Error: CGI can not open fdout\nfopen: %s",
  6365. status);
  6366. goto done;
  6367. }
  6368. setbuf(in, NULL);
  6369. setbuf(out, NULL);
  6370. setbuf(err, NULL);
  6371. fout.fp = out;
  6372. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  6373. /* This is a POST/PUT request, or another request with body data. */
  6374. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  6375. /* Error sending the body data */
  6376. mg_cry(conn,
  6377. "Error: CGI program \"%s\": Forward body data failed",
  6378. prog);
  6379. goto done;
  6380. }
  6381. }
  6382. /* Close so child gets an EOF. */
  6383. fclose(in);
  6384. in = NULL;
  6385. fdin[1] = -1;
  6386. /* Now read CGI reply into a buffer. We need to set correct
  6387. * status code, thus we need to see all HTTP headers first.
  6388. * Do not send anything back to client, until we buffer in all
  6389. * HTTP headers. */
  6390. data_len = 0;
  6391. buf = (char *)mg_malloc(buflen);
  6392. if (buf == NULL) {
  6393. send_http_error(conn,
  6394. 500,
  6395. "Error: Not enough memory for CGI buffer (%u bytes)",
  6396. (unsigned int)buflen);
  6397. mg_cry(conn,
  6398. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  6399. "bytes)",
  6400. prog,
  6401. (unsigned int)buflen);
  6402. goto done;
  6403. }
  6404. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  6405. if (headers_len <= 0) {
  6406. /* Could not parse the CGI response. Check if some error message on
  6407. * stderr. */
  6408. i = pull_all(err, conn, buf, (int)buflen);
  6409. if (i > 0) {
  6410. mg_cry(conn,
  6411. "Error: CGI program \"%s\" sent error "
  6412. "message: [%.*s]",
  6413. prog,
  6414. i,
  6415. buf);
  6416. send_http_error(conn,
  6417. 500,
  6418. "Error: CGI program \"%s\" sent error "
  6419. "message: [%.*s]",
  6420. prog,
  6421. i,
  6422. buf);
  6423. } else {
  6424. mg_cry(conn,
  6425. "Error: CGI program sent malformed or too big "
  6426. "(>%u bytes) HTTP headers: [%.*s]",
  6427. (unsigned)buflen,
  6428. data_len,
  6429. buf);
  6430. send_http_error(conn,
  6431. 500,
  6432. "Error: CGI program sent malformed or too big "
  6433. "(>%u bytes) HTTP headers: [%.*s]",
  6434. (unsigned)buflen,
  6435. data_len,
  6436. buf);
  6437. }
  6438. goto done;
  6439. }
  6440. pbuf = buf;
  6441. buf[headers_len - 1] = '\0';
  6442. parse_http_headers(&pbuf, &ri);
  6443. /* Make up and send the status line */
  6444. status_text = "OK";
  6445. if ((status = get_header(&ri, "Status")) != NULL) {
  6446. conn->status_code = atoi(status);
  6447. status_text = status;
  6448. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  6449. status_text++;
  6450. }
  6451. } else if (get_header(&ri, "Location") != NULL) {
  6452. conn->status_code = 302;
  6453. } else {
  6454. conn->status_code = 200;
  6455. }
  6456. connection_state = get_header(&ri, "Connection");
  6457. if (!header_has_option(connection_state, "keep-alive")) {
  6458. conn->must_close = 1;
  6459. }
  6460. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  6461. /* Send headers */
  6462. for (i = 0; i < ri.num_headers; i++) {
  6463. mg_printf(conn,
  6464. "%s: %s\r\n",
  6465. ri.http_headers[i].name,
  6466. ri.http_headers[i].value);
  6467. }
  6468. mg_write(conn, "\r\n", 2);
  6469. /* Send chunk of data that may have been read after the headers */
  6470. conn->num_bytes_sent +=
  6471. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  6472. /* Read the rest of CGI output and send to the client */
  6473. send_file_data(conn, &fout, 0, INT64_MAX);
  6474. done:
  6475. mg_free(blk.var);
  6476. mg_free(blk.buf);
  6477. if (pid != (pid_t)-1) {
  6478. kill(pid, SIGKILL);
  6479. #if !defined(_WIN32)
  6480. {
  6481. int st;
  6482. while (waitpid(pid, &st, 0) != -1)
  6483. ; /* clean zombies */
  6484. }
  6485. #endif
  6486. }
  6487. if (fdin[0] != -1) {
  6488. close(fdin[0]);
  6489. }
  6490. if (fdout[1] != -1) {
  6491. close(fdout[1]);
  6492. }
  6493. if (in != NULL) {
  6494. fclose(in);
  6495. } else if (fdin[1] != -1) {
  6496. close(fdin[1]);
  6497. }
  6498. if (out != NULL) {
  6499. fclose(out);
  6500. } else if (fdout[0] != -1) {
  6501. close(fdout[0]);
  6502. }
  6503. if (err != NULL) {
  6504. fclose(err);
  6505. } else if (fderr[0] != -1) {
  6506. close(fderr[0]);
  6507. }
  6508. if (buf != NULL) {
  6509. mg_free(buf);
  6510. }
  6511. }
  6512. #endif /* !NO_CGI */
  6513. #if !defined(NO_FILES)
  6514. static void
  6515. mkcol(struct mg_connection *conn, const char *path)
  6516. {
  6517. int rc, body_len;
  6518. struct de de;
  6519. char date[64];
  6520. time_t curtime = time(NULL);
  6521. if (conn == NULL) {
  6522. return;
  6523. }
  6524. /* TODO (mid): Check the send_http_error situations in this function */
  6525. memset(&de.file, 0, sizeof(de.file));
  6526. if (!mg_stat(conn, path, &de.file)) {
  6527. mg_cry(conn,
  6528. "%s: mg_stat(%s) failed: %s",
  6529. __func__,
  6530. path,
  6531. strerror(ERRNO));
  6532. }
  6533. if (de.file.last_modified) {
  6534. /* TODO (high): This check does not seem to make any sense ! */
  6535. send_http_error(
  6536. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6537. return;
  6538. }
  6539. body_len = conn->data_len - conn->request_len;
  6540. if (body_len > 0) {
  6541. send_http_error(
  6542. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6543. return;
  6544. }
  6545. rc = mg_mkdir(path, 0755);
  6546. if (rc == 0) {
  6547. conn->status_code = 201;
  6548. gmt_time_string(date, sizeof(date), &curtime);
  6549. mg_printf(conn,
  6550. "HTTP/1.1 %d Created\r\n"
  6551. "Date: %s\r\n",
  6552. conn->status_code,
  6553. date);
  6554. send_static_cache_header(conn);
  6555. mg_printf(conn,
  6556. "Content-Length: 0\r\n"
  6557. "Connection: %s\r\n\r\n",
  6558. suggest_connection_header(conn));
  6559. } else if (rc == -1) {
  6560. if (errno == EEXIST) {
  6561. send_http_error(
  6562. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6563. } else if (errno == EACCES) {
  6564. send_http_error(
  6565. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6566. } else if (errno == ENOENT) {
  6567. send_http_error(
  6568. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  6569. } else {
  6570. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  6571. }
  6572. }
  6573. }
  6574. static void
  6575. put_file(struct mg_connection *conn, const char *path)
  6576. {
  6577. struct file file = STRUCT_FILE_INITIALIZER;
  6578. const char *range;
  6579. int64_t r1, r2;
  6580. int rc;
  6581. char date[64];
  6582. time_t curtime = time(NULL);
  6583. if (conn == NULL) {
  6584. return;
  6585. }
  6586. if (mg_stat(conn, path, &file)) {
  6587. /* File already exists */
  6588. conn->status_code = 200;
  6589. if (file.is_directory) {
  6590. /* This is an already existing directory,
  6591. * so there is nothing to do for the server. */
  6592. rc = 0;
  6593. } else {
  6594. /* File exists and is not a directory. */
  6595. /* Can it be replaced? */
  6596. if (file.membuf != NULL) {
  6597. /* This is an "in-memory" file, that can not be replaced */
  6598. send_http_error(
  6599. conn,
  6600. 405,
  6601. "Error: Put not possible\nReplacing %s is not supported",
  6602. path);
  6603. return;
  6604. }
  6605. /* Check if the server may write this file */
  6606. if (access(path, W_OK) == 0) {
  6607. /* Access granted */
  6608. conn->status_code = 200;
  6609. rc = 1;
  6610. } else {
  6611. send_http_error(
  6612. conn,
  6613. 403,
  6614. "Error: Put not possible\nReplacing %s is not allowed",
  6615. path);
  6616. return;
  6617. }
  6618. }
  6619. } else {
  6620. /* File should be created */
  6621. conn->status_code = 201;
  6622. rc = put_dir(conn, path);
  6623. }
  6624. if (rc == 0) {
  6625. /* put_dir returns 0 if path is a directory */
  6626. gmt_time_string(date, sizeof(date), &curtime);
  6627. mg_printf(conn,
  6628. "HTTP/1.1 %d %s\r\n",
  6629. conn->status_code,
  6630. mg_get_response_code_text(conn->status_code, NULL));
  6631. send_no_cache_header(conn);
  6632. mg_printf(conn,
  6633. "Date: %s\r\n"
  6634. "Content-Length: 0\r\n"
  6635. "Connection: %s\r\n\r\n",
  6636. date,
  6637. suggest_connection_header(conn));
  6638. /* Request to create a directory has been fulfilled successfully.
  6639. * No need to put a file. */
  6640. return;
  6641. }
  6642. if (rc == -1) {
  6643. /* put_dir returns -1 if the path is too long */
  6644. send_http_error(conn,
  6645. 414,
  6646. "Error: Path too long\nput_dir(%s): %s",
  6647. path,
  6648. strerror(ERRNO));
  6649. return;
  6650. }
  6651. if (rc == -2) {
  6652. /* put_dir returns -2 if the directory can not be created */
  6653. send_http_error(conn,
  6654. 500,
  6655. "Error: Can not create directory\nput_dir(%s): %s",
  6656. path,
  6657. strerror(ERRNO));
  6658. return;
  6659. }
  6660. /* A file should be created or overwritten. */
  6661. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  6662. mg_fclose(&file);
  6663. send_http_error(conn,
  6664. 500,
  6665. "Error: Can not create file\nfopen(%s): %s",
  6666. path,
  6667. strerror(ERRNO));
  6668. return;
  6669. }
  6670. fclose_on_exec(&file, conn);
  6671. range = mg_get_header(conn, "Content-Range");
  6672. r1 = r2 = 0;
  6673. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  6674. conn->status_code = 206; /* Partial content */
  6675. fseeko(file.fp, r1, SEEK_SET);
  6676. }
  6677. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  6678. /* forward_body_data failed.
  6679. * The error code has already been sent to the client,
  6680. * and conn->status_code is already set. */
  6681. mg_fclose(&file);
  6682. return;
  6683. }
  6684. gmt_time_string(date, sizeof(date), &curtime);
  6685. mg_printf(conn,
  6686. "HTTP/1.1 %d %s\r\n",
  6687. conn->status_code,
  6688. mg_get_response_code_text(conn->status_code, NULL));
  6689. send_no_cache_header(conn);
  6690. mg_printf(conn,
  6691. "Date: %s\r\n"
  6692. "Content-Length: 0\r\n"
  6693. "Connection: %s\r\n\r\n",
  6694. date,
  6695. suggest_connection_header(conn));
  6696. mg_fclose(&file);
  6697. }
  6698. static void
  6699. delete_file(struct mg_connection *conn, const char *path)
  6700. {
  6701. struct de de;
  6702. memset(&de.file, 0, sizeof(de.file));
  6703. if (!mg_stat(conn, path, &de.file)) {
  6704. /* mg_stat returns 0 if the file does not exist */
  6705. send_http_error(conn,
  6706. 404,
  6707. "Error: Cannot delete file\nFile %s not found",
  6708. path);
  6709. return;
  6710. }
  6711. if (de.file.membuf != NULL) {
  6712. /* the file is cached in memory */
  6713. send_http_error(
  6714. conn,
  6715. 405,
  6716. "Error: Delete not possible\nDeleting %s is not supported",
  6717. path);
  6718. return;
  6719. }
  6720. if (de.file.is_directory) {
  6721. if (remove_directory(conn, path)) {
  6722. /* Delete is successful: Return 204 without content. */
  6723. send_http_error(conn, 204, "%s", "");
  6724. } else {
  6725. /* Delete is not successful: Return 500 (Server error). */
  6726. send_http_error(conn, 500, "Error: Could not delete %s", path);
  6727. }
  6728. return;
  6729. }
  6730. /* This is an existing file (not a directory).
  6731. * Check if write permission is granted. */
  6732. if (access(path, W_OK) != 0) {
  6733. /* File is read only */
  6734. send_http_error(
  6735. conn,
  6736. 403,
  6737. "Error: Delete not possible\nDeleting %s is not allowed",
  6738. path);
  6739. return;
  6740. }
  6741. /* Try to delete it. */
  6742. if (mg_remove(path) == 0) {
  6743. /* Delete was successful: Return 204 without content. */
  6744. send_http_error(conn, 204, "%s", "");
  6745. } else {
  6746. /* Delete not successful (file locked). */
  6747. send_http_error(conn,
  6748. 423,
  6749. "Error: Cannot delete file\nremove(%s): %s",
  6750. path,
  6751. strerror(ERRNO));
  6752. }
  6753. }
  6754. #endif /* !NO_FILES */
  6755. static void
  6756. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  6757. static void
  6758. do_ssi_include(struct mg_connection *conn,
  6759. const char *ssi,
  6760. char *tag,
  6761. int include_level)
  6762. {
  6763. char file_name[MG_BUF_LEN], path[512], *p;
  6764. struct file file = STRUCT_FILE_INITIALIZER;
  6765. size_t len;
  6766. int truncated = 0;
  6767. if (conn == NULL) {
  6768. return;
  6769. }
  6770. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  6771. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  6772. * always < MG_BUF_LEN. */
  6773. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  6774. /* File name is relative to the webserver root */
  6775. file_name[511] = 0;
  6776. (void)mg_snprintf(conn,
  6777. &truncated,
  6778. path,
  6779. sizeof(path),
  6780. "%s/%s",
  6781. conn->ctx->config[DOCUMENT_ROOT],
  6782. file_name);
  6783. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  6784. /* File name is relative to the webserver working directory
  6785. * or it is absolute system path */
  6786. file_name[511] = 0;
  6787. (void)
  6788. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  6789. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  6790. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  6791. /* File name is relative to the currect document */
  6792. file_name[511] = 0;
  6793. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  6794. if (!truncated) {
  6795. if ((p = strrchr(path, '/')) != NULL) {
  6796. p[1] = '\0';
  6797. }
  6798. len = strlen(path);
  6799. (void)mg_snprintf(conn,
  6800. &truncated,
  6801. path + len,
  6802. sizeof(path) - len,
  6803. "%s",
  6804. file_name);
  6805. }
  6806. } else {
  6807. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  6808. return;
  6809. }
  6810. if (truncated) {
  6811. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  6812. return;
  6813. }
  6814. if (!mg_fopen(conn, path, "rb", &file)) {
  6815. mg_cry(conn,
  6816. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  6817. tag,
  6818. path,
  6819. strerror(ERRNO));
  6820. } else {
  6821. fclose_on_exec(&file, conn);
  6822. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  6823. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  6824. path) > 0) {
  6825. send_ssi_file(conn, path, &file, include_level + 1);
  6826. } else {
  6827. send_file_data(conn, &file, 0, INT64_MAX);
  6828. }
  6829. mg_fclose(&file);
  6830. }
  6831. }
  6832. #if !defined(NO_POPEN)
  6833. static void
  6834. do_ssi_exec(struct mg_connection *conn, char *tag)
  6835. {
  6836. char cmd[1024] = "";
  6837. struct file file = STRUCT_FILE_INITIALIZER;
  6838. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  6839. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  6840. } else {
  6841. cmd[1023] = 0;
  6842. if ((file.fp = popen(cmd, "r")) == NULL) {
  6843. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  6844. } else {
  6845. send_file_data(conn, &file, 0, INT64_MAX);
  6846. pclose(file.fp);
  6847. }
  6848. }
  6849. }
  6850. #endif /* !NO_POPEN */
  6851. static int
  6852. mg_fgetc(struct file *filep, int offset)
  6853. {
  6854. if (filep == NULL) {
  6855. return EOF;
  6856. }
  6857. if (filep->membuf != NULL && offset >= 0
  6858. && ((unsigned int)(offset)) < filep->size) {
  6859. return ((unsigned char *)filep->membuf)[offset];
  6860. } else if (filep->fp != NULL) {
  6861. return fgetc(filep->fp);
  6862. } else {
  6863. return EOF;
  6864. }
  6865. }
  6866. static void
  6867. send_ssi_file(struct mg_connection *conn,
  6868. const char *path,
  6869. struct file *filep,
  6870. int include_level)
  6871. {
  6872. char buf[MG_BUF_LEN];
  6873. int ch, offset, len, in_ssi_tag;
  6874. if (include_level > 10) {
  6875. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  6876. return;
  6877. }
  6878. in_ssi_tag = len = offset = 0;
  6879. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  6880. if (in_ssi_tag && ch == '>') {
  6881. in_ssi_tag = 0;
  6882. buf[len++] = (char)ch;
  6883. buf[len] = '\0';
  6884. /* assert(len <= (int) sizeof(buf)); */
  6885. if (len > (int)sizeof(buf)) {
  6886. break;
  6887. }
  6888. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  6889. /* Not an SSI tag, pass it */
  6890. (void)mg_write(conn, buf, (size_t)len);
  6891. } else {
  6892. if (!memcmp(buf + 5, "include", 7)) {
  6893. do_ssi_include(conn, path, buf + 12, include_level);
  6894. #if !defined(NO_POPEN)
  6895. } else if (!memcmp(buf + 5, "exec", 4)) {
  6896. do_ssi_exec(conn, buf + 9);
  6897. #endif /* !NO_POPEN */
  6898. } else {
  6899. mg_cry(conn,
  6900. "%s: unknown SSI "
  6901. "command: \"%s\"",
  6902. path,
  6903. buf);
  6904. }
  6905. }
  6906. len = 0;
  6907. } else if (in_ssi_tag) {
  6908. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  6909. /* Not an SSI tag */
  6910. in_ssi_tag = 0;
  6911. } else if (len == (int)sizeof(buf) - 2) {
  6912. mg_cry(conn, "%s: SSI tag is too large", path);
  6913. len = 0;
  6914. }
  6915. buf[len++] = (char)(ch & 0xff);
  6916. } else if (ch == '<') {
  6917. in_ssi_tag = 1;
  6918. if (len > 0) {
  6919. mg_write(conn, buf, (size_t)len);
  6920. }
  6921. len = 0;
  6922. buf[len++] = (char)(ch & 0xff);
  6923. } else {
  6924. buf[len++] = (char)(ch & 0xff);
  6925. if (len == (int)sizeof(buf)) {
  6926. mg_write(conn, buf, (size_t)len);
  6927. len = 0;
  6928. }
  6929. }
  6930. }
  6931. /* Send the rest of buffered data */
  6932. if (len > 0) {
  6933. mg_write(conn, buf, (size_t)len);
  6934. }
  6935. }
  6936. static void
  6937. handle_ssi_file_request(struct mg_connection *conn,
  6938. const char *path,
  6939. struct file *filep)
  6940. {
  6941. char date[64];
  6942. time_t curtime = time(NULL);
  6943. const char *cors1, *cors2, *cors3;
  6944. if (conn == NULL || path == NULL || filep == NULL) {
  6945. return;
  6946. }
  6947. if (mg_get_header(conn, "Origin")) {
  6948. /* Cross-origin resource sharing (CORS). */
  6949. cors1 = "Access-Control-Allow-Origin: ";
  6950. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6951. cors3 = "\r\n";
  6952. } else {
  6953. cors1 = cors2 = cors3 = "";
  6954. }
  6955. if (!mg_fopen(conn, path, "rb", filep)) {
  6956. /* File exists (precondition for calling this function),
  6957. * but can not be opened by the server. */
  6958. send_http_error(conn,
  6959. 500,
  6960. "Error: Cannot read file\nfopen(%s): %s",
  6961. path,
  6962. strerror(ERRNO));
  6963. } else {
  6964. conn->must_close = 1;
  6965. gmt_time_string(date, sizeof(date), &curtime);
  6966. fclose_on_exec(filep, conn);
  6967. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6968. send_no_cache_header(conn);
  6969. mg_printf(conn,
  6970. "%s%s%s"
  6971. "Date: %s\r\n"
  6972. "Content-Type: text/html\r\n"
  6973. "Connection: %s\r\n\r\n",
  6974. cors1,
  6975. cors2,
  6976. cors3,
  6977. date,
  6978. suggest_connection_header(conn));
  6979. send_ssi_file(conn, path, filep, 0);
  6980. mg_fclose(filep);
  6981. }
  6982. }
  6983. #if !defined(NO_FILES)
  6984. static void
  6985. send_options(struct mg_connection *conn)
  6986. {
  6987. char date[64];
  6988. time_t curtime = time(NULL);
  6989. if (!conn) {
  6990. return;
  6991. }
  6992. conn->status_code = 200;
  6993. conn->must_close = 1;
  6994. gmt_time_string(date, sizeof(date), &curtime);
  6995. mg_printf(conn,
  6996. "HTTP/1.1 200 OK\r\n"
  6997. "Date: %s\r\n"
  6998. /* TODO: "Cache-Control" (?) */
  6999. "Connection: %s\r\n"
  7000. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7001. "PROPFIND, MKCOL\r\n"
  7002. "DAV: 1\r\n\r\n",
  7003. date,
  7004. suggest_connection_header(conn));
  7005. }
  7006. /* Writes PROPFIND properties for a collection element */
  7007. static void
  7008. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  7009. {
  7010. char mtime[64];
  7011. if (conn == NULL || uri == NULL || filep == NULL) {
  7012. return;
  7013. }
  7014. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7015. conn->num_bytes_sent +=
  7016. mg_printf(conn,
  7017. "<d:response>"
  7018. "<d:href>%s</d:href>"
  7019. "<d:propstat>"
  7020. "<d:prop>"
  7021. "<d:resourcetype>%s</d:resourcetype>"
  7022. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7023. "<d:getlastmodified>%s</d:getlastmodified>"
  7024. "</d:prop>"
  7025. "<d:status>HTTP/1.1 200 OK</d:status>"
  7026. "</d:propstat>"
  7027. "</d:response>\n",
  7028. uri,
  7029. filep->is_directory ? "<d:collection/>" : "",
  7030. filep->size,
  7031. mtime);
  7032. }
  7033. static void
  7034. print_dav_dir_entry(struct de *de, void *data)
  7035. {
  7036. char href[PATH_MAX];
  7037. char href_encoded[PATH_MAX];
  7038. int truncated;
  7039. struct mg_connection *conn = (struct mg_connection *)data;
  7040. if (!de || !conn) {
  7041. return;
  7042. }
  7043. mg_snprintf(conn,
  7044. &truncated,
  7045. href,
  7046. sizeof(href),
  7047. "%s%s",
  7048. conn->request_info.local_uri,
  7049. de->file_name);
  7050. if (!truncated) {
  7051. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  7052. print_props(conn, href_encoded, &de->file);
  7053. }
  7054. }
  7055. static void
  7056. handle_propfind(struct mg_connection *conn,
  7057. const char *path,
  7058. struct file *filep)
  7059. {
  7060. const char *depth = mg_get_header(conn, "Depth");
  7061. char date[64];
  7062. time_t curtime = time(NULL);
  7063. gmt_time_string(date, sizeof(date), &curtime);
  7064. if (!conn || !path || !filep || !conn->ctx) {
  7065. return;
  7066. }
  7067. conn->must_close = 1;
  7068. conn->status_code = 207;
  7069. mg_printf(conn,
  7070. "HTTP/1.1 207 Multi-Status\r\n"
  7071. "Date: %s\r\n",
  7072. date);
  7073. send_static_cache_header(conn);
  7074. mg_printf(conn,
  7075. "Connection: %s\r\n"
  7076. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7077. suggest_connection_header(conn));
  7078. conn->num_bytes_sent +=
  7079. mg_printf(conn,
  7080. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7081. "<d:multistatus xmlns:d='DAV:'>\n");
  7082. /* Print properties for the requested resource itself */
  7083. print_props(conn, conn->request_info.local_uri, filep);
  7084. /* If it is a directory, print directory entries too if Depth is not 0 */
  7085. if (filep && filep->is_directory
  7086. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7087. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7088. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7089. }
  7090. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7091. }
  7092. #endif
  7093. void
  7094. mg_lock_connection(struct mg_connection *conn)
  7095. {
  7096. if (conn) {
  7097. (void)pthread_mutex_lock(&conn->mutex);
  7098. }
  7099. }
  7100. void
  7101. mg_unlock_connection(struct mg_connection *conn)
  7102. {
  7103. if (conn) {
  7104. (void)pthread_mutex_unlock(&conn->mutex);
  7105. }
  7106. }
  7107. void
  7108. mg_lock_context(struct mg_context *ctx)
  7109. {
  7110. if (ctx) {
  7111. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  7112. }
  7113. }
  7114. void
  7115. mg_unlock_context(struct mg_context *ctx)
  7116. {
  7117. if (ctx) {
  7118. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  7119. }
  7120. }
  7121. #if defined(USE_TIMERS)
  7122. #include "timer.inl"
  7123. #endif /* USE_TIMERS */
  7124. #ifdef USE_LUA
  7125. #include "mod_lua.inl"
  7126. #endif /* USE_LUA */
  7127. #ifdef USE_DUKTAPE
  7128. #include "mod_duktape.inl"
  7129. #endif /* USE_DUKTAPE */
  7130. #if defined(USE_WEBSOCKET)
  7131. /* START OF SHA-1 code
  7132. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  7133. #define SHA1HANDSOFF
  7134. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  7135. *
  7136. * #if defined(__sun)
  7137. * #include "solarisfixes.h"
  7138. * #endif
  7139. */
  7140. static int
  7141. is_big_endian(void)
  7142. {
  7143. static const int n = 1;
  7144. return ((char *)&n)[0] == 0;
  7145. }
  7146. union char64long16 {
  7147. unsigned char c[64];
  7148. uint32_t l[16];
  7149. };
  7150. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  7151. static uint32_t
  7152. blk0(union char64long16 *block, int i)
  7153. {
  7154. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  7155. if (!is_big_endian()) {
  7156. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00)
  7157. | (rol(block->l[i], 8) & 0x00FF00FF);
  7158. }
  7159. return block->l[i];
  7160. }
  7161. #define blk(i) \
  7162. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] \
  7163. ^ block->l[(i + 2) & 15] ^ block->l[i & 15], \
  7164. 1))
  7165. #define R0(v, w, x, y, z, i) \
  7166. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  7167. w = rol(w, 30);
  7168. #define R1(v, w, x, y, z, i) \
  7169. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  7170. w = rol(w, 30);
  7171. #define R2(v, w, x, y, z, i) \
  7172. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  7173. w = rol(w, 30);
  7174. #define R3(v, w, x, y, z, i) \
  7175. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  7176. w = rol(w, 30);
  7177. #define R4(v, w, x, y, z, i) \
  7178. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  7179. w = rol(w, 30);
  7180. typedef struct {
  7181. uint32_t state[5];
  7182. uint32_t count[2];
  7183. unsigned char buffer[64];
  7184. } SHA1_CTX;
  7185. static void
  7186. SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  7187. {
  7188. uint32_t a, b, c, d, e;
  7189. union char64long16 block[1];
  7190. memcpy(block, buffer, 64);
  7191. a = state[0];
  7192. b = state[1];
  7193. c = state[2];
  7194. d = state[3];
  7195. e = state[4];
  7196. R0(a, b, c, d, e, 0);
  7197. R0(e, a, b, c, d, 1);
  7198. R0(d, e, a, b, c, 2);
  7199. R0(c, d, e, a, b, 3);
  7200. R0(b, c, d, e, a, 4);
  7201. R0(a, b, c, d, e, 5);
  7202. R0(e, a, b, c, d, 6);
  7203. R0(d, e, a, b, c, 7);
  7204. R0(c, d, e, a, b, 8);
  7205. R0(b, c, d, e, a, 9);
  7206. R0(a, b, c, d, e, 10);
  7207. R0(e, a, b, c, d, 11);
  7208. R0(d, e, a, b, c, 12);
  7209. R0(c, d, e, a, b, 13);
  7210. R0(b, c, d, e, a, 14);
  7211. R0(a, b, c, d, e, 15);
  7212. R1(e, a, b, c, d, 16);
  7213. R1(d, e, a, b, c, 17);
  7214. R1(c, d, e, a, b, 18);
  7215. R1(b, c, d, e, a, 19);
  7216. R2(a, b, c, d, e, 20);
  7217. R2(e, a, b, c, d, 21);
  7218. R2(d, e, a, b, c, 22);
  7219. R2(c, d, e, a, b, 23);
  7220. R2(b, c, d, e, a, 24);
  7221. R2(a, b, c, d, e, 25);
  7222. R2(e, a, b, c, d, 26);
  7223. R2(d, e, a, b, c, 27);
  7224. R2(c, d, e, a, b, 28);
  7225. R2(b, c, d, e, a, 29);
  7226. R2(a, b, c, d, e, 30);
  7227. R2(e, a, b, c, d, 31);
  7228. R2(d, e, a, b, c, 32);
  7229. R2(c, d, e, a, b, 33);
  7230. R2(b, c, d, e, a, 34);
  7231. R2(a, b, c, d, e, 35);
  7232. R2(e, a, b, c, d, 36);
  7233. R2(d, e, a, b, c, 37);
  7234. R2(c, d, e, a, b, 38);
  7235. R2(b, c, d, e, a, 39);
  7236. R3(a, b, c, d, e, 40);
  7237. R3(e, a, b, c, d, 41);
  7238. R3(d, e, a, b, c, 42);
  7239. R3(c, d, e, a, b, 43);
  7240. R3(b, c, d, e, a, 44);
  7241. R3(a, b, c, d, e, 45);
  7242. R3(e, a, b, c, d, 46);
  7243. R3(d, e, a, b, c, 47);
  7244. R3(c, d, e, a, b, 48);
  7245. R3(b, c, d, e, a, 49);
  7246. R3(a, b, c, d, e, 50);
  7247. R3(e, a, b, c, d, 51);
  7248. R3(d, e, a, b, c, 52);
  7249. R3(c, d, e, a, b, 53);
  7250. R3(b, c, d, e, a, 54);
  7251. R3(a, b, c, d, e, 55);
  7252. R3(e, a, b, c, d, 56);
  7253. R3(d, e, a, b, c, 57);
  7254. R3(c, d, e, a, b, 58);
  7255. R3(b, c, d, e, a, 59);
  7256. R4(a, b, c, d, e, 60);
  7257. R4(e, a, b, c, d, 61);
  7258. R4(d, e, a, b, c, 62);
  7259. R4(c, d, e, a, b, 63);
  7260. R4(b, c, d, e, a, 64);
  7261. R4(a, b, c, d, e, 65);
  7262. R4(e, a, b, c, d, 66);
  7263. R4(d, e, a, b, c, 67);
  7264. R4(c, d, e, a, b, 68);
  7265. R4(b, c, d, e, a, 69);
  7266. R4(a, b, c, d, e, 70);
  7267. R4(e, a, b, c, d, 71);
  7268. R4(d, e, a, b, c, 72);
  7269. R4(c, d, e, a, b, 73);
  7270. R4(b, c, d, e, a, 74);
  7271. R4(a, b, c, d, e, 75);
  7272. R4(e, a, b, c, d, 76);
  7273. R4(d, e, a, b, c, 77);
  7274. R4(c, d, e, a, b, 78);
  7275. R4(b, c, d, e, a, 79);
  7276. state[0] += a;
  7277. state[1] += b;
  7278. state[2] += c;
  7279. state[3] += d;
  7280. state[4] += e;
  7281. a = b = c = d = e = 0;
  7282. memset(block, '\0', sizeof(block));
  7283. }
  7284. static void
  7285. SHA1Init(SHA1_CTX *context)
  7286. {
  7287. context->state[0] = 0x67452301;
  7288. context->state[1] = 0xEFCDAB89;
  7289. context->state[2] = 0x98BADCFE;
  7290. context->state[3] = 0x10325476;
  7291. context->state[4] = 0xC3D2E1F0;
  7292. context->count[0] = context->count[1] = 0;
  7293. }
  7294. static void
  7295. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  7296. {
  7297. uint32_t i, j;
  7298. j = context->count[0];
  7299. if ((context->count[0] += len << 3) < j) {
  7300. context->count[1]++;
  7301. }
  7302. context->count[1] += (len >> 29);
  7303. j = (j >> 3) & 63;
  7304. if ((j + len) > 63) {
  7305. memcpy(&context->buffer[j], data, (i = 64 - j));
  7306. SHA1Transform(context->state, context->buffer);
  7307. for (; i + 63 < len; i += 64) {
  7308. SHA1Transform(context->state, &data[i]);
  7309. }
  7310. j = 0;
  7311. } else
  7312. i = 0;
  7313. memcpy(&context->buffer[j], &data[i], len - i);
  7314. }
  7315. static void
  7316. SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  7317. {
  7318. unsigned i;
  7319. unsigned char finalcount[8], c;
  7320. for (i = 0; i < 8; i++) {
  7321. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  7322. >> ((3 - (i & 3)) * 8)) & 255);
  7323. }
  7324. c = 0200;
  7325. SHA1Update(context, &c, 1);
  7326. while ((context->count[0] & 504) != 448) {
  7327. c = 0000;
  7328. SHA1Update(context, &c, 1);
  7329. }
  7330. SHA1Update(context, finalcount, 8);
  7331. for (i = 0; i < 20; i++) {
  7332. digest[i] = (unsigned char)((context->state[i >> 2]
  7333. >> ((3 - (i & 3)) * 8)) & 255);
  7334. }
  7335. memset(context, '\0', sizeof(*context));
  7336. memset(&finalcount, '\0', sizeof(finalcount));
  7337. }
  7338. /* END OF SHA1 CODE */
  7339. static int
  7340. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  7341. {
  7342. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  7343. const char *protocol = NULL;
  7344. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  7345. SHA1_CTX sha_ctx;
  7346. int truncated;
  7347. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  7348. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  7349. if (truncated) {
  7350. conn->must_close = 1;
  7351. return 0;
  7352. }
  7353. SHA1Init(&sha_ctx);
  7354. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  7355. SHA1Final((unsigned char *)sha, &sha_ctx);
  7356. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  7357. mg_printf(conn,
  7358. "HTTP/1.1 101 Switching Protocols\r\n"
  7359. "Upgrade: websocket\r\n"
  7360. "Connection: Upgrade\r\n"
  7361. "Sec-WebSocket-Accept: %s\r\n",
  7362. b64_sha);
  7363. protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  7364. if (protocol) {
  7365. mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", protocol);
  7366. } else {
  7367. mg_printf(conn, "%s", "\r\n");
  7368. }
  7369. return 1;
  7370. }
  7371. static void
  7372. read_websocket(struct mg_connection *conn,
  7373. mg_websocket_data_handler ws_data_handler,
  7374. void *callback_data)
  7375. {
  7376. /* Pointer to the beginning of the portion of the incoming websocket
  7377. * message queue.
  7378. * The original websocket upgrade request is never removed, so the queue
  7379. * begins after it. */
  7380. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  7381. int n, error, exit_by_callback;
  7382. /* body_len is the length of the entire queue in bytes
  7383. * len is the length of the current message
  7384. * data_len is the length of the current message's data payload
  7385. * header_len is the length of the current message's header */
  7386. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  7387. /* "The masking key is a 32-bit value chosen at random by the client."
  7388. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  7389. */
  7390. unsigned char mask[4];
  7391. /* data points to the place where the message is stored when passed to the
  7392. * websocket_data callback. This is either mem on the stack, or a
  7393. * dynamically allocated buffer if it is too large. */
  7394. char mem[4096];
  7395. char *data = mem;
  7396. unsigned char mop; /* mask flag and opcode */
  7397. double timeout = -1.0;
  7398. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  7399. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  7400. }
  7401. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  7402. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7403. }
  7404. mg_set_thread_name("wsock");
  7405. /* Loop continuously, reading messages from the socket, invoking the
  7406. * callback, and waiting repeatedly until an error occurs. */
  7407. while (!conn->ctx->stop_flag) {
  7408. header_len = 0;
  7409. assert(conn->data_len >= conn->request_len);
  7410. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  7411. len = buf[1] & 127;
  7412. mask_len = buf[1] & 128 ? 4 : 0;
  7413. if (len < 126 && body_len >= mask_len) {
  7414. data_len = len;
  7415. header_len = 2 + mask_len;
  7416. } else if (len == 126 && body_len >= 4 + mask_len) {
  7417. header_len = 4 + mask_len;
  7418. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  7419. } else if (body_len >= 10 + mask_len) {
  7420. header_len = 10 + mask_len;
  7421. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  7422. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  7423. }
  7424. }
  7425. if (header_len > 0 && body_len >= header_len) {
  7426. /* Allocate space to hold websocket payload */
  7427. data = mem;
  7428. if (data_len > sizeof(mem)) {
  7429. data = (char *)mg_malloc(data_len);
  7430. if (data == NULL) {
  7431. /* Allocation failed, exit the loop and then close the
  7432. * connection */
  7433. mg_cry(conn, "websocket out of memory; closing connection");
  7434. break;
  7435. }
  7436. }
  7437. /* Copy the mask before we shift the queue and destroy it */
  7438. if (mask_len > 0) {
  7439. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  7440. } else {
  7441. memset(mask, 0, sizeof(mask));
  7442. }
  7443. /* Read frame payload from the first message in the queue into
  7444. * data and advance the queue by moving the memory in place. */
  7445. assert(body_len >= header_len);
  7446. if (data_len + header_len > body_len) {
  7447. mop = buf[0]; /* current mask and opcode */
  7448. /* Overflow case */
  7449. len = body_len - header_len;
  7450. memcpy(data, buf + header_len, len);
  7451. error = 0;
  7452. while (len < data_len) {
  7453. n = pull(
  7454. NULL, conn, data + len, (int)(data_len - len), timeout);
  7455. if (n <= 0) {
  7456. error = 1;
  7457. break;
  7458. }
  7459. len += (size_t)n;
  7460. }
  7461. if (error) {
  7462. mg_cry(conn, "Websocket pull failed; closing connection");
  7463. break;
  7464. }
  7465. conn->data_len = conn->request_len;
  7466. } else {
  7467. mop = buf[0]; /* current mask and opcode, overwritten by
  7468. * memmove() */
  7469. /* Length of the message being read at the front of the
  7470. * queue */
  7471. len = data_len + header_len;
  7472. /* Copy the data payload into the data pointer for the
  7473. * callback */
  7474. memcpy(data, buf + header_len, data_len);
  7475. /* Move the queue forward len bytes */
  7476. memmove(buf, buf + len, body_len - len);
  7477. /* Mark the queue as advanced */
  7478. conn->data_len -= (int)len;
  7479. }
  7480. /* Apply mask if necessary */
  7481. if (mask_len > 0) {
  7482. for (i = 0; i < data_len; ++i) {
  7483. data[i] ^= mask[i & 3];
  7484. }
  7485. }
  7486. /* Exit the loop if callback signals to exit (server side),
  7487. * or "connection close" opcode received (client side). */
  7488. exit_by_callback = 0;
  7489. if ((ws_data_handler != NULL)
  7490. && !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  7491. exit_by_callback = 1;
  7492. }
  7493. if (data != mem) {
  7494. mg_free(data);
  7495. }
  7496. if (exit_by_callback
  7497. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  7498. /* Opcode == 8, connection close */
  7499. break;
  7500. }
  7501. /* Not breaking the loop, process next websocket frame. */
  7502. } else {
  7503. /* Read from the socket into the next available location in the
  7504. * message queue. */
  7505. if ((n = pull(NULL,
  7506. conn,
  7507. conn->buf + conn->data_len,
  7508. conn->buf_size - conn->data_len,
  7509. timeout)) <= 0) {
  7510. /* Error, no bytes read */
  7511. break;
  7512. }
  7513. conn->data_len += n;
  7514. }
  7515. }
  7516. mg_set_thread_name("worker");
  7517. }
  7518. static int
  7519. mg_websocket_write_exec(struct mg_connection *conn,
  7520. int opcode,
  7521. const char *data,
  7522. size_t dataLen,
  7523. uint32_t masking_key)
  7524. {
  7525. unsigned char header[14];
  7526. size_t headerLen = 1;
  7527. int retval = -1;
  7528. header[0] = 0x80 + (opcode & 0xF);
  7529. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  7530. if (dataLen < 126) {
  7531. /* inline 7-bit length field */
  7532. header[1] = (unsigned char)dataLen;
  7533. headerLen = 2;
  7534. } else if (dataLen <= 0xFFFF) {
  7535. /* 16-bit length field */
  7536. header[1] = 126;
  7537. *(uint16_t *)(void *)(header + 2) = htons((uint16_t)dataLen);
  7538. headerLen = 4;
  7539. } else {
  7540. /* 64-bit length field */
  7541. header[1] = 127;
  7542. *(uint32_t *)(void *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  7543. *(uint32_t *)(void *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  7544. headerLen = 10;
  7545. }
  7546. if (masking_key) {
  7547. /* add mask */
  7548. header[1] |= 0x80;
  7549. *(uint32_t *)(void *)(header + headerLen) = masking_key;
  7550. headerLen += 4;
  7551. }
  7552. /* Note that POSIX/Winsock's send() is threadsafe
  7553. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  7554. * but mongoose's mg_printf/mg_write is not (because of the loop in
  7555. * push(), although that is only a problem if the packet is large or
  7556. * outgoing buffer is full). */
  7557. (void)mg_lock_connection(conn);
  7558. retval = mg_write(conn, header, headerLen);
  7559. if (dataLen > 0) {
  7560. retval = mg_write(conn, data, dataLen);
  7561. }
  7562. mg_unlock_connection(conn);
  7563. return retval;
  7564. }
  7565. int
  7566. mg_websocket_write(struct mg_connection *conn,
  7567. int opcode,
  7568. const char *data,
  7569. size_t dataLen)
  7570. {
  7571. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  7572. }
  7573. static void
  7574. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  7575. {
  7576. size_t i = 0;
  7577. i = 0;
  7578. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  7579. /* Convert in 32 bit words, if data is 4 byte aligned */
  7580. while (i < (in_len - 3)) {
  7581. *(uint32_t *)(void *)(out + i) =
  7582. *(uint32_t *)(void *)(in + i) ^ masking_key;
  7583. i += 4;
  7584. }
  7585. }
  7586. if (i != in_len) {
  7587. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  7588. while (i < in_len) {
  7589. *(uint8_t *)(void *)(out + i) =
  7590. *(uint8_t *)(void *)(in + i)
  7591. ^ *(((uint8_t *)&masking_key) + (i % 4));
  7592. i++;
  7593. }
  7594. }
  7595. }
  7596. int
  7597. mg_websocket_client_write(struct mg_connection *conn,
  7598. int opcode,
  7599. const char *data,
  7600. size_t dataLen)
  7601. {
  7602. int retval = -1;
  7603. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  7604. uint32_t masking_key = (uint32_t)get_random();
  7605. if (masked_data == NULL) {
  7606. /* Return -1 in an error case */
  7607. mg_cry(conn,
  7608. "Cannot allocate buffer for masked websocket response: "
  7609. "Out of memory");
  7610. return -1;
  7611. }
  7612. mask_data(data, dataLen, masking_key, masked_data);
  7613. retval = mg_websocket_write_exec(
  7614. conn, opcode, masked_data, dataLen, masking_key);
  7615. mg_free(masked_data);
  7616. return retval;
  7617. }
  7618. static void
  7619. handle_websocket_request(struct mg_connection *conn,
  7620. const char *path,
  7621. int is_callback_resource,
  7622. mg_websocket_connect_handler ws_connect_handler,
  7623. mg_websocket_ready_handler ws_ready_handler,
  7624. mg_websocket_data_handler ws_data_handler,
  7625. mg_websocket_close_handler ws_close_handler,
  7626. void *cbData)
  7627. {
  7628. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  7629. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  7630. int lua_websock = 0;
  7631. #if !defined(USE_LUA)
  7632. (void)path;
  7633. #endif
  7634. /* Step 1: Check websocket protocol version. */
  7635. /* Step 1.1: Check Sec-WebSocket-Key. */
  7636. if (!websock_key) {
  7637. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  7638. * requires a Sec-WebSocket-Key header.
  7639. */
  7640. /* It could be the hixie draft version
  7641. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  7642. */
  7643. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  7644. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  7645. char key3[8];
  7646. if ((key1 != NULL) && (key2 != NULL)) {
  7647. /* This version uses 8 byte body data in a GET request */
  7648. conn->content_len = 8;
  7649. if (8 == mg_read(conn, key3, 8)) {
  7650. /* This is the hixie version */
  7651. send_http_error(conn,
  7652. 426,
  7653. "%s",
  7654. "Protocol upgrade to RFC 6455 required");
  7655. return;
  7656. }
  7657. }
  7658. /* This is an unknown version */
  7659. send_http_error(conn, 400, "%s", "Malformed websocket request");
  7660. return;
  7661. }
  7662. /* Step 1.2: Check websocket protocol version. */
  7663. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  7664. if (version == NULL || strcmp(version, "13") != 0) {
  7665. /* Reject wrong versions */
  7666. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  7667. return;
  7668. }
  7669. /* Step 1.3: Could check for "Host", but we do not really nead this
  7670. * value for anything, so just ignore it. */
  7671. /* Step 2: If a callback is responsible, call it. */
  7672. if (is_callback_resource) {
  7673. if (ws_connect_handler != NULL
  7674. && ws_connect_handler(conn, cbData) != 0) {
  7675. /* C callback has returned non-zero, do not proceed with
  7676. * handshake.
  7677. */
  7678. /* Note that C callbacks are no longer called when Lua is
  7679. * responsible, so C can no longer filter callbacks for Lua. */
  7680. return;
  7681. }
  7682. }
  7683. #if defined(USE_LUA)
  7684. /* Step 3: No callback. Check if Lua is responsible. */
  7685. else {
  7686. /* Step 3.1: Check if Lua is responsible. */
  7687. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  7688. lua_websock =
  7689. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  7690. strlen(
  7691. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  7692. path);
  7693. }
  7694. if (lua_websock) {
  7695. /* Step 3.2: Lua is responsible: call it. */
  7696. conn->lua_websocket_state = lua_websocket_new(path, conn);
  7697. if (!conn->lua_websocket_state) {
  7698. /* Lua rejected the new client */
  7699. return;
  7700. }
  7701. }
  7702. }
  7703. #endif
  7704. /* Step 4: Check if there is a responsible websocket handler. */
  7705. if (!is_callback_resource && !lua_websock) {
  7706. /* There is no callback, an Lua is not responsible either. */
  7707. /* Reply with a 404 Not Found or with nothing at all?
  7708. * TODO (mid): check the websocket standards, how to reply to
  7709. * requests to invalid websocket addresses. */
  7710. send_http_error(conn, 404, "%s", "Not found");
  7711. return;
  7712. }
  7713. /* Step 5: The websocket connection has been accepted */
  7714. if (!send_websocket_handshake(conn, websock_key)) {
  7715. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  7716. return;
  7717. }
  7718. /* Step 6: Call the ready handler */
  7719. if (is_callback_resource) {
  7720. if (ws_ready_handler != NULL) {
  7721. ws_ready_handler(conn, cbData);
  7722. }
  7723. #if defined(USE_LUA)
  7724. } else if (lua_websock) {
  7725. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  7726. /* the ready handler returned false */
  7727. return;
  7728. }
  7729. #endif
  7730. }
  7731. /* Step 7: Enter the read loop */
  7732. if (is_callback_resource) {
  7733. read_websocket(conn, ws_data_handler, cbData);
  7734. #if defined(USE_LUA)
  7735. } else if (lua_websock) {
  7736. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  7737. #endif
  7738. }
  7739. /* Step 8: Call the close handler */
  7740. if (ws_close_handler) {
  7741. ws_close_handler(conn, cbData);
  7742. }
  7743. }
  7744. static int
  7745. is_websocket_protocol(const struct mg_connection *conn)
  7746. {
  7747. const char *upgrade, *connection;
  7748. /* A websocket protocoll has the following HTTP headers:
  7749. *
  7750. * Connection: Upgrade
  7751. * Upgrade: Websocket
  7752. */
  7753. upgrade = mg_get_header(conn, "Upgrade");
  7754. if (upgrade == NULL) {
  7755. return 0; /* fail early, don't waste time checking other header
  7756. * fields
  7757. */
  7758. }
  7759. if (!mg_strcasestr(upgrade, "websocket")) {
  7760. return 0;
  7761. }
  7762. connection = mg_get_header(conn, "Connection");
  7763. if (connection == NULL) {
  7764. return 0;
  7765. }
  7766. if (!mg_strcasestr(connection, "upgrade")) {
  7767. return 0;
  7768. }
  7769. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  7770. * "Sec-WebSocket-Version" are also required.
  7771. * Don't check them here, since even an unsupported websocket protocol
  7772. * request still IS a websocket request (in contrast to a standard HTTP
  7773. * request). It will fail later in handle_websocket_request.
  7774. */
  7775. return 1;
  7776. }
  7777. #endif /* !USE_WEBSOCKET */
  7778. static int
  7779. isbyte(int n)
  7780. {
  7781. return n >= 0 && n <= 255;
  7782. }
  7783. static int
  7784. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  7785. {
  7786. int n, a, b, c, d, slash = 32, len = 0;
  7787. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  7788. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  7789. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  7790. && slash < 33) {
  7791. len = n;
  7792. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  7793. | (uint32_t)d;
  7794. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  7795. }
  7796. return len;
  7797. }
  7798. static int
  7799. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  7800. {
  7801. int throttle = 0;
  7802. struct vec vec, val;
  7803. uint32_t net, mask;
  7804. char mult;
  7805. double v;
  7806. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  7807. mult = ',';
  7808. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0
  7809. || (lowercase(&mult) != 'k' && lowercase(&mult) != 'm'
  7810. && mult != ',')) {
  7811. continue;
  7812. }
  7813. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  7814. : 1;
  7815. if (vec.len == 1 && vec.ptr[0] == '*') {
  7816. throttle = (int)v;
  7817. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  7818. if ((remote_ip & mask) == net) {
  7819. throttle = (int)v;
  7820. }
  7821. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  7822. throttle = (int)v;
  7823. }
  7824. }
  7825. return throttle;
  7826. }
  7827. static uint32_t
  7828. get_remote_ip(const struct mg_connection *conn)
  7829. {
  7830. if (!conn) {
  7831. return 0;
  7832. }
  7833. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  7834. }
  7835. /* Experimental replacement for mg_upload. */
  7836. #include "handle_form.inl"
  7837. /* Replacement for mg_upload (Note: mg_upload is deprecated) */
  7838. struct mg_upload_user_data {
  7839. struct mg_connection *conn;
  7840. const char *destination_dir;
  7841. int num_uploaded_files;
  7842. };
  7843. /* Helper function for deprecated mg_upload. */
  7844. static int
  7845. mg_upload_field_found(const char *key,
  7846. const char *filename,
  7847. char *path,
  7848. size_t pathlen,
  7849. void *user_data)
  7850. {
  7851. int truncated = 0;
  7852. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7853. (void)key;
  7854. if (!filename) {
  7855. mg_cry(fud->conn, "%s: No filename set", __func__);
  7856. return FORM_FIELD_STORAGE_ABORT;
  7857. }
  7858. mg_snprintf(fud->conn,
  7859. &truncated,
  7860. path,
  7861. pathlen - 1,
  7862. "%s/%s",
  7863. fud->destination_dir,
  7864. filename);
  7865. if (!truncated) {
  7866. mg_cry(fud->conn, "%s: File path too long", __func__);
  7867. return FORM_FIELD_STORAGE_ABORT;
  7868. }
  7869. return FORM_FIELD_STORAGE_STORE;
  7870. }
  7871. /* Helper function for deprecated mg_upload. */
  7872. static int
  7873. mg_upload_field_get(const char *key,
  7874. const char *value,
  7875. size_t value_size,
  7876. void *user_data)
  7877. {
  7878. /* Function should never be called */
  7879. (void)key;
  7880. (void)value;
  7881. (void)value_size;
  7882. (void)user_data;
  7883. return 0;
  7884. }
  7885. /* Helper function for deprecated mg_upload. */
  7886. static int
  7887. mg_upload_field_stored(const char *path, size_t file_size, void *user_data)
  7888. {
  7889. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  7890. (void)file_size;
  7891. fud->num_uploaded_files++;
  7892. fud->conn->ctx->callbacks.upload(fud->conn, path);
  7893. return 0;
  7894. }
  7895. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  7896. int
  7897. mg_upload(struct mg_connection *conn, const char *destination_dir)
  7898. {
  7899. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  7900. struct mg_form_data_handler fdh = {mg_upload_field_found,
  7901. mg_upload_field_get,
  7902. mg_upload_field_stored,
  7903. 0};
  7904. int ret;
  7905. fdh.user_data = (void *)&fud;
  7906. ret = mg_handle_form_request(conn, &fdh);
  7907. if (ret < 0) {
  7908. mg_cry(conn, "%s: Error while parsing the request", __func__);
  7909. }
  7910. return fud.num_uploaded_files;
  7911. }
  7912. static int
  7913. get_first_ssl_listener_index(const struct mg_context *ctx)
  7914. {
  7915. unsigned int i;
  7916. int idx = -1;
  7917. if (ctx) {
  7918. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  7919. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  7920. }
  7921. }
  7922. return idx;
  7923. }
  7924. static void
  7925. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  7926. {
  7927. char host[1025];
  7928. const char *host_header;
  7929. size_t hostlen;
  7930. host_header = mg_get_header(conn, "Host");
  7931. hostlen = sizeof(host);
  7932. if (host_header != NULL) {
  7933. char *pos;
  7934. mg_strlcpy(host, host_header, hostlen);
  7935. host[hostlen - 1] = '\0';
  7936. pos = strchr(host, ':');
  7937. if (pos != NULL) {
  7938. *pos = '\0';
  7939. }
  7940. } else {
  7941. /* Cannot get host from the Host: header.
  7942. * Fallback to our IP address. */
  7943. if (conn) {
  7944. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  7945. }
  7946. }
  7947. /* Send host, port, uri and (if it exists) ?query_string */
  7948. if (conn) {
  7949. mg_printf(conn,
  7950. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  7951. host,
  7952. (int)ntohs(
  7953. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  7954. conn->request_info.local_uri,
  7955. (conn->request_info.query_string == NULL) ? "" : "?",
  7956. (conn->request_info.query_string == NULL)
  7957. ? ""
  7958. : conn->request_info.query_string);
  7959. }
  7960. }
  7961. static void
  7962. mg_set_handler_type(struct mg_context *ctx,
  7963. const char *uri,
  7964. int handler_type,
  7965. int is_delete_request,
  7966. mg_request_handler handler,
  7967. mg_websocket_connect_handler connect_handler,
  7968. mg_websocket_ready_handler ready_handler,
  7969. mg_websocket_data_handler data_handler,
  7970. mg_websocket_close_handler close_handler,
  7971. mg_authorization_handler auth_handler,
  7972. void *cbdata)
  7973. {
  7974. struct mg_handler_info *tmp_rh, **lastref;
  7975. size_t urilen = strlen(uri);
  7976. if (handler_type == WEBSOCKET_HANDLER) {
  7977. /* assert(handler == NULL); */
  7978. /* assert(is_delete_request || connect_handler!=NULL ||
  7979. * ready_handler!=NULL || data_handler!=NULL ||
  7980. * close_handler!=NULL);
  7981. */
  7982. /* assert(auth_handler == NULL); */
  7983. if (handler != NULL) {
  7984. return;
  7985. }
  7986. if (!is_delete_request && connect_handler == NULL
  7987. && ready_handler == NULL
  7988. && data_handler == NULL
  7989. && close_handler == NULL) {
  7990. return;
  7991. }
  7992. if (auth_handler != NULL) {
  7993. return;
  7994. }
  7995. } else if (handler_type == REQUEST_HANDLER) {
  7996. /* assert(connect_handler==NULL && ready_handler==NULL &&
  7997. * data_handler==NULL && close_handler==NULL); */
  7998. /* assert(is_delete_request || (handler!=NULL));
  7999. */
  8000. /* assert(auth_handler == NULL); */
  8001. if (connect_handler != NULL || ready_handler != NULL
  8002. || data_handler != NULL
  8003. || close_handler != NULL) {
  8004. return;
  8005. }
  8006. if (!is_delete_request && (handler == NULL)) {
  8007. return;
  8008. }
  8009. if (auth_handler != NULL) {
  8010. return;
  8011. }
  8012. } else { /* AUTH_HANDLER */
  8013. /* assert(handler == NULL); */
  8014. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8015. * data_handler==NULL && close_handler==NULL); */
  8016. /* assert(auth_handler != NULL); */
  8017. if (handler != NULL) {
  8018. return;
  8019. }
  8020. if (connect_handler != NULL || ready_handler != NULL
  8021. || data_handler != NULL
  8022. || close_handler != NULL) {
  8023. return;
  8024. }
  8025. if (!is_delete_request && (auth_handler == NULL)) {
  8026. return;
  8027. }
  8028. }
  8029. if (!ctx) {
  8030. return;
  8031. }
  8032. mg_lock_context(ctx);
  8033. /* first try to find an existing handler */
  8034. lastref = &(ctx->handlers);
  8035. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8036. if (tmp_rh->handler_type == handler_type) {
  8037. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8038. if (!is_delete_request) {
  8039. /* update existing handler */
  8040. if (handler_type == REQUEST_HANDLER) {
  8041. tmp_rh->handler = handler;
  8042. } else if (handler_type == WEBSOCKET_HANDLER) {
  8043. tmp_rh->connect_handler = connect_handler;
  8044. tmp_rh->ready_handler = ready_handler;
  8045. tmp_rh->data_handler = data_handler;
  8046. tmp_rh->close_handler = close_handler;
  8047. } else { /* AUTH_HANDLER */
  8048. tmp_rh->auth_handler = auth_handler;
  8049. }
  8050. tmp_rh->cbdata = cbdata;
  8051. } else {
  8052. /* remove existing handler */
  8053. *lastref = tmp_rh->next;
  8054. mg_free(tmp_rh->uri);
  8055. mg_free(tmp_rh);
  8056. }
  8057. mg_unlock_context(ctx);
  8058. return;
  8059. }
  8060. }
  8061. lastref = &(tmp_rh->next);
  8062. }
  8063. if (is_delete_request) {
  8064. /* no handler to set, this was a remove request to a non-existing
  8065. * handler */
  8066. mg_unlock_context(ctx);
  8067. return;
  8068. }
  8069. tmp_rh =
  8070. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8071. if (tmp_rh == NULL) {
  8072. mg_unlock_context(ctx);
  8073. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8074. return;
  8075. }
  8076. tmp_rh->uri = mg_strdup(uri);
  8077. if (!tmp_rh->uri) {
  8078. mg_unlock_context(ctx);
  8079. mg_free(tmp_rh);
  8080. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8081. return;
  8082. }
  8083. tmp_rh->uri_len = urilen;
  8084. if (handler_type == REQUEST_HANDLER) {
  8085. tmp_rh->handler = handler;
  8086. } else if (handler_type == WEBSOCKET_HANDLER) {
  8087. tmp_rh->connect_handler = connect_handler;
  8088. tmp_rh->ready_handler = ready_handler;
  8089. tmp_rh->data_handler = data_handler;
  8090. tmp_rh->close_handler = close_handler;
  8091. } else { /* AUTH_HANDLER */
  8092. tmp_rh->auth_handler = auth_handler;
  8093. }
  8094. tmp_rh->cbdata = cbdata;
  8095. tmp_rh->handler_type = handler_type;
  8096. tmp_rh->next = NULL;
  8097. *lastref = tmp_rh;
  8098. mg_unlock_context(ctx);
  8099. }
  8100. void
  8101. mg_set_request_handler(struct mg_context *ctx,
  8102. const char *uri,
  8103. mg_request_handler handler,
  8104. void *cbdata)
  8105. {
  8106. mg_set_handler_type(ctx,
  8107. uri,
  8108. REQUEST_HANDLER,
  8109. handler == NULL,
  8110. handler,
  8111. NULL,
  8112. NULL,
  8113. NULL,
  8114. NULL,
  8115. NULL,
  8116. cbdata);
  8117. }
  8118. void
  8119. mg_set_websocket_handler(struct mg_context *ctx,
  8120. const char *uri,
  8121. mg_websocket_connect_handler connect_handler,
  8122. mg_websocket_ready_handler ready_handler,
  8123. mg_websocket_data_handler data_handler,
  8124. mg_websocket_close_handler close_handler,
  8125. void *cbdata)
  8126. {
  8127. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8128. && (data_handler == NULL)
  8129. && (close_handler == NULL);
  8130. mg_set_handler_type(ctx,
  8131. uri,
  8132. WEBSOCKET_HANDLER,
  8133. is_delete_request,
  8134. NULL,
  8135. connect_handler,
  8136. ready_handler,
  8137. data_handler,
  8138. close_handler,
  8139. NULL,
  8140. cbdata);
  8141. }
  8142. void
  8143. mg_set_auth_handler(struct mg_context *ctx,
  8144. const char *uri,
  8145. mg_request_handler handler,
  8146. void *cbdata)
  8147. {
  8148. mg_set_handler_type(ctx,
  8149. uri,
  8150. AUTH_HANDLER,
  8151. handler == NULL,
  8152. NULL,
  8153. NULL,
  8154. NULL,
  8155. NULL,
  8156. NULL,
  8157. handler,
  8158. cbdata);
  8159. }
  8160. static int
  8161. get_request_handler(struct mg_connection *conn,
  8162. int handler_type,
  8163. mg_request_handler *handler,
  8164. mg_websocket_connect_handler *connect_handler,
  8165. mg_websocket_ready_handler *ready_handler,
  8166. mg_websocket_data_handler *data_handler,
  8167. mg_websocket_close_handler *close_handler,
  8168. mg_authorization_handler *auth_handler,
  8169. void **cbdata)
  8170. {
  8171. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8172. if (request_info) {
  8173. const char *uri = request_info->local_uri;
  8174. size_t urilen = strlen(uri);
  8175. struct mg_handler_info *tmp_rh;
  8176. if (!conn || !conn->ctx) {
  8177. return 0;
  8178. }
  8179. mg_lock_context(conn->ctx);
  8180. /* first try for an exact match */
  8181. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8182. tmp_rh = tmp_rh->next) {
  8183. if (tmp_rh->handler_type == handler_type) {
  8184. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8185. if (handler_type == WEBSOCKET_HANDLER) {
  8186. *connect_handler = tmp_rh->connect_handler;
  8187. *ready_handler = tmp_rh->ready_handler;
  8188. *data_handler = tmp_rh->data_handler;
  8189. *close_handler = tmp_rh->close_handler;
  8190. } else if (handler_type == REQUEST_HANDLER) {
  8191. *handler = tmp_rh->handler;
  8192. } else { /* AUTH_HANDLER */
  8193. *auth_handler = tmp_rh->auth_handler;
  8194. }
  8195. *cbdata = tmp_rh->cbdata;
  8196. mg_unlock_context(conn->ctx);
  8197. return 1;
  8198. }
  8199. }
  8200. }
  8201. /* next try for a partial match, we will accept uri/something */
  8202. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8203. tmp_rh = tmp_rh->next) {
  8204. if (tmp_rh->handler_type == handler_type) {
  8205. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8206. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8207. if (handler_type == WEBSOCKET_HANDLER) {
  8208. *connect_handler = tmp_rh->connect_handler;
  8209. *ready_handler = tmp_rh->ready_handler;
  8210. *data_handler = tmp_rh->data_handler;
  8211. *close_handler = tmp_rh->close_handler;
  8212. } else if (handler_type == REQUEST_HANDLER) {
  8213. *handler = tmp_rh->handler;
  8214. } else { /* AUTH_HANDLER */
  8215. *auth_handler = tmp_rh->auth_handler;
  8216. }
  8217. *cbdata = tmp_rh->cbdata;
  8218. mg_unlock_context(conn->ctx);
  8219. return 1;
  8220. }
  8221. }
  8222. }
  8223. /* finally try for pattern match */
  8224. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8225. tmp_rh = tmp_rh->next) {
  8226. if (tmp_rh->handler_type == handler_type) {
  8227. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  8228. if (handler_type == WEBSOCKET_HANDLER) {
  8229. *connect_handler = tmp_rh->connect_handler;
  8230. *ready_handler = tmp_rh->ready_handler;
  8231. *data_handler = tmp_rh->data_handler;
  8232. *close_handler = tmp_rh->close_handler;
  8233. } else if (handler_type == REQUEST_HANDLER) {
  8234. *handler = tmp_rh->handler;
  8235. } else { /* AUTH_HANDLER */
  8236. *auth_handler = tmp_rh->auth_handler;
  8237. }
  8238. *cbdata = tmp_rh->cbdata;
  8239. mg_unlock_context(conn->ctx);
  8240. return 1;
  8241. }
  8242. }
  8243. }
  8244. mg_unlock_context(conn->ctx);
  8245. }
  8246. return 0; /* none found */
  8247. }
  8248. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  8249. static int
  8250. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  8251. void *cbdata)
  8252. {
  8253. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8254. if (pcallbacks->websocket_connect) {
  8255. return pcallbacks->websocket_connect(conn);
  8256. }
  8257. /* No handler set - assume "OK" */
  8258. return 0;
  8259. }
  8260. static void
  8261. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  8262. {
  8263. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8264. if (pcallbacks->websocket_ready) {
  8265. pcallbacks->websocket_ready(conn);
  8266. }
  8267. }
  8268. static int
  8269. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  8270. int bits,
  8271. char *data,
  8272. size_t len,
  8273. void *cbdata)
  8274. {
  8275. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  8276. if (pcallbacks->websocket_data) {
  8277. return pcallbacks->websocket_data(conn, bits, data, len);
  8278. }
  8279. /* No handler set - assume "OK" */
  8280. return 1;
  8281. }
  8282. #endif
  8283. /* This is the heart of the Civetweb's logic.
  8284. * This function is called when the request is read, parsed and validated,
  8285. * and Civetweb must decide what action to take: serve a file, or
  8286. * a directory, or call embedded function, etcetera. */
  8287. static void
  8288. handle_request(struct mg_connection *conn)
  8289. {
  8290. if (conn) {
  8291. struct mg_request_info *ri = &conn->request_info;
  8292. char path[PATH_MAX];
  8293. int uri_len, ssl_index;
  8294. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  8295. is_put_or_delete_request = 0, is_callback_resource = 0;
  8296. int i;
  8297. struct file file = STRUCT_FILE_INITIALIZER;
  8298. mg_request_handler callback_handler = NULL;
  8299. mg_websocket_connect_handler ws_connect_handler = NULL;
  8300. mg_websocket_ready_handler ws_ready_handler = NULL;
  8301. mg_websocket_data_handler ws_data_handler = NULL;
  8302. mg_websocket_close_handler ws_close_handler = NULL;
  8303. void *callback_data = NULL;
  8304. mg_authorization_handler auth_handler = NULL;
  8305. void *auth_callback_data = NULL;
  8306. #if !defined(NO_FILES)
  8307. time_t curtime = time(NULL);
  8308. char date[64];
  8309. #endif
  8310. path[0] = 0;
  8311. if (!ri) {
  8312. return;
  8313. }
  8314. /* 1. get the request url */
  8315. /* 1.1. split into url and query string */
  8316. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  8317. != NULL) {
  8318. *((char *)conn->request_info.query_string++) = '\0';
  8319. }
  8320. uri_len = (int)strlen(ri->local_uri);
  8321. /* 1.2. decode url (if config says so) */
  8322. if (should_decode_url(conn)) {
  8323. mg_url_decode(
  8324. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  8325. }
  8326. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is
  8327. * not
  8328. * possible */
  8329. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  8330. /* step 1. completed, the url is known now */
  8331. DEBUG_TRACE("URL: %s", ri->local_uri);
  8332. /* 2. do a https redirect, if required */
  8333. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  8334. ssl_index = get_first_ssl_listener_index(conn->ctx);
  8335. if (ssl_index >= 0) {
  8336. redirect_to_https_port(conn, ssl_index);
  8337. } else {
  8338. /* A http to https forward port has been specified,
  8339. * but no https port to forward to. */
  8340. send_http_error(conn,
  8341. 503,
  8342. "%s",
  8343. "Error: SSL forward not configured properly");
  8344. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  8345. }
  8346. return;
  8347. }
  8348. /* 3. if this ip has limited speed, set it for this connection */
  8349. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  8350. get_remote_ip(conn),
  8351. ri->local_uri);
  8352. /* 4. call a "handle everything" callback, if registered */
  8353. if (conn->ctx->callbacks.begin_request != NULL) {
  8354. /* Note that since V1.7 the "begin_request" function is called
  8355. * before an authorization check. If an authorization check is
  8356. * required, use a request_handler instead. */
  8357. i = conn->ctx->callbacks.begin_request(conn);
  8358. if (i > 0) {
  8359. /* callback already processed the request. Store the
  8360. return value as a status code for the access log. */
  8361. conn->status_code = i;
  8362. return;
  8363. } else if (i == 0) {
  8364. /* civetweb should process the request */
  8365. } else {
  8366. /* unspecified - may change with the next version */
  8367. return;
  8368. }
  8369. }
  8370. /* request not yet handled by a handler or redirect, so the request
  8371. * is processed here */
  8372. /* 5. interpret the url to find out how the request must be handled
  8373. */
  8374. /* 5.1. first test, if the request targets the regular http(s)://
  8375. * protocol namespace or the websocket ws(s):// protocol namespace.
  8376. */
  8377. is_websocket_request = is_websocket_protocol(conn);
  8378. /* 5.2. check if the request will be handled by a callback */
  8379. if (get_request_handler(conn,
  8380. is_websocket_request ? WEBSOCKET_HANDLER
  8381. : REQUEST_HANDLER,
  8382. &callback_handler,
  8383. &ws_connect_handler,
  8384. &ws_ready_handler,
  8385. &ws_data_handler,
  8386. &ws_close_handler,
  8387. NULL,
  8388. &callback_data)) {
  8389. /* 5.2.1. A callback will handle this request. All requests
  8390. * handled
  8391. * by a callback have to be considered as requests to a script
  8392. * resource. */
  8393. is_callback_resource = 1;
  8394. is_script_resource = 1;
  8395. is_put_or_delete_request = is_put_or_delete_method(conn);
  8396. } else {
  8397. no_callback_resource:
  8398. /* 5.2.2. No callback is responsible for this request. The URI
  8399. * addresses a file based resource (static content or Lua/cgi
  8400. * scripts in the file system). */
  8401. is_callback_resource = 0;
  8402. interpret_uri(conn,
  8403. path,
  8404. sizeof(path),
  8405. &file,
  8406. &is_found,
  8407. &is_script_resource,
  8408. &is_websocket_request,
  8409. &is_put_or_delete_request);
  8410. }
  8411. /* 6. authorization check */
  8412. /* 6.1. a custom authorization handler is installed */
  8413. if (get_request_handler(conn,
  8414. AUTH_HANDLER,
  8415. NULL,
  8416. NULL,
  8417. NULL,
  8418. NULL,
  8419. NULL,
  8420. &auth_handler,
  8421. &auth_callback_data)) {
  8422. if (!auth_handler(conn, auth_callback_data)) {
  8423. return;
  8424. }
  8425. } else if (is_put_or_delete_request && !is_script_resource
  8426. && !is_callback_resource) {
  8427. /* 6.2. this request is a PUT/DELETE to a real file */
  8428. /* 6.2.1. thus, the server must have real files */
  8429. #if defined(NO_FILES)
  8430. if (1) {
  8431. #else
  8432. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8433. #endif
  8434. /* This server does not have any real files, thus the
  8435. * PUT/DELETE methods are not valid. */
  8436. send_http_error(conn,
  8437. 405,
  8438. "%s method not allowed",
  8439. conn->request_info.request_method);
  8440. return;
  8441. }
  8442. #if !defined(NO_FILES)
  8443. /* 6.2.2. Check if put authorization for static files is available.
  8444. */
  8445. if (!is_authorized_for_put(conn)) {
  8446. send_authorization_request(conn);
  8447. return;
  8448. }
  8449. #endif
  8450. } else {
  8451. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  8452. * or it is a PUT or DELETE request to a resource that does not
  8453. * correspond to a file. Check authorization. */
  8454. if (!check_authorization(conn, path)) {
  8455. send_authorization_request(conn);
  8456. return;
  8457. }
  8458. }
  8459. /* request is authorized or does not need authorization */
  8460. /* 7. check if there are request handlers for this uri */
  8461. if (is_callback_resource) {
  8462. if (!is_websocket_request) {
  8463. i = callback_handler(conn, callback_data);
  8464. if (i > 0) {
  8465. /* Do nothing, callback has served the request. Store
  8466. * the
  8467. * return value as status code for the log and discard
  8468. * all
  8469. * data from the client not used by the callback. */
  8470. conn->status_code = i;
  8471. discard_unread_request_data(conn);
  8472. } else {
  8473. /* TODO (high): what if the handler did NOT handle the
  8474. * request */
  8475. /* The last version did handle this as a file request,
  8476. * but
  8477. * since a file request is not always a script resource,
  8478. * the authorization check might be different */
  8479. interpret_uri(conn,
  8480. path,
  8481. sizeof(path),
  8482. &file,
  8483. &is_found,
  8484. &is_script_resource,
  8485. &is_websocket_request,
  8486. &is_put_or_delete_request);
  8487. callback_handler = NULL;
  8488. /* TODO (very low): goto is deprecated but for the
  8489. * moment,
  8490. * a goto is simpler than some curious loop. */
  8491. /* The situation "callback does not handle the request"
  8492. * needs to be reconsidered anyway. */
  8493. goto no_callback_resource;
  8494. }
  8495. } else {
  8496. #if defined(USE_WEBSOCKET)
  8497. handle_websocket_request(conn,
  8498. path,
  8499. is_callback_resource,
  8500. ws_connect_handler,
  8501. ws_ready_handler,
  8502. ws_data_handler,
  8503. ws_close_handler,
  8504. callback_data);
  8505. #endif
  8506. }
  8507. return;
  8508. }
  8509. /* 8. handle websocket requests */
  8510. #if defined(USE_WEBSOCKET)
  8511. if (is_websocket_request) {
  8512. if (is_script_resource) {
  8513. /* Websocket Lua script */
  8514. handle_websocket_request(conn,
  8515. path,
  8516. 0 /* Lua Script */,
  8517. NULL,
  8518. NULL,
  8519. NULL,
  8520. NULL,
  8521. &conn->ctx->callbacks);
  8522. } else {
  8523. #if defined(MG_LEGACY_INTERFACE)
  8524. handle_websocket_request(
  8525. conn,
  8526. path,
  8527. !is_script_resource /* could be deprecated global callback */,
  8528. deprecated_websocket_connect_wrapper,
  8529. deprecated_websocket_ready_wrapper,
  8530. deprecated_websocket_data_wrapper,
  8531. NULL,
  8532. &conn->ctx->callbacks);
  8533. #else
  8534. send_http_error(conn, 404, "%s", "Not found");
  8535. #endif
  8536. }
  8537. return;
  8538. } else
  8539. #endif
  8540. #if defined(NO_FILES)
  8541. /* 9a. In case the server uses only callbacks, this uri is
  8542. * unknown.
  8543. * Then, all request handling ends here. */
  8544. send_http_error(conn, 404, "%s", "Not Found");
  8545. #else
  8546. /* 9b. This request is either for a static file or resource handled
  8547. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  8548. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  8549. send_http_error(conn, 404, "%s", "Not Found");
  8550. return;
  8551. }
  8552. /* 10. File is handled by a script. */
  8553. if (is_script_resource) {
  8554. handle_file_based_request(conn, path, &file);
  8555. return;
  8556. }
  8557. /* 11. Handle put/delete/mkcol requests */
  8558. if (is_put_or_delete_request) {
  8559. /* 11.1. PUT method */
  8560. if (!strcmp(ri->request_method, "PUT")) {
  8561. put_file(conn, path);
  8562. return;
  8563. }
  8564. /* 11.2. DELETE method */
  8565. if (!strcmp(ri->request_method, "DELETE")) {
  8566. delete_file(conn, path);
  8567. return;
  8568. }
  8569. /* 11.3. MKCOL method */
  8570. if (!strcmp(ri->request_method, "MKCOL")) {
  8571. mkcol(conn, path);
  8572. return;
  8573. }
  8574. /* 11.4. PATCH method
  8575. * This method is not supported for static resources,
  8576. * only for scripts (Lua, CGI) and callbacks. */
  8577. send_http_error(conn,
  8578. 405,
  8579. "%s method not allowed",
  8580. conn->request_info.request_method);
  8581. return;
  8582. }
  8583. /* 11. File does not exist, or it was configured that it should be
  8584. * hidden */
  8585. if (!is_found || (must_hide_file(conn, path))) {
  8586. send_http_error(conn, 404, "%s", "Not found");
  8587. return;
  8588. }
  8589. /* 12. Directory uris should end with a slash */
  8590. if (file.is_directory && ri->local_uri[uri_len - 1] != '/') {
  8591. gmt_time_string(date, sizeof(date), &curtime);
  8592. mg_printf(conn,
  8593. "HTTP/1.1 301 Moved Permanently\r\n"
  8594. "Location: %s/\r\n"
  8595. "Date: %s\r\n"
  8596. /* "Cache-Control: private\r\n" (= default) */
  8597. "Content-Length: 0\r\n"
  8598. "Connection: %s\r\n\r\n",
  8599. ri->request_uri,
  8600. date,
  8601. suggest_connection_header(conn));
  8602. return;
  8603. }
  8604. /* 13. Handle other methods than GET/HEAD */
  8605. /* 13.1. Handle PROPFIND */
  8606. if (!strcmp(ri->request_method, "PROPFIND")) {
  8607. handle_propfind(conn, path, &file);
  8608. return;
  8609. }
  8610. /* 13.2. Handle OPTIONS for files */
  8611. if (!strcmp(ri->request_method, "OPTIONS")) {
  8612. /* This standard handler is only used for real files.
  8613. * Scripts should support the OPTIONS method themselves, to allow a
  8614. * maximum flexibility.
  8615. * Lua and CGI scripts may fully support CORS this way (including
  8616. * preflights). */
  8617. send_options(conn);
  8618. return;
  8619. }
  8620. /* 13.3. everything but GET and HEAD (e.g. POST) */
  8621. if (0 != strcmp(ri->request_method, "GET")
  8622. && 0 != strcmp(ri->request_method, "HEAD")) {
  8623. send_http_error(conn,
  8624. 405,
  8625. "%s method not allowed",
  8626. conn->request_info.request_method);
  8627. return;
  8628. }
  8629. /* 14. directories */
  8630. if (file.is_directory) {
  8631. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  8632. /* 14.1. use a substitute file */
  8633. /* TODO (high): substitute index may be a script resource.
  8634. * define what should be possible in this case. */
  8635. } else {
  8636. /* 14.2. no substitute file */
  8637. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  8638. "yes")) {
  8639. handle_directory_request(conn, path);
  8640. } else {
  8641. send_http_error(conn,
  8642. 403,
  8643. "%s",
  8644. "Error: Directory listing denied");
  8645. }
  8646. return;
  8647. }
  8648. }
  8649. handle_file_based_request(conn, path, &file);
  8650. #endif /* !defined(NO_FILES) */
  8651. #if 0
  8652. /* Perform redirect and auth checks before calling begin_request()
  8653. * handler.
  8654. * Otherwise, begin_request() would need to perform auth checks and
  8655. * redirects. */
  8656. #endif
  8657. }
  8658. return;
  8659. }
  8660. static void
  8661. handle_file_based_request(struct mg_connection *conn,
  8662. const char *path,
  8663. struct file *file)
  8664. {
  8665. if (!conn || !conn->ctx) {
  8666. return;
  8667. }
  8668. if (0) {
  8669. #ifdef USE_LUA
  8670. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  8671. strlen(
  8672. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  8673. path) > 0) {
  8674. /* Lua server page: an SSI like page containing mostly plain html
  8675. * code
  8676. * plus some tags with server generated contents. */
  8677. handle_lsp_request(conn, path, file, NULL);
  8678. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  8679. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  8680. path) > 0) {
  8681. /* Lua in-server module script: a CGI like script used to generate
  8682. * the
  8683. * entire reply. */
  8684. mg_exec_lua_script(conn, path, NULL);
  8685. #endif
  8686. #if defined(USE_DUKTAPE)
  8687. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  8688. strlen(
  8689. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  8690. path) > 0) {
  8691. /* Call duktape to generate the page */
  8692. mg_exec_duktape_script(conn, path);
  8693. #endif
  8694. #if !defined(NO_CGI)
  8695. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  8696. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  8697. path) > 0) {
  8698. /* CGI scripts may support all HTTP methods */
  8699. handle_cgi_request(conn, path);
  8700. #endif /* !NO_CGI */
  8701. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  8702. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  8703. path) > 0) {
  8704. handle_ssi_file_request(conn, path, file);
  8705. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  8706. /* Send 304 "Not Modified" - this must not send any body data */
  8707. send_http_error(conn, 304, "%s", "");
  8708. } else {
  8709. handle_static_file_request(conn, path, file, NULL);
  8710. }
  8711. }
  8712. static void
  8713. close_all_listening_sockets(struct mg_context *ctx)
  8714. {
  8715. unsigned int i;
  8716. if (!ctx) {
  8717. return;
  8718. }
  8719. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8720. closesocket(ctx->listening_sockets[i].sock);
  8721. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  8722. }
  8723. mg_free(ctx->listening_sockets);
  8724. ctx->listening_sockets = NULL;
  8725. mg_free(ctx->listening_ports);
  8726. ctx->listening_ports = NULL;
  8727. }
  8728. /* Valid listening port specification is: [ip_address:]port[s]
  8729. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  8730. * Examples for IPv6: [::]:80, [::1]:80,
  8731. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  8732. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  8733. static int
  8734. parse_port_string(const struct vec *vec, struct socket *so)
  8735. {
  8736. unsigned int a, b, c, d, port;
  8737. int ch, len;
  8738. #if defined(USE_IPV6)
  8739. char buf[100] = {0};
  8740. #endif
  8741. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  8742. * Also, all-zeroes in the socket address means binding to all addresses
  8743. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  8744. memset(so, 0, sizeof(*so));
  8745. so->lsa.sin.sin_family = AF_INET;
  8746. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  8747. == 5) {
  8748. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  8749. so->lsa.sin.sin_addr.s_addr =
  8750. htonl((a << 24) | (b << 16) | (c << 8) | d);
  8751. so->lsa.sin.sin_port = htons((uint16_t)port);
  8752. #if defined(USE_IPV6)
  8753. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  8754. && mg_inet_pton(
  8755. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  8756. /* IPv6 address, examples: see above */
  8757. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  8758. */
  8759. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  8760. #endif
  8761. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  8762. /* If only port is specified, bind to IPv4, INADDR_ANY */
  8763. so->lsa.sin.sin_port = htons((uint16_t)port);
  8764. } else {
  8765. /* Parsing failure. Make port invalid. */
  8766. port = 0;
  8767. len = 0;
  8768. }
  8769. /* sscanf and the option splitting code ensure the following condition
  8770. */
  8771. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  8772. return 0;
  8773. }
  8774. ch = vec->ptr[len]; /* Next character after the port number */
  8775. so->is_ssl = (ch == 's');
  8776. so->ssl_redir = (ch == 'r');
  8777. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  8778. return is_valid_port(port)
  8779. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  8780. }
  8781. static int
  8782. set_ports_option(struct mg_context *ctx)
  8783. {
  8784. const char *list;
  8785. int on = 1;
  8786. #if defined(USE_IPV6)
  8787. int off = 0;
  8788. #endif
  8789. struct vec vec;
  8790. struct socket so, *ptr;
  8791. in_port_t *portPtr;
  8792. union usa usa;
  8793. socklen_t len;
  8794. int portsTotal = 0;
  8795. int portsOk = 0;
  8796. if (!ctx) {
  8797. return 0;
  8798. }
  8799. memset(&so, 0, sizeof(so));
  8800. memset(&usa, 0, sizeof(usa));
  8801. len = sizeof(usa);
  8802. list = ctx->config[LISTENING_PORTS];
  8803. while ((list = next_option(list, &vec, NULL)) != NULL) {
  8804. portsTotal++;
  8805. if (!parse_port_string(&vec, &so)) {
  8806. mg_cry(fc(ctx),
  8807. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  8808. (int)vec.len,
  8809. vec.ptr,
  8810. portsTotal,
  8811. "[IP_ADDRESS:]PORT[s|r]");
  8812. continue;
  8813. }
  8814. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  8815. mg_cry(fc(ctx),
  8816. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  8817. "option set?",
  8818. portsTotal);
  8819. continue;
  8820. }
  8821. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  8822. == INVALID_SOCKET) {
  8823. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  8824. continue;
  8825. }
  8826. #ifdef _WIN32
  8827. /* Windows SO_REUSEADDR lets many procs binds to a
  8828. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  8829. * if someone already has the socket -- DTL */
  8830. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  8831. * Windows might need a few seconds before
  8832. * the same port can be used again in the
  8833. * same process, so a short Sleep may be
  8834. * required between mg_stop and mg_start.
  8835. */
  8836. if (setsockopt(so.sock,
  8837. SOL_SOCKET,
  8838. SO_EXCLUSIVEADDRUSE,
  8839. (SOCK_OPT_TYPE)&on,
  8840. sizeof(on)) != 0) {
  8841. mg_cry(fc(ctx),
  8842. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  8843. portsTotal);
  8844. }
  8845. #else
  8846. if (setsockopt(so.sock,
  8847. SOL_SOCKET,
  8848. SO_REUSEADDR,
  8849. (SOCK_OPT_TYPE)&on,
  8850. sizeof(on)) != 0) {
  8851. mg_cry(fc(ctx),
  8852. "cannot set socket option SO_REUSEADDR (entry %i)",
  8853. portsTotal);
  8854. }
  8855. #endif
  8856. #if defined(USE_IPV6)
  8857. if (so.lsa.sa.sa_family == AF_INET6
  8858. && setsockopt(so.sock,
  8859. IPPROTO_IPV6,
  8860. IPV6_V6ONLY,
  8861. (void *)&off,
  8862. sizeof(off)) != 0) {
  8863. mg_cry(fc(ctx),
  8864. "cannot set socket option IPV6_V6ONLY (entry %i)",
  8865. portsTotal);
  8866. }
  8867. #endif
  8868. if (so.lsa.sa.sa_family == AF_INET) {
  8869. len = sizeof(so.lsa.sin);
  8870. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8871. mg_cry(fc(ctx),
  8872. "cannot bind to %.*s: %d (%s)",
  8873. (int)vec.len,
  8874. vec.ptr,
  8875. (int)ERRNO,
  8876. strerror(errno));
  8877. closesocket(so.sock);
  8878. so.sock = INVALID_SOCKET;
  8879. continue;
  8880. }
  8881. }
  8882. #if defined(USE_IPV6)
  8883. else if (so.lsa.sa.sa_family == AF_INET6) {
  8884. len = sizeof(so.lsa.sin6);
  8885. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  8886. mg_cry(fc(ctx),
  8887. "cannot bind to IPv6 %.*s: %d (%s)",
  8888. (int)vec.len,
  8889. vec.ptr,
  8890. (int)ERRNO,
  8891. strerror(errno));
  8892. closesocket(so.sock);
  8893. so.sock = INVALID_SOCKET;
  8894. continue;
  8895. }
  8896. }
  8897. #endif
  8898. else {
  8899. mg_cry(fc(ctx),
  8900. "cannot bind: address family not supported (entry %i)",
  8901. portsTotal);
  8902. continue;
  8903. }
  8904. if (listen(so.sock, SOMAXCONN) != 0) {
  8905. mg_cry(fc(ctx),
  8906. "cannot listen to %.*s: %d (%s)",
  8907. (int)vec.len,
  8908. vec.ptr,
  8909. (int)ERRNO,
  8910. strerror(errno));
  8911. closesocket(so.sock);
  8912. so.sock = INVALID_SOCKET;
  8913. continue;
  8914. }
  8915. if (getsockname(so.sock, &(usa.sa), &len) != 0) {
  8916. int err = (int)ERRNO;
  8917. mg_cry(fc(ctx),
  8918. "call to getsockname failed %.*s: %d (%s)",
  8919. (int)vec.len,
  8920. vec.ptr,
  8921. err,
  8922. strerror(errno));
  8923. closesocket(so.sock);
  8924. so.sock = INVALID_SOCKET;
  8925. continue;
  8926. }
  8927. if ((ptr = (struct socket *)
  8928. mg_realloc(ctx->listening_sockets,
  8929. (ctx->num_listening_sockets + 1)
  8930. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  8931. mg_cry(fc(ctx), "%s", "Out of memory");
  8932. closesocket(so.sock);
  8933. so.sock = INVALID_SOCKET;
  8934. continue;
  8935. }
  8936. if ((portPtr =
  8937. (in_port_t *)mg_realloc(ctx->listening_ports,
  8938. (ctx->num_listening_sockets + 1)
  8939. * sizeof(ctx->listening_ports[0])))
  8940. == NULL) {
  8941. mg_cry(fc(ctx), "%s", "Out of memory");
  8942. closesocket(so.sock);
  8943. so.sock = INVALID_SOCKET;
  8944. mg_free(ptr);
  8945. continue;
  8946. }
  8947. set_close_on_exec(so.sock, fc(ctx));
  8948. ctx->listening_sockets = ptr;
  8949. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  8950. ctx->listening_ports = portPtr;
  8951. ctx->listening_ports[ctx->num_listening_sockets] =
  8952. ntohs(usa.sin.sin_port);
  8953. ctx->num_listening_sockets++;
  8954. portsOk++;
  8955. }
  8956. if (portsOk != portsTotal) {
  8957. close_all_listening_sockets(ctx);
  8958. portsOk = 0;
  8959. }
  8960. return portsOk;
  8961. }
  8962. static const char *
  8963. header_val(const struct mg_connection *conn, const char *header)
  8964. {
  8965. const char *header_value;
  8966. if ((header_value = mg_get_header(conn, header)) == NULL) {
  8967. return "-";
  8968. } else {
  8969. return header_value;
  8970. }
  8971. }
  8972. static void
  8973. log_access(const struct mg_connection *conn)
  8974. {
  8975. const struct mg_request_info *ri;
  8976. struct file fi;
  8977. char date[64], src_addr[IP_ADDR_STR_LEN];
  8978. struct tm *tm;
  8979. const char *referer;
  8980. const char *user_agent;
  8981. char buf[4096];
  8982. if (!conn || !conn->ctx) {
  8983. return;
  8984. }
  8985. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  8986. if (mg_fopen(conn, conn->ctx->config[ACCESS_LOG_FILE], "a+", &fi)
  8987. == 0) {
  8988. fi.fp = NULL;
  8989. }
  8990. } else {
  8991. fi.fp = NULL;
  8992. }
  8993. if (fi.fp == NULL && conn->ctx->callbacks.log_message == NULL) {
  8994. return;
  8995. }
  8996. tm = localtime(&conn->conn_birth_time);
  8997. if (tm != NULL) {
  8998. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  8999. } else {
  9000. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9001. date[sizeof(date) - 1] = '\0';
  9002. }
  9003. ri = &conn->request_info;
  9004. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9005. referer = header_val(conn, "Referer");
  9006. user_agent = header_val(conn, "User-Agent");
  9007. mg_snprintf(conn,
  9008. NULL, /* Ignore truncation in access log */
  9009. buf,
  9010. sizeof(buf),
  9011. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9012. src_addr,
  9013. ri->remote_user == NULL ? "-" : ri->remote_user,
  9014. date,
  9015. ri->request_method ? ri->request_method : "-",
  9016. ri->request_uri ? ri->request_uri : "-",
  9017. ri->query_string ? "?" : "",
  9018. ri->query_string ? ri->query_string : "",
  9019. ri->http_version,
  9020. conn->status_code,
  9021. conn->num_bytes_sent,
  9022. referer,
  9023. user_agent);
  9024. if (conn->ctx->callbacks.log_access) {
  9025. conn->ctx->callbacks.log_access(conn, buf);
  9026. }
  9027. if (fi.fp) {
  9028. flockfile(fi.fp);
  9029. fprintf(fi.fp, "%s\n", buf);
  9030. fflush(fi.fp);
  9031. funlockfile(fi.fp);
  9032. mg_fclose(&fi);
  9033. }
  9034. }
  9035. /* Verify given socket address against the ACL.
  9036. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9037. */
  9038. static int
  9039. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9040. {
  9041. int allowed, flag;
  9042. uint32_t net, mask;
  9043. struct vec vec;
  9044. if (ctx) {
  9045. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9046. /* If any ACL is set, deny by default */
  9047. allowed = list == NULL ? '+' : '-';
  9048. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9049. flag = vec.ptr[0];
  9050. if ((flag != '+' && flag != '-')
  9051. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9052. mg_cry(fc(ctx),
  9053. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9054. __func__);
  9055. return -1;
  9056. }
  9057. if (net == (remote_ip & mask)) {
  9058. allowed = flag;
  9059. }
  9060. }
  9061. return allowed == '+';
  9062. }
  9063. return -1;
  9064. }
  9065. #if !defined(_WIN32)
  9066. static int
  9067. set_uid_option(struct mg_context *ctx)
  9068. {
  9069. struct passwd *pw;
  9070. if (ctx) {
  9071. const char *uid = ctx->config[RUN_AS_USER];
  9072. int success = 0;
  9073. if (uid == NULL) {
  9074. success = 1;
  9075. } else {
  9076. if ((pw = getpwnam(uid)) == NULL) {
  9077. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9078. } else if (setgid(pw->pw_gid) == -1) {
  9079. mg_cry(fc(ctx),
  9080. "%s: setgid(%s): %s",
  9081. __func__,
  9082. uid,
  9083. strerror(errno));
  9084. } else if (setgroups(0, NULL)) {
  9085. mg_cry(fc(ctx),
  9086. "%s: setgroups(): %s",
  9087. __func__,
  9088. strerror(errno));
  9089. } else if (setuid(pw->pw_uid) == -1) {
  9090. mg_cry(fc(ctx),
  9091. "%s: setuid(%s): %s",
  9092. __func__,
  9093. uid,
  9094. strerror(errno));
  9095. } else {
  9096. success = 1;
  9097. }
  9098. }
  9099. return success;
  9100. }
  9101. return 0;
  9102. }
  9103. #endif /* !_WIN32 */
  9104. static void
  9105. tls_dtor(void *key)
  9106. {
  9107. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9108. /* key == pthread_getspecific(sTlsKey); */
  9109. if (tls) {
  9110. if (tls->is_master == 2) {
  9111. tls->is_master = -3; /* Mark memory as dead */
  9112. mg_free(tls);
  9113. }
  9114. }
  9115. pthread_setspecific(sTlsKey, NULL);
  9116. }
  9117. #if !defined(NO_SSL)
  9118. /* Must be set if sizeof(pthread_t) > sizeof(unsigned long) */
  9119. static unsigned long
  9120. ssl_id_callback(void)
  9121. {
  9122. #ifdef _WIN32
  9123. return GetCurrentThreadId();
  9124. #else
  9125. #ifdef __clang__
  9126. #pragma clang diagnostic push
  9127. #pragma clang diagnostic ignored "-Wunreachable-code"
  9128. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  9129. * or not, so one of the two conditions will be unreachable by construction.
  9130. * Unfortunately the C standard does not define a way to check this at
  9131. * compile time, since the #if preprocessor conditions can not use the sizeof
  9132. * operator as an argument. */
  9133. #endif
  9134. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  9135. /* This is the problematic case for CRYPTO_set_id_callback:
  9136. * The OS pthread_t can not be cast to unsigned long. */
  9137. struct mg_workerTLS *tls =
  9138. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  9139. if (tls == NULL) {
  9140. /* SSL called from an unknown thread: Create some thread index.
  9141. */
  9142. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  9143. tls->is_master = -2; /* -2 means "3rd party thread" */
  9144. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  9145. pthread_setspecific(sTlsKey, tls);
  9146. }
  9147. return tls->thread_idx;
  9148. } else {
  9149. /* pthread_t may be any data type, so a simple cast to unsigned long
  9150. * can rise a warning/error, depending on the platform.
  9151. * Here memcpy is used as an anything-to-anything cast. */
  9152. unsigned long ret = 0;
  9153. pthread_t t = pthread_self();
  9154. memcpy(&ret, &t, sizeof(pthread_t));
  9155. return ret;
  9156. }
  9157. #ifdef __clang__
  9158. #pragma clang diagnostic pop
  9159. #endif
  9160. #endif
  9161. }
  9162. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9163. static const char *ssl_error(void);
  9164. static int
  9165. refresh_trust(struct mg_connection *conn)
  9166. {
  9167. static int reload_lock = 0;
  9168. static long int data_check = 0;
  9169. struct stat cert_buf;
  9170. long int t;
  9171. char *pem;
  9172. int should_verify_peer;
  9173. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL
  9174. && conn->ctx->callbacks.init_ssl == NULL) {
  9175. return 0;
  9176. }
  9177. t = data_check;
  9178. if (stat(pem, &cert_buf) != -1) {
  9179. t = (long int)cert_buf.st_mtime;
  9180. }
  9181. if (data_check != t) {
  9182. data_check = t;
  9183. should_verify_peer =
  9184. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9185. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  9186. == 0);
  9187. if (should_verify_peer) {
  9188. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  9189. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  9190. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  9191. ca_file,
  9192. ca_path) != 1) {
  9193. mg_cry(fc(conn->ctx),
  9194. "SSL_CTX_load_verify_locations error: %s "
  9195. "ssl_verify_peer requires setting "
  9196. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9197. "present in "
  9198. "the .conf file?",
  9199. ssl_error());
  9200. return 0;
  9201. }
  9202. }
  9203. if (!reload_lock) {
  9204. reload_lock = 1;
  9205. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  9206. return 0;
  9207. }
  9208. reload_lock = 0;
  9209. }
  9210. }
  9211. /* lock while cert is reloading */
  9212. while (reload_lock) {
  9213. sleep(1);
  9214. }
  9215. return 1;
  9216. }
  9217. static pthread_mutex_t *ssl_mutexes;
  9218. static int
  9219. sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  9220. {
  9221. int ret, err;
  9222. int short_trust;
  9223. if (!conn) {
  9224. return 0;
  9225. }
  9226. short_trust =
  9227. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  9228. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  9229. if (short_trust) {
  9230. int trust_ret = refresh_trust(conn);
  9231. if (!trust_ret) {
  9232. return trust_ret;
  9233. }
  9234. }
  9235. conn->ssl = SSL_new(s);
  9236. if (conn->ssl == NULL) {
  9237. return 0;
  9238. }
  9239. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  9240. if (ret != 1) {
  9241. err = SSL_get_error(conn->ssl, ret);
  9242. (void)err; /* TODO: set some error message */
  9243. SSL_free(conn->ssl);
  9244. conn->ssl = NULL;
  9245. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9246. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9247. ERR_remove_state(0);
  9248. return 0;
  9249. }
  9250. ret = func(conn->ssl);
  9251. if (ret != 1) {
  9252. err = SSL_get_error(conn->ssl, ret);
  9253. (void)err; /* TODO: set some error message */
  9254. SSL_free(conn->ssl);
  9255. conn->ssl = NULL;
  9256. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9257. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9258. ERR_remove_state(0);
  9259. return 0;
  9260. }
  9261. return 1;
  9262. }
  9263. /* Return OpenSSL error message (from CRYPTO lib) */
  9264. static const char *
  9265. ssl_error(void)
  9266. {
  9267. unsigned long err;
  9268. err = ERR_get_error();
  9269. return err == 0 ? "" : ERR_error_string(err, NULL);
  9270. }
  9271. static void
  9272. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  9273. {
  9274. (void)line;
  9275. (void)file;
  9276. if (mode & 1) {
  9277. /* 1 is CRYPTO_LOCK */
  9278. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  9279. } else {
  9280. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  9281. }
  9282. }
  9283. #if !defined(NO_SSL_DL)
  9284. static void *
  9285. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  9286. {
  9287. union {
  9288. void *p;
  9289. void (*fp)(void);
  9290. } u;
  9291. void *dll_handle;
  9292. struct ssl_func *fp;
  9293. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  9294. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  9295. return NULL;
  9296. }
  9297. for (fp = sw; fp->name != NULL; fp++) {
  9298. #ifdef _WIN32
  9299. /* GetProcAddress() returns pointer to function */
  9300. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  9301. #else
  9302. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  9303. * pointers to function pointers. We need to use a union to make a
  9304. * cast. */
  9305. u.p = dlsym(dll_handle, fp->name);
  9306. #endif /* _WIN32 */
  9307. if (u.fp == NULL) {
  9308. mg_cry(fc(ctx),
  9309. "%s: %s: cannot find %s",
  9310. __func__,
  9311. dll_name,
  9312. fp->name);
  9313. dlclose(dll_handle);
  9314. return NULL;
  9315. } else {
  9316. fp->ptr = u.fp;
  9317. }
  9318. }
  9319. return dll_handle;
  9320. }
  9321. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  9322. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  9323. #endif /* NO_SSL_DL */
  9324. #if defined(SSL_ALREADY_INITIALIZED)
  9325. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  9326. #else
  9327. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  9328. #endif
  9329. static int
  9330. initialize_ssl(struct mg_context *ctx)
  9331. {
  9332. int i;
  9333. size_t size;
  9334. #if !defined(NO_SSL_DL)
  9335. if (!cryptolib_dll_handle) {
  9336. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  9337. if (!cryptolib_dll_handle) {
  9338. return 0;
  9339. }
  9340. }
  9341. #endif /* NO_SSL_DL */
  9342. if (mg_atomic_inc(&cryptolib_users) > 1) {
  9343. return 1;
  9344. }
  9345. /* Initialize locking callbacks, needed for thread safety.
  9346. * http://www.openssl.org/support/faq.html#PROG1
  9347. */
  9348. i = CRYPTO_num_locks();
  9349. if (i < 0) {
  9350. i = 0;
  9351. }
  9352. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  9353. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  9354. mg_cry(fc(ctx),
  9355. "%s: cannot allocate mutexes: %s",
  9356. __func__,
  9357. ssl_error());
  9358. return 0;
  9359. }
  9360. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9361. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  9362. }
  9363. CRYPTO_set_locking_callback(&ssl_locking_callback);
  9364. CRYPTO_set_id_callback(&ssl_id_callback);
  9365. return 1;
  9366. }
  9367. static int
  9368. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  9369. {
  9370. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  9371. mg_cry(fc(ctx),
  9372. "%s: cannot open certificate file %s: %s",
  9373. __func__,
  9374. pem,
  9375. ssl_error());
  9376. return 0;
  9377. }
  9378. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  9379. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  9380. mg_cry(fc(ctx),
  9381. "%s: cannot open private key file %s: %s",
  9382. __func__,
  9383. pem,
  9384. ssl_error());
  9385. return 0;
  9386. }
  9387. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  9388. mg_cry(fc(ctx),
  9389. "%s: certificate and private key do not match: %s",
  9390. __func__,
  9391. pem);
  9392. return 0;
  9393. }
  9394. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  9395. mg_cry(fc(ctx),
  9396. "%s: cannot use certificate chain file %s: %s",
  9397. __func__,
  9398. pem,
  9399. ssl_error());
  9400. return 0;
  9401. }
  9402. return 1;
  9403. }
  9404. static long
  9405. ssl_get_protocol(int version_id)
  9406. {
  9407. long ret = SSL_OP_ALL;
  9408. if (version_id > 0)
  9409. ret |= SSL_OP_NO_SSLv2;
  9410. if (version_id > 1)
  9411. ret |= SSL_OP_NO_SSLv3;
  9412. if (version_id > 2)
  9413. ret |= SSL_OP_NO_TLSv1;
  9414. if (version_id > 3)
  9415. ret |= SSL_OP_NO_TLSv1_1;
  9416. return ret;
  9417. }
  9418. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  9419. static int
  9420. set_ssl_option(struct mg_context *ctx)
  9421. {
  9422. const char *pem;
  9423. int callback_ret;
  9424. int should_verify_peer;
  9425. const char *ca_path;
  9426. const char *ca_file;
  9427. int use_default_verify_paths;
  9428. int verify_depth;
  9429. time_t now_rt = time(NULL);
  9430. struct timespec now_mt;
  9431. md5_byte_t ssl_context_id[16];
  9432. md5_state_t md5state;
  9433. int protocol_ver;
  9434. /* If PEM file is not specified and the init_ssl callback
  9435. * is not specified, skip SSL initialization. */
  9436. if (!ctx) {
  9437. return 0;
  9438. }
  9439. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  9440. && ctx->callbacks.init_ssl == NULL) {
  9441. return 1;
  9442. }
  9443. if (!initialize_ssl(ctx)) {
  9444. return 0;
  9445. }
  9446. #if !defined(NO_SSL_DL)
  9447. if (!ssllib_dll_handle) {
  9448. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  9449. if (!ssllib_dll_handle) {
  9450. return 0;
  9451. }
  9452. }
  9453. #endif /* NO_SSL_DL */
  9454. /* Initialize SSL library */
  9455. SSL_library_init();
  9456. SSL_load_error_strings();
  9457. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  9458. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  9459. return 0;
  9460. }
  9461. SSL_CTX_clear_options(ctx->ssl_ctx,
  9462. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  9463. | SSL_OP_NO_TLSv1_1);
  9464. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  9465. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  9466. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  9467. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  9468. /* If a callback has been specified, call it. */
  9469. callback_ret =
  9470. (ctx->callbacks.init_ssl == NULL)
  9471. ? 0
  9472. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  9473. /* If callback returns 0, civetweb sets up the SSL certificate.
  9474. * If it returns 1, civetweb assumes the calback already did this.
  9475. * If it returns -1, initializing ssl fails. */
  9476. if (callback_ret < 0) {
  9477. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  9478. return 0;
  9479. }
  9480. if (callback_ret > 0) {
  9481. if (pem != NULL) {
  9482. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  9483. }
  9484. return 1;
  9485. }
  9486. /* Use some UID as session context ID. */
  9487. md5_init(&md5state);
  9488. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  9489. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  9490. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  9491. md5_append(&md5state,
  9492. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  9493. strlen(ctx->config[LISTENING_PORTS]));
  9494. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  9495. md5_finish(&md5state, ssl_context_id);
  9496. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  9497. (const unsigned char *)&ssl_context_id,
  9498. sizeof(ssl_context_id));
  9499. if (pem != NULL) {
  9500. if (!ssl_use_pem_file(ctx, pem)) {
  9501. return 0;
  9502. }
  9503. }
  9504. should_verify_peer =
  9505. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  9506. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  9507. use_default_verify_paths =
  9508. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  9509. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  9510. if (should_verify_peer) {
  9511. ca_path = ctx->config[SSL_CA_PATH];
  9512. ca_file = ctx->config[SSL_CA_FILE];
  9513. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  9514. != 1) {
  9515. mg_cry(fc(ctx),
  9516. "SSL_CTX_load_verify_locations error: %s "
  9517. "ssl_verify_peer requires setting "
  9518. "either ssl_ca_path or ssl_ca_file. Is any of them "
  9519. "present in "
  9520. "the .conf file?",
  9521. ssl_error());
  9522. return 0;
  9523. }
  9524. SSL_CTX_set_verify(ctx->ssl_ctx,
  9525. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9526. NULL);
  9527. if (use_default_verify_paths
  9528. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  9529. mg_cry(fc(ctx),
  9530. "SSL_CTX_set_default_verify_paths error: %s",
  9531. ssl_error());
  9532. return 0;
  9533. }
  9534. if (ctx->config[SSL_VERIFY_DEPTH]) {
  9535. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  9536. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  9537. }
  9538. }
  9539. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  9540. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  9541. != 1) {
  9542. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  9543. }
  9544. }
  9545. return 1;
  9546. }
  9547. static void
  9548. uninitialize_ssl(struct mg_context *ctx)
  9549. {
  9550. int i;
  9551. (void)ctx;
  9552. if (mg_atomic_dec(&cryptolib_users) == 0) {
  9553. /* Shutdown according to
  9554. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  9555. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  9556. */
  9557. CRYPTO_set_locking_callback(NULL);
  9558. CRYPTO_set_id_callback(NULL);
  9559. ENGINE_cleanup();
  9560. CONF_modules_unload(1);
  9561. ERR_free_strings();
  9562. EVP_cleanup();
  9563. CRYPTO_cleanup_all_ex_data();
  9564. ERR_remove_state(0);
  9565. for (i = 0; i < CRYPTO_num_locks(); i++) {
  9566. pthread_mutex_destroy(&ssl_mutexes[i]);
  9567. }
  9568. mg_free(ssl_mutexes);
  9569. ssl_mutexes = NULL;
  9570. }
  9571. }
  9572. #endif /* !NO_SSL */
  9573. static int
  9574. set_gpass_option(struct mg_context *ctx)
  9575. {
  9576. if (ctx) {
  9577. struct file file = STRUCT_FILE_INITIALIZER;
  9578. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  9579. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  9580. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  9581. return 0;
  9582. }
  9583. return 1;
  9584. }
  9585. return 0;
  9586. }
  9587. static int
  9588. set_acl_option(struct mg_context *ctx)
  9589. {
  9590. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  9591. }
  9592. static void
  9593. reset_per_request_attributes(struct mg_connection *conn)
  9594. {
  9595. if (!conn) {
  9596. return;
  9597. }
  9598. conn->path_info = NULL;
  9599. conn->num_bytes_sent = conn->consumed_content = 0;
  9600. conn->status_code = -1;
  9601. conn->is_chunked = 0;
  9602. conn->must_close = conn->request_len = conn->throttle = 0;
  9603. conn->request_info.content_length = -1;
  9604. conn->request_info.remote_user = NULL;
  9605. conn->request_info.request_method = NULL;
  9606. conn->request_info.request_uri = NULL;
  9607. conn->request_info.local_uri = NULL;
  9608. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  9609. * local_uri and request_uri */
  9610. conn->request_info.http_version = NULL;
  9611. conn->request_info.num_headers = 0;
  9612. conn->data_len = 0;
  9613. conn->chunk_remainder = 0;
  9614. conn->internal_error = 0;
  9615. }
  9616. static int
  9617. set_sock_timeout(SOCKET sock, int milliseconds)
  9618. {
  9619. int r0 = 0, r1, r2;
  9620. #ifdef _WIN32
  9621. /* Windows specific */
  9622. DWORD tv = (DWORD)milliseconds;
  9623. #else
  9624. /* Linux, ... (not Windows) */
  9625. struct timeval tv;
  9626. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  9627. * max. time waiting for the acknowledged of TCP data before the connection
  9628. * will be forcefully closed and ETIMEDOUT is returned to the application.
  9629. * If this option is not set, the default timeout of 20-30 minutes is used.
  9630. */
  9631. /* #define TCP_USER_TIMEOUT (18) */
  9632. #if defined(TCP_USER_TIMEOUT)
  9633. unsigned int uto = (unsigned int)milliseconds;
  9634. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  9635. #endif
  9636. memset(&tv, 0, sizeof(tv));
  9637. tv.tv_sec = milliseconds / 1000;
  9638. tv.tv_usec = (milliseconds * 1000) % 1000000;
  9639. #endif /* _WIN32 */
  9640. r1 = setsockopt(
  9641. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9642. r2 = setsockopt(
  9643. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  9644. return r0 || r1 || r2;
  9645. }
  9646. static int
  9647. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  9648. {
  9649. if (setsockopt(sock,
  9650. IPPROTO_TCP,
  9651. TCP_NODELAY,
  9652. (SOCK_OPT_TYPE)&nodelay_on,
  9653. sizeof(nodelay_on)) != 0) {
  9654. /* Error */
  9655. return 1;
  9656. }
  9657. /* OK */
  9658. return 0;
  9659. }
  9660. static void
  9661. close_socket_gracefully(struct mg_connection *conn)
  9662. {
  9663. #if defined(_WIN32)
  9664. char buf[MG_BUF_LEN];
  9665. int n;
  9666. #endif
  9667. struct linger linger;
  9668. if (!conn) {
  9669. return;
  9670. }
  9671. /* Set linger option to avoid socket hanging out after close. This
  9672. * prevent
  9673. * ephemeral port exhaust problem under high QPS. */
  9674. linger.l_onoff = 1;
  9675. linger.l_linger = 1;
  9676. if (setsockopt(conn->client.sock,
  9677. SOL_SOCKET,
  9678. SO_LINGER,
  9679. (char *)&linger,
  9680. sizeof(linger)) != 0) {
  9681. mg_cry(conn,
  9682. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  9683. __func__,
  9684. strerror(ERRNO));
  9685. }
  9686. /* Send FIN to the client */
  9687. shutdown(conn->client.sock, SHUT_WR);
  9688. set_non_blocking_mode(conn->client.sock);
  9689. #if defined(_WIN32)
  9690. /* Read and discard pending incoming data. If we do not do that and
  9691. * close
  9692. * the socket, the data in the send buffer may be discarded. This
  9693. * behaviour is seen on Windows, when client keeps sending data
  9694. * when server decides to close the connection; then when client
  9695. * does recv() it gets no data back. */
  9696. do {
  9697. n = pull(
  9698. NULL, conn, buf, sizeof(buf), 1E-10 /* TODO: allow 0 as timeout */);
  9699. } while (n > 0);
  9700. #endif
  9701. /* Now we know that our FIN is ACK-ed, safe to close */
  9702. closesocket(conn->client.sock);
  9703. conn->client.sock = INVALID_SOCKET;
  9704. }
  9705. static void
  9706. close_connection(struct mg_connection *conn)
  9707. {
  9708. if (!conn || !conn->ctx) {
  9709. return;
  9710. }
  9711. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  9712. if (conn->lua_websocket_state) {
  9713. lua_websocket_close(conn, conn->lua_websocket_state);
  9714. conn->lua_websocket_state = NULL;
  9715. }
  9716. #endif
  9717. /* call the connection_close callback if assigned */
  9718. if ((conn->ctx->callbacks.connection_close != NULL)
  9719. && (conn->ctx->context_type == 1)) {
  9720. conn->ctx->callbacks.connection_close(conn);
  9721. }
  9722. mg_lock_connection(conn);
  9723. conn->must_close = 1;
  9724. #ifndef NO_SSL
  9725. if (conn->ssl != NULL) {
  9726. /* Run SSL_shutdown twice to ensure completly close SSL connection
  9727. */
  9728. SSL_shutdown(conn->ssl);
  9729. SSL_free(conn->ssl);
  9730. /* maybe not? CRYPTO_cleanup_all_ex_data(); */
  9731. /* see https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  9732. ERR_remove_state(0);
  9733. conn->ssl = NULL;
  9734. }
  9735. #endif
  9736. if (conn->client.sock != INVALID_SOCKET) {
  9737. close_socket_gracefully(conn);
  9738. conn->client.sock = INVALID_SOCKET;
  9739. }
  9740. mg_unlock_connection(conn);
  9741. }
  9742. void
  9743. mg_close_connection(struct mg_connection *conn)
  9744. {
  9745. struct mg_context *client_ctx = NULL;
  9746. unsigned int i;
  9747. if (conn == NULL) {
  9748. return;
  9749. }
  9750. if (conn->ctx->context_type == 2) {
  9751. client_ctx = conn->ctx;
  9752. /* client context: loops must end */
  9753. conn->ctx->stop_flag = 1;
  9754. }
  9755. #ifndef NO_SSL
  9756. if (conn->client_ssl_ctx != NULL) {
  9757. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  9758. }
  9759. #endif
  9760. close_connection(conn);
  9761. if (client_ctx != NULL) {
  9762. /* join worker thread and free context */
  9763. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  9764. if (client_ctx->workerthreadids[i] != 0) {
  9765. mg_join_thread(client_ctx->workerthreadids[i]);
  9766. }
  9767. }
  9768. mg_free(client_ctx->workerthreadids);
  9769. mg_free(client_ctx);
  9770. (void)pthread_mutex_destroy(&conn->mutex);
  9771. mg_free(conn);
  9772. }
  9773. }
  9774. static struct mg_connection *
  9775. mg_connect_client_impl(const struct mg_client_options *client_options,
  9776. int use_ssl,
  9777. char *ebuf,
  9778. size_t ebuf_len)
  9779. {
  9780. static struct mg_context fake_ctx;
  9781. struct mg_connection *conn = NULL;
  9782. SOCKET sock;
  9783. union usa sa;
  9784. if (!connect_socket(&fake_ctx,
  9785. client_options->host,
  9786. client_options->port,
  9787. use_ssl,
  9788. ebuf,
  9789. ebuf_len,
  9790. &sock,
  9791. &sa)) {
  9792. ;
  9793. } else if ((conn = (struct mg_connection *)
  9794. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  9795. mg_snprintf(NULL,
  9796. NULL, /* No truncation check for ebuf */
  9797. ebuf,
  9798. ebuf_len,
  9799. "calloc(): %s",
  9800. strerror(ERRNO));
  9801. closesocket(sock);
  9802. #ifndef NO_SSL
  9803. } else if (use_ssl
  9804. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  9805. == NULL) {
  9806. mg_snprintf(NULL,
  9807. NULL, /* No truncation check for ebuf */
  9808. ebuf,
  9809. ebuf_len,
  9810. "SSL_CTX_new error");
  9811. closesocket(sock);
  9812. mg_free(conn);
  9813. conn = NULL;
  9814. #endif /* NO_SSL */
  9815. } else {
  9816. #ifdef USE_IPV6
  9817. socklen_t len = (sa.sa.sa_family == AF_INET)
  9818. ? sizeof(conn->client.rsa.sin)
  9819. : sizeof(conn->client.rsa.sin6);
  9820. struct sockaddr *psa =
  9821. (sa.sa.sa_family == AF_INET)
  9822. ? (struct sockaddr *)&(conn->client.rsa.sin)
  9823. : (struct sockaddr *)&(conn->client.rsa.sin6);
  9824. #else
  9825. socklen_t len = sizeof(conn->client.rsa.sin);
  9826. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  9827. #endif
  9828. conn->buf_size = MAX_REQUEST_SIZE;
  9829. conn->buf = (char *)(conn + 1);
  9830. conn->ctx = &fake_ctx;
  9831. conn->client.sock = sock;
  9832. conn->client.lsa = sa;
  9833. if (getsockname(sock, psa, &len) != 0) {
  9834. mg_cry(conn,
  9835. "%s: getsockname() failed: %s",
  9836. __func__,
  9837. strerror(ERRNO));
  9838. }
  9839. conn->client.is_ssl = use_ssl ? 1 : 0;
  9840. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  9841. #ifndef NO_SSL
  9842. if (use_ssl) {
  9843. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  9844. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  9845. SSL_CTX_set_verify call is needed to switch off server
  9846. * certificate checking, which is off by default in OpenSSL and
  9847. on
  9848. * in yaSSL. */
  9849. // TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  9850. // SSL_VERIFY_PEER,
  9851. // verify_ssl_server);
  9852. if (client_options->client_cert) {
  9853. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  9854. mg_snprintf(NULL,
  9855. NULL, /* No truncation check for ebuf */
  9856. ebuf,
  9857. ebuf_len,
  9858. "Can not use SSL client certificate");
  9859. SSL_CTX_free(conn->client_ssl_ctx);
  9860. closesocket(sock);
  9861. mg_free(conn);
  9862. conn = NULL;
  9863. }
  9864. }
  9865. if (client_options->server_cert) {
  9866. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  9867. client_options->server_cert,
  9868. NULL);
  9869. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  9870. } else {
  9871. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  9872. }
  9873. if (!sslize(conn, conn->client_ssl_ctx, SSL_connect)) {
  9874. mg_snprintf(NULL,
  9875. NULL, /* No truncation check for ebuf */
  9876. ebuf,
  9877. ebuf_len,
  9878. "SSL connection error");
  9879. SSL_CTX_free(conn->client_ssl_ctx);
  9880. closesocket(sock);
  9881. mg_free(conn);
  9882. conn = NULL;
  9883. }
  9884. }
  9885. #endif
  9886. }
  9887. return conn;
  9888. }
  9889. CIVETWEB_API struct mg_connection *
  9890. mg_connect_client_secure(const struct mg_client_options *client_options,
  9891. char *error_buffer,
  9892. size_t error_buffer_size)
  9893. {
  9894. return mg_connect_client_impl(client_options,
  9895. 1,
  9896. error_buffer,
  9897. error_buffer_size);
  9898. }
  9899. struct mg_connection *
  9900. mg_connect_client(const char *host,
  9901. int port,
  9902. int use_ssl,
  9903. char *error_buffer,
  9904. size_t error_buffer_size)
  9905. {
  9906. struct mg_client_options opts;
  9907. memset(&opts, 0, sizeof(opts));
  9908. opts.host = host;
  9909. opts.port = port;
  9910. return mg_connect_client_impl(&opts,
  9911. use_ssl,
  9912. error_buffer,
  9913. error_buffer_size);
  9914. }
  9915. static const struct {
  9916. const char *proto;
  9917. size_t proto_len;
  9918. unsigned default_port;
  9919. } abs_uri_protocols[] = {{"http://", 7, 80},
  9920. {"https://", 8, 443},
  9921. {"ws://", 5, 80},
  9922. {"wss://", 6, 443},
  9923. {NULL, 0, 0}};
  9924. /* Check if the uri is valid.
  9925. * return 0 for invalid uri,
  9926. * return 1 for *,
  9927. * return 2 for relative uri,
  9928. * return 3 for absolute uri without port,
  9929. * return 4 for absolute uri with port */
  9930. static int
  9931. get_uri_type(const char *uri)
  9932. {
  9933. int i;
  9934. char *hostend, *portbegin, *portend;
  9935. unsigned long port;
  9936. /* According to the HTTP standard
  9937. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  9938. * URI can be an asterisk (*) or should start with slash (relative uri),
  9939. * or it should start with the protocol (absolute uri). */
  9940. if (uri[0] == '*' && uri[1] == '\0') {
  9941. /* asterisk */
  9942. return 1;
  9943. }
  9944. if (uri[0] == '/') {
  9945. /* relative uri */
  9946. return 2;
  9947. }
  9948. /* It could be an absolute uri: */
  9949. /* This function only checks if the uri is valid, not if it is
  9950. * addressing the current server. So civetweb can also be used
  9951. * as a proxy server. */
  9952. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9953. if (mg_strncasecmp(uri,
  9954. abs_uri_protocols[i].proto,
  9955. abs_uri_protocols[i].proto_len) == 0) {
  9956. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  9957. if (!hostend) {
  9958. return 0;
  9959. }
  9960. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  9961. if (!portbegin) {
  9962. return 3;
  9963. }
  9964. port = strtoul(portbegin + 1, &portend, 10);
  9965. if ((portend != hostend) || !port || !is_valid_port(port)) {
  9966. return 0;
  9967. }
  9968. return 4;
  9969. }
  9970. }
  9971. return 0;
  9972. }
  9973. /* Return NULL or the relative uri at the current server */
  9974. static const char *
  9975. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  9976. {
  9977. const char *server_domain;
  9978. size_t server_domain_len;
  9979. size_t request_domain_len = 0;
  9980. unsigned long port = 0;
  9981. int i;
  9982. const char *hostbegin = NULL;
  9983. const char *hostend = NULL;
  9984. const char *portbegin;
  9985. char *portend;
  9986. /* DNS is case insensitive, so use case insensitive string compare here
  9987. */
  9988. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  9989. if (!server_domain) {
  9990. return 0;
  9991. }
  9992. server_domain_len = strlen(server_domain);
  9993. if (!server_domain_len) {
  9994. return 0;
  9995. }
  9996. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  9997. if (mg_strncasecmp(uri,
  9998. abs_uri_protocols[i].proto,
  9999. abs_uri_protocols[i].proto_len) == 0) {
  10000. hostbegin = uri + abs_uri_protocols[i].proto_len;
  10001. hostend = strchr(hostbegin, '/');
  10002. if (!hostend) {
  10003. return 0;
  10004. }
  10005. portbegin = strchr(hostbegin, ':');
  10006. if ((!portbegin) || (portbegin > hostend)) {
  10007. port = abs_uri_protocols[i].default_port;
  10008. request_domain_len = (size_t)(hostend - hostbegin);
  10009. } else {
  10010. port = strtoul(portbegin + 1, &portend, 10);
  10011. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10012. return 0;
  10013. }
  10014. request_domain_len = (size_t)(portbegin - hostbegin);
  10015. }
  10016. /* protocol found, port set */
  10017. break;
  10018. }
  10019. }
  10020. if (!port) {
  10021. /* port remains 0 if the protocol is not found */
  10022. return 0;
  10023. }
  10024. #if defined(USE_IPV6)
  10025. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  10026. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  10027. /* Request is directed to a different port */
  10028. return 0;
  10029. }
  10030. } else
  10031. #endif
  10032. {
  10033. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  10034. /* Request is directed to a different port */
  10035. return 0;
  10036. }
  10037. }
  10038. if ((request_domain_len != server_domain_len)
  10039. || (0 != memcmp(server_domain, hostbegin, server_domain_len))) {
  10040. /* Request is directed to another server */
  10041. return 0;
  10042. }
  10043. return hostend;
  10044. }
  10045. static int
  10046. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  10047. {
  10048. const char *cl;
  10049. if (ebuf_len > 0) {
  10050. ebuf[0] = '\0';
  10051. }
  10052. *err = 0;
  10053. reset_per_request_attributes(conn);
  10054. if (!conn) {
  10055. mg_snprintf(conn,
  10056. NULL, /* No truncation check for ebuf */
  10057. ebuf,
  10058. ebuf_len,
  10059. "%s",
  10060. "Internal error");
  10061. *err = 500;
  10062. return 0;
  10063. }
  10064. /* Set the time the request was received. This value should be used for
  10065. * timeouts. */
  10066. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  10067. conn->request_len =
  10068. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  10069. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  10070. */
  10071. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  10072. mg_snprintf(conn,
  10073. NULL, /* No truncation check for ebuf */
  10074. ebuf,
  10075. ebuf_len,
  10076. "%s",
  10077. "Invalid request size");
  10078. *err = 500;
  10079. return 0;
  10080. }
  10081. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  10082. mg_snprintf(conn,
  10083. NULL, /* No truncation check for ebuf */
  10084. ebuf,
  10085. ebuf_len,
  10086. "%s",
  10087. "Request Too Large");
  10088. *err = 413;
  10089. return 0;
  10090. } else if (conn->request_len <= 0) {
  10091. if (conn->data_len > 0) {
  10092. mg_snprintf(conn,
  10093. NULL, /* No truncation check for ebuf */
  10094. ebuf,
  10095. ebuf_len,
  10096. "%s",
  10097. "Client sent malformed request");
  10098. *err = 400;
  10099. } else {
  10100. /* Server did not send anything -> just close the connection */
  10101. conn->must_close = 1;
  10102. mg_snprintf(conn,
  10103. NULL, /* No truncation check for ebuf */
  10104. ebuf,
  10105. ebuf_len,
  10106. "%s",
  10107. "Client did not send a request");
  10108. *err = 0;
  10109. }
  10110. return 0;
  10111. } else if (parse_http_message(conn->buf,
  10112. conn->buf_size,
  10113. &conn->request_info) <= 0) {
  10114. mg_snprintf(conn,
  10115. NULL, /* No truncation check for ebuf */
  10116. ebuf,
  10117. ebuf_len,
  10118. "%s",
  10119. "Bad Request");
  10120. *err = 400;
  10121. return 0;
  10122. } else {
  10123. /* Message is a valid request or response */
  10124. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  10125. /* Request/response has content length set */
  10126. char *endptr = NULL;
  10127. conn->content_len = strtoll(cl, &endptr, 10);
  10128. if (endptr == cl) {
  10129. mg_snprintf(conn,
  10130. NULL, /* No truncation check for ebuf */
  10131. ebuf,
  10132. ebuf_len,
  10133. "%s",
  10134. "Bad Request");
  10135. *err = 411;
  10136. return 0;
  10137. }
  10138. /* Publish the content length back to the request info. */
  10139. conn->request_info.content_length = conn->content_len;
  10140. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  10141. != NULL
  10142. && strcmp(cl, "chunked") == 0) {
  10143. conn->is_chunked = 1;
  10144. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  10145. || !mg_strcasecmp(conn->request_info.request_method,
  10146. "PUT")) {
  10147. /* POST or PUT request without content length set */
  10148. conn->content_len = -1;
  10149. } else if (!mg_strncasecmp(conn->request_info.request_method,
  10150. "HTTP/",
  10151. 5)) {
  10152. /* Response without content length set */
  10153. conn->content_len = -1;
  10154. } else {
  10155. /* Other request */
  10156. conn->content_len = 0;
  10157. }
  10158. }
  10159. return 1;
  10160. }
  10161. int
  10162. mg_get_response(struct mg_connection *conn,
  10163. char *ebuf,
  10164. size_t ebuf_len,
  10165. int timeout)
  10166. {
  10167. if (conn) {
  10168. /* Implementation of API function for HTTP clients */
  10169. int err, ret;
  10170. struct mg_context *octx = conn->ctx;
  10171. struct mg_context rctx = *(conn->ctx);
  10172. char txt[32]; /* will not overflow */
  10173. if (timeout >= 0) {
  10174. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  10175. rctx.config[REQUEST_TIMEOUT] = txt;
  10176. set_sock_timeout(conn->client.sock, timeout);
  10177. } else {
  10178. rctx.config[REQUEST_TIMEOUT] = NULL;
  10179. }
  10180. conn->ctx = &rctx;
  10181. ret = getreq(conn, ebuf, ebuf_len, &err);
  10182. conn->ctx = octx;
  10183. /* TODO: 1) uri is deprecated;
  10184. * 2) here, ri.uri is the http response code */
  10185. conn->request_info.uri = conn->request_info.request_uri;
  10186. /* TODO (mid): Define proper return values - maybe return length?
  10187. * For the first test use <0 for error and >0 for OK */
  10188. return (ret == 0) ? -1 : +1;
  10189. }
  10190. return -1;
  10191. }
  10192. struct mg_connection *
  10193. mg_download(const char *host,
  10194. int port,
  10195. int use_ssl,
  10196. char *ebuf,
  10197. size_t ebuf_len,
  10198. const char *fmt,
  10199. ...)
  10200. {
  10201. struct mg_connection *conn;
  10202. va_list ap;
  10203. int i;
  10204. int reqerr;
  10205. va_start(ap, fmt);
  10206. ebuf[0] = '\0';
  10207. /* open a connection */
  10208. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  10209. if (conn != NULL) {
  10210. i = mg_vprintf(conn, fmt, ap);
  10211. if (i <= 0) {
  10212. mg_snprintf(conn,
  10213. NULL, /* No truncation check for ebuf */
  10214. ebuf,
  10215. ebuf_len,
  10216. "%s",
  10217. "Error sending request");
  10218. } else {
  10219. getreq(conn, ebuf, ebuf_len, &reqerr);
  10220. /* TODO: 1) uri is deprecated;
  10221. * 2) here, ri.uri is the http response code */
  10222. conn->request_info.uri = conn->request_info.request_uri;
  10223. }
  10224. }
  10225. /* if an error occured, close the connection */
  10226. if (ebuf[0] != '\0' && conn != NULL) {
  10227. mg_close_connection(conn);
  10228. conn = NULL;
  10229. }
  10230. va_end(ap);
  10231. return conn;
  10232. }
  10233. struct websocket_client_thread_data {
  10234. struct mg_connection *conn;
  10235. mg_websocket_data_handler data_handler;
  10236. mg_websocket_close_handler close_handler;
  10237. void *callback_data;
  10238. };
  10239. #if defined(USE_WEBSOCKET)
  10240. #ifdef _WIN32
  10241. static unsigned __stdcall websocket_client_thread(void *data)
  10242. #else
  10243. static void *
  10244. websocket_client_thread(void *data)
  10245. #endif
  10246. {
  10247. struct websocket_client_thread_data *cdata =
  10248. (struct websocket_client_thread_data *)data;
  10249. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  10250. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  10251. if (cdata->close_handler != NULL) {
  10252. cdata->close_handler(cdata->conn, cdata->callback_data);
  10253. }
  10254. mg_free((void *)cdata);
  10255. #ifdef _WIN32
  10256. return 0;
  10257. #else
  10258. return NULL;
  10259. #endif
  10260. }
  10261. #endif
  10262. struct mg_connection *
  10263. mg_connect_websocket_client(const char *host,
  10264. int port,
  10265. int use_ssl,
  10266. char *error_buffer,
  10267. size_t error_buffer_size,
  10268. const char *path,
  10269. const char *origin,
  10270. mg_websocket_data_handler data_func,
  10271. mg_websocket_close_handler close_func,
  10272. void *user_data)
  10273. {
  10274. struct mg_connection *conn = NULL;
  10275. #if defined(USE_WEBSOCKET)
  10276. struct mg_context *newctx = NULL;
  10277. struct websocket_client_thread_data *thread_data;
  10278. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  10279. static const char *handshake_req;
  10280. if (origin != NULL) {
  10281. handshake_req = "GET %s HTTP/1.1\r\n"
  10282. "Host: %s\r\n"
  10283. "Upgrade: websocket\r\n"
  10284. "Connection: Upgrade\r\n"
  10285. "Sec-WebSocket-Key: %s\r\n"
  10286. "Sec-WebSocket-Version: 13\r\n"
  10287. "Origin: %s\r\n"
  10288. "\r\n";
  10289. } else {
  10290. handshake_req = "GET %s HTTP/1.1\r\n"
  10291. "Host: %s\r\n"
  10292. "Upgrade: websocket\r\n"
  10293. "Connection: Upgrade\r\n"
  10294. "Sec-WebSocket-Key: %s\r\n"
  10295. "Sec-WebSocket-Version: 13\r\n"
  10296. "\r\n";
  10297. }
  10298. /* Establish the client connection and request upgrade */
  10299. conn = mg_download(host,
  10300. port,
  10301. use_ssl,
  10302. error_buffer,
  10303. error_buffer_size,
  10304. handshake_req,
  10305. path,
  10306. host,
  10307. magic,
  10308. origin);
  10309. /* Connection object will be null if something goes wrong */
  10310. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  10311. if (!*error_buffer) {
  10312. /* if there is a connection, but it did not return 101,
  10313. * error_buffer is not yet set */
  10314. mg_snprintf(conn,
  10315. NULL, /* No truncation check for ebuf */
  10316. error_buffer,
  10317. error_buffer_size,
  10318. "Unexpected server reply");
  10319. }
  10320. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  10321. if (conn != NULL) {
  10322. mg_free(conn);
  10323. conn = NULL;
  10324. }
  10325. return conn;
  10326. }
  10327. /* For client connections, mg_context is fake. Since we need to set a
  10328. * callback function, we need to create a copy and modify it. */
  10329. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  10330. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  10331. newctx->user_data = user_data;
  10332. newctx->context_type = 2; /* client context type */
  10333. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  10334. newctx->workerthreadids =
  10335. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  10336. conn->ctx = newctx;
  10337. thread_data = (struct websocket_client_thread_data *)
  10338. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  10339. thread_data->conn = conn;
  10340. thread_data->data_handler = data_func;
  10341. thread_data->close_handler = close_func;
  10342. thread_data->callback_data = NULL;
  10343. /* Start a thread to read the websocket client connection
  10344. * This thread will automatically stop when mg_disconnect is
  10345. * called on the client connection */
  10346. if (mg_start_thread_with_id(websocket_client_thread,
  10347. (void *)thread_data,
  10348. newctx->workerthreadids) != 0) {
  10349. mg_free((void *)thread_data);
  10350. mg_free((void *)newctx->workerthreadids);
  10351. mg_free((void *)newctx);
  10352. mg_free((void *)conn);
  10353. conn = NULL;
  10354. DEBUG_TRACE("%s",
  10355. "Websocket client connect thread could not be started\r\n");
  10356. }
  10357. #else
  10358. /* Appease "unused parameter" warnings */
  10359. (void)host;
  10360. (void)port;
  10361. (void)use_ssl;
  10362. (void)error_buffer;
  10363. (void)error_buffer_size;
  10364. (void)path;
  10365. (void)origin;
  10366. (void)user_data;
  10367. (void)data_func;
  10368. (void)close_func;
  10369. #endif
  10370. return conn;
  10371. }
  10372. static void
  10373. process_new_connection(struct mg_connection *conn)
  10374. {
  10375. if (conn && conn->ctx) {
  10376. struct mg_request_info *ri = &conn->request_info;
  10377. int keep_alive_enabled, keep_alive, discard_len;
  10378. char ebuf[100];
  10379. const char *hostend;
  10380. int reqerr, uri_type;
  10381. keep_alive_enabled =
  10382. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  10383. /* Important: on new connection, reset the receiving buffer. Credit
  10384. * goes to crule42. */
  10385. conn->data_len = 0;
  10386. do {
  10387. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  10388. /* The request sent by the client could not be understood by
  10389. * the server, or it was incomplete or a timeout. Send an
  10390. * error message and close the connection. */
  10391. if (reqerr > 0) {
  10392. /*assert(ebuf[0] != '\0');*/
  10393. send_http_error(conn, reqerr, "%s", ebuf);
  10394. }
  10395. } else if (strcmp(ri->http_version, "1.0")
  10396. && strcmp(ri->http_version, "1.1")) {
  10397. mg_snprintf(conn,
  10398. NULL, /* No truncation check for ebuf */
  10399. ebuf,
  10400. sizeof(ebuf),
  10401. "Bad HTTP version: [%s]",
  10402. ri->http_version);
  10403. send_http_error(conn, 505, "%s", ebuf);
  10404. }
  10405. if (ebuf[0] == '\0') {
  10406. uri_type = get_uri_type(conn->request_info.request_uri);
  10407. switch (uri_type) {
  10408. case 1:
  10409. /* Asterisk */
  10410. conn->request_info.local_uri = NULL;
  10411. break;
  10412. case 2:
  10413. /* relative uri */
  10414. conn->request_info.local_uri =
  10415. conn->request_info.request_uri;
  10416. break;
  10417. case 3:
  10418. case 4:
  10419. /* absolute uri (with/without port) */
  10420. hostend = get_rel_url_at_current_server(
  10421. conn->request_info.request_uri, conn);
  10422. if (hostend) {
  10423. conn->request_info.local_uri = hostend;
  10424. } else {
  10425. conn->request_info.local_uri = NULL;
  10426. }
  10427. break;
  10428. default:
  10429. mg_snprintf(conn,
  10430. NULL, /* No truncation check for ebuf */
  10431. ebuf,
  10432. sizeof(ebuf),
  10433. "Invalid URI: [%s]",
  10434. ri->request_uri);
  10435. send_http_error(conn, 400, "%s", ebuf);
  10436. break;
  10437. }
  10438. /* TODO: cleanup uri, local_uri and request_uri */
  10439. conn->request_info.uri = conn->request_info.local_uri;
  10440. }
  10441. if (ebuf[0] == '\0') {
  10442. if (conn->request_info.local_uri) {
  10443. /* handle request to local server */
  10444. handle_request(conn);
  10445. if (conn->ctx->callbacks.end_request != NULL) {
  10446. conn->ctx->callbacks.end_request(conn,
  10447. conn->status_code);
  10448. }
  10449. log_access(conn);
  10450. } else {
  10451. /* TODO: handle non-local request (PROXY) */
  10452. conn->must_close = 1;
  10453. }
  10454. } else {
  10455. conn->must_close = 1;
  10456. }
  10457. if (ri->remote_user != NULL) {
  10458. mg_free((void *)ri->remote_user);
  10459. /* Important! When having connections with and without auth
  10460. * would cause double free and then crash */
  10461. ri->remote_user = NULL;
  10462. }
  10463. /* NOTE(lsm): order is important here. should_keep_alive() call
  10464. * is
  10465. * using parsed request, which will be invalid after memmove's
  10466. * below.
  10467. * Therefore, memorize should_keep_alive() result now for later
  10468. * use
  10469. * in loop exit condition. */
  10470. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled
  10471. && conn->content_len >= 0 && should_keep_alive(conn);
  10472. /* Discard all buffered data for this request */
  10473. discard_len = conn->content_len >= 0 && conn->request_len > 0
  10474. && conn->request_len + conn->content_len
  10475. < (int64_t)conn->data_len
  10476. ? (int)(conn->request_len + conn->content_len)
  10477. : conn->data_len;
  10478. /*assert(discard_len >= 0);*/
  10479. if (discard_len < 0)
  10480. break;
  10481. conn->data_len -= discard_len;
  10482. if (conn->data_len > 0) {
  10483. memmove(conn->buf,
  10484. conn->buf + discard_len,
  10485. (size_t)conn->data_len);
  10486. }
  10487. /* assert(conn->data_len >= 0); */
  10488. /* assert(conn->data_len <= conn->buf_size); */
  10489. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  10490. break;
  10491. }
  10492. } while (keep_alive);
  10493. }
  10494. }
  10495. /* Worker threads take accepted socket from the queue */
  10496. static int
  10497. consume_socket(struct mg_context *ctx, struct socket *sp)
  10498. {
  10499. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10500. if (!ctx) {
  10501. return 0;
  10502. }
  10503. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10504. DEBUG_TRACE("%s", "going idle");
  10505. /* If the queue is empty, wait. We're idle at this point. */
  10506. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  10507. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  10508. }
  10509. /* If we're stopping, sq_head may be equal to sq_tail. */
  10510. if (ctx->sq_head > ctx->sq_tail) {
  10511. /* Copy socket from the queue and increment tail */
  10512. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  10513. ctx->sq_tail++;
  10514. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  10515. /* Wrap pointers if needed */
  10516. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  10517. ctx->sq_tail -= QUEUE_SIZE(ctx);
  10518. ctx->sq_head -= QUEUE_SIZE(ctx);
  10519. }
  10520. }
  10521. (void)pthread_cond_signal(&ctx->sq_empty);
  10522. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10523. return !ctx->stop_flag;
  10524. #undef QUEUE_SIZE
  10525. }
  10526. static void *
  10527. worker_thread_run(void *thread_func_param)
  10528. {
  10529. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10530. struct mg_connection *conn;
  10531. struct mg_workerTLS tls;
  10532. #if defined(MG_LEGACY_INTERFACE)
  10533. uint32_t addr;
  10534. #endif
  10535. mg_set_thread_name("worker");
  10536. tls.is_master = 0;
  10537. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  10538. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10539. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10540. #endif
  10541. conn =
  10542. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  10543. if (conn == NULL) {
  10544. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  10545. } else {
  10546. pthread_setspecific(sTlsKey, &tls);
  10547. conn->buf_size = MAX_REQUEST_SIZE;
  10548. conn->buf = (char *)(conn + 1);
  10549. conn->ctx = ctx;
  10550. conn->request_info.user_data = ctx->user_data;
  10551. /* Allocate a mutex for this connection to allow communication both
  10552. * within the request handler and from elsewhere in the application
  10553. */
  10554. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10555. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  10556. * signal sq_empty condvar to wake up the master waiting in
  10557. * produce_socket() */
  10558. while (consume_socket(ctx, &conn->client)) {
  10559. conn->conn_birth_time = time(NULL);
  10560. /* Fill in IP, port info early so even if SSL setup below fails,
  10561. * error handler would have the corresponding info.
  10562. * Thanks to Johannes Winkelmann for the patch.
  10563. */
  10564. #if defined(USE_IPV6)
  10565. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  10566. conn->request_info.remote_port =
  10567. ntohs(conn->client.rsa.sin6.sin6_port);
  10568. } else
  10569. #endif
  10570. {
  10571. conn->request_info.remote_port =
  10572. ntohs(conn->client.rsa.sin.sin_port);
  10573. }
  10574. sockaddr_to_string(conn->request_info.remote_addr,
  10575. sizeof(conn->request_info.remote_addr),
  10576. &conn->client.rsa);
  10577. #if defined(MG_LEGACY_INTERFACE)
  10578. /* This legacy interface only works for the IPv4 case */
  10579. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  10580. memcpy(&conn->request_info.remote_ip, &addr, 4);
  10581. #endif
  10582. conn->request_info.is_ssl = conn->client.is_ssl;
  10583. if (!conn->client.is_ssl
  10584. #ifndef NO_SSL
  10585. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  10586. #endif
  10587. ) {
  10588. process_new_connection(conn);
  10589. }
  10590. close_connection(conn);
  10591. }
  10592. }
  10593. /* Signal master that we're done with connection and exiting */
  10594. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10595. ctx->running_worker_threads--;
  10596. (void)pthread_cond_signal(&ctx->thread_cond);
  10597. /* assert(ctx->running_worker_threads >= 0); */
  10598. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10599. pthread_setspecific(sTlsKey, NULL);
  10600. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10601. CloseHandle(tls.pthread_cond_helper_mutex);
  10602. #endif
  10603. pthread_mutex_destroy(&conn->mutex);
  10604. mg_free(conn);
  10605. DEBUG_TRACE("%s", "exiting");
  10606. return NULL;
  10607. }
  10608. /* Threads have different return types on Windows and Unix. */
  10609. #ifdef _WIN32
  10610. static unsigned __stdcall worker_thread(void *thread_func_param)
  10611. {
  10612. worker_thread_run(thread_func_param);
  10613. return 0;
  10614. }
  10615. #else
  10616. static void *
  10617. worker_thread(void *thread_func_param)
  10618. {
  10619. worker_thread_run(thread_func_param);
  10620. return NULL;
  10621. }
  10622. #endif /* _WIN32 */
  10623. /* Master thread adds accepted socket to a queue */
  10624. static void
  10625. produce_socket(struct mg_context *ctx, const struct socket *sp)
  10626. {
  10627. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  10628. if (!ctx) {
  10629. return;
  10630. }
  10631. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10632. /* If the queue is full, wait */
  10633. while (ctx->stop_flag == 0
  10634. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  10635. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  10636. }
  10637. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  10638. /* Copy socket to the queue and increment head */
  10639. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  10640. ctx->sq_head++;
  10641. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  10642. }
  10643. (void)pthread_cond_signal(&ctx->sq_full);
  10644. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10645. #undef QUEUE_SIZE
  10646. }
  10647. static void
  10648. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  10649. {
  10650. struct socket so;
  10651. char src_addr[IP_ADDR_STR_LEN];
  10652. socklen_t len = sizeof(so.rsa);
  10653. int on = 1;
  10654. int timeout;
  10655. if (!listener) {
  10656. return;
  10657. }
  10658. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  10659. == INVALID_SOCKET) {
  10660. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  10661. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  10662. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  10663. closesocket(so.sock);
  10664. so.sock = INVALID_SOCKET;
  10665. } else {
  10666. /* Put so socket structure into the queue */
  10667. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  10668. set_close_on_exec(so.sock, fc(ctx));
  10669. so.is_ssl = listener->is_ssl;
  10670. so.ssl_redir = listener->ssl_redir;
  10671. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  10672. mg_cry(fc(ctx),
  10673. "%s: getsockname() failed: %s",
  10674. __func__,
  10675. strerror(ERRNO));
  10676. }
  10677. /* Set TCP keep-alive. This is needed because if HTTP-level
  10678. * keep-alive
  10679. * is enabled, and client resets the connection, server won't get
  10680. * TCP FIN or RST and will keep the connection open forever. With
  10681. * TCP keep-alive, next keep-alive handshake will figure out that
  10682. * the client is down and will close the server end.
  10683. * Thanks to Igor Klopov who suggested the patch. */
  10684. if (setsockopt(so.sock,
  10685. SOL_SOCKET,
  10686. SO_KEEPALIVE,
  10687. (SOCK_OPT_TYPE)&on,
  10688. sizeof(on)) != 0) {
  10689. mg_cry(fc(ctx),
  10690. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  10691. __func__,
  10692. strerror(ERRNO));
  10693. }
  10694. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  10695. * to effectively fill up the underlying IP packet payload and reduce
  10696. * the overhead of sending lots of small buffers. However this hurts
  10697. * the server's throughput (ie. operations per second) when HTTP 1.1
  10698. * persistent connections are used and the responses are relatively
  10699. * small (eg. less than 1400 bytes).
  10700. */
  10701. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  10702. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  10703. if (set_tcp_nodelay(so.sock, 1) != 0) {
  10704. mg_cry(fc(ctx),
  10705. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  10706. __func__,
  10707. strerror(ERRNO));
  10708. }
  10709. }
  10710. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  10711. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  10712. } else {
  10713. timeout = -1;
  10714. }
  10715. /* Set socket timeout to the given value, but not more than a
  10716. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  10717. * so the server can exit after that time if requested. */
  10718. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  10719. set_sock_timeout(so.sock, timeout);
  10720. } else {
  10721. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  10722. }
  10723. produce_socket(ctx, &so);
  10724. }
  10725. }
  10726. static void
  10727. master_thread_run(void *thread_func_param)
  10728. {
  10729. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  10730. struct mg_workerTLS tls;
  10731. struct pollfd *pfd;
  10732. unsigned int i;
  10733. unsigned int workerthreadcount;
  10734. if (!ctx) {
  10735. return;
  10736. }
  10737. mg_set_thread_name("master");
  10738. /* Increase priority of the master thread */
  10739. #if defined(_WIN32)
  10740. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  10741. #elif defined(USE_MASTER_THREAD_PRIORITY)
  10742. int min_prio = sched_get_priority_min(SCHED_RR);
  10743. int max_prio = sched_get_priority_max(SCHED_RR);
  10744. if ((min_prio >= 0) && (max_prio >= 0)
  10745. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  10746. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  10747. struct sched_param sched_param = {0};
  10748. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  10749. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  10750. }
  10751. #endif
  10752. /* Initialize thread local storage */
  10753. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10754. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  10755. #endif
  10756. tls.is_master = 1;
  10757. pthread_setspecific(sTlsKey, &tls);
  10758. /* Server starts *now* */
  10759. ctx->start_time = time(NULL);
  10760. /* Allocate memory for the listening sockets, and start the server */
  10761. pfd =
  10762. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  10763. while (pfd != NULL && ctx->stop_flag == 0) {
  10764. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10765. pfd[i].fd = ctx->listening_sockets[i].sock;
  10766. pfd[i].events = POLLIN;
  10767. }
  10768. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  10769. for (i = 0; i < ctx->num_listening_sockets; i++) {
  10770. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  10771. * successful poll, and POLLIN is defined as
  10772. * (POLLRDNORM | POLLRDBAND)
  10773. * Therefore, we're checking pfd[i].revents & POLLIN, not
  10774. * pfd[i].revents == POLLIN. */
  10775. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  10776. accept_new_connection(&ctx->listening_sockets[i], ctx);
  10777. }
  10778. }
  10779. }
  10780. }
  10781. mg_free(pfd);
  10782. DEBUG_TRACE("%s", "stopping workers");
  10783. /* Stop signal received: somebody called mg_stop. Quit. */
  10784. close_all_listening_sockets(ctx);
  10785. /* Wakeup workers that are waiting for connections to handle. */
  10786. pthread_cond_broadcast(&ctx->sq_full);
  10787. /* Wait until all threads finish */
  10788. (void)pthread_mutex_lock(&ctx->thread_mutex);
  10789. while (ctx->running_worker_threads > 0) {
  10790. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  10791. }
  10792. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  10793. /* Join all worker threads to avoid leaking threads. */
  10794. workerthreadcount = ctx->cfg_worker_threads;
  10795. for (i = 0; i < workerthreadcount; i++) {
  10796. if (ctx->workerthreadids[i] != 0) {
  10797. mg_join_thread(ctx->workerthreadids[i]);
  10798. }
  10799. }
  10800. #if !defined(NO_SSL)
  10801. if (ctx->ssl_ctx != NULL) {
  10802. uninitialize_ssl(ctx);
  10803. }
  10804. #endif
  10805. DEBUG_TRACE("%s", "exiting");
  10806. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10807. CloseHandle(tls.pthread_cond_helper_mutex);
  10808. #endif
  10809. pthread_setspecific(sTlsKey, NULL);
  10810. /* Signal mg_stop() that we're done.
  10811. * WARNING: This must be the very last thing this
  10812. * thread does, as ctx becomes invalid after this line. */
  10813. ctx->stop_flag = 2;
  10814. }
  10815. /* Threads have different return types on Windows and Unix. */
  10816. #ifdef _WIN32
  10817. static unsigned __stdcall master_thread(void *thread_func_param)
  10818. {
  10819. master_thread_run(thread_func_param);
  10820. return 0;
  10821. }
  10822. #else
  10823. static void *
  10824. master_thread(void *thread_func_param)
  10825. {
  10826. master_thread_run(thread_func_param);
  10827. return NULL;
  10828. }
  10829. #endif /* _WIN32 */
  10830. static void
  10831. free_context(struct mg_context *ctx)
  10832. {
  10833. int i;
  10834. struct mg_handler_info *tmp_rh;
  10835. if (ctx == NULL) {
  10836. return;
  10837. }
  10838. if (ctx->callbacks.exit_context) {
  10839. ctx->callbacks.exit_context(ctx);
  10840. }
  10841. /* All threads exited, no sync is needed. Destroy thread mutex and
  10842. * condvars
  10843. */
  10844. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  10845. (void)pthread_cond_destroy(&ctx->thread_cond);
  10846. (void)pthread_cond_destroy(&ctx->sq_empty);
  10847. (void)pthread_cond_destroy(&ctx->sq_full);
  10848. /* Destroy other context global data structures mutex */
  10849. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  10850. #if defined(USE_TIMERS)
  10851. timers_exit(ctx);
  10852. #endif
  10853. /* Deallocate config parameters */
  10854. for (i = 0; i < NUM_OPTIONS; i++) {
  10855. if (ctx->config[i] != NULL) {
  10856. #if defined(_MSC_VER)
  10857. #pragma warning(suppress : 6001)
  10858. #endif
  10859. mg_free(ctx->config[i]);
  10860. }
  10861. }
  10862. /* Deallocate request handlers */
  10863. while (ctx->handlers) {
  10864. tmp_rh = ctx->handlers;
  10865. ctx->handlers = tmp_rh->next;
  10866. mg_free(tmp_rh->uri);
  10867. mg_free(tmp_rh);
  10868. }
  10869. #ifndef NO_SSL
  10870. /* Deallocate SSL context */
  10871. if (ctx->ssl_ctx != NULL) {
  10872. SSL_CTX_free(ctx->ssl_ctx);
  10873. }
  10874. #endif /* !NO_SSL */
  10875. /* Deallocate worker thread ID array */
  10876. if (ctx->workerthreadids != NULL) {
  10877. mg_free(ctx->workerthreadids);
  10878. }
  10879. /* Deallocate the tls variable */
  10880. if (mg_atomic_dec(&sTlsInit) == 0) {
  10881. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10882. DeleteCriticalSection(&global_log_file_lock);
  10883. #endif /* _WIN32 && !__SYMBIAN32__ */
  10884. #if !defined(_WIN32)
  10885. pthread_mutexattr_destroy(&pthread_mutex_attr);
  10886. #endif
  10887. pthread_key_delete(sTlsKey);
  10888. }
  10889. /* deallocate system name string */
  10890. mg_free(ctx->systemName);
  10891. /* Deallocate context itself */
  10892. mg_free(ctx);
  10893. }
  10894. void
  10895. mg_stop(struct mg_context *ctx)
  10896. {
  10897. pthread_t mt;
  10898. if (!ctx) {
  10899. return;
  10900. }
  10901. /* We don't use a lock here. Calling mg_stop with the same ctx from
  10902. * two threads is not allowed. */
  10903. mt = ctx->masterthreadid;
  10904. if (mt == 0) {
  10905. return;
  10906. }
  10907. ctx->masterthreadid = 0;
  10908. ctx->stop_flag = 1;
  10909. /* Wait until mg_fini() stops */
  10910. while (ctx->stop_flag != 2) {
  10911. (void)mg_sleep(10);
  10912. }
  10913. mg_join_thread(mt);
  10914. free_context(ctx);
  10915. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10916. (void)WSACleanup();
  10917. #endif /* _WIN32 && !__SYMBIAN32__ */
  10918. }
  10919. static void
  10920. get_system_name(char **sysName)
  10921. {
  10922. #if defined(_WIN32)
  10923. #if !defined(__SYMBIAN32__)
  10924. char name[128];
  10925. DWORD dwVersion = 0;
  10926. DWORD dwMajorVersion = 0;
  10927. DWORD dwMinorVersion = 0;
  10928. DWORD dwBuild = 0;
  10929. #ifdef _MSC_VER
  10930. #pragma warning(push)
  10931. // GetVersion was declared deprecated
  10932. #pragma warning(disable : 4996)
  10933. #endif
  10934. dwVersion = GetVersion();
  10935. #ifdef _MSC_VER
  10936. #pragma warning(pop)
  10937. #endif
  10938. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  10939. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  10940. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  10941. (void)dwBuild;
  10942. sprintf(name,
  10943. "Windows %u.%u",
  10944. (unsigned)dwMajorVersion,
  10945. (unsigned)dwMinorVersion);
  10946. *sysName = mg_strdup(name);
  10947. #else
  10948. *sysName = mg_strdup("Symbian");
  10949. #endif
  10950. #else
  10951. struct utsname name;
  10952. memset(&name, 0, sizeof(name));
  10953. uname(&name);
  10954. *sysName = mg_strdup(name.sysname);
  10955. #endif
  10956. }
  10957. struct mg_context *
  10958. mg_start(const struct mg_callbacks *callbacks,
  10959. void *user_data,
  10960. const char **options)
  10961. {
  10962. struct mg_context *ctx;
  10963. const char *name, *value, *default_value;
  10964. int idx, ok, workerthreadcount;
  10965. unsigned int i;
  10966. void (*exit_callback)(const struct mg_context *ctx) = 0;
  10967. struct mg_workerTLS tls;
  10968. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10969. WSADATA data;
  10970. WSAStartup(MAKEWORD(2, 2), &data);
  10971. #endif /* _WIN32 && !__SYMBIAN32__ */
  10972. /* Allocate context and initialize reasonable general case defaults. */
  10973. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  10974. return NULL;
  10975. }
  10976. /* Random number generator will initialize at the first call */
  10977. ctx->auth_nonce_mask =
  10978. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  10979. if (mg_atomic_inc(&sTlsInit) == 1) {
  10980. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  10981. InitializeCriticalSection(&global_log_file_lock);
  10982. #endif /* _WIN32 && !__SYMBIAN32__ */
  10983. #if !defined(_WIN32)
  10984. pthread_mutexattr_init(&pthread_mutex_attr);
  10985. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  10986. #endif
  10987. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  10988. /* Fatal error - abort start. However, this situation should
  10989. * never
  10990. * occur in practice. */
  10991. mg_atomic_dec(&sTlsInit);
  10992. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  10993. mg_free(ctx);
  10994. return NULL;
  10995. }
  10996. } else {
  10997. /* TODO (low): istead of sleeping, check if sTlsKey is already
  10998. * initialized. */
  10999. mg_sleep(1);
  11000. }
  11001. tls.is_master = -1;
  11002. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11003. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11004. tls.pthread_cond_helper_mutex = NULL;
  11005. #endif
  11006. pthread_setspecific(sTlsKey, &tls);
  11007. #if defined(USE_LUA)
  11008. lua_init_optional_libraries();
  11009. #endif
  11010. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  11011. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  11012. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  11013. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  11014. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  11015. if (!ok) {
  11016. /* Fatal error - abort start. However, this situation should never
  11017. * occur in practice. */
  11018. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  11019. mg_free(ctx);
  11020. pthread_setspecific(sTlsKey, NULL);
  11021. return NULL;
  11022. }
  11023. if (callbacks) {
  11024. ctx->callbacks = *callbacks;
  11025. exit_callback = callbacks->exit_context;
  11026. ctx->callbacks.exit_context = 0;
  11027. }
  11028. ctx->user_data = user_data;
  11029. ctx->handlers = NULL;
  11030. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  11031. ctx->shared_lua_websockets = 0;
  11032. #endif
  11033. while (options && (name = *options++) != NULL) {
  11034. if ((idx = get_option_index(name)) == -1) {
  11035. mg_cry(fc(ctx), "Invalid option: %s", name);
  11036. free_context(ctx);
  11037. pthread_setspecific(sTlsKey, NULL);
  11038. return NULL;
  11039. } else if ((value = *options++) == NULL) {
  11040. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  11041. free_context(ctx);
  11042. pthread_setspecific(sTlsKey, NULL);
  11043. return NULL;
  11044. }
  11045. if (ctx->config[idx] != NULL) {
  11046. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  11047. mg_free(ctx->config[idx]);
  11048. }
  11049. ctx->config[idx] = mg_strdup(value);
  11050. DEBUG_TRACE("[%s] -> [%s]", name, value);
  11051. }
  11052. /* Set default value if needed */
  11053. for (i = 0; config_options[i].name != NULL; i++) {
  11054. default_value = config_options[i].default_value;
  11055. if (ctx->config[i] == NULL && default_value != NULL) {
  11056. ctx->config[i] = mg_strdup(default_value);
  11057. }
  11058. }
  11059. #if defined(NO_FILES)
  11060. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  11061. mg_cry(fc(ctx), "%s", "Document root must not be set");
  11062. free_context(ctx);
  11063. pthread_setspecific(sTlsKey, NULL);
  11064. return NULL;
  11065. }
  11066. #endif
  11067. get_system_name(&ctx->systemName);
  11068. /* NOTE(lsm): order is important here. SSL certificates must
  11069. * be initialized before listening ports. UID must be set last. */
  11070. if (!set_gpass_option(ctx) ||
  11071. #if !defined(NO_SSL)
  11072. !set_ssl_option(ctx) ||
  11073. #endif
  11074. !set_ports_option(ctx) ||
  11075. #if !defined(_WIN32)
  11076. !set_uid_option(ctx) ||
  11077. #endif
  11078. !set_acl_option(ctx)) {
  11079. free_context(ctx);
  11080. pthread_setspecific(sTlsKey, NULL);
  11081. return NULL;
  11082. }
  11083. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  11084. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  11085. * won't kill the whole process. */
  11086. (void)signal(SIGPIPE, SIG_IGN);
  11087. #endif /* !_WIN32 && !__SYMBIAN32__ */
  11088. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  11089. if (workerthreadcount > MAX_WORKER_THREADS) {
  11090. mg_cry(fc(ctx), "Too many worker threads");
  11091. free_context(ctx);
  11092. pthread_setspecific(sTlsKey, NULL);
  11093. return NULL;
  11094. }
  11095. if (workerthreadcount > 0) {
  11096. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  11097. ctx->workerthreadids =
  11098. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  11099. if (ctx->workerthreadids == NULL) {
  11100. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  11101. free_context(ctx);
  11102. pthread_setspecific(sTlsKey, NULL);
  11103. return NULL;
  11104. }
  11105. }
  11106. #if defined(USE_TIMERS)
  11107. if (timers_init(ctx) != 0) {
  11108. mg_cry(fc(ctx), "Error creating timers");
  11109. free_context(ctx);
  11110. pthread_setspecific(sTlsKey, NULL);
  11111. return NULL;
  11112. }
  11113. #endif
  11114. /* Context has been created - init user libraries */
  11115. if (ctx->callbacks.init_context) {
  11116. ctx->callbacks.init_context(ctx);
  11117. }
  11118. ctx->callbacks.exit_context = exit_callback;
  11119. ctx->context_type = 1; /* server context */
  11120. /* Start master (listening) thread */
  11121. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  11122. /* Start worker threads */
  11123. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11124. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11125. ctx->running_worker_threads++;
  11126. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11127. if (mg_start_thread_with_id(worker_thread,
  11128. ctx,
  11129. &ctx->workerthreadids[i]) != 0) {
  11130. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11131. ctx->running_worker_threads--;
  11132. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11133. if (i > 0) {
  11134. mg_cry(fc(ctx),
  11135. "Cannot start worker thread %i: error %ld",
  11136. i + 1,
  11137. (long)ERRNO);
  11138. } else {
  11139. mg_cry(fc(ctx),
  11140. "Cannot create threads: error %ld",
  11141. (long)ERRNO);
  11142. free_context(ctx);
  11143. pthread_setspecific(sTlsKey, NULL);
  11144. return NULL;
  11145. }
  11146. break;
  11147. }
  11148. }
  11149. pthread_setspecific(sTlsKey, NULL);
  11150. return ctx;
  11151. }
  11152. /* Feature check API function */
  11153. unsigned
  11154. mg_check_feature(unsigned feature)
  11155. {
  11156. static const unsigned feature_set = 0
  11157. /* Set bits for available features according to API documentation.
  11158. * This bit mask is created at compile time, according to the active
  11159. * preprocessor defines. It is a single const value at runtime. */
  11160. #if !defined(NO_FILES)
  11161. | 1
  11162. #endif
  11163. #if !defined(NO_SSL)
  11164. | 2
  11165. #endif
  11166. #if !defined(NO_CGI)
  11167. | 4
  11168. #endif
  11169. #if defined(USE_IPV6)
  11170. | 8
  11171. #endif
  11172. #if defined(USE_WEBSOCKET)
  11173. | 16
  11174. #endif
  11175. #if defined(USE_LUA)
  11176. | 32
  11177. #endif
  11178. #if defined(USE_DUKTAPE)
  11179. | 64
  11180. #endif
  11181. /* Set some extra bits not defined in the API documentation.
  11182. * These bits may change without further notice. */
  11183. #if defined(MG_LEGACY_INTERFACE)
  11184. | 128
  11185. #endif
  11186. #if defined(MEMORY_DEBUGGING)
  11187. | 256
  11188. #endif
  11189. #if defined(USE_TIMERS)
  11190. | 512
  11191. #endif
  11192. #if !defined(NO_NONCE_CHECK)
  11193. | 1024
  11194. #endif
  11195. #if !defined(NO_POPEN)
  11196. | 2048
  11197. #endif
  11198. ;
  11199. return (feature & feature_set);
  11200. }