mongoose.c 445 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166
  1. #include "mongoose.h"
  2. #ifdef MG_MODULE_LINES
  3. #line 1 "mongoose/src/internal.h"
  4. #endif
  5. /*
  6. * Copyright (c) 2014 Cesanta Software Limited
  7. * All rights reserved
  8. */
  9. #ifndef CS_MONGOOSE_SRC_INTERNAL_H_
  10. #define CS_MONGOOSE_SRC_INTERNAL_H_
  11. #ifndef MG_MALLOC
  12. #define MG_MALLOC malloc
  13. #endif
  14. #ifndef MG_CALLOC
  15. #define MG_CALLOC calloc
  16. #endif
  17. #ifndef MG_REALLOC
  18. #define MG_REALLOC realloc
  19. #endif
  20. #ifndef MG_FREE
  21. #define MG_FREE free
  22. #endif
  23. #ifndef MBUF_REALLOC
  24. #define MBUF_REALLOC MG_REALLOC
  25. #endif
  26. #ifndef MBUF_FREE
  27. #define MBUF_FREE MG_FREE
  28. #endif
  29. #ifndef MG_STRDUP
  30. #define MG_STRDUP strdup
  31. #endif
  32. #define MG_SET_PTRPTR(_ptr, _v) \
  33. do { \
  34. if (_ptr) *(_ptr) = _v; \
  35. } while (0)
  36. #ifndef MG_INTERNAL
  37. #define MG_INTERNAL static
  38. #endif
  39. #ifdef PICOTCP
  40. #define NO_LIBC
  41. #define MG_DISABLE_PFS
  42. #endif
  43. /* Amalgamated: #include "mongoose/src/net.h" */
  44. /* Amalgamated: #include "mongoose/src/http.h" */
  45. /* Amalgamated: #include "common/cs_dbg.h" */
  46. #define MG_CTL_MSG_MESSAGE_SIZE 8192
  47. /* internals that need to be accessible in unit tests */
  48. MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
  49. int proto,
  50. union socket_address *sa);
  51. MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
  52. int *proto, char *host, size_t host_len);
  53. MG_INTERNAL void mg_call(struct mg_connection *nc,
  54. mg_event_handler_t ev_handler, int ev, void *ev_data);
  55. void mg_forward(struct mg_connection *from, struct mg_connection *to);
  56. MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
  57. MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
  58. MG_INTERNAL struct mg_connection *mg_create_connection(
  59. struct mg_mgr *mgr, mg_event_handler_t callback,
  60. struct mg_add_sock_opts opts);
  61. #ifdef _WIN32
  62. /* Retur value is the same as for MultiByteToWideChar. */
  63. int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
  64. #endif
  65. struct ctl_msg {
  66. mg_event_handler_t callback;
  67. char message[MG_CTL_MSG_MESSAGE_SIZE];
  68. };
  69. #if MG_ENABLE_MQTT
  70. struct mg_mqtt_message;
  71. MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
  72. #endif
  73. /* Forward declarations for testing. */
  74. extern void *(*test_malloc)(size_t size);
  75. extern void *(*test_calloc)(size_t count, size_t size);
  76. #ifndef MIN
  77. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  78. #endif
  79. #if MG_ENABLE_HTTP
  80. struct mg_serve_http_opts;
  81. /*
  82. * Reassemble the content of the buffer (buf, blen) which should be
  83. * in the HTTP chunked encoding, by collapsing data chunks to the
  84. * beginning of the buffer.
  85. *
  86. * If chunks get reassembled, modify hm->body to point to the reassembled
  87. * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
  88. * in nc->flags, delete reassembled body from the mbuf.
  89. *
  90. * Return reassembled body size.
  91. */
  92. MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
  93. struct http_message *hm, char *buf,
  94. size_t blen);
  95. MG_INTERNAL int mg_http_common_url_parse(const char *url, const char *schema,
  96. const char *schema_tls, int *use_ssl,
  97. char **user, char **pass, char **addr,
  98. int *port_i, const char **path);
  99. #if MG_ENABLE_FILESYSTEM
  100. MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
  101. const struct mg_serve_http_opts *opts,
  102. char **local_path,
  103. struct mg_str *remainder);
  104. MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
  105. MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
  106. #endif
  107. #if MG_ENABLE_HTTP_CGI
  108. MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
  109. const struct mg_str *path_info,
  110. const struct http_message *hm,
  111. const struct mg_serve_http_opts *opts);
  112. struct mg_http_proto_data_cgi;
  113. MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d);
  114. #endif
  115. #if MG_ENABLE_HTTP_SSI
  116. MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
  117. struct http_message *hm,
  118. const char *path,
  119. const struct mg_serve_http_opts *opts);
  120. #endif
  121. #if MG_ENABLE_HTTP_WEBDAV
  122. MG_INTERNAL int mg_is_dav_request(const struct mg_str *s);
  123. MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
  124. cs_stat_t *stp, struct http_message *hm,
  125. struct mg_serve_http_opts *opts);
  126. MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path);
  127. MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
  128. struct http_message *hm);
  129. MG_INTERNAL void mg_handle_move(struct mg_connection *c,
  130. const struct mg_serve_http_opts *opts,
  131. const char *path, struct http_message *hm);
  132. MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
  133. const struct mg_serve_http_opts *opts,
  134. const char *path);
  135. MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
  136. struct http_message *hm);
  137. #endif
  138. #if MG_ENABLE_HTTP_WEBSOCKET
  139. MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev, void *ev_data);
  140. MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
  141. const struct mg_str *key);
  142. #endif
  143. #endif /* MG_ENABLE_HTTP */
  144. MG_INTERNAL int mg_get_errno(void);
  145. MG_INTERNAL void mg_close_conn(struct mg_connection *conn);
  146. MG_INTERNAL int mg_http_common_url_parse(const char *url, const char *schema,
  147. const char *schema_tls, int *use_ssl,
  148. char **user, char **pass, char **addr,
  149. int *port_i, const char **path);
  150. #if MG_ENABLE_SNTP
  151. MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
  152. struct mg_sntp_message *msg);
  153. #endif
  154. #endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
  155. #ifdef MG_MODULE_LINES
  156. #line 1 "common/cs_dbg.h"
  157. #endif
  158. /*
  159. * Copyright (c) 2014-2016 Cesanta Software Limited
  160. * All rights reserved
  161. */
  162. #ifndef CS_COMMON_CS_DBG_H_
  163. #define CS_COMMON_CS_DBG_H_
  164. /* Amalgamated: #include "common/platform.h" */
  165. #if CS_ENABLE_STDIO
  166. #include <stdio.h>
  167. #endif
  168. #ifndef CS_ENABLE_DEBUG
  169. #define CS_ENABLE_DEBUG 0
  170. #endif
  171. #ifndef CS_LOG_ENABLE_TS_DIFF
  172. #define CS_LOG_ENABLE_TS_DIFF 0
  173. #endif
  174. #ifdef __cplusplus
  175. extern "C" {
  176. #endif /* __cplusplus */
  177. enum cs_log_level {
  178. LL_NONE = -1,
  179. LL_ERROR = 0,
  180. LL_WARN = 1,
  181. LL_INFO = 2,
  182. LL_DEBUG = 3,
  183. LL_VERBOSE_DEBUG = 4,
  184. _LL_MIN = -2,
  185. _LL_MAX = 5,
  186. };
  187. void cs_log_set_level(enum cs_log_level level);
  188. #if CS_ENABLE_STDIO
  189. void cs_log_set_file(FILE *file);
  190. extern enum cs_log_level cs_log_level;
  191. void cs_log_print_prefix(const char *func);
  192. void cs_log_printf(const char *fmt, ...);
  193. #define LOG(l, x) \
  194. do { \
  195. if (cs_log_level >= l) { \
  196. cs_log_print_prefix(__func__); \
  197. cs_log_printf x; \
  198. } \
  199. } while (0)
  200. #ifndef CS_NDEBUG
  201. #define DBG(x) \
  202. do { \
  203. if (cs_log_level >= LL_VERBOSE_DEBUG) { \
  204. cs_log_print_prefix(__func__); \
  205. cs_log_printf x; \
  206. } \
  207. } while (0)
  208. #else /* NDEBUG */
  209. #define DBG(x)
  210. #endif
  211. #else /* CS_ENABLE_STDIO */
  212. #define LOG(l, x)
  213. #define DBG(x)
  214. #endif
  215. #ifdef __cplusplus
  216. }
  217. #endif /* __cplusplus */
  218. #endif /* CS_COMMON_CS_DBG_H_ */
  219. #ifdef MG_MODULE_LINES
  220. #line 1 "common/cs_dbg.c"
  221. #endif
  222. /*
  223. * Copyright (c) 2014-2016 Cesanta Software Limited
  224. * All rights reserved
  225. */
  226. /* Amalgamated: #include "common/cs_dbg.h" */
  227. #include <stdarg.h>
  228. #include <stdio.h>
  229. /* Amalgamated: #include "common/cs_time.h" */
  230. WEAK enum cs_log_level cs_log_level =
  231. #if CS_ENABLE_DEBUG
  232. LL_VERBOSE_DEBUG;
  233. #else
  234. LL_ERROR;
  235. #endif
  236. #if CS_ENABLE_STDIO
  237. WEAK FILE *cs_log_file = NULL;
  238. #if CS_LOG_ENABLE_TS_DIFF
  239. WEAK double cs_log_ts;
  240. #endif
  241. WEAK void cs_log_print_prefix(const char *func) {
  242. char prefix[21];
  243. strncpy(prefix, func, 20);
  244. prefix[20] = '\0';
  245. if (cs_log_file == NULL) cs_log_file = stderr;
  246. fprintf(cs_log_file, "%-20s ", prefix);
  247. #if CS_LOG_ENABLE_TS_DIFF
  248. {
  249. double now = cs_time();
  250. fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
  251. cs_log_ts = now;
  252. }
  253. #endif
  254. }
  255. WEAK void cs_log_printf(const char *fmt, ...) {
  256. va_list ap;
  257. va_start(ap, fmt);
  258. vfprintf(cs_log_file, fmt, ap);
  259. va_end(ap);
  260. fputc('\n', cs_log_file);
  261. fflush(cs_log_file);
  262. }
  263. WEAK void cs_log_set_file(FILE *file) {
  264. cs_log_file = file;
  265. }
  266. #endif /* CS_ENABLE_STDIO */
  267. WEAK void cs_log_set_level(enum cs_log_level level) {
  268. cs_log_level = level;
  269. #if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
  270. cs_log_ts = cs_time();
  271. #endif
  272. }
  273. #ifdef MG_MODULE_LINES
  274. #line 1 "common/base64.c"
  275. #endif
  276. /*
  277. * Copyright (c) 2014 Cesanta Software Limited
  278. * All rights reserved
  279. */
  280. #ifndef EXCLUDE_COMMON
  281. /* Amalgamated: #include "common/base64.h" */
  282. #include <string.h>
  283. /* Amalgamated: #include "common/cs_dbg.h" */
  284. /* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
  285. #define NUM_UPPERCASES ('Z' - 'A' + 1)
  286. #define NUM_LETTERS (NUM_UPPERCASES * 2)
  287. #define NUM_DIGITS ('9' - '0' + 1)
  288. /*
  289. * Emit a base64 code char.
  290. *
  291. * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
  292. */
  293. static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
  294. if (v < NUM_UPPERCASES) {
  295. ctx->b64_putc(v + 'A', ctx->user_data);
  296. } else if (v < (NUM_LETTERS)) {
  297. ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
  298. } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
  299. ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
  300. } else {
  301. ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
  302. ctx->user_data);
  303. }
  304. }
  305. static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
  306. int a, b, c;
  307. a = ctx->chunk[0];
  308. b = ctx->chunk[1];
  309. c = ctx->chunk[2];
  310. cs_base64_emit_code(ctx, a >> 2);
  311. cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
  312. if (ctx->chunk_size > 1) {
  313. cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
  314. }
  315. if (ctx->chunk_size > 2) {
  316. cs_base64_emit_code(ctx, c & 63);
  317. }
  318. }
  319. void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
  320. void *user_data) {
  321. ctx->chunk_size = 0;
  322. ctx->b64_putc = b64_putc;
  323. ctx->user_data = user_data;
  324. }
  325. void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
  326. const unsigned char *src = (const unsigned char *) str;
  327. size_t i;
  328. for (i = 0; i < len; i++) {
  329. ctx->chunk[ctx->chunk_size++] = src[i];
  330. if (ctx->chunk_size == 3) {
  331. cs_base64_emit_chunk(ctx);
  332. ctx->chunk_size = 0;
  333. }
  334. }
  335. }
  336. void cs_base64_finish(struct cs_base64_ctx *ctx) {
  337. if (ctx->chunk_size > 0) {
  338. int i;
  339. memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
  340. cs_base64_emit_chunk(ctx);
  341. for (i = 0; i < (3 - ctx->chunk_size); i++) {
  342. ctx->b64_putc('=', ctx->user_data);
  343. }
  344. }
  345. }
  346. #define BASE64_ENCODE_BODY \
  347. static const char *b64 = \
  348. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
  349. int i, j, a, b, c; \
  350. \
  351. for (i = j = 0; i < src_len; i += 3) { \
  352. a = src[i]; \
  353. b = i + 1 >= src_len ? 0 : src[i + 1]; \
  354. c = i + 2 >= src_len ? 0 : src[i + 2]; \
  355. \
  356. BASE64_OUT(b64[a >> 2]); \
  357. BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
  358. if (i + 1 < src_len) { \
  359. BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
  360. } \
  361. if (i + 2 < src_len) { \
  362. BASE64_OUT(b64[c & 63]); \
  363. } \
  364. } \
  365. \
  366. while (j % 4 != 0) { \
  367. BASE64_OUT('='); \
  368. } \
  369. BASE64_FLUSH()
  370. #define BASE64_OUT(ch) \
  371. do { \
  372. dst[j++] = (ch); \
  373. } while (0)
  374. #define BASE64_FLUSH() \
  375. do { \
  376. dst[j++] = '\0'; \
  377. } while (0)
  378. void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
  379. BASE64_ENCODE_BODY;
  380. }
  381. #undef BASE64_OUT
  382. #undef BASE64_FLUSH
  383. #if CS_ENABLE_STDIO
  384. #define BASE64_OUT(ch) \
  385. do { \
  386. fprintf(f, "%c", (ch)); \
  387. j++; \
  388. } while (0)
  389. #define BASE64_FLUSH()
  390. void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
  391. BASE64_ENCODE_BODY;
  392. }
  393. #undef BASE64_OUT
  394. #undef BASE64_FLUSH
  395. #endif /* CS_ENABLE_STDIO */
  396. /* Convert one byte of encoded base64 input stream to 6-bit chunk */
  397. static unsigned char from_b64(unsigned char ch) {
  398. /* Inverse lookup map */
  399. static const unsigned char tab[128] = {
  400. 255, 255, 255, 255,
  401. 255, 255, 255, 255, /* 0 */
  402. 255, 255, 255, 255,
  403. 255, 255, 255, 255, /* 8 */
  404. 255, 255, 255, 255,
  405. 255, 255, 255, 255, /* 16 */
  406. 255, 255, 255, 255,
  407. 255, 255, 255, 255, /* 24 */
  408. 255, 255, 255, 255,
  409. 255, 255, 255, 255, /* 32 */
  410. 255, 255, 255, 62,
  411. 255, 255, 255, 63, /* 40 */
  412. 52, 53, 54, 55,
  413. 56, 57, 58, 59, /* 48 */
  414. 60, 61, 255, 255,
  415. 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
  416. 255, 0, 1, 2,
  417. 3, 4, 5, 6, /* 64 */
  418. 7, 8, 9, 10,
  419. 11, 12, 13, 14, /* 72 */
  420. 15, 16, 17, 18,
  421. 19, 20, 21, 22, /* 80 */
  422. 23, 24, 25, 255,
  423. 255, 255, 255, 255, /* 88 */
  424. 255, 26, 27, 28,
  425. 29, 30, 31, 32, /* 96 */
  426. 33, 34, 35, 36,
  427. 37, 38, 39, 40, /* 104 */
  428. 41, 42, 43, 44,
  429. 45, 46, 47, 48, /* 112 */
  430. 49, 50, 51, 255,
  431. 255, 255, 255, 255, /* 120 */
  432. };
  433. return tab[ch & 127];
  434. }
  435. int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
  436. unsigned char a, b, c, d;
  437. int orig_len = len;
  438. char *orig_dst = dst;
  439. while (len >= 4 && (a = from_b64(s[0])) != 255 &&
  440. (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
  441. (d = from_b64(s[3])) != 255) {
  442. s += 4;
  443. len -= 4;
  444. if (a == 200 || b == 200) break; /* '=' can't be there */
  445. *dst++ = a << 2 | b >> 4;
  446. if (c == 200) break;
  447. *dst++ = b << 4 | c >> 2;
  448. if (d == 200) break;
  449. *dst++ = c << 6 | d;
  450. }
  451. *dst = 0;
  452. if (dec_len != NULL) *dec_len = (dst - orig_dst);
  453. return orig_len - len;
  454. }
  455. #endif /* EXCLUDE_COMMON */
  456. #ifdef MG_MODULE_LINES
  457. #line 1 "common/cs_dirent.h"
  458. #endif
  459. /*
  460. * Copyright (c) 2014-2016 Cesanta Software Limited
  461. * All rights reserved
  462. */
  463. #ifndef CS_COMMON_CS_DIRENT_H_
  464. #define CS_COMMON_CS_DIRENT_H_
  465. #include <limits.h>
  466. /* Amalgamated: #include "common/platform.h" */
  467. #ifdef __cplusplus
  468. extern "C" {
  469. #endif /* __cplusplus */
  470. #if CS_DEFINE_DIRENT
  471. typedef struct { int dummy; } DIR;
  472. struct dirent {
  473. int d_ino;
  474. #ifdef _WIN32
  475. char d_name[MAX_PATH];
  476. #else
  477. /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
  478. char d_name[256];
  479. #endif
  480. };
  481. DIR *opendir(const char *dir_name);
  482. int closedir(DIR *dir);
  483. struct dirent *readdir(DIR *dir);
  484. #endif /* CS_DEFINE_DIRENT */
  485. #ifdef __cplusplus
  486. }
  487. #endif /* __cplusplus */
  488. #endif /* CS_COMMON_CS_DIRENT_H_ */
  489. #ifdef MG_MODULE_LINES
  490. #line 1 "common/cs_dirent.c"
  491. #endif
  492. /*
  493. * Copyright (c) 2015 Cesanta Software Limited
  494. * All rights reserved
  495. */
  496. #ifndef EXCLUDE_COMMON
  497. /* Amalgamated: #include "common/cs_dirent.h" */
  498. /*
  499. * This file contains POSIX opendir/closedir/readdir API implementation
  500. * for systems which do not natively support it (e.g. Windows).
  501. */
  502. #ifndef MG_FREE
  503. #define MG_FREE free
  504. #endif
  505. #ifndef MG_MALLOC
  506. #define MG_MALLOC malloc
  507. #endif
  508. #ifdef _WIN32
  509. struct win32_dir {
  510. DIR d;
  511. HANDLE handle;
  512. WIN32_FIND_DATAW info;
  513. struct dirent result;
  514. };
  515. DIR *opendir(const char *name) {
  516. struct win32_dir *dir = NULL;
  517. wchar_t wpath[MAX_PATH];
  518. DWORD attrs;
  519. if (name == NULL) {
  520. SetLastError(ERROR_BAD_ARGUMENTS);
  521. } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
  522. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  523. } else {
  524. to_wchar(name, wpath, ARRAY_SIZE(wpath));
  525. attrs = GetFileAttributesW(wpath);
  526. if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  527. (void) wcscat(wpath, L"\\*");
  528. dir->handle = FindFirstFileW(wpath, &dir->info);
  529. dir->result.d_name[0] = '\0';
  530. } else {
  531. MG_FREE(dir);
  532. dir = NULL;
  533. }
  534. }
  535. return (DIR *) dir;
  536. }
  537. int closedir(DIR *d) {
  538. struct win32_dir *dir = (struct win32_dir *) d;
  539. int result = 0;
  540. if (dir != NULL) {
  541. if (dir->handle != INVALID_HANDLE_VALUE)
  542. result = FindClose(dir->handle) ? 0 : -1;
  543. MG_FREE(dir);
  544. } else {
  545. result = -1;
  546. SetLastError(ERROR_BAD_ARGUMENTS);
  547. }
  548. return result;
  549. }
  550. struct dirent *readdir(DIR *d) {
  551. struct win32_dir *dir = (struct win32_dir *) d;
  552. struct dirent *result = NULL;
  553. if (dir) {
  554. memset(&dir->result, 0, sizeof(dir->result));
  555. if (dir->handle != INVALID_HANDLE_VALUE) {
  556. result = &dir->result;
  557. (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
  558. result->d_name, sizeof(result->d_name), NULL,
  559. NULL);
  560. if (!FindNextFileW(dir->handle, &dir->info)) {
  561. (void) FindClose(dir->handle);
  562. dir->handle = INVALID_HANDLE_VALUE;
  563. }
  564. } else {
  565. SetLastError(ERROR_FILE_NOT_FOUND);
  566. }
  567. } else {
  568. SetLastError(ERROR_BAD_ARGUMENTS);
  569. }
  570. return result;
  571. }
  572. #endif
  573. #endif /* EXCLUDE_COMMON */
  574. /* ISO C requires a translation unit to contain at least one declaration */
  575. typedef int cs_dirent_dummy;
  576. #ifdef MG_MODULE_LINES
  577. #line 1 "common/cs_time.c"
  578. #endif
  579. /*
  580. * Copyright (c) 2014-2016 Cesanta Software Limited
  581. * All rights reserved
  582. */
  583. /* Amalgamated: #include "common/cs_time.h" */
  584. #ifndef _WIN32
  585. #include <stddef.h>
  586. /*
  587. * There is no sys/time.h on ARMCC.
  588. */
  589. #if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
  590. !defined(__TI_COMPILER_VERSION__) && \
  591. (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
  592. #include <sys/time.h>
  593. #endif
  594. #else
  595. #include <windows.h>
  596. #endif
  597. WEAK double cs_time(void) {
  598. double now;
  599. #ifndef _WIN32
  600. struct timeval tv;
  601. if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
  602. now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
  603. #else
  604. SYSTEMTIME sysnow;
  605. FILETIME ftime;
  606. GetLocalTime(&sysnow);
  607. SystemTimeToFileTime(&sysnow, &ftime);
  608. /*
  609. * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
  610. * This should not cause a problems in this (21th) century
  611. * 2. Windows FILETIME is a number of 100-nanosecond intervals since January
  612. * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
  613. * thus, we need to convert to seconds and adjust amount (subtract 11644473600
  614. * seconds)
  615. */
  616. now = (double) (((int64_t) ftime.dwLowDateTime +
  617. ((int64_t) ftime.dwHighDateTime << 32)) /
  618. 10000000.0) -
  619. 11644473600;
  620. #endif /* _WIN32 */
  621. return now;
  622. }
  623. #ifdef MG_MODULE_LINES
  624. #line 1 "common/cs_endian.h"
  625. #endif
  626. /*
  627. * Copyright (c) 2014-2016 Cesanta Software Limited
  628. * All rights reserved
  629. */
  630. #ifndef CS_COMMON_CS_ENDIAN_H_
  631. #define CS_COMMON_CS_ENDIAN_H_
  632. /*
  633. * clang with std=-c99 uses __LITTLE_ENDIAN, by default
  634. * while for ex, RTOS gcc - LITTLE_ENDIAN, by default
  635. * it depends on __USE_BSD, but let's have everything
  636. */
  637. #if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
  638. #define BYTE_ORDER __BYTE_ORDER
  639. #ifndef LITTLE_ENDIAN
  640. #define LITTLE_ENDIAN __LITTLE_ENDIAN
  641. #endif /* LITTLE_ENDIAN */
  642. #ifndef BIG_ENDIAN
  643. #define BIG_ENDIAN __LITTLE_ENDIAN
  644. #endif /* BIG_ENDIAN */
  645. #endif /* BYTE_ORDER */
  646. #endif /* CS_COMMON_CS_ENDIAN_H_ */
  647. #ifdef MG_MODULE_LINES
  648. #line 1 "common/md5.c"
  649. #endif
  650. /*
  651. * This code implements the MD5 message-digest algorithm.
  652. * The algorithm is due to Ron Rivest. This code was
  653. * written by Colin Plumb in 1993, no copyright is claimed.
  654. * This code is in the public domain; do with it what you wish.
  655. *
  656. * Equivalent code is available from RSA Data Security, Inc.
  657. * This code has been tested against that, and is equivalent,
  658. * except that you don't need to include two pages of legalese
  659. * with every copy.
  660. *
  661. * To compute the message digest of a chunk of bytes, declare an
  662. * MD5Context structure, pass it to MD5Init, call MD5Update as
  663. * needed on buffers full of bytes, and then call MD5Final, which
  664. * will fill a supplied 16-byte array with the digest.
  665. */
  666. /* Amalgamated: #include "common/md5.h" */
  667. /* Amalgamated: #include "common/str_util.h" */
  668. #if !defined(EXCLUDE_COMMON)
  669. #if !DISABLE_MD5
  670. /* Amalgamated: #include "common/cs_endian.h" */
  671. static void byteReverse(unsigned char *buf, unsigned longs) {
  672. /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
  673. #if BYTE_ORDER == BIG_ENDIAN
  674. do {
  675. uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
  676. ((unsigned) buf[1] << 8 | buf[0]);
  677. *(uint32_t *) buf = t;
  678. buf += 4;
  679. } while (--longs);
  680. #else
  681. (void) buf;
  682. (void) longs;
  683. #endif
  684. }
  685. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  686. #define F2(x, y, z) F1(z, x, y)
  687. #define F3(x, y, z) (x ^ y ^ z)
  688. #define F4(x, y, z) (y ^ (x | ~z))
  689. #define MD5STEP(f, w, x, y, z, data, s) \
  690. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  691. /*
  692. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  693. * initialization constants.
  694. */
  695. void MD5_Init(MD5_CTX *ctx) {
  696. ctx->buf[0] = 0x67452301;
  697. ctx->buf[1] = 0xefcdab89;
  698. ctx->buf[2] = 0x98badcfe;
  699. ctx->buf[3] = 0x10325476;
  700. ctx->bits[0] = 0;
  701. ctx->bits[1] = 0;
  702. }
  703. static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
  704. register uint32_t a, b, c, d;
  705. a = buf[0];
  706. b = buf[1];
  707. c = buf[2];
  708. d = buf[3];
  709. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  710. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  711. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  712. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  713. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  714. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  715. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  716. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  717. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  718. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  719. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  720. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  721. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  722. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  723. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  724. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  725. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  726. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  727. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  728. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  729. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  730. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  731. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  732. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  733. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  734. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  735. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  736. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  737. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  738. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  739. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  740. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  741. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  742. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  743. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  744. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  745. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  746. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  747. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  748. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  749. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  750. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  751. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  752. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  753. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  754. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  755. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  756. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  757. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  758. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  759. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  760. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  761. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  762. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  763. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  764. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  765. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  766. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  767. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  768. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  769. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  770. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  771. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  772. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  773. buf[0] += a;
  774. buf[1] += b;
  775. buf[2] += c;
  776. buf[3] += d;
  777. }
  778. void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) {
  779. uint32_t t;
  780. t = ctx->bits[0];
  781. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  782. ctx->bits[1] += (uint32_t) len >> 29;
  783. t = (t >> 3) & 0x3f;
  784. if (t) {
  785. unsigned char *p = (unsigned char *) ctx->in + t;
  786. t = 64 - t;
  787. if (len < t) {
  788. memcpy(p, buf, len);
  789. return;
  790. }
  791. memcpy(p, buf, t);
  792. byteReverse(ctx->in, 16);
  793. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  794. buf += t;
  795. len -= t;
  796. }
  797. while (len >= 64) {
  798. memcpy(ctx->in, buf, 64);
  799. byteReverse(ctx->in, 16);
  800. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  801. buf += 64;
  802. len -= 64;
  803. }
  804. memcpy(ctx->in, buf, len);
  805. }
  806. void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) {
  807. unsigned count;
  808. unsigned char *p;
  809. uint32_t *a;
  810. count = (ctx->bits[0] >> 3) & 0x3F;
  811. p = ctx->in + count;
  812. *p++ = 0x80;
  813. count = 64 - 1 - count;
  814. if (count < 8) {
  815. memset(p, 0, count);
  816. byteReverse(ctx->in, 16);
  817. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  818. memset(ctx->in, 0, 56);
  819. } else {
  820. memset(p, 0, count - 8);
  821. }
  822. byteReverse(ctx->in, 14);
  823. a = (uint32_t *) ctx->in;
  824. a[14] = ctx->bits[0];
  825. a[15] = ctx->bits[1];
  826. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  827. byteReverse((unsigned char *) ctx->buf, 4);
  828. memcpy(digest, ctx->buf, 16);
  829. memset((char *) ctx, 0, sizeof(*ctx));
  830. }
  831. #endif /* DISABLE_MD5 */
  832. char *cs_md5(char buf[33], ...) {
  833. unsigned char hash[16];
  834. const unsigned char *p;
  835. va_list ap;
  836. MD5_CTX ctx;
  837. MD5_Init(&ctx);
  838. va_start(ap, buf);
  839. while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
  840. size_t len = va_arg(ap, size_t);
  841. MD5_Update(&ctx, p, len);
  842. }
  843. va_end(ap);
  844. MD5_Final(hash, &ctx);
  845. cs_to_hex(buf, hash, sizeof(hash));
  846. return buf;
  847. }
  848. #endif /* EXCLUDE_COMMON */
  849. #ifdef MG_MODULE_LINES
  850. #line 1 "common/mbuf.c"
  851. #endif
  852. /*
  853. * Copyright (c) 2014 Cesanta Software Limited
  854. * All rights reserved
  855. */
  856. #ifndef EXCLUDE_COMMON
  857. #include <assert.h>
  858. #include <string.h>
  859. /* Amalgamated: #include "common/mbuf.h" */
  860. #ifndef MBUF_REALLOC
  861. #define MBUF_REALLOC realloc
  862. #endif
  863. #ifndef MBUF_FREE
  864. #define MBUF_FREE free
  865. #endif
  866. WEAK void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
  867. mbuf->len = mbuf->size = 0;
  868. mbuf->buf = NULL;
  869. mbuf_resize(mbuf, initial_size);
  870. }
  871. WEAK void mbuf_free(struct mbuf *mbuf) {
  872. if (mbuf->buf != NULL) {
  873. MBUF_FREE(mbuf->buf);
  874. mbuf_init(mbuf, 0);
  875. }
  876. }
  877. WEAK void mbuf_resize(struct mbuf *a, size_t new_size) {
  878. if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
  879. char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
  880. /*
  881. * In case realloc fails, there's not much we can do, except keep things as
  882. * they are. Note that NULL is a valid return value from realloc when
  883. * size == 0, but that is covered too.
  884. */
  885. if (buf == NULL && new_size != 0) return;
  886. a->buf = buf;
  887. a->size = new_size;
  888. }
  889. }
  890. WEAK void mbuf_trim(struct mbuf *mbuf) {
  891. mbuf_resize(mbuf, mbuf->len);
  892. }
  893. WEAK size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
  894. char *p = NULL;
  895. assert(a != NULL);
  896. assert(a->len <= a->size);
  897. assert(off <= a->len);
  898. /* check overflow */
  899. if (~(size_t) 0 - (size_t) a->buf < len) return 0;
  900. if (a->len + len <= a->size) {
  901. memmove(a->buf + off + len, a->buf + off, a->len - off);
  902. if (buf != NULL) {
  903. memcpy(a->buf + off, buf, len);
  904. }
  905. a->len += len;
  906. } else {
  907. size_t new_size = (size_t)((a->len + len) * MBUF_SIZE_MULTIPLIER);
  908. if ((p = (char *) MBUF_REALLOC(a->buf, new_size)) != NULL) {
  909. a->buf = p;
  910. memmove(a->buf + off + len, a->buf + off, a->len - off);
  911. if (buf != NULL) memcpy(a->buf + off, buf, len);
  912. a->len += len;
  913. a->size = new_size;
  914. } else {
  915. len = 0;
  916. }
  917. }
  918. return len;
  919. }
  920. WEAK size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
  921. return mbuf_insert(a, a->len, buf, len);
  922. }
  923. WEAK void mbuf_remove(struct mbuf *mb, size_t n) {
  924. if (n > 0 && n <= mb->len) {
  925. memmove(mb->buf, mb->buf + n, mb->len - n);
  926. mb->len -= n;
  927. }
  928. }
  929. #endif /* EXCLUDE_COMMON */
  930. #ifdef MG_MODULE_LINES
  931. #line 1 "common/mg_str.c"
  932. #endif
  933. /*
  934. * Copyright (c) 2014-2016 Cesanta Software Limited
  935. * All rights reserved
  936. */
  937. /* Amalgamated: #include "common/mg_str.h" */
  938. #include <stdlib.h>
  939. #include <string.h>
  940. WEAK int mg_ncasecmp(const char *s1, const char *s2, size_t len);
  941. WEAK struct mg_str mg_mk_str(const char *s) {
  942. struct mg_str ret = {s, 0};
  943. if (s != NULL) ret.len = strlen(s);
  944. return ret;
  945. }
  946. WEAK struct mg_str mg_mk_str_n(const char *s, size_t len) {
  947. struct mg_str ret = {s, len};
  948. return ret;
  949. }
  950. WEAK int mg_vcmp(const struct mg_str *str1, const char *str2) {
  951. size_t n2 = strlen(str2), n1 = str1->len;
  952. int r = memcmp(str1->p, str2, (n1 < n2) ? n1 : n2);
  953. if (r == 0) {
  954. return n1 - n2;
  955. }
  956. return r;
  957. }
  958. WEAK int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
  959. size_t n2 = strlen(str2), n1 = str1->len;
  960. int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
  961. if (r == 0) {
  962. return n1 - n2;
  963. }
  964. return r;
  965. }
  966. WEAK struct mg_str mg_strdup(const struct mg_str s) {
  967. struct mg_str r = {NULL, 0};
  968. if (s.len > 0 && s.p != NULL) {
  969. r.p = (char *) MG_MALLOC(s.len);
  970. if (r.p != NULL) {
  971. memcpy((char *) r.p, s.p, s.len);
  972. r.len = s.len;
  973. }
  974. }
  975. return r;
  976. }
  977. WEAK int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  978. size_t i = 0;
  979. while (i < str1.len && i < str2.len) {
  980. if (str1.p[i] < str2.p[i]) return -1;
  981. if (str1.p[i] > str2.p[i]) return 1;
  982. i++;
  983. }
  984. if (i < str1.len) return 1;
  985. if (i < str2.len) return -1;
  986. return 0;
  987. }
  988. WEAK int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
  989. struct mg_str s1 = str1;
  990. struct mg_str s2 = str2;
  991. if (s1.len > n) {
  992. s1.len = n;
  993. }
  994. if (s2.len > n) {
  995. s2.len = n;
  996. }
  997. return mg_strcmp(s1, s2);
  998. }
  999. #ifdef MG_MODULE_LINES
  1000. #line 1 "common/sha1.c"
  1001. #endif
  1002. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  1003. /* 100% Public Domain */
  1004. /* Amalgamated: #include "common/sha1.h" */
  1005. #if !DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
  1006. /* Amalgamated: #include "common/cs_endian.h" */
  1007. #define SHA1HANDSOFF
  1008. #if defined(__sun)
  1009. /* Amalgamated: #include "common/solarisfixes.h" */
  1010. #endif
  1011. union char64long16 {
  1012. unsigned char c[64];
  1013. uint32_t l[16];
  1014. };
  1015. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  1016. static uint32_t blk0(union char64long16 *block, int i) {
  1017. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  1018. #if BYTE_ORDER == LITTLE_ENDIAN
  1019. block->l[i] =
  1020. (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
  1021. #endif
  1022. return block->l[i];
  1023. }
  1024. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  1025. #undef blk
  1026. #undef R0
  1027. #undef R1
  1028. #undef R2
  1029. #undef R3
  1030. #undef R4
  1031. #define blk(i) \
  1032. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  1033. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  1034. 1))
  1035. #define R0(v, w, x, y, z, i) \
  1036. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  1037. w = rol(w, 30);
  1038. #define R1(v, w, x, y, z, i) \
  1039. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  1040. w = rol(w, 30);
  1041. #define R2(v, w, x, y, z, i) \
  1042. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  1043. w = rol(w, 30);
  1044. #define R3(v, w, x, y, z, i) \
  1045. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  1046. w = rol(w, 30);
  1047. #define R4(v, w, x, y, z, i) \
  1048. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  1049. w = rol(w, 30);
  1050. void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
  1051. uint32_t a, b, c, d, e;
  1052. union char64long16 block[1];
  1053. memcpy(block, buffer, 64);
  1054. a = state[0];
  1055. b = state[1];
  1056. c = state[2];
  1057. d = state[3];
  1058. e = state[4];
  1059. R0(a, b, c, d, e, 0);
  1060. R0(e, a, b, c, d, 1);
  1061. R0(d, e, a, b, c, 2);
  1062. R0(c, d, e, a, b, 3);
  1063. R0(b, c, d, e, a, 4);
  1064. R0(a, b, c, d, e, 5);
  1065. R0(e, a, b, c, d, 6);
  1066. R0(d, e, a, b, c, 7);
  1067. R0(c, d, e, a, b, 8);
  1068. R0(b, c, d, e, a, 9);
  1069. R0(a, b, c, d, e, 10);
  1070. R0(e, a, b, c, d, 11);
  1071. R0(d, e, a, b, c, 12);
  1072. R0(c, d, e, a, b, 13);
  1073. R0(b, c, d, e, a, 14);
  1074. R0(a, b, c, d, e, 15);
  1075. R1(e, a, b, c, d, 16);
  1076. R1(d, e, a, b, c, 17);
  1077. R1(c, d, e, a, b, 18);
  1078. R1(b, c, d, e, a, 19);
  1079. R2(a, b, c, d, e, 20);
  1080. R2(e, a, b, c, d, 21);
  1081. R2(d, e, a, b, c, 22);
  1082. R2(c, d, e, a, b, 23);
  1083. R2(b, c, d, e, a, 24);
  1084. R2(a, b, c, d, e, 25);
  1085. R2(e, a, b, c, d, 26);
  1086. R2(d, e, a, b, c, 27);
  1087. R2(c, d, e, a, b, 28);
  1088. R2(b, c, d, e, a, 29);
  1089. R2(a, b, c, d, e, 30);
  1090. R2(e, a, b, c, d, 31);
  1091. R2(d, e, a, b, c, 32);
  1092. R2(c, d, e, a, b, 33);
  1093. R2(b, c, d, e, a, 34);
  1094. R2(a, b, c, d, e, 35);
  1095. R2(e, a, b, c, d, 36);
  1096. R2(d, e, a, b, c, 37);
  1097. R2(c, d, e, a, b, 38);
  1098. R2(b, c, d, e, a, 39);
  1099. R3(a, b, c, d, e, 40);
  1100. R3(e, a, b, c, d, 41);
  1101. R3(d, e, a, b, c, 42);
  1102. R3(c, d, e, a, b, 43);
  1103. R3(b, c, d, e, a, 44);
  1104. R3(a, b, c, d, e, 45);
  1105. R3(e, a, b, c, d, 46);
  1106. R3(d, e, a, b, c, 47);
  1107. R3(c, d, e, a, b, 48);
  1108. R3(b, c, d, e, a, 49);
  1109. R3(a, b, c, d, e, 50);
  1110. R3(e, a, b, c, d, 51);
  1111. R3(d, e, a, b, c, 52);
  1112. R3(c, d, e, a, b, 53);
  1113. R3(b, c, d, e, a, 54);
  1114. R3(a, b, c, d, e, 55);
  1115. R3(e, a, b, c, d, 56);
  1116. R3(d, e, a, b, c, 57);
  1117. R3(c, d, e, a, b, 58);
  1118. R3(b, c, d, e, a, 59);
  1119. R4(a, b, c, d, e, 60);
  1120. R4(e, a, b, c, d, 61);
  1121. R4(d, e, a, b, c, 62);
  1122. R4(c, d, e, a, b, 63);
  1123. R4(b, c, d, e, a, 64);
  1124. R4(a, b, c, d, e, 65);
  1125. R4(e, a, b, c, d, 66);
  1126. R4(d, e, a, b, c, 67);
  1127. R4(c, d, e, a, b, 68);
  1128. R4(b, c, d, e, a, 69);
  1129. R4(a, b, c, d, e, 70);
  1130. R4(e, a, b, c, d, 71);
  1131. R4(d, e, a, b, c, 72);
  1132. R4(c, d, e, a, b, 73);
  1133. R4(b, c, d, e, a, 74);
  1134. R4(a, b, c, d, e, 75);
  1135. R4(e, a, b, c, d, 76);
  1136. R4(d, e, a, b, c, 77);
  1137. R4(c, d, e, a, b, 78);
  1138. R4(b, c, d, e, a, 79);
  1139. state[0] += a;
  1140. state[1] += b;
  1141. state[2] += c;
  1142. state[3] += d;
  1143. state[4] += e;
  1144. /* Erase working structures. The order of operations is important,
  1145. * used to ensure that compiler doesn't optimize those out. */
  1146. memset(block, 0, sizeof(block));
  1147. a = b = c = d = e = 0;
  1148. (void) a;
  1149. (void) b;
  1150. (void) c;
  1151. (void) d;
  1152. (void) e;
  1153. }
  1154. void cs_sha1_init(cs_sha1_ctx *context) {
  1155. context->state[0] = 0x67452301;
  1156. context->state[1] = 0xEFCDAB89;
  1157. context->state[2] = 0x98BADCFE;
  1158. context->state[3] = 0x10325476;
  1159. context->state[4] = 0xC3D2E1F0;
  1160. context->count[0] = context->count[1] = 0;
  1161. }
  1162. void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
  1163. uint32_t len) {
  1164. uint32_t i, j;
  1165. j = context->count[0];
  1166. if ((context->count[0] += len << 3) < j) context->count[1]++;
  1167. context->count[1] += (len >> 29);
  1168. j = (j >> 3) & 63;
  1169. if ((j + len) > 63) {
  1170. memcpy(&context->buffer[j], data, (i = 64 - j));
  1171. cs_sha1_transform(context->state, context->buffer);
  1172. for (; i + 63 < len; i += 64) {
  1173. cs_sha1_transform(context->state, &data[i]);
  1174. }
  1175. j = 0;
  1176. } else
  1177. i = 0;
  1178. memcpy(&context->buffer[j], &data[i], len - i);
  1179. }
  1180. void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
  1181. unsigned i;
  1182. unsigned char finalcount[8], c;
  1183. for (i = 0; i < 8; i++) {
  1184. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  1185. ((3 - (i & 3)) * 8)) &
  1186. 255);
  1187. }
  1188. c = 0200;
  1189. cs_sha1_update(context, &c, 1);
  1190. while ((context->count[0] & 504) != 448) {
  1191. c = 0000;
  1192. cs_sha1_update(context, &c, 1);
  1193. }
  1194. cs_sha1_update(context, finalcount, 8);
  1195. for (i = 0; i < 20; i++) {
  1196. digest[i] =
  1197. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  1198. }
  1199. memset(context, '\0', sizeof(*context));
  1200. memset(&finalcount, '\0', sizeof(finalcount));
  1201. }
  1202. void cs_hmac_sha1(const unsigned char *key, size_t keylen,
  1203. const unsigned char *data, size_t datalen,
  1204. unsigned char out[20]) {
  1205. cs_sha1_ctx ctx;
  1206. unsigned char buf1[64], buf2[64], tmp_key[20], i;
  1207. if (keylen > sizeof(buf1)) {
  1208. cs_sha1_init(&ctx);
  1209. cs_sha1_update(&ctx, key, keylen);
  1210. cs_sha1_final(tmp_key, &ctx);
  1211. key = tmp_key;
  1212. keylen = sizeof(tmp_key);
  1213. }
  1214. memset(buf1, 0, sizeof(buf1));
  1215. memset(buf2, 0, sizeof(buf2));
  1216. memcpy(buf1, key, keylen);
  1217. memcpy(buf2, key, keylen);
  1218. for (i = 0; i < sizeof(buf1); i++) {
  1219. buf1[i] ^= 0x36;
  1220. buf2[i] ^= 0x5c;
  1221. }
  1222. cs_sha1_init(&ctx);
  1223. cs_sha1_update(&ctx, buf1, sizeof(buf1));
  1224. cs_sha1_update(&ctx, data, datalen);
  1225. cs_sha1_final(out, &ctx);
  1226. cs_sha1_init(&ctx);
  1227. cs_sha1_update(&ctx, buf2, sizeof(buf2));
  1228. cs_sha1_update(&ctx, out, 20);
  1229. cs_sha1_final(out, &ctx);
  1230. }
  1231. #endif /* EXCLUDE_COMMON */
  1232. #ifdef MG_MODULE_LINES
  1233. #line 1 "common/str_util.c"
  1234. #endif
  1235. /*
  1236. * Copyright (c) 2015 Cesanta Software Limited
  1237. * All rights reserved
  1238. */
  1239. #ifndef EXCLUDE_COMMON
  1240. /* Amalgamated: #include "common/platform.h" */
  1241. /* Amalgamated: #include "common/str_util.h" */
  1242. #ifndef C_DISABLE_BUILTIN_SNPRINTF
  1243. #define C_DISABLE_BUILTIN_SNPRINTF 0
  1244. #endif
  1245. #ifndef MG_MALLOC
  1246. #define MG_MALLOC malloc
  1247. #endif
  1248. #ifndef MG_FREE
  1249. #define MG_FREE free
  1250. #endif
  1251. WEAK size_t c_strnlen(const char *s, size_t maxlen) {
  1252. size_t l = 0;
  1253. for (; l < maxlen && s[l] != '\0'; l++) {
  1254. }
  1255. return l;
  1256. }
  1257. #define C_SNPRINTF_APPEND_CHAR(ch) \
  1258. do { \
  1259. if (i < (int) buf_size) buf[i] = ch; \
  1260. i++; \
  1261. } while (0)
  1262. #define C_SNPRINTF_FLAG_ZERO 1
  1263. #if C_DISABLE_BUILTIN_SNPRINTF
  1264. WEAK int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
  1265. return vsnprintf(buf, buf_size, fmt, ap);
  1266. }
  1267. #else
  1268. static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
  1269. int field_width) {
  1270. char tmp[40];
  1271. int i = 0, k = 0, neg = 0;
  1272. if (num < 0) {
  1273. neg++;
  1274. num = -num;
  1275. }
  1276. /* Print into temporary buffer - in reverse order */
  1277. do {
  1278. int rem = num % base;
  1279. if (rem < 10) {
  1280. tmp[k++] = '0' + rem;
  1281. } else {
  1282. tmp[k++] = 'a' + (rem - 10);
  1283. }
  1284. num /= base;
  1285. } while (num > 0);
  1286. /* Zero padding */
  1287. if (flags && C_SNPRINTF_FLAG_ZERO) {
  1288. while (k < field_width && k < (int) sizeof(tmp) - 1) {
  1289. tmp[k++] = '0';
  1290. }
  1291. }
  1292. /* And sign */
  1293. if (neg) {
  1294. tmp[k++] = '-';
  1295. }
  1296. /* Now output */
  1297. while (--k >= 0) {
  1298. C_SNPRINTF_APPEND_CHAR(tmp[k]);
  1299. }
  1300. return i;
  1301. }
  1302. WEAK int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
  1303. int ch, i = 0, len_mod, flags, precision, field_width;
  1304. while ((ch = *fmt++) != '\0') {
  1305. if (ch != '%') {
  1306. C_SNPRINTF_APPEND_CHAR(ch);
  1307. } else {
  1308. /*
  1309. * Conversion specification:
  1310. * zero or more flags (one of: # 0 - <space> + ')
  1311. * an optional minimum field width (digits)
  1312. * an optional precision (. followed by digits, or *)
  1313. * an optional length modifier (one of: hh h l ll L q j z t)
  1314. * conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
  1315. */
  1316. flags = field_width = precision = len_mod = 0;
  1317. /* Flags. only zero-pad flag is supported. */
  1318. if (*fmt == '0') {
  1319. flags |= C_SNPRINTF_FLAG_ZERO;
  1320. }
  1321. /* Field width */
  1322. while (*fmt >= '0' && *fmt <= '9') {
  1323. field_width *= 10;
  1324. field_width += *fmt++ - '0';
  1325. }
  1326. /* Dynamic field width */
  1327. if (*fmt == '*') {
  1328. field_width = va_arg(ap, int);
  1329. fmt++;
  1330. }
  1331. /* Precision */
  1332. if (*fmt == '.') {
  1333. fmt++;
  1334. if (*fmt == '*') {
  1335. precision = va_arg(ap, int);
  1336. fmt++;
  1337. } else {
  1338. while (*fmt >= '0' && *fmt <= '9') {
  1339. precision *= 10;
  1340. precision += *fmt++ - '0';
  1341. }
  1342. }
  1343. }
  1344. /* Length modifier */
  1345. switch (*fmt) {
  1346. case 'h':
  1347. case 'l':
  1348. case 'L':
  1349. case 'I':
  1350. case 'q':
  1351. case 'j':
  1352. case 'z':
  1353. case 't':
  1354. len_mod = *fmt++;
  1355. if (*fmt == 'h') {
  1356. len_mod = 'H';
  1357. fmt++;
  1358. }
  1359. if (*fmt == 'l') {
  1360. len_mod = 'q';
  1361. fmt++;
  1362. }
  1363. break;
  1364. }
  1365. ch = *fmt++;
  1366. if (ch == 's') {
  1367. const char *s = va_arg(ap, const char *); /* Always fetch parameter */
  1368. int j;
  1369. int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
  1370. for (j = 0; j < pad; j++) {
  1371. C_SNPRINTF_APPEND_CHAR(' ');
  1372. }
  1373. /* `s` may be NULL in case of %.*s */
  1374. if (s != NULL) {
  1375. /* Ignore negative and 0 precisions */
  1376. for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
  1377. C_SNPRINTF_APPEND_CHAR(s[j]);
  1378. }
  1379. }
  1380. } else if (ch == 'c') {
  1381. ch = va_arg(ap, int); /* Always fetch parameter */
  1382. C_SNPRINTF_APPEND_CHAR(ch);
  1383. } else if (ch == 'd' && len_mod == 0) {
  1384. i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
  1385. field_width);
  1386. } else if (ch == 'd' && len_mod == 'l') {
  1387. i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
  1388. field_width);
  1389. #ifdef SSIZE_MAX
  1390. } else if (ch == 'd' && len_mod == 'z') {
  1391. i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
  1392. field_width);
  1393. #endif
  1394. } else if (ch == 'd' && len_mod == 'q') {
  1395. i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
  1396. field_width);
  1397. } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
  1398. i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
  1399. ch == 'x' ? 16 : 10, flags, field_width);
  1400. } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
  1401. i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
  1402. ch == 'x' ? 16 : 10, flags, field_width);
  1403. } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
  1404. i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
  1405. ch == 'x' ? 16 : 10, flags, field_width);
  1406. } else if (ch == 'p') {
  1407. unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
  1408. C_SNPRINTF_APPEND_CHAR('0');
  1409. C_SNPRINTF_APPEND_CHAR('x');
  1410. i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
  1411. } else {
  1412. #ifndef NO_LIBC
  1413. /*
  1414. * TODO(lsm): abort is not nice in a library, remove it
  1415. * Also, ESP8266 SDK doesn't have it
  1416. */
  1417. abort();
  1418. #endif
  1419. }
  1420. }
  1421. }
  1422. /* Zero-terminate the result */
  1423. if (buf_size > 0) {
  1424. buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
  1425. }
  1426. return i;
  1427. }
  1428. #endif
  1429. WEAK int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
  1430. int result;
  1431. va_list ap;
  1432. va_start(ap, fmt);
  1433. result = c_vsnprintf(buf, buf_size, fmt, ap);
  1434. va_end(ap);
  1435. return result;
  1436. }
  1437. #ifdef _WIN32
  1438. int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1439. int ret;
  1440. char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
  1441. strncpy(buf, path, sizeof(buf));
  1442. buf[sizeof(buf) - 1] = '\0';
  1443. /* Trim trailing slashes. Leave backslash for paths like "X:\" */
  1444. p = buf + strlen(buf) - 1;
  1445. while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
  1446. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1447. ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1448. /*
  1449. * Convert back to Unicode. If doubly-converted string does not match the
  1450. * original, something is fishy, reject.
  1451. */
  1452. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1453. NULL, NULL);
  1454. if (strcmp(buf, buf2) != 0) {
  1455. wbuf[0] = L'\0';
  1456. ret = 0;
  1457. }
  1458. return ret;
  1459. }
  1460. #endif /* _WIN32 */
  1461. /* The simplest O(mn) algorithm. Better implementation are GPLed */
  1462. WEAK const char *c_strnstr(const char *s, const char *find, size_t slen) {
  1463. size_t find_length = strlen(find);
  1464. size_t i;
  1465. for (i = 0; i < slen; i++) {
  1466. if (i + find_length > slen) {
  1467. return NULL;
  1468. }
  1469. if (strncmp(&s[i], find, find_length) == 0) {
  1470. return &s[i];
  1471. }
  1472. }
  1473. return NULL;
  1474. }
  1475. #if CS_ENABLE_STRDUP
  1476. WEAK char *strdup(const char *src) {
  1477. size_t len = strlen(src) + 1;
  1478. char *ret = MG_MALLOC(len);
  1479. if (ret != NULL) {
  1480. strcpy(ret, src);
  1481. }
  1482. return ret;
  1483. }
  1484. #endif
  1485. WEAK void cs_to_hex(char *to, const unsigned char *p, size_t len) {
  1486. static const char *hex = "0123456789abcdef";
  1487. for (; len--; p++) {
  1488. *to++ = hex[p[0] >> 4];
  1489. *to++ = hex[p[0] & 0x0f];
  1490. }
  1491. *to = '\0';
  1492. }
  1493. static int fourbit(int ch) {
  1494. if (ch >= '0' && ch <= '9') {
  1495. return ch - '0';
  1496. } else if (ch >= 'a' && ch <= 'f') {
  1497. return ch - 'a' + 10;
  1498. } else if (ch >= 'A' && ch <= 'F') {
  1499. return ch - 'A' + 10;
  1500. }
  1501. return 0;
  1502. }
  1503. WEAK void cs_from_hex(char *to, const char *p, size_t len) {
  1504. size_t i;
  1505. for (i = 0; i < len; i += 2) {
  1506. *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
  1507. }
  1508. *to = '\0';
  1509. }
  1510. #if CS_ENABLE_TO64
  1511. WEAK int64_t cs_to64(const char *s) {
  1512. int64_t result = 0;
  1513. int64_t neg = 1;
  1514. while (*s && isspace((unsigned char) *s)) s++;
  1515. if (*s == '-') {
  1516. neg = -1;
  1517. s++;
  1518. }
  1519. while (isdigit((unsigned char) *s)) {
  1520. result *= 10;
  1521. result += (*s - '0');
  1522. s++;
  1523. }
  1524. return result * neg;
  1525. }
  1526. #endif
  1527. static int str_util_lowercase(const char *s) {
  1528. return tolower(*(const unsigned char *) s);
  1529. }
  1530. WEAK int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  1531. int diff = 0;
  1532. if (len > 0) do {
  1533. diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
  1534. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1535. return diff;
  1536. }
  1537. WEAK int mg_casecmp(const char *s1, const char *s2) {
  1538. return mg_ncasecmp(s1, s2, (size_t) ~0);
  1539. }
  1540. WEAK int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
  1541. int ret;
  1542. va_list ap;
  1543. va_start(ap, fmt);
  1544. ret = mg_avprintf(buf, size, fmt, ap);
  1545. va_end(ap);
  1546. return ret;
  1547. }
  1548. WEAK int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
  1549. va_list ap_copy;
  1550. int len;
  1551. va_copy(ap_copy, ap);
  1552. len = vsnprintf(*buf, size, fmt, ap_copy);
  1553. va_end(ap_copy);
  1554. if (len < 0) {
  1555. /* eCos and Windows are not standard-compliant and return -1 when
  1556. * the buffer is too small. Keep allocating larger buffers until we
  1557. * succeed or out of memory. */
  1558. *buf = NULL; /* LCOV_EXCL_START */
  1559. while (len < 0) {
  1560. MG_FREE(*buf);
  1561. size *= 2;
  1562. if ((*buf = (char *) MG_MALLOC(size)) == NULL) break;
  1563. va_copy(ap_copy, ap);
  1564. len = vsnprintf(*buf, size, fmt, ap_copy);
  1565. va_end(ap_copy);
  1566. }
  1567. /* LCOV_EXCL_STOP */
  1568. } else if (len >= (int) size) {
  1569. /* Standard-compliant code path. Allocate a buffer that is large enough. */
  1570. if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
  1571. len = -1; /* LCOV_EXCL_LINE */
  1572. } else { /* LCOV_EXCL_LINE */
  1573. va_copy(ap_copy, ap);
  1574. len = vsnprintf(*buf, len + 1, fmt, ap_copy);
  1575. va_end(ap_copy);
  1576. }
  1577. }
  1578. return len;
  1579. }
  1580. #endif /* EXCLUDE_COMMON */
  1581. #ifdef MG_MODULE_LINES
  1582. #line 1 "mongoose/src/tun.h"
  1583. #endif
  1584. /*
  1585. * Copyright (c) 2014-2016 Cesanta Software Limited
  1586. * All rights reserved
  1587. */
  1588. #ifndef CS_MONGOOSE_SRC_TUN_H_
  1589. #define CS_MONGOOSE_SRC_TUN_H_
  1590. #if MG_ENABLE_TUN
  1591. /* Amalgamated: #include "mongoose/src/net.h" */
  1592. /* Amalgamated: #include "common/mg_str.h" */
  1593. #ifndef MG_TUN_RECONNECT_INTERVAL
  1594. #define MG_TUN_RECONNECT_INTERVAL 1
  1595. #endif
  1596. #define MG_TUN_PROTO_NAME "mg_tun"
  1597. #define MG_TUN_DATA_FRAME 0x0
  1598. #define MG_TUN_F_END_STREAM 0x1
  1599. /*
  1600. * MG TUN frame format is loosely based on HTTP/2.
  1601. * However since the communication happens via WebSocket
  1602. * there is no need to encode the frame length, since that's
  1603. * solved by WebSocket framing.
  1604. *
  1605. * TODO(mkm): Detailed description of the protocol.
  1606. */
  1607. struct mg_tun_frame {
  1608. uint8_t type;
  1609. uint8_t flags;
  1610. uint32_t stream_id; /* opaque stream identifier */
  1611. struct mg_str body;
  1612. };
  1613. struct mg_tun_ssl_opts {
  1614. #if MG_ENABLE_SSL
  1615. const char *ssl_cert;
  1616. const char *ssl_key;
  1617. const char *ssl_ca_cert;
  1618. #else
  1619. int dummy; /* some compilers don't like empty structs */
  1620. #endif
  1621. };
  1622. struct mg_tun_client {
  1623. struct mg_mgr *mgr;
  1624. struct mg_iface *iface;
  1625. const char *disp_url;
  1626. struct mg_tun_ssl_opts ssl;
  1627. uint32_t last_stream_id; /* stream id of most recently accepted connection */
  1628. struct mg_connection *disp;
  1629. struct mg_connection *listener;
  1630. struct mg_connection *reconnect;
  1631. };
  1632. #ifdef __cplusplus
  1633. extern "C" {
  1634. #endif /* __cplusplus */
  1635. struct mg_connection *mg_tun_bind_opt(struct mg_mgr *mgr,
  1636. const char *dispatcher,
  1637. mg_event_handler_t handler,
  1638. struct mg_bind_opts opts);
  1639. int mg_tun_parse_frame(void *data, size_t len, struct mg_tun_frame *frame);
  1640. void mg_tun_send_frame(struct mg_connection *ws, uint32_t stream_id,
  1641. uint8_t type, uint8_t flags, struct mg_str msg);
  1642. void mg_tun_destroy_client(struct mg_tun_client *client);
  1643. #ifdef __cplusplus
  1644. }
  1645. #endif /* __cplusplus */
  1646. #endif /* MG_ENABLE_TUN */
  1647. #endif /* CS_MONGOOSE_SRC_TUN_H_ */
  1648. #ifdef MG_MODULE_LINES
  1649. #line 1 "mongoose/src/net.c"
  1650. #endif
  1651. /*
  1652. * Copyright (c) 2014 Cesanta Software Limited
  1653. * All rights reserved
  1654. *
  1655. * This software is dual-licensed: you can redistribute it and/or modify
  1656. * it under the terms of the GNU General Public License version 2 as
  1657. * published by the Free Software Foundation. For the terms of this
  1658. * license, see <http://www.gnu.org/licenses/>.
  1659. *
  1660. * You are free to use this software under the terms of the GNU General
  1661. * Public License, but WITHOUT ANY WARRANTY; without even the implied
  1662. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  1663. * See the GNU General Public License for more details.
  1664. *
  1665. * Alternatively, you can license this software under a commercial
  1666. * license, as set out in <https://www.cesanta.com/license>.
  1667. */
  1668. /* Amalgamated: #include "common/cs_time.h" */
  1669. /* Amalgamated: #include "mongoose/src/dns.h" */
  1670. /* Amalgamated: #include "mongoose/src/internal.h" */
  1671. /* Amalgamated: #include "mongoose/src/resolv.h" */
  1672. /* Amalgamated: #include "mongoose/src/util.h" */
  1673. /* Amalgamated: #include "mongoose/src/tun.h" */
  1674. #define MG_MAX_HOST_LEN 200
  1675. #define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
  1676. memcpy(dst, src, sizeof(*dst));
  1677. /* Which flags can be pre-set by the user at connection creation time. */
  1678. #define _MG_ALLOWED_CONNECT_FLAGS_MASK \
  1679. (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
  1680. MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
  1681. /* Which flags should be modifiable by user's callbacks. */
  1682. #define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
  1683. (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
  1684. MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
  1685. MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
  1686. #ifndef intptr_t
  1687. #define intptr_t long
  1688. #endif
  1689. MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
  1690. DBG(("%p %p", mgr, c));
  1691. c->mgr = mgr;
  1692. c->next = mgr->active_connections;
  1693. mgr->active_connections = c;
  1694. c->prev = NULL;
  1695. if (c->next != NULL) c->next->prev = c;
  1696. if (c->sock != INVALID_SOCKET) {
  1697. c->iface->vtable->add_conn(c);
  1698. }
  1699. }
  1700. MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
  1701. if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
  1702. if (conn->prev) conn->prev->next = conn->next;
  1703. if (conn->next) conn->next->prev = conn->prev;
  1704. conn->prev = conn->next = NULL;
  1705. conn->iface->vtable->remove_conn(conn);
  1706. }
  1707. MG_INTERNAL void mg_call(struct mg_connection *nc,
  1708. mg_event_handler_t ev_handler, int ev, void *ev_data) {
  1709. if (ev_handler == NULL) {
  1710. /*
  1711. * If protocol handler is specified, call it. Otherwise, call user-specified
  1712. * event handler.
  1713. */
  1714. ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
  1715. }
  1716. if (ev != MG_EV_POLL) {
  1717. DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc,
  1718. ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
  1719. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  1720. }
  1721. #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
  1722. /* LCOV_EXCL_START */
  1723. if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL &&
  1724. ev != MG_EV_SEND /* handled separately */) {
  1725. if (ev == MG_EV_RECV) {
  1726. mg_hexdump_connection(nc, nc->mgr->hexdump_file, nc->recv_mbuf.buf,
  1727. *(int *) ev_data, ev);
  1728. } else {
  1729. mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
  1730. }
  1731. }
  1732. /* LCOV_EXCL_STOP */
  1733. #endif
  1734. if (ev_handler != NULL) {
  1735. unsigned long flags_before = nc->flags;
  1736. size_t recv_mbuf_before = nc->recv_mbuf.len, recved;
  1737. ev_handler(nc, ev, ev_data);
  1738. recved = (recv_mbuf_before - nc->recv_mbuf.len);
  1739. /* Prevent user handler from fiddling with system flags. */
  1740. if (ev_handler == nc->handler && nc->flags != flags_before) {
  1741. nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
  1742. (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
  1743. }
  1744. if (recved > 0 && !(nc->flags & MG_F_UDP)) {
  1745. nc->iface->vtable->recved(nc, recved);
  1746. }
  1747. }
  1748. if (ev != MG_EV_POLL) {
  1749. DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc,
  1750. ev_handler == nc->handler ? "user" : "proto", nc->flags,
  1751. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  1752. }
  1753. }
  1754. void mg_if_timer(struct mg_connection *c, double now) {
  1755. if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
  1756. double old_value = c->ev_timer_time;
  1757. mg_call(c, NULL, MG_EV_TIMER, &now);
  1758. /*
  1759. * To prevent timer firing all the time, reset the timer after delivery.
  1760. * However, in case user sets it to new value, do not reset.
  1761. */
  1762. if (c->ev_timer_time == old_value) {
  1763. c->ev_timer_time = 0;
  1764. }
  1765. }
  1766. }
  1767. void mg_if_poll(struct mg_connection *nc, time_t now) {
  1768. if (!(nc->flags & MG_F_SSL) || (nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
  1769. mg_call(nc, NULL, MG_EV_POLL, &now);
  1770. }
  1771. }
  1772. static void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
  1773. if (destroy_if) conn->iface->vtable->destroy_conn(conn);
  1774. if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
  1775. conn->proto_data_destructor(conn->proto_data);
  1776. }
  1777. #if MG_ENABLE_SSL
  1778. mg_ssl_if_conn_free(conn);
  1779. #endif
  1780. mbuf_free(&conn->recv_mbuf);
  1781. mbuf_free(&conn->send_mbuf);
  1782. memset(conn, 0, sizeof(*conn));
  1783. MG_FREE(conn);
  1784. }
  1785. void mg_close_conn(struct mg_connection *conn) {
  1786. DBG(("%p %lu %d", conn, conn->flags, conn->sock));
  1787. mg_remove_conn(conn);
  1788. conn->iface->vtable->destroy_conn(conn);
  1789. mg_call(conn, NULL, MG_EV_CLOSE, NULL);
  1790. mg_destroy_conn(conn, 0 /* destroy_if */);
  1791. }
  1792. void mg_mgr_init(struct mg_mgr *m, void *user_data) {
  1793. struct mg_mgr_init_opts opts;
  1794. memset(&opts, 0, sizeof(opts));
  1795. mg_mgr_init_opt(m, user_data, opts);
  1796. }
  1797. void mg_mgr_init_opt(struct mg_mgr *m, void *user_data,
  1798. struct mg_mgr_init_opts opts) {
  1799. memset(m, 0, sizeof(*m));
  1800. #if MG_ENABLE_BROADCAST
  1801. m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
  1802. #endif
  1803. m->user_data = user_data;
  1804. #ifdef _WIN32
  1805. {
  1806. WSADATA data;
  1807. WSAStartup(MAKEWORD(2, 2), &data);
  1808. }
  1809. #elif defined(__unix__)
  1810. /* Ignore SIGPIPE signal, so if client cancels the request, it
  1811. * won't kill the whole process. */
  1812. signal(SIGPIPE, SIG_IGN);
  1813. #endif
  1814. #if MG_ENABLE_SSL
  1815. {
  1816. static int init_done;
  1817. if (!init_done) {
  1818. mg_ssl_if_init();
  1819. init_done++;
  1820. }
  1821. }
  1822. #endif
  1823. {
  1824. int i;
  1825. if (opts.num_ifaces == 0) {
  1826. opts.num_ifaces = mg_num_ifaces;
  1827. opts.ifaces = mg_ifaces;
  1828. }
  1829. if (opts.main_iface != NULL) {
  1830. opts.ifaces[MG_MAIN_IFACE] = opts.main_iface;
  1831. }
  1832. m->num_ifaces = opts.num_ifaces;
  1833. m->ifaces =
  1834. (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces);
  1835. for (i = 0; i < mg_num_ifaces; i++) {
  1836. m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m);
  1837. m->ifaces[i]->vtable->init(m->ifaces[i]);
  1838. }
  1839. }
  1840. DBG(("=================================="));
  1841. DBG(("init mgr=%p", m));
  1842. }
  1843. #if MG_ENABLE_JAVASCRIPT
  1844. static enum v7_err mg_send_js(struct v7 *v7, v7_val_t *res) {
  1845. v7_val_t arg0 = v7_arg(v7, 0);
  1846. v7_val_t arg1 = v7_arg(v7, 1);
  1847. struct mg_connection *c = (struct mg_connection *) v7_get_ptr(v7, arg0);
  1848. size_t len = 0;
  1849. if (v7_is_string(arg1)) {
  1850. const char *data = v7_get_string(v7, &arg1, &len);
  1851. mg_send(c, data, len);
  1852. }
  1853. *res = v7_mk_number(v7, len);
  1854. return V7_OK;
  1855. }
  1856. enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
  1857. const char *init_file_name) {
  1858. v7_val_t v;
  1859. m->v7 = v7;
  1860. v7_set_method(v7, v7_get_global(v7), "mg_send", mg_send_js);
  1861. return v7_exec_file(v7, init_file_name, &v);
  1862. }
  1863. #endif
  1864. void mg_mgr_free(struct mg_mgr *m) {
  1865. struct mg_connection *conn, *tmp_conn;
  1866. DBG(("%p", m));
  1867. if (m == NULL) return;
  1868. /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
  1869. mg_mgr_poll(m, 0);
  1870. #if MG_ENABLE_BROADCAST
  1871. if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
  1872. if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
  1873. m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
  1874. #endif
  1875. for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
  1876. tmp_conn = conn->next;
  1877. mg_close_conn(conn);
  1878. }
  1879. {
  1880. int i;
  1881. for (i = 0; i < m->num_ifaces; i++) {
  1882. m->ifaces[i]->vtable->free(m->ifaces[i]);
  1883. MG_FREE(m->ifaces[i]);
  1884. }
  1885. MG_FREE(m->ifaces);
  1886. }
  1887. }
  1888. time_t mg_mgr_poll(struct mg_mgr *m, int timeout_ms) {
  1889. int i;
  1890. time_t now = 0; /* oh GCC, seriously ? */
  1891. if (m->num_ifaces == 0) {
  1892. LOG(LL_ERROR, ("cannot poll: no interfaces"));
  1893. return 0;
  1894. }
  1895. for (i = 0; i < m->num_ifaces; i++) {
  1896. now = m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms);
  1897. }
  1898. return now;
  1899. }
  1900. int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
  1901. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  1902. int len;
  1903. if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  1904. mg_send(nc, buf, len);
  1905. }
  1906. if (buf != mem && buf != NULL) {
  1907. MG_FREE(buf); /* LCOV_EXCL_LINE */
  1908. } /* LCOV_EXCL_LINE */
  1909. return len;
  1910. }
  1911. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  1912. int len;
  1913. va_list ap;
  1914. va_start(ap, fmt);
  1915. len = mg_vprintf(conn, fmt, ap);
  1916. va_end(ap);
  1917. return len;
  1918. }
  1919. #if MG_ENABLE_SYNC_RESOLVER
  1920. /* TODO(lsm): use non-blocking resolver */
  1921. static int mg_resolve2(const char *host, struct in_addr *ina) {
  1922. #if MG_ENABLE_GETADDRINFO
  1923. int rv = 0;
  1924. struct addrinfo hints, *servinfo, *p;
  1925. struct sockaddr_in *h = NULL;
  1926. memset(&hints, 0, sizeof hints);
  1927. hints.ai_family = AF_INET;
  1928. hints.ai_socktype = SOCK_STREAM;
  1929. if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
  1930. DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno())));
  1931. return 0;
  1932. }
  1933. for (p = servinfo; p != NULL; p = p->ai_next) {
  1934. memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
  1935. memcpy(ina, &h->sin_addr, sizeof(ina));
  1936. }
  1937. freeaddrinfo(servinfo);
  1938. return 1;
  1939. #else
  1940. struct hostent *he;
  1941. if ((he = gethostbyname(host)) == NULL) {
  1942. DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno())));
  1943. } else {
  1944. memcpy(ina, he->h_addr_list[0], sizeof(*ina));
  1945. return 1;
  1946. }
  1947. return 0;
  1948. #endif /* MG_ENABLE_GETADDRINFO */
  1949. }
  1950. int mg_resolve(const char *host, char *buf, size_t n) {
  1951. struct in_addr ad;
  1952. return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
  1953. }
  1954. #endif /* MG_ENABLE_SYNC_RESOLVER */
  1955. MG_INTERNAL struct mg_connection *mg_create_connection_base(
  1956. struct mg_mgr *mgr, mg_event_handler_t callback,
  1957. struct mg_add_sock_opts opts) {
  1958. struct mg_connection *conn;
  1959. if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
  1960. conn->sock = INVALID_SOCKET;
  1961. conn->handler = callback;
  1962. conn->mgr = mgr;
  1963. conn->last_io_time = (time_t) mg_time();
  1964. conn->iface =
  1965. (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]);
  1966. conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
  1967. conn->user_data = opts.user_data;
  1968. /*
  1969. * SIZE_MAX is defined as a long long constant in
  1970. * system headers on some platforms and so it
  1971. * doesn't compile with pedantic ansi flags.
  1972. */
  1973. conn->recv_mbuf_limit = ~0;
  1974. } else {
  1975. MG_SET_PTRPTR(opts.error_string, "failed to create connection");
  1976. }
  1977. return conn;
  1978. }
  1979. MG_INTERNAL struct mg_connection *mg_create_connection(
  1980. struct mg_mgr *mgr, mg_event_handler_t callback,
  1981. struct mg_add_sock_opts opts) {
  1982. struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
  1983. if (conn != NULL && !conn->iface->vtable->create_conn(conn)) {
  1984. MG_FREE(conn);
  1985. conn = NULL;
  1986. }
  1987. if (conn == NULL) {
  1988. MG_SET_PTRPTR(opts.error_string, "failed to init connection");
  1989. }
  1990. return conn;
  1991. }
  1992. /*
  1993. * Address format: [PROTO://][HOST]:PORT
  1994. *
  1995. * HOST could be IPv4/IPv6 address or a host name.
  1996. * `host` is a destination buffer to hold parsed HOST part. Shoud be at least
  1997. * MG_MAX_HOST_LEN bytes long.
  1998. * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
  1999. *
  2000. * Return:
  2001. * -1 on parse error
  2002. * 0 if HOST needs DNS lookup
  2003. * >0 length of the address string
  2004. */
  2005. MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
  2006. int *proto, char *host, size_t host_len) {
  2007. unsigned int a, b, c, d, port = 0;
  2008. int ch, len = 0;
  2009. #if MG_ENABLE_IPV6
  2010. char buf[100];
  2011. #endif
  2012. /*
  2013. * MacOS needs that. If we do not zero it, subsequent bind() will fail.
  2014. * Also, all-zeroes in the socket address means binding to all addresses
  2015. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  2016. */
  2017. memset(sa, 0, sizeof(*sa));
  2018. sa->sin.sin_family = AF_INET;
  2019. *proto = SOCK_STREAM;
  2020. if (strncmp(str, "udp://", 6) == 0) {
  2021. str += 6;
  2022. *proto = SOCK_DGRAM;
  2023. } else if (strncmp(str, "tcp://", 6) == 0) {
  2024. str += 6;
  2025. }
  2026. if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  2027. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  2028. sa->sin.sin_addr.s_addr =
  2029. htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
  2030. sa->sin.sin_port = htons((uint16_t) port);
  2031. #if MG_ENABLE_IPV6
  2032. } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
  2033. inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
  2034. /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
  2035. sa->sin6.sin6_family = AF_INET6;
  2036. sa->sin.sin_port = htons((uint16_t) port);
  2037. #endif
  2038. #if MG_ENABLE_ASYNC_RESOLVER
  2039. } else if (strlen(str) < host_len &&
  2040. sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
  2041. sa->sin.sin_port = htons((uint16_t) port);
  2042. if (mg_resolve_from_hosts_file(host, sa) != 0) {
  2043. /*
  2044. * if resolving from hosts file failed and the host
  2045. * we are trying to resolve is `localhost` - we should
  2046. * try to resolve it using `gethostbyname` and do not try
  2047. * to resolve it via DNS server if gethostbyname has failed too
  2048. */
  2049. if (mg_ncasecmp(host, "localhost", 9) != 0) {
  2050. return 0;
  2051. }
  2052. #if MG_ENABLE_SYNC_RESOLVER
  2053. if (!mg_resolve2(host, &sa->sin.sin_addr)) {
  2054. return -1;
  2055. }
  2056. #else
  2057. return -1;
  2058. #endif
  2059. }
  2060. #endif
  2061. } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
  2062. sscanf(str, "%u%n", &port, &len) == 1) {
  2063. /* If only port is specified, bind to IPv4, INADDR_ANY */
  2064. sa->sin.sin_port = htons((uint16_t) port);
  2065. } else {
  2066. return -1;
  2067. }
  2068. /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */
  2069. (void) host;
  2070. (void) host_len;
  2071. ch = str[len]; /* Character that follows the address */
  2072. return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
  2073. }
  2074. struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
  2075. struct mg_add_sock_opts opts;
  2076. struct mg_connection *nc;
  2077. memset(&opts, 0, sizeof(opts));
  2078. nc = mg_create_connection(lc->mgr, lc->handler, opts);
  2079. if (nc == NULL) return NULL;
  2080. nc->listener = lc;
  2081. nc->proto_handler = lc->proto_handler;
  2082. nc->user_data = lc->user_data;
  2083. nc->recv_mbuf_limit = lc->recv_mbuf_limit;
  2084. nc->iface = lc->iface;
  2085. if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL;
  2086. mg_add_conn(nc->mgr, nc);
  2087. DBG(("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags));
  2088. return nc;
  2089. }
  2090. void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
  2091. size_t sa_len) {
  2092. (void) sa_len;
  2093. nc->sa = *sa;
  2094. mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
  2095. }
  2096. void mg_send(struct mg_connection *nc, const void *buf, int len) {
  2097. nc->last_io_time = (time_t) mg_time();
  2098. if (nc->flags & MG_F_UDP) {
  2099. nc->iface->vtable->udp_send(nc, buf, len);
  2100. } else {
  2101. nc->iface->vtable->tcp_send(nc, buf, len);
  2102. }
  2103. #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
  2104. if (nc->mgr && nc->mgr->hexdump_file != NULL) {
  2105. mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, len, MG_EV_SEND);
  2106. }
  2107. #endif
  2108. }
  2109. void mg_if_sent_cb(struct mg_connection *nc, int num_sent) {
  2110. if (num_sent < 0) {
  2111. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2112. }
  2113. mg_call(nc, NULL, MG_EV_SEND, &num_sent);
  2114. }
  2115. MG_INTERNAL void mg_recv_common(struct mg_connection *nc, void *buf, int len,
  2116. int own) {
  2117. DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len));
  2118. if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
  2119. DBG(("%p discarded %d bytes", nc, len));
  2120. /*
  2121. * This connection will not survive next poll. Do not deliver events,
  2122. * send data to /dev/null without acking.
  2123. */
  2124. if (own) {
  2125. MG_FREE(buf);
  2126. }
  2127. return;
  2128. }
  2129. nc->last_io_time = (time_t) mg_time();
  2130. if (!own) {
  2131. mbuf_append(&nc->recv_mbuf, buf, len);
  2132. } else if (nc->recv_mbuf.len == 0) {
  2133. /* Adopt buf as recv_mbuf's backing store. */
  2134. mbuf_free(&nc->recv_mbuf);
  2135. nc->recv_mbuf.buf = (char *) buf;
  2136. nc->recv_mbuf.size = nc->recv_mbuf.len = len;
  2137. } else {
  2138. mbuf_append(&nc->recv_mbuf, buf, len);
  2139. MG_FREE(buf);
  2140. }
  2141. mg_call(nc, NULL, MG_EV_RECV, &len);
  2142. }
  2143. void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len, int own) {
  2144. mg_recv_common(nc, buf, len, own);
  2145. }
  2146. void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
  2147. union socket_address *sa, size_t sa_len) {
  2148. assert(nc->flags & MG_F_UDP);
  2149. DBG(("%p %u", nc, (unsigned int) len));
  2150. if (nc->flags & MG_F_LISTENING) {
  2151. struct mg_connection *lc = nc;
  2152. /*
  2153. * Do we have an existing connection for this source?
  2154. * This is very inefficient for long connection lists.
  2155. */
  2156. for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
  2157. if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0 && nc->listener == lc) {
  2158. break;
  2159. }
  2160. }
  2161. if (nc == NULL) {
  2162. struct mg_add_sock_opts opts;
  2163. memset(&opts, 0, sizeof(opts));
  2164. /* Create fake connection w/out sock initialization */
  2165. nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
  2166. if (nc != NULL) {
  2167. nc->sock = lc->sock;
  2168. nc->listener = lc;
  2169. nc->sa = *sa;
  2170. nc->proto_handler = lc->proto_handler;
  2171. nc->user_data = lc->user_data;
  2172. nc->recv_mbuf_limit = lc->recv_mbuf_limit;
  2173. nc->flags = MG_F_UDP;
  2174. /*
  2175. * Long-lived UDP "connections" i.e. interactions that involve more
  2176. * than one request and response are rare, most are transactional:
  2177. * response is sent and the "connection" is closed. Or - should be.
  2178. * But users (including ourselves) tend to forget about that part,
  2179. * because UDP is connectionless and one does not think about
  2180. * processing a UDP request as handling a connection that needs to be
  2181. * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should
  2182. * be a reasonable default for most use cases, but it is possible to
  2183. * turn it off the connection should be kept alive after processing.
  2184. */
  2185. nc->flags |= MG_F_SEND_AND_CLOSE;
  2186. mg_add_conn(lc->mgr, nc);
  2187. mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
  2188. } else {
  2189. DBG(("OOM"));
  2190. /* No return here, we still need to drop on the floor */
  2191. }
  2192. }
  2193. }
  2194. if (nc != NULL) {
  2195. mg_recv_common(nc, buf, len, 1);
  2196. } else {
  2197. /* Drop on the floor. */
  2198. MG_FREE(buf);
  2199. nc->iface->vtable->recved(nc, len);
  2200. }
  2201. }
  2202. /*
  2203. * Schedules an async connect for a resolved address and proto.
  2204. * Called from two places: `mg_connect_opt()` and from async resolver.
  2205. * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
  2206. * with a failure flag to indicate connection failure.
  2207. */
  2208. MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
  2209. int proto,
  2210. union socket_address *sa) {
  2211. DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
  2212. inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
  2213. nc->flags |= MG_F_CONNECTING;
  2214. if (proto == SOCK_DGRAM) {
  2215. nc->iface->vtable->connect_udp(nc);
  2216. } else {
  2217. nc->iface->vtable->connect_tcp(nc, sa);
  2218. }
  2219. mg_add_conn(nc->mgr, nc);
  2220. return nc;
  2221. }
  2222. void mg_if_connect_cb(struct mg_connection *nc, int err) {
  2223. DBG(("%p connect, err=%d", nc, err));
  2224. nc->flags &= ~MG_F_CONNECTING;
  2225. if (err != 0) {
  2226. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2227. }
  2228. mg_call(nc, NULL, MG_EV_CONNECT, &err);
  2229. }
  2230. #if MG_ENABLE_ASYNC_RESOLVER
  2231. /*
  2232. * Callback for the async resolver on mg_connect_opt() call.
  2233. * Main task of this function is to trigger MG_EV_CONNECT event with
  2234. * either failure (and dealloc the connection)
  2235. * or success (and proceed with connect()
  2236. */
  2237. static void resolve_cb(struct mg_dns_message *msg, void *data,
  2238. enum mg_resolve_err e) {
  2239. struct mg_connection *nc = (struct mg_connection *) data;
  2240. int i;
  2241. int failure = -1;
  2242. nc->flags &= ~MG_F_RESOLVING;
  2243. if (msg != NULL) {
  2244. /*
  2245. * Take the first DNS A answer and run...
  2246. */
  2247. for (i = 0; i < msg->num_answers; i++) {
  2248. if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
  2249. /*
  2250. * Async resolver guarantees that there is at least one answer.
  2251. * TODO(lsm): handle IPv6 answers too
  2252. */
  2253. mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
  2254. 4);
  2255. mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
  2256. &nc->sa);
  2257. return;
  2258. }
  2259. }
  2260. }
  2261. if (e == MG_RESOLVE_TIMEOUT) {
  2262. double now = mg_time();
  2263. mg_call(nc, NULL, MG_EV_TIMER, &now);
  2264. }
  2265. /*
  2266. * If we get there was no MG_DNS_A_RECORD in the answer
  2267. */
  2268. mg_call(nc, NULL, MG_EV_CONNECT, &failure);
  2269. mg_call(nc, NULL, MG_EV_CLOSE, NULL);
  2270. mg_destroy_conn(nc, 1 /* destroy_if */);
  2271. }
  2272. #endif
  2273. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
  2274. mg_event_handler_t callback) {
  2275. struct mg_connect_opts opts;
  2276. memset(&opts, 0, sizeof(opts));
  2277. return mg_connect_opt(mgr, address, callback, opts);
  2278. }
  2279. struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
  2280. mg_event_handler_t callback,
  2281. struct mg_connect_opts opts) {
  2282. struct mg_connection *nc = NULL;
  2283. int proto, rc;
  2284. struct mg_add_sock_opts add_sock_opts;
  2285. char host[MG_MAX_HOST_LEN];
  2286. MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
  2287. if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
  2288. return NULL;
  2289. }
  2290. if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) <
  2291. 0) {
  2292. /* Address is malformed */
  2293. MG_SET_PTRPTR(opts.error_string, "cannot parse address");
  2294. mg_destroy_conn(nc, 1 /* destroy_if */);
  2295. return NULL;
  2296. }
  2297. nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
  2298. nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
  2299. nc->user_data = opts.user_data;
  2300. #if MG_ENABLE_SSL
  2301. DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
  2302. (opts.ssl_key ? opts.ssl_key : "-"),
  2303. (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
  2304. if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
  2305. opts.ssl_psk_identity != NULL) {
  2306. const char *err_msg = NULL;
  2307. struct mg_ssl_if_conn_params params;
  2308. if (nc->flags & MG_F_UDP) {
  2309. MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
  2310. mg_destroy_conn(nc, 1 /* destroy_if */);
  2311. return NULL;
  2312. }
  2313. memset(&params, 0, sizeof(params));
  2314. params.cert = opts.ssl_cert;
  2315. params.key = opts.ssl_key;
  2316. params.ca_cert = opts.ssl_ca_cert;
  2317. params.cipher_suites = opts.ssl_cipher_suites;
  2318. params.psk_identity = opts.ssl_psk_identity;
  2319. params.psk_key = opts.ssl_psk_key;
  2320. if (opts.ssl_ca_cert != NULL) {
  2321. if (opts.ssl_server_name != NULL) {
  2322. if (strcmp(opts.ssl_server_name, "*") != 0) {
  2323. params.server_name = opts.ssl_server_name;
  2324. }
  2325. } else if (rc == 0) { /* If it's a DNS name, use host. */
  2326. params.server_name = host;
  2327. }
  2328. }
  2329. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  2330. MG_SET_PTRPTR(opts.error_string, err_msg);
  2331. mg_destroy_conn(nc, 1 /* destroy_if */);
  2332. return NULL;
  2333. }
  2334. nc->flags |= MG_F_SSL;
  2335. }
  2336. #endif /* MG_ENABLE_SSL */
  2337. if (rc == 0) {
  2338. #if MG_ENABLE_ASYNC_RESOLVER
  2339. /*
  2340. * DNS resolution is required for host.
  2341. * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
  2342. */
  2343. struct mg_connection *dns_conn = NULL;
  2344. struct mg_resolve_async_opts o;
  2345. memset(&o, 0, sizeof(o));
  2346. o.dns_conn = &dns_conn;
  2347. if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
  2348. o) != 0) {
  2349. MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
  2350. mg_destroy_conn(nc, 1 /* destroy_if */);
  2351. return NULL;
  2352. }
  2353. nc->priv_2 = dns_conn;
  2354. nc->flags |= MG_F_RESOLVING;
  2355. return nc;
  2356. #else
  2357. MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
  2358. mg_destroy_conn(nc, 1 /* destroy_if */);
  2359. return NULL;
  2360. #endif
  2361. } else {
  2362. /* Address is parsed and resolved to IP. proceed with connect() */
  2363. return mg_do_connect(nc, proto, &nc->sa);
  2364. }
  2365. }
  2366. struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
  2367. mg_event_handler_t event_handler) {
  2368. struct mg_bind_opts opts;
  2369. memset(&opts, 0, sizeof(opts));
  2370. return mg_bind_opt(srv, address, event_handler, opts);
  2371. }
  2372. struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
  2373. mg_event_handler_t callback,
  2374. struct mg_bind_opts opts) {
  2375. union socket_address sa;
  2376. struct mg_connection *nc = NULL;
  2377. int proto, rc;
  2378. struct mg_add_sock_opts add_sock_opts;
  2379. char host[MG_MAX_HOST_LEN];
  2380. MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
  2381. #if MG_ENABLE_TUN
  2382. if (mg_strncmp(mg_mk_str(address), mg_mk_str("ws://"), 5) == 0 ||
  2383. mg_strncmp(mg_mk_str(address), mg_mk_str("wss://"), 6) == 0) {
  2384. return mg_tun_bind_opt(mgr, address, callback, opts);
  2385. }
  2386. #endif
  2387. if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
  2388. MG_SET_PTRPTR(opts.error_string, "cannot parse address");
  2389. return NULL;
  2390. }
  2391. nc = mg_create_connection(mgr, callback, add_sock_opts);
  2392. if (nc == NULL) {
  2393. return NULL;
  2394. }
  2395. nc->sa = sa;
  2396. nc->flags |= MG_F_LISTENING;
  2397. if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP;
  2398. #if MG_ENABLE_SSL
  2399. DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
  2400. (opts.ssl_key ? opts.ssl_key : "-"),
  2401. (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
  2402. if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
  2403. const char *err_msg = NULL;
  2404. struct mg_ssl_if_conn_params params;
  2405. if (nc->flags & MG_F_UDP) {
  2406. MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
  2407. mg_destroy_conn(nc, 1 /* destroy_if */);
  2408. return NULL;
  2409. }
  2410. memset(&params, 0, sizeof(params));
  2411. params.cert = opts.ssl_cert;
  2412. params.key = opts.ssl_key;
  2413. params.ca_cert = opts.ssl_ca_cert;
  2414. params.cipher_suites = opts.ssl_cipher_suites;
  2415. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  2416. MG_SET_PTRPTR(opts.error_string, err_msg);
  2417. mg_destroy_conn(nc, 1 /* destroy_if */);
  2418. return NULL;
  2419. }
  2420. nc->flags |= MG_F_SSL;
  2421. }
  2422. #endif /* MG_ENABLE_SSL */
  2423. if (nc->flags & MG_F_UDP) {
  2424. rc = nc->iface->vtable->listen_udp(nc, &nc->sa);
  2425. } else {
  2426. rc = nc->iface->vtable->listen_tcp(nc, &nc->sa);
  2427. }
  2428. if (rc != 0) {
  2429. DBG(("Failed to open listener: %d", rc));
  2430. MG_SET_PTRPTR(opts.error_string, "failed to open listener");
  2431. mg_destroy_conn(nc, 1 /* destroy_if */);
  2432. return NULL;
  2433. }
  2434. mg_add_conn(nc->mgr, nc);
  2435. return nc;
  2436. }
  2437. struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
  2438. return conn == NULL ? s->active_connections : conn->next;
  2439. }
  2440. #if MG_ENABLE_BROADCAST
  2441. void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
  2442. size_t len) {
  2443. struct ctl_msg ctl_msg;
  2444. /*
  2445. * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
  2446. * where `mg_broadcast()` pushes the message.
  2447. * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
  2448. * specified callback for each connection. Thus the callback function executes
  2449. * in event manager thread.
  2450. */
  2451. if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
  2452. len < sizeof(ctl_msg.message)) {
  2453. size_t dummy;
  2454. ctl_msg.callback = cb;
  2455. memcpy(ctl_msg.message, data, len);
  2456. dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
  2457. offsetof(struct ctl_msg, message) + len, 0);
  2458. dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
  2459. (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
  2460. }
  2461. }
  2462. #endif /* MG_ENABLE_BROADCAST */
  2463. static int isbyte(int n) {
  2464. return n >= 0 && n <= 255;
  2465. }
  2466. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  2467. int n, a, b, c, d, slash = 32, len = 0;
  2468. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  2469. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  2470. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  2471. slash < 33) {
  2472. len = n;
  2473. *net =
  2474. ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
  2475. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  2476. }
  2477. return len;
  2478. }
  2479. int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
  2480. int allowed, flag;
  2481. uint32_t net, mask;
  2482. struct mg_str vec;
  2483. /* If any ACL is set, deny by default */
  2484. allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
  2485. while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
  2486. flag = vec.p[0];
  2487. if ((flag != '+' && flag != '-') ||
  2488. parse_net(&vec.p[1], &net, &mask) == 0) {
  2489. return -1;
  2490. }
  2491. if (net == (remote_ip & mask)) {
  2492. allowed = flag;
  2493. }
  2494. }
  2495. DBG(("%08x %c", remote_ip, allowed));
  2496. return allowed == '+';
  2497. }
  2498. /* Move data from one connection to another */
  2499. void mg_forward(struct mg_connection *from, struct mg_connection *to) {
  2500. mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
  2501. mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
  2502. }
  2503. double mg_set_timer(struct mg_connection *c, double timestamp) {
  2504. double result = c->ev_timer_time;
  2505. c->ev_timer_time = timestamp;
  2506. /*
  2507. * If this connection is resolving, it's not in the list of active
  2508. * connections, so not processed yet. It has a DNS resolver connection
  2509. * linked to it. Set up a timer for the DNS connection.
  2510. */
  2511. DBG(("%p %p %d -> %lu", c, c->priv_2, c->flags & MG_F_RESOLVING,
  2512. (unsigned long) timestamp));
  2513. if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
  2514. ((struct mg_connection *) c->priv_2)->ev_timer_time = timestamp;
  2515. }
  2516. return result;
  2517. }
  2518. void mg_sock_set(struct mg_connection *nc, sock_t sock) {
  2519. if (sock != INVALID_SOCKET) {
  2520. nc->iface->vtable->sock_set(nc, sock);
  2521. }
  2522. }
  2523. void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
  2524. union socket_address *sa) {
  2525. nc->iface->vtable->get_conn_addr(nc, remote, sa);
  2526. }
  2527. struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
  2528. mg_event_handler_t callback,
  2529. struct mg_add_sock_opts opts) {
  2530. struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
  2531. if (nc != NULL) {
  2532. mg_sock_set(nc, sock);
  2533. mg_add_conn(nc->mgr, nc);
  2534. }
  2535. return nc;
  2536. }
  2537. struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
  2538. mg_event_handler_t callback) {
  2539. struct mg_add_sock_opts opts;
  2540. memset(&opts, 0, sizeof(opts));
  2541. return mg_add_sock_opt(s, sock, callback, opts);
  2542. }
  2543. double mg_time(void) {
  2544. return cs_time();
  2545. }
  2546. #ifdef MG_MODULE_LINES
  2547. #line 1 "mongoose/src/net_if_socket.h"
  2548. #endif
  2549. /*
  2550. * Copyright (c) 2014-2016 Cesanta Software Limited
  2551. * All rights reserved
  2552. */
  2553. #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
  2554. #define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
  2555. /* Amalgamated: #include "mongoose/src/net_if.h" */
  2556. #ifdef __cplusplus
  2557. extern "C" {
  2558. #endif /* __cplusplus */
  2559. #ifndef MG_ENABLE_NET_IF_SOCKET
  2560. #define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
  2561. #endif
  2562. extern struct mg_iface_vtable mg_socket_iface_vtable;
  2563. #ifdef __cplusplus
  2564. }
  2565. #endif /* __cplusplus */
  2566. #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */
  2567. #ifdef MG_MODULE_LINES
  2568. #line 1 "mongoose/src/net_if_tun.h"
  2569. #endif
  2570. /*
  2571. * Copyright (c) 2014-2016 Cesanta Software Limited
  2572. * All rights reserved
  2573. */
  2574. #ifndef CS_MONGOOSE_SRC_NET_IF_TUN_H_
  2575. #define CS_MONGOOSE_SRC_NET_IF_TUN_H_
  2576. #if MG_ENABLE_TUN
  2577. /* Amalgamated: #include "mongoose/src/net_if.h" */
  2578. struct mg_tun_client;
  2579. #ifdef __cplusplus
  2580. extern "C" {
  2581. #endif /* __cplusplus */
  2582. extern struct mg_iface_vtable mg_tun_iface_vtable;
  2583. struct mg_connection *mg_tun_if_find_conn(struct mg_tun_client *client,
  2584. uint32_t stream_id);
  2585. #ifdef __cplusplus
  2586. }
  2587. #endif /* __cplusplus */
  2588. #endif /* MG_ENABLE_TUN */
  2589. #endif /* CS_MONGOOSE_SRC_NET_IF_TUN_H_ */
  2590. #ifdef MG_MODULE_LINES
  2591. #line 1 "mongoose/src/net_if.c"
  2592. #endif
  2593. /* Amalgamated: #include "mongoose/src/net_if.h" */
  2594. /* Amalgamated: #include "mongoose/src/internal.h" */
  2595. /* Amalgamated: #include "mongoose/src/net_if_socket.h" */
  2596. /* Amalgamated: #include "mongoose/src/net_if_tun.h" */
  2597. extern struct mg_iface_vtable mg_default_iface_vtable;
  2598. #if MG_ENABLE_TUN
  2599. struct mg_iface_vtable *mg_ifaces[] = {&mg_default_iface_vtable,
  2600. &mg_tun_iface_vtable};
  2601. #else
  2602. struct mg_iface_vtable *mg_ifaces[] = {&mg_default_iface_vtable};
  2603. #endif
  2604. int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0]));
  2605. struct mg_iface *mg_if_create_iface(struct mg_iface_vtable *vtable,
  2606. struct mg_mgr *mgr) {
  2607. struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface));
  2608. iface->mgr = mgr;
  2609. iface->data = NULL;
  2610. iface->vtable = vtable;
  2611. return iface;
  2612. }
  2613. struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
  2614. struct mg_iface_vtable *vtable,
  2615. struct mg_iface *from) {
  2616. int i = 0;
  2617. if (from != NULL) {
  2618. for (i = 0; i < mgr->num_ifaces; i++) {
  2619. if (mgr->ifaces[i] == from) {
  2620. i++;
  2621. break;
  2622. }
  2623. }
  2624. }
  2625. for (; i < mgr->num_ifaces; i++) {
  2626. if (mgr->ifaces[i]->vtable == vtable) {
  2627. return mgr->ifaces[i];
  2628. }
  2629. }
  2630. return NULL;
  2631. }
  2632. #ifdef MG_MODULE_LINES
  2633. #line 1 "mongoose/src/net_if_socket.c"
  2634. #endif
  2635. /*
  2636. * Copyright (c) 2014-2016 Cesanta Software Limited
  2637. * All rights reserved
  2638. */
  2639. #if MG_ENABLE_NET_IF_SOCKET
  2640. /* Amalgamated: #include "mongoose/src/net_if_socket.h" */
  2641. /* Amalgamated: #include "mongoose/src/internal.h" */
  2642. /* Amalgamated: #include "mongoose/src/util.h" */
  2643. #define MG_TCP_RECV_BUFFER_SIZE 1024
  2644. #define MG_UDP_RECV_BUFFER_SIZE 1500
  2645. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  2646. int proto);
  2647. #if MG_ENABLE_SSL
  2648. static void mg_ssl_begin(struct mg_connection *nc);
  2649. #endif
  2650. void mg_set_non_blocking_mode(sock_t sock) {
  2651. #ifdef _WIN32
  2652. unsigned long on = 1;
  2653. ioctlsocket(sock, FIONBIO, &on);
  2654. #else
  2655. int flags = fcntl(sock, F_GETFL, 0);
  2656. fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2657. #endif
  2658. }
  2659. static int mg_is_error(int n) {
  2660. int err = mg_get_errno();
  2661. return (n < 0 && err != EINPROGRESS && err != EWOULDBLOCK
  2662. #ifndef WINCE
  2663. && err != EAGAIN && err != EINTR
  2664. #endif
  2665. #ifdef _WIN32
  2666. && WSAGetLastError() != WSAEINTR &&
  2667. WSAGetLastError() != WSAEWOULDBLOCK
  2668. #endif
  2669. );
  2670. }
  2671. void mg_socket_if_connect_tcp(struct mg_connection *nc,
  2672. const union socket_address *sa) {
  2673. int rc, proto = 0;
  2674. nc->sock = socket(AF_INET, SOCK_STREAM, proto);
  2675. if (nc->sock == INVALID_SOCKET) {
  2676. nc->err = mg_get_errno() ? mg_get_errno() : 1;
  2677. return;
  2678. }
  2679. #if !defined(MG_ESP8266)
  2680. mg_set_non_blocking_mode(nc->sock);
  2681. #endif
  2682. rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
  2683. nc->err = mg_is_error(rc) ? mg_get_errno() : 0;
  2684. DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(),
  2685. nc->err));
  2686. }
  2687. void mg_socket_if_connect_udp(struct mg_connection *nc) {
  2688. nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
  2689. if (nc->sock == INVALID_SOCKET) {
  2690. nc->err = mg_get_errno() ? mg_get_errno() : 1;
  2691. return;
  2692. }
  2693. if (nc->flags & MG_F_ENABLE_BROADCAST) {
  2694. int optval = 1;
  2695. setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval,
  2696. sizeof(optval));
  2697. }
  2698. nc->err = 0;
  2699. }
  2700. int mg_socket_if_listen_tcp(struct mg_connection *nc,
  2701. union socket_address *sa) {
  2702. int proto = 0;
  2703. sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
  2704. if (sock == INVALID_SOCKET) {
  2705. return (mg_get_errno() ? mg_get_errno() : 1);
  2706. }
  2707. mg_sock_set(nc, sock);
  2708. return 0;
  2709. }
  2710. int mg_socket_if_listen_udp(struct mg_connection *nc,
  2711. union socket_address *sa) {
  2712. sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
  2713. if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1);
  2714. mg_sock_set(nc, sock);
  2715. return 0;
  2716. }
  2717. void mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf,
  2718. size_t len) {
  2719. mbuf_append(&nc->send_mbuf, buf, len);
  2720. }
  2721. void mg_socket_if_udp_send(struct mg_connection *nc, const void *buf,
  2722. size_t len) {
  2723. mbuf_append(&nc->send_mbuf, buf, len);
  2724. }
  2725. void mg_socket_if_recved(struct mg_connection *nc, size_t len) {
  2726. (void) nc;
  2727. (void) len;
  2728. }
  2729. int mg_socket_if_create_conn(struct mg_connection *nc) {
  2730. (void) nc;
  2731. return 1;
  2732. }
  2733. void mg_socket_if_destroy_conn(struct mg_connection *nc) {
  2734. if (nc->sock == INVALID_SOCKET) return;
  2735. if (!(nc->flags & MG_F_UDP)) {
  2736. closesocket(nc->sock);
  2737. } else {
  2738. /* Only close outgoing UDP sockets or listeners. */
  2739. if (nc->listener == NULL) closesocket(nc->sock);
  2740. }
  2741. nc->sock = INVALID_SOCKET;
  2742. }
  2743. static int mg_accept_conn(struct mg_connection *lc) {
  2744. struct mg_connection *nc;
  2745. union socket_address sa;
  2746. socklen_t sa_len = sizeof(sa);
  2747. /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
  2748. sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
  2749. if (sock == INVALID_SOCKET) {
  2750. if (mg_is_error(-1)) DBG(("%p: failed to accept: %d", lc, mg_get_errno()));
  2751. return 0;
  2752. }
  2753. nc = mg_if_accept_new_conn(lc);
  2754. if (nc == NULL) {
  2755. closesocket(sock);
  2756. return 0;
  2757. }
  2758. DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
  2759. ntohs(sa.sin.sin_port)));
  2760. mg_sock_set(nc, sock);
  2761. #if MG_ENABLE_SSL
  2762. if (lc->flags & MG_F_SSL) {
  2763. if (mg_ssl_if_conn_accept(nc, lc) != MG_SSL_OK) mg_close_conn(nc);
  2764. } else
  2765. #endif
  2766. {
  2767. mg_if_accept_tcp_cb(nc, &sa, sa_len);
  2768. }
  2769. return 1;
  2770. }
  2771. /* 'sa' must be an initialized address to bind to */
  2772. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  2773. int proto) {
  2774. socklen_t sa_len =
  2775. (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
  2776. sock_t sock = INVALID_SOCKET;
  2777. #if !MG_LWIP
  2778. int on = 1;
  2779. #endif
  2780. if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET &&
  2781. #if !MG_LWIP /* LWIP doesn't support either */
  2782. #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
  2783. /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
  2784. !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
  2785. sizeof(on)) &&
  2786. #endif
  2787. #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
  2788. /*
  2789. * SO_RESUSEADDR is not enabled on Windows because the semantics of
  2790. * SO_REUSEADDR on UNIX and Windows is different. On Windows,
  2791. * SO_REUSEADDR allows to bind a socket to a port without error even if
  2792. * the port is already open by another program. This is not the behavior
  2793. * SO_REUSEADDR was designed for, and leads to hard-to-track failure
  2794. * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
  2795. * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
  2796. */
  2797. !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
  2798. #endif
  2799. #endif /* !MG_LWIP */
  2800. !bind(sock, &sa->sa, sa_len) &&
  2801. (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
  2802. #if !MG_LWIP
  2803. mg_set_non_blocking_mode(sock);
  2804. /* In case port was set to 0, get the real port number */
  2805. (void) getsockname(sock, &sa->sa, &sa_len);
  2806. #endif
  2807. } else if (sock != INVALID_SOCKET) {
  2808. closesocket(sock);
  2809. sock = INVALID_SOCKET;
  2810. }
  2811. return sock;
  2812. }
  2813. static void mg_write_to_socket(struct mg_connection *nc) {
  2814. struct mbuf *io = &nc->send_mbuf;
  2815. int n = 0;
  2816. #if MG_LWIP
  2817. /* With LWIP we don't know if the socket is ready */
  2818. if (io->len == 0) return;
  2819. #endif
  2820. assert(io->len > 0);
  2821. if (nc->flags & MG_F_UDP) {
  2822. int n =
  2823. sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
  2824. DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, mg_get_errno(),
  2825. inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
  2826. if (n > 0) {
  2827. mbuf_remove(io, n);
  2828. mg_if_sent_cb(nc, n);
  2829. }
  2830. return;
  2831. }
  2832. #if MG_ENABLE_SSL
  2833. if (nc->flags & MG_F_SSL) {
  2834. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  2835. n = mg_ssl_if_write(nc, io->buf, io->len);
  2836. DBG(("%p %d bytes -> %d (SSL)", nc, n, nc->sock));
  2837. if (n < 0) {
  2838. if (n != MG_SSL_WANT_READ && n != MG_SSL_WANT_WRITE) {
  2839. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2840. }
  2841. return;
  2842. } else {
  2843. /* Successful SSL operation, clear off SSL wait flags */
  2844. nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
  2845. }
  2846. } else {
  2847. mg_ssl_begin(nc);
  2848. return;
  2849. }
  2850. } else
  2851. #endif
  2852. {
  2853. n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0);
  2854. DBG(("%p %d bytes -> %d", nc, n, nc->sock));
  2855. if (n < 0 && mg_is_error(n)) {
  2856. /* Something went wrong, drop the connection. */
  2857. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2858. return;
  2859. }
  2860. }
  2861. if (n > 0) {
  2862. mbuf_remove(io, n);
  2863. mg_if_sent_cb(nc, n);
  2864. }
  2865. }
  2866. MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
  2867. size_t avail;
  2868. if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
  2869. avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
  2870. return avail > max ? max : avail;
  2871. }
  2872. static void mg_handle_tcp_read(struct mg_connection *conn) {
  2873. int n = 0;
  2874. char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
  2875. if (buf == NULL) {
  2876. DBG(("OOM"));
  2877. return;
  2878. }
  2879. #if MG_ENABLE_SSL
  2880. if (conn->flags & MG_F_SSL) {
  2881. if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
  2882. /* SSL library may have more bytes ready to read than we ask to read.
  2883. * Therefore, read in a loop until we read everything. Without the loop,
  2884. * we skip to the next select() cycle which can just timeout. */
  2885. while ((n = mg_ssl_if_read(conn, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) {
  2886. DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
  2887. mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
  2888. buf = NULL;
  2889. if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
  2890. /* buf has been freed, we need a new one. */
  2891. buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
  2892. if (buf == NULL) break;
  2893. }
  2894. MG_FREE(buf);
  2895. if (n < 0 && n != MG_SSL_WANT_READ) conn->flags |= MG_F_CLOSE_IMMEDIATELY;
  2896. } else {
  2897. MG_FREE(buf);
  2898. mg_ssl_begin(conn);
  2899. return;
  2900. }
  2901. } else
  2902. #endif
  2903. {
  2904. n = (int) MG_RECV_FUNC(conn->sock, buf,
  2905. recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
  2906. DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
  2907. if (n > 0) {
  2908. mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
  2909. } else {
  2910. MG_FREE(buf);
  2911. }
  2912. if (n == 0) {
  2913. /* Orderly shutdown of the socket, try flushing output. */
  2914. conn->flags |= MG_F_SEND_AND_CLOSE;
  2915. } else if (mg_is_error(n)) {
  2916. conn->flags |= MG_F_CLOSE_IMMEDIATELY;
  2917. }
  2918. }
  2919. }
  2920. static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa,
  2921. socklen_t *sa_len, char **buf) {
  2922. int n;
  2923. *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
  2924. if (*buf == NULL) {
  2925. DBG(("Out of memory"));
  2926. return -ENOMEM;
  2927. }
  2928. n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len);
  2929. if (n <= 0) {
  2930. DBG(("%p recvfrom: %s", nc, strerror(mg_get_errno())));
  2931. MG_FREE(*buf);
  2932. }
  2933. return n;
  2934. }
  2935. static void mg_handle_udp_read(struct mg_connection *nc) {
  2936. char *buf = NULL;
  2937. union socket_address sa;
  2938. socklen_t sa_len = sizeof(sa);
  2939. int n = mg_recvfrom(nc, &sa, &sa_len, &buf);
  2940. DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
  2941. ntohs(nc->sa.sin.sin_port)));
  2942. mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
  2943. }
  2944. #if MG_ENABLE_SSL
  2945. static void mg_ssl_begin(struct mg_connection *nc) {
  2946. int server_side = (nc->listener != NULL);
  2947. enum mg_ssl_if_result res = mg_ssl_if_handshake(nc);
  2948. DBG(("%p %d res %d", nc, server_side, res));
  2949. if (res == MG_SSL_OK) {
  2950. nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
  2951. nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
  2952. if (server_side) {
  2953. union socket_address sa;
  2954. socklen_t sa_len = sizeof(sa);
  2955. (void) getpeername(nc->sock, &sa.sa, &sa_len);
  2956. mg_if_accept_tcp_cb(nc, &sa, sa_len);
  2957. } else {
  2958. mg_if_connect_cb(nc, 0);
  2959. }
  2960. } else if (res != MG_SSL_WANT_READ && res != MG_SSL_WANT_WRITE) {
  2961. if (!server_side) {
  2962. mg_if_connect_cb(nc, res);
  2963. }
  2964. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2965. }
  2966. }
  2967. #endif /* MG_ENABLE_SSL */
  2968. #define _MG_F_FD_CAN_READ 1
  2969. #define _MG_F_FD_CAN_WRITE 1 << 1
  2970. #define _MG_F_FD_ERROR 1 << 2
  2971. void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
  2972. int worth_logging =
  2973. fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE));
  2974. if (worth_logging) {
  2975. DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
  2976. fd_flags, nc->flags, (int) nc->recv_mbuf.len,
  2977. (int) nc->send_mbuf.len));
  2978. }
  2979. if (nc->flags & MG_F_CONNECTING) {
  2980. if (fd_flags != 0) {
  2981. int err = 0;
  2982. #if !defined(MG_ESP8266)
  2983. if (!(nc->flags & MG_F_UDP)) {
  2984. socklen_t len = sizeof(err);
  2985. int ret =
  2986. getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
  2987. if (ret != 0) {
  2988. err = 1;
  2989. } else if (err == EAGAIN || err == EWOULDBLOCK) {
  2990. err = 0;
  2991. }
  2992. }
  2993. #else
  2994. /*
  2995. * On ESP8266 we use blocking connect.
  2996. */
  2997. err = nc->err;
  2998. #endif
  2999. #if MG_ENABLE_SSL
  3000. if ((nc->flags & MG_F_SSL) && err == 0) {
  3001. mg_ssl_begin(nc);
  3002. } else {
  3003. mg_if_connect_cb(nc, err);
  3004. }
  3005. #else
  3006. mg_if_connect_cb(nc, err);
  3007. #endif
  3008. } else if (nc->err != 0) {
  3009. mg_if_connect_cb(nc, nc->err);
  3010. }
  3011. }
  3012. if (fd_flags & _MG_F_FD_CAN_READ) {
  3013. if (nc->flags & MG_F_UDP) {
  3014. mg_handle_udp_read(nc);
  3015. } else {
  3016. if (nc->flags & MG_F_LISTENING) {
  3017. /*
  3018. * We're not looping here, and accepting just one connection at
  3019. * a time. The reason is that eCos does not respect non-blocking
  3020. * flag on a listening socket and hangs in a loop.
  3021. */
  3022. mg_accept_conn(nc);
  3023. } else {
  3024. mg_handle_tcp_read(nc);
  3025. }
  3026. }
  3027. }
  3028. if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
  3029. if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
  3030. mg_write_to_socket(nc);
  3031. }
  3032. mg_if_poll(nc, (time_t) now);
  3033. mg_if_timer(nc, now);
  3034. }
  3035. if (worth_logging) {
  3036. DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
  3037. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  3038. }
  3039. }
  3040. #if MG_ENABLE_BROADCAST
  3041. static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
  3042. struct ctl_msg ctl_msg;
  3043. int len =
  3044. (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
  3045. size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
  3046. DBG(("read %d from ctl socket", len));
  3047. (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
  3048. if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
  3049. struct mg_connection *nc;
  3050. for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
  3051. ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message);
  3052. }
  3053. }
  3054. }
  3055. #endif
  3056. /* Associate a socket to a connection. */
  3057. void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) {
  3058. mg_set_non_blocking_mode(sock);
  3059. mg_set_close_on_exec(sock);
  3060. nc->sock = sock;
  3061. DBG(("%p %d", nc, sock));
  3062. }
  3063. void mg_socket_if_init(struct mg_iface *iface) {
  3064. (void) iface;
  3065. DBG(("%p using select()", iface->mgr));
  3066. #if MG_ENABLE_BROADCAST
  3067. do {
  3068. mg_socketpair(iface->mgr->ctl, SOCK_DGRAM);
  3069. } while (iface->mgr->ctl[0] == INVALID_SOCKET);
  3070. #endif
  3071. }
  3072. void mg_socket_if_free(struct mg_iface *iface) {
  3073. (void) iface;
  3074. }
  3075. void mg_socket_if_add_conn(struct mg_connection *nc) {
  3076. (void) nc;
  3077. }
  3078. void mg_socket_if_remove_conn(struct mg_connection *nc) {
  3079. (void) nc;
  3080. }
  3081. void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
  3082. if (sock != INVALID_SOCKET
  3083. #ifdef __unix__
  3084. && sock < (sock_t) FD_SETSIZE
  3085. #endif
  3086. ) {
  3087. FD_SET(sock, set);
  3088. if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
  3089. *max_fd = sock;
  3090. }
  3091. }
  3092. }
  3093. time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) {
  3094. struct mg_mgr *mgr = iface->mgr;
  3095. double now = mg_time();
  3096. double min_timer;
  3097. struct mg_connection *nc, *tmp;
  3098. struct timeval tv;
  3099. fd_set read_set, write_set, err_set;
  3100. sock_t max_fd = INVALID_SOCKET;
  3101. int num_fds, num_ev, num_timers = 0;
  3102. #ifdef __unix__
  3103. int try_dup = 1;
  3104. #endif
  3105. FD_ZERO(&read_set);
  3106. FD_ZERO(&write_set);
  3107. FD_ZERO(&err_set);
  3108. #if MG_ENABLE_BROADCAST
  3109. mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
  3110. #endif
  3111. /*
  3112. * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
  3113. * e.g. timer-only "connections".
  3114. */
  3115. min_timer = 0;
  3116. for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
  3117. tmp = nc->next;
  3118. if (nc->sock != INVALID_SOCKET) {
  3119. num_fds++;
  3120. #ifdef __unix__
  3121. /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */
  3122. if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) {
  3123. int new_sock = dup(nc->sock);
  3124. if (new_sock >= 0 && new_sock < (sock_t) FD_SETSIZE) {
  3125. closesocket(nc->sock);
  3126. DBG(("new sock %d -> %d", nc->sock, new_sock));
  3127. nc->sock = new_sock;
  3128. } else {
  3129. try_dup = 0;
  3130. }
  3131. }
  3132. #endif
  3133. if (!(nc->flags & MG_F_WANT_WRITE) &&
  3134. nc->recv_mbuf.len < nc->recv_mbuf_limit &&
  3135. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
  3136. mg_add_to_set(nc->sock, &read_set, &max_fd);
  3137. }
  3138. if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
  3139. (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
  3140. mg_add_to_set(nc->sock, &write_set, &max_fd);
  3141. mg_add_to_set(nc->sock, &err_set, &max_fd);
  3142. }
  3143. }
  3144. if (nc->ev_timer_time > 0) {
  3145. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  3146. min_timer = nc->ev_timer_time;
  3147. }
  3148. num_timers++;
  3149. }
  3150. }
  3151. /*
  3152. * If there is a timer to be fired earlier than the requested timeout,
  3153. * adjust the timeout.
  3154. */
  3155. if (num_timers > 0) {
  3156. double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
  3157. if (timer_timeout_ms < timeout_ms) {
  3158. timeout_ms = (int) timer_timeout_ms;
  3159. }
  3160. }
  3161. if (timeout_ms < 0) timeout_ms = 0;
  3162. tv.tv_sec = timeout_ms / 1000;
  3163. tv.tv_usec = (timeout_ms % 1000) * 1000;
  3164. num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
  3165. now = mg_time();
  3166. #if 0
  3167. DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
  3168. timeout_ms));
  3169. #endif
  3170. #if MG_ENABLE_BROADCAST
  3171. if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
  3172. FD_ISSET(mgr->ctl[1], &read_set)) {
  3173. mg_mgr_handle_ctl_sock(mgr);
  3174. }
  3175. #endif
  3176. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  3177. int fd_flags = 0;
  3178. if (nc->sock != INVALID_SOCKET) {
  3179. if (num_ev > 0) {
  3180. fd_flags = (FD_ISSET(nc->sock, &read_set) &&
  3181. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
  3182. ? _MG_F_FD_CAN_READ
  3183. : 0) |
  3184. (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
  3185. (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
  3186. }
  3187. #if MG_LWIP
  3188. /* With LWIP socket emulation layer, we don't get write events for UDP */
  3189. if ((nc->flags & MG_F_UDP) && nc->listener == NULL) {
  3190. fd_flags |= _MG_F_FD_CAN_WRITE;
  3191. }
  3192. #endif
  3193. }
  3194. tmp = nc->next;
  3195. mg_mgr_handle_conn(nc, fd_flags, now);
  3196. }
  3197. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  3198. tmp = nc->next;
  3199. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  3200. (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
  3201. mg_close_conn(nc);
  3202. }
  3203. }
  3204. return (time_t) now;
  3205. }
  3206. #if MG_ENABLE_BROADCAST
  3207. int mg_socketpair(sock_t sp[2], int sock_type) {
  3208. union socket_address sa;
  3209. sock_t sock;
  3210. socklen_t len = sizeof(sa.sin);
  3211. int ret = 0;
  3212. sock = sp[0] = sp[1] = INVALID_SOCKET;
  3213. (void) memset(&sa, 0, sizeof(sa));
  3214. sa.sin.sin_family = AF_INET;
  3215. sa.sin.sin_port = htons(0);
  3216. sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
  3217. if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
  3218. } else if (bind(sock, &sa.sa, len) != 0) {
  3219. } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
  3220. } else if (getsockname(sock, &sa.sa, &len) != 0) {
  3221. } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
  3222. } else if (connect(sp[0], &sa.sa, len) != 0) {
  3223. } else if (sock_type == SOCK_DGRAM &&
  3224. (getsockname(sp[0], &sa.sa, &len) != 0 ||
  3225. connect(sock, &sa.sa, len) != 0)) {
  3226. } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
  3227. : accept(sock, &sa.sa, &len))) ==
  3228. INVALID_SOCKET) {
  3229. } else {
  3230. mg_set_close_on_exec(sp[0]);
  3231. mg_set_close_on_exec(sp[1]);
  3232. if (sock_type == SOCK_STREAM) closesocket(sock);
  3233. ret = 1;
  3234. }
  3235. if (!ret) {
  3236. if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
  3237. if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
  3238. if (sock != INVALID_SOCKET) closesocket(sock);
  3239. sock = sp[0] = sp[1] = INVALID_SOCKET;
  3240. }
  3241. return ret;
  3242. }
  3243. #endif /* MG_ENABLE_BROADCAST */
  3244. static void mg_sock_get_addr(sock_t sock, int remote,
  3245. union socket_address *sa) {
  3246. socklen_t slen = sizeof(*sa);
  3247. memset(sa, 0, slen);
  3248. if (remote) {
  3249. getpeername(sock, &sa->sa, &slen);
  3250. } else {
  3251. getsockname(sock, &sa->sa, &slen);
  3252. }
  3253. }
  3254. void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
  3255. union socket_address sa;
  3256. mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
  3257. mg_sock_addr_to_str(&sa, buf, len, flags);
  3258. }
  3259. void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote,
  3260. union socket_address *sa) {
  3261. mg_sock_get_addr(nc->sock, remote, sa);
  3262. }
  3263. /* clang-format off */
  3264. #define MG_SOCKET_IFACE_VTABLE \
  3265. { \
  3266. mg_socket_if_init, \
  3267. mg_socket_if_free, \
  3268. mg_socket_if_add_conn, \
  3269. mg_socket_if_remove_conn, \
  3270. mg_socket_if_poll, \
  3271. mg_socket_if_listen_tcp, \
  3272. mg_socket_if_listen_udp, \
  3273. mg_socket_if_connect_tcp, \
  3274. mg_socket_if_connect_udp, \
  3275. mg_socket_if_tcp_send, \
  3276. mg_socket_if_udp_send, \
  3277. mg_socket_if_recved, \
  3278. mg_socket_if_create_conn, \
  3279. mg_socket_if_destroy_conn, \
  3280. mg_socket_if_sock_set, \
  3281. mg_socket_if_get_conn_addr, \
  3282. }
  3283. /* clang-format on */
  3284. struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE;
  3285. #if MG_NET_IF == MG_NET_IF_SOCKET
  3286. struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE;
  3287. #endif
  3288. #endif /* MG_ENABLE_NET_IF_SOCKET */
  3289. #ifdef MG_MODULE_LINES
  3290. #line 1 "mongoose/src/net_if_tun.c"
  3291. #endif
  3292. /*
  3293. * Copyright (c) 2014-2016 Cesanta Software Limited
  3294. * All rights reserved
  3295. */
  3296. #if MG_ENABLE_TUN
  3297. /* Amalgamated: #include "common/cs_dbg.h" */
  3298. /* Amalgamated: #include "common/cs_time.h" */
  3299. /* Amalgamated: #include "mongoose/src/internal.h" */
  3300. /* Amalgamated: #include "mongoose/src/net_if_tun.h" */
  3301. /* Amalgamated: #include "mongoose/src/tun.h" */
  3302. /* Amalgamated: #include "mongoose/src/util.h" */
  3303. #define MG_TCP_RECV_BUFFER_SIZE 1024
  3304. #define MG_UDP_RECV_BUFFER_SIZE 1500
  3305. void mg_tun_if_connect_tcp(struct mg_connection *nc,
  3306. const union socket_address *sa) {
  3307. (void) nc;
  3308. (void) sa;
  3309. }
  3310. void mg_tun_if_connect_udp(struct mg_connection *nc) {
  3311. (void) nc;
  3312. }
  3313. int mg_tun_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  3314. (void) nc;
  3315. (void) sa;
  3316. return 0;
  3317. }
  3318. int mg_tun_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  3319. (void) nc;
  3320. (void) sa;
  3321. return -1;
  3322. }
  3323. void mg_tun_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
  3324. struct mg_tun_client *client = (struct mg_tun_client *) nc->iface->data;
  3325. uint32_t stream_id = (uint32_t)(uintptr_t) nc->mgr_data;
  3326. struct mg_str msg = {(char *) buf, len};
  3327. #if MG_ENABLE_HEXDUMP
  3328. char hex[512];
  3329. mg_hexdump(buf, len, hex, sizeof(hex));
  3330. LOG(LL_DEBUG, ("sending to stream %zu:\n%s", stream_id, hex));
  3331. #endif
  3332. mg_tun_send_frame(client->disp, stream_id, MG_TUN_DATA_FRAME, 0, msg);
  3333. }
  3334. void mg_tun_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
  3335. (void) nc;
  3336. (void) buf;
  3337. (void) len;
  3338. }
  3339. void mg_tun_if_recved(struct mg_connection *nc, size_t len) {
  3340. (void) nc;
  3341. (void) len;
  3342. }
  3343. int mg_tun_if_create_conn(struct mg_connection *nc) {
  3344. (void) nc;
  3345. return 1;
  3346. }
  3347. void mg_tun_if_destroy_conn(struct mg_connection *nc) {
  3348. struct mg_tun_client *client = (struct mg_tun_client *) nc->iface->data;
  3349. if (nc->flags & MG_F_LISTENING) {
  3350. mg_tun_destroy_client(client);
  3351. } else if (client->disp) {
  3352. uint32_t stream_id = (uint32_t)(uintptr_t) nc->mgr_data;
  3353. struct mg_str msg = {NULL, 0};
  3354. LOG(LL_DEBUG, ("closing %zu:", stream_id));
  3355. mg_tun_send_frame(client->disp, stream_id, MG_TUN_DATA_FRAME,
  3356. MG_TUN_F_END_STREAM, msg);
  3357. }
  3358. }
  3359. /* Associate a socket to a connection. */
  3360. void mg_tun_if_sock_set(struct mg_connection *nc, sock_t sock) {
  3361. (void) nc;
  3362. (void) sock;
  3363. }
  3364. void mg_tun_if_init(struct mg_iface *iface) {
  3365. (void) iface;
  3366. }
  3367. void mg_tun_if_free(struct mg_iface *iface) {
  3368. (void) iface;
  3369. }
  3370. void mg_tun_if_add_conn(struct mg_connection *nc) {
  3371. nc->sock = INVALID_SOCKET;
  3372. }
  3373. void mg_tun_if_remove_conn(struct mg_connection *nc) {
  3374. (void) nc;
  3375. }
  3376. time_t mg_tun_if_poll(struct mg_iface *iface, int timeout_ms) {
  3377. (void) iface;
  3378. (void) timeout_ms;
  3379. return (time_t) cs_time();
  3380. }
  3381. void mg_tun_if_get_conn_addr(struct mg_connection *nc, int remote,
  3382. union socket_address *sa) {
  3383. (void) nc;
  3384. (void) remote;
  3385. (void) sa;
  3386. }
  3387. struct mg_connection *mg_tun_if_find_conn(struct mg_tun_client *client,
  3388. uint32_t stream_id) {
  3389. struct mg_connection *nc = NULL;
  3390. for (nc = client->mgr->active_connections; nc != NULL; nc = nc->next) {
  3391. if (nc->iface != client->iface || (nc->flags & MG_F_LISTENING)) {
  3392. continue;
  3393. }
  3394. if (stream_id == (uint32_t)(uintptr_t) nc->mgr_data) {
  3395. return nc;
  3396. }
  3397. }
  3398. if (stream_id > client->last_stream_id) {
  3399. /* create a new connection */
  3400. LOG(LL_DEBUG, ("new stream 0x%lx, accepting", stream_id));
  3401. nc = mg_if_accept_new_conn(client->listener);
  3402. nc->mgr_data = (void *) (uintptr_t) stream_id;
  3403. client->last_stream_id = stream_id;
  3404. } else {
  3405. LOG(LL_DEBUG, ("Ignoring stream 0x%lx (last_stream_id 0x%lx)", stream_id,
  3406. client->last_stream_id));
  3407. }
  3408. return nc;
  3409. }
  3410. /* clang-format off */
  3411. #define MG_TUN_IFACE_VTABLE \
  3412. { \
  3413. mg_tun_if_init, \
  3414. mg_tun_if_free, \
  3415. mg_tun_if_add_conn, \
  3416. mg_tun_if_remove_conn, \
  3417. mg_tun_if_poll, \
  3418. mg_tun_if_listen_tcp, \
  3419. mg_tun_if_listen_udp, \
  3420. mg_tun_if_connect_tcp, \
  3421. mg_tun_if_connect_udp, \
  3422. mg_tun_if_tcp_send, \
  3423. mg_tun_if_udp_send, \
  3424. mg_tun_if_recved, \
  3425. mg_tun_if_create_conn, \
  3426. mg_tun_if_destroy_conn, \
  3427. mg_tun_if_sock_set, \
  3428. mg_tun_if_get_conn_addr, \
  3429. }
  3430. /* clang-format on */
  3431. struct mg_iface_vtable mg_tun_iface_vtable = MG_TUN_IFACE_VTABLE;
  3432. #endif /* MG_ENABLE_TUN */
  3433. #ifdef MG_MODULE_LINES
  3434. #line 1 "mongoose/src/ssl_if_openssl.c"
  3435. #endif
  3436. /*
  3437. * Copyright (c) 2014-2016 Cesanta Software Limited
  3438. * All rights reserved
  3439. */
  3440. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
  3441. #ifdef __APPLE__
  3442. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3443. #endif
  3444. #include <openssl/ssl.h>
  3445. struct mg_ssl_if_ctx {
  3446. SSL *ssl;
  3447. SSL_CTX *ssl_ctx;
  3448. struct mbuf psk;
  3449. size_t identity_len;
  3450. };
  3451. void mg_ssl_if_init() {
  3452. SSL_library_init();
  3453. }
  3454. enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
  3455. struct mg_connection *lc) {
  3456. struct mg_ssl_if_ctx *ctx =
  3457. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  3458. struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
  3459. nc->ssl_if_data = ctx;
  3460. if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
  3461. ctx->ssl_ctx = lc_ctx->ssl_ctx;
  3462. if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
  3463. return MG_SSL_ERROR;
  3464. }
  3465. return MG_SSL_OK;
  3466. }
  3467. static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
  3468. const char *key, const char **err_msg);
  3469. static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert);
  3470. static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl);
  3471. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  3472. const char *identity,
  3473. const char *key_str);
  3474. enum mg_ssl_if_result mg_ssl_if_conn_init(
  3475. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  3476. const char **err_msg) {
  3477. struct mg_ssl_if_ctx *ctx =
  3478. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  3479. DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
  3480. (params->key ? params->key : ""),
  3481. (params->ca_cert ? params->ca_cert : "")));
  3482. if (ctx == NULL) {
  3483. MG_SET_PTRPTR(err_msg, "Out of memory");
  3484. return MG_SSL_ERROR;
  3485. }
  3486. nc->ssl_if_data = ctx;
  3487. if (nc->flags & MG_F_LISTENING) {
  3488. ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  3489. } else {
  3490. ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  3491. }
  3492. if (ctx->ssl_ctx == NULL) {
  3493. MG_SET_PTRPTR(err_msg, "Failed to create SSL context");
  3494. return MG_SSL_ERROR;
  3495. }
  3496. if (params->cert != NULL &&
  3497. mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
  3498. MG_SSL_OK) {
  3499. return MG_SSL_ERROR;
  3500. }
  3501. if (params->ca_cert != NULL &&
  3502. mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
  3503. MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
  3504. return MG_SSL_ERROR;
  3505. }
  3506. if (params->server_name != NULL) {
  3507. #ifdef KR_VERSION
  3508. SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
  3509. #else
  3510. /* TODO(rojer): Implement server name verification on OpenSSL. */
  3511. #endif
  3512. }
  3513. if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
  3514. MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
  3515. return MG_SSL_ERROR;
  3516. }
  3517. mbuf_init(&ctx->psk, 0);
  3518. if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
  3519. MG_SSL_OK) {
  3520. MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
  3521. return MG_SSL_ERROR;
  3522. }
  3523. if (!(nc->flags & MG_F_LISTENING) &&
  3524. (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
  3525. MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
  3526. return MG_SSL_ERROR;
  3527. }
  3528. nc->flags |= MG_F_SSL;
  3529. return MG_SSL_OK;
  3530. }
  3531. static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc,
  3532. int res) {
  3533. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3534. int err = SSL_get_error(ctx->ssl, res);
  3535. if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ;
  3536. if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE;
  3537. DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err));
  3538. nc->err = err;
  3539. return MG_SSL_ERROR;
  3540. }
  3541. enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
  3542. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3543. int server_side = (nc->listener != NULL);
  3544. int res;
  3545. /* If descriptor is not yet set, do it now. */
  3546. if (SSL_get_fd(ctx->ssl) < 0) {
  3547. if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR;
  3548. }
  3549. res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
  3550. if (res != 1) return mg_ssl_if_ssl_err(nc, res);
  3551. return MG_SSL_OK;
  3552. }
  3553. int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
  3554. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3555. int n = SSL_read(ctx->ssl, buf, buf_size);
  3556. DBG(("%p %d -> %d", nc, (int) buf_size, n));
  3557. if (n < 0) return mg_ssl_if_ssl_err(nc, n);
  3558. if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  3559. return n;
  3560. }
  3561. int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
  3562. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3563. int n = SSL_write(ctx->ssl, data, len);
  3564. DBG(("%p %d -> %d", nc, (int) len, n));
  3565. if (n <= 0) return mg_ssl_if_ssl_err(nc, n);
  3566. return n;
  3567. }
  3568. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  3569. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3570. if (ctx == NULL) return;
  3571. nc->ssl_if_data = NULL;
  3572. if (ctx->ssl != NULL) SSL_free(ctx->ssl);
  3573. if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
  3574. mbuf_free(&ctx->psk);
  3575. memset(ctx, 0, sizeof(*ctx));
  3576. MG_FREE(ctx);
  3577. }
  3578. /*
  3579. * Cipher suite options used for TLS negotiation.
  3580. * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
  3581. */
  3582. static const char mg_s_cipher_list[] =
  3583. #if defined(MG_SSL_CRYPTO_MODERN)
  3584. "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
  3585. "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
  3586. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  3587. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  3588. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  3589. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  3590. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  3591. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
  3592. "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
  3593. #elif defined(MG_SSL_CRYPTO_OLD)
  3594. "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
  3595. "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
  3596. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  3597. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  3598. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  3599. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  3600. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  3601. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
  3602. "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
  3603. "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
  3604. "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
  3605. "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
  3606. #else /* Default - intermediate. */
  3607. "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
  3608. "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
  3609. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  3610. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  3611. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  3612. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  3613. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  3614. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
  3615. "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
  3616. "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
  3617. "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
  3618. #endif
  3619. ;
  3620. /*
  3621. * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
  3622. * Will be used if none are provided by the user in the certificate file.
  3623. */
  3624. #if !MG_DISABLE_PFS && !defined(KR_VERSION)
  3625. static const char mg_s_default_dh_params[] =
  3626. "\
  3627. -----BEGIN DH PARAMETERS-----\n\
  3628. MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
  3629. Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
  3630. +E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
  3631. ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
  3632. wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
  3633. 9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
  3634. -----END DH PARAMETERS-----\n";
  3635. #endif
  3636. static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
  3637. if (cert == NULL || strcmp(cert, "*") == 0) {
  3638. return MG_SSL_OK;
  3639. }
  3640. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
  3641. return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
  3642. : MG_SSL_ERROR;
  3643. }
  3644. static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
  3645. const char *key,
  3646. const char **err_msg) {
  3647. if (key == NULL) key = cert;
  3648. if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
  3649. return MG_SSL_OK;
  3650. } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
  3651. MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
  3652. return MG_SSL_ERROR;
  3653. } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) {
  3654. MG_SET_PTRPTR(err_msg, "Invalid SSL key");
  3655. return MG_SSL_ERROR;
  3656. } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
  3657. MG_SET_PTRPTR(err_msg, "Invalid CA bundle");
  3658. return MG_SSL_ERROR;
  3659. } else {
  3660. SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  3661. #if !MG_DISABLE_PFS && !defined(KR_VERSION)
  3662. BIO *bio = NULL;
  3663. DH *dh = NULL;
  3664. /* Try to read DH parameters from the cert/key file. */
  3665. bio = BIO_new_file(cert, "r");
  3666. if (bio != NULL) {
  3667. dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  3668. BIO_free(bio);
  3669. }
  3670. /*
  3671. * If there are no DH params in the file, fall back to hard-coded ones.
  3672. * Not ideal, but better than nothing.
  3673. */
  3674. if (dh == NULL) {
  3675. bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
  3676. dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  3677. BIO_free(bio);
  3678. }
  3679. if (dh != NULL) {
  3680. SSL_CTX_set_tmp_dh(ctx, dh);
  3681. SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
  3682. DH_free(dh);
  3683. }
  3684. #if OPENSSL_VERSION_NUMBER > 0x10002000L
  3685. SSL_CTX_set_ecdh_auto(ctx, 1);
  3686. #endif
  3687. #endif
  3688. }
  3689. return MG_SSL_OK;
  3690. }
  3691. static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) {
  3692. return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
  3693. ? MG_SSL_OK
  3694. : MG_SSL_ERROR);
  3695. }
  3696. #ifndef KR_VERSION
  3697. static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint,
  3698. char *identity,
  3699. unsigned int max_identity_len,
  3700. unsigned char *psk,
  3701. unsigned int max_psk_len) {
  3702. struct mg_ssl_if_ctx *ctx =
  3703. (struct mg_ssl_if_ctx *) ssl->ctx->msg_callback_arg;
  3704. size_t key_len = ctx->psk.len - ctx->identity_len - 1;
  3705. DBG(("hint: '%s'", (hint ? hint : "")));
  3706. if (ctx->identity_len + 1 > max_identity_len) {
  3707. DBG(("identity too long"));
  3708. return 0;
  3709. }
  3710. if (key_len > max_psk_len) {
  3711. DBG(("key too long"));
  3712. return 0;
  3713. }
  3714. memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
  3715. memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
  3716. (void) ssl;
  3717. return key_len;
  3718. }
  3719. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  3720. const char *identity,
  3721. const char *key_str) {
  3722. unsigned char key[32];
  3723. size_t key_len;
  3724. size_t i = 0;
  3725. if (identity == NULL && key_str == NULL) return MG_SSL_OK;
  3726. if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
  3727. key_len = strlen(key_str);
  3728. if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
  3729. memset(key, 0, sizeof(key));
  3730. key_len = 0;
  3731. for (i = 0; key_str[i] != '\0'; i++) {
  3732. unsigned char c;
  3733. char hc = tolower((int) key_str[i]);
  3734. if (hc >= '0' && hc <= '9') {
  3735. c = hc - '0';
  3736. } else if (hc >= 'a' && hc <= 'f') {
  3737. c = hc - 'a' + 0xa;
  3738. } else {
  3739. return MG_SSL_ERROR;
  3740. }
  3741. key_len = i / 2;
  3742. key[key_len] <<= 4;
  3743. key[key_len] |= c;
  3744. }
  3745. key_len++;
  3746. DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
  3747. ctx->identity_len = strlen(identity);
  3748. mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
  3749. mbuf_append(&ctx->psk, key, key_len);
  3750. SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
  3751. /* Hack: there is no field for us to keep this, so we use msg_callback_arg */
  3752. ctx->ssl_ctx->msg_callback_arg = ctx;
  3753. return MG_SSL_OK;
  3754. }
  3755. #else
  3756. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  3757. const char *identity,
  3758. const char *key_str) {
  3759. (void) ctx;
  3760. (void) identity;
  3761. (void) key_str;
  3762. /* Krypton does not support PSK. */
  3763. return MG_SSL_ERROR;
  3764. }
  3765. #endif /* defined(KR_VERSION) */
  3766. const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
  3767. const char *ca_cert) {
  3768. const char *err_msg = NULL;
  3769. struct mg_ssl_if_conn_params params;
  3770. memset(&params, 0, sizeof(params));
  3771. params.cert = cert;
  3772. params.ca_cert = ca_cert;
  3773. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  3774. return err_msg;
  3775. }
  3776. return NULL;
  3777. }
  3778. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */
  3779. #ifdef MG_MODULE_LINES
  3780. #line 1 "mongoose/src/ssl_if_mbedtls.c"
  3781. #endif
  3782. /*
  3783. * Copyright (c) 2014-2016 Cesanta Software Limited
  3784. * All rights reserved
  3785. */
  3786. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
  3787. #include <mbedtls/debug.h>
  3788. #include <mbedtls/ecp.h>
  3789. #include <mbedtls/platform.h>
  3790. #include <mbedtls/ssl.h>
  3791. #include <mbedtls/x509_crt.h>
  3792. static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line,
  3793. const char *str) {
  3794. enum cs_log_level cs_level;
  3795. switch (level) {
  3796. case 1:
  3797. cs_level = LL_ERROR;
  3798. break;
  3799. case 2:
  3800. case 3:
  3801. cs_level = LL_DEBUG;
  3802. break;
  3803. default:
  3804. cs_level = LL_VERBOSE_DEBUG;
  3805. }
  3806. /* mbedTLS passes strings with \n at the end, strip it. */
  3807. LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str));
  3808. (void) file;
  3809. (void) line;
  3810. }
  3811. struct mg_ssl_if_ctx {
  3812. mbedtls_ssl_config *conf;
  3813. mbedtls_ssl_context *ssl;
  3814. mbedtls_x509_crt *cert;
  3815. mbedtls_pk_context *key;
  3816. mbedtls_x509_crt *ca_cert;
  3817. struct mbuf cipher_suites;
  3818. };
  3819. /* Must be provided by the platform. ctx is struct mg_connection. */
  3820. extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len);
  3821. void mg_ssl_if_init() {
  3822. }
  3823. enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
  3824. struct mg_connection *lc) {
  3825. struct mg_ssl_if_ctx *ctx =
  3826. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  3827. struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
  3828. nc->ssl_if_data = ctx;
  3829. if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
  3830. ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
  3831. if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
  3832. return MG_SSL_ERROR;
  3833. }
  3834. return MG_SSL_OK;
  3835. }
  3836. static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
  3837. const char *cert, const char *key,
  3838. const char **err_msg);
  3839. static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
  3840. const char *cert);
  3841. static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
  3842. const char *ciphers);
  3843. static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
  3844. const char *identity,
  3845. const char *key);
  3846. enum mg_ssl_if_result mg_ssl_if_conn_init(
  3847. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  3848. const char **err_msg) {
  3849. struct mg_ssl_if_ctx *ctx =
  3850. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  3851. DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
  3852. (params->key ? params->key : ""),
  3853. (params->ca_cert ? params->ca_cert : "")));
  3854. if (ctx == NULL) {
  3855. MG_SET_PTRPTR(err_msg, "Out of memory");
  3856. return MG_SSL_ERROR;
  3857. }
  3858. nc->ssl_if_data = ctx;
  3859. ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf));
  3860. mbuf_init(&ctx->cipher_suites, 0);
  3861. mbedtls_ssl_config_init(ctx->conf);
  3862. mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
  3863. if (mbedtls_ssl_config_defaults(
  3864. ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER
  3865. : MBEDTLS_SSL_IS_CLIENT),
  3866. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
  3867. MG_SET_PTRPTR(err_msg, "Failed to init SSL config");
  3868. return MG_SSL_ERROR;
  3869. }
  3870. /* TLS 1.2 and up */
  3871. mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  3872. MBEDTLS_SSL_MINOR_VERSION_3);
  3873. mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
  3874. if (params->cert != NULL &&
  3875. mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
  3876. return MG_SSL_ERROR;
  3877. }
  3878. if (params->ca_cert != NULL &&
  3879. mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
  3880. MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
  3881. return MG_SSL_ERROR;
  3882. }
  3883. if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
  3884. MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
  3885. return MG_SSL_ERROR;
  3886. }
  3887. if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
  3888. MG_SSL_OK) {
  3889. MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
  3890. return MG_SSL_ERROR;
  3891. }
  3892. if (!(nc->flags & MG_F_LISTENING)) {
  3893. ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
  3894. mbedtls_ssl_init(ctx->ssl);
  3895. if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
  3896. MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
  3897. return MG_SSL_ERROR;
  3898. }
  3899. if (params->server_name != NULL &&
  3900. mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
  3901. return MG_SSL_ERROR;
  3902. }
  3903. }
  3904. #ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
  3905. if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
  3906. #if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
  3907. MBEDTLS_SSL_MAX_FRAG_LEN_512
  3908. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
  3909. MBEDTLS_SSL_MAX_FRAG_LEN_1024
  3910. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
  3911. MBEDTLS_SSL_MAX_FRAG_LEN_2048
  3912. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
  3913. MBEDTLS_SSL_MAX_FRAG_LEN_4096
  3914. #else
  3915. #error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
  3916. #endif
  3917. ) != 0) {
  3918. return MG_SSL_ERROR;
  3919. }
  3920. #endif
  3921. nc->flags |= MG_F_SSL;
  3922. return MG_SSL_OK;
  3923. }
  3924. #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  3925. int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len);
  3926. int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len);
  3927. #else
  3928. static int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
  3929. struct mg_connection *nc = (struct mg_connection *) ctx;
  3930. int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
  3931. LOG(LL_DEBUG, ("%p %d -> %d", nc, (int) len, n));
  3932. if (n >= 0) return n;
  3933. n = mg_get_errno();
  3934. return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_WRITE : -1);
  3935. }
  3936. static int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
  3937. struct mg_connection *nc = (struct mg_connection *) ctx;
  3938. int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
  3939. LOG(LL_DEBUG, ("%p %d <- %d", nc, (int) len, n));
  3940. if (n >= 0) return n;
  3941. n = mg_get_errno();
  3942. return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_READ : -1);
  3943. }
  3944. #endif
  3945. static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
  3946. int ret) {
  3947. if (ret == MBEDTLS_ERR_SSL_WANT_READ) return MG_SSL_WANT_READ;
  3948. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) return MG_SSL_WANT_WRITE;
  3949. if (ret !=
  3950. MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { /* CLOSE_NOTIFY = Normal shutdown */
  3951. LOG(LL_ERROR, ("%p SSL error: %d", nc, ret));
  3952. }
  3953. nc->err = ret;
  3954. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  3955. return MG_SSL_ERROR;
  3956. }
  3957. static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) {
  3958. if (ctx->cert != NULL) {
  3959. mbedtls_x509_crt_free(ctx->cert);
  3960. MG_FREE(ctx->cert);
  3961. ctx->cert = NULL;
  3962. mbedtls_pk_free(ctx->key);
  3963. MG_FREE(ctx->key);
  3964. ctx->key = NULL;
  3965. }
  3966. if (ctx->ca_cert != NULL) {
  3967. mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
  3968. mbedtls_x509_crt_free(ctx->ca_cert);
  3969. MG_FREE(ctx->ca_cert);
  3970. ctx->ca_cert = NULL;
  3971. }
  3972. }
  3973. enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
  3974. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3975. int err;
  3976. /* If bio is not yet set, do it now. */
  3977. if (ctx->ssl->p_bio == NULL) {
  3978. mbedtls_ssl_set_bio(ctx->ssl, nc, ssl_socket_send, ssl_socket_recv, NULL);
  3979. }
  3980. err = mbedtls_ssl_handshake(ctx->ssl);
  3981. if (err != 0) return mg_ssl_if_mbed_err(nc, err);
  3982. #ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
  3983. /*
  3984. * Free the peer certificate, we don't need it after handshake.
  3985. * Note that this effectively disables renegotiation.
  3986. */
  3987. mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
  3988. mbedtls_free(ctx->ssl->session->peer_cert);
  3989. ctx->ssl->session->peer_cert = NULL;
  3990. /* On a client connection we can also free our own and CA certs. */
  3991. if (nc->listener == NULL) {
  3992. if (ctx->conf->key_cert != NULL) {
  3993. /* Note that this assumes one key_cert entry, which matches our init. */
  3994. MG_FREE(ctx->conf->key_cert);
  3995. ctx->conf->key_cert = NULL;
  3996. }
  3997. mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
  3998. mg_ssl_if_mbed_free_certs_and_keys(ctx);
  3999. }
  4000. #endif
  4001. return MG_SSL_OK;
  4002. }
  4003. int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
  4004. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4005. int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, buf_size);
  4006. DBG(("%p %d -> %d", nc, (int) buf_size, n));
  4007. if (n < 0) return mg_ssl_if_mbed_err(nc, n);
  4008. if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4009. return n;
  4010. }
  4011. int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
  4012. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4013. int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) data, len);
  4014. DBG(("%p %d -> %d", nc, (int) len, n));
  4015. if (n < 0) return mg_ssl_if_mbed_err(nc, n);
  4016. return n;
  4017. }
  4018. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  4019. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4020. if (ctx == NULL) return;
  4021. nc->ssl_if_data = NULL;
  4022. if (ctx->ssl != NULL) {
  4023. mbedtls_ssl_free(ctx->ssl);
  4024. MG_FREE(ctx->ssl);
  4025. }
  4026. mg_ssl_if_mbed_free_certs_and_keys(ctx);
  4027. if (ctx->conf != NULL) {
  4028. mbedtls_ssl_config_free(ctx->conf);
  4029. MG_FREE(ctx->conf);
  4030. }
  4031. mbuf_free(&ctx->cipher_suites);
  4032. memset(ctx, 0, sizeof(*ctx));
  4033. MG_FREE(ctx);
  4034. }
  4035. static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
  4036. const char *ca_cert) {
  4037. if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) {
  4038. return MG_SSL_OK;
  4039. }
  4040. ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert));
  4041. mbedtls_x509_crt_init(ctx->ca_cert);
  4042. if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
  4043. return MG_SSL_ERROR;
  4044. }
  4045. mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
  4046. mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  4047. return MG_SSL_OK;
  4048. }
  4049. static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
  4050. const char *cert, const char *key,
  4051. const char **err_msg) {
  4052. if (key == NULL) key = cert;
  4053. if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
  4054. return MG_SSL_OK;
  4055. }
  4056. ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert));
  4057. mbedtls_x509_crt_init(ctx->cert);
  4058. ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key));
  4059. mbedtls_pk_init(ctx->key);
  4060. if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
  4061. MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
  4062. return MG_SSL_ERROR;
  4063. }
  4064. if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) {
  4065. MG_SET_PTRPTR(err_msg, "Invalid SSL key");
  4066. return MG_SSL_ERROR;
  4067. }
  4068. if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
  4069. MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert");
  4070. return MG_SSL_ERROR;
  4071. }
  4072. return MG_SSL_OK;
  4073. }
  4074. static const int mg_s_cipher_list[] = {
  4075. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  4076. MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  4077. MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
  4078. MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
  4079. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
  4080. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
  4081. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
  4082. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
  4083. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
  4084. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
  4085. MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
  4086. MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
  4087. MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, 0};
  4088. /*
  4089. * Ciphers can be specified as a colon-separated list of cipher suite names.
  4090. * These can be found in
  4091. * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267
  4092. * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM
  4093. */
  4094. static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
  4095. const char *ciphers) {
  4096. if (ciphers != NULL) {
  4097. int l, id;
  4098. const char *s = ciphers, *e;
  4099. char tmp[50];
  4100. while (s != NULL) {
  4101. e = strchr(s, ':');
  4102. l = (e != NULL ? (e - s) : (int) strlen(s));
  4103. strncpy(tmp, s, l);
  4104. tmp[l] = '\0';
  4105. id = mbedtls_ssl_get_ciphersuite_id(tmp);
  4106. DBG(("%s -> %04x", tmp, id));
  4107. if (id != 0) {
  4108. mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
  4109. }
  4110. s = (e != NULL ? e + 1 : NULL);
  4111. }
  4112. if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR;
  4113. id = 0;
  4114. mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
  4115. mbuf_trim(&ctx->cipher_suites);
  4116. mbedtls_ssl_conf_ciphersuites(ctx->conf,
  4117. (const int *) ctx->cipher_suites.buf);
  4118. } else {
  4119. mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
  4120. }
  4121. return MG_SSL_OK;
  4122. }
  4123. static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
  4124. const char *identity,
  4125. const char *key_str) {
  4126. unsigned char key[32];
  4127. size_t key_len;
  4128. if (identity == NULL && key_str == NULL) return MG_SSL_OK;
  4129. if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
  4130. key_len = strlen(key_str);
  4131. if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
  4132. size_t i = 0;
  4133. memset(key, 0, sizeof(key));
  4134. key_len = 0;
  4135. for (i = 0; key_str[i] != '\0'; i++) {
  4136. unsigned char c;
  4137. char hc = tolower((int) key_str[i]);
  4138. if (hc >= '0' && hc <= '9') {
  4139. c = hc - '0';
  4140. } else if (hc >= 'a' && hc <= 'f') {
  4141. c = hc - 'a' + 0xa;
  4142. } else {
  4143. return MG_SSL_ERROR;
  4144. }
  4145. key_len = i / 2;
  4146. key[key_len] <<= 4;
  4147. key[key_len] |= c;
  4148. }
  4149. key_len++;
  4150. DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
  4151. /* mbedTLS makes copies of psk and identity. */
  4152. if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len,
  4153. (const unsigned char *) identity,
  4154. strlen(identity)) != 0) {
  4155. return MG_SSL_ERROR;
  4156. }
  4157. return MG_SSL_OK;
  4158. }
  4159. const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
  4160. const char *ca_cert) {
  4161. const char *err_msg = NULL;
  4162. struct mg_ssl_if_conn_params params;
  4163. memset(&params, 0, sizeof(params));
  4164. params.cert = cert;
  4165. params.ca_cert = ca_cert;
  4166. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  4167. return err_msg;
  4168. }
  4169. return NULL;
  4170. }
  4171. /* Lazy RNG. Warning: it would be a bad idea to do this in production! */
  4172. #ifdef MG_SSL_MBED_DUMMY_RANDOM
  4173. int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) {
  4174. (void) ctx;
  4175. while (len--) *buf++ = rand();
  4176. return 0;
  4177. }
  4178. #endif
  4179. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */
  4180. #ifdef MG_MODULE_LINES
  4181. #line 1 "mongoose/src/uri.c"
  4182. #endif
  4183. /*
  4184. * Copyright (c) 2014 Cesanta Software Limited
  4185. * All rights reserved
  4186. */
  4187. /* Amalgamated: #include "mongoose/src/internal.h" */
  4188. /* Amalgamated: #include "mongoose/src/uri.h" */
  4189. /*
  4190. * scan string until `sep`, keeping track of component boundaries in `res`.
  4191. *
  4192. * `p` will point to the char after the separator or it will be `end`.
  4193. */
  4194. static void parse_uri_component(const char **p, const char *end, char sep,
  4195. struct mg_str *res) {
  4196. res->p = *p;
  4197. for (; *p < end; (*p)++) {
  4198. if (**p == sep) {
  4199. break;
  4200. }
  4201. }
  4202. res->len = (*p) - res->p;
  4203. if (*p < end) (*p)++;
  4204. }
  4205. int mg_parse_uri(struct mg_str uri, struct mg_str *scheme,
  4206. struct mg_str *user_info, struct mg_str *host,
  4207. unsigned int *port, struct mg_str *path, struct mg_str *query,
  4208. struct mg_str *fragment) {
  4209. struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
  4210. rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
  4211. unsigned int rport = 0;
  4212. enum {
  4213. P_START,
  4214. P_SCHEME_OR_PORT,
  4215. P_USER_INFO,
  4216. P_HOST,
  4217. P_PORT,
  4218. P_REST
  4219. } state = P_START;
  4220. const char *p = uri.p, *end = p + uri.len;
  4221. while (p < end) {
  4222. switch (state) {
  4223. case P_START:
  4224. /*
  4225. * expecting on of:
  4226. * - `scheme://xxxx`
  4227. * - `xxxx:port`
  4228. * - `xxxx/path`
  4229. */
  4230. for (; p < end; p++) {
  4231. if (*p == ':') {
  4232. state = P_SCHEME_OR_PORT;
  4233. break;
  4234. } else if (*p == '/') {
  4235. state = P_REST;
  4236. break;
  4237. }
  4238. }
  4239. if (state == P_START || state == P_REST) {
  4240. rhost.p = uri.p;
  4241. rhost.len = p - uri.p;
  4242. }
  4243. break;
  4244. case P_SCHEME_OR_PORT:
  4245. if (end - p >= 3 && strncmp(p, "://", 3) == 0) {
  4246. rscheme.p = uri.p;
  4247. rscheme.len = p - uri.p;
  4248. state = P_USER_INFO;
  4249. p += 2; /* point to last separator char */
  4250. } else {
  4251. rhost.p = uri.p;
  4252. rhost.len = p - uri.p;
  4253. state = P_PORT;
  4254. }
  4255. break;
  4256. case P_USER_INFO:
  4257. p++;
  4258. ruser_info.p = p;
  4259. for (; p < end; p++) {
  4260. if (*p == '@') {
  4261. state = P_HOST;
  4262. break;
  4263. } else if (*p == '/') {
  4264. break;
  4265. }
  4266. }
  4267. if (p == end || *p == '/') {
  4268. /* backtrack and parse as host */
  4269. state = P_HOST;
  4270. p = ruser_info.p;
  4271. }
  4272. ruser_info.len = p - ruser_info.p;
  4273. break;
  4274. case P_HOST:
  4275. if (*p == '@') p++;
  4276. rhost.p = p;
  4277. for (; p < end; p++) {
  4278. if (*p == ':') {
  4279. state = P_PORT;
  4280. break;
  4281. } else if (*p == '/') {
  4282. state = P_REST;
  4283. break;
  4284. }
  4285. }
  4286. rhost.len = p - rhost.p;
  4287. break;
  4288. case P_PORT:
  4289. p++;
  4290. for (; p < end; p++) {
  4291. if (*p == '/') {
  4292. state = P_REST;
  4293. break;
  4294. }
  4295. rport *= 10;
  4296. rport += *p - '0';
  4297. }
  4298. break;
  4299. case P_REST:
  4300. /* `p` points to separator. `path` includes the separator */
  4301. parse_uri_component(&p, end, '?', &rpath);
  4302. parse_uri_component(&p, end, '#', &rquery);
  4303. parse_uri_component(&p, end, '\0', &rfragment);
  4304. break;
  4305. }
  4306. }
  4307. if (scheme != 0) *scheme = rscheme;
  4308. if (user_info != 0) *user_info = ruser_info;
  4309. if (host != 0) *host = rhost;
  4310. if (port != 0) *port = rport;
  4311. if (path != 0) *path = rpath;
  4312. if (query != 0) *query = rquery;
  4313. if (fragment != 0) *fragment = rfragment;
  4314. return 0;
  4315. }
  4316. /* Normalize the URI path. Remove/resolve "." and "..". */
  4317. int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
  4318. const char *s = in->p, *se = s + in->len;
  4319. char *cp = (char *) out->p, *d;
  4320. if (in->len == 0 || *s != '/') {
  4321. out->len = 0;
  4322. return 0;
  4323. }
  4324. d = cp;
  4325. while (s < se) {
  4326. const char *next = s;
  4327. struct mg_str component;
  4328. parse_uri_component(&next, se, '/', &component);
  4329. if (mg_vcmp(&component, ".") == 0) {
  4330. /* Yum. */
  4331. } else if (mg_vcmp(&component, "..") == 0) {
  4332. /* Backtrack to previous slash. */
  4333. if (d > cp + 1 && *(d - 1) == '/') d--;
  4334. while (d > cp && *(d - 1) != '/') d--;
  4335. } else {
  4336. memmove(d, s, next - s);
  4337. d += next - s;
  4338. }
  4339. s = next;
  4340. }
  4341. if (d == cp) *d++ = '/';
  4342. out->p = cp;
  4343. out->len = d - cp;
  4344. return 1;
  4345. }
  4346. #ifdef MG_MODULE_LINES
  4347. #line 1 "mongoose/src/http.c"
  4348. #endif
  4349. /*
  4350. * Copyright (c) 2014 Cesanta Software Limited
  4351. * All rights reserved
  4352. */
  4353. #if MG_ENABLE_HTTP
  4354. /* Amalgamated: #include "mongoose/src/internal.h" */
  4355. /* Amalgamated: #include "mongoose/src/util.h" */
  4356. /* Amalgamated: #include "common/sha1.h" */
  4357. /* Amalgamated: #include "common/md5.h" */
  4358. static const char *mg_version_header = "Mongoose/" MG_VERSION;
  4359. enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
  4360. struct mg_http_proto_data_file {
  4361. FILE *fp; /* Opened file. */
  4362. int64_t cl; /* Content-Length. How many bytes to send. */
  4363. int64_t sent; /* How many bytes have been already sent. */
  4364. int keepalive; /* Keep connection open after sending. */
  4365. enum mg_http_proto_data_type type;
  4366. };
  4367. #if MG_ENABLE_HTTP_CGI
  4368. struct mg_http_proto_data_cgi {
  4369. struct mg_connection *cgi_nc;
  4370. };
  4371. #endif
  4372. struct mg_http_proto_data_chuncked {
  4373. int64_t body_len; /* How many bytes of chunked body was reassembled. */
  4374. };
  4375. struct mg_http_endpoint {
  4376. struct mg_http_endpoint *next;
  4377. const char *name;
  4378. size_t name_len;
  4379. mg_event_handler_t handler;
  4380. };
  4381. enum mg_http_multipart_stream_state {
  4382. MPS_BEGIN,
  4383. MPS_WAITING_FOR_BOUNDARY,
  4384. MPS_WAITING_FOR_CHUNK,
  4385. MPS_GOT_CHUNK,
  4386. MPS_GOT_BOUNDARY,
  4387. MPS_FINALIZE,
  4388. MPS_FINISHED
  4389. };
  4390. struct mg_http_multipart_stream {
  4391. const char *boundary;
  4392. int boundary_len;
  4393. const char *var_name;
  4394. const char *file_name;
  4395. void *user_data;
  4396. int prev_io_len;
  4397. enum mg_http_multipart_stream_state state;
  4398. int processing_part;
  4399. };
  4400. struct mg_reverse_proxy_data {
  4401. struct mg_connection *linked_conn;
  4402. };
  4403. struct mg_http_proto_data {
  4404. #if MG_ENABLE_FILESYSTEM
  4405. struct mg_http_proto_data_file file;
  4406. #endif
  4407. #if MG_ENABLE_HTTP_CGI
  4408. struct mg_http_proto_data_cgi cgi;
  4409. #endif
  4410. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4411. struct mg_http_multipart_stream mp_stream;
  4412. #endif
  4413. struct mg_http_proto_data_chuncked chunk;
  4414. struct mg_http_endpoint *endpoints;
  4415. mg_event_handler_t endpoint_handler;
  4416. struct mg_reverse_proxy_data reverse_proxy_data;
  4417. };
  4418. static void mg_http_conn_destructor(void *proto_data);
  4419. struct mg_connection *mg_connect_http_base(
  4420. struct mg_mgr *mgr, mg_event_handler_t ev_handler,
  4421. struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
  4422. const char *url, const char **path, char **user, char **pass, char **addr);
  4423. static struct mg_http_proto_data *mg_http_get_proto_data(
  4424. struct mg_connection *c) {
  4425. if (c->proto_data == NULL) {
  4426. c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
  4427. c->proto_data_destructor = mg_http_conn_destructor;
  4428. }
  4429. return (struct mg_http_proto_data *) c->proto_data;
  4430. }
  4431. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4432. static void mg_http_free_proto_data_mp_stream(
  4433. struct mg_http_multipart_stream *mp) {
  4434. MG_FREE((void *) mp->boundary);
  4435. MG_FREE((void *) mp->var_name);
  4436. MG_FREE((void *) mp->file_name);
  4437. memset(mp, 0, sizeof(*mp));
  4438. }
  4439. #endif
  4440. #if MG_ENABLE_FILESYSTEM
  4441. static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
  4442. if (d != NULL) {
  4443. if (d->fp != NULL) {
  4444. fclose(d->fp);
  4445. }
  4446. memset(d, 0, sizeof(struct mg_http_proto_data_file));
  4447. }
  4448. }
  4449. #endif
  4450. static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
  4451. struct mg_http_endpoint *current = *ep;
  4452. while (current != NULL) {
  4453. struct mg_http_endpoint *tmp = current->next;
  4454. MG_FREE((void *) current->name);
  4455. MG_FREE(current);
  4456. current = tmp;
  4457. }
  4458. ep = NULL;
  4459. }
  4460. static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) {
  4461. if (rpd->linked_conn != NULL) {
  4462. /*
  4463. * Connection has linked one, we have to unlink & close it
  4464. * since _this_ connection is going to die and
  4465. * it doesn't make sense to keep another one
  4466. */
  4467. struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn);
  4468. if (pd->reverse_proxy_data.linked_conn != NULL) {
  4469. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  4470. pd->reverse_proxy_data.linked_conn = NULL;
  4471. }
  4472. rpd->linked_conn = NULL;
  4473. }
  4474. }
  4475. static void mg_http_conn_destructor(void *proto_data) {
  4476. struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
  4477. #if MG_ENABLE_FILESYSTEM
  4478. mg_http_free_proto_data_file(&pd->file);
  4479. #endif
  4480. #if MG_ENABLE_HTTP_CGI
  4481. mg_http_free_proto_data_cgi(&pd->cgi);
  4482. #endif
  4483. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4484. mg_http_free_proto_data_mp_stream(&pd->mp_stream);
  4485. #endif
  4486. mg_http_free_proto_data_endpoints(&pd->endpoints);
  4487. mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
  4488. MG_FREE(proto_data);
  4489. }
  4490. #if MG_ENABLE_FILESYSTEM
  4491. #define MIME_ENTRY(_ext, _type) \
  4492. { _ext, sizeof(_ext) - 1, _type }
  4493. static const struct {
  4494. const char *extension;
  4495. size_t ext_len;
  4496. const char *mime_type;
  4497. } mg_static_builtin_mime_types[] = {
  4498. MIME_ENTRY("html", "text/html"),
  4499. MIME_ENTRY("html", "text/html"),
  4500. MIME_ENTRY("htm", "text/html"),
  4501. MIME_ENTRY("shtm", "text/html"),
  4502. MIME_ENTRY("shtml", "text/html"),
  4503. MIME_ENTRY("css", "text/css"),
  4504. MIME_ENTRY("js", "application/x-javascript"),
  4505. MIME_ENTRY("ico", "image/x-icon"),
  4506. MIME_ENTRY("gif", "image/gif"),
  4507. MIME_ENTRY("jpg", "image/jpeg"),
  4508. MIME_ENTRY("jpeg", "image/jpeg"),
  4509. MIME_ENTRY("png", "image/png"),
  4510. MIME_ENTRY("svg", "image/svg+xml"),
  4511. MIME_ENTRY("txt", "text/plain"),
  4512. MIME_ENTRY("torrent", "application/x-bittorrent"),
  4513. MIME_ENTRY("wav", "audio/x-wav"),
  4514. MIME_ENTRY("mp3", "audio/x-mp3"),
  4515. MIME_ENTRY("mid", "audio/mid"),
  4516. MIME_ENTRY("m3u", "audio/x-mpegurl"),
  4517. MIME_ENTRY("ogg", "application/ogg"),
  4518. MIME_ENTRY("ram", "audio/x-pn-realaudio"),
  4519. MIME_ENTRY("xml", "text/xml"),
  4520. MIME_ENTRY("ttf", "application/x-font-ttf"),
  4521. MIME_ENTRY("json", "application/json"),
  4522. MIME_ENTRY("xslt", "application/xml"),
  4523. MIME_ENTRY("xsl", "application/xml"),
  4524. MIME_ENTRY("ra", "audio/x-pn-realaudio"),
  4525. MIME_ENTRY("doc", "application/msword"),
  4526. MIME_ENTRY("exe", "application/octet-stream"),
  4527. MIME_ENTRY("zip", "application/x-zip-compressed"),
  4528. MIME_ENTRY("xls", "application/excel"),
  4529. MIME_ENTRY("tgz", "application/x-tar-gz"),
  4530. MIME_ENTRY("tar", "application/x-tar"),
  4531. MIME_ENTRY("gz", "application/x-gunzip"),
  4532. MIME_ENTRY("arj", "application/x-arj-compressed"),
  4533. MIME_ENTRY("rar", "application/x-rar-compressed"),
  4534. MIME_ENTRY("rtf", "application/rtf"),
  4535. MIME_ENTRY("pdf", "application/pdf"),
  4536. MIME_ENTRY("swf", "application/x-shockwave-flash"),
  4537. MIME_ENTRY("mpg", "video/mpeg"),
  4538. MIME_ENTRY("webm", "video/webm"),
  4539. MIME_ENTRY("mpeg", "video/mpeg"),
  4540. MIME_ENTRY("mov", "video/quicktime"),
  4541. MIME_ENTRY("mp4", "video/mp4"),
  4542. MIME_ENTRY("m4v", "video/x-m4v"),
  4543. MIME_ENTRY("asf", "video/x-ms-asf"),
  4544. MIME_ENTRY("avi", "video/x-msvideo"),
  4545. MIME_ENTRY("bmp", "image/bmp"),
  4546. {NULL, 0, NULL}};
  4547. static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
  4548. const struct mg_serve_http_opts *opts) {
  4549. const char *ext, *overrides;
  4550. size_t i, path_len;
  4551. struct mg_str r, k, v;
  4552. path_len = strlen(path);
  4553. overrides = opts->custom_mime_types;
  4554. while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
  4555. ext = path + (path_len - k.len);
  4556. if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
  4557. return v;
  4558. }
  4559. }
  4560. for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
  4561. ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
  4562. if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
  4563. mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
  4564. r.p = mg_static_builtin_mime_types[i].mime_type;
  4565. r.len = strlen(r.p);
  4566. return r;
  4567. }
  4568. }
  4569. r.p = dflt;
  4570. r.len = strlen(r.p);
  4571. return r;
  4572. }
  4573. #endif
  4574. /*
  4575. * Check whether full request is buffered. Return:
  4576. * -1 if request is malformed
  4577. * 0 if request is not yet fully buffered
  4578. * >0 actual request length, including last \r\n\r\n
  4579. */
  4580. static int mg_http_get_request_len(const char *s, int buf_len) {
  4581. const unsigned char *buf = (unsigned char *) s;
  4582. int i;
  4583. for (i = 0; i < buf_len; i++) {
  4584. if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
  4585. return -1;
  4586. } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
  4587. return i + 2;
  4588. } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
  4589. buf[i + 2] == '\n') {
  4590. return i + 3;
  4591. }
  4592. }
  4593. return 0;
  4594. }
  4595. static const char *mg_http_parse_headers(const char *s, const char *end,
  4596. int len, struct http_message *req) {
  4597. int i = 0;
  4598. while (i < (int) ARRAY_SIZE(req->header_names) - 1) {
  4599. struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
  4600. s = mg_skip(s, end, ": ", k);
  4601. s = mg_skip(s, end, "\r\n", v);
  4602. while (v->len > 0 && v->p[v->len - 1] == ' ') {
  4603. v->len--; /* Trim trailing spaces in header value */
  4604. }
  4605. /*
  4606. * If header value is empty - skip it and go to next (if any).
  4607. * NOTE: Do not add it to headers_values because such addition changes API
  4608. * behaviour
  4609. */
  4610. if (k->len != 0 && v->len == 0) {
  4611. continue;
  4612. }
  4613. if (k->len == 0 || v->len == 0) {
  4614. k->p = v->p = NULL;
  4615. k->len = v->len = 0;
  4616. break;
  4617. }
  4618. if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
  4619. req->body.len = (size_t) to64(v->p);
  4620. req->message.len = len + req->body.len;
  4621. }
  4622. i++;
  4623. }
  4624. return s;
  4625. }
  4626. int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
  4627. const char *end, *qs;
  4628. int len = mg_http_get_request_len(s, n);
  4629. if (len <= 0) return len;
  4630. memset(hm, 0, sizeof(*hm));
  4631. hm->message.p = s;
  4632. hm->body.p = s + len;
  4633. hm->message.len = hm->body.len = (size_t) ~0;
  4634. end = s + len;
  4635. /* Request is fully buffered. Skip leading whitespaces. */
  4636. while (s < end && isspace(*(unsigned char *) s)) s++;
  4637. if (is_req) {
  4638. /* Parse request line: method, URI, proto */
  4639. s = mg_skip(s, end, " ", &hm->method);
  4640. s = mg_skip(s, end, " ", &hm->uri);
  4641. s = mg_skip(s, end, "\r\n", &hm->proto);
  4642. if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
  4643. /* If URI contains '?' character, initialize query_string */
  4644. if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
  4645. hm->query_string.p = qs + 1;
  4646. hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
  4647. hm->uri.len = qs - hm->uri.p;
  4648. }
  4649. } else {
  4650. s = mg_skip(s, end, " ", &hm->proto);
  4651. if (end - s < 4 || s[3] != ' ') return -1;
  4652. hm->resp_code = atoi(s);
  4653. if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
  4654. s += 4;
  4655. s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
  4656. }
  4657. s = mg_http_parse_headers(s, end, len, hm);
  4658. /*
  4659. * mg_parse_http() is used to parse both HTTP requests and HTTP
  4660. * responses. If HTTP response does not have Content-Length set, then
  4661. * body is read until socket is closed, i.e. body.len is infinite (~0).
  4662. *
  4663. * For HTTP requests though, according to
  4664. * http://tools.ietf.org/html/rfc7231#section-8.1.3,
  4665. * only POST and PUT methods have defined body semantics.
  4666. * Therefore, if Content-Length is not specified and methods are
  4667. * not one of PUT or POST, set body length to 0.
  4668. *
  4669. * So,
  4670. * if it is HTTP request, and Content-Length is not set,
  4671. * and method is not (PUT or POST) then reset body length to zero.
  4672. */
  4673. if (hm->body.len == (size_t) ~0 && is_req &&
  4674. mg_vcasecmp(&hm->method, "PUT") != 0 &&
  4675. mg_vcasecmp(&hm->method, "POST") != 0) {
  4676. hm->body.len = 0;
  4677. hm->message.len = len;
  4678. }
  4679. return len;
  4680. }
  4681. struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
  4682. size_t i, len = strlen(name);
  4683. for (i = 0; hm->header_names[i].len > 0; i++) {
  4684. struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
  4685. if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
  4686. return v;
  4687. }
  4688. return NULL;
  4689. }
  4690. #if MG_ENABLE_FILESYSTEM
  4691. static void mg_http_transfer_file_data(struct mg_connection *nc) {
  4692. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  4693. char buf[MG_MAX_HTTP_SEND_MBUF];
  4694. size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent);
  4695. if (pd->file.type == DATA_FILE) {
  4696. struct mbuf *io = &nc->send_mbuf;
  4697. if (io->len < sizeof(buf)) {
  4698. to_read = sizeof(buf) - io->len;
  4699. }
  4700. if (left > 0 && to_read > left) {
  4701. to_read = left;
  4702. }
  4703. if (to_read == 0) {
  4704. /* Rate limiting. send_mbuf is too full, wait until it's drained. */
  4705. } else if (pd->file.sent < pd->file.cl &&
  4706. (n = fread(buf, 1, to_read, pd->file.fp)) > 0) {
  4707. mg_send(nc, buf, n);
  4708. pd->file.sent += n;
  4709. } else {
  4710. if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
  4711. mg_http_free_proto_data_file(&pd->file);
  4712. }
  4713. } else if (pd->file.type == DATA_PUT) {
  4714. struct mbuf *io = &nc->recv_mbuf;
  4715. size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len;
  4716. size_t n = fwrite(io->buf, 1, to_write, pd->file.fp);
  4717. if (n > 0) {
  4718. mbuf_remove(io, n);
  4719. pd->file.sent += n;
  4720. }
  4721. if (n == 0 || pd->file.sent >= pd->file.cl) {
  4722. if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
  4723. mg_http_free_proto_data_file(&pd->file);
  4724. }
  4725. }
  4726. #if MG_ENABLE_HTTP_CGI
  4727. else if (pd->cgi.cgi_nc != NULL) {
  4728. /* This is POST data that needs to be forwarded to the CGI process */
  4729. if (pd->cgi.cgi_nc != NULL) {
  4730. mg_forward(nc, pd->cgi.cgi_nc);
  4731. } else {
  4732. nc->flags |= MG_F_SEND_AND_CLOSE;
  4733. }
  4734. }
  4735. #endif
  4736. }
  4737. #endif /* MG_ENABLE_FILESYSTEM */
  4738. /*
  4739. * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
  4740. * if it's incomplete. If the chunk is fully buffered, return total number of
  4741. * bytes in a chunk, and store data in `data`, `data_len`.
  4742. */
  4743. static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
  4744. size_t *chunk_len) {
  4745. unsigned char *s = (unsigned char *) buf;
  4746. size_t n = 0; /* scanned chunk length */
  4747. size_t i = 0; /* index in s */
  4748. /* Scan chunk length. That should be a hexadecimal number. */
  4749. while (i < len && isxdigit(s[i])) {
  4750. n *= 16;
  4751. n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
  4752. i++;
  4753. }
  4754. /* Skip new line */
  4755. if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
  4756. return 0;
  4757. }
  4758. i += 2;
  4759. /* Record where the data is */
  4760. *chunk_data = (char *) s + i;
  4761. *chunk_len = n;
  4762. /* Skip data */
  4763. i += n;
  4764. /* Skip new line */
  4765. if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
  4766. return 0;
  4767. }
  4768. return i + 2;
  4769. }
  4770. MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
  4771. struct http_message *hm, char *buf,
  4772. size_t blen) {
  4773. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  4774. char *data;
  4775. size_t i, n, data_len, body_len, zero_chunk_received = 0;
  4776. /* Find out piece of received data that is not yet reassembled */
  4777. body_len = (size_t) pd->chunk.body_len;
  4778. assert(blen >= body_len);
  4779. /* Traverse all fully buffered chunks */
  4780. for (i = body_len;
  4781. (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
  4782. i += n) {
  4783. /* Collapse chunk data to the rest of HTTP body */
  4784. memmove(buf + body_len, data, data_len);
  4785. body_len += data_len;
  4786. hm->body.len = body_len;
  4787. if (data_len == 0) {
  4788. zero_chunk_received = 1;
  4789. i += n;
  4790. break;
  4791. }
  4792. }
  4793. if (i > body_len) {
  4794. /* Shift unparsed content to the parsed body */
  4795. assert(i <= blen);
  4796. memmove(buf + body_len, buf + i, blen - i);
  4797. memset(buf + body_len + blen - i, 0, i - body_len);
  4798. nc->recv_mbuf.len -= i - body_len;
  4799. pd->chunk.body_len = body_len;
  4800. /* Send MG_EV_HTTP_CHUNK event */
  4801. nc->flags &= ~MG_F_DELETE_CHUNK;
  4802. mg_call(nc, nc->handler, MG_EV_HTTP_CHUNK, hm);
  4803. /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
  4804. if (nc->flags & MG_F_DELETE_CHUNK) {
  4805. memset(buf, 0, body_len);
  4806. memmove(buf, buf + body_len, blen - i);
  4807. nc->recv_mbuf.len -= body_len;
  4808. hm->body.len = 0;
  4809. pd->chunk.body_len = 0;
  4810. }
  4811. if (zero_chunk_received) {
  4812. /* Total message size is len(body) + len(headers) */
  4813. hm->message.len =
  4814. (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p);
  4815. }
  4816. }
  4817. return body_len;
  4818. }
  4819. static mg_event_handler_t mg_http_get_endpoint_handler(
  4820. struct mg_connection *nc, struct mg_str *uri_path) {
  4821. struct mg_http_proto_data *pd;
  4822. mg_event_handler_t ret = NULL;
  4823. int matched, matched_max = 0;
  4824. struct mg_http_endpoint *ep;
  4825. if (nc == NULL) {
  4826. return NULL;
  4827. }
  4828. pd = mg_http_get_proto_data(nc);
  4829. ep = pd->endpoints;
  4830. while (ep != NULL) {
  4831. const struct mg_str name_s = {ep->name, ep->name_len};
  4832. if ((matched = mg_match_prefix_n(name_s, *uri_path)) != -1) {
  4833. if (matched > matched_max) {
  4834. /* Looking for the longest suitable handler */
  4835. ret = ep->handler;
  4836. matched_max = matched;
  4837. }
  4838. }
  4839. ep = ep->next;
  4840. }
  4841. return ret;
  4842. }
  4843. static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
  4844. struct http_message *hm) {
  4845. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  4846. if (pd->endpoint_handler == NULL || ev == MG_EV_HTTP_REQUEST) {
  4847. pd->endpoint_handler =
  4848. ev == MG_EV_HTTP_REQUEST
  4849. ? mg_http_get_endpoint_handler(nc->listener, &hm->uri)
  4850. : NULL;
  4851. }
  4852. mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, ev,
  4853. hm);
  4854. }
  4855. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4856. static void mg_http_multipart_continue(struct mg_connection *nc);
  4857. static void mg_http_multipart_begin(struct mg_connection *nc,
  4858. struct http_message *hm, int req_len);
  4859. #endif
  4860. /*
  4861. * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
  4862. * If a big structure is declared in a big function, lx106 gcc will make it
  4863. * even bigger (round up to 4k, from 700 bytes of actual size).
  4864. */
  4865. #ifdef __xtensa__
  4866. static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
  4867. struct http_message *hm) __attribute__((noinline));
  4868. void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
  4869. struct http_message hm;
  4870. mg_http_handler2(nc, ev, ev_data, &hm);
  4871. }
  4872. static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
  4873. struct http_message *hm) {
  4874. #else /* !__XTENSA__ */
  4875. void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
  4876. struct http_message shm;
  4877. struct http_message *hm = &shm;
  4878. #endif /* __XTENSA__ */
  4879. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  4880. struct mbuf *io = &nc->recv_mbuf;
  4881. int req_len;
  4882. const int is_req = (nc->listener != NULL);
  4883. #if MG_ENABLE_HTTP_WEBSOCKET
  4884. struct mg_str *vec;
  4885. #endif
  4886. if (ev == MG_EV_CLOSE) {
  4887. #if MG_ENABLE_HTTP_CGI
  4888. /* Close associated CGI forwarder connection */
  4889. if (pd->cgi.cgi_nc != NULL) {
  4890. pd->cgi.cgi_nc->user_data = NULL;
  4891. pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4892. }
  4893. #endif
  4894. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4895. if (pd->mp_stream.boundary != NULL) {
  4896. /*
  4897. * Multipart message is in progress, but connection is closed.
  4898. * Finish part and request with an error flag.
  4899. */
  4900. struct mg_http_multipart_part mp;
  4901. memset(&mp, 0, sizeof(mp));
  4902. mp.status = -1;
  4903. mp.var_name = pd->mp_stream.var_name;
  4904. mp.file_name = pd->mp_stream.file_name;
  4905. mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
  4906. MG_EV_HTTP_PART_END, &mp);
  4907. mp.var_name = NULL;
  4908. mp.file_name = NULL;
  4909. mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
  4910. MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
  4911. } else
  4912. #endif
  4913. if (io->len > 0 && mg_parse_http(io->buf, io->len, hm, is_req) > 0) {
  4914. /*
  4915. * For HTTP messages without Content-Length, always send HTTP message
  4916. * before MG_EV_CLOSE message.
  4917. */
  4918. int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
  4919. hm->message.len = io->len;
  4920. hm->body.len = io->buf + io->len - hm->body.p;
  4921. mg_http_call_endpoint_handler(nc, ev2, hm);
  4922. }
  4923. }
  4924. #if MG_ENABLE_FILESYSTEM
  4925. if (pd->file.fp != NULL) {
  4926. mg_http_transfer_file_data(nc);
  4927. }
  4928. #endif
  4929. mg_call(nc, nc->handler, ev, ev_data);
  4930. if (ev == MG_EV_RECV) {
  4931. struct mg_str *s;
  4932. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4933. if (pd->mp_stream.boundary != NULL) {
  4934. mg_http_multipart_continue(nc);
  4935. return;
  4936. }
  4937. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  4938. req_len = mg_parse_http(io->buf, io->len, hm, is_req);
  4939. if (req_len > 0 &&
  4940. (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
  4941. mg_vcasecmp(s, "chunked") == 0) {
  4942. mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
  4943. }
  4944. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4945. if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
  4946. s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
  4947. mg_http_multipart_begin(nc, hm, req_len);
  4948. mg_http_multipart_continue(nc);
  4949. return;
  4950. }
  4951. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  4952. /* TODO(alashkin): refactor this ifelseifelseifelseifelse */
  4953. if ((req_len < 0 ||
  4954. (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
  4955. DBG(("invalid request"));
  4956. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4957. } else if (req_len == 0) {
  4958. /* Do nothing, request is not yet fully buffered */
  4959. }
  4960. #if MG_ENABLE_HTTP_WEBSOCKET
  4961. else if (nc->listener == NULL &&
  4962. mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
  4963. /* We're websocket client, got handshake response from server. */
  4964. /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
  4965. mbuf_remove(io, req_len);
  4966. nc->proto_handler = mg_ws_handler;
  4967. nc->flags |= MG_F_IS_WEBSOCKET;
  4968. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
  4969. mg_ws_handler(nc, MG_EV_RECV, ev_data);
  4970. } else if (nc->listener != NULL &&
  4971. (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
  4972. mg_event_handler_t handler;
  4973. /* This is a websocket request. Switch protocol handlers. */
  4974. mbuf_remove(io, req_len);
  4975. nc->proto_handler = mg_ws_handler;
  4976. nc->flags |= MG_F_IS_WEBSOCKET;
  4977. /*
  4978. * If we have a handler set up with mg_register_http_endpoint(),
  4979. * deliver subsequent websocket events to this handler after the
  4980. * protocol switch.
  4981. */
  4982. handler = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
  4983. if (handler != NULL) {
  4984. nc->handler = handler;
  4985. }
  4986. /* Send handshake */
  4987. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, hm);
  4988. if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) {
  4989. if (nc->send_mbuf.len == 0) {
  4990. mg_ws_handshake(nc, vec);
  4991. }
  4992. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
  4993. mg_ws_handler(nc, MG_EV_RECV, ev_data);
  4994. }
  4995. }
  4996. #endif /* MG_ENABLE_HTTP_WEBSOCKET */
  4997. else if (hm->message.len <= io->len) {
  4998. int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
  4999. /* Whole HTTP message is fully buffered, call event handler */
  5000. #if MG_ENABLE_JAVASCRIPT
  5001. v7_val_t v1, v2, headers, req, args, res;
  5002. struct v7 *v7 = nc->mgr->v7;
  5003. const char *ev_name = trigger_ev == MG_EV_HTTP_REPLY ? "onsnd" : "onrcv";
  5004. int i, js_callback_handled_request = 0;
  5005. if (v7 != NULL) {
  5006. /* Lookup JS callback */
  5007. v1 = v7_get(v7, v7_get_global(v7), "Http", ~0);
  5008. v2 = v7_get(v7, v1, ev_name, ~0);
  5009. /* Create callback params. TODO(lsm): own/disown those */
  5010. args = v7_mk_array(v7);
  5011. req = v7_mk_object(v7);
  5012. headers = v7_mk_object(v7);
  5013. /* Populate request object */
  5014. v7_set(v7, req, "method", ~0,
  5015. v7_mk_string(v7, hm->method.p, hm->method.len, 1));
  5016. v7_set(v7, req, "uri", ~0, v7_mk_string(v7, hm->uri.p, hm->uri.len, 1));
  5017. v7_set(v7, req, "body", ~0,
  5018. v7_mk_string(v7, hm->body.p, hm->body.len, 1));
  5019. v7_set(v7, req, "headers", ~0, headers);
  5020. for (i = 0; hm->header_names[i].len > 0; i++) {
  5021. const struct mg_str *name = &hm->header_names[i];
  5022. const struct mg_str *value = &hm->header_values[i];
  5023. v7_set(v7, headers, name->p, name->len,
  5024. v7_mk_string(v7, value->p, value->len, 1));
  5025. }
  5026. /* Invoke callback. TODO(lsm): report errors */
  5027. v7_array_push(v7, args, v7_mk_foreign(v7, nc));
  5028. v7_array_push(v7, args, req);
  5029. if (v7_apply(v7, v2, V7_UNDEFINED, args, &res) == V7_OK &&
  5030. v7_is_truthy(v7, res)) {
  5031. js_callback_handled_request++;
  5032. }
  5033. }
  5034. /* If JS callback returns true, stop request processing */
  5035. if (js_callback_handled_request) {
  5036. nc->flags |= MG_F_SEND_AND_CLOSE;
  5037. } else {
  5038. mg_http_call_endpoint_handler(nc, trigger_ev, hm);
  5039. }
  5040. #else
  5041. mg_http_call_endpoint_handler(nc, trigger_ev, hm);
  5042. #endif
  5043. mbuf_remove(io, hm->message.len);
  5044. }
  5045. }
  5046. (void) pd;
  5047. }
  5048. static size_t mg_get_line_len(const char *buf, size_t buf_len) {
  5049. size_t len = 0;
  5050. while (len < buf_len && buf[len] != '\n') len++;
  5051. return len == buf_len ? 0 : len + 1;
  5052. }
  5053. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5054. static void mg_http_multipart_begin(struct mg_connection *nc,
  5055. struct http_message *hm, int req_len) {
  5056. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  5057. struct mg_str *ct;
  5058. struct mbuf *io = &nc->recv_mbuf;
  5059. char boundary[100];
  5060. int boundary_len;
  5061. ct = mg_get_http_header(hm, "Content-Type");
  5062. if (ct == NULL) {
  5063. /* We need more data - or it isn't multipart mesage */
  5064. goto exit_mp;
  5065. }
  5066. /* Content-type should start with "multipart" */
  5067. if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
  5068. goto exit_mp;
  5069. }
  5070. boundary_len =
  5071. mg_http_parse_header(ct, "boundary", boundary, sizeof(boundary));
  5072. if (boundary_len == 0) {
  5073. /*
  5074. * Content type is multipart, but there is no boundary,
  5075. * probably malformed request
  5076. */
  5077. nc->flags = MG_F_CLOSE_IMMEDIATELY;
  5078. DBG(("invalid request"));
  5079. goto exit_mp;
  5080. }
  5081. /* If we reach this place - that is multipart request */
  5082. if (pd->mp_stream.boundary != NULL) {
  5083. /*
  5084. * Another streaming request was in progress,
  5085. * looks like protocol error
  5086. */
  5087. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  5088. } else {
  5089. pd->mp_stream.state = MPS_BEGIN;
  5090. pd->mp_stream.boundary = MG_STRDUP(boundary);
  5091. pd->mp_stream.boundary_len = strlen(boundary);
  5092. pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
  5093. pd->endpoint_handler = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
  5094. if (pd->endpoint_handler == NULL) {
  5095. pd->endpoint_handler = nc->handler;
  5096. }
  5097. mg_call(nc, pd->endpoint_handler, MG_EV_HTTP_MULTIPART_REQUEST, hm);
  5098. mbuf_remove(io, req_len);
  5099. }
  5100. exit_mp:
  5101. ;
  5102. }
  5103. #define CONTENT_DISPOSITION "Content-Disposition: "
  5104. static void mg_http_multipart_call_handler(struct mg_connection *c, int ev,
  5105. const char *data, size_t data_len) {
  5106. struct mg_http_multipart_part mp;
  5107. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5108. memset(&mp, 0, sizeof(mp));
  5109. mp.var_name = pd->mp_stream.var_name;
  5110. mp.file_name = pd->mp_stream.file_name;
  5111. mp.user_data = pd->mp_stream.user_data;
  5112. mp.data.p = data;
  5113. mp.data.len = data_len;
  5114. mg_call(c, pd->endpoint_handler, ev, &mp);
  5115. pd->mp_stream.user_data = mp.user_data;
  5116. }
  5117. static int mg_http_multipart_got_chunk(struct mg_connection *c) {
  5118. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5119. struct mbuf *io = &c->recv_mbuf;
  5120. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf,
  5121. pd->mp_stream.prev_io_len);
  5122. mbuf_remove(io, pd->mp_stream.prev_io_len);
  5123. pd->mp_stream.prev_io_len = 0;
  5124. pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
  5125. return 0;
  5126. }
  5127. static int mg_http_multipart_finalize(struct mg_connection *c) {
  5128. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5129. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
  5130. MG_FREE((void *) pd->mp_stream.file_name);
  5131. pd->mp_stream.file_name = NULL;
  5132. MG_FREE((void *) pd->mp_stream.var_name);
  5133. pd->mp_stream.var_name = NULL;
  5134. mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
  5135. mg_http_free_proto_data_mp_stream(&pd->mp_stream);
  5136. pd->mp_stream.state = MPS_FINISHED;
  5137. return 1;
  5138. }
  5139. static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
  5140. const char *boundary;
  5141. struct mbuf *io = &c->recv_mbuf;
  5142. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5143. if (pd->mp_stream.boundary == NULL) {
  5144. pd->mp_stream.state = MPS_FINALIZE;
  5145. DBG(("Invalid request: boundary not initialized"));
  5146. return 0;
  5147. }
  5148. if ((int) io->len < pd->mp_stream.boundary_len + 2) {
  5149. return 0;
  5150. }
  5151. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  5152. if (boundary != NULL) {
  5153. const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
  5154. if (io->len - (boundary_end - io->buf) < 4) {
  5155. return 0;
  5156. }
  5157. if (strncmp(boundary_end, "--\r\n", 4) == 0) {
  5158. pd->mp_stream.state = MPS_FINALIZE;
  5159. mbuf_remove(io, (boundary_end - io->buf) + 4);
  5160. } else {
  5161. pd->mp_stream.state = MPS_GOT_BOUNDARY;
  5162. }
  5163. } else {
  5164. return 0;
  5165. }
  5166. return 1;
  5167. }
  5168. static int mg_http_multipart_process_boundary(struct mg_connection *c) {
  5169. int data_size;
  5170. const char *boundary, *block_begin;
  5171. struct mbuf *io = &c->recv_mbuf;
  5172. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5173. char file_name[100], var_name[100];
  5174. int line_len;
  5175. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  5176. block_begin = boundary + pd->mp_stream.boundary_len + 2;
  5177. data_size = io->len - (block_begin - io->buf);
  5178. while (data_size > 0 &&
  5179. (line_len = mg_get_line_len(block_begin, data_size)) != 0) {
  5180. if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
  5181. mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
  5182. sizeof(CONTENT_DISPOSITION) - 1) == 0) {
  5183. struct mg_str header;
  5184. header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
  5185. header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
  5186. mg_http_parse_header(&header, "name", var_name, sizeof(var_name) - 2);
  5187. mg_http_parse_header(&header, "filename", file_name,
  5188. sizeof(file_name) - 2);
  5189. block_begin += line_len;
  5190. data_size -= line_len;
  5191. continue;
  5192. }
  5193. if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
  5194. mbuf_remove(io, block_begin - io->buf + 2);
  5195. if (pd->mp_stream.processing_part != 0) {
  5196. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
  5197. }
  5198. MG_FREE((void *) pd->mp_stream.file_name);
  5199. pd->mp_stream.file_name = MG_STRDUP(file_name);
  5200. MG_FREE((void *) pd->mp_stream.var_name);
  5201. pd->mp_stream.var_name = MG_STRDUP(var_name);
  5202. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
  5203. pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
  5204. pd->mp_stream.processing_part++;
  5205. return 1;
  5206. }
  5207. block_begin += line_len;
  5208. }
  5209. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  5210. return 0;
  5211. }
  5212. static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
  5213. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5214. struct mbuf *io = &c->recv_mbuf;
  5215. const char *boundary;
  5216. if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
  5217. return 0;
  5218. }
  5219. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  5220. if (boundary == NULL && pd->mp_stream.prev_io_len == 0) {
  5221. pd->mp_stream.prev_io_len = io->len;
  5222. return 0;
  5223. } else if (boundary == NULL &&
  5224. (int) io->len >
  5225. pd->mp_stream.prev_io_len + pd->mp_stream.boundary_len + 4) {
  5226. pd->mp_stream.state = MPS_GOT_CHUNK;
  5227. return 1;
  5228. } else if (boundary != NULL) {
  5229. int data_size = (boundary - io->buf - 4);
  5230. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_size);
  5231. mbuf_remove(io, (boundary - io->buf));
  5232. pd->mp_stream.prev_io_len = 0;
  5233. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  5234. return 1;
  5235. } else {
  5236. return 0;
  5237. }
  5238. }
  5239. static void mg_http_multipart_continue(struct mg_connection *c) {
  5240. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5241. while (1) {
  5242. switch (pd->mp_stream.state) {
  5243. case MPS_BEGIN: {
  5244. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  5245. break;
  5246. }
  5247. case MPS_WAITING_FOR_BOUNDARY: {
  5248. if (mg_http_multipart_wait_for_boundary(c) == 0) {
  5249. return;
  5250. }
  5251. break;
  5252. }
  5253. case MPS_GOT_BOUNDARY: {
  5254. if (mg_http_multipart_process_boundary(c) == 0) {
  5255. return;
  5256. }
  5257. break;
  5258. }
  5259. case MPS_WAITING_FOR_CHUNK: {
  5260. if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
  5261. return;
  5262. }
  5263. break;
  5264. }
  5265. case MPS_GOT_CHUNK: {
  5266. if (mg_http_multipart_got_chunk(c) == 0) {
  5267. return;
  5268. }
  5269. break;
  5270. }
  5271. case MPS_FINALIZE: {
  5272. if (mg_http_multipart_finalize(c) == 0) {
  5273. return;
  5274. }
  5275. break;
  5276. }
  5277. case MPS_FINISHED: {
  5278. mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
  5279. return;
  5280. }
  5281. }
  5282. }
  5283. }
  5284. struct file_upload_state {
  5285. char *lfn;
  5286. size_t num_recd;
  5287. FILE *fp;
  5288. };
  5289. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  5290. void mg_set_protocol_http_websocket(struct mg_connection *nc) {
  5291. nc->proto_handler = mg_http_handler;
  5292. }
  5293. const char *mg_status_message(int status_code) {
  5294. switch (status_code) {
  5295. case 206:
  5296. return "Partial Content";
  5297. case 301:
  5298. return "Moved";
  5299. case 302:
  5300. return "Found";
  5301. case 400:
  5302. return "Bad Request";
  5303. case 401:
  5304. return "Unauthorized";
  5305. case 403:
  5306. return "Forbidden";
  5307. case 404:
  5308. return "Not Found";
  5309. case 416:
  5310. return "Requested Range Not Satisfiable";
  5311. case 418:
  5312. return "I'm a teapot";
  5313. case 500:
  5314. return "Internal Server Error";
  5315. case 502:
  5316. return "Bad Gateway";
  5317. case 503:
  5318. return "Service Unavailable";
  5319. #if MG_ENABLE_EXTRA_ERRORS_DESC
  5320. case 100:
  5321. return "Continue";
  5322. case 101:
  5323. return "Switching Protocols";
  5324. case 102:
  5325. return "Processing";
  5326. case 200:
  5327. return "OK";
  5328. case 201:
  5329. return "Created";
  5330. case 202:
  5331. return "Accepted";
  5332. case 203:
  5333. return "Non-Authoritative Information";
  5334. case 204:
  5335. return "No Content";
  5336. case 205:
  5337. return "Reset Content";
  5338. case 207:
  5339. return "Multi-Status";
  5340. case 208:
  5341. return "Already Reported";
  5342. case 226:
  5343. return "IM Used";
  5344. case 300:
  5345. return "Multiple Choices";
  5346. case 303:
  5347. return "See Other";
  5348. case 304:
  5349. return "Not Modified";
  5350. case 305:
  5351. return "Use Proxy";
  5352. case 306:
  5353. return "Switch Proxy";
  5354. case 307:
  5355. return "Temporary Redirect";
  5356. case 308:
  5357. return "Permanent Redirect";
  5358. case 402:
  5359. return "Payment Required";
  5360. case 405:
  5361. return "Method Not Allowed";
  5362. case 406:
  5363. return "Not Acceptable";
  5364. case 407:
  5365. return "Proxy Authentication Required";
  5366. case 408:
  5367. return "Request Timeout";
  5368. case 409:
  5369. return "Conflict";
  5370. case 410:
  5371. return "Gone";
  5372. case 411:
  5373. return "Length Required";
  5374. case 412:
  5375. return "Precondition Failed";
  5376. case 413:
  5377. return "Payload Too Large";
  5378. case 414:
  5379. return "URI Too Long";
  5380. case 415:
  5381. return "Unsupported Media Type";
  5382. case 417:
  5383. return "Expectation Failed";
  5384. case 422:
  5385. return "Unprocessable Entity";
  5386. case 423:
  5387. return "Locked";
  5388. case 424:
  5389. return "Failed Dependency";
  5390. case 426:
  5391. return "Upgrade Required";
  5392. case 428:
  5393. return "Precondition Required";
  5394. case 429:
  5395. return "Too Many Requests";
  5396. case 431:
  5397. return "Request Header Fields Too Large";
  5398. case 451:
  5399. return "Unavailable For Legal Reasons";
  5400. case 501:
  5401. return "Not Implemented";
  5402. case 504:
  5403. return "Gateway Timeout";
  5404. case 505:
  5405. return "HTTP Version Not Supported";
  5406. case 506:
  5407. return "Variant Also Negotiates";
  5408. case 507:
  5409. return "Insufficient Storage";
  5410. case 508:
  5411. return "Loop Detected";
  5412. case 510:
  5413. return "Not Extended";
  5414. case 511:
  5415. return "Network Authentication Required";
  5416. #endif /* MG_ENABLE_EXTRA_ERRORS_DESC */
  5417. default:
  5418. return "OK";
  5419. }
  5420. }
  5421. void mg_send_response_line_s(struct mg_connection *nc, int status_code,
  5422. const struct mg_str extra_headers) {
  5423. mg_printf(nc, "HTTP/1.1 %d %s\r\nServer: %s\r\n", status_code,
  5424. mg_status_message(status_code), mg_version_header);
  5425. if (extra_headers.len > 0) {
  5426. mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p);
  5427. }
  5428. }
  5429. void mg_send_response_line(struct mg_connection *nc, int status_code,
  5430. const char *extra_headers) {
  5431. mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
  5432. }
  5433. void mg_http_send_redirect(struct mg_connection *nc, int status_code,
  5434. const struct mg_str location,
  5435. const struct mg_str extra_headers) {
  5436. char bbody[100], *pbody = bbody;
  5437. int bl = mg_asprintf(&pbody, sizeof(bbody),
  5438. "<p>Moved <a href='%.*s'>here</a>.\r\n",
  5439. (int) location.len, location.p);
  5440. char bhead[150], *phead = bhead;
  5441. mg_asprintf(&phead, sizeof(bhead),
  5442. "Location: %.*s\r\n"
  5443. "Content-Type: text/html\r\n"
  5444. "Content-Length: %d\r\n"
  5445. "Cache-Control: no-cache\r\n"
  5446. "%.*s%s",
  5447. (int) location.len, location.p, bl, (int) extra_headers.len,
  5448. extra_headers.p, (extra_headers.len > 0 ? "\r\n" : ""));
  5449. mg_send_response_line(nc, status_code, phead);
  5450. if (phead != bhead) MG_FREE(phead);
  5451. mg_send(nc, pbody, bl);
  5452. if (pbody != bbody) MG_FREE(pbody);
  5453. }
  5454. void mg_send_head(struct mg_connection *c, int status_code,
  5455. int64_t content_length, const char *extra_headers) {
  5456. mg_send_response_line(c, status_code, extra_headers);
  5457. if (content_length < 0) {
  5458. mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
  5459. } else {
  5460. mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
  5461. }
  5462. mg_send(c, "\r\n", 2);
  5463. }
  5464. void mg_http_send_error(struct mg_connection *nc, int code,
  5465. const char *reason) {
  5466. if (!reason) reason = mg_status_message(code);
  5467. LOG(LL_DEBUG, ("%p %d %s", nc, code, reason));
  5468. mg_send_head(nc, code, strlen(reason),
  5469. "Content-Type: text/plain\r\nConnection: close");
  5470. mg_send(nc, reason, strlen(reason));
  5471. nc->flags |= MG_F_SEND_AND_CLOSE;
  5472. }
  5473. #if MG_ENABLE_FILESYSTEM
  5474. static void mg_http_construct_etag(char *buf, size_t buf_len,
  5475. const cs_stat_t *st) {
  5476. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
  5477. (int64_t) st->st_size);
  5478. }
  5479. #ifndef WINCE
  5480. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  5481. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  5482. }
  5483. #else
  5484. /* Look wince_lib.c for WindowsCE implementation */
  5485. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t);
  5486. #endif
  5487. static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
  5488. int64_t *b) {
  5489. /*
  5490. * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
  5491. * so we have this. Ugh.
  5492. */
  5493. int result;
  5494. char *p = (char *) MG_MALLOC(header->len + 1);
  5495. if (p == NULL) return 0;
  5496. memcpy(p, header->p, header->len);
  5497. p[header->len] = '\0';
  5498. result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5499. MG_FREE(p);
  5500. return result;
  5501. }
  5502. void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
  5503. const char *path, const struct mg_str mime_type,
  5504. const struct mg_str extra_headers) {
  5505. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  5506. cs_stat_t st;
  5507. LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p));
  5508. if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) {
  5509. int code, err = mg_get_errno();
  5510. switch (err) {
  5511. case EACCES:
  5512. code = 403;
  5513. break;
  5514. case ENOENT:
  5515. code = 404;
  5516. break;
  5517. default:
  5518. code = 500;
  5519. };
  5520. mg_http_send_error(nc, code, "Open failed");
  5521. } else {
  5522. char etag[50], current_time[50], last_modified[50], range[70];
  5523. time_t t = (time_t) mg_time();
  5524. int64_t r1 = 0, r2 = 0, cl = st.st_size;
  5525. struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
  5526. int n, status_code = 200;
  5527. /* Handle Range header */
  5528. range[0] = '\0';
  5529. if (range_hdr != NULL &&
  5530. (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  5531. r2 >= 0) {
  5532. /* If range is specified like "400-", set second limit to content len */
  5533. if (n == 1) {
  5534. r2 = cl - 1;
  5535. }
  5536. if (r1 > r2 || r2 >= cl) {
  5537. status_code = 416;
  5538. cl = 0;
  5539. snprintf(range, sizeof(range),
  5540. "Content-Range: bytes */%" INT64_FMT "\r\n",
  5541. (int64_t) st.st_size);
  5542. } else {
  5543. status_code = 206;
  5544. cl = r2 - r1 + 1;
  5545. snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
  5546. "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5547. r1, r1 + cl - 1, (int64_t) st.st_size);
  5548. #if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
  5549. _XOPEN_SOURCE >= 600
  5550. fseeko(pd->file.fp, r1, SEEK_SET);
  5551. #else
  5552. fseek(pd->file.fp, (long) r1, SEEK_SET);
  5553. #endif
  5554. }
  5555. }
  5556. #if !MG_DISABLE_HTTP_KEEP_ALIVE
  5557. {
  5558. struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection");
  5559. if (conn_hdr != NULL) {
  5560. pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0);
  5561. } else {
  5562. pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0);
  5563. }
  5564. }
  5565. #endif
  5566. mg_http_construct_etag(etag, sizeof(etag), &st);
  5567. mg_gmt_time_string(current_time, sizeof(current_time), &t);
  5568. mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime);
  5569. /*
  5570. * Content length casted to size_t because:
  5571. * 1) that's the maximum buffer size anyway
  5572. * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
  5573. * position
  5574. * TODO(mkm): fix ESP8266 RTOS SDK
  5575. */
  5576. mg_send_response_line_s(nc, status_code, extra_headers);
  5577. mg_printf(nc,
  5578. "Date: %s\r\n"
  5579. "Last-Modified: %s\r\n"
  5580. "Accept-Ranges: bytes\r\n"
  5581. "Content-Type: %.*s\r\n"
  5582. "Connection: %s\r\n"
  5583. "Content-Length: %" SIZE_T_FMT
  5584. "\r\n"
  5585. "%sEtag: %s\r\n\r\n",
  5586. current_time, last_modified, (int) mime_type.len, mime_type.p,
  5587. (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
  5588. etag);
  5589. pd->file.cl = cl;
  5590. pd->file.type = DATA_FILE;
  5591. mg_http_transfer_file_data(nc);
  5592. }
  5593. }
  5594. static void mg_http_serve_file2(struct mg_connection *nc, const char *path,
  5595. struct http_message *hm,
  5596. struct mg_serve_http_opts *opts) {
  5597. #if MG_ENABLE_HTTP_SSI
  5598. if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) {
  5599. mg_handle_ssi_request(nc, hm, path, opts);
  5600. return;
  5601. }
  5602. #endif
  5603. mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts),
  5604. mg_mk_str(opts->extra_headers));
  5605. }
  5606. #endif
  5607. int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
  5608. int is_form_url_encoded) {
  5609. int i, j, a, b;
  5610. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  5611. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  5612. if (src[i] == '%') {
  5613. if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
  5614. isxdigit(*(const unsigned char *) (src + i + 2))) {
  5615. a = tolower(*(const unsigned char *) (src + i + 1));
  5616. b = tolower(*(const unsigned char *) (src + i + 2));
  5617. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  5618. i += 2;
  5619. } else {
  5620. return -1;
  5621. }
  5622. } else if (is_form_url_encoded && src[i] == '+') {
  5623. dst[j] = ' ';
  5624. } else {
  5625. dst[j] = src[i];
  5626. }
  5627. }
  5628. dst[j] = '\0'; /* Null-terminate the destination */
  5629. return i >= src_len ? j : -1;
  5630. }
  5631. int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
  5632. size_t dst_len) {
  5633. const char *p, *e, *s;
  5634. size_t name_len;
  5635. int len;
  5636. if (dst == NULL || dst_len == 0) {
  5637. len = -2;
  5638. } else if (buf->p == NULL || name == NULL || buf->len == 0) {
  5639. len = -1;
  5640. dst[0] = '\0';
  5641. } else {
  5642. name_len = strlen(name);
  5643. e = buf->p + buf->len;
  5644. len = -1;
  5645. dst[0] = '\0';
  5646. for (p = buf->p; p + name_len < e; p++) {
  5647. if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
  5648. !mg_ncasecmp(name, p, name_len)) {
  5649. p += name_len + 1;
  5650. s = (const char *) memchr(p, '&', (size_t)(e - p));
  5651. if (s == NULL) {
  5652. s = e;
  5653. }
  5654. len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
  5655. if (len == -1) {
  5656. len = -2;
  5657. }
  5658. break;
  5659. }
  5660. }
  5661. }
  5662. return len;
  5663. }
  5664. void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
  5665. char chunk_size[50];
  5666. int n;
  5667. n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
  5668. mg_send(nc, chunk_size, n);
  5669. mg_send(nc, buf, len);
  5670. mg_send(nc, "\r\n", 2);
  5671. }
  5672. void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
  5673. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  5674. int len;
  5675. va_list ap;
  5676. va_start(ap, fmt);
  5677. len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
  5678. va_end(ap);
  5679. if (len >= 0) {
  5680. mg_send_http_chunk(nc, buf, len);
  5681. }
  5682. /* LCOV_EXCL_START */
  5683. if (buf != mem && buf != NULL) {
  5684. MG_FREE(buf);
  5685. }
  5686. /* LCOV_EXCL_STOP */
  5687. }
  5688. void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
  5689. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  5690. int i, j, len;
  5691. va_list ap;
  5692. va_start(ap, fmt);
  5693. len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
  5694. va_end(ap);
  5695. if (len >= 0) {
  5696. for (i = j = 0; i < len; i++) {
  5697. if (buf[i] == '<' || buf[i] == '>') {
  5698. mg_send(nc, buf + j, i - j);
  5699. mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4);
  5700. j = i + 1;
  5701. }
  5702. }
  5703. mg_send(nc, buf + j, i - j);
  5704. }
  5705. /* LCOV_EXCL_START */
  5706. if (buf != mem && buf != NULL) {
  5707. MG_FREE(buf);
  5708. }
  5709. /* LCOV_EXCL_STOP */
  5710. }
  5711. int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
  5712. size_t buf_size) {
  5713. int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name);
  5714. const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
  5715. if (buf != NULL && buf_size > 0) buf[0] = '\0';
  5716. if (hdr == NULL) return 0;
  5717. /* Find where variable starts */
  5718. for (s = hdr->p; s != NULL && s + n < end; s++) {
  5719. if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') &&
  5720. s[n] == '=' && !strncmp(s, var_name, n))
  5721. break;
  5722. }
  5723. if (s != NULL && &s[n + 1] < end) {
  5724. s += n + 1;
  5725. if (*s == '"' || *s == '\'') {
  5726. ch = ch1 = *s++;
  5727. }
  5728. p = s;
  5729. while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
  5730. if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
  5731. buf[len++] = *p++;
  5732. }
  5733. if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
  5734. len = 0;
  5735. } else {
  5736. if (len > 0 && s[len - 1] == ',') len--;
  5737. if (len > 0 && s[len - 1] == ';') len--;
  5738. buf[len] = '\0';
  5739. }
  5740. }
  5741. return len;
  5742. }
  5743. int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
  5744. char *pass, size_t pass_len) {
  5745. struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
  5746. if (hdr == NULL) return -1;
  5747. return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len);
  5748. }
  5749. int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
  5750. char *pass, size_t pass_len) {
  5751. char *buf = NULL;
  5752. char fmt[64];
  5753. int res = 0;
  5754. if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1;
  5755. buf = (char *) MG_MALLOC(hdr->len);
  5756. cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
  5757. /* e.g. "%123[^:]:%321[^\n]" */
  5758. snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]",
  5759. user_len - 1, pass_len - 1);
  5760. if (sscanf(buf, fmt, user, pass) == 0) {
  5761. res = -1;
  5762. }
  5763. MG_FREE(buf);
  5764. return res;
  5765. }
  5766. #if MG_ENABLE_FILESYSTEM
  5767. static int mg_is_file_hidden(const char *path,
  5768. const struct mg_serve_http_opts *opts,
  5769. int exclude_specials) {
  5770. const char *p1 = opts->per_directory_auth_file;
  5771. const char *p2 = opts->hidden_file_pattern;
  5772. /* Strip directory path from the file name */
  5773. const char *pdir = strrchr(path, DIRSEP);
  5774. if (pdir != NULL) {
  5775. path = pdir + 1;
  5776. }
  5777. return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
  5778. (p1 != NULL &&
  5779. mg_match_prefix(p1, strlen(p1), path) == (int) strlen(p1)) ||
  5780. (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
  5781. }
  5782. #if !MG_DISABLE_HTTP_DIGEST_AUTH
  5783. static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
  5784. size_t uri_len, const char *ha1, size_t ha1_len,
  5785. const char *nonce, size_t nonce_len, const char *nc,
  5786. size_t nc_len, const char *cnonce, size_t cnonce_len,
  5787. const char *qop, size_t qop_len, char *resp) {
  5788. static const char colon[] = ":";
  5789. static const size_t one = 1;
  5790. char ha2[33];
  5791. cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
  5792. cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
  5793. nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
  5794. colon, one, ha2, sizeof(ha2) - 1, NULL);
  5795. }
  5796. int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
  5797. const char *method, const char *uri,
  5798. const char *auth_domain, const char *user,
  5799. const char *passwd) {
  5800. static const char colon[] = ":", qop[] = "auth";
  5801. static const size_t one = 1;
  5802. char ha1[33], resp[33], cnonce[40];
  5803. snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) mg_time());
  5804. cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
  5805. (size_t) strlen(auth_domain), colon, one, passwd,
  5806. (size_t) strlen(passwd), NULL);
  5807. mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
  5808. cnonce, strlen(cnonce), "1", one, cnonce, strlen(cnonce), qop,
  5809. sizeof(qop) - 1, resp);
  5810. return snprintf(buf, buf_len,
  5811. "Authorization: Digest username=\"%s\","
  5812. "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
  5813. "nonce=%s,response=%s\r\n",
  5814. user, auth_domain, uri, qop, cnonce, cnonce, resp);
  5815. }
  5816. /*
  5817. * Check for authentication timeout.
  5818. * Clients send time stamp encoded in nonce. Make sure it is not too old,
  5819. * to prevent replay attacks.
  5820. * Assumption: nonce is a hexadecimal number of seconds since 1970.
  5821. */
  5822. static int mg_check_nonce(const char *nonce) {
  5823. unsigned long now = (unsigned long) mg_time();
  5824. unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
  5825. return now < val || now - val < 3600;
  5826. }
  5827. int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
  5828. FILE *fp) {
  5829. struct mg_str *hdr;
  5830. char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
  5831. char user[50], cnonce[33], response[40], uri[200], qop[20], nc[20], nonce[30];
  5832. char expected_response[33];
  5833. /* Parse "Authorization:" header, fail fast on parse error */
  5834. if (hm == NULL || fp == NULL ||
  5835. (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
  5836. mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 ||
  5837. mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 ||
  5838. mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 ||
  5839. mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 ||
  5840. mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 ||
  5841. mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 ||
  5842. mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 ||
  5843. mg_check_nonce(nonce) == 0) {
  5844. return 0;
  5845. }
  5846. /*
  5847. * Read passwords file line by line. If should have htdigest format,
  5848. * i.e. each line should be a colon-separated sequence:
  5849. * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
  5850. */
  5851. while (fgets(buf, sizeof(buf), fp) != NULL) {
  5852. if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
  5853. strcmp(user, f_user) == 0 &&
  5854. /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
  5855. strcmp(auth_domain, f_domain) == 0) {
  5856. /* User and domain matched, check the password */
  5857. mg_mkmd5resp(
  5858. hm->method.p, hm->method.len, hm->uri.p,
  5859. hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0),
  5860. f_ha1, strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce,
  5861. strlen(cnonce), qop, strlen(qop), expected_response);
  5862. return mg_casecmp(response, expected_response) == 0;
  5863. }
  5864. }
  5865. /* None of the entries in the passwords file matched - return failure */
  5866. return 0;
  5867. }
  5868. static int mg_is_authorized(struct http_message *hm, const char *path,
  5869. int is_directory, const char *domain,
  5870. const char *passwords_file,
  5871. int is_global_pass_file) {
  5872. char buf[MG_MAX_PATH];
  5873. const char *p;
  5874. FILE *fp;
  5875. int authorized = 1;
  5876. if (domain != NULL && passwords_file != NULL) {
  5877. if (is_global_pass_file) {
  5878. fp = mg_fopen(passwords_file, "r");
  5879. } else if (is_directory) {
  5880. snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP, passwords_file);
  5881. fp = mg_fopen(buf, "r");
  5882. } else {
  5883. p = strrchr(path, DIRSEP);
  5884. if (p == NULL) p = path;
  5885. snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path), path, DIRSEP,
  5886. passwords_file);
  5887. fp = mg_fopen(buf, "r");
  5888. }
  5889. if (fp != NULL) {
  5890. authorized = mg_http_check_digest_auth(hm, domain, fp);
  5891. fclose(fp);
  5892. }
  5893. }
  5894. LOG(LL_DEBUG, ("%s '%s' %d %d", path, passwords_file ? passwords_file : "",
  5895. is_global_pass_file, authorized));
  5896. return authorized;
  5897. }
  5898. #else
  5899. static int mg_is_authorized(struct http_message *hm, const char *path,
  5900. int is_directory, const char *domain,
  5901. const char *passwords_file,
  5902. int is_global_pass_file) {
  5903. (void) hm;
  5904. (void) path;
  5905. (void) is_directory;
  5906. (void) domain;
  5907. (void) passwords_file;
  5908. (void) is_global_pass_file;
  5909. return 1;
  5910. }
  5911. #endif
  5912. #if MG_ENABLE_DIRECTORY_LISTING
  5913. static size_t mg_url_encode(const char *src, size_t s_len, char *dst,
  5914. size_t dst_len) {
  5915. static const char *dont_escape = "._-$,;~()/";
  5916. static const char *hex = "0123456789abcdef";
  5917. size_t i = 0, j = 0;
  5918. for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
  5919. if (isalnum(*(const unsigned char *) (src + i)) ||
  5920. strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) {
  5921. dst[j] = src[i];
  5922. } else if (j + 3 < dst_len) {
  5923. dst[j] = '%';
  5924. dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4];
  5925. dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf];
  5926. j += 2;
  5927. }
  5928. }
  5929. dst[j] = '\0';
  5930. return j;
  5931. }
  5932. static void mg_escape(const char *src, char *dst, size_t dst_len) {
  5933. size_t n = 0;
  5934. while (*src != '\0' && n + 5 < dst_len) {
  5935. unsigned char ch = *(unsigned char *) src++;
  5936. if (ch == '<') {
  5937. n += snprintf(dst + n, dst_len - n, "%s", "&lt;");
  5938. } else {
  5939. dst[n++] = ch;
  5940. }
  5941. }
  5942. dst[n] = '\0';
  5943. }
  5944. static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
  5945. cs_stat_t *stp) {
  5946. char size[64], mod[64], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE];
  5947. int64_t fsize = stp->st_size;
  5948. int is_dir = S_ISDIR(stp->st_mode);
  5949. const char *slash = is_dir ? "/" : "";
  5950. if (is_dir) {
  5951. snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
  5952. } else {
  5953. /*
  5954. * We use (double) cast below because MSVC 6 compiler cannot
  5955. * convert unsigned __int64 to double.
  5956. */
  5957. if (fsize < 1024) {
  5958. snprintf(size, sizeof(size), "%d", (int) fsize);
  5959. } else if (fsize < 0x100000) {
  5960. snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
  5961. } else if (fsize < 0x40000000) {
  5962. snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
  5963. } else {
  5964. snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
  5965. }
  5966. }
  5967. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
  5968. mg_escape(file_name, path, sizeof(path));
  5969. mg_url_encode(file_name, strlen(file_name), href, sizeof(href));
  5970. mg_printf_http_chunk(nc,
  5971. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  5972. "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
  5973. href, slash, path, slash, mod, is_dir ? -1 : fsize,
  5974. size);
  5975. }
  5976. static void mg_scan_directory(struct mg_connection *nc, const char *dir,
  5977. const struct mg_serve_http_opts *opts,
  5978. void (*func)(struct mg_connection *, const char *,
  5979. cs_stat_t *)) {
  5980. char path[MAX_PATH_SIZE];
  5981. cs_stat_t st;
  5982. struct dirent *dp;
  5983. DIR *dirp;
  5984. LOG(LL_DEBUG, ("%p [%s]", nc, dir));
  5985. if ((dirp = (opendir(dir))) != NULL) {
  5986. while ((dp = readdir(dirp)) != NULL) {
  5987. /* Do not show current dir and hidden files */
  5988. if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
  5989. continue;
  5990. }
  5991. snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
  5992. if (mg_stat(path, &st) == 0) {
  5993. func(nc, (const char *) dp->d_name, &st);
  5994. }
  5995. }
  5996. closedir(dirp);
  5997. } else {
  5998. LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno()));
  5999. }
  6000. }
  6001. static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
  6002. struct http_message *hm,
  6003. struct mg_serve_http_opts *opts) {
  6004. static const char *sort_js_code =
  6005. "<script>function srt(tb, sc, so, d) {"
  6006. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  6007. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  6008. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  6009. "t1 = a.cells[2].getAttribute('name'), "
  6010. "t2 = b.cells[2].getAttribute('name'); "
  6011. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  6012. "n1 ? parseInt(n2) - parseInt(n1) : "
  6013. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  6014. static const char *sort_js_code2 =
  6015. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  6016. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  6017. "};"
  6018. "window.onload = function() {"
  6019. "var tb = document.getElementById('tb');"
  6020. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  6021. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  6022. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  6023. "sc = c; ev.preventDefault();}};"
  6024. "srt(tb, sc, so, true);"
  6025. "}"
  6026. "</script>";
  6027. mg_send_response_line(nc, 200, opts->extra_headers);
  6028. mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
  6029. "Content-Type", "text/html; charset=utf-8");
  6030. mg_printf_http_chunk(
  6031. nc,
  6032. "<html><head><title>Index of %.*s</title>%s%s"
  6033. "<style>th,td {text-align: left; padding-right: 1em; "
  6034. "font-family: monospace; }</style></head>\n"
  6035. "<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>"
  6036. "<tr><th><a href=# rel=0>Name</a></th><th>"
  6037. "<a href=# rel=1>Modified</a</th>"
  6038. "<th><a href=# rel=2>Size</a></th></tr>"
  6039. "<tr><td colspan=3><hr></td></tr>\n"
  6040. "</thead>\n"
  6041. "<tbody id=tb>",
  6042. (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
  6043. (int) hm->uri.len, hm->uri.p);
  6044. mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
  6045. mg_printf_http_chunk(nc,
  6046. "</tbody><tr><td colspan=3><hr></td></tr>\n"
  6047. "</table>\n"
  6048. "<address>%s</address>\n"
  6049. "</body></html>",
  6050. mg_version_header);
  6051. mg_send_http_chunk(nc, "", 0);
  6052. /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
  6053. nc->flags |= MG_F_SEND_AND_CLOSE;
  6054. }
  6055. #endif /* MG_ENABLE_DIRECTORY_LISTING */
  6056. /*
  6057. * Given a directory path, find one of the files specified in the
  6058. * comma-separated list of index files `list`.
  6059. * First found index file wins. If an index file is found, then gets
  6060. * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
  6061. * If index file is not found, then `path` and `stp` remain unchanged.
  6062. */
  6063. MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
  6064. char **index_file, cs_stat_t *stp) {
  6065. struct mg_str vec;
  6066. size_t path_len = strlen(path);
  6067. int found = 0;
  6068. *index_file = NULL;
  6069. /* Traverse index files list. For each entry, append it to the given */
  6070. /* path and see if the file exists. If it exists, break the loop */
  6071. while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
  6072. cs_stat_t st;
  6073. size_t len = path_len + 1 + vec.len + 1;
  6074. *index_file = (char *) MG_REALLOC(*index_file, len);
  6075. if (*index_file == NULL) break;
  6076. snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
  6077. /* Does it exist? Is it a file? */
  6078. if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
  6079. /* Yes it does, break the loop */
  6080. *stp = st;
  6081. found = 1;
  6082. break;
  6083. }
  6084. }
  6085. if (!found) {
  6086. MG_FREE(*index_file);
  6087. *index_file = NULL;
  6088. }
  6089. LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : "")));
  6090. }
  6091. #if MG_ENABLE_HTTP_URL_REWRITES
  6092. static int mg_http_send_port_based_redirect(
  6093. struct mg_connection *c, struct http_message *hm,
  6094. const struct mg_serve_http_opts *opts) {
  6095. const char *rewrites = opts->url_rewrites;
  6096. struct mg_str a, b;
  6097. char local_port[20] = {'%'};
  6098. mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
  6099. MG_SOCK_STRINGIFY_PORT);
  6100. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  6101. if (mg_vcmp(&a, local_port) == 0) {
  6102. mg_send_response_line(c, 301, NULL);
  6103. mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
  6104. (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
  6105. hm->uri.p);
  6106. return 1;
  6107. }
  6108. }
  6109. return 0;
  6110. }
  6111. static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev,
  6112. void *ev_data) {
  6113. struct http_message *hm = (struct http_message *) ev_data;
  6114. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  6115. if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
  6116. DBG(("%p: upstream closed", nc));
  6117. return;
  6118. }
  6119. switch (ev) {
  6120. case MG_EV_CONNECT:
  6121. if (*(int *) ev_data != 0) {
  6122. mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL);
  6123. }
  6124. break;
  6125. /* TODO(mkm): handle streaming */
  6126. case MG_EV_HTTP_REPLY:
  6127. mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p,
  6128. hm->message.len);
  6129. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  6130. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  6131. break;
  6132. case MG_EV_CLOSE:
  6133. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  6134. break;
  6135. }
  6136. }
  6137. void mg_http_reverse_proxy(struct mg_connection *nc,
  6138. const struct http_message *hm, struct mg_str mount,
  6139. struct mg_str upstream) {
  6140. struct mg_connection *be;
  6141. char burl[256], *purl = burl;
  6142. char *addr = NULL;
  6143. const char *path = NULL;
  6144. int i;
  6145. const char *error;
  6146. struct mg_connect_opts opts;
  6147. memset(&opts, 0, sizeof(opts));
  6148. opts.error_string = &error;
  6149. mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p,
  6150. (int) (hm->uri.len - mount.len), hm->uri.p + mount.len);
  6151. be = mg_connect_http_base(nc->mgr, mg_reverse_proxy_handler, opts, "http://",
  6152. "https://", purl, &path, NULL /* user */,
  6153. NULL /* pass */, &addr);
  6154. LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len,
  6155. hm->uri.p, purl, (int) mount.len, mount.p));
  6156. if (be == NULL) {
  6157. LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error));
  6158. mg_http_send_error(nc, 502, NULL);
  6159. goto cleanup;
  6160. }
  6161. /* link connections to each other, they must live and die together */
  6162. mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc;
  6163. mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be;
  6164. /* send request upstream */
  6165. mg_printf(be, "%.*s %s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p,
  6166. path);
  6167. mg_printf(be, "Host: %s\r\n", addr);
  6168. for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) {
  6169. struct mg_str hn = hm->header_names[i];
  6170. struct mg_str hv = hm->header_values[i];
  6171. /* we rewrite the host header */
  6172. if (mg_vcasecmp(&hn, "Host") == 0) continue;
  6173. /*
  6174. * Don't pass chunked transfer encoding to the client because hm->body is
  6175. * already dechunked when we arrive here.
  6176. */
  6177. if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 &&
  6178. mg_vcasecmp(&hv, "chunked") == 0) {
  6179. mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len);
  6180. continue;
  6181. }
  6182. /* We don't support proxying Expect: 100-continue. */
  6183. if (mg_vcasecmp(&hn, "Expect") == 0 &&
  6184. mg_vcasecmp(&hv, "100-continue") == 0) {
  6185. continue;
  6186. }
  6187. mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
  6188. }
  6189. mg_send(be, "\r\n", 2);
  6190. mg_send(be, hm->body.p, hm->body.len);
  6191. cleanup:
  6192. if (purl != burl) MG_FREE(purl);
  6193. }
  6194. static int mg_http_handle_forwarding(struct mg_connection *nc,
  6195. struct http_message *hm,
  6196. const struct mg_serve_http_opts *opts) {
  6197. const char *rewrites = opts->url_rewrites;
  6198. struct mg_str a, b;
  6199. struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://");
  6200. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  6201. if (mg_strncmp(a, hm->uri, a.len) == 0) {
  6202. if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) {
  6203. mg_http_reverse_proxy(nc, hm, a, b);
  6204. return 1;
  6205. }
  6206. }
  6207. }
  6208. return 0;
  6209. }
  6210. #endif
  6211. MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
  6212. const struct mg_serve_http_opts *opts,
  6213. char **local_path,
  6214. struct mg_str *remainder) {
  6215. int ok = 1;
  6216. const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
  6217. struct mg_str root = {NULL, 0};
  6218. const char *file_uri_start = cp;
  6219. *local_path = NULL;
  6220. remainder->p = NULL;
  6221. remainder->len = 0;
  6222. { /* 1. Determine which root to use. */
  6223. #if MG_ENABLE_HTTP_URL_REWRITES
  6224. const char *rewrites = opts->url_rewrites;
  6225. #else
  6226. const char *rewrites = "";
  6227. #endif
  6228. struct mg_str *hh = mg_get_http_header(hm, "Host");
  6229. struct mg_str a, b;
  6230. /* Check rewrites first. */
  6231. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  6232. if (a.len > 1 && a.p[0] == '@') {
  6233. /* Host rewrite. */
  6234. if (hh != NULL && hh->len == a.len - 1 &&
  6235. mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
  6236. root = b;
  6237. break;
  6238. }
  6239. } else {
  6240. /* Regular rewrite, URI=directory */
  6241. int match_len = mg_match_prefix_n(a, hm->uri);
  6242. if (match_len > 0) {
  6243. file_uri_start = hm->uri.p + match_len;
  6244. if (*file_uri_start == '/' || file_uri_start == cp_end) {
  6245. /* Match ended at component boundary, ok. */
  6246. } else if (*(file_uri_start - 1) == '/') {
  6247. /* Pattern ends with '/', backtrack. */
  6248. file_uri_start--;
  6249. } else {
  6250. /* No match: must fall on the component boundary. */
  6251. continue;
  6252. }
  6253. root = b;
  6254. break;
  6255. }
  6256. }
  6257. }
  6258. /* If no rewrite rules matched, use DAV or regular document root. */
  6259. if (root.p == NULL) {
  6260. #if MG_ENABLE_HTTP_WEBDAV
  6261. if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
  6262. root.p = opts->dav_document_root;
  6263. root.len = strlen(opts->dav_document_root);
  6264. } else
  6265. #endif
  6266. {
  6267. root.p = opts->document_root;
  6268. root.len = strlen(opts->document_root);
  6269. }
  6270. }
  6271. assert(root.p != NULL && root.len > 0);
  6272. }
  6273. { /* 2. Find where in the canonical URI path the local path ends. */
  6274. const char *u = file_uri_start + 1;
  6275. char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
  6276. char *lp_end = lp + root.len + hm->uri.len + 1;
  6277. char *p = lp, *ps;
  6278. int exists = 1;
  6279. if (lp == NULL) {
  6280. ok = 0;
  6281. goto out;
  6282. }
  6283. memcpy(p, root.p, root.len);
  6284. p += root.len;
  6285. if (*(p - 1) == DIRSEP) p--;
  6286. *p = '\0';
  6287. ps = p;
  6288. /* Chop off URI path components one by one and build local path. */
  6289. while (u <= cp_end) {
  6290. const char *next = u;
  6291. struct mg_str component;
  6292. if (exists) {
  6293. cs_stat_t st;
  6294. exists = (mg_stat(lp, &st) == 0);
  6295. if (exists && S_ISREG(st.st_mode)) {
  6296. /* We found the terminal, the rest of the URI (if any) is path_info.
  6297. */
  6298. if (*(u - 1) == '/') u--;
  6299. break;
  6300. }
  6301. }
  6302. if (u >= cp_end) break;
  6303. parse_uri_component((const char **) &next, cp_end, '/', &component);
  6304. if (component.len > 0) {
  6305. int len;
  6306. memmove(p + 1, component.p, component.len);
  6307. len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
  6308. if (len <= 0) {
  6309. ok = 0;
  6310. break;
  6311. }
  6312. component.p = p + 1;
  6313. component.len = len;
  6314. if (mg_vcmp(&component, ".") == 0) {
  6315. /* Yum. */
  6316. } else if (mg_vcmp(&component, "..") == 0) {
  6317. while (p > ps && *p != DIRSEP) p--;
  6318. *p = '\0';
  6319. } else {
  6320. size_t i;
  6321. #ifdef _WIN32
  6322. /* On Windows, make sure it's valid Unicode (no funny stuff). */
  6323. wchar_t buf[MG_MAX_PATH * 2];
  6324. if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
  6325. DBG(("[%.*s] smells funny", (int) component.len, component.p));
  6326. ok = 0;
  6327. break;
  6328. }
  6329. #endif
  6330. *p++ = DIRSEP;
  6331. /* No NULs and DIRSEPs in the component (percent-encoded). */
  6332. for (i = 0; i < component.len; i++, p++) {
  6333. if (*p == '\0' || *p == DIRSEP
  6334. #ifdef _WIN32
  6335. /* On Windows, "/" is also accepted, so check for that too. */
  6336. ||
  6337. *p == '/'
  6338. #endif
  6339. ) {
  6340. ok = 0;
  6341. break;
  6342. }
  6343. }
  6344. }
  6345. }
  6346. u = next;
  6347. }
  6348. if (ok) {
  6349. *local_path = lp;
  6350. if (u > cp_end) u = cp_end;
  6351. remainder->p = u;
  6352. remainder->len = cp_end - u;
  6353. } else {
  6354. MG_FREE(lp);
  6355. }
  6356. }
  6357. out:
  6358. LOG(LL_DEBUG,
  6359. ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
  6360. *local_path ? *local_path : "", (int) remainder->len, remainder->p));
  6361. return ok;
  6362. }
  6363. static int mg_get_month_index(const char *s) {
  6364. static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  6365. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  6366. size_t i;
  6367. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  6368. if (!strcmp(s, month_names[i])) return (int) i;
  6369. return -1;
  6370. }
  6371. static int mg_num_leap_years(int year) {
  6372. return year / 4 - year / 100 + year / 400;
  6373. }
  6374. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6375. MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
  6376. static const unsigned short days_before_month[] = {
  6377. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  6378. char month_str[32];
  6379. int second, minute, hour, day, month, year, leap_days, days;
  6380. time_t result = (time_t) 0;
  6381. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
  6382. &minute, &second) == 6) ||
  6383. (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
  6384. &minute, &second) == 6) ||
  6385. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
  6386. &hour, &minute, &second) == 6) ||
  6387. (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
  6388. &minute, &second) == 6)) &&
  6389. year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
  6390. leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
  6391. year -= 1970;
  6392. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  6393. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  6394. }
  6395. return result;
  6396. }
  6397. MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
  6398. struct mg_str *hdr;
  6399. if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
  6400. char etag[64];
  6401. mg_http_construct_etag(etag, sizeof(etag), st);
  6402. return mg_vcasecmp(hdr, etag) == 0;
  6403. } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
  6404. return st->st_mtime <= mg_parse_date_string(hdr->p);
  6405. } else {
  6406. return 0;
  6407. }
  6408. }
  6409. static void mg_http_send_digest_auth_request(struct mg_connection *c,
  6410. const char *domain) {
  6411. mg_printf(c,
  6412. "HTTP/1.1 401 Unauthorized\r\n"
  6413. "WWW-Authenticate: Digest qop=\"auth\", "
  6414. "realm=\"%s\", nonce=\"%lu\"\r\n"
  6415. "Content-Length: 0\r\n\r\n",
  6416. domain, (unsigned long) mg_time());
  6417. }
  6418. static void mg_http_send_options(struct mg_connection *nc) {
  6419. mg_printf(nc, "%s",
  6420. "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, OPTIONS"
  6421. #if MG_ENABLE_HTTP_WEBDAV
  6422. ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
  6423. #endif
  6424. "\r\n\r\n");
  6425. nc->flags |= MG_F_SEND_AND_CLOSE;
  6426. }
  6427. static int mg_is_creation_request(const struct http_message *hm) {
  6428. return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
  6429. }
  6430. MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
  6431. const struct mg_str *path_info,
  6432. struct http_message *hm,
  6433. struct mg_serve_http_opts *opts) {
  6434. int exists, is_directory, is_cgi;
  6435. #if MG_ENABLE_HTTP_WEBDAV
  6436. int is_dav = mg_is_dav_request(&hm->method);
  6437. #else
  6438. int is_dav = 0;
  6439. #endif
  6440. char *index_file = NULL;
  6441. cs_stat_t st;
  6442. exists = (mg_stat(path, &st) == 0);
  6443. is_directory = exists && S_ISDIR(st.st_mode);
  6444. if (is_directory)
  6445. mg_find_index_file(path, opts->index_files, &index_file, &st);
  6446. is_cgi =
  6447. (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
  6448. index_file ? index_file : path) > 0);
  6449. LOG(LL_DEBUG,
  6450. ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
  6451. (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
  6452. is_cgi, index_file ? index_file : ""));
  6453. if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
  6454. mg_printf(nc,
  6455. "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
  6456. "Content-Length: 0\r\n\r\n",
  6457. (int) hm->uri.len, hm->uri.p);
  6458. MG_FREE(index_file);
  6459. return;
  6460. }
  6461. /* If we have path_info, the only way to handle it is CGI. */
  6462. if (path_info->len > 0 && !is_cgi) {
  6463. mg_http_send_error(nc, 501, NULL);
  6464. MG_FREE(index_file);
  6465. return;
  6466. }
  6467. if (is_dav && opts->dav_document_root == NULL) {
  6468. mg_http_send_error(nc, 501, NULL);
  6469. } else if (!mg_is_authorized(hm, path, is_directory, opts->auth_domain,
  6470. opts->global_auth_file, 1) ||
  6471. !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
  6472. opts->per_directory_auth_file, 0)) {
  6473. mg_http_send_digest_auth_request(nc, opts->auth_domain);
  6474. } else if (is_cgi) {
  6475. #if MG_ENABLE_HTTP_CGI
  6476. mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
  6477. #else
  6478. mg_http_send_error(nc, 501, NULL);
  6479. #endif /* MG_ENABLE_HTTP_CGI */
  6480. } else if ((!exists ||
  6481. mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
  6482. !mg_is_creation_request(hm)) {
  6483. mg_http_send_error(nc, 404, NULL);
  6484. #if MG_ENABLE_HTTP_WEBDAV
  6485. } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
  6486. mg_handle_propfind(nc, path, &st, hm, opts);
  6487. #if !MG_DISABLE_DAV_AUTH
  6488. } else if (is_dav &&
  6489. (opts->dav_auth_file == NULL ||
  6490. (strcmp(opts->dav_auth_file, "-") != 0 &&
  6491. !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
  6492. opts->dav_auth_file, 1)))) {
  6493. mg_http_send_digest_auth_request(nc, opts->auth_domain);
  6494. #endif
  6495. } else if (!mg_vcmp(&hm->method, "MKCOL")) {
  6496. mg_handle_mkcol(nc, path, hm);
  6497. } else if (!mg_vcmp(&hm->method, "DELETE")) {
  6498. mg_handle_delete(nc, opts, path);
  6499. } else if (!mg_vcmp(&hm->method, "PUT")) {
  6500. mg_handle_put(nc, path, hm);
  6501. } else if (!mg_vcmp(&hm->method, "MOVE")) {
  6502. mg_handle_move(nc, opts, path, hm);
  6503. #if MG_ENABLE_FAKE_DAVLOCK
  6504. } else if (!mg_vcmp(&hm->method, "LOCK")) {
  6505. mg_handle_lock(nc, path);
  6506. #endif
  6507. #endif /* MG_ENABLE_HTTP_WEBDAV */
  6508. } else if (!mg_vcmp(&hm->method, "OPTIONS")) {
  6509. mg_http_send_options(nc);
  6510. } else if (is_directory && index_file == NULL) {
  6511. #if MG_ENABLE_DIRECTORY_LISTING
  6512. if (strcmp(opts->enable_directory_listing, "yes") == 0) {
  6513. mg_send_directory_listing(nc, path, hm, opts);
  6514. } else {
  6515. mg_http_send_error(nc, 403, NULL);
  6516. }
  6517. #else
  6518. mg_http_send_error(nc, 501, NULL);
  6519. #endif
  6520. } else if (mg_is_not_modified(hm, &st)) {
  6521. mg_http_send_error(nc, 304, "Not Modified");
  6522. } else {
  6523. mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
  6524. }
  6525. MG_FREE(index_file);
  6526. }
  6527. void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
  6528. struct mg_serve_http_opts opts) {
  6529. char *path = NULL;
  6530. struct mg_str *hdr, path_info;
  6531. uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
  6532. if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
  6533. /* Not allowed to connect */
  6534. mg_http_send_error(nc, 403, NULL);
  6535. nc->flags |= MG_F_SEND_AND_CLOSE;
  6536. return;
  6537. }
  6538. #if MG_ENABLE_HTTP_URL_REWRITES
  6539. if (mg_http_handle_forwarding(nc, hm, &opts)) {
  6540. return;
  6541. }
  6542. if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
  6543. return;
  6544. }
  6545. #endif
  6546. if (opts.document_root == NULL) {
  6547. opts.document_root = ".";
  6548. }
  6549. if (opts.per_directory_auth_file == NULL) {
  6550. opts.per_directory_auth_file = ".htpasswd";
  6551. }
  6552. if (opts.enable_directory_listing == NULL) {
  6553. opts.enable_directory_listing = "yes";
  6554. }
  6555. if (opts.cgi_file_pattern == NULL) {
  6556. opts.cgi_file_pattern = "**.cgi$|**.php$";
  6557. }
  6558. if (opts.ssi_pattern == NULL) {
  6559. opts.ssi_pattern = "**.shtml$|**.shtm$";
  6560. }
  6561. if (opts.index_files == NULL) {
  6562. opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
  6563. }
  6564. /* Normalize path - resolve "." and ".." (in-place). */
  6565. if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
  6566. mg_http_send_error(nc, 400, NULL);
  6567. return;
  6568. }
  6569. if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
  6570. mg_http_send_error(nc, 404, NULL);
  6571. return;
  6572. }
  6573. mg_send_http_file(nc, path, &path_info, hm, &opts);
  6574. MG_FREE(path);
  6575. path = NULL;
  6576. /* Close connection for non-keep-alive requests */
  6577. if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
  6578. ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
  6579. mg_vcmp(hdr, "keep-alive") != 0)) {
  6580. #if 0
  6581. nc->flags |= MG_F_SEND_AND_CLOSE;
  6582. #endif
  6583. }
  6584. }
  6585. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  6586. void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
  6587. mg_fu_fname_fn local_name_fn) {
  6588. switch (ev) {
  6589. case MG_EV_HTTP_PART_BEGIN: {
  6590. struct mg_http_multipart_part *mp =
  6591. (struct mg_http_multipart_part *) ev_data;
  6592. struct file_upload_state *fus =
  6593. (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus));
  6594. struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
  6595. mp->user_data = NULL;
  6596. if (lfn.p == NULL || lfn.len == 0) {
  6597. LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
  6598. mg_printf(nc,
  6599. "HTTP/1.1 403 Not Allowed\r\n"
  6600. "Content-Type: text/plain\r\n"
  6601. "Connection: close\r\n\r\n"
  6602. "Not allowed to upload %s\r\n",
  6603. mp->file_name);
  6604. nc->flags |= MG_F_SEND_AND_CLOSE;
  6605. return;
  6606. }
  6607. fus->lfn = (char *) MG_MALLOC(lfn.len + 1);
  6608. memcpy(fus->lfn, lfn.p, lfn.len);
  6609. fus->lfn[lfn.len] = '\0';
  6610. if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p);
  6611. LOG(LL_DEBUG,
  6612. ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
  6613. fus->fp = mg_fopen(fus->lfn, "w");
  6614. if (fus->fp == NULL) {
  6615. mg_printf(nc,
  6616. "HTTP/1.1 500 Internal Server Error\r\n"
  6617. "Content-Type: text/plain\r\n"
  6618. "Connection: close\r\n\r\n");
  6619. LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno()));
  6620. mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno());
  6621. /* Do not close the connection just yet, discard remainder of the data.
  6622. * This is because at the time of writing some browsers (Chrome) fail to
  6623. * render response before all the data is sent. */
  6624. }
  6625. mp->user_data = (void *) fus;
  6626. break;
  6627. }
  6628. case MG_EV_HTTP_PART_DATA: {
  6629. struct mg_http_multipart_part *mp =
  6630. (struct mg_http_multipart_part *) ev_data;
  6631. struct file_upload_state *fus =
  6632. (struct file_upload_state *) mp->user_data;
  6633. if (fus == NULL || fus->fp == NULL) break;
  6634. if (fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
  6635. LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn,
  6636. mg_get_errno(), (int) fus->num_recd));
  6637. if (mg_get_errno() == ENOSPC
  6638. #ifdef SPIFFS_ERR_FULL
  6639. || mg_get_errno() == SPIFFS_ERR_FULL
  6640. #endif
  6641. ) {
  6642. mg_printf(nc,
  6643. "HTTP/1.1 413 Payload Too Large\r\n"
  6644. "Content-Type: text/plain\r\n"
  6645. "Connection: close\r\n\r\n");
  6646. mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
  6647. fus->lfn, (int) fus->num_recd);
  6648. } else {
  6649. mg_printf(nc,
  6650. "HTTP/1.1 500 Internal Server Error\r\n"
  6651. "Content-Type: text/plain\r\n"
  6652. "Connection: close\r\n\r\n");
  6653. mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
  6654. mg_get_errno(), (int) fus->num_recd);
  6655. }
  6656. fclose(fus->fp);
  6657. remove(fus->lfn);
  6658. fus->fp = NULL;
  6659. /* Do not close the connection just yet, discard remainder of the data.
  6660. * This is because at the time of writing some browsers (Chrome) fail to
  6661. * render response before all the data is sent. */
  6662. return;
  6663. }
  6664. fus->num_recd += mp->data.len;
  6665. LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
  6666. (int) fus->num_recd));
  6667. break;
  6668. }
  6669. case MG_EV_HTTP_PART_END: {
  6670. struct mg_http_multipart_part *mp =
  6671. (struct mg_http_multipart_part *) ev_data;
  6672. struct file_upload_state *fus =
  6673. (struct file_upload_state *) mp->user_data;
  6674. if (fus == NULL) break;
  6675. if (mp->status >= 0 && fus->fp != NULL) {
  6676. LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
  6677. fus->lfn, (int) fus->num_recd));
  6678. // mg_printf(nc,
  6679. // "HTTP/1.1 200 OK\r\n"
  6680. // "Content-Type: text/plain\r\n"
  6681. // "Connection: close\r\n\r\n"
  6682. // "Ok, %s - %d bytes.\r\n",
  6683. // mp->file_name, (int) fus->num_recd);
  6684. } else {
  6685. LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
  6686. /*
  6687. * mp->status < 0 means connection was terminated, so no reason to send
  6688. * HTTP reply
  6689. */
  6690. }
  6691. if (fus->fp != NULL) fclose(fus->fp);
  6692. MG_FREE(fus->lfn);
  6693. MG_FREE(fus);
  6694. mp->user_data = NULL;
  6695. nc->flags |= MG_F_SEND_AND_CLOSE;
  6696. break;
  6697. }
  6698. }
  6699. }
  6700. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  6701. #endif /* MG_ENABLE_FILESYSTEM */
  6702. /* returns 0 on success, -1 on error */
  6703. MG_INTERNAL int mg_http_common_url_parse(const char *url, const char *schema,
  6704. const char *schema_tls, int *use_ssl,
  6705. char **user, char **pass, char **addr,
  6706. int *port_i, const char **path) {
  6707. int addr_len = 0;
  6708. int auth_sep_pos = -1;
  6709. int user_sep_pos = -1;
  6710. int port_pos = -1;
  6711. (void) user;
  6712. (void) pass;
  6713. if (strncmp(url, schema, strlen(schema)) == 0) {
  6714. url += strlen(schema);
  6715. } else if (strncmp(url, schema_tls, strlen(schema_tls)) == 0) {
  6716. url += strlen(schema_tls);
  6717. *use_ssl = 1;
  6718. #if !MG_ENABLE_SSL
  6719. return -1; /* SSL is not enabled, cannot do HTTPS URLs */
  6720. #endif
  6721. }
  6722. while (*url != '\0') {
  6723. *addr = (char *) MG_REALLOC(*addr, addr_len + 6 /* space for port too. */);
  6724. if (*addr == NULL) {
  6725. DBG(("OOM"));
  6726. return -1;
  6727. }
  6728. if (*url == '/') {
  6729. break;
  6730. }
  6731. if (*url == '@') {
  6732. auth_sep_pos = addr_len;
  6733. user_sep_pos = port_pos;
  6734. port_pos = -1;
  6735. }
  6736. if (*url == ':') port_pos = addr_len;
  6737. (*addr)[addr_len++] = *url;
  6738. (*addr)[addr_len] = '\0';
  6739. url++;
  6740. }
  6741. if (addr_len == 0) goto cleanup;
  6742. if (port_pos < 0) {
  6743. *port_i = addr_len;
  6744. addr_len += sprintf(*addr + addr_len, ":%d", *use_ssl ? 443 : 80);
  6745. } else {
  6746. *port_i = -1;
  6747. }
  6748. if (*path == NULL) *path = url;
  6749. if (**path == '\0') *path = "/";
  6750. if (user != NULL && pass != NULL) {
  6751. if (auth_sep_pos == -1) {
  6752. *user = NULL;
  6753. *pass = NULL;
  6754. } else {
  6755. /* user is from 0 to user_sep_pos */
  6756. *user = (char *) MG_MALLOC(user_sep_pos + 1);
  6757. memcpy(*user, *addr, user_sep_pos);
  6758. (*user)[user_sep_pos] = '\0';
  6759. /* pass is from user_sep_pos + 1 to auth_sep_pos */
  6760. *pass = (char *) MG_MALLOC(auth_sep_pos - user_sep_pos - 1 + 1);
  6761. memcpy(*pass, *addr + user_sep_pos + 1, auth_sep_pos - user_sep_pos - 1);
  6762. (*pass)[auth_sep_pos - user_sep_pos - 1] = '\0';
  6763. /* move address proper to the front */
  6764. memmove(*addr, *addr + auth_sep_pos + 1, addr_len - auth_sep_pos);
  6765. }
  6766. }
  6767. DBG(("%s %s", *addr, *path));
  6768. return 0;
  6769. cleanup:
  6770. MG_FREE(*addr);
  6771. return -1;
  6772. }
  6773. struct mg_connection *mg_connect_http_base(
  6774. struct mg_mgr *mgr, mg_event_handler_t ev_handler,
  6775. struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
  6776. const char *url, const char **path, char **user, char **pass, char **addr) {
  6777. struct mg_connection *nc = NULL;
  6778. int port_i = -1;
  6779. int use_ssl = 0;
  6780. if (mg_http_common_url_parse(url, schema, schema_ssl, &use_ssl, user, pass,
  6781. addr, &port_i, path) < 0) {
  6782. MG_SET_PTRPTR(opts.error_string, "cannot parse url");
  6783. return NULL;
  6784. }
  6785. LOG(LL_DEBUG, ("%s use_ssl? %d", url, use_ssl));
  6786. if (use_ssl) {
  6787. #if MG_ENABLE_SSL
  6788. /*
  6789. * Schema requires SSL, but no SSL parameters were provided in opts.
  6790. * In order to maintain backward compatibility, use a faux-SSL with no
  6791. * verification.
  6792. */
  6793. if (opts.ssl_ca_cert == NULL) {
  6794. opts.ssl_ca_cert = "*";
  6795. }
  6796. #else
  6797. MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
  6798. if (user != NULL) MG_FREE(*user);
  6799. if (pass != NULL) MG_FREE(*pass);
  6800. MG_FREE(*addr);
  6801. return NULL;
  6802. #endif
  6803. }
  6804. if ((nc = mg_connect_opt(mgr, *addr, ev_handler, opts)) != NULL) {
  6805. mg_set_protocol_http_websocket(nc);
  6806. /* If the port was addred by us, restore the original host. */
  6807. if (port_i >= 0) (*addr)[port_i] = '\0';
  6808. }
  6809. return nc;
  6810. }
  6811. struct mg_connection *mg_connect_http_opt(struct mg_mgr *mgr,
  6812. mg_event_handler_t ev_handler,
  6813. struct mg_connect_opts opts,
  6814. const char *url,
  6815. const char *extra_headers,
  6816. const char *post_data) {
  6817. char *user = NULL, *pass = NULL, *addr = NULL;
  6818. const char *path = NULL;
  6819. struct mbuf auth;
  6820. struct mg_connection *nc =
  6821. mg_connect_http_base(mgr, ev_handler, opts, "http://", "https://", url,
  6822. &path, &user, &pass, &addr);
  6823. if (nc == NULL) {
  6824. return NULL;
  6825. }
  6826. mbuf_init(&auth, 0);
  6827. if (user != NULL) {
  6828. mg_basic_auth_header(user, pass, &auth);
  6829. }
  6830. mg_printf(nc, "%s %s HTTP/1.1\r\nHost: %s\r\nContent-Length: %" SIZE_T_FMT
  6831. "\r\n%.*s%s\r\n%s",
  6832. post_data == NULL ? "GET" : "POST", path, addr,
  6833. post_data == NULL ? 0 : strlen(post_data), (int) auth.len,
  6834. (auth.buf == NULL ? "" : auth.buf),
  6835. extra_headers == NULL ? "" : extra_headers,
  6836. post_data == NULL ? "" : post_data);
  6837. mbuf_free(&auth);
  6838. MG_FREE(user);
  6839. MG_FREE(pass);
  6840. MG_FREE(addr);
  6841. return nc;
  6842. }
  6843. struct mg_connection *mg_connect_http(struct mg_mgr *mgr,
  6844. mg_event_handler_t ev_handler,
  6845. const char *url,
  6846. const char *extra_headers,
  6847. const char *post_data) {
  6848. struct mg_connect_opts opts;
  6849. memset(&opts, 0, sizeof(opts));
  6850. return mg_connect_http_opt(mgr, ev_handler, opts, url, extra_headers,
  6851. post_data);
  6852. }
  6853. size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
  6854. size_t var_name_len, char *file_name,
  6855. size_t file_name_len, const char **data,
  6856. size_t *data_len) {
  6857. static const char cd[] = "Content-Disposition: ";
  6858. size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
  6859. if (buf == NULL || buf_len <= 0) return 0;
  6860. if ((hl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
  6861. if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
  6862. /* Get boundary length */
  6863. bl = mg_get_line_len(buf, buf_len);
  6864. /* Loop through headers, fetch variable name and file name */
  6865. var_name[0] = file_name[0] = '\0';
  6866. for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
  6867. if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
  6868. struct mg_str header;
  6869. header.p = buf + n + cdl;
  6870. header.len = ll - (cdl + 2);
  6871. mg_http_parse_header(&header, "name", var_name, var_name_len);
  6872. mg_http_parse_header(&header, "filename", file_name, file_name_len);
  6873. }
  6874. }
  6875. /* Scan through the body, search for terminating boundary */
  6876. for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
  6877. if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
  6878. if (data_len != NULL) *data_len = (pos - 2) - hl;
  6879. if (data != NULL) *data = buf + hl;
  6880. return pos;
  6881. }
  6882. }
  6883. return 0;
  6884. }
  6885. void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
  6886. mg_event_handler_t handler) {
  6887. struct mg_http_proto_data *pd = NULL;
  6888. struct mg_http_endpoint *new_ep = NULL;
  6889. if (nc == NULL) return;
  6890. new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
  6891. if (new_ep == NULL) return;
  6892. pd = mg_http_get_proto_data(nc);
  6893. new_ep->name = MG_STRDUP(uri_path);
  6894. new_ep->name_len = strlen(new_ep->name);
  6895. new_ep->handler = handler;
  6896. new_ep->next = pd->endpoints;
  6897. pd->endpoints = new_ep;
  6898. }
  6899. #endif /* MG_ENABLE_HTTP */
  6900. #ifdef MG_MODULE_LINES
  6901. #line 1 "mongoose/src/http_cgi.c"
  6902. #endif
  6903. /*
  6904. * Copyright (c) 2014-2016 Cesanta Software Limited
  6905. * All rights reserved
  6906. */
  6907. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
  6908. #ifndef MG_MAX_CGI_ENVIR_VARS
  6909. #define MG_MAX_CGI_ENVIR_VARS 64
  6910. #endif
  6911. #ifndef MG_ENV_EXPORT_TO_CGI
  6912. #define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
  6913. #endif
  6914. /*
  6915. * This structure helps to create an environment for the spawned CGI program.
  6916. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6917. * last element must be NULL.
  6918. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6919. * strings must reside in a contiguous buffer. The end of the buffer is
  6920. * marked by two '\0' characters.
  6921. * We satisfy both worlds: we create an envp array (which is vars), all
  6922. * entries are actually pointers inside buf.
  6923. */
  6924. struct mg_cgi_env_block {
  6925. struct mg_connection *nc;
  6926. char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  6927. const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
  6928. int len; /* Space taken */
  6929. int nvars; /* Number of variables in envp[] */
  6930. };
  6931. #ifdef _WIN32
  6932. struct mg_threadparam {
  6933. sock_t s;
  6934. HANDLE hPipe;
  6935. };
  6936. static int mg_wait_until_ready(sock_t sock, int for_read) {
  6937. fd_set set;
  6938. FD_ZERO(&set);
  6939. FD_SET(sock, &set);
  6940. return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
  6941. }
  6942. static void *mg_push_to_stdin(void *arg) {
  6943. struct mg_threadparam *tp = (struct mg_threadparam *) arg;
  6944. int n, sent, stop = 0;
  6945. DWORD k;
  6946. char buf[BUFSIZ];
  6947. while (!stop && mg_wait_until_ready(tp->s, 1) &&
  6948. (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
  6949. if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
  6950. for (sent = 0; !stop && sent < n; sent += k) {
  6951. if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
  6952. }
  6953. }
  6954. DBG(("%s", "FORWARED EVERYTHING TO CGI"));
  6955. CloseHandle(tp->hPipe);
  6956. MG_FREE(tp);
  6957. return NULL;
  6958. }
  6959. static void *mg_pull_from_stdout(void *arg) {
  6960. struct mg_threadparam *tp = (struct mg_threadparam *) arg;
  6961. int k = 0, stop = 0;
  6962. DWORD n, sent;
  6963. char buf[BUFSIZ];
  6964. while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
  6965. for (sent = 0; !stop && sent < n; sent += k) {
  6966. if (mg_wait_until_ready(tp->s, 0) &&
  6967. (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
  6968. stop = 1;
  6969. }
  6970. }
  6971. DBG(("%s", "EOF FROM CGI"));
  6972. CloseHandle(tp->hPipe);
  6973. shutdown(tp->s, 2); // Without this, IO thread may get truncated data
  6974. closesocket(tp->s);
  6975. MG_FREE(tp);
  6976. return NULL;
  6977. }
  6978. static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
  6979. void *(*func)(void *)) {
  6980. struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
  6981. if (tp != NULL) {
  6982. tp->s = sock;
  6983. tp->hPipe = hPipe;
  6984. mg_start_thread(func, tp);
  6985. }
  6986. }
  6987. static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
  6988. wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
  6989. to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
  6990. GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
  6991. WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
  6992. }
  6993. static int mg_start_process(const char *interp, const char *cmd,
  6994. const char *env, const char *envp[],
  6995. const char *dir, sock_t sock) {
  6996. STARTUPINFOW si;
  6997. PROCESS_INFORMATION pi;
  6998. HANDLE a[2], b[2], me = GetCurrentProcess();
  6999. wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
  7000. char buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
  7001. buf4[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE];
  7002. DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
  7003. FILE *fp;
  7004. memset(&si, 0, sizeof(si));
  7005. memset(&pi, 0, sizeof(pi));
  7006. si.cb = sizeof(si);
  7007. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  7008. si.wShowWindow = SW_HIDE;
  7009. si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  7010. CreatePipe(&a[0], &a[1], NULL, 0);
  7011. CreatePipe(&b[0], &b[1], NULL, 0);
  7012. DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
  7013. DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
  7014. if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
  7015. buf[0] = buf[1] = '\0';
  7016. fgets(buf, sizeof(buf), fp);
  7017. buf[sizeof(buf) - 1] = '\0';
  7018. if (buf[0] == '#' && buf[1] == '!') {
  7019. interp = buf + 2;
  7020. /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
  7021. while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
  7022. interp++;
  7023. }
  7024. }
  7025. fclose(fp);
  7026. }
  7027. snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
  7028. mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
  7029. mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
  7030. to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
  7031. if (interp != NULL) {
  7032. mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
  7033. snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
  7034. } else {
  7035. snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
  7036. }
  7037. to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
  7038. if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
  7039. (void *) env, full_dir, &si, &pi) != 0) {
  7040. mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
  7041. mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
  7042. CloseHandle(si.hStdOutput);
  7043. CloseHandle(si.hStdInput);
  7044. CloseHandle(pi.hThread);
  7045. CloseHandle(pi.hProcess);
  7046. } else {
  7047. CloseHandle(a[1]);
  7048. CloseHandle(b[0]);
  7049. closesocket(sock);
  7050. }
  7051. DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
  7052. /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
  7053. (void) envp;
  7054. return (pi.hProcess != NULL);
  7055. }
  7056. #else
  7057. static int mg_start_process(const char *interp, const char *cmd,
  7058. const char *env, const char *envp[],
  7059. const char *dir, sock_t sock) {
  7060. char buf[500];
  7061. pid_t pid = fork();
  7062. (void) env;
  7063. if (pid == 0) {
  7064. /*
  7065. * In Linux `chdir` declared with `warn_unused_result` attribute
  7066. * To shutup compiler we have yo use result in some way
  7067. */
  7068. int tmp = chdir(dir);
  7069. (void) tmp;
  7070. (void) dup2(sock, 0);
  7071. (void) dup2(sock, 1);
  7072. closesocket(sock);
  7073. /*
  7074. * After exec, all signal handlers are restored to their default values,
  7075. * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
  7076. * implementation, SIGCHLD's handler will leave unchanged after exec
  7077. * if it was set to be ignored. Restore it to default action.
  7078. */
  7079. signal(SIGCHLD, SIG_DFL);
  7080. if (interp == NULL) {
  7081. execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
  7082. } else {
  7083. execle(interp, interp, cmd, (char *) 0, envp);
  7084. }
  7085. snprintf(buf, sizeof(buf),
  7086. "Status: 500\r\n\r\n"
  7087. "500 Server Error: %s%s%s: %s",
  7088. interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
  7089. strerror(errno));
  7090. send(1, buf, strlen(buf), 0);
  7091. _exit(EXIT_FAILURE); /* exec call failed */
  7092. }
  7093. return (pid != 0);
  7094. }
  7095. #endif /* _WIN32 */
  7096. /*
  7097. * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7098. * pointer into the vars array.
  7099. */
  7100. static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
  7101. int n, space;
  7102. char *added = block->buf + block->len;
  7103. va_list ap;
  7104. /* Calculate how much space is left in the buffer */
  7105. space = sizeof(block->buf) - (block->len + 2);
  7106. if (space > 0) {
  7107. /* Copy VARIABLE=VALUE\0 string into the free space */
  7108. va_start(ap, fmt);
  7109. n = vsnprintf(added, (size_t) space, fmt, ap);
  7110. va_end(ap);
  7111. /* Make sure we do not overflow buffer and the envp array */
  7112. if (n > 0 && n + 1 < space &&
  7113. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  7114. /* Append a pointer to the added string into the envp array */
  7115. block->vars[block->nvars++] = added;
  7116. /* Bump up used length counter. Include \0 terminator */
  7117. block->len += n + 1;
  7118. }
  7119. }
  7120. return added;
  7121. }
  7122. static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
  7123. const char *s;
  7124. if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
  7125. }
  7126. static void mg_prepare_cgi_environment(struct mg_connection *nc,
  7127. const char *prog,
  7128. const struct mg_str *path_info,
  7129. const struct http_message *hm,
  7130. const struct mg_serve_http_opts *opts,
  7131. struct mg_cgi_env_block *blk) {
  7132. const char *s;
  7133. struct mg_str *h;
  7134. char *p;
  7135. size_t i;
  7136. char buf[100];
  7137. blk->len = blk->nvars = 0;
  7138. blk->nc = nc;
  7139. if ((s = getenv("SERVER_NAME")) != NULL) {
  7140. mg_addenv(blk, "SERVER_NAME=%s", s);
  7141. } else {
  7142. mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
  7143. mg_addenv(blk, "SERVER_NAME=%s", buf);
  7144. }
  7145. mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
  7146. mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
  7147. mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
  7148. /* Prepare the environment block */
  7149. mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7150. mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7151. mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7152. mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
  7153. mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
  7154. hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
  7155. hm->query_string.p);
  7156. mg_conn_addr_to_str(nc, buf, sizeof(buf),
  7157. MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
  7158. mg_addenv(blk, "REMOTE_ADDR=%s", buf);
  7159. mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
  7160. mg_addenv(blk, "SERVER_PORT=%s", buf);
  7161. s = hm->uri.p + hm->uri.len - path_info->len - 1;
  7162. if (*s == '/') {
  7163. const char *base_name = strrchr(prog, DIRSEP);
  7164. mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
  7165. (base_name != NULL ? base_name + 1 : prog));
  7166. } else {
  7167. mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
  7168. }
  7169. mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
  7170. if (path_info != NULL && path_info->len > 0) {
  7171. mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
  7172. /* Not really translated... */
  7173. mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
  7174. }
  7175. #if MG_ENABLE_SSL
  7176. mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
  7177. #else
  7178. mg_addenv(blk, "HTTPS=off");
  7179. #endif
  7180. if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
  7181. NULL) {
  7182. mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
  7183. }
  7184. if (hm->query_string.len > 0) {
  7185. mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
  7186. hm->query_string.p);
  7187. }
  7188. if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
  7189. NULL) {
  7190. mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
  7191. }
  7192. mg_addenv2(blk, "PATH");
  7193. mg_addenv2(blk, "TMP");
  7194. mg_addenv2(blk, "TEMP");
  7195. mg_addenv2(blk, "TMPDIR");
  7196. mg_addenv2(blk, "PERLLIB");
  7197. mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
  7198. #ifdef _WIN32
  7199. mg_addenv2(blk, "COMSPEC");
  7200. mg_addenv2(blk, "SYSTEMROOT");
  7201. mg_addenv2(blk, "SystemDrive");
  7202. mg_addenv2(blk, "ProgramFiles");
  7203. mg_addenv2(blk, "ProgramFiles(x86)");
  7204. mg_addenv2(blk, "CommonProgramFiles(x86)");
  7205. #else
  7206. mg_addenv2(blk, "LD_LIBRARY_PATH");
  7207. #endif /* _WIN32 */
  7208. /* Add all headers as HTTP_* variables */
  7209. for (i = 0; hm->header_names[i].len > 0; i++) {
  7210. p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
  7211. hm->header_names[i].p, (int) hm->header_values[i].len,
  7212. hm->header_values[i].p);
  7213. /* Convert variable name into uppercase, and change - to _ */
  7214. for (; *p != '=' && *p != '\0'; p++) {
  7215. if (*p == '-') *p = '_';
  7216. *p = (char) toupper(*(unsigned char *) p);
  7217. }
  7218. }
  7219. blk->vars[blk->nvars++] = NULL;
  7220. blk->buf[blk->len++] = '\0';
  7221. }
  7222. static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
  7223. void *ev_data) {
  7224. struct mg_connection *nc = (struct mg_connection *) cgi_nc->user_data;
  7225. (void) ev_data;
  7226. if (nc == NULL) {
  7227. cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  7228. return;
  7229. }
  7230. switch (ev) {
  7231. case MG_EV_RECV:
  7232. /*
  7233. * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
  7234. * It outputs headers, then body. Headers might include "Status"
  7235. * header, which changes CODE, and it might include "Location" header
  7236. * which changes CODE to 302.
  7237. *
  7238. * Therefore we do not send the output from the CGI script to the user
  7239. * until all CGI headers are received.
  7240. *
  7241. * Here we parse the output from the CGI script, and if all headers has
  7242. * been received, send appropriate reply line, and forward all
  7243. * received headers to the client.
  7244. */
  7245. if (nc->flags & MG_F_USER_1) {
  7246. struct mbuf *io = &cgi_nc->recv_mbuf;
  7247. int len = mg_http_get_request_len(io->buf, io->len);
  7248. if (len == 0) break;
  7249. if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
  7250. cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  7251. mg_http_send_error(nc, 500, "Bad headers");
  7252. } else {
  7253. struct http_message hm;
  7254. struct mg_str *h;
  7255. mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
  7256. if (mg_get_http_header(&hm, "Location") != NULL) {
  7257. mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
  7258. } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
  7259. mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
  7260. } else {
  7261. mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
  7262. }
  7263. }
  7264. nc->flags &= ~MG_F_USER_1;
  7265. }
  7266. if (!(nc->flags & MG_F_USER_1)) {
  7267. mg_forward(cgi_nc, nc);
  7268. }
  7269. break;
  7270. case MG_EV_CLOSE:
  7271. mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
  7272. nc->flags |= MG_F_SEND_AND_CLOSE;
  7273. break;
  7274. }
  7275. }
  7276. MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
  7277. const struct mg_str *path_info,
  7278. const struct http_message *hm,
  7279. const struct mg_serve_http_opts *opts) {
  7280. struct mg_cgi_env_block blk;
  7281. char dir[MAX_PATH_SIZE];
  7282. const char *p;
  7283. sock_t fds[2];
  7284. DBG(("%p [%s]", nc, prog));
  7285. mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
  7286. /*
  7287. * CGI must be executed in its own directory. 'dir' must point to the
  7288. * directory containing executable program, 'p' must point to the
  7289. * executable program name relative to 'dir'.
  7290. */
  7291. if ((p = strrchr(prog, DIRSEP)) == NULL) {
  7292. snprintf(dir, sizeof(dir), "%s", ".");
  7293. } else {
  7294. snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
  7295. prog = p + 1;
  7296. }
  7297. /*
  7298. * Try to create socketpair in a loop until success. mg_socketpair()
  7299. * can be interrupted by a signal and fail.
  7300. * TODO(lsm): use sigaction to restart interrupted syscall
  7301. */
  7302. do {
  7303. mg_socketpair(fds, SOCK_STREAM);
  7304. } while (fds[0] == INVALID_SOCKET);
  7305. if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
  7306. fds[1]) != 0) {
  7307. size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
  7308. struct mg_connection *cgi_nc =
  7309. mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler);
  7310. struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
  7311. cgi_pd->cgi.cgi_nc = cgi_nc;
  7312. cgi_pd->cgi.cgi_nc->user_data = nc;
  7313. nc->flags |= MG_F_USER_1;
  7314. /* Push POST data to the CGI */
  7315. if (n > 0 && n < nc->recv_mbuf.len) {
  7316. mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n);
  7317. }
  7318. mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
  7319. } else {
  7320. closesocket(fds[0]);
  7321. mg_http_send_error(nc, 500, "CGI failure");
  7322. }
  7323. #ifndef _WIN32
  7324. closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
  7325. #endif
  7326. }
  7327. MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
  7328. if (d != NULL) {
  7329. if (d->cgi_nc != NULL) d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  7330. memset(d, 0, sizeof(struct mg_http_proto_data_cgi));
  7331. }
  7332. }
  7333. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
  7334. #ifdef MG_MODULE_LINES
  7335. #line 1 "mongoose/src/http_ssi.c"
  7336. #endif
  7337. /*
  7338. * Copyright (c) 2014-2016 Cesanta Software Limited
  7339. * All rights reserved
  7340. */
  7341. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
  7342. static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
  7343. const char *path, FILE *fp, int include_level,
  7344. const struct mg_serve_http_opts *opts);
  7345. static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
  7346. char buf[BUFSIZ];
  7347. size_t n;
  7348. while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
  7349. mg_send(nc, buf, n);
  7350. }
  7351. }
  7352. static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
  7353. const char *ssi, char *tag, int include_level,
  7354. const struct mg_serve_http_opts *opts) {
  7355. char file_name[BUFSIZ], path[MAX_PATH_SIZE], *p;
  7356. FILE *fp;
  7357. /*
  7358. * sscanf() is safe here, since send_ssi_file() also uses buffer
  7359. * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  7360. */
  7361. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  7362. /* File name is relative to the webserver root */
  7363. snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
  7364. } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
  7365. /*
  7366. * File name is relative to the webserver working directory
  7367. * or it is absolute system path
  7368. */
  7369. snprintf(path, sizeof(path), "%s", file_name);
  7370. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
  7371. sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  7372. /* File name is relative to the currect document */
  7373. snprintf(path, sizeof(path), "%s", ssi);
  7374. if ((p = strrchr(path, DIRSEP)) != NULL) {
  7375. p[1] = '\0';
  7376. }
  7377. snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
  7378. } else {
  7379. mg_printf(nc, "Bad SSI #include: [%s]", tag);
  7380. return;
  7381. }
  7382. if ((fp = mg_fopen(path, "rb")) == NULL) {
  7383. mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
  7384. strerror(mg_get_errno()));
  7385. } else {
  7386. mg_set_close_on_exec((sock_t) fileno(fp));
  7387. if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
  7388. 0) {
  7389. mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
  7390. } else {
  7391. mg_send_file_data(nc, fp);
  7392. }
  7393. fclose(fp);
  7394. }
  7395. }
  7396. #if MG_ENABLE_HTTP_SSI_EXEC
  7397. static void do_ssi_exec(struct mg_connection *nc, char *tag) {
  7398. char cmd[BUFSIZ];
  7399. FILE *fp;
  7400. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  7401. mg_printf(nc, "Bad SSI #exec: [%s]", tag);
  7402. } else if ((fp = popen(cmd, "r")) == NULL) {
  7403. mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
  7404. } else {
  7405. mg_send_file_data(nc, fp);
  7406. pclose(fp);
  7407. }
  7408. }
  7409. #endif /* MG_ENABLE_HTTP_SSI_EXEC */
  7410. /*
  7411. * SSI directive has the following format:
  7412. * <!--#directive parameter=value parameter=value -->
  7413. */
  7414. static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
  7415. const char *path, FILE *fp, int include_level,
  7416. const struct mg_serve_http_opts *opts) {
  7417. static const struct mg_str btag = MG_MK_STR("<!--#");
  7418. static const struct mg_str d_include = MG_MK_STR("include");
  7419. static const struct mg_str d_call = MG_MK_STR("call");
  7420. #if MG_ENABLE_HTTP_SSI_EXEC
  7421. static const struct mg_str d_exec = MG_MK_STR("exec");
  7422. #endif
  7423. char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
  7424. int ch, len, in_ssi_tag;
  7425. if (include_level > 10) {
  7426. mg_printf(nc, "SSI #include level is too deep (%s)", path);
  7427. return;
  7428. }
  7429. in_ssi_tag = len = 0;
  7430. while ((ch = fgetc(fp)) != EOF) {
  7431. if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  7432. size_t i = len - 2;
  7433. in_ssi_tag = 0;
  7434. /* Trim closing --> */
  7435. buf[i--] = '\0';
  7436. while (i > 0 && buf[i] == ' ') {
  7437. buf[i--] = '\0';
  7438. }
  7439. /* Handle known SSI directives */
  7440. if (strncmp(p, d_include.p, d_include.len) == 0) {
  7441. mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
  7442. opts);
  7443. } else if (strncmp(p, d_call.p, d_call.len) == 0) {
  7444. struct mg_ssi_call_ctx cctx;
  7445. memset(&cctx, 0, sizeof(cctx));
  7446. cctx.req = hm;
  7447. cctx.file = mg_mk_str(path);
  7448. cctx.arg = mg_mk_str(p + d_call.len + 1);
  7449. mg_call(nc, NULL, MG_EV_SSI_CALL,
  7450. (void *) cctx.arg.p); /* NUL added above */
  7451. mg_call(nc, NULL, MG_EV_SSI_CALL_CTX, &cctx);
  7452. #if MG_ENABLE_HTTP_SSI_EXEC
  7453. } else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
  7454. do_ssi_exec(nc, p + d_exec.len + 1);
  7455. #endif
  7456. } else {
  7457. /* Silently ignore unknown SSI directive. */
  7458. }
  7459. len = 0;
  7460. } else if (ch == '<') {
  7461. in_ssi_tag = 1;
  7462. if (len > 0) {
  7463. mg_send(nc, buf, (size_t) len);
  7464. }
  7465. len = 0;
  7466. buf[len++] = ch & 0xff;
  7467. } else if (in_ssi_tag) {
  7468. if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
  7469. /* Not an SSI tag */
  7470. in_ssi_tag = 0;
  7471. } else if (len == (int) sizeof(buf) - 2) {
  7472. mg_printf(nc, "%s: SSI tag is too large", path);
  7473. len = 0;
  7474. }
  7475. buf[len++] = ch & 0xff;
  7476. } else {
  7477. buf[len++] = ch & 0xff;
  7478. if (len == (int) sizeof(buf)) {
  7479. mg_send(nc, buf, (size_t) len);
  7480. len = 0;
  7481. }
  7482. }
  7483. }
  7484. /* Send the rest of buffered data */
  7485. if (len > 0) {
  7486. mg_send(nc, buf, (size_t) len);
  7487. }
  7488. }
  7489. MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
  7490. struct http_message *hm,
  7491. const char *path,
  7492. const struct mg_serve_http_opts *opts) {
  7493. FILE *fp;
  7494. struct mg_str mime_type;
  7495. DBG(("%p %s", nc, path));
  7496. if ((fp = mg_fopen(path, "rb")) == NULL) {
  7497. mg_http_send_error(nc, 404, NULL);
  7498. } else {
  7499. mg_set_close_on_exec((sock_t) fileno(fp));
  7500. mime_type = mg_get_mime_type(path, "text/plain", opts);
  7501. mg_send_response_line(nc, 200, opts->extra_headers);
  7502. mg_printf(nc,
  7503. "Content-Type: %.*s\r\n"
  7504. "Connection: close\r\n\r\n",
  7505. (int) mime_type.len, mime_type.p);
  7506. mg_send_ssi_file(nc, hm, path, fp, 0, opts);
  7507. fclose(fp);
  7508. nc->flags |= MG_F_SEND_AND_CLOSE;
  7509. }
  7510. }
  7511. #endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
  7512. #ifdef MG_MODULE_LINES
  7513. #line 1 "mongoose/src/http_webdav.c"
  7514. #endif
  7515. /*
  7516. * Copyright (c) 2014-2016 Cesanta Software Limited
  7517. * All rights reserved
  7518. */
  7519. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
  7520. MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
  7521. static const char *methods[] = {
  7522. "PUT",
  7523. "DELETE",
  7524. "MKCOL",
  7525. "PROPFIND",
  7526. "MOVE"
  7527. #if MG_ENABLE_FAKE_DAVLOCK
  7528. ,
  7529. "LOCK",
  7530. "UNLOCK"
  7531. #endif
  7532. };
  7533. size_t i;
  7534. for (i = 0; i < ARRAY_SIZE(methods); i++) {
  7535. if (mg_vcmp(s, methods[i]) == 0) {
  7536. return 1;
  7537. }
  7538. }
  7539. return 0;
  7540. }
  7541. static int mg_mkdir(const char *path, uint32_t mode) {
  7542. #ifndef _WIN32
  7543. return mkdir(path, mode);
  7544. #else
  7545. (void) mode;
  7546. return _mkdir(path);
  7547. #endif
  7548. }
  7549. static void mg_print_props(struct mg_connection *nc, const char *name,
  7550. cs_stat_t *stp) {
  7551. char mtime[64], buf[MAX_PATH_SIZE * 3];
  7552. time_t t = stp->st_mtime; /* store in local variable for NDK compile */
  7553. mg_gmt_time_string(mtime, sizeof(mtime), &t);
  7554. mg_url_encode(name, strlen(name), buf, sizeof(buf));
  7555. mg_printf(nc,
  7556. "<d:response>"
  7557. "<d:href>%s</d:href>"
  7558. "<d:propstat>"
  7559. "<d:prop>"
  7560. "<d:resourcetype>%s</d:resourcetype>"
  7561. "<d:getcontentlength>%" INT64_FMT
  7562. "</d:getcontentlength>"
  7563. "<d:getlastmodified>%s</d:getlastmodified>"
  7564. "</d:prop>"
  7565. "<d:status>HTTP/1.1 200 OK</d:status>"
  7566. "</d:propstat>"
  7567. "</d:response>\n",
  7568. buf, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
  7569. (int64_t) stp->st_size, mtime);
  7570. }
  7571. MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
  7572. cs_stat_t *stp, struct http_message *hm,
  7573. struct mg_serve_http_opts *opts) {
  7574. static const char header[] =
  7575. "HTTP/1.1 207 Multi-Status\r\n"
  7576. "Connection: close\r\n"
  7577. "Content-Type: text/xml; charset=utf-8\r\n\r\n"
  7578. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7579. "<d:multistatus xmlns:d='DAV:'>\n";
  7580. static const char footer[] = "</d:multistatus>\n";
  7581. const struct mg_str *depth = mg_get_http_header(hm, "Depth");
  7582. /* Print properties for the requested resource itself */
  7583. if (S_ISDIR(stp->st_mode) &&
  7584. strcmp(opts->enable_directory_listing, "yes") != 0) {
  7585. mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
  7586. } else {
  7587. char uri[MAX_PATH_SIZE];
  7588. mg_send(nc, header, sizeof(header) - 1);
  7589. snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
  7590. mg_print_props(nc, uri, stp);
  7591. if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
  7592. mg_scan_directory(nc, path, opts, mg_print_props);
  7593. }
  7594. mg_send(nc, footer, sizeof(footer) - 1);
  7595. nc->flags |= MG_F_SEND_AND_CLOSE;
  7596. }
  7597. }
  7598. #if MG_ENABLE_FAKE_DAVLOCK
  7599. /*
  7600. * Windows explorer (probably there are another WebDav clients like it)
  7601. * requires LOCK support in webdav. W/out this, it still works, but fails
  7602. * to save file: shows error message and offers "Save As".
  7603. * "Save as" works, but this message is very annoying.
  7604. * This is fake lock, which doesn't lock something, just returns LOCK token,
  7605. * UNLOCK always answers "OK".
  7606. * With this fake LOCK Windows Explorer looks happy and saves file.
  7607. * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
  7608. * Windows native DAV client. This is why FAKE LOCK is not enabed by default
  7609. */
  7610. MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
  7611. static const char *reply =
  7612. "HTTP/1.1 207 Multi-Status\r\n"
  7613. "Connection: close\r\n"
  7614. "Content-Type: text/xml; charset=utf-8\r\n\r\n"
  7615. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7616. "<d:multistatus xmlns:d='DAV:'>\n"
  7617. "<D:lockdiscovery>\n"
  7618. "<D:activelock>\n"
  7619. "<D:locktoken>\n"
  7620. "<D:href>\n"
  7621. "opaquelocktoken:%s%u"
  7622. "</D:href>"
  7623. "</D:locktoken>"
  7624. "</D:activelock>\n"
  7625. "</D:lockdiscovery>"
  7626. "</d:multistatus>\n";
  7627. mg_printf(nc, reply, path, (unsigned int) mg_time());
  7628. nc->flags |= MG_F_SEND_AND_CLOSE;
  7629. }
  7630. #endif
  7631. MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
  7632. struct http_message *hm) {
  7633. int status_code = 500;
  7634. if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
  7635. status_code = 415;
  7636. } else if (!mg_mkdir(path, 0755)) {
  7637. status_code = 201;
  7638. } else if (errno == EEXIST) {
  7639. status_code = 405;
  7640. } else if (errno == EACCES) {
  7641. status_code = 403;
  7642. } else if (errno == ENOENT) {
  7643. status_code = 409;
  7644. } else {
  7645. status_code = 500;
  7646. }
  7647. mg_http_send_error(nc, status_code, NULL);
  7648. }
  7649. static int mg_remove_directory(const struct mg_serve_http_opts *opts,
  7650. const char *dir) {
  7651. char path[MAX_PATH_SIZE];
  7652. struct dirent *dp;
  7653. cs_stat_t st;
  7654. DIR *dirp;
  7655. if ((dirp = opendir(dir)) == NULL) return 0;
  7656. while ((dp = readdir(dirp)) != NULL) {
  7657. if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
  7658. continue;
  7659. }
  7660. snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  7661. mg_stat(path, &st);
  7662. if (S_ISDIR(st.st_mode)) {
  7663. mg_remove_directory(opts, path);
  7664. } else {
  7665. remove(path);
  7666. }
  7667. }
  7668. closedir(dirp);
  7669. rmdir(dir);
  7670. return 1;
  7671. }
  7672. MG_INTERNAL void mg_handle_move(struct mg_connection *c,
  7673. const struct mg_serve_http_opts *opts,
  7674. const char *path, struct http_message *hm) {
  7675. const struct mg_str *dest = mg_get_http_header(hm, "Destination");
  7676. if (dest == NULL) {
  7677. mg_http_send_error(c, 411, NULL);
  7678. } else {
  7679. const char *p = (char *) memchr(dest->p, '/', dest->len);
  7680. if (p != NULL && p[1] == '/' &&
  7681. (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
  7682. char buf[MAX_PATH_SIZE];
  7683. snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
  7684. (int) (dest->p + dest->len - p), p);
  7685. if (rename(path, buf) == 0) {
  7686. mg_http_send_error(c, 200, NULL);
  7687. } else {
  7688. mg_http_send_error(c, 418, NULL);
  7689. }
  7690. } else {
  7691. mg_http_send_error(c, 500, NULL);
  7692. }
  7693. }
  7694. }
  7695. MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
  7696. const struct mg_serve_http_opts *opts,
  7697. const char *path) {
  7698. cs_stat_t st;
  7699. if (mg_stat(path, &st) != 0) {
  7700. mg_http_send_error(nc, 404, NULL);
  7701. } else if (S_ISDIR(st.st_mode)) {
  7702. mg_remove_directory(opts, path);
  7703. mg_http_send_error(nc, 204, NULL);
  7704. } else if (remove(path) == 0) {
  7705. mg_http_send_error(nc, 204, NULL);
  7706. } else {
  7707. mg_http_send_error(nc, 423, NULL);
  7708. }
  7709. }
  7710. /* Return -1 on error, 1 on success. */
  7711. static int mg_create_itermediate_directories(const char *path) {
  7712. const char *s;
  7713. /* Create intermediate directories if they do not exist */
  7714. for (s = path + 1; *s != '\0'; s++) {
  7715. if (*s == '/') {
  7716. char buf[MAX_PATH_SIZE];
  7717. cs_stat_t st;
  7718. snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
  7719. buf[sizeof(buf) - 1] = '\0';
  7720. if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
  7721. return -1;
  7722. }
  7723. }
  7724. }
  7725. return 1;
  7726. }
  7727. MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
  7728. struct http_message *hm) {
  7729. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  7730. cs_stat_t st;
  7731. const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
  7732. int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  7733. mg_http_free_proto_data_file(&pd->file);
  7734. if ((rc = mg_create_itermediate_directories(path)) == 0) {
  7735. mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
  7736. } else if (rc == -1) {
  7737. mg_http_send_error(nc, 500, NULL);
  7738. } else if (cl_hdr == NULL) {
  7739. mg_http_send_error(nc, 411, NULL);
  7740. } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
  7741. mg_http_send_error(nc, 500, NULL);
  7742. } else {
  7743. const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
  7744. int64_t r1 = 0, r2 = 0;
  7745. pd->file.type = DATA_PUT;
  7746. mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
  7747. pd->file.cl = to64(cl_hdr->p);
  7748. if (range_hdr != NULL &&
  7749. mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
  7750. status_code = 206;
  7751. fseeko(pd->file.fp, r1, SEEK_SET);
  7752. pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
  7753. }
  7754. mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
  7755. /* Remove HTTP request from the mbuf, leave only payload */
  7756. mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
  7757. mg_http_transfer_file_data(nc);
  7758. }
  7759. }
  7760. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
  7761. #ifdef MG_MODULE_LINES
  7762. #line 1 "mongoose/src/http_websocket.c"
  7763. #endif
  7764. /*
  7765. * Copyright (c) 2014 Cesanta Software Limited
  7766. * All rights reserved
  7767. */
  7768. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
  7769. #ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
  7770. #define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
  7771. #endif
  7772. #define MG_WS_NO_HOST_HEADER_MAGIC ((char *) 0x1)
  7773. static int mg_is_ws_fragment(unsigned char flags) {
  7774. return (flags & 0x80) == 0 || (flags & 0x0f) == 0;
  7775. }
  7776. static int mg_is_ws_first_fragment(unsigned char flags) {
  7777. return (flags & 0x80) == 0 && (flags & 0x0f) != 0;
  7778. }
  7779. static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
  7780. struct websocket_message *wsm) {
  7781. if (wsm->flags & 0x8) {
  7782. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
  7783. } else {
  7784. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_FRAME, wsm);
  7785. }
  7786. }
  7787. static int mg_deliver_websocket_data(struct mg_connection *nc) {
  7788. /* Using unsigned char *, cause of integer arithmetic below */
  7789. uint64_t i, data_len = 0, frame_len = 0, buf_len = nc->recv_mbuf.len, len,
  7790. mask_len = 0, header_len = 0;
  7791. unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p,
  7792. *e = p + buf_len;
  7793. unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */
  7794. int ok, reass = buf_len > 0 && mg_is_ws_fragment(p[0]) &&
  7795. !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
  7796. /* If that's a continuation frame that must be reassembled, handle it */
  7797. if (reass && !mg_is_ws_first_fragment(p[0]) &&
  7798. buf_len >= 1 + sizeof(*sizep) && buf_len >= 1 + sizeof(*sizep) + *sizep) {
  7799. buf += 1 + sizeof(*sizep) + *sizep;
  7800. buf_len -= 1 + sizeof(*sizep) + *sizep;
  7801. }
  7802. if (buf_len >= 2) {
  7803. len = buf[1] & 127;
  7804. mask_len = buf[1] & 128 ? 4 : 0;
  7805. if (len < 126 && buf_len >= mask_len) {
  7806. data_len = len;
  7807. header_len = 2 + mask_len;
  7808. } else if (len == 126 && buf_len >= 4 + mask_len) {
  7809. header_len = 4 + mask_len;
  7810. data_len = ntohs(*(uint16_t *) &buf[2]);
  7811. } else if (buf_len >= 10 + mask_len) {
  7812. header_len = 10 + mask_len;
  7813. data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) +
  7814. ntohl(*(uint32_t *) &buf[6]);
  7815. }
  7816. }
  7817. frame_len = header_len + data_len;
  7818. ok = frame_len > 0 && frame_len <= buf_len;
  7819. if (ok) {
  7820. struct websocket_message wsm;
  7821. wsm.size = (size_t) data_len;
  7822. wsm.data = buf + header_len;
  7823. wsm.flags = buf[0];
  7824. /* Apply mask if necessary */
  7825. if (mask_len > 0) {
  7826. for (i = 0; i < data_len; i++) {
  7827. buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
  7828. }
  7829. }
  7830. if (reass) {
  7831. /* On first fragmented frame, nullify size */
  7832. if (mg_is_ws_first_fragment(wsm.flags)) {
  7833. mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep));
  7834. p[0] &= ~0x0f; /* Next frames will be treated as continuation */
  7835. buf = p + 1 + sizeof(*sizep);
  7836. *sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */
  7837. }
  7838. /* Append this frame to the reassembled buffer */
  7839. memmove(buf, wsm.data, e - wsm.data);
  7840. (*sizep) += wsm.size;
  7841. nc->recv_mbuf.len -= wsm.data - buf;
  7842. /* On last fragmented frame - call user handler and remove data */
  7843. if (wsm.flags & 0x80) {
  7844. wsm.data = p + 1 + sizeof(*sizep);
  7845. wsm.size = *sizep;
  7846. mg_handle_incoming_websocket_frame(nc, &wsm);
  7847. mbuf_remove(&nc->recv_mbuf, 1 + sizeof(*sizep) + *sizep);
  7848. }
  7849. } else {
  7850. /* TODO(lsm): properly handle OOB control frames during defragmentation */
  7851. mg_handle_incoming_websocket_frame(nc, &wsm);
  7852. mbuf_remove(&nc->recv_mbuf, (size_t) frame_len); /* Cleanup frame */
  7853. }
  7854. /* If client closes, close too */
  7855. if ((buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) {
  7856. nc->flags |= MG_F_SEND_AND_CLOSE;
  7857. }
  7858. }
  7859. return ok;
  7860. }
  7861. struct ws_mask_ctx {
  7862. size_t pos; /* zero means unmasked */
  7863. uint32_t mask;
  7864. };
  7865. static uint32_t mg_ws_random_mask(void) {
  7866. uint32_t mask;
  7867. /*
  7868. * The spec requires WS client to generate hard to
  7869. * guess mask keys. From RFC6455, Section 5.3:
  7870. *
  7871. * The unpredictability of the masking key is essential to prevent
  7872. * authors of malicious applications from selecting the bytes that appear on
  7873. * the wire.
  7874. *
  7875. * Hence this feature is essential when the actual end user of this API
  7876. * is untrusted code that wouldn't have access to a lower level net API
  7877. * anyway (e.g. web browsers). Hence this feature is low prio for most
  7878. * mongoose use cases and thus can be disabled, e.g. when porting to a platform
  7879. * that lacks rand().
  7880. */
  7881. #if MG_DISABLE_WS_RANDOM_MASK
  7882. mask = 0xefbeadde; /* generated with a random number generator, I swear */
  7883. #else
  7884. if (sizeof(long) >= 4) {
  7885. mask = (uint32_t) rand();
  7886. } else if (sizeof(long) == 2) {
  7887. mask = (uint32_t) rand() << 16 | (uint32_t) rand();
  7888. }
  7889. #endif
  7890. return mask;
  7891. }
  7892. static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
  7893. struct ws_mask_ctx *ctx) {
  7894. int header_len;
  7895. unsigned char header[10];
  7896. header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : 0x80) + (op & 0x0f);
  7897. if (len < 126) {
  7898. header[1] = (unsigned char) len;
  7899. header_len = 2;
  7900. } else if (len < 65535) {
  7901. uint16_t tmp = htons((uint16_t) len);
  7902. header[1] = 126;
  7903. memcpy(&header[2], &tmp, sizeof(tmp));
  7904. header_len = 4;
  7905. } else {
  7906. uint32_t tmp;
  7907. header[1] = 127;
  7908. tmp = htonl((uint32_t)((uint64_t) len >> 32));
  7909. memcpy(&header[2], &tmp, sizeof(tmp));
  7910. tmp = htonl((uint32_t)(len & 0xffffffff));
  7911. memcpy(&header[6], &tmp, sizeof(tmp));
  7912. header_len = 10;
  7913. }
  7914. /* client connections enable masking */
  7915. if (nc->listener == NULL) {
  7916. header[1] |= 1 << 7; /* set masking flag */
  7917. mg_send(nc, header, header_len);
  7918. ctx->mask = mg_ws_random_mask();
  7919. mg_send(nc, &ctx->mask, sizeof(ctx->mask));
  7920. ctx->pos = nc->send_mbuf.len;
  7921. } else {
  7922. mg_send(nc, header, header_len);
  7923. ctx->pos = 0;
  7924. }
  7925. }
  7926. static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
  7927. size_t i;
  7928. if (ctx->pos == 0) return;
  7929. for (i = 0; i < (mbuf->len - ctx->pos); i++) {
  7930. mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
  7931. }
  7932. }
  7933. void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
  7934. size_t len) {
  7935. struct ws_mask_ctx ctx;
  7936. DBG(("%p %d %d", nc, op, (int) len));
  7937. mg_send_ws_header(nc, op, len, &ctx);
  7938. mg_send(nc, data, len);
  7939. mg_ws_mask_frame(&nc->send_mbuf, &ctx);
  7940. if (op == WEBSOCKET_OP_CLOSE) {
  7941. nc->flags |= MG_F_SEND_AND_CLOSE;
  7942. }
  7943. }
  7944. void mg_send_websocket_framev(struct mg_connection *nc, int op,
  7945. const struct mg_str *strv, int strvcnt) {
  7946. struct ws_mask_ctx ctx;
  7947. int i;
  7948. int len = 0;
  7949. for (i = 0; i < strvcnt; i++) {
  7950. len += strv[i].len;
  7951. }
  7952. mg_send_ws_header(nc, op, len, &ctx);
  7953. for (i = 0; i < strvcnt; i++) {
  7954. mg_send(nc, strv[i].p, strv[i].len);
  7955. }
  7956. mg_ws_mask_frame(&nc->send_mbuf, &ctx);
  7957. if (op == WEBSOCKET_OP_CLOSE) {
  7958. nc->flags |= MG_F_SEND_AND_CLOSE;
  7959. }
  7960. }
  7961. void mg_printf_websocket_frame(struct mg_connection *nc, int op,
  7962. const char *fmt, ...) {
  7963. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  7964. va_list ap;
  7965. int len;
  7966. va_start(ap, fmt);
  7967. if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  7968. mg_send_websocket_frame(nc, op, buf, len);
  7969. }
  7970. va_end(ap);
  7971. if (buf != mem && buf != NULL) {
  7972. MG_FREE(buf);
  7973. }
  7974. }
  7975. MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
  7976. void *ev_data) {
  7977. mg_call(nc, nc->handler, ev, ev_data);
  7978. switch (ev) {
  7979. case MG_EV_RECV:
  7980. do {
  7981. } while (mg_deliver_websocket_data(nc));
  7982. break;
  7983. case MG_EV_POLL:
  7984. /* Ping idle websocket connections */
  7985. {
  7986. time_t now = *(time_t *) ev_data;
  7987. if (nc->flags & MG_F_IS_WEBSOCKET &&
  7988. now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
  7989. mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
  7990. }
  7991. }
  7992. break;
  7993. default:
  7994. break;
  7995. }
  7996. }
  7997. #ifndef MG_EXT_SHA1
  7998. static void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
  7999. const size_t *msg_lens, uint8_t *digest) {
  8000. size_t i;
  8001. cs_sha1_ctx sha_ctx;
  8002. cs_sha1_init(&sha_ctx);
  8003. for (i = 0; i < num_msgs; i++) {
  8004. cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
  8005. }
  8006. cs_sha1_final(digest, &sha_ctx);
  8007. }
  8008. #else
  8009. extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
  8010. const size_t *msg_lens, uint8_t *digest);
  8011. #endif
  8012. MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
  8013. const struct mg_str *key) {
  8014. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8015. const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
  8016. const size_t msg_lens[2] = {key->len, 36};
  8017. unsigned char sha[20];
  8018. char b64_sha[30];
  8019. mg_hash_sha1_v(2, msgs, msg_lens, sha);
  8020. mg_base64_encode(sha, sizeof(sha), b64_sha);
  8021. mg_printf(nc, "%s%s%s",
  8022. "HTTP/1.1 101 Switching Protocols\r\n"
  8023. "Upgrade: websocket\r\n"
  8024. "Connection: Upgrade\r\n"
  8025. "Sec-WebSocket-Accept: ",
  8026. b64_sha, "\r\n\r\n");
  8027. DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
  8028. }
  8029. void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
  8030. const char *host, const char *protocol,
  8031. const char *extra_headers) {
  8032. mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
  8033. NULL);
  8034. }
  8035. void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
  8036. const char *host, const char *protocol,
  8037. const char *extra_headers, const char *user,
  8038. const char *pass) {
  8039. struct mbuf auth;
  8040. char key[25];
  8041. uint32_t nonce[4];
  8042. nonce[0] = mg_ws_random_mask();
  8043. nonce[1] = mg_ws_random_mask();
  8044. nonce[2] = mg_ws_random_mask();
  8045. nonce[3] = mg_ws_random_mask();
  8046. mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
  8047. mbuf_init(&auth, 0);
  8048. if (user != NULL) {
  8049. mg_basic_auth_header(user, pass, &auth);
  8050. }
  8051. /*
  8052. * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
  8053. * broken: it doesn't like zero length to be passed to %.*s
  8054. * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
  8055. * because it handles NULL specially (and incorrectly).
  8056. */
  8057. mg_printf(nc,
  8058. "GET %s HTTP/1.1\r\n"
  8059. "Upgrade: websocket\r\n"
  8060. "Connection: Upgrade\r\n"
  8061. "%.*s"
  8062. "Sec-WebSocket-Version: 13\r\n"
  8063. "Sec-WebSocket-Key: %s\r\n",
  8064. path, (int) auth.len, (auth.buf == NULL ? "" : auth.buf), key);
  8065. /* TODO(mkm): take default hostname from http proto data if host == NULL */
  8066. if (host != MG_WS_NO_HOST_HEADER_MAGIC) {
  8067. mg_printf(nc, "Host: %s\r\n", host);
  8068. }
  8069. if (protocol != NULL) {
  8070. mg_printf(nc, "Sec-WebSocket-Protocol: %s\r\n", protocol);
  8071. }
  8072. if (extra_headers != NULL) {
  8073. mg_printf(nc, "%s", extra_headers);
  8074. }
  8075. mg_printf(nc, "\r\n");
  8076. mbuf_free(&auth);
  8077. }
  8078. void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
  8079. const char *extra_headers) {
  8080. mg_send_websocket_handshake2(nc, path, MG_WS_NO_HOST_HEADER_MAGIC, NULL,
  8081. extra_headers);
  8082. }
  8083. struct mg_connection *mg_connect_ws_opt(struct mg_mgr *mgr,
  8084. mg_event_handler_t ev_handler,
  8085. struct mg_connect_opts opts,
  8086. const char *url, const char *protocol,
  8087. const char *extra_headers) {
  8088. char *user = NULL, *pass = NULL, *addr = NULL;
  8089. const char *path = NULL;
  8090. struct mg_connection *nc =
  8091. mg_connect_http_base(mgr, ev_handler, opts, "ws://", "wss://", url, &path,
  8092. &user, &pass, &addr);
  8093. if (nc != NULL) {
  8094. mg_send_websocket_handshake3(nc, path, addr, protocol, extra_headers, user,
  8095. pass);
  8096. }
  8097. MG_FREE(addr);
  8098. MG_FREE(user);
  8099. MG_FREE(pass);
  8100. return nc;
  8101. }
  8102. struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
  8103. mg_event_handler_t ev_handler,
  8104. const char *url, const char *protocol,
  8105. const char *extra_headers) {
  8106. struct mg_connect_opts opts;
  8107. memset(&opts, 0, sizeof(opts));
  8108. return mg_connect_ws_opt(mgr, ev_handler, opts, url, protocol, extra_headers);
  8109. }
  8110. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
  8111. #ifdef MG_MODULE_LINES
  8112. #line 1 "mongoose/src/util.c"
  8113. #endif
  8114. /*
  8115. * Copyright (c) 2014 Cesanta Software Limited
  8116. * All rights reserved
  8117. */
  8118. /* Amalgamated: #include "common/base64.h" */
  8119. /* Amalgamated: #include "mongoose/src/internal.h" */
  8120. /* Amalgamated: #include "mongoose/src/util.h" */
  8121. /* For platforms with limited libc */
  8122. #ifndef MAX
  8123. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  8124. #endif
  8125. const char *mg_skip(const char *s, const char *end, const char *delims,
  8126. struct mg_str *v) {
  8127. v->p = s;
  8128. while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
  8129. v->len = s - v->p;
  8130. while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
  8131. return s;
  8132. }
  8133. static int lowercase(const char *s) {
  8134. return tolower(*(const unsigned char *) s);
  8135. }
  8136. #if MG_ENABLE_FILESYSTEM
  8137. int mg_stat(const char *path, cs_stat_t *st) {
  8138. #ifdef _WIN32
  8139. wchar_t wpath[MAX_PATH_SIZE];
  8140. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  8141. DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
  8142. return _wstati64(wpath, st);
  8143. #else
  8144. return stat(path, st);
  8145. #endif
  8146. }
  8147. FILE *mg_fopen(const char *path, const char *mode) {
  8148. #ifdef _WIN32
  8149. wchar_t wpath[MAX_PATH_SIZE], wmode[10];
  8150. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  8151. to_wchar(mode, wmode, ARRAY_SIZE(wmode));
  8152. return _wfopen(wpath, wmode);
  8153. #else
  8154. return fopen(path, mode);
  8155. #endif
  8156. }
  8157. int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
  8158. #if defined(_WIN32) && !defined(WINCE)
  8159. wchar_t wpath[MAX_PATH_SIZE];
  8160. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  8161. return _wopen(wpath, flag, mode);
  8162. #else
  8163. return open(path, flag, mode); /* LCOV_EXCL_LINE */
  8164. #endif
  8165. }
  8166. #endif
  8167. void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
  8168. cs_base64_encode(src, src_len, dst);
  8169. }
  8170. int mg_base64_decode(const unsigned char *s, int len, char *dst) {
  8171. return cs_base64_decode(s, len, dst, NULL);
  8172. }
  8173. #if MG_ENABLE_THREADS
  8174. void *mg_start_thread(void *(*f)(void *), void *p) {
  8175. #ifdef WINCE
  8176. return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
  8177. #elif defined(_WIN32)
  8178. return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
  8179. #else
  8180. pthread_t thread_id = (pthread_t) 0;
  8181. pthread_attr_t attr;
  8182. (void) pthread_attr_init(&attr);
  8183. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  8184. #if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
  8185. (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
  8186. #endif
  8187. pthread_create(&thread_id, &attr, f, p);
  8188. pthread_attr_destroy(&attr);
  8189. return (void *) thread_id;
  8190. #endif
  8191. }
  8192. #endif /* MG_ENABLE_THREADS */
  8193. /* Set close-on-exec bit for a given socket. */
  8194. void mg_set_close_on_exec(sock_t sock) {
  8195. #if defined(_WIN32) && !defined(WINCE)
  8196. (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
  8197. #elif defined(__unix__)
  8198. fcntl(sock, F_SETFD, FD_CLOEXEC);
  8199. #else
  8200. (void) sock;
  8201. #endif
  8202. }
  8203. void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
  8204. int flags) {
  8205. int is_v6;
  8206. if (buf == NULL || len <= 0) return;
  8207. memset(buf, 0, len);
  8208. #if MG_ENABLE_IPV6
  8209. is_v6 = sa->sa.sa_family == AF_INET6;
  8210. #else
  8211. is_v6 = 0;
  8212. #endif
  8213. if (flags & MG_SOCK_STRINGIFY_IP) {
  8214. #if MG_ENABLE_IPV6
  8215. const void *addr = NULL;
  8216. char *start = buf;
  8217. socklen_t capacity = len;
  8218. if (!is_v6) {
  8219. addr = &sa->sin.sin_addr;
  8220. } else {
  8221. addr = (void *) &sa->sin6.sin6_addr;
  8222. if (flags & MG_SOCK_STRINGIFY_PORT) {
  8223. *buf = '[';
  8224. start++;
  8225. capacity--;
  8226. }
  8227. }
  8228. if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
  8229. goto cleanup;
  8230. }
  8231. #elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
  8232. /* Only Windoze Vista (and newer) have inet_ntop() */
  8233. char *addr_str = inet_ntoa(sa->sin.sin_addr);
  8234. if (addr_str != NULL) {
  8235. strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
  8236. } else {
  8237. goto cleanup;
  8238. }
  8239. #else
  8240. if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len - 1) == NULL) {
  8241. goto cleanup;
  8242. }
  8243. #endif
  8244. }
  8245. if (flags & MG_SOCK_STRINGIFY_PORT) {
  8246. int port = ntohs(sa->sin.sin_port);
  8247. if (flags & MG_SOCK_STRINGIFY_IP) {
  8248. int buf_len = strlen(buf);
  8249. snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
  8250. port);
  8251. } else {
  8252. snprintf(buf, len, "%d", port);
  8253. }
  8254. }
  8255. return;
  8256. cleanup:
  8257. *buf = '\0';
  8258. }
  8259. void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
  8260. int flags) {
  8261. union socket_address sa;
  8262. memset(&sa, 0, sizeof(sa));
  8263. mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
  8264. mg_sock_addr_to_str(&sa, buf, len, flags);
  8265. }
  8266. #if MG_ENABLE_HEXDUMP
  8267. static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
  8268. int offset) {
  8269. const unsigned char *p = (const unsigned char *) buf;
  8270. char ascii[17] = "";
  8271. int i, idx, n = 0;
  8272. for (i = 0; i < len; i++) {
  8273. idx = i % 16;
  8274. if (idx == 0) {
  8275. if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
  8276. n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
  8277. }
  8278. if (dst_len - n < 0) {
  8279. return n;
  8280. }
  8281. n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
  8282. ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
  8283. ascii[idx + 1] = '\0';
  8284. }
  8285. while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " ");
  8286. n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
  8287. return n;
  8288. }
  8289. int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
  8290. return mg_hexdump_n(buf, len, dst, dst_len, 0);
  8291. }
  8292. void mg_hexdumpf(FILE *fp, const void *buf, int len) {
  8293. char tmp[80];
  8294. int offset = 0, n;
  8295. while (len > 0) {
  8296. n = (len < 16 ? len : 16);
  8297. mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
  8298. fputs(tmp, fp);
  8299. offset += n;
  8300. len -= n;
  8301. }
  8302. }
  8303. void mg_hexdump_connection(struct mg_connection *nc, const char *path,
  8304. const void *buf, int num_bytes, int ev) {
  8305. FILE *fp = NULL;
  8306. char *hexbuf, src[60], dst[60];
  8307. int buf_size = num_bytes * 5 + 100;
  8308. if (strcmp(path, "-") == 0) {
  8309. fp = stdout;
  8310. } else if (strcmp(path, "--") == 0) {
  8311. fp = stderr;
  8312. #if MG_ENABLE_FILESYSTEM
  8313. } else {
  8314. fp = mg_fopen(path, "a");
  8315. #endif
  8316. }
  8317. if (fp == NULL) return;
  8318. mg_conn_addr_to_str(nc, src, sizeof(src),
  8319. MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
  8320. mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
  8321. MG_SOCK_STRINGIFY_PORT |
  8322. MG_SOCK_STRINGIFY_REMOTE);
  8323. fprintf(
  8324. fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc, src,
  8325. ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND
  8326. ? "->"
  8327. : ev == MG_EV_ACCEPT
  8328. ? "<A"
  8329. : ev == MG_EV_CONNECT ? "C>" : "XX",
  8330. dst, num_bytes);
  8331. if (num_bytes > 0 && (hexbuf = (char *) MG_MALLOC(buf_size)) != NULL) {
  8332. mg_hexdump(buf, num_bytes, hexbuf, buf_size);
  8333. fprintf(fp, "%s", hexbuf);
  8334. MG_FREE(hexbuf);
  8335. }
  8336. if (fp != stdin && fp != stdout) fclose(fp);
  8337. }
  8338. #endif
  8339. int mg_is_big_endian(void) {
  8340. static const int n = 1;
  8341. /* TODO(mkm) use compiletime check with 4-byte char literal */
  8342. return ((char *) &n)[0] == 0;
  8343. }
  8344. const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
  8345. struct mg_str *eq_val) {
  8346. if (list == NULL || *list == '\0') {
  8347. /* End of the list */
  8348. list = NULL;
  8349. } else {
  8350. val->p = list;
  8351. if ((list = strchr(val->p, ',')) != NULL) {
  8352. /* Comma found. Store length and shift the list ptr */
  8353. val->len = list - val->p;
  8354. list++;
  8355. } else {
  8356. /* This value is the last one */
  8357. list = val->p + strlen(val->p);
  8358. val->len = list - val->p;
  8359. }
  8360. if (eq_val != NULL) {
  8361. /* Value has form "x=y", adjust pointers and lengths */
  8362. /* so that val points to "x", and eq_val points to "y". */
  8363. eq_val->len = 0;
  8364. eq_val->p = (const char *) memchr(val->p, '=', val->len);
  8365. if (eq_val->p != NULL) {
  8366. eq_val->p++; /* Skip over '=' character */
  8367. eq_val->len = val->p + val->len - eq_val->p;
  8368. val->len = (eq_val->p - val->p) - 1;
  8369. }
  8370. }
  8371. }
  8372. return list;
  8373. }
  8374. int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
  8375. const char *or_str;
  8376. size_t len, i = 0, j = 0;
  8377. int res;
  8378. if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL) {
  8379. struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
  8380. res = mg_match_prefix_n(pstr, str);
  8381. if (res > 0) return res;
  8382. pstr.p = or_str + 1;
  8383. pstr.len = (pattern.p + pattern.len) - (or_str + 1);
  8384. return mg_match_prefix_n(pstr, str);
  8385. }
  8386. for (; i < pattern.len; i++, j++) {
  8387. if (pattern.p[i] == '?' && j != str.len) {
  8388. continue;
  8389. } else if (pattern.p[i] == '$') {
  8390. return j == str.len ? (int) j : -1;
  8391. } else if (pattern.p[i] == '*') {
  8392. i++;
  8393. if (pattern.p[i] == '*') {
  8394. i++;
  8395. len = str.len - j;
  8396. } else {
  8397. len = 0;
  8398. while (j + len != str.len && str.p[j + len] != '/') {
  8399. len++;
  8400. }
  8401. }
  8402. if (i == pattern.len) {
  8403. return j + len;
  8404. }
  8405. do {
  8406. const struct mg_str pstr = {pattern.p + i, pattern.len - i};
  8407. const struct mg_str sstr = {str.p + j + len, str.len - j - len};
  8408. res = mg_match_prefix_n(pstr, sstr);
  8409. } while (res == -1 && len-- > 0);
  8410. return res == -1 ? -1 : (int) (j + res + len);
  8411. } else if (lowercase(&pattern.p[i]) != lowercase(&str.p[j])) {
  8412. return -1;
  8413. }
  8414. }
  8415. return j;
  8416. }
  8417. int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
  8418. const struct mg_str pstr = {pattern, (size_t) pattern_len};
  8419. return mg_match_prefix_n(pstr, mg_mk_str(str));
  8420. }
  8421. DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
  8422. #ifndef WINCE
  8423. return errno;
  8424. #else
  8425. /* TODO(alashkin): translate error codes? */
  8426. return GetLastError();
  8427. #endif
  8428. }
  8429. void mg_mbuf_append_base64_putc(char ch, void *user_data) {
  8430. struct mbuf *mbuf = (struct mbuf *) user_data;
  8431. mbuf_append(mbuf, &ch, sizeof(ch));
  8432. }
  8433. void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
  8434. struct cs_base64_ctx ctx;
  8435. cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
  8436. cs_base64_update(&ctx, (const char *) data, len);
  8437. cs_base64_finish(&ctx);
  8438. }
  8439. void mg_basic_auth_header(const char *user, const char *pass,
  8440. struct mbuf *buf) {
  8441. const char *header_prefix = "Authorization: Basic ";
  8442. const char *header_suffix = "\r\n";
  8443. struct cs_base64_ctx ctx;
  8444. cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
  8445. mbuf_append(buf, header_prefix, strlen(header_prefix));
  8446. cs_base64_update(&ctx, user, strlen(user));
  8447. if (pass != NULL) {
  8448. cs_base64_update(&ctx, ":", 1);
  8449. cs_base64_update(&ctx, pass, strlen(pass));
  8450. }
  8451. cs_base64_finish(&ctx);
  8452. mbuf_append(buf, header_suffix, strlen(header_suffix));
  8453. }
  8454. #ifdef MG_MODULE_LINES
  8455. #line 1 "mongoose/src/mqtt.c"
  8456. #endif
  8457. /*
  8458. * Copyright (c) 2014 Cesanta Software Limited
  8459. * All rights reserved
  8460. */
  8461. #if MG_ENABLE_MQTT
  8462. #include <string.h>
  8463. /* Amalgamated: #include "mongoose/src/internal.h" */
  8464. /* Amalgamated: #include "mongoose/src/mqtt.h" */
  8465. static uint16_t getu16(const char *p) {
  8466. const uint8_t *up = (const uint8_t *) p;
  8467. return (up[0] << 8) + up[1];
  8468. }
  8469. static const char *scanto(const char *p, struct mg_str *s) {
  8470. s->len = getu16(p);
  8471. s->p = p + 2;
  8472. return s->p + s->len;
  8473. }
  8474. MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
  8475. uint8_t header;
  8476. size_t len = 0;
  8477. int cmd;
  8478. const char *p = &io->buf[1], *end;
  8479. if (io->len < 2) return -1;
  8480. header = io->buf[0];
  8481. cmd = header >> 4;
  8482. /* decode mqtt variable length */
  8483. do {
  8484. len += (*p & 127) << 7 * (p - &io->buf[1]);
  8485. } while ((*p++ & 128) != 0 && ((size_t)(p - io->buf) <= io->len));
  8486. end = p + len;
  8487. if (end > io->buf + io->len + 1) {
  8488. return -1;
  8489. }
  8490. mm->cmd = cmd;
  8491. mm->qos = MG_MQTT_GET_QOS(header);
  8492. switch (cmd) {
  8493. case MG_MQTT_CMD_CONNECT: {
  8494. p = scanto(p, &mm->protocol_name);
  8495. mm->protocol_version = *(uint8_t *) p++;
  8496. mm->connect_flags = *(uint8_t *) p++;
  8497. mm->keep_alive_timer = getu16(p);
  8498. p += 2;
  8499. if (p < end) p = scanto(p, &mm->client_id);
  8500. if (p < end && (mm->connect_flags & MG_MQTT_HAS_WILL))
  8501. p = scanto(p, &mm->will_topic);
  8502. if (p < end && (mm->connect_flags & MG_MQTT_HAS_WILL))
  8503. p = scanto(p, &mm->will_message);
  8504. if (p < end && (mm->connect_flags & MG_MQTT_HAS_USER_NAME))
  8505. p = scanto(p, &mm->user_name);
  8506. if (p < end && (mm->connect_flags & MG_MQTT_HAS_PASSWORD))
  8507. p = scanto(p, &mm->password);
  8508. LOG(LL_DEBUG,
  8509. ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
  8510. "will_msg [%.*s] user_name [%.*s] password [%.*s]",
  8511. len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
  8512. (int) mm->protocol_name.len, mm->protocol_name.p,
  8513. (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
  8514. mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
  8515. (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
  8516. mm->password.p));
  8517. break;
  8518. }
  8519. case MG_MQTT_CMD_CONNACK:
  8520. mm->connack_ret_code = p[1];
  8521. break;
  8522. case MG_MQTT_CMD_PUBACK:
  8523. case MG_MQTT_CMD_PUBREC:
  8524. case MG_MQTT_CMD_PUBREL:
  8525. case MG_MQTT_CMD_PUBCOMP:
  8526. case MG_MQTT_CMD_SUBACK:
  8527. mm->message_id = getu16(p);
  8528. break;
  8529. case MG_MQTT_CMD_PUBLISH: {
  8530. if (MG_MQTT_GET_QOS(header) > 0) {
  8531. mm->message_id = getu16(p);
  8532. p += 2;
  8533. }
  8534. p = scanto(p, &mm->topic);
  8535. mm->payload.p = p;
  8536. mm->payload.len = end - p;
  8537. break;
  8538. }
  8539. case MG_MQTT_CMD_SUBSCRIBE:
  8540. mm->message_id = getu16(p);
  8541. p += 2;
  8542. /*
  8543. * topic expressions are left in the payload and can be parsed with
  8544. * `mg_mqtt_next_subscribe_topic`
  8545. */
  8546. mm->payload.p = p;
  8547. mm->payload.len = end - p;
  8548. break;
  8549. default:
  8550. /* Unhandled command */
  8551. break;
  8552. }
  8553. return end - io->buf;
  8554. }
  8555. static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data) {
  8556. int len;
  8557. struct mbuf *io = &nc->recv_mbuf;
  8558. struct mg_mqtt_message mm;
  8559. memset(&mm, 0, sizeof(mm));
  8560. nc->handler(nc, ev, ev_data);
  8561. switch (ev) {
  8562. case MG_EV_RECV:
  8563. len = parse_mqtt(io, &mm);
  8564. if (len == -1) break; /* not fully buffered */
  8565. nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm);
  8566. mbuf_remove(io, len);
  8567. break;
  8568. }
  8569. }
  8570. static void mg_mqtt_proto_data_destructor(void *proto_data) {
  8571. MG_FREE(proto_data);
  8572. }
  8573. void mg_set_protocol_mqtt(struct mg_connection *nc) {
  8574. nc->proto_handler = mqtt_handler;
  8575. nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
  8576. nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
  8577. }
  8578. void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
  8579. static struct mg_send_mqtt_handshake_opts opts;
  8580. mg_send_mqtt_handshake_opt(nc, client_id, opts);
  8581. }
  8582. void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
  8583. struct mg_send_mqtt_handshake_opts opts) {
  8584. uint8_t header = MG_MQTT_CMD_CONNECT << 4;
  8585. uint8_t rem_len;
  8586. uint16_t keep_alive;
  8587. uint16_t len;
  8588. struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
  8589. /*
  8590. * 9: version_header(len, magic_string, version_number), 1: flags, 2:
  8591. * keep-alive timer,
  8592. * 2: client_identifier_len, n: client_id
  8593. */
  8594. rem_len = 9 + 1 + 2 + 2 + (uint8_t) strlen(client_id);
  8595. if (opts.user_name != NULL) {
  8596. opts.flags |= MG_MQTT_HAS_USER_NAME;
  8597. rem_len += (uint8_t) strlen(opts.user_name) + 2;
  8598. }
  8599. if (opts.password != NULL) {
  8600. opts.flags |= MG_MQTT_HAS_PASSWORD;
  8601. rem_len += (uint8_t) strlen(opts.password) + 2;
  8602. }
  8603. if (opts.will_topic != NULL && opts.will_message != NULL) {
  8604. opts.flags |= MG_MQTT_HAS_WILL;
  8605. rem_len += (uint8_t) strlen(opts.will_topic) + 2;
  8606. rem_len += (uint8_t) strlen(opts.will_message) + 2;
  8607. }
  8608. mg_send(nc, &header, 1);
  8609. mg_send(nc, &rem_len, 1);
  8610. mg_send(nc, "\00\06MQIsdp\03", 9);
  8611. mg_send(nc, &opts.flags, 1);
  8612. if (opts.keep_alive == 0) {
  8613. opts.keep_alive = 60;
  8614. }
  8615. keep_alive = htons(opts.keep_alive);
  8616. mg_send(nc, &keep_alive, 2);
  8617. len = htons((uint16_t) strlen(client_id));
  8618. mg_send(nc, &len, 2);
  8619. mg_send(nc, client_id, strlen(client_id));
  8620. if (opts.flags & MG_MQTT_HAS_WILL) {
  8621. len = htons((uint16_t) strlen(opts.will_topic));
  8622. mg_send(nc, &len, 2);
  8623. mg_send(nc, opts.will_topic, strlen(opts.will_topic));
  8624. len = htons((uint16_t) strlen(opts.will_message));
  8625. mg_send(nc, &len, 2);
  8626. mg_send(nc, opts.will_message, strlen(opts.will_message));
  8627. }
  8628. if (opts.flags & MG_MQTT_HAS_USER_NAME) {
  8629. len = htons((uint16_t) strlen(opts.user_name));
  8630. mg_send(nc, &len, 2);
  8631. mg_send(nc, opts.user_name, strlen(opts.user_name));
  8632. }
  8633. if (opts.flags & MG_MQTT_HAS_PASSWORD) {
  8634. len = htons((uint16_t) strlen(opts.password));
  8635. mg_send(nc, &len, 2);
  8636. mg_send(nc, opts.password, strlen(opts.password));
  8637. }
  8638. if (pd != NULL) {
  8639. pd->keep_alive = opts.keep_alive;
  8640. }
  8641. }
  8642. static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
  8643. uint8_t flags, size_t len) {
  8644. size_t off = nc->send_mbuf.len - len;
  8645. uint8_t header = cmd << 4 | (uint8_t) flags;
  8646. uint8_t buf[1 + sizeof(size_t)];
  8647. uint8_t *vlen = &buf[1];
  8648. assert(nc->send_mbuf.len >= len);
  8649. buf[0] = header;
  8650. /* mqtt variable length encoding */
  8651. do {
  8652. *vlen = len % 0x80;
  8653. len /= 0x80;
  8654. if (len > 0) *vlen |= 0x80;
  8655. vlen++;
  8656. } while (len > 0);
  8657. mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
  8658. }
  8659. void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
  8660. uint16_t message_id, int flags, const void *data,
  8661. size_t len) {
  8662. size_t old_len = nc->send_mbuf.len;
  8663. uint16_t topic_len = htons((uint16_t) strlen(topic));
  8664. uint16_t message_id_net = htons(message_id);
  8665. mg_send(nc, &topic_len, 2);
  8666. mg_send(nc, topic, strlen(topic));
  8667. if (MG_MQTT_GET_QOS(flags) > 0) {
  8668. mg_send(nc, &message_id_net, 2);
  8669. }
  8670. mg_send(nc, data, len);
  8671. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
  8672. nc->send_mbuf.len - old_len);
  8673. }
  8674. void mg_mqtt_subscribe(struct mg_connection *nc,
  8675. const struct mg_mqtt_topic_expression *topics,
  8676. size_t topics_len, uint16_t message_id) {
  8677. size_t old_len = nc->send_mbuf.len;
  8678. uint16_t message_id_n = htons(message_id);
  8679. size_t i;
  8680. mg_send(nc, (char *) &message_id_n, 2);
  8681. for (i = 0; i < topics_len; i++) {
  8682. uint16_t topic_len_n = htons((uint16_t) strlen(topics[i].topic));
  8683. mg_send(nc, &topic_len_n, 2);
  8684. mg_send(nc, topics[i].topic, strlen(topics[i].topic));
  8685. mg_send(nc, &topics[i].qos, 1);
  8686. }
  8687. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
  8688. nc->send_mbuf.len - old_len);
  8689. }
  8690. int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
  8691. struct mg_str *topic, uint8_t *qos, int pos) {
  8692. unsigned char *buf = (unsigned char *) msg->payload.p + pos;
  8693. if ((size_t) pos >= msg->payload.len) {
  8694. return -1;
  8695. }
  8696. topic->len = buf[0] << 8 | buf[1];
  8697. topic->p = (char *) buf + 2;
  8698. *qos = buf[2 + topic->len];
  8699. return pos + 2 + topic->len + 1;
  8700. }
  8701. void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
  8702. size_t topics_len, uint16_t message_id) {
  8703. size_t old_len = nc->send_mbuf.len;
  8704. uint16_t message_id_n = htons(message_id);
  8705. size_t i;
  8706. mg_send(nc, (char *) &message_id_n, 2);
  8707. for (i = 0; i < topics_len; i++) {
  8708. uint16_t topic_len_n = htons((uint16_t) strlen(topics[i]));
  8709. mg_send(nc, &topic_len_n, 2);
  8710. mg_send(nc, topics[i], strlen(topics[i]));
  8711. }
  8712. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
  8713. nc->send_mbuf.len - old_len);
  8714. }
  8715. void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
  8716. uint8_t unused = 0;
  8717. mg_send(nc, &unused, 1);
  8718. mg_send(nc, &return_code, 1);
  8719. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
  8720. }
  8721. /*
  8722. * Sends a command which contains only a `message_id` and a QoS level of 1.
  8723. *
  8724. * Helper function.
  8725. */
  8726. static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
  8727. uint16_t message_id) {
  8728. uint16_t message_id_net = htons(message_id);
  8729. mg_send(nc, &message_id_net, 2);
  8730. mg_mqtt_prepend_header(nc, cmd, MG_MQTT_QOS(1), 2);
  8731. }
  8732. void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
  8733. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
  8734. }
  8735. void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
  8736. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
  8737. }
  8738. void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
  8739. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
  8740. }
  8741. void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
  8742. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
  8743. }
  8744. void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
  8745. uint16_t message_id) {
  8746. size_t i;
  8747. uint16_t message_id_net = htons(message_id);
  8748. mg_send(nc, &message_id_net, 2);
  8749. for (i = 0; i < qoss_len; i++) {
  8750. mg_send(nc, &qoss[i], 1);
  8751. }
  8752. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
  8753. }
  8754. void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
  8755. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
  8756. }
  8757. void mg_mqtt_ping(struct mg_connection *nc) {
  8758. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
  8759. }
  8760. void mg_mqtt_pong(struct mg_connection *nc) {
  8761. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
  8762. }
  8763. void mg_mqtt_disconnect(struct mg_connection *nc) {
  8764. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
  8765. }
  8766. #endif /* MG_ENABLE_MQTT */
  8767. #ifdef MG_MODULE_LINES
  8768. #line 1 "mongoose/src/mqtt_server.c"
  8769. #endif
  8770. /*
  8771. * Copyright (c) 2014 Cesanta Software Limited
  8772. * All rights reserved
  8773. */
  8774. /* Amalgamated: #include "mongoose/src/internal.h" */
  8775. /* Amalgamated: #include "mongoose/src/mqtt-server.h" */
  8776. #if MG_ENABLE_MQTT_BROKER
  8777. static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
  8778. struct mg_mqtt_session *s,
  8779. struct mg_connection *nc) {
  8780. s->brk = brk;
  8781. s->subscriptions = NULL;
  8782. s->num_subscriptions = 0;
  8783. s->nc = nc;
  8784. }
  8785. static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
  8786. LIST_INSERT_HEAD(&s->brk->sessions, s, link);
  8787. }
  8788. static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
  8789. LIST_REMOVE(s, link);
  8790. }
  8791. static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
  8792. size_t i;
  8793. for (i = 0; i < s->num_subscriptions; i++) {
  8794. MG_FREE((void *) s->subscriptions[i].topic);
  8795. }
  8796. MG_FREE(s->subscriptions);
  8797. MG_FREE(s);
  8798. }
  8799. static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
  8800. mg_mqtt_remove_session(s);
  8801. mg_mqtt_destroy_session(s);
  8802. }
  8803. void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
  8804. LIST_INIT(&brk->sessions);
  8805. brk->user_data = user_data;
  8806. }
  8807. static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
  8808. struct mg_connection *nc) {
  8809. struct mg_mqtt_session *s = (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
  8810. if (s == NULL) {
  8811. /* LCOV_EXCL_START */
  8812. mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
  8813. return;
  8814. /* LCOV_EXCL_STOP */
  8815. }
  8816. /* TODO(mkm): check header (magic and version) */
  8817. mg_mqtt_session_init(brk, s, nc);
  8818. s->user_data = nc->user_data;
  8819. nc->user_data = s;
  8820. mg_mqtt_add_session(s);
  8821. mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
  8822. }
  8823. static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
  8824. struct mg_mqtt_message *msg) {
  8825. struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->user_data;
  8826. uint8_t qoss[512];
  8827. size_t qoss_len = 0;
  8828. struct mg_str topic;
  8829. uint8_t qos;
  8830. int pos;
  8831. struct mg_mqtt_topic_expression *te;
  8832. for (pos = 0;
  8833. (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
  8834. qoss[qoss_len++] = qos;
  8835. }
  8836. ss->subscriptions = (struct mg_mqtt_topic_expression *) MG_REALLOC(
  8837. ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len);
  8838. for (pos = 0;
  8839. (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
  8840. ss->num_subscriptions++) {
  8841. te = &ss->subscriptions[ss->num_subscriptions];
  8842. te->topic = (char *) MG_MALLOC(topic.len + 1);
  8843. te->qos = qos;
  8844. strncpy((char *) te->topic, topic.p, topic.len + 1);
  8845. }
  8846. mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id);
  8847. }
  8848. /*
  8849. * Matches a topic against a topic expression
  8850. *
  8851. * See http://goo.gl/iWk21X
  8852. *
  8853. * Returns 1 if it matches; 0 otherwise.
  8854. */
  8855. static int mg_mqtt_match_topic_expression(const char *exp,
  8856. const struct mg_str *topic) {
  8857. /* TODO(mkm): implement real matching */
  8858. size_t len = strlen(exp);
  8859. if (strchr(exp, '#')) {
  8860. len -= 2;
  8861. if (topic->len < len) {
  8862. len = topic->len;
  8863. }
  8864. }
  8865. return strncmp(topic->p, exp, len) == 0;
  8866. }
  8867. static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
  8868. struct mg_mqtt_message *msg) {
  8869. struct mg_mqtt_session *s;
  8870. size_t i;
  8871. for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
  8872. for (i = 0; i < s->num_subscriptions; i++) {
  8873. if (mg_mqtt_match_topic_expression(s->subscriptions[i].topic,
  8874. &msg->topic)) {
  8875. char buf[100], *p = buf;
  8876. mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
  8877. msg->topic.p);
  8878. if (p == NULL) {
  8879. return;
  8880. }
  8881. mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
  8882. if (p != buf) {
  8883. MG_FREE(p);
  8884. }
  8885. break;
  8886. }
  8887. }
  8888. }
  8889. }
  8890. void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
  8891. struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
  8892. struct mg_mqtt_broker *brk;
  8893. if (nc->listener) {
  8894. brk = (struct mg_mqtt_broker *) nc->listener->user_data;
  8895. } else {
  8896. brk = (struct mg_mqtt_broker *) nc->user_data;
  8897. }
  8898. switch (ev) {
  8899. case MG_EV_ACCEPT:
  8900. mg_set_protocol_mqtt(nc);
  8901. nc->user_data = NULL; /* Clear up the inherited pointer to broker */
  8902. break;
  8903. case MG_EV_MQTT_CONNECT:
  8904. mg_mqtt_broker_handle_connect(brk, nc);
  8905. break;
  8906. case MG_EV_MQTT_SUBSCRIBE:
  8907. mg_mqtt_broker_handle_subscribe(nc, msg);
  8908. break;
  8909. case MG_EV_MQTT_PUBLISH:
  8910. mg_mqtt_broker_handle_publish(brk, msg);
  8911. break;
  8912. case MG_EV_CLOSE:
  8913. if (nc->listener && nc->user_data != NULL) {
  8914. mg_mqtt_close_session((struct mg_mqtt_session *) nc->user_data);
  8915. }
  8916. break;
  8917. }
  8918. }
  8919. struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
  8920. struct mg_mqtt_session *s) {
  8921. return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
  8922. }
  8923. #endif /* MG_ENABLE_MQTT_BROKER */
  8924. #ifdef MG_MODULE_LINES
  8925. #line 1 "mongoose/src/dns.c"
  8926. #endif
  8927. /*
  8928. * Copyright (c) 2014 Cesanta Software Limited
  8929. * All rights reserved
  8930. */
  8931. #if MG_ENABLE_DNS
  8932. /* Amalgamated: #include "mongoose/src/internal.h" */
  8933. /* Amalgamated: #include "mongoose/src/dns.h" */
  8934. static int mg_dns_tid = 0xa0;
  8935. struct mg_dns_header {
  8936. uint16_t transaction_id;
  8937. uint16_t flags;
  8938. uint16_t num_questions;
  8939. uint16_t num_answers;
  8940. uint16_t num_authority_prs;
  8941. uint16_t num_other_prs;
  8942. };
  8943. struct mg_dns_resource_record *mg_dns_next_record(
  8944. struct mg_dns_message *msg, int query,
  8945. struct mg_dns_resource_record *prev) {
  8946. struct mg_dns_resource_record *rr;
  8947. for (rr = (prev == NULL ? msg->answers : prev + 1);
  8948. rr - msg->answers < msg->num_answers; rr++) {
  8949. if (rr->rtype == query) {
  8950. return rr;
  8951. }
  8952. }
  8953. return NULL;
  8954. }
  8955. int mg_dns_parse_record_data(struct mg_dns_message *msg,
  8956. struct mg_dns_resource_record *rr, void *data,
  8957. size_t data_len) {
  8958. switch (rr->rtype) {
  8959. case MG_DNS_A_RECORD:
  8960. if (data_len < sizeof(struct in_addr)) {
  8961. return -1;
  8962. }
  8963. if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
  8964. return -1;
  8965. }
  8966. memcpy(data, rr->rdata.p, data_len);
  8967. return 0;
  8968. #if MG_ENABLE_IPV6
  8969. case MG_DNS_AAAA_RECORD:
  8970. if (data_len < sizeof(struct in6_addr)) {
  8971. return -1; /* LCOV_EXCL_LINE */
  8972. }
  8973. memcpy(data, rr->rdata.p, data_len);
  8974. return 0;
  8975. #endif
  8976. case MG_DNS_CNAME_RECORD:
  8977. mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
  8978. return 0;
  8979. }
  8980. return -1;
  8981. }
  8982. int mg_dns_insert_header(struct mbuf *io, size_t pos,
  8983. struct mg_dns_message *msg) {
  8984. struct mg_dns_header header;
  8985. memset(&header, 0, sizeof(header));
  8986. header.transaction_id = msg->transaction_id;
  8987. header.flags = htons(msg->flags);
  8988. header.num_questions = htons(msg->num_questions);
  8989. header.num_answers = htons(msg->num_answers);
  8990. return mbuf_insert(io, pos, &header, sizeof(header));
  8991. }
  8992. int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
  8993. unsigned char *begin, *end;
  8994. struct mg_dns_resource_record *last_q;
  8995. if (msg->num_questions <= 0) return 0;
  8996. begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
  8997. last_q = &msg->questions[msg->num_questions - 1];
  8998. end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
  8999. return mbuf_append(io, begin, end - begin);
  9000. }
  9001. int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
  9002. const char *s;
  9003. unsigned char n;
  9004. size_t pos = io->len;
  9005. do {
  9006. if ((s = strchr(name, '.')) == NULL) {
  9007. s = name + len;
  9008. }
  9009. if (s - name > 127) {
  9010. return -1; /* TODO(mkm) cover */
  9011. }
  9012. n = s - name; /* chunk length */
  9013. mbuf_append(io, &n, 1); /* send length */
  9014. mbuf_append(io, name, n);
  9015. if (*s == '.') {
  9016. n++;
  9017. }
  9018. name += n;
  9019. len -= n;
  9020. } while (*s != '\0');
  9021. mbuf_append(io, "\0", 1); /* Mark end of host name */
  9022. return io->len - pos;
  9023. }
  9024. int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
  9025. const char *name, size_t nlen, const void *rdata,
  9026. size_t rlen) {
  9027. size_t pos = io->len;
  9028. uint16_t u16;
  9029. uint32_t u32;
  9030. if (rr->kind == MG_DNS_INVALID_RECORD) {
  9031. return -1; /* LCOV_EXCL_LINE */
  9032. }
  9033. if (mg_dns_encode_name(io, name, nlen) == -1) {
  9034. return -1;
  9035. }
  9036. u16 = htons(rr->rtype);
  9037. mbuf_append(io, &u16, 2);
  9038. u16 = htons(rr->rclass);
  9039. mbuf_append(io, &u16, 2);
  9040. if (rr->kind == MG_DNS_ANSWER) {
  9041. u32 = htonl(rr->ttl);
  9042. mbuf_append(io, &u32, 4);
  9043. if (rr->rtype == MG_DNS_CNAME_RECORD) {
  9044. int clen;
  9045. /* fill size after encoding */
  9046. size_t off = io->len;
  9047. mbuf_append(io, &u16, 2);
  9048. if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
  9049. return -1;
  9050. }
  9051. u16 = clen;
  9052. io->buf[off] = u16 >> 8;
  9053. io->buf[off + 1] = u16 & 0xff;
  9054. } else {
  9055. u16 = htons((uint16_t) rlen);
  9056. mbuf_append(io, &u16, 2);
  9057. mbuf_append(io, rdata, rlen);
  9058. }
  9059. }
  9060. return io->len - pos;
  9061. }
  9062. void mg_send_dns_query(struct mg_connection *nc, const char *name,
  9063. int query_type) {
  9064. struct mg_dns_message *msg =
  9065. (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
  9066. struct mbuf pkt;
  9067. struct mg_dns_resource_record *rr = &msg->questions[0];
  9068. DBG(("%s %d", name, query_type));
  9069. mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
  9070. msg->transaction_id = ++mg_dns_tid;
  9071. msg->flags = 0x100;
  9072. msg->num_questions = 1;
  9073. mg_dns_insert_header(&pkt, 0, msg);
  9074. rr->rtype = query_type;
  9075. rr->rclass = 1; /* Class: inet */
  9076. rr->kind = MG_DNS_QUESTION;
  9077. if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
  9078. /* TODO(mkm): return an error code */
  9079. goto cleanup; /* LCOV_EXCL_LINE */
  9080. }
  9081. /* TCP DNS requires messages to be prefixed with len */
  9082. if (!(nc->flags & MG_F_UDP)) {
  9083. uint16_t len = htons((uint16_t) pkt.len);
  9084. mbuf_insert(&pkt, 0, &len, 2);
  9085. }
  9086. mg_send(nc, pkt.buf, pkt.len);
  9087. mbuf_free(&pkt);
  9088. cleanup:
  9089. MG_FREE(msg);
  9090. }
  9091. static unsigned char *mg_parse_dns_resource_record(
  9092. unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
  9093. int reply) {
  9094. unsigned char *name = data;
  9095. int chunk_len, data_len;
  9096. while (data < end && (chunk_len = *data)) {
  9097. if (((unsigned char *) data)[0] & 0xc0) {
  9098. data += 1;
  9099. break;
  9100. }
  9101. data += chunk_len + 1;
  9102. }
  9103. if (data > end - 5) {
  9104. return NULL;
  9105. }
  9106. rr->name.p = (char *) name;
  9107. rr->name.len = data - name + 1;
  9108. data++;
  9109. rr->rtype = data[0] << 8 | data[1];
  9110. data += 2;
  9111. rr->rclass = data[0] << 8 | data[1];
  9112. data += 2;
  9113. rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
  9114. if (reply) {
  9115. if (data >= end - 6) {
  9116. return NULL;
  9117. }
  9118. rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
  9119. data[2] << 8 | data[3];
  9120. data += 4;
  9121. data_len = *data << 8 | *(data + 1);
  9122. data += 2;
  9123. rr->rdata.p = (char *) data;
  9124. rr->rdata.len = data_len;
  9125. data += data_len;
  9126. }
  9127. return data;
  9128. }
  9129. int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
  9130. struct mg_dns_header *header = (struct mg_dns_header *) buf;
  9131. unsigned char *data = (unsigned char *) buf + sizeof(*header);
  9132. unsigned char *end = (unsigned char *) buf + len;
  9133. int i;
  9134. memset(msg, 0, sizeof(*msg));
  9135. msg->pkt.p = buf;
  9136. msg->pkt.len = len;
  9137. if (len < (int) sizeof(*header)) return -1;
  9138. msg->transaction_id = header->transaction_id;
  9139. msg->flags = ntohs(header->flags);
  9140. msg->num_questions = ntohs(header->num_questions);
  9141. if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
  9142. msg->num_questions = (int) ARRAY_SIZE(msg->questions);
  9143. }
  9144. msg->num_answers = ntohs(header->num_answers);
  9145. if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
  9146. msg->num_answers = (int) ARRAY_SIZE(msg->answers);
  9147. }
  9148. for (i = 0; i < msg->num_questions; i++) {
  9149. data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
  9150. if (data == NULL) return -1;
  9151. }
  9152. for (i = 0; i < msg->num_answers; i++) {
  9153. data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
  9154. if (data == NULL) return -1;
  9155. }
  9156. return 0;
  9157. }
  9158. size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
  9159. char *dst, int dst_len) {
  9160. int chunk_len;
  9161. char *old_dst = dst;
  9162. const unsigned char *data = (unsigned char *) name->p;
  9163. const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
  9164. if (data >= end) {
  9165. return 0;
  9166. }
  9167. while ((chunk_len = *data++)) {
  9168. int leeway = dst_len - (dst - old_dst);
  9169. if (data >= end) {
  9170. return 0;
  9171. }
  9172. if (chunk_len & 0xc0) {
  9173. uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
  9174. if (off >= msg->pkt.len) {
  9175. return 0;
  9176. }
  9177. data = (unsigned char *) msg->pkt.p + off;
  9178. continue;
  9179. }
  9180. if (chunk_len > leeway) {
  9181. chunk_len = leeway;
  9182. }
  9183. if (data + chunk_len >= end) {
  9184. return 0;
  9185. }
  9186. memcpy(dst, data, chunk_len);
  9187. data += chunk_len;
  9188. dst += chunk_len;
  9189. leeway -= chunk_len;
  9190. if (leeway == 0) {
  9191. return dst - old_dst;
  9192. }
  9193. *dst++ = '.';
  9194. }
  9195. if (dst != old_dst) {
  9196. *--dst = 0;
  9197. }
  9198. return dst - old_dst;
  9199. }
  9200. static void dns_handler(struct mg_connection *nc, int ev, void *ev_data) {
  9201. struct mbuf *io = &nc->recv_mbuf;
  9202. struct mg_dns_message msg;
  9203. /* Pass low-level events to the user handler */
  9204. nc->handler(nc, ev, ev_data);
  9205. switch (ev) {
  9206. case MG_EV_RECV:
  9207. if (!(nc->flags & MG_F_UDP)) {
  9208. mbuf_remove(&nc->recv_mbuf, 2);
  9209. }
  9210. if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
  9211. /* reply + recursion allowed + format error */
  9212. memset(&msg, 0, sizeof(msg));
  9213. msg.flags = 0x8081;
  9214. mg_dns_insert_header(io, 0, &msg);
  9215. if (!(nc->flags & MG_F_UDP)) {
  9216. uint16_t len = htons((uint16_t) io->len);
  9217. mbuf_insert(io, 0, &len, 2);
  9218. }
  9219. mg_send(nc, io->buf, io->len);
  9220. } else {
  9221. /* Call user handler with parsed message */
  9222. nc->handler(nc, MG_DNS_MESSAGE, &msg);
  9223. }
  9224. mbuf_remove(io, io->len);
  9225. break;
  9226. }
  9227. }
  9228. void mg_set_protocol_dns(struct mg_connection *nc) {
  9229. nc->proto_handler = dns_handler;
  9230. }
  9231. #endif /* MG_ENABLE_DNS */
  9232. #ifdef MG_MODULE_LINES
  9233. #line 1 "mongoose/src/dns_server.c"
  9234. #endif
  9235. /*
  9236. * Copyright (c) 2014 Cesanta Software Limited
  9237. * All rights reserved
  9238. */
  9239. #if MG_ENABLE_DNS_SERVER
  9240. /* Amalgamated: #include "mongoose/src/internal.h" */
  9241. /* Amalgamated: #include "mongoose/src/dns-server.h" */
  9242. struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
  9243. struct mg_dns_message *msg) {
  9244. struct mg_dns_reply rep;
  9245. rep.msg = msg;
  9246. rep.io = io;
  9247. rep.start = io->len;
  9248. /* reply + recursion allowed */
  9249. msg->flags |= 0x8080;
  9250. mg_dns_copy_questions(io, msg);
  9251. msg->num_answers = 0;
  9252. return rep;
  9253. }
  9254. void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
  9255. size_t sent = r->io->len - r->start;
  9256. mg_dns_insert_header(r->io, r->start, r->msg);
  9257. if (!(nc->flags & MG_F_UDP)) {
  9258. uint16_t len = htons((uint16_t) sent);
  9259. mbuf_insert(r->io, r->start, &len, 2);
  9260. }
  9261. if (&nc->send_mbuf != r->io) {
  9262. mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
  9263. r->io->len = r->start;
  9264. }
  9265. }
  9266. int mg_dns_reply_record(struct mg_dns_reply *reply,
  9267. struct mg_dns_resource_record *question,
  9268. const char *name, int rtype, int ttl, const void *rdata,
  9269. size_t rdata_len) {
  9270. struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
  9271. char rname[512];
  9272. struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
  9273. if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
  9274. return -1; /* LCOV_EXCL_LINE */
  9275. }
  9276. if (name == NULL) {
  9277. name = rname;
  9278. rname[511] = 0;
  9279. mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
  9280. }
  9281. *ans = *question;
  9282. ans->kind = MG_DNS_ANSWER;
  9283. ans->rtype = rtype;
  9284. ans->ttl = ttl;
  9285. if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
  9286. rdata_len) == -1) {
  9287. return -1; /* LCOV_EXCL_LINE */
  9288. };
  9289. msg->num_answers++;
  9290. return 0;
  9291. }
  9292. #endif /* MG_ENABLE_DNS_SERVER */
  9293. #ifdef MG_MODULE_LINES
  9294. #line 1 "mongoose/src/resolv.c"
  9295. #endif
  9296. /*
  9297. * Copyright (c) 2014 Cesanta Software Limited
  9298. * All rights reserved
  9299. */
  9300. #if MG_ENABLE_ASYNC_RESOLVER
  9301. /* Amalgamated: #include "mongoose/src/internal.h" */
  9302. /* Amalgamated: #include "mongoose/src/resolv.h" */
  9303. #ifndef MG_DEFAULT_NAMESERVER
  9304. #define MG_DEFAULT_NAMESERVER "8.8.8.8"
  9305. #endif
  9306. static const char *mg_default_dns_server = "udp://" MG_DEFAULT_NAMESERVER ":53";
  9307. MG_INTERNAL char mg_dns_server[256];
  9308. struct mg_resolve_async_request {
  9309. char name[1024];
  9310. int query;
  9311. mg_resolve_callback_t callback;
  9312. void *data;
  9313. time_t timeout;
  9314. int max_retries;
  9315. enum mg_resolve_err err;
  9316. /* state */
  9317. time_t last_time;
  9318. int retries;
  9319. };
  9320. /*
  9321. * Find what nameserver to use.
  9322. *
  9323. * Return 0 if OK, -1 if error
  9324. */
  9325. static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
  9326. int ret = -1;
  9327. #ifdef _WIN32
  9328. int i;
  9329. LONG err;
  9330. HKEY hKey, hSub;
  9331. wchar_t subkey[512], value[128],
  9332. *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
  9333. if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
  9334. ERROR_SUCCESS) {
  9335. fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
  9336. ret = -1;
  9337. } else {
  9338. for (ret = -1, i = 0; 1; i++) {
  9339. DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
  9340. if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
  9341. NULL) != ERROR_SUCCESS) {
  9342. break;
  9343. }
  9344. if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
  9345. (RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
  9346. &len) == ERROR_SUCCESS ||
  9347. RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
  9348. &len) == ERROR_SUCCESS)) {
  9349. /*
  9350. * See https://github.com/cesanta/mongoose/issues/176
  9351. * The value taken from the registry can be empty, a single
  9352. * IP address, or multiple IP addresses separated by comma.
  9353. * If it's empty, check the next interface.
  9354. * If it's multiple IP addresses, take the first one.
  9355. */
  9356. wchar_t *comma = wcschr(value, ',');
  9357. if (value[0] == '\0') {
  9358. continue;
  9359. }
  9360. if (comma != NULL) {
  9361. *comma = '\0';
  9362. }
  9363. snprintf(name, name_len, "udp://%S:53", value);
  9364. ret = 0;
  9365. RegCloseKey(hSub);
  9366. break;
  9367. }
  9368. }
  9369. RegCloseKey(hKey);
  9370. }
  9371. #elif MG_ENABLE_FILESYSTEM
  9372. FILE *fp;
  9373. char line[512];
  9374. if ((fp = mg_fopen("/etc/resolv.conf", "r")) == NULL) {
  9375. ret = -1;
  9376. } else {
  9377. /* Try to figure out what nameserver to use */
  9378. for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
  9379. unsigned int a, b, c, d;
  9380. if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
  9381. snprintf(name, name_len, "udp://%u.%u.%u.%u:53", a, b, c, d);
  9382. ret = 0;
  9383. break;
  9384. }
  9385. }
  9386. (void) fclose(fp);
  9387. }
  9388. #else
  9389. snprintf(name, name_len, "%s", mg_default_dns_server);
  9390. #endif /* _WIN32 */
  9391. return ret;
  9392. }
  9393. int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
  9394. #if MG_ENABLE_FILESYSTEM
  9395. /* TODO(mkm) cache /etc/hosts */
  9396. FILE *fp;
  9397. char line[1024];
  9398. char *p;
  9399. char alias[256];
  9400. unsigned int a, b, c, d;
  9401. int len = 0;
  9402. if ((fp = mg_fopen("/etc/hosts", "r")) == NULL) {
  9403. return -1;
  9404. }
  9405. for (; fgets(line, sizeof(line), fp) != NULL;) {
  9406. if (line[0] == '#') continue;
  9407. if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
  9408. /* TODO(mkm): handle ipv6 */
  9409. continue;
  9410. }
  9411. for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
  9412. if (strcmp(alias, name) == 0) {
  9413. usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
  9414. fclose(fp);
  9415. return 0;
  9416. }
  9417. }
  9418. }
  9419. fclose(fp);
  9420. #else
  9421. (void) name;
  9422. (void) usa;
  9423. #endif
  9424. return -1;
  9425. }
  9426. static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data) {
  9427. time_t now = (time_t) mg_time();
  9428. struct mg_resolve_async_request *req;
  9429. struct mg_dns_message *msg;
  9430. int first = 0;
  9431. if (ev != MG_EV_POLL) DBG(("ev=%d user_data=%p", ev, nc->user_data));
  9432. req = (struct mg_resolve_async_request *) nc->user_data;
  9433. if (req == NULL) {
  9434. return;
  9435. }
  9436. switch (ev) {
  9437. case MG_EV_CONNECT:
  9438. /* don't depend on timer not being at epoch for sending out first req */
  9439. first = 1;
  9440. /* fallthrough */
  9441. case MG_EV_POLL:
  9442. if (req->retries > req->max_retries) {
  9443. req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
  9444. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9445. break;
  9446. }
  9447. if (first || now - req->last_time >= req->timeout) {
  9448. mg_send_dns_query(nc, req->name, req->query);
  9449. req->last_time = now;
  9450. req->retries++;
  9451. }
  9452. break;
  9453. case MG_EV_RECV:
  9454. msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
  9455. if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
  9456. msg->num_answers > 0) {
  9457. req->callback(msg, req->data, MG_RESOLVE_OK);
  9458. nc->user_data = NULL;
  9459. MG_FREE(req);
  9460. } else {
  9461. req->err = MG_RESOLVE_NO_ANSWERS;
  9462. }
  9463. MG_FREE(msg);
  9464. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9465. break;
  9466. case MG_EV_SEND:
  9467. /*
  9468. * If a send error occurs, prevent closing of the connection by the core.
  9469. * We will retry after timeout.
  9470. */
  9471. nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
  9472. mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
  9473. break;
  9474. case MG_EV_TIMER:
  9475. req->err = MG_RESOLVE_TIMEOUT;
  9476. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9477. break;
  9478. case MG_EV_CLOSE:
  9479. /* If we got here with request still not done, fire an error callback. */
  9480. if (req != NULL) {
  9481. req->callback(NULL, req->data, req->err);
  9482. nc->user_data = NULL;
  9483. MG_FREE(req);
  9484. }
  9485. break;
  9486. }
  9487. }
  9488. int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
  9489. mg_resolve_callback_t cb, void *data) {
  9490. struct mg_resolve_async_opts opts;
  9491. memset(&opts, 0, sizeof(opts));
  9492. return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
  9493. }
  9494. int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
  9495. mg_resolve_callback_t cb, void *data,
  9496. struct mg_resolve_async_opts opts) {
  9497. struct mg_resolve_async_request *req;
  9498. struct mg_connection *dns_nc;
  9499. const char *nameserver = opts.nameserver_url;
  9500. DBG(("%s %d %p", name, query, opts.dns_conn));
  9501. /* resolve with DNS */
  9502. req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
  9503. if (req == NULL) {
  9504. return -1;
  9505. }
  9506. strncpy(req->name, name, sizeof(req->name));
  9507. req->query = query;
  9508. req->callback = cb;
  9509. req->data = data;
  9510. /* TODO(mkm): parse defaults out of resolve.conf */
  9511. req->max_retries = opts.max_retries ? opts.max_retries : 2;
  9512. req->timeout = opts.timeout ? opts.timeout : 5;
  9513. /* Lazily initialize dns server */
  9514. if (nameserver == NULL && mg_dns_server[0] == '\0' &&
  9515. mg_get_ip_address_of_nameserver(mg_dns_server, sizeof(mg_dns_server)) ==
  9516. -1) {
  9517. strncpy(mg_dns_server, mg_default_dns_server, sizeof(mg_dns_server));
  9518. }
  9519. if (nameserver == NULL) {
  9520. nameserver = mg_dns_server;
  9521. }
  9522. dns_nc = mg_connect(mgr, nameserver, mg_resolve_async_eh);
  9523. if (dns_nc == NULL) {
  9524. MG_FREE(req);
  9525. return -1;
  9526. }
  9527. dns_nc->user_data = req;
  9528. if (opts.dns_conn != NULL) {
  9529. *opts.dns_conn = dns_nc;
  9530. }
  9531. return 0;
  9532. }
  9533. #endif /* MG_ENABLE_ASYNC_RESOLVER */
  9534. #ifdef MG_MODULE_LINES
  9535. #line 1 "mongoose/src/coap.c"
  9536. #endif
  9537. /*
  9538. * Copyright (c) 2015 Cesanta Software Limited
  9539. * All rights reserved
  9540. * This software is dual-licensed: you can redistribute it and/or modify
  9541. * it under the terms of the GNU General Public License version 2 as
  9542. * published by the Free Software Foundation. For the terms of this
  9543. * license, see <http://www.gnu.org/licenses/>.
  9544. *
  9545. * You are free to use this software under the terms of the GNU General
  9546. * Public License, but WITHOUT ANY WARRANTY; without even the implied
  9547. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9548. * See the GNU General Public License for more details.
  9549. *
  9550. * Alternatively, you can license this software under a commercial
  9551. * license, as set out in <https://www.cesanta.com/license>.
  9552. */
  9553. /* Amalgamated: #include "mongoose/src/internal.h" */
  9554. /* Amalgamated: #include "mongoose/src/coap.h" */
  9555. #if MG_ENABLE_COAP
  9556. void mg_coap_free_options(struct mg_coap_message *cm) {
  9557. while (cm->options != NULL) {
  9558. struct mg_coap_option *next = cm->options->next;
  9559. MG_FREE(cm->options);
  9560. cm->options = next;
  9561. }
  9562. }
  9563. struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
  9564. uint32_t number, char *value,
  9565. size_t len) {
  9566. struct mg_coap_option *new_option =
  9567. (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
  9568. new_option->number = number;
  9569. new_option->value.p = value;
  9570. new_option->value.len = len;
  9571. if (cm->options == NULL) {
  9572. cm->options = cm->optiomg_tail = new_option;
  9573. } else {
  9574. /*
  9575. * A very simple attention to help clients to compose options:
  9576. * CoAP wants to see options ASC ordered.
  9577. * Could be change by using sort in coap_compose
  9578. */
  9579. if (cm->optiomg_tail->number <= new_option->number) {
  9580. /* if option is already ordered just add it */
  9581. cm->optiomg_tail = cm->optiomg_tail->next = new_option;
  9582. } else {
  9583. /* looking for appropriate position */
  9584. struct mg_coap_option *current_opt = cm->options;
  9585. struct mg_coap_option *prev_opt = 0;
  9586. while (current_opt != NULL) {
  9587. if (current_opt->number > new_option->number) {
  9588. break;
  9589. }
  9590. prev_opt = current_opt;
  9591. current_opt = current_opt->next;
  9592. }
  9593. if (prev_opt != NULL) {
  9594. prev_opt->next = new_option;
  9595. new_option->next = current_opt;
  9596. } else {
  9597. /* insert new_option to the beginning */
  9598. new_option->next = cm->options;
  9599. cm->options = new_option;
  9600. }
  9601. }
  9602. }
  9603. return new_option;
  9604. }
  9605. /*
  9606. * Fills CoAP header in mg_coap_message.
  9607. *
  9608. * Helper function.
  9609. */
  9610. static char *coap_parse_header(char *ptr, struct mbuf *io,
  9611. struct mg_coap_message *cm) {
  9612. if (io->len < sizeof(uint32_t)) {
  9613. cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
  9614. return NULL;
  9615. }
  9616. /*
  9617. * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version
  9618. * number. Implementations of this specification MUST set this field
  9619. * to 1 (01 binary). Other values are reserved for future versions.
  9620. * Messages with unknown version numbers MUST be silently ignored.
  9621. */
  9622. if (((uint8_t) *ptr >> 6) != 1) {
  9623. cm->flags |= MG_COAP_IGNORE;
  9624. return NULL;
  9625. }
  9626. /*
  9627. * Type (T): 2-bit unsigned integer. Indicates if this message is of
  9628. * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
  9629. * Reset (3).
  9630. */
  9631. cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
  9632. cm->flags |= MG_COAP_MSG_TYPE_FIELD;
  9633. /*
  9634. * Token Length (TKL): 4-bit unsigned integer. Indicates the length of
  9635. * the variable-length Token field (0-8 bytes). Lengths 9-15 are
  9636. * reserved, MUST NOT be sent, and MUST be processed as a message
  9637. * format error.
  9638. */
  9639. cm->token.len = *ptr & 0x0F;
  9640. if (cm->token.len > 8) {
  9641. cm->flags |= MG_COAP_FORMAT_ERROR;
  9642. return NULL;
  9643. }
  9644. ptr++;
  9645. /*
  9646. * Code: 8-bit unsigned integer, split into a 3-bit class (most
  9647. * significant bits) and a 5-bit detail (least significant bits)
  9648. */
  9649. cm->code_class = (uint8_t) *ptr >> 5;
  9650. cm->code_detail = *ptr & 0x1F;
  9651. cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
  9652. ptr++;
  9653. /* Message ID: 16-bit unsigned integer in network byte order. */
  9654. cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
  9655. cm->flags |= MG_COAP_MSG_ID_FIELD;
  9656. ptr += 2;
  9657. return ptr;
  9658. }
  9659. /*
  9660. * Fills token information in mg_coap_message.
  9661. *
  9662. * Helper function.
  9663. */
  9664. static char *coap_get_token(char *ptr, struct mbuf *io,
  9665. struct mg_coap_message *cm) {
  9666. if (cm->token.len != 0) {
  9667. if (ptr + cm->token.len > io->buf + io->len) {
  9668. cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
  9669. return NULL;
  9670. } else {
  9671. cm->token.p = ptr;
  9672. ptr += cm->token.len;
  9673. cm->flags |= MG_COAP_TOKEN_FIELD;
  9674. }
  9675. }
  9676. return ptr;
  9677. }
  9678. /*
  9679. * Returns Option Delta or Length.
  9680. *
  9681. * Helper function.
  9682. */
  9683. static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
  9684. int ret = 0;
  9685. if (*opt_info == 13) {
  9686. /*
  9687. * 13: An 8-bit unsigned integer follows the initial byte and
  9688. * indicates the Option Delta/Length minus 13.
  9689. */
  9690. if (ptr < io->buf + io->len) {
  9691. *opt_info = (uint8_t) *ptr + 13;
  9692. ret = sizeof(uint8_t);
  9693. } else {
  9694. ret = -1; /* LCOV_EXCL_LINE */
  9695. }
  9696. } else if (*opt_info == 14) {
  9697. /*
  9698. * 14: A 16-bit unsigned integer in network byte order follows the
  9699. * initial byte and indicates the Option Delta/Length minus 269.
  9700. */
  9701. if (ptr + sizeof(uint8_t) < io->buf + io->len) {
  9702. *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
  9703. ret = sizeof(uint16_t);
  9704. } else {
  9705. ret = -1; /* LCOV_EXCL_LINE */
  9706. }
  9707. }
  9708. return ret;
  9709. }
  9710. /*
  9711. * Fills options in mg_coap_message.
  9712. *
  9713. * Helper function.
  9714. *
  9715. * General options format:
  9716. * +---------------+---------------+
  9717. * | Option Delta | Option Length | 1 byte
  9718. * +---------------+---------------+
  9719. * \ Option Delta (extended) \ 0-2 bytes
  9720. * +-------------------------------+
  9721. * / Option Length (extended) \ 0-2 bytes
  9722. * +-------------------------------+
  9723. * \ Option Value \ 0 or more bytes
  9724. * +-------------------------------+
  9725. */
  9726. static char *coap_get_options(char *ptr, struct mbuf *io,
  9727. struct mg_coap_message *cm) {
  9728. uint16_t prev_opt = 0;
  9729. if (ptr == io->buf + io->len) {
  9730. /* end of packet, ok */
  9731. return NULL;
  9732. }
  9733. /* 0xFF is payload marker */
  9734. while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
  9735. uint16_t option_delta, option_lenght;
  9736. int optinfo_len;
  9737. /* Option Delta: 4-bit unsigned integer */
  9738. option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
  9739. /* Option Length: 4-bit unsigned integer */
  9740. option_lenght = *ptr & 0x0F;
  9741. if (option_delta == 15 || option_lenght == 15) {
  9742. /*
  9743. * 15: Reserved for future use. If the field is set to this value,
  9744. * it MUST be processed as a message format error
  9745. */
  9746. cm->flags |= MG_COAP_FORMAT_ERROR;
  9747. break;
  9748. }
  9749. ptr++;
  9750. /* check for extended option delta */
  9751. optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
  9752. if (optinfo_len == -1) {
  9753. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  9754. break; /* LCOV_EXCL_LINE */
  9755. }
  9756. ptr += optinfo_len;
  9757. /* check or extended option lenght */
  9758. optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
  9759. if (optinfo_len == -1) {
  9760. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  9761. break; /* LCOV_EXCL_LINE */
  9762. }
  9763. ptr += optinfo_len;
  9764. /*
  9765. * Instead of specifying the Option Number directly, the instances MUST
  9766. * appear in order of their Option Numbers and a delta encoding is used
  9767. * between them.
  9768. */
  9769. option_delta += prev_opt;
  9770. mg_coap_add_option(cm, option_delta, ptr, option_lenght);
  9771. prev_opt = option_delta;
  9772. if (ptr + option_lenght > io->buf + io->len) {
  9773. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  9774. break; /* LCOV_EXCL_LINE */
  9775. }
  9776. ptr += option_lenght;
  9777. }
  9778. if ((cm->flags & MG_COAP_ERROR) != 0) {
  9779. mg_coap_free_options(cm);
  9780. return NULL;
  9781. }
  9782. cm->flags |= MG_COAP_OPTIOMG_FIELD;
  9783. if (ptr == io->buf + io->len) {
  9784. /* end of packet, ok */
  9785. return NULL;
  9786. }
  9787. ptr++;
  9788. return ptr;
  9789. }
  9790. uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
  9791. char *ptr;
  9792. memset(cm, 0, sizeof(*cm));
  9793. if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
  9794. return cm->flags;
  9795. }
  9796. if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
  9797. return cm->flags;
  9798. }
  9799. if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
  9800. return cm->flags;
  9801. }
  9802. /* the rest is payload */
  9803. cm->payload.len = io->len - (ptr - io->buf);
  9804. if (cm->payload.len != 0) {
  9805. cm->payload.p = ptr;
  9806. cm->flags |= MG_COAP_PAYLOAD_FIELD;
  9807. }
  9808. return cm->flags;
  9809. }
  9810. /*
  9811. * Calculates extended size of given Opt Number/Length in coap message.
  9812. *
  9813. * Helper function.
  9814. */
  9815. static size_t coap_get_ext_opt_size(uint32_t value) {
  9816. int ret = 0;
  9817. if (value >= 13 && value <= 0xFF + 13) {
  9818. ret = sizeof(uint8_t);
  9819. } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
  9820. ret = sizeof(uint16_t);
  9821. }
  9822. return ret;
  9823. }
  9824. /*
  9825. * Splits given Opt Number/Length into base and ext values.
  9826. *
  9827. * Helper function.
  9828. */
  9829. static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
  9830. int ret = 0;
  9831. if (value < 13) {
  9832. *base = value;
  9833. } else if (value >= 13 && value <= 0xFF + 13) {
  9834. *base = 13;
  9835. *ext = value - 13;
  9836. ret = sizeof(uint8_t);
  9837. } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
  9838. *base = 14;
  9839. *ext = value - 269;
  9840. ret = sizeof(uint16_t);
  9841. }
  9842. return ret;
  9843. }
  9844. /*
  9845. * Puts uint16_t (in network order) into given char stream.
  9846. *
  9847. * Helper function.
  9848. */
  9849. static char *coap_add_uint16(char *ptr, uint16_t val) {
  9850. *ptr = val >> 8;
  9851. ptr++;
  9852. *ptr = val & 0x00FF;
  9853. ptr++;
  9854. return ptr;
  9855. }
  9856. /*
  9857. * Puts extended value of Opt Number/Length into given char stream.
  9858. *
  9859. * Helper function.
  9860. */
  9861. static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
  9862. if (len == sizeof(uint8_t)) {
  9863. *ptr = (char) val;
  9864. ptr++;
  9865. } else if (len == sizeof(uint16_t)) {
  9866. ptr = coap_add_uint16(ptr, val);
  9867. }
  9868. return ptr;
  9869. }
  9870. /*
  9871. * Verifies given mg_coap_message and calculates message size for it.
  9872. *
  9873. * Helper function.
  9874. */
  9875. static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
  9876. size_t *len) {
  9877. struct mg_coap_option *opt;
  9878. uint32_t prev_opt_number;
  9879. *len = 4; /* header */
  9880. if (cm->msg_type > MG_COAP_MSG_MAX) {
  9881. return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
  9882. }
  9883. if (cm->token.len > 8) {
  9884. return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
  9885. }
  9886. if (cm->code_class > 7) {
  9887. return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
  9888. }
  9889. if (cm->code_detail > 31) {
  9890. return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
  9891. }
  9892. *len += cm->token.len;
  9893. if (cm->payload.len != 0) {
  9894. *len += cm->payload.len + 1; /* ... + 1; add payload marker */
  9895. }
  9896. opt = cm->options;
  9897. prev_opt_number = 0;
  9898. while (opt != NULL) {
  9899. *len += 1; /* basic delta/length */
  9900. *len += coap_get_ext_opt_size(opt->number - prev_opt_number);
  9901. *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
  9902. /*
  9903. * Current implementation performs check if
  9904. * option_number > previous option_number and produces an error
  9905. * TODO(alashkin): write design doc with limitations
  9906. * May be resorting is more suitable solution.
  9907. */
  9908. if ((opt->next != NULL && opt->number > opt->next->number) ||
  9909. opt->value.len > 0xFFFF + 269 ||
  9910. opt->number - prev_opt_number > 0xFFFF + 269) {
  9911. return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
  9912. }
  9913. *len += opt->value.len;
  9914. prev_opt_number = opt->number;
  9915. opt = opt->next;
  9916. }
  9917. return 0;
  9918. }
  9919. uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
  9920. struct mg_coap_option *opt;
  9921. uint32_t res, prev_opt_number;
  9922. size_t prev_io_len, packet_size;
  9923. char *ptr;
  9924. res = coap_calculate_packet_size(cm, &packet_size);
  9925. if (res != 0) {
  9926. return res;
  9927. }
  9928. /* saving previous lenght to handle non-empty mbuf */
  9929. prev_io_len = io->len;
  9930. mbuf_append(io, NULL, packet_size);
  9931. ptr = io->buf + prev_io_len;
  9932. /*
  9933. * since cm is verified, it is possible to use bits shift operator
  9934. * without additional zeroing of unused bits
  9935. */
  9936. /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
  9937. *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
  9938. ptr++;
  9939. /* code class: 3 bits, code detail: 5 bits */
  9940. *ptr = (cm->code_class << 5) | (cm->code_detail);
  9941. ptr++;
  9942. ptr = coap_add_uint16(ptr, cm->msg_id);
  9943. if (cm->token.len != 0) {
  9944. memcpy(ptr, cm->token.p, cm->token.len);
  9945. ptr += cm->token.len;
  9946. }
  9947. opt = cm->options;
  9948. prev_opt_number = 0;
  9949. while (opt != NULL) {
  9950. uint8_t delta_base = 0, length_base = 0;
  9951. uint16_t delta_ext = 0, length_ext = 0;
  9952. size_t opt_delta_len =
  9953. coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
  9954. size_t opt_lenght_len =
  9955. coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
  9956. *ptr = (delta_base << 4) | length_base;
  9957. ptr++;
  9958. ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
  9959. ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
  9960. if (opt->value.len != 0) {
  9961. memcpy(ptr, opt->value.p, opt->value.len);
  9962. ptr += opt->value.len;
  9963. }
  9964. prev_opt_number = opt->number;
  9965. opt = opt->next;
  9966. }
  9967. if (cm->payload.len != 0) {
  9968. *ptr = (char) -1;
  9969. ptr++;
  9970. memcpy(ptr, cm->payload.p, cm->payload.len);
  9971. }
  9972. return 0;
  9973. }
  9974. uint32_t mg_coap_send_message(struct mg_connection *nc,
  9975. struct mg_coap_message *cm) {
  9976. struct mbuf packet_out;
  9977. uint32_t compose_res;
  9978. mbuf_init(&packet_out, 0);
  9979. compose_res = mg_coap_compose(cm, &packet_out);
  9980. if (compose_res != 0) {
  9981. return compose_res; /* LCOV_EXCL_LINE */
  9982. }
  9983. mg_send(nc, packet_out.buf, (int) packet_out.len);
  9984. mbuf_free(&packet_out);
  9985. return 0;
  9986. }
  9987. uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
  9988. struct mg_coap_message cm;
  9989. memset(&cm, 0, sizeof(cm));
  9990. cm.msg_type = MG_COAP_MSG_ACK;
  9991. cm.msg_id = msg_id;
  9992. return mg_coap_send_message(nc, &cm);
  9993. }
  9994. static void coap_handler(struct mg_connection *nc, int ev, void *ev_data) {
  9995. struct mbuf *io = &nc->recv_mbuf;
  9996. struct mg_coap_message cm;
  9997. uint32_t parse_res;
  9998. memset(&cm, 0, sizeof(cm));
  9999. nc->handler(nc, ev, ev_data);
  10000. switch (ev) {
  10001. case MG_EV_RECV:
  10002. parse_res = mg_coap_parse(io, &cm);
  10003. if ((parse_res & MG_COAP_IGNORE) == 0) {
  10004. if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
  10005. /*
  10006. * Since we support UDP only
  10007. * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
  10008. */
  10009. cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
  10010. } /* LCOV_EXCL_LINE */
  10011. nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm);
  10012. }
  10013. mg_coap_free_options(&cm);
  10014. mbuf_remove(io, io->len);
  10015. break;
  10016. }
  10017. }
  10018. /*
  10019. * Attach built-in CoAP event handler to the given connection.
  10020. *
  10021. * The user-defined event handler will receive following extra events:
  10022. *
  10023. * - MG_EV_COAP_CON
  10024. * - MG_EV_COAP_NOC
  10025. * - MG_EV_COAP_ACK
  10026. * - MG_EV_COAP_RST
  10027. */
  10028. int mg_set_protocol_coap(struct mg_connection *nc) {
  10029. /* supports UDP only */
  10030. if ((nc->flags & MG_F_UDP) == 0) {
  10031. return -1;
  10032. }
  10033. nc->proto_handler = coap_handler;
  10034. return 0;
  10035. }
  10036. #endif /* MG_ENABLE_COAP */
  10037. #ifdef MG_MODULE_LINES
  10038. #line 1 "mongoose/src/tun.c"
  10039. #endif
  10040. /*
  10041. * Copyright (c) 2014 Cesanta Software Limited
  10042. * All rights reserved
  10043. */
  10044. #if MG_ENABLE_TUN
  10045. /* Amalgamated: #include "common/cs_dbg.h" */
  10046. /* Amalgamated: #include "mongoose/src/http.h" */
  10047. /* Amalgamated: #include "mongoose/src/internal.h" */
  10048. /* Amalgamated: #include "mongoose/src/net.h" */
  10049. /* Amalgamated: #include "mongoose/src/net_if_tun.h" */
  10050. /* Amalgamated: #include "mongoose/src/tun.h" */
  10051. /* Amalgamated: #include "mongoose/src/util.h" */
  10052. static void mg_tun_reconnect(struct mg_tun_client *client, int timeout);
  10053. static void mg_tun_init_client(struct mg_tun_client *client, struct mg_mgr *mgr,
  10054. struct mg_iface *iface, const char *dispatcher,
  10055. struct mg_tun_ssl_opts ssl) {
  10056. client->mgr = mgr;
  10057. client->iface = iface;
  10058. client->disp_url = dispatcher;
  10059. client->last_stream_id = 0;
  10060. client->ssl = ssl;
  10061. client->disp = NULL; /* will be set by mg_tun_reconnect */
  10062. client->listener = NULL; /* will be set by mg_do_bind */
  10063. client->reconnect = NULL; /* will be set by mg_tun_reconnect */
  10064. }
  10065. void mg_tun_log_frame(struct mg_tun_frame *frame) {
  10066. LOG(LL_DEBUG, ("Got TUN frame: type=0x%x, flags=0x%x stream_id=0x%lx, "
  10067. "len=%zu",
  10068. frame->type, frame->flags, frame->stream_id, frame->body.len));
  10069. #if MG_ENABLE_HEXDUMP
  10070. {
  10071. char hex[512];
  10072. mg_hexdump(frame->body.p, frame->body.len, hex, sizeof(hex) - 1);
  10073. hex[sizeof(hex) - 1] = '\0';
  10074. LOG(LL_DEBUG, ("body:\n%s", hex));
  10075. }
  10076. #else
  10077. LOG(LL_DEBUG, ("body: '%.*s'", (int) frame->body.len, frame->body.p));
  10078. #endif
  10079. }
  10080. static void mg_tun_close_all(struct mg_tun_client *client) {
  10081. struct mg_connection *nc;
  10082. for (nc = client->mgr->active_connections; nc != NULL; nc = nc->next) {
  10083. if (nc->iface == client->iface && !(nc->flags & MG_F_LISTENING)) {
  10084. LOG(LL_DEBUG, ("Closing tunneled connection %p", nc));
  10085. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10086. /* mg_close_conn(nc); */
  10087. }
  10088. }
  10089. }
  10090. static void mg_tun_client_handler(struct mg_connection *nc, int ev,
  10091. void *ev_data) {
  10092. struct mg_tun_client *client = (struct mg_tun_client *) nc->user_data;
  10093. switch (ev) {
  10094. case MG_EV_CONNECT: {
  10095. int err = *(int *) ev_data;
  10096. if (err) {
  10097. LOG(LL_ERROR, ("Cannot connect to the tunnel dispatcher: %d", err));
  10098. } else {
  10099. LOG(LL_INFO, ("Connected to the tunnel dispatcher"));
  10100. }
  10101. break;
  10102. }
  10103. case MG_EV_HTTP_REPLY: {
  10104. struct http_message *hm = (struct http_message *) ev_data;
  10105. if (hm->resp_code != 200) {
  10106. LOG(LL_ERROR,
  10107. ("Tunnel dispatcher reply non-OK status code %d", hm->resp_code));
  10108. }
  10109. break;
  10110. }
  10111. case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
  10112. LOG(LL_INFO, ("Tunnel dispatcher handshake done"));
  10113. break;
  10114. }
  10115. case MG_EV_WEBSOCKET_FRAME: {
  10116. struct websocket_message *wm = (struct websocket_message *) ev_data;
  10117. struct mg_connection *tc;
  10118. struct mg_tun_frame frame;
  10119. if (mg_tun_parse_frame(wm->data, wm->size, &frame) == -1) {
  10120. LOG(LL_ERROR, ("Got invalid tun frame dropping", wm->size));
  10121. break;
  10122. }
  10123. mg_tun_log_frame(&frame);
  10124. tc = mg_tun_if_find_conn(client, frame.stream_id);
  10125. if (tc == NULL) {
  10126. if (frame.body.len > 0) {
  10127. LOG(LL_DEBUG, ("Got frame after receiving end has been closed"));
  10128. }
  10129. break;
  10130. }
  10131. if (frame.body.len > 0) {
  10132. mg_if_recv_tcp_cb(tc, (void *) frame.body.p, frame.body.len,
  10133. 0 /* own */);
  10134. }
  10135. if (frame.flags & MG_TUN_F_END_STREAM) {
  10136. LOG(LL_DEBUG, ("Closing tunneled connection because got end of stream "
  10137. "from other end"));
  10138. tc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10139. mg_close_conn(tc);
  10140. }
  10141. break;
  10142. }
  10143. case MG_EV_CLOSE: {
  10144. LOG(LL_DEBUG, ("Closing all tunneled connections"));
  10145. /*
  10146. * The client might have been already freed when the listening socket is
  10147. * closed.
  10148. */
  10149. if (client != NULL) {
  10150. mg_tun_close_all(client);
  10151. client->disp = NULL;
  10152. LOG(LL_INFO, ("Dispatcher connection is no more, reconnecting"));
  10153. /* TODO(mkm): implement exp back off */
  10154. mg_tun_reconnect(client, MG_TUN_RECONNECT_INTERVAL);
  10155. }
  10156. break;
  10157. }
  10158. default:
  10159. break;
  10160. }
  10161. }
  10162. static void mg_tun_do_reconnect(struct mg_tun_client *client) {
  10163. struct mg_connection *dc;
  10164. struct mg_connect_opts opts;
  10165. memset(&opts, 0, sizeof(opts));
  10166. #if MG_ENABLE_SSL
  10167. opts.ssl_cert = client->ssl.ssl_cert;
  10168. opts.ssl_key = client->ssl.ssl_key;
  10169. opts.ssl_ca_cert = client->ssl.ssl_ca_cert;
  10170. #endif
  10171. /* HTTP/Websocket listener */
  10172. if ((dc = mg_connect_ws_opt(client->mgr, mg_tun_client_handler, opts,
  10173. client->disp_url, MG_TUN_PROTO_NAME, NULL)) ==
  10174. NULL) {
  10175. LOG(LL_ERROR,
  10176. ("Cannot connect to WS server on addr [%s]\n", client->disp_url));
  10177. return;
  10178. }
  10179. client->disp = dc;
  10180. dc->user_data = client;
  10181. }
  10182. void mg_tun_reconnect_ev_handler(struct mg_connection *nc, int ev,
  10183. void *ev_data) {
  10184. struct mg_tun_client *client = (struct mg_tun_client *) nc->user_data;
  10185. (void) ev_data;
  10186. switch (ev) {
  10187. case MG_EV_TIMER:
  10188. if (!(client->listener->flags & MG_F_TUN_DO_NOT_RECONNECT)) {
  10189. mg_tun_do_reconnect(client);
  10190. } else {
  10191. /* Reconnecting is suppressed, we'll check again at the next poll */
  10192. mg_tun_reconnect(client, 0);
  10193. }
  10194. break;
  10195. }
  10196. }
  10197. static void mg_tun_reconnect(struct mg_tun_client *client, int timeout) {
  10198. if (client->reconnect == NULL) {
  10199. client->reconnect =
  10200. mg_add_sock(client->mgr, INVALID_SOCKET, mg_tun_reconnect_ev_handler);
  10201. client->reconnect->user_data = client;
  10202. }
  10203. client->reconnect->ev_timer_time = mg_time() + timeout;
  10204. }
  10205. static struct mg_tun_client *mg_tun_create_client(struct mg_mgr *mgr,
  10206. const char *dispatcher,
  10207. struct mg_tun_ssl_opts ssl) {
  10208. struct mg_tun_client *client = NULL;
  10209. struct mg_iface *iface = mg_find_iface(mgr, &mg_tun_iface_vtable, NULL);
  10210. if (iface == NULL) {
  10211. LOG(LL_ERROR, ("The tun feature requires the manager to have a tun "
  10212. "interface enabled"));
  10213. return NULL;
  10214. }
  10215. client = (struct mg_tun_client *) MG_MALLOC(sizeof(*client));
  10216. mg_tun_init_client(client, mgr, iface, dispatcher, ssl);
  10217. iface->data = client;
  10218. /*
  10219. * We need to give application a chance to set MG_F_TUN_DO_NOT_RECONNECT on a
  10220. * listening connection right after mg_tun_bind_opt() returned it, so we
  10221. * should use mg_tun_reconnect() here, instead of mg_tun_do_reconnect()
  10222. */
  10223. mg_tun_reconnect(client, 0);
  10224. return client;
  10225. }
  10226. void mg_tun_destroy_client(struct mg_tun_client *client) {
  10227. /*
  10228. * NOTE:
  10229. * `client` is NULL in case of OOM
  10230. * `client->disp` is NULL if connection failed
  10231. * `client->iface is NULL is `mg_find_iface` failed
  10232. */
  10233. if (client != NULL && client->disp != NULL) {
  10234. /* the dispatcher connection handler will in turn close all tunnels */
  10235. client->disp->flags |= MG_F_CLOSE_IMMEDIATELY;
  10236. /* this is used as a signal to other tun handlers that the party is over */
  10237. client->disp->user_data = NULL;
  10238. }
  10239. if (client != NULL && client->reconnect != NULL) {
  10240. client->reconnect->flags |= MG_F_CLOSE_IMMEDIATELY;
  10241. }
  10242. if (client != NULL && client->iface != NULL) {
  10243. client->iface->data = NULL;
  10244. }
  10245. MG_FREE(client);
  10246. }
  10247. static struct mg_connection *mg_tun_do_bind(struct mg_tun_client *client,
  10248. mg_event_handler_t handler,
  10249. struct mg_bind_opts opts) {
  10250. struct mg_connection *lc;
  10251. opts.iface = client->iface;
  10252. lc = mg_bind_opt(client->mgr, ":1234" /* dummy port */, handler, opts);
  10253. client->listener = lc;
  10254. return lc;
  10255. }
  10256. struct mg_connection *mg_tun_bind_opt(struct mg_mgr *mgr,
  10257. const char *dispatcher,
  10258. mg_event_handler_t handler,
  10259. struct mg_bind_opts opts) {
  10260. #if MG_ENABLE_SSL
  10261. struct mg_tun_ssl_opts ssl = {opts.ssl_cert, opts.ssl_key, opts.ssl_ca_cert};
  10262. #else
  10263. struct mg_tun_ssl_opts ssl = {0};
  10264. #endif
  10265. struct mg_tun_client *client = mg_tun_create_client(mgr, dispatcher, ssl);
  10266. if (client == NULL) {
  10267. return NULL;
  10268. }
  10269. #if MG_ENABLE_SSL
  10270. /* these options don't make sense in the local mouth of the tunnel */
  10271. opts.ssl_cert = NULL;
  10272. opts.ssl_key = NULL;
  10273. opts.ssl_ca_cert = NULL;
  10274. #endif
  10275. return mg_tun_do_bind(client, handler, opts);
  10276. }
  10277. int mg_tun_parse_frame(void *data, size_t len, struct mg_tun_frame *frame) {
  10278. const size_t header_size = sizeof(uint32_t) + sizeof(uint8_t) * 2;
  10279. if (len < header_size) {
  10280. return -1;
  10281. }
  10282. frame->type = *(uint8_t *) (data);
  10283. frame->flags = *(uint8_t *) ((char *) data + 1);
  10284. memcpy(&frame->stream_id, (char *) data + 2, sizeof(uint32_t));
  10285. frame->stream_id = ntohl(frame->stream_id);
  10286. frame->body.p = (char *) data + header_size;
  10287. frame->body.len = len - header_size;
  10288. return 0;
  10289. }
  10290. void mg_tun_send_frame(struct mg_connection *ws, uint32_t stream_id,
  10291. uint8_t type, uint8_t flags, struct mg_str msg) {
  10292. stream_id = htonl(stream_id);
  10293. {
  10294. struct mg_str parts[] = {
  10295. {(char *) &type, sizeof(type)},
  10296. {(char *) &flags, sizeof(flags)},
  10297. {(char *) &stream_id, sizeof(stream_id)},
  10298. {msg.p, msg.len} /* vc6 doesn't like just `msg` here */};
  10299. mg_send_websocket_framev(ws, WEBSOCKET_OP_BINARY, parts,
  10300. sizeof(parts) / sizeof(parts[0]));
  10301. }
  10302. }
  10303. #endif /* MG_ENABLE_TUN */
  10304. #ifdef MG_MODULE_LINES
  10305. #line 1 "mongoose/src/sntp.c"
  10306. #endif
  10307. /*
  10308. * Copyright (c) 2016 Cesanta Software Limited
  10309. * All rights reserved
  10310. */
  10311. /* Amalgamated: #include "mongoose/src/internal.h" */
  10312. /* Amalgamated: #include "mongoose/src/sntp.h" */
  10313. /* Amalgamated: #include "mongoose/src/util.h" */
  10314. #if MG_ENABLE_SNTP
  10315. #define SNTP_TIME_OFFSET 2208988800
  10316. #ifndef SNTP_TIMEOUT
  10317. #define SNTP_TIMEOUT 10
  10318. #endif
  10319. #ifndef SNTP_ATTEMPTS
  10320. #define SNTP_ATTEMPTS 3
  10321. #endif
  10322. static uint64_t mg_get_sec(uint64_t val) {
  10323. return (val & 0xFFFFFFFF00000000) >> 32;
  10324. }
  10325. static uint64_t mg_get_usec(uint64_t val) {
  10326. uint64_t tmp = (val & 0x00000000FFFFFFFF);
  10327. tmp *= 1000000;
  10328. tmp >>= 32;
  10329. return tmp;
  10330. }
  10331. static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
  10332. uint64_t tmp;
  10333. tmp = mg_get_sec(val);
  10334. tmp -= SNTP_TIME_OFFSET;
  10335. tv->tv_sec = tmp;
  10336. tv->tv_usec = mg_get_usec(val);
  10337. }
  10338. static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
  10339. uint32_t tmp;
  10340. memcpy(&tmp, ntp, sizeof(tmp));
  10341. tmp = ntohl(tmp);
  10342. *val = (uint64_t) tmp << 32;
  10343. memcpy(&tmp, ntp + 4, sizeof(tmp));
  10344. tmp = ntohl(tmp);
  10345. *val |= tmp;
  10346. }
  10347. void mg_sntp_send_request(struct mg_connection *c) {
  10348. char buf[48] = {0};
  10349. /*
  10350. * header - 8 bit:
  10351. * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
  10352. * mode (3 bit) - 3 (client)
  10353. */
  10354. buf[0] = (3 << 6) | (4 << 3) | 3;
  10355. /*
  10356. * Next fields should be empty in client request
  10357. * stratum, 8 bit
  10358. * poll interval, 8 bit
  10359. * rrecision, 8 bit
  10360. * root delay, 32 bit
  10361. * root dispersion, 32 bit
  10362. * ref id, 32 bit
  10363. * ref timestamp, 64 bit
  10364. * originate Timestamp, 64 bit
  10365. * receive Timestamp, 64 bit
  10366. */
  10367. /*
  10368. * convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
  10369. * according to rfc868 it is 2208988800L sec
  10370. * this information is used to correct roundtrip delay
  10371. * but if local clock is absolutely broken (and doesn't work even
  10372. * as simple timer), it is better to disable it
  10373. */
  10374. #ifndef MG_SNMP_NO_DELAY_CORRECTION
  10375. uint32_t sec;
  10376. sec = htonl(mg_time() + SNTP_TIME_OFFSET);
  10377. memcpy(&buf[40], &sec, sizeof(sec));
  10378. #endif
  10379. mg_send(c, buf, sizeof(buf));
  10380. }
  10381. #ifndef MG_SNMP_NO_DELAY_CORRECTION
  10382. static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
  10383. /* roundloop delay = (T4 - T1) - (T3 - T2) */
  10384. uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
  10385. (mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
  10386. uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
  10387. (mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
  10388. return (d1 > d2) ? d1 - d2 : 0;
  10389. }
  10390. #endif
  10391. MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
  10392. struct mg_sntp_message *msg) {
  10393. uint8_t hdr;
  10394. uint64_t orig_ts_T1, recv_ts_T2, trsm_ts_T3, delay = 0;
  10395. int mode;
  10396. struct timeval tv;
  10397. (void) orig_ts_T1;
  10398. (void) recv_ts_T2;
  10399. if (len < 48) {
  10400. return -1;
  10401. }
  10402. hdr = buf[0];
  10403. if ((hdr & 0x38) >> 3 != 4) {
  10404. /* Wrong version */
  10405. return -1;
  10406. }
  10407. mode = hdr & 0x7;
  10408. if (mode != 4 && mode != 5) {
  10409. /* Not a server reply */
  10410. return -1;
  10411. }
  10412. memset(msg, 0, sizeof(*msg));
  10413. msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
  10414. mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
  10415. #ifndef MG_SNMP_NO_DELAY_CORRECTION
  10416. mg_get_ntp_ts(&buf[24], &orig_ts_T1);
  10417. mg_get_ntp_ts(&buf[32], &recv_ts_T2);
  10418. delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
  10419. #endif
  10420. mg_ntp_to_tv(trsm_ts_T3, &tv);
  10421. msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
  10422. return 0;
  10423. }
  10424. static void mg_sntp_handler(struct mg_connection *c, int ev, void *ev_data) {
  10425. struct mbuf *io = &c->recv_mbuf;
  10426. struct mg_sntp_message msg;
  10427. c->handler(c, ev, ev_data);
  10428. switch (ev) {
  10429. case MG_EV_RECV: {
  10430. if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
  10431. DBG(("Invalid SNTP packet received (%d)", (int) io->len));
  10432. c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL);
  10433. } else {
  10434. c->handler(c, MG_SNTP_REPLY, (void *) &msg);
  10435. }
  10436. mbuf_remove(io, io->len);
  10437. break;
  10438. }
  10439. }
  10440. }
  10441. int mg_set_protocol_sntp(struct mg_connection *c) {
  10442. if ((c->flags & MG_F_UDP) == 0) {
  10443. return -1;
  10444. }
  10445. c->proto_handler = mg_sntp_handler;
  10446. return 0;
  10447. }
  10448. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
  10449. mg_event_handler_t event_handler,
  10450. const char *sntp_server_name) {
  10451. struct mg_connection *c = NULL;
  10452. char url[100], *p_url = url;
  10453. const char *proto = "", *port = "", *tmp;
  10454. /* If port is not specified, use default (123) */
  10455. tmp = strchr(sntp_server_name, ':');
  10456. if (tmp != NULL && *(tmp + 1) == '/') {
  10457. tmp = strchr(tmp + 1, ':');
  10458. }
  10459. if (tmp == NULL) {
  10460. port = ":123";
  10461. }
  10462. /* Add udp:// if needed */
  10463. if (strncmp(sntp_server_name, "udp://", 6) != 0) {
  10464. proto = "udp://";
  10465. }
  10466. mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
  10467. c = mg_connect(mgr, p_url, event_handler);
  10468. if (c == NULL) {
  10469. goto cleanup;
  10470. }
  10471. mg_set_protocol_sntp(c);
  10472. cleanup:
  10473. if (p_url != url) {
  10474. MG_FREE(p_url);
  10475. }
  10476. return c;
  10477. }
  10478. struct sntp_data {
  10479. mg_event_handler_t hander;
  10480. int count;
  10481. };
  10482. static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
  10483. void *ev_data) {
  10484. struct sntp_data *sd = (struct sntp_data *) c->user_data;
  10485. switch (ev) {
  10486. case MG_EV_CONNECT:
  10487. if (*(int *) ev_data != 0) {
  10488. mg_call(c, sd->hander, MG_SNTP_FAILED, NULL);
  10489. break;
  10490. }
  10491. /* fallthrough */
  10492. case MG_EV_TIMER:
  10493. if (sd->count <= SNTP_ATTEMPTS) {
  10494. mg_sntp_send_request(c);
  10495. mg_set_timer(c, mg_time() + 10);
  10496. sd->count++;
  10497. } else {
  10498. mg_call(c, sd->hander, MG_SNTP_FAILED, NULL);
  10499. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  10500. }
  10501. break;
  10502. case MG_SNTP_MALFORMED_REPLY:
  10503. mg_call(c, sd->hander, MG_SNTP_FAILED, NULL);
  10504. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  10505. break;
  10506. case MG_SNTP_REPLY:
  10507. mg_call(c, sd->hander, MG_SNTP_REPLY, ev_data);
  10508. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  10509. break;
  10510. case MG_EV_CLOSE:
  10511. MG_FREE(c->user_data);
  10512. c->user_data = NULL;
  10513. break;
  10514. }
  10515. }
  10516. struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
  10517. mg_event_handler_t event_handler,
  10518. const char *sntp_server_name) {
  10519. struct mg_connection *c;
  10520. struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
  10521. if (sd == NULL) {
  10522. return NULL;
  10523. }
  10524. c = mg_sntp_connect(mgr, mg_sntp_util_ev_handler, sntp_server_name);
  10525. if (c == NULL) {
  10526. MG_FREE(sd);
  10527. return NULL;
  10528. }
  10529. sd->hander = event_handler;
  10530. c->user_data = sd;
  10531. return c;
  10532. }
  10533. #endif /* MG_ENABLE_SNTP */
  10534. #ifdef MG_MODULE_LINES
  10535. #line 1 "common/platforms/cc3200/cc3200_libc.c"
  10536. #endif
  10537. /*
  10538. * Copyright (c) 2014-2016 Cesanta Software Limited
  10539. * All rights reserved
  10540. */
  10541. #if CS_PLATFORM == CS_P_CC3200
  10542. #include <stdio.h>
  10543. #include <string.h>
  10544. #ifndef __TI_COMPILER_VERSION__
  10545. #include <reent.h>
  10546. #include <sys/stat.h>
  10547. #include <sys/time.h>
  10548. #include <unistd.h>
  10549. #endif
  10550. #include <inc/hw_types.h>
  10551. #include <inc/hw_memmap.h>
  10552. #include <driverlib/prcm.h>
  10553. #include <driverlib/rom.h>
  10554. #include <driverlib/rom_map.h>
  10555. #include <driverlib/uart.h>
  10556. #include <driverlib/utils.h>
  10557. #define CONSOLE_UART UARTA0_BASE
  10558. #ifdef __TI_COMPILER_VERSION__
  10559. int asprintf(char **strp, const char *fmt, ...) {
  10560. va_list ap;
  10561. int len;
  10562. *strp = MG_MALLOC(BUFSIZ);
  10563. if (*strp == NULL) return -1;
  10564. va_start(ap, fmt);
  10565. len = vsnprintf(*strp, BUFSIZ, fmt, ap);
  10566. va_end(ap);
  10567. if (len > 0) {
  10568. *strp = MG_REALLOC(*strp, len + 1);
  10569. if (*strp == NULL) return -1;
  10570. }
  10571. if (len >= BUFSIZ) {
  10572. va_start(ap, fmt);
  10573. len = vsnprintf(*strp, len + 1, fmt, ap);
  10574. va_end(ap);
  10575. }
  10576. return len;
  10577. }
  10578. #if MG_TI_NO_HOST_INTERFACE
  10579. time_t HOSTtime() {
  10580. struct timeval tp;
  10581. gettimeofday(&tp, NULL);
  10582. return tp.tv_sec;
  10583. }
  10584. #endif
  10585. #endif /* __TI_COMPILER_VERSION__ */
  10586. #ifndef __TI_COMPILER_VERSION__
  10587. int _gettimeofday_r(struct _reent *r, struct timeval *tp, void *tzp) {
  10588. #else
  10589. int gettimeofday(struct timeval *tp, void *tzp) {
  10590. #endif
  10591. unsigned long long r1 = 0, r2;
  10592. /* Achieve two consecutive reads of the same value. */
  10593. do {
  10594. r2 = r1;
  10595. r1 = PRCMSlowClkCtrFastGet();
  10596. } while (r1 != r2);
  10597. /* This is a 32768 Hz counter. */
  10598. tp->tv_sec = (r1 >> 15);
  10599. /* 1/32768-th of a second is 30.517578125 microseconds, approx. 31,
  10600. * but we round down so it doesn't overflow at 32767 */
  10601. tp->tv_usec = (r1 & 0x7FFF) * 30;
  10602. return 0;
  10603. }
  10604. void fprint_str(FILE *fp, const char *str) {
  10605. while (*str != '\0') {
  10606. if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
  10607. MAP_UARTCharPut(CONSOLE_UART, *str++);
  10608. }
  10609. }
  10610. void _exit(int status) {
  10611. fprint_str(stderr, "_exit\n");
  10612. /* cause an unaligned access exception, that will drop you into gdb */
  10613. *(int *) 1 = status;
  10614. while (1)
  10615. ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
  10616. }
  10617. void _not_implemented(const char *what) {
  10618. fprint_str(stderr, what);
  10619. fprint_str(stderr, " is not implemented\n");
  10620. _exit(42);
  10621. }
  10622. int _kill(int pid, int sig) {
  10623. (void) pid;
  10624. (void) sig;
  10625. _not_implemented("_kill");
  10626. return -1;
  10627. }
  10628. int _getpid() {
  10629. fprint_str(stderr, "_getpid is not implemented\n");
  10630. return 42;
  10631. }
  10632. int _isatty(int fd) {
  10633. /* 0, 1 and 2 are TTYs. */
  10634. return fd < 2;
  10635. }
  10636. #endif /* CS_PLATFORM == CS_P_CC3200 */
  10637. #ifdef MG_MODULE_LINES
  10638. #line 1 "common/platforms/msp432/msp432_libc.c"
  10639. #endif
  10640. /*
  10641. * Copyright (c) 2014-2016 Cesanta Software Limited
  10642. * All rights reserved
  10643. */
  10644. #if CS_PLATFORM == CS_P_MSP432
  10645. #include <ti/sysbios/BIOS.h>
  10646. #include <ti/sysbios/knl/Clock.h>
  10647. int gettimeofday(struct timeval *tp, void *tzp) {
  10648. uint32_t ticks = Clock_getTicks();
  10649. tp->tv_sec = ticks / 1000;
  10650. tp->tv_usec = (ticks % 1000) * 1000;
  10651. return 0;
  10652. }
  10653. #endif /* CS_PLATFORM == CS_P_MSP432 */
  10654. #ifdef MG_MODULE_LINES
  10655. #line 1 "common/platforms/nrf5/nrf5_libc.c"
  10656. #endif
  10657. /*
  10658. * Copyright (c) 2014-2016 Cesanta Software Limited
  10659. * All rights reserved
  10660. */
  10661. #if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
  10662. defined(__ARMCC_VERSION)
  10663. int gettimeofday(struct timeval *tp, void *tzp) {
  10664. /* TODO */
  10665. tp->tv_sec = 0;
  10666. tp->tv_usec = 0;
  10667. return 0;
  10668. }
  10669. #endif
  10670. #ifdef MG_MODULE_LINES
  10671. #line 1 "common/platforms/simplelink/sl_fs_slfs.h"
  10672. #endif
  10673. /*
  10674. * Copyright (c) 2014-2016 Cesanta Software Limited
  10675. * All rights reserved
  10676. */
  10677. #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
  10678. #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
  10679. #if defined(MG_FS_SLFS)
  10680. #include <stdio.h>
  10681. #ifndef __TI_COMPILER_VERSION__
  10682. #include <unistd.h>
  10683. #include <sys/stat.h>
  10684. #endif
  10685. #define MAX_OPEN_SLFS_FILES 8
  10686. /* Indirect libc interface - same functions, different names. */
  10687. int fs_slfs_open(const char *pathname, int flags, mode_t mode);
  10688. int fs_slfs_close(int fd);
  10689. ssize_t fs_slfs_read(int fd, void *buf, size_t count);
  10690. ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
  10691. int fs_slfs_stat(const char *pathname, struct stat *s);
  10692. int fs_slfs_fstat(int fd, struct stat *s);
  10693. off_t fs_slfs_lseek(int fd, off_t offset, int whence);
  10694. int fs_slfs_unlink(const char *filename);
  10695. int fs_slfs_rename(const char *from, const char *to);
  10696. void fs_slfs_set_new_file_size(const char *name, size_t size);
  10697. #endif /* defined(MG_FS_SLFS) */
  10698. #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
  10699. #ifdef MG_MODULE_LINES
  10700. #line 1 "common/platforms/simplelink/sl_fs_slfs.c"
  10701. #endif
  10702. /*
  10703. * Copyright (c) 2014-2016 Cesanta Software Limited
  10704. * All rights reserved
  10705. */
  10706. /* Standard libc interface to TI SimpleLink FS. */
  10707. #if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
  10708. /* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
  10709. #include <errno.h>
  10710. #if CS_PLATFORM == CS_P_CC3200
  10711. #include <inc/hw_types.h>
  10712. #endif
  10713. #include <simplelink/include/simplelink.h>
  10714. #include <simplelink/include/fs.h>
  10715. /* Amalgamated: #include "common/cs_dbg.h" */
  10716. /* From sl_fs.c */
  10717. extern int set_errno(int e);
  10718. static const char *drop_dir(const char *fname, bool *is_slfs);
  10719. /*
  10720. * With SLFS, you have to pre-declare max file size. Yes. Really.
  10721. * 64K should be enough for everyone. Right?
  10722. */
  10723. #ifndef FS_SLFS_MAX_FILE_SIZE
  10724. #define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
  10725. #endif
  10726. struct sl_file_size_hint {
  10727. char *name;
  10728. size_t size;
  10729. };
  10730. struct sl_fd_info {
  10731. _i32 fh;
  10732. _off_t pos;
  10733. size_t size;
  10734. };
  10735. static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
  10736. static struct sl_file_size_hint s_sl_file_size_hints[MAX_OPEN_SLFS_FILES];
  10737. static int sl_fs_to_errno(_i32 r) {
  10738. DBG(("SL error: %d", (int) r));
  10739. switch (r) {
  10740. case SL_FS_OK:
  10741. return 0;
  10742. case SL_FS_FILE_NAME_EXIST:
  10743. return EEXIST;
  10744. case SL_FS_WRONG_FILE_NAME:
  10745. return EINVAL;
  10746. case SL_FS_ERR_NO_AVAILABLE_NV_INDEX:
  10747. case SL_FS_ERR_NO_AVAILABLE_BLOCKS:
  10748. return ENOSPC;
  10749. case SL_FS_ERR_FAILED_TO_ALLOCATE_MEM:
  10750. return ENOMEM;
  10751. case SL_FS_ERR_FILE_NOT_EXISTS:
  10752. return ENOENT;
  10753. case SL_FS_ERR_NOT_SUPPORTED:
  10754. return ENOTSUP;
  10755. }
  10756. return ENXIO;
  10757. }
  10758. int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
  10759. int fd;
  10760. for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
  10761. if (s_sl_fds[fd].fh <= 0) break;
  10762. }
  10763. if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
  10764. struct sl_fd_info *fi = &s_sl_fds[fd];
  10765. /*
  10766. * Apply path manipulations again, in case we got here directly
  10767. * (via TI libc's "add_device").
  10768. */
  10769. pathname = drop_dir(pathname, NULL);
  10770. _u32 am = 0;
  10771. fi->size = (size_t) -1;
  10772. int rw = (flags & 3);
  10773. if (rw == O_RDONLY) {
  10774. SlFsFileInfo_t sl_fi;
  10775. _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
  10776. if (r == SL_FS_OK) {
  10777. fi->size = sl_fi.FileLen;
  10778. }
  10779. am = FS_MODE_OPEN_READ;
  10780. } else {
  10781. if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
  10782. // FailFS files cannot be opened for append and will be truncated
  10783. // when opened for write.
  10784. return set_errno(ENOTSUP);
  10785. }
  10786. if (flags & O_CREAT) {
  10787. size_t i, size = FS_SLFS_MAX_FILE_SIZE;
  10788. for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
  10789. if (s_sl_file_size_hints[i].name != NULL &&
  10790. strcmp(s_sl_file_size_hints[i].name, pathname) == 0) {
  10791. size = s_sl_file_size_hints[i].size;
  10792. MG_FREE(s_sl_file_size_hints[i].name);
  10793. s_sl_file_size_hints[i].name = NULL;
  10794. break;
  10795. }
  10796. }
  10797. DBG(("creating %s with max size %d", pathname, (int) size));
  10798. am = FS_MODE_OPEN_CREATE(size, 0);
  10799. } else {
  10800. am = FS_MODE_OPEN_WRITE;
  10801. }
  10802. }
  10803. _i32 r = sl_FsOpen((_u8 *) pathname, am, NULL, &fi->fh);
  10804. DBG(("sl_FsOpen(%s, 0x%x) = %d, %d", pathname, (int) am, (int) r,
  10805. (int) fi->fh));
  10806. if (r == SL_FS_OK) {
  10807. fi->pos = 0;
  10808. r = fd;
  10809. } else {
  10810. fi->fh = -1;
  10811. r = set_errno(sl_fs_to_errno(r));
  10812. }
  10813. return r;
  10814. }
  10815. int fs_slfs_close(int fd) {
  10816. struct sl_fd_info *fi = &s_sl_fds[fd];
  10817. if (fi->fh <= 0) return set_errno(EBADF);
  10818. _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
  10819. DBG(("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
  10820. s_sl_fds[fd].fh = -1;
  10821. return set_errno(sl_fs_to_errno(r));
  10822. }
  10823. ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
  10824. struct sl_fd_info *fi = &s_sl_fds[fd];
  10825. if (fi->fh <= 0) return set_errno(EBADF);
  10826. /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
  10827. */
  10828. if (fi->pos == fi->size) return 0;
  10829. _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
  10830. DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
  10831. (int) r));
  10832. if (r >= 0) {
  10833. fi->pos += r;
  10834. return r;
  10835. }
  10836. return set_errno(sl_fs_to_errno(r));
  10837. }
  10838. ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
  10839. struct sl_fd_info *fi = &s_sl_fds[fd];
  10840. if (fi->fh <= 0) return set_errno(EBADF);
  10841. _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
  10842. DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
  10843. (int) r));
  10844. if (r >= 0) {
  10845. fi->pos += r;
  10846. return r;
  10847. }
  10848. return set_errno(sl_fs_to_errno(r));
  10849. }
  10850. int fs_slfs_stat(const char *pathname, struct stat *s) {
  10851. SlFsFileInfo_t sl_fi;
  10852. /*
  10853. * Apply path manipulations again, in case we got here directly
  10854. * (via TI libc's "add_device").
  10855. */
  10856. pathname = drop_dir(pathname, NULL);
  10857. _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
  10858. if (r == SL_FS_OK) {
  10859. s->st_mode = S_IFREG | 0666;
  10860. s->st_nlink = 1;
  10861. s->st_size = sl_fi.FileLen;
  10862. return 0;
  10863. }
  10864. return set_errno(sl_fs_to_errno(r));
  10865. }
  10866. int fs_slfs_fstat(int fd, struct stat *s) {
  10867. struct sl_fd_info *fi = &s_sl_fds[fd];
  10868. if (fi->fh <= 0) return set_errno(EBADF);
  10869. s->st_mode = 0666;
  10870. s->st_mode = S_IFREG | 0666;
  10871. s->st_nlink = 1;
  10872. s->st_size = fi->size;
  10873. return 0;
  10874. }
  10875. off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
  10876. if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
  10877. switch (whence) {
  10878. case SEEK_SET:
  10879. s_sl_fds[fd].pos = offset;
  10880. break;
  10881. case SEEK_CUR:
  10882. s_sl_fds[fd].pos += offset;
  10883. break;
  10884. case SEEK_END:
  10885. return set_errno(ENOTSUP);
  10886. }
  10887. return 0;
  10888. }
  10889. int fs_slfs_unlink(const char *pathname) {
  10890. /*
  10891. * Apply path manipulations again, in case we got here directly
  10892. * (via TI libc's "add_device").
  10893. */
  10894. pathname = drop_dir(pathname, NULL);
  10895. return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
  10896. }
  10897. int fs_slfs_rename(const char *from, const char *to) {
  10898. return set_errno(ENOTSUP);
  10899. }
  10900. void fs_slfs_set_new_file_size(const char *name, size_t size) {
  10901. int i;
  10902. for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
  10903. if (s_sl_file_size_hints[i].name == NULL) {
  10904. DBG(("File size hint: %s %d", name, (int) size));
  10905. s_sl_file_size_hints[i].name = MG_STRDUP(name);
  10906. s_sl_file_size_hints[i].size = size;
  10907. break;
  10908. }
  10909. }
  10910. }
  10911. #endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
  10912. #ifdef MG_MODULE_LINES
  10913. #line 1 "common/platforms/simplelink/sl_fs.c"
  10914. #endif
  10915. /*
  10916. * Copyright (c) 2014-2016 Cesanta Software Limited
  10917. * All rights reserved
  10918. */
  10919. #if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
  10920. (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
  10921. #include <errno.h>
  10922. #include <stdbool.h>
  10923. #include <stdio.h>
  10924. #include <stdlib.h>
  10925. #include <string.h>
  10926. #ifdef __TI_COMPILER_VERSION__
  10927. #include <file.h>
  10928. #endif
  10929. /* Amalgamated: #include "common/cs_dbg.h" */
  10930. /* Amalgamated: #include "common/platform.h" */
  10931. #ifdef CC3200_FS_SPIFFS
  10932. /* Amalgamated: #include "cc3200_fs_spiffs.h" */
  10933. #endif
  10934. #ifdef MG_FS_SLFS
  10935. /* Amalgamated: #include "sl_fs_slfs.h" */
  10936. #endif
  10937. #define NUM_SYS_FDS 3
  10938. #define SPIFFS_FD_BASE 10
  10939. #define SLFS_FD_BASE 100
  10940. #ifndef MG_UART_CHAR_PUT
  10941. #if CS_PLATFORM == CS_P_CC3200
  10942. #include <inc/hw_types.h>
  10943. #include <inc/hw_memmap.h>
  10944. #include <driverlib/rom.h>
  10945. #include <driverlib/rom_map.h>
  10946. #include <driverlib/uart.h>
  10947. #define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
  10948. #else
  10949. #define MG_UART_CHAR_PUT(fd, c)
  10950. #endif /* CS_PLATFORM == CS_P_CC3200 */
  10951. #endif /* !MG_UART_CHAR_PUT */
  10952. int set_errno(int e) {
  10953. errno = e;
  10954. return (e == 0 ? 0 : -1);
  10955. }
  10956. static const char *drop_dir(const char *fname, bool *is_slfs) {
  10957. if (is_slfs != NULL) {
  10958. *is_slfs = (strncmp(fname, "SL:", 3) == 0);
  10959. if (*is_slfs) fname += 3;
  10960. }
  10961. /* Drop "./", if any */
  10962. if (fname[0] == '.' && fname[1] == '/') {
  10963. fname += 2;
  10964. }
  10965. /*
  10966. * Drop / if it is the only one in the path.
  10967. * This allows use of /pretend/directories but serves /file.txt as normal.
  10968. */
  10969. if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
  10970. fname++;
  10971. }
  10972. return fname;
  10973. }
  10974. enum fd_type {
  10975. FD_INVALID,
  10976. FD_SYS,
  10977. #ifdef CC3200_FS_SPIFFS
  10978. FD_SPIFFS,
  10979. #endif
  10980. #ifdef MG_FS_SLFS
  10981. FD_SLFS
  10982. #endif
  10983. };
  10984. static int fd_type(int fd) {
  10985. if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
  10986. #ifdef CC3200_FS_SPIFFS
  10987. if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
  10988. return FD_SPIFFS;
  10989. }
  10990. #endif
  10991. #ifdef MG_FS_SLFS
  10992. if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
  10993. return FD_SLFS;
  10994. }
  10995. #endif
  10996. return FD_INVALID;
  10997. }
  10998. #if MG_TI_NO_HOST_INTERFACE
  10999. int open(const char *pathname, unsigned flags, int mode) {
  11000. #else
  11001. int _open(const char *pathname, int flags, mode_t mode) {
  11002. #endif
  11003. int fd = -1;
  11004. bool is_sl;
  11005. const char *fname = drop_dir(pathname, &is_sl);
  11006. if (is_sl) {
  11007. #ifdef MG_FS_SLFS
  11008. fd = fs_slfs_open(fname, flags, mode);
  11009. if (fd >= 0) fd += SLFS_FD_BASE;
  11010. #endif
  11011. } else {
  11012. #ifdef CC3200_FS_SPIFFS
  11013. fd = fs_spiffs_open(fname, flags, mode);
  11014. if (fd >= 0) fd += SPIFFS_FD_BASE;
  11015. #endif
  11016. }
  11017. LOG(LL_DEBUG,
  11018. ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
  11019. return fd;
  11020. }
  11021. int _stat(const char *pathname, struct stat *st) {
  11022. int res = -1;
  11023. bool is_sl;
  11024. const char *fname = drop_dir(pathname, &is_sl);
  11025. memset(st, 0, sizeof(*st));
  11026. /* Simulate statting the root directory. */
  11027. if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
  11028. st->st_ino = 0;
  11029. st->st_mode = S_IFDIR | 0777;
  11030. st->st_nlink = 1;
  11031. st->st_size = 0;
  11032. return 0;
  11033. }
  11034. if (is_sl) {
  11035. #ifdef MG_FS_SLFS
  11036. res = fs_slfs_stat(fname, st);
  11037. #endif
  11038. } else {
  11039. #ifdef CC3200_FS_SPIFFS
  11040. res = fs_spiffs_stat(fname, st);
  11041. #endif
  11042. }
  11043. LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
  11044. return res;
  11045. }
  11046. #if MG_TI_NO_HOST_INTERFACE
  11047. int close(int fd) {
  11048. #else
  11049. int _close(int fd) {
  11050. #endif
  11051. int r = -1;
  11052. switch (fd_type(fd)) {
  11053. case FD_INVALID:
  11054. r = set_errno(EBADF);
  11055. break;
  11056. case FD_SYS:
  11057. r = set_errno(EACCES);
  11058. break;
  11059. #ifdef CC3200_FS_SPIFFS
  11060. case FD_SPIFFS:
  11061. r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
  11062. break;
  11063. #endif
  11064. #ifdef MG_FS_SLFS
  11065. case FD_SLFS:
  11066. r = fs_slfs_close(fd - SLFS_FD_BASE);
  11067. break;
  11068. #endif
  11069. }
  11070. DBG(("close(%d) = %d", fd, r));
  11071. return r;
  11072. }
  11073. #if MG_TI_NO_HOST_INTERFACE
  11074. off_t lseek(int fd, off_t offset, int whence) {
  11075. #else
  11076. off_t _lseek(int fd, off_t offset, int whence) {
  11077. #endif
  11078. int r = -1;
  11079. switch (fd_type(fd)) {
  11080. case FD_INVALID:
  11081. r = set_errno(EBADF);
  11082. break;
  11083. case FD_SYS:
  11084. r = set_errno(ESPIPE);
  11085. break;
  11086. #ifdef CC3200_FS_SPIFFS
  11087. case FD_SPIFFS:
  11088. r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
  11089. break;
  11090. #endif
  11091. #ifdef MG_FS_SLFS
  11092. case FD_SLFS:
  11093. r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
  11094. break;
  11095. #endif
  11096. }
  11097. DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
  11098. return r;
  11099. }
  11100. int _fstat(int fd, struct stat *s) {
  11101. int r = -1;
  11102. memset(s, 0, sizeof(*s));
  11103. switch (fd_type(fd)) {
  11104. case FD_INVALID:
  11105. r = set_errno(EBADF);
  11106. break;
  11107. case FD_SYS: {
  11108. /* Create barely passable stats for STD{IN,OUT,ERR}. */
  11109. memset(s, 0, sizeof(*s));
  11110. s->st_ino = fd;
  11111. s->st_mode = S_IFCHR | 0666;
  11112. r = 0;
  11113. break;
  11114. }
  11115. #ifdef CC3200_FS_SPIFFS
  11116. case FD_SPIFFS:
  11117. r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
  11118. break;
  11119. #endif
  11120. #ifdef MG_FS_SLFS
  11121. case FD_SLFS:
  11122. r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
  11123. break;
  11124. #endif
  11125. }
  11126. DBG(("fstat(%d) = %d", fd, r));
  11127. return r;
  11128. }
  11129. #if MG_TI_NO_HOST_INTERFACE
  11130. int read(int fd, char *buf, unsigned count) {
  11131. #else
  11132. ssize_t _read(int fd, void *buf, size_t count) {
  11133. #endif
  11134. int r = -1;
  11135. switch (fd_type(fd)) {
  11136. case FD_INVALID:
  11137. r = set_errno(EBADF);
  11138. break;
  11139. case FD_SYS: {
  11140. if (fd != 0) {
  11141. r = set_errno(EACCES);
  11142. break;
  11143. }
  11144. /* Should we allow reading from stdin = uart? */
  11145. r = set_errno(ENOTSUP);
  11146. break;
  11147. }
  11148. #ifdef CC3200_FS_SPIFFS
  11149. case FD_SPIFFS:
  11150. r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
  11151. break;
  11152. #endif
  11153. #ifdef MG_FS_SLFS
  11154. case FD_SLFS:
  11155. r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
  11156. break;
  11157. #endif
  11158. }
  11159. DBG(("read(%d, %u) = %d", fd, count, r));
  11160. return r;
  11161. }
  11162. #if MG_TI_NO_HOST_INTERFACE
  11163. int write(int fd, const char *buf, unsigned count) {
  11164. #else
  11165. ssize_t _write(int fd, const void *buf, size_t count) {
  11166. #endif
  11167. int r = -1;
  11168. size_t i = 0;
  11169. switch (fd_type(fd)) {
  11170. case FD_INVALID:
  11171. r = set_errno(EBADF);
  11172. break;
  11173. case FD_SYS: {
  11174. if (fd == 0) {
  11175. r = set_errno(EACCES);
  11176. break;
  11177. }
  11178. for (i = 0; i < count; i++) {
  11179. const char c = ((const char *) buf)[i];
  11180. if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
  11181. MG_UART_CHAR_PUT(fd, c);
  11182. }
  11183. r = count;
  11184. break;
  11185. }
  11186. #ifdef CC3200_FS_SPIFFS
  11187. case FD_SPIFFS:
  11188. r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
  11189. break;
  11190. #endif
  11191. #ifdef MG_FS_SLFS
  11192. case FD_SLFS:
  11193. r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
  11194. break;
  11195. #endif
  11196. }
  11197. return r;
  11198. }
  11199. /*
  11200. * On Newlib we override rename directly too, because the default
  11201. * implementation using _link and _unlink doesn't work for us.
  11202. */
  11203. #if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
  11204. int rename(const char *frompath, const char *topath) {
  11205. int r = -1;
  11206. bool is_sl_from, is_sl_to;
  11207. const char *from = drop_dir(frompath, &is_sl_from);
  11208. const char *to = drop_dir(topath, &is_sl_to);
  11209. if (is_sl_from || is_sl_to) {
  11210. set_errno(ENOTSUP);
  11211. } else {
  11212. #ifdef CC3200_FS_SPIFFS
  11213. r = fs_spiffs_rename(from, to);
  11214. #endif
  11215. }
  11216. DBG(("rename(%s, %s) = %d", from, to, r));
  11217. return r;
  11218. }
  11219. #endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
  11220. #if MG_TI_NO_HOST_INTERFACE
  11221. int unlink(const char *pathname) {
  11222. #else
  11223. int _unlink(const char *pathname) {
  11224. #endif
  11225. int r = -1;
  11226. bool is_sl;
  11227. const char *fname = drop_dir(pathname, &is_sl);
  11228. if (is_sl) {
  11229. #ifdef MG_FS_SLFS
  11230. r = fs_slfs_unlink(fname);
  11231. #endif
  11232. } else {
  11233. #ifdef CC3200_FS_SPIFFS
  11234. r = fs_spiffs_unlink(fname);
  11235. #endif
  11236. }
  11237. DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
  11238. return r;
  11239. }
  11240. #ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
  11241. DIR *opendir(const char *dir_name) {
  11242. DIR *r = NULL;
  11243. bool is_sl;
  11244. drop_dir(dir_name, &is_sl);
  11245. if (is_sl) {
  11246. r = NULL;
  11247. set_errno(ENOTSUP);
  11248. } else {
  11249. r = fs_spiffs_opendir(dir_name);
  11250. }
  11251. DBG(("opendir(%s) = %p", dir_name, r));
  11252. return r;
  11253. }
  11254. struct dirent *readdir(DIR *dir) {
  11255. struct dirent *res = fs_spiffs_readdir(dir);
  11256. DBG(("readdir(%p) = %p", dir, res));
  11257. return res;
  11258. }
  11259. int closedir(DIR *dir) {
  11260. int res = fs_spiffs_closedir(dir);
  11261. DBG(("closedir(%p) = %d", dir, res));
  11262. return res;
  11263. }
  11264. int rmdir(const char *path) {
  11265. return fs_spiffs_rmdir(path);
  11266. }
  11267. int mkdir(const char *path, mode_t mode) {
  11268. (void) path;
  11269. (void) mode;
  11270. /* for spiffs supports only root dir, which comes from mongoose as '.' */
  11271. return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
  11272. }
  11273. #endif
  11274. int sl_fs_init(void) {
  11275. int ret = 1;
  11276. #ifdef __TI_COMPILER_VERSION__
  11277. #ifdef MG_FS_SLFS
  11278. #pragma diag_push
  11279. #pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
  11280. */
  11281. ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
  11282. fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
  11283. fs_slfs_rename) == 0);
  11284. #pragma diag_pop
  11285. #endif
  11286. #endif
  11287. return ret;
  11288. }
  11289. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
  11290. defined(MG_FS_SPIFFS)) */
  11291. #ifdef MG_MODULE_LINES
  11292. #line 1 "common/platforms/simplelink/sl_socket.c"
  11293. #endif
  11294. /*
  11295. * Copyright (c) 2014-2016 Cesanta Software Limited
  11296. * All rights reserved
  11297. */
  11298. #if MG_NET_IF == MG_NET_IF_SIMPLELINK
  11299. #include <errno.h>
  11300. #include <stdio.h>
  11301. /* Amalgamated: #include "common/platform.h" */
  11302. const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
  11303. int res;
  11304. struct in_addr *in = (struct in_addr *) src;
  11305. if (af != AF_INET) {
  11306. errno = EAFNOSUPPORT;
  11307. return NULL;
  11308. }
  11309. res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
  11310. SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
  11311. SL_IPV4_BYTE(in->s_addr, 3));
  11312. return res > 0 ? dst : NULL;
  11313. }
  11314. char *inet_ntoa(struct in_addr n) {
  11315. static char a[16];
  11316. return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
  11317. }
  11318. int inet_pton(int af, const char *src, void *dst) {
  11319. uint32_t a0, a1, a2, a3;
  11320. uint8_t *db = (uint8_t *) dst;
  11321. if (af != AF_INET) {
  11322. errno = EAFNOSUPPORT;
  11323. return 0;
  11324. }
  11325. if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
  11326. return 0;
  11327. }
  11328. *db = a3;
  11329. *(db + 1) = a2;
  11330. *(db + 2) = a1;
  11331. *(db + 3) = a0;
  11332. return 1;
  11333. }
  11334. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
  11335. #ifdef MG_MODULE_LINES
  11336. #line 1 "common/platforms/simplelink/sl_mg_task.c"
  11337. #endif
  11338. #if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
  11339. /* Amalgamated: #include "mg_task.h" */
  11340. #include <oslib/osi.h>
  11341. enum mg_q_msg_type {
  11342. MG_Q_MSG_CB,
  11343. };
  11344. struct mg_q_msg {
  11345. enum mg_q_msg_type type;
  11346. void (*cb)(struct mg_mgr *mgr, void *arg);
  11347. void *arg;
  11348. };
  11349. static OsiMsgQ_t s_mg_q;
  11350. static void mg_task(void *arg);
  11351. bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
  11352. if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
  11353. return false;
  11354. }
  11355. if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
  11356. (void *) mg_init, priority, NULL) != OSI_OK) {
  11357. return false;
  11358. }
  11359. return true;
  11360. }
  11361. static void mg_task(void *arg) {
  11362. struct mg_mgr mgr;
  11363. mg_init_cb mg_init = (mg_init_cb) arg;
  11364. mg_mgr_init(&mgr, NULL);
  11365. mg_init(&mgr);
  11366. while (1) {
  11367. struct mg_q_msg msg;
  11368. mg_mgr_poll(&mgr, 1);
  11369. if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
  11370. switch (msg.type) {
  11371. case MG_Q_MSG_CB: {
  11372. msg.cb(&mgr, msg.arg);
  11373. }
  11374. }
  11375. }
  11376. }
  11377. void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
  11378. struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
  11379. osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
  11380. }
  11381. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
  11382. */
  11383. #ifdef MG_MODULE_LINES
  11384. #line 1 "common/platforms/simplelink/sl_net_if.h"
  11385. #endif
  11386. /*
  11387. * Copyright (c) 2014-2016 Cesanta Software Limited
  11388. * All rights reserved
  11389. */
  11390. #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
  11391. #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
  11392. /* Amalgamated: #include "mongoose/src/net_if.h" */
  11393. #ifdef __cplusplus
  11394. extern "C" {
  11395. #endif /* __cplusplus */
  11396. #ifndef MG_ENABLE_NET_IF_SIMPLELINK
  11397. #define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
  11398. #endif
  11399. extern struct mg_iface_vtable mg_simplelink_iface_vtable;
  11400. #ifdef __cplusplus
  11401. }
  11402. #endif /* __cplusplus */
  11403. #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
  11404. #ifdef MG_MODULE_LINES
  11405. #line 1 "common/platforms/simplelink/sl_net_if.c"
  11406. #endif
  11407. /*
  11408. * Copyright (c) 2014-2016 Cesanta Software Limited
  11409. * All rights reserved
  11410. */
  11411. /* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
  11412. #if MG_ENABLE_NET_IF_SIMPLELINK
  11413. /* Amalgamated: #include "mongoose/src/internal.h" */
  11414. /* Amalgamated: #include "mongoose/src/util.h" */
  11415. #define MG_TCP_RECV_BUFFER_SIZE 1024
  11416. #define MG_UDP_RECV_BUFFER_SIZE 1500
  11417. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  11418. int proto);
  11419. int sl_set_ssl_opts(struct mg_connection *nc);
  11420. void mg_set_non_blocking_mode(sock_t sock) {
  11421. SlSockNonblocking_t opt;
  11422. opt.NonblockingEnabled = 1;
  11423. sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
  11424. }
  11425. static int mg_is_error(int n) {
  11426. return (n < 0 && n != SL_EALREADY && n != SL_EAGAIN);
  11427. }
  11428. void mg_sl_if_connect_tcp(struct mg_connection *nc,
  11429. const union socket_address *sa) {
  11430. int proto = 0;
  11431. if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
  11432. sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
  11433. if (sock < 0) {
  11434. nc->err = sock;
  11435. goto out;
  11436. }
  11437. mg_sock_set(nc, sock);
  11438. #if MG_ENABLE_SSL
  11439. nc->err = sl_set_ssl_opts(nc);
  11440. if (nc->err != 0) goto out;
  11441. #endif
  11442. nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
  11443. out:
  11444. DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
  11445. ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
  11446. }
  11447. void mg_sl_if_connect_udp(struct mg_connection *nc) {
  11448. sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
  11449. if (sock < 0) {
  11450. nc->err = sock;
  11451. return;
  11452. }
  11453. mg_sock_set(nc, sock);
  11454. nc->err = 0;
  11455. }
  11456. int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  11457. int proto = 0;
  11458. if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
  11459. sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
  11460. if (sock < 0) return sock;
  11461. mg_sock_set(nc, sock);
  11462. #if MG_ENABLE_SSL
  11463. return sl_set_ssl_opts(nc);
  11464. #else
  11465. return 0;
  11466. #endif
  11467. }
  11468. int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  11469. sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
  11470. if (sock == INVALID_SOCKET) return (errno ? errno : 1);
  11471. mg_sock_set(nc, sock);
  11472. return 0;
  11473. }
  11474. void mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
  11475. mbuf_append(&nc->send_mbuf, buf, len);
  11476. }
  11477. void mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
  11478. mbuf_append(&nc->send_mbuf, buf, len);
  11479. }
  11480. void mg_sl_if_recved(struct mg_connection *nc, size_t len) {
  11481. (void) nc;
  11482. (void) len;
  11483. }
  11484. int mg_sl_if_create_conn(struct mg_connection *nc) {
  11485. (void) nc;
  11486. return 1;
  11487. }
  11488. void mg_sl_if_destroy_conn(struct mg_connection *nc) {
  11489. if (nc->sock == INVALID_SOCKET) return;
  11490. /* For UDP, only close outgoing sockets or listeners. */
  11491. if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
  11492. sl_Close(nc->sock);
  11493. }
  11494. nc->sock = INVALID_SOCKET;
  11495. }
  11496. static int mg_accept_conn(struct mg_connection *lc) {
  11497. struct mg_connection *nc;
  11498. union socket_address sa;
  11499. socklen_t sa_len = sizeof(sa);
  11500. sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
  11501. if (sock < 0) {
  11502. DBG(("%p: failed to accept: %d", lc, sock));
  11503. return 0;
  11504. }
  11505. nc = mg_if_accept_new_conn(lc);
  11506. if (nc == NULL) {
  11507. sl_Close(sock);
  11508. return 0;
  11509. }
  11510. DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
  11511. ntohs(sa.sin.sin_port)));
  11512. mg_sock_set(nc, sock);
  11513. if (nc->flags & MG_F_SSL) nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
  11514. mg_if_accept_tcp_cb(nc, &sa, sa_len);
  11515. return 1;
  11516. }
  11517. /* 'sa' must be an initialized address to bind to */
  11518. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  11519. int proto) {
  11520. int r;
  11521. socklen_t sa_len =
  11522. (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
  11523. sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
  11524. if (sock < 0) return sock;
  11525. if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) {
  11526. sl_Close(sock);
  11527. return r;
  11528. }
  11529. if (type != SOCK_DGRAM && (r = sl_Listen(sock, SOMAXCONN)) < 0) {
  11530. sl_Close(sock);
  11531. return r;
  11532. }
  11533. mg_set_non_blocking_mode(sock);
  11534. return sock;
  11535. }
  11536. static void mg_write_to_socket(struct mg_connection *nc) {
  11537. struct mbuf *io = &nc->send_mbuf;
  11538. int n = 0;
  11539. if (nc->flags & MG_F_UDP) {
  11540. n = sl_SendTo(nc->sock, io->buf, io->len, 0, &nc->sa.sa,
  11541. sizeof(nc->sa.sin));
  11542. DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
  11543. inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
  11544. } else {
  11545. n = (int) sl_Send(nc->sock, io->buf, io->len, 0);
  11546. DBG(("%p %d bytes -> %d", nc, n, nc->sock));
  11547. }
  11548. if (n > 0) {
  11549. mbuf_remove(io, n);
  11550. mg_if_sent_cb(nc, n);
  11551. } else if (n < 0 && mg_is_error(n)) {
  11552. /* Something went wrong, drop the connection. */
  11553. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  11554. }
  11555. }
  11556. MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
  11557. size_t avail;
  11558. if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
  11559. avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
  11560. return avail > max ? max : avail;
  11561. }
  11562. static void mg_handle_tcp_read(struct mg_connection *conn) {
  11563. int n = 0;
  11564. char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
  11565. if (buf == NULL) {
  11566. DBG(("OOM"));
  11567. return;
  11568. }
  11569. n = (int) sl_Recv(conn->sock, buf,
  11570. recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
  11571. DBG(("%p %d bytes <- %d", conn, n, conn->sock));
  11572. if (n > 0) {
  11573. mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
  11574. } else {
  11575. MG_FREE(buf);
  11576. }
  11577. if (n == 0) {
  11578. /* Orderly shutdown of the socket, try flushing output. */
  11579. conn->flags |= MG_F_SEND_AND_CLOSE;
  11580. } else if (mg_is_error(n)) {
  11581. conn->flags |= MG_F_CLOSE_IMMEDIATELY;
  11582. }
  11583. }
  11584. static void mg_handle_udp_read(struct mg_connection *nc) {
  11585. char *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
  11586. if (buf == NULL) return;
  11587. union socket_address sa;
  11588. socklen_t sa_len = sizeof(sa);
  11589. int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
  11590. (SlSockAddr_t *) &sa, &sa_len);
  11591. DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
  11592. ntohs(nc->sa.sin.sin_port)));
  11593. if (n > 0) {
  11594. mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
  11595. } else {
  11596. MG_FREE(buf);
  11597. }
  11598. }
  11599. #define _MG_F_FD_CAN_READ 1
  11600. #define _MG_F_FD_CAN_WRITE 1 << 1
  11601. #define _MG_F_FD_ERROR 1 << 2
  11602. void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
  11603. DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
  11604. fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  11605. if (nc->flags & MG_F_CONNECTING) {
  11606. if (nc->flags & MG_F_UDP || nc->err != SL_EALREADY) {
  11607. mg_if_connect_cb(nc, nc->err);
  11608. } else {
  11609. /* In SimpleLink, to get status of non-blocking connect() we need to wait
  11610. * until socket is writable and repeat the call to sl_Connect again,
  11611. * which will now return the real status. */
  11612. if (fd_flags & _MG_F_FD_CAN_WRITE) {
  11613. nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
  11614. DBG(("%p conn res=%d", nc, nc->err));
  11615. if (nc->err == SL_ESECSNOVERIFY ||
  11616. /* TODO(rojer): Provide API to set the date for verification. */
  11617. nc->err == SL_ESECDATEERROR) {
  11618. nc->err = 0;
  11619. }
  11620. if (nc->flags & MG_F_SSL && nc->err == 0) {
  11621. nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
  11622. }
  11623. mg_if_connect_cb(nc, nc->err);
  11624. }
  11625. }
  11626. /* Ignore read/write in further processing, we've handled it. */
  11627. fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
  11628. }
  11629. if (fd_flags & _MG_F_FD_CAN_READ) {
  11630. if (nc->flags & MG_F_UDP) {
  11631. mg_handle_udp_read(nc);
  11632. } else {
  11633. if (nc->flags & MG_F_LISTENING) {
  11634. mg_accept_conn(nc);
  11635. } else {
  11636. mg_handle_tcp_read(nc);
  11637. }
  11638. }
  11639. }
  11640. if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
  11641. if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
  11642. mg_write_to_socket(nc);
  11643. }
  11644. if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
  11645. mg_if_poll(nc, now);
  11646. }
  11647. mg_if_timer(nc, now);
  11648. }
  11649. DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
  11650. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  11651. }
  11652. /* Associate a socket to a connection. */
  11653. void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
  11654. mg_set_non_blocking_mode(sock);
  11655. nc->sock = sock;
  11656. DBG(("%p %d", nc, sock));
  11657. }
  11658. void mg_sl_if_init(struct mg_iface *iface) {
  11659. (void) iface;
  11660. DBG(("%p using sl_Select()", iface->mgr));
  11661. }
  11662. void mg_sl_if_free(struct mg_iface *iface) {
  11663. (void) iface;
  11664. }
  11665. void mg_sl_if_add_conn(struct mg_connection *nc) {
  11666. (void) nc;
  11667. }
  11668. void mg_sl_if_remove_conn(struct mg_connection *nc) {
  11669. (void) nc;
  11670. }
  11671. time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
  11672. struct mg_mgr *mgr = iface->mgr;
  11673. double now = mg_time();
  11674. double min_timer;
  11675. struct mg_connection *nc, *tmp;
  11676. struct SlTimeval_t tv;
  11677. SlFdSet_t read_set, write_set, err_set;
  11678. sock_t max_fd = INVALID_SOCKET;
  11679. int num_fds, num_ev = 0, num_timers = 0;
  11680. SL_FD_ZERO(&read_set);
  11681. SL_FD_ZERO(&write_set);
  11682. SL_FD_ZERO(&err_set);
  11683. /*
  11684. * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
  11685. * e.g. timer-only "connections".
  11686. */
  11687. min_timer = 0;
  11688. for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
  11689. tmp = nc->next;
  11690. if (nc->sock != INVALID_SOCKET) {
  11691. num_fds++;
  11692. if (!(nc->flags & MG_F_WANT_WRITE) &&
  11693. nc->recv_mbuf.len < nc->recv_mbuf_limit &&
  11694. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
  11695. SL_FD_SET(nc->sock, &read_set);
  11696. if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
  11697. }
  11698. if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
  11699. (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
  11700. SL_FD_SET(nc->sock, &write_set);
  11701. SL_FD_SET(nc->sock, &err_set);
  11702. if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
  11703. }
  11704. }
  11705. if (nc->ev_timer_time > 0) {
  11706. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  11707. min_timer = nc->ev_timer_time;
  11708. }
  11709. num_timers++;
  11710. }
  11711. }
  11712. /*
  11713. * If there is a timer to be fired earlier than the requested timeout,
  11714. * adjust the timeout.
  11715. */
  11716. if (num_timers > 0) {
  11717. double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
  11718. if (timer_timeout_ms < timeout_ms) {
  11719. timeout_ms = timer_timeout_ms;
  11720. }
  11721. }
  11722. if (timeout_ms < 0) timeout_ms = 0;
  11723. tv.tv_sec = timeout_ms / 1000;
  11724. tv.tv_usec = (timeout_ms % 1000) * 1000;
  11725. if (num_fds > 0) {
  11726. num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
  11727. }
  11728. now = mg_time();
  11729. DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
  11730. num_fds, timeout_ms));
  11731. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  11732. int fd_flags = 0;
  11733. if (nc->sock != INVALID_SOCKET) {
  11734. if (num_ev > 0) {
  11735. fd_flags =
  11736. (SL_FD_ISSET(nc->sock, &read_set) &&
  11737. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
  11738. ? _MG_F_FD_CAN_READ
  11739. : 0) |
  11740. (SL_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
  11741. (SL_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
  11742. }
  11743. /* SimpleLink does not report UDP sockets as writeable. */
  11744. if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
  11745. fd_flags |= _MG_F_FD_CAN_WRITE;
  11746. }
  11747. }
  11748. tmp = nc->next;
  11749. mg_mgr_handle_conn(nc, fd_flags, now);
  11750. }
  11751. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  11752. tmp = nc->next;
  11753. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  11754. (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
  11755. mg_close_conn(nc);
  11756. }
  11757. }
  11758. return now;
  11759. }
  11760. void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
  11761. union socket_address *sa) {
  11762. /* SimpleLink does not provide a way to get socket's peer address after
  11763. * accept or connect. Address hould have been preserved in the connection,
  11764. * so we do our best here by using it. */
  11765. if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
  11766. }
  11767. void sl_restart_cb(struct mg_mgr *mgr) {
  11768. /*
  11769. * SimpleLink has been restarted, meaning all sockets have been invalidated.
  11770. * We try our best - we'll restart the listeners, but for outgoing
  11771. * connections we have no option but to terminate.
  11772. */
  11773. struct mg_connection *nc;
  11774. for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
  11775. if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
  11776. if (nc->flags & MG_F_LISTENING) {
  11777. DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
  11778. ntohs(nc->sa.sin.sin_port)));
  11779. int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
  11780. : mg_sl_if_listen_tcp(nc, &nc->sa));
  11781. if (res == 0) continue;
  11782. /* Well, we tried and failed. Fall through to closing. */
  11783. }
  11784. nc->sock = INVALID_SOCKET;
  11785. DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
  11786. ntohs(nc->sa.sin.sin_port)));
  11787. /* TODO(rojer): Outgoing UDP? */
  11788. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  11789. }
  11790. }
  11791. /* clang-format off */
  11792. #define MG_SL_IFACE_VTABLE \
  11793. { \
  11794. mg_sl_if_init, \
  11795. mg_sl_if_free, \
  11796. mg_sl_if_add_conn, \
  11797. mg_sl_if_remove_conn, \
  11798. mg_sl_if_poll, \
  11799. mg_sl_if_listen_tcp, \
  11800. mg_sl_if_listen_udp, \
  11801. mg_sl_if_connect_tcp, \
  11802. mg_sl_if_connect_udp, \
  11803. mg_sl_if_tcp_send, \
  11804. mg_sl_if_udp_send, \
  11805. mg_sl_if_recved, \
  11806. mg_sl_if_create_conn, \
  11807. mg_sl_if_destroy_conn, \
  11808. mg_sl_if_sock_set, \
  11809. mg_sl_if_get_conn_addr, \
  11810. }
  11811. /* clang-format on */
  11812. struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
  11813. #if MG_NET_IF == MG_NET_IF_SIMPLELINK
  11814. struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
  11815. #endif
  11816. #endif /* MG_ENABLE_NET_IF_SIMPLELINK */
  11817. #ifdef MG_MODULE_LINES
  11818. #line 1 "common/platforms/simplelink/sl_ssl_if.c"
  11819. #endif
  11820. /*
  11821. * Copyright (c) 2014-2016 Cesanta Software Limited
  11822. * All rights reserved
  11823. */
  11824. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
  11825. struct mg_ssl_if_ctx {
  11826. char *ssl_cert;
  11827. char *ssl_key;
  11828. char *ssl_ca_cert;
  11829. char *ssl_server_name;
  11830. };
  11831. void mg_ssl_if_init() {
  11832. }
  11833. enum mg_ssl_if_result mg_ssl_if_conn_init(
  11834. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  11835. const char **err_msg) {
  11836. struct mg_ssl_if_ctx *ctx =
  11837. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  11838. if (ctx == NULL) {
  11839. MG_SET_PTRPTR(err_msg, "Out of memory");
  11840. return MG_SSL_ERROR;
  11841. }
  11842. nc->ssl_if_data = ctx;
  11843. if (params->cert != NULL || params->key != NULL) {
  11844. if (params->cert != NULL && params->key != NULL) {
  11845. ctx->ssl_cert = MG_STRDUP(params->cert);
  11846. ctx->ssl_key = MG_STRDUP(params->key);
  11847. } else {
  11848. MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
  11849. return MG_SSL_ERROR;
  11850. }
  11851. }
  11852. if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
  11853. ctx->ssl_ca_cert = MG_STRDUP(params->ca_cert);
  11854. }
  11855. /* TODO(rojer): cipher_suites. */
  11856. if (params->server_name != NULL) {
  11857. ctx->ssl_server_name = MG_STRDUP(params->server_name);
  11858. }
  11859. return MG_SSL_OK;
  11860. }
  11861. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  11862. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  11863. if (ctx == NULL) return;
  11864. nc->ssl_if_data = NULL;
  11865. MG_FREE(ctx->ssl_cert);
  11866. MG_FREE(ctx->ssl_key);
  11867. MG_FREE(ctx->ssl_ca_cert);
  11868. MG_FREE(ctx->ssl_server_name);
  11869. memset(ctx, 0, sizeof(*ctx));
  11870. MG_FREE(ctx);
  11871. }
  11872. bool pem_to_der(const char *pem_file, const char *der_file) {
  11873. bool ret = false;
  11874. FILE *pf = NULL, *df = NULL;
  11875. bool writing = false;
  11876. pf = fopen(pem_file, "r");
  11877. if (pf == NULL) goto clean;
  11878. remove(der_file);
  11879. fs_slfs_set_new_file_size(der_file + 3, 2048);
  11880. df = fopen(der_file, "w");
  11881. if (df == NULL) goto clean;
  11882. while (1) {
  11883. char pem_buf[70];
  11884. char der_buf[48];
  11885. if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
  11886. if (writing) {
  11887. if (strstr(pem_buf, "-----END ") != NULL) {
  11888. ret = true;
  11889. break;
  11890. }
  11891. int l = 0;
  11892. while (!isspace((unsigned int) pem_buf[l])) l++;
  11893. int der_len = 0;
  11894. cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
  11895. der_buf, &der_len);
  11896. if (der_len <= 0) break;
  11897. if (fwrite(der_buf, 1, der_len, df) != der_len) break;
  11898. } else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
  11899. writing = true;
  11900. }
  11901. }
  11902. clean:
  11903. if (pf != NULL) fclose(pf);
  11904. if (df != NULL) {
  11905. fclose(df);
  11906. if (!ret) remove(der_file);
  11907. }
  11908. return ret;
  11909. }
  11910. #if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
  11911. /* If the file's extension is .pem, convert it to DER format and put on SLFS. */
  11912. static char *sl_pem2der(const char *pem_file) {
  11913. const char *pem_ext = strstr(pem_file, ".pem");
  11914. if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
  11915. return MG_STRDUP(pem_file);
  11916. }
  11917. char *der_file = NULL;
  11918. /* DER file must be located on SLFS, add prefix. */
  11919. int l = mg_asprintf(&der_file, 0, "SL:%.*s.der", (int) (pem_ext - pem_file),
  11920. pem_file);
  11921. if (der_file == NULL) return NULL;
  11922. bool result = false;
  11923. cs_stat_t st;
  11924. if (mg_stat(der_file, &st) != 0) {
  11925. result = pem_to_der(pem_file, der_file);
  11926. LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
  11927. } else {
  11928. /* File exists, assume it's already been converted. */
  11929. result = true;
  11930. }
  11931. if (result) {
  11932. /* Strip the SL: prefix we added since NWP does not expect it. */
  11933. memmove(der_file, der_file + 3, l - 2 /* including \0 */);
  11934. } else {
  11935. MG_FREE(der_file);
  11936. der_file = NULL;
  11937. }
  11938. return der_file;
  11939. }
  11940. #else
  11941. static char *sl_pem2der(const char *pem_file) {
  11942. return MG_STRDUP(pem_file);
  11943. }
  11944. #endif
  11945. int sl_set_ssl_opts(struct mg_connection *nc) {
  11946. int err;
  11947. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  11948. DBG(("%p ssl ctx: %p", nc, ctx));
  11949. if (ctx != NULL) {
  11950. DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
  11951. (ctx->ssl_key ? ctx->ssl_cert : "-"),
  11952. (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
  11953. (ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
  11954. if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
  11955. char *ssl_cert = sl_pem2der(ctx->ssl_cert);
  11956. char *ssl_key = sl_pem2der(ctx->ssl_key);
  11957. if (ssl_cert != NULL && ssl_key != NULL) {
  11958. err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
  11959. SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
  11960. strlen(ssl_cert));
  11961. LOG(LL_INFO, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
  11962. err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
  11963. SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
  11964. strlen(ssl_key));
  11965. LOG(LL_INFO, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
  11966. } else {
  11967. err = -1;
  11968. }
  11969. MG_FREE(ssl_cert);
  11970. MG_FREE(ssl_key);
  11971. if (err != 0) return err;
  11972. }
  11973. if (ctx->ssl_ca_cert != NULL) {
  11974. if (ctx->ssl_ca_cert[0] != '\0') {
  11975. char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
  11976. if (ssl_ca_cert != NULL) {
  11977. err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
  11978. SL_SO_SECURE_FILES_CA_FILE_NAME, ssl_ca_cert,
  11979. strlen(ssl_ca_cert));
  11980. LOG(LL_INFO, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
  11981. } else {
  11982. err = -1;
  11983. }
  11984. MG_FREE(ssl_ca_cert);
  11985. if (err != 0) return err;
  11986. }
  11987. }
  11988. if (ctx->ssl_server_name != NULL) {
  11989. err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
  11990. SO_SECURE_DOMAIN_NAME_VERIFICATION,
  11991. ctx->ssl_server_name, strlen(ctx->ssl_server_name));
  11992. DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
  11993. /* Domain name verificationw as added in a NWP service pack, older
  11994. * versions return SL_ENOPROTOOPT. There isn't much we can do about it,
  11995. * so we ignore the error. */
  11996. if (err != 0 && err != SL_ENOPROTOOPT) return err;
  11997. }
  11998. }
  11999. return 0;
  12000. }
  12001. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
  12002. #ifdef MG_MODULE_LINES
  12003. #line 1 "common/platforms/lwip/mg_lwip_net_if.h"
  12004. #endif
  12005. /*
  12006. * Copyright (c) 2014-2016 Cesanta Software Limited
  12007. * All rights reserved
  12008. */
  12009. #ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
  12010. #define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
  12011. #ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  12012. #define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  12013. #endif
  12014. #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  12015. #include <stdint.h>
  12016. extern struct mg_iface_vtable mg_lwip_iface_vtable;
  12017. struct mg_lwip_conn_state {
  12018. struct mg_connection *nc;
  12019. struct mg_connection *lc;
  12020. union {
  12021. struct tcp_pcb *tcp;
  12022. struct udp_pcb *udp;
  12023. } pcb;
  12024. err_t err;
  12025. size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
  12026. struct pbuf *rx_chain; /* Chain of incoming data segments. */
  12027. size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
  12028. /* Last SSL write size, for retries. */
  12029. int last_ssl_write_size;
  12030. /* Whether MG_SIG_RECV is already pending for this connection */
  12031. int recv_pending;
  12032. };
  12033. enum mg_sig_type {
  12034. MG_SIG_CONNECT_RESULT = 1,
  12035. MG_SIG_RECV = 2,
  12036. MG_SIG_SENT_CB = 3,
  12037. MG_SIG_CLOSE_CONN = 4,
  12038. MG_SIG_TOMBSTONE = 5,
  12039. MG_SIG_ACCEPT = 6,
  12040. };
  12041. void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
  12042. /* To be implemented by the platform. */
  12043. void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
  12044. #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
  12045. #endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
  12046. #ifdef MG_MODULE_LINES
  12047. #line 1 "common/platforms/lwip/mg_lwip_net_if.c"
  12048. #endif
  12049. /*
  12050. * Copyright (c) 2014-2016 Cesanta Software Limited
  12051. * All rights reserved
  12052. */
  12053. #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  12054. #include <lwip/pbuf.h>
  12055. #include <lwip/tcp.h>
  12056. #if CS_PLATFORM != CS_P_STM32
  12057. #include <lwip/tcp_impl.h>
  12058. #endif
  12059. #include <lwip/udp.h>
  12060. /* Amalgamated: #include "common/cs_dbg.h" */
  12061. /*
  12062. * Depending on whether Mongoose is compiled with ipv6 support, use right
  12063. * lwip functions
  12064. */
  12065. #if MG_ENABLE_IPV6
  12066. #define TCP_NEW tcp_new_ip6
  12067. #define TCP_BIND tcp_bind_ip6
  12068. #define UDP_BIND udp_bind_ip6
  12069. #define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
  12070. #define SET_ADDR(dst, src) \
  12071. memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
  12072. sizeof((dst)->sin6.sin6_addr.s6_addr))
  12073. #else
  12074. #define TCP_NEW tcp_new
  12075. #define TCP_BIND tcp_bind
  12076. #define UDP_BIND udp_bind
  12077. #define IPADDR_NTOA ipaddr_ntoa
  12078. #define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = GET_IPV4(src)
  12079. #endif
  12080. /*
  12081. * If lwip is compiled with ipv6 support, then API changes even for ipv4
  12082. */
  12083. #if !defined(LWIP_IPV6) || !LWIP_IPV6
  12084. #define GET_IPV4(ipX_addr) ((ipX_addr)->addr)
  12085. #else
  12086. #define GET_IPV4(ipX_addr) ((ipX_addr)->ip4.addr)
  12087. #endif
  12088. void mg_lwip_ssl_do_hs(struct mg_connection *nc);
  12089. void mg_lwip_ssl_send(struct mg_connection *nc);
  12090. void mg_lwip_ssl_recv(struct mg_connection *nc);
  12091. void mg_lwip_if_init(struct mg_iface *iface);
  12092. void mg_lwip_if_free(struct mg_iface *iface);
  12093. void mg_lwip_if_add_conn(struct mg_connection *nc);
  12094. void mg_lwip_if_remove_conn(struct mg_connection *nc);
  12095. time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
  12096. #ifdef RTOS_SDK
  12097. extern void mgos_lock();
  12098. extern void mgos_unlock();
  12099. #else
  12100. #define mgos_lock()
  12101. #define mgos_unlock()
  12102. #endif
  12103. static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
  12104. #if LWIP_TCP_KEEPALIVE
  12105. void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
  12106. int interval, int count) {
  12107. if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
  12108. return;
  12109. }
  12110. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12111. struct tcp_pcb *tpcb = cs->pcb.tcp;
  12112. if (idle > 0 && interval > 0 && count > 0) {
  12113. tpcb->keep_idle = idle * 1000;
  12114. tpcb->keep_intvl = interval * 1000;
  12115. tpcb->keep_cnt = count;
  12116. tpcb->so_options |= SOF_KEEPALIVE;
  12117. } else {
  12118. tpcb->so_options &= ~SOF_KEEPALIVE;
  12119. }
  12120. }
  12121. #elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
  12122. #warning LWIP TCP keepalive is disabled. Please consider enabling it.
  12123. #endif /* LWIP_TCP_KEEPALIVE */
  12124. static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
  12125. struct mg_connection *nc = (struct mg_connection *) arg;
  12126. DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
  12127. tpcb->remote_port, err));
  12128. if (nc == NULL) {
  12129. tcp_abort(tpcb);
  12130. return ERR_ARG;
  12131. }
  12132. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12133. cs->err = err;
  12134. #if LWIP_TCP_KEEPALIVE
  12135. if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
  12136. #endif
  12137. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12138. return ERR_OK;
  12139. }
  12140. static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
  12141. struct mg_connection *nc = (struct mg_connection *) arg;
  12142. DBG(("%p conn error %d", nc, err));
  12143. if (nc == NULL) return;
  12144. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12145. cs->pcb.tcp = NULL; /* Has already been deallocated */
  12146. if (nc->flags & MG_F_CONNECTING) {
  12147. cs->err = err;
  12148. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12149. } else {
  12150. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12151. }
  12152. }
  12153. static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
  12154. struct pbuf *p, err_t err) {
  12155. struct mg_connection *nc = (struct mg_connection *) arg;
  12156. DBG(("%p %p %u %d", nc, tpcb, (p != NULL ? p->tot_len : 0), err));
  12157. if (p == NULL) {
  12158. if (nc != NULL) {
  12159. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12160. } else {
  12161. /* Tombstoned connection, do nothing. */
  12162. }
  12163. return ERR_OK;
  12164. } else if (nc == NULL) {
  12165. tcp_abort(tpcb);
  12166. return ERR_ARG;
  12167. }
  12168. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12169. /*
  12170. * If we get a chain of more than one segment at once, we need to bump
  12171. * refcount on the subsequent bufs to make them independent.
  12172. */
  12173. if (p->next != NULL) {
  12174. struct pbuf *q = p->next;
  12175. for (; q != NULL; q = q->next) pbuf_ref(q);
  12176. }
  12177. if (cs->rx_chain == NULL) {
  12178. cs->rx_offset = 0;
  12179. } else if (pbuf_clen(cs->rx_chain) >= 4) {
  12180. /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
  12181. * will be completely blocked. We already have at least 4 in the chain,
  12182. * this one is, so we have to make a copy and release this one. */
  12183. struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
  12184. if (np != NULL) {
  12185. pbuf_copy(np, p);
  12186. pbuf_free(p);
  12187. p = np;
  12188. }
  12189. }
  12190. mg_lwip_recv_common(nc, p);
  12191. return ERR_OK;
  12192. }
  12193. static void mg_lwip_handle_recv_tcp(struct mg_connection *nc) {
  12194. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12195. #if MG_ENABLE_SSL
  12196. if (nc->flags & MG_F_SSL) {
  12197. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  12198. mg_lwip_ssl_recv(nc);
  12199. } else {
  12200. mg_lwip_ssl_do_hs(nc);
  12201. }
  12202. return;
  12203. }
  12204. #endif
  12205. mgos_lock();
  12206. while (cs->rx_chain != NULL) {
  12207. struct pbuf *seg = cs->rx_chain;
  12208. size_t len = (seg->len - cs->rx_offset);
  12209. char *data = (char *) MG_MALLOC(len);
  12210. if (data == NULL) {
  12211. mgos_unlock();
  12212. DBG(("OOM"));
  12213. return;
  12214. }
  12215. pbuf_copy_partial(seg, data, len, cs->rx_offset);
  12216. mgos_unlock();
  12217. mg_if_recv_tcp_cb(nc, data, len, 1 /* own */);
  12218. mgos_lock();
  12219. cs->rx_offset += len;
  12220. if (cs->rx_offset == cs->rx_chain->len) {
  12221. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  12222. pbuf_free(seg);
  12223. cs->rx_offset = 0;
  12224. }
  12225. }
  12226. mgos_unlock();
  12227. if (nc->send_mbuf.len > 0) {
  12228. mg_lwip_mgr_schedule_poll(nc->mgr);
  12229. }
  12230. }
  12231. static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
  12232. u16_t num_sent) {
  12233. struct mg_connection *nc = (struct mg_connection *) arg;
  12234. DBG(("%p %p %u", nc, tpcb, num_sent));
  12235. if (nc == NULL) {
  12236. tcp_abort(tpcb);
  12237. return ERR_ABRT;
  12238. }
  12239. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12240. cs->num_sent += num_sent;
  12241. mg_lwip_post_signal(MG_SIG_SENT_CB, nc);
  12242. return ERR_OK;
  12243. }
  12244. void mg_lwip_if_connect_tcp(struct mg_connection *nc,
  12245. const union socket_address *sa) {
  12246. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12247. struct tcp_pcb *tpcb = TCP_NEW();
  12248. cs->pcb.tcp = tpcb;
  12249. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  12250. u16_t port = ntohs(sa->sin.sin_port);
  12251. tcp_arg(tpcb, nc);
  12252. tcp_err(tpcb, mg_lwip_tcp_error_cb);
  12253. tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
  12254. tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
  12255. cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
  12256. DBG(("%p tcp_bind = %d", nc, cs->err));
  12257. if (cs->err != ERR_OK) {
  12258. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12259. return;
  12260. }
  12261. cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
  12262. DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err));
  12263. if (cs->err != ERR_OK) {
  12264. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12265. return;
  12266. }
  12267. }
  12268. /*
  12269. * Lwip included in the SDKs for nRF5x chips has different type for the
  12270. * callback of `udp_recv()`
  12271. */
  12272. #if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52 || \
  12273. CS_PLATFORM == CS_P_STM32
  12274. static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
  12275. const ip_addr_t *addr, u16_t port)
  12276. #else
  12277. static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
  12278. ip_addr_t *addr, u16_t port)
  12279. #endif
  12280. {
  12281. struct mg_connection *nc = (struct mg_connection *) arg;
  12282. DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
  12283. /* Put address in a separate pbuf and tack it onto the packet. */
  12284. struct pbuf *sap =
  12285. pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
  12286. if (sap == NULL) {
  12287. pbuf_free(p);
  12288. return;
  12289. }
  12290. union socket_address *sa = (union socket_address *) sap->payload;
  12291. sa->sin.sin_addr.s_addr = addr->addr;
  12292. sa->sin.sin_port = htons(port);
  12293. /* Logic in the recv handler requires that there be exactly one data pbuf. */
  12294. p = pbuf_coalesce(p, PBUF_RAW);
  12295. pbuf_chain(sap, p);
  12296. mg_lwip_recv_common(nc, sap);
  12297. (void) pcb;
  12298. }
  12299. static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
  12300. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12301. mgos_lock();
  12302. if (cs->rx_chain == NULL) {
  12303. cs->rx_chain = p;
  12304. } else {
  12305. pbuf_chain(cs->rx_chain, p);
  12306. }
  12307. if (!cs->recv_pending) {
  12308. cs->recv_pending = 1;
  12309. mg_lwip_post_signal(MG_SIG_RECV, nc);
  12310. }
  12311. mgos_unlock();
  12312. }
  12313. static void mg_lwip_handle_recv_udp(struct mg_connection *nc) {
  12314. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12315. /*
  12316. * For UDP, RX chain consists of interleaved address and packet bufs:
  12317. * Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
  12318. */
  12319. while (cs->rx_chain != NULL) {
  12320. struct pbuf *sap = cs->rx_chain;
  12321. struct pbuf *p = sap->next;
  12322. cs->rx_chain = pbuf_dechain(p);
  12323. size_t data_len = p->len;
  12324. char *data = (char *) MG_MALLOC(data_len);
  12325. if (data != NULL) {
  12326. pbuf_copy_partial(p, data, data_len, 0);
  12327. pbuf_free(p);
  12328. mg_if_recv_udp_cb(nc, data, data_len,
  12329. (union socket_address *) sap->payload, sap->len);
  12330. pbuf_free(sap);
  12331. } else {
  12332. pbuf_free(p);
  12333. pbuf_free(sap);
  12334. }
  12335. }
  12336. }
  12337. void mg_lwip_if_connect_udp(struct mg_connection *nc) {
  12338. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12339. struct udp_pcb *upcb = udp_new();
  12340. cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
  12341. DBG(("%p udp_bind %p = %d", nc, upcb, cs->err));
  12342. if (cs->err == ERR_OK) {
  12343. udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
  12344. cs->pcb.udp = upcb;
  12345. } else {
  12346. udp_remove(upcb);
  12347. }
  12348. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12349. }
  12350. void mg_lwip_accept_conn(struct mg_connection *nc, struct tcp_pcb *tpcb) {
  12351. union socket_address sa;
  12352. SET_ADDR(&sa, &tpcb->remote_ip);
  12353. sa.sin.sin_port = htons(tpcb->remote_port);
  12354. mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
  12355. }
  12356. void mg_lwip_handle_accept(struct mg_connection *nc) {
  12357. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12358. #if MG_ENABLE_SSL
  12359. if (cs->lc->flags & MG_F_SSL) {
  12360. if (mg_ssl_if_conn_accept(nc, cs->lc) != MG_SSL_OK) {
  12361. LOG(LL_ERROR, ("SSL error"));
  12362. tcp_close(cs->pcb.tcp);
  12363. }
  12364. } else
  12365. #endif
  12366. {
  12367. mg_lwip_accept_conn(nc, cs->pcb.tcp);
  12368. }
  12369. }
  12370. static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
  12371. struct mg_connection *lc = (struct mg_connection *) arg;
  12372. DBG(("%p conn %p from %s:%u", lc, newtpcb,
  12373. IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
  12374. struct mg_connection *nc = mg_if_accept_new_conn(lc);
  12375. if (nc == NULL) {
  12376. tcp_abort(newtpcb);
  12377. return ERR_ABRT;
  12378. }
  12379. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12380. cs->lc = lc;
  12381. cs->pcb.tcp = newtpcb;
  12382. /* We need to set up callbacks before returning because data may start
  12383. * arriving immediately. */
  12384. tcp_arg(newtpcb, nc);
  12385. tcp_err(newtpcb, mg_lwip_tcp_error_cb);
  12386. tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
  12387. tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
  12388. #if LWIP_TCP_KEEPALIVE
  12389. mg_lwip_set_keepalive_params(nc, 60, 10, 6);
  12390. #endif
  12391. mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
  12392. (void) err;
  12393. return ERR_OK;
  12394. }
  12395. int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  12396. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12397. struct tcp_pcb *tpcb = TCP_NEW();
  12398. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  12399. u16_t port = ntohs(sa->sin.sin_port);
  12400. cs->err = TCP_BIND(tpcb, ip, port);
  12401. DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
  12402. if (cs->err != ERR_OK) {
  12403. tcp_close(tpcb);
  12404. return -1;
  12405. }
  12406. tcp_arg(tpcb, nc);
  12407. tpcb = tcp_listen(tpcb);
  12408. cs->pcb.tcp = tpcb;
  12409. tcp_accept(tpcb, mg_lwip_accept_cb);
  12410. return 0;
  12411. }
  12412. int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  12413. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12414. struct udp_pcb *upcb = udp_new();
  12415. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  12416. u16_t port = ntohs(sa->sin.sin_port);
  12417. cs->err = UDP_BIND(upcb, ip, port);
  12418. DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
  12419. if (cs->err != ERR_OK) {
  12420. udp_remove(upcb);
  12421. return -1;
  12422. }
  12423. udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
  12424. cs->pcb.udp = upcb;
  12425. return 0;
  12426. }
  12427. int mg_lwip_tcp_write(struct mg_connection *nc, const void *data,
  12428. uint16_t len) {
  12429. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12430. struct tcp_pcb *tpcb = cs->pcb.tcp;
  12431. len = MIN(tpcb->mss, MIN(len, tpcb->snd_buf));
  12432. if (len == 0) {
  12433. DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf,
  12434. tpcb->snd_queuelen, tpcb->unsent, tpcb->unacked));
  12435. tcp_output(tpcb);
  12436. return 0;
  12437. }
  12438. /*
  12439. * On ESP8266 we only allow one TCP segment in flight at any given time.
  12440. * This may increase latency and reduce efficiency of tcp windowing,
  12441. * but memory is scarce and precious on that platform so we do this to
  12442. * reduce footprint.
  12443. */
  12444. #if CS_PLATFORM == CS_P_ESP8266
  12445. if (tpcb->unacked != NULL) {
  12446. return 0;
  12447. }
  12448. if (tpcb->unsent != NULL) {
  12449. len = MIN(len, (TCP_MSS - tpcb->unsent->len));
  12450. }
  12451. #endif
  12452. err_t err = tcp_write(tpcb, data, len, TCP_WRITE_FLAG_COPY);
  12453. DBG(("%p tcp_write %u = %d", tpcb, len, err));
  12454. if (err != ERR_OK) {
  12455. /*
  12456. * We ignore ERR_MEM because memory will be freed up when the data is sent
  12457. * and we'll retry.
  12458. */
  12459. return (err == ERR_MEM ? 0 : -1);
  12460. }
  12461. return len;
  12462. }
  12463. static void mg_lwip_send_more(struct mg_connection *nc) {
  12464. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12465. if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) {
  12466. DBG(("%p invalid socket", nc));
  12467. return;
  12468. }
  12469. int num_written = mg_lwip_tcp_write(nc, nc->send_mbuf.buf, nc->send_mbuf.len);
  12470. DBG(("%p mg_lwip_tcp_write %u = %d", nc, nc->send_mbuf.len, num_written));
  12471. if (num_written == 0) return;
  12472. if (num_written < 0) {
  12473. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12474. }
  12475. mbuf_remove(&nc->send_mbuf, num_written);
  12476. mbuf_trim(&nc->send_mbuf);
  12477. }
  12478. void mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf,
  12479. size_t len) {
  12480. mbuf_append(&nc->send_mbuf, buf, len);
  12481. mg_lwip_mgr_schedule_poll(nc->mgr);
  12482. }
  12483. void mg_lwip_if_udp_send(struct mg_connection *nc, const void *buf,
  12484. size_t len) {
  12485. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12486. if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) {
  12487. /*
  12488. * In case of UDP, this usually means, what
  12489. * async DNS resolve is still in progress and connection
  12490. * is not ready yet
  12491. */
  12492. DBG(("%p socket is not connected", nc));
  12493. return;
  12494. }
  12495. struct udp_pcb *upcb = cs->pcb.udp;
  12496. struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
  12497. ip_addr_t *ip = (ip_addr_t *) &nc->sa.sin.sin_addr.s_addr;
  12498. u16_t port = ntohs(nc->sa.sin.sin_port);
  12499. if (p == NULL) {
  12500. DBG(("OOM"));
  12501. return;
  12502. }
  12503. memcpy(p->payload, buf, len);
  12504. cs->err = udp_sendto(upcb, p, (ip_addr_t *) ip, port);
  12505. DBG(("%p udp_sendto = %d", nc, cs->err));
  12506. pbuf_free(p);
  12507. if (cs->err != ERR_OK) {
  12508. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12509. } else {
  12510. cs->num_sent += len;
  12511. mg_lwip_post_signal(MG_SIG_SENT_CB, nc);
  12512. }
  12513. }
  12514. void mg_lwip_if_recved(struct mg_connection *nc, size_t len) {
  12515. if (nc->flags & MG_F_UDP) return;
  12516. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12517. if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) {
  12518. DBG(("%p invalid socket", nc));
  12519. return;
  12520. }
  12521. DBG(("%p %p %u", nc, cs->pcb.tcp, len));
  12522. /* Currently SSL acknowledges data immediately.
  12523. * TODO(rojer): Find a way to propagate mg_lwip_if_recved. */
  12524. #if MG_ENABLE_SSL
  12525. if (!(nc->flags & MG_F_SSL)) {
  12526. tcp_recved(cs->pcb.tcp, len);
  12527. }
  12528. #else
  12529. tcp_recved(cs->pcb.tcp, len);
  12530. #endif
  12531. mbuf_trim(&nc->recv_mbuf);
  12532. }
  12533. int mg_lwip_if_create_conn(struct mg_connection *nc) {
  12534. struct mg_lwip_conn_state *cs =
  12535. (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
  12536. if (cs == NULL) return 0;
  12537. cs->nc = nc;
  12538. nc->sock = (intptr_t) cs;
  12539. return 1;
  12540. }
  12541. void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
  12542. if (nc->sock == INVALID_SOCKET) return;
  12543. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12544. if (!(nc->flags & MG_F_UDP)) {
  12545. struct tcp_pcb *tpcb = cs->pcb.tcp;
  12546. if (tpcb != NULL) {
  12547. tcp_arg(tpcb, NULL);
  12548. DBG(("%p tcp_close %p", nc, tpcb));
  12549. tcp_arg(tpcb, NULL);
  12550. tcp_close(tpcb);
  12551. }
  12552. while (cs->rx_chain != NULL) {
  12553. struct pbuf *seg = cs->rx_chain;
  12554. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  12555. pbuf_free(seg);
  12556. }
  12557. memset(cs, 0, sizeof(*cs));
  12558. MG_FREE(cs);
  12559. } else if (nc->listener == NULL) {
  12560. /* Only close outgoing UDP pcb or listeners. */
  12561. struct udp_pcb *upcb = cs->pcb.udp;
  12562. if (upcb != NULL) {
  12563. DBG(("%p udp_remove %p", nc, upcb));
  12564. udp_remove(upcb);
  12565. }
  12566. memset(cs, 0, sizeof(*cs));
  12567. MG_FREE(cs);
  12568. }
  12569. nc->sock = INVALID_SOCKET;
  12570. }
  12571. void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
  12572. union socket_address *sa) {
  12573. memset(sa, 0, sizeof(*sa));
  12574. if (nc->sock == INVALID_SOCKET) return;
  12575. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12576. if (nc->flags & MG_F_UDP) {
  12577. struct udp_pcb *upcb = cs->pcb.udp;
  12578. if (remote) {
  12579. memcpy(sa, &nc->sa, sizeof(*sa));
  12580. } else {
  12581. sa->sin.sin_port = htons(upcb->local_port);
  12582. SET_ADDR(sa, &upcb->local_ip);
  12583. }
  12584. } else {
  12585. struct tcp_pcb *tpcb = cs->pcb.tcp;
  12586. if (remote) {
  12587. sa->sin.sin_port = htons(tpcb->remote_port);
  12588. SET_ADDR(sa, &tpcb->remote_ip);
  12589. } else {
  12590. sa->sin.sin_port = htons(tpcb->local_port);
  12591. SET_ADDR(sa, &tpcb->local_ip);
  12592. }
  12593. }
  12594. }
  12595. void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
  12596. nc->sock = sock;
  12597. }
  12598. /* clang-format off */
  12599. #define MG_LWIP_IFACE_VTABLE \
  12600. { \
  12601. mg_lwip_if_init, \
  12602. mg_lwip_if_free, \
  12603. mg_lwip_if_add_conn, \
  12604. mg_lwip_if_remove_conn, \
  12605. mg_lwip_if_poll, \
  12606. mg_lwip_if_listen_tcp, \
  12607. mg_lwip_if_listen_udp, \
  12608. mg_lwip_if_connect_tcp, \
  12609. mg_lwip_if_connect_udp, \
  12610. mg_lwip_if_tcp_send, \
  12611. mg_lwip_if_udp_send, \
  12612. mg_lwip_if_recved, \
  12613. mg_lwip_if_create_conn, \
  12614. mg_lwip_if_destroy_conn, \
  12615. mg_lwip_if_sock_set, \
  12616. mg_lwip_if_get_conn_addr, \
  12617. }
  12618. /* clang-format on */
  12619. struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
  12620. #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  12621. struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
  12622. #endif
  12623. #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
  12624. #ifdef MG_MODULE_LINES
  12625. #line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
  12626. #endif
  12627. /*
  12628. * Copyright (c) 2014-2016 Cesanta Software Limited
  12629. * All rights reserved
  12630. */
  12631. #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  12632. #ifndef MG_SIG_QUEUE_LEN
  12633. #define MG_SIG_QUEUE_LEN 32
  12634. #endif
  12635. struct mg_ev_mgr_lwip_signal {
  12636. int sig;
  12637. struct mg_connection *nc;
  12638. };
  12639. struct mg_ev_mgr_lwip_data {
  12640. struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
  12641. int sig_queue_len;
  12642. int start_index;
  12643. };
  12644. void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
  12645. struct mg_ev_mgr_lwip_data *md =
  12646. (struct mg_ev_mgr_lwip_data *) nc->iface->data;
  12647. mgos_lock();
  12648. if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
  12649. mgos_unlock();
  12650. return;
  12651. }
  12652. int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
  12653. md->sig_queue[end_index].sig = sig;
  12654. md->sig_queue[end_index].nc = nc;
  12655. md->sig_queue_len++;
  12656. mg_lwip_mgr_schedule_poll(nc->mgr);
  12657. mgos_unlock();
  12658. }
  12659. void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
  12660. struct mg_ev_mgr_lwip_data *md =
  12661. (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
  12662. while (md->sig_queue_len > 0) {
  12663. mgos_lock();
  12664. int sig = md->sig_queue[md->start_index].sig;
  12665. struct mg_connection *nc = md->sig_queue[md->start_index].nc;
  12666. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12667. md->start_index = (md->start_index + 1) % MG_SIG_QUEUE_LEN;
  12668. md->sig_queue_len--;
  12669. mgos_unlock();
  12670. if (nc->iface == NULL || nc->mgr == NULL) continue;
  12671. switch (sig) {
  12672. case MG_SIG_CONNECT_RESULT: {
  12673. #if MG_ENABLE_SSL
  12674. if (cs->err == 0 && (nc->flags & MG_F_SSL) &&
  12675. !(nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
  12676. mg_lwip_ssl_do_hs(nc);
  12677. } else
  12678. #endif
  12679. {
  12680. mg_if_connect_cb(nc, cs->err);
  12681. }
  12682. break;
  12683. }
  12684. case MG_SIG_CLOSE_CONN: {
  12685. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  12686. mg_close_conn(nc);
  12687. break;
  12688. }
  12689. case MG_SIG_RECV: {
  12690. cs->recv_pending = 0;
  12691. if (nc->flags & MG_F_UDP) {
  12692. mg_lwip_handle_recv_udp(nc);
  12693. } else {
  12694. mg_lwip_handle_recv_tcp(nc);
  12695. }
  12696. break;
  12697. }
  12698. case MG_SIG_SENT_CB: {
  12699. if (cs->num_sent > 0) mg_if_sent_cb(nc, cs->num_sent);
  12700. cs->num_sent = 0;
  12701. if (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE) &&
  12702. !(nc->flags & MG_F_WANT_WRITE)) {
  12703. mg_close_conn(nc);
  12704. }
  12705. break;
  12706. }
  12707. case MG_SIG_TOMBSTONE: {
  12708. break;
  12709. }
  12710. case MG_SIG_ACCEPT: {
  12711. mg_lwip_handle_accept(nc);
  12712. break;
  12713. }
  12714. }
  12715. }
  12716. }
  12717. void mg_lwip_if_init(struct mg_iface *iface) {
  12718. LOG(LL_INFO, ("%p Mongoose init"));
  12719. iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
  12720. }
  12721. void mg_lwip_if_free(struct mg_iface *iface) {
  12722. MG_FREE(iface->data);
  12723. iface->data = NULL;
  12724. }
  12725. void mg_lwip_if_add_conn(struct mg_connection *nc) {
  12726. (void) nc;
  12727. }
  12728. void mg_lwip_if_remove_conn(struct mg_connection *nc) {
  12729. struct mg_ev_mgr_lwip_data *md =
  12730. (struct mg_ev_mgr_lwip_data *) nc->iface->data;
  12731. /* Walk the queue and null-out further signals for this conn. */
  12732. for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
  12733. if (md->sig_queue[i].nc == nc) {
  12734. md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
  12735. }
  12736. }
  12737. }
  12738. time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
  12739. struct mg_mgr *mgr = iface->mgr;
  12740. int n = 0;
  12741. double now = mg_time();
  12742. struct mg_connection *nc, *tmp;
  12743. double min_timer = 0;
  12744. int num_timers = 0;
  12745. #if 0
  12746. DBG(("begin poll @%u", (unsigned int) (now * 1000)));
  12747. #endif
  12748. mg_ev_mgr_lwip_process_signals(mgr);
  12749. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  12750. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12751. tmp = nc->next;
  12752. n++;
  12753. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  12754. ((nc->flags & MG_F_SEND_AND_CLOSE) && (nc->flags & MG_F_UDP) &&
  12755. (nc->send_mbuf.len == 0))) {
  12756. mg_close_conn(nc);
  12757. continue;
  12758. }
  12759. mg_if_poll(nc, now);
  12760. mg_if_timer(nc, now);
  12761. #if MG_ENABLE_SSL
  12762. if ((nc->flags & MG_F_SSL) && cs != NULL && cs->pcb.tcp != NULL &&
  12763. cs->pcb.tcp->state == ESTABLISHED) {
  12764. if (((nc->flags & MG_F_WANT_WRITE) ||
  12765. ((nc->send_mbuf.len > 0) &&
  12766. (nc->flags & MG_F_SSL_HANDSHAKE_DONE))) &&
  12767. cs->pcb.tcp->snd_buf > 0) {
  12768. /* Can write more. */
  12769. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  12770. if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_send(nc);
  12771. } else {
  12772. mg_lwip_ssl_do_hs(nc);
  12773. }
  12774. }
  12775. if (cs->rx_chain != NULL || (nc->flags & MG_F_WANT_READ)) {
  12776. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  12777. if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_recv(nc);
  12778. } else {
  12779. mg_lwip_ssl_do_hs(nc);
  12780. }
  12781. }
  12782. } else
  12783. #endif /* MG_ENABLE_SSL */
  12784. {
  12785. if (!(nc->flags & (MG_F_CONNECTING | MG_F_UDP))) {
  12786. if (nc->send_mbuf.len > 0) mg_lwip_send_more(nc);
  12787. }
  12788. }
  12789. if (nc->sock != INVALID_SOCKET &&
  12790. !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
  12791. cs->pcb.tcp->unsent != NULL) {
  12792. tcp_output(cs->pcb.tcp);
  12793. }
  12794. if (nc->ev_timer_time > 0) {
  12795. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  12796. min_timer = nc->ev_timer_time;
  12797. }
  12798. num_timers++;
  12799. }
  12800. }
  12801. #if 0
  12802. DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
  12803. (unsigned int) (now * 1000), n, num_timers,
  12804. (unsigned int) (min_timer * 1000), timeout_ms));
  12805. #endif
  12806. (void) timeout_ms;
  12807. return now;
  12808. }
  12809. uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr) {
  12810. struct mg_connection *nc;
  12811. double now = mg_time();
  12812. double min_timer = 0;
  12813. int num_timers = 0;
  12814. mg_ev_mgr_lwip_process_signals(mgr);
  12815. for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
  12816. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12817. if (nc->ev_timer_time > 0) {
  12818. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  12819. min_timer = nc->ev_timer_time;
  12820. }
  12821. num_timers++;
  12822. }
  12823. if (nc->send_mbuf.len > 0) {
  12824. int can_send = 0;
  12825. /* We have stuff to send, but can we? */
  12826. if (nc->flags & MG_F_UDP) {
  12827. /* UDP is always ready for sending. */
  12828. can_send = (cs->pcb.udp != NULL);
  12829. } else {
  12830. can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
  12831. }
  12832. /* We want and can send, request a poll immediately. */
  12833. if (can_send) return 0;
  12834. }
  12835. }
  12836. uint32_t timeout_ms = ~0;
  12837. if (num_timers > 0) {
  12838. double timer_timeout_ms = (min_timer - now) * 1000 + 1 /* rounding */;
  12839. if (timer_timeout_ms < timeout_ms) {
  12840. timeout_ms = timer_timeout_ms;
  12841. }
  12842. }
  12843. return timeout_ms;
  12844. }
  12845. #endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
  12846. #ifdef MG_MODULE_LINES
  12847. #line 1 "common/platforms/lwip/mg_lwip_ssl_if.c"
  12848. #endif
  12849. /*
  12850. * Copyright (c) 2014-2016 Cesanta Software Limited
  12851. * All rights reserved
  12852. */
  12853. #if MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  12854. /* Amalgamated: #include "common/cs_dbg.h" */
  12855. #include <lwip/pbuf.h>
  12856. #include <lwip/tcp.h>
  12857. #ifndef MG_LWIP_SSL_IO_SIZE
  12858. #define MG_LWIP_SSL_IO_SIZE 1024
  12859. #endif
  12860. /*
  12861. * Stop processing incoming SSL traffic when recv_mbuf.size is this big.
  12862. * It'a a uick solution for SSL recv pushback.
  12863. */
  12864. #ifndef MG_LWIP_SSL_RECV_MBUF_LIMIT
  12865. #define MG_LWIP_SSL_RECV_MBUF_LIMIT 3072
  12866. #endif
  12867. #ifndef MIN
  12868. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  12869. #endif
  12870. void mg_lwip_ssl_do_hs(struct mg_connection *nc) {
  12871. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12872. int server_side = (nc->listener != NULL);
  12873. enum mg_ssl_if_result res;
  12874. if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
  12875. res = mg_ssl_if_handshake(nc);
  12876. DBG(("%p %d %d %d", nc, nc->flags, server_side, res));
  12877. if (res != MG_SSL_OK) {
  12878. if (res == MG_SSL_WANT_WRITE) {
  12879. nc->flags |= MG_F_WANT_WRITE;
  12880. cs->err = 0;
  12881. } else if (res == MG_SSL_WANT_READ) {
  12882. /*
  12883. * Nothing to do in particular, we are callback-driven.
  12884. * What we definitely do not need anymore is SSL reading (nothing left).
  12885. */
  12886. nc->flags &= ~MG_F_WANT_READ;
  12887. cs->err = 0;
  12888. } else {
  12889. cs->err = res;
  12890. if (server_side) {
  12891. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12892. } else {
  12893. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12894. }
  12895. }
  12896. } else {
  12897. cs->err = 0;
  12898. nc->flags &= ~MG_F_WANT_WRITE;
  12899. /*
  12900. * Handshake is done. Schedule a read immediately to consume app data
  12901. * which may already be waiting.
  12902. */
  12903. nc->flags |= (MG_F_SSL_HANDSHAKE_DONE | MG_F_WANT_READ);
  12904. if (server_side) {
  12905. mg_lwip_accept_conn(nc, cs->pcb.tcp);
  12906. } else {
  12907. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12908. }
  12909. }
  12910. }
  12911. void mg_lwip_ssl_send(struct mg_connection *nc) {
  12912. if (nc->sock == INVALID_SOCKET) {
  12913. DBG(("%p invalid socket", nc));
  12914. return;
  12915. }
  12916. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12917. /* It's ok if the buffer is empty. Return value of 0 may also be valid. */
  12918. int len = cs->last_ssl_write_size;
  12919. if (len == 0) {
  12920. len = MIN(MG_LWIP_SSL_IO_SIZE, nc->send_mbuf.len);
  12921. }
  12922. int ret = mg_ssl_if_write(nc, nc->send_mbuf.buf, len);
  12923. DBG(("%p SSL_write %u = %d, %d", nc, len, ret));
  12924. if (ret > 0) {
  12925. mbuf_remove(&nc->send_mbuf, ret);
  12926. mbuf_trim(&nc->send_mbuf);
  12927. cs->last_ssl_write_size = 0;
  12928. } else if (ret < 0) {
  12929. /* This is tricky. We must remember the exact data we were sending to retry
  12930. * exactly the same send next time. */
  12931. cs->last_ssl_write_size = len;
  12932. }
  12933. if (ret == len) {
  12934. nc->flags &= ~MG_F_WANT_WRITE;
  12935. } else if (ret == MG_SSL_WANT_WRITE) {
  12936. nc->flags |= MG_F_WANT_WRITE;
  12937. } else {
  12938. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12939. }
  12940. }
  12941. void mg_lwip_ssl_recv(struct mg_connection *nc) {
  12942. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12943. /* Don't deliver data before connect callback */
  12944. if (nc->flags & MG_F_CONNECTING) return;
  12945. while (nc->recv_mbuf.len < MG_LWIP_SSL_RECV_MBUF_LIMIT) {
  12946. char *buf = (char *) MG_MALLOC(MG_LWIP_SSL_IO_SIZE);
  12947. if (buf == NULL) return;
  12948. int ret = mg_ssl_if_read(nc, buf, MG_LWIP_SSL_IO_SIZE);
  12949. DBG(("%p %p SSL_read %u = %d", nc, cs->rx_chain, MG_LWIP_SSL_IO_SIZE, ret));
  12950. if (ret <= 0) {
  12951. MG_FREE(buf);
  12952. if (ret == MG_SSL_WANT_WRITE) {
  12953. nc->flags |= MG_F_WANT_WRITE;
  12954. return;
  12955. } else if (ret == MG_SSL_WANT_READ) {
  12956. /*
  12957. * Nothing to do in particular, we are callback-driven.
  12958. * What we definitely do not need anymore is SSL reading (nothing left).
  12959. */
  12960. nc->flags &= ~MG_F_WANT_READ;
  12961. cs->err = 0;
  12962. return;
  12963. } else {
  12964. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12965. return;
  12966. }
  12967. } else {
  12968. mg_if_recv_tcp_cb(nc, buf, ret, 1 /* own */);
  12969. }
  12970. }
  12971. }
  12972. #ifdef KR_VERSION
  12973. ssize_t kr_send(int fd, const void *buf, size_t len) {
  12974. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
  12975. int ret = mg_lwip_tcp_write(cs->nc, buf, len);
  12976. DBG(("%p mg_lwip_tcp_write %u = %d", cs->nc, len, ret));
  12977. if (ret == 0) ret = KR_IO_WOULDBLOCK;
  12978. return ret;
  12979. }
  12980. ssize_t kr_recv(int fd, void *buf, size_t len) {
  12981. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
  12982. struct pbuf *seg = cs->rx_chain;
  12983. if (seg == NULL) {
  12984. DBG(("%u - nothing to read", len));
  12985. return KR_IO_WOULDBLOCK;
  12986. }
  12987. size_t seg_len = (seg->len - cs->rx_offset);
  12988. DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
  12989. len = MIN(len, seg_len);
  12990. pbuf_copy_partial(seg, buf, len, cs->rx_offset);
  12991. cs->rx_offset += len;
  12992. tcp_recved(cs->pcb.tcp, len);
  12993. if (cs->rx_offset == cs->rx_chain->len) {
  12994. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  12995. pbuf_free(seg);
  12996. cs->rx_offset = 0;
  12997. }
  12998. return len;
  12999. }
  13000. #elif MG_SSL_IF == MG_SSL_IF_MBEDTLS
  13001. int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
  13002. struct mg_connection *nc = (struct mg_connection *) ctx;
  13003. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13004. int ret = mg_lwip_tcp_write(cs->nc, buf, len);
  13005. LOG(LL_DEBUG, ("%p %d -> %d", nc, len, ret));
  13006. if (ret == 0) ret = MBEDTLS_ERR_SSL_WANT_WRITE;
  13007. return ret;
  13008. }
  13009. int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
  13010. struct mg_connection *nc = (struct mg_connection *) ctx;
  13011. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13012. struct pbuf *seg = cs->rx_chain;
  13013. if (seg == NULL) {
  13014. DBG(("%u - nothing to read", len));
  13015. return MBEDTLS_ERR_SSL_WANT_READ;
  13016. }
  13017. size_t seg_len = (seg->len - cs->rx_offset);
  13018. DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
  13019. len = MIN(len, seg_len);
  13020. pbuf_copy_partial(seg, buf, len, cs->rx_offset);
  13021. cs->rx_offset += len;
  13022. /* TCP PCB may be NULL if connection has already been closed
  13023. * but we still have data to deliver to SSL. */
  13024. if (cs->pcb.tcp != NULL) tcp_recved(cs->pcb.tcp, len);
  13025. if (cs->rx_offset == cs->rx_chain->len) {
  13026. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  13027. pbuf_free(seg);
  13028. cs->rx_offset = 0;
  13029. }
  13030. LOG(LL_DEBUG, ("%p <- %d", nc, (int) len));
  13031. return len;
  13032. }
  13033. #endif
  13034. #endif /* MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
  13035. #ifdef MG_MODULE_LINES
  13036. #line 1 "common/platforms/wince/wince_libc.c"
  13037. #endif
  13038. /*
  13039. * Copyright (c) 2016 Cesanta Software Limited
  13040. * All rights reserved
  13041. */
  13042. #ifdef WINCE
  13043. const char *strerror(int err) {
  13044. /*
  13045. * TODO(alashkin): there is no strerror on WinCE;
  13046. * look for similar wce_xxxx function
  13047. */
  13048. static char buf[10];
  13049. snprintf(buf, sizeof(buf), "%d", err);
  13050. return buf;
  13051. }
  13052. int open(const char *filename, int oflag, int pmode) {
  13053. /*
  13054. * TODO(alashkin): mg_open function is not used in mongoose
  13055. * but exists in documentation as utility function
  13056. * Shall we delete it at all or implement for WinCE as well?
  13057. */
  13058. DebugBreak();
  13059. return 0; /* for compiler */
  13060. }
  13061. int _wstati64(const wchar_t *path, cs_stat_t *st) {
  13062. DWORD fa = GetFileAttributesW(path);
  13063. if (fa == INVALID_FILE_ATTRIBUTES) {
  13064. return -1;
  13065. }
  13066. memset(st, 0, sizeof(*st));
  13067. if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
  13068. HANDLE h;
  13069. FILETIME ftime;
  13070. st->st_mode |= _S_IFREG;
  13071. h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
  13072. FILE_ATTRIBUTE_NORMAL, NULL);
  13073. if (h == INVALID_HANDLE_VALUE) {
  13074. return -1;
  13075. }
  13076. st->st_size = GetFileSize(h, NULL);
  13077. GetFileTime(h, NULL, NULL, &ftime);
  13078. st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
  13079. ((uint64_t) ftime.dwHighDateTime << 32)) /
  13080. 10000000.0) -
  13081. 11644473600);
  13082. CloseHandle(h);
  13083. } else {
  13084. st->st_mode |= _S_IFDIR;
  13085. }
  13086. return 0;
  13087. }
  13088. /* Windows CE doesn't have neither gmtime nor strftime */
  13089. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  13090. FILETIME ft;
  13091. SYSTEMTIME systime;
  13092. if (t != NULL) {
  13093. uint64_t filetime = (*t + 11644473600) * 10000000;
  13094. ft.dwLowDateTime = filetime & 0xFFFFFFFF;
  13095. ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
  13096. FileTimeToSystemTime(&ft, &systime);
  13097. } else {
  13098. GetSystemTime(&systime);
  13099. }
  13100. /* There is no PRIu16 in WinCE SDK */
  13101. snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
  13102. (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
  13103. (int) systime.wMinute, (int) systime.wSecond);
  13104. }
  13105. #endif
  13106. #ifdef MG_MODULE_LINES
  13107. #line 1 "common/platforms/pic32/pic32_net_if.h"
  13108. #endif
  13109. /*
  13110. * Copyright (c) 2014-2016 Cesanta Software Limited
  13111. * All rights reserved
  13112. */
  13113. #ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
  13114. #define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
  13115. /* Amalgamated: #include "mongoose/src/net_if.h" */
  13116. #ifdef __cplusplus
  13117. extern "C" {
  13118. #endif /* __cplusplus */
  13119. #ifndef MG_ENABLE_NET_IF_PIC32
  13120. #define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
  13121. #endif
  13122. extern struct mg_iface_vtable mg_pic32_iface_vtable;
  13123. #ifdef __cplusplus
  13124. }
  13125. #endif /* __cplusplus */
  13126. #endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
  13127. #ifdef MG_MODULE_LINES
  13128. #line 1 "common/platforms/pic32/pic32_net_if.c"
  13129. #endif
  13130. /*
  13131. * Copyright (c) 2014-2016 Cesanta Software Limited
  13132. * All rights reserved
  13133. */
  13134. #if MG_ENABLE_NET_IF_PIC32
  13135. int mg_pic32_if_create_conn(struct mg_connection *nc) {
  13136. (void) nc;
  13137. return 1;
  13138. }
  13139. void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
  13140. (void) nc;
  13141. (void) len;
  13142. }
  13143. void mg_pic32_if_add_conn(struct mg_connection *nc) {
  13144. (void) nc;
  13145. }
  13146. void mg_pic32_if_init(struct mg_iface *iface) {
  13147. (void) iface;
  13148. (void) mg_get_errno(); /* Shutup compiler */
  13149. }
  13150. void mg_pic32_if_free(struct mg_iface *iface) {
  13151. (void) iface;
  13152. }
  13153. void mg_pic32_if_remove_conn(struct mg_connection *nc) {
  13154. (void) nc;
  13155. }
  13156. void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
  13157. if (nc->sock == INVALID_SOCKET) return;
  13158. /* For UDP, only close outgoing sockets or listeners. */
  13159. if (!(nc->flags & MG_F_UDP)) {
  13160. /* Close TCP */
  13161. TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
  13162. } else if (nc->listener == NULL) {
  13163. /* Only close outgoing UDP or listeners. */
  13164. TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
  13165. }
  13166. nc->sock = INVALID_SOCKET;
  13167. }
  13168. int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  13169. nc->sock = TCPIP_UDP_ServerOpen(
  13170. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  13171. : IP_ADDRESS_TYPE_IPV6,
  13172. ntohs(sa->sin.sin_port),
  13173. sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
  13174. if (nc->sock == INVALID_SOCKET) {
  13175. return -1;
  13176. }
  13177. return 0;
  13178. }
  13179. void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
  13180. size_t len) {
  13181. mbuf_append(&nc->send_mbuf, buf, len);
  13182. }
  13183. void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
  13184. size_t len) {
  13185. mbuf_append(&nc->send_mbuf, buf, len);
  13186. }
  13187. int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  13188. nc->sock = TCPIP_TCP_ServerOpen(
  13189. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  13190. : IP_ADDRESS_TYPE_IPV6,
  13191. ntohs(sa->sin.sin_port),
  13192. sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
  13193. memcpy(&nc->sa, sa, sizeof(*sa));
  13194. if (nc->sock == INVALID_SOCKET) {
  13195. return -1;
  13196. }
  13197. return 0;
  13198. }
  13199. static int mg_accept_conn(struct mg_connection *lc) {
  13200. struct mg_connection *nc;
  13201. TCP_SOCKET_INFO si;
  13202. union socket_address sa;
  13203. nc = mg_if_accept_new_conn(lc);
  13204. if (nc == NULL) {
  13205. return 0;
  13206. }
  13207. nc->sock = lc->sock;
  13208. nc->flags &= ~MG_F_LISTENING;
  13209. if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
  13210. return 0;
  13211. }
  13212. if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
  13213. sa.sin.sin_family = AF_INET;
  13214. sa.sin.sin_port = htons(si.remotePort);
  13215. sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
  13216. } else {
  13217. /* TODO(alashkin): do something with _potential_ IPv6 */
  13218. memset(&sa, 0, sizeof(sa));
  13219. }
  13220. mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
  13221. return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
  13222. }
  13223. char *inet_ntoa(struct in_addr in) {
  13224. static char addr[17];
  13225. snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
  13226. (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
  13227. (int) in.S_un.S_un_b.s_b4);
  13228. return addr;
  13229. }
  13230. static void mg_handle_send(struct mg_connection *nc) {
  13231. uint16_t bytes_written = 0;
  13232. if (nc->flags & MG_F_UDP) {
  13233. if (!TCPIP_UDP_RemoteBind(
  13234. (UDP_SOCKET) nc->sock,
  13235. nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  13236. : IP_ADDRESS_TYPE_IPV6,
  13237. ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
  13238. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13239. return;
  13240. }
  13241. bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
  13242. if (bytes_written >= nc->send_mbuf.len) {
  13243. if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
  13244. (uint8_t *) nc->send_mbuf.buf,
  13245. nc->send_mbuf.len) != nc->send_mbuf.len) {
  13246. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13247. bytes_written = 0;
  13248. }
  13249. }
  13250. } else {
  13251. bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
  13252. if (bytes_written != 0) {
  13253. if (bytes_written > nc->send_mbuf.len) {
  13254. bytes_written = nc->send_mbuf.len;
  13255. }
  13256. if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
  13257. (uint8_t *) nc->send_mbuf.buf,
  13258. bytes_written) != bytes_written) {
  13259. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13260. bytes_written = 0;
  13261. }
  13262. }
  13263. }
  13264. if (bytes_written != 0) {
  13265. mbuf_remove(&nc->send_mbuf, bytes_written);
  13266. mg_if_sent_cb(nc, bytes_written);
  13267. }
  13268. }
  13269. static void mg_handle_recv(struct mg_connection *nc) {
  13270. uint16_t bytes_read = 0;
  13271. uint8_t *buf = NULL;
  13272. if (nc->flags & MG_F_UDP) {
  13273. bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
  13274. if (bytes_read != 0 &&
  13275. (nc->recv_mbuf_limit == -1 ||
  13276. nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
  13277. buf = (uint8_t *) MG_MALLOC(bytes_read);
  13278. if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
  13279. bytes_read) {
  13280. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13281. bytes_read = 0;
  13282. MG_FREE(buf);
  13283. }
  13284. }
  13285. } else {
  13286. bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
  13287. if (bytes_read != 0) {
  13288. if (nc->recv_mbuf_limit != -1 &&
  13289. nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
  13290. bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
  13291. }
  13292. buf = (uint8_t *) MG_MALLOC(bytes_read);
  13293. if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
  13294. bytes_read) {
  13295. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13296. MG_FREE(buf);
  13297. bytes_read = 0;
  13298. }
  13299. }
  13300. }
  13301. if (bytes_read != 0) {
  13302. mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
  13303. }
  13304. }
  13305. time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
  13306. struct mg_mgr *mgr = iface->mgr;
  13307. double now = mg_time();
  13308. struct mg_connection *nc, *tmp;
  13309. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  13310. tmp = nc->next;
  13311. if (nc->flags & MG_F_CONNECTING) {
  13312. /* processing connections */
  13313. if (nc->flags & MG_F_UDP ||
  13314. TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
  13315. mg_if_connect_cb(nc, 0);
  13316. }
  13317. } else if (nc->flags & MG_F_LISTENING) {
  13318. if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
  13319. /* accept new connections */
  13320. mg_accept_conn(nc);
  13321. }
  13322. } else {
  13323. if (nc->send_mbuf.len != 0) {
  13324. mg_handle_send(nc);
  13325. }
  13326. if (nc->recv_mbuf_limit == -1 ||
  13327. nc->recv_mbuf.len < nc->recv_mbuf_limit) {
  13328. mg_handle_recv(nc);
  13329. }
  13330. }
  13331. }
  13332. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  13333. tmp = nc->next;
  13334. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  13335. (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
  13336. mg_close_conn(nc);
  13337. }
  13338. }
  13339. return now;
  13340. }
  13341. void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
  13342. nc->sock = sock;
  13343. }
  13344. void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
  13345. union socket_address *sa) {
  13346. /* TODO(alaskin): not implemented yet */
  13347. }
  13348. void mg_pic32_if_connect_tcp(struct mg_connection *nc,
  13349. const union socket_address *sa) {
  13350. nc->sock = TCPIP_TCP_ClientOpen(
  13351. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  13352. : IP_ADDRESS_TYPE_IPV6,
  13353. ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
  13354. nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
  13355. }
  13356. void mg_pic32_if_connect_udp(struct mg_connection *nc) {
  13357. nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
  13358. nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
  13359. }
  13360. /* clang-format off */
  13361. #define MG_PIC32_IFACE_VTABLE \
  13362. { \
  13363. mg_pic32_if_init, \
  13364. mg_pic32_if_free, \
  13365. mg_pic32_if_add_conn, \
  13366. mg_pic32_if_remove_conn, \
  13367. mg_pic32_if_poll, \
  13368. mg_pic32_if_listen_tcp, \
  13369. mg_pic32_if_listen_udp, \
  13370. mg_pic32_if_connect_tcp, \
  13371. mg_pic32_if_connect_udp, \
  13372. mg_pic32_if_tcp_send, \
  13373. mg_pic32_if_udp_send, \
  13374. mg_pic32_if_recved, \
  13375. mg_pic32_if_create_conn, \
  13376. mg_pic32_if_destroy_conn, \
  13377. mg_pic32_if_sock_set, \
  13378. mg_pic32_if_get_conn_addr, \
  13379. }
  13380. /* clang-format on */
  13381. struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
  13382. #if MG_NET_IF == MG_NET_IF_PIC32
  13383. struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
  13384. #endif
  13385. #endif /* MG_ENABLE_NET_IF_PIC32 */