civetweb.c 376 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386
  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. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __clang__
  114. /* When using -Weverything, clang does not accept it's own headers
  115. * in a release build configuration. Disable what is too much in
  116. * -Weverything. */
  117. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  118. #endif
  119. #ifdef __MACH__ /* Apple OSX section */
  120. #ifdef __clang__
  121. /* Avoid warnings for Xopen 7.00 and higher */
  122. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  123. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  124. #endif
  125. #define CLOCK_MONOTONIC (1)
  126. #define CLOCK_REALTIME (2)
  127. #include <sys/errno.h>
  128. #include <sys/time.h>
  129. #include <mach/clock.h>
  130. #include <mach/mach.h>
  131. #include <mach/mach_time.h>
  132. #include <assert.h>
  133. /* clock_gettime is not implemented on OSX prior to 10.12 */
  134. static int
  135. _civet_clock_gettime(int clk_id, struct timespec *t)
  136. {
  137. memset(t, 0, sizeof(*t));
  138. if (clk_id == CLOCK_REALTIME) {
  139. struct timeval now;
  140. int rv = gettimeofday(&now, NULL);
  141. if (rv) {
  142. return rv;
  143. }
  144. t->tv_sec = now.tv_sec;
  145. t->tv_nsec = now.tv_usec * 1000;
  146. return 0;
  147. } else if (clk_id == CLOCK_MONOTONIC) {
  148. static uint64_t clock_start_time = 0;
  149. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  150. uint64_t now = mach_absolute_time();
  151. if (clock_start_time == 0) {
  152. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  153. #if defined(DEBUG)
  154. assert(mach_status == KERN_SUCCESS);
  155. #else
  156. /* appease "unused variable" warning for release builds */
  157. (void)mach_status;
  158. #endif
  159. clock_start_time = now;
  160. }
  161. now = (uint64_t)((double)(now - clock_start_time)
  162. * (double)timebase_ifo.numer
  163. / (double)timebase_ifo.denom);
  164. t->tv_sec = now / 1000000000;
  165. t->tv_nsec = now % 1000000000;
  166. return 0;
  167. }
  168. return -1; /* EINVAL - Clock ID is unknown */
  169. }
  170. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  171. #ifdef __CLOCK_AVAILABILITY
  172. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  173. * declared but it may be NULL at runtime. So we need to check before using
  174. * it. */
  175. static int
  176. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  177. {
  178. if (clock_gettime) {
  179. return clock_gettime(clk_id, t);
  180. }
  181. return _civet_clock_gettime(clk_id, t);
  182. }
  183. #define clock_gettime _civet_safe_clock_gettime
  184. #else
  185. #define clock_gettime _civet_clock_gettime
  186. #endif
  187. #endif
  188. #include <time.h>
  189. #include <stdlib.h>
  190. #include <stdarg.h>
  191. #include <assert.h>
  192. #include <string.h>
  193. #include <ctype.h>
  194. #include <limits.h>
  195. #include <stddef.h>
  196. #include <stdio.h>
  197. #include <stdint.h>
  198. #ifndef INT64_MAX
  199. #define INT64_MAX (9223372036854775807)
  200. #endif
  201. #ifndef MAX_WORKER_THREADS
  202. #define MAX_WORKER_THREADS (1024 * 64)
  203. #endif
  204. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  205. #define SOCKET_TIMEOUT_QUANTUM (2000)
  206. #endif
  207. #define SHUTDOWN_RD (0)
  208. #define SHUTDOWN_WR (1)
  209. #define SHUTDOWN_BOTH (2)
  210. mg_static_assert(MAX_WORKER_THREADS >= 1,
  211. "worker threads must be a positive number");
  212. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  213. "size_t data type size check");
  214. #if defined(_WIN32) \
  215. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  216. #include <windows.h>
  217. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  218. #include <ws2tcpip.h>
  219. typedef const char *SOCK_OPT_TYPE;
  220. #if !defined(PATH_MAX)
  221. #define PATH_MAX (MAX_PATH)
  222. #endif
  223. #if !defined(PATH_MAX)
  224. #define PATH_MAX (4096)
  225. #endif
  226. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  227. #ifndef _IN_PORT_T
  228. #ifndef in_port_t
  229. #define in_port_t u_short
  230. #endif
  231. #endif
  232. #ifndef _WIN32_WCE
  233. #include <process.h>
  234. #include <direct.h>
  235. #include <io.h>
  236. #else /* _WIN32_WCE */
  237. #define NO_CGI /* WinCE has no pipes */
  238. #define NO_POPEN /* WinCE has no popen */
  239. typedef long off_t;
  240. #define errno ((int)(GetLastError()))
  241. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  242. #endif /* _WIN32_WCE */
  243. #define MAKEUQUAD(lo, hi) \
  244. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  245. #define RATE_DIFF (10000000) /* 100 nsecs */
  246. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  247. #define SYS2UNIX_TIME(lo, hi) \
  248. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  249. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  250. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  251. * Also use _strtoui64 on modern M$ compilers */
  252. #if defined(_MSC_VER)
  253. #if (_MSC_VER < 1300)
  254. #define STRX(x) #x
  255. #define STR(x) STRX(x)
  256. #define __func__ __FILE__ ":" STR(__LINE__)
  257. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  258. #define strtoll(x, y, z) (_atoi64(x))
  259. #else
  260. #define __func__ __FUNCTION__
  261. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  262. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  263. #endif
  264. #endif /* _MSC_VER */
  265. #define ERRNO ((int)(GetLastError()))
  266. #define NO_SOCKLEN_T
  267. #if defined(_WIN64) || defined(__MINGW64__)
  268. #define SSL_LIB "ssleay64.dll"
  269. #define CRYPTO_LIB "libeay64.dll"
  270. #else
  271. #define SSL_LIB "ssleay32.dll"
  272. #define CRYPTO_LIB "libeay32.dll"
  273. #endif
  274. #define O_NONBLOCK (0)
  275. #ifndef W_OK
  276. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  277. #endif
  278. #if !defined(EWOULDBLOCK)
  279. #define EWOULDBLOCK WSAEWOULDBLOCK
  280. #endif /* !EWOULDBLOCK */
  281. #define _POSIX_
  282. #define INT64_FMT "I64d"
  283. #define UINT64_FMT "I64u"
  284. #define WINCDECL __cdecl
  285. #define vsnprintf_impl _vsnprintf
  286. #define access _access
  287. #define mg_sleep(x) (Sleep(x))
  288. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  289. #ifndef popen
  290. #define popen(x, y) (_popen(x, y))
  291. #endif
  292. #ifndef pclose
  293. #define pclose(x) (_pclose(x))
  294. #endif
  295. #define close(x) (_close(x))
  296. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  297. #define RTLD_LAZY (0)
  298. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  299. #define fdopen(x, y) (_fdopen((x), (y)))
  300. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  301. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  302. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  303. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  304. #define sleep(x) (Sleep((x)*1000))
  305. #define rmdir(x) (_rmdir(x))
  306. #define timegm(x) (_mkgmtime(x))
  307. #if !defined(fileno)
  308. #define fileno(x) (_fileno(x))
  309. #endif /* !fileno MINGW #defines fileno */
  310. typedef HANDLE pthread_mutex_t;
  311. typedef DWORD pthread_key_t;
  312. typedef HANDLE pthread_t;
  313. typedef struct {
  314. CRITICAL_SECTION threadIdSec;
  315. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  316. } pthread_cond_t;
  317. #ifndef __clockid_t_defined
  318. typedef DWORD clockid_t;
  319. #endif
  320. #ifndef CLOCK_MONOTONIC
  321. #define CLOCK_MONOTONIC (1)
  322. #endif
  323. #ifndef CLOCK_REALTIME
  324. #define CLOCK_REALTIME (2)
  325. #endif
  326. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  327. #define _TIMESPEC_DEFINED
  328. #endif
  329. #ifndef _TIMESPEC_DEFINED
  330. struct timespec {
  331. time_t tv_sec; /* seconds */
  332. long tv_nsec; /* nanoseconds */
  333. };
  334. #endif
  335. #if !defined(WIN_PTHREADS_TIME_H)
  336. #define MUST_IMPLEMENT_CLOCK_GETTIME
  337. #endif
  338. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  339. #define clock_gettime mg_clock_gettime
  340. static int
  341. clock_gettime(clockid_t clk_id, struct timespec *tp)
  342. {
  343. FILETIME ft;
  344. ULARGE_INTEGER li;
  345. BOOL ok = FALSE;
  346. double d;
  347. static double perfcnt_per_sec = 0.0;
  348. if (tp) {
  349. memset(tp, 0, sizeof(*tp));
  350. if (clk_id == CLOCK_REALTIME) {
  351. GetSystemTimeAsFileTime(&ft);
  352. li.LowPart = ft.dwLowDateTime;
  353. li.HighPart = ft.dwHighDateTime;
  354. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  355. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  356. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  357. ok = TRUE;
  358. } else if (clk_id == CLOCK_MONOTONIC) {
  359. if (perfcnt_per_sec == 0.0) {
  360. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  361. perfcnt_per_sec = 1.0 / li.QuadPart;
  362. }
  363. if (perfcnt_per_sec != 0.0) {
  364. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  365. d = li.QuadPart * perfcnt_per_sec;
  366. tp->tv_sec = (time_t)d;
  367. d -= tp->tv_sec;
  368. tp->tv_nsec = (long)(d * 1.0E9);
  369. ok = TRUE;
  370. }
  371. }
  372. }
  373. return ok ? 0 : -1;
  374. }
  375. #endif
  376. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  377. static int pthread_mutex_lock(pthread_mutex_t *);
  378. static int pthread_mutex_unlock(pthread_mutex_t *);
  379. static void path_to_unicode(const struct mg_connection *conn,
  380. const char *path,
  381. wchar_t *wbuf,
  382. size_t wbuf_len);
  383. /* All file operations need to be rewritten to solve #246. */
  384. #include "file_ops.inl"
  385. struct mg_file;
  386. static const char *
  387. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  388. /* POSIX dirent interface */
  389. struct dirent {
  390. char d_name[PATH_MAX];
  391. };
  392. typedef struct DIR {
  393. HANDLE handle;
  394. WIN32_FIND_DATAW info;
  395. struct dirent result;
  396. } DIR;
  397. #if defined(_WIN32) && !defined(POLLIN)
  398. #ifndef HAVE_POLL
  399. struct pollfd {
  400. SOCKET fd;
  401. short events;
  402. short revents;
  403. };
  404. #define POLLIN (0x0300)
  405. #endif
  406. #endif
  407. /* Mark required libraries */
  408. #if defined(_MSC_VER)
  409. #pragma comment(lib, "Ws2_32.lib")
  410. #endif
  411. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  412. WINDOWS / UNIX include block */
  413. #include <sys/wait.h>
  414. #include <sys/socket.h>
  415. #include <sys/poll.h>
  416. #include <netinet/in.h>
  417. #include <arpa/inet.h>
  418. #include <sys/time.h>
  419. #include <sys/utsname.h>
  420. #include <stdint.h>
  421. #include <inttypes.h>
  422. #include <netdb.h>
  423. #include <netinet/tcp.h>
  424. typedef const void *SOCK_OPT_TYPE;
  425. #if defined(ANDROID)
  426. typedef unsigned short int in_port_t;
  427. #endif
  428. #include <pwd.h>
  429. #include <unistd.h>
  430. #include <grp.h>
  431. #include <dirent.h>
  432. #define vsnprintf_impl vsnprintf
  433. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  434. #include <dlfcn.h>
  435. #endif
  436. #include <pthread.h>
  437. #if defined(__MACH__)
  438. #define SSL_LIB "libssl.dylib"
  439. #define CRYPTO_LIB "libcrypto.dylib"
  440. #else
  441. #if !defined(SSL_LIB)
  442. #define SSL_LIB "libssl.so"
  443. #endif
  444. #if !defined(CRYPTO_LIB)
  445. #define CRYPTO_LIB "libcrypto.so"
  446. #endif
  447. #endif
  448. #ifndef O_BINARY
  449. #define O_BINARY (0)
  450. #endif /* O_BINARY */
  451. #define closesocket(a) (close(a))
  452. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  453. #define mg_remove(conn, x) (remove(x))
  454. #define mg_sleep(x) (usleep((x)*1000))
  455. #define mg_opendir(conn, x) (opendir(x))
  456. #define mg_closedir(x) (closedir(x))
  457. #define mg_readdir(x) (readdir(x))
  458. #define ERRNO (errno)
  459. #define INVALID_SOCKET (-1)
  460. #define INT64_FMT PRId64
  461. #define UINT64_FMT PRIu64
  462. typedef int SOCKET;
  463. #define WINCDECL
  464. #if defined(__hpux)
  465. /* HPUX 11 does not have monotonic, fall back to realtime */
  466. #ifndef CLOCK_MONOTONIC
  467. #define CLOCK_MONOTONIC CLOCK_REALTIME
  468. #endif
  469. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  470. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  471. * the prototypes use int* rather than socklen_t* which matches the
  472. * actual library expectation. When called with the wrong size arg
  473. * accept() returns a zero client inet addr and check_acl() always
  474. * fails. Since socklen_t is widely used below, just force replace
  475. * their typedef with int. - DTL
  476. */
  477. #define socklen_t int
  478. #endif /* hpux */
  479. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  480. WINDOWS / UNIX include block */
  481. /* va_copy should always be a macro, C99 and C++11 - DTL */
  482. #ifndef va_copy
  483. #define va_copy(x, y) ((x) = (y))
  484. #endif
  485. #ifdef _WIN32
  486. /* Create substitutes for POSIX functions in Win32. */
  487. #if defined(__MINGW32__)
  488. /* Show no warning in case system functions are not used. */
  489. #pragma GCC diagnostic push
  490. #pragma GCC diagnostic ignored "-Wunused-function"
  491. #endif
  492. static CRITICAL_SECTION global_log_file_lock;
  493. static DWORD
  494. pthread_self(void)
  495. {
  496. return GetCurrentThreadId();
  497. }
  498. static int
  499. pthread_key_create(
  500. pthread_key_t *key,
  501. void (*_ignored)(void *) /* destructor not supported for Windows */
  502. )
  503. {
  504. (void)_ignored;
  505. if ((key != 0)) {
  506. *key = TlsAlloc();
  507. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  508. }
  509. return -2;
  510. }
  511. static int
  512. pthread_key_delete(pthread_key_t key)
  513. {
  514. return TlsFree(key) ? 0 : 1;
  515. }
  516. static int
  517. pthread_setspecific(pthread_key_t key, void *value)
  518. {
  519. return TlsSetValue(key, value) ? 0 : 1;
  520. }
  521. static void *
  522. pthread_getspecific(pthread_key_t key)
  523. {
  524. return TlsGetValue(key);
  525. }
  526. #if defined(__MINGW32__)
  527. /* Enable unused function warning again */
  528. #pragma GCC diagnostic pop
  529. #endif
  530. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  531. #else
  532. static pthread_mutexattr_t pthread_mutex_attr;
  533. #endif /* _WIN32 */
  534. #define PASSWORDS_FILE_NAME ".htpasswd"
  535. #define CGI_ENVIRONMENT_SIZE (4096)
  536. #define MAX_CGI_ENVIR_VARS (256)
  537. #define MG_BUF_LEN (8192)
  538. #ifndef MAX_REQUEST_SIZE
  539. #define MAX_REQUEST_SIZE (16384)
  540. #endif
  541. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  542. "request size length must be a positive number");
  543. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  544. #if defined(_WIN32_WCE)
  545. /* Create substitutes for POSIX functions in Win32. */
  546. #if defined(__MINGW32__)
  547. /* Show no warning in case system functions are not used. */
  548. #pragma GCC diagnostic push
  549. #pragma GCC diagnostic ignored "-Wunused-function"
  550. #endif
  551. static time_t
  552. time(time_t *ptime)
  553. {
  554. time_t t;
  555. SYSTEMTIME st;
  556. FILETIME ft;
  557. GetSystemTime(&st);
  558. SystemTimeToFileTime(&st, &ft);
  559. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  560. if (ptime != NULL) {
  561. *ptime = t;
  562. }
  563. return t;
  564. }
  565. static struct tm *
  566. localtime_s(const time_t *ptime, struct tm *ptm)
  567. {
  568. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  569. FILETIME ft, lft;
  570. SYSTEMTIME st;
  571. TIME_ZONE_INFORMATION tzinfo;
  572. if (ptm == NULL) {
  573. return NULL;
  574. }
  575. *(int64_t *)&ft = t;
  576. FileTimeToLocalFileTime(&ft, &lft);
  577. FileTimeToSystemTime(&lft, &st);
  578. ptm->tm_year = st.wYear - 1900;
  579. ptm->tm_mon = st.wMonth - 1;
  580. ptm->tm_wday = st.wDayOfWeek;
  581. ptm->tm_mday = st.wDay;
  582. ptm->tm_hour = st.wHour;
  583. ptm->tm_min = st.wMinute;
  584. ptm->tm_sec = st.wSecond;
  585. ptm->tm_yday = 0; /* hope nobody uses this */
  586. ptm->tm_isdst =
  587. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  588. return ptm;
  589. }
  590. static struct tm *
  591. gmtime_s(const time_t *ptime, struct tm *ptm)
  592. {
  593. /* FIXME(lsm): fix this. */
  594. return localtime_s(ptime, ptm);
  595. }
  596. static int mg_atomic_inc(volatile int *addr);
  597. static struct tm tm_array[MAX_WORKER_THREADS];
  598. static int tm_index = 0;
  599. static struct tm *
  600. localtime(const time_t *ptime)
  601. {
  602. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  603. return localtime_s(ptime, tm_array + i);
  604. }
  605. static struct tm *
  606. gmtime(const time_t *ptime)
  607. {
  608. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  609. return gmtime_s(ptime, tm_array + i);
  610. }
  611. static size_t
  612. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  613. {
  614. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  615. // for WinCE");
  616. return 0;
  617. }
  618. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  619. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  620. #define remove(f) mg_remove(NULL, f)
  621. static int
  622. rename(const char *a, const char *b)
  623. {
  624. wchar_t wa[PATH_MAX];
  625. wchar_t wb[PATH_MAX];
  626. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  627. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  628. return MoveFileW(wa, wb) ? 0 : -1;
  629. }
  630. struct stat {
  631. int64_t st_size;
  632. time_t st_mtime;
  633. };
  634. static int
  635. stat(const char *name, struct stat *st)
  636. {
  637. wchar_t wbuf[PATH_MAX];
  638. WIN32_FILE_ATTRIBUTE_DATA attr;
  639. time_t creation_time, write_time;
  640. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  641. memset(&attr, 0, sizeof(attr));
  642. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  643. st->st_size =
  644. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  645. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  646. attr.ftLastWriteTime.dwHighDateTime);
  647. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  648. attr.ftCreationTime.dwHighDateTime);
  649. if (creation_time > write_time) {
  650. st->st_mtime = creation_time;
  651. } else {
  652. st->st_mtime = write_time;
  653. }
  654. return 0;
  655. }
  656. #define access(x, a) 1 /* not required anyway */
  657. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  658. #define EEXIST 1 /* TODO: See Windows error codes */
  659. #define EACCES 2 /* TODO: See Windows error codes */
  660. #define ENOENT 3 /* TODO: See Windows Error codes */
  661. #if defined(__MINGW32__)
  662. /* Enable unused function warning again */
  663. #pragma GCC diagnostic pop
  664. #endif
  665. #endif /* defined(_WIN32_WCE) */
  666. #if defined(__GNUC__)
  667. /* Show no warning in case system functions are not used. */
  668. #pragma GCC diagnostic push
  669. #pragma GCC diagnostic ignored "-Wunused-function"
  670. #endif
  671. #if defined(__clang__)
  672. /* Show no warning in case system functions are not used. */
  673. #pragma clang diagnostic push
  674. #pragma clang diagnostic ignored "-Wunused-function"
  675. #endif
  676. /* Get a unique thread ID as unsigned long, independent from the data type
  677. * of thread IDs defined by the operating system API.
  678. * If two calls to mg_current_thread_id return the same value, they calls
  679. * are done from the same thread. If they return different values, they are
  680. * done from different threads. (Provided this function is used in the same
  681. * process context and threads are not repeatedly created and deleted, but
  682. * CivetWeb does not do that).
  683. * This function must match the signature required for SSL id callbacks:
  684. * CRYPTO_set_id_callback
  685. */
  686. static unsigned long
  687. mg_current_thread_id(void)
  688. {
  689. #ifdef _WIN32
  690. return GetCurrentThreadId();
  691. #else
  692. #ifdef __clang__
  693. #pragma clang diagnostic push
  694. #pragma clang diagnostic ignored "-Wunreachable-code"
  695. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  696. * or not, so one of the two conditions will be unreachable by construction.
  697. * Unfortunately the C standard does not define a way to check this at
  698. * compile time, since the #if preprocessor conditions can not use the sizeof
  699. * operator as an argument. */
  700. #endif
  701. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  702. /* This is the problematic case for CRYPTO_set_id_callback:
  703. * The OS pthread_t can not be cast to unsigned long. */
  704. struct mg_workerTLS *tls =
  705. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  706. if (tls == NULL) {
  707. /* SSL called from an unknown thread: Create some thread index.
  708. */
  709. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  710. tls->is_master = -2; /* -2 means "3rd party thread" */
  711. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  712. pthread_setspecific(sTlsKey, tls);
  713. }
  714. return tls->thread_idx;
  715. } else {
  716. /* pthread_t may be any data type, so a simple cast to unsigned long
  717. * can rise a warning/error, depending on the platform.
  718. * Here memcpy is used as an anything-to-anything cast. */
  719. unsigned long ret = 0;
  720. pthread_t t = pthread_self();
  721. memcpy(&ret, &t, sizeof(pthread_t));
  722. return ret;
  723. }
  724. #ifdef __clang__
  725. #pragma clang diagnostic pop
  726. #endif
  727. #endif
  728. }
  729. #if defined(__GNUC__)
  730. /* Show no warning in case system functions are not used. */
  731. #pragma GCC diagnostic pop
  732. #endif
  733. #if defined(__clang__)
  734. /* Show no warning in case system functions are not used. */
  735. #pragma clang diagnostic pop
  736. #endif
  737. #if !defined(DEBUG_TRACE)
  738. #if defined(DEBUG)
  739. static void DEBUG_TRACE_FUNC(const char *func,
  740. unsigned line,
  741. PRINTF_FORMAT_STRING(const char *fmt),
  742. ...) PRINTF_ARGS(3, 4);
  743. static void
  744. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  745. {
  746. va_list args;
  747. struct timespec tsnow;
  748. uint64_t nsnow;
  749. static uint64_t nslast;
  750. /* Get some operating system independent thread id */
  751. unsigned long thread_id = mg_current_thread_id();
  752. clock_gettime(CLOCK_REALTIME, &tsnow);
  753. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  754. flockfile(stdout);
  755. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  756. (unsigned long)tsnow.tv_sec,
  757. (unsigned long)tsnow.tv_nsec,
  758. nsnow - nslast,
  759. thread_id,
  760. func,
  761. line);
  762. va_start(args, fmt);
  763. vprintf(fmt, args);
  764. va_end(args);
  765. putchar('\n');
  766. fflush(stdout);
  767. funlockfile(stdout);
  768. nslast = nsnow;
  769. }
  770. #define DEBUG_TRACE(fmt, ...) \
  771. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  772. #else
  773. #define DEBUG_TRACE(fmt, ...) \
  774. do { \
  775. } while (0)
  776. #endif /* DEBUG */
  777. #endif /* DEBUG_TRACE */
  778. #if defined(MEMORY_DEBUGGING)
  779. static unsigned long mg_memory_debug_blockCount = 0;
  780. static unsigned long mg_memory_debug_totalMemUsed = 0;
  781. static void *
  782. mg_malloc_ex(size_t size, const char *file, unsigned line)
  783. {
  784. void *data = malloc(size + sizeof(size_t));
  785. void *memory = 0;
  786. char mallocStr[256];
  787. if (data) {
  788. *(size_t *)data = size;
  789. mg_memory_debug_totalMemUsed += size;
  790. mg_memory_debug_blockCount++;
  791. memory = (void *)(((char *)data) + sizeof(size_t));
  792. }
  793. sprintf(mallocStr,
  794. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  795. memory,
  796. (unsigned long)size,
  797. mg_memory_debug_totalMemUsed,
  798. mg_memory_debug_blockCount,
  799. file,
  800. line);
  801. #if defined(_WIN32)
  802. OutputDebugStringA(mallocStr);
  803. #else
  804. DEBUG_TRACE("%s", mallocStr);
  805. #endif
  806. return memory;
  807. }
  808. static void *
  809. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  810. {
  811. void *data = mg_malloc_ex(size * count, file, line);
  812. if (data) {
  813. memset(data, 0, size * count);
  814. }
  815. return data;
  816. }
  817. static void
  818. mg_free_ex(void *memory, const char *file, unsigned line)
  819. {
  820. char mallocStr[256];
  821. void *data = (void *)(((char *)memory) - sizeof(size_t));
  822. size_t size;
  823. if (memory) {
  824. size = *(size_t *)data;
  825. mg_memory_debug_totalMemUsed -= size;
  826. mg_memory_debug_blockCount--;
  827. sprintf(mallocStr,
  828. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  829. memory,
  830. (unsigned long)size,
  831. mg_memory_debug_totalMemUsed,
  832. mg_memory_debug_blockCount,
  833. file,
  834. line);
  835. #if defined(_WIN32)
  836. OutputDebugStringA(mallocStr);
  837. #else
  838. DEBUG_TRACE("%s", mallocStr);
  839. #endif
  840. free(data);
  841. }
  842. }
  843. static void *
  844. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  845. {
  846. char mallocStr[256];
  847. void *data;
  848. void *_realloc;
  849. size_t oldsize;
  850. if (newsize) {
  851. if (memory) {
  852. data = (void *)(((char *)memory) - sizeof(size_t));
  853. oldsize = *(size_t *)data;
  854. _realloc = realloc(data, newsize + sizeof(size_t));
  855. if (_realloc) {
  856. data = _realloc;
  857. mg_memory_debug_totalMemUsed -= oldsize;
  858. sprintf(mallocStr,
  859. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  860. memory,
  861. (unsigned long)oldsize,
  862. mg_memory_debug_totalMemUsed,
  863. mg_memory_debug_blockCount,
  864. file,
  865. line);
  866. #if defined(_WIN32)
  867. OutputDebugStringA(mallocStr);
  868. #else
  869. DEBUG_TRACE("%s", mallocStr);
  870. #endif
  871. mg_memory_debug_totalMemUsed += newsize;
  872. sprintf(mallocStr,
  873. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  874. memory,
  875. (unsigned long)newsize,
  876. mg_memory_debug_totalMemUsed,
  877. mg_memory_debug_blockCount,
  878. file,
  879. line);
  880. #if defined(_WIN32)
  881. OutputDebugStringA(mallocStr);
  882. #else
  883. DEBUG_TRACE("%s", mallocStr);
  884. #endif
  885. *(size_t *)data = newsize;
  886. data = (void *)(((char *)data) + sizeof(size_t));
  887. } else {
  888. #if defined(_WIN32)
  889. OutputDebugStringA("MEM: realloc failed\n");
  890. #else
  891. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  892. #endif
  893. return _realloc;
  894. }
  895. } else {
  896. data = mg_malloc_ex(newsize, file, line);
  897. }
  898. } else {
  899. data = 0;
  900. mg_free_ex(memory, file, line);
  901. }
  902. return data;
  903. }
  904. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  905. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  906. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  907. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  908. #else
  909. static __inline void *
  910. mg_malloc(size_t a)
  911. {
  912. return malloc(a);
  913. }
  914. static __inline void *
  915. mg_calloc(size_t a, size_t b)
  916. {
  917. return calloc(a, b);
  918. }
  919. static __inline void *
  920. mg_realloc(void *a, size_t b)
  921. {
  922. return realloc(a, b);
  923. }
  924. static __inline void
  925. mg_free(void *a)
  926. {
  927. free(a);
  928. }
  929. #endif
  930. static void mg_vsnprintf(const struct mg_connection *conn,
  931. int *truncated,
  932. char *buf,
  933. size_t buflen,
  934. const char *fmt,
  935. va_list ap);
  936. static void mg_snprintf(const struct mg_connection *conn,
  937. int *truncated,
  938. char *buf,
  939. size_t buflen,
  940. PRINTF_FORMAT_STRING(const char *fmt),
  941. ...) PRINTF_ARGS(5, 6);
  942. /* This following lines are just meant as a reminder to use the mg-functions
  943. * for memory management */
  944. #ifdef malloc
  945. #undef malloc
  946. #endif
  947. #ifdef calloc
  948. #undef calloc
  949. #endif
  950. #ifdef realloc
  951. #undef realloc
  952. #endif
  953. #ifdef free
  954. #undef free
  955. #endif
  956. #ifdef snprintf
  957. #undef snprintf
  958. #endif
  959. #ifdef vsnprintf
  960. #undef vsnprintf
  961. #endif
  962. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  963. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  964. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  965. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  966. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  967. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  968. * but this define only works well for Windows. */
  969. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  970. #endif
  971. #define MD5_STATIC static
  972. #include "md5.inl"
  973. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  974. #ifdef NO_SOCKLEN_T
  975. typedef int socklen_t;
  976. #endif /* NO_SOCKLEN_T */
  977. #define _DARWIN_UNLIMITED_SELECT
  978. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  979. #if !defined(MSG_NOSIGNAL)
  980. #define MSG_NOSIGNAL (0)
  981. #endif
  982. #if !defined(SOMAXCONN)
  983. #define SOMAXCONN (100)
  984. #endif
  985. /* Size of the accepted socket queue */
  986. #if !defined(MGSQLEN)
  987. #define MGSQLEN (20)
  988. #endif
  989. #if defined(NO_SSL)
  990. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  991. typedef struct SSL_CTX SSL_CTX;
  992. #else
  993. #if defined(NO_SSL_DL)
  994. #include <openssl/ssl.h>
  995. #include <openssl/err.h>
  996. #include <openssl/crypto.h>
  997. #include <openssl/x509.h>
  998. #include <openssl/pem.h>
  999. #include <openssl/engine.h>
  1000. #include <openssl/conf.h>
  1001. #include <openssl/dh.h>
  1002. #else
  1003. /* SSL loaded dynamically from DLL.
  1004. * I put the prototypes here to be independent from OpenSSL source
  1005. * installation. */
  1006. typedef struct ssl_st SSL;
  1007. typedef struct ssl_method_st SSL_METHOD;
  1008. typedef struct ssl_ctx_st SSL_CTX;
  1009. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1010. typedef struct x509_name X509_NAME;
  1011. typedef struct asn1_integer ASN1_INTEGER;
  1012. typedef struct evp_md EVP_MD;
  1013. typedef struct x509 X509;
  1014. #define SSL_CTRL_OPTIONS (32)
  1015. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1016. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1017. #define SSL_VERIFY_NONE (0)
  1018. #define SSL_VERIFY_PEER (1)
  1019. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1020. #define SSL_VERIFY_CLIENT_ONCE (4)
  1021. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1022. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1023. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1024. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1025. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1026. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1027. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1028. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1029. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1030. #define SSL_ERROR_NONE (0)
  1031. #define SSL_ERROR_SSL (1)
  1032. #define SSL_ERROR_WANT_READ (2)
  1033. #define SSL_ERROR_WANT_WRITE (3)
  1034. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1035. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1036. #define SSL_ERROR_ZERO_RETURN (6)
  1037. #define SSL_ERROR_WANT_CONNECT (7)
  1038. #define SSL_ERROR_WANT_ACCEPT (8)
  1039. struct ssl_func {
  1040. const char *name; /* SSL function name */
  1041. void (*ptr)(void); /* Function pointer */
  1042. };
  1043. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1044. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1045. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1046. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1047. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1048. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1049. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1050. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1051. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1052. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1053. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1054. #define SSL_CTX_use_PrivateKey_file \
  1055. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1056. #define SSL_CTX_use_certificate_file \
  1057. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1058. #define SSL_CTX_set_default_passwd_cb \
  1059. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1060. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1061. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1062. #define SSL_CTX_use_certificate_chain_file \
  1063. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1064. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1065. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1066. #define SSL_CTX_set_verify \
  1067. (*(void (*)(SSL_CTX *, \
  1068. int, \
  1069. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1070. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1071. #define SSL_CTX_load_verify_locations \
  1072. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1073. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1074. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1075. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1076. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1077. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1078. #define SSL_CIPHER_get_name \
  1079. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1080. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1081. #define SSL_CTX_set_session_id_context \
  1082. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1083. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1084. #define SSL_CTX_set_cipher_list \
  1085. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1086. #define SSL_CTX_set_options(ctx, op) \
  1087. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1088. #define SSL_CTX_clear_options(ctx, op) \
  1089. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1090. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1091. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1092. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1093. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1094. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1095. #define CRYPTO_set_locking_callback \
  1096. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1097. #define CRYPTO_set_id_callback \
  1098. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1099. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1100. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1101. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1102. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1103. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1104. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1105. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1106. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1107. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1108. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1109. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1110. #define X509_NAME_oneline \
  1111. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1112. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1113. #define i2c_ASN1_INTEGER \
  1114. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1115. #define EVP_get_digestbyname \
  1116. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1117. #define ASN1_digest \
  1118. (*(int (*)(int (*)(), \
  1119. const EVP_MD *, \
  1120. char *, \
  1121. unsigned char *, \
  1122. unsigned int *))crypto_sw[18].ptr)
  1123. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1124. /* set_ssl_option() function updates this array.
  1125. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1126. * of respective functions. The macros above (like SSL_connect()) are really
  1127. * just calling these functions indirectly via the pointer. */
  1128. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1129. {"SSL_accept", NULL},
  1130. {"SSL_connect", NULL},
  1131. {"SSL_read", NULL},
  1132. {"SSL_write", NULL},
  1133. {"SSL_get_error", NULL},
  1134. {"SSL_set_fd", NULL},
  1135. {"SSL_new", NULL},
  1136. {"SSL_CTX_new", NULL},
  1137. {"SSLv23_server_method", NULL},
  1138. {"SSL_library_init", NULL},
  1139. {"SSL_CTX_use_PrivateKey_file", NULL},
  1140. {"SSL_CTX_use_certificate_file", NULL},
  1141. {"SSL_CTX_set_default_passwd_cb", NULL},
  1142. {"SSL_CTX_free", NULL},
  1143. {"SSL_load_error_strings", NULL},
  1144. {"SSL_CTX_use_certificate_chain_file", NULL},
  1145. {"SSLv23_client_method", NULL},
  1146. {"SSL_pending", NULL},
  1147. {"SSL_CTX_set_verify", NULL},
  1148. {"SSL_shutdown", NULL},
  1149. {"SSL_CTX_load_verify_locations", NULL},
  1150. {"SSL_CTX_set_default_verify_paths", NULL},
  1151. {"SSL_CTX_set_verify_depth", NULL},
  1152. {"SSL_get_peer_certificate", NULL},
  1153. {"SSL_get_version", NULL},
  1154. {"SSL_get_current_cipher", NULL},
  1155. {"SSL_CIPHER_get_name", NULL},
  1156. {"SSL_CTX_check_private_key", NULL},
  1157. {"SSL_CTX_set_session_id_context", NULL},
  1158. {"SSL_CTX_ctrl", NULL},
  1159. {"SSL_CTX_set_cipher_list", NULL},
  1160. {NULL, NULL}};
  1161. /* Similar array as ssl_sw. These functions could be located in different
  1162. * lib. */
  1163. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1164. {"CRYPTO_set_locking_callback", NULL},
  1165. {"CRYPTO_set_id_callback", NULL},
  1166. {"ERR_get_error", NULL},
  1167. {"ERR_error_string", NULL},
  1168. {"ERR_remove_state", NULL},
  1169. {"ERR_free_strings", NULL},
  1170. {"ENGINE_cleanup", NULL},
  1171. {"CONF_modules_unload", NULL},
  1172. {"CRYPTO_cleanup_all_ex_data", NULL},
  1173. {"EVP_cleanup", NULL},
  1174. {"X509_free", NULL},
  1175. {"X509_get_subject_name", NULL},
  1176. {"X509_get_issuer_name", NULL},
  1177. {"X509_NAME_oneline", NULL},
  1178. {"X509_get_serialNumber", NULL},
  1179. {"i2c_ASN1_INTEGER", NULL},
  1180. {"EVP_get_digestbyname", NULL},
  1181. {"ASN1_digest", NULL},
  1182. {"i2d_X509", NULL},
  1183. {NULL, NULL}};
  1184. #endif /* NO_SSL_DL */
  1185. #endif /* NO_SSL */
  1186. #if !defined(NO_CACHING)
  1187. static const char *month_names[] = {"Jan",
  1188. "Feb",
  1189. "Mar",
  1190. "Apr",
  1191. "May",
  1192. "Jun",
  1193. "Jul",
  1194. "Aug",
  1195. "Sep",
  1196. "Oct",
  1197. "Nov",
  1198. "Dec"};
  1199. #endif /* !NO_CACHING */
  1200. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1201. * union u. */
  1202. union usa {
  1203. struct sockaddr sa;
  1204. struct sockaddr_in sin;
  1205. #if defined(USE_IPV6)
  1206. struct sockaddr_in6 sin6;
  1207. #endif
  1208. };
  1209. /* Describes a string (chunk of memory). */
  1210. struct vec {
  1211. const char *ptr;
  1212. size_t len;
  1213. };
  1214. struct mg_file_stat {
  1215. /* File properties filled by mg_stat: */
  1216. uint64_t size;
  1217. time_t last_modified;
  1218. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1219. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1220. * case we need a "Content-Eencoding: gzip" header */
  1221. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1222. };
  1223. struct mg_file_in_memory {
  1224. char *p;
  1225. uint32_t pos;
  1226. char mode;
  1227. };
  1228. struct mg_file_access {
  1229. /* File properties filled by mg_fopen: */
  1230. FILE *fp;
  1231. /* TODO: struct mg_file_in_memory *mf; */
  1232. const char *membuf; /* TODO: remove */
  1233. };
  1234. struct mg_file {
  1235. struct mg_file_stat stat;
  1236. struct mg_file_access access;
  1237. };
  1238. #define STRUCT_FILE_INITIALIZER \
  1239. { \
  1240. { \
  1241. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1242. } \
  1243. , \
  1244. { \
  1245. (FILE *) NULL, (const char *)NULL \
  1246. } \
  1247. }
  1248. /* Describes listening socket, or socket which was accept()-ed by the master
  1249. * thread and queued for future handling by the worker thread. */
  1250. struct socket {
  1251. SOCKET sock; /* Listening socket */
  1252. union usa lsa; /* Local socket address */
  1253. union usa rsa; /* Remote socket address */
  1254. unsigned char is_ssl; /* Is port SSL-ed */
  1255. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1256. * port */
  1257. unsigned char in_use; /* Is valid */
  1258. };
  1259. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1260. enum {
  1261. CGI_EXTENSIONS,
  1262. CGI_ENVIRONMENT,
  1263. PUT_DELETE_PASSWORDS_FILE,
  1264. CGI_INTERPRETER,
  1265. PROTECT_URI,
  1266. AUTHENTICATION_DOMAIN,
  1267. SSI_EXTENSIONS,
  1268. THROTTLE,
  1269. ACCESS_LOG_FILE,
  1270. ENABLE_DIRECTORY_LISTING,
  1271. ERROR_LOG_FILE,
  1272. GLOBAL_PASSWORDS_FILE,
  1273. INDEX_FILES,
  1274. ENABLE_KEEP_ALIVE,
  1275. ACCESS_CONTROL_LIST,
  1276. EXTRA_MIME_TYPES,
  1277. LISTENING_PORTS,
  1278. DOCUMENT_ROOT,
  1279. SSL_CERTIFICATE,
  1280. NUM_THREADS,
  1281. RUN_AS_USER,
  1282. REWRITE,
  1283. HIDE_FILES,
  1284. REQUEST_TIMEOUT,
  1285. KEEP_ALIVE_TIMEOUT,
  1286. SSL_DO_VERIFY_PEER,
  1287. SSL_CA_PATH,
  1288. SSL_CA_FILE,
  1289. SSL_VERIFY_DEPTH,
  1290. SSL_DEFAULT_VERIFY_PATHS,
  1291. SSL_CIPHER_LIST,
  1292. SSL_PROTOCOL_VERSION,
  1293. SSL_SHORT_TRUST,
  1294. #if defined(USE_WEBSOCKET)
  1295. WEBSOCKET_TIMEOUT,
  1296. #endif
  1297. DECODE_URL,
  1298. #if defined(USE_LUA)
  1299. LUA_PRELOAD_FILE,
  1300. LUA_SCRIPT_EXTENSIONS,
  1301. LUA_SERVER_PAGE_EXTENSIONS,
  1302. #endif
  1303. #if defined(USE_DUKTAPE)
  1304. DUKTAPE_SCRIPT_EXTENSIONS,
  1305. #endif
  1306. #if defined(USE_WEBSOCKET)
  1307. WEBSOCKET_ROOT,
  1308. #endif
  1309. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1310. LUA_WEBSOCKET_EXTENSIONS,
  1311. #endif
  1312. ACCESS_CONTROL_ALLOW_ORIGIN,
  1313. ERROR_PAGES,
  1314. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1315. * socket option typedef TCP_NODELAY. */
  1316. #if !defined(NO_CACHING)
  1317. STATIC_FILE_MAX_AGE,
  1318. #endif
  1319. #if defined(__linux__)
  1320. ALLOW_SENDFILE_CALL,
  1321. #endif
  1322. #if defined(_WIN32)
  1323. CASE_SENSITIVE_FILES,
  1324. #endif
  1325. NUM_OPTIONS
  1326. };
  1327. /* Config option name, config types, default value */
  1328. static struct mg_option config_options[] = {
  1329. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1330. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1331. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1332. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1333. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1334. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1335. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1336. {"throttle", CONFIG_TYPE_STRING, NULL},
  1337. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1338. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1339. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1340. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1341. {"index_files",
  1342. CONFIG_TYPE_STRING,
  1343. #ifdef USE_LUA
  1344. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1345. "index.shtml,index.php"},
  1346. #else
  1347. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1348. #endif
  1349. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1350. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1351. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1352. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1353. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1354. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1355. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1356. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1357. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1358. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1359. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1360. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1361. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1362. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1363. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1364. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1365. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1366. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1367. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1368. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1369. #if defined(USE_WEBSOCKET)
  1370. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1371. #endif
  1372. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1373. #if defined(USE_LUA)
  1374. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1375. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1376. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1377. #endif
  1378. #if defined(USE_DUKTAPE)
  1379. /* The support for duktape is still in alpha version state.
  1380. * The name of this config option might change. */
  1381. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1382. #endif
  1383. #if defined(USE_WEBSOCKET)
  1384. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1385. #endif
  1386. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1387. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1388. #endif
  1389. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1390. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1391. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1392. #if !defined(NO_CACHING)
  1393. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1394. #endif
  1395. #if defined(__linux__)
  1396. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1397. #endif
  1398. #if defined(_WIN32)
  1399. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1400. #endif
  1401. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1402. /* Check if the config_options and the corresponding enum have compatible
  1403. * sizes. */
  1404. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1405. == (NUM_OPTIONS + 1),
  1406. "config_options and enum not sync");
  1407. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1408. struct mg_handler_info {
  1409. /* Name/Pattern of the URI. */
  1410. char *uri;
  1411. size_t uri_len;
  1412. /* handler type */
  1413. int handler_type;
  1414. /* Handler for http/https or authorization requests. */
  1415. mg_request_handler handler;
  1416. /* Handler for ws/wss (websocket) requests. */
  1417. mg_websocket_connect_handler connect_handler;
  1418. mg_websocket_ready_handler ready_handler;
  1419. mg_websocket_data_handler data_handler;
  1420. mg_websocket_close_handler close_handler;
  1421. /* accepted subprotocols for ws/wss requests. */
  1422. struct mg_websocket_subprotocols *subprotocols;
  1423. /* Handler for authorization requests */
  1424. mg_authorization_handler auth_handler;
  1425. /* User supplied argument for the handler function. */
  1426. void *cbdata;
  1427. /* next handler in a linked list */
  1428. struct mg_handler_info *next;
  1429. };
  1430. struct mg_context {
  1431. volatile int stop_flag; /* Should we stop event loop */
  1432. SSL_CTX *ssl_ctx; /* SSL context */
  1433. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1434. struct mg_callbacks callbacks; /* User-defined callback function */
  1435. void *user_data; /* User-defined data */
  1436. int context_type; /* 1 = server context,
  1437. * 2 = ws/wss client context,
  1438. */
  1439. struct socket *listening_sockets;
  1440. struct pollfd *listening_socket_fds;
  1441. unsigned int num_listening_sockets;
  1442. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1443. #ifdef ALTERNATIVE_QUEUE
  1444. struct socket *client_socks;
  1445. void **client_wait_events;
  1446. #else
  1447. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1448. volatile int sq_head; /* Head of the socket queue */
  1449. volatile int sq_tail; /* Tail of the socket queue */
  1450. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1451. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1452. #endif
  1453. pthread_t masterthreadid; /* The master thread ID */
  1454. unsigned int
  1455. cfg_worker_threads; /* The number of configured worker threads. */
  1456. pthread_t *workerthreadids; /* The worker thread IDs */
  1457. time_t start_time; /* Server start time, used for authentication */
  1458. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1459. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1460. unsigned long nonce_count; /* Used nonces, used for authentication */
  1461. char *systemName; /* What operating system is running */
  1462. /* linked list of uri handlers */
  1463. struct mg_handler_info *handlers;
  1464. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1465. /* linked list of shared lua websockets */
  1466. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1467. #endif
  1468. #ifdef USE_TIMERS
  1469. struct ttimers *timers;
  1470. #endif
  1471. };
  1472. struct mg_connection {
  1473. struct mg_request_info request_info;
  1474. struct mg_context *ctx;
  1475. SSL *ssl; /* SSL descriptor */
  1476. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1477. struct socket client; /* Connected client */
  1478. time_t conn_birth_time; /* Time (wall clock) when connection was
  1479. * established */
  1480. struct timespec req_time; /* Time (since system start) when the request
  1481. * was received */
  1482. int64_t num_bytes_sent; /* Total bytes sent to client */
  1483. int64_t content_len; /* Content-Length header value */
  1484. int64_t consumed_content; /* How many bytes of content have been read */
  1485. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1486. * data available, 2: all data read */
  1487. size_t chunk_remainder; /* Unread data from the last chunk */
  1488. char *buf; /* Buffer for received data */
  1489. char *path_info; /* PATH_INFO part of the URL */
  1490. int must_close; /* 1 if connection must be closed */
  1491. int in_error_handler; /* 1 if in handler for user defined error
  1492. * pages */
  1493. int handled_requests; /* Number of requests handled by this connection */
  1494. int buf_size; /* Buffer size */
  1495. int request_len; /* Size of the request + headers in a buffer */
  1496. int data_len; /* Total size of data in a buffer */
  1497. int status_code; /* HTTP reply status code, e.g. 200 */
  1498. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1499. * throttle */
  1500. time_t last_throttle_time; /* Last time throttled data was sent */
  1501. int64_t last_throttle_bytes; /* Bytes sent this second */
  1502. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1503. * atomic transmissions for websockets */
  1504. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1505. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1506. #endif
  1507. int thread_index; /* Thread index within ctx */
  1508. };
  1509. static pthread_key_t sTlsKey; /* Thread local storage index */
  1510. static int sTlsInit = 0;
  1511. static int thread_idx_max = 0;
  1512. struct mg_workerTLS {
  1513. int is_master;
  1514. unsigned long thread_idx;
  1515. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1516. HANDLE pthread_cond_helper_mutex;
  1517. struct mg_workerTLS *next_waiting_thread;
  1518. #endif
  1519. };
  1520. /* Directory entry */
  1521. struct de {
  1522. struct mg_connection *conn;
  1523. char *file_name;
  1524. struct mg_file_stat file;
  1525. };
  1526. #if defined(USE_WEBSOCKET)
  1527. static int is_websocket_protocol(const struct mg_connection *conn);
  1528. #else
  1529. #define is_websocket_protocol(conn) (0)
  1530. #endif
  1531. static int
  1532. mg_atomic_inc(volatile int *addr)
  1533. {
  1534. int ret;
  1535. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1536. /* Depending on the SDK, this function uses either
  1537. * (volatile unsigned int *) or (volatile LONG *),
  1538. * so whatever you use, the other SDK is likely to raise a warning. */
  1539. ret = InterlockedIncrement((volatile long *)addr);
  1540. #elif defined(__GNUC__) \
  1541. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1542. ret = __sync_add_and_fetch(addr, 1);
  1543. #else
  1544. ret = (++(*addr));
  1545. #endif
  1546. return ret;
  1547. }
  1548. static int
  1549. mg_atomic_dec(volatile int *addr)
  1550. {
  1551. int ret;
  1552. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1553. /* Depending on the SDK, this function uses either
  1554. * (volatile unsigned int *) or (volatile LONG *),
  1555. * so whatever you use, the other SDK is likely to raise a warning. */
  1556. ret = InterlockedDecrement((volatile long *)addr);
  1557. #elif defined(__GNUC__) \
  1558. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  1559. ret = __sync_sub_and_fetch(addr, 1);
  1560. #else
  1561. ret = (--(*addr));
  1562. #endif
  1563. return ret;
  1564. }
  1565. #if !defined(NO_THREAD_NAME)
  1566. #if defined(_WIN32) && defined(_MSC_VER)
  1567. /* Set the thread name for debugging purposes in Visual Studio
  1568. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1569. */
  1570. #pragma pack(push, 8)
  1571. typedef struct tagTHREADNAME_INFO {
  1572. DWORD dwType; /* Must be 0x1000. */
  1573. LPCSTR szName; /* Pointer to name (in user addr space). */
  1574. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1575. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1576. } THREADNAME_INFO;
  1577. #pragma pack(pop)
  1578. #elif defined(__linux__)
  1579. #include <sys/prctl.h>
  1580. #include <sys/sendfile.h>
  1581. #include <sys/eventfd.h>
  1582. #if defined(ALTERNATIVE_QUEUE)
  1583. static void *
  1584. event_create(void)
  1585. {
  1586. int ret = eventfd(0, EFD_CLOEXEC);
  1587. if (ret == -1) {
  1588. /* Linux uses -1 on error, Windows NULL. */
  1589. /* However, Linux does not return 0 on success either. */
  1590. return 0;
  1591. }
  1592. return (void *)ret;
  1593. }
  1594. static int
  1595. event_wait(void *eventhdl)
  1596. {
  1597. uint64_t u;
  1598. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1599. if (s != sizeof(uint64_t)) {
  1600. /* error */
  1601. return 0;
  1602. }
  1603. (void)u; /* the value is not required */
  1604. return 1;
  1605. }
  1606. static int
  1607. event_signal(void *eventhdl)
  1608. {
  1609. uint64_t u = 1;
  1610. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1611. if (s != sizeof(uint64_t)) {
  1612. /* error */
  1613. return 0;
  1614. }
  1615. return 1;
  1616. }
  1617. static void
  1618. event_destroy(void *eventhdl)
  1619. {
  1620. close((int)eventhdl);
  1621. }
  1622. #endif
  1623. #endif
  1624. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1625. struct posix_event {
  1626. pthread_mutex_t mutex;
  1627. pthread_cond_t cond;
  1628. };
  1629. static void *
  1630. event_create(void)
  1631. {
  1632. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1633. if (ret == 0) {
  1634. /* out of memory */
  1635. return 0;
  1636. }
  1637. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1638. /* pthread mutex not available */
  1639. mg_free(ret);
  1640. return 0;
  1641. }
  1642. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1643. /* pthread cond not available */
  1644. pthread_mutex_destroy(&(ret->mutex));
  1645. mg_free(ret);
  1646. return 0;
  1647. }
  1648. return (void *)ret;
  1649. }
  1650. static int
  1651. event_wait(void *eventhdl)
  1652. {
  1653. struct posix_event *ev = (struct posix_event *)eventhdl;
  1654. pthread_mutex_lock(&(ev->mutex));
  1655. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1656. pthread_mutex_unlock(&(ev->mutex));
  1657. return 1;
  1658. }
  1659. static int
  1660. event_signal(void *eventhdl)
  1661. {
  1662. struct posix_event *ev = (struct posix_event *)eventhdl;
  1663. pthread_mutex_lock(&(ev->mutex));
  1664. pthread_cond_signal(&(ev->cond));
  1665. pthread_mutex_unlock(&(ev->mutex));
  1666. return 1;
  1667. }
  1668. static void
  1669. event_destroy(void *eventhdl)
  1670. {
  1671. struct posix_event *ev = (struct posix_event *)eventhdl;
  1672. pthread_cond_destroy(&(ev->cond));
  1673. pthread_mutex_destroy(&(ev->mutex));
  1674. mg_free(ev);
  1675. }
  1676. #endif
  1677. static void
  1678. mg_set_thread_name(const char *name)
  1679. {
  1680. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1681. mg_snprintf(
  1682. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1683. #if defined(_WIN32)
  1684. #if defined(_MSC_VER)
  1685. /* Windows and Visual Studio Compiler */
  1686. __try
  1687. {
  1688. THREADNAME_INFO info;
  1689. info.dwType = 0x1000;
  1690. info.szName = threadName;
  1691. info.dwThreadID = ~0U;
  1692. info.dwFlags = 0;
  1693. RaiseException(0x406D1388,
  1694. 0,
  1695. sizeof(info) / sizeof(ULONG_PTR),
  1696. (ULONG_PTR *)&info);
  1697. }
  1698. __except(EXCEPTION_EXECUTE_HANDLER)
  1699. {
  1700. }
  1701. #elif defined(__MINGW32__)
  1702. /* No option known to set thread name for MinGW */
  1703. #endif
  1704. #elif defined(__GLIBC__) \
  1705. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1706. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1707. (void)pthread_setname_np(pthread_self(), threadName);
  1708. #elif defined(__linux__)
  1709. /* on linux we can use the old prctl function */
  1710. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1711. #endif
  1712. }
  1713. #else /* !defined(NO_THREAD_NAME) */
  1714. void
  1715. mg_set_thread_name(const char *threadName)
  1716. {
  1717. }
  1718. #endif
  1719. #if defined(MG_LEGACY_INTERFACE)
  1720. const char **
  1721. mg_get_valid_option_names(void)
  1722. {
  1723. /* This function is deprecated. Use mg_get_valid_options instead. */
  1724. static const char *
  1725. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1726. int i;
  1727. for (i = 0; config_options[i].name != NULL; i++) {
  1728. data[i * 2] = config_options[i].name;
  1729. data[i * 2 + 1] = config_options[i].default_value;
  1730. }
  1731. return data;
  1732. }
  1733. #endif
  1734. const struct mg_option *
  1735. mg_get_valid_options(void)
  1736. {
  1737. return config_options;
  1738. }
  1739. /* Do not open file (used in is_file_in_memory) */
  1740. #define MG_FOPEN_MODE_NONE (0)
  1741. /* Open file for read only access */
  1742. #define MG_FOPEN_MODE_READ (1)
  1743. /* Open file for writing, create and overwrite */
  1744. #define MG_FOPEN_MODE_WRITE (2)
  1745. /* Open file for writing, create and append */
  1746. #define MG_FOPEN_MODE_APPEND (4)
  1747. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1748. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1749. static int
  1750. open_file_in_memory(const struct mg_connection *conn,
  1751. const char *path,
  1752. struct mg_file *filep,
  1753. int mode)
  1754. {
  1755. size_t size = 0;
  1756. const char *buf = NULL;
  1757. if (!conn) {
  1758. return 0;
  1759. }
  1760. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1761. return 0;
  1762. }
  1763. if (conn->ctx->callbacks.open_file) {
  1764. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1765. if (buf != NULL) {
  1766. if (filep == NULL) {
  1767. /* This is a file in memory, but we cannot store the properties
  1768. * now.
  1769. * Called from "is_file_in_memory" function. */
  1770. return 1;
  1771. }
  1772. /* NOTE: override filep->size only on success. Otherwise, it might
  1773. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1774. filep->access.membuf = buf;
  1775. filep->access.fp = NULL;
  1776. /* Size was set by the callback */
  1777. filep->stat.size = size;
  1778. /* Assume the data may change during runtime by setting
  1779. * last_modified = now */
  1780. filep->stat.last_modified = time(NULL);
  1781. filep->stat.is_directory = 0;
  1782. filep->stat.is_gzipped = 0;
  1783. }
  1784. }
  1785. return (buf != NULL);
  1786. }
  1787. static int
  1788. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1789. {
  1790. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1791. }
  1792. static int
  1793. is_file_opened(const struct mg_file_access *fileacc)
  1794. {
  1795. if (!fileacc) {
  1796. return 0;
  1797. }
  1798. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1799. }
  1800. static int mg_stat(const struct mg_connection *conn,
  1801. const char *path,
  1802. struct mg_file_stat *filep);
  1803. /* mg_fopen will open a file either in memory or on the disk.
  1804. * The input parameter path is a string in UTF-8 encoding.
  1805. * The input parameter mode is MG_FOPEN_MODE_*
  1806. * On success, either fp or membuf will be set in the output
  1807. * struct file. All status members will also be set.
  1808. * The function returns 1 on success, 0 on error. */
  1809. static int
  1810. mg_fopen(const struct mg_connection *conn,
  1811. const char *path,
  1812. int mode,
  1813. struct mg_file *filep)
  1814. {
  1815. int found;
  1816. if (!filep) {
  1817. return 0;
  1818. }
  1819. filep->access.fp = NULL;
  1820. filep->access.membuf = NULL;
  1821. if (!is_file_in_memory(conn, path)) {
  1822. /* filep is initialized in mg_stat: all fields with memset to,
  1823. * some fields like size and modification date with values */
  1824. found = mg_stat(conn, path, &(filep->stat));
  1825. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1826. /* file does not exist and will not be created */
  1827. return 0;
  1828. }
  1829. #ifdef _WIN32
  1830. {
  1831. wchar_t wbuf[PATH_MAX];
  1832. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1833. switch (mode) {
  1834. case MG_FOPEN_MODE_READ:
  1835. filep->access.fp = _wfopen(wbuf, L"rb");
  1836. break;
  1837. case MG_FOPEN_MODE_WRITE:
  1838. filep->access.fp = _wfopen(wbuf, L"wb");
  1839. break;
  1840. case MG_FOPEN_MODE_APPEND:
  1841. filep->access.fp = _wfopen(wbuf, L"ab");
  1842. break;
  1843. }
  1844. }
  1845. #else
  1846. /* Linux et al already use unicode. No need to convert. */
  1847. switch (mode) {
  1848. case MG_FOPEN_MODE_READ:
  1849. filep->access.fp = fopen(path, "r");
  1850. break;
  1851. case MG_FOPEN_MODE_WRITE:
  1852. filep->access.fp = fopen(path, "w");
  1853. break;
  1854. case MG_FOPEN_MODE_APPEND:
  1855. filep->access.fp = fopen(path, "a");
  1856. break;
  1857. }
  1858. #endif
  1859. if (!found) {
  1860. /* File did not exist before fopen was called.
  1861. * Maybe it has been created now. Get stat info
  1862. * like creation time now. */
  1863. found = mg_stat(conn, path, &(filep->stat));
  1864. (void)found;
  1865. }
  1866. /* file is on disk */
  1867. return (filep->access.fp != NULL);
  1868. } else {
  1869. /* is_file_in_memory returned true */
  1870. if (open_file_in_memory(conn, path, filep, mode)) {
  1871. /* file is in memory */
  1872. return (filep->access.membuf != NULL);
  1873. }
  1874. }
  1875. /* Open failed */
  1876. return 0;
  1877. }
  1878. /* return 0 on success, just like fclose */
  1879. static int
  1880. mg_fclose(struct mg_file_access *fileacc)
  1881. {
  1882. int ret = -1;
  1883. if (fileacc != NULL) {
  1884. if (fileacc->fp != NULL) {
  1885. ret = fclose(fileacc->fp);
  1886. } else if (fileacc->membuf != NULL) {
  1887. ret = 0;
  1888. }
  1889. /* reset all members of fileacc */
  1890. memset(fileacc, 0, sizeof(*fileacc));
  1891. }
  1892. return ret;
  1893. }
  1894. static void
  1895. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1896. {
  1897. for (; *src != '\0' && n > 1; n--) {
  1898. *dst++ = *src++;
  1899. }
  1900. *dst = '\0';
  1901. }
  1902. static int
  1903. lowercase(const char *s)
  1904. {
  1905. return tolower(*(const unsigned char *)s);
  1906. }
  1907. int
  1908. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1909. {
  1910. int diff = 0;
  1911. if (len > 0) {
  1912. do {
  1913. diff = lowercase(s1++) - lowercase(s2++);
  1914. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1915. }
  1916. return diff;
  1917. }
  1918. int
  1919. mg_strcasecmp(const char *s1, const char *s2)
  1920. {
  1921. int diff;
  1922. do {
  1923. diff = lowercase(s1++) - lowercase(s2++);
  1924. } while (diff == 0 && s1[-1] != '\0');
  1925. return diff;
  1926. }
  1927. static char *
  1928. mg_strndup(const char *ptr, size_t len)
  1929. {
  1930. char *p;
  1931. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1932. mg_strlcpy(p, ptr, len + 1);
  1933. }
  1934. return p;
  1935. }
  1936. static char *
  1937. mg_strdup(const char *str)
  1938. {
  1939. return mg_strndup(str, strlen(str));
  1940. }
  1941. static const char *
  1942. mg_strcasestr(const char *big_str, const char *small_str)
  1943. {
  1944. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1945. if (big_len >= small_len) {
  1946. for (i = 0; i <= (big_len - small_len); i++) {
  1947. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1948. return big_str + i;
  1949. }
  1950. }
  1951. }
  1952. return NULL;
  1953. }
  1954. /* Return null terminated string of given maximum length.
  1955. * Report errors if length is exceeded. */
  1956. static void
  1957. mg_vsnprintf(const struct mg_connection *conn,
  1958. int *truncated,
  1959. char *buf,
  1960. size_t buflen,
  1961. const char *fmt,
  1962. va_list ap)
  1963. {
  1964. int n, ok;
  1965. if (buflen == 0) {
  1966. return;
  1967. }
  1968. #ifdef __clang__
  1969. #pragma clang diagnostic push
  1970. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1971. /* Using fmt as a non-literal is intended here, since it is mostly called
  1972. * indirectly by mg_snprintf */
  1973. #endif
  1974. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1975. ok = (n >= 0) && ((size_t)n < buflen);
  1976. #ifdef __clang__
  1977. #pragma clang diagnostic pop
  1978. #endif
  1979. if (ok) {
  1980. if (truncated) {
  1981. *truncated = 0;
  1982. }
  1983. } else {
  1984. if (truncated) {
  1985. *truncated = 1;
  1986. }
  1987. mg_cry(conn,
  1988. "truncating vsnprintf buffer: [%.*s]",
  1989. (int)((buflen > 200) ? 200 : (buflen - 1)),
  1990. buf);
  1991. n = (int)buflen - 1;
  1992. }
  1993. buf[n] = '\0';
  1994. }
  1995. static void
  1996. mg_snprintf(const struct mg_connection *conn,
  1997. int *truncated,
  1998. char *buf,
  1999. size_t buflen,
  2000. const char *fmt,
  2001. ...)
  2002. {
  2003. va_list ap;
  2004. va_start(ap, fmt);
  2005. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2006. va_end(ap);
  2007. }
  2008. static int
  2009. get_option_index(const char *name)
  2010. {
  2011. int i;
  2012. for (i = 0; config_options[i].name != NULL; i++) {
  2013. if (strcmp(config_options[i].name, name) == 0) {
  2014. return i;
  2015. }
  2016. }
  2017. return -1;
  2018. }
  2019. const char *
  2020. mg_get_option(const struct mg_context *ctx, const char *name)
  2021. {
  2022. int i;
  2023. if ((i = get_option_index(name)) == -1) {
  2024. return NULL;
  2025. } else if (!ctx || ctx->config[i] == NULL) {
  2026. return "";
  2027. } else {
  2028. return ctx->config[i];
  2029. }
  2030. }
  2031. struct mg_context *
  2032. mg_get_context(const struct mg_connection *conn)
  2033. {
  2034. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2035. }
  2036. void *
  2037. mg_get_user_data(const struct mg_context *ctx)
  2038. {
  2039. return (ctx == NULL) ? NULL : ctx->user_data;
  2040. }
  2041. void
  2042. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2043. {
  2044. if (conn != NULL) {
  2045. conn->request_info.conn_data = data;
  2046. }
  2047. }
  2048. void *
  2049. mg_get_user_connection_data(const struct mg_connection *conn)
  2050. {
  2051. if (conn != NULL) {
  2052. return conn->request_info.conn_data;
  2053. }
  2054. return NULL;
  2055. }
  2056. size_t
  2057. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2058. {
  2059. size_t i;
  2060. if (!ctx) {
  2061. return 0;
  2062. }
  2063. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2064. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2065. ports[i] =
  2066. #if defined(USE_IPV6)
  2067. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2068. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2069. :
  2070. #endif
  2071. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2072. }
  2073. return i;
  2074. }
  2075. int
  2076. mg_get_server_ports(const struct mg_context *ctx,
  2077. int size,
  2078. struct mg_server_ports *ports)
  2079. {
  2080. int i, cnt = 0;
  2081. if (size <= 0) {
  2082. return -1;
  2083. }
  2084. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2085. if (!ctx) {
  2086. return -1;
  2087. }
  2088. if (!ctx->listening_sockets) {
  2089. return -1;
  2090. }
  2091. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2092. ports[cnt].port =
  2093. #if defined(USE_IPV6)
  2094. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2095. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2096. :
  2097. #endif
  2098. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2099. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2100. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2101. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2102. /* IPv4 */
  2103. ports[cnt].protocol = 1;
  2104. cnt++;
  2105. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2106. /* IPv6 */
  2107. ports[cnt].protocol = 3;
  2108. cnt++;
  2109. }
  2110. }
  2111. return cnt;
  2112. }
  2113. static void
  2114. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2115. {
  2116. buf[0] = '\0';
  2117. if (!usa) {
  2118. return;
  2119. }
  2120. if (usa->sa.sa_family == AF_INET) {
  2121. getnameinfo(&usa->sa,
  2122. sizeof(usa->sin),
  2123. buf,
  2124. (unsigned)len,
  2125. NULL,
  2126. 0,
  2127. NI_NUMERICHOST);
  2128. }
  2129. #if defined(USE_IPV6)
  2130. else if (usa->sa.sa_family == AF_INET6) {
  2131. getnameinfo(&usa->sa,
  2132. sizeof(usa->sin6),
  2133. buf,
  2134. (unsigned)len,
  2135. NULL,
  2136. 0,
  2137. NI_NUMERICHOST);
  2138. }
  2139. #endif
  2140. }
  2141. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2142. * included in all responses other than 100, 101, 5xx. */
  2143. static void
  2144. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2145. {
  2146. struct tm *tm;
  2147. tm = ((t != NULL) ? gmtime(t) : NULL);
  2148. if (tm != NULL) {
  2149. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2150. } else {
  2151. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2152. buf[buf_len - 1] = '\0';
  2153. }
  2154. }
  2155. /* difftime for struct timespec. Return value is in seconds. */
  2156. static double
  2157. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2158. {
  2159. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2160. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2161. }
  2162. /* Print error message to the opened error log stream. */
  2163. void
  2164. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2165. {
  2166. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2167. va_list ap;
  2168. struct mg_file fi;
  2169. time_t timestamp;
  2170. va_start(ap, fmt);
  2171. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2172. va_end(ap);
  2173. buf[sizeof(buf) - 1] = 0;
  2174. if (!conn) {
  2175. puts(buf);
  2176. return;
  2177. }
  2178. /* Do not lock when getting the callback value, here and below.
  2179. * I suppose this is fine, since function cannot disappear in the
  2180. * same way string option can. */
  2181. if ((conn->ctx->callbacks.log_message == NULL)
  2182. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2183. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2184. if (mg_fopen(conn,
  2185. conn->ctx->config[ERROR_LOG_FILE],
  2186. MG_FOPEN_MODE_APPEND,
  2187. &fi) == 0) {
  2188. fi.access.fp = NULL;
  2189. }
  2190. } else {
  2191. fi.access.fp = NULL;
  2192. }
  2193. if (fi.access.fp != NULL) {
  2194. flockfile(fi.access.fp);
  2195. timestamp = time(NULL);
  2196. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2197. fprintf(fi.access.fp,
  2198. "[%010lu] [error] [client %s] ",
  2199. (unsigned long)timestamp,
  2200. src_addr);
  2201. if (conn->request_info.request_method != NULL) {
  2202. fprintf(fi.access.fp,
  2203. "%s %s: ",
  2204. conn->request_info.request_method,
  2205. conn->request_info.request_uri);
  2206. }
  2207. fprintf(fi.access.fp, "%s", buf);
  2208. fputc('\n', fi.access.fp);
  2209. fflush(fi.access.fp);
  2210. funlockfile(fi.access.fp);
  2211. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2212. * mg_cry here anyway ;-) */
  2213. }
  2214. }
  2215. }
  2216. /* Return fake connection structure. Used for logging, if connection
  2217. * is not applicable at the moment of logging. */
  2218. static struct mg_connection *
  2219. fc(struct mg_context *ctx)
  2220. {
  2221. static struct mg_connection fake_connection;
  2222. fake_connection.ctx = ctx;
  2223. return &fake_connection;
  2224. }
  2225. const char *
  2226. mg_version(void)
  2227. {
  2228. return CIVETWEB_VERSION;
  2229. }
  2230. const struct mg_request_info *
  2231. mg_get_request_info(const struct mg_connection *conn)
  2232. {
  2233. if (!conn) {
  2234. return NULL;
  2235. }
  2236. return &conn->request_info;
  2237. }
  2238. /* Skip the characters until one of the delimiters characters found.
  2239. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2240. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2241. * Delimiters can be quoted with quotechar. */
  2242. static char *
  2243. skip_quoted(char **buf,
  2244. const char *delimiters,
  2245. const char *whitespace,
  2246. char quotechar)
  2247. {
  2248. char *p, *begin_word, *end_word, *end_whitespace;
  2249. begin_word = *buf;
  2250. end_word = begin_word + strcspn(begin_word, delimiters);
  2251. /* Check for quotechar */
  2252. if (end_word > begin_word) {
  2253. p = end_word - 1;
  2254. while (*p == quotechar) {
  2255. /* While the delimiter is quoted, look for the next delimiter. */
  2256. /* This happens, e.g., in calls from parse_auth_header,
  2257. * if the user name contains a " character. */
  2258. /* If there is anything beyond end_word, copy it. */
  2259. if (*end_word != '\0') {
  2260. size_t end_off = strcspn(end_word + 1, delimiters);
  2261. memmove(p, end_word, end_off + 1);
  2262. p += end_off; /* p must correspond to end_word - 1 */
  2263. end_word += end_off + 1;
  2264. } else {
  2265. *p = '\0';
  2266. break;
  2267. }
  2268. }
  2269. for (p++; p < end_word; p++) {
  2270. *p = '\0';
  2271. }
  2272. }
  2273. if (*end_word == '\0') {
  2274. *buf = end_word;
  2275. } else {
  2276. #if defined(__GNUC__) || defined(__MINGW32__)
  2277. /* Disable spurious conversion warning for GCC */
  2278. #pragma GCC diagnostic push
  2279. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2280. #endif
  2281. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2282. #if defined(__GNUC__) || defined(__MINGW32__)
  2283. #pragma GCC diagnostic pop
  2284. #endif
  2285. for (p = end_word; p < end_whitespace; p++) {
  2286. *p = '\0';
  2287. }
  2288. *buf = end_whitespace;
  2289. }
  2290. return begin_word;
  2291. }
  2292. /* Simplified version of skip_quoted without quote char
  2293. * and whitespace == delimiters */
  2294. static char *
  2295. skip(char **buf, const char *delimiters)
  2296. {
  2297. return skip_quoted(buf, delimiters, delimiters, 0);
  2298. }
  2299. /* Return HTTP header value, or NULL if not found. */
  2300. static const char *
  2301. get_header(const struct mg_request_info *ri, const char *name)
  2302. {
  2303. int i;
  2304. if (ri) {
  2305. for (i = 0; i < ri->num_headers; i++) {
  2306. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2307. return ri->http_headers[i].value;
  2308. }
  2309. }
  2310. }
  2311. return NULL;
  2312. }
  2313. const char *
  2314. mg_get_header(const struct mg_connection *conn, const char *name)
  2315. {
  2316. if (!conn) {
  2317. return NULL;
  2318. }
  2319. return get_header(&conn->request_info, name);
  2320. }
  2321. /* A helper function for traversing a comma separated list of values.
  2322. * It returns a list pointer shifted to the next value, or NULL if the end
  2323. * of the list found.
  2324. * Value is stored in val vector. If value has form "x=y", then eq_val
  2325. * vector is initialized to point to the "y" part, and val vector length
  2326. * is adjusted to point only to "x". */
  2327. static const char *
  2328. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2329. {
  2330. int end;
  2331. reparse:
  2332. if (val == NULL || list == NULL || *list == '\0') {
  2333. /* End of the list */
  2334. list = NULL;
  2335. } else {
  2336. /* Skip over leading LWS */
  2337. while (*list == ' ' || *list == '\t')
  2338. list++;
  2339. val->ptr = list;
  2340. if ((list = strchr(val->ptr, ',')) != NULL) {
  2341. /* Comma found. Store length and shift the list ptr */
  2342. val->len = ((size_t)(list - val->ptr));
  2343. list++;
  2344. } else {
  2345. /* This value is the last one */
  2346. list = val->ptr + strlen(val->ptr);
  2347. val->len = ((size_t)(list - val->ptr));
  2348. }
  2349. /* Adjust length for trailing LWS */
  2350. end = (int)val->len - 1;
  2351. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2352. end--;
  2353. val->len = (size_t)(end + 1);
  2354. if (val->len == 0) {
  2355. /* Ignore any empty entries. */
  2356. goto reparse;
  2357. }
  2358. if (eq_val != NULL) {
  2359. /* Value has form "x=y", adjust pointers and lengths
  2360. * so that val points to "x", and eq_val points to "y". */
  2361. eq_val->len = 0;
  2362. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2363. if (eq_val->ptr != NULL) {
  2364. eq_val->ptr++; /* Skip over '=' character */
  2365. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2366. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2367. }
  2368. }
  2369. }
  2370. return list;
  2371. }
  2372. /* A helper function for checking if a comma separated list of values contains
  2373. * the given option (case insensitvely).
  2374. * 'header' can be NULL, in which case false is returned. */
  2375. static int
  2376. header_has_option(const char *header, const char *option)
  2377. {
  2378. struct vec opt_vec;
  2379. struct vec eq_vec;
  2380. assert(option != NULL);
  2381. assert(option[0] != '\0');
  2382. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2383. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2384. return 1;
  2385. }
  2386. return 0;
  2387. }
  2388. /* Perform case-insensitive match of string against pattern */
  2389. static int
  2390. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2391. {
  2392. const char *or_str;
  2393. size_t i;
  2394. int j, len, res;
  2395. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2396. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2397. return (res > 0) ? res : match_prefix(or_str + 1,
  2398. (size_t)((pattern + pattern_len)
  2399. - (or_str + 1)),
  2400. str);
  2401. }
  2402. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2403. if (pattern[i] == '?' && str[j] != '\0') {
  2404. continue;
  2405. } else if (pattern[i] == '$') {
  2406. return (str[j] == '\0') ? j : -1;
  2407. } else if (pattern[i] == '*') {
  2408. i++;
  2409. if (pattern[i] == '*') {
  2410. i++;
  2411. len = (int)strlen(str + j);
  2412. } else {
  2413. len = (int)strcspn(str + j, "/");
  2414. }
  2415. if (i == pattern_len) {
  2416. return j + len;
  2417. }
  2418. do {
  2419. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2420. } while (res == -1 && len-- > 0);
  2421. return (res == -1) ? -1 : j + res + len;
  2422. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2423. return -1;
  2424. }
  2425. }
  2426. return j;
  2427. }
  2428. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2429. * This function must tolerate situations when connection info is not
  2430. * set up, for example if request parsing failed. */
  2431. static int
  2432. should_keep_alive(const struct mg_connection *conn)
  2433. {
  2434. if (conn != NULL) {
  2435. const char *http_version = conn->request_info.http_version;
  2436. const char *header = mg_get_header(conn, "Connection");
  2437. if (conn->must_close || conn->status_code == 401
  2438. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2439. || (header != NULL && !header_has_option(header, "keep-alive"))
  2440. || (header == NULL && http_version
  2441. && 0 != strcmp(http_version, "1.1"))) {
  2442. return 0;
  2443. }
  2444. return 1;
  2445. }
  2446. return 0;
  2447. }
  2448. static int
  2449. should_decode_url(const struct mg_connection *conn)
  2450. {
  2451. if (!conn || !conn->ctx) {
  2452. return 0;
  2453. }
  2454. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2455. }
  2456. static const char *
  2457. suggest_connection_header(const struct mg_connection *conn)
  2458. {
  2459. return should_keep_alive(conn) ? "keep-alive" : "close";
  2460. }
  2461. static int
  2462. send_no_cache_header(struct mg_connection *conn)
  2463. {
  2464. /* Send all current and obsolete cache opt-out directives. */
  2465. return mg_printf(conn,
  2466. "Cache-Control: no-cache, no-store, "
  2467. "must-revalidate, private, max-age=0\r\n"
  2468. "Pragma: no-cache\r\n"
  2469. "Expires: 0\r\n");
  2470. }
  2471. static int
  2472. send_static_cache_header(struct mg_connection *conn)
  2473. {
  2474. #if !defined(NO_CACHING)
  2475. /* Read the server config to check how long a file may be cached.
  2476. * The configuration is in seconds. */
  2477. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2478. if (max_age <= 0) {
  2479. /* 0 means "do not cache". All values <0 are reserved
  2480. * and may be used differently in the future. */
  2481. /* If a file should not be cached, do not only send
  2482. * max-age=0, but also pragmas and Expires headers. */
  2483. return send_no_cache_header(conn);
  2484. }
  2485. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2486. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2487. /* See also https://www.mnot.net/cache_docs/ */
  2488. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2489. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2490. * year to 31622400 seconds. For the moment, we just send whatever has
  2491. * been configured, still the behavior for >1 year should be considered
  2492. * as undefined. */
  2493. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2494. #else /* NO_CACHING */
  2495. return send_no_cache_header(conn);
  2496. #endif /* !NO_CACHING */
  2497. }
  2498. static void handle_file_based_request(struct mg_connection *conn,
  2499. const char *path,
  2500. struct mg_file *filep);
  2501. const char *
  2502. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2503. {
  2504. /* See IANA HTTP status code assignment:
  2505. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2506. */
  2507. switch (response_code) {
  2508. /* RFC2616 Section 10.1 - Informational 1xx */
  2509. case 100:
  2510. return "Continue"; /* RFC2616 Section 10.1.1 */
  2511. case 101:
  2512. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2513. case 102:
  2514. return "Processing"; /* RFC2518 Section 10.1 */
  2515. /* RFC2616 Section 10.2 - Successful 2xx */
  2516. case 200:
  2517. return "OK"; /* RFC2616 Section 10.2.1 */
  2518. case 201:
  2519. return "Created"; /* RFC2616 Section 10.2.2 */
  2520. case 202:
  2521. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2522. case 203:
  2523. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2524. case 204:
  2525. return "No Content"; /* RFC2616 Section 10.2.5 */
  2526. case 205:
  2527. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2528. case 206:
  2529. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2530. case 207:
  2531. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2532. case 208:
  2533. return "Already Reported"; /* RFC5842 Section 7.1 */
  2534. case 226:
  2535. return "IM used"; /* RFC3229 Section 10.4.1 */
  2536. /* RFC2616 Section 10.3 - Redirection 3xx */
  2537. case 300:
  2538. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2539. case 301:
  2540. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2541. case 302:
  2542. return "Found"; /* RFC2616 Section 10.3.3 */
  2543. case 303:
  2544. return "See Other"; /* RFC2616 Section 10.3.4 */
  2545. case 304:
  2546. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2547. case 305:
  2548. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2549. case 307:
  2550. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2551. case 308:
  2552. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2553. /* RFC2616 Section 10.4 - Client Error 4xx */
  2554. case 400:
  2555. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2556. case 401:
  2557. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2558. case 402:
  2559. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2560. case 403:
  2561. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2562. case 404:
  2563. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2564. case 405:
  2565. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2566. case 406:
  2567. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2568. case 407:
  2569. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2570. case 408:
  2571. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2572. case 409:
  2573. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2574. case 410:
  2575. return "Gone"; /* RFC2616 Section 10.4.11 */
  2576. case 411:
  2577. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2578. case 412:
  2579. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2580. case 413:
  2581. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2582. case 414:
  2583. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2584. case 415:
  2585. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2586. case 416:
  2587. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2588. case 417:
  2589. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2590. case 421:
  2591. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2592. case 422:
  2593. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2594. * Section 11.2 */
  2595. case 423:
  2596. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2597. case 424:
  2598. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2599. * Section 11.4 */
  2600. case 426:
  2601. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2602. case 428:
  2603. return "Precondition Required"; /* RFC 6585, Section 3 */
  2604. case 429:
  2605. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2606. case 431:
  2607. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2608. case 451:
  2609. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2610. * Section 3 */
  2611. /* RFC2616 Section 10.5 - Server Error 5xx */
  2612. case 500:
  2613. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2614. case 501:
  2615. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2616. case 502:
  2617. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2618. case 503:
  2619. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2620. case 504:
  2621. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2622. case 505:
  2623. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2624. case 506:
  2625. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2626. case 507:
  2627. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2628. * Section 11.5 */
  2629. case 508:
  2630. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2631. case 510:
  2632. return "Not Extended"; /* RFC 2774, Section 7 */
  2633. case 511:
  2634. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2635. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2636. * E.g., "de facto" standards due to common use, ... */
  2637. case 418:
  2638. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2639. case 419:
  2640. return "Authentication Timeout"; /* common use */
  2641. case 420:
  2642. return "Enhance Your Calm"; /* common use */
  2643. case 440:
  2644. return "Login Timeout"; /* common use */
  2645. case 509:
  2646. return "Bandwidth Limit Exceeded"; /* common use */
  2647. default:
  2648. /* This error code is unknown. This should not happen. */
  2649. if (conn) {
  2650. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2651. }
  2652. /* Return at least a category according to RFC 2616 Section 10. */
  2653. if (response_code >= 100 && response_code < 200) {
  2654. /* Unknown informational status code */
  2655. return "Information";
  2656. }
  2657. if (response_code >= 200 && response_code < 300) {
  2658. /* Unknown success code */
  2659. return "Success";
  2660. }
  2661. if (response_code >= 300 && response_code < 400) {
  2662. /* Unknown redirection code */
  2663. return "Redirection";
  2664. }
  2665. if (response_code >= 400 && response_code < 500) {
  2666. /* Unknown request error code */
  2667. return "Client Error";
  2668. }
  2669. if (response_code >= 500 && response_code < 600) {
  2670. /* Unknown server error code */
  2671. return "Server Error";
  2672. }
  2673. /* Response code not even within reasonable range */
  2674. return "";
  2675. }
  2676. }
  2677. static void send_http_error(struct mg_connection *,
  2678. int,
  2679. PRINTF_FORMAT_STRING(const char *fmt),
  2680. ...) PRINTF_ARGS(3, 4);
  2681. static void
  2682. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2683. {
  2684. char buf[MG_BUF_LEN];
  2685. va_list ap;
  2686. int len, i, page_handler_found, scope, truncated, has_body;
  2687. char date[64];
  2688. time_t curtime = time(NULL);
  2689. const char *error_handler = NULL;
  2690. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2691. const char *error_page_file_ext, *tstr;
  2692. const char *status_text = mg_get_response_code_text(conn, status);
  2693. if (conn == NULL) {
  2694. return;
  2695. }
  2696. conn->status_code = status;
  2697. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2698. || conn->ctx->callbacks.http_error(conn, status)) {
  2699. if (!conn->in_error_handler) {
  2700. /* Send user defined error pages, if defined */
  2701. error_handler = conn->ctx->config[ERROR_PAGES];
  2702. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2703. page_handler_found = 0;
  2704. if (error_handler != NULL) {
  2705. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2706. switch (scope) {
  2707. case 1: /* Handler for specific error, e.g. 404 error */
  2708. mg_snprintf(conn,
  2709. &truncated,
  2710. buf,
  2711. sizeof(buf) - 32,
  2712. "%serror%03u.",
  2713. error_handler,
  2714. status);
  2715. break;
  2716. case 2: /* Handler for error group, e.g., 5xx error handler
  2717. * for all server errors (500-599) */
  2718. mg_snprintf(conn,
  2719. &truncated,
  2720. buf,
  2721. sizeof(buf) - 32,
  2722. "%serror%01uxx.",
  2723. error_handler,
  2724. status / 100);
  2725. break;
  2726. default: /* Handler for all errors */
  2727. mg_snprintf(conn,
  2728. &truncated,
  2729. buf,
  2730. sizeof(buf) - 32,
  2731. "%serror.",
  2732. error_handler);
  2733. break;
  2734. }
  2735. /* String truncation in buf may only occur if error_handler
  2736. * is too long. This string is from the config, not from a
  2737. * client. */
  2738. (void)truncated;
  2739. len = (int)strlen(buf);
  2740. tstr = strchr(error_page_file_ext, '.');
  2741. while (tstr) {
  2742. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2743. i++)
  2744. buf[len + i - 1] = tstr[i];
  2745. buf[len + i - 1] = 0;
  2746. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2747. page_handler_found = 1;
  2748. break;
  2749. }
  2750. tstr = strchr(tstr + i, '.');
  2751. }
  2752. }
  2753. }
  2754. if (page_handler_found) {
  2755. conn->in_error_handler = 1;
  2756. handle_file_based_request(conn, buf, &error_page_file);
  2757. conn->in_error_handler = 0;
  2758. return;
  2759. }
  2760. }
  2761. /* No custom error page. Send default error page. */
  2762. gmt_time_string(date, sizeof(date), &curtime);
  2763. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2764. has_body = (status > 199 && status != 204 && status != 304);
  2765. conn->must_close = 1;
  2766. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2767. send_no_cache_header(conn);
  2768. if (has_body) {
  2769. mg_printf(conn,
  2770. "%s",
  2771. "Content-Type: text/plain; charset=utf-8\r\n");
  2772. }
  2773. mg_printf(conn,
  2774. "Date: %s\r\n"
  2775. "Connection: close\r\n\r\n",
  2776. date);
  2777. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2778. if (has_body) {
  2779. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2780. if (fmt != NULL) {
  2781. va_start(ap, fmt);
  2782. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2783. va_end(ap);
  2784. mg_write(conn, buf, strlen(buf));
  2785. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2786. }
  2787. } else {
  2788. /* No body allowed. Close the connection. */
  2789. DEBUG_TRACE("Error %i", status);
  2790. }
  2791. }
  2792. }
  2793. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2794. /* Create substitutes for POSIX functions in Win32. */
  2795. #if defined(__MINGW32__)
  2796. /* Show no warning in case system functions are not used. */
  2797. #pragma GCC diagnostic push
  2798. #pragma GCC diagnostic ignored "-Wunused-function"
  2799. #endif
  2800. static int
  2801. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2802. {
  2803. (void)unused;
  2804. *mutex = CreateMutex(NULL, FALSE, NULL);
  2805. return (*mutex == NULL) ? -1 : 0;
  2806. }
  2807. static int
  2808. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2809. {
  2810. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2811. }
  2812. static int
  2813. pthread_mutex_lock(pthread_mutex_t *mutex)
  2814. {
  2815. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2816. }
  2817. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2818. static int
  2819. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2820. {
  2821. switch (WaitForSingleObject(*mutex, 0)) {
  2822. case WAIT_OBJECT_0:
  2823. return 0;
  2824. case WAIT_TIMEOUT:
  2825. return -2; /* EBUSY */
  2826. }
  2827. return -1;
  2828. }
  2829. #endif
  2830. static int
  2831. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2832. {
  2833. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2834. }
  2835. static int
  2836. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2837. {
  2838. (void)unused;
  2839. InitializeCriticalSection(&cv->threadIdSec);
  2840. cv->waiting_thread = NULL;
  2841. return 0;
  2842. }
  2843. static int
  2844. pthread_cond_timedwait(pthread_cond_t *cv,
  2845. pthread_mutex_t *mutex,
  2846. const struct timespec *abstime)
  2847. {
  2848. struct mg_workerTLS **ptls,
  2849. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2850. int ok;
  2851. struct timespec tsnow;
  2852. int64_t nsnow, nswaitabs, nswaitrel;
  2853. DWORD mswaitrel;
  2854. EnterCriticalSection(&cv->threadIdSec);
  2855. /* Add this thread to cv's waiting list */
  2856. ptls = &cv->waiting_thread;
  2857. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2858. ;
  2859. tls->next_waiting_thread = NULL;
  2860. *ptls = tls;
  2861. LeaveCriticalSection(&cv->threadIdSec);
  2862. if (abstime) {
  2863. clock_gettime(CLOCK_REALTIME, &tsnow);
  2864. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2865. nswaitabs =
  2866. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2867. nswaitrel = nswaitabs - nsnow;
  2868. if (nswaitrel < 0) {
  2869. nswaitrel = 0;
  2870. }
  2871. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2872. } else {
  2873. mswaitrel = INFINITE;
  2874. }
  2875. pthread_mutex_unlock(mutex);
  2876. ok = (WAIT_OBJECT_0
  2877. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2878. if (!ok) {
  2879. ok = 1;
  2880. EnterCriticalSection(&cv->threadIdSec);
  2881. ptls = &cv->waiting_thread;
  2882. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2883. if (*ptls == tls) {
  2884. *ptls = tls->next_waiting_thread;
  2885. ok = 0;
  2886. break;
  2887. }
  2888. }
  2889. LeaveCriticalSection(&cv->threadIdSec);
  2890. if (ok) {
  2891. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2892. }
  2893. }
  2894. /* This thread has been removed from cv's waiting list */
  2895. pthread_mutex_lock(mutex);
  2896. return ok ? 0 : -1;
  2897. }
  2898. static int
  2899. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2900. {
  2901. return pthread_cond_timedwait(cv, mutex, NULL);
  2902. }
  2903. static int
  2904. pthread_cond_signal(pthread_cond_t *cv)
  2905. {
  2906. HANDLE wkup = NULL;
  2907. BOOL ok = FALSE;
  2908. EnterCriticalSection(&cv->threadIdSec);
  2909. if (cv->waiting_thread) {
  2910. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2911. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2912. ok = SetEvent(wkup);
  2913. assert(ok);
  2914. }
  2915. LeaveCriticalSection(&cv->threadIdSec);
  2916. return ok ? 0 : 1;
  2917. }
  2918. static int
  2919. pthread_cond_broadcast(pthread_cond_t *cv)
  2920. {
  2921. EnterCriticalSection(&cv->threadIdSec);
  2922. while (cv->waiting_thread) {
  2923. pthread_cond_signal(cv);
  2924. }
  2925. LeaveCriticalSection(&cv->threadIdSec);
  2926. return 0;
  2927. }
  2928. static int
  2929. pthread_cond_destroy(pthread_cond_t *cv)
  2930. {
  2931. EnterCriticalSection(&cv->threadIdSec);
  2932. assert(cv->waiting_thread == NULL);
  2933. LeaveCriticalSection(&cv->threadIdSec);
  2934. DeleteCriticalSection(&cv->threadIdSec);
  2935. return 0;
  2936. }
  2937. #ifdef ALTERNATIVE_QUEUE
  2938. static void *
  2939. event_create(void)
  2940. {
  2941. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2942. }
  2943. static int
  2944. event_wait(void *eventhdl)
  2945. {
  2946. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2947. return (res == WAIT_OBJECT_0);
  2948. }
  2949. static int
  2950. event_signal(void *eventhdl)
  2951. {
  2952. return (int)SetEvent((HANDLE)eventhdl);
  2953. }
  2954. static void
  2955. event_destroy(void *eventhdl)
  2956. {
  2957. CloseHandle((HANDLE)eventhdl);
  2958. }
  2959. #endif
  2960. #if defined(__MINGW32__)
  2961. /* Enable unused function warning again */
  2962. #pragma GCC diagnostic pop
  2963. #endif
  2964. /* For Windows, change all slashes to backslashes in path names. */
  2965. static void
  2966. change_slashes_to_backslashes(char *path)
  2967. {
  2968. int i;
  2969. for (i = 0; path[i] != '\0'; i++) {
  2970. if (path[i] == '/') {
  2971. path[i] = '\\';
  2972. }
  2973. /* remove double backslash (check i > 0 to preserve UNC paths,
  2974. * like \\server\file.txt) */
  2975. if ((path[i] == '\\') && (i > 0)) {
  2976. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2977. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2978. }
  2979. }
  2980. }
  2981. }
  2982. static int
  2983. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2984. {
  2985. int diff;
  2986. do {
  2987. diff = tolower(*s1) - tolower(*s2);
  2988. s1++;
  2989. s2++;
  2990. } while (diff == 0 && s1[-1] != '\0');
  2991. return diff;
  2992. }
  2993. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2994. * wbuf and wbuf_len is a target buffer and its length. */
  2995. static void
  2996. path_to_unicode(const struct mg_connection *conn,
  2997. const char *path,
  2998. wchar_t *wbuf,
  2999. size_t wbuf_len)
  3000. {
  3001. char buf[PATH_MAX], buf2[PATH_MAX];
  3002. wchar_t wbuf2[MAX_PATH + 1];
  3003. DWORD long_len, err;
  3004. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3005. mg_strlcpy(buf, path, sizeof(buf));
  3006. change_slashes_to_backslashes(buf);
  3007. /* Convert to Unicode and back. If doubly-converted string does not
  3008. * match the original, something is fishy, reject. */
  3009. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3010. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3011. WideCharToMultiByte(
  3012. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3013. if (strcmp(buf, buf2) != 0) {
  3014. wbuf[0] = L'\0';
  3015. }
  3016. /* Windows file systems are not case sensitive, but you can still use
  3017. * uppercase and lowercase letters (on all modern file systems).
  3018. * The server can check if the URI uses the same upper/lowercase
  3019. * letters an the file system, effectively making Windows servers
  3020. * case sensitive (like Linux servers are). It is still not possible
  3021. * to use two files with the same name in different cases on Windows
  3022. * (like /a and /A) - this would be possible in Linux.
  3023. * As a default, Windows is not case sensitive, but the case sensitive
  3024. * file name check can be activated by an additional configuration. */
  3025. if (conn) {
  3026. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3027. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3028. /* Use case sensitive compare function */
  3029. fcompare = wcscmp;
  3030. }
  3031. }
  3032. (void)conn; /* conn is currently unused */
  3033. #if !defined(_WIN32_WCE)
  3034. /* Only accept a full file path, not a Windows short (8.3) path. */
  3035. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3036. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3037. if (long_len == 0) {
  3038. err = GetLastError();
  3039. if (err == ERROR_FILE_NOT_FOUND) {
  3040. /* File does not exist. This is not always a problem here. */
  3041. return;
  3042. }
  3043. }
  3044. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3045. /* Short name is used. */
  3046. wbuf[0] = L'\0';
  3047. }
  3048. #else
  3049. (void)long_len;
  3050. (void)wbuf2;
  3051. (void)err;
  3052. if (strchr(path, '~')) {
  3053. wbuf[0] = L'\0';
  3054. }
  3055. #endif
  3056. }
  3057. /* Windows happily opens files with some garbage at the end of file name.
  3058. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3059. * "a.cgi", despite one would expect an error back.
  3060. * This function returns non-0 if path ends with some garbage. */
  3061. static int
  3062. path_cannot_disclose_cgi(const char *path)
  3063. {
  3064. static const char *allowed_last_characters = "_-";
  3065. int last = path[strlen(path) - 1];
  3066. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3067. }
  3068. static int
  3069. mg_stat(const struct mg_connection *conn,
  3070. const char *path,
  3071. struct mg_file_stat *filep)
  3072. {
  3073. wchar_t wbuf[PATH_MAX];
  3074. WIN32_FILE_ATTRIBUTE_DATA info;
  3075. time_t creation_time;
  3076. if (!filep) {
  3077. return 0;
  3078. }
  3079. memset(filep, 0, sizeof(*filep));
  3080. if (conn && is_file_in_memory(conn, path)) {
  3081. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3082. * memset */
  3083. filep->last_modified = time(NULL); /* xxxxxxxx */
  3084. /* last_modified = now ... assumes the file may change during runtime,
  3085. * so every mg_fopen call may return different data */
  3086. /* last_modified = conn->ctx.start_time;
  3087. * May be used it the data does not change during runtime. This allows
  3088. * browser caching. Since we do not know, we have to assume the file
  3089. * in memory may change. */
  3090. return 1;
  3091. }
  3092. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3093. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3094. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3095. filep->last_modified =
  3096. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3097. info.ftLastWriteTime.dwHighDateTime);
  3098. /* On Windows, the file creation time can be higher than the
  3099. * modification time, e.g. when a file is copied.
  3100. * Since the Last-Modified timestamp is used for caching
  3101. * it should be based on the most recent timestamp. */
  3102. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3103. info.ftCreationTime.dwHighDateTime);
  3104. if (creation_time > filep->last_modified) {
  3105. filep->last_modified = creation_time;
  3106. }
  3107. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3108. /* If file name is fishy, reset the file structure and return
  3109. * error.
  3110. * Note it is important to reset, not just return the error, cause
  3111. * functions like is_file_opened() check the struct. */
  3112. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3113. memset(filep, 0, sizeof(*filep));
  3114. return 0;
  3115. }
  3116. return 1;
  3117. }
  3118. return 0;
  3119. }
  3120. static int
  3121. mg_remove(const struct mg_connection *conn, const char *path)
  3122. {
  3123. wchar_t wbuf[PATH_MAX];
  3124. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3125. return DeleteFileW(wbuf) ? 0 : -1;
  3126. }
  3127. static int
  3128. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3129. {
  3130. wchar_t wbuf[PATH_MAX];
  3131. (void)mode;
  3132. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3133. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3134. }
  3135. /* Create substitutes for POSIX functions in Win32. */
  3136. #if defined(__MINGW32__)
  3137. /* Show no warning in case system functions are not used. */
  3138. #pragma GCC diagnostic push
  3139. #pragma GCC diagnostic ignored "-Wunused-function"
  3140. #endif
  3141. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3142. static DIR *
  3143. mg_opendir(const struct mg_connection *conn, const char *name)
  3144. {
  3145. DIR *dir = NULL;
  3146. wchar_t wpath[PATH_MAX];
  3147. DWORD attrs;
  3148. if (name == NULL) {
  3149. SetLastError(ERROR_BAD_ARGUMENTS);
  3150. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3151. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3152. } else {
  3153. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3154. attrs = GetFileAttributesW(wpath);
  3155. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3156. == FILE_ATTRIBUTE_DIRECTORY)) {
  3157. (void)wcscat(wpath, L"\\*");
  3158. dir->handle = FindFirstFileW(wpath, &dir->info);
  3159. dir->result.d_name[0] = '\0';
  3160. } else {
  3161. mg_free(dir);
  3162. dir = NULL;
  3163. }
  3164. }
  3165. return dir;
  3166. }
  3167. static int
  3168. mg_closedir(DIR *dir)
  3169. {
  3170. int result = 0;
  3171. if (dir != NULL) {
  3172. if (dir->handle != INVALID_HANDLE_VALUE)
  3173. result = FindClose(dir->handle) ? 0 : -1;
  3174. mg_free(dir);
  3175. } else {
  3176. result = -1;
  3177. SetLastError(ERROR_BAD_ARGUMENTS);
  3178. }
  3179. return result;
  3180. }
  3181. static struct dirent *
  3182. mg_readdir(DIR *dir)
  3183. {
  3184. struct dirent *result = 0;
  3185. if (dir) {
  3186. if (dir->handle != INVALID_HANDLE_VALUE) {
  3187. result = &dir->result;
  3188. (void)WideCharToMultiByte(CP_UTF8,
  3189. 0,
  3190. dir->info.cFileName,
  3191. -1,
  3192. result->d_name,
  3193. sizeof(result->d_name),
  3194. NULL,
  3195. NULL);
  3196. if (!FindNextFileW(dir->handle, &dir->info)) {
  3197. (void)FindClose(dir->handle);
  3198. dir->handle = INVALID_HANDLE_VALUE;
  3199. }
  3200. } else {
  3201. SetLastError(ERROR_FILE_NOT_FOUND);
  3202. }
  3203. } else {
  3204. SetLastError(ERROR_BAD_ARGUMENTS);
  3205. }
  3206. return result;
  3207. }
  3208. #ifndef HAVE_POLL
  3209. static int
  3210. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3211. {
  3212. struct timeval tv;
  3213. fd_set set;
  3214. unsigned int i;
  3215. int result;
  3216. SOCKET maxfd = 0;
  3217. memset(&tv, 0, sizeof(tv));
  3218. tv.tv_sec = milliseconds / 1000;
  3219. tv.tv_usec = (milliseconds % 1000) * 1000;
  3220. FD_ZERO(&set);
  3221. for (i = 0; i < n; i++) {
  3222. FD_SET((SOCKET)pfd[i].fd, &set);
  3223. pfd[i].revents = 0;
  3224. if (pfd[i].fd > maxfd) {
  3225. maxfd = pfd[i].fd;
  3226. }
  3227. }
  3228. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3229. for (i = 0; i < n; i++) {
  3230. if (FD_ISSET(pfd[i].fd, &set)) {
  3231. pfd[i].revents = POLLIN;
  3232. }
  3233. }
  3234. }
  3235. /* We should subtract the time used in select from remaining
  3236. * "milliseconds", in particular if called from mg_poll with a
  3237. * timeout quantum.
  3238. * Unfortunately, the remaining time is not stored in "tv" in all
  3239. * implementations, so the result in "tv" must be considered undefined.
  3240. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3241. return result;
  3242. }
  3243. #endif /* HAVE_POLL */
  3244. #if defined(__MINGW32__)
  3245. /* Enable unused function warning again */
  3246. #pragma GCC diagnostic pop
  3247. #endif
  3248. static void
  3249. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3250. {
  3251. (void)conn; /* Unused. */
  3252. #if defined(_WIN32_WCE)
  3253. (void)sock;
  3254. #else
  3255. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3256. #endif
  3257. }
  3258. int
  3259. mg_start_thread(mg_thread_func_t f, void *p)
  3260. {
  3261. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3262. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3263. */
  3264. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3265. == ((uintptr_t)(-1L)))
  3266. ? -1
  3267. : 0);
  3268. #else
  3269. return (
  3270. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3271. ? -1
  3272. : 0);
  3273. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3274. }
  3275. /* Start a thread storing the thread context. */
  3276. static int
  3277. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3278. void *p,
  3279. pthread_t *threadidptr)
  3280. {
  3281. uintptr_t uip;
  3282. HANDLE threadhandle;
  3283. int result = -1;
  3284. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3285. threadhandle = (HANDLE)uip;
  3286. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3287. *threadidptr = threadhandle;
  3288. result = 0;
  3289. }
  3290. return result;
  3291. }
  3292. /* Wait for a thread to finish. */
  3293. static int
  3294. mg_join_thread(pthread_t threadid)
  3295. {
  3296. int result;
  3297. DWORD dwevent;
  3298. result = -1;
  3299. dwevent = WaitForSingleObject(threadid, INFINITE);
  3300. if (dwevent == WAIT_FAILED) {
  3301. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3302. } else {
  3303. if (dwevent == WAIT_OBJECT_0) {
  3304. CloseHandle(threadid);
  3305. result = 0;
  3306. }
  3307. }
  3308. return result;
  3309. }
  3310. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3311. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3312. /* Create substitutes for POSIX functions in Win32. */
  3313. #if defined(__MINGW32__)
  3314. /* Show no warning in case system functions are not used. */
  3315. #pragma GCC diagnostic push
  3316. #pragma GCC diagnostic ignored "-Wunused-function"
  3317. #endif
  3318. static HANDLE
  3319. dlopen(const char *dll_name, int flags)
  3320. {
  3321. wchar_t wbuf[PATH_MAX];
  3322. (void)flags;
  3323. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3324. return LoadLibraryW(wbuf);
  3325. }
  3326. static int
  3327. dlclose(void *handle)
  3328. {
  3329. int result;
  3330. if (FreeLibrary((HMODULE)handle) != 0) {
  3331. result = 0;
  3332. } else {
  3333. result = -1;
  3334. }
  3335. return result;
  3336. }
  3337. #if defined(__MINGW32__)
  3338. /* Enable unused function warning again */
  3339. #pragma GCC diagnostic pop
  3340. #endif
  3341. #endif
  3342. #if !defined(NO_CGI)
  3343. #define SIGKILL (0)
  3344. static int
  3345. kill(pid_t pid, int sig_num)
  3346. {
  3347. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3348. (void)CloseHandle((HANDLE)pid);
  3349. return 0;
  3350. }
  3351. static void
  3352. trim_trailing_whitespaces(char *s)
  3353. {
  3354. char *e = s + strlen(s) - 1;
  3355. while (e > s && isspace(*(unsigned char *)e)) {
  3356. *e-- = '\0';
  3357. }
  3358. }
  3359. static pid_t
  3360. spawn_process(struct mg_connection *conn,
  3361. const char *prog,
  3362. char *envblk,
  3363. char *envp[],
  3364. int fdin[2],
  3365. int fdout[2],
  3366. int fderr[2],
  3367. const char *dir)
  3368. {
  3369. HANDLE me;
  3370. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3371. cmdline[PATH_MAX], buf[PATH_MAX];
  3372. int truncated;
  3373. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3374. STARTUPINFOA si;
  3375. PROCESS_INFORMATION pi = {0};
  3376. (void)envp;
  3377. memset(&si, 0, sizeof(si));
  3378. si.cb = sizeof(si);
  3379. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3380. si.wShowWindow = SW_HIDE;
  3381. me = GetCurrentProcess();
  3382. DuplicateHandle(me,
  3383. (HANDLE)_get_osfhandle(fdin[0]),
  3384. me,
  3385. &si.hStdInput,
  3386. 0,
  3387. TRUE,
  3388. DUPLICATE_SAME_ACCESS);
  3389. DuplicateHandle(me,
  3390. (HANDLE)_get_osfhandle(fdout[1]),
  3391. me,
  3392. &si.hStdOutput,
  3393. 0,
  3394. TRUE,
  3395. DUPLICATE_SAME_ACCESS);
  3396. DuplicateHandle(me,
  3397. (HANDLE)_get_osfhandle(fderr[1]),
  3398. me,
  3399. &si.hStdError,
  3400. 0,
  3401. TRUE,
  3402. DUPLICATE_SAME_ACCESS);
  3403. /* Mark handles that should not be inherited. See
  3404. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3405. */
  3406. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3407. HANDLE_FLAG_INHERIT,
  3408. 0);
  3409. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3410. HANDLE_FLAG_INHERIT,
  3411. 0);
  3412. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3413. HANDLE_FLAG_INHERIT,
  3414. 0);
  3415. /* If CGI file is a script, try to read the interpreter line */
  3416. interp = conn->ctx->config[CGI_INTERPRETER];
  3417. if (interp == NULL) {
  3418. buf[0] = buf[1] = '\0';
  3419. /* Read the first line of the script into the buffer */
  3420. mg_snprintf(
  3421. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3422. if (truncated) {
  3423. pi.hProcess = (pid_t)-1;
  3424. goto spawn_cleanup;
  3425. }
  3426. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3427. p = (char *)file.access.membuf;
  3428. mg_fgets(buf, sizeof(buf), &file, &p);
  3429. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3430. buf[sizeof(buf) - 1] = '\0';
  3431. }
  3432. if (buf[0] == '#' && buf[1] == '!') {
  3433. trim_trailing_whitespaces(buf + 2);
  3434. } else {
  3435. buf[2] = '\0';
  3436. }
  3437. interp = buf + 2;
  3438. }
  3439. if (interp[0] != '\0') {
  3440. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3441. interp = full_interp;
  3442. }
  3443. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3444. if (interp[0] != '\0') {
  3445. mg_snprintf(conn,
  3446. &truncated,
  3447. cmdline,
  3448. sizeof(cmdline),
  3449. "\"%s\" \"%s\\%s\"",
  3450. interp,
  3451. full_dir,
  3452. prog);
  3453. } else {
  3454. mg_snprintf(conn,
  3455. &truncated,
  3456. cmdline,
  3457. sizeof(cmdline),
  3458. "\"%s\\%s\"",
  3459. full_dir,
  3460. prog);
  3461. }
  3462. if (truncated) {
  3463. pi.hProcess = (pid_t)-1;
  3464. goto spawn_cleanup;
  3465. }
  3466. DEBUG_TRACE("Running [%s]", cmdline);
  3467. if (CreateProcessA(NULL,
  3468. cmdline,
  3469. NULL,
  3470. NULL,
  3471. TRUE,
  3472. CREATE_NEW_PROCESS_GROUP,
  3473. envblk,
  3474. NULL,
  3475. &si,
  3476. &pi) == 0) {
  3477. mg_cry(
  3478. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3479. pi.hProcess = (pid_t)-1;
  3480. /* goto spawn_cleanup; */
  3481. }
  3482. spawn_cleanup:
  3483. (void)CloseHandle(si.hStdOutput);
  3484. (void)CloseHandle(si.hStdError);
  3485. (void)CloseHandle(si.hStdInput);
  3486. if (pi.hThread != NULL) {
  3487. (void)CloseHandle(pi.hThread);
  3488. }
  3489. return (pid_t)pi.hProcess;
  3490. }
  3491. #endif /* !NO_CGI */
  3492. static int
  3493. set_blocking_mode(SOCKET sock, int blocking)
  3494. {
  3495. unsigned long non_blocking = !blocking;
  3496. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3497. }
  3498. #else
  3499. static int
  3500. mg_stat(const struct mg_connection *conn,
  3501. const char *path,
  3502. struct mg_file_stat *filep)
  3503. {
  3504. struct stat st;
  3505. if (!filep) {
  3506. return 0;
  3507. }
  3508. memset(filep, 0, sizeof(*filep));
  3509. if (conn && is_file_in_memory(conn, path)) {
  3510. return 1;
  3511. }
  3512. if (0 == stat(path, &st)) {
  3513. filep->size = (uint64_t)(st.st_size);
  3514. filep->last_modified = st.st_mtime;
  3515. filep->is_directory = S_ISDIR(st.st_mode);
  3516. return 1;
  3517. }
  3518. return 0;
  3519. }
  3520. static void
  3521. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3522. {
  3523. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3524. if (conn) {
  3525. mg_cry(conn,
  3526. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3527. __func__,
  3528. strerror(ERRNO));
  3529. }
  3530. }
  3531. }
  3532. int
  3533. mg_start_thread(mg_thread_func_t func, void *param)
  3534. {
  3535. pthread_t thread_id;
  3536. pthread_attr_t attr;
  3537. int result;
  3538. (void)pthread_attr_init(&attr);
  3539. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3540. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3541. /* Compile-time option to control stack size,
  3542. * e.g. -DUSE_STACK_SIZE=16384 */
  3543. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3544. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3545. result = pthread_create(&thread_id, &attr, func, param);
  3546. pthread_attr_destroy(&attr);
  3547. return result;
  3548. }
  3549. /* Start a thread storing the thread context. */
  3550. static int
  3551. mg_start_thread_with_id(mg_thread_func_t func,
  3552. void *param,
  3553. pthread_t *threadidptr)
  3554. {
  3555. pthread_t thread_id;
  3556. pthread_attr_t attr;
  3557. int result;
  3558. (void)pthread_attr_init(&attr);
  3559. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3560. /* Compile-time option to control stack size,
  3561. * e.g. -DUSE_STACK_SIZE=16384 */
  3562. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3563. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3564. result = pthread_create(&thread_id, &attr, func, param);
  3565. pthread_attr_destroy(&attr);
  3566. if ((result == 0) && (threadidptr != NULL)) {
  3567. *threadidptr = thread_id;
  3568. }
  3569. return result;
  3570. }
  3571. /* Wait for a thread to finish. */
  3572. static int
  3573. mg_join_thread(pthread_t threadid)
  3574. {
  3575. int result;
  3576. result = pthread_join(threadid, NULL);
  3577. return result;
  3578. }
  3579. #ifndef NO_CGI
  3580. static pid_t
  3581. spawn_process(struct mg_connection *conn,
  3582. const char *prog,
  3583. char *envblk,
  3584. char *envp[],
  3585. int fdin[2],
  3586. int fdout[2],
  3587. int fderr[2],
  3588. const char *dir)
  3589. {
  3590. pid_t pid;
  3591. const char *interp;
  3592. (void)envblk;
  3593. if (conn == NULL) {
  3594. return 0;
  3595. }
  3596. if ((pid = fork()) == -1) {
  3597. /* Parent */
  3598. send_http_error(conn,
  3599. 500,
  3600. "Error: Creating CGI process\nfork(): %s",
  3601. strerror(ERRNO));
  3602. } else if (pid == 0) {
  3603. /* Child */
  3604. if (chdir(dir) != 0) {
  3605. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3606. } else if (dup2(fdin[0], 0) == -1) {
  3607. mg_cry(conn,
  3608. "%s: dup2(%d, 0): %s",
  3609. __func__,
  3610. fdin[0],
  3611. strerror(ERRNO));
  3612. } else if (dup2(fdout[1], 1) == -1) {
  3613. mg_cry(conn,
  3614. "%s: dup2(%d, 1): %s",
  3615. __func__,
  3616. fdout[1],
  3617. strerror(ERRNO));
  3618. } else if (dup2(fderr[1], 2) == -1) {
  3619. mg_cry(conn,
  3620. "%s: dup2(%d, 2): %s",
  3621. __func__,
  3622. fderr[1],
  3623. strerror(ERRNO));
  3624. } else {
  3625. /* Keep stderr and stdout in two different pipes.
  3626. * Stdout will be sent back to the client,
  3627. * stderr should go into a server error log. */
  3628. (void)close(fdin[0]);
  3629. (void)close(fdout[1]);
  3630. (void)close(fderr[1]);
  3631. /* Close write end fdin and read end fdout and fderr */
  3632. (void)close(fdin[1]);
  3633. (void)close(fdout[0]);
  3634. (void)close(fderr[0]);
  3635. /* After exec, all signal handlers are restored to their default
  3636. * values, with one exception of SIGCHLD. According to
  3637. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3638. * leave unchanged after exec if it was set to be ignored. Restore
  3639. * it to default action. */
  3640. signal(SIGCHLD, SIG_DFL);
  3641. interp = conn->ctx->config[CGI_INTERPRETER];
  3642. if (interp == NULL) {
  3643. (void)execle(prog, prog, NULL, envp);
  3644. mg_cry(conn,
  3645. "%s: execle(%s): %s",
  3646. __func__,
  3647. prog,
  3648. strerror(ERRNO));
  3649. } else {
  3650. (void)execle(interp, interp, prog, NULL, envp);
  3651. mg_cry(conn,
  3652. "%s: execle(%s %s): %s",
  3653. __func__,
  3654. interp,
  3655. prog,
  3656. strerror(ERRNO));
  3657. }
  3658. }
  3659. exit(EXIT_FAILURE);
  3660. }
  3661. return pid;
  3662. }
  3663. #endif /* !NO_CGI */
  3664. static int
  3665. set_blocking_mode(SOCKET sock, int blocking)
  3666. {
  3667. int flags;
  3668. flags = fcntl(sock, F_GETFL, 0);
  3669. if (blocking) {
  3670. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3671. } else {
  3672. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3673. }
  3674. return 0;
  3675. }
  3676. #endif /* _WIN32 */
  3677. /* End of initial operating system specific define block. */
  3678. /* Get a random number (independent of C rand function) */
  3679. static uint64_t
  3680. get_random(void)
  3681. {
  3682. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3683. static uint64_t lcg = 0; /* Linear congruential generator */
  3684. struct timespec now;
  3685. memset(&now, 0, sizeof(now));
  3686. clock_gettime(CLOCK_MONOTONIC, &now);
  3687. if (lfsr == 0) {
  3688. /* lfsr will be only 0 if has not been initialized,
  3689. * so this code is called only once. */
  3690. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3691. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3692. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3693. + (uint64_t)(ptrdiff_t)&now;
  3694. } else {
  3695. /* Get the next step of both random number generators. */
  3696. lfsr = (lfsr >> 1)
  3697. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3698. << 63);
  3699. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3700. }
  3701. /* Combining two pseudo-random number generators and a high resolution part
  3702. * of the current server time will make it hard (impossible?) to guess the
  3703. * next number. */
  3704. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3705. }
  3706. static int
  3707. mg_poll(struct pollfd *pfd,
  3708. unsigned int n,
  3709. int milliseconds,
  3710. volatile int *stop_server)
  3711. {
  3712. int ms_now, result;
  3713. /* Call poll, but only for a maximum time of a few seconds.
  3714. * This will allow to stop the server after some seconds, instead
  3715. * of having to wait for a long socket timeout. */
  3716. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3717. do {
  3718. if (*stop_server) {
  3719. /* Shut down signal */
  3720. return -2;
  3721. }
  3722. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3723. ms_now = milliseconds;
  3724. }
  3725. result = poll(pfd, n, ms_now);
  3726. if (result != 0) {
  3727. /* Poll returned either success (1) or error (-1).
  3728. * Forward both to the caller. */
  3729. return result;
  3730. }
  3731. /* Poll returned timeout (0). */
  3732. if (milliseconds > 0) {
  3733. milliseconds -= ms_now;
  3734. }
  3735. } while (milliseconds != 0);
  3736. return result;
  3737. }
  3738. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3739. * descriptor. Return number of bytes written. */
  3740. static int
  3741. push(struct mg_context *ctx,
  3742. FILE *fp,
  3743. SOCKET sock,
  3744. SSL *ssl,
  3745. const char *buf,
  3746. int len,
  3747. double timeout)
  3748. {
  3749. struct timespec start, now;
  3750. int n, err;
  3751. #ifdef _WIN32
  3752. typedef int len_t;
  3753. #else
  3754. typedef size_t len_t;
  3755. #endif
  3756. if (timeout > 0) {
  3757. memset(&start, 0, sizeof(start));
  3758. memset(&now, 0, sizeof(now));
  3759. clock_gettime(CLOCK_MONOTONIC, &start);
  3760. }
  3761. if (ctx == NULL) {
  3762. return -1;
  3763. }
  3764. #ifdef NO_SSL
  3765. if (ssl) {
  3766. return -1;
  3767. }
  3768. #endif
  3769. do {
  3770. #ifndef NO_SSL
  3771. if (ssl != NULL) {
  3772. n = SSL_write(ssl, buf, len);
  3773. if (n <= 0) {
  3774. err = SSL_get_error(ssl, n);
  3775. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3776. err = ERRNO;
  3777. } else if ((err == SSL_ERROR_WANT_READ)
  3778. || (err == SSL_ERROR_WANT_WRITE)) {
  3779. n = 0;
  3780. } else {
  3781. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3782. return -1;
  3783. }
  3784. } else {
  3785. err = 0;
  3786. }
  3787. } else
  3788. #endif
  3789. if (fp != NULL) {
  3790. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3791. if (ferror(fp)) {
  3792. n = -1;
  3793. err = ERRNO;
  3794. } else {
  3795. err = 0;
  3796. }
  3797. } else {
  3798. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3799. err = (n < 0) ? ERRNO : 0;
  3800. if (n <= 0) {
  3801. /* shutdown of the socket at client side */
  3802. return -1;
  3803. }
  3804. #if defined(TEMPORARY_INSTRUMENTATION)
  3805. {
  3806. FILE *f = fopen("r:\\all.txt", "ab");
  3807. fprintf(f, "\r\n%010u SEND:\r\n", GetTickCount());
  3808. fwrite(buf, 1, n, f);
  3809. fclose(f);
  3810. }
  3811. #endif
  3812. }
  3813. if (ctx->stop_flag) {
  3814. return -1;
  3815. }
  3816. if ((n > 0) || (n == 0 && len == 0)) {
  3817. /* some data has been read, or no data was requested */
  3818. return n;
  3819. }
  3820. if (n < 0) {
  3821. /* socket error - check errno */
  3822. DEBUG_TRACE("send() failed, error %d", err);
  3823. /* TODO: error handling depending on the error code.
  3824. * These codes are different between Windows and Linux.
  3825. */
  3826. return -1;
  3827. }
  3828. /* Only in case n=0 (timeout), repeat calling the write function */
  3829. if (timeout > 0) {
  3830. clock_gettime(CLOCK_MONOTONIC, &now);
  3831. }
  3832. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3833. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3834. used */
  3835. return -1;
  3836. }
  3837. static int64_t
  3838. push_all(struct mg_context *ctx,
  3839. FILE *fp,
  3840. SOCKET sock,
  3841. SSL *ssl,
  3842. const char *buf,
  3843. int64_t len)
  3844. {
  3845. double timeout = -1.0;
  3846. int64_t n, nwritten = 0;
  3847. if (ctx == NULL) {
  3848. return -1;
  3849. }
  3850. if (ctx->config[REQUEST_TIMEOUT]) {
  3851. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3852. }
  3853. while (len > 0 && ctx->stop_flag == 0) {
  3854. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3855. if (n < 0) {
  3856. if (nwritten == 0) {
  3857. nwritten = n; /* Propagate the error */
  3858. }
  3859. break;
  3860. } else if (n == 0) {
  3861. break; /* No more data to write */
  3862. } else {
  3863. nwritten += n;
  3864. len -= n;
  3865. }
  3866. }
  3867. return nwritten;
  3868. }
  3869. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3870. * Return negative value on error, or number of bytes read on success. */
  3871. static int
  3872. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3873. {
  3874. int nread, err = 0;
  3875. #ifdef _WIN32
  3876. typedef int len_t;
  3877. #else
  3878. typedef size_t len_t;
  3879. #endif
  3880. if (fp != NULL) {
  3881. #if !defined(_WIN32_WCE)
  3882. /* Use read() instead of fread(), because if we're reading from the
  3883. * CGI pipe, fread() may block until IO buffer is filled up. We
  3884. * cannot afford to block and must pass all read bytes immediately
  3885. * to the client. */
  3886. nread = (int)read(fileno(fp), buf, (size_t)len);
  3887. #else
  3888. /* WinCE does not support CGI pipes */
  3889. nread = (int)fread(buf, 1, (size_t)len, fp);
  3890. #endif
  3891. err = (nread < 0) ? ERRNO : 0;
  3892. #ifndef NO_SSL
  3893. } else if (conn->ssl != NULL) {
  3894. struct pollfd pfd[1];
  3895. int pollres;
  3896. pfd[0].fd = conn->client.sock;
  3897. pfd[0].events = POLLIN;
  3898. pollres =
  3899. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3900. if (conn->ctx->stop_flag) {
  3901. return -1;
  3902. }
  3903. if (pollres > 0) {
  3904. nread = SSL_read(conn->ssl, buf, len);
  3905. if (nread <= 0) {
  3906. err = SSL_get_error(conn->ssl, nread);
  3907. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3908. err = ERRNO;
  3909. } else if ((err == SSL_ERROR_WANT_READ)
  3910. || (err == SSL_ERROR_WANT_WRITE)) {
  3911. nread = 0;
  3912. } else {
  3913. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3914. return -1;
  3915. }
  3916. } else {
  3917. err = 0;
  3918. }
  3919. } else if (pollres < 0) {
  3920. /* Error */
  3921. return -1;
  3922. } else {
  3923. /* pollres = 0 means timeout */
  3924. nread = 0;
  3925. }
  3926. #endif
  3927. } else {
  3928. struct pollfd pfd[1];
  3929. int pollres;
  3930. pfd[0].fd = conn->client.sock;
  3931. pfd[0].events = POLLIN;
  3932. pollres =
  3933. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3934. if (conn->ctx->stop_flag) {
  3935. return -1;
  3936. }
  3937. if (pollres > 0) {
  3938. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3939. err = (nread < 0) ? ERRNO : 0;
  3940. if (nread <= 0) {
  3941. /* shutdown of the socket at client side */
  3942. return -1;
  3943. }
  3944. #if defined(TEMPORARY_INSTRUMENTATION)
  3945. {
  3946. FILE *f = fopen("r:\\all.txt", "ab");
  3947. fprintf(f, "\r\n%010u RECV:\r\n", GetTickCount());
  3948. fwrite(buf, 1, nread, f);
  3949. fclose(f);
  3950. }
  3951. #endif
  3952. } else if (pollres < 0) {
  3953. /* error callint poll */
  3954. return -1;
  3955. } else {
  3956. /* pollres = 0 means timeout */
  3957. nread = 0;
  3958. }
  3959. }
  3960. if (conn->ctx->stop_flag) {
  3961. return -1;
  3962. }
  3963. if ((nread > 0) || (nread == 0 && len == 0)) {
  3964. /* some data has been read, or no data was requested */
  3965. return nread;
  3966. }
  3967. if (nread < 0) {
  3968. /* socket error - check errno */
  3969. #ifdef _WIN32
  3970. if (err == WSAEWOULDBLOCK) {
  3971. /* TODO: check if this is still required */
  3972. /* standard case if called from close_socket_gracefully */
  3973. return -1;
  3974. } else if (err == WSAETIMEDOUT) {
  3975. /* TODO: check if this is still required */
  3976. /* timeout is handled by the while loop */
  3977. return 0;
  3978. } else if (err == WSAECONNABORTED) {
  3979. /* See https://www.chilkatsoft.com/p/p_299.asp */
  3980. return -1;
  3981. } else {
  3982. DEBUG_TRACE("recv() failed, error %d", err);
  3983. return -1;
  3984. }
  3985. #else
  3986. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  3987. * if the timeout is reached and if the socket was set to non-
  3988. * blocking in close_socket_gracefully, so we can not distinguish
  3989. * here. We have to wait for the timeout in both cases for now.
  3990. */
  3991. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  3992. /* TODO: check if this is still required */
  3993. /* EAGAIN/EWOULDBLOCK:
  3994. * standard case if called from close_socket_gracefully
  3995. * => should return -1 */
  3996. /* or timeout occured
  3997. * => the code must stay in the while loop */
  3998. /* EINTR can be generated on a socket with a timeout set even
  3999. * when SA_RESTART is effective for all relevant signals
  4000. * (see signal(7)).
  4001. * => stay in the while loop */
  4002. } else {
  4003. DEBUG_TRACE("recv() failed, error %d", err);
  4004. return -1;
  4005. }
  4006. #endif
  4007. }
  4008. /* Timeout occured, but no data available. */
  4009. return -1;
  4010. }
  4011. static int
  4012. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4013. {
  4014. int n, nread = 0;
  4015. double timeout = -1.0;
  4016. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4017. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4018. }
  4019. while (len > 0 && conn->ctx->stop_flag == 0) {
  4020. n = pull(fp, conn, buf + nread, len, timeout);
  4021. if (n < 0) {
  4022. if (nread == 0) {
  4023. nread = n; /* Propagate the error */
  4024. }
  4025. break;
  4026. } else if (n == 0) {
  4027. break; /* No more data to read */
  4028. } else {
  4029. conn->consumed_content += n;
  4030. nread += n;
  4031. len -= n;
  4032. }
  4033. }
  4034. return nread;
  4035. }
  4036. static void
  4037. discard_unread_request_data(struct mg_connection *conn)
  4038. {
  4039. char buf[MG_BUF_LEN];
  4040. size_t to_read;
  4041. int nread;
  4042. if (conn == NULL) {
  4043. return;
  4044. }
  4045. to_read = sizeof(buf);
  4046. if (conn->is_chunked) {
  4047. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4048. * completely */
  4049. while (conn->is_chunked == 1) {
  4050. nread = mg_read(conn, buf, to_read);
  4051. if (nread <= 0) {
  4052. break;
  4053. }
  4054. }
  4055. } else {
  4056. /* Not chunked: content length is known */
  4057. while (conn->consumed_content < conn->content_len) {
  4058. if (to_read
  4059. > (size_t)(conn->content_len - conn->consumed_content)) {
  4060. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4061. }
  4062. nread = mg_read(conn, buf, to_read);
  4063. if (nread <= 0) {
  4064. break;
  4065. }
  4066. }
  4067. }
  4068. }
  4069. static int
  4070. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4071. {
  4072. int64_t n, buffered_len, nread;
  4073. int64_t len64 =
  4074. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4075. * int, we may not read more
  4076. * bytes */
  4077. const char *body;
  4078. if (conn == NULL) {
  4079. return 0;
  4080. }
  4081. /* If Content-Length is not set for a PUT or POST request, read until
  4082. * socket is closed */
  4083. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4084. conn->content_len = INT64_MAX;
  4085. conn->must_close = 1;
  4086. }
  4087. nread = 0;
  4088. if (conn->consumed_content < conn->content_len) {
  4089. /* Adjust number of bytes to read. */
  4090. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4091. if (left_to_read < len64) {
  4092. /* Do not read more than the total content length of the request.
  4093. */
  4094. len64 = left_to_read;
  4095. }
  4096. /* Return buffered data */
  4097. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4098. - conn->consumed_content;
  4099. if (buffered_len > 0) {
  4100. if (len64 < buffered_len) {
  4101. buffered_len = len64;
  4102. }
  4103. body = conn->buf + conn->request_len + conn->consumed_content;
  4104. memcpy(buf, body, (size_t)buffered_len);
  4105. len64 -= buffered_len;
  4106. conn->consumed_content += buffered_len;
  4107. nread += buffered_len;
  4108. buf = (char *)buf + buffered_len;
  4109. }
  4110. /* We have returned all buffered data. Read new data from the remote
  4111. * socket.
  4112. */
  4113. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4114. nread += n;
  4115. } else {
  4116. nread = ((nread > 0) ? nread : n);
  4117. }
  4118. }
  4119. return (int)nread;
  4120. }
  4121. static char
  4122. mg_getc(struct mg_connection *conn)
  4123. {
  4124. char c;
  4125. if (conn == NULL) {
  4126. return 0;
  4127. }
  4128. conn->content_len++;
  4129. if (mg_read_inner(conn, &c, 1) <= 0) {
  4130. return (char)0;
  4131. }
  4132. return c;
  4133. }
  4134. int
  4135. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4136. {
  4137. if (len > INT_MAX) {
  4138. len = INT_MAX;
  4139. }
  4140. if (conn == NULL) {
  4141. return 0;
  4142. }
  4143. if (conn->is_chunked) {
  4144. size_t all_read = 0;
  4145. while (len > 0) {
  4146. if (conn->is_chunked == 2) {
  4147. /* No more data left to read */
  4148. return 0;
  4149. }
  4150. if (conn->chunk_remainder) {
  4151. /* copy from the remainder of the last received chunk */
  4152. long read_ret;
  4153. size_t read_now =
  4154. ((conn->chunk_remainder > len) ? (len)
  4155. : (conn->chunk_remainder));
  4156. conn->content_len += (int)read_now;
  4157. read_ret =
  4158. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4159. if (read_ret < 1) {
  4160. /* read error */
  4161. return -1;
  4162. }
  4163. all_read += (size_t)read_ret;
  4164. conn->chunk_remainder -= (size_t)read_ret;
  4165. len -= (size_t)read_ret;
  4166. if (conn->chunk_remainder == 0) {
  4167. /* Add data bytes in the current chunk have been read,
  4168. * so we are expecting \r\n now. */
  4169. char x1 = mg_getc(conn);
  4170. char x2 = mg_getc(conn);
  4171. if ((x1 != '\r') || (x2 != '\n')) {
  4172. /* Protocol violation */
  4173. return -1;
  4174. }
  4175. }
  4176. } else {
  4177. /* fetch a new chunk */
  4178. int i = 0;
  4179. char lenbuf[64];
  4180. char *end = 0;
  4181. unsigned long chunkSize = 0;
  4182. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4183. lenbuf[i] = mg_getc(conn);
  4184. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4185. continue;
  4186. }
  4187. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4188. lenbuf[i + 1] = 0;
  4189. chunkSize = strtoul(lenbuf, &end, 16);
  4190. if (chunkSize == 0) {
  4191. /* regular end of content */
  4192. conn->is_chunked = 2;
  4193. }
  4194. break;
  4195. }
  4196. if (!isxdigit(lenbuf[i])) {
  4197. /* illegal character for chunk length */
  4198. return -1;
  4199. }
  4200. }
  4201. if ((end == NULL) || (*end != '\r')) {
  4202. /* chunksize not set correctly */
  4203. return -1;
  4204. }
  4205. if (chunkSize == 0) {
  4206. break;
  4207. }
  4208. conn->chunk_remainder = chunkSize;
  4209. }
  4210. }
  4211. return (int)all_read;
  4212. }
  4213. return mg_read_inner(conn, buf, len);
  4214. }
  4215. int
  4216. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4217. {
  4218. time_t now;
  4219. int64_t n, total, allowed;
  4220. if (conn == NULL) {
  4221. return 0;
  4222. }
  4223. if (conn->throttle > 0) {
  4224. if ((now = time(NULL)) != conn->last_throttle_time) {
  4225. conn->last_throttle_time = now;
  4226. conn->last_throttle_bytes = 0;
  4227. }
  4228. allowed = conn->throttle - conn->last_throttle_bytes;
  4229. if (allowed > (int64_t)len) {
  4230. allowed = (int64_t)len;
  4231. }
  4232. if ((total = push_all(conn->ctx,
  4233. NULL,
  4234. conn->client.sock,
  4235. conn->ssl,
  4236. (const char *)buf,
  4237. (int64_t)allowed)) == allowed) {
  4238. buf = (const char *)buf + total;
  4239. conn->last_throttle_bytes += total;
  4240. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4241. allowed = (conn->throttle > ((int64_t)len - total))
  4242. ? (int64_t)len - total
  4243. : conn->throttle;
  4244. if ((n = push_all(conn->ctx,
  4245. NULL,
  4246. conn->client.sock,
  4247. conn->ssl,
  4248. (const char *)buf,
  4249. (int64_t)allowed)) != allowed) {
  4250. break;
  4251. }
  4252. sleep(1);
  4253. conn->last_throttle_bytes = allowed;
  4254. conn->last_throttle_time = time(NULL);
  4255. buf = (const char *)buf + n;
  4256. total += n;
  4257. }
  4258. }
  4259. } else {
  4260. total = push_all(conn->ctx,
  4261. NULL,
  4262. conn->client.sock,
  4263. conn->ssl,
  4264. (const char *)buf,
  4265. (int64_t)len);
  4266. }
  4267. return (int)total;
  4268. }
  4269. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4270. static int
  4271. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4272. {
  4273. va_list ap_copy;
  4274. size_t size = MG_BUF_LEN / 4;
  4275. int len = -1;
  4276. *buf = NULL;
  4277. while (len < 0) {
  4278. if (*buf) {
  4279. mg_free(*buf);
  4280. }
  4281. size *= 4;
  4282. *buf = (char *)mg_malloc(size);
  4283. if (!*buf) {
  4284. break;
  4285. }
  4286. va_copy(ap_copy, ap);
  4287. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4288. va_end(ap_copy);
  4289. (*buf)[size - 1] = 0;
  4290. }
  4291. return len;
  4292. }
  4293. /* Print message to buffer. If buffer is large enough to hold the message,
  4294. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4295. * and return allocated buffer. */
  4296. static int
  4297. alloc_vprintf(char **out_buf,
  4298. char *prealloc_buf,
  4299. size_t prealloc_size,
  4300. const char *fmt,
  4301. va_list ap)
  4302. {
  4303. va_list ap_copy;
  4304. int len;
  4305. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4306. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4307. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4308. * Therefore, we make two passes: on first pass, get required message
  4309. * length.
  4310. * On second pass, actually print the message. */
  4311. va_copy(ap_copy, ap);
  4312. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4313. va_end(ap_copy);
  4314. if (len < 0) {
  4315. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4316. * Switch to alternative code path that uses incremental allocations.
  4317. */
  4318. va_copy(ap_copy, ap);
  4319. len = alloc_vprintf2(out_buf, fmt, ap);
  4320. va_end(ap_copy);
  4321. } else if ((size_t)(len) >= prealloc_size) {
  4322. /* The pre-allocated buffer not large enough. */
  4323. /* Allocate a new buffer. */
  4324. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4325. if (!*out_buf) {
  4326. /* Allocation failed. Return -1 as "out of memory" error. */
  4327. return -1;
  4328. }
  4329. /* Buffer allocation successful. Store the string there. */
  4330. va_copy(ap_copy, ap);
  4331. IGNORE_UNUSED_RESULT(
  4332. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4333. va_end(ap_copy);
  4334. } else {
  4335. /* The pre-allocated buffer is large enough.
  4336. * Use it to store the string and return the address. */
  4337. va_copy(ap_copy, ap);
  4338. IGNORE_UNUSED_RESULT(
  4339. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4340. va_end(ap_copy);
  4341. *out_buf = prealloc_buf;
  4342. }
  4343. return len;
  4344. }
  4345. static int
  4346. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4347. {
  4348. char mem[MG_BUF_LEN];
  4349. char *buf = NULL;
  4350. int len;
  4351. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4352. len = mg_write(conn, buf, (size_t)len);
  4353. }
  4354. if (buf != mem && buf != NULL) {
  4355. mg_free(buf);
  4356. }
  4357. return len;
  4358. }
  4359. int
  4360. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4361. {
  4362. va_list ap;
  4363. int result;
  4364. va_start(ap, fmt);
  4365. result = mg_vprintf(conn, fmt, ap);
  4366. va_end(ap);
  4367. return result;
  4368. }
  4369. int
  4370. mg_url_decode(const char *src,
  4371. int src_len,
  4372. char *dst,
  4373. int dst_len,
  4374. int is_form_url_encoded)
  4375. {
  4376. int i, j, a, b;
  4377. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4378. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4379. if (i < src_len - 2 && src[i] == '%'
  4380. && isxdigit(*(const unsigned char *)(src + i + 1))
  4381. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4382. a = tolower(*(const unsigned char *)(src + i + 1));
  4383. b = tolower(*(const unsigned char *)(src + i + 2));
  4384. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4385. i += 2;
  4386. } else if (is_form_url_encoded && src[i] == '+') {
  4387. dst[j] = ' ';
  4388. } else {
  4389. dst[j] = src[i];
  4390. }
  4391. }
  4392. dst[j] = '\0'; /* Null-terminate the destination */
  4393. return (i >= src_len) ? j : -1;
  4394. }
  4395. int
  4396. mg_get_var(const char *data,
  4397. size_t data_len,
  4398. const char *name,
  4399. char *dst,
  4400. size_t dst_len)
  4401. {
  4402. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4403. }
  4404. int
  4405. mg_get_var2(const char *data,
  4406. size_t data_len,
  4407. const char *name,
  4408. char *dst,
  4409. size_t dst_len,
  4410. size_t occurrence)
  4411. {
  4412. const char *p, *e, *s;
  4413. size_t name_len;
  4414. int len;
  4415. if (dst == NULL || dst_len == 0) {
  4416. len = -2;
  4417. } else if (data == NULL || name == NULL || data_len == 0) {
  4418. len = -1;
  4419. dst[0] = '\0';
  4420. } else {
  4421. name_len = strlen(name);
  4422. e = data + data_len;
  4423. len = -1;
  4424. dst[0] = '\0';
  4425. /* data is "var1=val1&var2=val2...". Find variable first */
  4426. for (p = data; p + name_len < e; p++) {
  4427. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4428. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4429. /* Point p to variable value */
  4430. p += name_len + 1;
  4431. /* Point s to the end of the value */
  4432. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4433. if (s == NULL) {
  4434. s = e;
  4435. }
  4436. /* assert(s >= p); */
  4437. if (s < p) {
  4438. return -3;
  4439. }
  4440. /* Decode variable into destination buffer */
  4441. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4442. /* Redirect error code from -1 to -2 (destination buffer too
  4443. * small). */
  4444. if (len == -1) {
  4445. len = -2;
  4446. }
  4447. break;
  4448. }
  4449. }
  4450. }
  4451. return len;
  4452. }
  4453. /* HCP24: some changes to compare hole var_name */
  4454. int
  4455. mg_get_cookie(const char *cookie_header,
  4456. const char *var_name,
  4457. char *dst,
  4458. size_t dst_size)
  4459. {
  4460. const char *s, *p, *end;
  4461. int name_len, len = -1;
  4462. if (dst == NULL || dst_size == 0) {
  4463. return -2;
  4464. }
  4465. dst[0] = '\0';
  4466. if (var_name == NULL || (s = cookie_header) == NULL) {
  4467. return -1;
  4468. }
  4469. name_len = (int)strlen(var_name);
  4470. end = s + strlen(s);
  4471. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4472. if (s[name_len] == '=') {
  4473. /* HCP24: now check is it a substring or a full cookie name */
  4474. if ((s == cookie_header) || (s[-1] == ' ')) {
  4475. s += name_len + 1;
  4476. if ((p = strchr(s, ' ')) == NULL) {
  4477. p = end;
  4478. }
  4479. if (p[-1] == ';') {
  4480. p--;
  4481. }
  4482. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4483. s++;
  4484. p--;
  4485. }
  4486. if ((size_t)(p - s) < dst_size) {
  4487. len = (int)(p - s);
  4488. mg_strlcpy(dst, s, (size_t)len + 1);
  4489. } else {
  4490. len = -3;
  4491. }
  4492. break;
  4493. }
  4494. }
  4495. }
  4496. return len;
  4497. }
  4498. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4499. static void
  4500. base64_encode(const unsigned char *src, int src_len, char *dst)
  4501. {
  4502. static const char *b64 =
  4503. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4504. int i, j, a, b, c;
  4505. for (i = j = 0; i < src_len; i += 3) {
  4506. a = src[i];
  4507. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4508. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4509. dst[j++] = b64[a >> 2];
  4510. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4511. if (i + 1 < src_len) {
  4512. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4513. }
  4514. if (i + 2 < src_len) {
  4515. dst[j++] = b64[c & 63];
  4516. }
  4517. }
  4518. while (j % 4 != 0) {
  4519. dst[j++] = '=';
  4520. }
  4521. dst[j++] = '\0';
  4522. }
  4523. #endif
  4524. #if defined(USE_LUA)
  4525. static unsigned char
  4526. b64reverse(char letter)
  4527. {
  4528. if (letter >= 'A' && letter <= 'Z') {
  4529. return letter - 'A';
  4530. }
  4531. if (letter >= 'a' && letter <= 'z') {
  4532. return letter - 'a' + 26;
  4533. }
  4534. if (letter >= '0' && letter <= '9') {
  4535. return letter - '0' + 52;
  4536. }
  4537. if (letter == '+') {
  4538. return 62;
  4539. }
  4540. if (letter == '/') {
  4541. return 63;
  4542. }
  4543. if (letter == '=') {
  4544. return 255; /* normal end */
  4545. }
  4546. return 254; /* error */
  4547. }
  4548. static int
  4549. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4550. {
  4551. int i;
  4552. unsigned char a, b, c, d;
  4553. *dst_len = 0;
  4554. for (i = 0; i < src_len; i += 4) {
  4555. a = b64reverse(src[i]);
  4556. if (a >= 254) {
  4557. return i;
  4558. }
  4559. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4560. if (b >= 254) {
  4561. return i + 1;
  4562. }
  4563. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4564. if (c == 254) {
  4565. return i + 2;
  4566. }
  4567. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4568. if (d == 254) {
  4569. return i + 3;
  4570. }
  4571. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4572. if (c != 255) {
  4573. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4574. if (d != 255) {
  4575. dst[(*dst_len)++] = (c << 6) + d;
  4576. }
  4577. }
  4578. }
  4579. return -1;
  4580. }
  4581. #endif
  4582. static int
  4583. is_put_or_delete_method(const struct mg_connection *conn)
  4584. {
  4585. if (conn) {
  4586. const char *s = conn->request_info.request_method;
  4587. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4588. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4589. }
  4590. return 0;
  4591. }
  4592. static void
  4593. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4594. char *filename, /* out: filename */
  4595. size_t filename_buf_len, /* in: size of filename buffer */
  4596. struct mg_file_stat *filestat, /* out: file structure */
  4597. int *is_found, /* out: file found (directly) */
  4598. int *is_script_resource, /* out: handled by a script? */
  4599. int *is_websocket_request, /* out: websocket connetion? */
  4600. int *is_put_or_delete_request /* out: put/delete a file? */
  4601. )
  4602. {
  4603. /* TODO (high): Restructure this function */
  4604. #if !defined(NO_FILES)
  4605. const char *uri = conn->request_info.local_uri;
  4606. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4607. const char *rewrite;
  4608. struct vec a, b;
  4609. int match_len;
  4610. char gz_path[PATH_MAX];
  4611. char const *accept_encoding;
  4612. int truncated;
  4613. #if !defined(NO_CGI) || defined(USE_LUA)
  4614. char *p;
  4615. #endif
  4616. #else
  4617. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4618. #endif
  4619. memset(filestat, 0, sizeof(*filestat));
  4620. *filename = 0;
  4621. *is_found = 0;
  4622. *is_script_resource = 0;
  4623. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4624. #if defined(USE_WEBSOCKET)
  4625. *is_websocket_request = is_websocket_protocol(conn);
  4626. #if !defined(NO_FILES)
  4627. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4628. root = conn->ctx->config[WEBSOCKET_ROOT];
  4629. }
  4630. #endif /* !NO_FILES */
  4631. #else /* USE_WEBSOCKET */
  4632. *is_websocket_request = 0;
  4633. #endif /* USE_WEBSOCKET */
  4634. #if !defined(NO_FILES)
  4635. /* Note that root == NULL is a regular use case here. This occurs,
  4636. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4637. * config is not required. */
  4638. if (root == NULL) {
  4639. /* all file related outputs have already been set to 0, just return
  4640. */
  4641. return;
  4642. }
  4643. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4644. * of the path one byte on the right.
  4645. * If document_root is NULL, leave the file empty. */
  4646. mg_snprintf(
  4647. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4648. if (truncated) {
  4649. goto interpret_cleanup;
  4650. }
  4651. rewrite = conn->ctx->config[REWRITE];
  4652. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4653. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4654. mg_snprintf(conn,
  4655. &truncated,
  4656. filename,
  4657. filename_buf_len - 1,
  4658. "%.*s%s",
  4659. (int)b.len,
  4660. b.ptr,
  4661. uri + match_len);
  4662. break;
  4663. }
  4664. }
  4665. if (truncated) {
  4666. goto interpret_cleanup;
  4667. }
  4668. /* Local file path and name, corresponding to requested URI
  4669. * is now stored in "filename" variable. */
  4670. if (mg_stat(conn, filename, filestat)) {
  4671. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4672. /* File exists. Check if it is a script type. */
  4673. if (0
  4674. #if !defined(NO_CGI)
  4675. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4676. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4677. filename) > 0
  4678. #endif
  4679. #if defined(USE_LUA)
  4680. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4681. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4682. filename) > 0
  4683. #endif
  4684. #if defined(USE_DUKTAPE)
  4685. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4686. strlen(
  4687. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4688. filename) > 0
  4689. #endif
  4690. ) {
  4691. /* The request addresses a CGI script or a Lua script. The URI
  4692. * corresponds to the script itself (like /path/script.cgi),
  4693. * and there is no additional resource path
  4694. * (like /path/script.cgi/something).
  4695. * Requests that modify (replace or delete) a resource, like
  4696. * PUT and DELETE requests, should replace/delete the script
  4697. * file.
  4698. * Requests that read or write from/to a resource, like GET and
  4699. * POST requests, should call the script and return the
  4700. * generated response. */
  4701. *is_script_resource = !*is_put_or_delete_request;
  4702. }
  4703. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4704. *is_found = 1;
  4705. return;
  4706. }
  4707. /* If we can't find the actual file, look for the file
  4708. * with the same name but a .gz extension. If we find it,
  4709. * use that and set the gzipped flag in the file struct
  4710. * to indicate that the response need to have the content-
  4711. * encoding: gzip header.
  4712. * We can only do this if the browser declares support. */
  4713. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4714. if (strstr(accept_encoding, "gzip") != NULL) {
  4715. mg_snprintf(
  4716. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4717. if (truncated) {
  4718. goto interpret_cleanup;
  4719. }
  4720. if (mg_stat(conn, gz_path, filestat)) {
  4721. if (filestat) {
  4722. filestat->is_gzipped = 1;
  4723. *is_found = 1;
  4724. }
  4725. /* Currently gz files can not be scripts. */
  4726. return;
  4727. }
  4728. }
  4729. }
  4730. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4731. /* Support PATH_INFO for CGI scripts. */
  4732. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4733. if (*p == '/') {
  4734. *p = '\0';
  4735. if ((0
  4736. #if !defined(NO_CGI)
  4737. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4738. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4739. filename) > 0
  4740. #endif
  4741. #if defined(USE_LUA)
  4742. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4743. strlen(
  4744. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4745. filename) > 0
  4746. #endif
  4747. #if defined(USE_DUKTAPE)
  4748. || match_prefix(
  4749. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4750. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4751. filename) > 0
  4752. #endif
  4753. ) && mg_stat(conn, filename, filestat)) {
  4754. /* Shift PATH_INFO block one character right, e.g.
  4755. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4756. * conn->path_info is pointing to the local variable "path"
  4757. * declared in handle_request(), so PATH_INFO is not valid
  4758. * after handle_request returns. */
  4759. conn->path_info = p + 1;
  4760. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4761. * trailing \0 */
  4762. p[1] = '/';
  4763. *is_script_resource = 1;
  4764. break;
  4765. } else {
  4766. *p = '/';
  4767. }
  4768. }
  4769. }
  4770. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4771. #endif /* !defined(NO_FILES) */
  4772. return;
  4773. #if !defined(NO_FILES)
  4774. /* Reset all outputs */
  4775. interpret_cleanup:
  4776. memset(filestat, 0, sizeof(*filestat));
  4777. *filename = 0;
  4778. *is_found = 0;
  4779. *is_script_resource = 0;
  4780. *is_websocket_request = 0;
  4781. *is_put_or_delete_request = 0;
  4782. #endif /* !defined(NO_FILES) */
  4783. }
  4784. /* Check whether full request is buffered. Return:
  4785. * -1 if request is malformed
  4786. * 0 if request is not yet fully buffered
  4787. * >0 actual request length, including last \r\n\r\n */
  4788. static int
  4789. get_request_len(const char *buf, int buflen)
  4790. {
  4791. const char *s, *e;
  4792. int len = 0;
  4793. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4794. /* Control characters are not allowed but >=128 is. */
  4795. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4796. && *(const unsigned char *)s < 128) {
  4797. len = -1;
  4798. break; /* [i_a] abort scan as soon as one malformed character is
  4799. * found; */
  4800. /* don't let subsequent \r\n\r\n win us over anyhow */
  4801. } else if (s[0] == '\n' && s[1] == '\n') {
  4802. len = (int)(s - buf) + 2;
  4803. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4804. len = (int)(s - buf) + 3;
  4805. }
  4806. return len;
  4807. }
  4808. #if !defined(NO_CACHING)
  4809. /* Convert month to the month number. Return -1 on error, or month number */
  4810. static int
  4811. get_month_index(const char *s)
  4812. {
  4813. size_t i;
  4814. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4815. if (!strcmp(s, month_names[i])) {
  4816. return (int)i;
  4817. }
  4818. }
  4819. return -1;
  4820. }
  4821. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4822. static time_t
  4823. parse_date_string(const char *datetime)
  4824. {
  4825. char month_str[32] = {0};
  4826. int second, minute, hour, day, month, year;
  4827. time_t result = (time_t)0;
  4828. struct tm tm;
  4829. if ((sscanf(datetime,
  4830. "%d/%3s/%d %d:%d:%d",
  4831. &day,
  4832. month_str,
  4833. &year,
  4834. &hour,
  4835. &minute,
  4836. &second) == 6) || (sscanf(datetime,
  4837. "%d %3s %d %d:%d:%d",
  4838. &day,
  4839. month_str,
  4840. &year,
  4841. &hour,
  4842. &minute,
  4843. &second) == 6)
  4844. || (sscanf(datetime,
  4845. "%*3s, %d %3s %d %d:%d:%d",
  4846. &day,
  4847. month_str,
  4848. &year,
  4849. &hour,
  4850. &minute,
  4851. &second) == 6) || (sscanf(datetime,
  4852. "%d-%3s-%d %d:%d:%d",
  4853. &day,
  4854. month_str,
  4855. &year,
  4856. &hour,
  4857. &minute,
  4858. &second) == 6)) {
  4859. month = get_month_index(month_str);
  4860. if ((month >= 0) && (year >= 1970)) {
  4861. memset(&tm, 0, sizeof(tm));
  4862. tm.tm_year = year - 1900;
  4863. tm.tm_mon = month;
  4864. tm.tm_mday = day;
  4865. tm.tm_hour = hour;
  4866. tm.tm_min = minute;
  4867. tm.tm_sec = second;
  4868. result = timegm(&tm);
  4869. }
  4870. }
  4871. return result;
  4872. }
  4873. #endif /* !NO_CACHING */
  4874. /* Protect against directory disclosure attack by removing '..',
  4875. * excessive '/' and '\' characters */
  4876. static void
  4877. remove_double_dots_and_double_slashes(char *s)
  4878. {
  4879. char *p = s;
  4880. while ((s[0] == '.') && (s[1] == '.')) {
  4881. s++;
  4882. }
  4883. while (*s != '\0') {
  4884. *p++ = *s++;
  4885. if (s[-1] == '/' || s[-1] == '\\') {
  4886. /* Skip all following slashes, backslashes and double-dots */
  4887. while (s[0] != '\0') {
  4888. if (s[0] == '/' || s[0] == '\\') {
  4889. s++;
  4890. } else if (s[0] == '.' && s[1] == '.') {
  4891. s += 2;
  4892. } else {
  4893. break;
  4894. }
  4895. }
  4896. }
  4897. }
  4898. *p = '\0';
  4899. }
  4900. static const struct {
  4901. const char *extension;
  4902. size_t ext_len;
  4903. const char *mime_type;
  4904. } builtin_mime_types[] = {
  4905. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4906. * application types */
  4907. {".doc", 4, "application/msword"},
  4908. {".eps", 4, "application/postscript"},
  4909. {".exe", 4, "application/octet-stream"},
  4910. {".js", 3, "application/javascript"},
  4911. {".json", 5, "application/json"},
  4912. {".pdf", 4, "application/pdf"},
  4913. {".ps", 3, "application/postscript"},
  4914. {".rtf", 4, "application/rtf"},
  4915. {".xhtml", 6, "application/xhtml+xml"},
  4916. {".xsl", 4, "application/xml"},
  4917. {".xslt", 5, "application/xml"},
  4918. /* fonts */
  4919. {".ttf", 4, "application/font-sfnt"},
  4920. {".cff", 4, "application/font-sfnt"},
  4921. {".otf", 4, "application/font-sfnt"},
  4922. {".aat", 4, "application/font-sfnt"},
  4923. {".sil", 4, "application/font-sfnt"},
  4924. {".pfr", 4, "application/font-tdpfr"},
  4925. {".woff", 5, "application/font-woff"},
  4926. /* audio */
  4927. {".mp3", 4, "audio/mpeg"},
  4928. {".oga", 4, "audio/ogg"},
  4929. {".ogg", 4, "audio/ogg"},
  4930. /* image */
  4931. {".gif", 4, "image/gif"},
  4932. {".ief", 4, "image/ief"},
  4933. {".jpeg", 5, "image/jpeg"},
  4934. {".jpg", 4, "image/jpeg"},
  4935. {".jpm", 4, "image/jpm"},
  4936. {".jpx", 4, "image/jpx"},
  4937. {".png", 4, "image/png"},
  4938. {".svg", 4, "image/svg+xml"},
  4939. {".tif", 4, "image/tiff"},
  4940. {".tiff", 5, "image/tiff"},
  4941. /* model */
  4942. {".wrl", 4, "model/vrml"},
  4943. /* text */
  4944. {".css", 4, "text/css"},
  4945. {".csv", 4, "text/csv"},
  4946. {".htm", 4, "text/html"},
  4947. {".html", 5, "text/html"},
  4948. {".sgm", 4, "text/sgml"},
  4949. {".shtm", 5, "text/html"},
  4950. {".shtml", 6, "text/html"},
  4951. {".txt", 4, "text/plain"},
  4952. {".xml", 4, "text/xml"},
  4953. /* video */
  4954. {".mov", 4, "video/quicktime"},
  4955. {".mp4", 4, "video/mp4"},
  4956. {".mpeg", 5, "video/mpeg"},
  4957. {".mpg", 4, "video/mpeg"},
  4958. {".ogv", 4, "video/ogg"},
  4959. {".qt", 3, "video/quicktime"},
  4960. /* not registered types
  4961. * (http://reference.sitepoint.com/html/mime-types-full,
  4962. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4963. {".arj", 4, "application/x-arj-compressed"},
  4964. {".gz", 3, "application/x-gunzip"},
  4965. {".rar", 4, "application/x-arj-compressed"},
  4966. {".swf", 4, "application/x-shockwave-flash"},
  4967. {".tar", 4, "application/x-tar"},
  4968. {".tgz", 4, "application/x-tar-gz"},
  4969. {".torrent", 8, "application/x-bittorrent"},
  4970. {".ppt", 4, "application/x-mspowerpoint"},
  4971. {".xls", 4, "application/x-msexcel"},
  4972. {".zip", 4, "application/x-zip-compressed"},
  4973. {".aac",
  4974. 4,
  4975. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4976. {".aif", 4, "audio/x-aif"},
  4977. {".m3u", 4, "audio/x-mpegurl"},
  4978. {".mid", 4, "audio/x-midi"},
  4979. {".ra", 3, "audio/x-pn-realaudio"},
  4980. {".ram", 4, "audio/x-pn-realaudio"},
  4981. {".wav", 4, "audio/x-wav"},
  4982. {".bmp", 4, "image/bmp"},
  4983. {".ico", 4, "image/x-icon"},
  4984. {".pct", 4, "image/x-pct"},
  4985. {".pict", 5, "image/pict"},
  4986. {".rgb", 4, "image/x-rgb"},
  4987. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  4988. {".asf", 4, "video/x-ms-asf"},
  4989. {".avi", 4, "video/x-msvideo"},
  4990. {".m4v", 4, "video/x-m4v"},
  4991. {NULL, 0, NULL}};
  4992. const char *
  4993. mg_get_builtin_mime_type(const char *path)
  4994. {
  4995. const char *ext;
  4996. size_t i, path_len;
  4997. path_len = strlen(path);
  4998. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  4999. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5000. if (path_len > builtin_mime_types[i].ext_len
  5001. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5002. return builtin_mime_types[i].mime_type;
  5003. }
  5004. }
  5005. return "text/plain";
  5006. }
  5007. /* Look at the "path" extension and figure what mime type it has.
  5008. * Store mime type in the vector. */
  5009. static void
  5010. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5011. {
  5012. struct vec ext_vec, mime_vec;
  5013. const char *list, *ext;
  5014. size_t path_len;
  5015. path_len = strlen(path);
  5016. if (ctx == NULL || vec == NULL) {
  5017. return;
  5018. }
  5019. /* Scan user-defined mime types first, in case user wants to
  5020. * override default mime types. */
  5021. list = ctx->config[EXTRA_MIME_TYPES];
  5022. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5023. /* ext now points to the path suffix */
  5024. ext = path + path_len - ext_vec.len;
  5025. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5026. *vec = mime_vec;
  5027. return;
  5028. }
  5029. }
  5030. vec->ptr = mg_get_builtin_mime_type(path);
  5031. vec->len = strlen(vec->ptr);
  5032. }
  5033. /* Stringify binary data. Output buffer must be twice as big as input,
  5034. * because each byte takes 2 bytes in string representation */
  5035. static void
  5036. bin2str(char *to, const unsigned char *p, size_t len)
  5037. {
  5038. static const char *hex = "0123456789abcdef";
  5039. for (; len--; p++) {
  5040. *to++ = hex[p[0] >> 4];
  5041. *to++ = hex[p[0] & 0x0f];
  5042. }
  5043. *to = '\0';
  5044. }
  5045. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5046. char *
  5047. mg_md5(char buf[33], ...)
  5048. {
  5049. md5_byte_t hash[16];
  5050. const char *p;
  5051. va_list ap;
  5052. md5_state_t ctx;
  5053. md5_init(&ctx);
  5054. va_start(ap, buf);
  5055. while ((p = va_arg(ap, const char *)) != NULL) {
  5056. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5057. }
  5058. va_end(ap);
  5059. md5_finish(&ctx, hash);
  5060. bin2str(buf, hash, sizeof(hash));
  5061. return buf;
  5062. }
  5063. /* Check the user's password, return 1 if OK */
  5064. static int
  5065. check_password(const char *method,
  5066. const char *ha1,
  5067. const char *uri,
  5068. const char *nonce,
  5069. const char *nc,
  5070. const char *cnonce,
  5071. const char *qop,
  5072. const char *response)
  5073. {
  5074. char ha2[32 + 1], expected_response[32 + 1];
  5075. /* Some of the parameters may be NULL */
  5076. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5077. || qop == NULL
  5078. || response == NULL) {
  5079. return 0;
  5080. }
  5081. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5082. if (strlen(response) != 32) {
  5083. return 0;
  5084. }
  5085. mg_md5(ha2, method, ":", uri, NULL);
  5086. mg_md5(expected_response,
  5087. ha1,
  5088. ":",
  5089. nonce,
  5090. ":",
  5091. nc,
  5092. ":",
  5093. cnonce,
  5094. ":",
  5095. qop,
  5096. ":",
  5097. ha2,
  5098. NULL);
  5099. return mg_strcasecmp(response, expected_response) == 0;
  5100. }
  5101. /* Use the global passwords file, if specified by auth_gpass option,
  5102. * or search for .htpasswd in the requested directory. */
  5103. static void
  5104. open_auth_file(struct mg_connection *conn,
  5105. const char *path,
  5106. struct mg_file *filep)
  5107. {
  5108. if (conn != NULL && conn->ctx != NULL) {
  5109. char name[PATH_MAX];
  5110. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5111. int truncated;
  5112. if (gpass != NULL) {
  5113. /* Use global passwords file */
  5114. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5115. #ifdef DEBUG
  5116. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5117. #endif
  5118. }
  5119. /* Important: using local struct mg_file to test path for
  5120. * is_directory
  5121. * flag. If filep is used, mg_stat() makes it appear as if auth file
  5122. * was opened. TODO: mg_stat must not make anything appear to be
  5123. * opened */
  5124. } else if (mg_stat(conn, path, &filep->stat)
  5125. && filep->stat.is_directory) {
  5126. mg_snprintf(conn,
  5127. &truncated,
  5128. name,
  5129. sizeof(name),
  5130. "%s/%s",
  5131. path,
  5132. PASSWORDS_FILE_NAME);
  5133. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5134. #ifdef DEBUG
  5135. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  5136. #endif
  5137. }
  5138. } else {
  5139. /* Try to find .htpasswd in requested directory. */
  5140. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5141. if (e[0] == '/') {
  5142. break;
  5143. }
  5144. }
  5145. mg_snprintf(conn,
  5146. &truncated,
  5147. name,
  5148. sizeof(name),
  5149. "%.*s/%s",
  5150. (int)(e - p),
  5151. p,
  5152. PASSWORDS_FILE_NAME);
  5153. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5154. #ifdef DEBUG
  5155. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  5156. #endif
  5157. }
  5158. }
  5159. }
  5160. }
  5161. /* Parsed Authorization header */
  5162. struct ah {
  5163. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5164. };
  5165. /* Return 1 on success. Always initializes the ah structure. */
  5166. static int
  5167. parse_auth_header(struct mg_connection *conn,
  5168. char *buf,
  5169. size_t buf_size,
  5170. struct ah *ah)
  5171. {
  5172. char *name, *value, *s;
  5173. const char *auth_header;
  5174. uint64_t nonce;
  5175. if (!ah || !conn) {
  5176. return 0;
  5177. }
  5178. (void)memset(ah, 0, sizeof(*ah));
  5179. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5180. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5181. return 0;
  5182. }
  5183. /* Make modifiable copy of the auth header */
  5184. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5185. s = buf;
  5186. /* Parse authorization header */
  5187. for (;;) {
  5188. /* Gobble initial spaces */
  5189. while (isspace(*(unsigned char *)s)) {
  5190. s++;
  5191. }
  5192. name = skip_quoted(&s, "=", " ", 0);
  5193. /* Value is either quote-delimited, or ends at first comma or space. */
  5194. if (s[0] == '\"') {
  5195. s++;
  5196. value = skip_quoted(&s, "\"", " ", '\\');
  5197. if (s[0] == ',') {
  5198. s++;
  5199. }
  5200. } else {
  5201. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5202. * spaces */
  5203. }
  5204. if (*name == '\0') {
  5205. break;
  5206. }
  5207. if (!strcmp(name, "username")) {
  5208. ah->user = value;
  5209. } else if (!strcmp(name, "cnonce")) {
  5210. ah->cnonce = value;
  5211. } else if (!strcmp(name, "response")) {
  5212. ah->response = value;
  5213. } else if (!strcmp(name, "uri")) {
  5214. ah->uri = value;
  5215. } else if (!strcmp(name, "qop")) {
  5216. ah->qop = value;
  5217. } else if (!strcmp(name, "nc")) {
  5218. ah->nc = value;
  5219. } else if (!strcmp(name, "nonce")) {
  5220. ah->nonce = value;
  5221. }
  5222. }
  5223. #ifndef NO_NONCE_CHECK
  5224. /* Read the nonce from the response. */
  5225. if (ah->nonce == NULL) {
  5226. return 0;
  5227. }
  5228. s = NULL;
  5229. nonce = strtoull(ah->nonce, &s, 10);
  5230. if ((s == NULL) || (*s != 0)) {
  5231. return 0;
  5232. }
  5233. /* Convert the nonce from the client to a number. */
  5234. nonce ^= conn->ctx->auth_nonce_mask;
  5235. /* The converted number corresponds to the time the nounce has been
  5236. * created. This should not be earlier than the server start. */
  5237. /* Server side nonce check is valuable in all situations but one:
  5238. * if the server restarts frequently, but the client should not see
  5239. * that, so the server should accept nonces from previous starts. */
  5240. /* However, the reasonable default is to not accept a nonce from a
  5241. * previous start, so if anyone changed the access rights between
  5242. * two restarts, a new login is required. */
  5243. if (nonce < (uint64_t)conn->ctx->start_time) {
  5244. /* nonce is from a previous start of the server and no longer valid
  5245. * (replay attack?) */
  5246. return 0;
  5247. }
  5248. /* Check if the nonce is too high, so it has not (yet) been used by the
  5249. * server. */
  5250. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5251. return 0;
  5252. }
  5253. #else
  5254. (void)nonce;
  5255. #endif
  5256. /* CGI needs it as REMOTE_USER */
  5257. if (ah->user != NULL) {
  5258. conn->request_info.remote_user = mg_strdup(ah->user);
  5259. } else {
  5260. return 0;
  5261. }
  5262. return 1;
  5263. }
  5264. static const char *
  5265. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5266. {
  5267. const char *eof;
  5268. size_t len;
  5269. const char *memend;
  5270. if (!filep) {
  5271. return NULL;
  5272. }
  5273. if (filep->access.membuf != NULL && *p != NULL) {
  5274. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5275. /* Search for \n from p till the end of stream */
  5276. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5277. if (eof != NULL) {
  5278. eof += 1; /* Include \n */
  5279. } else {
  5280. eof = memend; /* Copy remaining data */
  5281. }
  5282. len =
  5283. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5284. memcpy(buf, *p, len);
  5285. buf[len] = '\0';
  5286. *p += len;
  5287. return len ? eof : NULL;
  5288. } else if (filep->access.fp != NULL) {
  5289. return fgets(buf, (int)size, filep->access.fp);
  5290. } else {
  5291. return NULL;
  5292. }
  5293. }
  5294. /* Define the initial recursion depth for procesesing htpasswd files that
  5295. * include other htpasswd
  5296. * (or even the same) files. It is not difficult to provide a file or files
  5297. * s.t. they force civetweb
  5298. * to infinitely recurse and then crash.
  5299. */
  5300. #define INITIAL_DEPTH 9
  5301. #if INITIAL_DEPTH <= 0
  5302. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5303. #endif
  5304. struct read_auth_file_struct {
  5305. struct mg_connection *conn;
  5306. struct ah ah;
  5307. char *domain;
  5308. char buf[256 + 256 + 40];
  5309. char *f_user;
  5310. char *f_domain;
  5311. char *f_ha1;
  5312. };
  5313. static int
  5314. read_auth_file(struct mg_file *filep,
  5315. struct read_auth_file_struct *workdata,
  5316. int depth)
  5317. {
  5318. char *p;
  5319. int is_authorized = 0;
  5320. struct mg_file fp;
  5321. size_t l;
  5322. if (!filep || !workdata || 0 == depth) {
  5323. return 0;
  5324. }
  5325. /* Loop over passwords file */
  5326. p = (char *)filep->access.membuf;
  5327. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5328. l = strlen(workdata->buf);
  5329. while (l > 0) {
  5330. if (isspace(workdata->buf[l - 1])
  5331. || iscntrl(workdata->buf[l - 1])) {
  5332. l--;
  5333. workdata->buf[l] = 0;
  5334. } else
  5335. break;
  5336. }
  5337. if (l < 1) {
  5338. continue;
  5339. }
  5340. workdata->f_user = workdata->buf;
  5341. if (workdata->f_user[0] == ':') {
  5342. /* user names may not contain a ':' and may not be empty,
  5343. * so lines starting with ':' may be used for a special purpose */
  5344. if (workdata->f_user[1] == '#') {
  5345. /* :# is a comment */
  5346. continue;
  5347. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5348. if (mg_fopen(workdata->conn,
  5349. workdata->f_user + 9,
  5350. MG_FOPEN_MODE_READ,
  5351. &fp)) {
  5352. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5353. (void)mg_fclose(
  5354. &fp.access); /* ignore error on read only file */
  5355. /* No need to continue processing files once we have a
  5356. * match, since nothing will reset it back
  5357. * to 0.
  5358. */
  5359. if (is_authorized) {
  5360. return is_authorized;
  5361. }
  5362. } else {
  5363. mg_cry(workdata->conn,
  5364. "%s: cannot open authorization file: %s",
  5365. __func__,
  5366. workdata->buf);
  5367. }
  5368. continue;
  5369. }
  5370. /* everything is invalid for the moment (might change in the
  5371. * future) */
  5372. mg_cry(workdata->conn,
  5373. "%s: syntax error in authorization file: %s",
  5374. __func__,
  5375. workdata->buf);
  5376. continue;
  5377. }
  5378. workdata->f_domain = strchr(workdata->f_user, ':');
  5379. if (workdata->f_domain == NULL) {
  5380. mg_cry(workdata->conn,
  5381. "%s: syntax error in authorization file: %s",
  5382. __func__,
  5383. workdata->buf);
  5384. continue;
  5385. }
  5386. *(workdata->f_domain) = 0;
  5387. (workdata->f_domain)++;
  5388. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5389. if (workdata->f_ha1 == NULL) {
  5390. mg_cry(workdata->conn,
  5391. "%s: syntax error in authorization file: %s",
  5392. __func__,
  5393. workdata->buf);
  5394. continue;
  5395. }
  5396. *(workdata->f_ha1) = 0;
  5397. (workdata->f_ha1)++;
  5398. if (!strcmp(workdata->ah.user, workdata->f_user)
  5399. && !strcmp(workdata->domain, workdata->f_domain)) {
  5400. return check_password(workdata->conn->request_info.request_method,
  5401. workdata->f_ha1,
  5402. workdata->ah.uri,
  5403. workdata->ah.nonce,
  5404. workdata->ah.nc,
  5405. workdata->ah.cnonce,
  5406. workdata->ah.qop,
  5407. workdata->ah.response);
  5408. }
  5409. }
  5410. return is_authorized;
  5411. }
  5412. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5413. static int
  5414. authorize(struct mg_connection *conn, struct mg_file *filep)
  5415. {
  5416. struct read_auth_file_struct workdata;
  5417. char buf[MG_BUF_LEN];
  5418. if (!conn || !conn->ctx) {
  5419. return 0;
  5420. }
  5421. memset(&workdata, 0, sizeof(workdata));
  5422. workdata.conn = conn;
  5423. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5424. return 0;
  5425. }
  5426. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5427. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5428. }
  5429. /* Return 1 if request is authorised, 0 otherwise. */
  5430. static int
  5431. check_authorization(struct mg_connection *conn, const char *path)
  5432. {
  5433. char fname[PATH_MAX];
  5434. struct vec uri_vec, filename_vec;
  5435. const char *list;
  5436. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5437. int authorized = 1, truncated;
  5438. if (!conn || !conn->ctx) {
  5439. return 0;
  5440. }
  5441. list = conn->ctx->config[PROTECT_URI];
  5442. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5443. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5444. mg_snprintf(conn,
  5445. &truncated,
  5446. fname,
  5447. sizeof(fname),
  5448. "%.*s",
  5449. (int)filename_vec.len,
  5450. filename_vec.ptr);
  5451. if (truncated
  5452. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5453. mg_cry(conn,
  5454. "%s: cannot open %s: %s",
  5455. __func__,
  5456. fname,
  5457. strerror(errno));
  5458. }
  5459. break;
  5460. }
  5461. }
  5462. if (!is_file_opened(&file.access)) {
  5463. open_auth_file(conn, path, &file);
  5464. }
  5465. if (is_file_opened(&file.access)) {
  5466. authorized = authorize(conn, &file);
  5467. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5468. }
  5469. return authorized;
  5470. }
  5471. static void
  5472. send_authorization_request(struct mg_connection *conn)
  5473. {
  5474. char date[64];
  5475. time_t curtime = time(NULL);
  5476. if (conn && conn->ctx) {
  5477. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5478. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5479. nonce += conn->ctx->nonce_count;
  5480. ++conn->ctx->nonce_count;
  5481. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5482. nonce ^= conn->ctx->auth_nonce_mask;
  5483. conn->status_code = 401;
  5484. conn->must_close = 1;
  5485. gmt_time_string(date, sizeof(date), &curtime);
  5486. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5487. send_no_cache_header(conn);
  5488. mg_printf(conn,
  5489. "Date: %s\r\n"
  5490. "Connection: %s\r\n"
  5491. "Content-Length: 0\r\n"
  5492. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5493. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5494. date,
  5495. suggest_connection_header(conn),
  5496. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5497. nonce);
  5498. }
  5499. }
  5500. #if !defined(NO_FILES)
  5501. static int
  5502. is_authorized_for_put(struct mg_connection *conn)
  5503. {
  5504. if (conn) {
  5505. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5506. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5507. int ret = 0;
  5508. if (passfile != NULL
  5509. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5510. ret = authorize(conn, &file);
  5511. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5512. }
  5513. return ret;
  5514. }
  5515. return 0;
  5516. }
  5517. #endif
  5518. int
  5519. mg_modify_passwords_file(const char *fname,
  5520. const char *domain,
  5521. const char *user,
  5522. const char *pass)
  5523. {
  5524. int found, i;
  5525. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5526. FILE *fp, *fp2;
  5527. found = 0;
  5528. fp = fp2 = NULL;
  5529. /* Regard empty password as no password - remove user record. */
  5530. if (pass != NULL && pass[0] == '\0') {
  5531. pass = NULL;
  5532. }
  5533. /* Other arguments must not be empty */
  5534. if (fname == NULL || domain == NULL || user == NULL) {
  5535. return 0;
  5536. }
  5537. /* Using the given file format, user name and domain must not contain ':'
  5538. */
  5539. if (strchr(user, ':') != NULL) {
  5540. return 0;
  5541. }
  5542. if (strchr(domain, ':') != NULL) {
  5543. return 0;
  5544. }
  5545. /* Do not allow control characters like newline in user name and domain.
  5546. * Do not allow excessively long names either. */
  5547. for (i = 0; i < 255 && user[i] != 0; i++) {
  5548. if (iscntrl(user[i])) {
  5549. return 0;
  5550. }
  5551. }
  5552. if (user[i]) {
  5553. return 0;
  5554. }
  5555. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5556. if (iscntrl(domain[i])) {
  5557. return 0;
  5558. }
  5559. }
  5560. if (domain[i]) {
  5561. return 0;
  5562. }
  5563. /* The maximum length of the path to the password file is limited */
  5564. if ((strlen(fname) + 4) >= PATH_MAX) {
  5565. return 0;
  5566. }
  5567. /* Create a temporary file name. Length has been checked before. */
  5568. strcpy(tmp, fname);
  5569. strcat(tmp, ".tmp");
  5570. /* Create the file if does not exist */
  5571. /* Use of fopen here is OK, since fname is only ASCII */
  5572. if ((fp = fopen(fname, "a+")) != NULL) {
  5573. (void)fclose(fp);
  5574. }
  5575. /* Open the given file and temporary file */
  5576. if ((fp = fopen(fname, "r")) == NULL) {
  5577. return 0;
  5578. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5579. fclose(fp);
  5580. return 0;
  5581. }
  5582. /* Copy the stuff to temporary file */
  5583. while (fgets(line, sizeof(line), fp) != NULL) {
  5584. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5585. continue;
  5586. }
  5587. u[255] = 0;
  5588. d[255] = 0;
  5589. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5590. found++;
  5591. if (pass != NULL) {
  5592. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5593. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5594. }
  5595. } else {
  5596. fprintf(fp2, "%s", line);
  5597. }
  5598. }
  5599. /* If new user, just add it */
  5600. if (!found && pass != NULL) {
  5601. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5602. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5603. }
  5604. /* Close files */
  5605. fclose(fp);
  5606. fclose(fp2);
  5607. /* Put the temp file in place of real file */
  5608. IGNORE_UNUSED_RESULT(remove(fname));
  5609. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5610. return 1;
  5611. }
  5612. static int
  5613. is_valid_port(unsigned long port)
  5614. {
  5615. return port < 0xffff;
  5616. }
  5617. static int
  5618. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5619. {
  5620. struct addrinfo hints, *res, *ressave;
  5621. int func_ret = 0;
  5622. int gai_ret;
  5623. memset(&hints, 0, sizeof(struct addrinfo));
  5624. hints.ai_family = af;
  5625. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5626. if (gai_ret != 0) {
  5627. /* gai_strerror could be used to convert gai_ret to a string */
  5628. /* POSIX return values: see
  5629. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5630. */
  5631. /* Windows return values: see
  5632. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5633. */
  5634. return 0;
  5635. }
  5636. ressave = res;
  5637. while (res) {
  5638. if (dstlen >= res->ai_addrlen) {
  5639. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5640. func_ret = 1;
  5641. }
  5642. res = res->ai_next;
  5643. }
  5644. freeaddrinfo(ressave);
  5645. return func_ret;
  5646. }
  5647. static int
  5648. connect_socket(struct mg_context *ctx /* may be NULL */,
  5649. const char *host,
  5650. int port,
  5651. int use_ssl,
  5652. char *ebuf,
  5653. size_t ebuf_len,
  5654. SOCKET *sock /* output: socket, must not be NULL */,
  5655. union usa *sa /* output: socket address, must not be NULL */
  5656. )
  5657. {
  5658. int ip_ver = 0;
  5659. *sock = INVALID_SOCKET;
  5660. memset(sa, 0, sizeof(*sa));
  5661. if (ebuf_len > 0) {
  5662. *ebuf = 0;
  5663. }
  5664. if (host == NULL) {
  5665. mg_snprintf(NULL,
  5666. NULL, /* No truncation check for ebuf */
  5667. ebuf,
  5668. ebuf_len,
  5669. "%s",
  5670. "NULL host");
  5671. return 0;
  5672. }
  5673. if (port < 0 || !is_valid_port((unsigned)port)) {
  5674. mg_snprintf(NULL,
  5675. NULL, /* No truncation check for ebuf */
  5676. ebuf,
  5677. ebuf_len,
  5678. "%s",
  5679. "invalid port");
  5680. return 0;
  5681. }
  5682. #if !defined(NO_SSL)
  5683. if (use_ssl && (SSLv23_client_method == NULL)) {
  5684. mg_snprintf(NULL,
  5685. NULL, /* No truncation check for ebuf */
  5686. ebuf,
  5687. ebuf_len,
  5688. "%s",
  5689. "SSL is not initialized");
  5690. return 0;
  5691. }
  5692. #else
  5693. (void)use_ssl;
  5694. #endif
  5695. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5696. sa->sin.sin_port = htons((uint16_t)port);
  5697. ip_ver = 4;
  5698. #ifdef USE_IPV6
  5699. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5700. sa->sin6.sin6_port = htons((uint16_t)port);
  5701. ip_ver = 6;
  5702. } else if (host[0] == '[') {
  5703. /* While getaddrinfo on Windows will work with [::1],
  5704. * getaddrinfo on Linux only works with ::1 (without []). */
  5705. size_t l = strlen(host + 1);
  5706. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5707. if (h) {
  5708. h[l - 1] = 0;
  5709. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5710. sa->sin6.sin6_port = htons((uint16_t)port);
  5711. ip_ver = 6;
  5712. }
  5713. mg_free(h);
  5714. }
  5715. #endif
  5716. }
  5717. if (ip_ver == 0) {
  5718. mg_snprintf(NULL,
  5719. NULL, /* No truncation check for ebuf */
  5720. ebuf,
  5721. ebuf_len,
  5722. "%s",
  5723. "host not found");
  5724. return 0;
  5725. }
  5726. if (ip_ver == 4) {
  5727. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5728. }
  5729. #ifdef USE_IPV6
  5730. else if (ip_ver == 6) {
  5731. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5732. }
  5733. #endif
  5734. if (*sock == INVALID_SOCKET) {
  5735. mg_snprintf(NULL,
  5736. NULL, /* No truncation check for ebuf */
  5737. ebuf,
  5738. ebuf_len,
  5739. "socket(): %s",
  5740. strerror(ERRNO));
  5741. return 0;
  5742. }
  5743. set_close_on_exec(*sock, fc(ctx));
  5744. if ((ip_ver == 4)
  5745. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5746. == 0)) {
  5747. /* connected with IPv4 */
  5748. set_blocking_mode(*sock, 0);
  5749. return 1;
  5750. }
  5751. #ifdef USE_IPV6
  5752. if ((ip_ver == 6)
  5753. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5754. == 0)) {
  5755. /* connected with IPv6 */
  5756. set_blocking_mode(*sock, 0);
  5757. return 1;
  5758. }
  5759. #endif
  5760. /* Not connected */
  5761. mg_snprintf(NULL,
  5762. NULL, /* No truncation check for ebuf */
  5763. ebuf,
  5764. ebuf_len,
  5765. "connect(%s:%d): %s",
  5766. host,
  5767. port,
  5768. strerror(ERRNO));
  5769. closesocket(*sock);
  5770. *sock = INVALID_SOCKET;
  5771. return 0;
  5772. }
  5773. int
  5774. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5775. {
  5776. static const char *dont_escape = "._-$,;~()";
  5777. static const char *hex = "0123456789abcdef";
  5778. char *pos = dst;
  5779. const char *end = dst + dst_len - 1;
  5780. for (; *src != '\0' && pos < end; src++, pos++) {
  5781. if (isalnum(*(const unsigned char *)src)
  5782. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5783. *pos = *src;
  5784. } else if (pos + 2 < end) {
  5785. pos[0] = '%';
  5786. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5787. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5788. pos += 2;
  5789. } else {
  5790. break;
  5791. }
  5792. }
  5793. *pos = '\0';
  5794. return (*src == '\0') ? (int)(pos - dst) : -1;
  5795. }
  5796. static void
  5797. print_dir_entry(struct de *de)
  5798. {
  5799. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5800. struct tm *tm;
  5801. if (de->file.is_directory) {
  5802. mg_snprintf(de->conn,
  5803. NULL, /* Buffer is big enough */
  5804. size,
  5805. sizeof(size),
  5806. "%s",
  5807. "[DIRECTORY]");
  5808. } else {
  5809. /* We use (signed) cast below because MSVC 6 compiler cannot
  5810. * convert unsigned __int64 to double. Sigh. */
  5811. if (de->file.size < 1024) {
  5812. mg_snprintf(de->conn,
  5813. NULL, /* Buffer is big enough */
  5814. size,
  5815. sizeof(size),
  5816. "%d",
  5817. (int)de->file.size);
  5818. } else if (de->file.size < 0x100000) {
  5819. mg_snprintf(de->conn,
  5820. NULL, /* Buffer is big enough */
  5821. size,
  5822. sizeof(size),
  5823. "%.1fk",
  5824. (double)de->file.size / 1024.0);
  5825. } else if (de->file.size < 0x40000000) {
  5826. mg_snprintf(de->conn,
  5827. NULL, /* Buffer is big enough */
  5828. size,
  5829. sizeof(size),
  5830. "%.1fM",
  5831. (double)de->file.size / 1048576);
  5832. } else {
  5833. mg_snprintf(de->conn,
  5834. NULL, /* Buffer is big enough */
  5835. size,
  5836. sizeof(size),
  5837. "%.1fG",
  5838. (double)de->file.size / 1073741824);
  5839. }
  5840. }
  5841. /* Note: mg_snprintf will not cause a buffer overflow above.
  5842. * So, string truncation checks are not required here. */
  5843. tm = localtime(&de->file.last_modified);
  5844. if (tm != NULL) {
  5845. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5846. } else {
  5847. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5848. mod[sizeof(mod) - 1] = '\0';
  5849. }
  5850. mg_url_encode(de->file_name, href, sizeof(href));
  5851. de->conn->num_bytes_sent +=
  5852. mg_printf(de->conn,
  5853. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5854. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5855. de->conn->request_info.local_uri,
  5856. href,
  5857. de->file.is_directory ? "/" : "",
  5858. de->file_name,
  5859. de->file.is_directory ? "/" : "",
  5860. mod,
  5861. size);
  5862. }
  5863. /* This function is called from send_directory() and used for
  5864. * sorting directory entries by size, or name, or modification time.
  5865. * On windows, __cdecl specification is needed in case if project is built
  5866. * with __stdcall convention. qsort always requires __cdels callback. */
  5867. static int WINCDECL
  5868. compare_dir_entries(const void *p1, const void *p2)
  5869. {
  5870. if (p1 && p2) {
  5871. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5872. const char *query_string = a->conn->request_info.query_string;
  5873. int cmp_result = 0;
  5874. if (query_string == NULL) {
  5875. query_string = "na";
  5876. }
  5877. if (a->file.is_directory && !b->file.is_directory) {
  5878. return -1; /* Always put directories on top */
  5879. } else if (!a->file.is_directory && b->file.is_directory) {
  5880. return 1; /* Always put directories on top */
  5881. } else if (*query_string == 'n') {
  5882. cmp_result = strcmp(a->file_name, b->file_name);
  5883. } else if (*query_string == 's') {
  5884. cmp_result = (a->file.size == b->file.size)
  5885. ? 0
  5886. : ((a->file.size > b->file.size) ? 1 : -1);
  5887. } else if (*query_string == 'd') {
  5888. cmp_result =
  5889. (a->file.last_modified == b->file.last_modified)
  5890. ? 0
  5891. : ((a->file.last_modified > b->file.last_modified) ? 1
  5892. : -1);
  5893. }
  5894. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5895. }
  5896. return 0;
  5897. }
  5898. static int
  5899. must_hide_file(struct mg_connection *conn, const char *path)
  5900. {
  5901. if (conn && conn->ctx) {
  5902. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5903. const char *pattern = conn->ctx->config[HIDE_FILES];
  5904. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5905. || (pattern != NULL
  5906. && match_prefix(pattern, strlen(pattern), path) > 0);
  5907. }
  5908. return 0;
  5909. }
  5910. static int
  5911. scan_directory(struct mg_connection *conn,
  5912. const char *dir,
  5913. void *data,
  5914. void (*cb)(struct de *, void *))
  5915. {
  5916. char path[PATH_MAX];
  5917. struct dirent *dp;
  5918. DIR *dirp;
  5919. struct de de;
  5920. int truncated;
  5921. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5922. return 0;
  5923. } else {
  5924. de.conn = conn;
  5925. while ((dp = mg_readdir(dirp)) != NULL) {
  5926. /* Do not show current dir and hidden files */
  5927. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5928. || must_hide_file(conn, dp->d_name)) {
  5929. continue;
  5930. }
  5931. mg_snprintf(
  5932. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5933. /* If we don't memset stat structure to zero, mtime will have
  5934. * garbage and strftime() will segfault later on in
  5935. * print_dir_entry(). memset is required only if mg_stat()
  5936. * fails. For more details, see
  5937. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5938. memset(&de.file, 0, sizeof(de.file));
  5939. if (truncated) {
  5940. /* If the path is not complete, skip processing. */
  5941. continue;
  5942. }
  5943. if (!mg_stat(conn, path, &de.file)) {
  5944. mg_cry(conn,
  5945. "%s: mg_stat(%s) failed: %s",
  5946. __func__,
  5947. path,
  5948. strerror(ERRNO));
  5949. }
  5950. de.file_name = dp->d_name;
  5951. cb(&de, data);
  5952. }
  5953. (void)mg_closedir(dirp);
  5954. }
  5955. return 1;
  5956. }
  5957. #if !defined(NO_FILES)
  5958. static int
  5959. remove_directory(struct mg_connection *conn, const char *dir)
  5960. {
  5961. char path[PATH_MAX];
  5962. struct dirent *dp;
  5963. DIR *dirp;
  5964. struct de de;
  5965. int truncated;
  5966. int ok = 1;
  5967. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5968. return 0;
  5969. } else {
  5970. de.conn = conn;
  5971. while ((dp = mg_readdir(dirp)) != NULL) {
  5972. /* Do not show current dir (but show hidden files as they will
  5973. * also be removed) */
  5974. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5975. continue;
  5976. }
  5977. mg_snprintf(
  5978. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5979. /* If we don't memset stat structure to zero, mtime will have
  5980. * garbage and strftime() will segfault later on in
  5981. * print_dir_entry(). memset is required only if mg_stat()
  5982. * fails. For more details, see
  5983. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5984. memset(&de.file, 0, sizeof(de.file));
  5985. if (truncated) {
  5986. /* Do not delete anything shorter */
  5987. ok = 0;
  5988. continue;
  5989. }
  5990. if (!mg_stat(conn, path, &de.file)) {
  5991. mg_cry(conn,
  5992. "%s: mg_stat(%s) failed: %s",
  5993. __func__,
  5994. path,
  5995. strerror(ERRNO));
  5996. ok = 0;
  5997. }
  5998. if (de.file.is_directory) {
  5999. if (remove_directory(conn, path) == 0) {
  6000. ok = 0;
  6001. }
  6002. } else {
  6003. /* This will fail file is the file is in memory */
  6004. if (mg_remove(conn, path) == 0) {
  6005. ok = 0;
  6006. }
  6007. }
  6008. }
  6009. (void)mg_closedir(dirp);
  6010. IGNORE_UNUSED_RESULT(rmdir(dir));
  6011. }
  6012. return ok;
  6013. }
  6014. #endif
  6015. struct dir_scan_data {
  6016. struct de *entries;
  6017. unsigned int num_entries;
  6018. unsigned int arr_size;
  6019. };
  6020. /* Behaves like realloc(), but frees original pointer on failure */
  6021. static void *
  6022. realloc2(void *ptr, size_t size)
  6023. {
  6024. void *new_ptr = mg_realloc(ptr, size);
  6025. if (new_ptr == NULL) {
  6026. mg_free(ptr);
  6027. }
  6028. return new_ptr;
  6029. }
  6030. static void
  6031. dir_scan_callback(struct de *de, void *data)
  6032. {
  6033. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6034. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6035. dsd->arr_size *= 2;
  6036. dsd->entries =
  6037. (struct de *)realloc2(dsd->entries,
  6038. dsd->arr_size * sizeof(dsd->entries[0]));
  6039. }
  6040. if (dsd->entries == NULL) {
  6041. /* TODO(lsm, low): propagate an error to the caller */
  6042. dsd->num_entries = 0;
  6043. } else {
  6044. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6045. dsd->entries[dsd->num_entries].file = de->file;
  6046. dsd->entries[dsd->num_entries].conn = de->conn;
  6047. dsd->num_entries++;
  6048. }
  6049. }
  6050. static void
  6051. handle_directory_request(struct mg_connection *conn, const char *dir)
  6052. {
  6053. unsigned int i;
  6054. int sort_direction;
  6055. struct dir_scan_data data = {NULL, 0, 128};
  6056. char date[64];
  6057. time_t curtime = time(NULL);
  6058. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6059. send_http_error(conn,
  6060. 500,
  6061. "Error: Cannot open directory\nopendir(%s): %s",
  6062. dir,
  6063. strerror(ERRNO));
  6064. return;
  6065. }
  6066. gmt_time_string(date, sizeof(date), &curtime);
  6067. if (!conn) {
  6068. return;
  6069. }
  6070. sort_direction = ((conn->request_info.query_string != NULL)
  6071. && (conn->request_info.query_string[1] == 'd'))
  6072. ? 'a'
  6073. : 'd';
  6074. conn->must_close = 1;
  6075. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6076. send_static_cache_header(conn);
  6077. mg_printf(conn,
  6078. "Date: %s\r\n"
  6079. "Connection: close\r\n"
  6080. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6081. date);
  6082. conn->num_bytes_sent +=
  6083. mg_printf(conn,
  6084. "<html><head><title>Index of %s</title>"
  6085. "<style>th {text-align: left;}</style></head>"
  6086. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6087. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6088. "<th><a href=\"?d%c\">Modified</a></th>"
  6089. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6090. "<tr><td colspan=\"3\"><hr></td></tr>",
  6091. conn->request_info.local_uri,
  6092. conn->request_info.local_uri,
  6093. sort_direction,
  6094. sort_direction,
  6095. sort_direction);
  6096. /* Print first entry - link to a parent directory */
  6097. conn->num_bytes_sent +=
  6098. mg_printf(conn,
  6099. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6100. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6101. conn->request_info.local_uri,
  6102. "..",
  6103. "Parent directory",
  6104. "-",
  6105. "-");
  6106. /* Sort and print directory entries */
  6107. if (data.entries != NULL) {
  6108. qsort(data.entries,
  6109. (size_t)data.num_entries,
  6110. sizeof(data.entries[0]),
  6111. compare_dir_entries);
  6112. for (i = 0; i < data.num_entries; i++) {
  6113. print_dir_entry(&data.entries[i]);
  6114. mg_free(data.entries[i].file_name);
  6115. }
  6116. mg_free(data.entries);
  6117. }
  6118. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6119. conn->status_code = 200;
  6120. }
  6121. /* Send len bytes from the opened file to the client. */
  6122. static void
  6123. send_file_data(struct mg_connection *conn,
  6124. struct mg_file *filep,
  6125. int64_t offset,
  6126. int64_t len)
  6127. {
  6128. char buf[MG_BUF_LEN];
  6129. int to_read, num_read, num_written;
  6130. int64_t size;
  6131. if (!filep || !conn) {
  6132. return;
  6133. }
  6134. /* Sanity check the offset */
  6135. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6136. : (int64_t)(filep->stat.size);
  6137. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6138. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6139. /* file stored in memory */
  6140. if (len > size - offset) {
  6141. len = size - offset;
  6142. }
  6143. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6144. } else if (len > 0 && filep->access.fp != NULL) {
  6145. /* file stored on disk */
  6146. #if defined(__linux__)
  6147. /* sendfile is only available for Linux */
  6148. if ((conn->ssl == 0) && (conn->throttle == 0)
  6149. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6150. "yes"))) {
  6151. off_t sf_offs = (off_t)offset;
  6152. ssize_t sf_sent;
  6153. int sf_file = fileno(filep->access.fp);
  6154. int loop_cnt = 0;
  6155. do {
  6156. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6157. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6158. size_t sf_tosend =
  6159. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6160. sf_sent =
  6161. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6162. if (sf_sent > 0) {
  6163. conn->num_bytes_sent += sf_sent;
  6164. len -= sf_sent;
  6165. offset += sf_sent;
  6166. } else if (loop_cnt == 0) {
  6167. /* This file can not be sent using sendfile.
  6168. * This might be the case for pseudo-files in the
  6169. * /sys/ and /proc/ file system.
  6170. * Use the regular user mode copy code instead. */
  6171. break;
  6172. } else if (sf_sent == 0) {
  6173. /* No error, but 0 bytes sent. May be EOF? */
  6174. return;
  6175. }
  6176. loop_cnt++;
  6177. } while ((len > 0) && (sf_sent >= 0));
  6178. if (sf_sent > 0) {
  6179. return; /* OK */
  6180. }
  6181. /* sf_sent<0 means error, thus fall back to the classic way */
  6182. /* This is always the case, if sf_file is not a "normal" file,
  6183. * e.g., for sending data from the output of a CGI process. */
  6184. offset = (int64_t)sf_offs;
  6185. }
  6186. #endif
  6187. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6188. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6189. send_http_error(
  6190. conn,
  6191. 500,
  6192. "%s",
  6193. "Error: Unable to access file at requested position.");
  6194. } else {
  6195. while (len > 0) {
  6196. /* Calculate how much to read from the file in the buffer */
  6197. to_read = sizeof(buf);
  6198. if ((int64_t)to_read > len) {
  6199. to_read = (int)len;
  6200. }
  6201. /* Read from file, exit the loop on error */
  6202. if ((num_read =
  6203. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6204. <= 0) {
  6205. break;
  6206. }
  6207. /* Send read bytes to the client, exit the loop on error */
  6208. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6209. != num_read) {
  6210. break;
  6211. }
  6212. /* Both read and were successful, adjust counters */
  6213. conn->num_bytes_sent += num_written;
  6214. len -= num_written;
  6215. }
  6216. }
  6217. }
  6218. }
  6219. static int
  6220. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6221. {
  6222. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6223. }
  6224. static void
  6225. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6226. {
  6227. if (filestat != NULL && buf != NULL) {
  6228. mg_snprintf(NULL,
  6229. NULL, /* All calls to construct_etag use 64 byte buffer */
  6230. buf,
  6231. buf_len,
  6232. "\"%lx.%" INT64_FMT "\"",
  6233. (unsigned long)filestat->last_modified,
  6234. filestat->size);
  6235. }
  6236. }
  6237. static void
  6238. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6239. {
  6240. if (filep != NULL && filep->fp != NULL) {
  6241. #ifdef _WIN32
  6242. (void)conn; /* Unused. */
  6243. #else
  6244. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6245. mg_cry(conn,
  6246. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6247. __func__,
  6248. strerror(ERRNO));
  6249. }
  6250. #endif
  6251. }
  6252. }
  6253. static void
  6254. handle_static_file_request(struct mg_connection *conn,
  6255. const char *path,
  6256. struct mg_file *filep,
  6257. const char *mime_type,
  6258. const char *additional_headers)
  6259. {
  6260. char date[64], lm[64], etag[64];
  6261. char range[128]; /* large enough, so there will be no overflow */
  6262. const char *msg = "OK", *hdr;
  6263. time_t curtime = time(NULL);
  6264. int64_t cl, r1, r2;
  6265. struct vec mime_vec;
  6266. int n, truncated;
  6267. char gz_path[PATH_MAX];
  6268. const char *encoding = "";
  6269. const char *cors1, *cors2, *cors3;
  6270. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6271. return;
  6272. }
  6273. if (mime_type == NULL) {
  6274. get_mime_type(conn->ctx, path, &mime_vec);
  6275. } else {
  6276. mime_vec.ptr = mime_type;
  6277. mime_vec.len = strlen(mime_type);
  6278. }
  6279. if (filep->stat.size > INT64_MAX) {
  6280. send_http_error(conn,
  6281. 500,
  6282. "Error: File size is too large to send\n%" INT64_FMT,
  6283. filep->stat.size);
  6284. }
  6285. cl = (int64_t)filep->stat.size;
  6286. conn->status_code = 200;
  6287. range[0] = '\0';
  6288. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6289. * it's important to rewrite the filename after resolving
  6290. * the mime type from it, to preserve the actual file's type */
  6291. if (filep->stat.is_gzipped) {
  6292. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6293. if (truncated) {
  6294. send_http_error(conn,
  6295. 500,
  6296. "Error: Path of zipped file too long (%s)",
  6297. path);
  6298. return;
  6299. }
  6300. path = gz_path;
  6301. encoding = "Content-Encoding: gzip\r\n";
  6302. }
  6303. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6304. send_http_error(conn,
  6305. 500,
  6306. "Error: Cannot open file\nfopen(%s): %s",
  6307. path,
  6308. strerror(ERRNO));
  6309. return;
  6310. }
  6311. fclose_on_exec(&filep->access, conn);
  6312. /* If Range: header specified, act accordingly */
  6313. r1 = r2 = 0;
  6314. hdr = mg_get_header(conn, "Range");
  6315. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6316. && r2 >= 0) {
  6317. /* actually, range requests don't play well with a pre-gzipped
  6318. * file (since the range is specified in the uncompressed space) */
  6319. if (filep->stat.is_gzipped) {
  6320. send_http_error(
  6321. conn,
  6322. 501,
  6323. "%s",
  6324. "Error: Range requests in gzipped files are not supported");
  6325. (void)mg_fclose(
  6326. &filep->access); /* ignore error on read only file */
  6327. return;
  6328. }
  6329. conn->status_code = 206;
  6330. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6331. mg_snprintf(conn,
  6332. NULL, /* range buffer is big enough */
  6333. range,
  6334. sizeof(range),
  6335. "Content-Range: bytes "
  6336. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6337. r1,
  6338. r1 + cl - 1,
  6339. filep->stat.size);
  6340. msg = "Partial Content";
  6341. }
  6342. hdr = mg_get_header(conn, "Origin");
  6343. if (hdr) {
  6344. /* Cross-origin resource sharing (CORS), see
  6345. * http://www.html5rocks.com/en/tutorials/cors/,
  6346. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6347. * preflight is not supported for files. */
  6348. cors1 = "Access-Control-Allow-Origin: ";
  6349. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6350. cors3 = "\r\n";
  6351. } else {
  6352. cors1 = cors2 = cors3 = "";
  6353. }
  6354. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6355. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6356. gmt_time_string(date, sizeof(date), &curtime);
  6357. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6358. construct_etag(etag, sizeof(etag), &filep->stat);
  6359. (void)mg_printf(conn,
  6360. "HTTP/1.1 %d %s\r\n"
  6361. "%s%s%s"
  6362. "Date: %s\r\n",
  6363. conn->status_code,
  6364. msg,
  6365. cors1,
  6366. cors2,
  6367. cors3,
  6368. date);
  6369. send_static_cache_header(conn);
  6370. (void)mg_printf(conn,
  6371. "Last-Modified: %s\r\n"
  6372. "Etag: %s\r\n"
  6373. "Content-Type: %.*s\r\n"
  6374. "Content-Length: %" INT64_FMT "\r\n"
  6375. "Connection: %s\r\n"
  6376. "Accept-Ranges: bytes\r\n"
  6377. "%s%s",
  6378. lm,
  6379. etag,
  6380. (int)mime_vec.len,
  6381. mime_vec.ptr,
  6382. cl,
  6383. suggest_connection_header(conn),
  6384. range,
  6385. encoding);
  6386. /* The previous code must not add any header starting with X- to make
  6387. * sure no one of the additional_headers is included twice */
  6388. if (additional_headers != NULL) {
  6389. (void)mg_printf(conn,
  6390. "%.*s\r\n\r\n",
  6391. (int)strlen(additional_headers),
  6392. additional_headers);
  6393. } else {
  6394. (void)mg_printf(conn, "\r\n");
  6395. }
  6396. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6397. send_file_data(conn, filep, r1, cl);
  6398. }
  6399. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6400. }
  6401. #if !defined(NO_CACHING)
  6402. static void
  6403. handle_not_modified_static_file_request(struct mg_connection *conn,
  6404. struct mg_file *filep)
  6405. {
  6406. char date[64], lm[64], etag[64];
  6407. time_t curtime = time(NULL);
  6408. if (conn == NULL || filep == NULL) {
  6409. return;
  6410. }
  6411. conn->status_code = 304;
  6412. gmt_time_string(date, sizeof(date), &curtime);
  6413. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6414. construct_etag(etag, sizeof(etag), &filep->stat);
  6415. (void)mg_printf(conn,
  6416. "HTTP/1.1 %d %s\r\n"
  6417. "Date: %s\r\n",
  6418. conn->status_code,
  6419. mg_get_response_code_text(conn, conn->status_code),
  6420. date);
  6421. send_static_cache_header(conn);
  6422. (void)mg_printf(conn,
  6423. "Last-Modified: %s\r\n"
  6424. "Etag: %s\r\n"
  6425. "Connection: %s\r\n"
  6426. "\r\n",
  6427. lm,
  6428. etag,
  6429. suggest_connection_header(conn));
  6430. }
  6431. #endif
  6432. void
  6433. mg_send_file(struct mg_connection *conn, const char *path)
  6434. {
  6435. mg_send_mime_file(conn, path, NULL);
  6436. }
  6437. void
  6438. mg_send_mime_file(struct mg_connection *conn,
  6439. const char *path,
  6440. const char *mime_type)
  6441. {
  6442. mg_send_mime_file2(conn, path, mime_type, NULL);
  6443. }
  6444. void
  6445. mg_send_mime_file2(struct mg_connection *conn,
  6446. const char *path,
  6447. const char *mime_type,
  6448. const char *additional_headers)
  6449. {
  6450. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6451. if (mg_stat(conn, path, &file.stat)) {
  6452. if (file.stat.is_directory) {
  6453. if (!conn) {
  6454. return;
  6455. }
  6456. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6457. "yes")) {
  6458. handle_directory_request(conn, path);
  6459. } else {
  6460. send_http_error(conn,
  6461. 403,
  6462. "%s",
  6463. "Error: Directory listing denied");
  6464. }
  6465. } else {
  6466. handle_static_file_request(
  6467. conn, path, &file, mime_type, additional_headers);
  6468. }
  6469. } else {
  6470. send_http_error(conn, 404, "%s", "Error: File not found");
  6471. }
  6472. }
  6473. /* For a given PUT path, create all intermediate subdirectories.
  6474. * Return 0 if the path itself is a directory.
  6475. * Return 1 if the path leads to a file.
  6476. * Return -1 for if the path is too long.
  6477. * Return -2 if path can not be created.
  6478. */
  6479. static int
  6480. put_dir(struct mg_connection *conn, const char *path)
  6481. {
  6482. char buf[PATH_MAX];
  6483. const char *s, *p;
  6484. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6485. size_t len;
  6486. int res = 1;
  6487. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6488. len = (size_t)(p - path);
  6489. if (len >= sizeof(buf)) {
  6490. /* path too long */
  6491. res = -1;
  6492. break;
  6493. }
  6494. memcpy(buf, path, len);
  6495. buf[len] = '\0';
  6496. /* Try to create intermediate directory */
  6497. DEBUG_TRACE("mkdir(%s)", buf);
  6498. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6499. /* path does not exixt and can not be created */
  6500. res = -2;
  6501. break;
  6502. }
  6503. /* Is path itself a directory? */
  6504. if (p[1] == '\0') {
  6505. res = 0;
  6506. }
  6507. }
  6508. return res;
  6509. }
  6510. static void
  6511. remove_bad_file(const struct mg_connection *conn, const char *path)
  6512. {
  6513. int r = mg_remove(conn, path);
  6514. if (r != 0) {
  6515. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6516. }
  6517. }
  6518. long long
  6519. mg_store_body(struct mg_connection *conn, const char *path)
  6520. {
  6521. char buf[MG_BUF_LEN];
  6522. long long len = 0;
  6523. int ret, n;
  6524. struct mg_file fi;
  6525. if (conn->consumed_content != 0) {
  6526. mg_cry(conn, "%s: Contents already consumed", __func__);
  6527. return -11;
  6528. }
  6529. ret = put_dir(conn, path);
  6530. if (ret < 0) {
  6531. /* -1 for path too long,
  6532. * -2 for path can not be created. */
  6533. return ret;
  6534. }
  6535. if (ret != 1) {
  6536. /* Return 0 means, path itself is a directory. */
  6537. return 0;
  6538. }
  6539. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6540. return -12;
  6541. }
  6542. ret = mg_read(conn, buf, sizeof(buf));
  6543. while (ret > 0) {
  6544. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6545. if (n != ret) {
  6546. (void)mg_fclose(
  6547. &fi.access); /* File is bad and will be removed anyway. */
  6548. remove_bad_file(conn, path);
  6549. return -13;
  6550. }
  6551. ret = mg_read(conn, buf, sizeof(buf));
  6552. }
  6553. /* File is open for writing. If fclose fails, there was probably an
  6554. * error flushing the buffer to disk, so the file on disk might be
  6555. * broken. Delete it and return an error to the caller. */
  6556. if (mg_fclose(&fi.access) != 0) {
  6557. remove_bad_file(conn, path);
  6558. return -14;
  6559. }
  6560. return len;
  6561. }
  6562. /* Parse HTTP headers from the given buffer, advance buf pointer
  6563. * to the point where parsing stopped.
  6564. * All parameters must be valid pointers (not NULL).
  6565. * Return <0 on error. */
  6566. static int
  6567. parse_http_headers(char **buf, struct mg_request_info *ri)
  6568. {
  6569. int i;
  6570. ri->num_headers = 0;
  6571. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6572. char *dp = *buf;
  6573. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6574. dp++;
  6575. }
  6576. if (dp == *buf) {
  6577. /* End of headers reached. */
  6578. break;
  6579. }
  6580. if (*dp != ':') {
  6581. /* This is not a valid field. */
  6582. return -1;
  6583. }
  6584. /* End of header key (*dp == ':') */
  6585. /* Truncate here and set the key name */
  6586. *dp = 0;
  6587. ri->http_headers[i].name = *buf;
  6588. do {
  6589. dp++;
  6590. } while (*dp == ' ');
  6591. /* The rest of the line is the value */
  6592. ri->http_headers[i].value = dp;
  6593. *buf = dp + strcspn(dp, "\r\n");
  6594. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6595. *buf = NULL;
  6596. }
  6597. ri->num_headers = i + 1;
  6598. if (*buf) {
  6599. (*buf)[0] = 0;
  6600. (*buf)[1] = 0;
  6601. *buf += 2;
  6602. } else {
  6603. *buf = dp;
  6604. break;
  6605. }
  6606. if ((*buf)[0] == '\r') {
  6607. /* This is the end of the header */
  6608. break;
  6609. }
  6610. }
  6611. return ri->num_headers;
  6612. }
  6613. static int
  6614. is_valid_http_method(const char *method)
  6615. {
  6616. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6617. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6618. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6619. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6620. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6621. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6622. /* TRACE method (RFC 2616) is not supported for security reasons */
  6623. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6624. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6625. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6626. /* Unsupported WEBDAV Methods: */
  6627. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6628. /* + 11 methods from RFC 3253 */
  6629. /* ORDERPATCH (RFC 3648) */
  6630. /* ACL (RFC 3744) */
  6631. /* SEARCH (RFC 5323) */
  6632. /* + MicroSoft extensions
  6633. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6634. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6635. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6636. }
  6637. /* Parse HTTP request, fill in mg_request_info structure.
  6638. * This function modifies the buffer by NUL-terminating
  6639. * HTTP request components, header names and header values.
  6640. * Parameters:
  6641. * buf (in/out): pointer to the HTTP header to parse and split
  6642. * len (in): length of HTTP header buffer
  6643. * re (out): parsed header as mg_request_info
  6644. * buf and ri must be valid pointers (not NULL), len>0.
  6645. * Returns <0 on error. */
  6646. static int
  6647. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6648. {
  6649. int is_request, request_length;
  6650. char *start_line;
  6651. request_length = get_request_len(buf, len);
  6652. if (request_length > 0) {
  6653. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6654. * remote_port */
  6655. ri->remote_user = ri->request_method = ri->request_uri =
  6656. ri->http_version = NULL;
  6657. ri->num_headers = 0;
  6658. buf[request_length - 1] = '\0';
  6659. /* RFC says that all initial whitespaces should be ingored */
  6660. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6661. buf++;
  6662. }
  6663. start_line = skip(&buf, "\r\n");
  6664. ri->request_method = skip(&start_line, " ");
  6665. ri->request_uri = skip(&start_line, " ");
  6666. ri->http_version = start_line;
  6667. /* HTTP message could be either HTTP request:
  6668. * "GET / HTTP/1.0 ..."
  6669. * or a HTTP response:
  6670. * "HTTP/1.0 200 OK ..."
  6671. * otherwise it is invalid.
  6672. */
  6673. is_request = is_valid_http_method(ri->request_method);
  6674. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6675. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6676. /* Not a valid request or response: invalid */
  6677. return -1;
  6678. }
  6679. if (is_request) {
  6680. ri->http_version += 5;
  6681. }
  6682. if (parse_http_headers(&buf, ri) < 0) {
  6683. /* Error while parsing headers */
  6684. return -1;
  6685. }
  6686. }
  6687. return request_length;
  6688. }
  6689. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6690. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6691. * buffer (which marks the end of HTTP request). Buffer buf may already
  6692. * have some data. The length of the data is stored in nread.
  6693. * Upon every read operation, increase nread by the number of bytes read. */
  6694. static int
  6695. read_request(FILE *fp,
  6696. struct mg_connection *conn,
  6697. char *buf,
  6698. int bufsiz,
  6699. int *nread)
  6700. {
  6701. int request_len, n = 0;
  6702. struct timespec last_action_time;
  6703. double request_timeout;
  6704. if (!conn) {
  6705. return 0;
  6706. }
  6707. memset(&last_action_time, 0, sizeof(last_action_time));
  6708. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6709. /* value of request_timeout is in seconds, config in milliseconds */
  6710. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6711. } else {
  6712. request_timeout = -1.0;
  6713. }
  6714. if (conn->handled_requests > 0) {
  6715. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6716. request_timeout =
  6717. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6718. }
  6719. }
  6720. request_len = get_request_len(buf, *nread);
  6721. /* first time reading from this connection */
  6722. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6723. while (request_len == 0) {
  6724. /* Full request not yet received */
  6725. if (conn->ctx->stop_flag != 0) {
  6726. /* Server is to be stopped. */
  6727. return -1;
  6728. }
  6729. if (*nread >= bufsiz) {
  6730. /* Request too long */
  6731. return -2;
  6732. }
  6733. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6734. if (n < 0) {
  6735. /* Receive error */
  6736. return -1;
  6737. }
  6738. *nread += n;
  6739. request_len = get_request_len(buf, *nread);
  6740. if ((request_len == 0) && (request_timeout >= 0)) {
  6741. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6742. > request_timeout) {
  6743. /* Timeout */
  6744. return -1;
  6745. }
  6746. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6747. }
  6748. }
  6749. return request_len;
  6750. }
  6751. #if !defined(NO_FILES)
  6752. /* For given directory path, substitute it to valid index file.
  6753. * Return 1 if index file has been found, 0 if not found.
  6754. * If the file is found, it's stats is returned in stp. */
  6755. static int
  6756. substitute_index_file(struct mg_connection *conn,
  6757. char *path,
  6758. size_t path_len,
  6759. struct mg_file *filep)
  6760. {
  6761. if (conn && conn->ctx) {
  6762. const char *list = conn->ctx->config[INDEX_FILES];
  6763. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6764. struct vec filename_vec;
  6765. size_t n = strlen(path);
  6766. int found = 0;
  6767. /* The 'path' given to us points to the directory. Remove all trailing
  6768. * directory separator characters from the end of the path, and
  6769. * then append single directory separator character. */
  6770. while (n > 0 && path[n - 1] == '/') {
  6771. n--;
  6772. }
  6773. path[n] = '/';
  6774. /* Traverse index files list. For each entry, append it to the given
  6775. * path and see if the file exists. If it exists, break the loop */
  6776. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6777. /* Ignore too long entries that may overflow path buffer */
  6778. if (filename_vec.len > path_len - (n + 2)) {
  6779. continue;
  6780. }
  6781. /* Prepare full path to the index file */
  6782. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6783. /* Does it exist? */
  6784. if (mg_stat(conn, path, &file.stat)) {
  6785. /* Yes it does, break the loop */
  6786. *filep = file;
  6787. found = 1;
  6788. break;
  6789. }
  6790. }
  6791. /* If no index file exists, restore directory path */
  6792. if (!found) {
  6793. path[n] = '\0';
  6794. }
  6795. return found;
  6796. }
  6797. return 0;
  6798. }
  6799. #endif
  6800. #if !defined(NO_CACHING)
  6801. /* Return True if we should reply 304 Not Modified. */
  6802. static int
  6803. is_not_modified(const struct mg_connection *conn,
  6804. const struct mg_file_stat *filestat)
  6805. {
  6806. char etag[64];
  6807. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6808. const char *inm = mg_get_header(conn, "If-None-Match");
  6809. construct_etag(etag, sizeof(etag), filestat);
  6810. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6811. || ((ims != NULL)
  6812. && (filestat->last_modified <= parse_date_string(ims)));
  6813. }
  6814. #endif /* !NO_CACHING */
  6815. #if !defined(NO_CGI) || !defined(NO_FILES)
  6816. static int
  6817. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6818. {
  6819. const char *expect, *body;
  6820. char buf[MG_BUF_LEN];
  6821. int to_read, nread, success = 0;
  6822. int64_t buffered_len;
  6823. double timeout = -1.0;
  6824. if (!conn) {
  6825. return 0;
  6826. }
  6827. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6828. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6829. }
  6830. expect = mg_get_header(conn, "Expect");
  6831. /* assert(fp != NULL); */
  6832. if (!fp) {
  6833. send_http_error(conn, 500, "%s", "Error: NULL File");
  6834. return 0;
  6835. }
  6836. if (conn->content_len == -1 && !conn->is_chunked) {
  6837. /* Content length is not specified by the client. */
  6838. send_http_error(conn,
  6839. 411,
  6840. "%s",
  6841. "Error: Client did not specify content length");
  6842. } else if ((expect != NULL)
  6843. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6844. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6845. send_http_error(conn,
  6846. 417,
  6847. "Error: Can not fulfill expectation %s",
  6848. expect);
  6849. } else {
  6850. if (expect != NULL) {
  6851. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6852. conn->status_code = 100;
  6853. } else {
  6854. conn->status_code = 200;
  6855. }
  6856. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6857. - conn->consumed_content;
  6858. /* assert(buffered_len >= 0); */
  6859. /* assert(conn->consumed_content == 0); */
  6860. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6861. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6862. return 0;
  6863. }
  6864. if (buffered_len > 0) {
  6865. if ((int64_t)buffered_len > conn->content_len) {
  6866. buffered_len = (int)conn->content_len;
  6867. }
  6868. body = conn->buf + conn->request_len + conn->consumed_content;
  6869. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6870. conn->consumed_content += buffered_len;
  6871. }
  6872. nread = 0;
  6873. while (conn->consumed_content < conn->content_len) {
  6874. to_read = sizeof(buf);
  6875. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6876. to_read = (int)(conn->content_len - conn->consumed_content);
  6877. }
  6878. nread = pull(NULL, conn, buf, to_read, timeout);
  6879. if (nread <= 0
  6880. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6881. break;
  6882. }
  6883. conn->consumed_content += nread;
  6884. }
  6885. if (conn->consumed_content == conn->content_len) {
  6886. success = (nread >= 0);
  6887. }
  6888. /* Each error code path in this function must send an error */
  6889. if (!success) {
  6890. /* NOTE: Maybe some data has already been sent. */
  6891. /* TODO (low): If some data has been sent, a correct error
  6892. * reply can no longer be sent, so just close the connection */
  6893. send_http_error(conn, 500, "%s", "");
  6894. }
  6895. }
  6896. return success;
  6897. }
  6898. #endif
  6899. #if !defined(NO_CGI)
  6900. /* This structure helps to create an environment for the spawned CGI program.
  6901. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6902. * last element must be NULL.
  6903. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6904. * strings must reside in a contiguous buffer. The end of the buffer is
  6905. * marked by two '\0' characters.
  6906. * We satisfy both worlds: we create an envp array (which is vars), all
  6907. * entries are actually pointers inside buf. */
  6908. struct cgi_environment {
  6909. struct mg_connection *conn;
  6910. /* Data block */
  6911. char *buf; /* Environment buffer */
  6912. size_t buflen; /* Space available in buf */
  6913. size_t bufused; /* Space taken in buf */
  6914. /* Index block */
  6915. char **var; /* char **envp */
  6916. size_t varlen; /* Number of variables available in var */
  6917. size_t varused; /* Number of variables stored in var */
  6918. };
  6919. static void addenv(struct cgi_environment *env,
  6920. PRINTF_FORMAT_STRING(const char *fmt),
  6921. ...) PRINTF_ARGS(2, 3);
  6922. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6923. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6924. static void
  6925. addenv(struct cgi_environment *env, const char *fmt, ...)
  6926. {
  6927. size_t n, space;
  6928. int truncated = 0;
  6929. char *added;
  6930. va_list ap;
  6931. /* Calculate how much space is left in the buffer */
  6932. space = (env->buflen - env->bufused);
  6933. /* Calculate an estimate for the required space */
  6934. n = strlen(fmt) + 2 + 128;
  6935. do {
  6936. if (space <= n) {
  6937. /* Allocate new buffer */
  6938. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6939. added = (char *)mg_realloc(env->buf, n);
  6940. if (!added) {
  6941. /* Out of memory */
  6942. mg_cry(env->conn,
  6943. "%s: Cannot allocate memory for CGI variable [%s]",
  6944. __func__,
  6945. fmt);
  6946. return;
  6947. }
  6948. env->buf = added;
  6949. env->buflen = n;
  6950. space = (env->buflen - env->bufused);
  6951. }
  6952. /* Make a pointer to the free space int the buffer */
  6953. added = env->buf + env->bufused;
  6954. /* Copy VARIABLE=VALUE\0 string into the free space */
  6955. va_start(ap, fmt);
  6956. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6957. va_end(ap);
  6958. /* Do not add truncated strings to the environment */
  6959. if (truncated) {
  6960. /* Reallocate the buffer */
  6961. space = 0;
  6962. n = 1;
  6963. }
  6964. } while (truncated);
  6965. /* Calculate number of bytes added to the environment */
  6966. n = strlen(added) + 1;
  6967. env->bufused += n;
  6968. /* Now update the variable index */
  6969. space = (env->varlen - env->varused);
  6970. if (space < 2) {
  6971. mg_cry(env->conn,
  6972. "%s: Cannot register CGI variable [%s]",
  6973. __func__,
  6974. fmt);
  6975. return;
  6976. }
  6977. /* Append a pointer to the added string into the envp array */
  6978. env->var[env->varused] = added;
  6979. env->varused++;
  6980. }
  6981. static void
  6982. prepare_cgi_environment(struct mg_connection *conn,
  6983. const char *prog,
  6984. struct cgi_environment *env)
  6985. {
  6986. const char *s;
  6987. struct vec var_vec;
  6988. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  6989. int i, truncated, uri_len;
  6990. if (conn == NULL || prog == NULL || env == NULL) {
  6991. return;
  6992. }
  6993. env->conn = conn;
  6994. env->buflen = CGI_ENVIRONMENT_SIZE;
  6995. env->bufused = 0;
  6996. env->buf = (char *)mg_malloc(env->buflen);
  6997. env->varlen = MAX_CGI_ENVIR_VARS;
  6998. env->varused = 0;
  6999. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7000. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7001. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7002. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7003. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7004. /* Prepare the environment block */
  7005. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7006. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7007. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7008. #if defined(USE_IPV6)
  7009. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7010. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7011. } else
  7012. #endif
  7013. {
  7014. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7015. }
  7016. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7017. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7018. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7019. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7020. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7021. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7022. /* SCRIPT_NAME */
  7023. uri_len = (int)strlen(conn->request_info.local_uri);
  7024. if (conn->path_info == NULL) {
  7025. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7026. /* URI: /path_to_script/script.cgi */
  7027. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7028. } else {
  7029. /* URI: /path_to_script/ ... using index.cgi */
  7030. char *index_file = strrchr(prog, '/');
  7031. if (index_file) {
  7032. addenv(env,
  7033. "SCRIPT_NAME=%s%s",
  7034. conn->request_info.local_uri,
  7035. index_file + 1);
  7036. }
  7037. }
  7038. } else {
  7039. /* URI: /path_to_script/script.cgi/path_info */
  7040. addenv(env,
  7041. "SCRIPT_NAME=%.*s",
  7042. uri_len - (int)strlen(conn->path_info),
  7043. conn->request_info.local_uri);
  7044. }
  7045. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7046. if (conn->path_info == NULL) {
  7047. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7048. } else {
  7049. addenv(env,
  7050. "PATH_TRANSLATED=%s%s",
  7051. conn->ctx->config[DOCUMENT_ROOT],
  7052. conn->path_info);
  7053. }
  7054. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7055. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7056. addenv(env, "CONTENT_TYPE=%s", s);
  7057. }
  7058. if (conn->request_info.query_string != NULL) {
  7059. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7060. }
  7061. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7062. addenv(env, "CONTENT_LENGTH=%s", s);
  7063. }
  7064. if ((s = getenv("PATH")) != NULL) {
  7065. addenv(env, "PATH=%s", s);
  7066. }
  7067. if (conn->path_info != NULL) {
  7068. addenv(env, "PATH_INFO=%s", conn->path_info);
  7069. }
  7070. if (conn->status_code > 0) {
  7071. /* CGI error handler should show the status code */
  7072. addenv(env, "STATUS=%d", conn->status_code);
  7073. }
  7074. #if defined(_WIN32)
  7075. if ((s = getenv("COMSPEC")) != NULL) {
  7076. addenv(env, "COMSPEC=%s", s);
  7077. }
  7078. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7079. addenv(env, "SYSTEMROOT=%s", s);
  7080. }
  7081. if ((s = getenv("SystemDrive")) != NULL) {
  7082. addenv(env, "SystemDrive=%s", s);
  7083. }
  7084. if ((s = getenv("ProgramFiles")) != NULL) {
  7085. addenv(env, "ProgramFiles=%s", s);
  7086. }
  7087. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7088. addenv(env, "ProgramFiles(x86)=%s", s);
  7089. }
  7090. #else
  7091. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7092. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7093. }
  7094. #endif /* _WIN32 */
  7095. if ((s = getenv("PERLLIB")) != NULL) {
  7096. addenv(env, "PERLLIB=%s", s);
  7097. }
  7098. if (conn->request_info.remote_user != NULL) {
  7099. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7100. addenv(env, "%s", "AUTH_TYPE=Digest");
  7101. }
  7102. /* Add all headers as HTTP_* variables */
  7103. for (i = 0; i < conn->request_info.num_headers; i++) {
  7104. (void)mg_snprintf(conn,
  7105. &truncated,
  7106. http_var_name,
  7107. sizeof(http_var_name),
  7108. "HTTP_%s",
  7109. conn->request_info.http_headers[i].name);
  7110. if (truncated) {
  7111. mg_cry(conn,
  7112. "%s: HTTP header variable too long [%s]",
  7113. __func__,
  7114. conn->request_info.http_headers[i].name);
  7115. continue;
  7116. }
  7117. /* Convert variable name into uppercase, and change - to _ */
  7118. for (p = http_var_name; *p != '\0'; p++) {
  7119. if (*p == '-') {
  7120. *p = '_';
  7121. }
  7122. *p = (char)toupper(*(unsigned char *)p);
  7123. }
  7124. addenv(env,
  7125. "%s=%s",
  7126. http_var_name,
  7127. conn->request_info.http_headers[i].value);
  7128. }
  7129. /* Add user-specified variables */
  7130. s = conn->ctx->config[CGI_ENVIRONMENT];
  7131. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7132. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7133. }
  7134. env->var[env->varused] = NULL;
  7135. env->buf[env->bufused] = '\0';
  7136. }
  7137. static void
  7138. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7139. {
  7140. char *buf;
  7141. size_t buflen;
  7142. int headers_len, data_len, i, truncated;
  7143. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7144. const char *status, *status_text, *connection_state;
  7145. char *pbuf, dir[PATH_MAX], *p;
  7146. struct mg_request_info ri;
  7147. struct cgi_environment blk;
  7148. FILE *in = NULL, *out = NULL, *err = NULL;
  7149. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7150. pid_t pid = (pid_t)-1;
  7151. if (conn == NULL) {
  7152. return;
  7153. }
  7154. buf = NULL;
  7155. buflen = 16384;
  7156. prepare_cgi_environment(conn, prog, &blk);
  7157. /* CGI must be executed in its own directory. 'dir' must point to the
  7158. * directory containing executable program, 'p' must point to the
  7159. * executable program name relative to 'dir'. */
  7160. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7161. if (truncated) {
  7162. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7163. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7164. goto done;
  7165. }
  7166. if ((p = strrchr(dir, '/')) != NULL) {
  7167. *p++ = '\0';
  7168. } else {
  7169. dir[0] = '.', dir[1] = '\0';
  7170. p = (char *)prog;
  7171. }
  7172. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7173. status = strerror(ERRNO);
  7174. mg_cry(conn,
  7175. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7176. prog,
  7177. status);
  7178. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7179. goto done;
  7180. }
  7181. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7182. if (pid == (pid_t)-1) {
  7183. status = strerror(ERRNO);
  7184. mg_cry(conn,
  7185. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7186. prog,
  7187. status);
  7188. send_http_error(conn,
  7189. 500,
  7190. "Error: Cannot spawn CGI process [%s]: %s",
  7191. prog,
  7192. status);
  7193. goto done;
  7194. }
  7195. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7196. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7197. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7198. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7199. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7200. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7201. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7202. /* Parent closes only one side of the pipes.
  7203. * If we don't mark them as closed, close() attempt before
  7204. * return from this function throws an exception on Windows.
  7205. * Windows does not like when closed descriptor is closed again. */
  7206. (void)close(fdin[0]);
  7207. (void)close(fdout[1]);
  7208. (void)close(fderr[1]);
  7209. fdin[0] = fdout[1] = fderr[1] = -1;
  7210. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7211. status = strerror(ERRNO);
  7212. mg_cry(conn,
  7213. "Error: CGI program \"%s\": Can not open stdin: %s",
  7214. prog,
  7215. status);
  7216. send_http_error(conn,
  7217. 500,
  7218. "Error: CGI can not open fdin\nfopen: %s",
  7219. status);
  7220. goto done;
  7221. }
  7222. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7223. status = strerror(ERRNO);
  7224. mg_cry(conn,
  7225. "Error: CGI program \"%s\": Can not open stdout: %s",
  7226. prog,
  7227. status);
  7228. send_http_error(conn,
  7229. 500,
  7230. "Error: CGI can not open fdout\nfopen: %s",
  7231. status);
  7232. goto done;
  7233. }
  7234. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7235. status = strerror(ERRNO);
  7236. mg_cry(conn,
  7237. "Error: CGI program \"%s\": Can not open stderr: %s",
  7238. prog,
  7239. status);
  7240. send_http_error(conn,
  7241. 500,
  7242. "Error: CGI can not open fdout\nfopen: %s",
  7243. status);
  7244. goto done;
  7245. }
  7246. setbuf(in, NULL);
  7247. setbuf(out, NULL);
  7248. setbuf(err, NULL);
  7249. fout.access.fp = out;
  7250. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7251. /* This is a POST/PUT request, or another request with body data. */
  7252. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7253. /* Error sending the body data */
  7254. mg_cry(conn,
  7255. "Error: CGI program \"%s\": Forward body data failed",
  7256. prog);
  7257. goto done;
  7258. }
  7259. }
  7260. /* Close so child gets an EOF. */
  7261. fclose(in);
  7262. in = NULL;
  7263. fdin[1] = -1;
  7264. /* Now read CGI reply into a buffer. We need to set correct
  7265. * status code, thus we need to see all HTTP headers first.
  7266. * Do not send anything back to client, until we buffer in all
  7267. * HTTP headers. */
  7268. data_len = 0;
  7269. buf = (char *)mg_malloc(buflen);
  7270. if (buf == NULL) {
  7271. send_http_error(conn,
  7272. 500,
  7273. "Error: Not enough memory for CGI buffer (%u bytes)",
  7274. (unsigned int)buflen);
  7275. mg_cry(conn,
  7276. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7277. "bytes)",
  7278. prog,
  7279. (unsigned int)buflen);
  7280. goto done;
  7281. }
  7282. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7283. if (headers_len <= 0) {
  7284. /* Could not parse the CGI response. Check if some error message on
  7285. * stderr. */
  7286. i = pull_all(err, conn, buf, (int)buflen);
  7287. if (i > 0) {
  7288. mg_cry(conn,
  7289. "Error: CGI program \"%s\" sent error "
  7290. "message: [%.*s]",
  7291. prog,
  7292. i,
  7293. buf);
  7294. send_http_error(conn,
  7295. 500,
  7296. "Error: CGI program \"%s\" sent error "
  7297. "message: [%.*s]",
  7298. prog,
  7299. i,
  7300. buf);
  7301. } else {
  7302. mg_cry(conn,
  7303. "Error: CGI program sent malformed or too big "
  7304. "(>%u bytes) HTTP headers: [%.*s]",
  7305. (unsigned)buflen,
  7306. data_len,
  7307. buf);
  7308. send_http_error(conn,
  7309. 500,
  7310. "Error: CGI program sent malformed or too big "
  7311. "(>%u bytes) HTTP headers: [%.*s]",
  7312. (unsigned)buflen,
  7313. data_len,
  7314. buf);
  7315. }
  7316. goto done;
  7317. }
  7318. pbuf = buf;
  7319. buf[headers_len - 1] = '\0';
  7320. parse_http_headers(&pbuf, &ri);
  7321. /* Make up and send the status line */
  7322. status_text = "OK";
  7323. if ((status = get_header(&ri, "Status")) != NULL) {
  7324. conn->status_code = atoi(status);
  7325. status_text = status;
  7326. while (isdigit(*(const unsigned char *)status_text)
  7327. || *status_text == ' ') {
  7328. status_text++;
  7329. }
  7330. } else if (get_header(&ri, "Location") != NULL) {
  7331. conn->status_code = 302;
  7332. } else {
  7333. conn->status_code = 200;
  7334. }
  7335. connection_state = get_header(&ri, "Connection");
  7336. if (!header_has_option(connection_state, "keep-alive")) {
  7337. conn->must_close = 1;
  7338. }
  7339. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7340. /* Send headers */
  7341. for (i = 0; i < ri.num_headers; i++) {
  7342. mg_printf(conn,
  7343. "%s: %s\r\n",
  7344. ri.http_headers[i].name,
  7345. ri.http_headers[i].value);
  7346. }
  7347. mg_write(conn, "\r\n", 2);
  7348. /* Send chunk of data that may have been read after the headers */
  7349. conn->num_bytes_sent +=
  7350. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7351. /* Read the rest of CGI output and send to the client */
  7352. send_file_data(conn, &fout, 0, INT64_MAX);
  7353. done:
  7354. mg_free(blk.var);
  7355. mg_free(blk.buf);
  7356. if (pid != (pid_t)-1) {
  7357. kill(pid, SIGKILL);
  7358. #if !defined(_WIN32)
  7359. {
  7360. int st;
  7361. while (waitpid(pid, &st, 0) != -1)
  7362. ; /* clean zombies */
  7363. }
  7364. #endif
  7365. }
  7366. if (fdin[0] != -1) {
  7367. close(fdin[0]);
  7368. }
  7369. if (fdout[1] != -1) {
  7370. close(fdout[1]);
  7371. }
  7372. if (in != NULL) {
  7373. fclose(in);
  7374. } else if (fdin[1] != -1) {
  7375. close(fdin[1]);
  7376. }
  7377. if (out != NULL) {
  7378. fclose(out);
  7379. } else if (fdout[0] != -1) {
  7380. close(fdout[0]);
  7381. }
  7382. if (err != NULL) {
  7383. fclose(err);
  7384. } else if (fderr[0] != -1) {
  7385. close(fderr[0]);
  7386. }
  7387. if (buf != NULL) {
  7388. mg_free(buf);
  7389. }
  7390. }
  7391. #endif /* !NO_CGI */
  7392. #if !defined(NO_FILES)
  7393. static void
  7394. mkcol(struct mg_connection *conn, const char *path)
  7395. {
  7396. int rc, body_len;
  7397. struct de de;
  7398. char date[64];
  7399. time_t curtime = time(NULL);
  7400. if (conn == NULL) {
  7401. return;
  7402. }
  7403. /* TODO (mid): Check the send_http_error situations in this function */
  7404. memset(&de.file, 0, sizeof(de.file));
  7405. if (!mg_stat(conn, path, &de.file)) {
  7406. mg_cry(conn,
  7407. "%s: mg_stat(%s) failed: %s",
  7408. __func__,
  7409. path,
  7410. strerror(ERRNO));
  7411. }
  7412. if (de.file.last_modified) {
  7413. /* TODO (high): This check does not seem to make any sense ! */
  7414. send_http_error(
  7415. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7416. return;
  7417. }
  7418. body_len = conn->data_len - conn->request_len;
  7419. if (body_len > 0) {
  7420. send_http_error(
  7421. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7422. return;
  7423. }
  7424. rc = mg_mkdir(conn, path, 0755);
  7425. if (rc == 0) {
  7426. conn->status_code = 201;
  7427. gmt_time_string(date, sizeof(date), &curtime);
  7428. mg_printf(conn,
  7429. "HTTP/1.1 %d Created\r\n"
  7430. "Date: %s\r\n",
  7431. conn->status_code,
  7432. date);
  7433. send_static_cache_header(conn);
  7434. mg_printf(conn,
  7435. "Content-Length: 0\r\n"
  7436. "Connection: %s\r\n\r\n",
  7437. suggest_connection_header(conn));
  7438. } else if (rc == -1) {
  7439. if (errno == EEXIST) {
  7440. send_http_error(
  7441. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7442. } else if (errno == EACCES) {
  7443. send_http_error(
  7444. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7445. } else if (errno == ENOENT) {
  7446. send_http_error(
  7447. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7448. } else {
  7449. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7450. }
  7451. }
  7452. }
  7453. static void
  7454. put_file(struct mg_connection *conn, const char *path)
  7455. {
  7456. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7457. const char *range;
  7458. int64_t r1, r2;
  7459. int rc;
  7460. char date[64];
  7461. time_t curtime = time(NULL);
  7462. if (conn == NULL) {
  7463. return;
  7464. }
  7465. if (mg_stat(conn, path, &file.stat)) {
  7466. /* File already exists */
  7467. conn->status_code = 200;
  7468. if (file.stat.is_directory) {
  7469. /* This is an already existing directory,
  7470. * so there is nothing to do for the server. */
  7471. rc = 0;
  7472. } else {
  7473. /* File exists and is not a directory. */
  7474. /* Can it be replaced? */
  7475. if (file.access.membuf != NULL) {
  7476. /* This is an "in-memory" file, that can not be replaced */
  7477. send_http_error(
  7478. conn,
  7479. 405,
  7480. "Error: Put not possible\nReplacing %s is not supported",
  7481. path);
  7482. return;
  7483. }
  7484. /* Check if the server may write this file */
  7485. if (access(path, W_OK) == 0) {
  7486. /* Access granted */
  7487. conn->status_code = 200;
  7488. rc = 1;
  7489. } else {
  7490. send_http_error(
  7491. conn,
  7492. 403,
  7493. "Error: Put not possible\nReplacing %s is not allowed",
  7494. path);
  7495. return;
  7496. }
  7497. }
  7498. } else {
  7499. /* File should be created */
  7500. conn->status_code = 201;
  7501. rc = put_dir(conn, path);
  7502. }
  7503. if (rc == 0) {
  7504. /* put_dir returns 0 if path is a directory */
  7505. gmt_time_string(date, sizeof(date), &curtime);
  7506. mg_printf(conn,
  7507. "HTTP/1.1 %d %s\r\n",
  7508. conn->status_code,
  7509. mg_get_response_code_text(NULL, conn->status_code));
  7510. send_no_cache_header(conn);
  7511. mg_printf(conn,
  7512. "Date: %s\r\n"
  7513. "Content-Length: 0\r\n"
  7514. "Connection: %s\r\n\r\n",
  7515. date,
  7516. suggest_connection_header(conn));
  7517. /* Request to create a directory has been fulfilled successfully.
  7518. * No need to put a file. */
  7519. return;
  7520. }
  7521. if (rc == -1) {
  7522. /* put_dir returns -1 if the path is too long */
  7523. send_http_error(conn,
  7524. 414,
  7525. "Error: Path too long\nput_dir(%s): %s",
  7526. path,
  7527. strerror(ERRNO));
  7528. return;
  7529. }
  7530. if (rc == -2) {
  7531. /* put_dir returns -2 if the directory can not be created */
  7532. send_http_error(conn,
  7533. 500,
  7534. "Error: Can not create directory\nput_dir(%s): %s",
  7535. path,
  7536. strerror(ERRNO));
  7537. return;
  7538. }
  7539. /* A file should be created or overwritten. */
  7540. /* TODO: Test if write or write+read is required. */
  7541. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7542. || file.access.fp == NULL) {
  7543. (void)mg_fclose(&file.access);
  7544. send_http_error(conn,
  7545. 500,
  7546. "Error: Can not create file\nfopen(%s): %s",
  7547. path,
  7548. strerror(ERRNO));
  7549. return;
  7550. }
  7551. fclose_on_exec(&file.access, conn);
  7552. range = mg_get_header(conn, "Content-Range");
  7553. r1 = r2 = 0;
  7554. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7555. conn->status_code = 206; /* Partial content */
  7556. fseeko(file.access.fp, r1, SEEK_SET);
  7557. }
  7558. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7559. /* forward_body_data failed.
  7560. * The error code has already been sent to the client,
  7561. * and conn->status_code is already set. */
  7562. (void)mg_fclose(&file.access);
  7563. return;
  7564. }
  7565. if (mg_fclose(&file.access) != 0) {
  7566. /* fclose failed. This might have different reasons, but a likely
  7567. * one is "no space on disk", http 507. */
  7568. conn->status_code = 507;
  7569. }
  7570. gmt_time_string(date, sizeof(date), &curtime);
  7571. mg_printf(conn,
  7572. "HTTP/1.1 %d %s\r\n",
  7573. conn->status_code,
  7574. mg_get_response_code_text(NULL, conn->status_code));
  7575. send_no_cache_header(conn);
  7576. mg_printf(conn,
  7577. "Date: %s\r\n"
  7578. "Content-Length: 0\r\n"
  7579. "Connection: %s\r\n\r\n",
  7580. date,
  7581. suggest_connection_header(conn));
  7582. }
  7583. static void
  7584. delete_file(struct mg_connection *conn, const char *path)
  7585. {
  7586. struct de de;
  7587. memset(&de.file, 0, sizeof(de.file));
  7588. if (!mg_stat(conn, path, &de.file)) {
  7589. /* mg_stat returns 0 if the file does not exist */
  7590. send_http_error(conn,
  7591. 404,
  7592. "Error: Cannot delete file\nFile %s not found",
  7593. path);
  7594. return;
  7595. }
  7596. #if 0 /* Ignore if a file in memory is inside a folder */
  7597. if (de.access.membuf != NULL) {
  7598. /* the file is cached in memory */
  7599. send_http_error(
  7600. conn,
  7601. 405,
  7602. "Error: Delete not possible\nDeleting %s is not supported",
  7603. path);
  7604. return;
  7605. }
  7606. #endif
  7607. if (de.file.is_directory) {
  7608. if (remove_directory(conn, path)) {
  7609. /* Delete is successful: Return 204 without content. */
  7610. send_http_error(conn, 204, "%s", "");
  7611. } else {
  7612. /* Delete is not successful: Return 500 (Server error). */
  7613. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7614. }
  7615. return;
  7616. }
  7617. /* This is an existing file (not a directory).
  7618. * Check if write permission is granted. */
  7619. if (access(path, W_OK) != 0) {
  7620. /* File is read only */
  7621. send_http_error(
  7622. conn,
  7623. 403,
  7624. "Error: Delete not possible\nDeleting %s is not allowed",
  7625. path);
  7626. return;
  7627. }
  7628. /* Try to delete it. */
  7629. if (mg_remove(conn, path) == 0) {
  7630. /* Delete was successful: Return 204 without content. */
  7631. send_http_error(conn, 204, "%s", "");
  7632. } else {
  7633. /* Delete not successful (file locked). */
  7634. send_http_error(conn,
  7635. 423,
  7636. "Error: Cannot delete file\nremove(%s): %s",
  7637. path,
  7638. strerror(ERRNO));
  7639. }
  7640. }
  7641. #endif /* !NO_FILES */
  7642. static void
  7643. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7644. static void
  7645. do_ssi_include(struct mg_connection *conn,
  7646. const char *ssi,
  7647. char *tag,
  7648. int include_level)
  7649. {
  7650. char file_name[MG_BUF_LEN], path[512], *p;
  7651. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7652. size_t len;
  7653. int truncated = 0;
  7654. if (conn == NULL) {
  7655. return;
  7656. }
  7657. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7658. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7659. * always < MG_BUF_LEN. */
  7660. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7661. /* File name is relative to the webserver root */
  7662. file_name[511] = 0;
  7663. (void)mg_snprintf(conn,
  7664. &truncated,
  7665. path,
  7666. sizeof(path),
  7667. "%s/%s",
  7668. conn->ctx->config[DOCUMENT_ROOT],
  7669. file_name);
  7670. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7671. /* File name is relative to the webserver working directory
  7672. * or it is absolute system path */
  7673. file_name[511] = 0;
  7674. (void)
  7675. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7676. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7677. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7678. /* File name is relative to the currect document */
  7679. file_name[511] = 0;
  7680. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7681. if (!truncated) {
  7682. if ((p = strrchr(path, '/')) != NULL) {
  7683. p[1] = '\0';
  7684. }
  7685. len = strlen(path);
  7686. (void)mg_snprintf(conn,
  7687. &truncated,
  7688. path + len,
  7689. sizeof(path) - len,
  7690. "%s",
  7691. file_name);
  7692. }
  7693. } else {
  7694. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7695. return;
  7696. }
  7697. if (truncated) {
  7698. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7699. return;
  7700. }
  7701. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7702. mg_cry(conn,
  7703. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7704. tag,
  7705. path,
  7706. strerror(ERRNO));
  7707. } else {
  7708. fclose_on_exec(&file.access, conn);
  7709. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7710. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7711. path) > 0) {
  7712. send_ssi_file(conn, path, &file, include_level + 1);
  7713. } else {
  7714. send_file_data(conn, &file, 0, INT64_MAX);
  7715. }
  7716. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7717. }
  7718. }
  7719. #if !defined(NO_POPEN)
  7720. static void
  7721. do_ssi_exec(struct mg_connection *conn, char *tag)
  7722. {
  7723. char cmd[1024] = "";
  7724. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7725. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7726. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7727. } else {
  7728. cmd[1023] = 0;
  7729. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7730. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7731. } else {
  7732. send_file_data(conn, &file, 0, INT64_MAX);
  7733. pclose(file.access.fp);
  7734. }
  7735. }
  7736. }
  7737. #endif /* !NO_POPEN */
  7738. static int
  7739. mg_fgetc(struct mg_file *filep, int offset)
  7740. {
  7741. if (filep == NULL) {
  7742. return EOF;
  7743. }
  7744. if (filep->access.membuf != NULL && offset >= 0
  7745. && ((unsigned int)(offset)) < filep->stat.size) {
  7746. return ((const unsigned char *)filep->access.membuf)[offset];
  7747. } else if (filep->access.fp != NULL) {
  7748. return fgetc(filep->access.fp);
  7749. } else {
  7750. return EOF;
  7751. }
  7752. }
  7753. static void
  7754. send_ssi_file(struct mg_connection *conn,
  7755. const char *path,
  7756. struct mg_file *filep,
  7757. int include_level)
  7758. {
  7759. char buf[MG_BUF_LEN];
  7760. int ch, offset, len, in_ssi_tag;
  7761. if (include_level > 10) {
  7762. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7763. return;
  7764. }
  7765. in_ssi_tag = len = offset = 0;
  7766. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7767. if (in_ssi_tag && ch == '>') {
  7768. in_ssi_tag = 0;
  7769. buf[len++] = (char)ch;
  7770. buf[len] = '\0';
  7771. /* assert(len <= (int) sizeof(buf)); */
  7772. if (len > (int)sizeof(buf)) {
  7773. break;
  7774. }
  7775. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7776. /* Not an SSI tag, pass it */
  7777. (void)mg_write(conn, buf, (size_t)len);
  7778. } else {
  7779. if (!memcmp(buf + 5, "include", 7)) {
  7780. do_ssi_include(conn, path, buf + 12, include_level);
  7781. #if !defined(NO_POPEN)
  7782. } else if (!memcmp(buf + 5, "exec", 4)) {
  7783. do_ssi_exec(conn, buf + 9);
  7784. #endif /* !NO_POPEN */
  7785. } else {
  7786. mg_cry(conn,
  7787. "%s: unknown SSI "
  7788. "command: \"%s\"",
  7789. path,
  7790. buf);
  7791. }
  7792. }
  7793. len = 0;
  7794. } else if (in_ssi_tag) {
  7795. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7796. /* Not an SSI tag */
  7797. in_ssi_tag = 0;
  7798. } else if (len == (int)sizeof(buf) - 2) {
  7799. mg_cry(conn, "%s: SSI tag is too large", path);
  7800. len = 0;
  7801. }
  7802. buf[len++] = (char)(ch & 0xff);
  7803. } else if (ch == '<') {
  7804. in_ssi_tag = 1;
  7805. if (len > 0) {
  7806. mg_write(conn, buf, (size_t)len);
  7807. }
  7808. len = 0;
  7809. buf[len++] = (char)(ch & 0xff);
  7810. } else {
  7811. buf[len++] = (char)(ch & 0xff);
  7812. if (len == (int)sizeof(buf)) {
  7813. mg_write(conn, buf, (size_t)len);
  7814. len = 0;
  7815. }
  7816. }
  7817. }
  7818. /* Send the rest of buffered data */
  7819. if (len > 0) {
  7820. mg_write(conn, buf, (size_t)len);
  7821. }
  7822. }
  7823. static void
  7824. handle_ssi_file_request(struct mg_connection *conn,
  7825. const char *path,
  7826. struct mg_file *filep)
  7827. {
  7828. char date[64];
  7829. time_t curtime = time(NULL);
  7830. const char *cors1, *cors2, *cors3;
  7831. if (conn == NULL || path == NULL || filep == NULL) {
  7832. return;
  7833. }
  7834. if (mg_get_header(conn, "Origin")) {
  7835. /* Cross-origin resource sharing (CORS). */
  7836. cors1 = "Access-Control-Allow-Origin: ";
  7837. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7838. cors3 = "\r\n";
  7839. } else {
  7840. cors1 = cors2 = cors3 = "";
  7841. }
  7842. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7843. /* File exists (precondition for calling this function),
  7844. * but can not be opened by the server. */
  7845. send_http_error(conn,
  7846. 500,
  7847. "Error: Cannot read file\nfopen(%s): %s",
  7848. path,
  7849. strerror(ERRNO));
  7850. } else {
  7851. conn->must_close = 1;
  7852. gmt_time_string(date, sizeof(date), &curtime);
  7853. fclose_on_exec(&filep->access, conn);
  7854. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7855. send_no_cache_header(conn);
  7856. mg_printf(conn,
  7857. "%s%s%s"
  7858. "Date: %s\r\n"
  7859. "Content-Type: text/html\r\n"
  7860. "Connection: %s\r\n\r\n",
  7861. cors1,
  7862. cors2,
  7863. cors3,
  7864. date,
  7865. suggest_connection_header(conn));
  7866. send_ssi_file(conn, path, filep, 0);
  7867. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  7868. }
  7869. }
  7870. #if !defined(NO_FILES)
  7871. static void
  7872. send_options(struct mg_connection *conn)
  7873. {
  7874. char date[64];
  7875. time_t curtime = time(NULL);
  7876. if (!conn) {
  7877. return;
  7878. }
  7879. conn->status_code = 200;
  7880. conn->must_close = 1;
  7881. gmt_time_string(date, sizeof(date), &curtime);
  7882. mg_printf(conn,
  7883. "HTTP/1.1 200 OK\r\n"
  7884. "Date: %s\r\n"
  7885. /* TODO: "Cache-Control" (?) */
  7886. "Connection: %s\r\n"
  7887. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7888. "PROPFIND, MKCOL\r\n"
  7889. "DAV: 1\r\n\r\n",
  7890. date,
  7891. suggest_connection_header(conn));
  7892. }
  7893. /* Writes PROPFIND properties for a collection element */
  7894. static void
  7895. print_props(struct mg_connection *conn,
  7896. const char *uri,
  7897. struct mg_file_stat *filep)
  7898. {
  7899. char mtime[64];
  7900. if (conn == NULL || uri == NULL || filep == NULL) {
  7901. return;
  7902. }
  7903. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7904. conn->num_bytes_sent +=
  7905. mg_printf(conn,
  7906. "<d:response>"
  7907. "<d:href>%s</d:href>"
  7908. "<d:propstat>"
  7909. "<d:prop>"
  7910. "<d:resourcetype>%s</d:resourcetype>"
  7911. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7912. "<d:getlastmodified>%s</d:getlastmodified>"
  7913. "</d:prop>"
  7914. "<d:status>HTTP/1.1 200 OK</d:status>"
  7915. "</d:propstat>"
  7916. "</d:response>\n",
  7917. uri,
  7918. filep->is_directory ? "<d:collection/>" : "",
  7919. filep->size,
  7920. mtime);
  7921. }
  7922. static void
  7923. print_dav_dir_entry(struct de *de, void *data)
  7924. {
  7925. char href[PATH_MAX];
  7926. char href_encoded[PATH_MAX * 3 /* worst case */];
  7927. int truncated;
  7928. struct mg_connection *conn = (struct mg_connection *)data;
  7929. if (!de || !conn) {
  7930. return;
  7931. }
  7932. mg_snprintf(conn,
  7933. &truncated,
  7934. href,
  7935. sizeof(href),
  7936. "%s%s",
  7937. conn->request_info.local_uri,
  7938. de->file_name);
  7939. if (!truncated) {
  7940. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7941. print_props(conn, href_encoded, &de->file);
  7942. }
  7943. }
  7944. static void
  7945. handle_propfind(struct mg_connection *conn,
  7946. const char *path,
  7947. struct mg_file_stat *filep)
  7948. {
  7949. const char *depth = mg_get_header(conn, "Depth");
  7950. char date[64];
  7951. time_t curtime = time(NULL);
  7952. gmt_time_string(date, sizeof(date), &curtime);
  7953. if (!conn || !path || !filep || !conn->ctx) {
  7954. return;
  7955. }
  7956. conn->must_close = 1;
  7957. conn->status_code = 207;
  7958. mg_printf(conn,
  7959. "HTTP/1.1 207 Multi-Status\r\n"
  7960. "Date: %s\r\n",
  7961. date);
  7962. send_static_cache_header(conn);
  7963. mg_printf(conn,
  7964. "Connection: %s\r\n"
  7965. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7966. suggest_connection_header(conn));
  7967. conn->num_bytes_sent +=
  7968. mg_printf(conn,
  7969. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7970. "<d:multistatus xmlns:d='DAV:'>\n");
  7971. /* Print properties for the requested resource itself */
  7972. print_props(conn, conn->request_info.local_uri, filep);
  7973. /* If it is a directory, print directory entries too if Depth is not 0 */
  7974. if (filep && filep->is_directory
  7975. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7976. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7977. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7978. }
  7979. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  7980. }
  7981. #endif
  7982. void
  7983. mg_lock_connection(struct mg_connection *conn)
  7984. {
  7985. if (conn) {
  7986. (void)pthread_mutex_lock(&conn->mutex);
  7987. }
  7988. }
  7989. void
  7990. mg_unlock_connection(struct mg_connection *conn)
  7991. {
  7992. if (conn) {
  7993. (void)pthread_mutex_unlock(&conn->mutex);
  7994. }
  7995. }
  7996. void
  7997. mg_lock_context(struct mg_context *ctx)
  7998. {
  7999. if (ctx) {
  8000. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8001. }
  8002. }
  8003. void
  8004. mg_unlock_context(struct mg_context *ctx)
  8005. {
  8006. if (ctx) {
  8007. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8008. }
  8009. }
  8010. #if defined(USE_TIMERS)
  8011. #include "timer.inl"
  8012. #endif /* USE_TIMERS */
  8013. #ifdef USE_LUA
  8014. #include "mod_lua.inl"
  8015. #endif /* USE_LUA */
  8016. #ifdef USE_DUKTAPE
  8017. #include "mod_duktape.inl"
  8018. #endif /* USE_DUKTAPE */
  8019. #if defined(USE_WEBSOCKET)
  8020. #define SHA_API static
  8021. #include "sha1.inl"
  8022. static int
  8023. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8024. {
  8025. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8026. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8027. SHA1_CTX sha_ctx;
  8028. int truncated;
  8029. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8030. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8031. if (truncated) {
  8032. conn->must_close = 1;
  8033. return 0;
  8034. }
  8035. SHA1_Init(&sha_ctx);
  8036. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8037. SHA1_Final(&sha_ctx, (unsigned char *)sha);
  8038. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8039. mg_printf(conn,
  8040. "HTTP/1.1 101 Switching Protocols\r\n"
  8041. "Upgrade: websocket\r\n"
  8042. "Connection: Upgrade\r\n"
  8043. "Sec-WebSocket-Accept: %s\r\n",
  8044. b64_sha);
  8045. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8046. mg_printf(conn,
  8047. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8048. conn->request_info.acceptedWebSocketSubprotocol);
  8049. } else {
  8050. mg_printf(conn, "%s", "\r\n");
  8051. }
  8052. return 1;
  8053. }
  8054. static void
  8055. read_websocket(struct mg_connection *conn,
  8056. mg_websocket_data_handler ws_data_handler,
  8057. void *callback_data)
  8058. {
  8059. /* Pointer to the beginning of the portion of the incoming websocket
  8060. * message queue.
  8061. * The original websocket upgrade request is never removed, so the queue
  8062. * begins after it. */
  8063. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8064. int n, error, exit_by_callback;
  8065. /* body_len is the length of the entire queue in bytes
  8066. * len is the length of the current message
  8067. * data_len is the length of the current message's data payload
  8068. * header_len is the length of the current message's header */
  8069. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8070. /* "The masking key is a 32-bit value chosen at random by the client."
  8071. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8072. */
  8073. unsigned char mask[4];
  8074. /* data points to the place where the message is stored when passed to
  8075. * the
  8076. * websocket_data callback. This is either mem on the stack, or a
  8077. * dynamically allocated buffer if it is too large. */
  8078. unsigned char mem[4096];
  8079. unsigned char *data = mem;
  8080. unsigned char mop; /* mask flag and opcode */
  8081. double timeout = -1.0;
  8082. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8083. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8084. }
  8085. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8086. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8087. }
  8088. mg_set_thread_name("wsock");
  8089. /* Loop continuously, reading messages from the socket, invoking the
  8090. * callback, and waiting repeatedly until an error occurs. */
  8091. while (!conn->ctx->stop_flag) {
  8092. header_len = 0;
  8093. assert(conn->data_len >= conn->request_len);
  8094. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8095. len = buf[1] & 127;
  8096. mask_len = (buf[1] & 128) ? 4 : 0;
  8097. if ((len < 126) && (body_len >= mask_len)) {
  8098. data_len = len;
  8099. header_len = 2 + mask_len;
  8100. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8101. header_len = 4 + mask_len;
  8102. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8103. } else if (body_len >= (10 + mask_len)) {
  8104. header_len = 10 + mask_len;
  8105. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8106. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8107. }
  8108. }
  8109. if (header_len > 0 && body_len >= header_len) {
  8110. /* Allocate space to hold websocket payload */
  8111. data = mem;
  8112. if (data_len > sizeof(mem)) {
  8113. data = (unsigned char *)mg_malloc(data_len);
  8114. if (data == NULL) {
  8115. /* Allocation failed, exit the loop and then close the
  8116. * connection */
  8117. mg_cry(conn, "websocket out of memory; closing connection");
  8118. break;
  8119. }
  8120. }
  8121. /* Copy the mask before we shift the queue and destroy it */
  8122. if (mask_len > 0) {
  8123. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8124. } else {
  8125. memset(mask, 0, sizeof(mask));
  8126. }
  8127. /* Read frame payload from the first message in the queue into
  8128. * data and advance the queue by moving the memory in place. */
  8129. assert(body_len >= header_len);
  8130. if (data_len + header_len > body_len) {
  8131. mop = buf[0]; /* current mask and opcode */
  8132. /* Overflow case */
  8133. len = body_len - header_len;
  8134. memcpy(data, buf + header_len, len);
  8135. error = 0;
  8136. while (len < data_len) {
  8137. n = pull(NULL,
  8138. conn,
  8139. (char *)(data + len),
  8140. (int)(data_len - len),
  8141. timeout);
  8142. if (n <= 0) {
  8143. error = 1;
  8144. break;
  8145. }
  8146. len += (size_t)n;
  8147. }
  8148. if (error) {
  8149. mg_cry(conn, "Websocket pull failed; closing connection");
  8150. break;
  8151. }
  8152. conn->data_len = conn->request_len;
  8153. } else {
  8154. mop = buf[0]; /* current mask and opcode, overwritten by
  8155. * memmove() */
  8156. /* Length of the message being read at the front of the
  8157. * queue */
  8158. len = data_len + header_len;
  8159. /* Copy the data payload into the data pointer for the
  8160. * callback */
  8161. memcpy(data, buf + header_len, data_len);
  8162. /* Move the queue forward len bytes */
  8163. memmove(buf, buf + len, body_len - len);
  8164. /* Mark the queue as advanced */
  8165. conn->data_len -= (int)len;
  8166. }
  8167. /* Apply mask if necessary */
  8168. if (mask_len > 0) {
  8169. for (i = 0; i < data_len; ++i) {
  8170. data[i] ^= mask[i & 3];
  8171. }
  8172. }
  8173. /* Exit the loop if callback signals to exit (server side),
  8174. * or "connection close" opcode received (client side). */
  8175. exit_by_callback = 0;
  8176. if ((ws_data_handler != NULL)
  8177. && !ws_data_handler(
  8178. conn, mop, (char *)data, data_len, callback_data)) {
  8179. exit_by_callback = 1;
  8180. }
  8181. if (data != mem) {
  8182. mg_free(data);
  8183. }
  8184. if (exit_by_callback
  8185. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8186. /* Opcode == 8, connection close */
  8187. break;
  8188. }
  8189. /* Not breaking the loop, process next websocket frame. */
  8190. } else {
  8191. /* Read from the socket into the next available location in the
  8192. * message queue. */
  8193. if ((n = pull(NULL,
  8194. conn,
  8195. conn->buf + conn->data_len,
  8196. conn->buf_size - conn->data_len,
  8197. timeout)) <= 0) {
  8198. /* Error, no bytes read */
  8199. break;
  8200. }
  8201. conn->data_len += n;
  8202. }
  8203. }
  8204. mg_set_thread_name("worker");
  8205. }
  8206. static int
  8207. mg_websocket_write_exec(struct mg_connection *conn,
  8208. int opcode,
  8209. const char *data,
  8210. size_t dataLen,
  8211. uint32_t masking_key)
  8212. {
  8213. unsigned char header[14];
  8214. size_t headerLen = 1;
  8215. int retval = -1;
  8216. #if defined(__GNUC__) || defined(__MINGW32__)
  8217. /* Disable spurious conversion warning for GCC */
  8218. #pragma GCC diagnostic push
  8219. #pragma GCC diagnostic ignored "-Wconversion"
  8220. #endif
  8221. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8222. #if defined(__GNUC__) || defined(__MINGW32__)
  8223. #pragma GCC diagnostic pop
  8224. #endif
  8225. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8226. if (dataLen < 126) {
  8227. /* inline 7-bit length field */
  8228. header[1] = (unsigned char)dataLen;
  8229. headerLen = 2;
  8230. } else if (dataLen <= 0xFFFF) {
  8231. /* 16-bit length field */
  8232. uint16_t len = htons((uint16_t)dataLen);
  8233. header[1] = 126;
  8234. memcpy(header + 2, &len, 2);
  8235. headerLen = 4;
  8236. } else {
  8237. /* 64-bit length field */
  8238. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8239. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8240. header[1] = 127;
  8241. memcpy(header + 2, &len1, 4);
  8242. memcpy(header + 6, &len2, 4);
  8243. headerLen = 10;
  8244. }
  8245. if (masking_key) {
  8246. /* add mask */
  8247. header[1] |= 0x80;
  8248. memcpy(header + headerLen, &masking_key, 4);
  8249. headerLen += 4;
  8250. }
  8251. /* Note that POSIX/Winsock's send() is threadsafe
  8252. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8253. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8254. * push(), although that is only a problem if the packet is large or
  8255. * outgoing buffer is full). */
  8256. (void)mg_lock_connection(conn);
  8257. retval = mg_write(conn, header, headerLen);
  8258. if (dataLen > 0) {
  8259. retval = mg_write(conn, data, dataLen);
  8260. }
  8261. mg_unlock_connection(conn);
  8262. return retval;
  8263. }
  8264. int
  8265. mg_websocket_write(struct mg_connection *conn,
  8266. int opcode,
  8267. const char *data,
  8268. size_t dataLen)
  8269. {
  8270. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8271. }
  8272. static void
  8273. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8274. {
  8275. size_t i = 0;
  8276. i = 0;
  8277. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8278. /* Convert in 32 bit words, if data is 4 byte aligned */
  8279. while (i < (in_len - 3)) {
  8280. *(uint32_t *)(void *)(out + i) =
  8281. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8282. i += 4;
  8283. }
  8284. }
  8285. if (i != in_len) {
  8286. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8287. while (i < in_len) {
  8288. *(uint8_t *)(void *)(out + i) =
  8289. *(uint8_t *)(void *)(in + i)
  8290. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8291. i++;
  8292. }
  8293. }
  8294. }
  8295. int
  8296. mg_websocket_client_write(struct mg_connection *conn,
  8297. int opcode,
  8298. const char *data,
  8299. size_t dataLen)
  8300. {
  8301. int retval = -1;
  8302. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8303. uint32_t masking_key = (uint32_t)get_random();
  8304. if (masked_data == NULL) {
  8305. /* Return -1 in an error case */
  8306. mg_cry(conn,
  8307. "Cannot allocate buffer for masked websocket response: "
  8308. "Out of memory");
  8309. return -1;
  8310. }
  8311. mask_data(data, dataLen, masking_key, masked_data);
  8312. retval = mg_websocket_write_exec(
  8313. conn, opcode, masked_data, dataLen, masking_key);
  8314. mg_free(masked_data);
  8315. return retval;
  8316. }
  8317. static void
  8318. handle_websocket_request(struct mg_connection *conn,
  8319. const char *path,
  8320. int is_callback_resource,
  8321. struct mg_websocket_subprotocols *subprotocols,
  8322. mg_websocket_connect_handler ws_connect_handler,
  8323. mg_websocket_ready_handler ws_ready_handler,
  8324. mg_websocket_data_handler ws_data_handler,
  8325. mg_websocket_close_handler ws_close_handler,
  8326. void *cbData)
  8327. {
  8328. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8329. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8330. int lua_websock = 0;
  8331. #if !defined(USE_LUA)
  8332. (void)path;
  8333. #endif
  8334. /* Step 1: Check websocket protocol version. */
  8335. /* Step 1.1: Check Sec-WebSocket-Key. */
  8336. if (!websock_key) {
  8337. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8338. * requires a Sec-WebSocket-Key header.
  8339. */
  8340. /* It could be the hixie draft version
  8341. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8342. */
  8343. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8344. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8345. char key3[8];
  8346. if ((key1 != NULL) && (key2 != NULL)) {
  8347. /* This version uses 8 byte body data in a GET request */
  8348. conn->content_len = 8;
  8349. if (8 == mg_read(conn, key3, 8)) {
  8350. /* This is the hixie version */
  8351. send_http_error(conn,
  8352. 426,
  8353. "%s",
  8354. "Protocol upgrade to RFC 6455 required");
  8355. return;
  8356. }
  8357. }
  8358. /* This is an unknown version */
  8359. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8360. return;
  8361. }
  8362. /* Step 1.2: Check websocket protocol version. */
  8363. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8364. if (version == NULL || strcmp(version, "13") != 0) {
  8365. /* Reject wrong versions */
  8366. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8367. return;
  8368. }
  8369. /* Step 1.3: Could check for "Host", but we do not really nead this
  8370. * value for anything, so just ignore it. */
  8371. /* Step 2: If a callback is responsible, call it. */
  8372. if (is_callback_resource) {
  8373. /* Step 2.1 check and select subprotocol */
  8374. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8375. if (protocol && subprotocols) {
  8376. int idx;
  8377. unsigned long len;
  8378. const char *sep, *curSubProtocol,
  8379. *acceptedWebSocketSubprotocol = NULL;
  8380. /* look for matching subprotocol */
  8381. do {
  8382. sep = strchr(protocol, ',');
  8383. curSubProtocol = protocol;
  8384. len = sep ? (unsigned long)(sep - protocol) : strlen(protocol);
  8385. while (sep && isspace(*++sep))
  8386. ; // ignore leading whitespaces
  8387. protocol = sep;
  8388. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8389. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8390. && (strncmp(curSubProtocol,
  8391. subprotocols->subprotocols[idx],
  8392. len) == 0)) {
  8393. acceptedWebSocketSubprotocol =
  8394. subprotocols->subprotocols[idx];
  8395. break;
  8396. }
  8397. }
  8398. } while (sep && !acceptedWebSocketSubprotocol);
  8399. conn->request_info.acceptedWebSocketSubprotocol =
  8400. acceptedWebSocketSubprotocol;
  8401. } else if (protocol) {
  8402. /* keep legacy behavior */
  8403. /* The protocol is a comma seperated list of names. */
  8404. /* The server must only return one value from this list. */
  8405. /* First check if it is a list or just a single value. */
  8406. const char *sep = strrchr(protocol, ',');
  8407. if (sep == NULL) {
  8408. /* Just a single protocol -> accept it. */
  8409. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8410. } else {
  8411. /* Multiple protocols -> accept the last one. */
  8412. /* This is just a quick fix if the client offers multiple
  8413. * protocols. The handler should have a list of accepted
  8414. * protocols on his own
  8415. * and use it to select one protocol among those the client has
  8416. * offered.
  8417. */
  8418. while (isspace(*++sep))
  8419. ; // ignore leading whitespaces
  8420. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8421. }
  8422. }
  8423. if (ws_connect_handler != NULL
  8424. && ws_connect_handler(conn, cbData) != 0) {
  8425. /* C callback has returned non-zero, do not proceed with
  8426. * handshake.
  8427. */
  8428. /* Note that C callbacks are no longer called when Lua is
  8429. * responsible, so C can no longer filter callbacks for Lua. */
  8430. return;
  8431. }
  8432. }
  8433. #if defined(USE_LUA)
  8434. /* Step 3: No callback. Check if Lua is responsible. */
  8435. else {
  8436. /* Step 3.1: Check if Lua is responsible. */
  8437. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8438. lua_websock =
  8439. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8440. strlen(
  8441. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8442. path);
  8443. }
  8444. if (lua_websock) {
  8445. /* Step 3.2: Lua is responsible: call it. */
  8446. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8447. if (!conn->lua_websocket_state) {
  8448. /* Lua rejected the new client */
  8449. return;
  8450. }
  8451. }
  8452. }
  8453. #endif
  8454. /* Step 4: Check if there is a responsible websocket handler. */
  8455. if (!is_callback_resource && !lua_websock) {
  8456. /* There is no callback, and Lua is not responsible either. */
  8457. /* Reply with a 404 Not Found or with nothing at all?
  8458. * TODO (mid): check the websocket standards, how to reply to
  8459. * requests to invalid websocket addresses. */
  8460. send_http_error(conn, 404, "%s", "Not found");
  8461. return;
  8462. }
  8463. /* Step 5: The websocket connection has been accepted */
  8464. if (!send_websocket_handshake(conn, websock_key)) {
  8465. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8466. return;
  8467. }
  8468. /* Step 6: Call the ready handler */
  8469. if (is_callback_resource) {
  8470. if (ws_ready_handler != NULL) {
  8471. ws_ready_handler(conn, cbData);
  8472. }
  8473. #if defined(USE_LUA)
  8474. } else if (lua_websock) {
  8475. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8476. /* the ready handler returned false */
  8477. return;
  8478. }
  8479. #endif
  8480. }
  8481. /* Step 7: Enter the read loop */
  8482. if (is_callback_resource) {
  8483. read_websocket(conn, ws_data_handler, cbData);
  8484. #if defined(USE_LUA)
  8485. } else if (lua_websock) {
  8486. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8487. #endif
  8488. }
  8489. /* Step 8: Call the close handler */
  8490. if (ws_close_handler) {
  8491. ws_close_handler(conn, cbData);
  8492. }
  8493. }
  8494. static int
  8495. is_websocket_protocol(const struct mg_connection *conn)
  8496. {
  8497. const char *upgrade, *connection;
  8498. /* A websocket protocoll has the following HTTP headers:
  8499. *
  8500. * Connection: Upgrade
  8501. * Upgrade: Websocket
  8502. */
  8503. upgrade = mg_get_header(conn, "Upgrade");
  8504. if (upgrade == NULL) {
  8505. return 0; /* fail early, don't waste time checking other header
  8506. * fields
  8507. */
  8508. }
  8509. if (!mg_strcasestr(upgrade, "websocket")) {
  8510. return 0;
  8511. }
  8512. connection = mg_get_header(conn, "Connection");
  8513. if (connection == NULL) {
  8514. return 0;
  8515. }
  8516. if (!mg_strcasestr(connection, "upgrade")) {
  8517. return 0;
  8518. }
  8519. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8520. * "Sec-WebSocket-Version" are also required.
  8521. * Don't check them here, since even an unsupported websocket protocol
  8522. * request still IS a websocket request (in contrast to a standard HTTP
  8523. * request). It will fail later in handle_websocket_request.
  8524. */
  8525. return 1;
  8526. }
  8527. #endif /* !USE_WEBSOCKET */
  8528. static int
  8529. isbyte(int n)
  8530. {
  8531. return n >= 0 && n <= 255;
  8532. }
  8533. static int
  8534. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8535. {
  8536. int n, a, b, c, d, slash = 32, len = 0;
  8537. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8538. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8539. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8540. && slash < 33) {
  8541. len = n;
  8542. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8543. | (uint32_t)d;
  8544. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8545. }
  8546. return len;
  8547. }
  8548. static int
  8549. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8550. {
  8551. int throttle = 0;
  8552. struct vec vec, val;
  8553. uint32_t net, mask;
  8554. char mult;
  8555. double v;
  8556. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8557. mult = ',';
  8558. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8559. || (v < 0) || ((lowercase(&mult) != 'k')
  8560. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8561. continue;
  8562. }
  8563. v *= (lowercase(&mult) == 'k')
  8564. ? 1024
  8565. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8566. if (vec.len == 1 && vec.ptr[0] == '*') {
  8567. throttle = (int)v;
  8568. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8569. if ((remote_ip & mask) == net) {
  8570. throttle = (int)v;
  8571. }
  8572. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8573. throttle = (int)v;
  8574. }
  8575. }
  8576. return throttle;
  8577. }
  8578. static uint32_t
  8579. get_remote_ip(const struct mg_connection *conn)
  8580. {
  8581. if (!conn) {
  8582. return 0;
  8583. }
  8584. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8585. }
  8586. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8587. #include "handle_form.inl"
  8588. #if defined(MG_LEGACY_INTERFACE)
  8589. /* Implement the deprecated mg_upload function by calling the new
  8590. * mg_handle_form_request function. While mg_upload could only handle
  8591. * HTML forms sent as POST request in multipart/form-data format
  8592. * containing only file input elements, mg_handle_form_request can
  8593. * handle all form input elements and all standard request methods. */
  8594. struct mg_upload_user_data {
  8595. struct mg_connection *conn;
  8596. const char *destination_dir;
  8597. int num_uploaded_files;
  8598. };
  8599. /* Helper function for deprecated mg_upload. */
  8600. static int
  8601. mg_upload_field_found(const char *key,
  8602. const char *filename,
  8603. char *path,
  8604. size_t pathlen,
  8605. void *user_data)
  8606. {
  8607. int truncated = 0;
  8608. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8609. (void)key;
  8610. if (!filename) {
  8611. mg_cry(fud->conn, "%s: No filename set", __func__);
  8612. return FORM_FIELD_STORAGE_ABORT;
  8613. }
  8614. mg_snprintf(fud->conn,
  8615. &truncated,
  8616. path,
  8617. pathlen - 1,
  8618. "%s/%s",
  8619. fud->destination_dir,
  8620. filename);
  8621. if (!truncated) {
  8622. mg_cry(fud->conn, "%s: File path too long", __func__);
  8623. return FORM_FIELD_STORAGE_ABORT;
  8624. }
  8625. return FORM_FIELD_STORAGE_STORE;
  8626. }
  8627. /* Helper function for deprecated mg_upload. */
  8628. static int
  8629. mg_upload_field_get(const char *key,
  8630. const char *value,
  8631. size_t value_size,
  8632. void *user_data)
  8633. {
  8634. /* Function should never be called */
  8635. (void)key;
  8636. (void)value;
  8637. (void)value_size;
  8638. (void)user_data;
  8639. return 0;
  8640. }
  8641. /* Helper function for deprecated mg_upload. */
  8642. static int
  8643. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8644. {
  8645. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8646. (void)file_size;
  8647. fud->num_uploaded_files++;
  8648. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8649. return 0;
  8650. }
  8651. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8652. int
  8653. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8654. {
  8655. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8656. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8657. mg_upload_field_get,
  8658. mg_upload_field_stored,
  8659. 0};
  8660. int ret;
  8661. fdh.user_data = (void *)&fud;
  8662. ret = mg_handle_form_request(conn, &fdh);
  8663. if (ret < 0) {
  8664. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8665. }
  8666. return fud.num_uploaded_files;
  8667. }
  8668. #endif
  8669. static int
  8670. get_first_ssl_listener_index(const struct mg_context *ctx)
  8671. {
  8672. unsigned int i;
  8673. int idx = -1;
  8674. if (ctx) {
  8675. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8676. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8677. }
  8678. }
  8679. return idx;
  8680. }
  8681. static void
  8682. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8683. {
  8684. char host[1025];
  8685. const char *host_header;
  8686. size_t hostlen;
  8687. host_header = mg_get_header(conn, "Host");
  8688. hostlen = sizeof(host);
  8689. if (host_header != NULL) {
  8690. char *pos;
  8691. mg_strlcpy(host, host_header, hostlen);
  8692. host[hostlen - 1] = '\0';
  8693. pos = strchr(host, ':');
  8694. if (pos != NULL) {
  8695. *pos = '\0';
  8696. }
  8697. } else {
  8698. /* Cannot get host from the Host: header.
  8699. * Fallback to our IP address. */
  8700. if (conn) {
  8701. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8702. }
  8703. }
  8704. /* Send host, port, uri and (if it exists) ?query_string */
  8705. if (conn) {
  8706. mg_printf(conn,
  8707. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8708. host,
  8709. #if defined(USE_IPV6)
  8710. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8711. == AF_INET6)
  8712. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8713. .lsa.sin6.sin6_port)
  8714. :
  8715. #endif
  8716. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8717. .lsa.sin.sin_port),
  8718. conn->request_info.local_uri,
  8719. (conn->request_info.query_string == NULL) ? "" : "?",
  8720. (conn->request_info.query_string == NULL)
  8721. ? ""
  8722. : conn->request_info.query_string);
  8723. }
  8724. }
  8725. static void
  8726. mg_set_handler_type(struct mg_context *ctx,
  8727. const char *uri,
  8728. int handler_type,
  8729. int is_delete_request,
  8730. mg_request_handler handler,
  8731. struct mg_websocket_subprotocols *subprotocols,
  8732. mg_websocket_connect_handler connect_handler,
  8733. mg_websocket_ready_handler ready_handler,
  8734. mg_websocket_data_handler data_handler,
  8735. mg_websocket_close_handler close_handler,
  8736. mg_authorization_handler auth_handler,
  8737. void *cbdata)
  8738. {
  8739. struct mg_handler_info *tmp_rh, **lastref;
  8740. size_t urilen = strlen(uri);
  8741. if (handler_type == WEBSOCKET_HANDLER) {
  8742. /* assert(handler == NULL); */
  8743. /* assert(is_delete_request || connect_handler!=NULL ||
  8744. * ready_handler!=NULL || data_handler!=NULL ||
  8745. * close_handler!=NULL);
  8746. */
  8747. /* assert(auth_handler == NULL); */
  8748. if (handler != NULL) {
  8749. return;
  8750. }
  8751. if (!is_delete_request && connect_handler == NULL
  8752. && ready_handler == NULL
  8753. && data_handler == NULL
  8754. && close_handler == NULL) {
  8755. return;
  8756. }
  8757. if (auth_handler != NULL) {
  8758. return;
  8759. }
  8760. } else if (handler_type == REQUEST_HANDLER) {
  8761. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8762. * data_handler==NULL && close_handler==NULL); */
  8763. /* assert(is_delete_request || (handler!=NULL));
  8764. */
  8765. /* assert(auth_handler == NULL); */
  8766. if (connect_handler != NULL || ready_handler != NULL
  8767. || data_handler != NULL
  8768. || close_handler != NULL) {
  8769. return;
  8770. }
  8771. if (!is_delete_request && (handler == NULL)) {
  8772. return;
  8773. }
  8774. if (auth_handler != NULL) {
  8775. return;
  8776. }
  8777. } else { /* AUTH_HANDLER */
  8778. /* assert(handler == NULL); */
  8779. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8780. * data_handler==NULL && close_handler==NULL); */
  8781. /* assert(auth_handler != NULL); */
  8782. if (handler != NULL) {
  8783. return;
  8784. }
  8785. if (connect_handler != NULL || ready_handler != NULL
  8786. || data_handler != NULL
  8787. || close_handler != NULL) {
  8788. return;
  8789. }
  8790. if (!is_delete_request && (auth_handler == NULL)) {
  8791. return;
  8792. }
  8793. }
  8794. if (!ctx) {
  8795. return;
  8796. }
  8797. mg_lock_context(ctx);
  8798. /* first try to find an existing handler */
  8799. lastref = &(ctx->handlers);
  8800. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8801. if (tmp_rh->handler_type == handler_type) {
  8802. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8803. if (!is_delete_request) {
  8804. /* update existing handler */
  8805. if (handler_type == REQUEST_HANDLER) {
  8806. tmp_rh->handler = handler;
  8807. } else if (handler_type == WEBSOCKET_HANDLER) {
  8808. tmp_rh->subprotocols = subprotocols;
  8809. tmp_rh->connect_handler = connect_handler;
  8810. tmp_rh->ready_handler = ready_handler;
  8811. tmp_rh->data_handler = data_handler;
  8812. tmp_rh->close_handler = close_handler;
  8813. } else { /* AUTH_HANDLER */
  8814. tmp_rh->auth_handler = auth_handler;
  8815. }
  8816. tmp_rh->cbdata = cbdata;
  8817. } else {
  8818. /* remove existing handler */
  8819. *lastref = tmp_rh->next;
  8820. mg_free(tmp_rh->uri);
  8821. mg_free(tmp_rh);
  8822. }
  8823. mg_unlock_context(ctx);
  8824. return;
  8825. }
  8826. }
  8827. lastref = &(tmp_rh->next);
  8828. }
  8829. if (is_delete_request) {
  8830. /* no handler to set, this was a remove request to a non-existing
  8831. * handler */
  8832. mg_unlock_context(ctx);
  8833. return;
  8834. }
  8835. tmp_rh =
  8836. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8837. if (tmp_rh == NULL) {
  8838. mg_unlock_context(ctx);
  8839. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8840. return;
  8841. }
  8842. tmp_rh->uri = mg_strdup(uri);
  8843. if (!tmp_rh->uri) {
  8844. mg_unlock_context(ctx);
  8845. mg_free(tmp_rh);
  8846. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8847. return;
  8848. }
  8849. tmp_rh->uri_len = urilen;
  8850. if (handler_type == REQUEST_HANDLER) {
  8851. tmp_rh->handler = handler;
  8852. } else if (handler_type == WEBSOCKET_HANDLER) {
  8853. tmp_rh->subprotocols = subprotocols;
  8854. tmp_rh->connect_handler = connect_handler;
  8855. tmp_rh->ready_handler = ready_handler;
  8856. tmp_rh->data_handler = data_handler;
  8857. tmp_rh->close_handler = close_handler;
  8858. } else { /* AUTH_HANDLER */
  8859. tmp_rh->auth_handler = auth_handler;
  8860. }
  8861. tmp_rh->cbdata = cbdata;
  8862. tmp_rh->handler_type = handler_type;
  8863. tmp_rh->next = NULL;
  8864. *lastref = tmp_rh;
  8865. mg_unlock_context(ctx);
  8866. }
  8867. void
  8868. mg_set_request_handler(struct mg_context *ctx,
  8869. const char *uri,
  8870. mg_request_handler handler,
  8871. void *cbdata)
  8872. {
  8873. mg_set_handler_type(ctx,
  8874. uri,
  8875. REQUEST_HANDLER,
  8876. handler == NULL,
  8877. handler,
  8878. NULL,
  8879. NULL,
  8880. NULL,
  8881. NULL,
  8882. NULL,
  8883. NULL,
  8884. cbdata);
  8885. }
  8886. void
  8887. mg_set_websocket_handler(struct mg_context *ctx,
  8888. const char *uri,
  8889. mg_websocket_connect_handler connect_handler,
  8890. mg_websocket_ready_handler ready_handler,
  8891. mg_websocket_data_handler data_handler,
  8892. mg_websocket_close_handler close_handler,
  8893. void *cbdata)
  8894. {
  8895. mg_set_websocket_handler_with_subprotocols(ctx,
  8896. uri,
  8897. NULL,
  8898. connect_handler,
  8899. ready_handler,
  8900. data_handler,
  8901. close_handler,
  8902. cbdata);
  8903. }
  8904. void
  8905. mg_set_websocket_handler_with_subprotocols(
  8906. struct mg_context *ctx,
  8907. const char *uri,
  8908. struct mg_websocket_subprotocols *subprotocols,
  8909. mg_websocket_connect_handler connect_handler,
  8910. mg_websocket_ready_handler ready_handler,
  8911. mg_websocket_data_handler data_handler,
  8912. mg_websocket_close_handler close_handler,
  8913. void *cbdata)
  8914. {
  8915. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8916. && (data_handler == NULL)
  8917. && (close_handler == NULL);
  8918. mg_set_handler_type(ctx,
  8919. uri,
  8920. WEBSOCKET_HANDLER,
  8921. is_delete_request,
  8922. NULL,
  8923. subprotocols,
  8924. connect_handler,
  8925. ready_handler,
  8926. data_handler,
  8927. close_handler,
  8928. NULL,
  8929. cbdata);
  8930. }
  8931. void
  8932. mg_set_auth_handler(struct mg_context *ctx,
  8933. const char *uri,
  8934. mg_request_handler handler,
  8935. void *cbdata)
  8936. {
  8937. mg_set_handler_type(ctx,
  8938. uri,
  8939. AUTH_HANDLER,
  8940. handler == NULL,
  8941. NULL,
  8942. NULL,
  8943. NULL,
  8944. NULL,
  8945. NULL,
  8946. NULL,
  8947. handler,
  8948. cbdata);
  8949. }
  8950. static int
  8951. get_request_handler(struct mg_connection *conn,
  8952. int handler_type,
  8953. mg_request_handler *handler,
  8954. struct mg_websocket_subprotocols **subprotocols,
  8955. mg_websocket_connect_handler *connect_handler,
  8956. mg_websocket_ready_handler *ready_handler,
  8957. mg_websocket_data_handler *data_handler,
  8958. mg_websocket_close_handler *close_handler,
  8959. mg_authorization_handler *auth_handler,
  8960. void **cbdata)
  8961. {
  8962. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8963. if (request_info) {
  8964. const char *uri = request_info->local_uri;
  8965. size_t urilen = strlen(uri);
  8966. struct mg_handler_info *tmp_rh;
  8967. if (!conn || !conn->ctx) {
  8968. return 0;
  8969. }
  8970. mg_lock_context(conn->ctx);
  8971. /* first try for an exact match */
  8972. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8973. tmp_rh = tmp_rh->next) {
  8974. if (tmp_rh->handler_type == handler_type) {
  8975. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8976. if (handler_type == WEBSOCKET_HANDLER) {
  8977. *subprotocols = tmp_rh->subprotocols;
  8978. *connect_handler = tmp_rh->connect_handler;
  8979. *ready_handler = tmp_rh->ready_handler;
  8980. *data_handler = tmp_rh->data_handler;
  8981. *close_handler = tmp_rh->close_handler;
  8982. } else if (handler_type == REQUEST_HANDLER) {
  8983. *handler = tmp_rh->handler;
  8984. } else { /* AUTH_HANDLER */
  8985. *auth_handler = tmp_rh->auth_handler;
  8986. }
  8987. *cbdata = tmp_rh->cbdata;
  8988. mg_unlock_context(conn->ctx);
  8989. return 1;
  8990. }
  8991. }
  8992. }
  8993. /* next try for a partial match, we will accept uri/something */
  8994. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8995. tmp_rh = tmp_rh->next) {
  8996. if (tmp_rh->handler_type == handler_type) {
  8997. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  8998. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  8999. if (handler_type == WEBSOCKET_HANDLER) {
  9000. *subprotocols = tmp_rh->subprotocols;
  9001. *connect_handler = tmp_rh->connect_handler;
  9002. *ready_handler = tmp_rh->ready_handler;
  9003. *data_handler = tmp_rh->data_handler;
  9004. *close_handler = tmp_rh->close_handler;
  9005. } else if (handler_type == REQUEST_HANDLER) {
  9006. *handler = tmp_rh->handler;
  9007. } else { /* AUTH_HANDLER */
  9008. *auth_handler = tmp_rh->auth_handler;
  9009. }
  9010. *cbdata = tmp_rh->cbdata;
  9011. mg_unlock_context(conn->ctx);
  9012. return 1;
  9013. }
  9014. }
  9015. }
  9016. /* finally try for pattern match */
  9017. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9018. tmp_rh = tmp_rh->next) {
  9019. if (tmp_rh->handler_type == handler_type) {
  9020. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9021. if (handler_type == WEBSOCKET_HANDLER) {
  9022. *subprotocols = tmp_rh->subprotocols;
  9023. *connect_handler = tmp_rh->connect_handler;
  9024. *ready_handler = tmp_rh->ready_handler;
  9025. *data_handler = tmp_rh->data_handler;
  9026. *close_handler = tmp_rh->close_handler;
  9027. } else if (handler_type == REQUEST_HANDLER) {
  9028. *handler = tmp_rh->handler;
  9029. } else { /* AUTH_HANDLER */
  9030. *auth_handler = tmp_rh->auth_handler;
  9031. }
  9032. *cbdata = tmp_rh->cbdata;
  9033. mg_unlock_context(conn->ctx);
  9034. return 1;
  9035. }
  9036. }
  9037. }
  9038. mg_unlock_context(conn->ctx);
  9039. }
  9040. return 0; /* none found */
  9041. }
  9042. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9043. static int
  9044. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9045. void *cbdata)
  9046. {
  9047. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9048. if (pcallbacks->websocket_connect) {
  9049. return pcallbacks->websocket_connect(conn);
  9050. }
  9051. /* No handler set - assume "OK" */
  9052. return 0;
  9053. }
  9054. static void
  9055. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9056. {
  9057. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9058. if (pcallbacks->websocket_ready) {
  9059. pcallbacks->websocket_ready(conn);
  9060. }
  9061. }
  9062. static int
  9063. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9064. int bits,
  9065. char *data,
  9066. size_t len,
  9067. void *cbdata)
  9068. {
  9069. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9070. if (pcallbacks->websocket_data) {
  9071. return pcallbacks->websocket_data(conn, bits, data, len);
  9072. }
  9073. /* No handler set - assume "OK" */
  9074. return 1;
  9075. }
  9076. #endif
  9077. /* This is the heart of the Civetweb's logic.
  9078. * This function is called when the request is read, parsed and validated,
  9079. * and Civetweb must decide what action to take: serve a file, or
  9080. * a directory, or call embedded function, etcetera. */
  9081. static void
  9082. handle_request(struct mg_connection *conn)
  9083. {
  9084. if (conn) {
  9085. struct mg_request_info *ri = &conn->request_info;
  9086. char path[PATH_MAX];
  9087. int uri_len, ssl_index;
  9088. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9089. is_put_or_delete_request = 0, is_callback_resource = 0;
  9090. int i;
  9091. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9092. mg_request_handler callback_handler = NULL;
  9093. struct mg_websocket_subprotocols *subprotocols;
  9094. mg_websocket_connect_handler ws_connect_handler = NULL;
  9095. mg_websocket_ready_handler ws_ready_handler = NULL;
  9096. mg_websocket_data_handler ws_data_handler = NULL;
  9097. mg_websocket_close_handler ws_close_handler = NULL;
  9098. void *callback_data = NULL;
  9099. mg_authorization_handler auth_handler = NULL;
  9100. void *auth_callback_data = NULL;
  9101. #if !defined(NO_FILES)
  9102. time_t curtime = time(NULL);
  9103. char date[64];
  9104. #endif
  9105. path[0] = 0;
  9106. if (!ri) {
  9107. return;
  9108. }
  9109. /* 1. get the request url */
  9110. /* 1.1. split into url and query string */
  9111. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9112. != NULL) {
  9113. *((char *)conn->request_info.query_string++) = '\0';
  9114. }
  9115. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9116. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9117. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9118. if (ssl_index >= 0) {
  9119. redirect_to_https_port(conn, ssl_index);
  9120. } else {
  9121. /* A http to https forward port has been specified,
  9122. * but no https port to forward to. */
  9123. send_http_error(conn,
  9124. 503,
  9125. "%s",
  9126. "Error: SSL forward not configured properly");
  9127. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9128. }
  9129. return;
  9130. }
  9131. uri_len = (int)strlen(ri->local_uri);
  9132. /* 1.3. decode url (if config says so) */
  9133. if (should_decode_url(conn)) {
  9134. mg_url_decode(
  9135. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9136. }
  9137. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9138. * not possible */
  9139. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9140. /* step 1. completed, the url is known now */
  9141. uri_len = (int)strlen(ri->local_uri);
  9142. DEBUG_TRACE("URL: %s", ri->local_uri);
  9143. /* 3. if this ip has limited speed, set it for this connection */
  9144. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9145. get_remote_ip(conn),
  9146. ri->local_uri);
  9147. /* 4. call a "handle everything" callback, if registered */
  9148. if (conn->ctx->callbacks.begin_request != NULL) {
  9149. /* Note that since V1.7 the "begin_request" function is called
  9150. * before an authorization check. If an authorization check is
  9151. * required, use a request_handler instead. */
  9152. i = conn->ctx->callbacks.begin_request(conn);
  9153. if (i > 0) {
  9154. /* callback already processed the request. Store the
  9155. return value as a status code for the access log. */
  9156. conn->status_code = i;
  9157. discard_unread_request_data(conn);
  9158. return;
  9159. } else if (i == 0) {
  9160. /* civetweb should process the request */
  9161. } else {
  9162. /* unspecified - may change with the next version */
  9163. return;
  9164. }
  9165. }
  9166. /* request not yet handled by a handler or redirect, so the request
  9167. * is processed here */
  9168. /* 5. interpret the url to find out how the request must be handled
  9169. */
  9170. /* 5.1. first test, if the request targets the regular http(s)://
  9171. * protocol namespace or the websocket ws(s):// protocol namespace.
  9172. */
  9173. is_websocket_request = is_websocket_protocol(conn);
  9174. /* 5.2. check if the request will be handled by a callback */
  9175. if (get_request_handler(conn,
  9176. is_websocket_request ? WEBSOCKET_HANDLER
  9177. : REQUEST_HANDLER,
  9178. &callback_handler,
  9179. &subprotocols,
  9180. &ws_connect_handler,
  9181. &ws_ready_handler,
  9182. &ws_data_handler,
  9183. &ws_close_handler,
  9184. NULL,
  9185. &callback_data)) {
  9186. /* 5.2.1. A callback will handle this request. All requests
  9187. * handled
  9188. * by a callback have to be considered as requests to a script
  9189. * resource. */
  9190. is_callback_resource = 1;
  9191. is_script_resource = 1;
  9192. is_put_or_delete_request = is_put_or_delete_method(conn);
  9193. } else {
  9194. no_callback_resource:
  9195. /* 5.2.2. No callback is responsible for this request. The URI
  9196. * addresses a file based resource (static content or Lua/cgi
  9197. * scripts in the file system). */
  9198. is_callback_resource = 0;
  9199. interpret_uri(conn,
  9200. path,
  9201. sizeof(path),
  9202. &file.stat,
  9203. &is_found,
  9204. &is_script_resource,
  9205. &is_websocket_request,
  9206. &is_put_or_delete_request);
  9207. }
  9208. /* 6. authorization check */
  9209. /* 6.1. a custom authorization handler is installed */
  9210. if (get_request_handler(conn,
  9211. AUTH_HANDLER,
  9212. NULL,
  9213. NULL,
  9214. NULL,
  9215. NULL,
  9216. NULL,
  9217. NULL,
  9218. &auth_handler,
  9219. &auth_callback_data)) {
  9220. if (!auth_handler(conn, auth_callback_data)) {
  9221. return;
  9222. }
  9223. } else if (is_put_or_delete_request && !is_script_resource
  9224. && !is_callback_resource) {
  9225. /* 6.2. this request is a PUT/DELETE to a real file */
  9226. /* 6.2.1. thus, the server must have real files */
  9227. #if defined(NO_FILES)
  9228. if (1) {
  9229. #else
  9230. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9231. #endif
  9232. /* This server does not have any real files, thus the
  9233. * PUT/DELETE methods are not valid. */
  9234. send_http_error(conn,
  9235. 405,
  9236. "%s method not allowed",
  9237. conn->request_info.request_method);
  9238. return;
  9239. }
  9240. #if !defined(NO_FILES)
  9241. /* 6.2.2. Check if put authorization for static files is
  9242. * available.
  9243. */
  9244. if (!is_authorized_for_put(conn)) {
  9245. send_authorization_request(conn);
  9246. return;
  9247. }
  9248. #endif
  9249. } else {
  9250. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9251. * or it is a PUT or DELETE request to a resource that does not
  9252. * correspond to a file. Check authorization. */
  9253. if (!check_authorization(conn, path)) {
  9254. send_authorization_request(conn);
  9255. return;
  9256. }
  9257. }
  9258. /* request is authorized or does not need authorization */
  9259. /* 7. check if there are request handlers for this uri */
  9260. if (is_callback_resource) {
  9261. if (!is_websocket_request) {
  9262. i = callback_handler(conn, callback_data);
  9263. if (i > 0) {
  9264. /* Do nothing, callback has served the request. Store
  9265. * the
  9266. * return value as status code for the log and discard
  9267. * all
  9268. * data from the client not used by the callback. */
  9269. conn->status_code = i;
  9270. discard_unread_request_data(conn);
  9271. } else {
  9272. /* TODO (high): what if the handler did NOT handle the
  9273. * request */
  9274. /* The last version did handle this as a file request,
  9275. * but
  9276. * since a file request is not always a script resource,
  9277. * the authorization check might be different */
  9278. interpret_uri(conn,
  9279. path,
  9280. sizeof(path),
  9281. &file.stat,
  9282. &is_found,
  9283. &is_script_resource,
  9284. &is_websocket_request,
  9285. &is_put_or_delete_request);
  9286. callback_handler = NULL;
  9287. /* TODO (very low): goto is deprecated but for the
  9288. * moment,
  9289. * a goto is simpler than some curious loop. */
  9290. /* The situation "callback does not handle the request"
  9291. * needs to be reconsidered anyway. */
  9292. goto no_callback_resource;
  9293. }
  9294. } else {
  9295. #if defined(USE_WEBSOCKET)
  9296. handle_websocket_request(conn,
  9297. path,
  9298. is_callback_resource,
  9299. subprotocols,
  9300. ws_connect_handler,
  9301. ws_ready_handler,
  9302. ws_data_handler,
  9303. ws_close_handler,
  9304. callback_data);
  9305. #endif
  9306. }
  9307. return;
  9308. }
  9309. /* 8. handle websocket requests */
  9310. #if defined(USE_WEBSOCKET)
  9311. if (is_websocket_request) {
  9312. if (is_script_resource) {
  9313. /* Websocket Lua script */
  9314. handle_websocket_request(conn,
  9315. path,
  9316. 0 /* Lua Script */,
  9317. NULL,
  9318. NULL,
  9319. NULL,
  9320. NULL,
  9321. NULL,
  9322. &conn->ctx->callbacks);
  9323. } else {
  9324. #if defined(MG_LEGACY_INTERFACE)
  9325. handle_websocket_request(
  9326. conn,
  9327. path,
  9328. !is_script_resource /* could be deprecated global callback */,
  9329. NULL,
  9330. deprecated_websocket_connect_wrapper,
  9331. deprecated_websocket_ready_wrapper,
  9332. deprecated_websocket_data_wrapper,
  9333. NULL,
  9334. &conn->ctx->callbacks);
  9335. #else
  9336. send_http_error(conn, 404, "%s", "Not found");
  9337. #endif
  9338. }
  9339. return;
  9340. } else
  9341. #endif
  9342. #if defined(NO_FILES)
  9343. /* 9a. In case the server uses only callbacks, this uri is
  9344. * unknown.
  9345. * Then, all request handling ends here. */
  9346. send_http_error(conn, 404, "%s", "Not Found");
  9347. #else
  9348. /* 9b. This request is either for a static file or resource handled
  9349. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9350. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9351. send_http_error(conn, 404, "%s", "Not Found");
  9352. return;
  9353. }
  9354. /* 10. File is handled by a script. */
  9355. if (is_script_resource) {
  9356. handle_file_based_request(conn, path, &file);
  9357. return;
  9358. }
  9359. /* 11. Handle put/delete/mkcol requests */
  9360. if (is_put_or_delete_request) {
  9361. /* 11.1. PUT method */
  9362. if (!strcmp(ri->request_method, "PUT")) {
  9363. put_file(conn, path);
  9364. return;
  9365. }
  9366. /* 11.2. DELETE method */
  9367. if (!strcmp(ri->request_method, "DELETE")) {
  9368. delete_file(conn, path);
  9369. return;
  9370. }
  9371. /* 11.3. MKCOL method */
  9372. if (!strcmp(ri->request_method, "MKCOL")) {
  9373. mkcol(conn, path);
  9374. return;
  9375. }
  9376. /* 11.4. PATCH method
  9377. * This method is not supported for static resources,
  9378. * only for scripts (Lua, CGI) and callbacks. */
  9379. send_http_error(conn,
  9380. 405,
  9381. "%s method not allowed",
  9382. conn->request_info.request_method);
  9383. return;
  9384. }
  9385. /* 11. File does not exist, or it was configured that it should be
  9386. * hidden */
  9387. if (!is_found || (must_hide_file(conn, path))) {
  9388. send_http_error(conn, 404, "%s", "Not found");
  9389. return;
  9390. }
  9391. /* 12. Directory uris should end with a slash */
  9392. if (file.stat.is_directory && (uri_len > 0)
  9393. && (ri->local_uri[uri_len - 1] != '/')) {
  9394. gmt_time_string(date, sizeof(date), &curtime);
  9395. mg_printf(conn,
  9396. "HTTP/1.1 301 Moved Permanently\r\n"
  9397. "Location: %s/\r\n"
  9398. "Date: %s\r\n"
  9399. /* "Cache-Control: private\r\n" (= default) */
  9400. "Content-Length: 0\r\n"
  9401. "Connection: %s\r\n\r\n",
  9402. ri->request_uri,
  9403. date,
  9404. suggest_connection_header(conn));
  9405. return;
  9406. }
  9407. /* 13. Handle other methods than GET/HEAD */
  9408. /* 13.1. Handle PROPFIND */
  9409. if (!strcmp(ri->request_method, "PROPFIND")) {
  9410. handle_propfind(conn, path, &file.stat);
  9411. return;
  9412. }
  9413. /* 13.2. Handle OPTIONS for files */
  9414. if (!strcmp(ri->request_method, "OPTIONS")) {
  9415. /* This standard handler is only used for real files.
  9416. * Scripts should support the OPTIONS method themselves, to allow a
  9417. * maximum flexibility.
  9418. * Lua and CGI scripts may fully support CORS this way (including
  9419. * preflights). */
  9420. send_options(conn);
  9421. return;
  9422. }
  9423. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9424. if (0 != strcmp(ri->request_method, "GET")
  9425. && 0 != strcmp(ri->request_method, "HEAD")) {
  9426. send_http_error(conn,
  9427. 405,
  9428. "%s method not allowed",
  9429. conn->request_info.request_method);
  9430. return;
  9431. }
  9432. /* 14. directories */
  9433. if (file.stat.is_directory) {
  9434. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9435. /* 14.1. use a substitute file */
  9436. /* TODO (high): substitute index may be a script resource.
  9437. * define what should be possible in this case. */
  9438. } else {
  9439. /* 14.2. no substitute file */
  9440. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9441. "yes")) {
  9442. handle_directory_request(conn, path);
  9443. } else {
  9444. send_http_error(conn,
  9445. 403,
  9446. "%s",
  9447. "Error: Directory listing denied");
  9448. }
  9449. return;
  9450. }
  9451. }
  9452. handle_file_based_request(conn, path, &file);
  9453. #endif /* !defined(NO_FILES) */
  9454. #if 0
  9455. /* Perform redirect and auth checks before calling begin_request()
  9456. * handler.
  9457. * Otherwise, begin_request() would need to perform auth checks and
  9458. * redirects. */
  9459. #endif
  9460. }
  9461. return;
  9462. }
  9463. static void
  9464. handle_file_based_request(struct mg_connection *conn,
  9465. const char *path,
  9466. struct mg_file *file)
  9467. {
  9468. if (!conn || !conn->ctx) {
  9469. return;
  9470. }
  9471. if (0) {
  9472. #ifdef USE_LUA
  9473. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9474. strlen(
  9475. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9476. path) > 0) {
  9477. /* Lua server page: an SSI like page containing mostly plain html
  9478. * code
  9479. * plus some tags with server generated contents. */
  9480. handle_lsp_request(conn, path, file, NULL);
  9481. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9482. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9483. path) > 0) {
  9484. /* Lua in-server module script: a CGI like script used to generate
  9485. * the
  9486. * entire reply. */
  9487. mg_exec_lua_script(conn, path, NULL);
  9488. #endif
  9489. #if defined(USE_DUKTAPE)
  9490. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9491. strlen(
  9492. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9493. path) > 0) {
  9494. /* Call duktape to generate the page */
  9495. mg_exec_duktape_script(conn, path);
  9496. #endif
  9497. #if !defined(NO_CGI)
  9498. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9499. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9500. path) > 0) {
  9501. /* CGI scripts may support all HTTP methods */
  9502. handle_cgi_request(conn, path);
  9503. #endif /* !NO_CGI */
  9504. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9505. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9506. path) > 0) {
  9507. handle_ssi_file_request(conn, path, file);
  9508. #if !defined(NO_CACHING)
  9509. } else if ((!conn->in_error_handler)
  9510. && is_not_modified(conn, &file->stat)) {
  9511. /* Send 304 "Not Modified" - this must not send any body data */
  9512. handle_not_modified_static_file_request(conn, file);
  9513. #endif /* !NO_CACHING */
  9514. } else {
  9515. handle_static_file_request(conn, path, file, NULL, NULL);
  9516. }
  9517. }
  9518. static void
  9519. close_all_listening_sockets(struct mg_context *ctx)
  9520. {
  9521. unsigned int i;
  9522. if (!ctx) {
  9523. return;
  9524. }
  9525. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9526. closesocket(ctx->listening_sockets[i].sock);
  9527. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9528. }
  9529. mg_free(ctx->listening_sockets);
  9530. ctx->listening_sockets = NULL;
  9531. mg_free(ctx->listening_socket_fds);
  9532. ctx->listening_socket_fds = NULL;
  9533. }
  9534. /* Valid listening port specification is: [ip_address:]port[s]
  9535. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9536. * Examples for IPv6: [::]:80, [::1]:80,
  9537. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9538. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9539. * In order to bind to both, IPv4 and IPv6, you can either add
  9540. * both ports using 8080,[::]:8080, or the short form +8080.
  9541. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9542. * one only accepting IPv4 the other only IPv6. +8080 creates
  9543. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9544. * environment, they might work differently, or might not work
  9545. * at all - it must be tested what options work best in the
  9546. * relevant network environment.
  9547. */
  9548. static int
  9549. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9550. {
  9551. unsigned int a, b, c, d, port;
  9552. int ch, len;
  9553. #if defined(USE_IPV6)
  9554. char buf[100] = {0};
  9555. #endif
  9556. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9557. * Also, all-zeroes in the socket address means binding to all addresses
  9558. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9559. memset(so, 0, sizeof(*so));
  9560. so->lsa.sin.sin_family = AF_INET;
  9561. *ip_version = 0;
  9562. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9563. == 5) {
  9564. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9565. so->lsa.sin.sin_addr.s_addr =
  9566. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9567. so->lsa.sin.sin_port = htons((uint16_t)port);
  9568. *ip_version = 4;
  9569. #if defined(USE_IPV6)
  9570. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9571. && mg_inet_pton(
  9572. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9573. /* IPv6 address, examples: see above */
  9574. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9575. */
  9576. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9577. *ip_version = 6;
  9578. #endif
  9579. } else if ((vec->ptr[0] == '+')
  9580. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9581. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9582. /* Add 1 to len for the + character we skipped before */
  9583. len++;
  9584. #if defined(USE_IPV6)
  9585. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9586. so->lsa.sin6.sin6_family = AF_INET6;
  9587. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9588. *ip_version = 4 + 6;
  9589. #else
  9590. /* Bind to IPv4 only, since IPv6 is not built in. */
  9591. so->lsa.sin.sin_port = htons((uint16_t)port);
  9592. *ip_version = 4;
  9593. #endif
  9594. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9595. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9596. so->lsa.sin.sin_port = htons((uint16_t)port);
  9597. *ip_version = 4;
  9598. } else {
  9599. /* Parsing failure. Make port invalid. */
  9600. port = 0;
  9601. len = 0;
  9602. }
  9603. /* sscanf and the option splitting code ensure the following condition
  9604. */
  9605. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9606. *ip_version = 0;
  9607. return 0;
  9608. }
  9609. ch = vec->ptr[len]; /* Next character after the port number */
  9610. so->is_ssl = (ch == 's');
  9611. so->ssl_redir = (ch == 'r');
  9612. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9613. if (is_valid_port(port)
  9614. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9615. return 1;
  9616. }
  9617. /* Reset ip_version to 0 of there is an error */
  9618. *ip_version = 0;
  9619. return 0;
  9620. }
  9621. static int
  9622. set_ports_option(struct mg_context *ctx)
  9623. {
  9624. const char *list;
  9625. int on = 1;
  9626. #if defined(USE_IPV6)
  9627. int off = 0;
  9628. #endif
  9629. struct vec vec;
  9630. struct socket so, *ptr;
  9631. struct pollfd *pfd;
  9632. union usa usa;
  9633. socklen_t len;
  9634. int ip_version;
  9635. int portsTotal = 0;
  9636. int portsOk = 0;
  9637. if (!ctx) {
  9638. return 0;
  9639. }
  9640. memset(&so, 0, sizeof(so));
  9641. memset(&usa, 0, sizeof(usa));
  9642. len = sizeof(usa);
  9643. list = ctx->config[LISTENING_PORTS];
  9644. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9645. portsTotal++;
  9646. if (!parse_port_string(&vec, &so, &ip_version)) {
  9647. mg_cry(fc(ctx),
  9648. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9649. (int)vec.len,
  9650. vec.ptr,
  9651. portsTotal,
  9652. "[IP_ADDRESS:]PORT[s|r]");
  9653. continue;
  9654. }
  9655. #if !defined(NO_SSL)
  9656. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9657. mg_cry(fc(ctx),
  9658. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9659. "option set?",
  9660. portsTotal);
  9661. continue;
  9662. }
  9663. #endif
  9664. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9665. == INVALID_SOCKET) {
  9666. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9667. continue;
  9668. }
  9669. #ifdef _WIN32
  9670. /* Windows SO_REUSEADDR lets many procs binds to a
  9671. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9672. * if someone already has the socket -- DTL */
  9673. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9674. * Windows might need a few seconds before
  9675. * the same port can be used again in the
  9676. * same process, so a short Sleep may be
  9677. * required between mg_stop and mg_start.
  9678. */
  9679. if (setsockopt(so.sock,
  9680. SOL_SOCKET,
  9681. SO_EXCLUSIVEADDRUSE,
  9682. (SOCK_OPT_TYPE)&on,
  9683. sizeof(on)) != 0) {
  9684. /* Set reuse option, but don't abort on errors. */
  9685. mg_cry(fc(ctx),
  9686. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9687. portsTotal);
  9688. }
  9689. #else
  9690. if (setsockopt(so.sock,
  9691. SOL_SOCKET,
  9692. SO_REUSEADDR,
  9693. (SOCK_OPT_TYPE)&on,
  9694. sizeof(on)) != 0) {
  9695. /* Set reuse option, but don't abort on errors. */
  9696. mg_cry(fc(ctx),
  9697. "cannot set socket option SO_REUSEADDR (entry %i)",
  9698. portsTotal);
  9699. }
  9700. #endif
  9701. if (ip_version > 4) {
  9702. #if defined(USE_IPV6)
  9703. if (ip_version == 6) {
  9704. if (so.lsa.sa.sa_family == AF_INET6
  9705. && setsockopt(so.sock,
  9706. IPPROTO_IPV6,
  9707. IPV6_V6ONLY,
  9708. (void *)&off,
  9709. sizeof(off)) != 0) {
  9710. /* Set IPv6 only option, but don't abort on errors. */
  9711. mg_cry(fc(ctx),
  9712. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9713. portsTotal);
  9714. }
  9715. }
  9716. #else
  9717. mg_cry(fc(ctx), "IPv6 not available");
  9718. closesocket(so.sock);
  9719. so.sock = INVALID_SOCKET;
  9720. continue;
  9721. #endif
  9722. }
  9723. if (so.lsa.sa.sa_family == AF_INET) {
  9724. len = sizeof(so.lsa.sin);
  9725. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9726. mg_cry(fc(ctx),
  9727. "cannot bind to %.*s: %d (%s)",
  9728. (int)vec.len,
  9729. vec.ptr,
  9730. (int)ERRNO,
  9731. strerror(errno));
  9732. closesocket(so.sock);
  9733. so.sock = INVALID_SOCKET;
  9734. continue;
  9735. }
  9736. }
  9737. #if defined(USE_IPV6)
  9738. else if (so.lsa.sa.sa_family == AF_INET6) {
  9739. len = sizeof(so.lsa.sin6);
  9740. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9741. mg_cry(fc(ctx),
  9742. "cannot bind to IPv6 %.*s: %d (%s)",
  9743. (int)vec.len,
  9744. vec.ptr,
  9745. (int)ERRNO,
  9746. strerror(errno));
  9747. closesocket(so.sock);
  9748. so.sock = INVALID_SOCKET;
  9749. continue;
  9750. }
  9751. }
  9752. #endif
  9753. else {
  9754. mg_cry(fc(ctx),
  9755. "cannot bind: address family not supported (entry %i)",
  9756. portsTotal);
  9757. continue;
  9758. }
  9759. if (listen(so.sock, SOMAXCONN) != 0) {
  9760. mg_cry(fc(ctx),
  9761. "cannot listen to %.*s: %d (%s)",
  9762. (int)vec.len,
  9763. vec.ptr,
  9764. (int)ERRNO,
  9765. strerror(errno));
  9766. closesocket(so.sock);
  9767. so.sock = INVALID_SOCKET;
  9768. continue;
  9769. }
  9770. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9771. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9772. int err = (int)ERRNO;
  9773. mg_cry(fc(ctx),
  9774. "call to getsockname failed %.*s: %d (%s)",
  9775. (int)vec.len,
  9776. vec.ptr,
  9777. err,
  9778. strerror(errno));
  9779. closesocket(so.sock);
  9780. so.sock = INVALID_SOCKET;
  9781. continue;
  9782. }
  9783. /* Update lsa port in case of random free ports */
  9784. #if defined(USE_IPV6)
  9785. if (so.lsa.sa.sa_family == AF_INET6) {
  9786. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9787. } else
  9788. #endif
  9789. {
  9790. so.lsa.sin.sin_port = usa.sin.sin_port;
  9791. }
  9792. if ((ptr = (struct socket *)
  9793. mg_realloc(ctx->listening_sockets,
  9794. (ctx->num_listening_sockets + 1)
  9795. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9796. mg_cry(fc(ctx), "%s", "Out of memory");
  9797. closesocket(so.sock);
  9798. so.sock = INVALID_SOCKET;
  9799. continue;
  9800. }
  9801. if ((pfd = (struct pollfd *)mg_realloc(
  9802. ctx->listening_socket_fds,
  9803. (ctx->num_listening_sockets + 1)
  9804. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9805. mg_cry(fc(ctx), "%s", "Out of memory");
  9806. closesocket(so.sock);
  9807. so.sock = INVALID_SOCKET;
  9808. mg_free(ptr);
  9809. continue;
  9810. }
  9811. set_close_on_exec(so.sock, fc(ctx));
  9812. ctx->listening_sockets = ptr;
  9813. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9814. ctx->listening_socket_fds = pfd;
  9815. ctx->num_listening_sockets++;
  9816. portsOk++;
  9817. }
  9818. if (portsOk != portsTotal) {
  9819. close_all_listening_sockets(ctx);
  9820. portsOk = 0;
  9821. }
  9822. return portsOk;
  9823. }
  9824. static const char *
  9825. header_val(const struct mg_connection *conn, const char *header)
  9826. {
  9827. const char *header_value;
  9828. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9829. return "-";
  9830. } else {
  9831. return header_value;
  9832. }
  9833. }
  9834. static void
  9835. log_access(const struct mg_connection *conn)
  9836. {
  9837. const struct mg_request_info *ri;
  9838. struct mg_file fi;
  9839. char date[64], src_addr[IP_ADDR_STR_LEN];
  9840. struct tm *tm;
  9841. const char *referer;
  9842. const char *user_agent;
  9843. char buf[4096];
  9844. if (!conn || !conn->ctx) {
  9845. return;
  9846. }
  9847. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9848. if (mg_fopen(conn,
  9849. conn->ctx->config[ACCESS_LOG_FILE],
  9850. MG_FOPEN_MODE_APPEND,
  9851. &fi) == 0) {
  9852. fi.access.fp = NULL;
  9853. }
  9854. } else {
  9855. fi.access.fp = NULL;
  9856. }
  9857. /* Log is written to a file and/or a callback. If both are not set,
  9858. * executing the rest of the function is pointless. */
  9859. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9860. return;
  9861. }
  9862. tm = localtime(&conn->conn_birth_time);
  9863. if (tm != NULL) {
  9864. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9865. } else {
  9866. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9867. date[sizeof(date) - 1] = '\0';
  9868. }
  9869. ri = &conn->request_info;
  9870. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9871. referer = header_val(conn, "Referer");
  9872. user_agent = header_val(conn, "User-Agent");
  9873. mg_snprintf(conn,
  9874. NULL, /* Ignore truncation in access log */
  9875. buf,
  9876. sizeof(buf),
  9877. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9878. src_addr,
  9879. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9880. date,
  9881. ri->request_method ? ri->request_method : "-",
  9882. ri->request_uri ? ri->request_uri : "-",
  9883. ri->query_string ? "?" : "",
  9884. ri->query_string ? ri->query_string : "",
  9885. ri->http_version,
  9886. conn->status_code,
  9887. conn->num_bytes_sent,
  9888. referer,
  9889. user_agent);
  9890. if (conn->ctx->callbacks.log_access) {
  9891. conn->ctx->callbacks.log_access(conn, buf);
  9892. }
  9893. if (fi.access.fp) {
  9894. int ok = 1;
  9895. flockfile(fi.access.fp);
  9896. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  9897. ok = 0;
  9898. }
  9899. if (fflush(fi.access.fp) != 0) {
  9900. ok = 0;
  9901. }
  9902. funlockfile(fi.access.fp);
  9903. if (mg_fclose(&fi.access) != 0) {
  9904. ok = 0;
  9905. }
  9906. if (!ok) {
  9907. mg_cry(conn,
  9908. "Error writing log file %s",
  9909. conn->ctx->config[ACCESS_LOG_FILE]);
  9910. }
  9911. }
  9912. }
  9913. /* Verify given socket address against the ACL.
  9914. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9915. */
  9916. static int
  9917. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9918. {
  9919. int allowed, flag;
  9920. uint32_t net, mask;
  9921. struct vec vec;
  9922. if (ctx) {
  9923. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9924. /* If any ACL is set, deny by default */
  9925. allowed = (list == NULL) ? '+' : '-';
  9926. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9927. flag = vec.ptr[0];
  9928. if ((flag != '+' && flag != '-')
  9929. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9930. mg_cry(fc(ctx),
  9931. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9932. __func__);
  9933. return -1;
  9934. }
  9935. if (net == (remote_ip & mask)) {
  9936. allowed = flag;
  9937. }
  9938. }
  9939. return allowed == '+';
  9940. }
  9941. return -1;
  9942. }
  9943. #if !defined(_WIN32)
  9944. static int
  9945. set_uid_option(struct mg_context *ctx)
  9946. {
  9947. struct passwd *pw;
  9948. if (ctx) {
  9949. const char *uid = ctx->config[RUN_AS_USER];
  9950. int success = 0;
  9951. if (uid == NULL) {
  9952. success = 1;
  9953. } else {
  9954. if ((pw = getpwnam(uid)) == NULL) {
  9955. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9956. } else if (setgid(pw->pw_gid) == -1) {
  9957. mg_cry(fc(ctx),
  9958. "%s: setgid(%s): %s",
  9959. __func__,
  9960. uid,
  9961. strerror(errno));
  9962. } else if (setgroups(0, NULL)) {
  9963. mg_cry(fc(ctx),
  9964. "%s: setgroups(): %s",
  9965. __func__,
  9966. strerror(errno));
  9967. } else if (setuid(pw->pw_uid) == -1) {
  9968. mg_cry(fc(ctx),
  9969. "%s: setuid(%s): %s",
  9970. __func__,
  9971. uid,
  9972. strerror(errno));
  9973. } else {
  9974. success = 1;
  9975. }
  9976. }
  9977. return success;
  9978. }
  9979. return 0;
  9980. }
  9981. #endif /* !_WIN32 */
  9982. static void
  9983. tls_dtor(void *key)
  9984. {
  9985. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  9986. /* key == pthread_getspecific(sTlsKey); */
  9987. if (tls) {
  9988. if (tls->is_master == 2) {
  9989. tls->is_master = -3; /* Mark memory as dead */
  9990. mg_free(tls);
  9991. }
  9992. }
  9993. pthread_setspecific(sTlsKey, NULL);
  9994. }
  9995. #if !defined(NO_SSL)
  9996. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  9997. static const char *ssl_error(void);
  9998. static int
  9999. refresh_trust(struct mg_connection *conn)
  10000. {
  10001. static int reload_lock = 0;
  10002. static long int data_check = 0;
  10003. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10004. struct stat cert_buf;
  10005. long int t;
  10006. char *pem;
  10007. int should_verify_peer;
  10008. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10009. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10010. * refresh_trust still can not work. */
  10011. return 0;
  10012. }
  10013. t = data_check;
  10014. if (stat(pem, &cert_buf) != -1) {
  10015. t = (long int)cert_buf.st_mtime;
  10016. }
  10017. if (data_check != t) {
  10018. data_check = t;
  10019. should_verify_peer =
  10020. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10021. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10022. == 0);
  10023. if (should_verify_peer) {
  10024. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10025. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10026. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10027. ca_file,
  10028. ca_path) != 1) {
  10029. mg_cry(fc(conn->ctx),
  10030. "SSL_CTX_load_verify_locations error: %s "
  10031. "ssl_verify_peer requires setting "
  10032. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10033. "present in "
  10034. "the .conf file?",
  10035. ssl_error());
  10036. return 0;
  10037. }
  10038. }
  10039. if (1 == mg_atomic_inc(p_reload_lock)) {
  10040. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10041. return 0;
  10042. }
  10043. *p_reload_lock = 0;
  10044. }
  10045. }
  10046. /* lock while cert is reloading */
  10047. while (*p_reload_lock) {
  10048. sleep(1);
  10049. }
  10050. return 1;
  10051. }
  10052. static pthread_mutex_t *ssl_mutexes;
  10053. static int
  10054. sslize(struct mg_connection *conn,
  10055. SSL_CTX *s,
  10056. int (*func)(SSL *),
  10057. volatile int *stop_server)
  10058. {
  10059. int ret, err;
  10060. int short_trust;
  10061. unsigned i;
  10062. if (!conn) {
  10063. return 0;
  10064. }
  10065. short_trust =
  10066. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10067. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10068. if (short_trust) {
  10069. int trust_ret = refresh_trust(conn);
  10070. if (!trust_ret) {
  10071. return trust_ret;
  10072. }
  10073. }
  10074. conn->ssl = SSL_new(s);
  10075. if (conn->ssl == NULL) {
  10076. return 0;
  10077. }
  10078. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10079. if (ret != 1) {
  10080. err = SSL_get_error(conn->ssl, ret);
  10081. (void)err; /* TODO: set some error message */
  10082. SSL_free(conn->ssl);
  10083. conn->ssl = NULL;
  10084. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10085. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10086. ERR_remove_state(0);
  10087. return 0;
  10088. }
  10089. /* SSL functions may fail and require to be called again:
  10090. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10091. * Here "func" could be SSL_connect or SSL_accept. */
  10092. for (i = 16; i <= 1024; i *= 2) {
  10093. ret = func(conn->ssl);
  10094. if (ret != 1) {
  10095. err = SSL_get_error(conn->ssl, ret);
  10096. if ((err == SSL_ERROR_WANT_CONNECT)
  10097. || (err == SSL_ERROR_WANT_ACCEPT)
  10098. || (err == SSL_ERROR_WANT_READ)
  10099. || (err == SSL_ERROR_WANT_WRITE)) {
  10100. /* Need to retry the function call "later".
  10101. * See https://linux.die.net/man/3/ssl_get_error
  10102. * This is typical for non-blocking sockets. */
  10103. if (*stop_server) {
  10104. /* Don't wait if the server is going to be stopped. */
  10105. break;
  10106. }
  10107. mg_sleep(i);
  10108. } else if (err == SSL_ERROR_SYSCALL) {
  10109. /* This is an IO error. Look at errno. */
  10110. err = errno;
  10111. /* TODO: set some error message */
  10112. break;
  10113. } else {
  10114. /* This is an SSL specific error */
  10115. /* TODO: set some error message */
  10116. break;
  10117. }
  10118. } else {
  10119. /* success */
  10120. break;
  10121. }
  10122. }
  10123. if (ret != 1) {
  10124. SSL_free(conn->ssl);
  10125. conn->ssl = NULL;
  10126. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10127. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10128. ERR_remove_state(0);
  10129. return 0;
  10130. }
  10131. return 1;
  10132. }
  10133. /* Return OpenSSL error message (from CRYPTO lib) */
  10134. static const char *
  10135. ssl_error(void)
  10136. {
  10137. unsigned long err;
  10138. err = ERR_get_error();
  10139. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10140. }
  10141. static int
  10142. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10143. {
  10144. int i;
  10145. const char hexdigit[] = "0123456789abcdef";
  10146. if (memlen <= 0 || buflen <= 0) {
  10147. return 0;
  10148. }
  10149. if (buflen < (3 * memlen)) {
  10150. return 0;
  10151. }
  10152. for (i = 0; i < memlen; i++) {
  10153. if (i > 0) {
  10154. buf[3 * i - 1] = ' ';
  10155. }
  10156. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10157. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10158. }
  10159. buf[3 * memlen - 1] = 0;
  10160. return 1;
  10161. }
  10162. static void
  10163. ssl_get_client_cert_info(struct mg_connection *conn)
  10164. {
  10165. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10166. if (cert) {
  10167. char str_subject[1024];
  10168. char str_issuer[1024];
  10169. char str_serial[1024];
  10170. char str_finger[1024];
  10171. unsigned char buf[256];
  10172. int len;
  10173. unsigned int ulen;
  10174. /* Handle to algorithm used for fingerprint */
  10175. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10176. /* Get Subject and issuer */
  10177. X509_NAME *subj = X509_get_subject_name(cert);
  10178. X509_NAME *iss = X509_get_issuer_name(cert);
  10179. /* Get serial number */
  10180. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10181. /* Translate subject and issuer to a string */
  10182. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10183. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10184. /* Translate serial number to a hex string */
  10185. len = i2c_ASN1_INTEGER(serial, NULL);
  10186. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  10187. unsigned char *pbuf = buf;
  10188. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  10189. if (!hexdump2string(
  10190. buf, len2, str_serial, (int)sizeof(str_serial))) {
  10191. *str_serial = 0;
  10192. }
  10193. } else {
  10194. *str_serial = 0;
  10195. }
  10196. /* Calculate SHA1 fingerprint and store as a hex string */
  10197. ulen = 0;
  10198. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10199. if (!hexdump2string(
  10200. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10201. *str_finger = 0;
  10202. }
  10203. conn->request_info.client_cert =
  10204. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10205. if (conn->request_info.client_cert) {
  10206. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10207. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10208. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10209. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10210. } else {
  10211. /* TODO: write some OOM message */
  10212. }
  10213. X509_free(cert);
  10214. }
  10215. }
  10216. static void
  10217. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10218. {
  10219. (void)line;
  10220. (void)file;
  10221. if (mode & 1) {
  10222. /* 1 is CRYPTO_LOCK */
  10223. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10224. } else {
  10225. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10226. }
  10227. }
  10228. #if !defined(NO_SSL_DL)
  10229. static void *
  10230. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10231. {
  10232. union {
  10233. void *p;
  10234. void (*fp)(void);
  10235. } u;
  10236. void *dll_handle;
  10237. struct ssl_func *fp;
  10238. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10239. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10240. return NULL;
  10241. }
  10242. for (fp = sw; fp->name != NULL; fp++) {
  10243. #ifdef _WIN32
  10244. /* GetProcAddress() returns pointer to function */
  10245. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10246. #else
  10247. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10248. * pointers to function pointers. We need to use a union to make a
  10249. * cast. */
  10250. u.p = dlsym(dll_handle, fp->name);
  10251. #endif /* _WIN32 */
  10252. if (u.fp == NULL) {
  10253. mg_cry(fc(ctx),
  10254. "%s: %s: cannot find %s",
  10255. __func__,
  10256. dll_name,
  10257. fp->name);
  10258. dlclose(dll_handle);
  10259. return NULL;
  10260. } else {
  10261. fp->ptr = u.fp;
  10262. }
  10263. }
  10264. return dll_handle;
  10265. }
  10266. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10267. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10268. #endif /* NO_SSL_DL */
  10269. #if defined(SSL_ALREADY_INITIALIZED)
  10270. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10271. #else
  10272. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10273. #endif
  10274. static int
  10275. initialize_ssl(struct mg_context *ctx)
  10276. {
  10277. int i;
  10278. size_t size;
  10279. #if !defined(NO_SSL_DL)
  10280. if (!cryptolib_dll_handle) {
  10281. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10282. if (!cryptolib_dll_handle) {
  10283. return 0;
  10284. }
  10285. }
  10286. #endif /* NO_SSL_DL */
  10287. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10288. return 1;
  10289. }
  10290. /* Initialize locking callbacks, needed for thread safety.
  10291. * http://www.openssl.org/support/faq.html#PROG1
  10292. */
  10293. i = CRYPTO_num_locks();
  10294. if (i < 0) {
  10295. i = 0;
  10296. }
  10297. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10298. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10299. mg_cry(fc(ctx),
  10300. "%s: cannot allocate mutexes: %s",
  10301. __func__,
  10302. ssl_error());
  10303. return 0;
  10304. }
  10305. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10306. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10307. }
  10308. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10309. CRYPTO_set_id_callback(&mg_current_thread_id);
  10310. return 1;
  10311. }
  10312. static int
  10313. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10314. {
  10315. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10316. mg_cry(fc(ctx),
  10317. "%s: cannot open certificate file %s: %s",
  10318. __func__,
  10319. pem,
  10320. ssl_error());
  10321. return 0;
  10322. }
  10323. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10324. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10325. mg_cry(fc(ctx),
  10326. "%s: cannot open private key file %s: %s",
  10327. __func__,
  10328. pem,
  10329. ssl_error());
  10330. return 0;
  10331. }
  10332. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10333. mg_cry(fc(ctx),
  10334. "%s: certificate and private key do not match: %s",
  10335. __func__,
  10336. pem);
  10337. return 0;
  10338. }
  10339. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10340. mg_cry(fc(ctx),
  10341. "%s: cannot use certificate chain file %s: %s",
  10342. __func__,
  10343. pem,
  10344. ssl_error());
  10345. return 0;
  10346. }
  10347. return 1;
  10348. }
  10349. static long
  10350. ssl_get_protocol(int version_id)
  10351. {
  10352. long ret = SSL_OP_ALL;
  10353. if (version_id > 0)
  10354. ret |= SSL_OP_NO_SSLv2;
  10355. if (version_id > 1)
  10356. ret |= SSL_OP_NO_SSLv3;
  10357. if (version_id > 2)
  10358. ret |= SSL_OP_NO_TLSv1;
  10359. if (version_id > 3)
  10360. ret |= SSL_OP_NO_TLSv1_1;
  10361. return ret;
  10362. }
  10363. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10364. static int
  10365. set_ssl_option(struct mg_context *ctx)
  10366. {
  10367. const char *pem;
  10368. int callback_ret;
  10369. int should_verify_peer;
  10370. const char *ca_path;
  10371. const char *ca_file;
  10372. int use_default_verify_paths;
  10373. int verify_depth;
  10374. time_t now_rt = time(NULL);
  10375. struct timespec now_mt;
  10376. md5_byte_t ssl_context_id[16];
  10377. md5_state_t md5state;
  10378. int protocol_ver;
  10379. /* If PEM file is not specified and the init_ssl callback
  10380. * is not specified, skip SSL initialization. */
  10381. if (!ctx) {
  10382. return 0;
  10383. }
  10384. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10385. && ctx->callbacks.init_ssl == NULL) {
  10386. return 1;
  10387. }
  10388. if (!initialize_ssl(ctx)) {
  10389. return 0;
  10390. }
  10391. #if !defined(NO_SSL_DL)
  10392. if (!ssllib_dll_handle) {
  10393. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10394. if (!ssllib_dll_handle) {
  10395. return 0;
  10396. }
  10397. }
  10398. #endif /* NO_SSL_DL */
  10399. /* Initialize SSL library */
  10400. SSL_library_init();
  10401. SSL_load_error_strings();
  10402. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10403. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10404. return 0;
  10405. }
  10406. SSL_CTX_clear_options(ctx->ssl_ctx,
  10407. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10408. | SSL_OP_NO_TLSv1_1);
  10409. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10410. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10411. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10412. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10413. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10414. /* If a callback has been specified, call it. */
  10415. callback_ret =
  10416. (ctx->callbacks.init_ssl == NULL)
  10417. ? 0
  10418. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10419. /* If callback returns 0, civetweb sets up the SSL certificate.
  10420. * If it returns 1, civetweb assumes the calback already did this.
  10421. * If it returns -1, initializing ssl fails. */
  10422. if (callback_ret < 0) {
  10423. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10424. return 0;
  10425. }
  10426. if (callback_ret > 0) {
  10427. if (pem != NULL) {
  10428. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10429. }
  10430. return 1;
  10431. }
  10432. /* Use some UID as session context ID. */
  10433. md5_init(&md5state);
  10434. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10435. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10436. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10437. md5_append(&md5state,
  10438. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10439. strlen(ctx->config[LISTENING_PORTS]));
  10440. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10441. md5_finish(&md5state, ssl_context_id);
  10442. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10443. (const unsigned char *)&ssl_context_id,
  10444. sizeof(ssl_context_id));
  10445. if (pem != NULL) {
  10446. if (!ssl_use_pem_file(ctx, pem)) {
  10447. return 0;
  10448. }
  10449. }
  10450. should_verify_peer =
  10451. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10452. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10453. use_default_verify_paths =
  10454. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10455. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10456. if (should_verify_peer) {
  10457. ca_path = ctx->config[SSL_CA_PATH];
  10458. ca_file = ctx->config[SSL_CA_FILE];
  10459. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10460. != 1) {
  10461. mg_cry(fc(ctx),
  10462. "SSL_CTX_load_verify_locations error: %s "
  10463. "ssl_verify_peer requires setting "
  10464. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10465. "present in "
  10466. "the .conf file?",
  10467. ssl_error());
  10468. return 0;
  10469. }
  10470. SSL_CTX_set_verify(ctx->ssl_ctx,
  10471. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10472. NULL);
  10473. if (use_default_verify_paths
  10474. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10475. mg_cry(fc(ctx),
  10476. "SSL_CTX_set_default_verify_paths error: %s",
  10477. ssl_error());
  10478. return 0;
  10479. }
  10480. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10481. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10482. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10483. }
  10484. }
  10485. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10486. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10487. != 1) {
  10488. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10489. }
  10490. }
  10491. return 1;
  10492. }
  10493. static void
  10494. uninitialize_ssl(struct mg_context *ctx)
  10495. {
  10496. int i;
  10497. (void)ctx;
  10498. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10499. /* Shutdown according to
  10500. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10501. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10502. */
  10503. CRYPTO_set_locking_callback(NULL);
  10504. CRYPTO_set_id_callback(NULL);
  10505. ENGINE_cleanup();
  10506. CONF_modules_unload(1);
  10507. ERR_free_strings();
  10508. EVP_cleanup();
  10509. CRYPTO_cleanup_all_ex_data();
  10510. ERR_remove_state(0);
  10511. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10512. pthread_mutex_destroy(&ssl_mutexes[i]);
  10513. }
  10514. mg_free(ssl_mutexes);
  10515. ssl_mutexes = NULL;
  10516. }
  10517. }
  10518. #endif /* !NO_SSL */
  10519. static int
  10520. set_gpass_option(struct mg_context *ctx)
  10521. {
  10522. if (ctx) {
  10523. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10524. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10525. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10526. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10527. return 0;
  10528. }
  10529. return 1;
  10530. }
  10531. return 0;
  10532. }
  10533. static int
  10534. set_acl_option(struct mg_context *ctx)
  10535. {
  10536. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10537. }
  10538. static void
  10539. reset_per_request_attributes(struct mg_connection *conn)
  10540. {
  10541. if (!conn) {
  10542. return;
  10543. }
  10544. conn->path_info = NULL;
  10545. conn->num_bytes_sent = conn->consumed_content = 0;
  10546. conn->status_code = -1;
  10547. conn->is_chunked = 0;
  10548. conn->must_close = conn->request_len = conn->throttle = 0;
  10549. conn->request_info.content_length = -1;
  10550. conn->request_info.remote_user = NULL;
  10551. conn->request_info.request_method = NULL;
  10552. conn->request_info.request_uri = NULL;
  10553. conn->request_info.local_uri = NULL;
  10554. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10555. * local_uri and request_uri */
  10556. conn->request_info.http_version = NULL;
  10557. conn->request_info.num_headers = 0;
  10558. conn->data_len = 0;
  10559. conn->chunk_remainder = 0;
  10560. }
  10561. #if 0
  10562. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10563. * Leave this function here (commented out) for reference until
  10564. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10565. * no longer required.
  10566. */
  10567. static int
  10568. set_sock_timeout(SOCKET sock, int milliseconds)
  10569. {
  10570. int r0 = 0, r1, r2;
  10571. #ifdef _WIN32
  10572. /* Windows specific */
  10573. DWORD tv = (DWORD)milliseconds;
  10574. #else
  10575. /* Linux, ... (not Windows) */
  10576. struct timeval tv;
  10577. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10578. * max. time waiting for the acknowledged of TCP data before the connection
  10579. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10580. * If this option is not set, the default timeout of 20-30 minutes is used.
  10581. */
  10582. /* #define TCP_USER_TIMEOUT (18) */
  10583. #if defined(TCP_USER_TIMEOUT)
  10584. unsigned int uto = (unsigned int)milliseconds;
  10585. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10586. #endif
  10587. memset(&tv, 0, sizeof(tv));
  10588. tv.tv_sec = milliseconds / 1000;
  10589. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10590. #endif /* _WIN32 */
  10591. r1 = setsockopt(
  10592. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10593. r2 = setsockopt(
  10594. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10595. return r0 || r1 || r2;
  10596. }
  10597. #endif
  10598. static int
  10599. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10600. {
  10601. if (setsockopt(sock,
  10602. IPPROTO_TCP,
  10603. TCP_NODELAY,
  10604. (SOCK_OPT_TYPE)&nodelay_on,
  10605. sizeof(nodelay_on)) != 0) {
  10606. /* Error */
  10607. return 1;
  10608. }
  10609. /* OK */
  10610. return 0;
  10611. }
  10612. static void
  10613. close_socket_gracefully(struct mg_connection *conn)
  10614. {
  10615. #if defined(_WIN32)
  10616. char buf[MG_BUF_LEN];
  10617. int n;
  10618. #endif
  10619. struct linger linger;
  10620. int error_code = 0;
  10621. socklen_t opt_len = sizeof(error_code);
  10622. if (!conn) {
  10623. return;
  10624. }
  10625. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  10626. * "Note that enabling a nonzero timeout on a nonblocking socket
  10627. * is not recommended.", so set it to blocking now */
  10628. set_blocking_mode(conn->client.sock, 1);
  10629. /* Send FIN to the client */
  10630. shutdown(conn->client.sock, SHUTDOWN_WR);
  10631. #if defined(_WIN32)
  10632. /* Read and discard pending incoming data. If we do not do that and
  10633. * close
  10634. * the socket, the data in the send buffer may be discarded. This
  10635. * behaviour is seen on Windows, when client keeps sending data
  10636. * when server decides to close the connection; then when client
  10637. * does recv() it gets no data back. */
  10638. do {
  10639. n = pull(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  10640. } while (n > 0);
  10641. #endif
  10642. /* Set linger option to avoid socket hanging out after close. This
  10643. * prevent ephemeral port exhaust problem under high QPS. */
  10644. linger.l_onoff = 1;
  10645. linger.l_linger = 1;
  10646. if (getsockopt(conn->client.sock,
  10647. SOL_SOCKET,
  10648. SO_ERROR,
  10649. (char *)&error_code,
  10650. &opt_len) != 0) {
  10651. /* Cannot determine if socket is already closed. This should
  10652. * not occur and never did in a test. Log an error message
  10653. * and continue. */
  10654. mg_cry(conn,
  10655. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10656. __func__,
  10657. strerror(ERRNO));
  10658. } else if (error_code == ECONNRESET) {
  10659. /* Socket already closed by client/peer, close socket without linger */
  10660. } else {
  10661. /* Set linger timeout */
  10662. if (setsockopt(conn->client.sock,
  10663. SOL_SOCKET,
  10664. SO_LINGER,
  10665. (char *)&linger,
  10666. sizeof(linger)) != 0) {
  10667. mg_cry(conn,
  10668. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  10669. __func__,
  10670. strerror(ERRNO));
  10671. }
  10672. }
  10673. /* Now we know that our FIN is ACK-ed, safe to close */
  10674. closesocket(conn->client.sock);
  10675. conn->client.sock = INVALID_SOCKET;
  10676. }
  10677. static void
  10678. close_connection(struct mg_connection *conn)
  10679. {
  10680. if (!conn || !conn->ctx) {
  10681. return;
  10682. }
  10683. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10684. if (conn->lua_websocket_state) {
  10685. lua_websocket_close(conn, conn->lua_websocket_state);
  10686. conn->lua_websocket_state = NULL;
  10687. }
  10688. #endif
  10689. /* call the connection_close callback if assigned */
  10690. if ((conn->ctx->callbacks.connection_close != NULL)
  10691. && (conn->ctx->context_type == 1)) {
  10692. conn->ctx->callbacks.connection_close(conn);
  10693. }
  10694. mg_lock_connection(conn);
  10695. conn->must_close = 1;
  10696. #ifndef NO_SSL
  10697. if (conn->ssl != NULL) {
  10698. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10699. */
  10700. SSL_shutdown(conn->ssl);
  10701. SSL_free(conn->ssl);
  10702. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10703. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10704. ERR_remove_state(0);
  10705. conn->ssl = NULL;
  10706. }
  10707. #endif
  10708. if (conn->client.sock != INVALID_SOCKET) {
  10709. close_socket_gracefully(conn);
  10710. conn->client.sock = INVALID_SOCKET;
  10711. }
  10712. mg_unlock_connection(conn);
  10713. }
  10714. void
  10715. mg_close_connection(struct mg_connection *conn)
  10716. {
  10717. struct mg_context *client_ctx = NULL;
  10718. if (conn == NULL) {
  10719. return;
  10720. }
  10721. #if defined(USE_WEBSOCKET)
  10722. if (conn->ctx->context_type == 2) {
  10723. unsigned int i;
  10724. /* ws/wss client */
  10725. client_ctx = conn->ctx;
  10726. /* client context: loops must end */
  10727. conn->ctx->stop_flag = 1;
  10728. /* We need to get the client thread out of the select/recv call here. */
  10729. /* Since we use a sleep quantum of some seconds to check for recv
  10730. * timeouts, we will just wait a few seconds in mg_join_thread. */
  10731. /* join worker thread */
  10732. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10733. if (client_ctx->workerthreadids[i] != 0) {
  10734. mg_join_thread(client_ctx->workerthreadids[i]);
  10735. }
  10736. }
  10737. }
  10738. #else
  10739. (void)client_ctx;
  10740. #endif
  10741. close_connection(conn);
  10742. #ifndef NO_SSL
  10743. if (conn->client_ssl_ctx != NULL) {
  10744. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10745. }
  10746. #endif
  10747. if (client_ctx != NULL) {
  10748. /* free context */
  10749. mg_free(client_ctx->workerthreadids);
  10750. mg_free(client_ctx);
  10751. (void)pthread_mutex_destroy(&conn->mutex);
  10752. mg_free(conn);
  10753. }
  10754. }
  10755. static struct mg_connection *
  10756. mg_connect_client_impl(const struct mg_client_options *client_options,
  10757. int use_ssl,
  10758. char *ebuf,
  10759. size_t ebuf_len)
  10760. {
  10761. static struct mg_context fake_ctx;
  10762. struct mg_connection *conn = NULL;
  10763. SOCKET sock;
  10764. union usa sa;
  10765. if (!connect_socket(&fake_ctx,
  10766. client_options->host,
  10767. client_options->port,
  10768. use_ssl,
  10769. ebuf,
  10770. ebuf_len,
  10771. &sock,
  10772. &sa)) {
  10773. ;
  10774. } else if ((conn = (struct mg_connection *)
  10775. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10776. mg_snprintf(NULL,
  10777. NULL, /* No truncation check for ebuf */
  10778. ebuf,
  10779. ebuf_len,
  10780. "calloc(): %s",
  10781. strerror(ERRNO));
  10782. closesocket(sock);
  10783. #ifndef NO_SSL
  10784. } else if (use_ssl
  10785. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10786. == NULL) {
  10787. mg_snprintf(NULL,
  10788. NULL, /* No truncation check for ebuf */
  10789. ebuf,
  10790. ebuf_len,
  10791. "SSL_CTX_new error");
  10792. closesocket(sock);
  10793. mg_free(conn);
  10794. conn = NULL;
  10795. #endif /* NO_SSL */
  10796. } else {
  10797. #ifdef USE_IPV6
  10798. socklen_t len = (sa.sa.sa_family == AF_INET)
  10799. ? sizeof(conn->client.rsa.sin)
  10800. : sizeof(conn->client.rsa.sin6);
  10801. struct sockaddr *psa =
  10802. (sa.sa.sa_family == AF_INET)
  10803. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10804. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10805. #else
  10806. socklen_t len = sizeof(conn->client.rsa.sin);
  10807. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10808. #endif
  10809. conn->buf_size = MAX_REQUEST_SIZE;
  10810. conn->buf = (char *)(conn + 1);
  10811. conn->ctx = &fake_ctx;
  10812. conn->client.sock = sock;
  10813. conn->client.lsa = sa;
  10814. if (getsockname(sock, psa, &len) != 0) {
  10815. mg_cry(conn,
  10816. "%s: getsockname() failed: %s",
  10817. __func__,
  10818. strerror(ERRNO));
  10819. }
  10820. conn->client.is_ssl = use_ssl ? 1 : 0;
  10821. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10822. #ifndef NO_SSL
  10823. if (use_ssl) {
  10824. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10825. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10826. * SSL_CTX_set_verify call is needed to switch off server
  10827. * certificate checking, which is off by default in OpenSSL and
  10828. * on in yaSSL. */
  10829. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10830. * SSL_VERIFY_PEER, verify_ssl_server); */
  10831. if (client_options->client_cert) {
  10832. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10833. mg_snprintf(NULL,
  10834. NULL, /* No truncation check for ebuf */
  10835. ebuf,
  10836. ebuf_len,
  10837. "Can not use SSL client certificate");
  10838. SSL_CTX_free(conn->client_ssl_ctx);
  10839. closesocket(sock);
  10840. mg_free(conn);
  10841. conn = NULL;
  10842. }
  10843. }
  10844. if (client_options->server_cert) {
  10845. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10846. client_options->server_cert,
  10847. NULL);
  10848. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10849. } else {
  10850. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10851. }
  10852. if (!sslize(conn,
  10853. conn->client_ssl_ctx,
  10854. SSL_connect,
  10855. &(conn->ctx->stop_flag))) {
  10856. mg_snprintf(NULL,
  10857. NULL, /* No truncation check for ebuf */
  10858. ebuf,
  10859. ebuf_len,
  10860. "SSL connection error");
  10861. SSL_CTX_free(conn->client_ssl_ctx);
  10862. closesocket(sock);
  10863. mg_free(conn);
  10864. conn = NULL;
  10865. }
  10866. }
  10867. #endif
  10868. }
  10869. if (conn) {
  10870. set_blocking_mode(sock, 0);
  10871. }
  10872. return conn;
  10873. }
  10874. CIVETWEB_API struct mg_connection *
  10875. mg_connect_client_secure(const struct mg_client_options *client_options,
  10876. char *error_buffer,
  10877. size_t error_buffer_size)
  10878. {
  10879. return mg_connect_client_impl(client_options,
  10880. 1,
  10881. error_buffer,
  10882. error_buffer_size);
  10883. }
  10884. struct mg_connection *
  10885. mg_connect_client(const char *host,
  10886. int port,
  10887. int use_ssl,
  10888. char *error_buffer,
  10889. size_t error_buffer_size)
  10890. {
  10891. struct mg_client_options opts;
  10892. memset(&opts, 0, sizeof(opts));
  10893. opts.host = host;
  10894. opts.port = port;
  10895. return mg_connect_client_impl(&opts,
  10896. use_ssl,
  10897. error_buffer,
  10898. error_buffer_size);
  10899. }
  10900. static const struct {
  10901. const char *proto;
  10902. size_t proto_len;
  10903. unsigned default_port;
  10904. } abs_uri_protocols[] = {{"http://", 7, 80},
  10905. {"https://", 8, 443},
  10906. {"ws://", 5, 80},
  10907. {"wss://", 6, 443},
  10908. {NULL, 0, 0}};
  10909. /* Check if the uri is valid.
  10910. * return 0 for invalid uri,
  10911. * return 1 for *,
  10912. * return 2 for relative uri,
  10913. * return 3 for absolute uri without port,
  10914. * return 4 for absolute uri with port */
  10915. static int
  10916. get_uri_type(const char *uri)
  10917. {
  10918. int i;
  10919. char *hostend, *portbegin, *portend;
  10920. unsigned long port;
  10921. /* According to the HTTP standard
  10922. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10923. * URI can be an asterisk (*) or should start with slash (relative uri),
  10924. * or it should start with the protocol (absolute uri). */
  10925. if (uri[0] == '*' && uri[1] == '\0') {
  10926. /* asterisk */
  10927. return 1;
  10928. }
  10929. /* Valid URIs according to RFC 3986
  10930. * (https://www.ietf.org/rfc/rfc3986.txt)
  10931. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10932. * and unreserved characters A-Z a-z 0-9 and -._~
  10933. * and % encoded symbols.
  10934. */
  10935. for (i = 0; uri[i] != 0; i++) {
  10936. if (uri[i] < 33) {
  10937. /* control characters and spaces are invalid */
  10938. return 0;
  10939. }
  10940. if (uri[i] > 126) {
  10941. /* non-ascii characters must be % encoded */
  10942. return 0;
  10943. } else {
  10944. switch (uri[i]) {
  10945. case '"': /* 34 */
  10946. case '<': /* 60 */
  10947. case '>': /* 62 */
  10948. case '\\': /* 92 */
  10949. case '^': /* 94 */
  10950. case '`': /* 96 */
  10951. case '{': /* 123 */
  10952. case '|': /* 124 */
  10953. case '}': /* 125 */
  10954. return 0;
  10955. default:
  10956. /* character is ok */
  10957. break;
  10958. }
  10959. }
  10960. }
  10961. /* A relative uri starts with a / character */
  10962. if (uri[0] == '/') {
  10963. /* relative uri */
  10964. return 2;
  10965. }
  10966. /* It could be an absolute uri: */
  10967. /* This function only checks if the uri is valid, not if it is
  10968. * addressing the current server. So civetweb can also be used
  10969. * as a proxy server. */
  10970. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  10971. if (mg_strncasecmp(uri,
  10972. abs_uri_protocols[i].proto,
  10973. abs_uri_protocols[i].proto_len) == 0) {
  10974. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  10975. if (!hostend) {
  10976. return 0;
  10977. }
  10978. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  10979. if (!portbegin) {
  10980. return 3;
  10981. }
  10982. port = strtoul(portbegin + 1, &portend, 10);
  10983. if ((portend != hostend) || !port || !is_valid_port(port)) {
  10984. return 0;
  10985. }
  10986. return 4;
  10987. }
  10988. }
  10989. return 0;
  10990. }
  10991. /* Return NULL or the relative uri at the current server */
  10992. static const char *
  10993. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  10994. {
  10995. const char *server_domain;
  10996. size_t server_domain_len;
  10997. size_t request_domain_len = 0;
  10998. unsigned long port = 0;
  10999. int i;
  11000. const char *hostbegin = NULL;
  11001. const char *hostend = NULL;
  11002. const char *portbegin;
  11003. char *portend;
  11004. /* DNS is case insensitive, so use case insensitive string compare here
  11005. */
  11006. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11007. if (!server_domain) {
  11008. return 0;
  11009. }
  11010. server_domain_len = strlen(server_domain);
  11011. if (!server_domain_len) {
  11012. return 0;
  11013. }
  11014. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11015. if (mg_strncasecmp(uri,
  11016. abs_uri_protocols[i].proto,
  11017. abs_uri_protocols[i].proto_len) == 0) {
  11018. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11019. hostend = strchr(hostbegin, '/');
  11020. if (!hostend) {
  11021. return 0;
  11022. }
  11023. portbegin = strchr(hostbegin, ':');
  11024. if ((!portbegin) || (portbegin > hostend)) {
  11025. port = abs_uri_protocols[i].default_port;
  11026. request_domain_len = (size_t)(hostend - hostbegin);
  11027. } else {
  11028. port = strtoul(portbegin + 1, &portend, 10);
  11029. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11030. return 0;
  11031. }
  11032. request_domain_len = (size_t)(portbegin - hostbegin);
  11033. }
  11034. /* protocol found, port set */
  11035. break;
  11036. }
  11037. }
  11038. if (!port) {
  11039. /* port remains 0 if the protocol is not found */
  11040. return 0;
  11041. }
  11042. /* Check if the request is directed to a different server. */
  11043. /* First check if the port is the same (IPv4 and IPv6). */
  11044. #if defined(USE_IPV6)
  11045. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11046. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11047. /* Request is directed to a different port */
  11048. return 0;
  11049. }
  11050. } else
  11051. #endif
  11052. {
  11053. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11054. /* Request is directed to a different port */
  11055. return 0;
  11056. }
  11057. }
  11058. /* Finally check if the server corresponds to the authentication
  11059. * domain of the server (the server domain).
  11060. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11061. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11062. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11063. * or http://mydomain.com.fake/path/file.ext).
  11064. */
  11065. if ((request_domain_len == server_domain_len)
  11066. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11067. /* Request is directed to this server - full name match. */
  11068. } else {
  11069. if (request_domain_len < (server_domain_len + 2)) {
  11070. /* Request is directed to another server: The server name is longer
  11071. * than
  11072. * the request name. Drop this case here to avoid overflows in the
  11073. * following checks. */
  11074. return 0;
  11075. }
  11076. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11077. /* Request is directed to another server: It could be a substring
  11078. * like notmyserver.com */
  11079. return 0;
  11080. }
  11081. if (0 != memcmp(server_domain,
  11082. hostbegin + request_domain_len - server_domain_len,
  11083. server_domain_len)) {
  11084. /* Request is directed to another server:
  11085. * The server name is different. */
  11086. return 0;
  11087. }
  11088. }
  11089. return hostend;
  11090. }
  11091. static int
  11092. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11093. {
  11094. const char *cl;
  11095. if (ebuf_len > 0) {
  11096. ebuf[0] = '\0';
  11097. }
  11098. *err = 0;
  11099. reset_per_request_attributes(conn);
  11100. if (!conn) {
  11101. mg_snprintf(conn,
  11102. NULL, /* No truncation check for ebuf */
  11103. ebuf,
  11104. ebuf_len,
  11105. "%s",
  11106. "Internal error");
  11107. *err = 500;
  11108. return 0;
  11109. }
  11110. /* Set the time the request was received. This value should be used for
  11111. * timeouts. */
  11112. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11113. conn->request_len =
  11114. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11115. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11116. */
  11117. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11118. mg_snprintf(conn,
  11119. NULL, /* No truncation check for ebuf */
  11120. ebuf,
  11121. ebuf_len,
  11122. "%s",
  11123. "Invalid request size");
  11124. *err = 500;
  11125. return 0;
  11126. }
  11127. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11128. mg_snprintf(conn,
  11129. NULL, /* No truncation check for ebuf */
  11130. ebuf,
  11131. ebuf_len,
  11132. "%s",
  11133. "Request Too Large");
  11134. *err = 413;
  11135. return 0;
  11136. } else if (conn->request_len <= 0) {
  11137. if (conn->data_len > 0) {
  11138. mg_snprintf(conn,
  11139. NULL, /* No truncation check for ebuf */
  11140. ebuf,
  11141. ebuf_len,
  11142. "%s",
  11143. "Client sent malformed request");
  11144. *err = 400;
  11145. } else {
  11146. /* Server did not recv anything -> just close the connection */
  11147. conn->must_close = 1;
  11148. mg_snprintf(conn,
  11149. NULL, /* No truncation check for ebuf */
  11150. ebuf,
  11151. ebuf_len,
  11152. "%s",
  11153. "Client did not send a request");
  11154. *err = 0;
  11155. }
  11156. return 0;
  11157. } else if (parse_http_message(conn->buf,
  11158. conn->buf_size,
  11159. &conn->request_info) <= 0) {
  11160. mg_snprintf(conn,
  11161. NULL, /* No truncation check for ebuf */
  11162. ebuf,
  11163. ebuf_len,
  11164. "%s",
  11165. "Bad Request");
  11166. *err = 400;
  11167. return 0;
  11168. } else {
  11169. /* Message is a valid request or response */
  11170. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11171. /* Request/response has content length set */
  11172. char *endptr = NULL;
  11173. conn->content_len = strtoll(cl, &endptr, 10);
  11174. if (endptr == cl) {
  11175. mg_snprintf(conn,
  11176. NULL, /* No truncation check for ebuf */
  11177. ebuf,
  11178. ebuf_len,
  11179. "%s",
  11180. "Bad Request");
  11181. *err = 411;
  11182. return 0;
  11183. }
  11184. /* Publish the content length back to the request info. */
  11185. conn->request_info.content_length = conn->content_len;
  11186. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11187. != NULL
  11188. && !mg_strcasecmp(cl, "chunked")) {
  11189. conn->is_chunked = 1;
  11190. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11191. || !mg_strcasecmp(conn->request_info.request_method,
  11192. "PUT")) {
  11193. /* POST or PUT request without content length set */
  11194. conn->content_len = -1;
  11195. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11196. "HTTP/",
  11197. 5)) {
  11198. /* Response without content length set */
  11199. conn->content_len = -1;
  11200. } else {
  11201. /* Other request */
  11202. conn->content_len = 0;
  11203. }
  11204. }
  11205. return 1;
  11206. }
  11207. int
  11208. mg_get_response(struct mg_connection *conn,
  11209. char *ebuf,
  11210. size_t ebuf_len,
  11211. int timeout)
  11212. {
  11213. if (conn) {
  11214. /* Implementation of API function for HTTP clients */
  11215. int err, ret;
  11216. struct mg_context *octx = conn->ctx;
  11217. struct mg_context rctx = *(conn->ctx);
  11218. char txt[32]; /* will not overflow */
  11219. if (timeout >= 0) {
  11220. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11221. rctx.config[REQUEST_TIMEOUT] = txt;
  11222. /* Not required for non-blocking sockets.
  11223. set_sock_timeout(conn->client.sock, timeout);
  11224. */
  11225. } else {
  11226. rctx.config[REQUEST_TIMEOUT] = NULL;
  11227. }
  11228. conn->ctx = &rctx;
  11229. ret = getreq(conn, ebuf, ebuf_len, &err);
  11230. conn->ctx = octx;
  11231. /* TODO: 1) uri is deprecated;
  11232. * 2) here, ri.uri is the http response code */
  11233. conn->request_info.uri = conn->request_info.request_uri;
  11234. /* TODO (mid): Define proper return values - maybe return length?
  11235. * For the first test use <0 for error and >0 for OK */
  11236. return (ret == 0) ? -1 : +1;
  11237. }
  11238. return -1;
  11239. }
  11240. struct mg_connection *
  11241. mg_download(const char *host,
  11242. int port,
  11243. int use_ssl,
  11244. char *ebuf,
  11245. size_t ebuf_len,
  11246. const char *fmt,
  11247. ...)
  11248. {
  11249. struct mg_connection *conn;
  11250. va_list ap;
  11251. int i;
  11252. int reqerr;
  11253. va_start(ap, fmt);
  11254. ebuf[0] = '\0';
  11255. /* open a connection */
  11256. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11257. if (conn != NULL) {
  11258. i = mg_vprintf(conn, fmt, ap);
  11259. if (i <= 0) {
  11260. mg_snprintf(conn,
  11261. NULL, /* No truncation check for ebuf */
  11262. ebuf,
  11263. ebuf_len,
  11264. "%s",
  11265. "Error sending request");
  11266. } else {
  11267. getreq(conn, ebuf, ebuf_len, &reqerr);
  11268. /* TODO: 1) uri is deprecated;
  11269. * 2) here, ri.uri is the http response code */
  11270. conn->request_info.uri = conn->request_info.request_uri;
  11271. }
  11272. }
  11273. /* if an error occured, close the connection */
  11274. if (ebuf[0] != '\0' && conn != NULL) {
  11275. mg_close_connection(conn);
  11276. conn = NULL;
  11277. }
  11278. va_end(ap);
  11279. return conn;
  11280. }
  11281. struct websocket_client_thread_data {
  11282. struct mg_connection *conn;
  11283. mg_websocket_data_handler data_handler;
  11284. mg_websocket_close_handler close_handler;
  11285. void *callback_data;
  11286. };
  11287. #if defined(USE_WEBSOCKET)
  11288. #ifdef _WIN32
  11289. static unsigned __stdcall websocket_client_thread(void *data)
  11290. #else
  11291. static void *
  11292. websocket_client_thread(void *data)
  11293. #endif
  11294. {
  11295. struct websocket_client_thread_data *cdata =
  11296. (struct websocket_client_thread_data *)data;
  11297. mg_set_thread_name("ws-clnt");
  11298. if (cdata->conn->ctx) {
  11299. if (cdata->conn->ctx->callbacks.init_thread) {
  11300. /* 3 indicates a websocket client thread */
  11301. /* TODO: check if conn->ctx can be set */
  11302. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11303. }
  11304. }
  11305. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11306. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11307. if (cdata->close_handler != NULL) {
  11308. cdata->close_handler(cdata->conn, cdata->callback_data);
  11309. }
  11310. /* The websocket_client context has only this thread. If it runs out,
  11311. set the stop_flag to 2 (= "stopped"). */
  11312. cdata->conn->ctx->stop_flag = 2;
  11313. mg_free((void *)cdata);
  11314. #ifdef _WIN32
  11315. return 0;
  11316. #else
  11317. return NULL;
  11318. #endif
  11319. }
  11320. #endif
  11321. struct mg_connection *
  11322. mg_connect_websocket_client(const char *host,
  11323. int port,
  11324. int use_ssl,
  11325. char *error_buffer,
  11326. size_t error_buffer_size,
  11327. const char *path,
  11328. const char *origin,
  11329. mg_websocket_data_handler data_func,
  11330. mg_websocket_close_handler close_func,
  11331. void *user_data)
  11332. {
  11333. struct mg_connection *conn = NULL;
  11334. #if defined(USE_WEBSOCKET)
  11335. struct mg_context *newctx = NULL;
  11336. struct websocket_client_thread_data *thread_data;
  11337. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11338. static const char *handshake_req;
  11339. if (origin != NULL) {
  11340. handshake_req = "GET %s HTTP/1.1\r\n"
  11341. "Host: %s\r\n"
  11342. "Upgrade: websocket\r\n"
  11343. "Connection: Upgrade\r\n"
  11344. "Sec-WebSocket-Key: %s\r\n"
  11345. "Sec-WebSocket-Version: 13\r\n"
  11346. "Origin: %s\r\n"
  11347. "\r\n";
  11348. } else {
  11349. handshake_req = "GET %s HTTP/1.1\r\n"
  11350. "Host: %s\r\n"
  11351. "Upgrade: websocket\r\n"
  11352. "Connection: Upgrade\r\n"
  11353. "Sec-WebSocket-Key: %s\r\n"
  11354. "Sec-WebSocket-Version: 13\r\n"
  11355. "\r\n";
  11356. }
  11357. /* Establish the client connection and request upgrade */
  11358. conn = mg_download(host,
  11359. port,
  11360. use_ssl,
  11361. error_buffer,
  11362. error_buffer_size,
  11363. handshake_req,
  11364. path,
  11365. host,
  11366. magic,
  11367. origin);
  11368. /* Connection object will be null if something goes wrong */
  11369. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11370. if (!*error_buffer) {
  11371. /* if there is a connection, but it did not return 101,
  11372. * error_buffer is not yet set */
  11373. mg_snprintf(conn,
  11374. NULL, /* No truncation check for ebuf */
  11375. error_buffer,
  11376. error_buffer_size,
  11377. "Unexpected server reply");
  11378. }
  11379. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11380. if (conn != NULL) {
  11381. mg_free(conn);
  11382. conn = NULL;
  11383. }
  11384. return conn;
  11385. }
  11386. /* For client connections, mg_context is fake. Since we need to set a
  11387. * callback function, we need to create a copy and modify it. */
  11388. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11389. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11390. newctx->user_data = user_data;
  11391. newctx->context_type = 2; /* ws/wss client context type */
  11392. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11393. newctx->workerthreadids =
  11394. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11395. conn->ctx = newctx;
  11396. thread_data = (struct websocket_client_thread_data *)
  11397. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11398. thread_data->conn = conn;
  11399. thread_data->data_handler = data_func;
  11400. thread_data->close_handler = close_func;
  11401. thread_data->callback_data = NULL;
  11402. /* Start a thread to read the websocket client connection
  11403. * This thread will automatically stop when mg_disconnect is
  11404. * called on the client connection */
  11405. if (mg_start_thread_with_id(websocket_client_thread,
  11406. (void *)thread_data,
  11407. newctx->workerthreadids) != 0) {
  11408. mg_free((void *)thread_data);
  11409. mg_free((void *)newctx->workerthreadids);
  11410. mg_free((void *)newctx);
  11411. mg_free((void *)conn);
  11412. conn = NULL;
  11413. DEBUG_TRACE("%s",
  11414. "Websocket client connect thread could not be started\r\n");
  11415. }
  11416. #else
  11417. /* Appease "unused parameter" warnings */
  11418. (void)host;
  11419. (void)port;
  11420. (void)use_ssl;
  11421. (void)error_buffer;
  11422. (void)error_buffer_size;
  11423. (void)path;
  11424. (void)origin;
  11425. (void)user_data;
  11426. (void)data_func;
  11427. (void)close_func;
  11428. #endif
  11429. return conn;
  11430. }
  11431. static void
  11432. process_new_connection(struct mg_connection *conn)
  11433. {
  11434. if (conn && conn->ctx) {
  11435. struct mg_request_info *ri = &conn->request_info;
  11436. int keep_alive_enabled, keep_alive, discard_len;
  11437. char ebuf[100];
  11438. const char *hostend;
  11439. int reqerr, uri_type;
  11440. keep_alive_enabled =
  11441. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11442. /* Important: on new connection, reset the receiving buffer. Credit
  11443. * goes to crule42. */
  11444. conn->data_len = 0;
  11445. conn->handled_requests = 0;
  11446. do {
  11447. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11448. conn->handled_requests + 1);
  11449. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11450. /* The request sent by the client could not be understood by
  11451. * the server, or it was incomplete or a timeout. Send an
  11452. * error message and close the connection. */
  11453. if (reqerr > 0) {
  11454. /*assert(ebuf[0] != '\0');*/
  11455. send_http_error(conn, reqerr, "%s", ebuf);
  11456. }
  11457. } else if (strcmp(ri->http_version, "1.0")
  11458. && strcmp(ri->http_version, "1.1")) {
  11459. mg_snprintf(conn,
  11460. NULL, /* No truncation check for ebuf */
  11461. ebuf,
  11462. sizeof(ebuf),
  11463. "Bad HTTP version: [%s]",
  11464. ri->http_version);
  11465. send_http_error(conn, 505, "%s", ebuf);
  11466. }
  11467. if (ebuf[0] == '\0') {
  11468. uri_type = get_uri_type(conn->request_info.request_uri);
  11469. switch (uri_type) {
  11470. case 1:
  11471. /* Asterisk */
  11472. conn->request_info.local_uri = NULL;
  11473. break;
  11474. case 2:
  11475. /* relative uri */
  11476. conn->request_info.local_uri =
  11477. conn->request_info.request_uri;
  11478. break;
  11479. case 3:
  11480. case 4:
  11481. /* absolute uri (with/without port) */
  11482. hostend = get_rel_url_at_current_server(
  11483. conn->request_info.request_uri, conn);
  11484. if (hostend) {
  11485. conn->request_info.local_uri = hostend;
  11486. } else {
  11487. conn->request_info.local_uri = NULL;
  11488. }
  11489. break;
  11490. default:
  11491. mg_snprintf(conn,
  11492. NULL, /* No truncation check for ebuf */
  11493. ebuf,
  11494. sizeof(ebuf),
  11495. "Invalid URI");
  11496. send_http_error(conn, 400, "%s", ebuf);
  11497. conn->request_info.local_uri = NULL;
  11498. break;
  11499. }
  11500. /* TODO: cleanup uri, local_uri and request_uri */
  11501. conn->request_info.uri = conn->request_info.local_uri;
  11502. }
  11503. DEBUG_TRACE("http: %s, error: %s",
  11504. (ri->http_version ? ri->http_version : "none"),
  11505. (ebuf[0] ? ebuf : "none"));
  11506. if (ebuf[0] == '\0') {
  11507. if (conn->request_info.local_uri) {
  11508. /* handle request to local server */
  11509. handle_request(conn);
  11510. DEBUG_TRACE("%s", "handle_request done");
  11511. if (conn->ctx->callbacks.end_request != NULL) {
  11512. conn->ctx->callbacks.end_request(conn,
  11513. conn->status_code);
  11514. DEBUG_TRACE("%s", "end_request callback done");
  11515. }
  11516. log_access(conn);
  11517. } else {
  11518. /* TODO: handle non-local request (PROXY) */
  11519. conn->must_close = 1;
  11520. }
  11521. } else {
  11522. conn->must_close = 1;
  11523. }
  11524. if (ri->remote_user != NULL) {
  11525. mg_free((void *)ri->remote_user);
  11526. /* Important! When having connections with and without auth
  11527. * would cause double free and then crash */
  11528. ri->remote_user = NULL;
  11529. }
  11530. /* NOTE(lsm): order is important here. should_keep_alive() call
  11531. * is
  11532. * using parsed request, which will be invalid after memmove's
  11533. * below.
  11534. * Therefore, memorize should_keep_alive() result now for later
  11535. * use
  11536. * in loop exit condition. */
  11537. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11538. && (conn->content_len >= 0) && should_keep_alive(conn);
  11539. /* Discard all buffered data for this request */
  11540. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11541. && ((conn->request_len + conn->content_len)
  11542. < (int64_t)conn->data_len))
  11543. ? (int)(conn->request_len + conn->content_len)
  11544. : conn->data_len;
  11545. /*assert(discard_len >= 0);*/
  11546. if (discard_len < 0) {
  11547. DEBUG_TRACE("internal error: discard_len = %li",
  11548. (long int)discard_len);
  11549. break;
  11550. }
  11551. conn->data_len -= discard_len;
  11552. if (conn->data_len > 0) {
  11553. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11554. memmove(conn->buf,
  11555. conn->buf + discard_len,
  11556. (size_t)conn->data_len);
  11557. }
  11558. /* assert(conn->data_len >= 0); */
  11559. /* assert(conn->data_len <= conn->buf_size); */
  11560. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11561. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11562. (long int)conn->data_len,
  11563. (long int)conn->buf_size);
  11564. break;
  11565. }
  11566. conn->handled_requests++;
  11567. } while (keep_alive);
  11568. }
  11569. }
  11570. #if defined(ALTERNATIVE_QUEUE)
  11571. static void
  11572. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11573. {
  11574. unsigned int i;
  11575. for (;;) {
  11576. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11577. /* find a free worker slot and signal it */
  11578. if (ctx->client_socks[i].in_use == 0) {
  11579. ctx->client_socks[i] = *sp;
  11580. ctx->client_socks[i].in_use = 1;
  11581. event_signal(ctx->client_wait_events[i]);
  11582. return;
  11583. }
  11584. }
  11585. /* queue is full */
  11586. mg_sleep(1);
  11587. }
  11588. }
  11589. static int
  11590. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11591. {
  11592. DEBUG_TRACE("%s", "going idle");
  11593. ctx->client_socks[thread_index].in_use = 0;
  11594. event_wait(ctx->client_wait_events[thread_index]);
  11595. *sp = ctx->client_socks[thread_index];
  11596. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11597. return !ctx->stop_flag;
  11598. }
  11599. #else /* ALTERNATIVE_QUEUE */
  11600. /* Worker threads take accepted socket from the queue */
  11601. static int
  11602. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11603. {
  11604. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11605. (void)thread_index;
  11606. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11607. DEBUG_TRACE("%s", "going idle");
  11608. /* If the queue is empty, wait. We're idle at this point. */
  11609. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11610. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11611. }
  11612. /* If we're stopping, sq_head may be equal to sq_tail. */
  11613. if (ctx->sq_head > ctx->sq_tail) {
  11614. /* Copy socket from the queue and increment tail */
  11615. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11616. ctx->sq_tail++;
  11617. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11618. /* Wrap pointers if needed */
  11619. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11620. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11621. ctx->sq_head -= QUEUE_SIZE(ctx);
  11622. }
  11623. }
  11624. (void)pthread_cond_signal(&ctx->sq_empty);
  11625. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11626. return !ctx->stop_flag;
  11627. #undef QUEUE_SIZE
  11628. }
  11629. /* Master thread adds accepted socket to a queue */
  11630. static void
  11631. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11632. {
  11633. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11634. if (!ctx) {
  11635. return;
  11636. }
  11637. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11638. /* If the queue is full, wait */
  11639. while (ctx->stop_flag == 0
  11640. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11641. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11642. }
  11643. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11644. /* Copy socket to the queue and increment head */
  11645. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11646. ctx->sq_head++;
  11647. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11648. }
  11649. (void)pthread_cond_signal(&ctx->sq_full);
  11650. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11651. #undef QUEUE_SIZE
  11652. }
  11653. #endif /* ALTERNATIVE_QUEUE */
  11654. struct worker_thread_args {
  11655. struct mg_context *ctx;
  11656. int index;
  11657. };
  11658. static void *
  11659. worker_thread_run(struct worker_thread_args *thread_args)
  11660. {
  11661. struct mg_context *ctx = thread_args->ctx;
  11662. struct mg_connection *conn;
  11663. struct mg_workerTLS tls;
  11664. #if defined(MG_LEGACY_INTERFACE)
  11665. uint32_t addr;
  11666. #endif
  11667. mg_set_thread_name("worker");
  11668. tls.is_master = 0;
  11669. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11670. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11671. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11672. #endif
  11673. if (ctx->callbacks.init_thread) {
  11674. /* call init_thread for a worker thread (type 1) */
  11675. ctx->callbacks.init_thread(ctx, 1);
  11676. }
  11677. conn =
  11678. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  11679. if (conn == NULL) {
  11680. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  11681. } else {
  11682. pthread_setspecific(sTlsKey, &tls);
  11683. conn->buf_size = MAX_REQUEST_SIZE;
  11684. conn->buf = (char *)(conn + 1);
  11685. conn->ctx = ctx;
  11686. conn->thread_index = thread_args->index;
  11687. conn->request_info.user_data = ctx->user_data;
  11688. /* Allocate a mutex for this connection to allow communication both
  11689. * within the request handler and from elsewhere in the application
  11690. */
  11691. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11692. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11693. * signal sq_empty condvar to wake up the master waiting in
  11694. * produce_socket() */
  11695. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11696. conn->conn_birth_time = time(NULL);
  11697. /* Fill in IP, port info early so even if SSL setup below fails,
  11698. * error handler would have the corresponding info.
  11699. * Thanks to Johannes Winkelmann for the patch.
  11700. */
  11701. #if defined(USE_IPV6)
  11702. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11703. conn->request_info.remote_port =
  11704. ntohs(conn->client.rsa.sin6.sin6_port);
  11705. } else
  11706. #endif
  11707. {
  11708. conn->request_info.remote_port =
  11709. ntohs(conn->client.rsa.sin.sin_port);
  11710. }
  11711. sockaddr_to_string(conn->request_info.remote_addr,
  11712. sizeof(conn->request_info.remote_addr),
  11713. &conn->client.rsa);
  11714. DEBUG_TRACE("Start processing connection from %s",
  11715. conn->request_info.remote_addr);
  11716. #if defined(MG_LEGACY_INTERFACE)
  11717. /* This legacy interface only works for the IPv4 case */
  11718. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11719. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11720. #endif
  11721. conn->request_info.is_ssl = conn->client.is_ssl;
  11722. if (conn->client.is_ssl) {
  11723. #ifndef NO_SSL
  11724. /* HTTPS connection */
  11725. if (sslize(conn,
  11726. conn->ctx->ssl_ctx,
  11727. SSL_accept,
  11728. &(conn->ctx->stop_flag))) {
  11729. /* Get SSL client certificate information (if set) */
  11730. ssl_get_client_cert_info(conn);
  11731. /* process HTTPS connection */
  11732. process_new_connection(conn);
  11733. /* Free client certificate info */
  11734. if (conn->request_info.client_cert) {
  11735. mg_free(
  11736. (void *)(conn->request_info.client_cert->subject));
  11737. mg_free(
  11738. (void *)(conn->request_info.client_cert->issuer));
  11739. mg_free(
  11740. (void *)(conn->request_info.client_cert->serial));
  11741. mg_free(
  11742. (void *)(conn->request_info.client_cert->finger));
  11743. conn->request_info.client_cert->subject = 0;
  11744. conn->request_info.client_cert->issuer = 0;
  11745. conn->request_info.client_cert->serial = 0;
  11746. conn->request_info.client_cert->finger = 0;
  11747. mg_free(conn->request_info.client_cert);
  11748. conn->request_info.client_cert = 0;
  11749. }
  11750. }
  11751. #endif
  11752. } else {
  11753. /* process HTTP connection */
  11754. process_new_connection(conn);
  11755. }
  11756. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  11757. conn->request_info.remote_addr,
  11758. difftime(time(NULL), conn->conn_birth_time));
  11759. close_connection(conn);
  11760. DEBUG_TRACE("%s", "Connection closed");
  11761. }
  11762. }
  11763. pthread_setspecific(sTlsKey, NULL);
  11764. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11765. CloseHandle(tls.pthread_cond_helper_mutex);
  11766. #endif
  11767. pthread_mutex_destroy(&conn->mutex);
  11768. mg_free(conn);
  11769. DEBUG_TRACE("%s", "exiting");
  11770. return NULL;
  11771. }
  11772. /* Threads have different return types on Windows and Unix. */
  11773. #ifdef _WIN32
  11774. static unsigned __stdcall worker_thread(void *thread_func_param)
  11775. {
  11776. struct worker_thread_args *pwta =
  11777. (struct worker_thread_args *)thread_func_param;
  11778. worker_thread_run(pwta);
  11779. mg_free(thread_func_param);
  11780. return 0;
  11781. }
  11782. #else
  11783. static void *
  11784. worker_thread(void *thread_func_param)
  11785. {
  11786. struct worker_thread_args *pwta =
  11787. (struct worker_thread_args *)thread_func_param;
  11788. worker_thread_run(pwta);
  11789. mg_free(thread_func_param);
  11790. return NULL;
  11791. }
  11792. #endif /* _WIN32 */
  11793. static void
  11794. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11795. {
  11796. struct socket so;
  11797. char src_addr[IP_ADDR_STR_LEN];
  11798. socklen_t len = sizeof(so.rsa);
  11799. int on = 1;
  11800. int timeout;
  11801. if (!listener) {
  11802. return;
  11803. }
  11804. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11805. == INVALID_SOCKET) {
  11806. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11807. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11808. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11809. closesocket(so.sock);
  11810. so.sock = INVALID_SOCKET;
  11811. } else {
  11812. /* Put so socket structure into the queue */
  11813. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11814. set_close_on_exec(so.sock, fc(ctx));
  11815. so.is_ssl = listener->is_ssl;
  11816. so.ssl_redir = listener->ssl_redir;
  11817. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11818. mg_cry(fc(ctx),
  11819. "%s: getsockname() failed: %s",
  11820. __func__,
  11821. strerror(ERRNO));
  11822. }
  11823. /* Set TCP keep-alive. This is needed because if HTTP-level
  11824. * keep-alive
  11825. * is enabled, and client resets the connection, server won't get
  11826. * TCP FIN or RST and will keep the connection open forever. With
  11827. * TCP keep-alive, next keep-alive handshake will figure out that
  11828. * the client is down and will close the server end.
  11829. * Thanks to Igor Klopov who suggested the patch. */
  11830. if (setsockopt(so.sock,
  11831. SOL_SOCKET,
  11832. SO_KEEPALIVE,
  11833. (SOCK_OPT_TYPE)&on,
  11834. sizeof(on)) != 0) {
  11835. mg_cry(fc(ctx),
  11836. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11837. __func__,
  11838. strerror(ERRNO));
  11839. }
  11840. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11841. * to effectively fill up the underlying IP packet payload and
  11842. * reduce the overhead of sending lots of small buffers. However
  11843. * this hurts the server's throughput (ie. operations per second)
  11844. * when HTTP 1.1 persistent connections are used and the responses
  11845. * are relatively small (eg. less than 1400 bytes).
  11846. */
  11847. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11848. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11849. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11850. mg_cry(fc(ctx),
  11851. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11852. __func__,
  11853. strerror(ERRNO));
  11854. }
  11855. }
  11856. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11857. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11858. } else {
  11859. timeout = -1;
  11860. }
  11861. /* TODO: if non blocking sockets are used, timeouts are implemented
  11862. * differently */
  11863. // if (timeout > 0) {
  11864. // set_sock_timeout(so.sock, timeout);
  11865. //}
  11866. (void)timeout;
  11867. set_blocking_mode(so.sock, 0);
  11868. produce_socket(ctx, &so);
  11869. }
  11870. }
  11871. static void
  11872. master_thread_run(void *thread_func_param)
  11873. {
  11874. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11875. struct mg_workerTLS tls;
  11876. struct pollfd *pfd;
  11877. unsigned int i;
  11878. unsigned int workerthreadcount;
  11879. if (!ctx) {
  11880. return;
  11881. }
  11882. mg_set_thread_name("master");
  11883. /* Increase priority of the master thread */
  11884. #if defined(_WIN32)
  11885. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11886. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11887. int min_prio = sched_get_priority_min(SCHED_RR);
  11888. int max_prio = sched_get_priority_max(SCHED_RR);
  11889. if ((min_prio >= 0) && (max_prio >= 0)
  11890. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11891. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11892. struct sched_param sched_param = {0};
  11893. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11894. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11895. }
  11896. #endif
  11897. /* Initialize thread local storage */
  11898. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11899. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11900. #endif
  11901. tls.is_master = 1;
  11902. pthread_setspecific(sTlsKey, &tls);
  11903. if (ctx->callbacks.init_thread) {
  11904. /* Callback for the master thread (type 0) */
  11905. ctx->callbacks.init_thread(ctx, 0);
  11906. }
  11907. /* Server starts *now* */
  11908. ctx->start_time = time(NULL);
  11909. /* Start the server */
  11910. pfd = ctx->listening_socket_fds;
  11911. while (ctx->stop_flag == 0) {
  11912. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11913. pfd[i].fd = ctx->listening_sockets[i].sock;
  11914. pfd[i].events = POLLIN;
  11915. }
  11916. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11917. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11918. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11919. * successful poll, and POLLIN is defined as
  11920. * (POLLRDNORM | POLLRDBAND)
  11921. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11922. * pfd[i].revents == POLLIN. */
  11923. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11924. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11925. }
  11926. }
  11927. }
  11928. }
  11929. /* Here stop_flag is 1 - Initiate shutdown. */
  11930. DEBUG_TRACE("%s", "stopping workers");
  11931. /* Stop signal received: somebody called mg_stop. Quit. */
  11932. close_all_listening_sockets(ctx);
  11933. /* Wakeup workers that are waiting for connections to handle. */
  11934. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11935. #if defined(ALTERNATIVE_QUEUE)
  11936. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11937. event_signal(ctx->client_wait_events[i]);
  11938. /* Since we know all sockets, we can shutdown the connections. */
  11939. if (ctx->client_socks[i].in_use) {
  11940. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11941. }
  11942. }
  11943. #else
  11944. pthread_cond_broadcast(&ctx->sq_full);
  11945. #endif
  11946. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11947. /* Join all worker threads to avoid leaking threads. */
  11948. workerthreadcount = ctx->cfg_worker_threads;
  11949. for (i = 0; i < workerthreadcount; i++) {
  11950. if (ctx->workerthreadids[i] != 0) {
  11951. mg_join_thread(ctx->workerthreadids[i]);
  11952. }
  11953. }
  11954. #if !defined(NO_SSL)
  11955. if (ctx->ssl_ctx != NULL) {
  11956. uninitialize_ssl(ctx);
  11957. }
  11958. #endif
  11959. DEBUG_TRACE("%s", "exiting");
  11960. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11961. CloseHandle(tls.pthread_cond_helper_mutex);
  11962. #endif
  11963. pthread_setspecific(sTlsKey, NULL);
  11964. /* Signal mg_stop() that we're done.
  11965. * WARNING: This must be the very last thing this
  11966. * thread does, as ctx becomes invalid after this line. */
  11967. ctx->stop_flag = 2;
  11968. }
  11969. /* Threads have different return types on Windows and Unix. */
  11970. #ifdef _WIN32
  11971. static unsigned __stdcall master_thread(void *thread_func_param)
  11972. {
  11973. master_thread_run(thread_func_param);
  11974. return 0;
  11975. }
  11976. #else
  11977. static void *
  11978. master_thread(void *thread_func_param)
  11979. {
  11980. master_thread_run(thread_func_param);
  11981. return NULL;
  11982. }
  11983. #endif /* _WIN32 */
  11984. static void
  11985. free_context(struct mg_context *ctx)
  11986. {
  11987. int i;
  11988. struct mg_handler_info *tmp_rh;
  11989. if (ctx == NULL) {
  11990. return;
  11991. }
  11992. if (ctx->callbacks.exit_context) {
  11993. ctx->callbacks.exit_context(ctx);
  11994. }
  11995. /* All threads exited, no sync is needed. Destroy thread mutex and
  11996. * condvars
  11997. */
  11998. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  11999. #if defined(ALTERNATIVE_QUEUE)
  12000. mg_free(ctx->client_socks);
  12001. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12002. event_destroy(ctx->client_wait_events[i]);
  12003. }
  12004. mg_free(ctx->client_wait_events);
  12005. #else
  12006. (void)pthread_cond_destroy(&ctx->sq_empty);
  12007. (void)pthread_cond_destroy(&ctx->sq_full);
  12008. #endif
  12009. /* Destroy other context global data structures mutex */
  12010. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12011. #if defined(USE_TIMERS)
  12012. timers_exit(ctx);
  12013. #endif
  12014. /* Deallocate config parameters */
  12015. for (i = 0; i < NUM_OPTIONS; i++) {
  12016. if (ctx->config[i] != NULL) {
  12017. #if defined(_MSC_VER)
  12018. #pragma warning(suppress : 6001)
  12019. #endif
  12020. mg_free(ctx->config[i]);
  12021. }
  12022. }
  12023. /* Deallocate request handlers */
  12024. while (ctx->handlers) {
  12025. tmp_rh = ctx->handlers;
  12026. ctx->handlers = tmp_rh->next;
  12027. mg_free(tmp_rh->uri);
  12028. mg_free(tmp_rh);
  12029. }
  12030. #ifndef NO_SSL
  12031. /* Deallocate SSL context */
  12032. if (ctx->ssl_ctx != NULL) {
  12033. SSL_CTX_free(ctx->ssl_ctx);
  12034. }
  12035. #endif /* !NO_SSL */
  12036. /* Deallocate worker thread ID array */
  12037. if (ctx->workerthreadids != NULL) {
  12038. mg_free(ctx->workerthreadids);
  12039. }
  12040. /* Deallocate the tls variable */
  12041. if (mg_atomic_dec(&sTlsInit) == 0) {
  12042. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12043. DeleteCriticalSection(&global_log_file_lock);
  12044. #endif /* _WIN32 && !__SYMBIAN32__ */
  12045. #if !defined(_WIN32)
  12046. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12047. #endif
  12048. pthread_key_delete(sTlsKey);
  12049. #if defined(USE_LUA)
  12050. lua_exit_optional_libraries();
  12051. #endif
  12052. }
  12053. /* deallocate system name string */
  12054. mg_free(ctx->systemName);
  12055. /* Deallocate context itself */
  12056. mg_free(ctx);
  12057. }
  12058. void
  12059. mg_stop(struct mg_context *ctx)
  12060. {
  12061. pthread_t mt;
  12062. if (!ctx) {
  12063. return;
  12064. }
  12065. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12066. * two threads is not allowed. */
  12067. mt = ctx->masterthreadid;
  12068. if (mt == 0) {
  12069. return;
  12070. }
  12071. ctx->masterthreadid = 0;
  12072. /* Set stop flag, so all threads know they have to exit. */
  12073. ctx->stop_flag = 1;
  12074. /* Wait until everything has stopped. */
  12075. while (ctx->stop_flag != 2) {
  12076. (void)mg_sleep(10);
  12077. }
  12078. mg_join_thread(mt);
  12079. free_context(ctx);
  12080. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12081. (void)WSACleanup();
  12082. #endif /* _WIN32 && !__SYMBIAN32__ */
  12083. }
  12084. static void
  12085. get_system_name(char **sysName)
  12086. {
  12087. #if defined(_WIN32)
  12088. #if !defined(__SYMBIAN32__)
  12089. #if defined(_WIN32_WCE)
  12090. *sysName = mg_strdup("WinCE");
  12091. #else
  12092. char name[128];
  12093. DWORD dwVersion = 0;
  12094. DWORD dwMajorVersion = 0;
  12095. DWORD dwMinorVersion = 0;
  12096. DWORD dwBuild = 0;
  12097. #ifdef _MSC_VER
  12098. #pragma warning(push)
  12099. /* GetVersion was declared deprecated */
  12100. #pragma warning(disable : 4996)
  12101. #endif
  12102. dwVersion = GetVersion();
  12103. #ifdef _MSC_VER
  12104. #pragma warning(pop)
  12105. #endif
  12106. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12107. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12108. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12109. (void)dwBuild;
  12110. sprintf(name,
  12111. "Windows %u.%u",
  12112. (unsigned)dwMajorVersion,
  12113. (unsigned)dwMinorVersion);
  12114. *sysName = mg_strdup(name);
  12115. #endif
  12116. #else
  12117. *sysName = mg_strdup("Symbian");
  12118. #endif
  12119. #else
  12120. struct utsname name;
  12121. memset(&name, 0, sizeof(name));
  12122. uname(&name);
  12123. *sysName = mg_strdup(name.sysname);
  12124. #endif
  12125. }
  12126. struct mg_context *
  12127. mg_start(const struct mg_callbacks *callbacks,
  12128. void *user_data,
  12129. const char **options)
  12130. {
  12131. struct mg_context *ctx;
  12132. const char *name, *value, *default_value;
  12133. int idx, ok, workerthreadcount;
  12134. unsigned int i;
  12135. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12136. struct mg_workerTLS tls;
  12137. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12138. WSADATA data;
  12139. WSAStartup(MAKEWORD(2, 2), &data);
  12140. #endif /* _WIN32 && !__SYMBIAN32__ */
  12141. /* Allocate context and initialize reasonable general case defaults. */
  12142. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12143. return NULL;
  12144. }
  12145. /* Random number generator will initialize at the first call */
  12146. ctx->auth_nonce_mask =
  12147. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12148. if (mg_atomic_inc(&sTlsInit) == 1) {
  12149. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12150. InitializeCriticalSection(&global_log_file_lock);
  12151. #endif /* _WIN32 && !__SYMBIAN32__ */
  12152. #if !defined(_WIN32)
  12153. pthread_mutexattr_init(&pthread_mutex_attr);
  12154. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12155. #endif
  12156. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12157. /* Fatal error - abort start. However, this situation should
  12158. * never
  12159. * occur in practice. */
  12160. mg_atomic_dec(&sTlsInit);
  12161. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12162. mg_free(ctx);
  12163. return NULL;
  12164. }
  12165. #if defined(USE_LUA)
  12166. lua_init_optional_libraries();
  12167. #endif
  12168. } else {
  12169. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12170. * initialized. */
  12171. mg_sleep(1);
  12172. }
  12173. tls.is_master = -1;
  12174. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12175. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12176. tls.pthread_cond_helper_mutex = NULL;
  12177. #endif
  12178. pthread_setspecific(sTlsKey, &tls);
  12179. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12180. #if !defined(ALTERNATIVE_QUEUE)
  12181. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12182. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12183. #endif
  12184. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12185. if (!ok) {
  12186. /* Fatal error - abort start. However, this situation should never
  12187. * occur in practice. */
  12188. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12189. mg_free(ctx);
  12190. pthread_setspecific(sTlsKey, NULL);
  12191. return NULL;
  12192. }
  12193. if (callbacks) {
  12194. ctx->callbacks = *callbacks;
  12195. exit_callback = callbacks->exit_context;
  12196. ctx->callbacks.exit_context = 0;
  12197. }
  12198. ctx->user_data = user_data;
  12199. ctx->handlers = NULL;
  12200. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12201. ctx->shared_lua_websockets = 0;
  12202. #endif
  12203. while (options && (name = *options++) != NULL) {
  12204. if ((idx = get_option_index(name)) == -1) {
  12205. mg_cry(fc(ctx), "Invalid option: %s", name);
  12206. free_context(ctx);
  12207. pthread_setspecific(sTlsKey, NULL);
  12208. return NULL;
  12209. } else if ((value = *options++) == NULL) {
  12210. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12211. free_context(ctx);
  12212. pthread_setspecific(sTlsKey, NULL);
  12213. return NULL;
  12214. }
  12215. if (ctx->config[idx] != NULL) {
  12216. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12217. mg_free(ctx->config[idx]);
  12218. }
  12219. ctx->config[idx] = mg_strdup(value);
  12220. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12221. }
  12222. /* Set default value if needed */
  12223. for (i = 0; config_options[i].name != NULL; i++) {
  12224. default_value = config_options[i].default_value;
  12225. if (ctx->config[i] == NULL && default_value != NULL) {
  12226. ctx->config[i] = mg_strdup(default_value);
  12227. }
  12228. }
  12229. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12230. if (workerthreadcount > MAX_WORKER_THREADS) {
  12231. mg_cry(fc(ctx), "Too many worker threads");
  12232. free_context(ctx);
  12233. pthread_setspecific(sTlsKey, NULL);
  12234. return NULL;
  12235. }
  12236. if (workerthreadcount <= 0) {
  12237. mg_cry(fc(ctx), "Invalid number of worker threads");
  12238. free_context(ctx);
  12239. pthread_setspecific(sTlsKey, NULL);
  12240. return NULL;
  12241. }
  12242. #if defined(NO_FILES)
  12243. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12244. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12245. free_context(ctx);
  12246. pthread_setspecific(sTlsKey, NULL);
  12247. return NULL;
  12248. }
  12249. #endif
  12250. get_system_name(&ctx->systemName);
  12251. /* NOTE(lsm): order is important here. SSL certificates must
  12252. * be initialized before listening ports. UID must be set last. */
  12253. if (!set_gpass_option(ctx) ||
  12254. #if !defined(NO_SSL)
  12255. !set_ssl_option(ctx) ||
  12256. #endif
  12257. !set_ports_option(ctx) ||
  12258. #if !defined(_WIN32)
  12259. !set_uid_option(ctx) ||
  12260. #endif
  12261. !set_acl_option(ctx)) {
  12262. free_context(ctx);
  12263. pthread_setspecific(sTlsKey, NULL);
  12264. return NULL;
  12265. }
  12266. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12267. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12268. * won't kill the whole process. */
  12269. (void)signal(SIGPIPE, SIG_IGN);
  12270. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12271. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12272. ctx->workerthreadids =
  12273. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12274. if (ctx->workerthreadids == NULL) {
  12275. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12276. free_context(ctx);
  12277. pthread_setspecific(sTlsKey, NULL);
  12278. return NULL;
  12279. }
  12280. #if defined(ALTERNATIVE_QUEUE)
  12281. ctx->client_wait_events =
  12282. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12283. if (ctx->client_wait_events == NULL) {
  12284. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12285. mg_free(ctx->workerthreadids);
  12286. free_context(ctx);
  12287. pthread_setspecific(sTlsKey, NULL);
  12288. return NULL;
  12289. }
  12290. ctx->client_socks =
  12291. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12292. if (ctx->client_wait_events == NULL) {
  12293. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12294. mg_free(ctx->client_socks);
  12295. mg_free(ctx->workerthreadids);
  12296. free_context(ctx);
  12297. pthread_setspecific(sTlsKey, NULL);
  12298. return NULL;
  12299. }
  12300. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12301. ctx->client_wait_events[i] = event_create();
  12302. if (ctx->client_wait_events[i] == 0) {
  12303. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12304. /* TODO: clean all and exit */
  12305. }
  12306. }
  12307. #endif
  12308. #if defined(USE_TIMERS)
  12309. if (timers_init(ctx) != 0) {
  12310. mg_cry(fc(ctx), "Error creating timers");
  12311. free_context(ctx);
  12312. pthread_setspecific(sTlsKey, NULL);
  12313. return NULL;
  12314. }
  12315. #endif
  12316. /* Context has been created - init user libraries */
  12317. if (ctx->callbacks.init_context) {
  12318. ctx->callbacks.init_context(ctx);
  12319. }
  12320. ctx->callbacks.exit_context = exit_callback;
  12321. ctx->context_type = 1; /* server context */
  12322. /* Start master (listening) thread */
  12323. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12324. /* Start worker threads */
  12325. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12326. struct worker_thread_args *wta =
  12327. mg_malloc(sizeof(struct worker_thread_args));
  12328. if (wta) {
  12329. wta->ctx = ctx;
  12330. wta->index = (int)i;
  12331. }
  12332. if ((wta == NULL)
  12333. || (mg_start_thread_with_id(worker_thread,
  12334. wta,
  12335. &ctx->workerthreadids[i]) != 0)) {
  12336. /* thread was not created */
  12337. if (wta != NULL) {
  12338. mg_free(wta);
  12339. }
  12340. if (i > 0) {
  12341. mg_cry(fc(ctx),
  12342. "Cannot start worker thread %i: error %ld",
  12343. i + 1,
  12344. (long)ERRNO);
  12345. } else {
  12346. mg_cry(fc(ctx),
  12347. "Cannot create threads: error %ld",
  12348. (long)ERRNO);
  12349. free_context(ctx);
  12350. pthread_setspecific(sTlsKey, NULL);
  12351. return NULL;
  12352. }
  12353. break;
  12354. }
  12355. }
  12356. pthread_setspecific(sTlsKey, NULL);
  12357. return ctx;
  12358. }
  12359. /* Feature check API function */
  12360. unsigned
  12361. mg_check_feature(unsigned feature)
  12362. {
  12363. static const unsigned feature_set = 0
  12364. /* Set bits for available features according to API documentation.
  12365. * This bit mask is created at compile time, according to the active
  12366. * preprocessor defines. It is a single const value at runtime. */
  12367. #if !defined(NO_FILES)
  12368. | 0x0001u
  12369. #endif
  12370. #if !defined(NO_SSL)
  12371. | 0x0002u
  12372. #endif
  12373. #if !defined(NO_CGI)
  12374. | 0x0004u
  12375. #endif
  12376. #if defined(USE_IPV6)
  12377. | 0x0008u
  12378. #endif
  12379. #if defined(USE_WEBSOCKET)
  12380. | 0x0010u
  12381. #endif
  12382. #if defined(USE_LUA)
  12383. | 0x0020u
  12384. #endif
  12385. #if defined(USE_DUKTAPE)
  12386. | 0x0040u
  12387. #endif
  12388. #if !defined(NO_CACHING)
  12389. | 0x0080u
  12390. #endif
  12391. /* Set some extra bits not defined in the API documentation.
  12392. * These bits may change without further notice. */
  12393. #if defined(MG_LEGACY_INTERFACE)
  12394. | 0x8000u
  12395. #endif
  12396. #if defined(MEMORY_DEBUGGING)
  12397. | 0x0100u
  12398. #endif
  12399. #if defined(USE_TIMERS)
  12400. | 0x0200u
  12401. #endif
  12402. #if !defined(NO_NONCE_CHECK)
  12403. | 0x0400u
  12404. #endif
  12405. #if !defined(NO_POPEN)
  12406. | 0x0800u
  12407. #endif
  12408. ;
  12409. return (feature & feature_set);
  12410. }