mongoose.c 449 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294
  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. ///////////////////////////////////////////////////////////////////////////////////////////////////////
  284. #define MG_TIMER_CALLED 4
  285. void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
  286. unsigned flags, void (*fn)(void *), void *arg) {
  287. t->id = 0, t->period_ms = ms, t->expire = 0;
  288. t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
  289. *head = t;
  290. }
  291. void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
  292. while (*head && *head != t) head = &(*head)->next;
  293. if (*head) *head = t->next;
  294. }
  295. // t: expiration time, prd: period, now: current time. Return true if expired
  296. bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
  297. if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
  298. if (*t == 0) *t = now + prd; // Firt poll? Set expiration
  299. if (*t > now) return false; // Not expired yet, return
  300. *t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
  301. return true; // Expired, return true
  302. }
  303. void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
  304. struct mg_timer *t, *tmp;
  305. for (t = *head; t != NULL; t = tmp) {
  306. bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
  307. !(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
  308. bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
  309. tmp = t->next;
  310. if (!once && !expired) continue;
  311. if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
  312. t->fn(t->arg);
  313. }
  314. t->flags |= MG_TIMER_CALLED;
  315. }
  316. }
  317. struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds,
  318. unsigned flags, void (*fn)(void *), void *arg) {
  319. struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t));
  320. if (t != NULL) {
  321. mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg);
  322. t->id = mgr->timerid++;
  323. }
  324. return t;
  325. }
  326. ////////////////////////////////////////////////////////////////////////////////////////////////////
  327. /* Amalgamated: #include "common/cs_dbg.h" */
  328. /* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
  329. #define NUM_UPPERCASES ('Z' - 'A' + 1)
  330. #define NUM_LETTERS (NUM_UPPERCASES * 2)
  331. #define NUM_DIGITS ('9' - '0' + 1)
  332. /*
  333. * Emit a base64 code char.
  334. *
  335. * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
  336. */
  337. static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
  338. if (v < NUM_UPPERCASES) {
  339. ctx->b64_putc(v + 'A', ctx->user_data);
  340. } else if (v < (NUM_LETTERS)) {
  341. ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
  342. } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
  343. ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
  344. } else {
  345. ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
  346. ctx->user_data);
  347. }
  348. }
  349. static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
  350. int a, b, c;
  351. a = ctx->chunk[0];
  352. b = ctx->chunk[1];
  353. c = ctx->chunk[2];
  354. cs_base64_emit_code(ctx, a >> 2);
  355. cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
  356. if (ctx->chunk_size > 1) {
  357. cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
  358. }
  359. if (ctx->chunk_size > 2) {
  360. cs_base64_emit_code(ctx, c & 63);
  361. }
  362. }
  363. void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
  364. void *user_data) {
  365. ctx->chunk_size = 0;
  366. ctx->b64_putc = b64_putc;
  367. ctx->user_data = user_data;
  368. }
  369. void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
  370. const unsigned char *src = (const unsigned char *) str;
  371. size_t i;
  372. for (i = 0; i < len; i++) {
  373. ctx->chunk[ctx->chunk_size++] = src[i];
  374. if (ctx->chunk_size == 3) {
  375. cs_base64_emit_chunk(ctx);
  376. ctx->chunk_size = 0;
  377. }
  378. }
  379. }
  380. void cs_base64_finish(struct cs_base64_ctx *ctx) {
  381. if (ctx->chunk_size > 0) {
  382. int i;
  383. memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
  384. cs_base64_emit_chunk(ctx);
  385. for (i = 0; i < (3 - ctx->chunk_size); i++) {
  386. ctx->b64_putc('=', ctx->user_data);
  387. }
  388. }
  389. }
  390. #define BASE64_ENCODE_BODY \
  391. static const char *b64 = \
  392. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
  393. int i, j, a, b, c; \
  394. \
  395. for (i = j = 0; i < src_len; i += 3) { \
  396. a = src[i]; \
  397. b = i + 1 >= src_len ? 0 : src[i + 1]; \
  398. c = i + 2 >= src_len ? 0 : src[i + 2]; \
  399. \
  400. BASE64_OUT(b64[a >> 2]); \
  401. BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
  402. if (i + 1 < src_len) { \
  403. BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
  404. } \
  405. if (i + 2 < src_len) { \
  406. BASE64_OUT(b64[c & 63]); \
  407. } \
  408. } \
  409. \
  410. while (j % 4 != 0) { \
  411. BASE64_OUT('='); \
  412. } \
  413. BASE64_FLUSH()
  414. #define BASE64_OUT(ch) \
  415. do { \
  416. dst[j++] = (ch); \
  417. } while (0)
  418. #define BASE64_FLUSH() \
  419. do { \
  420. dst[j++] = '\0'; \
  421. } while (0)
  422. void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
  423. BASE64_ENCODE_BODY;
  424. }
  425. #undef BASE64_OUT
  426. #undef BASE64_FLUSH
  427. #if CS_ENABLE_STDIO
  428. #define BASE64_OUT(ch) \
  429. do { \
  430. fprintf(f, "%c", (ch)); \
  431. j++; \
  432. } while (0)
  433. #define BASE64_FLUSH()
  434. void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
  435. BASE64_ENCODE_BODY;
  436. }
  437. #undef BASE64_OUT
  438. #undef BASE64_FLUSH
  439. #endif /* CS_ENABLE_STDIO */
  440. /* Convert one byte of encoded base64 input stream to 6-bit chunk */
  441. static unsigned char from_b64(unsigned char ch) {
  442. /* Inverse lookup map */
  443. static const unsigned char tab[128] = {
  444. 255, 255, 255, 255,
  445. 255, 255, 255, 255, /* 0 */
  446. 255, 255, 255, 255,
  447. 255, 255, 255, 255, /* 8 */
  448. 255, 255, 255, 255,
  449. 255, 255, 255, 255, /* 16 */
  450. 255, 255, 255, 255,
  451. 255, 255, 255, 255, /* 24 */
  452. 255, 255, 255, 255,
  453. 255, 255, 255, 255, /* 32 */
  454. 255, 255, 255, 62,
  455. 255, 255, 255, 63, /* 40 */
  456. 52, 53, 54, 55,
  457. 56, 57, 58, 59, /* 48 */
  458. 60, 61, 255, 255,
  459. 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
  460. 255, 0, 1, 2,
  461. 3, 4, 5, 6, /* 64 */
  462. 7, 8, 9, 10,
  463. 11, 12, 13, 14, /* 72 */
  464. 15, 16, 17, 18,
  465. 19, 20, 21, 22, /* 80 */
  466. 23, 24, 25, 255,
  467. 255, 255, 255, 255, /* 88 */
  468. 255, 26, 27, 28,
  469. 29, 30, 31, 32, /* 96 */
  470. 33, 34, 35, 36,
  471. 37, 38, 39, 40, /* 104 */
  472. 41, 42, 43, 44,
  473. 45, 46, 47, 48, /* 112 */
  474. 49, 50, 51, 255,
  475. 255, 255, 255, 255, /* 120 */
  476. };
  477. return tab[ch & 127];
  478. }
  479. int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
  480. unsigned char a, b, c, d;
  481. int orig_len = len;
  482. char *orig_dst = dst;
  483. while (len >= 4 && (a = from_b64(s[0])) != 255 &&
  484. (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
  485. (d = from_b64(s[3])) != 255) {
  486. s += 4;
  487. len -= 4;
  488. if (a == 200 || b == 200) break; /* '=' can't be there */
  489. *dst++ = a << 2 | b >> 4;
  490. if (c == 200) break;
  491. *dst++ = b << 4 | c >> 2;
  492. if (d == 200) break;
  493. *dst++ = c << 6 | d;
  494. }
  495. *dst = 0;
  496. if (dec_len != NULL) *dec_len = (dst - orig_dst);
  497. return orig_len - len;
  498. }
  499. #endif /* EXCLUDE_COMMON */
  500. #ifdef MG_MODULE_LINES
  501. #line 1 "common/cs_dirent.h"
  502. #endif
  503. /*
  504. * Copyright (c) 2014-2016 Cesanta Software Limited
  505. * All rights reserved
  506. */
  507. #ifndef CS_COMMON_CS_DIRENT_H_
  508. #define CS_COMMON_CS_DIRENT_H_
  509. #include <limits.h>
  510. /* Amalgamated: #include "common/platform.h" */
  511. #ifdef __cplusplus
  512. extern "C" {
  513. #endif /* __cplusplus */
  514. #if CS_DEFINE_DIRENT
  515. typedef struct { int dummy; } DIR;
  516. struct dirent {
  517. int d_ino;
  518. #ifdef _WIN32
  519. char d_name[MAX_PATH];
  520. #else
  521. /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
  522. char d_name[256];
  523. #endif
  524. };
  525. DIR *opendir(const char *dir_name);
  526. int closedir(DIR *dir);
  527. struct dirent *readdir(DIR *dir);
  528. #endif /* CS_DEFINE_DIRENT */
  529. #ifdef __cplusplus
  530. }
  531. #endif /* __cplusplus */
  532. #endif /* CS_COMMON_CS_DIRENT_H_ */
  533. #ifdef MG_MODULE_LINES
  534. #line 1 "common/cs_dirent.c"
  535. #endif
  536. /*
  537. * Copyright (c) 2015 Cesanta Software Limited
  538. * All rights reserved
  539. */
  540. #ifndef EXCLUDE_COMMON
  541. /* Amalgamated: #include "common/cs_dirent.h" */
  542. /*
  543. * This file contains POSIX opendir/closedir/readdir API implementation
  544. * for systems which do not natively support it (e.g. Windows).
  545. */
  546. #ifndef MG_FREE
  547. #define MG_FREE free
  548. #endif
  549. #ifndef MG_MALLOC
  550. #define MG_MALLOC malloc
  551. #endif
  552. #ifdef _WIN32
  553. struct win32_dir {
  554. DIR d;
  555. HANDLE handle;
  556. WIN32_FIND_DATAW info;
  557. struct dirent result;
  558. };
  559. DIR *opendir(const char *name) {
  560. struct win32_dir *dir = NULL;
  561. wchar_t wpath[MAX_PATH];
  562. DWORD attrs;
  563. if (name == NULL) {
  564. SetLastError(ERROR_BAD_ARGUMENTS);
  565. } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
  566. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  567. } else {
  568. to_wchar(name, wpath, ARRAY_SIZE(wpath));
  569. attrs = GetFileAttributesW(wpath);
  570. if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  571. (void) wcscat(wpath, L"\\*");
  572. dir->handle = FindFirstFileW(wpath, &dir->info);
  573. dir->result.d_name[0] = '\0';
  574. } else {
  575. MG_FREE(dir);
  576. dir = NULL;
  577. }
  578. }
  579. return (DIR *) dir;
  580. }
  581. int closedir(DIR *d) {
  582. struct win32_dir *dir = (struct win32_dir *) d;
  583. int result = 0;
  584. if (dir != NULL) {
  585. if (dir->handle != INVALID_HANDLE_VALUE)
  586. result = FindClose(dir->handle) ? 0 : -1;
  587. MG_FREE(dir);
  588. } else {
  589. result = -1;
  590. SetLastError(ERROR_BAD_ARGUMENTS);
  591. }
  592. return result;
  593. }
  594. struct dirent *readdir(DIR *d) {
  595. struct win32_dir *dir = (struct win32_dir *) d;
  596. struct dirent *result = NULL;
  597. if (dir) {
  598. memset(&dir->result, 0, sizeof(dir->result));
  599. if (dir->handle != INVALID_HANDLE_VALUE) {
  600. result = &dir->result;
  601. (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
  602. result->d_name, sizeof(result->d_name), NULL,
  603. NULL);
  604. if (!FindNextFileW(dir->handle, &dir->info)) {
  605. (void) FindClose(dir->handle);
  606. dir->handle = INVALID_HANDLE_VALUE;
  607. }
  608. } else {
  609. SetLastError(ERROR_FILE_NOT_FOUND);
  610. }
  611. } else {
  612. SetLastError(ERROR_BAD_ARGUMENTS);
  613. }
  614. return result;
  615. }
  616. #endif
  617. #endif /* EXCLUDE_COMMON */
  618. /* ISO C requires a translation unit to contain at least one declaration */
  619. typedef int cs_dirent_dummy;
  620. #ifdef MG_MODULE_LINES
  621. #line 1 "common/cs_time.c"
  622. #endif
  623. /*
  624. * Copyright (c) 2014-2016 Cesanta Software Limited
  625. * All rights reserved
  626. */
  627. /* Amalgamated: #include "common/cs_time.h" */
  628. #ifndef _WIN32
  629. #include <stddef.h>
  630. /*
  631. * There is no sys/time.h on ARMCC.
  632. */
  633. #if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
  634. !defined(__TI_COMPILER_VERSION__) && \
  635. (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
  636. #include <sys/time.h>
  637. #endif
  638. #else
  639. #include <windows.h>
  640. #endif
  641. WEAK double cs_time(void) {
  642. double now;
  643. #ifndef _WIN32
  644. struct timeval tv;
  645. if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
  646. now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
  647. #else
  648. SYSTEMTIME sysnow;
  649. FILETIME ftime;
  650. GetLocalTime(&sysnow);
  651. SystemTimeToFileTime(&sysnow, &ftime);
  652. /*
  653. * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
  654. * This should not cause a problems in this (21th) century
  655. * 2. Windows FILETIME is a number of 100-nanosecond intervals since January
  656. * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
  657. * thus, we need to convert to seconds and adjust amount (subtract 11644473600
  658. * seconds)
  659. */
  660. now = (double) (((int64_t) ftime.dwLowDateTime +
  661. ((int64_t) ftime.dwHighDateTime << 32)) /
  662. 10000000.0) -
  663. 11644473600;
  664. #endif /* _WIN32 */
  665. return now;
  666. }
  667. #ifdef MG_MODULE_LINES
  668. #line 1 "common/cs_endian.h"
  669. #endif
  670. /*
  671. * Copyright (c) 2014-2016 Cesanta Software Limited
  672. * All rights reserved
  673. */
  674. #ifndef CS_COMMON_CS_ENDIAN_H_
  675. #define CS_COMMON_CS_ENDIAN_H_
  676. /*
  677. * clang with std=-c99 uses __LITTLE_ENDIAN, by default
  678. * while for ex, RTOS gcc - LITTLE_ENDIAN, by default
  679. * it depends on __USE_BSD, but let's have everything
  680. */
  681. #if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
  682. #define BYTE_ORDER __BYTE_ORDER
  683. #ifndef LITTLE_ENDIAN
  684. #define LITTLE_ENDIAN __LITTLE_ENDIAN
  685. #endif /* LITTLE_ENDIAN */
  686. #ifndef BIG_ENDIAN
  687. #define BIG_ENDIAN __LITTLE_ENDIAN
  688. #endif /* BIG_ENDIAN */
  689. #endif /* BYTE_ORDER */
  690. #endif /* CS_COMMON_CS_ENDIAN_H_ */
  691. #ifdef MG_MODULE_LINES
  692. #line 1 "common/md5.c"
  693. #endif
  694. /*
  695. * This code implements the MD5 message-digest algorithm.
  696. * The algorithm is due to Ron Rivest. This code was
  697. * written by Colin Plumb in 1993, no copyright is claimed.
  698. * This code is in the public domain; do with it what you wish.
  699. *
  700. * Equivalent code is available from RSA Data Security, Inc.
  701. * This code has been tested against that, and is equivalent,
  702. * except that you don't need to include two pages of legalese
  703. * with every copy.
  704. *
  705. * To compute the message digest of a chunk of bytes, declare an
  706. * MD5Context structure, pass it to MD5Init, call MD5Update as
  707. * needed on buffers full of bytes, and then call MD5Final, which
  708. * will fill a supplied 16-byte array with the digest.
  709. */
  710. /* Amalgamated: #include "common/md5.h" */
  711. /* Amalgamated: #include "common/str_util.h" */
  712. #if !defined(EXCLUDE_COMMON)
  713. #if !DISABLE_MD5
  714. /* Amalgamated: #include "common/cs_endian.h" */
  715. static void byteReverse(unsigned char *buf, unsigned longs) {
  716. /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
  717. #if BYTE_ORDER == BIG_ENDIAN
  718. do {
  719. uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
  720. ((unsigned) buf[1] << 8 | buf[0]);
  721. *(uint32_t *) buf = t;
  722. buf += 4;
  723. } while (--longs);
  724. #else
  725. (void) buf;
  726. (void) longs;
  727. #endif
  728. }
  729. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  730. #define F2(x, y, z) F1(z, x, y)
  731. #define F3(x, y, z) (x ^ y ^ z)
  732. #define F4(x, y, z) (y ^ (x | ~z))
  733. #define MD5STEP(f, w, x, y, z, data, s) \
  734. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  735. /*
  736. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  737. * initialization constants.
  738. */
  739. void MD5_Init(MD5_CTX *ctx) {
  740. ctx->buf[0] = 0x67452301;
  741. ctx->buf[1] = 0xefcdab89;
  742. ctx->buf[2] = 0x98badcfe;
  743. ctx->buf[3] = 0x10325476;
  744. ctx->bits[0] = 0;
  745. ctx->bits[1] = 0;
  746. }
  747. static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
  748. register uint32_t a, b, c, d;
  749. a = buf[0];
  750. b = buf[1];
  751. c = buf[2];
  752. d = buf[3];
  753. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  754. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  755. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  756. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  757. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  758. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  759. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  760. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  761. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  762. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  763. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  764. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  765. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  766. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  767. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  768. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  769. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  770. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  771. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  772. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  773. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  774. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  775. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  776. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  777. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  778. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  779. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  780. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  781. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  782. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  783. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  784. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  785. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  786. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  787. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  788. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  789. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  790. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  791. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  792. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  793. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  794. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  795. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  796. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  797. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  798. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  799. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  800. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  801. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  802. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  803. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  804. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  805. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  806. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  807. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  808. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  809. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  810. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  811. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  812. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  813. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  814. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  815. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  816. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  817. buf[0] += a;
  818. buf[1] += b;
  819. buf[2] += c;
  820. buf[3] += d;
  821. }
  822. void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) {
  823. uint32_t t;
  824. t = ctx->bits[0];
  825. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  826. ctx->bits[1] += (uint32_t) len >> 29;
  827. t = (t >> 3) & 0x3f;
  828. if (t) {
  829. unsigned char *p = (unsigned char *) ctx->in + t;
  830. t = 64 - t;
  831. if (len < t) {
  832. memcpy(p, buf, len);
  833. return;
  834. }
  835. memcpy(p, buf, t);
  836. byteReverse(ctx->in, 16);
  837. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  838. buf += t;
  839. len -= t;
  840. }
  841. while (len >= 64) {
  842. memcpy(ctx->in, buf, 64);
  843. byteReverse(ctx->in, 16);
  844. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  845. buf += 64;
  846. len -= 64;
  847. }
  848. memcpy(ctx->in, buf, len);
  849. }
  850. void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) {
  851. unsigned count;
  852. unsigned char *p;
  853. uint32_t *a;
  854. count = (ctx->bits[0] >> 3) & 0x3F;
  855. p = ctx->in + count;
  856. *p++ = 0x80;
  857. count = 64 - 1 - count;
  858. if (count < 8) {
  859. memset(p, 0, count);
  860. byteReverse(ctx->in, 16);
  861. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  862. memset(ctx->in, 0, 56);
  863. } else {
  864. memset(p, 0, count - 8);
  865. }
  866. byteReverse(ctx->in, 14);
  867. a = (uint32_t *) ctx->in;
  868. a[14] = ctx->bits[0];
  869. a[15] = ctx->bits[1];
  870. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  871. byteReverse((unsigned char *) ctx->buf, 4);
  872. memcpy(digest, ctx->buf, 16);
  873. memset((char *) ctx, 0, sizeof(*ctx));
  874. }
  875. #endif /* DISABLE_MD5 */
  876. char *cs_md5(char buf[33], ...) {
  877. unsigned char hash[16];
  878. const unsigned char *p;
  879. va_list ap;
  880. MD5_CTX ctx;
  881. MD5_Init(&ctx);
  882. va_start(ap, buf);
  883. while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
  884. size_t len = va_arg(ap, size_t);
  885. MD5_Update(&ctx, p, len);
  886. }
  887. va_end(ap);
  888. MD5_Final(hash, &ctx);
  889. cs_to_hex(buf, hash, sizeof(hash));
  890. return buf;
  891. }
  892. #endif /* EXCLUDE_COMMON */
  893. #ifdef MG_MODULE_LINES
  894. #line 1 "common/mbuf.c"
  895. #endif
  896. /*
  897. * Copyright (c) 2014 Cesanta Software Limited
  898. * All rights reserved
  899. */
  900. #ifndef EXCLUDE_COMMON
  901. #include <assert.h>
  902. #include <string.h>
  903. /* Amalgamated: #include "common/mbuf.h" */
  904. #ifndef MBUF_REALLOC
  905. #define MBUF_REALLOC realloc
  906. #endif
  907. #ifndef MBUF_FREE
  908. #define MBUF_FREE free
  909. #endif
  910. WEAK void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
  911. mbuf->len = mbuf->size = 0;
  912. mbuf->buf = NULL;
  913. mbuf_resize(mbuf, initial_size);
  914. }
  915. WEAK void mbuf_free(struct mbuf *mbuf) {
  916. if (mbuf->buf != NULL) {
  917. MBUF_FREE(mbuf->buf);
  918. mbuf_init(mbuf, 0);
  919. }
  920. }
  921. WEAK void mbuf_resize(struct mbuf *a, size_t new_size) {
  922. if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
  923. char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
  924. /*
  925. * In case realloc fails, there's not much we can do, except keep things as
  926. * they are. Note that NULL is a valid return value from realloc when
  927. * size == 0, but that is covered too.
  928. */
  929. if (buf == NULL && new_size != 0) return;
  930. a->buf = buf;
  931. a->size = new_size;
  932. }
  933. }
  934. WEAK void mbuf_trim(struct mbuf *mbuf) {
  935. mbuf_resize(mbuf, mbuf->len);
  936. }
  937. WEAK size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
  938. char *p = NULL;
  939. assert(a != NULL);
  940. assert(a->len <= a->size);
  941. assert(off <= a->len);
  942. /* check overflow */
  943. if (~(size_t) 0 - (size_t) a->buf < len) return 0;
  944. if (a->len + len <= a->size) {
  945. memmove(a->buf + off + len, a->buf + off, a->len - off);
  946. if (buf != NULL) {
  947. memcpy(a->buf + off, buf, len);
  948. }
  949. a->len += len;
  950. } else {
  951. size_t new_size = (size_t)((a->len + len) * MBUF_SIZE_MULTIPLIER);
  952. if ((p = (char *) MBUF_REALLOC(a->buf, new_size)) != NULL) {
  953. a->buf = p;
  954. memmove(a->buf + off + len, a->buf + off, a->len - off);
  955. if (buf != NULL) memcpy(a->buf + off, buf, len);
  956. a->len += len;
  957. a->size = new_size;
  958. } else {
  959. len = 0;
  960. }
  961. }
  962. return len;
  963. }
  964. WEAK size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
  965. return mbuf_insert(a, a->len, buf, len);
  966. }
  967. WEAK void mbuf_remove(struct mbuf *mb, size_t n) {
  968. if (n > 0 && n <= mb->len) {
  969. memmove(mb->buf, mb->buf + n, mb->len - n);
  970. mb->len -= n;
  971. }
  972. }
  973. #endif /* EXCLUDE_COMMON */
  974. #ifdef MG_MODULE_LINES
  975. #line 1 "common/mg_str.c"
  976. #endif
  977. /*
  978. * Copyright (c) 2014-2016 Cesanta Software Limited
  979. * All rights reserved
  980. */
  981. /* Amalgamated: #include "common/mg_str.h" */
  982. #include <stdlib.h>
  983. #include <string.h>
  984. WEAK int mg_ncasecmp(const char *s1, const char *s2, size_t len);
  985. WEAK struct mg_str mg_mk_str(const char *s) {
  986. struct mg_str ret = {s, 0};
  987. if (s != NULL) ret.len = strlen(s);
  988. return ret;
  989. }
  990. WEAK struct mg_str mg_mk_str_n(const char *s, size_t len) {
  991. struct mg_str ret = {s, len};
  992. return ret;
  993. }
  994. WEAK int mg_vcmp(const struct mg_str *str1, const char *str2) {
  995. size_t n2 = strlen(str2), n1 = str1->len;
  996. int r = memcmp(str1->p, str2, (n1 < n2) ? n1 : n2);
  997. if (r == 0) {
  998. return n1 - n2;
  999. }
  1000. return r;
  1001. }
  1002. WEAK int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
  1003. size_t n2 = strlen(str2), n1 = str1->len;
  1004. int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
  1005. if (r == 0) {
  1006. return n1 - n2;
  1007. }
  1008. return r;
  1009. }
  1010. WEAK struct mg_str mg_strdup(const struct mg_str s) {
  1011. struct mg_str r = {NULL, 0};
  1012. if (s.len > 0 && s.p != NULL) {
  1013. r.p = (char *) MG_MALLOC(s.len);
  1014. if (r.p != NULL) {
  1015. memcpy((char *) r.p, s.p, s.len);
  1016. r.len = s.len;
  1017. }
  1018. }
  1019. return r;
  1020. }
  1021. WEAK int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  1022. size_t i = 0;
  1023. while (i < str1.len && i < str2.len) {
  1024. if (str1.p[i] < str2.p[i]) return -1;
  1025. if (str1.p[i] > str2.p[i]) return 1;
  1026. i++;
  1027. }
  1028. if (i < str1.len) return 1;
  1029. if (i < str2.len) return -1;
  1030. return 0;
  1031. }
  1032. WEAK int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
  1033. struct mg_str s1 = str1;
  1034. struct mg_str s2 = str2;
  1035. if (s1.len > n) {
  1036. s1.len = n;
  1037. }
  1038. if (s2.len > n) {
  1039. s2.len = n;
  1040. }
  1041. return mg_strcmp(s1, s2);
  1042. }
  1043. #ifdef MG_MODULE_LINES
  1044. #line 1 "common/sha1.c"
  1045. #endif
  1046. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  1047. /* 100% Public Domain */
  1048. /* Amalgamated: #include "common/sha1.h" */
  1049. #if !DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
  1050. /* Amalgamated: #include "common/cs_endian.h" */
  1051. #define SHA1HANDSOFF
  1052. #if defined(__sun)
  1053. /* Amalgamated: #include "common/solarisfixes.h" */
  1054. #endif
  1055. union char64long16 {
  1056. unsigned char c[64];
  1057. uint32_t l[16];
  1058. };
  1059. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  1060. static uint32_t blk0(union char64long16 *block, int i) {
  1061. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  1062. #if BYTE_ORDER == LITTLE_ENDIAN
  1063. block->l[i] =
  1064. (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
  1065. #endif
  1066. return block->l[i];
  1067. }
  1068. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  1069. #undef blk
  1070. #undef R0
  1071. #undef R1
  1072. #undef R2
  1073. #undef R3
  1074. #undef R4
  1075. #define blk(i) \
  1076. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  1077. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  1078. 1))
  1079. #define R0(v, w, x, y, z, i) \
  1080. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  1081. w = rol(w, 30);
  1082. #define R1(v, w, x, y, z, i) \
  1083. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  1084. w = rol(w, 30);
  1085. #define R2(v, w, x, y, z, i) \
  1086. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  1087. w = rol(w, 30);
  1088. #define R3(v, w, x, y, z, i) \
  1089. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  1090. w = rol(w, 30);
  1091. #define R4(v, w, x, y, z, i) \
  1092. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  1093. w = rol(w, 30);
  1094. void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
  1095. uint32_t a, b, c, d, e;
  1096. union char64long16 block[1];
  1097. memcpy(block, buffer, 64);
  1098. a = state[0];
  1099. b = state[1];
  1100. c = state[2];
  1101. d = state[3];
  1102. e = state[4];
  1103. R0(a, b, c, d, e, 0);
  1104. R0(e, a, b, c, d, 1);
  1105. R0(d, e, a, b, c, 2);
  1106. R0(c, d, e, a, b, 3);
  1107. R0(b, c, d, e, a, 4);
  1108. R0(a, b, c, d, e, 5);
  1109. R0(e, a, b, c, d, 6);
  1110. R0(d, e, a, b, c, 7);
  1111. R0(c, d, e, a, b, 8);
  1112. R0(b, c, d, e, a, 9);
  1113. R0(a, b, c, d, e, 10);
  1114. R0(e, a, b, c, d, 11);
  1115. R0(d, e, a, b, c, 12);
  1116. R0(c, d, e, a, b, 13);
  1117. R0(b, c, d, e, a, 14);
  1118. R0(a, b, c, d, e, 15);
  1119. R1(e, a, b, c, d, 16);
  1120. R1(d, e, a, b, c, 17);
  1121. R1(c, d, e, a, b, 18);
  1122. R1(b, c, d, e, a, 19);
  1123. R2(a, b, c, d, e, 20);
  1124. R2(e, a, b, c, d, 21);
  1125. R2(d, e, a, b, c, 22);
  1126. R2(c, d, e, a, b, 23);
  1127. R2(b, c, d, e, a, 24);
  1128. R2(a, b, c, d, e, 25);
  1129. R2(e, a, b, c, d, 26);
  1130. R2(d, e, a, b, c, 27);
  1131. R2(c, d, e, a, b, 28);
  1132. R2(b, c, d, e, a, 29);
  1133. R2(a, b, c, d, e, 30);
  1134. R2(e, a, b, c, d, 31);
  1135. R2(d, e, a, b, c, 32);
  1136. R2(c, d, e, a, b, 33);
  1137. R2(b, c, d, e, a, 34);
  1138. R2(a, b, c, d, e, 35);
  1139. R2(e, a, b, c, d, 36);
  1140. R2(d, e, a, b, c, 37);
  1141. R2(c, d, e, a, b, 38);
  1142. R2(b, c, d, e, a, 39);
  1143. R3(a, b, c, d, e, 40);
  1144. R3(e, a, b, c, d, 41);
  1145. R3(d, e, a, b, c, 42);
  1146. R3(c, d, e, a, b, 43);
  1147. R3(b, c, d, e, a, 44);
  1148. R3(a, b, c, d, e, 45);
  1149. R3(e, a, b, c, d, 46);
  1150. R3(d, e, a, b, c, 47);
  1151. R3(c, d, e, a, b, 48);
  1152. R3(b, c, d, e, a, 49);
  1153. R3(a, b, c, d, e, 50);
  1154. R3(e, a, b, c, d, 51);
  1155. R3(d, e, a, b, c, 52);
  1156. R3(c, d, e, a, b, 53);
  1157. R3(b, c, d, e, a, 54);
  1158. R3(a, b, c, d, e, 55);
  1159. R3(e, a, b, c, d, 56);
  1160. R3(d, e, a, b, c, 57);
  1161. R3(c, d, e, a, b, 58);
  1162. R3(b, c, d, e, a, 59);
  1163. R4(a, b, c, d, e, 60);
  1164. R4(e, a, b, c, d, 61);
  1165. R4(d, e, a, b, c, 62);
  1166. R4(c, d, e, a, b, 63);
  1167. R4(b, c, d, e, a, 64);
  1168. R4(a, b, c, d, e, 65);
  1169. R4(e, a, b, c, d, 66);
  1170. R4(d, e, a, b, c, 67);
  1171. R4(c, d, e, a, b, 68);
  1172. R4(b, c, d, e, a, 69);
  1173. R4(a, b, c, d, e, 70);
  1174. R4(e, a, b, c, d, 71);
  1175. R4(d, e, a, b, c, 72);
  1176. R4(c, d, e, a, b, 73);
  1177. R4(b, c, d, e, a, 74);
  1178. R4(a, b, c, d, e, 75);
  1179. R4(e, a, b, c, d, 76);
  1180. R4(d, e, a, b, c, 77);
  1181. R4(c, d, e, a, b, 78);
  1182. R4(b, c, d, e, a, 79);
  1183. state[0] += a;
  1184. state[1] += b;
  1185. state[2] += c;
  1186. state[3] += d;
  1187. state[4] += e;
  1188. /* Erase working structures. The order of operations is important,
  1189. * used to ensure that compiler doesn't optimize those out. */
  1190. memset(block, 0, sizeof(block));
  1191. a = b = c = d = e = 0;
  1192. (void) a;
  1193. (void) b;
  1194. (void) c;
  1195. (void) d;
  1196. (void) e;
  1197. }
  1198. void cs_sha1_init(cs_sha1_ctx *context) {
  1199. context->state[0] = 0x67452301;
  1200. context->state[1] = 0xEFCDAB89;
  1201. context->state[2] = 0x98BADCFE;
  1202. context->state[3] = 0x10325476;
  1203. context->state[4] = 0xC3D2E1F0;
  1204. context->count[0] = context->count[1] = 0;
  1205. }
  1206. void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
  1207. uint32_t len) {
  1208. uint32_t i, j;
  1209. j = context->count[0];
  1210. if ((context->count[0] += len << 3) < j) context->count[1]++;
  1211. context->count[1] += (len >> 29);
  1212. j = (j >> 3) & 63;
  1213. if ((j + len) > 63) {
  1214. memcpy(&context->buffer[j], data, (i = 64 - j));
  1215. cs_sha1_transform(context->state, context->buffer);
  1216. for (; i + 63 < len; i += 64) {
  1217. cs_sha1_transform(context->state, &data[i]);
  1218. }
  1219. j = 0;
  1220. } else
  1221. i = 0;
  1222. memcpy(&context->buffer[j], &data[i], len - i);
  1223. }
  1224. void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
  1225. unsigned i;
  1226. unsigned char finalcount[8], c;
  1227. for (i = 0; i < 8; i++) {
  1228. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  1229. ((3 - (i & 3)) * 8)) &
  1230. 255);
  1231. }
  1232. c = 0200;
  1233. cs_sha1_update(context, &c, 1);
  1234. while ((context->count[0] & 504) != 448) {
  1235. c = 0000;
  1236. cs_sha1_update(context, &c, 1);
  1237. }
  1238. cs_sha1_update(context, finalcount, 8);
  1239. for (i = 0; i < 20; i++) {
  1240. digest[i] =
  1241. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  1242. }
  1243. memset(context, '\0', sizeof(*context));
  1244. memset(&finalcount, '\0', sizeof(finalcount));
  1245. }
  1246. void cs_hmac_sha1(const unsigned char *key, size_t keylen,
  1247. const unsigned char *data, size_t datalen,
  1248. unsigned char out[20]) {
  1249. cs_sha1_ctx ctx;
  1250. unsigned char buf1[64], buf2[64], tmp_key[20], i;
  1251. if (keylen > sizeof(buf1)) {
  1252. cs_sha1_init(&ctx);
  1253. cs_sha1_update(&ctx, key, keylen);
  1254. cs_sha1_final(tmp_key, &ctx);
  1255. key = tmp_key;
  1256. keylen = sizeof(tmp_key);
  1257. }
  1258. memset(buf1, 0, sizeof(buf1));
  1259. memset(buf2, 0, sizeof(buf2));
  1260. memcpy(buf1, key, keylen);
  1261. memcpy(buf2, key, keylen);
  1262. for (i = 0; i < sizeof(buf1); i++) {
  1263. buf1[i] ^= 0x36;
  1264. buf2[i] ^= 0x5c;
  1265. }
  1266. cs_sha1_init(&ctx);
  1267. cs_sha1_update(&ctx, buf1, sizeof(buf1));
  1268. cs_sha1_update(&ctx, data, datalen);
  1269. cs_sha1_final(out, &ctx);
  1270. cs_sha1_init(&ctx);
  1271. cs_sha1_update(&ctx, buf2, sizeof(buf2));
  1272. cs_sha1_update(&ctx, out, 20);
  1273. cs_sha1_final(out, &ctx);
  1274. }
  1275. #endif /* EXCLUDE_COMMON */
  1276. #ifdef MG_MODULE_LINES
  1277. #line 1 "common/str_util.c"
  1278. #endif
  1279. /*
  1280. * Copyright (c) 2015 Cesanta Software Limited
  1281. * All rights reserved
  1282. */
  1283. #ifndef EXCLUDE_COMMON
  1284. /* Amalgamated: #include "common/platform.h" */
  1285. /* Amalgamated: #include "common/str_util.h" */
  1286. #ifndef C_DISABLE_BUILTIN_SNPRINTF
  1287. #define C_DISABLE_BUILTIN_SNPRINTF 0
  1288. #endif
  1289. #ifndef MG_MALLOC
  1290. #define MG_MALLOC malloc
  1291. #endif
  1292. #ifndef MG_FREE
  1293. #define MG_FREE free
  1294. #endif
  1295. WEAK size_t c_strnlen(const char *s, size_t maxlen) {
  1296. size_t l = 0;
  1297. for (; l < maxlen && s[l] != '\0'; l++) {
  1298. }
  1299. return l;
  1300. }
  1301. #define C_SNPRINTF_APPEND_CHAR(ch) \
  1302. do { \
  1303. if (i < (int) buf_size) buf[i] = ch; \
  1304. i++; \
  1305. } while (0)
  1306. #define C_SNPRINTF_FLAG_ZERO 1
  1307. #if C_DISABLE_BUILTIN_SNPRINTF
  1308. WEAK int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
  1309. return vsnprintf(buf, buf_size, fmt, ap);
  1310. }
  1311. #else
  1312. static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
  1313. int field_width) {
  1314. char tmp[40];
  1315. int i = 0, k = 0, neg = 0;
  1316. if (num < 0) {
  1317. neg++;
  1318. num = -num;
  1319. }
  1320. /* Print into temporary buffer - in reverse order */
  1321. do {
  1322. int rem = num % base;
  1323. if (rem < 10) {
  1324. tmp[k++] = '0' + rem;
  1325. } else {
  1326. tmp[k++] = 'a' + (rem - 10);
  1327. }
  1328. num /= base;
  1329. } while (num > 0);
  1330. /* Zero padding */
  1331. if (flags && C_SNPRINTF_FLAG_ZERO) {
  1332. while (k < field_width && k < (int) sizeof(tmp) - 1) {
  1333. tmp[k++] = '0';
  1334. }
  1335. }
  1336. /* And sign */
  1337. if (neg) {
  1338. tmp[k++] = '-';
  1339. }
  1340. /* Now output */
  1341. while (--k >= 0) {
  1342. C_SNPRINTF_APPEND_CHAR(tmp[k]);
  1343. }
  1344. return i;
  1345. }
  1346. WEAK int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
  1347. int ch, i = 0, len_mod, flags, precision, field_width;
  1348. while ((ch = *fmt++) != '\0') {
  1349. if (ch != '%') {
  1350. C_SNPRINTF_APPEND_CHAR(ch);
  1351. } else {
  1352. /*
  1353. * Conversion specification:
  1354. * zero or more flags (one of: # 0 - <space> + ')
  1355. * an optional minimum field width (digits)
  1356. * an optional precision (. followed by digits, or *)
  1357. * an optional length modifier (one of: hh h l ll L q j z t)
  1358. * conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
  1359. */
  1360. flags = field_width = precision = len_mod = 0;
  1361. /* Flags. only zero-pad flag is supported. */
  1362. if (*fmt == '0') {
  1363. flags |= C_SNPRINTF_FLAG_ZERO;
  1364. }
  1365. /* Field width */
  1366. while (*fmt >= '0' && *fmt <= '9') {
  1367. field_width *= 10;
  1368. field_width += *fmt++ - '0';
  1369. }
  1370. /* Dynamic field width */
  1371. if (*fmt == '*') {
  1372. field_width = va_arg(ap, int);
  1373. fmt++;
  1374. }
  1375. /* Precision */
  1376. if (*fmt == '.') {
  1377. fmt++;
  1378. if (*fmt == '*') {
  1379. precision = va_arg(ap, int);
  1380. fmt++;
  1381. } else {
  1382. while (*fmt >= '0' && *fmt <= '9') {
  1383. precision *= 10;
  1384. precision += *fmt++ - '0';
  1385. }
  1386. }
  1387. }
  1388. /* Length modifier */
  1389. switch (*fmt) {
  1390. case 'h':
  1391. case 'l':
  1392. case 'L':
  1393. case 'I':
  1394. case 'q':
  1395. case 'j':
  1396. case 'z':
  1397. case 't':
  1398. len_mod = *fmt++;
  1399. if (*fmt == 'h') {
  1400. len_mod = 'H';
  1401. fmt++;
  1402. }
  1403. if (*fmt == 'l') {
  1404. len_mod = 'q';
  1405. fmt++;
  1406. }
  1407. break;
  1408. }
  1409. ch = *fmt++;
  1410. if (ch == 's') {
  1411. const char *s = va_arg(ap, const char *); /* Always fetch parameter */
  1412. int j;
  1413. int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
  1414. for (j = 0; j < pad; j++) {
  1415. C_SNPRINTF_APPEND_CHAR(' ');
  1416. }
  1417. /* `s` may be NULL in case of %.*s */
  1418. if (s != NULL) {
  1419. /* Ignore negative and 0 precisions */
  1420. for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
  1421. C_SNPRINTF_APPEND_CHAR(s[j]);
  1422. }
  1423. }
  1424. } else if (ch == 'c') {
  1425. ch = va_arg(ap, int); /* Always fetch parameter */
  1426. C_SNPRINTF_APPEND_CHAR(ch);
  1427. } else if (ch == 'd' && len_mod == 0) {
  1428. i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
  1429. field_width);
  1430. } else if (ch == 'd' && len_mod == 'l') {
  1431. i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
  1432. field_width);
  1433. #ifdef SSIZE_MAX
  1434. } else if (ch == 'd' && len_mod == 'z') {
  1435. i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
  1436. field_width);
  1437. #endif
  1438. } else if (ch == 'd' && len_mod == 'q') {
  1439. i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
  1440. field_width);
  1441. } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
  1442. i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
  1443. ch == 'x' ? 16 : 10, flags, field_width);
  1444. } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
  1445. i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
  1446. ch == 'x' ? 16 : 10, flags, field_width);
  1447. } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
  1448. i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
  1449. ch == 'x' ? 16 : 10, flags, field_width);
  1450. } else if (ch == 'p') {
  1451. unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
  1452. C_SNPRINTF_APPEND_CHAR('0');
  1453. C_SNPRINTF_APPEND_CHAR('x');
  1454. i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
  1455. } else {
  1456. #ifndef NO_LIBC
  1457. /*
  1458. * TODO(lsm): abort is not nice in a library, remove it
  1459. * Also, ESP8266 SDK doesn't have it
  1460. */
  1461. abort();
  1462. #endif
  1463. }
  1464. }
  1465. }
  1466. /* Zero-terminate the result */
  1467. if (buf_size > 0) {
  1468. buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
  1469. }
  1470. return i;
  1471. }
  1472. #endif
  1473. WEAK int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
  1474. int result;
  1475. va_list ap;
  1476. va_start(ap, fmt);
  1477. result = c_vsnprintf(buf, buf_size, fmt, ap);
  1478. va_end(ap);
  1479. return result;
  1480. }
  1481. #ifdef _WIN32
  1482. int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1483. int ret;
  1484. char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
  1485. strncpy(buf, path, sizeof(buf));
  1486. buf[sizeof(buf) - 1] = '\0';
  1487. /* Trim trailing slashes. Leave backslash for paths like "X:\" */
  1488. p = buf + strlen(buf) - 1;
  1489. while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
  1490. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1491. ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1492. /*
  1493. * Convert back to Unicode. If doubly-converted string does not match the
  1494. * original, something is fishy, reject.
  1495. */
  1496. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1497. NULL, NULL);
  1498. if (strcmp(buf, buf2) != 0) {
  1499. wbuf[0] = L'\0';
  1500. ret = 0;
  1501. }
  1502. return ret;
  1503. }
  1504. #endif /* _WIN32 */
  1505. /* The simplest O(mn) algorithm. Better implementation are GPLed */
  1506. WEAK const char *c_strnstr(const char *s, const char *find, size_t slen) {
  1507. size_t find_length = strlen(find);
  1508. size_t i;
  1509. for (i = 0; i < slen; i++) {
  1510. if (i + find_length > slen) {
  1511. return NULL;
  1512. }
  1513. if (strncmp(&s[i], find, find_length) == 0) {
  1514. return &s[i];
  1515. }
  1516. }
  1517. return NULL;
  1518. }
  1519. #if CS_ENABLE_STRDUP
  1520. WEAK char *strdup(const char *src) {
  1521. size_t len = strlen(src) + 1;
  1522. char *ret = MG_MALLOC(len);
  1523. if (ret != NULL) {
  1524. strcpy(ret, src);
  1525. }
  1526. return ret;
  1527. }
  1528. #endif
  1529. WEAK void cs_to_hex(char *to, const unsigned char *p, size_t len) {
  1530. static const char *hex = "0123456789abcdef";
  1531. for (; len--; p++) {
  1532. *to++ = hex[p[0] >> 4];
  1533. *to++ = hex[p[0] & 0x0f];
  1534. }
  1535. *to = '\0';
  1536. }
  1537. static int fourbit(int ch) {
  1538. if (ch >= '0' && ch <= '9') {
  1539. return ch - '0';
  1540. } else if (ch >= 'a' && ch <= 'f') {
  1541. return ch - 'a' + 10;
  1542. } else if (ch >= 'A' && ch <= 'F') {
  1543. return ch - 'A' + 10;
  1544. }
  1545. return 0;
  1546. }
  1547. WEAK void cs_from_hex(char *to, const char *p, size_t len) {
  1548. size_t i;
  1549. for (i = 0; i < len; i += 2) {
  1550. *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
  1551. }
  1552. *to = '\0';
  1553. }
  1554. #if CS_ENABLE_TO64
  1555. WEAK int64_t cs_to64(const char *s) {
  1556. int64_t result = 0;
  1557. int64_t neg = 1;
  1558. while (*s && isspace((unsigned char) *s)) s++;
  1559. if (*s == '-') {
  1560. neg = -1;
  1561. s++;
  1562. }
  1563. while (isdigit((unsigned char) *s)) {
  1564. result *= 10;
  1565. result += (*s - '0');
  1566. s++;
  1567. }
  1568. return result * neg;
  1569. }
  1570. #endif
  1571. static int str_util_lowercase(const char *s) {
  1572. return tolower(*(const unsigned char *) s);
  1573. }
  1574. WEAK int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  1575. int diff = 0;
  1576. if (len > 0) do {
  1577. diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
  1578. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1579. return diff;
  1580. }
  1581. WEAK int mg_casecmp(const char *s1, const char *s2) {
  1582. return mg_ncasecmp(s1, s2, (size_t) ~0);
  1583. }
  1584. WEAK int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
  1585. int ret;
  1586. va_list ap;
  1587. va_start(ap, fmt);
  1588. ret = mg_avprintf(buf, size, fmt, ap);
  1589. va_end(ap);
  1590. return ret;
  1591. }
  1592. WEAK int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
  1593. va_list ap_copy;
  1594. int len;
  1595. va_copy(ap_copy, ap);
  1596. len = vsnprintf(*buf, size, fmt, ap_copy);
  1597. va_end(ap_copy);
  1598. if (len < 0) {
  1599. /* eCos and Windows are not standard-compliant and return -1 when
  1600. * the buffer is too small. Keep allocating larger buffers until we
  1601. * succeed or out of memory. */
  1602. *buf = NULL; /* LCOV_EXCL_START */
  1603. while (len < 0) {
  1604. MG_FREE(*buf);
  1605. size *= 2;
  1606. if ((*buf = (char *) MG_MALLOC(size)) == NULL) break;
  1607. va_copy(ap_copy, ap);
  1608. len = vsnprintf(*buf, size, fmt, ap_copy);
  1609. va_end(ap_copy);
  1610. }
  1611. /* LCOV_EXCL_STOP */
  1612. } else if (len >= (int) size) {
  1613. /* Standard-compliant code path. Allocate a buffer that is large enough. */
  1614. if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
  1615. len = -1; /* LCOV_EXCL_LINE */
  1616. } else { /* LCOV_EXCL_LINE */
  1617. va_copy(ap_copy, ap);
  1618. len = vsnprintf(*buf, len + 1, fmt, ap_copy);
  1619. va_end(ap_copy);
  1620. }
  1621. }
  1622. return len;
  1623. }
  1624. #endif /* EXCLUDE_COMMON */
  1625. #ifdef MG_MODULE_LINES
  1626. #line 1 "mongoose/src/tun.h"
  1627. #endif
  1628. /*
  1629. * Copyright (c) 2014-2016 Cesanta Software Limited
  1630. * All rights reserved
  1631. */
  1632. #ifndef CS_MONGOOSE_SRC_TUN_H_
  1633. #define CS_MONGOOSE_SRC_TUN_H_
  1634. #if MG_ENABLE_TUN
  1635. /* Amalgamated: #include "mongoose/src/net.h" */
  1636. /* Amalgamated: #include "common/mg_str.h" */
  1637. #ifndef MG_TUN_RECONNECT_INTERVAL
  1638. #define MG_TUN_RECONNECT_INTERVAL 1
  1639. #endif
  1640. #define MG_TUN_PROTO_NAME "mg_tun"
  1641. #define MG_TUN_DATA_FRAME 0x0
  1642. #define MG_TUN_F_END_STREAM 0x1
  1643. /*
  1644. * MG TUN frame format is loosely based on HTTP/2.
  1645. * However since the communication happens via WebSocket
  1646. * there is no need to encode the frame length, since that's
  1647. * solved by WebSocket framing.
  1648. *
  1649. * TODO(mkm): Detailed description of the protocol.
  1650. */
  1651. struct mg_tun_frame {
  1652. uint8_t type;
  1653. uint8_t flags;
  1654. uint32_t stream_id; /* opaque stream identifier */
  1655. struct mg_str body;
  1656. };
  1657. struct mg_tun_ssl_opts {
  1658. #if MG_ENABLE_SSL
  1659. const char *ssl_cert;
  1660. const char *ssl_key;
  1661. const char *ssl_ca_cert;
  1662. #else
  1663. int dummy; /* some compilers don't like empty structs */
  1664. #endif
  1665. };
  1666. struct mg_tun_client {
  1667. struct mg_mgr *mgr;
  1668. struct mg_iface *iface;
  1669. const char *disp_url;
  1670. struct mg_tun_ssl_opts ssl;
  1671. uint32_t last_stream_id; /* stream id of most recently accepted connection */
  1672. struct mg_connection *disp;
  1673. struct mg_connection *listener;
  1674. struct mg_connection *reconnect;
  1675. };
  1676. #ifdef __cplusplus
  1677. extern "C" {
  1678. #endif /* __cplusplus */
  1679. struct mg_connection *mg_tun_bind_opt(struct mg_mgr *mgr,
  1680. const char *dispatcher,
  1681. mg_event_handler_t handler,
  1682. struct mg_bind_opts opts);
  1683. int mg_tun_parse_frame(void *data, size_t len, struct mg_tun_frame *frame);
  1684. void mg_tun_send_frame(struct mg_connection *ws, uint32_t stream_id,
  1685. uint8_t type, uint8_t flags, struct mg_str msg);
  1686. void mg_tun_destroy_client(struct mg_tun_client *client);
  1687. #ifdef __cplusplus
  1688. }
  1689. #endif /* __cplusplus */
  1690. #endif /* MG_ENABLE_TUN */
  1691. #endif /* CS_MONGOOSE_SRC_TUN_H_ */
  1692. #ifdef MG_MODULE_LINES
  1693. #line 1 "mongoose/src/net.c"
  1694. #endif
  1695. /*
  1696. * Copyright (c) 2014 Cesanta Software Limited
  1697. * All rights reserved
  1698. *
  1699. * This software is dual-licensed: you can redistribute it and/or modify
  1700. * it under the terms of the GNU General Public License version 2 as
  1701. * published by the Free Software Foundation. For the terms of this
  1702. * license, see <http://www.gnu.org/licenses/>.
  1703. *
  1704. * You are free to use this software under the terms of the GNU General
  1705. * Public License, but WITHOUT ANY WARRANTY; without even the implied
  1706. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  1707. * See the GNU General Public License for more details.
  1708. *
  1709. * Alternatively, you can license this software under a commercial
  1710. * license, as set out in <https://www.cesanta.com/license>.
  1711. */
  1712. /* Amalgamated: #include "common/cs_time.h" */
  1713. /* Amalgamated: #include "mongoose/src/dns.h" */
  1714. /* Amalgamated: #include "mongoose/src/internal.h" */
  1715. /* Amalgamated: #include "mongoose/src/resolv.h" */
  1716. /* Amalgamated: #include "mongoose/src/util.h" */
  1717. /* Amalgamated: #include "mongoose/src/tun.h" */
  1718. #define MG_MAX_HOST_LEN 200
  1719. #define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
  1720. memcpy(dst, src, sizeof(*dst));
  1721. /* Which flags can be pre-set by the user at connection creation time. */
  1722. #define _MG_ALLOWED_CONNECT_FLAGS_MASK \
  1723. (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
  1724. MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
  1725. /* Which flags should be modifiable by user's callbacks. */
  1726. #define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
  1727. (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
  1728. MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
  1729. MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
  1730. #ifndef intptr_t
  1731. #define intptr_t long
  1732. #endif
  1733. MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
  1734. DBG(("%p %p", mgr, c));
  1735. c->mgr = mgr;
  1736. c->next = mgr->active_connections;
  1737. mgr->active_connections = c;
  1738. c->prev = NULL;
  1739. if (c->next != NULL) c->next->prev = c;
  1740. if (c->sock != INVALID_SOCKET) {
  1741. c->iface->vtable->add_conn(c);
  1742. }
  1743. }
  1744. MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
  1745. if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
  1746. if (conn->prev) conn->prev->next = conn->next;
  1747. if (conn->next) conn->next->prev = conn->prev;
  1748. conn->prev = conn->next = NULL;
  1749. conn->iface->vtable->remove_conn(conn);
  1750. }
  1751. MG_INTERNAL void mg_call(struct mg_connection *nc,
  1752. mg_event_handler_t ev_handler, int ev, void *ev_data) {
  1753. if (ev_handler == NULL) {
  1754. /*
  1755. * If protocol handler is specified, call it. Otherwise, call user-specified
  1756. * event handler.
  1757. */
  1758. ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
  1759. }
  1760. if (ev != MG_EV_POLL) {
  1761. DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc,
  1762. ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
  1763. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  1764. }
  1765. #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
  1766. /* LCOV_EXCL_START */
  1767. if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL &&
  1768. ev != MG_EV_SEND /* handled separately */) {
  1769. if (ev == MG_EV_RECV) {
  1770. mg_hexdump_connection(nc, nc->mgr->hexdump_file, nc->recv_mbuf.buf,
  1771. *(int *) ev_data, ev);
  1772. } else {
  1773. mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
  1774. }
  1775. }
  1776. /* LCOV_EXCL_STOP */
  1777. #endif
  1778. if (ev_handler != NULL) {
  1779. unsigned long flags_before = nc->flags;
  1780. size_t recv_mbuf_before = nc->recv_mbuf.len, recved;
  1781. ev_handler(nc, ev, ev_data);
  1782. recved = (recv_mbuf_before - nc->recv_mbuf.len);
  1783. /* Prevent user handler from fiddling with system flags. */
  1784. if (ev_handler == nc->handler && nc->flags != flags_before) {
  1785. nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
  1786. (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
  1787. }
  1788. if (recved > 0 && !(nc->flags & MG_F_UDP)) {
  1789. nc->iface->vtable->recved(nc, recved);
  1790. }
  1791. }
  1792. if (ev != MG_EV_POLL) {
  1793. DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc,
  1794. ev_handler == nc->handler ? "user" : "proto", nc->flags,
  1795. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  1796. }
  1797. }
  1798. void mg_if_timer(struct mg_connection *c, double now) {
  1799. if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
  1800. double old_value = c->ev_timer_time;
  1801. mg_call(c, NULL, MG_EV_TIMER, &now);
  1802. /*
  1803. * To prevent timer firing all the time, reset the timer after delivery.
  1804. * However, in case user sets it to new value, do not reset.
  1805. */
  1806. if (c->ev_timer_time == old_value) {
  1807. c->ev_timer_time = 0;
  1808. }
  1809. }
  1810. }
  1811. void mg_if_poll(struct mg_connection *nc, time_t now) {
  1812. if (!(nc->flags & MG_F_SSL) || (nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
  1813. mg_call(nc, NULL, MG_EV_POLL, &now);
  1814. }
  1815. }
  1816. static void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
  1817. if (destroy_if) conn->iface->vtable->destroy_conn(conn);
  1818. if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
  1819. conn->proto_data_destructor(conn->proto_data);
  1820. }
  1821. #if MG_ENABLE_SSL
  1822. mg_ssl_if_conn_free(conn);
  1823. #endif
  1824. mbuf_free(&conn->recv_mbuf);
  1825. mbuf_free(&conn->send_mbuf);
  1826. memset(conn, 0, sizeof(*conn));
  1827. MG_FREE(conn);
  1828. }
  1829. void mg_close_conn(struct mg_connection *conn) {
  1830. DBG(("%p %lu %d", conn, conn->flags, conn->sock));
  1831. mg_remove_conn(conn);
  1832. conn->iface->vtable->destroy_conn(conn);
  1833. mg_call(conn, NULL, MG_EV_CLOSE, NULL);
  1834. mg_destroy_conn(conn, 0 /* destroy_if */);
  1835. }
  1836. void mg_mgr_init(struct mg_mgr *m, void *user_data) {
  1837. struct mg_mgr_init_opts opts;
  1838. memset(&opts, 0, sizeof(opts));
  1839. mg_mgr_init_opt(m, user_data, opts);
  1840. }
  1841. void mg_mgr_init_opt(struct mg_mgr *m, void *user_data,
  1842. struct mg_mgr_init_opts opts) {
  1843. memset(m, 0, sizeof(*m));
  1844. #if MG_ENABLE_BROADCAST
  1845. m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
  1846. #endif
  1847. m->user_data = user_data;
  1848. #ifdef _WIN32
  1849. {
  1850. WSADATA data;
  1851. WSAStartup(MAKEWORD(2, 2), &data);
  1852. }
  1853. #elif defined(__unix__)
  1854. /* Ignore SIGPIPE signal, so if client cancels the request, it
  1855. * won't kill the whole process. */
  1856. signal(SIGPIPE, SIG_IGN);
  1857. #endif
  1858. #if MG_ENABLE_SSL
  1859. {
  1860. static int init_done;
  1861. if (!init_done) {
  1862. mg_ssl_if_init();
  1863. init_done++;
  1864. }
  1865. }
  1866. #endif
  1867. {
  1868. int i;
  1869. if (opts.num_ifaces == 0) {
  1870. opts.num_ifaces = mg_num_ifaces;
  1871. opts.ifaces = mg_ifaces;
  1872. }
  1873. if (opts.main_iface != NULL) {
  1874. opts.ifaces[MG_MAIN_IFACE] = opts.main_iface;
  1875. }
  1876. m->num_ifaces = opts.num_ifaces;
  1877. m->ifaces =
  1878. (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces);
  1879. for (i = 0; i < mg_num_ifaces; i++) {
  1880. m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m);
  1881. m->ifaces[i]->vtable->init(m->ifaces[i]);
  1882. }
  1883. }
  1884. DBG(("=================================="));
  1885. DBG(("init mgr=%p", m));
  1886. }
  1887. #if MG_ENABLE_JAVASCRIPT
  1888. static enum v7_err mg_send_js(struct v7 *v7, v7_val_t *res) {
  1889. v7_val_t arg0 = v7_arg(v7, 0);
  1890. v7_val_t arg1 = v7_arg(v7, 1);
  1891. struct mg_connection *c = (struct mg_connection *) v7_get_ptr(v7, arg0);
  1892. size_t len = 0;
  1893. if (v7_is_string(arg1)) {
  1894. const char *data = v7_get_string(v7, &arg1, &len);
  1895. mg_send(c, data, len);
  1896. }
  1897. *res = v7_mk_number(v7, len);
  1898. return V7_OK;
  1899. }
  1900. enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
  1901. const char *init_file_name) {
  1902. v7_val_t v;
  1903. m->v7 = v7;
  1904. v7_set_method(v7, v7_get_global(v7), "mg_send", mg_send_js);
  1905. return v7_exec_file(v7, init_file_name, &v);
  1906. }
  1907. #endif
  1908. #if MG_ENABLE_CUSTOM_MILLIS
  1909. #else
  1910. uint64_t mg_millis(void) {
  1911. #if MG_ARCH == MG_ARCH_WIN32
  1912. return GetTickCount();
  1913. #elif MG_ARCH == MG_ARCH_RP2040
  1914. return time_us_64() / 1000;
  1915. #elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \
  1916. MG_ARCH == MG_ARCH_FREERTOS
  1917. return xTaskGetTickCount() * portTICK_PERIOD_MS;
  1918. #elif MG_ARCH == MG_ARCH_AZURERTOS
  1919. return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND);
  1920. #elif MG_ARCH == MG_ARCH_TIRTOS
  1921. return (uint64_t) Clock_getTicks();
  1922. #elif MG_ARCH == MG_ARCH_ZEPHYR
  1923. return (uint64_t) k_uptime_get();
  1924. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
  1925. return (uint64_t) rt_time_get();
  1926. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
  1927. return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq());
  1928. #elif MG_ARCH == MG_ARCH_RTTHREAD
  1929. return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND);
  1930. #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
  1931. // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
  1932. // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
  1933. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000;
  1934. #elif MG_ARCH == MG_ARCH_UNIX
  1935. struct timespec ts = {0, 0};
  1936. // See #1615 - prefer monotonic clock
  1937. #if defined(CLOCK_MONOTONIC_RAW)
  1938. // Raw hardware-based time that is not subject to NTP adjustment
  1939. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  1940. #elif defined(CLOCK_MONOTONIC)
  1941. // Affected by the incremental adjustments performed by adjtime and NTP
  1942. clock_gettime(CLOCK_MONOTONIC, &ts);
  1943. #else
  1944. // Affected by discontinuous jumps in the system time and by the incremental
  1945. // adjustments performed by adjtime and NTP
  1946. clock_gettime(CLOCK_REALTIME, &ts);
  1947. #endif
  1948. return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000);
  1949. #elif defined(ARDUINO)
  1950. return (uint64_t) millis();
  1951. #else
  1952. return (uint64_t) (time(NULL) * 1000);
  1953. #endif
  1954. }
  1955. #endif
  1956. void mg_mgr_free(struct mg_mgr *m) {
  1957. struct mg_connection *conn, *tmp_conn;
  1958. DBG(("%p", m));
  1959. if (m == NULL) return;
  1960. /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
  1961. mg_mgr_poll(m, 0);
  1962. #if MG_ENABLE_BROADCAST
  1963. if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
  1964. if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
  1965. m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
  1966. #endif
  1967. for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
  1968. tmp_conn = conn->next;
  1969. mg_close_conn(conn);
  1970. }
  1971. {
  1972. int i;
  1973. for (i = 0; i < m->num_ifaces; i++) {
  1974. m->ifaces[i]->vtable->free(m->ifaces[i]);
  1975. MG_FREE(m->ifaces[i]);
  1976. }
  1977. MG_FREE(m->ifaces);
  1978. }
  1979. }
  1980. time_t mg_mgr_poll(struct mg_mgr *m, int timeout_ms) {
  1981. int i;
  1982. time_t now = 0; /* oh GCC, seriously ? */
  1983. if (m->num_ifaces == 0) {
  1984. LOG(LL_ERROR, ("cannot poll: no interfaces"));
  1985. return 0;
  1986. }
  1987. // uint64_t _now;
  1988. // _now = mg_millis();
  1989. // mg_timer_poll(&m->timers, _now);
  1990. for (i = 0; i < m->num_ifaces; i++) {
  1991. now = m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms);
  1992. }
  1993. return now;
  1994. }
  1995. int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
  1996. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  1997. int len;
  1998. if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  1999. mg_send(nc, buf, len);
  2000. }
  2001. if (buf != mem && buf != NULL) {
  2002. MG_FREE(buf); /* LCOV_EXCL_LINE */
  2003. } /* LCOV_EXCL_LINE */
  2004. return len;
  2005. }
  2006. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  2007. int len;
  2008. va_list ap;
  2009. va_start(ap, fmt);
  2010. len = mg_vprintf(conn, fmt, ap);
  2011. va_end(ap);
  2012. return len;
  2013. }
  2014. #if MG_ENABLE_SYNC_RESOLVER
  2015. /* TODO(lsm): use non-blocking resolver */
  2016. static int mg_resolve2(const char *host, struct in_addr *ina) {
  2017. #if MG_ENABLE_GETADDRINFO
  2018. int rv = 0;
  2019. struct addrinfo hints, *servinfo, *p;
  2020. struct sockaddr_in *h = NULL;
  2021. memset(&hints, 0, sizeof hints);
  2022. hints.ai_family = AF_INET;
  2023. hints.ai_socktype = SOCK_STREAM;
  2024. if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
  2025. DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno())));
  2026. return 0;
  2027. }
  2028. for (p = servinfo; p != NULL; p = p->ai_next) {
  2029. memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
  2030. memcpy(ina, &h->sin_addr, sizeof(ina));
  2031. }
  2032. freeaddrinfo(servinfo);
  2033. return 1;
  2034. #else
  2035. struct hostent *he;
  2036. if ((he = gethostbyname(host)) == NULL) {
  2037. DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno())));
  2038. } else {
  2039. memcpy(ina, he->h_addr_list[0], sizeof(*ina));
  2040. return 1;
  2041. }
  2042. return 0;
  2043. #endif /* MG_ENABLE_GETADDRINFO */
  2044. }
  2045. int mg_resolve(const char *host, char *buf, size_t n) {
  2046. struct in_addr ad;
  2047. return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
  2048. }
  2049. #endif /* MG_ENABLE_SYNC_RESOLVER */
  2050. MG_INTERNAL struct mg_connection *mg_create_connection_base(
  2051. struct mg_mgr *mgr, mg_event_handler_t callback,
  2052. struct mg_add_sock_opts opts) {
  2053. struct mg_connection *conn;
  2054. if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
  2055. conn->sock = INVALID_SOCKET;
  2056. conn->handler = callback;
  2057. conn->mgr = mgr;
  2058. conn->last_io_time = (time_t) mg_time();
  2059. conn->iface =
  2060. (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]);
  2061. conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
  2062. conn->user_data = opts.user_data;
  2063. /*
  2064. * SIZE_MAX is defined as a long long constant in
  2065. * system headers on some platforms and so it
  2066. * doesn't compile with pedantic ansi flags.
  2067. */
  2068. conn->recv_mbuf_limit = ~0;
  2069. } else {
  2070. MG_SET_PTRPTR(opts.error_string, "failed to create connection");
  2071. }
  2072. return conn;
  2073. }
  2074. MG_INTERNAL struct mg_connection *mg_create_connection(
  2075. struct mg_mgr *mgr, mg_event_handler_t callback,
  2076. struct mg_add_sock_opts opts) {
  2077. struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
  2078. if (conn != NULL && !conn->iface->vtable->create_conn(conn)) {
  2079. MG_FREE(conn);
  2080. conn = NULL;
  2081. }
  2082. if (conn == NULL) {
  2083. MG_SET_PTRPTR(opts.error_string, "failed to init connection");
  2084. }
  2085. return conn;
  2086. }
  2087. /*
  2088. * Address format: [PROTO://][HOST]:PORT
  2089. *
  2090. * HOST could be IPv4/IPv6 address or a host name.
  2091. * `host` is a destination buffer to hold parsed HOST part. Shoud be at least
  2092. * MG_MAX_HOST_LEN bytes long.
  2093. * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
  2094. *
  2095. * Return:
  2096. * -1 on parse error
  2097. * 0 if HOST needs DNS lookup
  2098. * >0 length of the address string
  2099. */
  2100. MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
  2101. int *proto, char *host, size_t host_len) {
  2102. unsigned int a, b, c, d, port = 0;
  2103. int ch, len = 0;
  2104. #if MG_ENABLE_IPV6
  2105. char buf[100];
  2106. #endif
  2107. /*
  2108. * MacOS needs that. If we do not zero it, subsequent bind() will fail.
  2109. * Also, all-zeroes in the socket address means binding to all addresses
  2110. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  2111. */
  2112. memset(sa, 0, sizeof(*sa));
  2113. sa->sin.sin_family = AF_INET;
  2114. *proto = SOCK_STREAM;
  2115. if (strncmp(str, "udp://", 6) == 0) {
  2116. str += 6;
  2117. *proto = SOCK_DGRAM;
  2118. } else if (strncmp(str, "tcp://", 6) == 0) {
  2119. str += 6;
  2120. }
  2121. if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  2122. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  2123. sa->sin.sin_addr.s_addr =
  2124. htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
  2125. sa->sin.sin_port = htons((uint16_t) port);
  2126. #if MG_ENABLE_IPV6
  2127. } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
  2128. inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
  2129. /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
  2130. sa->sin6.sin6_family = AF_INET6;
  2131. sa->sin.sin_port = htons((uint16_t) port);
  2132. #endif
  2133. #if MG_ENABLE_ASYNC_RESOLVER
  2134. } else if (strlen(str) < host_len &&
  2135. sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
  2136. sa->sin.sin_port = htons((uint16_t) port);
  2137. if (mg_resolve_from_hosts_file(host, sa) != 0) {
  2138. /*
  2139. * if resolving from hosts file failed and the host
  2140. * we are trying to resolve is `localhost` - we should
  2141. * try to resolve it using `gethostbyname` and do not try
  2142. * to resolve it via DNS server if gethostbyname has failed too
  2143. */
  2144. if (mg_ncasecmp(host, "localhost", 9) != 0) {
  2145. return 0;
  2146. }
  2147. #if MG_ENABLE_SYNC_RESOLVER
  2148. if (!mg_resolve2(host, &sa->sin.sin_addr)) {
  2149. return -1;
  2150. }
  2151. #else
  2152. return -1;
  2153. #endif
  2154. }
  2155. #endif
  2156. } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
  2157. sscanf(str, "%u%n", &port, &len) == 1) {
  2158. /* If only port is specified, bind to IPv4, INADDR_ANY */
  2159. sa->sin.sin_port = htons((uint16_t) port);
  2160. } else {
  2161. return -1;
  2162. }
  2163. /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */
  2164. (void) host;
  2165. (void) host_len;
  2166. ch = str[len]; /* Character that follows the address */
  2167. return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
  2168. }
  2169. struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
  2170. struct mg_add_sock_opts opts;
  2171. struct mg_connection *nc;
  2172. memset(&opts, 0, sizeof(opts));
  2173. nc = mg_create_connection(lc->mgr, lc->handler, opts);
  2174. if (nc == NULL) return NULL;
  2175. nc->listener = lc;
  2176. nc->proto_handler = lc->proto_handler;
  2177. nc->user_data = lc->user_data;
  2178. nc->recv_mbuf_limit = lc->recv_mbuf_limit;
  2179. nc->iface = lc->iface;
  2180. if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL;
  2181. mg_add_conn(nc->mgr, nc);
  2182. DBG(("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags));
  2183. return nc;
  2184. }
  2185. void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
  2186. size_t sa_len) {
  2187. (void) sa_len;
  2188. nc->sa = *sa;
  2189. mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
  2190. }
  2191. void mg_send(struct mg_connection *nc, const void *buf, int len) {
  2192. nc->last_io_time = (time_t) mg_time();
  2193. if (nc->flags & MG_F_UDP) {
  2194. nc->iface->vtable->udp_send(nc, buf, len);
  2195. } else {
  2196. nc->iface->vtable->tcp_send(nc, buf, len);
  2197. }
  2198. #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
  2199. if (nc->mgr && nc->mgr->hexdump_file != NULL) {
  2200. mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, len, MG_EV_SEND);
  2201. }
  2202. #endif
  2203. }
  2204. void mg_if_sent_cb(struct mg_connection *nc, int num_sent) {
  2205. if (num_sent < 0) {
  2206. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2207. }
  2208. mg_call(nc, NULL, MG_EV_SEND, &num_sent);
  2209. }
  2210. MG_INTERNAL void mg_recv_common(struct mg_connection *nc, void *buf, int len,
  2211. int own) {
  2212. DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len));
  2213. if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
  2214. DBG(("%p discarded %d bytes", nc, len));
  2215. /*
  2216. * This connection will not survive next poll. Do not deliver events,
  2217. * send data to /dev/null without acking.
  2218. */
  2219. if (own) {
  2220. MG_FREE(buf);
  2221. }
  2222. return;
  2223. }
  2224. nc->last_io_time = (time_t) mg_time();
  2225. if (!own) {
  2226. mbuf_append(&nc->recv_mbuf, buf, len);
  2227. } else if (nc->recv_mbuf.len == 0) {
  2228. /* Adopt buf as recv_mbuf's backing store. */
  2229. mbuf_free(&nc->recv_mbuf);
  2230. nc->recv_mbuf.buf = (char *) buf;
  2231. nc->recv_mbuf.size = nc->recv_mbuf.len = len;
  2232. } else {
  2233. mbuf_append(&nc->recv_mbuf, buf, len);
  2234. MG_FREE(buf);
  2235. }
  2236. mg_call(nc, NULL, MG_EV_RECV, &len);
  2237. }
  2238. void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len, int own) {
  2239. mg_recv_common(nc, buf, len, own);
  2240. }
  2241. void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
  2242. union socket_address *sa, size_t sa_len) {
  2243. assert(nc->flags & MG_F_UDP);
  2244. DBG(("%p %u", nc, (unsigned int) len));
  2245. if (nc->flags & MG_F_LISTENING) {
  2246. struct mg_connection *lc = nc;
  2247. /*
  2248. * Do we have an existing connection for this source?
  2249. * This is very inefficient for long connection lists.
  2250. */
  2251. for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
  2252. if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0 && nc->listener == lc) {
  2253. break;
  2254. }
  2255. }
  2256. if (nc == NULL) {
  2257. struct mg_add_sock_opts opts;
  2258. memset(&opts, 0, sizeof(opts));
  2259. /* Create fake connection w/out sock initialization */
  2260. nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
  2261. if (nc != NULL) {
  2262. nc->sock = lc->sock;
  2263. nc->listener = lc;
  2264. nc->sa = *sa;
  2265. nc->proto_handler = lc->proto_handler;
  2266. nc->user_data = lc->user_data;
  2267. nc->recv_mbuf_limit = lc->recv_mbuf_limit;
  2268. nc->flags = MG_F_UDP;
  2269. /*
  2270. * Long-lived UDP "connections" i.e. interactions that involve more
  2271. * than one request and response are rare, most are transactional:
  2272. * response is sent and the "connection" is closed. Or - should be.
  2273. * But users (including ourselves) tend to forget about that part,
  2274. * because UDP is connectionless and one does not think about
  2275. * processing a UDP request as handling a connection that needs to be
  2276. * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should
  2277. * be a reasonable default for most use cases, but it is possible to
  2278. * turn it off the connection should be kept alive after processing.
  2279. */
  2280. nc->flags |= MG_F_SEND_AND_CLOSE;
  2281. mg_add_conn(lc->mgr, nc);
  2282. mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
  2283. } else {
  2284. DBG(("OOM"));
  2285. /* No return here, we still need to drop on the floor */
  2286. }
  2287. }
  2288. }
  2289. if (nc != NULL) {
  2290. mg_recv_common(nc, buf, len, 1);
  2291. } else {
  2292. /* Drop on the floor. */
  2293. MG_FREE(buf);
  2294. nc->iface->vtable->recved(nc, len);
  2295. }
  2296. }
  2297. /*
  2298. * Schedules an async connect for a resolved address and proto.
  2299. * Called from two places: `mg_connect_opt()` and from async resolver.
  2300. * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
  2301. * with a failure flag to indicate connection failure.
  2302. */
  2303. MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
  2304. int proto,
  2305. union socket_address *sa) {
  2306. DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
  2307. inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
  2308. nc->flags |= MG_F_CONNECTING;
  2309. if (proto == SOCK_DGRAM) {
  2310. nc->iface->vtable->connect_udp(nc);
  2311. } else {
  2312. nc->iface->vtable->connect_tcp(nc, sa);
  2313. }
  2314. mg_add_conn(nc->mgr, nc);
  2315. return nc;
  2316. }
  2317. void mg_if_connect_cb(struct mg_connection *nc, int err) {
  2318. DBG(("%p connect, err=%d", nc, err));
  2319. nc->flags &= ~MG_F_CONNECTING;
  2320. if (err != 0) {
  2321. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2322. }
  2323. mg_call(nc, NULL, MG_EV_CONNECT, &err);
  2324. }
  2325. #if MG_ENABLE_ASYNC_RESOLVER
  2326. /*
  2327. * Callback for the async resolver on mg_connect_opt() call.
  2328. * Main task of this function is to trigger MG_EV_CONNECT event with
  2329. * either failure (and dealloc the connection)
  2330. * or success (and proceed with connect()
  2331. */
  2332. static void resolve_cb(struct mg_dns_message *msg, void *data,
  2333. enum mg_resolve_err e) {
  2334. struct mg_connection *nc = (struct mg_connection *) data;
  2335. int i;
  2336. int failure = -1;
  2337. nc->flags &= ~MG_F_RESOLVING;
  2338. if (msg != NULL) {
  2339. /*
  2340. * Take the first DNS A answer and run...
  2341. */
  2342. for (i = 0; i < msg->num_answers; i++) {
  2343. if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
  2344. /*
  2345. * Async resolver guarantees that there is at least one answer.
  2346. * TODO(lsm): handle IPv6 answers too
  2347. */
  2348. mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
  2349. 4);
  2350. mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
  2351. &nc->sa);
  2352. return;
  2353. }
  2354. }
  2355. }
  2356. if (e == MG_RESOLVE_TIMEOUT) {
  2357. double now = mg_time();
  2358. mg_call(nc, NULL, MG_EV_TIMER, &now);
  2359. }
  2360. /*
  2361. * If we get there was no MG_DNS_A_RECORD in the answer
  2362. */
  2363. mg_call(nc, NULL, MG_EV_CONNECT, &failure);
  2364. mg_call(nc, NULL, MG_EV_CLOSE, NULL);
  2365. mg_destroy_conn(nc, 1 /* destroy_if */);
  2366. }
  2367. #endif
  2368. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
  2369. mg_event_handler_t callback) {
  2370. struct mg_connect_opts opts;
  2371. memset(&opts, 0, sizeof(opts));
  2372. return mg_connect_opt(mgr, address, callback, opts);
  2373. }
  2374. struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
  2375. mg_event_handler_t callback,
  2376. struct mg_connect_opts opts) {
  2377. struct mg_connection *nc = NULL;
  2378. int proto, rc;
  2379. struct mg_add_sock_opts add_sock_opts;
  2380. char host[MG_MAX_HOST_LEN];
  2381. MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
  2382. if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
  2383. return NULL;
  2384. }
  2385. if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) <
  2386. 0) {
  2387. /* Address is malformed */
  2388. MG_SET_PTRPTR(opts.error_string, "cannot parse address");
  2389. mg_destroy_conn(nc, 1 /* destroy_if */);
  2390. return NULL;
  2391. }
  2392. nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
  2393. nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
  2394. nc->user_data = opts.user_data;
  2395. #if MG_ENABLE_SSL
  2396. DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
  2397. (opts.ssl_key ? opts.ssl_key : "-"),
  2398. (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
  2399. if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
  2400. opts.ssl_psk_identity != NULL) {
  2401. const char *err_msg = NULL;
  2402. struct mg_ssl_if_conn_params params;
  2403. if (nc->flags & MG_F_UDP) {
  2404. MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
  2405. mg_destroy_conn(nc, 1 /* destroy_if */);
  2406. return NULL;
  2407. }
  2408. memset(&params, 0, sizeof(params));
  2409. params.cert = opts.ssl_cert;
  2410. params.key = opts.ssl_key;
  2411. params.ca_cert = opts.ssl_ca_cert;
  2412. params.cipher_suites = opts.ssl_cipher_suites;
  2413. params.psk_identity = opts.ssl_psk_identity;
  2414. params.psk_key = opts.ssl_psk_key;
  2415. if (opts.ssl_ca_cert != NULL) {
  2416. if (opts.ssl_server_name != NULL) {
  2417. if (strcmp(opts.ssl_server_name, "*") != 0) {
  2418. params.server_name = opts.ssl_server_name;
  2419. }
  2420. } else if (rc == 0) { /* If it's a DNS name, use host. */
  2421. params.server_name = host;
  2422. }
  2423. }
  2424. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  2425. MG_SET_PTRPTR(opts.error_string, err_msg);
  2426. mg_destroy_conn(nc, 1 /* destroy_if */);
  2427. return NULL;
  2428. }
  2429. nc->flags |= MG_F_SSL;
  2430. }
  2431. #endif /* MG_ENABLE_SSL */
  2432. if (rc == 0) {
  2433. #if MG_ENABLE_ASYNC_RESOLVER
  2434. /*
  2435. * DNS resolution is required for host.
  2436. * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
  2437. */
  2438. struct mg_connection *dns_conn = NULL;
  2439. struct mg_resolve_async_opts o;
  2440. memset(&o, 0, sizeof(o));
  2441. o.dns_conn = &dns_conn;
  2442. if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
  2443. o) != 0) {
  2444. MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
  2445. mg_destroy_conn(nc, 1 /* destroy_if */);
  2446. return NULL;
  2447. }
  2448. nc->priv_2 = dns_conn;
  2449. nc->flags |= MG_F_RESOLVING;
  2450. return nc;
  2451. #else
  2452. MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
  2453. mg_destroy_conn(nc, 1 /* destroy_if */);
  2454. return NULL;
  2455. #endif
  2456. } else {
  2457. /* Address is parsed and resolved to IP. proceed with connect() */
  2458. return mg_do_connect(nc, proto, &nc->sa);
  2459. }
  2460. }
  2461. struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
  2462. mg_event_handler_t event_handler) {
  2463. struct mg_bind_opts opts;
  2464. memset(&opts, 0, sizeof(opts));
  2465. return mg_bind_opt(srv, address, event_handler, opts);
  2466. }
  2467. struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
  2468. mg_event_handler_t callback,
  2469. struct mg_bind_opts opts) {
  2470. union socket_address sa;
  2471. struct mg_connection *nc = NULL;
  2472. int proto, rc;
  2473. struct mg_add_sock_opts add_sock_opts;
  2474. char host[MG_MAX_HOST_LEN];
  2475. MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
  2476. #if MG_ENABLE_TUN
  2477. if (mg_strncmp(mg_mk_str(address), mg_mk_str("ws://"), 5) == 0 ||
  2478. mg_strncmp(mg_mk_str(address), mg_mk_str("wss://"), 6) == 0) {
  2479. return mg_tun_bind_opt(mgr, address, callback, opts);
  2480. }
  2481. #endif
  2482. if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
  2483. MG_SET_PTRPTR(opts.error_string, "cannot parse address");
  2484. return NULL;
  2485. }
  2486. nc = mg_create_connection(mgr, callback, add_sock_opts);
  2487. if (nc == NULL) {
  2488. return NULL;
  2489. }
  2490. nc->sa = sa;
  2491. nc->flags |= MG_F_LISTENING;
  2492. if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP;
  2493. #if MG_ENABLE_SSL
  2494. DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
  2495. (opts.ssl_key ? opts.ssl_key : "-"),
  2496. (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
  2497. if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
  2498. const char *err_msg = NULL;
  2499. struct mg_ssl_if_conn_params params;
  2500. if (nc->flags & MG_F_UDP) {
  2501. MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
  2502. mg_destroy_conn(nc, 1 /* destroy_if */);
  2503. return NULL;
  2504. }
  2505. memset(&params, 0, sizeof(params));
  2506. params.cert = opts.ssl_cert;
  2507. params.key = opts.ssl_key;
  2508. params.ca_cert = opts.ssl_ca_cert;
  2509. params.cipher_suites = opts.ssl_cipher_suites;
  2510. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  2511. MG_SET_PTRPTR(opts.error_string, err_msg);
  2512. mg_destroy_conn(nc, 1 /* destroy_if */);
  2513. return NULL;
  2514. }
  2515. nc->flags |= MG_F_SSL;
  2516. }
  2517. #endif /* MG_ENABLE_SSL */
  2518. if (nc->flags & MG_F_UDP) {
  2519. rc = nc->iface->vtable->listen_udp(nc, &nc->sa);
  2520. } else {
  2521. rc = nc->iface->vtable->listen_tcp(nc, &nc->sa);
  2522. }
  2523. if (rc != 0) {
  2524. DBG(("Failed to open listener: %d", rc));
  2525. MG_SET_PTRPTR(opts.error_string, "failed to open listener");
  2526. mg_destroy_conn(nc, 1 /* destroy_if */);
  2527. return NULL;
  2528. }
  2529. mg_add_conn(nc->mgr, nc);
  2530. return nc;
  2531. }
  2532. struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
  2533. return conn == NULL ? s->active_connections : conn->next;
  2534. }
  2535. #if MG_ENABLE_BROADCAST
  2536. void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
  2537. size_t len) {
  2538. struct ctl_msg ctl_msg;
  2539. /*
  2540. * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
  2541. * where `mg_broadcast()` pushes the message.
  2542. * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
  2543. * specified callback for each connection. Thus the callback function executes
  2544. * in event manager thread.
  2545. */
  2546. if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
  2547. len < sizeof(ctl_msg.message)) {
  2548. size_t dummy;
  2549. ctl_msg.callback = cb;
  2550. memcpy(ctl_msg.message, data, len);
  2551. dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
  2552. offsetof(struct ctl_msg, message) + len, 0);
  2553. dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
  2554. (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
  2555. }
  2556. }
  2557. #endif /* MG_ENABLE_BROADCAST */
  2558. static int isbyte(int n) {
  2559. return n >= 0 && n <= 255;
  2560. }
  2561. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  2562. int n, a, b, c, d, slash = 32, len = 0;
  2563. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  2564. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  2565. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  2566. slash < 33) {
  2567. len = n;
  2568. *net =
  2569. ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
  2570. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  2571. }
  2572. return len;
  2573. }
  2574. int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
  2575. int allowed, flag;
  2576. uint32_t net, mask;
  2577. struct mg_str vec;
  2578. /* If any ACL is set, deny by default */
  2579. allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
  2580. while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
  2581. flag = vec.p[0];
  2582. if ((flag != '+' && flag != '-') ||
  2583. parse_net(&vec.p[1], &net, &mask) == 0) {
  2584. return -1;
  2585. }
  2586. if (net == (remote_ip & mask)) {
  2587. allowed = flag;
  2588. }
  2589. }
  2590. DBG(("%08x %c", remote_ip, allowed));
  2591. return allowed == '+';
  2592. }
  2593. /* Move data from one connection to another */
  2594. void mg_forward(struct mg_connection *from, struct mg_connection *to) {
  2595. mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
  2596. mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
  2597. }
  2598. double mg_set_timer(struct mg_connection *c, double timestamp) {
  2599. double result = c->ev_timer_time;
  2600. c->ev_timer_time = timestamp;
  2601. /*
  2602. * If this connection is resolving, it's not in the list of active
  2603. * connections, so not processed yet. It has a DNS resolver connection
  2604. * linked to it. Set up a timer for the DNS connection.
  2605. */
  2606. DBG(("%p %p %d -> %lu", c, c->priv_2, c->flags & MG_F_RESOLVING,
  2607. (unsigned long) timestamp));
  2608. if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
  2609. ((struct mg_connection *) c->priv_2)->ev_timer_time = timestamp;
  2610. }
  2611. return result;
  2612. }
  2613. void mg_sock_set(struct mg_connection *nc, sock_t sock) {
  2614. if (sock != INVALID_SOCKET) {
  2615. nc->iface->vtable->sock_set(nc, sock);
  2616. }
  2617. }
  2618. void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
  2619. union socket_address *sa) {
  2620. nc->iface->vtable->get_conn_addr(nc, remote, sa);
  2621. }
  2622. struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
  2623. mg_event_handler_t callback,
  2624. struct mg_add_sock_opts opts) {
  2625. struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
  2626. if (nc != NULL) {
  2627. mg_sock_set(nc, sock);
  2628. mg_add_conn(nc->mgr, nc);
  2629. }
  2630. return nc;
  2631. }
  2632. struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
  2633. mg_event_handler_t callback) {
  2634. struct mg_add_sock_opts opts;
  2635. memset(&opts, 0, sizeof(opts));
  2636. return mg_add_sock_opt(s, sock, callback, opts);
  2637. }
  2638. double mg_time(void) {
  2639. return cs_time();
  2640. }
  2641. #ifdef MG_MODULE_LINES
  2642. #line 1 "mongoose/src/net_if_socket.h"
  2643. #endif
  2644. /*
  2645. * Copyright (c) 2014-2016 Cesanta Software Limited
  2646. * All rights reserved
  2647. */
  2648. #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
  2649. #define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
  2650. /* Amalgamated: #include "mongoose/src/net_if.h" */
  2651. #ifdef __cplusplus
  2652. extern "C" {
  2653. #endif /* __cplusplus */
  2654. #ifndef MG_ENABLE_NET_IF_SOCKET
  2655. #define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
  2656. #endif
  2657. extern struct mg_iface_vtable mg_socket_iface_vtable;
  2658. #ifdef __cplusplus
  2659. }
  2660. #endif /* __cplusplus */
  2661. #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */
  2662. #ifdef MG_MODULE_LINES
  2663. #line 1 "mongoose/src/net_if_tun.h"
  2664. #endif
  2665. /*
  2666. * Copyright (c) 2014-2016 Cesanta Software Limited
  2667. * All rights reserved
  2668. */
  2669. #ifndef CS_MONGOOSE_SRC_NET_IF_TUN_H_
  2670. #define CS_MONGOOSE_SRC_NET_IF_TUN_H_
  2671. #if MG_ENABLE_TUN
  2672. /* Amalgamated: #include "mongoose/src/net_if.h" */
  2673. struct mg_tun_client;
  2674. #ifdef __cplusplus
  2675. extern "C" {
  2676. #endif /* __cplusplus */
  2677. extern struct mg_iface_vtable mg_tun_iface_vtable;
  2678. struct mg_connection *mg_tun_if_find_conn(struct mg_tun_client *client,
  2679. uint32_t stream_id);
  2680. #ifdef __cplusplus
  2681. }
  2682. #endif /* __cplusplus */
  2683. #endif /* MG_ENABLE_TUN */
  2684. #endif /* CS_MONGOOSE_SRC_NET_IF_TUN_H_ */
  2685. #ifdef MG_MODULE_LINES
  2686. #line 1 "mongoose/src/net_if.c"
  2687. #endif
  2688. /* Amalgamated: #include "mongoose/src/net_if.h" */
  2689. /* Amalgamated: #include "mongoose/src/internal.h" */
  2690. /* Amalgamated: #include "mongoose/src/net_if_socket.h" */
  2691. /* Amalgamated: #include "mongoose/src/net_if_tun.h" */
  2692. extern struct mg_iface_vtable mg_default_iface_vtable;
  2693. #if MG_ENABLE_TUN
  2694. struct mg_iface_vtable *mg_ifaces[] = {&mg_default_iface_vtable,
  2695. &mg_tun_iface_vtable};
  2696. #else
  2697. struct mg_iface_vtable *mg_ifaces[] = {&mg_default_iface_vtable};
  2698. #endif
  2699. int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0]));
  2700. struct mg_iface *mg_if_create_iface(struct mg_iface_vtable *vtable,
  2701. struct mg_mgr *mgr) {
  2702. struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface));
  2703. iface->mgr = mgr;
  2704. iface->data = NULL;
  2705. iface->vtable = vtable;
  2706. return iface;
  2707. }
  2708. struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
  2709. struct mg_iface_vtable *vtable,
  2710. struct mg_iface *from) {
  2711. int i = 0;
  2712. if (from != NULL) {
  2713. for (i = 0; i < mgr->num_ifaces; i++) {
  2714. if (mgr->ifaces[i] == from) {
  2715. i++;
  2716. break;
  2717. }
  2718. }
  2719. }
  2720. for (; i < mgr->num_ifaces; i++) {
  2721. if (mgr->ifaces[i]->vtable == vtable) {
  2722. return mgr->ifaces[i];
  2723. }
  2724. }
  2725. return NULL;
  2726. }
  2727. #ifdef MG_MODULE_LINES
  2728. #line 1 "mongoose/src/net_if_socket.c"
  2729. #endif
  2730. /*
  2731. * Copyright (c) 2014-2016 Cesanta Software Limited
  2732. * All rights reserved
  2733. */
  2734. #if MG_ENABLE_NET_IF_SOCKET
  2735. /* Amalgamated: #include "mongoose/src/net_if_socket.h" */
  2736. /* Amalgamated: #include "mongoose/src/internal.h" */
  2737. /* Amalgamated: #include "mongoose/src/util.h" */
  2738. #define MG_TCP_RECV_BUFFER_SIZE 1024
  2739. #define MG_UDP_RECV_BUFFER_SIZE 1500
  2740. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  2741. int proto);
  2742. #if MG_ENABLE_SSL
  2743. static void mg_ssl_begin(struct mg_connection *nc);
  2744. #endif
  2745. void mg_set_non_blocking_mode(sock_t sock) {
  2746. #ifdef _WIN32
  2747. unsigned long on = 1;
  2748. ioctlsocket(sock, FIONBIO, &on);
  2749. #else
  2750. int flags = fcntl(sock, F_GETFL, 0);
  2751. fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2752. #endif
  2753. }
  2754. static int mg_is_error(int n) {
  2755. int err = mg_get_errno();
  2756. return (n < 0 && err != EINPROGRESS && err != EWOULDBLOCK
  2757. #ifndef WINCE
  2758. && err != EAGAIN && err != EINTR
  2759. #endif
  2760. #ifdef _WIN32
  2761. && WSAGetLastError() != WSAEINTR &&
  2762. WSAGetLastError() != WSAEWOULDBLOCK
  2763. #endif
  2764. );
  2765. }
  2766. void mg_socket_if_connect_tcp(struct mg_connection *nc,
  2767. const union socket_address *sa) {
  2768. int rc, proto = 0;
  2769. nc->sock = socket(AF_INET, SOCK_STREAM, proto);
  2770. if (nc->sock == INVALID_SOCKET) {
  2771. nc->err = mg_get_errno() ? mg_get_errno() : 1;
  2772. return;
  2773. }
  2774. #if !defined(MG_ESP8266)
  2775. mg_set_non_blocking_mode(nc->sock);
  2776. #endif
  2777. rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
  2778. nc->err = mg_is_error(rc) ? mg_get_errno() : 0;
  2779. DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(),
  2780. nc->err));
  2781. }
  2782. void mg_socket_if_connect_udp(struct mg_connection *nc) {
  2783. nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
  2784. if (nc->sock == INVALID_SOCKET) {
  2785. nc->err = mg_get_errno() ? mg_get_errno() : 1;
  2786. return;
  2787. }
  2788. if (nc->flags & MG_F_ENABLE_BROADCAST) {
  2789. int optval = 1;
  2790. setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval,
  2791. sizeof(optval));
  2792. }
  2793. nc->err = 0;
  2794. }
  2795. int mg_socket_if_listen_tcp(struct mg_connection *nc,
  2796. union socket_address *sa) {
  2797. int proto = 0;
  2798. sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
  2799. if (sock == INVALID_SOCKET) {
  2800. return (mg_get_errno() ? mg_get_errno() : 1);
  2801. }
  2802. mg_sock_set(nc, sock);
  2803. return 0;
  2804. }
  2805. int mg_socket_if_listen_udp(struct mg_connection *nc,
  2806. union socket_address *sa) {
  2807. sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
  2808. if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1);
  2809. mg_sock_set(nc, sock);
  2810. return 0;
  2811. }
  2812. void mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf,
  2813. size_t len) {
  2814. mbuf_append(&nc->send_mbuf, buf, len);
  2815. }
  2816. void mg_socket_if_udp_send(struct mg_connection *nc, const void *buf,
  2817. size_t len) {
  2818. mbuf_append(&nc->send_mbuf, buf, len);
  2819. }
  2820. void mg_socket_if_recved(struct mg_connection *nc, size_t len) {
  2821. (void) nc;
  2822. (void) len;
  2823. }
  2824. int mg_socket_if_create_conn(struct mg_connection *nc) {
  2825. (void) nc;
  2826. return 1;
  2827. }
  2828. void mg_socket_if_destroy_conn(struct mg_connection *nc) {
  2829. if (nc->sock == INVALID_SOCKET) return;
  2830. if (!(nc->flags & MG_F_UDP)) {
  2831. closesocket(nc->sock);
  2832. } else {
  2833. /* Only close outgoing UDP sockets or listeners. */
  2834. if (nc->listener == NULL) closesocket(nc->sock);
  2835. }
  2836. nc->sock = INVALID_SOCKET;
  2837. }
  2838. static int mg_accept_conn(struct mg_connection *lc) {
  2839. struct mg_connection *nc;
  2840. union socket_address sa;
  2841. socklen_t sa_len = sizeof(sa);
  2842. /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
  2843. sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
  2844. if (sock == INVALID_SOCKET) {
  2845. if (mg_is_error(-1)) DBG(("%p: failed to accept: %d", lc, mg_get_errno()));
  2846. return 0;
  2847. }
  2848. nc = mg_if_accept_new_conn(lc);
  2849. if (nc == NULL) {
  2850. closesocket(sock);
  2851. return 0;
  2852. }
  2853. DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
  2854. ntohs(sa.sin.sin_port)));
  2855. mg_sock_set(nc, sock);
  2856. #if MG_ENABLE_SSL
  2857. if (lc->flags & MG_F_SSL) {
  2858. if (mg_ssl_if_conn_accept(nc, lc) != MG_SSL_OK) mg_close_conn(nc);
  2859. } else
  2860. #endif
  2861. {
  2862. mg_if_accept_tcp_cb(nc, &sa, sa_len);
  2863. }
  2864. return 1;
  2865. }
  2866. /* 'sa' must be an initialized address to bind to */
  2867. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  2868. int proto) {
  2869. socklen_t sa_len =
  2870. (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
  2871. sock_t sock = INVALID_SOCKET;
  2872. #if !MG_LWIP
  2873. int on = 1;
  2874. #endif
  2875. if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET &&
  2876. #if !MG_LWIP /* LWIP doesn't support either */
  2877. #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
  2878. /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
  2879. !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
  2880. sizeof(on)) &&
  2881. #endif
  2882. #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
  2883. /*
  2884. * SO_RESUSEADDR is not enabled on Windows because the semantics of
  2885. * SO_REUSEADDR on UNIX and Windows is different. On Windows,
  2886. * SO_REUSEADDR allows to bind a socket to a port without error even if
  2887. * the port is already open by another program. This is not the behavior
  2888. * SO_REUSEADDR was designed for, and leads to hard-to-track failure
  2889. * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
  2890. * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
  2891. */
  2892. !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
  2893. #endif
  2894. #endif /* !MG_LWIP */
  2895. !bind(sock, &sa->sa, sa_len) &&
  2896. (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
  2897. #if !MG_LWIP
  2898. mg_set_non_blocking_mode(sock);
  2899. /* In case port was set to 0, get the real port number */
  2900. (void) getsockname(sock, &sa->sa, &sa_len);
  2901. #endif
  2902. } else if (sock != INVALID_SOCKET) {
  2903. closesocket(sock);
  2904. sock = INVALID_SOCKET;
  2905. }
  2906. return sock;
  2907. }
  2908. static void mg_write_to_socket(struct mg_connection *nc) {
  2909. struct mbuf *io = &nc->send_mbuf;
  2910. int n = 0;
  2911. #if MG_LWIP
  2912. /* With LWIP we don't know if the socket is ready */
  2913. if (io->len == 0) return;
  2914. #endif
  2915. assert(io->len > 0);
  2916. if (nc->flags & MG_F_UDP) {
  2917. int n =
  2918. sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
  2919. DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, mg_get_errno(),
  2920. inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
  2921. if (n > 0) {
  2922. mbuf_remove(io, n);
  2923. mg_if_sent_cb(nc, n);
  2924. }
  2925. return;
  2926. }
  2927. #if MG_ENABLE_SSL
  2928. if (nc->flags & MG_F_SSL) {
  2929. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  2930. n = mg_ssl_if_write(nc, io->buf, io->len);
  2931. DBG(("%p %d bytes -> %d (SSL)", nc, n, nc->sock));
  2932. if (n < 0) {
  2933. if (n != MG_SSL_WANT_READ && n != MG_SSL_WANT_WRITE) {
  2934. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2935. }
  2936. return;
  2937. } else {
  2938. /* Successful SSL operation, clear off SSL wait flags */
  2939. nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
  2940. }
  2941. } else {
  2942. mg_ssl_begin(nc);
  2943. return;
  2944. }
  2945. } else
  2946. #endif
  2947. {
  2948. n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0);
  2949. DBG(("%p %d bytes -> %d", nc, n, nc->sock));
  2950. if (n < 0 && mg_is_error(n)) {
  2951. /* Something went wrong, drop the connection. */
  2952. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2953. return;
  2954. }
  2955. }
  2956. if (n > 0) {
  2957. mbuf_remove(io, n);
  2958. mg_if_sent_cb(nc, n);
  2959. }
  2960. }
  2961. MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
  2962. size_t avail;
  2963. if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
  2964. avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
  2965. return avail > max ? max : avail;
  2966. }
  2967. static void mg_handle_tcp_read(struct mg_connection *conn) {
  2968. int n = 0;
  2969. char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
  2970. if (buf == NULL) {
  2971. DBG(("OOM"));
  2972. return;
  2973. }
  2974. #if MG_ENABLE_SSL
  2975. if (conn->flags & MG_F_SSL) {
  2976. if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
  2977. /* SSL library may have more bytes ready to read than we ask to read.
  2978. * Therefore, read in a loop until we read everything. Without the loop,
  2979. * we skip to the next select() cycle which can just timeout. */
  2980. while ((n = mg_ssl_if_read(conn, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) {
  2981. DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
  2982. mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
  2983. buf = NULL;
  2984. if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
  2985. /* buf has been freed, we need a new one. */
  2986. buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
  2987. if (buf == NULL) break;
  2988. }
  2989. MG_FREE(buf);
  2990. if (n < 0 && n != MG_SSL_WANT_READ) conn->flags |= MG_F_CLOSE_IMMEDIATELY;
  2991. } else {
  2992. MG_FREE(buf);
  2993. mg_ssl_begin(conn);
  2994. return;
  2995. }
  2996. } else
  2997. #endif
  2998. {
  2999. n = (int) MG_RECV_FUNC(conn->sock, buf,
  3000. recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
  3001. DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
  3002. if (n > 0) {
  3003. mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
  3004. } else {
  3005. MG_FREE(buf);
  3006. }
  3007. if (n == 0) {
  3008. /* Orderly shutdown of the socket, try flushing output. */
  3009. conn->flags |= MG_F_SEND_AND_CLOSE;
  3010. } else if (mg_is_error(n)) {
  3011. conn->flags |= MG_F_CLOSE_IMMEDIATELY;
  3012. }
  3013. }
  3014. }
  3015. static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa,
  3016. socklen_t *sa_len, char **buf) {
  3017. int n;
  3018. *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
  3019. if (*buf == NULL) {
  3020. DBG(("Out of memory"));
  3021. return -ENOMEM;
  3022. }
  3023. n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len);
  3024. if (n <= 0) {
  3025. DBG(("%p recvfrom: %s", nc, strerror(mg_get_errno())));
  3026. MG_FREE(*buf);
  3027. }
  3028. return n;
  3029. }
  3030. static void mg_handle_udp_read(struct mg_connection *nc) {
  3031. char *buf = NULL;
  3032. union socket_address sa;
  3033. socklen_t sa_len = sizeof(sa);
  3034. int n = mg_recvfrom(nc, &sa, &sa_len, &buf);
  3035. DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
  3036. ntohs(nc->sa.sin.sin_port)));
  3037. mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
  3038. }
  3039. #if MG_ENABLE_SSL
  3040. static void mg_ssl_begin(struct mg_connection *nc) {
  3041. int server_side = (nc->listener != NULL);
  3042. enum mg_ssl_if_result res = mg_ssl_if_handshake(nc);
  3043. DBG(("%p %d res %d", nc, server_side, res));
  3044. if (res == MG_SSL_OK) {
  3045. nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
  3046. nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
  3047. if (server_side) {
  3048. union socket_address sa;
  3049. socklen_t sa_len = sizeof(sa);
  3050. (void) getpeername(nc->sock, &sa.sa, &sa_len);
  3051. mg_if_accept_tcp_cb(nc, &sa, sa_len);
  3052. } else {
  3053. mg_if_connect_cb(nc, 0);
  3054. }
  3055. } else if (res != MG_SSL_WANT_READ && res != MG_SSL_WANT_WRITE) {
  3056. if (!server_side) {
  3057. mg_if_connect_cb(nc, res);
  3058. }
  3059. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  3060. }
  3061. }
  3062. #endif /* MG_ENABLE_SSL */
  3063. #define _MG_F_FD_CAN_READ 1
  3064. #define _MG_F_FD_CAN_WRITE 1 << 1
  3065. #define _MG_F_FD_ERROR 1 << 2
  3066. void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
  3067. int worth_logging =
  3068. fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE));
  3069. if (worth_logging) {
  3070. DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
  3071. fd_flags, nc->flags, (int) nc->recv_mbuf.len,
  3072. (int) nc->send_mbuf.len));
  3073. }
  3074. if (nc->flags & MG_F_CONNECTING) {
  3075. if (fd_flags != 0) {
  3076. int err = 0;
  3077. #if !defined(MG_ESP8266)
  3078. if (!(nc->flags & MG_F_UDP)) {
  3079. socklen_t len = sizeof(err);
  3080. int ret =
  3081. getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
  3082. if (ret != 0) {
  3083. err = 1;
  3084. } else if (err == EAGAIN || err == EWOULDBLOCK) {
  3085. err = 0;
  3086. }
  3087. }
  3088. #else
  3089. /*
  3090. * On ESP8266 we use blocking connect.
  3091. */
  3092. err = nc->err;
  3093. #endif
  3094. #if MG_ENABLE_SSL
  3095. if ((nc->flags & MG_F_SSL) && err == 0) {
  3096. mg_ssl_begin(nc);
  3097. } else {
  3098. mg_if_connect_cb(nc, err);
  3099. }
  3100. #else
  3101. mg_if_connect_cb(nc, err);
  3102. #endif
  3103. } else if (nc->err != 0) {
  3104. mg_if_connect_cb(nc, nc->err);
  3105. }
  3106. }
  3107. if (fd_flags & _MG_F_FD_CAN_READ) {
  3108. if (nc->flags & MG_F_UDP) {
  3109. mg_handle_udp_read(nc);
  3110. } else {
  3111. if (nc->flags & MG_F_LISTENING) {
  3112. /*
  3113. * We're not looping here, and accepting just one connection at
  3114. * a time. The reason is that eCos does not respect non-blocking
  3115. * flag on a listening socket and hangs in a loop.
  3116. */
  3117. mg_accept_conn(nc);
  3118. } else {
  3119. mg_handle_tcp_read(nc);
  3120. }
  3121. }
  3122. }
  3123. if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
  3124. if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
  3125. mg_write_to_socket(nc);
  3126. }
  3127. mg_if_poll(nc, (time_t) now);
  3128. mg_if_timer(nc, now);
  3129. }
  3130. if (worth_logging) {
  3131. DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
  3132. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  3133. }
  3134. }
  3135. #if MG_ENABLE_BROADCAST
  3136. static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
  3137. struct ctl_msg ctl_msg;
  3138. int len =
  3139. (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
  3140. size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
  3141. DBG(("read %d from ctl socket", len));
  3142. (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
  3143. if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
  3144. struct mg_connection *nc;
  3145. for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
  3146. ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message);
  3147. }
  3148. }
  3149. }
  3150. #endif
  3151. /* Associate a socket to a connection. */
  3152. void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) {
  3153. mg_set_non_blocking_mode(sock);
  3154. mg_set_close_on_exec(sock);
  3155. nc->sock = sock;
  3156. DBG(("%p %d", nc, sock));
  3157. }
  3158. void mg_socket_if_init(struct mg_iface *iface) {
  3159. (void) iface;
  3160. DBG(("%p using select()", iface->mgr));
  3161. #if MG_ENABLE_BROADCAST
  3162. do {
  3163. mg_socketpair(iface->mgr->ctl, SOCK_DGRAM);
  3164. } while (iface->mgr->ctl[0] == INVALID_SOCKET);
  3165. #endif
  3166. }
  3167. void mg_socket_if_free(struct mg_iface *iface) {
  3168. (void) iface;
  3169. }
  3170. void mg_socket_if_add_conn(struct mg_connection *nc) {
  3171. (void) nc;
  3172. }
  3173. void mg_socket_if_remove_conn(struct mg_connection *nc) {
  3174. (void) nc;
  3175. }
  3176. void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
  3177. if (sock != INVALID_SOCKET
  3178. #ifdef __unix__
  3179. && sock < (sock_t) FD_SETSIZE
  3180. #endif
  3181. ) {
  3182. FD_SET(sock, set);
  3183. if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
  3184. *max_fd = sock;
  3185. }
  3186. }
  3187. }
  3188. time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) {
  3189. struct mg_mgr *mgr = iface->mgr;
  3190. double now = mg_time();
  3191. double min_timer;
  3192. struct mg_connection *nc, *tmp;
  3193. struct timeval tv;
  3194. fd_set read_set, write_set, err_set;
  3195. sock_t max_fd = INVALID_SOCKET;
  3196. int num_fds, num_ev, num_timers = 0;
  3197. #ifdef __unix__
  3198. int try_dup = 1;
  3199. #endif
  3200. FD_ZERO(&read_set);
  3201. FD_ZERO(&write_set);
  3202. FD_ZERO(&err_set);
  3203. #if MG_ENABLE_BROADCAST
  3204. mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
  3205. #endif
  3206. /*
  3207. * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
  3208. * e.g. timer-only "connections".
  3209. */
  3210. min_timer = 0;
  3211. for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
  3212. tmp = nc->next;
  3213. if (nc->sock != INVALID_SOCKET) {
  3214. num_fds++;
  3215. #ifdef __unix__
  3216. /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */
  3217. if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) {
  3218. int new_sock = dup(nc->sock);
  3219. if (new_sock >= 0 && new_sock < (sock_t) FD_SETSIZE) {
  3220. closesocket(nc->sock);
  3221. DBG(("new sock %d -> %d", nc->sock, new_sock));
  3222. nc->sock = new_sock;
  3223. } else {
  3224. try_dup = 0;
  3225. }
  3226. }
  3227. #endif
  3228. if (!(nc->flags & MG_F_WANT_WRITE) &&
  3229. nc->recv_mbuf.len < nc->recv_mbuf_limit &&
  3230. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
  3231. mg_add_to_set(nc->sock, &read_set, &max_fd);
  3232. }
  3233. if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
  3234. (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
  3235. mg_add_to_set(nc->sock, &write_set, &max_fd);
  3236. mg_add_to_set(nc->sock, &err_set, &max_fd);
  3237. }
  3238. }
  3239. if (nc->ev_timer_time > 0) {
  3240. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  3241. min_timer = nc->ev_timer_time;
  3242. }
  3243. num_timers++;
  3244. }
  3245. }
  3246. /*
  3247. * If there is a timer to be fired earlier than the requested timeout,
  3248. * adjust the timeout.
  3249. */
  3250. if (num_timers > 0) {
  3251. double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
  3252. if (timer_timeout_ms < timeout_ms) {
  3253. timeout_ms = (int) timer_timeout_ms;
  3254. }
  3255. }
  3256. if (timeout_ms < 0) timeout_ms = 0;
  3257. tv.tv_sec = timeout_ms / 1000;
  3258. tv.tv_usec = (timeout_ms % 1000) * 1000;
  3259. num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
  3260. now = mg_time();
  3261. #if 0
  3262. DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
  3263. timeout_ms));
  3264. #endif
  3265. #if MG_ENABLE_BROADCAST
  3266. if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
  3267. FD_ISSET(mgr->ctl[1], &read_set)) {
  3268. mg_mgr_handle_ctl_sock(mgr);
  3269. }
  3270. #endif
  3271. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  3272. int fd_flags = 0;
  3273. if (nc->sock != INVALID_SOCKET) {
  3274. if (num_ev > 0) {
  3275. fd_flags = (FD_ISSET(nc->sock, &read_set) &&
  3276. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
  3277. ? _MG_F_FD_CAN_READ
  3278. : 0) |
  3279. (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
  3280. (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
  3281. }
  3282. #if MG_LWIP
  3283. /* With LWIP socket emulation layer, we don't get write events for UDP */
  3284. if ((nc->flags & MG_F_UDP) && nc->listener == NULL) {
  3285. fd_flags |= _MG_F_FD_CAN_WRITE;
  3286. }
  3287. #endif
  3288. }
  3289. tmp = nc->next;
  3290. mg_mgr_handle_conn(nc, fd_flags, now);
  3291. }
  3292. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  3293. tmp = nc->next;
  3294. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  3295. (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
  3296. mg_close_conn(nc);
  3297. }
  3298. }
  3299. return (time_t) now;
  3300. }
  3301. #if MG_ENABLE_BROADCAST
  3302. int mg_socketpair(sock_t sp[2], int sock_type) {
  3303. union socket_address sa;
  3304. sock_t sock;
  3305. socklen_t len = sizeof(sa.sin);
  3306. int ret = 0;
  3307. sock = sp[0] = sp[1] = INVALID_SOCKET;
  3308. (void) memset(&sa, 0, sizeof(sa));
  3309. sa.sin.sin_family = AF_INET;
  3310. sa.sin.sin_port = htons(0);
  3311. sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
  3312. if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
  3313. } else if (bind(sock, &sa.sa, len) != 0) {
  3314. } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
  3315. } else if (getsockname(sock, &sa.sa, &len) != 0) {
  3316. } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
  3317. } else if (connect(sp[0], &sa.sa, len) != 0) {
  3318. } else if (sock_type == SOCK_DGRAM &&
  3319. (getsockname(sp[0], &sa.sa, &len) != 0 ||
  3320. connect(sock, &sa.sa, len) != 0)) {
  3321. } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
  3322. : accept(sock, &sa.sa, &len))) ==
  3323. INVALID_SOCKET) {
  3324. } else {
  3325. mg_set_close_on_exec(sp[0]);
  3326. mg_set_close_on_exec(sp[1]);
  3327. if (sock_type == SOCK_STREAM) closesocket(sock);
  3328. ret = 1;
  3329. }
  3330. if (!ret) {
  3331. if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
  3332. if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
  3333. if (sock != INVALID_SOCKET) closesocket(sock);
  3334. sock = sp[0] = sp[1] = INVALID_SOCKET;
  3335. }
  3336. return ret;
  3337. }
  3338. #endif /* MG_ENABLE_BROADCAST */
  3339. static void mg_sock_get_addr(sock_t sock, int remote,
  3340. union socket_address *sa) {
  3341. socklen_t slen = sizeof(*sa);
  3342. memset(sa, 0, slen);
  3343. if (remote) {
  3344. getpeername(sock, &sa->sa, &slen);
  3345. } else {
  3346. getsockname(sock, &sa->sa, &slen);
  3347. }
  3348. }
  3349. void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
  3350. union socket_address sa;
  3351. mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
  3352. mg_sock_addr_to_str(&sa, buf, len, flags);
  3353. }
  3354. void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote,
  3355. union socket_address *sa) {
  3356. mg_sock_get_addr(nc->sock, remote, sa);
  3357. }
  3358. /* clang-format off */
  3359. #define MG_SOCKET_IFACE_VTABLE \
  3360. { \
  3361. mg_socket_if_init, \
  3362. mg_socket_if_free, \
  3363. mg_socket_if_add_conn, \
  3364. mg_socket_if_remove_conn, \
  3365. mg_socket_if_poll, \
  3366. mg_socket_if_listen_tcp, \
  3367. mg_socket_if_listen_udp, \
  3368. mg_socket_if_connect_tcp, \
  3369. mg_socket_if_connect_udp, \
  3370. mg_socket_if_tcp_send, \
  3371. mg_socket_if_udp_send, \
  3372. mg_socket_if_recved, \
  3373. mg_socket_if_create_conn, \
  3374. mg_socket_if_destroy_conn, \
  3375. mg_socket_if_sock_set, \
  3376. mg_socket_if_get_conn_addr, \
  3377. }
  3378. /* clang-format on */
  3379. struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE;
  3380. #if MG_NET_IF == MG_NET_IF_SOCKET
  3381. struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE;
  3382. #endif
  3383. #endif /* MG_ENABLE_NET_IF_SOCKET */
  3384. #ifdef MG_MODULE_LINES
  3385. #line 1 "mongoose/src/net_if_tun.c"
  3386. #endif
  3387. /*
  3388. * Copyright (c) 2014-2016 Cesanta Software Limited
  3389. * All rights reserved
  3390. */
  3391. #if MG_ENABLE_TUN
  3392. /* Amalgamated: #include "common/cs_dbg.h" */
  3393. /* Amalgamated: #include "common/cs_time.h" */
  3394. /* Amalgamated: #include "mongoose/src/internal.h" */
  3395. /* Amalgamated: #include "mongoose/src/net_if_tun.h" */
  3396. /* Amalgamated: #include "mongoose/src/tun.h" */
  3397. /* Amalgamated: #include "mongoose/src/util.h" */
  3398. #define MG_TCP_RECV_BUFFER_SIZE 1024
  3399. #define MG_UDP_RECV_BUFFER_SIZE 1500
  3400. void mg_tun_if_connect_tcp(struct mg_connection *nc,
  3401. const union socket_address *sa) {
  3402. (void) nc;
  3403. (void) sa;
  3404. }
  3405. void mg_tun_if_connect_udp(struct mg_connection *nc) {
  3406. (void) nc;
  3407. }
  3408. int mg_tun_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  3409. (void) nc;
  3410. (void) sa;
  3411. return 0;
  3412. }
  3413. int mg_tun_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  3414. (void) nc;
  3415. (void) sa;
  3416. return -1;
  3417. }
  3418. void mg_tun_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
  3419. struct mg_tun_client *client = (struct mg_tun_client *) nc->iface->data;
  3420. uint32_t stream_id = (uint32_t)(uintptr_t) nc->mgr_data;
  3421. struct mg_str msg = {(char *) buf, len};
  3422. #if MG_ENABLE_HEXDUMP
  3423. char hex[512];
  3424. mg_hexdump(buf, len, hex, sizeof(hex));
  3425. LOG(LL_DEBUG, ("sending to stream %zu:\n%s", stream_id, hex));
  3426. #endif
  3427. mg_tun_send_frame(client->disp, stream_id, MG_TUN_DATA_FRAME, 0, msg);
  3428. }
  3429. void mg_tun_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
  3430. (void) nc;
  3431. (void) buf;
  3432. (void) len;
  3433. }
  3434. void mg_tun_if_recved(struct mg_connection *nc, size_t len) {
  3435. (void) nc;
  3436. (void) len;
  3437. }
  3438. int mg_tun_if_create_conn(struct mg_connection *nc) {
  3439. (void) nc;
  3440. return 1;
  3441. }
  3442. void mg_tun_if_destroy_conn(struct mg_connection *nc) {
  3443. struct mg_tun_client *client = (struct mg_tun_client *) nc->iface->data;
  3444. if (nc->flags & MG_F_LISTENING) {
  3445. mg_tun_destroy_client(client);
  3446. } else if (client->disp) {
  3447. uint32_t stream_id = (uint32_t)(uintptr_t) nc->mgr_data;
  3448. struct mg_str msg = {NULL, 0};
  3449. LOG(LL_DEBUG, ("closing %zu:", stream_id));
  3450. mg_tun_send_frame(client->disp, stream_id, MG_TUN_DATA_FRAME,
  3451. MG_TUN_F_END_STREAM, msg);
  3452. }
  3453. }
  3454. /* Associate a socket to a connection. */
  3455. void mg_tun_if_sock_set(struct mg_connection *nc, sock_t sock) {
  3456. (void) nc;
  3457. (void) sock;
  3458. }
  3459. void mg_tun_if_init(struct mg_iface *iface) {
  3460. (void) iface;
  3461. }
  3462. void mg_tun_if_free(struct mg_iface *iface) {
  3463. (void) iface;
  3464. }
  3465. void mg_tun_if_add_conn(struct mg_connection *nc) {
  3466. nc->sock = INVALID_SOCKET;
  3467. }
  3468. void mg_tun_if_remove_conn(struct mg_connection *nc) {
  3469. (void) nc;
  3470. }
  3471. time_t mg_tun_if_poll(struct mg_iface *iface, int timeout_ms) {
  3472. (void) iface;
  3473. (void) timeout_ms;
  3474. return (time_t) cs_time();
  3475. }
  3476. void mg_tun_if_get_conn_addr(struct mg_connection *nc, int remote,
  3477. union socket_address *sa) {
  3478. (void) nc;
  3479. (void) remote;
  3480. (void) sa;
  3481. }
  3482. struct mg_connection *mg_tun_if_find_conn(struct mg_tun_client *client,
  3483. uint32_t stream_id) {
  3484. struct mg_connection *nc = NULL;
  3485. for (nc = client->mgr->active_connections; nc != NULL; nc = nc->next) {
  3486. if (nc->iface != client->iface || (nc->flags & MG_F_LISTENING)) {
  3487. continue;
  3488. }
  3489. if (stream_id == (uint32_t)(uintptr_t) nc->mgr_data) {
  3490. return nc;
  3491. }
  3492. }
  3493. if (stream_id > client->last_stream_id) {
  3494. /* create a new connection */
  3495. LOG(LL_DEBUG, ("new stream 0x%lx, accepting", stream_id));
  3496. nc = mg_if_accept_new_conn(client->listener);
  3497. nc->mgr_data = (void *) (uintptr_t) stream_id;
  3498. client->last_stream_id = stream_id;
  3499. } else {
  3500. LOG(LL_DEBUG, ("Ignoring stream 0x%lx (last_stream_id 0x%lx)", stream_id,
  3501. client->last_stream_id));
  3502. }
  3503. return nc;
  3504. }
  3505. /* clang-format off */
  3506. #define MG_TUN_IFACE_VTABLE \
  3507. { \
  3508. mg_tun_if_init, \
  3509. mg_tun_if_free, \
  3510. mg_tun_if_add_conn, \
  3511. mg_tun_if_remove_conn, \
  3512. mg_tun_if_poll, \
  3513. mg_tun_if_listen_tcp, \
  3514. mg_tun_if_listen_udp, \
  3515. mg_tun_if_connect_tcp, \
  3516. mg_tun_if_connect_udp, \
  3517. mg_tun_if_tcp_send, \
  3518. mg_tun_if_udp_send, \
  3519. mg_tun_if_recved, \
  3520. mg_tun_if_create_conn, \
  3521. mg_tun_if_destroy_conn, \
  3522. mg_tun_if_sock_set, \
  3523. mg_tun_if_get_conn_addr, \
  3524. }
  3525. /* clang-format on */
  3526. struct mg_iface_vtable mg_tun_iface_vtable = MG_TUN_IFACE_VTABLE;
  3527. #endif /* MG_ENABLE_TUN */
  3528. #ifdef MG_MODULE_LINES
  3529. #line 1 "mongoose/src/ssl_if_openssl.c"
  3530. #endif
  3531. /*
  3532. * Copyright (c) 2014-2016 Cesanta Software Limited
  3533. * All rights reserved
  3534. */
  3535. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
  3536. #ifdef __APPLE__
  3537. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3538. #endif
  3539. #include <openssl/ssl.h>
  3540. struct mg_ssl_if_ctx {
  3541. SSL *ssl;
  3542. SSL_CTX *ssl_ctx;
  3543. struct mbuf psk;
  3544. size_t identity_len;
  3545. };
  3546. void mg_ssl_if_init() {
  3547. SSL_library_init();
  3548. }
  3549. enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
  3550. struct mg_connection *lc) {
  3551. struct mg_ssl_if_ctx *ctx =
  3552. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  3553. struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
  3554. nc->ssl_if_data = ctx;
  3555. if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
  3556. ctx->ssl_ctx = lc_ctx->ssl_ctx;
  3557. if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
  3558. return MG_SSL_ERROR;
  3559. }
  3560. return MG_SSL_OK;
  3561. }
  3562. static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
  3563. const char *key, const char **err_msg);
  3564. static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert);
  3565. static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl);
  3566. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  3567. const char *identity,
  3568. const char *key_str);
  3569. enum mg_ssl_if_result mg_ssl_if_conn_init(
  3570. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  3571. const char **err_msg) {
  3572. struct mg_ssl_if_ctx *ctx =
  3573. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  3574. DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
  3575. (params->key ? params->key : ""),
  3576. (params->ca_cert ? params->ca_cert : "")));
  3577. if (ctx == NULL) {
  3578. MG_SET_PTRPTR(err_msg, "Out of memory");
  3579. return MG_SSL_ERROR;
  3580. }
  3581. nc->ssl_if_data = ctx;
  3582. if (nc->flags & MG_F_LISTENING) {
  3583. ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  3584. } else {
  3585. ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  3586. }
  3587. if (ctx->ssl_ctx == NULL) {
  3588. MG_SET_PTRPTR(err_msg, "Failed to create SSL context");
  3589. return MG_SSL_ERROR;
  3590. }
  3591. if (params->cert != NULL &&
  3592. mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
  3593. MG_SSL_OK) {
  3594. return MG_SSL_ERROR;
  3595. }
  3596. if (params->ca_cert != NULL &&
  3597. mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
  3598. MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
  3599. return MG_SSL_ERROR;
  3600. }
  3601. if (params->server_name != NULL) {
  3602. #ifdef KR_VERSION
  3603. SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
  3604. #else
  3605. /* TODO(rojer): Implement server name verification on OpenSSL. */
  3606. #endif
  3607. }
  3608. if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
  3609. MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
  3610. return MG_SSL_ERROR;
  3611. }
  3612. mbuf_init(&ctx->psk, 0);
  3613. if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
  3614. MG_SSL_OK) {
  3615. MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
  3616. return MG_SSL_ERROR;
  3617. }
  3618. if (!(nc->flags & MG_F_LISTENING) &&
  3619. (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
  3620. MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
  3621. return MG_SSL_ERROR;
  3622. }
  3623. nc->flags |= MG_F_SSL;
  3624. return MG_SSL_OK;
  3625. }
  3626. static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc,
  3627. int res) {
  3628. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3629. int err = SSL_get_error(ctx->ssl, res);
  3630. if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ;
  3631. if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE;
  3632. DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err));
  3633. nc->err = err;
  3634. return MG_SSL_ERROR;
  3635. }
  3636. enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
  3637. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3638. int server_side = (nc->listener != NULL);
  3639. int res;
  3640. /* If descriptor is not yet set, do it now. */
  3641. if (SSL_get_fd(ctx->ssl) < 0) {
  3642. if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR;
  3643. }
  3644. res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
  3645. if (res != 1) return mg_ssl_if_ssl_err(nc, res);
  3646. return MG_SSL_OK;
  3647. }
  3648. int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
  3649. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3650. int n = SSL_read(ctx->ssl, buf, buf_size);
  3651. DBG(("%p %d -> %d", nc, (int) buf_size, n));
  3652. if (n < 0) return mg_ssl_if_ssl_err(nc, n);
  3653. if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  3654. return n;
  3655. }
  3656. int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
  3657. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3658. int n = SSL_write(ctx->ssl, data, len);
  3659. DBG(("%p %d -> %d", nc, (int) len, n));
  3660. if (n <= 0) return mg_ssl_if_ssl_err(nc, n);
  3661. return n;
  3662. }
  3663. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  3664. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  3665. if (ctx == NULL) return;
  3666. nc->ssl_if_data = NULL;
  3667. if (ctx->ssl != NULL) SSL_free(ctx->ssl);
  3668. if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
  3669. mbuf_free(&ctx->psk);
  3670. memset(ctx, 0, sizeof(*ctx));
  3671. MG_FREE(ctx);
  3672. }
  3673. /*
  3674. * Cipher suite options used for TLS negotiation.
  3675. * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
  3676. */
  3677. static const char mg_s_cipher_list[] =
  3678. #if defined(MG_SSL_CRYPTO_MODERN)
  3679. "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
  3680. "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
  3681. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  3682. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  3683. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  3684. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  3685. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  3686. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
  3687. "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
  3688. #elif defined(MG_SSL_CRYPTO_OLD)
  3689. "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
  3690. "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
  3691. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  3692. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  3693. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  3694. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  3695. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  3696. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
  3697. "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
  3698. "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
  3699. "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
  3700. "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
  3701. #else /* Default - intermediate. */
  3702. "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
  3703. "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
  3704. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  3705. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  3706. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  3707. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  3708. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  3709. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
  3710. "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
  3711. "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
  3712. "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
  3713. #endif
  3714. ;
  3715. /*
  3716. * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
  3717. * Will be used if none are provided by the user in the certificate file.
  3718. */
  3719. #if !MG_DISABLE_PFS && !defined(KR_VERSION)
  3720. static const char mg_s_default_dh_params[] =
  3721. "\
  3722. -----BEGIN DH PARAMETERS-----\n\
  3723. MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
  3724. Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
  3725. +E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
  3726. ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
  3727. wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
  3728. 9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
  3729. -----END DH PARAMETERS-----\n";
  3730. #endif
  3731. static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
  3732. if (cert == NULL || strcmp(cert, "*") == 0) {
  3733. return MG_SSL_OK;
  3734. }
  3735. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
  3736. return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
  3737. : MG_SSL_ERROR;
  3738. }
  3739. static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
  3740. const char *key,
  3741. const char **err_msg) {
  3742. if (key == NULL) key = cert;
  3743. if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
  3744. return MG_SSL_OK;
  3745. } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
  3746. MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
  3747. return MG_SSL_ERROR;
  3748. } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) {
  3749. MG_SET_PTRPTR(err_msg, "Invalid SSL key");
  3750. return MG_SSL_ERROR;
  3751. } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
  3752. MG_SET_PTRPTR(err_msg, "Invalid CA bundle");
  3753. return MG_SSL_ERROR;
  3754. } else {
  3755. SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  3756. #if !MG_DISABLE_PFS && !defined(KR_VERSION)
  3757. BIO *bio = NULL;
  3758. DH *dh = NULL;
  3759. /* Try to read DH parameters from the cert/key file. */
  3760. bio = BIO_new_file(cert, "r");
  3761. if (bio != NULL) {
  3762. dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  3763. BIO_free(bio);
  3764. }
  3765. /*
  3766. * If there are no DH params in the file, fall back to hard-coded ones.
  3767. * Not ideal, but better than nothing.
  3768. */
  3769. if (dh == NULL) {
  3770. bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
  3771. dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  3772. BIO_free(bio);
  3773. }
  3774. if (dh != NULL) {
  3775. SSL_CTX_set_tmp_dh(ctx, dh);
  3776. SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
  3777. DH_free(dh);
  3778. }
  3779. #if OPENSSL_VERSION_NUMBER > 0x10002000L
  3780. SSL_CTX_set_ecdh_auto(ctx, 1);
  3781. #endif
  3782. #endif
  3783. }
  3784. return MG_SSL_OK;
  3785. }
  3786. static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) {
  3787. return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
  3788. ? MG_SSL_OK
  3789. : MG_SSL_ERROR);
  3790. }
  3791. #ifndef KR_VERSION
  3792. static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint,
  3793. char *identity,
  3794. unsigned int max_identity_len,
  3795. unsigned char *psk,
  3796. unsigned int max_psk_len) {
  3797. struct mg_ssl_if_ctx *ctx =
  3798. (struct mg_ssl_if_ctx *) ssl->ctx->msg_callback_arg;
  3799. size_t key_len = ctx->psk.len - ctx->identity_len - 1;
  3800. DBG(("hint: '%s'", (hint ? hint : "")));
  3801. if (ctx->identity_len + 1 > max_identity_len) {
  3802. DBG(("identity too long"));
  3803. return 0;
  3804. }
  3805. if (key_len > max_psk_len) {
  3806. DBG(("key too long"));
  3807. return 0;
  3808. }
  3809. memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
  3810. memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
  3811. (void) ssl;
  3812. return key_len;
  3813. }
  3814. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  3815. const char *identity,
  3816. const char *key_str) {
  3817. unsigned char key[32];
  3818. size_t key_len;
  3819. size_t i = 0;
  3820. if (identity == NULL && key_str == NULL) return MG_SSL_OK;
  3821. if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
  3822. key_len = strlen(key_str);
  3823. if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
  3824. memset(key, 0, sizeof(key));
  3825. key_len = 0;
  3826. for (i = 0; key_str[i] != '\0'; i++) {
  3827. unsigned char c;
  3828. char hc = tolower((int) key_str[i]);
  3829. if (hc >= '0' && hc <= '9') {
  3830. c = hc - '0';
  3831. } else if (hc >= 'a' && hc <= 'f') {
  3832. c = hc - 'a' + 0xa;
  3833. } else {
  3834. return MG_SSL_ERROR;
  3835. }
  3836. key_len = i / 2;
  3837. key[key_len] <<= 4;
  3838. key[key_len] |= c;
  3839. }
  3840. key_len++;
  3841. DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
  3842. ctx->identity_len = strlen(identity);
  3843. mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
  3844. mbuf_append(&ctx->psk, key, key_len);
  3845. SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
  3846. /* Hack: there is no field for us to keep this, so we use msg_callback_arg */
  3847. ctx->ssl_ctx->msg_callback_arg = ctx;
  3848. return MG_SSL_OK;
  3849. }
  3850. #else
  3851. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  3852. const char *identity,
  3853. const char *key_str) {
  3854. (void) ctx;
  3855. (void) identity;
  3856. (void) key_str;
  3857. /* Krypton does not support PSK. */
  3858. return MG_SSL_ERROR;
  3859. }
  3860. #endif /* defined(KR_VERSION) */
  3861. const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
  3862. const char *ca_cert) {
  3863. const char *err_msg = NULL;
  3864. struct mg_ssl_if_conn_params params;
  3865. memset(&params, 0, sizeof(params));
  3866. params.cert = cert;
  3867. params.ca_cert = ca_cert;
  3868. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  3869. return err_msg;
  3870. }
  3871. return NULL;
  3872. }
  3873. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */
  3874. #ifdef MG_MODULE_LINES
  3875. #line 1 "mongoose/src/ssl_if_mbedtls.c"
  3876. #endif
  3877. /*
  3878. * Copyright (c) 2014-2016 Cesanta Software Limited
  3879. * All rights reserved
  3880. */
  3881. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
  3882. #include <mbedtls/debug.h>
  3883. #include <mbedtls/ecp.h>
  3884. #include <mbedtls/platform.h>
  3885. #include <mbedtls/ssl.h>
  3886. #include <mbedtls/x509_crt.h>
  3887. static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line,
  3888. const char *str) {
  3889. enum cs_log_level cs_level;
  3890. switch (level) {
  3891. case 1:
  3892. cs_level = LL_ERROR;
  3893. break;
  3894. case 2:
  3895. case 3:
  3896. cs_level = LL_DEBUG;
  3897. break;
  3898. default:
  3899. cs_level = LL_VERBOSE_DEBUG;
  3900. }
  3901. /* mbedTLS passes strings with \n at the end, strip it. */
  3902. LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str));
  3903. (void) file;
  3904. (void) line;
  3905. }
  3906. struct mg_ssl_if_ctx {
  3907. mbedtls_ssl_config *conf;
  3908. mbedtls_ssl_context *ssl;
  3909. mbedtls_x509_crt *cert;
  3910. mbedtls_pk_context *key;
  3911. mbedtls_x509_crt *ca_cert;
  3912. struct mbuf cipher_suites;
  3913. };
  3914. /* Must be provided by the platform. ctx is struct mg_connection. */
  3915. extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len);
  3916. void mg_ssl_if_init() {
  3917. }
  3918. enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
  3919. struct mg_connection *lc) {
  3920. struct mg_ssl_if_ctx *ctx =
  3921. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  3922. struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
  3923. nc->ssl_if_data = ctx;
  3924. if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
  3925. ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
  3926. if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
  3927. return MG_SSL_ERROR;
  3928. }
  3929. return MG_SSL_OK;
  3930. }
  3931. static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
  3932. const char *cert, const char *key,
  3933. const char **err_msg);
  3934. static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
  3935. const char *cert);
  3936. static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
  3937. const char *ciphers);
  3938. static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
  3939. const char *identity,
  3940. const char *key);
  3941. enum mg_ssl_if_result mg_ssl_if_conn_init(
  3942. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  3943. const char **err_msg) {
  3944. struct mg_ssl_if_ctx *ctx =
  3945. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  3946. DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
  3947. (params->key ? params->key : ""),
  3948. (params->ca_cert ? params->ca_cert : "")));
  3949. if (ctx == NULL) {
  3950. MG_SET_PTRPTR(err_msg, "Out of memory");
  3951. return MG_SSL_ERROR;
  3952. }
  3953. nc->ssl_if_data = ctx;
  3954. ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf));
  3955. mbuf_init(&ctx->cipher_suites, 0);
  3956. mbedtls_ssl_config_init(ctx->conf);
  3957. mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
  3958. if (mbedtls_ssl_config_defaults(
  3959. ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER
  3960. : MBEDTLS_SSL_IS_CLIENT),
  3961. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
  3962. MG_SET_PTRPTR(err_msg, "Failed to init SSL config");
  3963. return MG_SSL_ERROR;
  3964. }
  3965. /* TLS 1.2 and up */
  3966. mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  3967. MBEDTLS_SSL_MINOR_VERSION_3);
  3968. mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
  3969. if (params->cert != NULL &&
  3970. mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
  3971. return MG_SSL_ERROR;
  3972. }
  3973. if (params->ca_cert != NULL &&
  3974. mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
  3975. MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
  3976. return MG_SSL_ERROR;
  3977. }
  3978. if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
  3979. MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
  3980. return MG_SSL_ERROR;
  3981. }
  3982. if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
  3983. MG_SSL_OK) {
  3984. MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
  3985. return MG_SSL_ERROR;
  3986. }
  3987. if (!(nc->flags & MG_F_LISTENING)) {
  3988. ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
  3989. mbedtls_ssl_init(ctx->ssl);
  3990. if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
  3991. MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
  3992. return MG_SSL_ERROR;
  3993. }
  3994. if (params->server_name != NULL &&
  3995. mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
  3996. return MG_SSL_ERROR;
  3997. }
  3998. }
  3999. #ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
  4000. if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
  4001. #if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
  4002. MBEDTLS_SSL_MAX_FRAG_LEN_512
  4003. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
  4004. MBEDTLS_SSL_MAX_FRAG_LEN_1024
  4005. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
  4006. MBEDTLS_SSL_MAX_FRAG_LEN_2048
  4007. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
  4008. MBEDTLS_SSL_MAX_FRAG_LEN_4096
  4009. #else
  4010. #error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
  4011. #endif
  4012. ) != 0) {
  4013. return MG_SSL_ERROR;
  4014. }
  4015. #endif
  4016. nc->flags |= MG_F_SSL;
  4017. return MG_SSL_OK;
  4018. }
  4019. #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  4020. int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len);
  4021. int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len);
  4022. #else
  4023. static int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
  4024. struct mg_connection *nc = (struct mg_connection *) ctx;
  4025. int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
  4026. LOG(LL_DEBUG, ("%p %d -> %d", nc, (int) len, n));
  4027. if (n >= 0) return n;
  4028. n = mg_get_errno();
  4029. return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_WRITE : -1);
  4030. }
  4031. static int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
  4032. struct mg_connection *nc = (struct mg_connection *) ctx;
  4033. int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
  4034. LOG(LL_DEBUG, ("%p %d <- %d", nc, (int) len, n));
  4035. if (n >= 0) return n;
  4036. n = mg_get_errno();
  4037. return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_READ : -1);
  4038. }
  4039. #endif
  4040. static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
  4041. int ret) {
  4042. if (ret == MBEDTLS_ERR_SSL_WANT_READ) return MG_SSL_WANT_READ;
  4043. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) return MG_SSL_WANT_WRITE;
  4044. if (ret !=
  4045. MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { /* CLOSE_NOTIFY = Normal shutdown */
  4046. LOG(LL_ERROR, ("%p SSL error: %d", nc, ret));
  4047. }
  4048. nc->err = ret;
  4049. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4050. return MG_SSL_ERROR;
  4051. }
  4052. static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) {
  4053. if (ctx->cert != NULL) {
  4054. mbedtls_x509_crt_free(ctx->cert);
  4055. MG_FREE(ctx->cert);
  4056. ctx->cert = NULL;
  4057. mbedtls_pk_free(ctx->key);
  4058. MG_FREE(ctx->key);
  4059. ctx->key = NULL;
  4060. }
  4061. if (ctx->ca_cert != NULL) {
  4062. mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
  4063. mbedtls_x509_crt_free(ctx->ca_cert);
  4064. MG_FREE(ctx->ca_cert);
  4065. ctx->ca_cert = NULL;
  4066. }
  4067. }
  4068. enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
  4069. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4070. int err;
  4071. /* If bio is not yet set, do it now. */
  4072. if (ctx->ssl->p_bio == NULL) {
  4073. mbedtls_ssl_set_bio(ctx->ssl, nc, ssl_socket_send, ssl_socket_recv, NULL);
  4074. }
  4075. err = mbedtls_ssl_handshake(ctx->ssl);
  4076. if (err != 0) return mg_ssl_if_mbed_err(nc, err);
  4077. #ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
  4078. /*
  4079. * Free the peer certificate, we don't need it after handshake.
  4080. * Note that this effectively disables renegotiation.
  4081. */
  4082. mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
  4083. mbedtls_free(ctx->ssl->session->peer_cert);
  4084. ctx->ssl->session->peer_cert = NULL;
  4085. /* On a client connection we can also free our own and CA certs. */
  4086. if (nc->listener == NULL) {
  4087. if (ctx->conf->key_cert != NULL) {
  4088. /* Note that this assumes one key_cert entry, which matches our init. */
  4089. MG_FREE(ctx->conf->key_cert);
  4090. ctx->conf->key_cert = NULL;
  4091. }
  4092. mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
  4093. mg_ssl_if_mbed_free_certs_and_keys(ctx);
  4094. }
  4095. #endif
  4096. return MG_SSL_OK;
  4097. }
  4098. int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
  4099. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4100. int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, buf_size);
  4101. DBG(("%p %d -> %d", nc, (int) buf_size, n));
  4102. if (n < 0) return mg_ssl_if_mbed_err(nc, n);
  4103. if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4104. return n;
  4105. }
  4106. int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
  4107. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4108. int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) data, len);
  4109. DBG(("%p %d -> %d", nc, (int) len, n));
  4110. if (n < 0) return mg_ssl_if_mbed_err(nc, n);
  4111. return n;
  4112. }
  4113. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  4114. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4115. if (ctx == NULL) return;
  4116. nc->ssl_if_data = NULL;
  4117. if (ctx->ssl != NULL) {
  4118. mbedtls_ssl_free(ctx->ssl);
  4119. MG_FREE(ctx->ssl);
  4120. }
  4121. mg_ssl_if_mbed_free_certs_and_keys(ctx);
  4122. if (ctx->conf != NULL) {
  4123. mbedtls_ssl_config_free(ctx->conf);
  4124. MG_FREE(ctx->conf);
  4125. }
  4126. mbuf_free(&ctx->cipher_suites);
  4127. memset(ctx, 0, sizeof(*ctx));
  4128. MG_FREE(ctx);
  4129. }
  4130. static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
  4131. const char *ca_cert) {
  4132. if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) {
  4133. return MG_SSL_OK;
  4134. }
  4135. ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert));
  4136. mbedtls_x509_crt_init(ctx->ca_cert);
  4137. if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
  4138. return MG_SSL_ERROR;
  4139. }
  4140. mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
  4141. mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  4142. return MG_SSL_OK;
  4143. }
  4144. static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
  4145. const char *cert, const char *key,
  4146. const char **err_msg) {
  4147. if (key == NULL) key = cert;
  4148. if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
  4149. return MG_SSL_OK;
  4150. }
  4151. ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert));
  4152. mbedtls_x509_crt_init(ctx->cert);
  4153. ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key));
  4154. mbedtls_pk_init(ctx->key);
  4155. if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
  4156. MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
  4157. return MG_SSL_ERROR;
  4158. }
  4159. if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) {
  4160. MG_SET_PTRPTR(err_msg, "Invalid SSL key");
  4161. return MG_SSL_ERROR;
  4162. }
  4163. if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
  4164. MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert");
  4165. return MG_SSL_ERROR;
  4166. }
  4167. return MG_SSL_OK;
  4168. }
  4169. static const int mg_s_cipher_list[] = {
  4170. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  4171. MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  4172. MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
  4173. MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
  4174. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
  4175. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
  4176. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
  4177. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
  4178. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
  4179. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
  4180. MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
  4181. MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
  4182. MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, 0};
  4183. /*
  4184. * Ciphers can be specified as a colon-separated list of cipher suite names.
  4185. * These can be found in
  4186. * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267
  4187. * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM
  4188. */
  4189. static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
  4190. const char *ciphers) {
  4191. if (ciphers != NULL) {
  4192. int l, id;
  4193. const char *s = ciphers, *e;
  4194. char tmp[50];
  4195. while (s != NULL) {
  4196. e = strchr(s, ':');
  4197. l = (e != NULL ? (e - s) : (int) strlen(s));
  4198. strncpy(tmp, s, l);
  4199. tmp[l] = '\0';
  4200. id = mbedtls_ssl_get_ciphersuite_id(tmp);
  4201. DBG(("%s -> %04x", tmp, id));
  4202. if (id != 0) {
  4203. mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
  4204. }
  4205. s = (e != NULL ? e + 1 : NULL);
  4206. }
  4207. if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR;
  4208. id = 0;
  4209. mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
  4210. mbuf_trim(&ctx->cipher_suites);
  4211. mbedtls_ssl_conf_ciphersuites(ctx->conf,
  4212. (const int *) ctx->cipher_suites.buf);
  4213. } else {
  4214. mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
  4215. }
  4216. return MG_SSL_OK;
  4217. }
  4218. static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
  4219. const char *identity,
  4220. const char *key_str) {
  4221. unsigned char key[32];
  4222. size_t key_len;
  4223. if (identity == NULL && key_str == NULL) return MG_SSL_OK;
  4224. if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
  4225. key_len = strlen(key_str);
  4226. if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
  4227. size_t i = 0;
  4228. memset(key, 0, sizeof(key));
  4229. key_len = 0;
  4230. for (i = 0; key_str[i] != '\0'; i++) {
  4231. unsigned char c;
  4232. char hc = tolower((int) key_str[i]);
  4233. if (hc >= '0' && hc <= '9') {
  4234. c = hc - '0';
  4235. } else if (hc >= 'a' && hc <= 'f') {
  4236. c = hc - 'a' + 0xa;
  4237. } else {
  4238. return MG_SSL_ERROR;
  4239. }
  4240. key_len = i / 2;
  4241. key[key_len] <<= 4;
  4242. key[key_len] |= c;
  4243. }
  4244. key_len++;
  4245. DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
  4246. /* mbedTLS makes copies of psk and identity. */
  4247. if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len,
  4248. (const unsigned char *) identity,
  4249. strlen(identity)) != 0) {
  4250. return MG_SSL_ERROR;
  4251. }
  4252. return MG_SSL_OK;
  4253. }
  4254. const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
  4255. const char *ca_cert) {
  4256. const char *err_msg = NULL;
  4257. struct mg_ssl_if_conn_params params;
  4258. memset(&params, 0, sizeof(params));
  4259. params.cert = cert;
  4260. params.ca_cert = ca_cert;
  4261. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  4262. return err_msg;
  4263. }
  4264. return NULL;
  4265. }
  4266. /* Lazy RNG. Warning: it would be a bad idea to do this in production! */
  4267. #ifdef MG_SSL_MBED_DUMMY_RANDOM
  4268. int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) {
  4269. (void) ctx;
  4270. while (len--) *buf++ = rand();
  4271. return 0;
  4272. }
  4273. #endif
  4274. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */
  4275. #ifdef MG_MODULE_LINES
  4276. #line 1 "mongoose/src/uri.c"
  4277. #endif
  4278. /*
  4279. * Copyright (c) 2014 Cesanta Software Limited
  4280. * All rights reserved
  4281. */
  4282. /* Amalgamated: #include "mongoose/src/internal.h" */
  4283. /* Amalgamated: #include "mongoose/src/uri.h" */
  4284. /*
  4285. * scan string until `sep`, keeping track of component boundaries in `res`.
  4286. *
  4287. * `p` will point to the char after the separator or it will be `end`.
  4288. */
  4289. static void parse_uri_component(const char **p, const char *end, char sep,
  4290. struct mg_str *res) {
  4291. res->p = *p;
  4292. for (; *p < end; (*p)++) {
  4293. if (**p == sep) {
  4294. break;
  4295. }
  4296. }
  4297. res->len = (*p) - res->p;
  4298. if (*p < end) (*p)++;
  4299. }
  4300. int mg_parse_uri(struct mg_str uri, struct mg_str *scheme,
  4301. struct mg_str *user_info, struct mg_str *host,
  4302. unsigned int *port, struct mg_str *path, struct mg_str *query,
  4303. struct mg_str *fragment) {
  4304. struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
  4305. rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
  4306. unsigned int rport = 0;
  4307. enum {
  4308. P_START,
  4309. P_SCHEME_OR_PORT,
  4310. P_USER_INFO,
  4311. P_HOST,
  4312. P_PORT,
  4313. P_REST
  4314. } state = P_START;
  4315. const char *p = uri.p, *end = p + uri.len;
  4316. while (p < end) {
  4317. switch (state) {
  4318. case P_START:
  4319. /*
  4320. * expecting on of:
  4321. * - `scheme://xxxx`
  4322. * - `xxxx:port`
  4323. * - `xxxx/path`
  4324. */
  4325. for (; p < end; p++) {
  4326. if (*p == ':') {
  4327. state = P_SCHEME_OR_PORT;
  4328. break;
  4329. } else if (*p == '/') {
  4330. state = P_REST;
  4331. break;
  4332. }
  4333. }
  4334. if (state == P_START || state == P_REST) {
  4335. rhost.p = uri.p;
  4336. rhost.len = p - uri.p;
  4337. }
  4338. break;
  4339. case P_SCHEME_OR_PORT:
  4340. if (end - p >= 3 && strncmp(p, "://", 3) == 0) {
  4341. rscheme.p = uri.p;
  4342. rscheme.len = p - uri.p;
  4343. state = P_USER_INFO;
  4344. p += 2; /* point to last separator char */
  4345. } else {
  4346. rhost.p = uri.p;
  4347. rhost.len = p - uri.p;
  4348. state = P_PORT;
  4349. }
  4350. break;
  4351. case P_USER_INFO:
  4352. p++;
  4353. ruser_info.p = p;
  4354. for (; p < end; p++) {
  4355. if (*p == '@') {
  4356. state = P_HOST;
  4357. break;
  4358. } else if (*p == '/') {
  4359. break;
  4360. }
  4361. }
  4362. if (p == end || *p == '/') {
  4363. /* backtrack and parse as host */
  4364. state = P_HOST;
  4365. p = ruser_info.p;
  4366. }
  4367. ruser_info.len = p - ruser_info.p;
  4368. break;
  4369. case P_HOST:
  4370. if (*p == '@') p++;
  4371. rhost.p = p;
  4372. for (; p < end; p++) {
  4373. if (*p == ':') {
  4374. state = P_PORT;
  4375. break;
  4376. } else if (*p == '/') {
  4377. state = P_REST;
  4378. break;
  4379. }
  4380. }
  4381. rhost.len = p - rhost.p;
  4382. break;
  4383. case P_PORT:
  4384. p++;
  4385. for (; p < end; p++) {
  4386. if (*p == '/') {
  4387. state = P_REST;
  4388. break;
  4389. }
  4390. rport *= 10;
  4391. rport += *p - '0';
  4392. }
  4393. break;
  4394. case P_REST:
  4395. /* `p` points to separator. `path` includes the separator */
  4396. parse_uri_component(&p, end, '?', &rpath);
  4397. parse_uri_component(&p, end, '#', &rquery);
  4398. parse_uri_component(&p, end, '\0', &rfragment);
  4399. break;
  4400. }
  4401. }
  4402. if (scheme != 0) *scheme = rscheme;
  4403. if (user_info != 0) *user_info = ruser_info;
  4404. if (host != 0) *host = rhost;
  4405. if (port != 0) *port = rport;
  4406. if (path != 0) *path = rpath;
  4407. if (query != 0) *query = rquery;
  4408. if (fragment != 0) *fragment = rfragment;
  4409. return 0;
  4410. }
  4411. /* Normalize the URI path. Remove/resolve "." and "..". */
  4412. int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
  4413. const char *s = in->p, *se = s + in->len;
  4414. char *cp = (char *) out->p, *d;
  4415. if (in->len == 0 || *s != '/') {
  4416. out->len = 0;
  4417. return 0;
  4418. }
  4419. d = cp;
  4420. while (s < se) {
  4421. const char *next = s;
  4422. struct mg_str component;
  4423. parse_uri_component(&next, se, '/', &component);
  4424. if (mg_vcmp(&component, ".") == 0) {
  4425. /* Yum. */
  4426. } else if (mg_vcmp(&component, "..") == 0) {
  4427. /* Backtrack to previous slash. */
  4428. if (d > cp + 1 && *(d - 1) == '/') d--;
  4429. while (d > cp && *(d - 1) != '/') d--;
  4430. } else {
  4431. memmove(d, s, next - s);
  4432. d += next - s;
  4433. }
  4434. s = next;
  4435. }
  4436. if (d == cp) *d++ = '/';
  4437. out->p = cp;
  4438. out->len = d - cp;
  4439. return 1;
  4440. }
  4441. #ifdef MG_MODULE_LINES
  4442. #line 1 "mongoose/src/http.c"
  4443. #endif
  4444. /*
  4445. * Copyright (c) 2014 Cesanta Software Limited
  4446. * All rights reserved
  4447. */
  4448. #if MG_ENABLE_HTTP
  4449. /* Amalgamated: #include "mongoose/src/internal.h" */
  4450. /* Amalgamated: #include "mongoose/src/util.h" */
  4451. /* Amalgamated: #include "common/sha1.h" */
  4452. /* Amalgamated: #include "common/md5.h" */
  4453. static const char *mg_version_header = "Mongoose/" MG_VERSION;
  4454. enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
  4455. struct mg_http_proto_data_file {
  4456. FILE *fp; /* Opened file. */
  4457. int64_t cl; /* Content-Length. How many bytes to send. */
  4458. int64_t sent; /* How many bytes have been already sent. */
  4459. int keepalive; /* Keep connection open after sending. */
  4460. enum mg_http_proto_data_type type;
  4461. };
  4462. #if MG_ENABLE_HTTP_CGI
  4463. struct mg_http_proto_data_cgi {
  4464. struct mg_connection *cgi_nc;
  4465. };
  4466. #endif
  4467. struct mg_http_proto_data_chuncked {
  4468. int64_t body_len; /* How many bytes of chunked body was reassembled. */
  4469. };
  4470. struct mg_http_endpoint {
  4471. struct mg_http_endpoint *next;
  4472. const char *name;
  4473. size_t name_len;
  4474. mg_event_handler_t handler;
  4475. };
  4476. enum mg_http_multipart_stream_state {
  4477. MPS_BEGIN,
  4478. MPS_WAITING_FOR_BOUNDARY,
  4479. MPS_WAITING_FOR_CHUNK,
  4480. MPS_GOT_CHUNK,
  4481. MPS_GOT_BOUNDARY,
  4482. MPS_FINALIZE,
  4483. MPS_FINISHED
  4484. };
  4485. struct mg_http_multipart_stream {
  4486. const char *boundary;
  4487. int boundary_len;
  4488. const char *var_name;
  4489. const char *file_name;
  4490. void *user_data;
  4491. int prev_io_len;
  4492. enum mg_http_multipart_stream_state state;
  4493. int processing_part;
  4494. };
  4495. struct mg_reverse_proxy_data {
  4496. struct mg_connection *linked_conn;
  4497. };
  4498. struct mg_http_proto_data {
  4499. #if MG_ENABLE_FILESYSTEM
  4500. struct mg_http_proto_data_file file;
  4501. #endif
  4502. #if MG_ENABLE_HTTP_CGI
  4503. struct mg_http_proto_data_cgi cgi;
  4504. #endif
  4505. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4506. struct mg_http_multipart_stream mp_stream;
  4507. #endif
  4508. struct mg_http_proto_data_chuncked chunk;
  4509. struct mg_http_endpoint *endpoints;
  4510. mg_event_handler_t endpoint_handler;
  4511. struct mg_reverse_proxy_data reverse_proxy_data;
  4512. };
  4513. static void mg_http_conn_destructor(void *proto_data);
  4514. struct mg_connection *mg_connect_http_base(
  4515. struct mg_mgr *mgr, mg_event_handler_t ev_handler,
  4516. struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
  4517. const char *url, const char **path, char **user, char **pass, char **addr);
  4518. static struct mg_http_proto_data *mg_http_get_proto_data(
  4519. struct mg_connection *c) {
  4520. if (c->proto_data == NULL) {
  4521. c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
  4522. c->proto_data_destructor = mg_http_conn_destructor;
  4523. }
  4524. return (struct mg_http_proto_data *) c->proto_data;
  4525. }
  4526. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4527. static void mg_http_free_proto_data_mp_stream(
  4528. struct mg_http_multipart_stream *mp) {
  4529. MG_FREE((void *) mp->boundary);
  4530. MG_FREE((void *) mp->var_name);
  4531. MG_FREE((void *) mp->file_name);
  4532. memset(mp, 0, sizeof(*mp));
  4533. }
  4534. #endif
  4535. #if MG_ENABLE_FILESYSTEM
  4536. static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
  4537. if (d != NULL) {
  4538. if (d->fp != NULL) {
  4539. fclose(d->fp);
  4540. }
  4541. memset(d, 0, sizeof(struct mg_http_proto_data_file));
  4542. }
  4543. }
  4544. #endif
  4545. static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
  4546. struct mg_http_endpoint *current = *ep;
  4547. while (current != NULL) {
  4548. struct mg_http_endpoint *tmp = current->next;
  4549. MG_FREE((void *) current->name);
  4550. MG_FREE(current);
  4551. current = tmp;
  4552. }
  4553. ep = NULL;
  4554. }
  4555. static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) {
  4556. if (rpd->linked_conn != NULL) {
  4557. /*
  4558. * Connection has linked one, we have to unlink & close it
  4559. * since _this_ connection is going to die and
  4560. * it doesn't make sense to keep another one
  4561. */
  4562. struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn);
  4563. if (pd->reverse_proxy_data.linked_conn != NULL) {
  4564. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  4565. pd->reverse_proxy_data.linked_conn = NULL;
  4566. }
  4567. rpd->linked_conn = NULL;
  4568. }
  4569. }
  4570. static void mg_http_conn_destructor(void *proto_data) {
  4571. struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
  4572. #if MG_ENABLE_FILESYSTEM
  4573. mg_http_free_proto_data_file(&pd->file);
  4574. #endif
  4575. #if MG_ENABLE_HTTP_CGI
  4576. mg_http_free_proto_data_cgi(&pd->cgi);
  4577. #endif
  4578. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4579. mg_http_free_proto_data_mp_stream(&pd->mp_stream);
  4580. #endif
  4581. mg_http_free_proto_data_endpoints(&pd->endpoints);
  4582. mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
  4583. MG_FREE(proto_data);
  4584. }
  4585. #if MG_ENABLE_FILESYSTEM
  4586. #define MIME_ENTRY(_ext, _type) \
  4587. { _ext, sizeof(_ext) - 1, _type }
  4588. static const struct {
  4589. const char *extension;
  4590. size_t ext_len;
  4591. const char *mime_type;
  4592. } mg_static_builtin_mime_types[] = {
  4593. MIME_ENTRY("html", "text/html"),
  4594. MIME_ENTRY("html", "text/html"),
  4595. MIME_ENTRY("htm", "text/html"),
  4596. MIME_ENTRY("shtm", "text/html"),
  4597. MIME_ENTRY("shtml", "text/html"),
  4598. MIME_ENTRY("css", "text/css"),
  4599. MIME_ENTRY("js", "application/x-javascript"),
  4600. MIME_ENTRY("ico", "image/x-icon"),
  4601. MIME_ENTRY("gif", "image/gif"),
  4602. MIME_ENTRY("jpg", "image/jpeg"),
  4603. MIME_ENTRY("jpeg", "image/jpeg"),
  4604. MIME_ENTRY("png", "image/png"),
  4605. MIME_ENTRY("svg", "image/svg+xml"),
  4606. MIME_ENTRY("txt", "text/plain"),
  4607. MIME_ENTRY("torrent", "application/x-bittorrent"),
  4608. MIME_ENTRY("wav", "audio/x-wav"),
  4609. MIME_ENTRY("mp3", "audio/x-mp3"),
  4610. MIME_ENTRY("mid", "audio/mid"),
  4611. MIME_ENTRY("m3u", "audio/x-mpegurl"),
  4612. MIME_ENTRY("ogg", "application/ogg"),
  4613. MIME_ENTRY("ram", "audio/x-pn-realaudio"),
  4614. MIME_ENTRY("xml", "text/xml"),
  4615. MIME_ENTRY("ttf", "application/x-font-ttf"),
  4616. MIME_ENTRY("json", "application/json"),
  4617. MIME_ENTRY("xslt", "application/xml"),
  4618. MIME_ENTRY("xsl", "application/xml"),
  4619. MIME_ENTRY("ra", "audio/x-pn-realaudio"),
  4620. MIME_ENTRY("doc", "application/msword"),
  4621. MIME_ENTRY("exe", "application/octet-stream"),
  4622. MIME_ENTRY("zip", "application/x-zip-compressed"),
  4623. MIME_ENTRY("xls", "application/excel"),
  4624. MIME_ENTRY("tgz", "application/x-tar-gz"),
  4625. MIME_ENTRY("tar", "application/x-tar"),
  4626. MIME_ENTRY("gz", "application/x-gunzip"),
  4627. MIME_ENTRY("arj", "application/x-arj-compressed"),
  4628. MIME_ENTRY("rar", "application/x-rar-compressed"),
  4629. MIME_ENTRY("rtf", "application/rtf"),
  4630. MIME_ENTRY("pdf", "application/pdf"),
  4631. MIME_ENTRY("swf", "application/x-shockwave-flash"),
  4632. MIME_ENTRY("mpg", "video/mpeg"),
  4633. MIME_ENTRY("webm", "video/webm"),
  4634. MIME_ENTRY("mpeg", "video/mpeg"),
  4635. MIME_ENTRY("mov", "video/quicktime"),
  4636. MIME_ENTRY("mp4", "video/mp4"),
  4637. MIME_ENTRY("m4v", "video/x-m4v"),
  4638. MIME_ENTRY("asf", "video/x-ms-asf"),
  4639. MIME_ENTRY("avi", "video/x-msvideo"),
  4640. MIME_ENTRY("bmp", "image/bmp"),
  4641. {NULL, 0, NULL}};
  4642. static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
  4643. const struct mg_serve_http_opts *opts) {
  4644. const char *ext, *overrides;
  4645. size_t i, path_len;
  4646. struct mg_str r, k, v;
  4647. path_len = strlen(path);
  4648. overrides = opts->custom_mime_types;
  4649. while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
  4650. ext = path + (path_len - k.len);
  4651. if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
  4652. return v;
  4653. }
  4654. }
  4655. for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
  4656. ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
  4657. if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
  4658. mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
  4659. r.p = mg_static_builtin_mime_types[i].mime_type;
  4660. r.len = strlen(r.p);
  4661. return r;
  4662. }
  4663. }
  4664. r.p = dflt;
  4665. r.len = strlen(r.p);
  4666. return r;
  4667. }
  4668. #endif
  4669. /*
  4670. * Check whether full request is buffered. Return:
  4671. * -1 if request is malformed
  4672. * 0 if request is not yet fully buffered
  4673. * >0 actual request length, including last \r\n\r\n
  4674. */
  4675. static int mg_http_get_request_len(const char *s, int buf_len) {
  4676. const unsigned char *buf = (unsigned char *) s;
  4677. int i;
  4678. for (i = 0; i < buf_len; i++) {
  4679. if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
  4680. return -1;
  4681. } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
  4682. return i + 2;
  4683. } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
  4684. buf[i + 2] == '\n') {
  4685. return i + 3;
  4686. }
  4687. }
  4688. return 0;
  4689. }
  4690. static const char *mg_http_parse_headers(const char *s, const char *end,
  4691. int len, struct http_message *req) {
  4692. int i = 0;
  4693. while (i < (int) ARRAY_SIZE(req->header_names) - 1) {
  4694. struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
  4695. s = mg_skip(s, end, ": ", k);
  4696. s = mg_skip(s, end, "\r\n", v);
  4697. while (v->len > 0 && v->p[v->len - 1] == ' ') {
  4698. v->len--; /* Trim trailing spaces in header value */
  4699. }
  4700. /*
  4701. * If header value is empty - skip it and go to next (if any).
  4702. * NOTE: Do not add it to headers_values because such addition changes API
  4703. * behaviour
  4704. */
  4705. if (k->len != 0 && v->len == 0) {
  4706. continue;
  4707. }
  4708. if (k->len == 0 || v->len == 0) {
  4709. k->p = v->p = NULL;
  4710. k->len = v->len = 0;
  4711. break;
  4712. }
  4713. if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
  4714. req->body.len = (size_t) to64(v->p);
  4715. req->message.len = len + req->body.len;
  4716. }
  4717. i++;
  4718. }
  4719. return s;
  4720. }
  4721. int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
  4722. const char *end, *qs;
  4723. int len = mg_http_get_request_len(s, n);
  4724. if (len <= 0) return len;
  4725. memset(hm, 0, sizeof(*hm));
  4726. hm->message.p = s;
  4727. hm->body.p = s + len;
  4728. hm->message.len = hm->body.len = (size_t) ~0;
  4729. end = s + len;
  4730. /* Request is fully buffered. Skip leading whitespaces. */
  4731. while (s < end && isspace(*(unsigned char *) s)) s++;
  4732. if (is_req) {
  4733. /* Parse request line: method, URI, proto */
  4734. s = mg_skip(s, end, " ", &hm->method);
  4735. s = mg_skip(s, end, " ", &hm->uri);
  4736. s = mg_skip(s, end, "\r\n", &hm->proto);
  4737. if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
  4738. /* If URI contains '?' character, initialize query_string */
  4739. if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
  4740. hm->query_string.p = qs + 1;
  4741. hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
  4742. hm->uri.len = qs - hm->uri.p;
  4743. }
  4744. } else {
  4745. s = mg_skip(s, end, " ", &hm->proto);
  4746. if (end - s < 4 || s[3] != ' ') return -1;
  4747. hm->resp_code = atoi(s);
  4748. if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
  4749. s += 4;
  4750. s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
  4751. }
  4752. s = mg_http_parse_headers(s, end, len, hm);
  4753. /*
  4754. * mg_parse_http() is used to parse both HTTP requests and HTTP
  4755. * responses. If HTTP response does not have Content-Length set, then
  4756. * body is read until socket is closed, i.e. body.len is infinite (~0).
  4757. *
  4758. * For HTTP requests though, according to
  4759. * http://tools.ietf.org/html/rfc7231#section-8.1.3,
  4760. * only POST and PUT methods have defined body semantics.
  4761. * Therefore, if Content-Length is not specified and methods are
  4762. * not one of PUT or POST, set body length to 0.
  4763. *
  4764. * So,
  4765. * if it is HTTP request, and Content-Length is not set,
  4766. * and method is not (PUT or POST) then reset body length to zero.
  4767. */
  4768. if (hm->body.len == (size_t) ~0 && is_req &&
  4769. mg_vcasecmp(&hm->method, "PUT") != 0 &&
  4770. mg_vcasecmp(&hm->method, "POST") != 0) {
  4771. hm->body.len = 0;
  4772. hm->message.len = len;
  4773. }
  4774. return len;
  4775. }
  4776. struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
  4777. size_t i, len = strlen(name);
  4778. for (i = 0; hm->header_names[i].len > 0; i++) {
  4779. struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
  4780. if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
  4781. return v;
  4782. }
  4783. return NULL;
  4784. }
  4785. #if MG_ENABLE_FILESYSTEM
  4786. static void mg_http_transfer_file_data(struct mg_connection *nc) {
  4787. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  4788. char buf[MG_MAX_HTTP_SEND_MBUF];
  4789. size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent);
  4790. if (pd->file.type == DATA_FILE) {
  4791. struct mbuf *io = &nc->send_mbuf;
  4792. if (io->len < sizeof(buf)) {
  4793. to_read = sizeof(buf) - io->len;
  4794. }
  4795. if (left > 0 && to_read > left) {
  4796. to_read = left;
  4797. }
  4798. if (to_read == 0) {
  4799. /* Rate limiting. send_mbuf is too full, wait until it's drained. */
  4800. } else if (pd->file.sent < pd->file.cl &&
  4801. (n = fread(buf, 1, to_read, pd->file.fp)) > 0) {
  4802. mg_send(nc, buf, n);
  4803. pd->file.sent += n;
  4804. } else {
  4805. if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
  4806. mg_http_free_proto_data_file(&pd->file);
  4807. }
  4808. } else if (pd->file.type == DATA_PUT) {
  4809. struct mbuf *io = &nc->recv_mbuf;
  4810. size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len;
  4811. size_t n = fwrite(io->buf, 1, to_write, pd->file.fp);
  4812. if (n > 0) {
  4813. mbuf_remove(io, n);
  4814. pd->file.sent += n;
  4815. }
  4816. if (n == 0 || pd->file.sent >= pd->file.cl) {
  4817. if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
  4818. mg_http_free_proto_data_file(&pd->file);
  4819. }
  4820. }
  4821. #if MG_ENABLE_HTTP_CGI
  4822. else if (pd->cgi.cgi_nc != NULL) {
  4823. /* This is POST data that needs to be forwarded to the CGI process */
  4824. if (pd->cgi.cgi_nc != NULL) {
  4825. mg_forward(nc, pd->cgi.cgi_nc);
  4826. } else {
  4827. nc->flags |= MG_F_SEND_AND_CLOSE;
  4828. }
  4829. }
  4830. #endif
  4831. }
  4832. #endif /* MG_ENABLE_FILESYSTEM */
  4833. /*
  4834. * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
  4835. * if it's incomplete. If the chunk is fully buffered, return total number of
  4836. * bytes in a chunk, and store data in `data`, `data_len`.
  4837. */
  4838. static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
  4839. size_t *chunk_len) {
  4840. unsigned char *s = (unsigned char *) buf;
  4841. size_t n = 0; /* scanned chunk length */
  4842. size_t i = 0; /* index in s */
  4843. /* Scan chunk length. That should be a hexadecimal number. */
  4844. while (i < len && isxdigit(s[i])) {
  4845. n *= 16;
  4846. n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
  4847. i++;
  4848. }
  4849. /* Skip new line */
  4850. if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
  4851. return 0;
  4852. }
  4853. i += 2;
  4854. /* Record where the data is */
  4855. *chunk_data = (char *) s + i;
  4856. *chunk_len = n;
  4857. /* Skip data */
  4858. i += n;
  4859. /* Skip new line */
  4860. if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
  4861. return 0;
  4862. }
  4863. return i + 2;
  4864. }
  4865. MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
  4866. struct http_message *hm, char *buf,
  4867. size_t blen) {
  4868. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  4869. char *data;
  4870. size_t i, n, data_len, body_len, zero_chunk_received = 0;
  4871. /* Find out piece of received data that is not yet reassembled */
  4872. body_len = (size_t) pd->chunk.body_len;
  4873. assert(blen >= body_len);
  4874. /* Traverse all fully buffered chunks */
  4875. for (i = body_len;
  4876. (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
  4877. i += n) {
  4878. /* Collapse chunk data to the rest of HTTP body */
  4879. memmove(buf + body_len, data, data_len);
  4880. body_len += data_len;
  4881. hm->body.len = body_len;
  4882. if (data_len == 0) {
  4883. zero_chunk_received = 1;
  4884. i += n;
  4885. break;
  4886. }
  4887. }
  4888. if (i > body_len) {
  4889. /* Shift unparsed content to the parsed body */
  4890. assert(i <= blen);
  4891. memmove(buf + body_len, buf + i, blen - i);
  4892. memset(buf + body_len + blen - i, 0, i - body_len);
  4893. nc->recv_mbuf.len -= i - body_len;
  4894. pd->chunk.body_len = body_len;
  4895. /* Send MG_EV_HTTP_CHUNK event */
  4896. nc->flags &= ~MG_F_DELETE_CHUNK;
  4897. mg_call(nc, nc->handler, MG_EV_HTTP_CHUNK, hm);
  4898. /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
  4899. if (nc->flags & MG_F_DELETE_CHUNK) {
  4900. memset(buf, 0, body_len);
  4901. memmove(buf, buf + body_len, blen - i);
  4902. nc->recv_mbuf.len -= body_len;
  4903. hm->body.len = 0;
  4904. pd->chunk.body_len = 0;
  4905. }
  4906. if (zero_chunk_received) {
  4907. /* Total message size is len(body) + len(headers) */
  4908. hm->message.len =
  4909. (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p);
  4910. }
  4911. }
  4912. return body_len;
  4913. }
  4914. static mg_event_handler_t mg_http_get_endpoint_handler(
  4915. struct mg_connection *nc, struct mg_str *uri_path) {
  4916. struct mg_http_proto_data *pd;
  4917. mg_event_handler_t ret = NULL;
  4918. int matched, matched_max = 0;
  4919. struct mg_http_endpoint *ep;
  4920. if (nc == NULL) {
  4921. return NULL;
  4922. }
  4923. pd = mg_http_get_proto_data(nc);
  4924. ep = pd->endpoints;
  4925. while (ep != NULL) {
  4926. const struct mg_str name_s = {ep->name, ep->name_len};
  4927. if ((matched = mg_match_prefix_n(name_s, *uri_path)) != -1) {
  4928. if (matched > matched_max) {
  4929. /* Looking for the longest suitable handler */
  4930. ret = ep->handler;
  4931. matched_max = matched;
  4932. }
  4933. }
  4934. ep = ep->next;
  4935. }
  4936. return ret;
  4937. }
  4938. static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
  4939. struct http_message *hm) {
  4940. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  4941. if (pd->endpoint_handler == NULL || ev == MG_EV_HTTP_REQUEST) {
  4942. pd->endpoint_handler =
  4943. ev == MG_EV_HTTP_REQUEST
  4944. ? mg_http_get_endpoint_handler(nc->listener, &hm->uri)
  4945. : NULL;
  4946. }
  4947. mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, ev,
  4948. hm);
  4949. }
  4950. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4951. static void mg_http_multipart_continue(struct mg_connection *nc);
  4952. static void mg_http_multipart_begin(struct mg_connection *nc,
  4953. struct http_message *hm, int req_len);
  4954. #endif
  4955. /*
  4956. * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
  4957. * If a big structure is declared in a big function, lx106 gcc will make it
  4958. * even bigger (round up to 4k, from 700 bytes of actual size).
  4959. */
  4960. #ifdef __xtensa__
  4961. static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
  4962. struct http_message *hm) __attribute__((noinline));
  4963. void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
  4964. struct http_message hm;
  4965. mg_http_handler2(nc, ev, ev_data, &hm);
  4966. }
  4967. static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
  4968. struct http_message *hm) {
  4969. #else /* !__XTENSA__ */
  4970. void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
  4971. struct http_message shm;
  4972. struct http_message *hm = &shm;
  4973. #endif /* __XTENSA__ */
  4974. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  4975. struct mbuf *io = &nc->recv_mbuf;
  4976. int req_len;
  4977. const int is_req = (nc->listener != NULL);
  4978. #if MG_ENABLE_HTTP_WEBSOCKET
  4979. struct mg_str *vec;
  4980. #endif
  4981. if (ev == MG_EV_CLOSE) {
  4982. #if MG_ENABLE_HTTP_CGI
  4983. /* Close associated CGI forwarder connection */
  4984. if (pd->cgi.cgi_nc != NULL) {
  4985. pd->cgi.cgi_nc->user_data = NULL;
  4986. pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4987. }
  4988. #endif
  4989. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  4990. if (pd->mp_stream.boundary != NULL) {
  4991. /*
  4992. * Multipart message is in progress, but connection is closed.
  4993. * Finish part and request with an error flag.
  4994. */
  4995. struct mg_http_multipart_part mp;
  4996. memset(&mp, 0, sizeof(mp));
  4997. mp.status = -1;
  4998. mp.var_name = pd->mp_stream.var_name;
  4999. mp.file_name = pd->mp_stream.file_name;
  5000. mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
  5001. MG_EV_HTTP_PART_END, &mp);
  5002. mp.var_name = NULL;
  5003. mp.file_name = NULL;
  5004. mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
  5005. MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
  5006. } else
  5007. #endif
  5008. if (io->len > 0 && mg_parse_http(io->buf, io->len, hm, is_req) > 0) {
  5009. /*
  5010. * For HTTP messages without Content-Length, always send HTTP message
  5011. * before MG_EV_CLOSE message.
  5012. */
  5013. int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
  5014. hm->message.len = io->len;
  5015. hm->body.len = io->buf + io->len - hm->body.p;
  5016. mg_http_call_endpoint_handler(nc, ev2, hm);
  5017. }
  5018. }
  5019. #if MG_ENABLE_FILESYSTEM
  5020. if (pd->file.fp != NULL) {
  5021. mg_http_transfer_file_data(nc);
  5022. }
  5023. #endif
  5024. mg_call(nc, nc->handler, ev, ev_data);
  5025. if (ev == MG_EV_RECV) {
  5026. struct mg_str *s;
  5027. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5028. if (pd->mp_stream.boundary != NULL) {
  5029. mg_http_multipart_continue(nc);
  5030. return;
  5031. }
  5032. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  5033. req_len = mg_parse_http(io->buf, io->len, hm, is_req);
  5034. if (req_len > 0 &&
  5035. (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
  5036. mg_vcasecmp(s, "chunked") == 0) {
  5037. mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
  5038. }
  5039. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5040. if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
  5041. s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
  5042. mg_http_multipart_begin(nc, hm, req_len);
  5043. mg_http_multipart_continue(nc);
  5044. return;
  5045. }
  5046. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  5047. /* TODO(alashkin): refactor this ifelseifelseifelseifelse */
  5048. if ((req_len < 0 ||
  5049. (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
  5050. DBG(("invalid request"));
  5051. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  5052. } else if (req_len == 0) {
  5053. /* Do nothing, request is not yet fully buffered */
  5054. }
  5055. #if MG_ENABLE_HTTP_WEBSOCKET
  5056. else if (nc->listener == NULL &&
  5057. mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
  5058. /* We're websocket client, got handshake response from server. */
  5059. /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
  5060. mbuf_remove(io, req_len);
  5061. nc->proto_handler = mg_ws_handler;
  5062. nc->flags |= MG_F_IS_WEBSOCKET;
  5063. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
  5064. mg_ws_handler(nc, MG_EV_RECV, ev_data);
  5065. } else if (nc->listener != NULL &&
  5066. (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
  5067. mg_event_handler_t handler;
  5068. /* This is a websocket request. Switch protocol handlers. */
  5069. mbuf_remove(io, req_len);
  5070. nc->proto_handler = mg_ws_handler;
  5071. nc->flags |= MG_F_IS_WEBSOCKET;
  5072. /*
  5073. * If we have a handler set up with mg_register_http_endpoint(),
  5074. * deliver subsequent websocket events to this handler after the
  5075. * protocol switch.
  5076. */
  5077. handler = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
  5078. if (handler != NULL) {
  5079. nc->handler = handler;
  5080. }
  5081. /* Send handshake */
  5082. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, hm);
  5083. if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) {
  5084. if (nc->send_mbuf.len == 0) {
  5085. mg_ws_handshake(nc, vec);
  5086. }
  5087. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
  5088. mg_ws_handler(nc, MG_EV_RECV, ev_data);
  5089. }
  5090. }
  5091. #endif /* MG_ENABLE_HTTP_WEBSOCKET */
  5092. else if (hm->message.len <= io->len) {
  5093. int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
  5094. /* Whole HTTP message is fully buffered, call event handler */
  5095. #if MG_ENABLE_JAVASCRIPT
  5096. v7_val_t v1, v2, headers, req, args, res;
  5097. struct v7 *v7 = nc->mgr->v7;
  5098. const char *ev_name = trigger_ev == MG_EV_HTTP_REPLY ? "onsnd" : "onrcv";
  5099. int i, js_callback_handled_request = 0;
  5100. if (v7 != NULL) {
  5101. /* Lookup JS callback */
  5102. v1 = v7_get(v7, v7_get_global(v7), "Http", ~0);
  5103. v2 = v7_get(v7, v1, ev_name, ~0);
  5104. /* Create callback params. TODO(lsm): own/disown those */
  5105. args = v7_mk_array(v7);
  5106. req = v7_mk_object(v7);
  5107. headers = v7_mk_object(v7);
  5108. /* Populate request object */
  5109. v7_set(v7, req, "method", ~0,
  5110. v7_mk_string(v7, hm->method.p, hm->method.len, 1));
  5111. v7_set(v7, req, "uri", ~0, v7_mk_string(v7, hm->uri.p, hm->uri.len, 1));
  5112. v7_set(v7, req, "body", ~0,
  5113. v7_mk_string(v7, hm->body.p, hm->body.len, 1));
  5114. v7_set(v7, req, "headers", ~0, headers);
  5115. for (i = 0; hm->header_names[i].len > 0; i++) {
  5116. const struct mg_str *name = &hm->header_names[i];
  5117. const struct mg_str *value = &hm->header_values[i];
  5118. v7_set(v7, headers, name->p, name->len,
  5119. v7_mk_string(v7, value->p, value->len, 1));
  5120. }
  5121. /* Invoke callback. TODO(lsm): report errors */
  5122. v7_array_push(v7, args, v7_mk_foreign(v7, nc));
  5123. v7_array_push(v7, args, req);
  5124. if (v7_apply(v7, v2, V7_UNDEFINED, args, &res) == V7_OK &&
  5125. v7_is_truthy(v7, res)) {
  5126. js_callback_handled_request++;
  5127. }
  5128. }
  5129. /* If JS callback returns true, stop request processing */
  5130. if (js_callback_handled_request) {
  5131. nc->flags |= MG_F_SEND_AND_CLOSE;
  5132. } else {
  5133. mg_http_call_endpoint_handler(nc, trigger_ev, hm);
  5134. }
  5135. #else
  5136. mg_http_call_endpoint_handler(nc, trigger_ev, hm);
  5137. #endif
  5138. mbuf_remove(io, hm->message.len);
  5139. }
  5140. }
  5141. (void) pd;
  5142. }
  5143. static size_t mg_get_line_len(const char *buf, size_t buf_len) {
  5144. size_t len = 0;
  5145. while (len < buf_len && buf[len] != '\n') len++;
  5146. return len == buf_len ? 0 : len + 1;
  5147. }
  5148. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5149. static void mg_http_multipart_begin(struct mg_connection *nc,
  5150. struct http_message *hm, int req_len) {
  5151. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  5152. struct mg_str *ct;
  5153. struct mbuf *io = &nc->recv_mbuf;
  5154. char boundary[100];
  5155. int boundary_len;
  5156. ct = mg_get_http_header(hm, "Content-Type");
  5157. if (ct == NULL) {
  5158. /* We need more data - or it isn't multipart mesage */
  5159. goto exit_mp;
  5160. }
  5161. /* Content-type should start with "multipart" */
  5162. if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
  5163. goto exit_mp;
  5164. }
  5165. boundary_len =
  5166. mg_http_parse_header(ct, "boundary", boundary, sizeof(boundary));
  5167. if (boundary_len == 0) {
  5168. /*
  5169. * Content type is multipart, but there is no boundary,
  5170. * probably malformed request
  5171. */
  5172. nc->flags = MG_F_CLOSE_IMMEDIATELY;
  5173. DBG(("invalid request"));
  5174. goto exit_mp;
  5175. }
  5176. /* If we reach this place - that is multipart request */
  5177. if (pd->mp_stream.boundary != NULL) {
  5178. /*
  5179. * Another streaming request was in progress,
  5180. * looks like protocol error
  5181. */
  5182. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  5183. } else {
  5184. pd->mp_stream.state = MPS_BEGIN;
  5185. pd->mp_stream.boundary = MG_STRDUP(boundary);
  5186. pd->mp_stream.boundary_len = strlen(boundary);
  5187. pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
  5188. pd->endpoint_handler = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
  5189. if (pd->endpoint_handler == NULL) {
  5190. pd->endpoint_handler = nc->handler;
  5191. }
  5192. mg_call(nc, pd->endpoint_handler, MG_EV_HTTP_MULTIPART_REQUEST, hm);
  5193. mbuf_remove(io, req_len);
  5194. }
  5195. exit_mp:
  5196. ;
  5197. }
  5198. #define CONTENT_DISPOSITION "Content-Disposition: "
  5199. static void mg_http_multipart_call_handler(struct mg_connection *c, int ev,
  5200. const char *data, size_t data_len) {
  5201. struct mg_http_multipart_part mp;
  5202. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5203. memset(&mp, 0, sizeof(mp));
  5204. mp.var_name = pd->mp_stream.var_name;
  5205. mp.file_name = pd->mp_stream.file_name;
  5206. mp.user_data = pd->mp_stream.user_data;
  5207. mp.data.p = data;
  5208. mp.data.len = data_len;
  5209. mg_call(c, pd->endpoint_handler, ev, &mp);
  5210. pd->mp_stream.user_data = mp.user_data;
  5211. }
  5212. static int mg_http_multipart_got_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. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf,
  5216. pd->mp_stream.prev_io_len);
  5217. mbuf_remove(io, pd->mp_stream.prev_io_len);
  5218. pd->mp_stream.prev_io_len = 0;
  5219. pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
  5220. return 0;
  5221. }
  5222. static int mg_http_multipart_finalize(struct mg_connection *c) {
  5223. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5224. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
  5225. MG_FREE((void *) pd->mp_stream.file_name);
  5226. pd->mp_stream.file_name = NULL;
  5227. MG_FREE((void *) pd->mp_stream.var_name);
  5228. pd->mp_stream.var_name = NULL;
  5229. mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
  5230. mg_http_free_proto_data_mp_stream(&pd->mp_stream);
  5231. pd->mp_stream.state = MPS_FINISHED;
  5232. return 1;
  5233. }
  5234. static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
  5235. const char *boundary;
  5236. struct mbuf *io = &c->recv_mbuf;
  5237. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5238. if (pd->mp_stream.boundary == NULL) {
  5239. pd->mp_stream.state = MPS_FINALIZE;
  5240. DBG(("Invalid request: boundary not initialized"));
  5241. return 0;
  5242. }
  5243. if ((int) io->len < pd->mp_stream.boundary_len + 2) {
  5244. return 0;
  5245. }
  5246. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  5247. if (boundary != NULL) {
  5248. const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
  5249. if (io->len - (boundary_end - io->buf) < 4) {
  5250. return 0;
  5251. }
  5252. if (strncmp(boundary_end, "--\r\n", 4) == 0) {
  5253. pd->mp_stream.state = MPS_FINALIZE;
  5254. mbuf_remove(io, (boundary_end - io->buf) + 4);
  5255. } else {
  5256. pd->mp_stream.state = MPS_GOT_BOUNDARY;
  5257. }
  5258. } else {
  5259. return 0;
  5260. }
  5261. return 1;
  5262. }
  5263. static int mg_http_multipart_process_boundary(struct mg_connection *c) {
  5264. int data_size;
  5265. const char *boundary, *block_begin;
  5266. struct mbuf *io = &c->recv_mbuf;
  5267. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5268. char file_name[100], var_name[100];
  5269. int line_len;
  5270. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  5271. block_begin = boundary + pd->mp_stream.boundary_len + 2;
  5272. data_size = io->len - (block_begin - io->buf);
  5273. while (data_size > 0 &&
  5274. (line_len = mg_get_line_len(block_begin, data_size)) != 0) {
  5275. if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
  5276. mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
  5277. sizeof(CONTENT_DISPOSITION) - 1) == 0) {
  5278. struct mg_str header;
  5279. header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
  5280. header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
  5281. mg_http_parse_header(&header, "name", var_name, sizeof(var_name) - 2);
  5282. mg_http_parse_header(&header, "filename", file_name,
  5283. sizeof(file_name) - 2);
  5284. block_begin += line_len;
  5285. data_size -= line_len;
  5286. continue;
  5287. }
  5288. if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
  5289. mbuf_remove(io, block_begin - io->buf + 2);
  5290. if (pd->mp_stream.processing_part != 0) {
  5291. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
  5292. }
  5293. MG_FREE((void *) pd->mp_stream.file_name);
  5294. pd->mp_stream.file_name = MG_STRDUP(file_name);
  5295. MG_FREE((void *) pd->mp_stream.var_name);
  5296. pd->mp_stream.var_name = MG_STRDUP(var_name);
  5297. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
  5298. pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
  5299. pd->mp_stream.processing_part++;
  5300. return 1;
  5301. }
  5302. block_begin += line_len;
  5303. }
  5304. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  5305. return 0;
  5306. }
  5307. static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
  5308. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5309. struct mbuf *io = &c->recv_mbuf;
  5310. const char *boundary;
  5311. if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
  5312. return 0;
  5313. }
  5314. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  5315. if (boundary == NULL && pd->mp_stream.prev_io_len == 0) {
  5316. pd->mp_stream.prev_io_len = io->len;
  5317. return 0;
  5318. } else if (boundary == NULL &&
  5319. (int) io->len >
  5320. pd->mp_stream.prev_io_len + pd->mp_stream.boundary_len + 4) {
  5321. pd->mp_stream.state = MPS_GOT_CHUNK;
  5322. return 1;
  5323. } else if (boundary != NULL) {
  5324. int data_size = (boundary - io->buf - 4);
  5325. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_size);
  5326. mbuf_remove(io, (boundary - io->buf));
  5327. pd->mp_stream.prev_io_len = 0;
  5328. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  5329. return 1;
  5330. } else {
  5331. return 0;
  5332. }
  5333. }
  5334. static void mg_http_multipart_continue(struct mg_connection *c) {
  5335. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  5336. while (1) {
  5337. switch (pd->mp_stream.state) {
  5338. case MPS_BEGIN: {
  5339. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  5340. break;
  5341. }
  5342. case MPS_WAITING_FOR_BOUNDARY: {
  5343. if (mg_http_multipart_wait_for_boundary(c) == 0) {
  5344. return;
  5345. }
  5346. break;
  5347. }
  5348. case MPS_GOT_BOUNDARY: {
  5349. if (mg_http_multipart_process_boundary(c) == 0) {
  5350. return;
  5351. }
  5352. break;
  5353. }
  5354. case MPS_WAITING_FOR_CHUNK: {
  5355. if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
  5356. return;
  5357. }
  5358. break;
  5359. }
  5360. case MPS_GOT_CHUNK: {
  5361. if (mg_http_multipart_got_chunk(c) == 0) {
  5362. return;
  5363. }
  5364. break;
  5365. }
  5366. case MPS_FINALIZE: {
  5367. if (mg_http_multipart_finalize(c) == 0) {
  5368. return;
  5369. }
  5370. break;
  5371. }
  5372. case MPS_FINISHED: {
  5373. mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
  5374. return;
  5375. }
  5376. }
  5377. }
  5378. }
  5379. struct file_upload_state {
  5380. char *lfn;
  5381. size_t num_recd;
  5382. FILE *fp;
  5383. };
  5384. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  5385. void mg_set_protocol_http_websocket(struct mg_connection *nc) {
  5386. nc->proto_handler = mg_http_handler;
  5387. }
  5388. const char *mg_status_message(int status_code) {
  5389. switch (status_code) {
  5390. case 206:
  5391. return "Partial Content";
  5392. case 301:
  5393. return "Moved";
  5394. case 302:
  5395. return "Found";
  5396. case 400:
  5397. return "Bad Request";
  5398. case 401:
  5399. return "Unauthorized";
  5400. case 403:
  5401. return "Forbidden";
  5402. case 404:
  5403. return "Not Found";
  5404. case 416:
  5405. return "Requested Range Not Satisfiable";
  5406. case 418:
  5407. return "I'm a teapot";
  5408. case 500:
  5409. return "Internal Server Error";
  5410. case 502:
  5411. return "Bad Gateway";
  5412. case 503:
  5413. return "Service Unavailable";
  5414. #if MG_ENABLE_EXTRA_ERRORS_DESC
  5415. case 100:
  5416. return "Continue";
  5417. case 101:
  5418. return "Switching Protocols";
  5419. case 102:
  5420. return "Processing";
  5421. case 200:
  5422. return "OK";
  5423. case 201:
  5424. return "Created";
  5425. case 202:
  5426. return "Accepted";
  5427. case 203:
  5428. return "Non-Authoritative Information";
  5429. case 204:
  5430. return "No Content";
  5431. case 205:
  5432. return "Reset Content";
  5433. case 207:
  5434. return "Multi-Status";
  5435. case 208:
  5436. return "Already Reported";
  5437. case 226:
  5438. return "IM Used";
  5439. case 300:
  5440. return "Multiple Choices";
  5441. case 303:
  5442. return "See Other";
  5443. case 304:
  5444. return "Not Modified";
  5445. case 305:
  5446. return "Use Proxy";
  5447. case 306:
  5448. return "Switch Proxy";
  5449. case 307:
  5450. return "Temporary Redirect";
  5451. case 308:
  5452. return "Permanent Redirect";
  5453. case 402:
  5454. return "Payment Required";
  5455. case 405:
  5456. return "Method Not Allowed";
  5457. case 406:
  5458. return "Not Acceptable";
  5459. case 407:
  5460. return "Proxy Authentication Required";
  5461. case 408:
  5462. return "Request Timeout";
  5463. case 409:
  5464. return "Conflict";
  5465. case 410:
  5466. return "Gone";
  5467. case 411:
  5468. return "Length Required";
  5469. case 412:
  5470. return "Precondition Failed";
  5471. case 413:
  5472. return "Payload Too Large";
  5473. case 414:
  5474. return "URI Too Long";
  5475. case 415:
  5476. return "Unsupported Media Type";
  5477. case 417:
  5478. return "Expectation Failed";
  5479. case 422:
  5480. return "Unprocessable Entity";
  5481. case 423:
  5482. return "Locked";
  5483. case 424:
  5484. return "Failed Dependency";
  5485. case 426:
  5486. return "Upgrade Required";
  5487. case 428:
  5488. return "Precondition Required";
  5489. case 429:
  5490. return "Too Many Requests";
  5491. case 431:
  5492. return "Request Header Fields Too Large";
  5493. case 451:
  5494. return "Unavailable For Legal Reasons";
  5495. case 501:
  5496. return "Not Implemented";
  5497. case 504:
  5498. return "Gateway Timeout";
  5499. case 505:
  5500. return "HTTP Version Not Supported";
  5501. case 506:
  5502. return "Variant Also Negotiates";
  5503. case 507:
  5504. return "Insufficient Storage";
  5505. case 508:
  5506. return "Loop Detected";
  5507. case 510:
  5508. return "Not Extended";
  5509. case 511:
  5510. return "Network Authentication Required";
  5511. #endif /* MG_ENABLE_EXTRA_ERRORS_DESC */
  5512. default:
  5513. return "OK";
  5514. }
  5515. }
  5516. void mg_send_response_line_s(struct mg_connection *nc, int status_code,
  5517. const struct mg_str extra_headers) {
  5518. mg_printf(nc, "HTTP/1.1 %d %s\r\nServer: %s\r\n", status_code,
  5519. mg_status_message(status_code), mg_version_header);
  5520. if (extra_headers.len > 0) {
  5521. mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p);
  5522. }
  5523. }
  5524. void mg_send_response_line(struct mg_connection *nc, int status_code,
  5525. const char *extra_headers) {
  5526. mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
  5527. }
  5528. void mg_http_send_redirect(struct mg_connection *nc, int status_code,
  5529. const struct mg_str location,
  5530. const struct mg_str extra_headers) {
  5531. char bbody[100], *pbody = bbody;
  5532. int bl = mg_asprintf(&pbody, sizeof(bbody),
  5533. "<p>Moved <a href='%.*s'>here</a>.\r\n",
  5534. (int) location.len, location.p);
  5535. char bhead[150], *phead = bhead;
  5536. mg_asprintf(&phead, sizeof(bhead),
  5537. "Location: %.*s\r\n"
  5538. "Content-Type: text/html\r\n"
  5539. "Content-Length: %d\r\n"
  5540. "Cache-Control: no-cache\r\n"
  5541. "%.*s%s",
  5542. (int) location.len, location.p, bl, (int) extra_headers.len,
  5543. extra_headers.p, (extra_headers.len > 0 ? "\r\n" : ""));
  5544. mg_send_response_line(nc, status_code, phead);
  5545. if (phead != bhead) MG_FREE(phead);
  5546. mg_send(nc, pbody, bl);
  5547. if (pbody != bbody) MG_FREE(pbody);
  5548. }
  5549. void mg_send_head(struct mg_connection *c, int status_code,
  5550. int64_t content_length, const char *extra_headers) {
  5551. mg_send_response_line(c, status_code, extra_headers);
  5552. if (content_length < 0) {
  5553. mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
  5554. } else {
  5555. mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
  5556. }
  5557. mg_send(c, "\r\n", 2);
  5558. }
  5559. void mg_http_send_error(struct mg_connection *nc, int code,
  5560. const char *reason) {
  5561. if (!reason) reason = mg_status_message(code);
  5562. LOG(LL_DEBUG, ("%p %d %s", nc, code, reason));
  5563. mg_send_head(nc, code, strlen(reason),
  5564. "Content-Type: text/plain\r\nConnection: close");
  5565. mg_send(nc, reason, strlen(reason));
  5566. nc->flags |= MG_F_SEND_AND_CLOSE;
  5567. }
  5568. #if MG_ENABLE_FILESYSTEM
  5569. static void mg_http_construct_etag(char *buf, size_t buf_len,
  5570. const cs_stat_t *st) {
  5571. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
  5572. (int64_t) st->st_size);
  5573. }
  5574. #ifndef WINCE
  5575. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  5576. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  5577. }
  5578. #else
  5579. /* Look wince_lib.c for WindowsCE implementation */
  5580. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t);
  5581. #endif
  5582. static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
  5583. int64_t *b) {
  5584. /*
  5585. * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
  5586. * so we have this. Ugh.
  5587. */
  5588. int result;
  5589. char *p = (char *) MG_MALLOC(header->len + 1);
  5590. if (p == NULL) return 0;
  5591. memcpy(p, header->p, header->len);
  5592. p[header->len] = '\0';
  5593. result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  5594. MG_FREE(p);
  5595. return result;
  5596. }
  5597. void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
  5598. const char *path, const struct mg_str mime_type,
  5599. const struct mg_str extra_headers) {
  5600. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  5601. cs_stat_t st;
  5602. LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p));
  5603. if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) {
  5604. int code, err = mg_get_errno();
  5605. switch (err) {
  5606. case EACCES:
  5607. code = 403;
  5608. break;
  5609. case ENOENT:
  5610. code = 404;
  5611. break;
  5612. default:
  5613. code = 500;
  5614. };
  5615. mg_http_send_error(nc, code, "Open failed");
  5616. } else {
  5617. char etag[50], current_time[50], last_modified[50], range[70];
  5618. time_t t = (time_t) mg_time();
  5619. int64_t r1 = 0, r2 = 0, cl = st.st_size;
  5620. struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
  5621. int n, status_code = 200;
  5622. /* Handle Range header */
  5623. range[0] = '\0';
  5624. if (range_hdr != NULL &&
  5625. (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  5626. r2 >= 0) {
  5627. /* If range is specified like "400-", set second limit to content len */
  5628. if (n == 1) {
  5629. r2 = cl - 1;
  5630. }
  5631. if (r1 > r2 || r2 >= cl) {
  5632. status_code = 416;
  5633. cl = 0;
  5634. snprintf(range, sizeof(range),
  5635. "Content-Range: bytes */%" INT64_FMT "\r\n",
  5636. (int64_t) st.st_size);
  5637. } else {
  5638. status_code = 206;
  5639. cl = r2 - r1 + 1;
  5640. snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
  5641. "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  5642. r1, r1 + cl - 1, (int64_t) st.st_size);
  5643. #if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
  5644. _XOPEN_SOURCE >= 600
  5645. fseeko(pd->file.fp, r1, SEEK_SET);
  5646. #else
  5647. fseek(pd->file.fp, (long) r1, SEEK_SET);
  5648. #endif
  5649. }
  5650. }
  5651. #if !MG_DISABLE_HTTP_KEEP_ALIVE
  5652. {
  5653. struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection");
  5654. if (conn_hdr != NULL) {
  5655. pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0);
  5656. } else {
  5657. pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0);
  5658. }
  5659. }
  5660. #endif
  5661. mg_http_construct_etag(etag, sizeof(etag), &st);
  5662. mg_gmt_time_string(current_time, sizeof(current_time), &t);
  5663. mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime);
  5664. /*
  5665. * Content length casted to size_t because:
  5666. * 1) that's the maximum buffer size anyway
  5667. * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
  5668. * position
  5669. * TODO(mkm): fix ESP8266 RTOS SDK
  5670. */
  5671. mg_send_response_line_s(nc, status_code, extra_headers);
  5672. mg_printf(nc,
  5673. "Date: %s\r\n"
  5674. "Last-Modified: %s\r\n"
  5675. "Accept-Ranges: bytes\r\n"
  5676. "Content-Type: %.*s\r\n"
  5677. "Connection: %s\r\n"
  5678. "Content-Length: %" SIZE_T_FMT
  5679. "\r\n"
  5680. "%sEtag: %s\r\n\r\n",
  5681. current_time, last_modified, (int) mime_type.len, mime_type.p,
  5682. (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
  5683. etag);
  5684. pd->file.cl = cl;
  5685. pd->file.type = DATA_FILE;
  5686. mg_http_transfer_file_data(nc);
  5687. }
  5688. }
  5689. static void mg_http_serve_file2(struct mg_connection *nc, const char *path,
  5690. struct http_message *hm,
  5691. struct mg_serve_http_opts *opts) {
  5692. #if MG_ENABLE_HTTP_SSI
  5693. if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) {
  5694. mg_handle_ssi_request(nc, hm, path, opts);
  5695. return;
  5696. }
  5697. #endif
  5698. mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts),
  5699. mg_mk_str(opts->extra_headers));
  5700. }
  5701. #endif
  5702. int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
  5703. int is_form_url_encoded) {
  5704. int i, j, a, b;
  5705. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  5706. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  5707. if (src[i] == '%') {
  5708. if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
  5709. isxdigit(*(const unsigned char *) (src + i + 2))) {
  5710. a = tolower(*(const unsigned char *) (src + i + 1));
  5711. b = tolower(*(const unsigned char *) (src + i + 2));
  5712. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  5713. i += 2;
  5714. } else {
  5715. return -1;
  5716. }
  5717. } else if (is_form_url_encoded && src[i] == '+') {
  5718. dst[j] = ' ';
  5719. } else {
  5720. dst[j] = src[i];
  5721. }
  5722. }
  5723. dst[j] = '\0'; /* Null-terminate the destination */
  5724. return i >= src_len ? j : -1;
  5725. }
  5726. int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
  5727. size_t dst_len) {
  5728. const char *p, *e, *s;
  5729. size_t name_len;
  5730. int len;
  5731. if (dst == NULL || dst_len == 0) {
  5732. len = -2;
  5733. } else if (buf->p == NULL || name == NULL || buf->len == 0) {
  5734. len = -1;
  5735. dst[0] = '\0';
  5736. } else {
  5737. name_len = strlen(name);
  5738. e = buf->p + buf->len;
  5739. len = -1;
  5740. dst[0] = '\0';
  5741. for (p = buf->p; p + name_len < e; p++) {
  5742. if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
  5743. !mg_ncasecmp(name, p, name_len)) {
  5744. p += name_len + 1;
  5745. s = (const char *) memchr(p, '&', (size_t)(e - p));
  5746. if (s == NULL) {
  5747. s = e;
  5748. }
  5749. len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
  5750. if (len == -1) {
  5751. len = -2;
  5752. }
  5753. break;
  5754. }
  5755. }
  5756. }
  5757. return len;
  5758. }
  5759. void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
  5760. char chunk_size[50];
  5761. int n;
  5762. n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
  5763. mg_send(nc, chunk_size, n);
  5764. mg_send(nc, buf, len);
  5765. mg_send(nc, "\r\n", 2);
  5766. }
  5767. void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
  5768. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  5769. int len;
  5770. va_list ap;
  5771. va_start(ap, fmt);
  5772. len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
  5773. va_end(ap);
  5774. if (len >= 0) {
  5775. mg_send_http_chunk(nc, buf, len);
  5776. }
  5777. /* LCOV_EXCL_START */
  5778. if (buf != mem && buf != NULL) {
  5779. MG_FREE(buf);
  5780. }
  5781. /* LCOV_EXCL_STOP */
  5782. }
  5783. void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
  5784. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  5785. int i, j, len;
  5786. va_list ap;
  5787. va_start(ap, fmt);
  5788. len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
  5789. va_end(ap);
  5790. if (len >= 0) {
  5791. for (i = j = 0; i < len; i++) {
  5792. if (buf[i] == '<' || buf[i] == '>') {
  5793. mg_send(nc, buf + j, i - j);
  5794. mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4);
  5795. j = i + 1;
  5796. }
  5797. }
  5798. mg_send(nc, buf + j, i - j);
  5799. }
  5800. /* LCOV_EXCL_START */
  5801. if (buf != mem && buf != NULL) {
  5802. MG_FREE(buf);
  5803. }
  5804. /* LCOV_EXCL_STOP */
  5805. }
  5806. int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
  5807. size_t buf_size) {
  5808. int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name);
  5809. const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
  5810. if (buf != NULL && buf_size > 0) buf[0] = '\0';
  5811. if (hdr == NULL) return 0;
  5812. /* Find where variable starts */
  5813. for (s = hdr->p; s != NULL && s + n < end; s++) {
  5814. if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') &&
  5815. s[n] == '=' && !strncmp(s, var_name, n))
  5816. break;
  5817. }
  5818. if (s != NULL && &s[n + 1] < end) {
  5819. s += n + 1;
  5820. if (*s == '"' || *s == '\'') {
  5821. ch = ch1 = *s++;
  5822. }
  5823. p = s;
  5824. while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
  5825. if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
  5826. buf[len++] = *p++;
  5827. }
  5828. if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
  5829. len = 0;
  5830. } else {
  5831. if (len > 0 && s[len - 1] == ',') len--;
  5832. if (len > 0 && s[len - 1] == ';') len--;
  5833. buf[len] = '\0';
  5834. }
  5835. }
  5836. return len;
  5837. }
  5838. int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
  5839. char *pass, size_t pass_len) {
  5840. struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
  5841. if (hdr == NULL) return -1;
  5842. return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len);
  5843. }
  5844. int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
  5845. char *pass, size_t pass_len) {
  5846. char *buf = NULL;
  5847. char fmt[64];
  5848. int res = 0;
  5849. if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1;
  5850. buf = (char *) MG_MALLOC(hdr->len);
  5851. cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
  5852. /* e.g. "%123[^:]:%321[^\n]" */
  5853. snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]",
  5854. user_len - 1, pass_len - 1);
  5855. if (sscanf(buf, fmt, user, pass) == 0) {
  5856. res = -1;
  5857. }
  5858. MG_FREE(buf);
  5859. return res;
  5860. }
  5861. #if MG_ENABLE_FILESYSTEM
  5862. static int mg_is_file_hidden(const char *path,
  5863. const struct mg_serve_http_opts *opts,
  5864. int exclude_specials) {
  5865. const char *p1 = opts->per_directory_auth_file;
  5866. const char *p2 = opts->hidden_file_pattern;
  5867. /* Strip directory path from the file name */
  5868. const char *pdir = strrchr(path, DIRSEP);
  5869. if (pdir != NULL) {
  5870. path = pdir + 1;
  5871. }
  5872. return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
  5873. (p1 != NULL &&
  5874. mg_match_prefix(p1, strlen(p1), path) == (int) strlen(p1)) ||
  5875. (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
  5876. }
  5877. #if !MG_DISABLE_HTTP_DIGEST_AUTH
  5878. static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
  5879. size_t uri_len, const char *ha1, size_t ha1_len,
  5880. const char *nonce, size_t nonce_len, const char *nc,
  5881. size_t nc_len, const char *cnonce, size_t cnonce_len,
  5882. const char *qop, size_t qop_len, char *resp) {
  5883. static const char colon[] = ":";
  5884. static const size_t one = 1;
  5885. char ha2[33];
  5886. cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
  5887. cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
  5888. nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
  5889. colon, one, ha2, sizeof(ha2) - 1, NULL);
  5890. }
  5891. int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
  5892. const char *method, const char *uri,
  5893. const char *auth_domain, const char *user,
  5894. const char *passwd) {
  5895. static const char colon[] = ":", qop[] = "auth";
  5896. static const size_t one = 1;
  5897. char ha1[33], resp[33], cnonce[40];
  5898. snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) mg_time());
  5899. cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
  5900. (size_t) strlen(auth_domain), colon, one, passwd,
  5901. (size_t) strlen(passwd), NULL);
  5902. mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
  5903. cnonce, strlen(cnonce), "1", one, cnonce, strlen(cnonce), qop,
  5904. sizeof(qop) - 1, resp);
  5905. return snprintf(buf, buf_len,
  5906. "Authorization: Digest username=\"%s\","
  5907. "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
  5908. "nonce=%s,response=%s\r\n",
  5909. user, auth_domain, uri, qop, cnonce, cnonce, resp);
  5910. }
  5911. /*
  5912. * Check for authentication timeout.
  5913. * Clients send time stamp encoded in nonce. Make sure it is not too old,
  5914. * to prevent replay attacks.
  5915. * Assumption: nonce is a hexadecimal number of seconds since 1970.
  5916. */
  5917. static int mg_check_nonce(const char *nonce) {
  5918. unsigned long now = (unsigned long) mg_time();
  5919. unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
  5920. return now < val || now - val < 3600;
  5921. }
  5922. int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
  5923. FILE *fp) {
  5924. struct mg_str *hdr;
  5925. char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
  5926. char user[50], cnonce[33], response[40], uri[200], qop[20], nc[20], nonce[30];
  5927. char expected_response[33];
  5928. /* Parse "Authorization:" header, fail fast on parse error */
  5929. if (hm == NULL || fp == NULL ||
  5930. (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
  5931. mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 ||
  5932. mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 ||
  5933. mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 ||
  5934. mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 ||
  5935. mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 ||
  5936. mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 ||
  5937. mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 ||
  5938. mg_check_nonce(nonce) == 0) {
  5939. return 0;
  5940. }
  5941. /*
  5942. * Read passwords file line by line. If should have htdigest format,
  5943. * i.e. each line should be a colon-separated sequence:
  5944. * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
  5945. */
  5946. while (fgets(buf, sizeof(buf), fp) != NULL) {
  5947. if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
  5948. strcmp(user, f_user) == 0 &&
  5949. /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
  5950. strcmp(auth_domain, f_domain) == 0) {
  5951. /* User and domain matched, check the password */
  5952. mg_mkmd5resp(
  5953. hm->method.p, hm->method.len, hm->uri.p,
  5954. hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0),
  5955. f_ha1, strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce,
  5956. strlen(cnonce), qop, strlen(qop), expected_response);
  5957. return mg_casecmp(response, expected_response) == 0;
  5958. }
  5959. }
  5960. /* None of the entries in the passwords file matched - return failure */
  5961. return 0;
  5962. }
  5963. static int mg_is_authorized(struct http_message *hm, const char *path,
  5964. int is_directory, const char *domain,
  5965. const char *passwords_file,
  5966. int is_global_pass_file) {
  5967. char buf[MG_MAX_PATH];
  5968. const char *p;
  5969. FILE *fp;
  5970. int authorized = 1;
  5971. if (domain != NULL && passwords_file != NULL) {
  5972. if (is_global_pass_file) {
  5973. fp = mg_fopen(passwords_file, "r");
  5974. } else if (is_directory) {
  5975. snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP, passwords_file);
  5976. fp = mg_fopen(buf, "r");
  5977. } else {
  5978. p = strrchr(path, DIRSEP);
  5979. if (p == NULL) p = path;
  5980. snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path), path, DIRSEP,
  5981. passwords_file);
  5982. fp = mg_fopen(buf, "r");
  5983. }
  5984. if (fp != NULL) {
  5985. authorized = mg_http_check_digest_auth(hm, domain, fp);
  5986. fclose(fp);
  5987. }
  5988. }
  5989. LOG(LL_DEBUG, ("%s '%s' %d %d", path, passwords_file ? passwords_file : "",
  5990. is_global_pass_file, authorized));
  5991. return authorized;
  5992. }
  5993. #else
  5994. static int mg_is_authorized(struct http_message *hm, const char *path,
  5995. int is_directory, const char *domain,
  5996. const char *passwords_file,
  5997. int is_global_pass_file) {
  5998. (void) hm;
  5999. (void) path;
  6000. (void) is_directory;
  6001. (void) domain;
  6002. (void) passwords_file;
  6003. (void) is_global_pass_file;
  6004. return 1;
  6005. }
  6006. #endif
  6007. #if MG_ENABLE_DIRECTORY_LISTING
  6008. static size_t mg_url_encode(const char *src, size_t s_len, char *dst,
  6009. size_t dst_len) {
  6010. static const char *dont_escape = "._-$,;~()/";
  6011. static const char *hex = "0123456789abcdef";
  6012. size_t i = 0, j = 0;
  6013. for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
  6014. if (isalnum(*(const unsigned char *) (src + i)) ||
  6015. strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) {
  6016. dst[j] = src[i];
  6017. } else if (j + 3 < dst_len) {
  6018. dst[j] = '%';
  6019. dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4];
  6020. dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf];
  6021. j += 2;
  6022. }
  6023. }
  6024. dst[j] = '\0';
  6025. return j;
  6026. }
  6027. static void mg_escape(const char *src, char *dst, size_t dst_len) {
  6028. size_t n = 0;
  6029. while (*src != '\0' && n + 5 < dst_len) {
  6030. unsigned char ch = *(unsigned char *) src++;
  6031. if (ch == '<') {
  6032. n += snprintf(dst + n, dst_len - n, "%s", "&lt;");
  6033. } else {
  6034. dst[n++] = ch;
  6035. }
  6036. }
  6037. dst[n] = '\0';
  6038. }
  6039. static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
  6040. cs_stat_t *stp) {
  6041. char size[64], mod[64], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE];
  6042. int64_t fsize = stp->st_size;
  6043. int is_dir = S_ISDIR(stp->st_mode);
  6044. const char *slash = is_dir ? "/" : "";
  6045. if (is_dir) {
  6046. snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
  6047. } else {
  6048. /*
  6049. * We use (double) cast below because MSVC 6 compiler cannot
  6050. * convert unsigned __int64 to double.
  6051. */
  6052. if (fsize < 1024) {
  6053. snprintf(size, sizeof(size), "%d", (int) fsize);
  6054. } else if (fsize < 0x100000) {
  6055. snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
  6056. } else if (fsize < 0x40000000) {
  6057. snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
  6058. } else {
  6059. snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
  6060. }
  6061. }
  6062. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
  6063. mg_escape(file_name, path, sizeof(path));
  6064. mg_url_encode(file_name, strlen(file_name), href, sizeof(href));
  6065. mg_printf_http_chunk(nc,
  6066. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  6067. "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
  6068. href, slash, path, slash, mod, is_dir ? -1 : fsize,
  6069. size);
  6070. }
  6071. static void mg_scan_directory(struct mg_connection *nc, const char *dir,
  6072. const struct mg_serve_http_opts *opts,
  6073. void (*func)(struct mg_connection *, const char *,
  6074. cs_stat_t *)) {
  6075. char path[MAX_PATH_SIZE];
  6076. cs_stat_t st;
  6077. struct dirent *dp;
  6078. DIR *dirp;
  6079. LOG(LL_DEBUG, ("%p [%s]", nc, dir));
  6080. if ((dirp = (opendir(dir))) != NULL) {
  6081. while ((dp = readdir(dirp)) != NULL) {
  6082. /* Do not show current dir and hidden files */
  6083. if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
  6084. continue;
  6085. }
  6086. snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
  6087. if (mg_stat(path, &st) == 0) {
  6088. func(nc, (const char *) dp->d_name, &st);
  6089. }
  6090. }
  6091. closedir(dirp);
  6092. } else {
  6093. LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno()));
  6094. }
  6095. }
  6096. static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
  6097. struct http_message *hm,
  6098. struct mg_serve_http_opts *opts) {
  6099. static const char *sort_js_code =
  6100. "<script>function srt(tb, sc, so, d) {"
  6101. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  6102. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  6103. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  6104. "t1 = a.cells[2].getAttribute('name'), "
  6105. "t2 = b.cells[2].getAttribute('name'); "
  6106. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  6107. "n1 ? parseInt(n2) - parseInt(n1) : "
  6108. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  6109. static const char *sort_js_code2 =
  6110. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  6111. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  6112. "};"
  6113. "window.onload = function() {"
  6114. "var tb = document.getElementById('tb');"
  6115. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  6116. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  6117. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  6118. "sc = c; ev.preventDefault();}};"
  6119. "srt(tb, sc, so, true);"
  6120. "}"
  6121. "</script>";
  6122. mg_send_response_line(nc, 200, opts->extra_headers);
  6123. mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
  6124. "Content-Type", "text/html; charset=utf-8");
  6125. mg_printf_http_chunk(
  6126. nc,
  6127. "<html><head><title>Index of %.*s</title>%s%s"
  6128. "<style>th,td {text-align: left; padding-right: 1em; "
  6129. "font-family: monospace; }</style></head>\n"
  6130. "<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>"
  6131. "<tr><th><a href=# rel=0>Name</a></th><th>"
  6132. "<a href=# rel=1>Modified</a</th>"
  6133. "<th><a href=# rel=2>Size</a></th></tr>"
  6134. "<tr><td colspan=3><hr></td></tr>\n"
  6135. "</thead>\n"
  6136. "<tbody id=tb>",
  6137. (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
  6138. (int) hm->uri.len, hm->uri.p);
  6139. mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
  6140. mg_printf_http_chunk(nc,
  6141. "</tbody><tr><td colspan=3><hr></td></tr>\n"
  6142. "</table>\n"
  6143. "<address>%s</address>\n"
  6144. "</body></html>",
  6145. mg_version_header);
  6146. mg_send_http_chunk(nc, "", 0);
  6147. /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
  6148. nc->flags |= MG_F_SEND_AND_CLOSE;
  6149. }
  6150. #endif /* MG_ENABLE_DIRECTORY_LISTING */
  6151. /*
  6152. * Given a directory path, find one of the files specified in the
  6153. * comma-separated list of index files `list`.
  6154. * First found index file wins. If an index file is found, then gets
  6155. * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
  6156. * If index file is not found, then `path` and `stp` remain unchanged.
  6157. */
  6158. MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
  6159. char **index_file, cs_stat_t *stp) {
  6160. struct mg_str vec;
  6161. size_t path_len = strlen(path);
  6162. int found = 0;
  6163. *index_file = NULL;
  6164. /* Traverse index files list. For each entry, append it to the given */
  6165. /* path and see if the file exists. If it exists, break the loop */
  6166. while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
  6167. cs_stat_t st;
  6168. size_t len = path_len + 1 + vec.len + 1;
  6169. *index_file = (char *) MG_REALLOC(*index_file, len);
  6170. if (*index_file == NULL) break;
  6171. snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
  6172. /* Does it exist? Is it a file? */
  6173. if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
  6174. /* Yes it does, break the loop */
  6175. *stp = st;
  6176. found = 1;
  6177. break;
  6178. }
  6179. }
  6180. if (!found) {
  6181. MG_FREE(*index_file);
  6182. *index_file = NULL;
  6183. }
  6184. LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : "")));
  6185. }
  6186. #if MG_ENABLE_HTTP_URL_REWRITES
  6187. static int mg_http_send_port_based_redirect(
  6188. struct mg_connection *c, struct http_message *hm,
  6189. const struct mg_serve_http_opts *opts) {
  6190. const char *rewrites = opts->url_rewrites;
  6191. struct mg_str a, b;
  6192. char local_port[20] = {'%'};
  6193. mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
  6194. MG_SOCK_STRINGIFY_PORT);
  6195. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  6196. if (mg_vcmp(&a, local_port) == 0) {
  6197. mg_send_response_line(c, 301, NULL);
  6198. mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
  6199. (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
  6200. hm->uri.p);
  6201. return 1;
  6202. }
  6203. }
  6204. return 0;
  6205. }
  6206. static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev,
  6207. void *ev_data) {
  6208. struct http_message *hm = (struct http_message *) ev_data;
  6209. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  6210. if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
  6211. DBG(("%p: upstream closed", nc));
  6212. return;
  6213. }
  6214. switch (ev) {
  6215. case MG_EV_CONNECT:
  6216. if (*(int *) ev_data != 0) {
  6217. mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL);
  6218. }
  6219. break;
  6220. /* TODO(mkm): handle streaming */
  6221. case MG_EV_HTTP_REPLY:
  6222. mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p,
  6223. hm->message.len);
  6224. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  6225. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  6226. break;
  6227. case MG_EV_CLOSE:
  6228. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  6229. break;
  6230. }
  6231. }
  6232. void mg_http_reverse_proxy(struct mg_connection *nc,
  6233. const struct http_message *hm, struct mg_str mount,
  6234. struct mg_str upstream) {
  6235. struct mg_connection *be;
  6236. char burl[256], *purl = burl;
  6237. char *addr = NULL;
  6238. const char *path = NULL;
  6239. int i;
  6240. const char *error;
  6241. struct mg_connect_opts opts;
  6242. memset(&opts, 0, sizeof(opts));
  6243. opts.error_string = &error;
  6244. mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p,
  6245. (int) (hm->uri.len - mount.len), hm->uri.p + mount.len);
  6246. be = mg_connect_http_base(nc->mgr, mg_reverse_proxy_handler, opts, "http://",
  6247. "https://", purl, &path, NULL /* user */,
  6248. NULL /* pass */, &addr);
  6249. LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len,
  6250. hm->uri.p, purl, (int) mount.len, mount.p));
  6251. if (be == NULL) {
  6252. LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error));
  6253. mg_http_send_error(nc, 502, NULL);
  6254. goto cleanup;
  6255. }
  6256. /* link connections to each other, they must live and die together */
  6257. mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc;
  6258. mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be;
  6259. /* send request upstream */
  6260. mg_printf(be, "%.*s %s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p,
  6261. path);
  6262. mg_printf(be, "Host: %s\r\n", addr);
  6263. for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) {
  6264. struct mg_str hn = hm->header_names[i];
  6265. struct mg_str hv = hm->header_values[i];
  6266. /* we rewrite the host header */
  6267. if (mg_vcasecmp(&hn, "Host") == 0) continue;
  6268. /*
  6269. * Don't pass chunked transfer encoding to the client because hm->body is
  6270. * already dechunked when we arrive here.
  6271. */
  6272. if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 &&
  6273. mg_vcasecmp(&hv, "chunked") == 0) {
  6274. mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len);
  6275. continue;
  6276. }
  6277. /* We don't support proxying Expect: 100-continue. */
  6278. if (mg_vcasecmp(&hn, "Expect") == 0 &&
  6279. mg_vcasecmp(&hv, "100-continue") == 0) {
  6280. continue;
  6281. }
  6282. mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
  6283. }
  6284. mg_send(be, "\r\n", 2);
  6285. mg_send(be, hm->body.p, hm->body.len);
  6286. cleanup:
  6287. if (purl != burl) MG_FREE(purl);
  6288. }
  6289. static int mg_http_handle_forwarding(struct mg_connection *nc,
  6290. struct http_message *hm,
  6291. const struct mg_serve_http_opts *opts) {
  6292. const char *rewrites = opts->url_rewrites;
  6293. struct mg_str a, b;
  6294. struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://");
  6295. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  6296. if (mg_strncmp(a, hm->uri, a.len) == 0) {
  6297. if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) {
  6298. mg_http_reverse_proxy(nc, hm, a, b);
  6299. return 1;
  6300. }
  6301. }
  6302. }
  6303. return 0;
  6304. }
  6305. #endif
  6306. MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
  6307. const struct mg_serve_http_opts *opts,
  6308. char **local_path,
  6309. struct mg_str *remainder) {
  6310. int ok = 1;
  6311. const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
  6312. struct mg_str root = {NULL, 0};
  6313. const char *file_uri_start = cp;
  6314. *local_path = NULL;
  6315. remainder->p = NULL;
  6316. remainder->len = 0;
  6317. { /* 1. Determine which root to use. */
  6318. #if MG_ENABLE_HTTP_URL_REWRITES
  6319. const char *rewrites = opts->url_rewrites;
  6320. #else
  6321. const char *rewrites = "";
  6322. #endif
  6323. struct mg_str *hh = mg_get_http_header(hm, "Host");
  6324. struct mg_str a, b;
  6325. /* Check rewrites first. */
  6326. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  6327. if (a.len > 1 && a.p[0] == '@') {
  6328. /* Host rewrite. */
  6329. if (hh != NULL && hh->len == a.len - 1 &&
  6330. mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
  6331. root = b;
  6332. break;
  6333. }
  6334. } else {
  6335. /* Regular rewrite, URI=directory */
  6336. int match_len = mg_match_prefix_n(a, hm->uri);
  6337. if (match_len > 0) {
  6338. file_uri_start = hm->uri.p + match_len;
  6339. if (*file_uri_start == '/' || file_uri_start == cp_end) {
  6340. /* Match ended at component boundary, ok. */
  6341. } else if (*(file_uri_start - 1) == '/') {
  6342. /* Pattern ends with '/', backtrack. */
  6343. file_uri_start--;
  6344. } else {
  6345. /* No match: must fall on the component boundary. */
  6346. continue;
  6347. }
  6348. root = b;
  6349. break;
  6350. }
  6351. }
  6352. }
  6353. /* If no rewrite rules matched, use DAV or regular document root. */
  6354. if (root.p == NULL) {
  6355. #if MG_ENABLE_HTTP_WEBDAV
  6356. if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
  6357. root.p = opts->dav_document_root;
  6358. root.len = strlen(opts->dav_document_root);
  6359. } else
  6360. #endif
  6361. {
  6362. root.p = opts->document_root;
  6363. root.len = strlen(opts->document_root);
  6364. }
  6365. }
  6366. assert(root.p != NULL && root.len > 0);
  6367. }
  6368. { /* 2. Find where in the canonical URI path the local path ends. */
  6369. const char *u = file_uri_start + 1;
  6370. char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
  6371. char *lp_end = lp + root.len + hm->uri.len + 1;
  6372. char *p = lp, *ps;
  6373. int exists = 1;
  6374. if (lp == NULL) {
  6375. ok = 0;
  6376. goto out;
  6377. }
  6378. memcpy(p, root.p, root.len);
  6379. p += root.len;
  6380. if (*(p - 1) == DIRSEP) p--;
  6381. *p = '\0';
  6382. ps = p;
  6383. /* Chop off URI path components one by one and build local path. */
  6384. while (u <= cp_end) {
  6385. const char *next = u;
  6386. struct mg_str component;
  6387. if (exists) {
  6388. cs_stat_t st;
  6389. exists = (mg_stat(lp, &st) == 0);
  6390. if (exists && S_ISREG(st.st_mode)) {
  6391. /* We found the terminal, the rest of the URI (if any) is path_info.
  6392. */
  6393. if (*(u - 1) == '/') u--;
  6394. break;
  6395. }
  6396. }
  6397. if (u >= cp_end) break;
  6398. parse_uri_component((const char **) &next, cp_end, '/', &component);
  6399. if (component.len > 0) {
  6400. int len;
  6401. memmove(p + 1, component.p, component.len);
  6402. len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
  6403. if (len <= 0) {
  6404. ok = 0;
  6405. break;
  6406. }
  6407. component.p = p + 1;
  6408. component.len = len;
  6409. if (mg_vcmp(&component, ".") == 0) {
  6410. /* Yum. */
  6411. } else if (mg_vcmp(&component, "..") == 0) {
  6412. while (p > ps && *p != DIRSEP) p--;
  6413. *p = '\0';
  6414. } else {
  6415. size_t i;
  6416. #ifdef _WIN32
  6417. /* On Windows, make sure it's valid Unicode (no funny stuff). */
  6418. wchar_t buf[MG_MAX_PATH * 2];
  6419. if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
  6420. DBG(("[%.*s] smells funny", (int) component.len, component.p));
  6421. ok = 0;
  6422. break;
  6423. }
  6424. #endif
  6425. *p++ = DIRSEP;
  6426. /* No NULs and DIRSEPs in the component (percent-encoded). */
  6427. for (i = 0; i < component.len; i++, p++) {
  6428. if (*p == '\0' || *p == DIRSEP
  6429. #ifdef _WIN32
  6430. /* On Windows, "/" is also accepted, so check for that too. */
  6431. ||
  6432. *p == '/'
  6433. #endif
  6434. ) {
  6435. ok = 0;
  6436. break;
  6437. }
  6438. }
  6439. }
  6440. }
  6441. u = next;
  6442. }
  6443. if (ok) {
  6444. *local_path = lp;
  6445. if (u > cp_end) u = cp_end;
  6446. remainder->p = u;
  6447. remainder->len = cp_end - u;
  6448. } else {
  6449. MG_FREE(lp);
  6450. }
  6451. }
  6452. out:
  6453. LOG(LL_DEBUG,
  6454. ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
  6455. *local_path ? *local_path : "", (int) remainder->len, remainder->p));
  6456. return ok;
  6457. }
  6458. static int mg_get_month_index(const char *s) {
  6459. static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  6460. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  6461. size_t i;
  6462. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  6463. if (!strcmp(s, month_names[i])) return (int) i;
  6464. return -1;
  6465. }
  6466. static int mg_num_leap_years(int year) {
  6467. return year / 4 - year / 100 + year / 400;
  6468. }
  6469. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6470. MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
  6471. static const unsigned short days_before_month[] = {
  6472. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  6473. char month_str[32];
  6474. int second, minute, hour, day, month, year, leap_days, days;
  6475. time_t result = (time_t) 0;
  6476. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
  6477. &minute, &second) == 6) ||
  6478. (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
  6479. &minute, &second) == 6) ||
  6480. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
  6481. &hour, &minute, &second) == 6) ||
  6482. (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
  6483. &minute, &second) == 6)) &&
  6484. year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
  6485. leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
  6486. year -= 1970;
  6487. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  6488. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  6489. }
  6490. return result;
  6491. }
  6492. MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
  6493. struct mg_str *hdr;
  6494. if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
  6495. char etag[64];
  6496. mg_http_construct_etag(etag, sizeof(etag), st);
  6497. return mg_vcasecmp(hdr, etag) == 0;
  6498. } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
  6499. return st->st_mtime <= mg_parse_date_string(hdr->p);
  6500. } else {
  6501. return 0;
  6502. }
  6503. }
  6504. static void mg_http_send_digest_auth_request(struct mg_connection *c,
  6505. const char *domain) {
  6506. mg_printf(c,
  6507. "HTTP/1.1 401 Unauthorized\r\n"
  6508. "WWW-Authenticate: Digest qop=\"auth\", "
  6509. "realm=\"%s\", nonce=\"%lu\"\r\n"
  6510. "Content-Length: 0\r\n\r\n",
  6511. domain, (unsigned long) mg_time());
  6512. }
  6513. static void mg_http_send_options(struct mg_connection *nc) {
  6514. mg_printf(nc, "%s",
  6515. "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, OPTIONS"
  6516. #if MG_ENABLE_HTTP_WEBDAV
  6517. ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
  6518. #endif
  6519. "\r\n\r\n");
  6520. nc->flags |= MG_F_SEND_AND_CLOSE;
  6521. }
  6522. static int mg_is_creation_request(const struct http_message *hm) {
  6523. return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
  6524. }
  6525. MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
  6526. const struct mg_str *path_info,
  6527. struct http_message *hm,
  6528. struct mg_serve_http_opts *opts) {
  6529. int exists, is_directory, is_cgi;
  6530. #if MG_ENABLE_HTTP_WEBDAV
  6531. int is_dav = mg_is_dav_request(&hm->method);
  6532. #else
  6533. int is_dav = 0;
  6534. #endif
  6535. char *index_file = NULL;
  6536. cs_stat_t st;
  6537. exists = (mg_stat(path, &st) == 0);
  6538. is_directory = exists && S_ISDIR(st.st_mode);
  6539. if (is_directory)
  6540. mg_find_index_file(path, opts->index_files, &index_file, &st);
  6541. is_cgi =
  6542. (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
  6543. index_file ? index_file : path) > 0);
  6544. LOG(LL_DEBUG,
  6545. ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
  6546. (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
  6547. is_cgi, index_file ? index_file : ""));
  6548. if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
  6549. mg_printf(nc,
  6550. "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
  6551. "Content-Length: 0\r\n\r\n",
  6552. (int) hm->uri.len, hm->uri.p);
  6553. MG_FREE(index_file);
  6554. return;
  6555. }
  6556. /* If we have path_info, the only way to handle it is CGI. */
  6557. if (path_info->len > 0 && !is_cgi) {
  6558. mg_http_send_error(nc, 501, NULL);
  6559. MG_FREE(index_file);
  6560. return;
  6561. }
  6562. if (is_dav && opts->dav_document_root == NULL) {
  6563. mg_http_send_error(nc, 501, NULL);
  6564. } else if (!mg_is_authorized(hm, path, is_directory, opts->auth_domain,
  6565. opts->global_auth_file, 1) ||
  6566. !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
  6567. opts->per_directory_auth_file, 0)) {
  6568. mg_http_send_digest_auth_request(nc, opts->auth_domain);
  6569. } else if (is_cgi) {
  6570. #if MG_ENABLE_HTTP_CGI
  6571. mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
  6572. #else
  6573. mg_http_send_error(nc, 501, NULL);
  6574. #endif /* MG_ENABLE_HTTP_CGI */
  6575. } else if ((!exists ||
  6576. mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
  6577. !mg_is_creation_request(hm)) {
  6578. mg_http_send_error(nc, 404, NULL);
  6579. #if MG_ENABLE_HTTP_WEBDAV
  6580. } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
  6581. mg_handle_propfind(nc, path, &st, hm, opts);
  6582. #if !MG_DISABLE_DAV_AUTH
  6583. } else if (is_dav &&
  6584. (opts->dav_auth_file == NULL ||
  6585. (strcmp(opts->dav_auth_file, "-") != 0 &&
  6586. !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
  6587. opts->dav_auth_file, 1)))) {
  6588. mg_http_send_digest_auth_request(nc, opts->auth_domain);
  6589. #endif
  6590. } else if (!mg_vcmp(&hm->method, "MKCOL")) {
  6591. mg_handle_mkcol(nc, path, hm);
  6592. } else if (!mg_vcmp(&hm->method, "DELETE")) {
  6593. mg_handle_delete(nc, opts, path);
  6594. } else if (!mg_vcmp(&hm->method, "PUT")) {
  6595. mg_handle_put(nc, path, hm);
  6596. } else if (!mg_vcmp(&hm->method, "MOVE")) {
  6597. mg_handle_move(nc, opts, path, hm);
  6598. #if MG_ENABLE_FAKE_DAVLOCK
  6599. } else if (!mg_vcmp(&hm->method, "LOCK")) {
  6600. mg_handle_lock(nc, path);
  6601. #endif
  6602. #endif /* MG_ENABLE_HTTP_WEBDAV */
  6603. } else if (!mg_vcmp(&hm->method, "OPTIONS")) {
  6604. mg_http_send_options(nc);
  6605. } else if (is_directory && index_file == NULL) {
  6606. #if MG_ENABLE_DIRECTORY_LISTING
  6607. if (strcmp(opts->enable_directory_listing, "yes") == 0) {
  6608. mg_send_directory_listing(nc, path, hm, opts);
  6609. } else {
  6610. mg_http_send_error(nc, 403, NULL);
  6611. }
  6612. #else
  6613. mg_http_send_error(nc, 501, NULL);
  6614. #endif
  6615. } else if (mg_is_not_modified(hm, &st)) {
  6616. mg_http_send_error(nc, 304, "Not Modified");
  6617. } else {
  6618. mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
  6619. }
  6620. MG_FREE(index_file);
  6621. }
  6622. void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
  6623. struct mg_serve_http_opts opts) {
  6624. char *path = NULL;
  6625. struct mg_str *hdr, path_info;
  6626. uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
  6627. if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
  6628. /* Not allowed to connect */
  6629. mg_http_send_error(nc, 403, NULL);
  6630. nc->flags |= MG_F_SEND_AND_CLOSE;
  6631. return;
  6632. }
  6633. #if MG_ENABLE_HTTP_URL_REWRITES
  6634. if (mg_http_handle_forwarding(nc, hm, &opts)) {
  6635. return;
  6636. }
  6637. if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
  6638. return;
  6639. }
  6640. #endif
  6641. if (opts.document_root == NULL) {
  6642. opts.document_root = ".";
  6643. }
  6644. if (opts.per_directory_auth_file == NULL) {
  6645. opts.per_directory_auth_file = ".htpasswd";
  6646. }
  6647. if (opts.enable_directory_listing == NULL) {
  6648. opts.enable_directory_listing = "yes";
  6649. }
  6650. if (opts.cgi_file_pattern == NULL) {
  6651. opts.cgi_file_pattern = "**.cgi$|**.php$";
  6652. }
  6653. if (opts.ssi_pattern == NULL) {
  6654. opts.ssi_pattern = "**.shtml$|**.shtm$";
  6655. }
  6656. if (opts.index_files == NULL) {
  6657. opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
  6658. }
  6659. /* Normalize path - resolve "." and ".." (in-place). */
  6660. if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
  6661. mg_http_send_error(nc, 400, NULL);
  6662. return;
  6663. }
  6664. if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
  6665. mg_http_send_error(nc, 404, NULL);
  6666. return;
  6667. }
  6668. mg_send_http_file(nc, path, &path_info, hm, &opts);
  6669. MG_FREE(path);
  6670. path = NULL;
  6671. /* Close connection for non-keep-alive requests */
  6672. if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
  6673. ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
  6674. mg_vcmp(hdr, "keep-alive") != 0)) {
  6675. #if 0
  6676. nc->flags |= MG_F_SEND_AND_CLOSE;
  6677. #endif
  6678. }
  6679. }
  6680. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  6681. void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
  6682. mg_fu_fname_fn local_name_fn) {
  6683. switch (ev) {
  6684. case MG_EV_HTTP_PART_BEGIN: {
  6685. struct mg_http_multipart_part *mp =
  6686. (struct mg_http_multipart_part *) ev_data;
  6687. struct file_upload_state *fus =
  6688. (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus));
  6689. struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
  6690. mp->user_data = NULL;
  6691. if (lfn.p == NULL || lfn.len == 0) {
  6692. LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
  6693. mg_printf(nc,
  6694. "HTTP/1.1 403 Not Allowed\r\n"
  6695. "Content-Type: text/plain\r\n"
  6696. "Connection: close\r\n\r\n"
  6697. "Not allowed to upload %s\r\n",
  6698. mp->file_name);
  6699. nc->flags |= MG_F_SEND_AND_CLOSE;
  6700. return;
  6701. }
  6702. fus->lfn = (char *) MG_MALLOC(lfn.len + 1);
  6703. memcpy(fus->lfn, lfn.p, lfn.len);
  6704. fus->lfn[lfn.len] = '\0';
  6705. if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p);
  6706. LOG(LL_DEBUG,
  6707. ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
  6708. fus->fp = mg_fopen(fus->lfn, "w");
  6709. if (fus->fp == NULL) {
  6710. mg_printf(nc,
  6711. "HTTP/1.1 500 Internal Server Error\r\n"
  6712. "Content-Type: text/plain\r\n"
  6713. "Connection: close\r\n\r\n");
  6714. LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno()));
  6715. mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno());
  6716. /* Do not close the connection just yet, discard remainder of the data.
  6717. * This is because at the time of writing some browsers (Chrome) fail to
  6718. * render response before all the data is sent. */
  6719. }
  6720. mp->user_data = (void *) fus;
  6721. break;
  6722. }
  6723. case MG_EV_HTTP_PART_DATA: {
  6724. struct mg_http_multipart_part *mp =
  6725. (struct mg_http_multipart_part *) ev_data;
  6726. struct file_upload_state *fus =
  6727. (struct file_upload_state *) mp->user_data;
  6728. if (fus == NULL || fus->fp == NULL) break;
  6729. if (fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
  6730. LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn,
  6731. mg_get_errno(), (int) fus->num_recd));
  6732. if (mg_get_errno() == ENOSPC
  6733. #ifdef SPIFFS_ERR_FULL
  6734. || mg_get_errno() == SPIFFS_ERR_FULL
  6735. #endif
  6736. ) {
  6737. mg_printf(nc,
  6738. "HTTP/1.1 413 Payload Too Large\r\n"
  6739. "Content-Type: text/plain\r\n"
  6740. "Connection: close\r\n\r\n");
  6741. mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
  6742. fus->lfn, (int) fus->num_recd);
  6743. } else {
  6744. mg_printf(nc,
  6745. "HTTP/1.1 500 Internal Server Error\r\n"
  6746. "Content-Type: text/plain\r\n"
  6747. "Connection: close\r\n\r\n");
  6748. mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
  6749. mg_get_errno(), (int) fus->num_recd);
  6750. }
  6751. fclose(fus->fp);
  6752. remove(fus->lfn);
  6753. fus->fp = NULL;
  6754. /* Do not close the connection just yet, discard remainder of the data.
  6755. * This is because at the time of writing some browsers (Chrome) fail to
  6756. * render response before all the data is sent. */
  6757. return;
  6758. }
  6759. fus->num_recd += mp->data.len;
  6760. LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
  6761. (int) fus->num_recd));
  6762. break;
  6763. }
  6764. case MG_EV_HTTP_PART_END: {
  6765. struct mg_http_multipart_part *mp =
  6766. (struct mg_http_multipart_part *) ev_data;
  6767. struct file_upload_state *fus =
  6768. (struct file_upload_state *) mp->user_data;
  6769. if (fus == NULL) break;
  6770. if (mp->status >= 0 && fus->fp != NULL) {
  6771. LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
  6772. fus->lfn, (int) fus->num_recd));
  6773. // mg_printf(nc,
  6774. // "HTTP/1.1 200 OK\r\n"
  6775. // "Content-Type: text/plain\r\n"
  6776. // "Connection: close\r\n\r\n"
  6777. // "Ok, %s - %d bytes.\r\n",
  6778. // mp->file_name, (int) fus->num_recd);
  6779. } else {
  6780. LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
  6781. /*
  6782. * mp->status < 0 means connection was terminated, so no reason to send
  6783. * HTTP reply
  6784. */
  6785. }
  6786. if (fus->fp != NULL) fclose(fus->fp);
  6787. MG_FREE(fus->lfn);
  6788. MG_FREE(fus);
  6789. mp->user_data = NULL;
  6790. nc->flags |= MG_F_SEND_AND_CLOSE;
  6791. break;
  6792. }
  6793. }
  6794. }
  6795. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  6796. #endif /* MG_ENABLE_FILESYSTEM */
  6797. /* returns 0 on success, -1 on error */
  6798. MG_INTERNAL int mg_http_common_url_parse(const char *url, const char *schema,
  6799. const char *schema_tls, int *use_ssl,
  6800. char **user, char **pass, char **addr,
  6801. int *port_i, const char **path) {
  6802. int addr_len = 0;
  6803. int auth_sep_pos = -1;
  6804. int user_sep_pos = -1;
  6805. int port_pos = -1;
  6806. (void) user;
  6807. (void) pass;
  6808. if (strncmp(url, schema, strlen(schema)) == 0) {
  6809. url += strlen(schema);
  6810. } else if (strncmp(url, schema_tls, strlen(schema_tls)) == 0) {
  6811. url += strlen(schema_tls);
  6812. *use_ssl = 1;
  6813. #if !MG_ENABLE_SSL
  6814. return -1; /* SSL is not enabled, cannot do HTTPS URLs */
  6815. #endif
  6816. }
  6817. while (*url != '\0') {
  6818. *addr = (char *) MG_REALLOC(*addr, addr_len + 6 /* space for port too. */);
  6819. if (*addr == NULL) {
  6820. DBG(("OOM"));
  6821. return -1;
  6822. }
  6823. if (*url == '/') {
  6824. break;
  6825. }
  6826. if (*url == '@') {
  6827. auth_sep_pos = addr_len;
  6828. user_sep_pos = port_pos;
  6829. port_pos = -1;
  6830. }
  6831. if (*url == ':') port_pos = addr_len;
  6832. (*addr)[addr_len++] = *url;
  6833. (*addr)[addr_len] = '\0';
  6834. url++;
  6835. }
  6836. if (addr_len == 0) goto cleanup;
  6837. if (port_pos < 0) {
  6838. *port_i = addr_len;
  6839. addr_len += sprintf(*addr + addr_len, ":%d", *use_ssl ? 443 : 80);
  6840. } else {
  6841. *port_i = -1;
  6842. }
  6843. if (*path == NULL) *path = url;
  6844. if (**path == '\0') *path = "/";
  6845. if (user != NULL && pass != NULL) {
  6846. if (auth_sep_pos == -1) {
  6847. *user = NULL;
  6848. *pass = NULL;
  6849. } else {
  6850. /* user is from 0 to user_sep_pos */
  6851. *user = (char *) MG_MALLOC(user_sep_pos + 1);
  6852. memcpy(*user, *addr, user_sep_pos);
  6853. (*user)[user_sep_pos] = '\0';
  6854. /* pass is from user_sep_pos + 1 to auth_sep_pos */
  6855. *pass = (char *) MG_MALLOC(auth_sep_pos - user_sep_pos - 1 + 1);
  6856. memcpy(*pass, *addr + user_sep_pos + 1, auth_sep_pos - user_sep_pos - 1);
  6857. (*pass)[auth_sep_pos - user_sep_pos - 1] = '\0';
  6858. /* move address proper to the front */
  6859. memmove(*addr, *addr + auth_sep_pos + 1, addr_len - auth_sep_pos);
  6860. }
  6861. }
  6862. DBG(("%s %s", *addr, *path));
  6863. return 0;
  6864. cleanup:
  6865. MG_FREE(*addr);
  6866. return -1;
  6867. }
  6868. struct mg_connection *mg_connect_http_base(
  6869. struct mg_mgr *mgr, mg_event_handler_t ev_handler,
  6870. struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
  6871. const char *url, const char **path, char **user, char **pass, char **addr) {
  6872. struct mg_connection *nc = NULL;
  6873. int port_i = -1;
  6874. int use_ssl = 0;
  6875. if (mg_http_common_url_parse(url, schema, schema_ssl, &use_ssl, user, pass,
  6876. addr, &port_i, path) < 0) {
  6877. MG_SET_PTRPTR(opts.error_string, "cannot parse url");
  6878. return NULL;
  6879. }
  6880. LOG(LL_DEBUG, ("%s use_ssl? %d", url, use_ssl));
  6881. if (use_ssl) {
  6882. #if MG_ENABLE_SSL
  6883. /*
  6884. * Schema requires SSL, but no SSL parameters were provided in opts.
  6885. * In order to maintain backward compatibility, use a faux-SSL with no
  6886. * verification.
  6887. */
  6888. if (opts.ssl_ca_cert == NULL) {
  6889. opts.ssl_ca_cert = "*";
  6890. }
  6891. #else
  6892. MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
  6893. if (user != NULL) MG_FREE(*user);
  6894. if (pass != NULL) MG_FREE(*pass);
  6895. MG_FREE(*addr);
  6896. return NULL;
  6897. #endif
  6898. }
  6899. if ((nc = mg_connect_opt(mgr, *addr, ev_handler, opts)) != NULL) {
  6900. mg_set_protocol_http_websocket(nc);
  6901. /* If the port was addred by us, restore the original host. */
  6902. if (port_i >= 0) (*addr)[port_i] = '\0';
  6903. }
  6904. return nc;
  6905. }
  6906. struct mg_connection *mg_connect_http_opt(struct mg_mgr *mgr,
  6907. mg_event_handler_t ev_handler,
  6908. struct mg_connect_opts opts,
  6909. const char *url,
  6910. const char *extra_headers,
  6911. const char *post_data) {
  6912. char *user = NULL, *pass = NULL, *addr = NULL;
  6913. const char *path = NULL;
  6914. struct mbuf auth;
  6915. struct mg_connection *nc =
  6916. mg_connect_http_base(mgr, ev_handler, opts, "http://", "https://", url,
  6917. &path, &user, &pass, &addr);
  6918. if (nc == NULL) {
  6919. return NULL;
  6920. }
  6921. mbuf_init(&auth, 0);
  6922. if (user != NULL) {
  6923. mg_basic_auth_header(user, pass, &auth);
  6924. }
  6925. mg_printf(nc, "%s %s HTTP/1.1\r\nHost: %s\r\nContent-Length: %" SIZE_T_FMT
  6926. "\r\n%.*s%s\r\n%s",
  6927. post_data == NULL ? "GET" : "POST", path, addr,
  6928. post_data == NULL ? 0 : strlen(post_data), (int) auth.len,
  6929. (auth.buf == NULL ? "" : auth.buf),
  6930. extra_headers == NULL ? "" : extra_headers,
  6931. post_data == NULL ? "" : post_data);
  6932. mbuf_free(&auth);
  6933. MG_FREE(user);
  6934. MG_FREE(pass);
  6935. MG_FREE(addr);
  6936. return nc;
  6937. }
  6938. struct mg_connection *mg_connect_http(struct mg_mgr *mgr,
  6939. mg_event_handler_t ev_handler,
  6940. const char *url,
  6941. const char *extra_headers,
  6942. const char *post_data) {
  6943. struct mg_connect_opts opts;
  6944. memset(&opts, 0, sizeof(opts));
  6945. return mg_connect_http_opt(mgr, ev_handler, opts, url, extra_headers,
  6946. post_data);
  6947. }
  6948. size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
  6949. size_t var_name_len, char *file_name,
  6950. size_t file_name_len, const char **data,
  6951. size_t *data_len) {
  6952. static const char cd[] = "Content-Disposition: ";
  6953. size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
  6954. if (buf == NULL || buf_len <= 0) return 0;
  6955. if ((hl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
  6956. if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
  6957. /* Get boundary length */
  6958. bl = mg_get_line_len(buf, buf_len);
  6959. /* Loop through headers, fetch variable name and file name */
  6960. var_name[0] = file_name[0] = '\0';
  6961. for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
  6962. if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
  6963. struct mg_str header;
  6964. header.p = buf + n + cdl;
  6965. header.len = ll - (cdl + 2);
  6966. mg_http_parse_header(&header, "name", var_name, var_name_len);
  6967. mg_http_parse_header(&header, "filename", file_name, file_name_len);
  6968. }
  6969. }
  6970. /* Scan through the body, search for terminating boundary */
  6971. for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
  6972. if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
  6973. if (data_len != NULL) *data_len = (pos - 2) - hl;
  6974. if (data != NULL) *data = buf + hl;
  6975. return pos;
  6976. }
  6977. }
  6978. return 0;
  6979. }
  6980. void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
  6981. mg_event_handler_t handler) {
  6982. struct mg_http_proto_data *pd = NULL;
  6983. struct mg_http_endpoint *new_ep = NULL;
  6984. if (nc == NULL) return;
  6985. new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
  6986. if (new_ep == NULL) return;
  6987. pd = mg_http_get_proto_data(nc);
  6988. new_ep->name = MG_STRDUP(uri_path);
  6989. new_ep->name_len = strlen(new_ep->name);
  6990. new_ep->handler = handler;
  6991. new_ep->next = pd->endpoints;
  6992. pd->endpoints = new_ep;
  6993. }
  6994. #endif /* MG_ENABLE_HTTP */
  6995. #ifdef MG_MODULE_LINES
  6996. #line 1 "mongoose/src/http_cgi.c"
  6997. #endif
  6998. /*
  6999. * Copyright (c) 2014-2016 Cesanta Software Limited
  7000. * All rights reserved
  7001. */
  7002. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
  7003. #ifndef MG_MAX_CGI_ENVIR_VARS
  7004. #define MG_MAX_CGI_ENVIR_VARS 64
  7005. #endif
  7006. #ifndef MG_ENV_EXPORT_TO_CGI
  7007. #define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
  7008. #endif
  7009. /*
  7010. * This structure helps to create an environment for the spawned CGI program.
  7011. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  7012. * last element must be NULL.
  7013. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  7014. * strings must reside in a contiguous buffer. The end of the buffer is
  7015. * marked by two '\0' characters.
  7016. * We satisfy both worlds: we create an envp array (which is vars), all
  7017. * entries are actually pointers inside buf.
  7018. */
  7019. struct mg_cgi_env_block {
  7020. struct mg_connection *nc;
  7021. char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  7022. const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
  7023. int len; /* Space taken */
  7024. int nvars; /* Number of variables in envp[] */
  7025. };
  7026. #ifdef _WIN32
  7027. struct mg_threadparam {
  7028. sock_t s;
  7029. HANDLE hPipe;
  7030. };
  7031. static int mg_wait_until_ready(sock_t sock, int for_read) {
  7032. fd_set set;
  7033. FD_ZERO(&set);
  7034. FD_SET(sock, &set);
  7035. return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
  7036. }
  7037. static void *mg_push_to_stdin(void *arg) {
  7038. struct mg_threadparam *tp = (struct mg_threadparam *) arg;
  7039. int n, sent, stop = 0;
  7040. DWORD k;
  7041. char buf[BUFSIZ];
  7042. while (!stop && mg_wait_until_ready(tp->s, 1) &&
  7043. (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
  7044. if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
  7045. for (sent = 0; !stop && sent < n; sent += k) {
  7046. if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
  7047. }
  7048. }
  7049. DBG(("%s", "FORWARED EVERYTHING TO CGI"));
  7050. CloseHandle(tp->hPipe);
  7051. MG_FREE(tp);
  7052. return NULL;
  7053. }
  7054. static void *mg_pull_from_stdout(void *arg) {
  7055. struct mg_threadparam *tp = (struct mg_threadparam *) arg;
  7056. int k = 0, stop = 0;
  7057. DWORD n, sent;
  7058. char buf[BUFSIZ];
  7059. while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
  7060. for (sent = 0; !stop && sent < n; sent += k) {
  7061. if (mg_wait_until_ready(tp->s, 0) &&
  7062. (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
  7063. stop = 1;
  7064. }
  7065. }
  7066. DBG(("%s", "EOF FROM CGI"));
  7067. CloseHandle(tp->hPipe);
  7068. shutdown(tp->s, 2); // Without this, IO thread may get truncated data
  7069. closesocket(tp->s);
  7070. MG_FREE(tp);
  7071. return NULL;
  7072. }
  7073. static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
  7074. void *(*func)(void *)) {
  7075. struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
  7076. if (tp != NULL) {
  7077. tp->s = sock;
  7078. tp->hPipe = hPipe;
  7079. mg_start_thread(func, tp);
  7080. }
  7081. }
  7082. static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
  7083. wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
  7084. to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
  7085. GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
  7086. WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
  7087. }
  7088. static int mg_start_process(const char *interp, const char *cmd,
  7089. const char *env, const char *envp[],
  7090. const char *dir, sock_t sock) {
  7091. STARTUPINFOW si;
  7092. PROCESS_INFORMATION pi;
  7093. HANDLE a[2], b[2], me = GetCurrentProcess();
  7094. wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
  7095. char buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
  7096. buf4[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE];
  7097. DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
  7098. FILE *fp;
  7099. memset(&si, 0, sizeof(si));
  7100. memset(&pi, 0, sizeof(pi));
  7101. si.cb = sizeof(si);
  7102. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  7103. si.wShowWindow = SW_HIDE;
  7104. si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  7105. CreatePipe(&a[0], &a[1], NULL, 0);
  7106. CreatePipe(&b[0], &b[1], NULL, 0);
  7107. DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
  7108. DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
  7109. if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
  7110. buf[0] = buf[1] = '\0';
  7111. fgets(buf, sizeof(buf), fp);
  7112. buf[sizeof(buf) - 1] = '\0';
  7113. if (buf[0] == '#' && buf[1] == '!') {
  7114. interp = buf + 2;
  7115. /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
  7116. while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
  7117. interp++;
  7118. }
  7119. }
  7120. fclose(fp);
  7121. }
  7122. snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
  7123. mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
  7124. mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
  7125. to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
  7126. if (interp != NULL) {
  7127. mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
  7128. snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
  7129. } else {
  7130. snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
  7131. }
  7132. to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
  7133. if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
  7134. (void *) env, full_dir, &si, &pi) != 0) {
  7135. mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
  7136. mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
  7137. CloseHandle(si.hStdOutput);
  7138. CloseHandle(si.hStdInput);
  7139. CloseHandle(pi.hThread);
  7140. CloseHandle(pi.hProcess);
  7141. } else {
  7142. CloseHandle(a[1]);
  7143. CloseHandle(b[0]);
  7144. closesocket(sock);
  7145. }
  7146. DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
  7147. /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
  7148. (void) envp;
  7149. return (pi.hProcess != NULL);
  7150. }
  7151. #else
  7152. static int mg_start_process(const char *interp, const char *cmd,
  7153. const char *env, const char *envp[],
  7154. const char *dir, sock_t sock) {
  7155. char buf[500];
  7156. pid_t pid = fork();
  7157. (void) env;
  7158. if (pid == 0) {
  7159. /*
  7160. * In Linux `chdir` declared with `warn_unused_result` attribute
  7161. * To shutup compiler we have yo use result in some way
  7162. */
  7163. int tmp = chdir(dir);
  7164. (void) tmp;
  7165. (void) dup2(sock, 0);
  7166. (void) dup2(sock, 1);
  7167. closesocket(sock);
  7168. /*
  7169. * After exec, all signal handlers are restored to their default values,
  7170. * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
  7171. * implementation, SIGCHLD's handler will leave unchanged after exec
  7172. * if it was set to be ignored. Restore it to default action.
  7173. */
  7174. signal(SIGCHLD, SIG_DFL);
  7175. if (interp == NULL) {
  7176. execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
  7177. } else {
  7178. execle(interp, interp, cmd, (char *) 0, envp);
  7179. }
  7180. snprintf(buf, sizeof(buf),
  7181. "Status: 500\r\n\r\n"
  7182. "500 Server Error: %s%s%s: %s",
  7183. interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
  7184. strerror(errno));
  7185. send(1, buf, strlen(buf), 0);
  7186. _exit(EXIT_FAILURE); /* exec call failed */
  7187. }
  7188. return (pid != 0);
  7189. }
  7190. #endif /* _WIN32 */
  7191. /*
  7192. * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  7193. * pointer into the vars array.
  7194. */
  7195. static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
  7196. int n, space;
  7197. char *added = block->buf + block->len;
  7198. va_list ap;
  7199. /* Calculate how much space is left in the buffer */
  7200. space = sizeof(block->buf) - (block->len + 2);
  7201. if (space > 0) {
  7202. /* Copy VARIABLE=VALUE\0 string into the free space */
  7203. va_start(ap, fmt);
  7204. n = vsnprintf(added, (size_t) space, fmt, ap);
  7205. va_end(ap);
  7206. /* Make sure we do not overflow buffer and the envp array */
  7207. if (n > 0 && n + 1 < space &&
  7208. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  7209. /* Append a pointer to the added string into the envp array */
  7210. block->vars[block->nvars++] = added;
  7211. /* Bump up used length counter. Include \0 terminator */
  7212. block->len += n + 1;
  7213. }
  7214. }
  7215. return added;
  7216. }
  7217. static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
  7218. const char *s;
  7219. if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
  7220. }
  7221. static void mg_prepare_cgi_environment(struct mg_connection *nc,
  7222. const char *prog,
  7223. const struct mg_str *path_info,
  7224. const struct http_message *hm,
  7225. const struct mg_serve_http_opts *opts,
  7226. struct mg_cgi_env_block *blk) {
  7227. const char *s;
  7228. struct mg_str *h;
  7229. char *p;
  7230. size_t i;
  7231. char buf[100];
  7232. blk->len = blk->nvars = 0;
  7233. blk->nc = nc;
  7234. if ((s = getenv("SERVER_NAME")) != NULL) {
  7235. mg_addenv(blk, "SERVER_NAME=%s", s);
  7236. } else {
  7237. mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
  7238. mg_addenv(blk, "SERVER_NAME=%s", buf);
  7239. }
  7240. mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
  7241. mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
  7242. mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
  7243. /* Prepare the environment block */
  7244. mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7245. mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7246. mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7247. mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
  7248. mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
  7249. hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
  7250. hm->query_string.p);
  7251. mg_conn_addr_to_str(nc, buf, sizeof(buf),
  7252. MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
  7253. mg_addenv(blk, "REMOTE_ADDR=%s", buf);
  7254. mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
  7255. mg_addenv(blk, "SERVER_PORT=%s", buf);
  7256. s = hm->uri.p + hm->uri.len - path_info->len - 1;
  7257. if (*s == '/') {
  7258. const char *base_name = strrchr(prog, DIRSEP);
  7259. mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
  7260. (base_name != NULL ? base_name + 1 : prog));
  7261. } else {
  7262. mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
  7263. }
  7264. mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
  7265. if (path_info != NULL && path_info->len > 0) {
  7266. mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
  7267. /* Not really translated... */
  7268. mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
  7269. }
  7270. #if MG_ENABLE_SSL
  7271. mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
  7272. #else
  7273. mg_addenv(blk, "HTTPS=off");
  7274. #endif
  7275. if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
  7276. NULL) {
  7277. mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
  7278. }
  7279. if (hm->query_string.len > 0) {
  7280. mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
  7281. hm->query_string.p);
  7282. }
  7283. if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
  7284. NULL) {
  7285. mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
  7286. }
  7287. mg_addenv2(blk, "PATH");
  7288. mg_addenv2(blk, "TMP");
  7289. mg_addenv2(blk, "TEMP");
  7290. mg_addenv2(blk, "TMPDIR");
  7291. mg_addenv2(blk, "PERLLIB");
  7292. mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
  7293. #ifdef _WIN32
  7294. mg_addenv2(blk, "COMSPEC");
  7295. mg_addenv2(blk, "SYSTEMROOT");
  7296. mg_addenv2(blk, "SystemDrive");
  7297. mg_addenv2(blk, "ProgramFiles");
  7298. mg_addenv2(blk, "ProgramFiles(x86)");
  7299. mg_addenv2(blk, "CommonProgramFiles(x86)");
  7300. #else
  7301. mg_addenv2(blk, "LD_LIBRARY_PATH");
  7302. #endif /* _WIN32 */
  7303. /* Add all headers as HTTP_* variables */
  7304. for (i = 0; hm->header_names[i].len > 0; i++) {
  7305. p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
  7306. hm->header_names[i].p, (int) hm->header_values[i].len,
  7307. hm->header_values[i].p);
  7308. /* Convert variable name into uppercase, and change - to _ */
  7309. for (; *p != '=' && *p != '\0'; p++) {
  7310. if (*p == '-') *p = '_';
  7311. *p = (char) toupper(*(unsigned char *) p);
  7312. }
  7313. }
  7314. blk->vars[blk->nvars++] = NULL;
  7315. blk->buf[blk->len++] = '\0';
  7316. }
  7317. static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
  7318. void *ev_data) {
  7319. struct mg_connection *nc = (struct mg_connection *) cgi_nc->user_data;
  7320. (void) ev_data;
  7321. if (nc == NULL) {
  7322. cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  7323. return;
  7324. }
  7325. switch (ev) {
  7326. case MG_EV_RECV:
  7327. /*
  7328. * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
  7329. * It outputs headers, then body. Headers might include "Status"
  7330. * header, which changes CODE, and it might include "Location" header
  7331. * which changes CODE to 302.
  7332. *
  7333. * Therefore we do not send the output from the CGI script to the user
  7334. * until all CGI headers are received.
  7335. *
  7336. * Here we parse the output from the CGI script, and if all headers has
  7337. * been received, send appropriate reply line, and forward all
  7338. * received headers to the client.
  7339. */
  7340. if (nc->flags & MG_F_USER_1) {
  7341. struct mbuf *io = &cgi_nc->recv_mbuf;
  7342. int len = mg_http_get_request_len(io->buf, io->len);
  7343. if (len == 0) break;
  7344. if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
  7345. cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  7346. mg_http_send_error(nc, 500, "Bad headers");
  7347. } else {
  7348. struct http_message hm;
  7349. struct mg_str *h;
  7350. mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
  7351. if (mg_get_http_header(&hm, "Location") != NULL) {
  7352. mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
  7353. } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
  7354. mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
  7355. } else {
  7356. mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
  7357. }
  7358. }
  7359. nc->flags &= ~MG_F_USER_1;
  7360. }
  7361. if (!(nc->flags & MG_F_USER_1)) {
  7362. mg_forward(cgi_nc, nc);
  7363. }
  7364. break;
  7365. case MG_EV_CLOSE:
  7366. mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
  7367. nc->flags |= MG_F_SEND_AND_CLOSE;
  7368. break;
  7369. }
  7370. }
  7371. MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
  7372. const struct mg_str *path_info,
  7373. const struct http_message *hm,
  7374. const struct mg_serve_http_opts *opts) {
  7375. struct mg_cgi_env_block blk;
  7376. char dir[MAX_PATH_SIZE];
  7377. const char *p;
  7378. sock_t fds[2];
  7379. DBG(("%p [%s]", nc, prog));
  7380. mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
  7381. /*
  7382. * CGI must be executed in its own directory. 'dir' must point to the
  7383. * directory containing executable program, 'p' must point to the
  7384. * executable program name relative to 'dir'.
  7385. */
  7386. if ((p = strrchr(prog, DIRSEP)) == NULL) {
  7387. snprintf(dir, sizeof(dir), "%s", ".");
  7388. } else {
  7389. snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
  7390. prog = p + 1;
  7391. }
  7392. /*
  7393. * Try to create socketpair in a loop until success. mg_socketpair()
  7394. * can be interrupted by a signal and fail.
  7395. * TODO(lsm): use sigaction to restart interrupted syscall
  7396. */
  7397. do {
  7398. mg_socketpair(fds, SOCK_STREAM);
  7399. } while (fds[0] == INVALID_SOCKET);
  7400. if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
  7401. fds[1]) != 0) {
  7402. size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
  7403. struct mg_connection *cgi_nc =
  7404. mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler);
  7405. struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
  7406. cgi_pd->cgi.cgi_nc = cgi_nc;
  7407. cgi_pd->cgi.cgi_nc->user_data = nc;
  7408. nc->flags |= MG_F_USER_1;
  7409. /* Push POST data to the CGI */
  7410. if (n > 0 && n < nc->recv_mbuf.len) {
  7411. mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n);
  7412. }
  7413. mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
  7414. } else {
  7415. closesocket(fds[0]);
  7416. mg_http_send_error(nc, 500, "CGI failure");
  7417. }
  7418. #ifndef _WIN32
  7419. closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
  7420. #endif
  7421. }
  7422. MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
  7423. if (d != NULL) {
  7424. if (d->cgi_nc != NULL) d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  7425. memset(d, 0, sizeof(struct mg_http_proto_data_cgi));
  7426. }
  7427. }
  7428. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
  7429. #ifdef MG_MODULE_LINES
  7430. #line 1 "mongoose/src/http_ssi.c"
  7431. #endif
  7432. /*
  7433. * Copyright (c) 2014-2016 Cesanta Software Limited
  7434. * All rights reserved
  7435. */
  7436. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
  7437. static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
  7438. const char *path, FILE *fp, int include_level,
  7439. const struct mg_serve_http_opts *opts);
  7440. static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
  7441. char buf[BUFSIZ];
  7442. size_t n;
  7443. while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
  7444. mg_send(nc, buf, n);
  7445. }
  7446. }
  7447. static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
  7448. const char *ssi, char *tag, int include_level,
  7449. const struct mg_serve_http_opts *opts) {
  7450. char file_name[BUFSIZ], path[MAX_PATH_SIZE], *p;
  7451. FILE *fp;
  7452. /*
  7453. * sscanf() is safe here, since send_ssi_file() also uses buffer
  7454. * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  7455. */
  7456. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  7457. /* File name is relative to the webserver root */
  7458. snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
  7459. } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
  7460. /*
  7461. * File name is relative to the webserver working directory
  7462. * or it is absolute system path
  7463. */
  7464. snprintf(path, sizeof(path), "%s", file_name);
  7465. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
  7466. sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  7467. /* File name is relative to the currect document */
  7468. snprintf(path, sizeof(path), "%s", ssi);
  7469. if ((p = strrchr(path, DIRSEP)) != NULL) {
  7470. p[1] = '\0';
  7471. }
  7472. snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
  7473. } else {
  7474. mg_printf(nc, "Bad SSI #include: [%s]", tag);
  7475. return;
  7476. }
  7477. if ((fp = mg_fopen(path, "rb")) == NULL) {
  7478. mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
  7479. strerror(mg_get_errno()));
  7480. } else {
  7481. mg_set_close_on_exec((sock_t) fileno(fp));
  7482. if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
  7483. 0) {
  7484. mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
  7485. } else {
  7486. mg_send_file_data(nc, fp);
  7487. }
  7488. fclose(fp);
  7489. }
  7490. }
  7491. #if MG_ENABLE_HTTP_SSI_EXEC
  7492. static void do_ssi_exec(struct mg_connection *nc, char *tag) {
  7493. char cmd[BUFSIZ];
  7494. FILE *fp;
  7495. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  7496. mg_printf(nc, "Bad SSI #exec: [%s]", tag);
  7497. } else if ((fp = popen(cmd, "r")) == NULL) {
  7498. mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
  7499. } else {
  7500. mg_send_file_data(nc, fp);
  7501. pclose(fp);
  7502. }
  7503. }
  7504. #endif /* MG_ENABLE_HTTP_SSI_EXEC */
  7505. /*
  7506. * SSI directive has the following format:
  7507. * <!--#directive parameter=value parameter=value -->
  7508. */
  7509. static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
  7510. const char *path, FILE *fp, int include_level,
  7511. const struct mg_serve_http_opts *opts) {
  7512. static const struct mg_str btag = MG_MK_STR("<!--#");
  7513. static const struct mg_str d_include = MG_MK_STR("include");
  7514. static const struct mg_str d_call = MG_MK_STR("call");
  7515. #if MG_ENABLE_HTTP_SSI_EXEC
  7516. static const struct mg_str d_exec = MG_MK_STR("exec");
  7517. #endif
  7518. char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
  7519. int ch, len, in_ssi_tag;
  7520. if (include_level > 10) {
  7521. mg_printf(nc, "SSI #include level is too deep (%s)", path);
  7522. return;
  7523. }
  7524. in_ssi_tag = len = 0;
  7525. while ((ch = fgetc(fp)) != EOF) {
  7526. if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  7527. size_t i = len - 2;
  7528. in_ssi_tag = 0;
  7529. /* Trim closing --> */
  7530. buf[i--] = '\0';
  7531. while (i > 0 && buf[i] == ' ') {
  7532. buf[i--] = '\0';
  7533. }
  7534. /* Handle known SSI directives */
  7535. if (strncmp(p, d_include.p, d_include.len) == 0) {
  7536. mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
  7537. opts);
  7538. } else if (strncmp(p, d_call.p, d_call.len) == 0) {
  7539. struct mg_ssi_call_ctx cctx;
  7540. memset(&cctx, 0, sizeof(cctx));
  7541. cctx.req = hm;
  7542. cctx.file = mg_mk_str(path);
  7543. cctx.arg = mg_mk_str(p + d_call.len + 1);
  7544. mg_call(nc, NULL, MG_EV_SSI_CALL,
  7545. (void *) cctx.arg.p); /* NUL added above */
  7546. mg_call(nc, NULL, MG_EV_SSI_CALL_CTX, &cctx);
  7547. #if MG_ENABLE_HTTP_SSI_EXEC
  7548. } else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
  7549. do_ssi_exec(nc, p + d_exec.len + 1);
  7550. #endif
  7551. } else {
  7552. /* Silently ignore unknown SSI directive. */
  7553. }
  7554. len = 0;
  7555. } else if (ch == '<') {
  7556. in_ssi_tag = 1;
  7557. if (len > 0) {
  7558. mg_send(nc, buf, (size_t) len);
  7559. }
  7560. len = 0;
  7561. buf[len++] = ch & 0xff;
  7562. } else if (in_ssi_tag) {
  7563. if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
  7564. /* Not an SSI tag */
  7565. in_ssi_tag = 0;
  7566. } else if (len == (int) sizeof(buf) - 2) {
  7567. mg_printf(nc, "%s: SSI tag is too large", path);
  7568. len = 0;
  7569. }
  7570. buf[len++] = ch & 0xff;
  7571. } else {
  7572. buf[len++] = ch & 0xff;
  7573. if (len == (int) sizeof(buf)) {
  7574. mg_send(nc, buf, (size_t) len);
  7575. len = 0;
  7576. }
  7577. }
  7578. }
  7579. /* Send the rest of buffered data */
  7580. if (len > 0) {
  7581. mg_send(nc, buf, (size_t) len);
  7582. }
  7583. }
  7584. MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
  7585. struct http_message *hm,
  7586. const char *path,
  7587. const struct mg_serve_http_opts *opts) {
  7588. FILE *fp;
  7589. struct mg_str mime_type;
  7590. DBG(("%p %s", nc, path));
  7591. if ((fp = mg_fopen(path, "rb")) == NULL) {
  7592. mg_http_send_error(nc, 404, NULL);
  7593. } else {
  7594. mg_set_close_on_exec((sock_t) fileno(fp));
  7595. mime_type = mg_get_mime_type(path, "text/plain", opts);
  7596. mg_send_response_line(nc, 200, opts->extra_headers);
  7597. mg_printf(nc,
  7598. "Content-Type: %.*s\r\n"
  7599. "Connection: close\r\n\r\n",
  7600. (int) mime_type.len, mime_type.p);
  7601. mg_send_ssi_file(nc, hm, path, fp, 0, opts);
  7602. fclose(fp);
  7603. nc->flags |= MG_F_SEND_AND_CLOSE;
  7604. }
  7605. }
  7606. #endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
  7607. #ifdef MG_MODULE_LINES
  7608. #line 1 "mongoose/src/http_webdav.c"
  7609. #endif
  7610. /*
  7611. * Copyright (c) 2014-2016 Cesanta Software Limited
  7612. * All rights reserved
  7613. */
  7614. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
  7615. MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
  7616. static const char *methods[] = {
  7617. "PUT",
  7618. "DELETE",
  7619. "MKCOL",
  7620. "PROPFIND",
  7621. "MOVE"
  7622. #if MG_ENABLE_FAKE_DAVLOCK
  7623. ,
  7624. "LOCK",
  7625. "UNLOCK"
  7626. #endif
  7627. };
  7628. size_t i;
  7629. for (i = 0; i < ARRAY_SIZE(methods); i++) {
  7630. if (mg_vcmp(s, methods[i]) == 0) {
  7631. return 1;
  7632. }
  7633. }
  7634. return 0;
  7635. }
  7636. static int mg_mkdir(const char *path, uint32_t mode) {
  7637. #ifndef _WIN32
  7638. return mkdir(path, mode);
  7639. #else
  7640. (void) mode;
  7641. return _mkdir(path);
  7642. #endif
  7643. }
  7644. static void mg_print_props(struct mg_connection *nc, const char *name,
  7645. cs_stat_t *stp) {
  7646. char mtime[64], buf[MAX_PATH_SIZE * 3];
  7647. time_t t = stp->st_mtime; /* store in local variable for NDK compile */
  7648. mg_gmt_time_string(mtime, sizeof(mtime), &t);
  7649. mg_url_encode(name, strlen(name), buf, sizeof(buf));
  7650. mg_printf(nc,
  7651. "<d:response>"
  7652. "<d:href>%s</d:href>"
  7653. "<d:propstat>"
  7654. "<d:prop>"
  7655. "<d:resourcetype>%s</d:resourcetype>"
  7656. "<d:getcontentlength>%" INT64_FMT
  7657. "</d:getcontentlength>"
  7658. "<d:getlastmodified>%s</d:getlastmodified>"
  7659. "</d:prop>"
  7660. "<d:status>HTTP/1.1 200 OK</d:status>"
  7661. "</d:propstat>"
  7662. "</d:response>\n",
  7663. buf, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
  7664. (int64_t) stp->st_size, mtime);
  7665. }
  7666. MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
  7667. cs_stat_t *stp, struct http_message *hm,
  7668. struct mg_serve_http_opts *opts) {
  7669. static const char header[] =
  7670. "HTTP/1.1 207 Multi-Status\r\n"
  7671. "Connection: close\r\n"
  7672. "Content-Type: text/xml; charset=utf-8\r\n\r\n"
  7673. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7674. "<d:multistatus xmlns:d='DAV:'>\n";
  7675. static const char footer[] = "</d:multistatus>\n";
  7676. const struct mg_str *depth = mg_get_http_header(hm, "Depth");
  7677. /* Print properties for the requested resource itself */
  7678. if (S_ISDIR(stp->st_mode) &&
  7679. strcmp(opts->enable_directory_listing, "yes") != 0) {
  7680. mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
  7681. } else {
  7682. char uri[MAX_PATH_SIZE];
  7683. mg_send(nc, header, sizeof(header) - 1);
  7684. snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
  7685. mg_print_props(nc, uri, stp);
  7686. if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
  7687. mg_scan_directory(nc, path, opts, mg_print_props);
  7688. }
  7689. mg_send(nc, footer, sizeof(footer) - 1);
  7690. nc->flags |= MG_F_SEND_AND_CLOSE;
  7691. }
  7692. }
  7693. #if MG_ENABLE_FAKE_DAVLOCK
  7694. /*
  7695. * Windows explorer (probably there are another WebDav clients like it)
  7696. * requires LOCK support in webdav. W/out this, it still works, but fails
  7697. * to save file: shows error message and offers "Save As".
  7698. * "Save as" works, but this message is very annoying.
  7699. * This is fake lock, which doesn't lock something, just returns LOCK token,
  7700. * UNLOCK always answers "OK".
  7701. * With this fake LOCK Windows Explorer looks happy and saves file.
  7702. * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
  7703. * Windows native DAV client. This is why FAKE LOCK is not enabed by default
  7704. */
  7705. MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
  7706. static const char *reply =
  7707. "HTTP/1.1 207 Multi-Status\r\n"
  7708. "Connection: close\r\n"
  7709. "Content-Type: text/xml; charset=utf-8\r\n\r\n"
  7710. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7711. "<d:multistatus xmlns:d='DAV:'>\n"
  7712. "<D:lockdiscovery>\n"
  7713. "<D:activelock>\n"
  7714. "<D:locktoken>\n"
  7715. "<D:href>\n"
  7716. "opaquelocktoken:%s%u"
  7717. "</D:href>"
  7718. "</D:locktoken>"
  7719. "</D:activelock>\n"
  7720. "</D:lockdiscovery>"
  7721. "</d:multistatus>\n";
  7722. mg_printf(nc, reply, path, (unsigned int) mg_time());
  7723. nc->flags |= MG_F_SEND_AND_CLOSE;
  7724. }
  7725. #endif
  7726. MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
  7727. struct http_message *hm) {
  7728. int status_code = 500;
  7729. if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
  7730. status_code = 415;
  7731. } else if (!mg_mkdir(path, 0755)) {
  7732. status_code = 201;
  7733. } else if (errno == EEXIST) {
  7734. status_code = 405;
  7735. } else if (errno == EACCES) {
  7736. status_code = 403;
  7737. } else if (errno == ENOENT) {
  7738. status_code = 409;
  7739. } else {
  7740. status_code = 500;
  7741. }
  7742. mg_http_send_error(nc, status_code, NULL);
  7743. }
  7744. static int mg_remove_directory(const struct mg_serve_http_opts *opts,
  7745. const char *dir) {
  7746. char path[MAX_PATH_SIZE];
  7747. struct dirent *dp;
  7748. cs_stat_t st;
  7749. DIR *dirp;
  7750. if ((dirp = opendir(dir)) == NULL) return 0;
  7751. while ((dp = readdir(dirp)) != NULL) {
  7752. if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
  7753. continue;
  7754. }
  7755. snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  7756. mg_stat(path, &st);
  7757. if (S_ISDIR(st.st_mode)) {
  7758. mg_remove_directory(opts, path);
  7759. } else {
  7760. remove(path);
  7761. }
  7762. }
  7763. closedir(dirp);
  7764. rmdir(dir);
  7765. return 1;
  7766. }
  7767. MG_INTERNAL void mg_handle_move(struct mg_connection *c,
  7768. const struct mg_serve_http_opts *opts,
  7769. const char *path, struct http_message *hm) {
  7770. const struct mg_str *dest = mg_get_http_header(hm, "Destination");
  7771. if (dest == NULL) {
  7772. mg_http_send_error(c, 411, NULL);
  7773. } else {
  7774. const char *p = (char *) memchr(dest->p, '/', dest->len);
  7775. if (p != NULL && p[1] == '/' &&
  7776. (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
  7777. char buf[MAX_PATH_SIZE];
  7778. snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
  7779. (int) (dest->p + dest->len - p), p);
  7780. if (rename(path, buf) == 0) {
  7781. mg_http_send_error(c, 200, NULL);
  7782. } else {
  7783. mg_http_send_error(c, 418, NULL);
  7784. }
  7785. } else {
  7786. mg_http_send_error(c, 500, NULL);
  7787. }
  7788. }
  7789. }
  7790. MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
  7791. const struct mg_serve_http_opts *opts,
  7792. const char *path) {
  7793. cs_stat_t st;
  7794. if (mg_stat(path, &st) != 0) {
  7795. mg_http_send_error(nc, 404, NULL);
  7796. } else if (S_ISDIR(st.st_mode)) {
  7797. mg_remove_directory(opts, path);
  7798. mg_http_send_error(nc, 204, NULL);
  7799. } else if (remove(path) == 0) {
  7800. mg_http_send_error(nc, 204, NULL);
  7801. } else {
  7802. mg_http_send_error(nc, 423, NULL);
  7803. }
  7804. }
  7805. /* Return -1 on error, 1 on success. */
  7806. static int mg_create_itermediate_directories(const char *path) {
  7807. const char *s;
  7808. /* Create intermediate directories if they do not exist */
  7809. for (s = path + 1; *s != '\0'; s++) {
  7810. if (*s == '/') {
  7811. char buf[MAX_PATH_SIZE];
  7812. cs_stat_t st;
  7813. snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
  7814. buf[sizeof(buf) - 1] = '\0';
  7815. if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
  7816. return -1;
  7817. }
  7818. }
  7819. }
  7820. return 1;
  7821. }
  7822. MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
  7823. struct http_message *hm) {
  7824. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  7825. cs_stat_t st;
  7826. const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
  7827. int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  7828. mg_http_free_proto_data_file(&pd->file);
  7829. if ((rc = mg_create_itermediate_directories(path)) == 0) {
  7830. mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
  7831. } else if (rc == -1) {
  7832. mg_http_send_error(nc, 500, NULL);
  7833. } else if (cl_hdr == NULL) {
  7834. mg_http_send_error(nc, 411, NULL);
  7835. } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
  7836. mg_http_send_error(nc, 500, NULL);
  7837. } else {
  7838. const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
  7839. int64_t r1 = 0, r2 = 0;
  7840. pd->file.type = DATA_PUT;
  7841. mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
  7842. pd->file.cl = to64(cl_hdr->p);
  7843. if (range_hdr != NULL &&
  7844. mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
  7845. status_code = 206;
  7846. fseeko(pd->file.fp, r1, SEEK_SET);
  7847. pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
  7848. }
  7849. mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
  7850. /* Remove HTTP request from the mbuf, leave only payload */
  7851. mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
  7852. mg_http_transfer_file_data(nc);
  7853. }
  7854. }
  7855. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
  7856. #ifdef MG_MODULE_LINES
  7857. #line 1 "mongoose/src/http_websocket.c"
  7858. #endif
  7859. /*
  7860. * Copyright (c) 2014 Cesanta Software Limited
  7861. * All rights reserved
  7862. */
  7863. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
  7864. #ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
  7865. #define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
  7866. #endif
  7867. #define MG_WS_NO_HOST_HEADER_MAGIC ((char *) 0x1)
  7868. static int mg_is_ws_fragment(unsigned char flags) {
  7869. return (flags & 0x80) == 0 || (flags & 0x0f) == 0;
  7870. }
  7871. static int mg_is_ws_first_fragment(unsigned char flags) {
  7872. return (flags & 0x80) == 0 && (flags & 0x0f) != 0;
  7873. }
  7874. static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
  7875. struct websocket_message *wsm) {
  7876. if (wsm->flags & 0x8) {
  7877. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
  7878. } else {
  7879. mg_call(nc, nc->handler, MG_EV_WEBSOCKET_FRAME, wsm);
  7880. }
  7881. }
  7882. static int mg_deliver_websocket_data(struct mg_connection *nc) {
  7883. /* Using unsigned char *, cause of integer arithmetic below */
  7884. uint64_t i, data_len = 0, frame_len = 0, buf_len = nc->recv_mbuf.len, len,
  7885. mask_len = 0, header_len = 0;
  7886. unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p,
  7887. *e = p + buf_len;
  7888. unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */
  7889. int ok, reass = buf_len > 0 && mg_is_ws_fragment(p[0]) &&
  7890. !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
  7891. /* If that's a continuation frame that must be reassembled, handle it */
  7892. if (reass && !mg_is_ws_first_fragment(p[0]) &&
  7893. buf_len >= 1 + sizeof(*sizep) && buf_len >= 1 + sizeof(*sizep) + *sizep) {
  7894. buf += 1 + sizeof(*sizep) + *sizep;
  7895. buf_len -= 1 + sizeof(*sizep) + *sizep;
  7896. }
  7897. if (buf_len >= 2) {
  7898. len = buf[1] & 127;
  7899. mask_len = buf[1] & 128 ? 4 : 0;
  7900. if (len < 126 && buf_len >= mask_len) {
  7901. data_len = len;
  7902. header_len = 2 + mask_len;
  7903. } else if (len == 126 && buf_len >= 4 + mask_len) {
  7904. header_len = 4 + mask_len;
  7905. data_len = ntohs(*(uint16_t *) &buf[2]);
  7906. } else if (buf_len >= 10 + mask_len) {
  7907. header_len = 10 + mask_len;
  7908. data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) +
  7909. ntohl(*(uint32_t *) &buf[6]);
  7910. }
  7911. }
  7912. frame_len = header_len + data_len;
  7913. ok = frame_len > 0 && frame_len <= buf_len;
  7914. if (ok) {
  7915. struct websocket_message wsm;
  7916. wsm.size = (size_t) data_len;
  7917. wsm.data = buf + header_len;
  7918. wsm.flags = buf[0];
  7919. /* Apply mask if necessary */
  7920. if (mask_len > 0) {
  7921. for (i = 0; i < data_len; i++) {
  7922. buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
  7923. }
  7924. }
  7925. if (reass) {
  7926. /* On first fragmented frame, nullify size */
  7927. if (mg_is_ws_first_fragment(wsm.flags)) {
  7928. mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep));
  7929. p[0] &= ~0x0f; /* Next frames will be treated as continuation */
  7930. buf = p + 1 + sizeof(*sizep);
  7931. *sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */
  7932. }
  7933. /* Append this frame to the reassembled buffer */
  7934. memmove(buf, wsm.data, e - wsm.data);
  7935. (*sizep) += wsm.size;
  7936. nc->recv_mbuf.len -= wsm.data - buf;
  7937. /* On last fragmented frame - call user handler and remove data */
  7938. if (wsm.flags & 0x80) {
  7939. wsm.data = p + 1 + sizeof(*sizep);
  7940. wsm.size = *sizep;
  7941. mg_handle_incoming_websocket_frame(nc, &wsm);
  7942. mbuf_remove(&nc->recv_mbuf, 1 + sizeof(*sizep) + *sizep);
  7943. }
  7944. } else {
  7945. /* TODO(lsm): properly handle OOB control frames during defragmentation */
  7946. mg_handle_incoming_websocket_frame(nc, &wsm);
  7947. mbuf_remove(&nc->recv_mbuf, (size_t) frame_len); /* Cleanup frame */
  7948. }
  7949. /* If client closes, close too */
  7950. if ((buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) {
  7951. nc->flags |= MG_F_SEND_AND_CLOSE;
  7952. }
  7953. }
  7954. return ok;
  7955. }
  7956. struct ws_mask_ctx {
  7957. size_t pos; /* zero means unmasked */
  7958. uint32_t mask;
  7959. };
  7960. static uint32_t mg_ws_random_mask(void) {
  7961. uint32_t mask;
  7962. /*
  7963. * The spec requires WS client to generate hard to
  7964. * guess mask keys. From RFC6455, Section 5.3:
  7965. *
  7966. * The unpredictability of the masking key is essential to prevent
  7967. * authors of malicious applications from selecting the bytes that appear on
  7968. * the wire.
  7969. *
  7970. * Hence this feature is essential when the actual end user of this API
  7971. * is untrusted code that wouldn't have access to a lower level net API
  7972. * anyway (e.g. web browsers). Hence this feature is low prio for most
  7973. * mongoose use cases and thus can be disabled, e.g. when porting to a platform
  7974. * that lacks rand().
  7975. */
  7976. #if MG_DISABLE_WS_RANDOM_MASK
  7977. mask = 0xefbeadde; /* generated with a random number generator, I swear */
  7978. #else
  7979. if (sizeof(long) >= 4) {
  7980. mask = (uint32_t) rand();
  7981. } else if (sizeof(long) == 2) {
  7982. mask = (uint32_t) rand() << 16 | (uint32_t) rand();
  7983. }
  7984. #endif
  7985. return mask;
  7986. }
  7987. static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
  7988. struct ws_mask_ctx *ctx) {
  7989. int header_len;
  7990. unsigned char header[10];
  7991. header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : 0x80) + (op & 0x0f);
  7992. if (len < 126) {
  7993. header[1] = (unsigned char) len;
  7994. header_len = 2;
  7995. } else if (len < 65535) {
  7996. uint16_t tmp = htons((uint16_t) len);
  7997. header[1] = 126;
  7998. memcpy(&header[2], &tmp, sizeof(tmp));
  7999. header_len = 4;
  8000. } else {
  8001. uint32_t tmp;
  8002. header[1] = 127;
  8003. tmp = htonl((uint32_t)((uint64_t) len >> 32));
  8004. memcpy(&header[2], &tmp, sizeof(tmp));
  8005. tmp = htonl((uint32_t)(len & 0xffffffff));
  8006. memcpy(&header[6], &tmp, sizeof(tmp));
  8007. header_len = 10;
  8008. }
  8009. /* client connections enable masking */
  8010. if (nc->listener == NULL) {
  8011. header[1] |= 1 << 7; /* set masking flag */
  8012. mg_send(nc, header, header_len);
  8013. ctx->mask = mg_ws_random_mask();
  8014. mg_send(nc, &ctx->mask, sizeof(ctx->mask));
  8015. ctx->pos = nc->send_mbuf.len;
  8016. } else {
  8017. mg_send(nc, header, header_len);
  8018. ctx->pos = 0;
  8019. }
  8020. }
  8021. static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
  8022. size_t i;
  8023. if (ctx->pos == 0) return;
  8024. for (i = 0; i < (mbuf->len - ctx->pos); i++) {
  8025. mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
  8026. }
  8027. }
  8028. void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
  8029. size_t len) {
  8030. struct ws_mask_ctx ctx;
  8031. DBG(("%p %d %d", nc, op, (int) len));
  8032. mg_send_ws_header(nc, op, len, &ctx);
  8033. mg_send(nc, data, len);
  8034. mg_ws_mask_frame(&nc->send_mbuf, &ctx);
  8035. if (op == WEBSOCKET_OP_CLOSE) {
  8036. nc->flags |= MG_F_SEND_AND_CLOSE;
  8037. }
  8038. }
  8039. void mg_send_websocket_framev(struct mg_connection *nc, int op,
  8040. const struct mg_str *strv, int strvcnt) {
  8041. struct ws_mask_ctx ctx;
  8042. int i;
  8043. int len = 0;
  8044. for (i = 0; i < strvcnt; i++) {
  8045. len += strv[i].len;
  8046. }
  8047. mg_send_ws_header(nc, op, len, &ctx);
  8048. for (i = 0; i < strvcnt; i++) {
  8049. mg_send(nc, strv[i].p, strv[i].len);
  8050. }
  8051. mg_ws_mask_frame(&nc->send_mbuf, &ctx);
  8052. if (op == WEBSOCKET_OP_CLOSE) {
  8053. nc->flags |= MG_F_SEND_AND_CLOSE;
  8054. }
  8055. }
  8056. void mg_printf_websocket_frame(struct mg_connection *nc, int op,
  8057. const char *fmt, ...) {
  8058. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  8059. va_list ap;
  8060. int len;
  8061. va_start(ap, fmt);
  8062. if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  8063. mg_send_websocket_frame(nc, op, buf, len);
  8064. }
  8065. va_end(ap);
  8066. if (buf != mem && buf != NULL) {
  8067. MG_FREE(buf);
  8068. }
  8069. }
  8070. MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
  8071. void *ev_data) {
  8072. mg_call(nc, nc->handler, ev, ev_data);
  8073. switch (ev) {
  8074. case MG_EV_RECV:
  8075. do {
  8076. } while (mg_deliver_websocket_data(nc));
  8077. break;
  8078. case MG_EV_POLL:
  8079. /* Ping idle websocket connections */
  8080. {
  8081. time_t now = *(time_t *) ev_data;
  8082. if (nc->flags & MG_F_IS_WEBSOCKET &&
  8083. now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
  8084. mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
  8085. }
  8086. }
  8087. break;
  8088. default:
  8089. break;
  8090. }
  8091. }
  8092. #ifndef MG_EXT_SHA1
  8093. static void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
  8094. const size_t *msg_lens, uint8_t *digest) {
  8095. size_t i;
  8096. cs_sha1_ctx sha_ctx;
  8097. cs_sha1_init(&sha_ctx);
  8098. for (i = 0; i < num_msgs; i++) {
  8099. cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
  8100. }
  8101. cs_sha1_final(digest, &sha_ctx);
  8102. }
  8103. #else
  8104. extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
  8105. const size_t *msg_lens, uint8_t *digest);
  8106. #endif
  8107. MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
  8108. const struct mg_str *key) {
  8109. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8110. const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
  8111. const size_t msg_lens[2] = {key->len, 36};
  8112. unsigned char sha[20];
  8113. char b64_sha[30];
  8114. mg_hash_sha1_v(2, msgs, msg_lens, sha);
  8115. mg_base64_encode(sha, sizeof(sha), b64_sha);
  8116. mg_printf(nc, "%s%s%s",
  8117. "HTTP/1.1 101 Switching Protocols\r\n"
  8118. "Upgrade: websocket\r\n"
  8119. "Connection: Upgrade\r\n"
  8120. "Sec-WebSocket-Accept: ",
  8121. b64_sha, "\r\n\r\n");
  8122. DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
  8123. }
  8124. void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
  8125. const char *host, const char *protocol,
  8126. const char *extra_headers) {
  8127. mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
  8128. NULL);
  8129. }
  8130. void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
  8131. const char *host, const char *protocol,
  8132. const char *extra_headers, const char *user,
  8133. const char *pass) {
  8134. struct mbuf auth;
  8135. char key[25];
  8136. uint32_t nonce[4];
  8137. nonce[0] = mg_ws_random_mask();
  8138. nonce[1] = mg_ws_random_mask();
  8139. nonce[2] = mg_ws_random_mask();
  8140. nonce[3] = mg_ws_random_mask();
  8141. mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
  8142. mbuf_init(&auth, 0);
  8143. if (user != NULL) {
  8144. mg_basic_auth_header(user, pass, &auth);
  8145. }
  8146. /*
  8147. * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
  8148. * broken: it doesn't like zero length to be passed to %.*s
  8149. * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
  8150. * because it handles NULL specially (and incorrectly).
  8151. */
  8152. mg_printf(nc,
  8153. "GET %s HTTP/1.1\r\n"
  8154. "Upgrade: websocket\r\n"
  8155. "Connection: Upgrade\r\n"
  8156. "%.*s"
  8157. "Sec-WebSocket-Version: 13\r\n"
  8158. "Sec-WebSocket-Key: %s\r\n",
  8159. path, (int) auth.len, (auth.buf == NULL ? "" : auth.buf), key);
  8160. /* TODO(mkm): take default hostname from http proto data if host == NULL */
  8161. if (host != MG_WS_NO_HOST_HEADER_MAGIC) {
  8162. mg_printf(nc, "Host: %s\r\n", host);
  8163. }
  8164. if (protocol != NULL) {
  8165. mg_printf(nc, "Sec-WebSocket-Protocol: %s\r\n", protocol);
  8166. }
  8167. if (extra_headers != NULL) {
  8168. mg_printf(nc, "%s", extra_headers);
  8169. }
  8170. mg_printf(nc, "\r\n");
  8171. mbuf_free(&auth);
  8172. }
  8173. void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
  8174. const char *extra_headers) {
  8175. mg_send_websocket_handshake2(nc, path, MG_WS_NO_HOST_HEADER_MAGIC, NULL,
  8176. extra_headers);
  8177. }
  8178. struct mg_connection *mg_connect_ws_opt(struct mg_mgr *mgr,
  8179. mg_event_handler_t ev_handler,
  8180. struct mg_connect_opts opts,
  8181. const char *url, const char *protocol,
  8182. const char *extra_headers) {
  8183. char *user = NULL, *pass = NULL, *addr = NULL;
  8184. const char *path = NULL;
  8185. struct mg_connection *nc =
  8186. mg_connect_http_base(mgr, ev_handler, opts, "ws://", "wss://", url, &path,
  8187. &user, &pass, &addr);
  8188. if (nc != NULL) {
  8189. mg_send_websocket_handshake3(nc, path, addr, protocol, extra_headers, user,
  8190. pass);
  8191. }
  8192. MG_FREE(addr);
  8193. MG_FREE(user);
  8194. MG_FREE(pass);
  8195. return nc;
  8196. }
  8197. struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
  8198. mg_event_handler_t ev_handler,
  8199. const char *url, const char *protocol,
  8200. const char *extra_headers) {
  8201. struct mg_connect_opts opts;
  8202. memset(&opts, 0, sizeof(opts));
  8203. return mg_connect_ws_opt(mgr, ev_handler, opts, url, protocol, extra_headers);
  8204. }
  8205. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
  8206. #ifdef MG_MODULE_LINES
  8207. #line 1 "mongoose/src/util.c"
  8208. #endif
  8209. /*
  8210. * Copyright (c) 2014 Cesanta Software Limited
  8211. * All rights reserved
  8212. */
  8213. /* Amalgamated: #include "common/base64.h" */
  8214. /* Amalgamated: #include "mongoose/src/internal.h" */
  8215. /* Amalgamated: #include "mongoose/src/util.h" */
  8216. /* For platforms with limited libc */
  8217. #ifndef MAX
  8218. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  8219. #endif
  8220. const char *mg_skip(const char *s, const char *end, const char *delims,
  8221. struct mg_str *v) {
  8222. v->p = s;
  8223. while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
  8224. v->len = s - v->p;
  8225. while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
  8226. return s;
  8227. }
  8228. static int lowercase(const char *s) {
  8229. return tolower(*(const unsigned char *) s);
  8230. }
  8231. #if MG_ENABLE_FILESYSTEM
  8232. int mg_stat(const char *path, cs_stat_t *st) {
  8233. #ifdef _WIN32
  8234. wchar_t wpath[MAX_PATH_SIZE];
  8235. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  8236. DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
  8237. return _wstati64(wpath, st);
  8238. #else
  8239. return stat(path, st);
  8240. #endif
  8241. }
  8242. FILE *mg_fopen(const char *path, const char *mode) {
  8243. #ifdef _WIN32
  8244. wchar_t wpath[MAX_PATH_SIZE], wmode[10];
  8245. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  8246. to_wchar(mode, wmode, ARRAY_SIZE(wmode));
  8247. return _wfopen(wpath, wmode);
  8248. #else
  8249. return fopen(path, mode);
  8250. #endif
  8251. }
  8252. int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
  8253. #if defined(_WIN32) && !defined(WINCE)
  8254. wchar_t wpath[MAX_PATH_SIZE];
  8255. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  8256. return _wopen(wpath, flag, mode);
  8257. #else
  8258. return open(path, flag, mode); /* LCOV_EXCL_LINE */
  8259. #endif
  8260. }
  8261. #endif
  8262. void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
  8263. cs_base64_encode(src, src_len, dst);
  8264. }
  8265. int mg_base64_decode(const unsigned char *s, int len, char *dst) {
  8266. return cs_base64_decode(s, len, dst, NULL);
  8267. }
  8268. #if MG_ENABLE_THREADS
  8269. void *mg_start_thread(void *(*f)(void *), void *p) {
  8270. #ifdef WINCE
  8271. return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
  8272. #elif defined(_WIN32)
  8273. return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
  8274. #else
  8275. pthread_t thread_id = (pthread_t) 0;
  8276. pthread_attr_t attr;
  8277. (void) pthread_attr_init(&attr);
  8278. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  8279. #if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
  8280. (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
  8281. #endif
  8282. pthread_create(&thread_id, &attr, f, p);
  8283. pthread_attr_destroy(&attr);
  8284. return (void *) thread_id;
  8285. #endif
  8286. }
  8287. #endif /* MG_ENABLE_THREADS */
  8288. /* Set close-on-exec bit for a given socket. */
  8289. void mg_set_close_on_exec(sock_t sock) {
  8290. #if defined(_WIN32) && !defined(WINCE)
  8291. (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
  8292. #elif defined(__unix__)
  8293. fcntl(sock, F_SETFD, FD_CLOEXEC);
  8294. #else
  8295. (void) sock;
  8296. #endif
  8297. }
  8298. void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
  8299. int flags) {
  8300. int is_v6;
  8301. if (buf == NULL || len <= 0) return;
  8302. memset(buf, 0, len);
  8303. #if MG_ENABLE_IPV6
  8304. is_v6 = sa->sa.sa_family == AF_INET6;
  8305. #else
  8306. is_v6 = 0;
  8307. #endif
  8308. if (flags & MG_SOCK_STRINGIFY_IP) {
  8309. #if MG_ENABLE_IPV6
  8310. const void *addr = NULL;
  8311. char *start = buf;
  8312. socklen_t capacity = len;
  8313. if (!is_v6) {
  8314. addr = &sa->sin.sin_addr;
  8315. } else {
  8316. addr = (void *) &sa->sin6.sin6_addr;
  8317. if (flags & MG_SOCK_STRINGIFY_PORT) {
  8318. *buf = '[';
  8319. start++;
  8320. capacity--;
  8321. }
  8322. }
  8323. if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
  8324. goto cleanup;
  8325. }
  8326. #elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
  8327. /* Only Windoze Vista (and newer) have inet_ntop() */
  8328. char *addr_str = inet_ntoa(sa->sin.sin_addr);
  8329. if (addr_str != NULL) {
  8330. strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
  8331. } else {
  8332. goto cleanup;
  8333. }
  8334. #else
  8335. if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len - 1) == NULL) {
  8336. goto cleanup;
  8337. }
  8338. #endif
  8339. }
  8340. if (flags & MG_SOCK_STRINGIFY_PORT) {
  8341. int port = ntohs(sa->sin.sin_port);
  8342. if (flags & MG_SOCK_STRINGIFY_IP) {
  8343. int buf_len = strlen(buf);
  8344. snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
  8345. port);
  8346. } else {
  8347. snprintf(buf, len, "%d", port);
  8348. }
  8349. }
  8350. return;
  8351. cleanup:
  8352. *buf = '\0';
  8353. }
  8354. void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
  8355. int flags) {
  8356. union socket_address sa;
  8357. memset(&sa, 0, sizeof(sa));
  8358. mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
  8359. mg_sock_addr_to_str(&sa, buf, len, flags);
  8360. }
  8361. #if MG_ENABLE_HEXDUMP
  8362. static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
  8363. int offset) {
  8364. const unsigned char *p = (const unsigned char *) buf;
  8365. char ascii[17] = "";
  8366. int i, idx, n = 0;
  8367. for (i = 0; i < len; i++) {
  8368. idx = i % 16;
  8369. if (idx == 0) {
  8370. if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
  8371. n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
  8372. }
  8373. if (dst_len - n < 0) {
  8374. return n;
  8375. }
  8376. n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
  8377. ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
  8378. ascii[idx + 1] = '\0';
  8379. }
  8380. while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " ");
  8381. n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
  8382. return n;
  8383. }
  8384. int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
  8385. return mg_hexdump_n(buf, len, dst, dst_len, 0);
  8386. }
  8387. void mg_hexdumpf(FILE *fp, const void *buf, int len) {
  8388. char tmp[80];
  8389. int offset = 0, n;
  8390. while (len > 0) {
  8391. n = (len < 16 ? len : 16);
  8392. mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
  8393. fputs(tmp, fp);
  8394. offset += n;
  8395. len -= n;
  8396. }
  8397. }
  8398. void mg_hexdump_connection(struct mg_connection *nc, const char *path,
  8399. const void *buf, int num_bytes, int ev) {
  8400. FILE *fp = NULL;
  8401. char *hexbuf, src[60], dst[60];
  8402. int buf_size = num_bytes * 5 + 100;
  8403. if (strcmp(path, "-") == 0) {
  8404. fp = stdout;
  8405. } else if (strcmp(path, "--") == 0) {
  8406. fp = stderr;
  8407. #if MG_ENABLE_FILESYSTEM
  8408. } else {
  8409. fp = mg_fopen(path, "a");
  8410. #endif
  8411. }
  8412. if (fp == NULL) return;
  8413. mg_conn_addr_to_str(nc, src, sizeof(src),
  8414. MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
  8415. mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
  8416. MG_SOCK_STRINGIFY_PORT |
  8417. MG_SOCK_STRINGIFY_REMOTE);
  8418. fprintf(
  8419. fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc, src,
  8420. ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND
  8421. ? "->"
  8422. : ev == MG_EV_ACCEPT
  8423. ? "<A"
  8424. : ev == MG_EV_CONNECT ? "C>" : "XX",
  8425. dst, num_bytes);
  8426. if (num_bytes > 0 && (hexbuf = (char *) MG_MALLOC(buf_size)) != NULL) {
  8427. mg_hexdump(buf, num_bytes, hexbuf, buf_size);
  8428. fprintf(fp, "%s", hexbuf);
  8429. MG_FREE(hexbuf);
  8430. }
  8431. if (fp != stdin && fp != stdout) fclose(fp);
  8432. }
  8433. #endif
  8434. int mg_is_big_endian(void) {
  8435. static const int n = 1;
  8436. /* TODO(mkm) use compiletime check with 4-byte char literal */
  8437. return ((char *) &n)[0] == 0;
  8438. }
  8439. const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
  8440. struct mg_str *eq_val) {
  8441. if (list == NULL || *list == '\0') {
  8442. /* End of the list */
  8443. list = NULL;
  8444. } else {
  8445. val->p = list;
  8446. if ((list = strchr(val->p, ',')) != NULL) {
  8447. /* Comma found. Store length and shift the list ptr */
  8448. val->len = list - val->p;
  8449. list++;
  8450. } else {
  8451. /* This value is the last one */
  8452. list = val->p + strlen(val->p);
  8453. val->len = list - val->p;
  8454. }
  8455. if (eq_val != NULL) {
  8456. /* Value has form "x=y", adjust pointers and lengths */
  8457. /* so that val points to "x", and eq_val points to "y". */
  8458. eq_val->len = 0;
  8459. eq_val->p = (const char *) memchr(val->p, '=', val->len);
  8460. if (eq_val->p != NULL) {
  8461. eq_val->p++; /* Skip over '=' character */
  8462. eq_val->len = val->p + val->len - eq_val->p;
  8463. val->len = (eq_val->p - val->p) - 1;
  8464. }
  8465. }
  8466. }
  8467. return list;
  8468. }
  8469. int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
  8470. const char *or_str;
  8471. size_t len, i = 0, j = 0;
  8472. int res;
  8473. if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL) {
  8474. struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
  8475. res = mg_match_prefix_n(pstr, str);
  8476. if (res > 0) return res;
  8477. pstr.p = or_str + 1;
  8478. pstr.len = (pattern.p + pattern.len) - (or_str + 1);
  8479. return mg_match_prefix_n(pstr, str);
  8480. }
  8481. for (; i < pattern.len; i++, j++) {
  8482. if (pattern.p[i] == '?' && j != str.len) {
  8483. continue;
  8484. } else if (pattern.p[i] == '$') {
  8485. return j == str.len ? (int) j : -1;
  8486. } else if (pattern.p[i] == '*') {
  8487. i++;
  8488. if (pattern.p[i] == '*') {
  8489. i++;
  8490. len = str.len - j;
  8491. } else {
  8492. len = 0;
  8493. while (j + len != str.len && str.p[j + len] != '/') {
  8494. len++;
  8495. }
  8496. }
  8497. if (i == pattern.len) {
  8498. return j + len;
  8499. }
  8500. do {
  8501. const struct mg_str pstr = {pattern.p + i, pattern.len - i};
  8502. const struct mg_str sstr = {str.p + j + len, str.len - j - len};
  8503. res = mg_match_prefix_n(pstr, sstr);
  8504. } while (res == -1 && len-- > 0);
  8505. return res == -1 ? -1 : (int) (j + res + len);
  8506. } else if (lowercase(&pattern.p[i]) != lowercase(&str.p[j])) {
  8507. return -1;
  8508. }
  8509. }
  8510. return j;
  8511. }
  8512. int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
  8513. const struct mg_str pstr = {pattern, (size_t) pattern_len};
  8514. return mg_match_prefix_n(pstr, mg_mk_str(str));
  8515. }
  8516. DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
  8517. #ifndef WINCE
  8518. return errno;
  8519. #else
  8520. /* TODO(alashkin): translate error codes? */
  8521. return GetLastError();
  8522. #endif
  8523. }
  8524. void mg_mbuf_append_base64_putc(char ch, void *user_data) {
  8525. struct mbuf *mbuf = (struct mbuf *) user_data;
  8526. mbuf_append(mbuf, &ch, sizeof(ch));
  8527. }
  8528. void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
  8529. struct cs_base64_ctx ctx;
  8530. cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
  8531. cs_base64_update(&ctx, (const char *) data, len);
  8532. cs_base64_finish(&ctx);
  8533. }
  8534. void mg_basic_auth_header(const char *user, const char *pass,
  8535. struct mbuf *buf) {
  8536. const char *header_prefix = "Authorization: Basic ";
  8537. const char *header_suffix = "\r\n";
  8538. struct cs_base64_ctx ctx;
  8539. cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
  8540. mbuf_append(buf, header_prefix, strlen(header_prefix));
  8541. cs_base64_update(&ctx, user, strlen(user));
  8542. if (pass != NULL) {
  8543. cs_base64_update(&ctx, ":", 1);
  8544. cs_base64_update(&ctx, pass, strlen(pass));
  8545. }
  8546. cs_base64_finish(&ctx);
  8547. mbuf_append(buf, header_suffix, strlen(header_suffix));
  8548. }
  8549. #ifdef MG_MODULE_LINES
  8550. #line 1 "mongoose/src/mqtt.c"
  8551. #endif
  8552. /*
  8553. * Copyright (c) 2014 Cesanta Software Limited
  8554. * All rights reserved
  8555. */
  8556. #if MG_ENABLE_MQTT
  8557. #include <string.h>
  8558. /* Amalgamated: #include "mongoose/src/internal.h" */
  8559. /* Amalgamated: #include "mongoose/src/mqtt.h" */
  8560. static uint16_t getu16(const char *p) {
  8561. const uint8_t *up = (const uint8_t *) p;
  8562. return (up[0] << 8) + up[1];
  8563. }
  8564. static const char *scanto(const char *p, struct mg_str *s) {
  8565. s->len = getu16(p);
  8566. s->p = p + 2;
  8567. return s->p + s->len;
  8568. }
  8569. MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
  8570. uint8_t header;
  8571. size_t len = 0;
  8572. int cmd;
  8573. const char *p = &io->buf[1], *end;
  8574. if (io->len < 2) return -1;
  8575. header = io->buf[0];
  8576. cmd = header >> 4;
  8577. /* decode mqtt variable length */
  8578. do {
  8579. len += (*p & 127) << 7 * (p - &io->buf[1]);
  8580. } while ((*p++ & 128) != 0 && ((size_t)(p - io->buf) <= io->len));
  8581. end = p + len;
  8582. if (end > io->buf + io->len + 1) {
  8583. return -1;
  8584. }
  8585. mm->cmd = cmd;
  8586. mm->qos = MG_MQTT_GET_QOS(header);
  8587. switch (cmd) {
  8588. case MG_MQTT_CMD_CONNECT: {
  8589. p = scanto(p, &mm->protocol_name);
  8590. mm->protocol_version = *(uint8_t *) p++;
  8591. mm->connect_flags = *(uint8_t *) p++;
  8592. mm->keep_alive_timer = getu16(p);
  8593. p += 2;
  8594. if (p < end) p = scanto(p, &mm->client_id);
  8595. if (p < end && (mm->connect_flags & MG_MQTT_HAS_WILL))
  8596. p = scanto(p, &mm->will_topic);
  8597. if (p < end && (mm->connect_flags & MG_MQTT_HAS_WILL))
  8598. p = scanto(p, &mm->will_message);
  8599. if (p < end && (mm->connect_flags & MG_MQTT_HAS_USER_NAME))
  8600. p = scanto(p, &mm->user_name);
  8601. if (p < end && (mm->connect_flags & MG_MQTT_HAS_PASSWORD))
  8602. p = scanto(p, &mm->password);
  8603. LOG(LL_DEBUG,
  8604. ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
  8605. "will_msg [%.*s] user_name [%.*s] password [%.*s]",
  8606. len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
  8607. (int) mm->protocol_name.len, mm->protocol_name.p,
  8608. (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
  8609. mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
  8610. (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
  8611. mm->password.p));
  8612. break;
  8613. }
  8614. case MG_MQTT_CMD_CONNACK:
  8615. mm->connack_ret_code = p[1];
  8616. break;
  8617. case MG_MQTT_CMD_PUBACK:
  8618. case MG_MQTT_CMD_PUBREC:
  8619. case MG_MQTT_CMD_PUBREL:
  8620. case MG_MQTT_CMD_PUBCOMP:
  8621. case MG_MQTT_CMD_SUBACK:
  8622. mm->message_id = getu16(p);
  8623. break;
  8624. case MG_MQTT_CMD_PUBLISH: {
  8625. if (MG_MQTT_GET_QOS(header) > 0) {
  8626. mm->message_id = getu16(p);
  8627. p += 2;
  8628. }
  8629. p = scanto(p, &mm->topic);
  8630. mm->payload.p = p;
  8631. mm->payload.len = end - p;
  8632. break;
  8633. }
  8634. case MG_MQTT_CMD_SUBSCRIBE:
  8635. mm->message_id = getu16(p);
  8636. p += 2;
  8637. /*
  8638. * topic expressions are left in the payload and can be parsed with
  8639. * `mg_mqtt_next_subscribe_topic`
  8640. */
  8641. mm->payload.p = p;
  8642. mm->payload.len = end - p;
  8643. break;
  8644. default:
  8645. /* Unhandled command */
  8646. break;
  8647. }
  8648. return end - io->buf;
  8649. }
  8650. static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data) {
  8651. int len;
  8652. struct mbuf *io = &nc->recv_mbuf;
  8653. struct mg_mqtt_message mm;
  8654. memset(&mm, 0, sizeof(mm));
  8655. nc->handler(nc, ev, ev_data);
  8656. switch (ev) {
  8657. case MG_EV_RECV:
  8658. len = parse_mqtt(io, &mm);
  8659. if (len == -1) break; /* not fully buffered */
  8660. nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm);
  8661. mbuf_remove(io, len);
  8662. break;
  8663. }
  8664. }
  8665. static void mg_mqtt_proto_data_destructor(void *proto_data) {
  8666. MG_FREE(proto_data);
  8667. }
  8668. void mg_set_protocol_mqtt(struct mg_connection *nc) {
  8669. nc->proto_handler = mqtt_handler;
  8670. nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
  8671. nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
  8672. }
  8673. void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
  8674. static struct mg_send_mqtt_handshake_opts opts;
  8675. mg_send_mqtt_handshake_opt(nc, client_id, opts);
  8676. }
  8677. void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
  8678. struct mg_send_mqtt_handshake_opts opts) {
  8679. uint8_t header = MG_MQTT_CMD_CONNECT << 4;
  8680. uint8_t rem_len;
  8681. uint16_t keep_alive;
  8682. uint16_t len;
  8683. struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
  8684. /*
  8685. * 9: version_header(len, magic_string, version_number), 1: flags, 2:
  8686. * keep-alive timer,
  8687. * 2: client_identifier_len, n: client_id
  8688. */
  8689. rem_len = 9 + 1 + 2 + 2 + (uint8_t) strlen(client_id);
  8690. if (opts.user_name != NULL) {
  8691. opts.flags |= MG_MQTT_HAS_USER_NAME;
  8692. rem_len += (uint8_t) strlen(opts.user_name) + 2;
  8693. }
  8694. if (opts.password != NULL) {
  8695. opts.flags |= MG_MQTT_HAS_PASSWORD;
  8696. rem_len += (uint8_t) strlen(opts.password) + 2;
  8697. }
  8698. if (opts.will_topic != NULL && opts.will_message != NULL) {
  8699. opts.flags |= MG_MQTT_HAS_WILL;
  8700. rem_len += (uint8_t) strlen(opts.will_topic) + 2;
  8701. rem_len += (uint8_t) strlen(opts.will_message) + 2;
  8702. }
  8703. mg_send(nc, &header, 1);
  8704. mg_send(nc, &rem_len, 1);
  8705. mg_send(nc, "\00\06MQIsdp\03", 9);
  8706. mg_send(nc, &opts.flags, 1);
  8707. if (opts.keep_alive == 0) {
  8708. opts.keep_alive = 60;
  8709. }
  8710. keep_alive = htons(opts.keep_alive);
  8711. mg_send(nc, &keep_alive, 2);
  8712. len = htons((uint16_t) strlen(client_id));
  8713. mg_send(nc, &len, 2);
  8714. mg_send(nc, client_id, strlen(client_id));
  8715. if (opts.flags & MG_MQTT_HAS_WILL) {
  8716. len = htons((uint16_t) strlen(opts.will_topic));
  8717. mg_send(nc, &len, 2);
  8718. mg_send(nc, opts.will_topic, strlen(opts.will_topic));
  8719. len = htons((uint16_t) strlen(opts.will_message));
  8720. mg_send(nc, &len, 2);
  8721. mg_send(nc, opts.will_message, strlen(opts.will_message));
  8722. }
  8723. if (opts.flags & MG_MQTT_HAS_USER_NAME) {
  8724. len = htons((uint16_t) strlen(opts.user_name));
  8725. mg_send(nc, &len, 2);
  8726. mg_send(nc, opts.user_name, strlen(opts.user_name));
  8727. }
  8728. if (opts.flags & MG_MQTT_HAS_PASSWORD) {
  8729. len = htons((uint16_t) strlen(opts.password));
  8730. mg_send(nc, &len, 2);
  8731. mg_send(nc, opts.password, strlen(opts.password));
  8732. }
  8733. if (pd != NULL) {
  8734. pd->keep_alive = opts.keep_alive;
  8735. }
  8736. }
  8737. static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
  8738. uint8_t flags, size_t len) {
  8739. size_t off = nc->send_mbuf.len - len;
  8740. uint8_t header = cmd << 4 | (uint8_t) flags;
  8741. uint8_t buf[1 + sizeof(size_t)];
  8742. uint8_t *vlen = &buf[1];
  8743. assert(nc->send_mbuf.len >= len);
  8744. buf[0] = header;
  8745. /* mqtt variable length encoding */
  8746. do {
  8747. *vlen = len % 0x80;
  8748. len /= 0x80;
  8749. if (len > 0) *vlen |= 0x80;
  8750. vlen++;
  8751. } while (len > 0);
  8752. mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
  8753. }
  8754. void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
  8755. uint16_t message_id, int flags, const void *data,
  8756. size_t len) {
  8757. size_t old_len = nc->send_mbuf.len;
  8758. uint16_t topic_len = htons((uint16_t) strlen(topic));
  8759. uint16_t message_id_net = htons(message_id);
  8760. mg_send(nc, &topic_len, 2);
  8761. mg_send(nc, topic, strlen(topic));
  8762. if (MG_MQTT_GET_QOS(flags) > 0) {
  8763. mg_send(nc, &message_id_net, 2);
  8764. }
  8765. mg_send(nc, data, len);
  8766. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
  8767. nc->send_mbuf.len - old_len);
  8768. }
  8769. void mg_mqtt_subscribe(struct mg_connection *nc,
  8770. const struct mg_mqtt_topic_expression *topics,
  8771. size_t topics_len, uint16_t message_id) {
  8772. size_t old_len = nc->send_mbuf.len;
  8773. uint16_t message_id_n = htons(message_id);
  8774. size_t i;
  8775. mg_send(nc, (char *) &message_id_n, 2);
  8776. for (i = 0; i < topics_len; i++) {
  8777. uint16_t topic_len_n = htons((uint16_t) strlen(topics[i].topic));
  8778. mg_send(nc, &topic_len_n, 2);
  8779. mg_send(nc, topics[i].topic, strlen(topics[i].topic));
  8780. mg_send(nc, &topics[i].qos, 1);
  8781. }
  8782. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
  8783. nc->send_mbuf.len - old_len);
  8784. }
  8785. int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
  8786. struct mg_str *topic, uint8_t *qos, int pos) {
  8787. unsigned char *buf = (unsigned char *) msg->payload.p + pos;
  8788. if ((size_t) pos >= msg->payload.len) {
  8789. return -1;
  8790. }
  8791. topic->len = buf[0] << 8 | buf[1];
  8792. topic->p = (char *) buf + 2;
  8793. *qos = buf[2 + topic->len];
  8794. return pos + 2 + topic->len + 1;
  8795. }
  8796. void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
  8797. size_t topics_len, uint16_t message_id) {
  8798. size_t old_len = nc->send_mbuf.len;
  8799. uint16_t message_id_n = htons(message_id);
  8800. size_t i;
  8801. mg_send(nc, (char *) &message_id_n, 2);
  8802. for (i = 0; i < topics_len; i++) {
  8803. uint16_t topic_len_n = htons((uint16_t) strlen(topics[i]));
  8804. mg_send(nc, &topic_len_n, 2);
  8805. mg_send(nc, topics[i], strlen(topics[i]));
  8806. }
  8807. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
  8808. nc->send_mbuf.len - old_len);
  8809. }
  8810. void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
  8811. uint8_t unused = 0;
  8812. mg_send(nc, &unused, 1);
  8813. mg_send(nc, &return_code, 1);
  8814. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
  8815. }
  8816. /*
  8817. * Sends a command which contains only a `message_id` and a QoS level of 1.
  8818. *
  8819. * Helper function.
  8820. */
  8821. static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
  8822. uint16_t message_id) {
  8823. uint16_t message_id_net = htons(message_id);
  8824. mg_send(nc, &message_id_net, 2);
  8825. mg_mqtt_prepend_header(nc, cmd, MG_MQTT_QOS(1), 2);
  8826. }
  8827. void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
  8828. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
  8829. }
  8830. void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
  8831. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
  8832. }
  8833. void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
  8834. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
  8835. }
  8836. void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
  8837. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
  8838. }
  8839. void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
  8840. uint16_t message_id) {
  8841. size_t i;
  8842. uint16_t message_id_net = htons(message_id);
  8843. mg_send(nc, &message_id_net, 2);
  8844. for (i = 0; i < qoss_len; i++) {
  8845. mg_send(nc, &qoss[i], 1);
  8846. }
  8847. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
  8848. }
  8849. void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
  8850. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
  8851. }
  8852. void mg_mqtt_ping(struct mg_connection *nc) {
  8853. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
  8854. }
  8855. void mg_mqtt_pong(struct mg_connection *nc) {
  8856. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
  8857. }
  8858. void mg_mqtt_disconnect(struct mg_connection *nc) {
  8859. mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
  8860. }
  8861. #endif /* MG_ENABLE_MQTT */
  8862. #ifdef MG_MODULE_LINES
  8863. #line 1 "mongoose/src/mqtt_server.c"
  8864. #endif
  8865. /*
  8866. * Copyright (c) 2014 Cesanta Software Limited
  8867. * All rights reserved
  8868. */
  8869. /* Amalgamated: #include "mongoose/src/internal.h" */
  8870. /* Amalgamated: #include "mongoose/src/mqtt-server.h" */
  8871. #if MG_ENABLE_MQTT_BROKER
  8872. static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
  8873. struct mg_mqtt_session *s,
  8874. struct mg_connection *nc) {
  8875. s->brk = brk;
  8876. s->subscriptions = NULL;
  8877. s->num_subscriptions = 0;
  8878. s->nc = nc;
  8879. }
  8880. static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
  8881. LIST_INSERT_HEAD(&s->brk->sessions, s, link);
  8882. }
  8883. static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
  8884. LIST_REMOVE(s, link);
  8885. }
  8886. static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
  8887. size_t i;
  8888. for (i = 0; i < s->num_subscriptions; i++) {
  8889. MG_FREE((void *) s->subscriptions[i].topic);
  8890. }
  8891. MG_FREE(s->subscriptions);
  8892. MG_FREE(s);
  8893. }
  8894. static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
  8895. mg_mqtt_remove_session(s);
  8896. mg_mqtt_destroy_session(s);
  8897. }
  8898. void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
  8899. LIST_INIT(&brk->sessions);
  8900. brk->user_data = user_data;
  8901. }
  8902. static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
  8903. struct mg_connection *nc) {
  8904. struct mg_mqtt_session *s = (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
  8905. if (s == NULL) {
  8906. /* LCOV_EXCL_START */
  8907. mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
  8908. return;
  8909. /* LCOV_EXCL_STOP */
  8910. }
  8911. /* TODO(mkm): check header (magic and version) */
  8912. mg_mqtt_session_init(brk, s, nc);
  8913. s->user_data = nc->user_data;
  8914. nc->user_data = s;
  8915. mg_mqtt_add_session(s);
  8916. mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
  8917. }
  8918. static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
  8919. struct mg_mqtt_message *msg) {
  8920. struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->user_data;
  8921. uint8_t qoss[512];
  8922. size_t qoss_len = 0;
  8923. struct mg_str topic;
  8924. uint8_t qos;
  8925. int pos;
  8926. struct mg_mqtt_topic_expression *te;
  8927. for (pos = 0;
  8928. (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
  8929. qoss[qoss_len++] = qos;
  8930. }
  8931. ss->subscriptions = (struct mg_mqtt_topic_expression *) MG_REALLOC(
  8932. ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len);
  8933. for (pos = 0;
  8934. (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
  8935. ss->num_subscriptions++) {
  8936. te = &ss->subscriptions[ss->num_subscriptions];
  8937. te->topic = (char *) MG_MALLOC(topic.len + 1);
  8938. te->qos = qos;
  8939. strncpy((char *) te->topic, topic.p, topic.len + 1);
  8940. }
  8941. mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id);
  8942. }
  8943. /*
  8944. * Matches a topic against a topic expression
  8945. *
  8946. * See http://goo.gl/iWk21X
  8947. *
  8948. * Returns 1 if it matches; 0 otherwise.
  8949. */
  8950. static int mg_mqtt_match_topic_expression(const char *exp,
  8951. const struct mg_str *topic) {
  8952. /* TODO(mkm): implement real matching */
  8953. size_t len = strlen(exp);
  8954. if (strchr(exp, '#')) {
  8955. len -= 2;
  8956. if (topic->len < len) {
  8957. len = topic->len;
  8958. }
  8959. }
  8960. return strncmp(topic->p, exp, len) == 0;
  8961. }
  8962. static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
  8963. struct mg_mqtt_message *msg) {
  8964. struct mg_mqtt_session *s;
  8965. size_t i;
  8966. for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
  8967. for (i = 0; i < s->num_subscriptions; i++) {
  8968. if (mg_mqtt_match_topic_expression(s->subscriptions[i].topic,
  8969. &msg->topic)) {
  8970. char buf[100], *p = buf;
  8971. mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
  8972. msg->topic.p);
  8973. if (p == NULL) {
  8974. return;
  8975. }
  8976. mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
  8977. if (p != buf) {
  8978. MG_FREE(p);
  8979. }
  8980. break;
  8981. }
  8982. }
  8983. }
  8984. }
  8985. void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
  8986. struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
  8987. struct mg_mqtt_broker *brk;
  8988. if (nc->listener) {
  8989. brk = (struct mg_mqtt_broker *) nc->listener->user_data;
  8990. } else {
  8991. brk = (struct mg_mqtt_broker *) nc->user_data;
  8992. }
  8993. switch (ev) {
  8994. case MG_EV_ACCEPT:
  8995. mg_set_protocol_mqtt(nc);
  8996. nc->user_data = NULL; /* Clear up the inherited pointer to broker */
  8997. break;
  8998. case MG_EV_MQTT_CONNECT:
  8999. mg_mqtt_broker_handle_connect(brk, nc);
  9000. break;
  9001. case MG_EV_MQTT_SUBSCRIBE:
  9002. mg_mqtt_broker_handle_subscribe(nc, msg);
  9003. break;
  9004. case MG_EV_MQTT_PUBLISH:
  9005. mg_mqtt_broker_handle_publish(brk, msg);
  9006. break;
  9007. case MG_EV_CLOSE:
  9008. if (nc->listener && nc->user_data != NULL) {
  9009. mg_mqtt_close_session((struct mg_mqtt_session *) nc->user_data);
  9010. }
  9011. break;
  9012. }
  9013. }
  9014. struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
  9015. struct mg_mqtt_session *s) {
  9016. return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
  9017. }
  9018. #endif /* MG_ENABLE_MQTT_BROKER */
  9019. #ifdef MG_MODULE_LINES
  9020. #line 1 "mongoose/src/dns.c"
  9021. #endif
  9022. /*
  9023. * Copyright (c) 2014 Cesanta Software Limited
  9024. * All rights reserved
  9025. */
  9026. #if MG_ENABLE_DNS
  9027. /* Amalgamated: #include "mongoose/src/internal.h" */
  9028. /* Amalgamated: #include "mongoose/src/dns.h" */
  9029. static int mg_dns_tid = 0xa0;
  9030. struct mg_dns_header {
  9031. uint16_t transaction_id;
  9032. uint16_t flags;
  9033. uint16_t num_questions;
  9034. uint16_t num_answers;
  9035. uint16_t num_authority_prs;
  9036. uint16_t num_other_prs;
  9037. };
  9038. struct mg_dns_resource_record *mg_dns_next_record(
  9039. struct mg_dns_message *msg, int query,
  9040. struct mg_dns_resource_record *prev) {
  9041. struct mg_dns_resource_record *rr;
  9042. for (rr = (prev == NULL ? msg->answers : prev + 1);
  9043. rr - msg->answers < msg->num_answers; rr++) {
  9044. if (rr->rtype == query) {
  9045. return rr;
  9046. }
  9047. }
  9048. return NULL;
  9049. }
  9050. int mg_dns_parse_record_data(struct mg_dns_message *msg,
  9051. struct mg_dns_resource_record *rr, void *data,
  9052. size_t data_len) {
  9053. switch (rr->rtype) {
  9054. case MG_DNS_A_RECORD:
  9055. if (data_len < sizeof(struct in_addr)) {
  9056. return -1;
  9057. }
  9058. if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
  9059. return -1;
  9060. }
  9061. memcpy(data, rr->rdata.p, data_len);
  9062. return 0;
  9063. #if MG_ENABLE_IPV6
  9064. case MG_DNS_AAAA_RECORD:
  9065. if (data_len < sizeof(struct in6_addr)) {
  9066. return -1; /* LCOV_EXCL_LINE */
  9067. }
  9068. memcpy(data, rr->rdata.p, data_len);
  9069. return 0;
  9070. #endif
  9071. case MG_DNS_CNAME_RECORD:
  9072. mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
  9073. return 0;
  9074. }
  9075. return -1;
  9076. }
  9077. int mg_dns_insert_header(struct mbuf *io, size_t pos,
  9078. struct mg_dns_message *msg) {
  9079. struct mg_dns_header header;
  9080. memset(&header, 0, sizeof(header));
  9081. header.transaction_id = msg->transaction_id;
  9082. header.flags = htons(msg->flags);
  9083. header.num_questions = htons(msg->num_questions);
  9084. header.num_answers = htons(msg->num_answers);
  9085. return mbuf_insert(io, pos, &header, sizeof(header));
  9086. }
  9087. int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
  9088. unsigned char *begin, *end;
  9089. struct mg_dns_resource_record *last_q;
  9090. if (msg->num_questions <= 0) return 0;
  9091. begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
  9092. last_q = &msg->questions[msg->num_questions - 1];
  9093. end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
  9094. return mbuf_append(io, begin, end - begin);
  9095. }
  9096. int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
  9097. const char *s;
  9098. unsigned char n;
  9099. size_t pos = io->len;
  9100. do {
  9101. if ((s = strchr(name, '.')) == NULL) {
  9102. s = name + len;
  9103. }
  9104. if (s - name > 127) {
  9105. return -1; /* TODO(mkm) cover */
  9106. }
  9107. n = s - name; /* chunk length */
  9108. mbuf_append(io, &n, 1); /* send length */
  9109. mbuf_append(io, name, n);
  9110. if (*s == '.') {
  9111. n++;
  9112. }
  9113. name += n;
  9114. len -= n;
  9115. } while (*s != '\0');
  9116. mbuf_append(io, "\0", 1); /* Mark end of host name */
  9117. return io->len - pos;
  9118. }
  9119. int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
  9120. const char *name, size_t nlen, const void *rdata,
  9121. size_t rlen) {
  9122. size_t pos = io->len;
  9123. uint16_t u16;
  9124. uint32_t u32;
  9125. if (rr->kind == MG_DNS_INVALID_RECORD) {
  9126. return -1; /* LCOV_EXCL_LINE */
  9127. }
  9128. if (mg_dns_encode_name(io, name, nlen) == -1) {
  9129. return -1;
  9130. }
  9131. u16 = htons(rr->rtype);
  9132. mbuf_append(io, &u16, 2);
  9133. u16 = htons(rr->rclass);
  9134. mbuf_append(io, &u16, 2);
  9135. if (rr->kind == MG_DNS_ANSWER) {
  9136. u32 = htonl(rr->ttl);
  9137. mbuf_append(io, &u32, 4);
  9138. if (rr->rtype == MG_DNS_CNAME_RECORD) {
  9139. int clen;
  9140. /* fill size after encoding */
  9141. size_t off = io->len;
  9142. mbuf_append(io, &u16, 2);
  9143. if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
  9144. return -1;
  9145. }
  9146. u16 = clen;
  9147. io->buf[off] = u16 >> 8;
  9148. io->buf[off + 1] = u16 & 0xff;
  9149. } else {
  9150. u16 = htons((uint16_t) rlen);
  9151. mbuf_append(io, &u16, 2);
  9152. mbuf_append(io, rdata, rlen);
  9153. }
  9154. }
  9155. return io->len - pos;
  9156. }
  9157. void mg_send_dns_query(struct mg_connection *nc, const char *name,
  9158. int query_type) {
  9159. struct mg_dns_message *msg =
  9160. (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
  9161. struct mbuf pkt;
  9162. struct mg_dns_resource_record *rr = &msg->questions[0];
  9163. DBG(("%s %d", name, query_type));
  9164. mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
  9165. msg->transaction_id = ++mg_dns_tid;
  9166. msg->flags = 0x100;
  9167. msg->num_questions = 1;
  9168. mg_dns_insert_header(&pkt, 0, msg);
  9169. rr->rtype = query_type;
  9170. rr->rclass = 1; /* Class: inet */
  9171. rr->kind = MG_DNS_QUESTION;
  9172. if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
  9173. /* TODO(mkm): return an error code */
  9174. goto cleanup; /* LCOV_EXCL_LINE */
  9175. }
  9176. /* TCP DNS requires messages to be prefixed with len */
  9177. if (!(nc->flags & MG_F_UDP)) {
  9178. uint16_t len = htons((uint16_t) pkt.len);
  9179. mbuf_insert(&pkt, 0, &len, 2);
  9180. }
  9181. mg_send(nc, pkt.buf, pkt.len);
  9182. mbuf_free(&pkt);
  9183. cleanup:
  9184. MG_FREE(msg);
  9185. }
  9186. static unsigned char *mg_parse_dns_resource_record(
  9187. unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
  9188. int reply) {
  9189. unsigned char *name = data;
  9190. int chunk_len, data_len;
  9191. while (data < end && (chunk_len = *data)) {
  9192. if (((unsigned char *) data)[0] & 0xc0) {
  9193. data += 1;
  9194. break;
  9195. }
  9196. data += chunk_len + 1;
  9197. }
  9198. if (data > end - 5) {
  9199. return NULL;
  9200. }
  9201. rr->name.p = (char *) name;
  9202. rr->name.len = data - name + 1;
  9203. data++;
  9204. rr->rtype = data[0] << 8 | data[1];
  9205. data += 2;
  9206. rr->rclass = data[0] << 8 | data[1];
  9207. data += 2;
  9208. rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
  9209. if (reply) {
  9210. if (data >= end - 6) {
  9211. return NULL;
  9212. }
  9213. rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
  9214. data[2] << 8 | data[3];
  9215. data += 4;
  9216. data_len = *data << 8 | *(data + 1);
  9217. data += 2;
  9218. rr->rdata.p = (char *) data;
  9219. rr->rdata.len = data_len;
  9220. data += data_len;
  9221. }
  9222. return data;
  9223. }
  9224. int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
  9225. struct mg_dns_header *header = (struct mg_dns_header *) buf;
  9226. unsigned char *data = (unsigned char *) buf + sizeof(*header);
  9227. unsigned char *end = (unsigned char *) buf + len;
  9228. int i;
  9229. memset(msg, 0, sizeof(*msg));
  9230. msg->pkt.p = buf;
  9231. msg->pkt.len = len;
  9232. if (len < (int) sizeof(*header)) return -1;
  9233. msg->transaction_id = header->transaction_id;
  9234. msg->flags = ntohs(header->flags);
  9235. msg->num_questions = ntohs(header->num_questions);
  9236. if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
  9237. msg->num_questions = (int) ARRAY_SIZE(msg->questions);
  9238. }
  9239. msg->num_answers = ntohs(header->num_answers);
  9240. if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
  9241. msg->num_answers = (int) ARRAY_SIZE(msg->answers);
  9242. }
  9243. for (i = 0; i < msg->num_questions; i++) {
  9244. data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
  9245. if (data == NULL) return -1;
  9246. }
  9247. for (i = 0; i < msg->num_answers; i++) {
  9248. data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
  9249. if (data == NULL) return -1;
  9250. }
  9251. return 0;
  9252. }
  9253. size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
  9254. char *dst, int dst_len) {
  9255. int chunk_len;
  9256. char *old_dst = dst;
  9257. const unsigned char *data = (unsigned char *) name->p;
  9258. const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
  9259. if (data >= end) {
  9260. return 0;
  9261. }
  9262. while ((chunk_len = *data++)) {
  9263. int leeway = dst_len - (dst - old_dst);
  9264. if (data >= end) {
  9265. return 0;
  9266. }
  9267. if (chunk_len & 0xc0) {
  9268. uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
  9269. if (off >= msg->pkt.len) {
  9270. return 0;
  9271. }
  9272. data = (unsigned char *) msg->pkt.p + off;
  9273. continue;
  9274. }
  9275. if (chunk_len > leeway) {
  9276. chunk_len = leeway;
  9277. }
  9278. if (data + chunk_len >= end) {
  9279. return 0;
  9280. }
  9281. memcpy(dst, data, chunk_len);
  9282. data += chunk_len;
  9283. dst += chunk_len;
  9284. leeway -= chunk_len;
  9285. if (leeway == 0) {
  9286. return dst - old_dst;
  9287. }
  9288. *dst++ = '.';
  9289. }
  9290. if (dst != old_dst) {
  9291. *--dst = 0;
  9292. }
  9293. return dst - old_dst;
  9294. }
  9295. static void dns_handler(struct mg_connection *nc, int ev, void *ev_data) {
  9296. struct mbuf *io = &nc->recv_mbuf;
  9297. struct mg_dns_message msg;
  9298. /* Pass low-level events to the user handler */
  9299. nc->handler(nc, ev, ev_data);
  9300. switch (ev) {
  9301. case MG_EV_RECV:
  9302. if (!(nc->flags & MG_F_UDP)) {
  9303. mbuf_remove(&nc->recv_mbuf, 2);
  9304. }
  9305. if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
  9306. /* reply + recursion allowed + format error */
  9307. memset(&msg, 0, sizeof(msg));
  9308. msg.flags = 0x8081;
  9309. mg_dns_insert_header(io, 0, &msg);
  9310. if (!(nc->flags & MG_F_UDP)) {
  9311. uint16_t len = htons((uint16_t) io->len);
  9312. mbuf_insert(io, 0, &len, 2);
  9313. }
  9314. mg_send(nc, io->buf, io->len);
  9315. } else {
  9316. /* Call user handler with parsed message */
  9317. nc->handler(nc, MG_DNS_MESSAGE, &msg);
  9318. }
  9319. mbuf_remove(io, io->len);
  9320. break;
  9321. }
  9322. }
  9323. void mg_set_protocol_dns(struct mg_connection *nc) {
  9324. nc->proto_handler = dns_handler;
  9325. }
  9326. #endif /* MG_ENABLE_DNS */
  9327. #ifdef MG_MODULE_LINES
  9328. #line 1 "mongoose/src/dns_server.c"
  9329. #endif
  9330. /*
  9331. * Copyright (c) 2014 Cesanta Software Limited
  9332. * All rights reserved
  9333. */
  9334. #if MG_ENABLE_DNS_SERVER
  9335. /* Amalgamated: #include "mongoose/src/internal.h" */
  9336. /* Amalgamated: #include "mongoose/src/dns-server.h" */
  9337. struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
  9338. struct mg_dns_message *msg) {
  9339. struct mg_dns_reply rep;
  9340. rep.msg = msg;
  9341. rep.io = io;
  9342. rep.start = io->len;
  9343. /* reply + recursion allowed */
  9344. msg->flags |= 0x8080;
  9345. mg_dns_copy_questions(io, msg);
  9346. msg->num_answers = 0;
  9347. return rep;
  9348. }
  9349. void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
  9350. size_t sent = r->io->len - r->start;
  9351. mg_dns_insert_header(r->io, r->start, r->msg);
  9352. if (!(nc->flags & MG_F_UDP)) {
  9353. uint16_t len = htons((uint16_t) sent);
  9354. mbuf_insert(r->io, r->start, &len, 2);
  9355. }
  9356. if (&nc->send_mbuf != r->io) {
  9357. mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
  9358. r->io->len = r->start;
  9359. }
  9360. }
  9361. int mg_dns_reply_record(struct mg_dns_reply *reply,
  9362. struct mg_dns_resource_record *question,
  9363. const char *name, int rtype, int ttl, const void *rdata,
  9364. size_t rdata_len) {
  9365. struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
  9366. char rname[512];
  9367. struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
  9368. if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
  9369. return -1; /* LCOV_EXCL_LINE */
  9370. }
  9371. if (name == NULL) {
  9372. name = rname;
  9373. rname[511] = 0;
  9374. mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
  9375. }
  9376. *ans = *question;
  9377. ans->kind = MG_DNS_ANSWER;
  9378. ans->rtype = rtype;
  9379. ans->ttl = ttl;
  9380. if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
  9381. rdata_len) == -1) {
  9382. return -1; /* LCOV_EXCL_LINE */
  9383. };
  9384. msg->num_answers++;
  9385. return 0;
  9386. }
  9387. #endif /* MG_ENABLE_DNS_SERVER */
  9388. #ifdef MG_MODULE_LINES
  9389. #line 1 "mongoose/src/resolv.c"
  9390. #endif
  9391. /*
  9392. * Copyright (c) 2014 Cesanta Software Limited
  9393. * All rights reserved
  9394. */
  9395. #if MG_ENABLE_ASYNC_RESOLVER
  9396. /* Amalgamated: #include "mongoose/src/internal.h" */
  9397. /* Amalgamated: #include "mongoose/src/resolv.h" */
  9398. #ifndef MG_DEFAULT_NAMESERVER
  9399. #define MG_DEFAULT_NAMESERVER "8.8.8.8"
  9400. #endif
  9401. static const char *mg_default_dns_server = "udp://" MG_DEFAULT_NAMESERVER ":53";
  9402. MG_INTERNAL char mg_dns_server[256];
  9403. struct mg_resolve_async_request {
  9404. char name[1024];
  9405. int query;
  9406. mg_resolve_callback_t callback;
  9407. void *data;
  9408. time_t timeout;
  9409. int max_retries;
  9410. enum mg_resolve_err err;
  9411. /* state */
  9412. time_t last_time;
  9413. int retries;
  9414. };
  9415. /*
  9416. * Find what nameserver to use.
  9417. *
  9418. * Return 0 if OK, -1 if error
  9419. */
  9420. static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
  9421. int ret = -1;
  9422. #ifdef _WIN32
  9423. int i;
  9424. LONG err;
  9425. HKEY hKey, hSub;
  9426. wchar_t subkey[512], value[128],
  9427. *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
  9428. if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
  9429. ERROR_SUCCESS) {
  9430. fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
  9431. ret = -1;
  9432. } else {
  9433. for (ret = -1, i = 0; 1; i++) {
  9434. DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
  9435. if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
  9436. NULL) != ERROR_SUCCESS) {
  9437. break;
  9438. }
  9439. if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
  9440. (RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
  9441. &len) == ERROR_SUCCESS ||
  9442. RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
  9443. &len) == ERROR_SUCCESS)) {
  9444. /*
  9445. * See https://github.com/cesanta/mongoose/issues/176
  9446. * The value taken from the registry can be empty, a single
  9447. * IP address, or multiple IP addresses separated by comma.
  9448. * If it's empty, check the next interface.
  9449. * If it's multiple IP addresses, take the first one.
  9450. */
  9451. wchar_t *comma = wcschr(value, ',');
  9452. if (value[0] == '\0') {
  9453. continue;
  9454. }
  9455. if (comma != NULL) {
  9456. *comma = '\0';
  9457. }
  9458. snprintf(name, name_len, "udp://%S:53", value);
  9459. ret = 0;
  9460. RegCloseKey(hSub);
  9461. break;
  9462. }
  9463. }
  9464. RegCloseKey(hKey);
  9465. }
  9466. #elif MG_ENABLE_FILESYSTEM
  9467. FILE *fp;
  9468. char line[512];
  9469. if ((fp = mg_fopen("/etc/resolv.conf", "r")) == NULL) {
  9470. ret = -1;
  9471. } else {
  9472. /* Try to figure out what nameserver to use */
  9473. for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
  9474. unsigned int a, b, c, d;
  9475. if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
  9476. snprintf(name, name_len, "udp://%u.%u.%u.%u:53", a, b, c, d);
  9477. ret = 0;
  9478. break;
  9479. }
  9480. }
  9481. (void) fclose(fp);
  9482. }
  9483. #else
  9484. snprintf(name, name_len, "%s", mg_default_dns_server);
  9485. #endif /* _WIN32 */
  9486. return ret;
  9487. }
  9488. int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
  9489. #if MG_ENABLE_FILESYSTEM
  9490. /* TODO(mkm) cache /etc/hosts */
  9491. FILE *fp;
  9492. char line[1024];
  9493. char *p;
  9494. char alias[256];
  9495. unsigned int a, b, c, d;
  9496. int len = 0;
  9497. if ((fp = mg_fopen("/etc/hosts", "r")) == NULL) {
  9498. return -1;
  9499. }
  9500. for (; fgets(line, sizeof(line), fp) != NULL;) {
  9501. if (line[0] == '#') continue;
  9502. if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
  9503. /* TODO(mkm): handle ipv6 */
  9504. continue;
  9505. }
  9506. for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
  9507. if (strcmp(alias, name) == 0) {
  9508. usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
  9509. fclose(fp);
  9510. return 0;
  9511. }
  9512. }
  9513. }
  9514. fclose(fp);
  9515. #else
  9516. (void) name;
  9517. (void) usa;
  9518. #endif
  9519. return -1;
  9520. }
  9521. static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data) {
  9522. time_t now = (time_t) mg_time();
  9523. struct mg_resolve_async_request *req;
  9524. struct mg_dns_message *msg;
  9525. int first = 0;
  9526. if (ev != MG_EV_POLL) DBG(("ev=%d user_data=%p", ev, nc->user_data));
  9527. req = (struct mg_resolve_async_request *) nc->user_data;
  9528. if (req == NULL) {
  9529. return;
  9530. }
  9531. switch (ev) {
  9532. case MG_EV_CONNECT:
  9533. /* don't depend on timer not being at epoch for sending out first req */
  9534. first = 1;
  9535. /* fallthrough */
  9536. case MG_EV_POLL:
  9537. if (req->retries > req->max_retries) {
  9538. req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
  9539. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9540. break;
  9541. }
  9542. if (first || now - req->last_time >= req->timeout) {
  9543. mg_send_dns_query(nc, req->name, req->query);
  9544. req->last_time = now;
  9545. req->retries++;
  9546. }
  9547. break;
  9548. case MG_EV_RECV:
  9549. msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
  9550. if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
  9551. msg->num_answers > 0) {
  9552. req->callback(msg, req->data, MG_RESOLVE_OK);
  9553. nc->user_data = NULL;
  9554. MG_FREE(req);
  9555. } else {
  9556. req->err = MG_RESOLVE_NO_ANSWERS;
  9557. }
  9558. MG_FREE(msg);
  9559. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9560. break;
  9561. case MG_EV_SEND:
  9562. /*
  9563. * If a send error occurs, prevent closing of the connection by the core.
  9564. * We will retry after timeout.
  9565. */
  9566. nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
  9567. mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
  9568. break;
  9569. case MG_EV_TIMER:
  9570. req->err = MG_RESOLVE_TIMEOUT;
  9571. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9572. break;
  9573. case MG_EV_CLOSE:
  9574. /* If we got here with request still not done, fire an error callback. */
  9575. if (req != NULL) {
  9576. req->callback(NULL, req->data, req->err);
  9577. nc->user_data = NULL;
  9578. MG_FREE(req);
  9579. }
  9580. break;
  9581. }
  9582. }
  9583. int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
  9584. mg_resolve_callback_t cb, void *data) {
  9585. struct mg_resolve_async_opts opts;
  9586. memset(&opts, 0, sizeof(opts));
  9587. return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
  9588. }
  9589. int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
  9590. mg_resolve_callback_t cb, void *data,
  9591. struct mg_resolve_async_opts opts) {
  9592. struct mg_resolve_async_request *req;
  9593. struct mg_connection *dns_nc;
  9594. const char *nameserver = opts.nameserver_url;
  9595. DBG(("%s %d %p", name, query, opts.dns_conn));
  9596. /* resolve with DNS */
  9597. req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
  9598. if (req == NULL) {
  9599. return -1;
  9600. }
  9601. strncpy(req->name, name, sizeof(req->name));
  9602. req->query = query;
  9603. req->callback = cb;
  9604. req->data = data;
  9605. /* TODO(mkm): parse defaults out of resolve.conf */
  9606. req->max_retries = opts.max_retries ? opts.max_retries : 2;
  9607. req->timeout = opts.timeout ? opts.timeout : 5;
  9608. /* Lazily initialize dns server */
  9609. if (nameserver == NULL && mg_dns_server[0] == '\0' &&
  9610. mg_get_ip_address_of_nameserver(mg_dns_server, sizeof(mg_dns_server)) ==
  9611. -1) {
  9612. strncpy(mg_dns_server, mg_default_dns_server, sizeof(mg_dns_server));
  9613. }
  9614. if (nameserver == NULL) {
  9615. nameserver = mg_dns_server;
  9616. }
  9617. dns_nc = mg_connect(mgr, nameserver, mg_resolve_async_eh);
  9618. if (dns_nc == NULL) {
  9619. MG_FREE(req);
  9620. return -1;
  9621. }
  9622. dns_nc->user_data = req;
  9623. if (opts.dns_conn != NULL) {
  9624. *opts.dns_conn = dns_nc;
  9625. }
  9626. return 0;
  9627. }
  9628. #endif /* MG_ENABLE_ASYNC_RESOLVER */
  9629. #ifdef MG_MODULE_LINES
  9630. #line 1 "mongoose/src/coap.c"
  9631. #endif
  9632. /*
  9633. * Copyright (c) 2015 Cesanta Software Limited
  9634. * All rights reserved
  9635. * This software is dual-licensed: you can redistribute it and/or modify
  9636. * it under the terms of the GNU General Public License version 2 as
  9637. * published by the Free Software Foundation. For the terms of this
  9638. * license, see <http://www.gnu.org/licenses/>.
  9639. *
  9640. * You are free to use this software under the terms of the GNU General
  9641. * Public License, but WITHOUT ANY WARRANTY; without even the implied
  9642. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9643. * See the GNU General Public License for more details.
  9644. *
  9645. * Alternatively, you can license this software under a commercial
  9646. * license, as set out in <https://www.cesanta.com/license>.
  9647. */
  9648. /* Amalgamated: #include "mongoose/src/internal.h" */
  9649. /* Amalgamated: #include "mongoose/src/coap.h" */
  9650. #if MG_ENABLE_COAP
  9651. void mg_coap_free_options(struct mg_coap_message *cm) {
  9652. while (cm->options != NULL) {
  9653. struct mg_coap_option *next = cm->options->next;
  9654. MG_FREE(cm->options);
  9655. cm->options = next;
  9656. }
  9657. }
  9658. struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
  9659. uint32_t number, char *value,
  9660. size_t len) {
  9661. struct mg_coap_option *new_option =
  9662. (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
  9663. new_option->number = number;
  9664. new_option->value.p = value;
  9665. new_option->value.len = len;
  9666. if (cm->options == NULL) {
  9667. cm->options = cm->optiomg_tail = new_option;
  9668. } else {
  9669. /*
  9670. * A very simple attention to help clients to compose options:
  9671. * CoAP wants to see options ASC ordered.
  9672. * Could be change by using sort in coap_compose
  9673. */
  9674. if (cm->optiomg_tail->number <= new_option->number) {
  9675. /* if option is already ordered just add it */
  9676. cm->optiomg_tail = cm->optiomg_tail->next = new_option;
  9677. } else {
  9678. /* looking for appropriate position */
  9679. struct mg_coap_option *current_opt = cm->options;
  9680. struct mg_coap_option *prev_opt = 0;
  9681. while (current_opt != NULL) {
  9682. if (current_opt->number > new_option->number) {
  9683. break;
  9684. }
  9685. prev_opt = current_opt;
  9686. current_opt = current_opt->next;
  9687. }
  9688. if (prev_opt != NULL) {
  9689. prev_opt->next = new_option;
  9690. new_option->next = current_opt;
  9691. } else {
  9692. /* insert new_option to the beginning */
  9693. new_option->next = cm->options;
  9694. cm->options = new_option;
  9695. }
  9696. }
  9697. }
  9698. return new_option;
  9699. }
  9700. /*
  9701. * Fills CoAP header in mg_coap_message.
  9702. *
  9703. * Helper function.
  9704. */
  9705. static char *coap_parse_header(char *ptr, struct mbuf *io,
  9706. struct mg_coap_message *cm) {
  9707. if (io->len < sizeof(uint32_t)) {
  9708. cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
  9709. return NULL;
  9710. }
  9711. /*
  9712. * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version
  9713. * number. Implementations of this specification MUST set this field
  9714. * to 1 (01 binary). Other values are reserved for future versions.
  9715. * Messages with unknown version numbers MUST be silently ignored.
  9716. */
  9717. if (((uint8_t) *ptr >> 6) != 1) {
  9718. cm->flags |= MG_COAP_IGNORE;
  9719. return NULL;
  9720. }
  9721. /*
  9722. * Type (T): 2-bit unsigned integer. Indicates if this message is of
  9723. * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
  9724. * Reset (3).
  9725. */
  9726. cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
  9727. cm->flags |= MG_COAP_MSG_TYPE_FIELD;
  9728. /*
  9729. * Token Length (TKL): 4-bit unsigned integer. Indicates the length of
  9730. * the variable-length Token field (0-8 bytes). Lengths 9-15 are
  9731. * reserved, MUST NOT be sent, and MUST be processed as a message
  9732. * format error.
  9733. */
  9734. cm->token.len = *ptr & 0x0F;
  9735. if (cm->token.len > 8) {
  9736. cm->flags |= MG_COAP_FORMAT_ERROR;
  9737. return NULL;
  9738. }
  9739. ptr++;
  9740. /*
  9741. * Code: 8-bit unsigned integer, split into a 3-bit class (most
  9742. * significant bits) and a 5-bit detail (least significant bits)
  9743. */
  9744. cm->code_class = (uint8_t) *ptr >> 5;
  9745. cm->code_detail = *ptr & 0x1F;
  9746. cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
  9747. ptr++;
  9748. /* Message ID: 16-bit unsigned integer in network byte order. */
  9749. cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
  9750. cm->flags |= MG_COAP_MSG_ID_FIELD;
  9751. ptr += 2;
  9752. return ptr;
  9753. }
  9754. /*
  9755. * Fills token information in mg_coap_message.
  9756. *
  9757. * Helper function.
  9758. */
  9759. static char *coap_get_token(char *ptr, struct mbuf *io,
  9760. struct mg_coap_message *cm) {
  9761. if (cm->token.len != 0) {
  9762. if (ptr + cm->token.len > io->buf + io->len) {
  9763. cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
  9764. return NULL;
  9765. } else {
  9766. cm->token.p = ptr;
  9767. ptr += cm->token.len;
  9768. cm->flags |= MG_COAP_TOKEN_FIELD;
  9769. }
  9770. }
  9771. return ptr;
  9772. }
  9773. /*
  9774. * Returns Option Delta or Length.
  9775. *
  9776. * Helper function.
  9777. */
  9778. static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
  9779. int ret = 0;
  9780. if (*opt_info == 13) {
  9781. /*
  9782. * 13: An 8-bit unsigned integer follows the initial byte and
  9783. * indicates the Option Delta/Length minus 13.
  9784. */
  9785. if (ptr < io->buf + io->len) {
  9786. *opt_info = (uint8_t) *ptr + 13;
  9787. ret = sizeof(uint8_t);
  9788. } else {
  9789. ret = -1; /* LCOV_EXCL_LINE */
  9790. }
  9791. } else if (*opt_info == 14) {
  9792. /*
  9793. * 14: A 16-bit unsigned integer in network byte order follows the
  9794. * initial byte and indicates the Option Delta/Length minus 269.
  9795. */
  9796. if (ptr + sizeof(uint8_t) < io->buf + io->len) {
  9797. *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
  9798. ret = sizeof(uint16_t);
  9799. } else {
  9800. ret = -1; /* LCOV_EXCL_LINE */
  9801. }
  9802. }
  9803. return ret;
  9804. }
  9805. /*
  9806. * Fills options in mg_coap_message.
  9807. *
  9808. * Helper function.
  9809. *
  9810. * General options format:
  9811. * +---------------+---------------+
  9812. * | Option Delta | Option Length | 1 byte
  9813. * +---------------+---------------+
  9814. * \ Option Delta (extended) \ 0-2 bytes
  9815. * +-------------------------------+
  9816. * / Option Length (extended) \ 0-2 bytes
  9817. * +-------------------------------+
  9818. * \ Option Value \ 0 or more bytes
  9819. * +-------------------------------+
  9820. */
  9821. static char *coap_get_options(char *ptr, struct mbuf *io,
  9822. struct mg_coap_message *cm) {
  9823. uint16_t prev_opt = 0;
  9824. if (ptr == io->buf + io->len) {
  9825. /* end of packet, ok */
  9826. return NULL;
  9827. }
  9828. /* 0xFF is payload marker */
  9829. while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
  9830. uint16_t option_delta, option_lenght;
  9831. int optinfo_len;
  9832. /* Option Delta: 4-bit unsigned integer */
  9833. option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
  9834. /* Option Length: 4-bit unsigned integer */
  9835. option_lenght = *ptr & 0x0F;
  9836. if (option_delta == 15 || option_lenght == 15) {
  9837. /*
  9838. * 15: Reserved for future use. If the field is set to this value,
  9839. * it MUST be processed as a message format error
  9840. */
  9841. cm->flags |= MG_COAP_FORMAT_ERROR;
  9842. break;
  9843. }
  9844. ptr++;
  9845. /* check for extended option delta */
  9846. optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
  9847. if (optinfo_len == -1) {
  9848. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  9849. break; /* LCOV_EXCL_LINE */
  9850. }
  9851. ptr += optinfo_len;
  9852. /* check or extended option lenght */
  9853. optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
  9854. if (optinfo_len == -1) {
  9855. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  9856. break; /* LCOV_EXCL_LINE */
  9857. }
  9858. ptr += optinfo_len;
  9859. /*
  9860. * Instead of specifying the Option Number directly, the instances MUST
  9861. * appear in order of their Option Numbers and a delta encoding is used
  9862. * between them.
  9863. */
  9864. option_delta += prev_opt;
  9865. mg_coap_add_option(cm, option_delta, ptr, option_lenght);
  9866. prev_opt = option_delta;
  9867. if (ptr + option_lenght > io->buf + io->len) {
  9868. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  9869. break; /* LCOV_EXCL_LINE */
  9870. }
  9871. ptr += option_lenght;
  9872. }
  9873. if ((cm->flags & MG_COAP_ERROR) != 0) {
  9874. mg_coap_free_options(cm);
  9875. return NULL;
  9876. }
  9877. cm->flags |= MG_COAP_OPTIOMG_FIELD;
  9878. if (ptr == io->buf + io->len) {
  9879. /* end of packet, ok */
  9880. return NULL;
  9881. }
  9882. ptr++;
  9883. return ptr;
  9884. }
  9885. uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
  9886. char *ptr;
  9887. memset(cm, 0, sizeof(*cm));
  9888. if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
  9889. return cm->flags;
  9890. }
  9891. if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
  9892. return cm->flags;
  9893. }
  9894. if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
  9895. return cm->flags;
  9896. }
  9897. /* the rest is payload */
  9898. cm->payload.len = io->len - (ptr - io->buf);
  9899. if (cm->payload.len != 0) {
  9900. cm->payload.p = ptr;
  9901. cm->flags |= MG_COAP_PAYLOAD_FIELD;
  9902. }
  9903. return cm->flags;
  9904. }
  9905. /*
  9906. * Calculates extended size of given Opt Number/Length in coap message.
  9907. *
  9908. * Helper function.
  9909. */
  9910. static size_t coap_get_ext_opt_size(uint32_t value) {
  9911. int ret = 0;
  9912. if (value >= 13 && value <= 0xFF + 13) {
  9913. ret = sizeof(uint8_t);
  9914. } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
  9915. ret = sizeof(uint16_t);
  9916. }
  9917. return ret;
  9918. }
  9919. /*
  9920. * Splits given Opt Number/Length into base and ext values.
  9921. *
  9922. * Helper function.
  9923. */
  9924. static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
  9925. int ret = 0;
  9926. if (value < 13) {
  9927. *base = value;
  9928. } else if (value >= 13 && value <= 0xFF + 13) {
  9929. *base = 13;
  9930. *ext = value - 13;
  9931. ret = sizeof(uint8_t);
  9932. } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
  9933. *base = 14;
  9934. *ext = value - 269;
  9935. ret = sizeof(uint16_t);
  9936. }
  9937. return ret;
  9938. }
  9939. /*
  9940. * Puts uint16_t (in network order) into given char stream.
  9941. *
  9942. * Helper function.
  9943. */
  9944. static char *coap_add_uint16(char *ptr, uint16_t val) {
  9945. *ptr = val >> 8;
  9946. ptr++;
  9947. *ptr = val & 0x00FF;
  9948. ptr++;
  9949. return ptr;
  9950. }
  9951. /*
  9952. * Puts extended value of Opt Number/Length into given char stream.
  9953. *
  9954. * Helper function.
  9955. */
  9956. static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
  9957. if (len == sizeof(uint8_t)) {
  9958. *ptr = (char) val;
  9959. ptr++;
  9960. } else if (len == sizeof(uint16_t)) {
  9961. ptr = coap_add_uint16(ptr, val);
  9962. }
  9963. return ptr;
  9964. }
  9965. /*
  9966. * Verifies given mg_coap_message and calculates message size for it.
  9967. *
  9968. * Helper function.
  9969. */
  9970. static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
  9971. size_t *len) {
  9972. struct mg_coap_option *opt;
  9973. uint32_t prev_opt_number;
  9974. *len = 4; /* header */
  9975. if (cm->msg_type > MG_COAP_MSG_MAX) {
  9976. return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
  9977. }
  9978. if (cm->token.len > 8) {
  9979. return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
  9980. }
  9981. if (cm->code_class > 7) {
  9982. return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
  9983. }
  9984. if (cm->code_detail > 31) {
  9985. return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
  9986. }
  9987. *len += cm->token.len;
  9988. if (cm->payload.len != 0) {
  9989. *len += cm->payload.len + 1; /* ... + 1; add payload marker */
  9990. }
  9991. opt = cm->options;
  9992. prev_opt_number = 0;
  9993. while (opt != NULL) {
  9994. *len += 1; /* basic delta/length */
  9995. *len += coap_get_ext_opt_size(opt->number - prev_opt_number);
  9996. *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
  9997. /*
  9998. * Current implementation performs check if
  9999. * option_number > previous option_number and produces an error
  10000. * TODO(alashkin): write design doc with limitations
  10001. * May be resorting is more suitable solution.
  10002. */
  10003. if ((opt->next != NULL && opt->number > opt->next->number) ||
  10004. opt->value.len > 0xFFFF + 269 ||
  10005. opt->number - prev_opt_number > 0xFFFF + 269) {
  10006. return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
  10007. }
  10008. *len += opt->value.len;
  10009. prev_opt_number = opt->number;
  10010. opt = opt->next;
  10011. }
  10012. return 0;
  10013. }
  10014. uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
  10015. struct mg_coap_option *opt;
  10016. uint32_t res, prev_opt_number;
  10017. size_t prev_io_len, packet_size;
  10018. char *ptr;
  10019. res = coap_calculate_packet_size(cm, &packet_size);
  10020. if (res != 0) {
  10021. return res;
  10022. }
  10023. /* saving previous lenght to handle non-empty mbuf */
  10024. prev_io_len = io->len;
  10025. mbuf_append(io, NULL, packet_size);
  10026. ptr = io->buf + prev_io_len;
  10027. /*
  10028. * since cm is verified, it is possible to use bits shift operator
  10029. * without additional zeroing of unused bits
  10030. */
  10031. /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
  10032. *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
  10033. ptr++;
  10034. /* code class: 3 bits, code detail: 5 bits */
  10035. *ptr = (cm->code_class << 5) | (cm->code_detail);
  10036. ptr++;
  10037. ptr = coap_add_uint16(ptr, cm->msg_id);
  10038. if (cm->token.len != 0) {
  10039. memcpy(ptr, cm->token.p, cm->token.len);
  10040. ptr += cm->token.len;
  10041. }
  10042. opt = cm->options;
  10043. prev_opt_number = 0;
  10044. while (opt != NULL) {
  10045. uint8_t delta_base = 0, length_base = 0;
  10046. uint16_t delta_ext = 0, length_ext = 0;
  10047. size_t opt_delta_len =
  10048. coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
  10049. size_t opt_lenght_len =
  10050. coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
  10051. *ptr = (delta_base << 4) | length_base;
  10052. ptr++;
  10053. ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
  10054. ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
  10055. if (opt->value.len != 0) {
  10056. memcpy(ptr, opt->value.p, opt->value.len);
  10057. ptr += opt->value.len;
  10058. }
  10059. prev_opt_number = opt->number;
  10060. opt = opt->next;
  10061. }
  10062. if (cm->payload.len != 0) {
  10063. *ptr = (char) -1;
  10064. ptr++;
  10065. memcpy(ptr, cm->payload.p, cm->payload.len);
  10066. }
  10067. return 0;
  10068. }
  10069. uint32_t mg_coap_send_message(struct mg_connection *nc,
  10070. struct mg_coap_message *cm) {
  10071. struct mbuf packet_out;
  10072. uint32_t compose_res;
  10073. mbuf_init(&packet_out, 0);
  10074. compose_res = mg_coap_compose(cm, &packet_out);
  10075. if (compose_res != 0) {
  10076. return compose_res; /* LCOV_EXCL_LINE */
  10077. }
  10078. mg_send(nc, packet_out.buf, (int) packet_out.len);
  10079. mbuf_free(&packet_out);
  10080. return 0;
  10081. }
  10082. uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
  10083. struct mg_coap_message cm;
  10084. memset(&cm, 0, sizeof(cm));
  10085. cm.msg_type = MG_COAP_MSG_ACK;
  10086. cm.msg_id = msg_id;
  10087. return mg_coap_send_message(nc, &cm);
  10088. }
  10089. static void coap_handler(struct mg_connection *nc, int ev, void *ev_data) {
  10090. struct mbuf *io = &nc->recv_mbuf;
  10091. struct mg_coap_message cm;
  10092. uint32_t parse_res;
  10093. memset(&cm, 0, sizeof(cm));
  10094. nc->handler(nc, ev, ev_data);
  10095. switch (ev) {
  10096. case MG_EV_RECV:
  10097. parse_res = mg_coap_parse(io, &cm);
  10098. if ((parse_res & MG_COAP_IGNORE) == 0) {
  10099. if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
  10100. /*
  10101. * Since we support UDP only
  10102. * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
  10103. */
  10104. cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
  10105. } /* LCOV_EXCL_LINE */
  10106. nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm);
  10107. }
  10108. mg_coap_free_options(&cm);
  10109. mbuf_remove(io, io->len);
  10110. break;
  10111. }
  10112. }
  10113. /*
  10114. * Attach built-in CoAP event handler to the given connection.
  10115. *
  10116. * The user-defined event handler will receive following extra events:
  10117. *
  10118. * - MG_EV_COAP_CON
  10119. * - MG_EV_COAP_NOC
  10120. * - MG_EV_COAP_ACK
  10121. * - MG_EV_COAP_RST
  10122. */
  10123. int mg_set_protocol_coap(struct mg_connection *nc) {
  10124. /* supports UDP only */
  10125. if ((nc->flags & MG_F_UDP) == 0) {
  10126. return -1;
  10127. }
  10128. nc->proto_handler = coap_handler;
  10129. return 0;
  10130. }
  10131. #endif /* MG_ENABLE_COAP */
  10132. #ifdef MG_MODULE_LINES
  10133. #line 1 "mongoose/src/tun.c"
  10134. #endif
  10135. /*
  10136. * Copyright (c) 2014 Cesanta Software Limited
  10137. * All rights reserved
  10138. */
  10139. #if MG_ENABLE_TUN
  10140. /* Amalgamated: #include "common/cs_dbg.h" */
  10141. /* Amalgamated: #include "mongoose/src/http.h" */
  10142. /* Amalgamated: #include "mongoose/src/internal.h" */
  10143. /* Amalgamated: #include "mongoose/src/net.h" */
  10144. /* Amalgamated: #include "mongoose/src/net_if_tun.h" */
  10145. /* Amalgamated: #include "mongoose/src/tun.h" */
  10146. /* Amalgamated: #include "mongoose/src/util.h" */
  10147. static void mg_tun_reconnect(struct mg_tun_client *client, int timeout);
  10148. static void mg_tun_init_client(struct mg_tun_client *client, struct mg_mgr *mgr,
  10149. struct mg_iface *iface, const char *dispatcher,
  10150. struct mg_tun_ssl_opts ssl) {
  10151. client->mgr = mgr;
  10152. client->iface = iface;
  10153. client->disp_url = dispatcher;
  10154. client->last_stream_id = 0;
  10155. client->ssl = ssl;
  10156. client->disp = NULL; /* will be set by mg_tun_reconnect */
  10157. client->listener = NULL; /* will be set by mg_do_bind */
  10158. client->reconnect = NULL; /* will be set by mg_tun_reconnect */
  10159. }
  10160. void mg_tun_log_frame(struct mg_tun_frame *frame) {
  10161. LOG(LL_DEBUG, ("Got TUN frame: type=0x%x, flags=0x%x stream_id=0x%lx, "
  10162. "len=%zu",
  10163. frame->type, frame->flags, frame->stream_id, frame->body.len));
  10164. #if MG_ENABLE_HEXDUMP
  10165. {
  10166. char hex[512];
  10167. mg_hexdump(frame->body.p, frame->body.len, hex, sizeof(hex) - 1);
  10168. hex[sizeof(hex) - 1] = '\0';
  10169. LOG(LL_DEBUG, ("body:\n%s", hex));
  10170. }
  10171. #else
  10172. LOG(LL_DEBUG, ("body: '%.*s'", (int) frame->body.len, frame->body.p));
  10173. #endif
  10174. }
  10175. static void mg_tun_close_all(struct mg_tun_client *client) {
  10176. struct mg_connection *nc;
  10177. for (nc = client->mgr->active_connections; nc != NULL; nc = nc->next) {
  10178. if (nc->iface == client->iface && !(nc->flags & MG_F_LISTENING)) {
  10179. LOG(LL_DEBUG, ("Closing tunneled connection %p", nc));
  10180. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10181. /* mg_close_conn(nc); */
  10182. }
  10183. }
  10184. }
  10185. static void mg_tun_client_handler(struct mg_connection *nc, int ev,
  10186. void *ev_data) {
  10187. struct mg_tun_client *client = (struct mg_tun_client *) nc->user_data;
  10188. switch (ev) {
  10189. case MG_EV_CONNECT: {
  10190. int err = *(int *) ev_data;
  10191. if (err) {
  10192. LOG(LL_ERROR, ("Cannot connect to the tunnel dispatcher: %d", err));
  10193. } else {
  10194. LOG(LL_INFO, ("Connected to the tunnel dispatcher"));
  10195. }
  10196. break;
  10197. }
  10198. case MG_EV_HTTP_REPLY: {
  10199. struct http_message *hm = (struct http_message *) ev_data;
  10200. if (hm->resp_code != 200) {
  10201. LOG(LL_ERROR,
  10202. ("Tunnel dispatcher reply non-OK status code %d", hm->resp_code));
  10203. }
  10204. break;
  10205. }
  10206. case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
  10207. LOG(LL_INFO, ("Tunnel dispatcher handshake done"));
  10208. break;
  10209. }
  10210. case MG_EV_WEBSOCKET_FRAME: {
  10211. struct websocket_message *wm = (struct websocket_message *) ev_data;
  10212. struct mg_connection *tc;
  10213. struct mg_tun_frame frame;
  10214. if (mg_tun_parse_frame(wm->data, wm->size, &frame) == -1) {
  10215. LOG(LL_ERROR, ("Got invalid tun frame dropping", wm->size));
  10216. break;
  10217. }
  10218. mg_tun_log_frame(&frame);
  10219. tc = mg_tun_if_find_conn(client, frame.stream_id);
  10220. if (tc == NULL) {
  10221. if (frame.body.len > 0) {
  10222. LOG(LL_DEBUG, ("Got frame after receiving end has been closed"));
  10223. }
  10224. break;
  10225. }
  10226. if (frame.body.len > 0) {
  10227. mg_if_recv_tcp_cb(tc, (void *) frame.body.p, frame.body.len,
  10228. 0 /* own */);
  10229. }
  10230. if (frame.flags & MG_TUN_F_END_STREAM) {
  10231. LOG(LL_DEBUG, ("Closing tunneled connection because got end of stream "
  10232. "from other end"));
  10233. tc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10234. mg_close_conn(tc);
  10235. }
  10236. break;
  10237. }
  10238. case MG_EV_CLOSE: {
  10239. LOG(LL_DEBUG, ("Closing all tunneled connections"));
  10240. /*
  10241. * The client might have been already freed when the listening socket is
  10242. * closed.
  10243. */
  10244. if (client != NULL) {
  10245. mg_tun_close_all(client);
  10246. client->disp = NULL;
  10247. LOG(LL_INFO, ("Dispatcher connection is no more, reconnecting"));
  10248. /* TODO(mkm): implement exp back off */
  10249. mg_tun_reconnect(client, MG_TUN_RECONNECT_INTERVAL);
  10250. }
  10251. break;
  10252. }
  10253. default:
  10254. break;
  10255. }
  10256. }
  10257. static void mg_tun_do_reconnect(struct mg_tun_client *client) {
  10258. struct mg_connection *dc;
  10259. struct mg_connect_opts opts;
  10260. memset(&opts, 0, sizeof(opts));
  10261. #if MG_ENABLE_SSL
  10262. opts.ssl_cert = client->ssl.ssl_cert;
  10263. opts.ssl_key = client->ssl.ssl_key;
  10264. opts.ssl_ca_cert = client->ssl.ssl_ca_cert;
  10265. #endif
  10266. /* HTTP/Websocket listener */
  10267. if ((dc = mg_connect_ws_opt(client->mgr, mg_tun_client_handler, opts,
  10268. client->disp_url, MG_TUN_PROTO_NAME, NULL)) ==
  10269. NULL) {
  10270. LOG(LL_ERROR,
  10271. ("Cannot connect to WS server on addr [%s]\n", client->disp_url));
  10272. return;
  10273. }
  10274. client->disp = dc;
  10275. dc->user_data = client;
  10276. }
  10277. void mg_tun_reconnect_ev_handler(struct mg_connection *nc, int ev,
  10278. void *ev_data) {
  10279. struct mg_tun_client *client = (struct mg_tun_client *) nc->user_data;
  10280. (void) ev_data;
  10281. switch (ev) {
  10282. case MG_EV_TIMER:
  10283. if (!(client->listener->flags & MG_F_TUN_DO_NOT_RECONNECT)) {
  10284. mg_tun_do_reconnect(client);
  10285. } else {
  10286. /* Reconnecting is suppressed, we'll check again at the next poll */
  10287. mg_tun_reconnect(client, 0);
  10288. }
  10289. break;
  10290. }
  10291. }
  10292. static void mg_tun_reconnect(struct mg_tun_client *client, int timeout) {
  10293. if (client->reconnect == NULL) {
  10294. client->reconnect =
  10295. mg_add_sock(client->mgr, INVALID_SOCKET, mg_tun_reconnect_ev_handler);
  10296. client->reconnect->user_data = client;
  10297. }
  10298. client->reconnect->ev_timer_time = mg_time() + timeout;
  10299. }
  10300. static struct mg_tun_client *mg_tun_create_client(struct mg_mgr *mgr,
  10301. const char *dispatcher,
  10302. struct mg_tun_ssl_opts ssl) {
  10303. struct mg_tun_client *client = NULL;
  10304. struct mg_iface *iface = mg_find_iface(mgr, &mg_tun_iface_vtable, NULL);
  10305. if (iface == NULL) {
  10306. LOG(LL_ERROR, ("The tun feature requires the manager to have a tun "
  10307. "interface enabled"));
  10308. return NULL;
  10309. }
  10310. client = (struct mg_tun_client *) MG_MALLOC(sizeof(*client));
  10311. mg_tun_init_client(client, mgr, iface, dispatcher, ssl);
  10312. iface->data = client;
  10313. /*
  10314. * We need to give application a chance to set MG_F_TUN_DO_NOT_RECONNECT on a
  10315. * listening connection right after mg_tun_bind_opt() returned it, so we
  10316. * should use mg_tun_reconnect() here, instead of mg_tun_do_reconnect()
  10317. */
  10318. mg_tun_reconnect(client, 0);
  10319. return client;
  10320. }
  10321. void mg_tun_destroy_client(struct mg_tun_client *client) {
  10322. /*
  10323. * NOTE:
  10324. * `client` is NULL in case of OOM
  10325. * `client->disp` is NULL if connection failed
  10326. * `client->iface is NULL is `mg_find_iface` failed
  10327. */
  10328. if (client != NULL && client->disp != NULL) {
  10329. /* the dispatcher connection handler will in turn close all tunnels */
  10330. client->disp->flags |= MG_F_CLOSE_IMMEDIATELY;
  10331. /* this is used as a signal to other tun handlers that the party is over */
  10332. client->disp->user_data = NULL;
  10333. }
  10334. if (client != NULL && client->reconnect != NULL) {
  10335. client->reconnect->flags |= MG_F_CLOSE_IMMEDIATELY;
  10336. }
  10337. if (client != NULL && client->iface != NULL) {
  10338. client->iface->data = NULL;
  10339. }
  10340. MG_FREE(client);
  10341. }
  10342. static struct mg_connection *mg_tun_do_bind(struct mg_tun_client *client,
  10343. mg_event_handler_t handler,
  10344. struct mg_bind_opts opts) {
  10345. struct mg_connection *lc;
  10346. opts.iface = client->iface;
  10347. lc = mg_bind_opt(client->mgr, ":1234" /* dummy port */, handler, opts);
  10348. client->listener = lc;
  10349. return lc;
  10350. }
  10351. struct mg_connection *mg_tun_bind_opt(struct mg_mgr *mgr,
  10352. const char *dispatcher,
  10353. mg_event_handler_t handler,
  10354. struct mg_bind_opts opts) {
  10355. #if MG_ENABLE_SSL
  10356. struct mg_tun_ssl_opts ssl = {opts.ssl_cert, opts.ssl_key, opts.ssl_ca_cert};
  10357. #else
  10358. struct mg_tun_ssl_opts ssl = {0};
  10359. #endif
  10360. struct mg_tun_client *client = mg_tun_create_client(mgr, dispatcher, ssl);
  10361. if (client == NULL) {
  10362. return NULL;
  10363. }
  10364. #if MG_ENABLE_SSL
  10365. /* these options don't make sense in the local mouth of the tunnel */
  10366. opts.ssl_cert = NULL;
  10367. opts.ssl_key = NULL;
  10368. opts.ssl_ca_cert = NULL;
  10369. #endif
  10370. return mg_tun_do_bind(client, handler, opts);
  10371. }
  10372. int mg_tun_parse_frame(void *data, size_t len, struct mg_tun_frame *frame) {
  10373. const size_t header_size = sizeof(uint32_t) + sizeof(uint8_t) * 2;
  10374. if (len < header_size) {
  10375. return -1;
  10376. }
  10377. frame->type = *(uint8_t *) (data);
  10378. frame->flags = *(uint8_t *) ((char *) data + 1);
  10379. memcpy(&frame->stream_id, (char *) data + 2, sizeof(uint32_t));
  10380. frame->stream_id = ntohl(frame->stream_id);
  10381. frame->body.p = (char *) data + header_size;
  10382. frame->body.len = len - header_size;
  10383. return 0;
  10384. }
  10385. void mg_tun_send_frame(struct mg_connection *ws, uint32_t stream_id,
  10386. uint8_t type, uint8_t flags, struct mg_str msg) {
  10387. stream_id = htonl(stream_id);
  10388. {
  10389. struct mg_str parts[] = {
  10390. {(char *) &type, sizeof(type)},
  10391. {(char *) &flags, sizeof(flags)},
  10392. {(char *) &stream_id, sizeof(stream_id)},
  10393. {msg.p, msg.len} /* vc6 doesn't like just `msg` here */};
  10394. mg_send_websocket_framev(ws, WEBSOCKET_OP_BINARY, parts,
  10395. sizeof(parts) / sizeof(parts[0]));
  10396. }
  10397. }
  10398. #endif /* MG_ENABLE_TUN */
  10399. #ifdef MG_MODULE_LINES
  10400. #line 1 "mongoose/src/sntp.c"
  10401. #endif
  10402. /*
  10403. * Copyright (c) 2016 Cesanta Software Limited
  10404. * All rights reserved
  10405. */
  10406. /* Amalgamated: #include "mongoose/src/internal.h" */
  10407. /* Amalgamated: #include "mongoose/src/sntp.h" */
  10408. /* Amalgamated: #include "mongoose/src/util.h" */
  10409. #if MG_ENABLE_SNTP
  10410. #define SNTP_TIME_OFFSET 2208988800
  10411. #ifndef SNTP_TIMEOUT
  10412. #define SNTP_TIMEOUT 10
  10413. #endif
  10414. #ifndef SNTP_ATTEMPTS
  10415. #define SNTP_ATTEMPTS 3
  10416. #endif
  10417. static uint64_t mg_get_sec(uint64_t val) {
  10418. return (val & 0xFFFFFFFF00000000) >> 32;
  10419. }
  10420. static uint64_t mg_get_usec(uint64_t val) {
  10421. uint64_t tmp = (val & 0x00000000FFFFFFFF);
  10422. tmp *= 1000000;
  10423. tmp >>= 32;
  10424. return tmp;
  10425. }
  10426. static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
  10427. uint64_t tmp;
  10428. tmp = mg_get_sec(val);
  10429. tmp -= SNTP_TIME_OFFSET;
  10430. tv->tv_sec = tmp;
  10431. tv->tv_usec = mg_get_usec(val);
  10432. }
  10433. static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
  10434. uint32_t tmp;
  10435. memcpy(&tmp, ntp, sizeof(tmp));
  10436. tmp = ntohl(tmp);
  10437. *val = (uint64_t) tmp << 32;
  10438. memcpy(&tmp, ntp + 4, sizeof(tmp));
  10439. tmp = ntohl(tmp);
  10440. *val |= tmp;
  10441. }
  10442. void mg_sntp_send_request(struct mg_connection *c) {
  10443. char buf[48] = {0};
  10444. /*
  10445. * header - 8 bit:
  10446. * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
  10447. * mode (3 bit) - 3 (client)
  10448. */
  10449. buf[0] = (3 << 6) | (4 << 3) | 3;
  10450. /*
  10451. * Next fields should be empty in client request
  10452. * stratum, 8 bit
  10453. * poll interval, 8 bit
  10454. * rrecision, 8 bit
  10455. * root delay, 32 bit
  10456. * root dispersion, 32 bit
  10457. * ref id, 32 bit
  10458. * ref timestamp, 64 bit
  10459. * originate Timestamp, 64 bit
  10460. * receive Timestamp, 64 bit
  10461. */
  10462. /*
  10463. * convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
  10464. * according to rfc868 it is 2208988800L sec
  10465. * this information is used to correct roundtrip delay
  10466. * but if local clock is absolutely broken (and doesn't work even
  10467. * as simple timer), it is better to disable it
  10468. */
  10469. #ifndef MG_SNMP_NO_DELAY_CORRECTION
  10470. uint32_t sec;
  10471. sec = htonl(mg_time() + SNTP_TIME_OFFSET);
  10472. memcpy(&buf[40], &sec, sizeof(sec));
  10473. #endif
  10474. mg_send(c, buf, sizeof(buf));
  10475. }
  10476. #ifndef MG_SNMP_NO_DELAY_CORRECTION
  10477. static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
  10478. /* roundloop delay = (T4 - T1) - (T3 - T2) */
  10479. uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
  10480. (mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
  10481. uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
  10482. (mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
  10483. return (d1 > d2) ? d1 - d2 : 0;
  10484. }
  10485. #endif
  10486. MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
  10487. struct mg_sntp_message *msg) {
  10488. uint8_t hdr;
  10489. uint64_t orig_ts_T1, recv_ts_T2, trsm_ts_T3, delay = 0;
  10490. int mode;
  10491. struct timeval tv;
  10492. (void) orig_ts_T1;
  10493. (void) recv_ts_T2;
  10494. if (len < 48) {
  10495. return -1;
  10496. }
  10497. hdr = buf[0];
  10498. if ((hdr & 0x38) >> 3 != 4) {
  10499. /* Wrong version */
  10500. return -1;
  10501. }
  10502. mode = hdr & 0x7;
  10503. if (mode != 4 && mode != 5) {
  10504. /* Not a server reply */
  10505. return -1;
  10506. }
  10507. memset(msg, 0, sizeof(*msg));
  10508. msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
  10509. mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
  10510. #ifndef MG_SNMP_NO_DELAY_CORRECTION
  10511. mg_get_ntp_ts(&buf[24], &orig_ts_T1);
  10512. mg_get_ntp_ts(&buf[32], &recv_ts_T2);
  10513. delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
  10514. #endif
  10515. mg_ntp_to_tv(trsm_ts_T3, &tv);
  10516. msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
  10517. return 0;
  10518. }
  10519. static void mg_sntp_handler(struct mg_connection *c, int ev, void *ev_data) {
  10520. struct mbuf *io = &c->recv_mbuf;
  10521. struct mg_sntp_message msg;
  10522. c->handler(c, ev, ev_data);
  10523. switch (ev) {
  10524. case MG_EV_RECV: {
  10525. if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
  10526. DBG(("Invalid SNTP packet received (%d)", (int) io->len));
  10527. c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL);
  10528. } else {
  10529. c->handler(c, MG_SNTP_REPLY, (void *) &msg);
  10530. }
  10531. mbuf_remove(io, io->len);
  10532. break;
  10533. }
  10534. }
  10535. }
  10536. int mg_set_protocol_sntp(struct mg_connection *c) {
  10537. if ((c->flags & MG_F_UDP) == 0) {
  10538. return -1;
  10539. }
  10540. c->proto_handler = mg_sntp_handler;
  10541. return 0;
  10542. }
  10543. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
  10544. mg_event_handler_t event_handler,
  10545. const char *sntp_server_name) {
  10546. struct mg_connection *c = NULL;
  10547. char url[100], *p_url = url;
  10548. const char *proto = "", *port = "", *tmp;
  10549. /* If port is not specified, use default (123) */
  10550. tmp = strchr(sntp_server_name, ':');
  10551. if (tmp != NULL && *(tmp + 1) == '/') {
  10552. tmp = strchr(tmp + 1, ':');
  10553. }
  10554. if (tmp == NULL) {
  10555. port = ":123";
  10556. }
  10557. /* Add udp:// if needed */
  10558. if (strncmp(sntp_server_name, "udp://", 6) != 0) {
  10559. proto = "udp://";
  10560. }
  10561. mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
  10562. c = mg_connect(mgr, p_url, event_handler);
  10563. if (c == NULL) {
  10564. goto cleanup;
  10565. }
  10566. mg_set_protocol_sntp(c);
  10567. cleanup:
  10568. if (p_url != url) {
  10569. MG_FREE(p_url);
  10570. }
  10571. return c;
  10572. }
  10573. struct sntp_data {
  10574. mg_event_handler_t hander;
  10575. int count;
  10576. };
  10577. static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
  10578. void *ev_data) {
  10579. struct sntp_data *sd = (struct sntp_data *) c->user_data;
  10580. switch (ev) {
  10581. case MG_EV_CONNECT:
  10582. if (*(int *) ev_data != 0) {
  10583. mg_call(c, sd->hander, MG_SNTP_FAILED, NULL);
  10584. break;
  10585. }
  10586. /* fallthrough */
  10587. case MG_EV_TIMER:
  10588. if (sd->count <= SNTP_ATTEMPTS) {
  10589. mg_sntp_send_request(c);
  10590. mg_set_timer(c, mg_time() + 10);
  10591. sd->count++;
  10592. } else {
  10593. mg_call(c, sd->hander, MG_SNTP_FAILED, NULL);
  10594. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  10595. }
  10596. break;
  10597. case MG_SNTP_MALFORMED_REPLY:
  10598. mg_call(c, sd->hander, MG_SNTP_FAILED, NULL);
  10599. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  10600. break;
  10601. case MG_SNTP_REPLY:
  10602. mg_call(c, sd->hander, MG_SNTP_REPLY, ev_data);
  10603. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  10604. break;
  10605. case MG_EV_CLOSE:
  10606. MG_FREE(c->user_data);
  10607. c->user_data = NULL;
  10608. break;
  10609. }
  10610. }
  10611. struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
  10612. mg_event_handler_t event_handler,
  10613. const char *sntp_server_name) {
  10614. struct mg_connection *c;
  10615. struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
  10616. if (sd == NULL) {
  10617. return NULL;
  10618. }
  10619. c = mg_sntp_connect(mgr, mg_sntp_util_ev_handler, sntp_server_name);
  10620. if (c == NULL) {
  10621. MG_FREE(sd);
  10622. return NULL;
  10623. }
  10624. sd->hander = event_handler;
  10625. c->user_data = sd;
  10626. return c;
  10627. }
  10628. #endif /* MG_ENABLE_SNTP */
  10629. #ifdef MG_MODULE_LINES
  10630. #line 1 "common/platforms/cc3200/cc3200_libc.c"
  10631. #endif
  10632. /*
  10633. * Copyright (c) 2014-2016 Cesanta Software Limited
  10634. * All rights reserved
  10635. */
  10636. #if CS_PLATFORM == CS_P_CC3200
  10637. #include <stdio.h>
  10638. #include <string.h>
  10639. #ifndef __TI_COMPILER_VERSION__
  10640. #include <reent.h>
  10641. #include <sys/stat.h>
  10642. #include <sys/time.h>
  10643. #include <unistd.h>
  10644. #endif
  10645. #include <inc/hw_types.h>
  10646. #include <inc/hw_memmap.h>
  10647. #include <driverlib/prcm.h>
  10648. #include <driverlib/rom.h>
  10649. #include <driverlib/rom_map.h>
  10650. #include <driverlib/uart.h>
  10651. #include <driverlib/utils.h>
  10652. #define CONSOLE_UART UARTA0_BASE
  10653. #ifdef __TI_COMPILER_VERSION__
  10654. int asprintf(char **strp, const char *fmt, ...) {
  10655. va_list ap;
  10656. int len;
  10657. *strp = MG_MALLOC(BUFSIZ);
  10658. if (*strp == NULL) return -1;
  10659. va_start(ap, fmt);
  10660. len = vsnprintf(*strp, BUFSIZ, fmt, ap);
  10661. va_end(ap);
  10662. if (len > 0) {
  10663. *strp = MG_REALLOC(*strp, len + 1);
  10664. if (*strp == NULL) return -1;
  10665. }
  10666. if (len >= BUFSIZ) {
  10667. va_start(ap, fmt);
  10668. len = vsnprintf(*strp, len + 1, fmt, ap);
  10669. va_end(ap);
  10670. }
  10671. return len;
  10672. }
  10673. #if MG_TI_NO_HOST_INTERFACE
  10674. time_t HOSTtime() {
  10675. struct timeval tp;
  10676. gettimeofday(&tp, NULL);
  10677. return tp.tv_sec;
  10678. }
  10679. #endif
  10680. #endif /* __TI_COMPILER_VERSION__ */
  10681. #ifndef __TI_COMPILER_VERSION__
  10682. int _gettimeofday_r(struct _reent *r, struct timeval *tp, void *tzp) {
  10683. #else
  10684. int gettimeofday(struct timeval *tp, void *tzp) {
  10685. #endif
  10686. unsigned long long r1 = 0, r2;
  10687. /* Achieve two consecutive reads of the same value. */
  10688. do {
  10689. r2 = r1;
  10690. r1 = PRCMSlowClkCtrFastGet();
  10691. } while (r1 != r2);
  10692. /* This is a 32768 Hz counter. */
  10693. tp->tv_sec = (r1 >> 15);
  10694. /* 1/32768-th of a second is 30.517578125 microseconds, approx. 31,
  10695. * but we round down so it doesn't overflow at 32767 */
  10696. tp->tv_usec = (r1 & 0x7FFF) * 30;
  10697. return 0;
  10698. }
  10699. void fprint_str(FILE *fp, const char *str) {
  10700. while (*str != '\0') {
  10701. if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
  10702. MAP_UARTCharPut(CONSOLE_UART, *str++);
  10703. }
  10704. }
  10705. void _exit(int status) {
  10706. fprint_str(stderr, "_exit\n");
  10707. /* cause an unaligned access exception, that will drop you into gdb */
  10708. *(int *) 1 = status;
  10709. while (1)
  10710. ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
  10711. }
  10712. void _not_implemented(const char *what) {
  10713. fprint_str(stderr, what);
  10714. fprint_str(stderr, " is not implemented\n");
  10715. _exit(42);
  10716. }
  10717. int _kill(int pid, int sig) {
  10718. (void) pid;
  10719. (void) sig;
  10720. _not_implemented("_kill");
  10721. return -1;
  10722. }
  10723. int _getpid() {
  10724. fprint_str(stderr, "_getpid is not implemented\n");
  10725. return 42;
  10726. }
  10727. int _isatty(int fd) {
  10728. /* 0, 1 and 2 are TTYs. */
  10729. return fd < 2;
  10730. }
  10731. #endif /* CS_PLATFORM == CS_P_CC3200 */
  10732. #ifdef MG_MODULE_LINES
  10733. #line 1 "common/platforms/msp432/msp432_libc.c"
  10734. #endif
  10735. /*
  10736. * Copyright (c) 2014-2016 Cesanta Software Limited
  10737. * All rights reserved
  10738. */
  10739. #if CS_PLATFORM == CS_P_MSP432
  10740. #include <ti/sysbios/BIOS.h>
  10741. #include <ti/sysbios/knl/Clock.h>
  10742. int gettimeofday(struct timeval *tp, void *tzp) {
  10743. uint32_t ticks = Clock_getTicks();
  10744. tp->tv_sec = ticks / 1000;
  10745. tp->tv_usec = (ticks % 1000) * 1000;
  10746. return 0;
  10747. }
  10748. #endif /* CS_PLATFORM == CS_P_MSP432 */
  10749. #ifdef MG_MODULE_LINES
  10750. #line 1 "common/platforms/nrf5/nrf5_libc.c"
  10751. #endif
  10752. /*
  10753. * Copyright (c) 2014-2016 Cesanta Software Limited
  10754. * All rights reserved
  10755. */
  10756. #if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
  10757. defined(__ARMCC_VERSION)
  10758. int gettimeofday(struct timeval *tp, void *tzp) {
  10759. /* TODO */
  10760. tp->tv_sec = 0;
  10761. tp->tv_usec = 0;
  10762. return 0;
  10763. }
  10764. #endif
  10765. #ifdef MG_MODULE_LINES
  10766. #line 1 "common/platforms/simplelink/sl_fs_slfs.h"
  10767. #endif
  10768. /*
  10769. * Copyright (c) 2014-2016 Cesanta Software Limited
  10770. * All rights reserved
  10771. */
  10772. #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
  10773. #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
  10774. #if defined(MG_FS_SLFS)
  10775. #include <stdio.h>
  10776. #ifndef __TI_COMPILER_VERSION__
  10777. #include <unistd.h>
  10778. #include <sys/stat.h>
  10779. #endif
  10780. #define MAX_OPEN_SLFS_FILES 8
  10781. /* Indirect libc interface - same functions, different names. */
  10782. int fs_slfs_open(const char *pathname, int flags, mode_t mode);
  10783. int fs_slfs_close(int fd);
  10784. ssize_t fs_slfs_read(int fd, void *buf, size_t count);
  10785. ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
  10786. int fs_slfs_stat(const char *pathname, struct stat *s);
  10787. int fs_slfs_fstat(int fd, struct stat *s);
  10788. off_t fs_slfs_lseek(int fd, off_t offset, int whence);
  10789. int fs_slfs_unlink(const char *filename);
  10790. int fs_slfs_rename(const char *from, const char *to);
  10791. void fs_slfs_set_new_file_size(const char *name, size_t size);
  10792. #endif /* defined(MG_FS_SLFS) */
  10793. #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
  10794. #ifdef MG_MODULE_LINES
  10795. #line 1 "common/platforms/simplelink/sl_fs_slfs.c"
  10796. #endif
  10797. /*
  10798. * Copyright (c) 2014-2016 Cesanta Software Limited
  10799. * All rights reserved
  10800. */
  10801. /* Standard libc interface to TI SimpleLink FS. */
  10802. #if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
  10803. /* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
  10804. #include <errno.h>
  10805. #if CS_PLATFORM == CS_P_CC3200
  10806. #include <inc/hw_types.h>
  10807. #endif
  10808. #include <simplelink/include/simplelink.h>
  10809. #include <simplelink/include/fs.h>
  10810. /* Amalgamated: #include "common/cs_dbg.h" */
  10811. /* From sl_fs.c */
  10812. extern int set_errno(int e);
  10813. static const char *drop_dir(const char *fname, bool *is_slfs);
  10814. /*
  10815. * With SLFS, you have to pre-declare max file size. Yes. Really.
  10816. * 64K should be enough for everyone. Right?
  10817. */
  10818. #ifndef FS_SLFS_MAX_FILE_SIZE
  10819. #define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
  10820. #endif
  10821. struct sl_file_size_hint {
  10822. char *name;
  10823. size_t size;
  10824. };
  10825. struct sl_fd_info {
  10826. _i32 fh;
  10827. _off_t pos;
  10828. size_t size;
  10829. };
  10830. static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
  10831. static struct sl_file_size_hint s_sl_file_size_hints[MAX_OPEN_SLFS_FILES];
  10832. static int sl_fs_to_errno(_i32 r) {
  10833. DBG(("SL error: %d", (int) r));
  10834. switch (r) {
  10835. case SL_FS_OK:
  10836. return 0;
  10837. case SL_FS_FILE_NAME_EXIST:
  10838. return EEXIST;
  10839. case SL_FS_WRONG_FILE_NAME:
  10840. return EINVAL;
  10841. case SL_FS_ERR_NO_AVAILABLE_NV_INDEX:
  10842. case SL_FS_ERR_NO_AVAILABLE_BLOCKS:
  10843. return ENOSPC;
  10844. case SL_FS_ERR_FAILED_TO_ALLOCATE_MEM:
  10845. return ENOMEM;
  10846. case SL_FS_ERR_FILE_NOT_EXISTS:
  10847. return ENOENT;
  10848. case SL_FS_ERR_NOT_SUPPORTED:
  10849. return ENOTSUP;
  10850. }
  10851. return ENXIO;
  10852. }
  10853. int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
  10854. int fd;
  10855. for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
  10856. if (s_sl_fds[fd].fh <= 0) break;
  10857. }
  10858. if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
  10859. struct sl_fd_info *fi = &s_sl_fds[fd];
  10860. /*
  10861. * Apply path manipulations again, in case we got here directly
  10862. * (via TI libc's "add_device").
  10863. */
  10864. pathname = drop_dir(pathname, NULL);
  10865. _u32 am = 0;
  10866. fi->size = (size_t) -1;
  10867. int rw = (flags & 3);
  10868. if (rw == O_RDONLY) {
  10869. SlFsFileInfo_t sl_fi;
  10870. _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
  10871. if (r == SL_FS_OK) {
  10872. fi->size = sl_fi.FileLen;
  10873. }
  10874. am = FS_MODE_OPEN_READ;
  10875. } else {
  10876. if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
  10877. // FailFS files cannot be opened for append and will be truncated
  10878. // when opened for write.
  10879. return set_errno(ENOTSUP);
  10880. }
  10881. if (flags & O_CREAT) {
  10882. size_t i, size = FS_SLFS_MAX_FILE_SIZE;
  10883. for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
  10884. if (s_sl_file_size_hints[i].name != NULL &&
  10885. strcmp(s_sl_file_size_hints[i].name, pathname) == 0) {
  10886. size = s_sl_file_size_hints[i].size;
  10887. MG_FREE(s_sl_file_size_hints[i].name);
  10888. s_sl_file_size_hints[i].name = NULL;
  10889. break;
  10890. }
  10891. }
  10892. DBG(("creating %s with max size %d", pathname, (int) size));
  10893. am = FS_MODE_OPEN_CREATE(size, 0);
  10894. } else {
  10895. am = FS_MODE_OPEN_WRITE;
  10896. }
  10897. }
  10898. _i32 r = sl_FsOpen((_u8 *) pathname, am, NULL, &fi->fh);
  10899. DBG(("sl_FsOpen(%s, 0x%x) = %d, %d", pathname, (int) am, (int) r,
  10900. (int) fi->fh));
  10901. if (r == SL_FS_OK) {
  10902. fi->pos = 0;
  10903. r = fd;
  10904. } else {
  10905. fi->fh = -1;
  10906. r = set_errno(sl_fs_to_errno(r));
  10907. }
  10908. return r;
  10909. }
  10910. int fs_slfs_close(int fd) {
  10911. struct sl_fd_info *fi = &s_sl_fds[fd];
  10912. if (fi->fh <= 0) return set_errno(EBADF);
  10913. _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
  10914. DBG(("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
  10915. s_sl_fds[fd].fh = -1;
  10916. return set_errno(sl_fs_to_errno(r));
  10917. }
  10918. ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
  10919. struct sl_fd_info *fi = &s_sl_fds[fd];
  10920. if (fi->fh <= 0) return set_errno(EBADF);
  10921. /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
  10922. */
  10923. if (fi->pos == fi->size) return 0;
  10924. _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
  10925. DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
  10926. (int) r));
  10927. if (r >= 0) {
  10928. fi->pos += r;
  10929. return r;
  10930. }
  10931. return set_errno(sl_fs_to_errno(r));
  10932. }
  10933. ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
  10934. struct sl_fd_info *fi = &s_sl_fds[fd];
  10935. if (fi->fh <= 0) return set_errno(EBADF);
  10936. _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
  10937. DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
  10938. (int) r));
  10939. if (r >= 0) {
  10940. fi->pos += r;
  10941. return r;
  10942. }
  10943. return set_errno(sl_fs_to_errno(r));
  10944. }
  10945. int fs_slfs_stat(const char *pathname, struct stat *s) {
  10946. SlFsFileInfo_t sl_fi;
  10947. /*
  10948. * Apply path manipulations again, in case we got here directly
  10949. * (via TI libc's "add_device").
  10950. */
  10951. pathname = drop_dir(pathname, NULL);
  10952. _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
  10953. if (r == SL_FS_OK) {
  10954. s->st_mode = S_IFREG | 0666;
  10955. s->st_nlink = 1;
  10956. s->st_size = sl_fi.FileLen;
  10957. return 0;
  10958. }
  10959. return set_errno(sl_fs_to_errno(r));
  10960. }
  10961. int fs_slfs_fstat(int fd, struct stat *s) {
  10962. struct sl_fd_info *fi = &s_sl_fds[fd];
  10963. if (fi->fh <= 0) return set_errno(EBADF);
  10964. s->st_mode = 0666;
  10965. s->st_mode = S_IFREG | 0666;
  10966. s->st_nlink = 1;
  10967. s->st_size = fi->size;
  10968. return 0;
  10969. }
  10970. off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
  10971. if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
  10972. switch (whence) {
  10973. case SEEK_SET:
  10974. s_sl_fds[fd].pos = offset;
  10975. break;
  10976. case SEEK_CUR:
  10977. s_sl_fds[fd].pos += offset;
  10978. break;
  10979. case SEEK_END:
  10980. return set_errno(ENOTSUP);
  10981. }
  10982. return 0;
  10983. }
  10984. int fs_slfs_unlink(const char *pathname) {
  10985. /*
  10986. * Apply path manipulations again, in case we got here directly
  10987. * (via TI libc's "add_device").
  10988. */
  10989. pathname = drop_dir(pathname, NULL);
  10990. return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
  10991. }
  10992. int fs_slfs_rename(const char *from, const char *to) {
  10993. return set_errno(ENOTSUP);
  10994. }
  10995. void fs_slfs_set_new_file_size(const char *name, size_t size) {
  10996. int i;
  10997. for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
  10998. if (s_sl_file_size_hints[i].name == NULL) {
  10999. DBG(("File size hint: %s %d", name, (int) size));
  11000. s_sl_file_size_hints[i].name = MG_STRDUP(name);
  11001. s_sl_file_size_hints[i].size = size;
  11002. break;
  11003. }
  11004. }
  11005. }
  11006. #endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
  11007. #ifdef MG_MODULE_LINES
  11008. #line 1 "common/platforms/simplelink/sl_fs.c"
  11009. #endif
  11010. /*
  11011. * Copyright (c) 2014-2016 Cesanta Software Limited
  11012. * All rights reserved
  11013. */
  11014. #if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
  11015. (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
  11016. #include <errno.h>
  11017. #include <stdbool.h>
  11018. #include <stdio.h>
  11019. #include <stdlib.h>
  11020. #include <string.h>
  11021. #ifdef __TI_COMPILER_VERSION__
  11022. #include <file.h>
  11023. #endif
  11024. /* Amalgamated: #include "common/cs_dbg.h" */
  11025. /* Amalgamated: #include "common/platform.h" */
  11026. #ifdef CC3200_FS_SPIFFS
  11027. /* Amalgamated: #include "cc3200_fs_spiffs.h" */
  11028. #endif
  11029. #ifdef MG_FS_SLFS
  11030. /* Amalgamated: #include "sl_fs_slfs.h" */
  11031. #endif
  11032. #define NUM_SYS_FDS 3
  11033. #define SPIFFS_FD_BASE 10
  11034. #define SLFS_FD_BASE 100
  11035. #ifndef MG_UART_CHAR_PUT
  11036. #if CS_PLATFORM == CS_P_CC3200
  11037. #include <inc/hw_types.h>
  11038. #include <inc/hw_memmap.h>
  11039. #include <driverlib/rom.h>
  11040. #include <driverlib/rom_map.h>
  11041. #include <driverlib/uart.h>
  11042. #define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
  11043. #else
  11044. #define MG_UART_CHAR_PUT(fd, c)
  11045. #endif /* CS_PLATFORM == CS_P_CC3200 */
  11046. #endif /* !MG_UART_CHAR_PUT */
  11047. int set_errno(int e) {
  11048. errno = e;
  11049. return (e == 0 ? 0 : -1);
  11050. }
  11051. static const char *drop_dir(const char *fname, bool *is_slfs) {
  11052. if (is_slfs != NULL) {
  11053. *is_slfs = (strncmp(fname, "SL:", 3) == 0);
  11054. if (*is_slfs) fname += 3;
  11055. }
  11056. /* Drop "./", if any */
  11057. if (fname[0] == '.' && fname[1] == '/') {
  11058. fname += 2;
  11059. }
  11060. /*
  11061. * Drop / if it is the only one in the path.
  11062. * This allows use of /pretend/directories but serves /file.txt as normal.
  11063. */
  11064. if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
  11065. fname++;
  11066. }
  11067. return fname;
  11068. }
  11069. enum fd_type {
  11070. FD_INVALID,
  11071. FD_SYS,
  11072. #ifdef CC3200_FS_SPIFFS
  11073. FD_SPIFFS,
  11074. #endif
  11075. #ifdef MG_FS_SLFS
  11076. FD_SLFS
  11077. #endif
  11078. };
  11079. static int fd_type(int fd) {
  11080. if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
  11081. #ifdef CC3200_FS_SPIFFS
  11082. if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
  11083. return FD_SPIFFS;
  11084. }
  11085. #endif
  11086. #ifdef MG_FS_SLFS
  11087. if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
  11088. return FD_SLFS;
  11089. }
  11090. #endif
  11091. return FD_INVALID;
  11092. }
  11093. #if MG_TI_NO_HOST_INTERFACE
  11094. int open(const char *pathname, unsigned flags, int mode) {
  11095. #else
  11096. int _open(const char *pathname, int flags, mode_t mode) {
  11097. #endif
  11098. int fd = -1;
  11099. bool is_sl;
  11100. const char *fname = drop_dir(pathname, &is_sl);
  11101. if (is_sl) {
  11102. #ifdef MG_FS_SLFS
  11103. fd = fs_slfs_open(fname, flags, mode);
  11104. if (fd >= 0) fd += SLFS_FD_BASE;
  11105. #endif
  11106. } else {
  11107. #ifdef CC3200_FS_SPIFFS
  11108. fd = fs_spiffs_open(fname, flags, mode);
  11109. if (fd >= 0) fd += SPIFFS_FD_BASE;
  11110. #endif
  11111. }
  11112. LOG(LL_DEBUG,
  11113. ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
  11114. return fd;
  11115. }
  11116. int _stat(const char *pathname, struct stat *st) {
  11117. int res = -1;
  11118. bool is_sl;
  11119. const char *fname = drop_dir(pathname, &is_sl);
  11120. memset(st, 0, sizeof(*st));
  11121. /* Simulate statting the root directory. */
  11122. if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
  11123. st->st_ino = 0;
  11124. st->st_mode = S_IFDIR | 0777;
  11125. st->st_nlink = 1;
  11126. st->st_size = 0;
  11127. return 0;
  11128. }
  11129. if (is_sl) {
  11130. #ifdef MG_FS_SLFS
  11131. res = fs_slfs_stat(fname, st);
  11132. #endif
  11133. } else {
  11134. #ifdef CC3200_FS_SPIFFS
  11135. res = fs_spiffs_stat(fname, st);
  11136. #endif
  11137. }
  11138. LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
  11139. return res;
  11140. }
  11141. #if MG_TI_NO_HOST_INTERFACE
  11142. int close(int fd) {
  11143. #else
  11144. int _close(int fd) {
  11145. #endif
  11146. int r = -1;
  11147. switch (fd_type(fd)) {
  11148. case FD_INVALID:
  11149. r = set_errno(EBADF);
  11150. break;
  11151. case FD_SYS:
  11152. r = set_errno(EACCES);
  11153. break;
  11154. #ifdef CC3200_FS_SPIFFS
  11155. case FD_SPIFFS:
  11156. r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
  11157. break;
  11158. #endif
  11159. #ifdef MG_FS_SLFS
  11160. case FD_SLFS:
  11161. r = fs_slfs_close(fd - SLFS_FD_BASE);
  11162. break;
  11163. #endif
  11164. }
  11165. DBG(("close(%d) = %d", fd, r));
  11166. return r;
  11167. }
  11168. #if MG_TI_NO_HOST_INTERFACE
  11169. off_t lseek(int fd, off_t offset, int whence) {
  11170. #else
  11171. off_t _lseek(int fd, off_t offset, int whence) {
  11172. #endif
  11173. int r = -1;
  11174. switch (fd_type(fd)) {
  11175. case FD_INVALID:
  11176. r = set_errno(EBADF);
  11177. break;
  11178. case FD_SYS:
  11179. r = set_errno(ESPIPE);
  11180. break;
  11181. #ifdef CC3200_FS_SPIFFS
  11182. case FD_SPIFFS:
  11183. r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
  11184. break;
  11185. #endif
  11186. #ifdef MG_FS_SLFS
  11187. case FD_SLFS:
  11188. r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
  11189. break;
  11190. #endif
  11191. }
  11192. DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
  11193. return r;
  11194. }
  11195. int _fstat(int fd, struct stat *s) {
  11196. int r = -1;
  11197. memset(s, 0, sizeof(*s));
  11198. switch (fd_type(fd)) {
  11199. case FD_INVALID:
  11200. r = set_errno(EBADF);
  11201. break;
  11202. case FD_SYS: {
  11203. /* Create barely passable stats for STD{IN,OUT,ERR}. */
  11204. memset(s, 0, sizeof(*s));
  11205. s->st_ino = fd;
  11206. s->st_mode = S_IFCHR | 0666;
  11207. r = 0;
  11208. break;
  11209. }
  11210. #ifdef CC3200_FS_SPIFFS
  11211. case FD_SPIFFS:
  11212. r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
  11213. break;
  11214. #endif
  11215. #ifdef MG_FS_SLFS
  11216. case FD_SLFS:
  11217. r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
  11218. break;
  11219. #endif
  11220. }
  11221. DBG(("fstat(%d) = %d", fd, r));
  11222. return r;
  11223. }
  11224. #if MG_TI_NO_HOST_INTERFACE
  11225. int read(int fd, char *buf, unsigned count) {
  11226. #else
  11227. ssize_t _read(int fd, void *buf, size_t count) {
  11228. #endif
  11229. int r = -1;
  11230. switch (fd_type(fd)) {
  11231. case FD_INVALID:
  11232. r = set_errno(EBADF);
  11233. break;
  11234. case FD_SYS: {
  11235. if (fd != 0) {
  11236. r = set_errno(EACCES);
  11237. break;
  11238. }
  11239. /* Should we allow reading from stdin = uart? */
  11240. r = set_errno(ENOTSUP);
  11241. break;
  11242. }
  11243. #ifdef CC3200_FS_SPIFFS
  11244. case FD_SPIFFS:
  11245. r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
  11246. break;
  11247. #endif
  11248. #ifdef MG_FS_SLFS
  11249. case FD_SLFS:
  11250. r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
  11251. break;
  11252. #endif
  11253. }
  11254. DBG(("read(%d, %u) = %d", fd, count, r));
  11255. return r;
  11256. }
  11257. #if MG_TI_NO_HOST_INTERFACE
  11258. int write(int fd, const char *buf, unsigned count) {
  11259. #else
  11260. ssize_t _write(int fd, const void *buf, size_t count) {
  11261. #endif
  11262. int r = -1;
  11263. size_t i = 0;
  11264. switch (fd_type(fd)) {
  11265. case FD_INVALID:
  11266. r = set_errno(EBADF);
  11267. break;
  11268. case FD_SYS: {
  11269. if (fd == 0) {
  11270. r = set_errno(EACCES);
  11271. break;
  11272. }
  11273. for (i = 0; i < count; i++) {
  11274. const char c = ((const char *) buf)[i];
  11275. if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
  11276. MG_UART_CHAR_PUT(fd, c);
  11277. }
  11278. r = count;
  11279. break;
  11280. }
  11281. #ifdef CC3200_FS_SPIFFS
  11282. case FD_SPIFFS:
  11283. r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
  11284. break;
  11285. #endif
  11286. #ifdef MG_FS_SLFS
  11287. case FD_SLFS:
  11288. r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
  11289. break;
  11290. #endif
  11291. }
  11292. return r;
  11293. }
  11294. /*
  11295. * On Newlib we override rename directly too, because the default
  11296. * implementation using _link and _unlink doesn't work for us.
  11297. */
  11298. #if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
  11299. int rename(const char *frompath, const char *topath) {
  11300. int r = -1;
  11301. bool is_sl_from, is_sl_to;
  11302. const char *from = drop_dir(frompath, &is_sl_from);
  11303. const char *to = drop_dir(topath, &is_sl_to);
  11304. if (is_sl_from || is_sl_to) {
  11305. set_errno(ENOTSUP);
  11306. } else {
  11307. #ifdef CC3200_FS_SPIFFS
  11308. r = fs_spiffs_rename(from, to);
  11309. #endif
  11310. }
  11311. DBG(("rename(%s, %s) = %d", from, to, r));
  11312. return r;
  11313. }
  11314. #endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
  11315. #if MG_TI_NO_HOST_INTERFACE
  11316. int unlink(const char *pathname) {
  11317. #else
  11318. int _unlink(const char *pathname) {
  11319. #endif
  11320. int r = -1;
  11321. bool is_sl;
  11322. const char *fname = drop_dir(pathname, &is_sl);
  11323. if (is_sl) {
  11324. #ifdef MG_FS_SLFS
  11325. r = fs_slfs_unlink(fname);
  11326. #endif
  11327. } else {
  11328. #ifdef CC3200_FS_SPIFFS
  11329. r = fs_spiffs_unlink(fname);
  11330. #endif
  11331. }
  11332. DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
  11333. return r;
  11334. }
  11335. #ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
  11336. DIR *opendir(const char *dir_name) {
  11337. DIR *r = NULL;
  11338. bool is_sl;
  11339. drop_dir(dir_name, &is_sl);
  11340. if (is_sl) {
  11341. r = NULL;
  11342. set_errno(ENOTSUP);
  11343. } else {
  11344. r = fs_spiffs_opendir(dir_name);
  11345. }
  11346. DBG(("opendir(%s) = %p", dir_name, r));
  11347. return r;
  11348. }
  11349. struct dirent *readdir(DIR *dir) {
  11350. struct dirent *res = fs_spiffs_readdir(dir);
  11351. DBG(("readdir(%p) = %p", dir, res));
  11352. return res;
  11353. }
  11354. int closedir(DIR *dir) {
  11355. int res = fs_spiffs_closedir(dir);
  11356. DBG(("closedir(%p) = %d", dir, res));
  11357. return res;
  11358. }
  11359. int rmdir(const char *path) {
  11360. return fs_spiffs_rmdir(path);
  11361. }
  11362. int mkdir(const char *path, mode_t mode) {
  11363. (void) path;
  11364. (void) mode;
  11365. /* for spiffs supports only root dir, which comes from mongoose as '.' */
  11366. return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
  11367. }
  11368. #endif
  11369. int sl_fs_init(void) {
  11370. int ret = 1;
  11371. #ifdef __TI_COMPILER_VERSION__
  11372. #ifdef MG_FS_SLFS
  11373. #pragma diag_push
  11374. #pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
  11375. */
  11376. ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
  11377. fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
  11378. fs_slfs_rename) == 0);
  11379. #pragma diag_pop
  11380. #endif
  11381. #endif
  11382. return ret;
  11383. }
  11384. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
  11385. defined(MG_FS_SPIFFS)) */
  11386. #ifdef MG_MODULE_LINES
  11387. #line 1 "common/platforms/simplelink/sl_socket.c"
  11388. #endif
  11389. /*
  11390. * Copyright (c) 2014-2016 Cesanta Software Limited
  11391. * All rights reserved
  11392. */
  11393. #if MG_NET_IF == MG_NET_IF_SIMPLELINK
  11394. #include <errno.h>
  11395. #include <stdio.h>
  11396. /* Amalgamated: #include "common/platform.h" */
  11397. const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
  11398. int res;
  11399. struct in_addr *in = (struct in_addr *) src;
  11400. if (af != AF_INET) {
  11401. errno = EAFNOSUPPORT;
  11402. return NULL;
  11403. }
  11404. res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
  11405. SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
  11406. SL_IPV4_BYTE(in->s_addr, 3));
  11407. return res > 0 ? dst : NULL;
  11408. }
  11409. char *inet_ntoa(struct in_addr n) {
  11410. static char a[16];
  11411. return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
  11412. }
  11413. int inet_pton(int af, const char *src, void *dst) {
  11414. uint32_t a0, a1, a2, a3;
  11415. uint8_t *db = (uint8_t *) dst;
  11416. if (af != AF_INET) {
  11417. errno = EAFNOSUPPORT;
  11418. return 0;
  11419. }
  11420. if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
  11421. return 0;
  11422. }
  11423. *db = a3;
  11424. *(db + 1) = a2;
  11425. *(db + 2) = a1;
  11426. *(db + 3) = a0;
  11427. return 1;
  11428. }
  11429. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
  11430. #ifdef MG_MODULE_LINES
  11431. #line 1 "common/platforms/simplelink/sl_mg_task.c"
  11432. #endif
  11433. #if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
  11434. /* Amalgamated: #include "mg_task.h" */
  11435. #include <oslib/osi.h>
  11436. enum mg_q_msg_type {
  11437. MG_Q_MSG_CB,
  11438. };
  11439. struct mg_q_msg {
  11440. enum mg_q_msg_type type;
  11441. void (*cb)(struct mg_mgr *mgr, void *arg);
  11442. void *arg;
  11443. };
  11444. static OsiMsgQ_t s_mg_q;
  11445. static void mg_task(void *arg);
  11446. bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
  11447. if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
  11448. return false;
  11449. }
  11450. if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
  11451. (void *) mg_init, priority, NULL) != OSI_OK) {
  11452. return false;
  11453. }
  11454. return true;
  11455. }
  11456. static void mg_task(void *arg) {
  11457. struct mg_mgr mgr;
  11458. mg_init_cb mg_init = (mg_init_cb) arg;
  11459. mg_mgr_init(&mgr, NULL);
  11460. mg_init(&mgr);
  11461. while (1) {
  11462. struct mg_q_msg msg;
  11463. mg_mgr_poll(&mgr, 1);
  11464. if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
  11465. switch (msg.type) {
  11466. case MG_Q_MSG_CB: {
  11467. msg.cb(&mgr, msg.arg);
  11468. }
  11469. }
  11470. }
  11471. }
  11472. void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
  11473. struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
  11474. osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
  11475. }
  11476. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
  11477. */
  11478. #ifdef MG_MODULE_LINES
  11479. #line 1 "common/platforms/simplelink/sl_net_if.h"
  11480. #endif
  11481. /*
  11482. * Copyright (c) 2014-2016 Cesanta Software Limited
  11483. * All rights reserved
  11484. */
  11485. #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
  11486. #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
  11487. /* Amalgamated: #include "mongoose/src/net_if.h" */
  11488. #ifdef __cplusplus
  11489. extern "C" {
  11490. #endif /* __cplusplus */
  11491. #ifndef MG_ENABLE_NET_IF_SIMPLELINK
  11492. #define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
  11493. #endif
  11494. extern struct mg_iface_vtable mg_simplelink_iface_vtable;
  11495. #ifdef __cplusplus
  11496. }
  11497. #endif /* __cplusplus */
  11498. #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
  11499. #ifdef MG_MODULE_LINES
  11500. #line 1 "common/platforms/simplelink/sl_net_if.c"
  11501. #endif
  11502. /*
  11503. * Copyright (c) 2014-2016 Cesanta Software Limited
  11504. * All rights reserved
  11505. */
  11506. /* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
  11507. #if MG_ENABLE_NET_IF_SIMPLELINK
  11508. /* Amalgamated: #include "mongoose/src/internal.h" */
  11509. /* Amalgamated: #include "mongoose/src/util.h" */
  11510. #define MG_TCP_RECV_BUFFER_SIZE 1024
  11511. #define MG_UDP_RECV_BUFFER_SIZE 1500
  11512. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  11513. int proto);
  11514. int sl_set_ssl_opts(struct mg_connection *nc);
  11515. void mg_set_non_blocking_mode(sock_t sock) {
  11516. SlSockNonblocking_t opt;
  11517. opt.NonblockingEnabled = 1;
  11518. sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
  11519. }
  11520. static int mg_is_error(int n) {
  11521. return (n < 0 && n != SL_EALREADY && n != SL_EAGAIN);
  11522. }
  11523. void mg_sl_if_connect_tcp(struct mg_connection *nc,
  11524. const union socket_address *sa) {
  11525. int proto = 0;
  11526. if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
  11527. sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
  11528. if (sock < 0) {
  11529. nc->err = sock;
  11530. goto out;
  11531. }
  11532. mg_sock_set(nc, sock);
  11533. #if MG_ENABLE_SSL
  11534. nc->err = sl_set_ssl_opts(nc);
  11535. if (nc->err != 0) goto out;
  11536. #endif
  11537. nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
  11538. out:
  11539. DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
  11540. ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
  11541. }
  11542. void mg_sl_if_connect_udp(struct mg_connection *nc) {
  11543. sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
  11544. if (sock < 0) {
  11545. nc->err = sock;
  11546. return;
  11547. }
  11548. mg_sock_set(nc, sock);
  11549. nc->err = 0;
  11550. }
  11551. int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  11552. int proto = 0;
  11553. if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
  11554. sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
  11555. if (sock < 0) return sock;
  11556. mg_sock_set(nc, sock);
  11557. #if MG_ENABLE_SSL
  11558. return sl_set_ssl_opts(nc);
  11559. #else
  11560. return 0;
  11561. #endif
  11562. }
  11563. int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  11564. sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
  11565. if (sock == INVALID_SOCKET) return (errno ? errno : 1);
  11566. mg_sock_set(nc, sock);
  11567. return 0;
  11568. }
  11569. void mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
  11570. mbuf_append(&nc->send_mbuf, buf, len);
  11571. }
  11572. void mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
  11573. mbuf_append(&nc->send_mbuf, buf, len);
  11574. }
  11575. void mg_sl_if_recved(struct mg_connection *nc, size_t len) {
  11576. (void) nc;
  11577. (void) len;
  11578. }
  11579. int mg_sl_if_create_conn(struct mg_connection *nc) {
  11580. (void) nc;
  11581. return 1;
  11582. }
  11583. void mg_sl_if_destroy_conn(struct mg_connection *nc) {
  11584. if (nc->sock == INVALID_SOCKET) return;
  11585. /* For UDP, only close outgoing sockets or listeners. */
  11586. if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
  11587. sl_Close(nc->sock);
  11588. }
  11589. nc->sock = INVALID_SOCKET;
  11590. }
  11591. static int mg_accept_conn(struct mg_connection *lc) {
  11592. struct mg_connection *nc;
  11593. union socket_address sa;
  11594. socklen_t sa_len = sizeof(sa);
  11595. sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
  11596. if (sock < 0) {
  11597. DBG(("%p: failed to accept: %d", lc, sock));
  11598. return 0;
  11599. }
  11600. nc = mg_if_accept_new_conn(lc);
  11601. if (nc == NULL) {
  11602. sl_Close(sock);
  11603. return 0;
  11604. }
  11605. DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
  11606. ntohs(sa.sin.sin_port)));
  11607. mg_sock_set(nc, sock);
  11608. if (nc->flags & MG_F_SSL) nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
  11609. mg_if_accept_tcp_cb(nc, &sa, sa_len);
  11610. return 1;
  11611. }
  11612. /* 'sa' must be an initialized address to bind to */
  11613. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  11614. int proto) {
  11615. int r;
  11616. socklen_t sa_len =
  11617. (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
  11618. sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
  11619. if (sock < 0) return sock;
  11620. if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) {
  11621. sl_Close(sock);
  11622. return r;
  11623. }
  11624. if (type != SOCK_DGRAM && (r = sl_Listen(sock, SOMAXCONN)) < 0) {
  11625. sl_Close(sock);
  11626. return r;
  11627. }
  11628. mg_set_non_blocking_mode(sock);
  11629. return sock;
  11630. }
  11631. static void mg_write_to_socket(struct mg_connection *nc) {
  11632. struct mbuf *io = &nc->send_mbuf;
  11633. int n = 0;
  11634. if (nc->flags & MG_F_UDP) {
  11635. n = sl_SendTo(nc->sock, io->buf, io->len, 0, &nc->sa.sa,
  11636. sizeof(nc->sa.sin));
  11637. DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
  11638. inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
  11639. } else {
  11640. n = (int) sl_Send(nc->sock, io->buf, io->len, 0);
  11641. DBG(("%p %d bytes -> %d", nc, n, nc->sock));
  11642. }
  11643. if (n > 0) {
  11644. mbuf_remove(io, n);
  11645. mg_if_sent_cb(nc, n);
  11646. } else if (n < 0 && mg_is_error(n)) {
  11647. /* Something went wrong, drop the connection. */
  11648. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  11649. }
  11650. }
  11651. MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
  11652. size_t avail;
  11653. if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
  11654. avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
  11655. return avail > max ? max : avail;
  11656. }
  11657. static void mg_handle_tcp_read(struct mg_connection *conn) {
  11658. int n = 0;
  11659. char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
  11660. if (buf == NULL) {
  11661. DBG(("OOM"));
  11662. return;
  11663. }
  11664. n = (int) sl_Recv(conn->sock, buf,
  11665. recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
  11666. DBG(("%p %d bytes <- %d", conn, n, conn->sock));
  11667. if (n > 0) {
  11668. mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
  11669. } else {
  11670. MG_FREE(buf);
  11671. }
  11672. if (n == 0) {
  11673. /* Orderly shutdown of the socket, try flushing output. */
  11674. conn->flags |= MG_F_SEND_AND_CLOSE;
  11675. } else if (mg_is_error(n)) {
  11676. conn->flags |= MG_F_CLOSE_IMMEDIATELY;
  11677. }
  11678. }
  11679. static void mg_handle_udp_read(struct mg_connection *nc) {
  11680. char *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
  11681. if (buf == NULL) return;
  11682. union socket_address sa;
  11683. socklen_t sa_len = sizeof(sa);
  11684. int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
  11685. (SlSockAddr_t *) &sa, &sa_len);
  11686. DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
  11687. ntohs(nc->sa.sin.sin_port)));
  11688. if (n > 0) {
  11689. mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
  11690. } else {
  11691. MG_FREE(buf);
  11692. }
  11693. }
  11694. #define _MG_F_FD_CAN_READ 1
  11695. #define _MG_F_FD_CAN_WRITE 1 << 1
  11696. #define _MG_F_FD_ERROR 1 << 2
  11697. void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
  11698. DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
  11699. fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  11700. if (nc->flags & MG_F_CONNECTING) {
  11701. if (nc->flags & MG_F_UDP || nc->err != SL_EALREADY) {
  11702. mg_if_connect_cb(nc, nc->err);
  11703. } else {
  11704. /* In SimpleLink, to get status of non-blocking connect() we need to wait
  11705. * until socket is writable and repeat the call to sl_Connect again,
  11706. * which will now return the real status. */
  11707. if (fd_flags & _MG_F_FD_CAN_WRITE) {
  11708. nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
  11709. DBG(("%p conn res=%d", nc, nc->err));
  11710. if (nc->err == SL_ESECSNOVERIFY ||
  11711. /* TODO(rojer): Provide API to set the date for verification. */
  11712. nc->err == SL_ESECDATEERROR) {
  11713. nc->err = 0;
  11714. }
  11715. if (nc->flags & MG_F_SSL && nc->err == 0) {
  11716. nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
  11717. }
  11718. mg_if_connect_cb(nc, nc->err);
  11719. }
  11720. }
  11721. /* Ignore read/write in further processing, we've handled it. */
  11722. fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
  11723. }
  11724. if (fd_flags & _MG_F_FD_CAN_READ) {
  11725. if (nc->flags & MG_F_UDP) {
  11726. mg_handle_udp_read(nc);
  11727. } else {
  11728. if (nc->flags & MG_F_LISTENING) {
  11729. mg_accept_conn(nc);
  11730. } else {
  11731. mg_handle_tcp_read(nc);
  11732. }
  11733. }
  11734. }
  11735. if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
  11736. if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
  11737. mg_write_to_socket(nc);
  11738. }
  11739. if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
  11740. mg_if_poll(nc, now);
  11741. }
  11742. mg_if_timer(nc, now);
  11743. }
  11744. DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
  11745. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  11746. }
  11747. /* Associate a socket to a connection. */
  11748. void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
  11749. mg_set_non_blocking_mode(sock);
  11750. nc->sock = sock;
  11751. DBG(("%p %d", nc, sock));
  11752. }
  11753. void mg_sl_if_init(struct mg_iface *iface) {
  11754. (void) iface;
  11755. DBG(("%p using sl_Select()", iface->mgr));
  11756. }
  11757. void mg_sl_if_free(struct mg_iface *iface) {
  11758. (void) iface;
  11759. }
  11760. void mg_sl_if_add_conn(struct mg_connection *nc) {
  11761. (void) nc;
  11762. }
  11763. void mg_sl_if_remove_conn(struct mg_connection *nc) {
  11764. (void) nc;
  11765. }
  11766. time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
  11767. struct mg_mgr *mgr = iface->mgr;
  11768. double now = mg_time();
  11769. double min_timer;
  11770. struct mg_connection *nc, *tmp;
  11771. struct SlTimeval_t tv;
  11772. SlFdSet_t read_set, write_set, err_set;
  11773. sock_t max_fd = INVALID_SOCKET;
  11774. int num_fds, num_ev = 0, num_timers = 0;
  11775. SL_FD_ZERO(&read_set);
  11776. SL_FD_ZERO(&write_set);
  11777. SL_FD_ZERO(&err_set);
  11778. /*
  11779. * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
  11780. * e.g. timer-only "connections".
  11781. */
  11782. min_timer = 0;
  11783. for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
  11784. tmp = nc->next;
  11785. if (nc->sock != INVALID_SOCKET) {
  11786. num_fds++;
  11787. if (!(nc->flags & MG_F_WANT_WRITE) &&
  11788. nc->recv_mbuf.len < nc->recv_mbuf_limit &&
  11789. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
  11790. SL_FD_SET(nc->sock, &read_set);
  11791. if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
  11792. }
  11793. if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
  11794. (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
  11795. SL_FD_SET(nc->sock, &write_set);
  11796. SL_FD_SET(nc->sock, &err_set);
  11797. if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
  11798. }
  11799. }
  11800. if (nc->ev_timer_time > 0) {
  11801. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  11802. min_timer = nc->ev_timer_time;
  11803. }
  11804. num_timers++;
  11805. }
  11806. }
  11807. /*
  11808. * If there is a timer to be fired earlier than the requested timeout,
  11809. * adjust the timeout.
  11810. */
  11811. if (num_timers > 0) {
  11812. double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
  11813. if (timer_timeout_ms < timeout_ms) {
  11814. timeout_ms = timer_timeout_ms;
  11815. }
  11816. }
  11817. if (timeout_ms < 0) timeout_ms = 0;
  11818. tv.tv_sec = timeout_ms / 1000;
  11819. tv.tv_usec = (timeout_ms % 1000) * 1000;
  11820. if (num_fds > 0) {
  11821. num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
  11822. }
  11823. now = mg_time();
  11824. DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
  11825. num_fds, timeout_ms));
  11826. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  11827. int fd_flags = 0;
  11828. if (nc->sock != INVALID_SOCKET) {
  11829. if (num_ev > 0) {
  11830. fd_flags =
  11831. (SL_FD_ISSET(nc->sock, &read_set) &&
  11832. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
  11833. ? _MG_F_FD_CAN_READ
  11834. : 0) |
  11835. (SL_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
  11836. (SL_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
  11837. }
  11838. /* SimpleLink does not report UDP sockets as writeable. */
  11839. if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
  11840. fd_flags |= _MG_F_FD_CAN_WRITE;
  11841. }
  11842. }
  11843. tmp = nc->next;
  11844. mg_mgr_handle_conn(nc, fd_flags, now);
  11845. }
  11846. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  11847. tmp = nc->next;
  11848. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  11849. (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
  11850. mg_close_conn(nc);
  11851. }
  11852. }
  11853. return now;
  11854. }
  11855. void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
  11856. union socket_address *sa) {
  11857. /* SimpleLink does not provide a way to get socket's peer address after
  11858. * accept or connect. Address hould have been preserved in the connection,
  11859. * so we do our best here by using it. */
  11860. if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
  11861. }
  11862. void sl_restart_cb(struct mg_mgr *mgr) {
  11863. /*
  11864. * SimpleLink has been restarted, meaning all sockets have been invalidated.
  11865. * We try our best - we'll restart the listeners, but for outgoing
  11866. * connections we have no option but to terminate.
  11867. */
  11868. struct mg_connection *nc;
  11869. for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
  11870. if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
  11871. if (nc->flags & MG_F_LISTENING) {
  11872. DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
  11873. ntohs(nc->sa.sin.sin_port)));
  11874. int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
  11875. : mg_sl_if_listen_tcp(nc, &nc->sa));
  11876. if (res == 0) continue;
  11877. /* Well, we tried and failed. Fall through to closing. */
  11878. }
  11879. nc->sock = INVALID_SOCKET;
  11880. DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
  11881. ntohs(nc->sa.sin.sin_port)));
  11882. /* TODO(rojer): Outgoing UDP? */
  11883. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  11884. }
  11885. }
  11886. /* clang-format off */
  11887. #define MG_SL_IFACE_VTABLE \
  11888. { \
  11889. mg_sl_if_init, \
  11890. mg_sl_if_free, \
  11891. mg_sl_if_add_conn, \
  11892. mg_sl_if_remove_conn, \
  11893. mg_sl_if_poll, \
  11894. mg_sl_if_listen_tcp, \
  11895. mg_sl_if_listen_udp, \
  11896. mg_sl_if_connect_tcp, \
  11897. mg_sl_if_connect_udp, \
  11898. mg_sl_if_tcp_send, \
  11899. mg_sl_if_udp_send, \
  11900. mg_sl_if_recved, \
  11901. mg_sl_if_create_conn, \
  11902. mg_sl_if_destroy_conn, \
  11903. mg_sl_if_sock_set, \
  11904. mg_sl_if_get_conn_addr, \
  11905. }
  11906. /* clang-format on */
  11907. struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
  11908. #if MG_NET_IF == MG_NET_IF_SIMPLELINK
  11909. struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
  11910. #endif
  11911. #endif /* MG_ENABLE_NET_IF_SIMPLELINK */
  11912. #ifdef MG_MODULE_LINES
  11913. #line 1 "common/platforms/simplelink/sl_ssl_if.c"
  11914. #endif
  11915. /*
  11916. * Copyright (c) 2014-2016 Cesanta Software Limited
  11917. * All rights reserved
  11918. */
  11919. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
  11920. struct mg_ssl_if_ctx {
  11921. char *ssl_cert;
  11922. char *ssl_key;
  11923. char *ssl_ca_cert;
  11924. char *ssl_server_name;
  11925. };
  11926. void mg_ssl_if_init() {
  11927. }
  11928. enum mg_ssl_if_result mg_ssl_if_conn_init(
  11929. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  11930. const char **err_msg) {
  11931. struct mg_ssl_if_ctx *ctx =
  11932. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  11933. if (ctx == NULL) {
  11934. MG_SET_PTRPTR(err_msg, "Out of memory");
  11935. return MG_SSL_ERROR;
  11936. }
  11937. nc->ssl_if_data = ctx;
  11938. if (params->cert != NULL || params->key != NULL) {
  11939. if (params->cert != NULL && params->key != NULL) {
  11940. ctx->ssl_cert = MG_STRDUP(params->cert);
  11941. ctx->ssl_key = MG_STRDUP(params->key);
  11942. } else {
  11943. MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
  11944. return MG_SSL_ERROR;
  11945. }
  11946. }
  11947. if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
  11948. ctx->ssl_ca_cert = MG_STRDUP(params->ca_cert);
  11949. }
  11950. /* TODO(rojer): cipher_suites. */
  11951. if (params->server_name != NULL) {
  11952. ctx->ssl_server_name = MG_STRDUP(params->server_name);
  11953. }
  11954. return MG_SSL_OK;
  11955. }
  11956. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  11957. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  11958. if (ctx == NULL) return;
  11959. nc->ssl_if_data = NULL;
  11960. MG_FREE(ctx->ssl_cert);
  11961. MG_FREE(ctx->ssl_key);
  11962. MG_FREE(ctx->ssl_ca_cert);
  11963. MG_FREE(ctx->ssl_server_name);
  11964. memset(ctx, 0, sizeof(*ctx));
  11965. MG_FREE(ctx);
  11966. }
  11967. bool pem_to_der(const char *pem_file, const char *der_file) {
  11968. bool ret = false;
  11969. FILE *pf = NULL, *df = NULL;
  11970. bool writing = false;
  11971. pf = fopen(pem_file, "r");
  11972. if (pf == NULL) goto clean;
  11973. remove(der_file);
  11974. fs_slfs_set_new_file_size(der_file + 3, 2048);
  11975. df = fopen(der_file, "w");
  11976. if (df == NULL) goto clean;
  11977. while (1) {
  11978. char pem_buf[70];
  11979. char der_buf[48];
  11980. if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
  11981. if (writing) {
  11982. if (strstr(pem_buf, "-----END ") != NULL) {
  11983. ret = true;
  11984. break;
  11985. }
  11986. int l = 0;
  11987. while (!isspace((unsigned int) pem_buf[l])) l++;
  11988. int der_len = 0;
  11989. cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
  11990. der_buf, &der_len);
  11991. if (der_len <= 0) break;
  11992. if (fwrite(der_buf, 1, der_len, df) != der_len) break;
  11993. } else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
  11994. writing = true;
  11995. }
  11996. }
  11997. clean:
  11998. if (pf != NULL) fclose(pf);
  11999. if (df != NULL) {
  12000. fclose(df);
  12001. if (!ret) remove(der_file);
  12002. }
  12003. return ret;
  12004. }
  12005. #if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
  12006. /* If the file's extension is .pem, convert it to DER format and put on SLFS. */
  12007. static char *sl_pem2der(const char *pem_file) {
  12008. const char *pem_ext = strstr(pem_file, ".pem");
  12009. if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
  12010. return MG_STRDUP(pem_file);
  12011. }
  12012. char *der_file = NULL;
  12013. /* DER file must be located on SLFS, add prefix. */
  12014. int l = mg_asprintf(&der_file, 0, "SL:%.*s.der", (int) (pem_ext - pem_file),
  12015. pem_file);
  12016. if (der_file == NULL) return NULL;
  12017. bool result = false;
  12018. cs_stat_t st;
  12019. if (mg_stat(der_file, &st) != 0) {
  12020. result = pem_to_der(pem_file, der_file);
  12021. LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
  12022. } else {
  12023. /* File exists, assume it's already been converted. */
  12024. result = true;
  12025. }
  12026. if (result) {
  12027. /* Strip the SL: prefix we added since NWP does not expect it. */
  12028. memmove(der_file, der_file + 3, l - 2 /* including \0 */);
  12029. } else {
  12030. MG_FREE(der_file);
  12031. der_file = NULL;
  12032. }
  12033. return der_file;
  12034. }
  12035. #else
  12036. static char *sl_pem2der(const char *pem_file) {
  12037. return MG_STRDUP(pem_file);
  12038. }
  12039. #endif
  12040. int sl_set_ssl_opts(struct mg_connection *nc) {
  12041. int err;
  12042. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  12043. DBG(("%p ssl ctx: %p", nc, ctx));
  12044. if (ctx != NULL) {
  12045. DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
  12046. (ctx->ssl_key ? ctx->ssl_cert : "-"),
  12047. (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
  12048. (ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
  12049. if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
  12050. char *ssl_cert = sl_pem2der(ctx->ssl_cert);
  12051. char *ssl_key = sl_pem2der(ctx->ssl_key);
  12052. if (ssl_cert != NULL && ssl_key != NULL) {
  12053. err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
  12054. SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
  12055. strlen(ssl_cert));
  12056. LOG(LL_INFO, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
  12057. err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
  12058. SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
  12059. strlen(ssl_key));
  12060. LOG(LL_INFO, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
  12061. } else {
  12062. err = -1;
  12063. }
  12064. MG_FREE(ssl_cert);
  12065. MG_FREE(ssl_key);
  12066. if (err != 0) return err;
  12067. }
  12068. if (ctx->ssl_ca_cert != NULL) {
  12069. if (ctx->ssl_ca_cert[0] != '\0') {
  12070. char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
  12071. if (ssl_ca_cert != NULL) {
  12072. err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
  12073. SL_SO_SECURE_FILES_CA_FILE_NAME, ssl_ca_cert,
  12074. strlen(ssl_ca_cert));
  12075. LOG(LL_INFO, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
  12076. } else {
  12077. err = -1;
  12078. }
  12079. MG_FREE(ssl_ca_cert);
  12080. if (err != 0) return err;
  12081. }
  12082. }
  12083. if (ctx->ssl_server_name != NULL) {
  12084. err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
  12085. SO_SECURE_DOMAIN_NAME_VERIFICATION,
  12086. ctx->ssl_server_name, strlen(ctx->ssl_server_name));
  12087. DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
  12088. /* Domain name verificationw as added in a NWP service pack, older
  12089. * versions return SL_ENOPROTOOPT. There isn't much we can do about it,
  12090. * so we ignore the error. */
  12091. if (err != 0 && err != SL_ENOPROTOOPT) return err;
  12092. }
  12093. }
  12094. return 0;
  12095. }
  12096. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
  12097. #ifdef MG_MODULE_LINES
  12098. #line 1 "common/platforms/lwip/mg_lwip_net_if.h"
  12099. #endif
  12100. /*
  12101. * Copyright (c) 2014-2016 Cesanta Software Limited
  12102. * All rights reserved
  12103. */
  12104. #ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
  12105. #define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
  12106. #ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  12107. #define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  12108. #endif
  12109. #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  12110. #include <stdint.h>
  12111. extern struct mg_iface_vtable mg_lwip_iface_vtable;
  12112. struct mg_lwip_conn_state {
  12113. struct mg_connection *nc;
  12114. struct mg_connection *lc;
  12115. union {
  12116. struct tcp_pcb *tcp;
  12117. struct udp_pcb *udp;
  12118. } pcb;
  12119. err_t err;
  12120. size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
  12121. struct pbuf *rx_chain; /* Chain of incoming data segments. */
  12122. size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
  12123. /* Last SSL write size, for retries. */
  12124. int last_ssl_write_size;
  12125. /* Whether MG_SIG_RECV is already pending for this connection */
  12126. int recv_pending;
  12127. };
  12128. enum mg_sig_type {
  12129. MG_SIG_CONNECT_RESULT = 1,
  12130. MG_SIG_RECV = 2,
  12131. MG_SIG_SENT_CB = 3,
  12132. MG_SIG_CLOSE_CONN = 4,
  12133. MG_SIG_TOMBSTONE = 5,
  12134. MG_SIG_ACCEPT = 6,
  12135. };
  12136. void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
  12137. /* To be implemented by the platform. */
  12138. void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
  12139. #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
  12140. #endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
  12141. #ifdef MG_MODULE_LINES
  12142. #line 1 "common/platforms/lwip/mg_lwip_net_if.c"
  12143. #endif
  12144. /*
  12145. * Copyright (c) 2014-2016 Cesanta Software Limited
  12146. * All rights reserved
  12147. */
  12148. #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  12149. #include <lwip/pbuf.h>
  12150. #include <lwip/tcp.h>
  12151. #if CS_PLATFORM != CS_P_STM32
  12152. #include <lwip/tcp_impl.h>
  12153. #endif
  12154. #include <lwip/udp.h>
  12155. /* Amalgamated: #include "common/cs_dbg.h" */
  12156. /*
  12157. * Depending on whether Mongoose is compiled with ipv6 support, use right
  12158. * lwip functions
  12159. */
  12160. #if MG_ENABLE_IPV6
  12161. #define TCP_NEW tcp_new_ip6
  12162. #define TCP_BIND tcp_bind_ip6
  12163. #define UDP_BIND udp_bind_ip6
  12164. #define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
  12165. #define SET_ADDR(dst, src) \
  12166. memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
  12167. sizeof((dst)->sin6.sin6_addr.s6_addr))
  12168. #else
  12169. #define TCP_NEW tcp_new
  12170. #define TCP_BIND tcp_bind
  12171. #define UDP_BIND udp_bind
  12172. #define IPADDR_NTOA ipaddr_ntoa
  12173. #define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = GET_IPV4(src)
  12174. #endif
  12175. /*
  12176. * If lwip is compiled with ipv6 support, then API changes even for ipv4
  12177. */
  12178. #if !defined(LWIP_IPV6) || !LWIP_IPV6
  12179. #define GET_IPV4(ipX_addr) ((ipX_addr)->addr)
  12180. #else
  12181. #define GET_IPV4(ipX_addr) ((ipX_addr)->ip4.addr)
  12182. #endif
  12183. void mg_lwip_ssl_do_hs(struct mg_connection *nc);
  12184. void mg_lwip_ssl_send(struct mg_connection *nc);
  12185. void mg_lwip_ssl_recv(struct mg_connection *nc);
  12186. void mg_lwip_if_init(struct mg_iface *iface);
  12187. void mg_lwip_if_free(struct mg_iface *iface);
  12188. void mg_lwip_if_add_conn(struct mg_connection *nc);
  12189. void mg_lwip_if_remove_conn(struct mg_connection *nc);
  12190. time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
  12191. #ifdef RTOS_SDK
  12192. extern void mgos_lock();
  12193. extern void mgos_unlock();
  12194. #else
  12195. #define mgos_lock()
  12196. #define mgos_unlock()
  12197. #endif
  12198. static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
  12199. #if LWIP_TCP_KEEPALIVE
  12200. void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
  12201. int interval, int count) {
  12202. if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
  12203. return;
  12204. }
  12205. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12206. struct tcp_pcb *tpcb = cs->pcb.tcp;
  12207. if (idle > 0 && interval > 0 && count > 0) {
  12208. tpcb->keep_idle = idle * 1000;
  12209. tpcb->keep_intvl = interval * 1000;
  12210. tpcb->keep_cnt = count;
  12211. tpcb->so_options |= SOF_KEEPALIVE;
  12212. } else {
  12213. tpcb->so_options &= ~SOF_KEEPALIVE;
  12214. }
  12215. }
  12216. #elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
  12217. #warning LWIP TCP keepalive is disabled. Please consider enabling it.
  12218. #endif /* LWIP_TCP_KEEPALIVE */
  12219. static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
  12220. struct mg_connection *nc = (struct mg_connection *) arg;
  12221. DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
  12222. tpcb->remote_port, err));
  12223. if (nc == NULL) {
  12224. tcp_abort(tpcb);
  12225. return ERR_ARG;
  12226. }
  12227. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12228. cs->err = err;
  12229. #if LWIP_TCP_KEEPALIVE
  12230. if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
  12231. #endif
  12232. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12233. return ERR_OK;
  12234. }
  12235. static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
  12236. struct mg_connection *nc = (struct mg_connection *) arg;
  12237. DBG(("%p conn error %d", nc, err));
  12238. if (nc == NULL) return;
  12239. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12240. cs->pcb.tcp = NULL; /* Has already been deallocated */
  12241. if (nc->flags & MG_F_CONNECTING) {
  12242. cs->err = err;
  12243. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12244. } else {
  12245. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12246. }
  12247. }
  12248. static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
  12249. struct pbuf *p, err_t err) {
  12250. struct mg_connection *nc = (struct mg_connection *) arg;
  12251. DBG(("%p %p %u %d", nc, tpcb, (p != NULL ? p->tot_len : 0), err));
  12252. if (p == NULL) {
  12253. if (nc != NULL) {
  12254. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12255. } else {
  12256. /* Tombstoned connection, do nothing. */
  12257. }
  12258. return ERR_OK;
  12259. } else if (nc == NULL) {
  12260. tcp_abort(tpcb);
  12261. return ERR_ARG;
  12262. }
  12263. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12264. /*
  12265. * If we get a chain of more than one segment at once, we need to bump
  12266. * refcount on the subsequent bufs to make them independent.
  12267. */
  12268. if (p->next != NULL) {
  12269. struct pbuf *q = p->next;
  12270. for (; q != NULL; q = q->next) pbuf_ref(q);
  12271. }
  12272. if (cs->rx_chain == NULL) {
  12273. cs->rx_offset = 0;
  12274. } else if (pbuf_clen(cs->rx_chain) >= 4) {
  12275. /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
  12276. * will be completely blocked. We already have at least 4 in the chain,
  12277. * this one is, so we have to make a copy and release this one. */
  12278. struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
  12279. if (np != NULL) {
  12280. pbuf_copy(np, p);
  12281. pbuf_free(p);
  12282. p = np;
  12283. }
  12284. }
  12285. mg_lwip_recv_common(nc, p);
  12286. return ERR_OK;
  12287. }
  12288. static void mg_lwip_handle_recv_tcp(struct mg_connection *nc) {
  12289. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12290. #if MG_ENABLE_SSL
  12291. if (nc->flags & MG_F_SSL) {
  12292. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  12293. mg_lwip_ssl_recv(nc);
  12294. } else {
  12295. mg_lwip_ssl_do_hs(nc);
  12296. }
  12297. return;
  12298. }
  12299. #endif
  12300. mgos_lock();
  12301. while (cs->rx_chain != NULL) {
  12302. struct pbuf *seg = cs->rx_chain;
  12303. size_t len = (seg->len - cs->rx_offset);
  12304. char *data = (char *) MG_MALLOC(len);
  12305. if (data == NULL) {
  12306. mgos_unlock();
  12307. DBG(("OOM"));
  12308. return;
  12309. }
  12310. pbuf_copy_partial(seg, data, len, cs->rx_offset);
  12311. mgos_unlock();
  12312. mg_if_recv_tcp_cb(nc, data, len, 1 /* own */);
  12313. mgos_lock();
  12314. cs->rx_offset += len;
  12315. if (cs->rx_offset == cs->rx_chain->len) {
  12316. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  12317. pbuf_free(seg);
  12318. cs->rx_offset = 0;
  12319. }
  12320. }
  12321. mgos_unlock();
  12322. if (nc->send_mbuf.len > 0) {
  12323. mg_lwip_mgr_schedule_poll(nc->mgr);
  12324. }
  12325. }
  12326. static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
  12327. u16_t num_sent) {
  12328. struct mg_connection *nc = (struct mg_connection *) arg;
  12329. DBG(("%p %p %u", nc, tpcb, num_sent));
  12330. if (nc == NULL) {
  12331. tcp_abort(tpcb);
  12332. return ERR_ABRT;
  12333. }
  12334. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12335. cs->num_sent += num_sent;
  12336. mg_lwip_post_signal(MG_SIG_SENT_CB, nc);
  12337. return ERR_OK;
  12338. }
  12339. void mg_lwip_if_connect_tcp(struct mg_connection *nc,
  12340. const union socket_address *sa) {
  12341. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12342. struct tcp_pcb *tpcb = TCP_NEW();
  12343. cs->pcb.tcp = tpcb;
  12344. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  12345. u16_t port = ntohs(sa->sin.sin_port);
  12346. tcp_arg(tpcb, nc);
  12347. tcp_err(tpcb, mg_lwip_tcp_error_cb);
  12348. tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
  12349. tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
  12350. cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
  12351. DBG(("%p tcp_bind = %d", nc, cs->err));
  12352. if (cs->err != ERR_OK) {
  12353. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12354. return;
  12355. }
  12356. cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
  12357. DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err));
  12358. if (cs->err != ERR_OK) {
  12359. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12360. return;
  12361. }
  12362. }
  12363. /*
  12364. * Lwip included in the SDKs for nRF5x chips has different type for the
  12365. * callback of `udp_recv()`
  12366. */
  12367. #if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52 || \
  12368. CS_PLATFORM == CS_P_STM32
  12369. static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
  12370. const ip_addr_t *addr, u16_t port)
  12371. #else
  12372. static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
  12373. ip_addr_t *addr, u16_t port)
  12374. #endif
  12375. {
  12376. struct mg_connection *nc = (struct mg_connection *) arg;
  12377. DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
  12378. /* Put address in a separate pbuf and tack it onto the packet. */
  12379. struct pbuf *sap =
  12380. pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
  12381. if (sap == NULL) {
  12382. pbuf_free(p);
  12383. return;
  12384. }
  12385. union socket_address *sa = (union socket_address *) sap->payload;
  12386. sa->sin.sin_addr.s_addr = addr->addr;
  12387. sa->sin.sin_port = htons(port);
  12388. /* Logic in the recv handler requires that there be exactly one data pbuf. */
  12389. p = pbuf_coalesce(p, PBUF_RAW);
  12390. pbuf_chain(sap, p);
  12391. mg_lwip_recv_common(nc, sap);
  12392. (void) pcb;
  12393. }
  12394. static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
  12395. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12396. mgos_lock();
  12397. if (cs->rx_chain == NULL) {
  12398. cs->rx_chain = p;
  12399. } else {
  12400. pbuf_chain(cs->rx_chain, p);
  12401. }
  12402. if (!cs->recv_pending) {
  12403. cs->recv_pending = 1;
  12404. mg_lwip_post_signal(MG_SIG_RECV, nc);
  12405. }
  12406. mgos_unlock();
  12407. }
  12408. static void mg_lwip_handle_recv_udp(struct mg_connection *nc) {
  12409. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12410. /*
  12411. * For UDP, RX chain consists of interleaved address and packet bufs:
  12412. * Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
  12413. */
  12414. while (cs->rx_chain != NULL) {
  12415. struct pbuf *sap = cs->rx_chain;
  12416. struct pbuf *p = sap->next;
  12417. cs->rx_chain = pbuf_dechain(p);
  12418. size_t data_len = p->len;
  12419. char *data = (char *) MG_MALLOC(data_len);
  12420. if (data != NULL) {
  12421. pbuf_copy_partial(p, data, data_len, 0);
  12422. pbuf_free(p);
  12423. mg_if_recv_udp_cb(nc, data, data_len,
  12424. (union socket_address *) sap->payload, sap->len);
  12425. pbuf_free(sap);
  12426. } else {
  12427. pbuf_free(p);
  12428. pbuf_free(sap);
  12429. }
  12430. }
  12431. }
  12432. void mg_lwip_if_connect_udp(struct mg_connection *nc) {
  12433. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12434. struct udp_pcb *upcb = udp_new();
  12435. cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
  12436. DBG(("%p udp_bind %p = %d", nc, upcb, cs->err));
  12437. if (cs->err == ERR_OK) {
  12438. udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
  12439. cs->pcb.udp = upcb;
  12440. } else {
  12441. udp_remove(upcb);
  12442. }
  12443. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12444. }
  12445. void mg_lwip_accept_conn(struct mg_connection *nc, struct tcp_pcb *tpcb) {
  12446. union socket_address sa;
  12447. SET_ADDR(&sa, &tpcb->remote_ip);
  12448. sa.sin.sin_port = htons(tpcb->remote_port);
  12449. mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
  12450. }
  12451. void mg_lwip_handle_accept(struct mg_connection *nc) {
  12452. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12453. #if MG_ENABLE_SSL
  12454. if (cs->lc->flags & MG_F_SSL) {
  12455. if (mg_ssl_if_conn_accept(nc, cs->lc) != MG_SSL_OK) {
  12456. LOG(LL_ERROR, ("SSL error"));
  12457. tcp_close(cs->pcb.tcp);
  12458. }
  12459. } else
  12460. #endif
  12461. {
  12462. mg_lwip_accept_conn(nc, cs->pcb.tcp);
  12463. }
  12464. }
  12465. static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
  12466. struct mg_connection *lc = (struct mg_connection *) arg;
  12467. DBG(("%p conn %p from %s:%u", lc, newtpcb,
  12468. IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
  12469. struct mg_connection *nc = mg_if_accept_new_conn(lc);
  12470. if (nc == NULL) {
  12471. tcp_abort(newtpcb);
  12472. return ERR_ABRT;
  12473. }
  12474. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12475. cs->lc = lc;
  12476. cs->pcb.tcp = newtpcb;
  12477. /* We need to set up callbacks before returning because data may start
  12478. * arriving immediately. */
  12479. tcp_arg(newtpcb, nc);
  12480. tcp_err(newtpcb, mg_lwip_tcp_error_cb);
  12481. tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
  12482. tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
  12483. #if LWIP_TCP_KEEPALIVE
  12484. mg_lwip_set_keepalive_params(nc, 60, 10, 6);
  12485. #endif
  12486. mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
  12487. (void) err;
  12488. return ERR_OK;
  12489. }
  12490. int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  12491. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12492. struct tcp_pcb *tpcb = TCP_NEW();
  12493. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  12494. u16_t port = ntohs(sa->sin.sin_port);
  12495. cs->err = TCP_BIND(tpcb, ip, port);
  12496. DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
  12497. if (cs->err != ERR_OK) {
  12498. tcp_close(tpcb);
  12499. return -1;
  12500. }
  12501. tcp_arg(tpcb, nc);
  12502. tpcb = tcp_listen(tpcb);
  12503. cs->pcb.tcp = tpcb;
  12504. tcp_accept(tpcb, mg_lwip_accept_cb);
  12505. return 0;
  12506. }
  12507. int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  12508. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12509. struct udp_pcb *upcb = udp_new();
  12510. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  12511. u16_t port = ntohs(sa->sin.sin_port);
  12512. cs->err = UDP_BIND(upcb, ip, port);
  12513. DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
  12514. if (cs->err != ERR_OK) {
  12515. udp_remove(upcb);
  12516. return -1;
  12517. }
  12518. udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
  12519. cs->pcb.udp = upcb;
  12520. return 0;
  12521. }
  12522. int mg_lwip_tcp_write(struct mg_connection *nc, const void *data,
  12523. uint16_t len) {
  12524. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12525. struct tcp_pcb *tpcb = cs->pcb.tcp;
  12526. len = MIN(tpcb->mss, MIN(len, tpcb->snd_buf));
  12527. if (len == 0) {
  12528. DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf,
  12529. tpcb->snd_queuelen, tpcb->unsent, tpcb->unacked));
  12530. tcp_output(tpcb);
  12531. return 0;
  12532. }
  12533. /*
  12534. * On ESP8266 we only allow one TCP segment in flight at any given time.
  12535. * This may increase latency and reduce efficiency of tcp windowing,
  12536. * but memory is scarce and precious on that platform so we do this to
  12537. * reduce footprint.
  12538. */
  12539. #if CS_PLATFORM == CS_P_ESP8266
  12540. if (tpcb->unacked != NULL) {
  12541. return 0;
  12542. }
  12543. if (tpcb->unsent != NULL) {
  12544. len = MIN(len, (TCP_MSS - tpcb->unsent->len));
  12545. }
  12546. #endif
  12547. err_t err = tcp_write(tpcb, data, len, TCP_WRITE_FLAG_COPY);
  12548. DBG(("%p tcp_write %u = %d", tpcb, len, err));
  12549. if (err != ERR_OK) {
  12550. /*
  12551. * We ignore ERR_MEM because memory will be freed up when the data is sent
  12552. * and we'll retry.
  12553. */
  12554. return (err == ERR_MEM ? 0 : -1);
  12555. }
  12556. return len;
  12557. }
  12558. static void mg_lwip_send_more(struct mg_connection *nc) {
  12559. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12560. if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) {
  12561. DBG(("%p invalid socket", nc));
  12562. return;
  12563. }
  12564. int num_written = mg_lwip_tcp_write(nc, nc->send_mbuf.buf, nc->send_mbuf.len);
  12565. DBG(("%p mg_lwip_tcp_write %u = %d", nc, nc->send_mbuf.len, num_written));
  12566. if (num_written == 0) return;
  12567. if (num_written < 0) {
  12568. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12569. }
  12570. mbuf_remove(&nc->send_mbuf, num_written);
  12571. mbuf_trim(&nc->send_mbuf);
  12572. }
  12573. void mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf,
  12574. size_t len) {
  12575. mbuf_append(&nc->send_mbuf, buf, len);
  12576. mg_lwip_mgr_schedule_poll(nc->mgr);
  12577. }
  12578. void mg_lwip_if_udp_send(struct mg_connection *nc, const void *buf,
  12579. size_t len) {
  12580. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12581. if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) {
  12582. /*
  12583. * In case of UDP, this usually means, what
  12584. * async DNS resolve is still in progress and connection
  12585. * is not ready yet
  12586. */
  12587. DBG(("%p socket is not connected", nc));
  12588. return;
  12589. }
  12590. struct udp_pcb *upcb = cs->pcb.udp;
  12591. struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
  12592. ip_addr_t *ip = (ip_addr_t *) &nc->sa.sin.sin_addr.s_addr;
  12593. u16_t port = ntohs(nc->sa.sin.sin_port);
  12594. if (p == NULL) {
  12595. DBG(("OOM"));
  12596. return;
  12597. }
  12598. memcpy(p->payload, buf, len);
  12599. cs->err = udp_sendto(upcb, p, (ip_addr_t *) ip, port);
  12600. DBG(("%p udp_sendto = %d", nc, cs->err));
  12601. pbuf_free(p);
  12602. if (cs->err != ERR_OK) {
  12603. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12604. } else {
  12605. cs->num_sent += len;
  12606. mg_lwip_post_signal(MG_SIG_SENT_CB, nc);
  12607. }
  12608. }
  12609. void mg_lwip_if_recved(struct mg_connection *nc, size_t len) {
  12610. if (nc->flags & MG_F_UDP) return;
  12611. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12612. if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) {
  12613. DBG(("%p invalid socket", nc));
  12614. return;
  12615. }
  12616. DBG(("%p %p %u", nc, cs->pcb.tcp, len));
  12617. /* Currently SSL acknowledges data immediately.
  12618. * TODO(rojer): Find a way to propagate mg_lwip_if_recved. */
  12619. #if MG_ENABLE_SSL
  12620. if (!(nc->flags & MG_F_SSL)) {
  12621. tcp_recved(cs->pcb.tcp, len);
  12622. }
  12623. #else
  12624. tcp_recved(cs->pcb.tcp, len);
  12625. #endif
  12626. mbuf_trim(&nc->recv_mbuf);
  12627. }
  12628. int mg_lwip_if_create_conn(struct mg_connection *nc) {
  12629. struct mg_lwip_conn_state *cs =
  12630. (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
  12631. if (cs == NULL) return 0;
  12632. cs->nc = nc;
  12633. nc->sock = (intptr_t) cs;
  12634. return 1;
  12635. }
  12636. void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
  12637. if (nc->sock == INVALID_SOCKET) return;
  12638. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12639. if (!(nc->flags & MG_F_UDP)) {
  12640. struct tcp_pcb *tpcb = cs->pcb.tcp;
  12641. if (tpcb != NULL) {
  12642. tcp_arg(tpcb, NULL);
  12643. DBG(("%p tcp_close %p", nc, tpcb));
  12644. tcp_arg(tpcb, NULL);
  12645. tcp_close(tpcb);
  12646. }
  12647. while (cs->rx_chain != NULL) {
  12648. struct pbuf *seg = cs->rx_chain;
  12649. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  12650. pbuf_free(seg);
  12651. }
  12652. memset(cs, 0, sizeof(*cs));
  12653. MG_FREE(cs);
  12654. } else if (nc->listener == NULL) {
  12655. /* Only close outgoing UDP pcb or listeners. */
  12656. struct udp_pcb *upcb = cs->pcb.udp;
  12657. if (upcb != NULL) {
  12658. DBG(("%p udp_remove %p", nc, upcb));
  12659. udp_remove(upcb);
  12660. }
  12661. memset(cs, 0, sizeof(*cs));
  12662. MG_FREE(cs);
  12663. }
  12664. nc->sock = INVALID_SOCKET;
  12665. }
  12666. void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
  12667. union socket_address *sa) {
  12668. memset(sa, 0, sizeof(*sa));
  12669. if (nc->sock == INVALID_SOCKET) return;
  12670. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12671. if (nc->flags & MG_F_UDP) {
  12672. struct udp_pcb *upcb = cs->pcb.udp;
  12673. if (remote) {
  12674. memcpy(sa, &nc->sa, sizeof(*sa));
  12675. } else {
  12676. sa->sin.sin_port = htons(upcb->local_port);
  12677. SET_ADDR(sa, &upcb->local_ip);
  12678. }
  12679. } else {
  12680. struct tcp_pcb *tpcb = cs->pcb.tcp;
  12681. if (remote) {
  12682. sa->sin.sin_port = htons(tpcb->remote_port);
  12683. SET_ADDR(sa, &tpcb->remote_ip);
  12684. } else {
  12685. sa->sin.sin_port = htons(tpcb->local_port);
  12686. SET_ADDR(sa, &tpcb->local_ip);
  12687. }
  12688. }
  12689. }
  12690. void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
  12691. nc->sock = sock;
  12692. }
  12693. /* clang-format off */
  12694. #define MG_LWIP_IFACE_VTABLE \
  12695. { \
  12696. mg_lwip_if_init, \
  12697. mg_lwip_if_free, \
  12698. mg_lwip_if_add_conn, \
  12699. mg_lwip_if_remove_conn, \
  12700. mg_lwip_if_poll, \
  12701. mg_lwip_if_listen_tcp, \
  12702. mg_lwip_if_listen_udp, \
  12703. mg_lwip_if_connect_tcp, \
  12704. mg_lwip_if_connect_udp, \
  12705. mg_lwip_if_tcp_send, \
  12706. mg_lwip_if_udp_send, \
  12707. mg_lwip_if_recved, \
  12708. mg_lwip_if_create_conn, \
  12709. mg_lwip_if_destroy_conn, \
  12710. mg_lwip_if_sock_set, \
  12711. mg_lwip_if_get_conn_addr, \
  12712. }
  12713. /* clang-format on */
  12714. struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
  12715. #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  12716. struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
  12717. #endif
  12718. #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
  12719. #ifdef MG_MODULE_LINES
  12720. #line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
  12721. #endif
  12722. /*
  12723. * Copyright (c) 2014-2016 Cesanta Software Limited
  12724. * All rights reserved
  12725. */
  12726. #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  12727. #ifndef MG_SIG_QUEUE_LEN
  12728. #define MG_SIG_QUEUE_LEN 32
  12729. #endif
  12730. struct mg_ev_mgr_lwip_signal {
  12731. int sig;
  12732. struct mg_connection *nc;
  12733. };
  12734. struct mg_ev_mgr_lwip_data {
  12735. struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
  12736. int sig_queue_len;
  12737. int start_index;
  12738. };
  12739. void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
  12740. struct mg_ev_mgr_lwip_data *md =
  12741. (struct mg_ev_mgr_lwip_data *) nc->iface->data;
  12742. mgos_lock();
  12743. if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
  12744. mgos_unlock();
  12745. return;
  12746. }
  12747. int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
  12748. md->sig_queue[end_index].sig = sig;
  12749. md->sig_queue[end_index].nc = nc;
  12750. md->sig_queue_len++;
  12751. mg_lwip_mgr_schedule_poll(nc->mgr);
  12752. mgos_unlock();
  12753. }
  12754. void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
  12755. struct mg_ev_mgr_lwip_data *md =
  12756. (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
  12757. while (md->sig_queue_len > 0) {
  12758. mgos_lock();
  12759. int sig = md->sig_queue[md->start_index].sig;
  12760. struct mg_connection *nc = md->sig_queue[md->start_index].nc;
  12761. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12762. md->start_index = (md->start_index + 1) % MG_SIG_QUEUE_LEN;
  12763. md->sig_queue_len--;
  12764. mgos_unlock();
  12765. if (nc->iface == NULL || nc->mgr == NULL) continue;
  12766. switch (sig) {
  12767. case MG_SIG_CONNECT_RESULT: {
  12768. #if MG_ENABLE_SSL
  12769. if (cs->err == 0 && (nc->flags & MG_F_SSL) &&
  12770. !(nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
  12771. mg_lwip_ssl_do_hs(nc);
  12772. } else
  12773. #endif
  12774. {
  12775. mg_if_connect_cb(nc, cs->err);
  12776. }
  12777. break;
  12778. }
  12779. case MG_SIG_CLOSE_CONN: {
  12780. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  12781. mg_close_conn(nc);
  12782. break;
  12783. }
  12784. case MG_SIG_RECV: {
  12785. cs->recv_pending = 0;
  12786. if (nc->flags & MG_F_UDP) {
  12787. mg_lwip_handle_recv_udp(nc);
  12788. } else {
  12789. mg_lwip_handle_recv_tcp(nc);
  12790. }
  12791. break;
  12792. }
  12793. case MG_SIG_SENT_CB: {
  12794. if (cs->num_sent > 0) mg_if_sent_cb(nc, cs->num_sent);
  12795. cs->num_sent = 0;
  12796. if (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE) &&
  12797. !(nc->flags & MG_F_WANT_WRITE)) {
  12798. mg_close_conn(nc);
  12799. }
  12800. break;
  12801. }
  12802. case MG_SIG_TOMBSTONE: {
  12803. break;
  12804. }
  12805. case MG_SIG_ACCEPT: {
  12806. mg_lwip_handle_accept(nc);
  12807. break;
  12808. }
  12809. }
  12810. }
  12811. }
  12812. void mg_lwip_if_init(struct mg_iface *iface) {
  12813. LOG(LL_INFO, ("%p Mongoose init"));
  12814. iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
  12815. }
  12816. void mg_lwip_if_free(struct mg_iface *iface) {
  12817. MG_FREE(iface->data);
  12818. iface->data = NULL;
  12819. }
  12820. void mg_lwip_if_add_conn(struct mg_connection *nc) {
  12821. (void) nc;
  12822. }
  12823. void mg_lwip_if_remove_conn(struct mg_connection *nc) {
  12824. struct mg_ev_mgr_lwip_data *md =
  12825. (struct mg_ev_mgr_lwip_data *) nc->iface->data;
  12826. /* Walk the queue and null-out further signals for this conn. */
  12827. for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
  12828. if (md->sig_queue[i].nc == nc) {
  12829. md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
  12830. }
  12831. }
  12832. }
  12833. time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
  12834. struct mg_mgr *mgr = iface->mgr;
  12835. int n = 0;
  12836. double now = mg_time();
  12837. struct mg_connection *nc, *tmp;
  12838. double min_timer = 0;
  12839. int num_timers = 0;
  12840. #if 0
  12841. DBG(("begin poll @%u", (unsigned int) (now * 1000)));
  12842. #endif
  12843. mg_ev_mgr_lwip_process_signals(mgr);
  12844. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  12845. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12846. tmp = nc->next;
  12847. n++;
  12848. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  12849. ((nc->flags & MG_F_SEND_AND_CLOSE) && (nc->flags & MG_F_UDP) &&
  12850. (nc->send_mbuf.len == 0))) {
  12851. mg_close_conn(nc);
  12852. continue;
  12853. }
  12854. mg_if_poll(nc, now);
  12855. mg_if_timer(nc, now);
  12856. #if MG_ENABLE_SSL
  12857. if ((nc->flags & MG_F_SSL) && cs != NULL && cs->pcb.tcp != NULL &&
  12858. cs->pcb.tcp->state == ESTABLISHED) {
  12859. if (((nc->flags & MG_F_WANT_WRITE) ||
  12860. ((nc->send_mbuf.len > 0) &&
  12861. (nc->flags & MG_F_SSL_HANDSHAKE_DONE))) &&
  12862. cs->pcb.tcp->snd_buf > 0) {
  12863. /* Can write more. */
  12864. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  12865. if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_send(nc);
  12866. } else {
  12867. mg_lwip_ssl_do_hs(nc);
  12868. }
  12869. }
  12870. if (cs->rx_chain != NULL || (nc->flags & MG_F_WANT_READ)) {
  12871. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  12872. if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_recv(nc);
  12873. } else {
  12874. mg_lwip_ssl_do_hs(nc);
  12875. }
  12876. }
  12877. } else
  12878. #endif /* MG_ENABLE_SSL */
  12879. {
  12880. if (!(nc->flags & (MG_F_CONNECTING | MG_F_UDP))) {
  12881. if (nc->send_mbuf.len > 0) mg_lwip_send_more(nc);
  12882. }
  12883. }
  12884. if (nc->sock != INVALID_SOCKET &&
  12885. !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
  12886. cs->pcb.tcp->unsent != NULL) {
  12887. tcp_output(cs->pcb.tcp);
  12888. }
  12889. if (nc->ev_timer_time > 0) {
  12890. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  12891. min_timer = nc->ev_timer_time;
  12892. }
  12893. num_timers++;
  12894. }
  12895. }
  12896. #if 0
  12897. DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
  12898. (unsigned int) (now * 1000), n, num_timers,
  12899. (unsigned int) (min_timer * 1000), timeout_ms));
  12900. #endif
  12901. (void) timeout_ms;
  12902. return now;
  12903. }
  12904. uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr) {
  12905. struct mg_connection *nc;
  12906. double now = mg_time();
  12907. double min_timer = 0;
  12908. int num_timers = 0;
  12909. mg_ev_mgr_lwip_process_signals(mgr);
  12910. for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
  12911. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12912. if (nc->ev_timer_time > 0) {
  12913. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  12914. min_timer = nc->ev_timer_time;
  12915. }
  12916. num_timers++;
  12917. }
  12918. if (nc->send_mbuf.len > 0) {
  12919. int can_send = 0;
  12920. /* We have stuff to send, but can we? */
  12921. if (nc->flags & MG_F_UDP) {
  12922. /* UDP is always ready for sending. */
  12923. can_send = (cs->pcb.udp != NULL);
  12924. } else {
  12925. can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
  12926. }
  12927. /* We want and can send, request a poll immediately. */
  12928. if (can_send) return 0;
  12929. }
  12930. }
  12931. uint32_t timeout_ms = ~0;
  12932. if (num_timers > 0) {
  12933. double timer_timeout_ms = (min_timer - now) * 1000 + 1 /* rounding */;
  12934. if (timer_timeout_ms < timeout_ms) {
  12935. timeout_ms = timer_timeout_ms;
  12936. }
  12937. }
  12938. return timeout_ms;
  12939. }
  12940. #endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
  12941. #ifdef MG_MODULE_LINES
  12942. #line 1 "common/platforms/lwip/mg_lwip_ssl_if.c"
  12943. #endif
  12944. /*
  12945. * Copyright (c) 2014-2016 Cesanta Software Limited
  12946. * All rights reserved
  12947. */
  12948. #if MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  12949. /* Amalgamated: #include "common/cs_dbg.h" */
  12950. #include <lwip/pbuf.h>
  12951. #include <lwip/tcp.h>
  12952. #ifndef MG_LWIP_SSL_IO_SIZE
  12953. #define MG_LWIP_SSL_IO_SIZE 1024
  12954. #endif
  12955. /*
  12956. * Stop processing incoming SSL traffic when recv_mbuf.size is this big.
  12957. * It'a a uick solution for SSL recv pushback.
  12958. */
  12959. #ifndef MG_LWIP_SSL_RECV_MBUF_LIMIT
  12960. #define MG_LWIP_SSL_RECV_MBUF_LIMIT 3072
  12961. #endif
  12962. #ifndef MIN
  12963. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  12964. #endif
  12965. void mg_lwip_ssl_do_hs(struct mg_connection *nc) {
  12966. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  12967. int server_side = (nc->listener != NULL);
  12968. enum mg_ssl_if_result res;
  12969. if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
  12970. res = mg_ssl_if_handshake(nc);
  12971. DBG(("%p %d %d %d", nc, nc->flags, server_side, res));
  12972. if (res != MG_SSL_OK) {
  12973. if (res == MG_SSL_WANT_WRITE) {
  12974. nc->flags |= MG_F_WANT_WRITE;
  12975. cs->err = 0;
  12976. } else if (res == MG_SSL_WANT_READ) {
  12977. /*
  12978. * Nothing to do in particular, we are callback-driven.
  12979. * What we definitely do not need anymore is SSL reading (nothing left).
  12980. */
  12981. nc->flags &= ~MG_F_WANT_READ;
  12982. cs->err = 0;
  12983. } else {
  12984. cs->err = res;
  12985. if (server_side) {
  12986. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  12987. } else {
  12988. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  12989. }
  12990. }
  12991. } else {
  12992. cs->err = 0;
  12993. nc->flags &= ~MG_F_WANT_WRITE;
  12994. /*
  12995. * Handshake is done. Schedule a read immediately to consume app data
  12996. * which may already be waiting.
  12997. */
  12998. nc->flags |= (MG_F_SSL_HANDSHAKE_DONE | MG_F_WANT_READ);
  12999. if (server_side) {
  13000. mg_lwip_accept_conn(nc, cs->pcb.tcp);
  13001. } else {
  13002. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  13003. }
  13004. }
  13005. }
  13006. void mg_lwip_ssl_send(struct mg_connection *nc) {
  13007. if (nc->sock == INVALID_SOCKET) {
  13008. DBG(("%p invalid socket", nc));
  13009. return;
  13010. }
  13011. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13012. /* It's ok if the buffer is empty. Return value of 0 may also be valid. */
  13013. int len = cs->last_ssl_write_size;
  13014. if (len == 0) {
  13015. len = MIN(MG_LWIP_SSL_IO_SIZE, nc->send_mbuf.len);
  13016. }
  13017. int ret = mg_ssl_if_write(nc, nc->send_mbuf.buf, len);
  13018. DBG(("%p SSL_write %u = %d, %d", nc, len, ret));
  13019. if (ret > 0) {
  13020. mbuf_remove(&nc->send_mbuf, ret);
  13021. mbuf_trim(&nc->send_mbuf);
  13022. cs->last_ssl_write_size = 0;
  13023. } else if (ret < 0) {
  13024. /* This is tricky. We must remember the exact data we were sending to retry
  13025. * exactly the same send next time. */
  13026. cs->last_ssl_write_size = len;
  13027. }
  13028. if (ret == len) {
  13029. nc->flags &= ~MG_F_WANT_WRITE;
  13030. } else if (ret == MG_SSL_WANT_WRITE) {
  13031. nc->flags |= MG_F_WANT_WRITE;
  13032. } else {
  13033. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  13034. }
  13035. }
  13036. void mg_lwip_ssl_recv(struct mg_connection *nc) {
  13037. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13038. /* Don't deliver data before connect callback */
  13039. if (nc->flags & MG_F_CONNECTING) return;
  13040. while (nc->recv_mbuf.len < MG_LWIP_SSL_RECV_MBUF_LIMIT) {
  13041. char *buf = (char *) MG_MALLOC(MG_LWIP_SSL_IO_SIZE);
  13042. if (buf == NULL) return;
  13043. int ret = mg_ssl_if_read(nc, buf, MG_LWIP_SSL_IO_SIZE);
  13044. DBG(("%p %p SSL_read %u = %d", nc, cs->rx_chain, MG_LWIP_SSL_IO_SIZE, ret));
  13045. if (ret <= 0) {
  13046. MG_FREE(buf);
  13047. if (ret == MG_SSL_WANT_WRITE) {
  13048. nc->flags |= MG_F_WANT_WRITE;
  13049. return;
  13050. } else if (ret == MG_SSL_WANT_READ) {
  13051. /*
  13052. * Nothing to do in particular, we are callback-driven.
  13053. * What we definitely do not need anymore is SSL reading (nothing left).
  13054. */
  13055. nc->flags &= ~MG_F_WANT_READ;
  13056. cs->err = 0;
  13057. return;
  13058. } else {
  13059. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  13060. return;
  13061. }
  13062. } else {
  13063. mg_if_recv_tcp_cb(nc, buf, ret, 1 /* own */);
  13064. }
  13065. }
  13066. }
  13067. #ifdef KR_VERSION
  13068. ssize_t kr_send(int fd, const void *buf, size_t len) {
  13069. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
  13070. int ret = mg_lwip_tcp_write(cs->nc, buf, len);
  13071. DBG(("%p mg_lwip_tcp_write %u = %d", cs->nc, len, ret));
  13072. if (ret == 0) ret = KR_IO_WOULDBLOCK;
  13073. return ret;
  13074. }
  13075. ssize_t kr_recv(int fd, void *buf, size_t len) {
  13076. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
  13077. struct pbuf *seg = cs->rx_chain;
  13078. if (seg == NULL) {
  13079. DBG(("%u - nothing to read", len));
  13080. return KR_IO_WOULDBLOCK;
  13081. }
  13082. size_t seg_len = (seg->len - cs->rx_offset);
  13083. DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
  13084. len = MIN(len, seg_len);
  13085. pbuf_copy_partial(seg, buf, len, cs->rx_offset);
  13086. cs->rx_offset += len;
  13087. tcp_recved(cs->pcb.tcp, len);
  13088. if (cs->rx_offset == cs->rx_chain->len) {
  13089. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  13090. pbuf_free(seg);
  13091. cs->rx_offset = 0;
  13092. }
  13093. return len;
  13094. }
  13095. #elif MG_SSL_IF == MG_SSL_IF_MBEDTLS
  13096. int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
  13097. struct mg_connection *nc = (struct mg_connection *) ctx;
  13098. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13099. int ret = mg_lwip_tcp_write(cs->nc, buf, len);
  13100. LOG(LL_DEBUG, ("%p %d -> %d", nc, len, ret));
  13101. if (ret == 0) ret = MBEDTLS_ERR_SSL_WANT_WRITE;
  13102. return ret;
  13103. }
  13104. int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
  13105. struct mg_connection *nc = (struct mg_connection *) ctx;
  13106. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13107. struct pbuf *seg = cs->rx_chain;
  13108. if (seg == NULL) {
  13109. DBG(("%u - nothing to read", len));
  13110. return MBEDTLS_ERR_SSL_WANT_READ;
  13111. }
  13112. size_t seg_len = (seg->len - cs->rx_offset);
  13113. DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
  13114. len = MIN(len, seg_len);
  13115. pbuf_copy_partial(seg, buf, len, cs->rx_offset);
  13116. cs->rx_offset += len;
  13117. /* TCP PCB may be NULL if connection has already been closed
  13118. * but we still have data to deliver to SSL. */
  13119. if (cs->pcb.tcp != NULL) tcp_recved(cs->pcb.tcp, len);
  13120. if (cs->rx_offset == cs->rx_chain->len) {
  13121. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  13122. pbuf_free(seg);
  13123. cs->rx_offset = 0;
  13124. }
  13125. LOG(LL_DEBUG, ("%p <- %d", nc, (int) len));
  13126. return len;
  13127. }
  13128. #endif
  13129. #endif /* MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
  13130. #ifdef MG_MODULE_LINES
  13131. #line 1 "common/platforms/wince/wince_libc.c"
  13132. #endif
  13133. /*
  13134. * Copyright (c) 2016 Cesanta Software Limited
  13135. * All rights reserved
  13136. */
  13137. #ifdef WINCE
  13138. const char *strerror(int err) {
  13139. /*
  13140. * TODO(alashkin): there is no strerror on WinCE;
  13141. * look for similar wce_xxxx function
  13142. */
  13143. static char buf[10];
  13144. snprintf(buf, sizeof(buf), "%d", err);
  13145. return buf;
  13146. }
  13147. int open(const char *filename, int oflag, int pmode) {
  13148. /*
  13149. * TODO(alashkin): mg_open function is not used in mongoose
  13150. * but exists in documentation as utility function
  13151. * Shall we delete it at all or implement for WinCE as well?
  13152. */
  13153. DebugBreak();
  13154. return 0; /* for compiler */
  13155. }
  13156. int _wstati64(const wchar_t *path, cs_stat_t *st) {
  13157. DWORD fa = GetFileAttributesW(path);
  13158. if (fa == INVALID_FILE_ATTRIBUTES) {
  13159. return -1;
  13160. }
  13161. memset(st, 0, sizeof(*st));
  13162. if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
  13163. HANDLE h;
  13164. FILETIME ftime;
  13165. st->st_mode |= _S_IFREG;
  13166. h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
  13167. FILE_ATTRIBUTE_NORMAL, NULL);
  13168. if (h == INVALID_HANDLE_VALUE) {
  13169. return -1;
  13170. }
  13171. st->st_size = GetFileSize(h, NULL);
  13172. GetFileTime(h, NULL, NULL, &ftime);
  13173. st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
  13174. ((uint64_t) ftime.dwHighDateTime << 32)) /
  13175. 10000000.0) -
  13176. 11644473600);
  13177. CloseHandle(h);
  13178. } else {
  13179. st->st_mode |= _S_IFDIR;
  13180. }
  13181. return 0;
  13182. }
  13183. /* Windows CE doesn't have neither gmtime nor strftime */
  13184. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  13185. FILETIME ft;
  13186. SYSTEMTIME systime;
  13187. if (t != NULL) {
  13188. uint64_t filetime = (*t + 11644473600) * 10000000;
  13189. ft.dwLowDateTime = filetime & 0xFFFFFFFF;
  13190. ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
  13191. FileTimeToSystemTime(&ft, &systime);
  13192. } else {
  13193. GetSystemTime(&systime);
  13194. }
  13195. /* There is no PRIu16 in WinCE SDK */
  13196. snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
  13197. (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
  13198. (int) systime.wMinute, (int) systime.wSecond);
  13199. }
  13200. #endif
  13201. #ifdef MG_MODULE_LINES
  13202. #line 1 "common/platforms/pic32/pic32_net_if.h"
  13203. #endif
  13204. /*
  13205. * Copyright (c) 2014-2016 Cesanta Software Limited
  13206. * All rights reserved
  13207. */
  13208. #ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
  13209. #define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
  13210. /* Amalgamated: #include "mongoose/src/net_if.h" */
  13211. #ifdef __cplusplus
  13212. extern "C" {
  13213. #endif /* __cplusplus */
  13214. #ifndef MG_ENABLE_NET_IF_PIC32
  13215. #define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
  13216. #endif
  13217. extern struct mg_iface_vtable mg_pic32_iface_vtable;
  13218. #ifdef __cplusplus
  13219. }
  13220. #endif /* __cplusplus */
  13221. #endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
  13222. #ifdef MG_MODULE_LINES
  13223. #line 1 "common/platforms/pic32/pic32_net_if.c"
  13224. #endif
  13225. /*
  13226. * Copyright (c) 2014-2016 Cesanta Software Limited
  13227. * All rights reserved
  13228. */
  13229. #if MG_ENABLE_NET_IF_PIC32
  13230. int mg_pic32_if_create_conn(struct mg_connection *nc) {
  13231. (void) nc;
  13232. return 1;
  13233. }
  13234. void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
  13235. (void) nc;
  13236. (void) len;
  13237. }
  13238. void mg_pic32_if_add_conn(struct mg_connection *nc) {
  13239. (void) nc;
  13240. }
  13241. void mg_pic32_if_init(struct mg_iface *iface) {
  13242. (void) iface;
  13243. (void) mg_get_errno(); /* Shutup compiler */
  13244. }
  13245. void mg_pic32_if_free(struct mg_iface *iface) {
  13246. (void) iface;
  13247. }
  13248. void mg_pic32_if_remove_conn(struct mg_connection *nc) {
  13249. (void) nc;
  13250. }
  13251. void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
  13252. if (nc->sock == INVALID_SOCKET) return;
  13253. /* For UDP, only close outgoing sockets or listeners. */
  13254. if (!(nc->flags & MG_F_UDP)) {
  13255. /* Close TCP */
  13256. TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
  13257. } else if (nc->listener == NULL) {
  13258. /* Only close outgoing UDP or listeners. */
  13259. TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
  13260. }
  13261. nc->sock = INVALID_SOCKET;
  13262. }
  13263. int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  13264. nc->sock = TCPIP_UDP_ServerOpen(
  13265. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  13266. : IP_ADDRESS_TYPE_IPV6,
  13267. ntohs(sa->sin.sin_port),
  13268. sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
  13269. if (nc->sock == INVALID_SOCKET) {
  13270. return -1;
  13271. }
  13272. return 0;
  13273. }
  13274. void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
  13275. size_t len) {
  13276. mbuf_append(&nc->send_mbuf, buf, len);
  13277. }
  13278. void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
  13279. size_t len) {
  13280. mbuf_append(&nc->send_mbuf, buf, len);
  13281. }
  13282. int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  13283. nc->sock = TCPIP_TCP_ServerOpen(
  13284. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  13285. : IP_ADDRESS_TYPE_IPV6,
  13286. ntohs(sa->sin.sin_port),
  13287. sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
  13288. memcpy(&nc->sa, sa, sizeof(*sa));
  13289. if (nc->sock == INVALID_SOCKET) {
  13290. return -1;
  13291. }
  13292. return 0;
  13293. }
  13294. static int mg_accept_conn(struct mg_connection *lc) {
  13295. struct mg_connection *nc;
  13296. TCP_SOCKET_INFO si;
  13297. union socket_address sa;
  13298. nc = mg_if_accept_new_conn(lc);
  13299. if (nc == NULL) {
  13300. return 0;
  13301. }
  13302. nc->sock = lc->sock;
  13303. nc->flags &= ~MG_F_LISTENING;
  13304. if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
  13305. return 0;
  13306. }
  13307. if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
  13308. sa.sin.sin_family = AF_INET;
  13309. sa.sin.sin_port = htons(si.remotePort);
  13310. sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
  13311. } else {
  13312. /* TODO(alashkin): do something with _potential_ IPv6 */
  13313. memset(&sa, 0, sizeof(sa));
  13314. }
  13315. mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
  13316. return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
  13317. }
  13318. char *inet_ntoa(struct in_addr in) {
  13319. static char addr[17];
  13320. snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
  13321. (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
  13322. (int) in.S_un.S_un_b.s_b4);
  13323. return addr;
  13324. }
  13325. static void mg_handle_send(struct mg_connection *nc) {
  13326. uint16_t bytes_written = 0;
  13327. if (nc->flags & MG_F_UDP) {
  13328. if (!TCPIP_UDP_RemoteBind(
  13329. (UDP_SOCKET) nc->sock,
  13330. nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  13331. : IP_ADDRESS_TYPE_IPV6,
  13332. ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
  13333. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13334. return;
  13335. }
  13336. bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
  13337. if (bytes_written >= nc->send_mbuf.len) {
  13338. if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
  13339. (uint8_t *) nc->send_mbuf.buf,
  13340. nc->send_mbuf.len) != nc->send_mbuf.len) {
  13341. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13342. bytes_written = 0;
  13343. }
  13344. }
  13345. } else {
  13346. bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
  13347. if (bytes_written != 0) {
  13348. if (bytes_written > nc->send_mbuf.len) {
  13349. bytes_written = nc->send_mbuf.len;
  13350. }
  13351. if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
  13352. (uint8_t *) nc->send_mbuf.buf,
  13353. bytes_written) != bytes_written) {
  13354. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13355. bytes_written = 0;
  13356. }
  13357. }
  13358. }
  13359. if (bytes_written != 0) {
  13360. mbuf_remove(&nc->send_mbuf, bytes_written);
  13361. mg_if_sent_cb(nc, bytes_written);
  13362. }
  13363. }
  13364. static void mg_handle_recv(struct mg_connection *nc) {
  13365. uint16_t bytes_read = 0;
  13366. uint8_t *buf = NULL;
  13367. if (nc->flags & MG_F_UDP) {
  13368. bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
  13369. if (bytes_read != 0 &&
  13370. (nc->recv_mbuf_limit == -1 ||
  13371. nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
  13372. buf = (uint8_t *) MG_MALLOC(bytes_read);
  13373. if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
  13374. bytes_read) {
  13375. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13376. bytes_read = 0;
  13377. MG_FREE(buf);
  13378. }
  13379. }
  13380. } else {
  13381. bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
  13382. if (bytes_read != 0) {
  13383. if (nc->recv_mbuf_limit != -1 &&
  13384. nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
  13385. bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
  13386. }
  13387. buf = (uint8_t *) MG_MALLOC(bytes_read);
  13388. if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
  13389. bytes_read) {
  13390. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13391. MG_FREE(buf);
  13392. bytes_read = 0;
  13393. }
  13394. }
  13395. }
  13396. if (bytes_read != 0) {
  13397. mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
  13398. }
  13399. }
  13400. time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
  13401. struct mg_mgr *mgr = iface->mgr;
  13402. double now = mg_time();
  13403. struct mg_connection *nc, *tmp;
  13404. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  13405. tmp = nc->next;
  13406. if (nc->flags & MG_F_CONNECTING) {
  13407. /* processing connections */
  13408. if (nc->flags & MG_F_UDP ||
  13409. TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
  13410. mg_if_connect_cb(nc, 0);
  13411. }
  13412. } else if (nc->flags & MG_F_LISTENING) {
  13413. if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
  13414. /* accept new connections */
  13415. mg_accept_conn(nc);
  13416. }
  13417. } else {
  13418. if (nc->send_mbuf.len != 0) {
  13419. mg_handle_send(nc);
  13420. }
  13421. if (nc->recv_mbuf_limit == -1 ||
  13422. nc->recv_mbuf.len < nc->recv_mbuf_limit) {
  13423. mg_handle_recv(nc);
  13424. }
  13425. }
  13426. }
  13427. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  13428. tmp = nc->next;
  13429. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  13430. (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
  13431. mg_close_conn(nc);
  13432. }
  13433. }
  13434. return now;
  13435. }
  13436. void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
  13437. nc->sock = sock;
  13438. }
  13439. void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
  13440. union socket_address *sa) {
  13441. /* TODO(alaskin): not implemented yet */
  13442. }
  13443. void mg_pic32_if_connect_tcp(struct mg_connection *nc,
  13444. const union socket_address *sa) {
  13445. nc->sock = TCPIP_TCP_ClientOpen(
  13446. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  13447. : IP_ADDRESS_TYPE_IPV6,
  13448. ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
  13449. nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
  13450. }
  13451. void mg_pic32_if_connect_udp(struct mg_connection *nc) {
  13452. nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
  13453. nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
  13454. }
  13455. /* clang-format off */
  13456. #define MG_PIC32_IFACE_VTABLE \
  13457. { \
  13458. mg_pic32_if_init, \
  13459. mg_pic32_if_free, \
  13460. mg_pic32_if_add_conn, \
  13461. mg_pic32_if_remove_conn, \
  13462. mg_pic32_if_poll, \
  13463. mg_pic32_if_listen_tcp, \
  13464. mg_pic32_if_listen_udp, \
  13465. mg_pic32_if_connect_tcp, \
  13466. mg_pic32_if_connect_udp, \
  13467. mg_pic32_if_tcp_send, \
  13468. mg_pic32_if_udp_send, \
  13469. mg_pic32_if_recved, \
  13470. mg_pic32_if_create_conn, \
  13471. mg_pic32_if_destroy_conn, \
  13472. mg_pic32_if_sock_set, \
  13473. mg_pic32_if_get_conn_addr, \
  13474. }
  13475. /* clang-format on */
  13476. struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
  13477. #if MG_NET_IF == MG_NET_IF_PIC32
  13478. struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
  13479. #endif
  13480. #endif /* MG_ENABLE_NET_IF_PIC32 */