mongoose.c 496 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597
  1. #include "mongoose.h"
  2. #ifdef MG_MODULE_LINES
  3. #line 1 "mongoose/src/mg_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. /* Amalgamated: #include "common/mg_mem.h" */
  12. #ifndef MBUF_REALLOC
  13. #define MBUF_REALLOC MG_REALLOC
  14. #endif
  15. #ifndef MBUF_FREE
  16. #define MBUF_FREE MG_FREE
  17. #endif
  18. #define MG_SET_PTRPTR(_ptr, _v) \
  19. do { \
  20. if (_ptr) *(_ptr) = _v; \
  21. } while (0)
  22. #ifndef MG_INTERNAL
  23. #define MG_INTERNAL static
  24. #endif
  25. #ifdef PICOTCP
  26. #define NO_LIBC
  27. #define MG_DISABLE_PFS
  28. #endif
  29. /* Amalgamated: #include "common/cs_dbg.h" */
  30. /* Amalgamated: #include "mg_http.h" */
  31. /* Amalgamated: #include "mg_net.h" */
  32. #ifndef MG_CTL_MSG_MESSAGE_SIZE
  33. #define MG_CTL_MSG_MESSAGE_SIZE 8192
  34. #endif
  35. /* internals that need to be accessible in unit tests */
  36. MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
  37. int proto,
  38. union socket_address *sa);
  39. MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
  40. int *proto, char *host, size_t host_len);
  41. MG_INTERNAL void mg_call(struct mg_connection *nc,
  42. mg_event_handler_t ev_handler, void *user_data, int ev,
  43. void *ev_data);
  44. void mg_forward(struct mg_connection *from, struct mg_connection *to);
  45. MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
  46. MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
  47. MG_INTERNAL struct mg_connection *mg_create_connection(
  48. struct mg_mgr *mgr, mg_event_handler_t callback,
  49. struct mg_add_sock_opts opts);
  50. #ifdef _WIN32
  51. /* Retur value is the same as for MultiByteToWideChar. */
  52. int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
  53. #endif
  54. struct ctl_msg {
  55. mg_event_handler_t callback;
  56. char message[MG_CTL_MSG_MESSAGE_SIZE];
  57. };
  58. #if MG_ENABLE_MQTT
  59. struct mg_mqtt_message;
  60. #define MG_MQTT_ERROR_INCOMPLETE_MSG -1
  61. #define MG_MQTT_ERROR_MALFORMED_MSG -2
  62. MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
  63. #endif
  64. /* Forward declarations for testing. */
  65. extern void *(*test_malloc)(size_t size);
  66. extern void *(*test_calloc)(size_t count, size_t size);
  67. #ifndef MIN
  68. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  69. #endif
  70. #if MG_ENABLE_HTTP
  71. struct mg_serve_http_opts;
  72. MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
  73. struct mg_connection *c);
  74. /*
  75. * Reassemble the content of the buffer (buf, blen) which should be
  76. * in the HTTP chunked encoding, by collapsing data chunks to the
  77. * beginning of the buffer.
  78. *
  79. * If chunks get reassembled, modify hm->body to point to the reassembled
  80. * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
  81. * in nc->flags, delete reassembled body from the mbuf.
  82. *
  83. * Return reassembled body size.
  84. */
  85. MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
  86. struct http_message *hm, char *buf,
  87. size_t blen);
  88. #if MG_ENABLE_FILESYSTEM
  89. MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
  90. const struct mg_serve_http_opts *opts,
  91. char **local_path,
  92. struct mg_str *remainder);
  93. MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
  94. MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
  95. #endif
  96. #if MG_ENABLE_HTTP_CGI
  97. MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
  98. const struct mg_str *path_info,
  99. const struct http_message *hm,
  100. const struct mg_serve_http_opts *opts);
  101. struct mg_http_proto_data_cgi;
  102. MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d);
  103. #endif
  104. #if MG_ENABLE_HTTP_SSI
  105. MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
  106. struct http_message *hm,
  107. const char *path,
  108. const struct mg_serve_http_opts *opts);
  109. #endif
  110. #if MG_ENABLE_HTTP_WEBDAV
  111. MG_INTERNAL int mg_is_dav_request(const struct mg_str *s);
  112. MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
  113. cs_stat_t *stp, struct http_message *hm,
  114. struct mg_serve_http_opts *opts);
  115. MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path);
  116. MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
  117. struct http_message *hm);
  118. MG_INTERNAL void mg_handle_move(struct mg_connection *c,
  119. const struct mg_serve_http_opts *opts,
  120. const char *path, struct http_message *hm);
  121. MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
  122. const struct mg_serve_http_opts *opts,
  123. const char *path);
  124. MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
  125. struct http_message *hm);
  126. #endif
  127. #if MG_ENABLE_HTTP_WEBSOCKET
  128. MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
  129. void *ev_data MG_UD_ARG(void *user_data));
  130. MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
  131. const struct mg_str *key,
  132. struct http_message *);
  133. #endif
  134. #endif /* MG_ENABLE_HTTP */
  135. MG_INTERNAL int mg_get_errno(void);
  136. MG_INTERNAL void mg_close_conn(struct mg_connection *conn);
  137. #if MG_ENABLE_SNTP
  138. MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
  139. struct mg_sntp_message *msg);
  140. #endif
  141. #endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
  142. #ifdef MG_MODULE_LINES
  143. #line 1 "common/mg_mem.h"
  144. #endif
  145. /*
  146. * Copyright (c) 2014-2018 Cesanta Software Limited
  147. * All rights reserved
  148. *
  149. * Licensed under the Apache License, Version 2.0 (the ""License"");
  150. * you may not use this file except in compliance with the License.
  151. * You may obtain a copy of the License at
  152. *
  153. * http://www.apache.org/licenses/LICENSE-2.0
  154. *
  155. * Unless required by applicable law or agreed to in writing, software
  156. * distributed under the License is distributed on an ""AS IS"" BASIS,
  157. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  158. * See the License for the specific language governing permissions and
  159. * limitations under the License.
  160. */
  161. #ifndef CS_COMMON_MG_MEM_H_
  162. #define CS_COMMON_MG_MEM_H_
  163. #ifdef __cplusplus
  164. extern "C" {
  165. #endif
  166. #ifndef MG_MALLOC
  167. #define MG_MALLOC malloc
  168. #endif
  169. #ifndef MG_CALLOC
  170. #define MG_CALLOC calloc
  171. #endif
  172. #ifndef MG_REALLOC
  173. #define MG_REALLOC realloc
  174. #endif
  175. #ifndef MG_FREE
  176. #define MG_FREE free
  177. #endif
  178. #ifdef __cplusplus
  179. }
  180. #endif
  181. #endif /* CS_COMMON_MG_MEM_H_ */
  182. #ifdef MG_MODULE_LINES
  183. #line 1 "common/cs_base64.c"
  184. #endif
  185. /*
  186. * Copyright (c) 2014-2018 Cesanta Software Limited
  187. * All rights reserved
  188. *
  189. * Licensed under the Apache License, Version 2.0 (the ""License"");
  190. * you may not use this file except in compliance with the License.
  191. * You may obtain a copy of the License at
  192. *
  193. * http://www.apache.org/licenses/LICENSE-2.0
  194. *
  195. * Unless required by applicable law or agreed to in writing, software
  196. * distributed under the License is distributed on an ""AS IS"" BASIS,
  197. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  198. * See the License for the specific language governing permissions and
  199. * limitations under the License.
  200. */
  201. #ifndef EXCLUDE_COMMON
  202. /* Amalgamated: #include "common/cs_base64.h" */
  203. #include <string.h>
  204. /* Amalgamated: #include "common/cs_dbg.h" */
  205. /* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
  206. #define NUM_UPPERCASES ('Z' - 'A' + 1)
  207. #define NUM_LETTERS (NUM_UPPERCASES * 2)
  208. #define NUM_DIGITS ('9' - '0' + 1)
  209. /*
  210. * Emit a base64 code char.
  211. *
  212. * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
  213. */
  214. static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
  215. if (v < NUM_UPPERCASES) {
  216. ctx->b64_putc(v + 'A', ctx->user_data);
  217. } else if (v < (NUM_LETTERS)) {
  218. ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
  219. } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
  220. ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
  221. } else {
  222. ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
  223. ctx->user_data);
  224. }
  225. }
  226. static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
  227. int a, b, c;
  228. a = ctx->chunk[0];
  229. b = ctx->chunk[1];
  230. c = ctx->chunk[2];
  231. cs_base64_emit_code(ctx, a >> 2);
  232. cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
  233. if (ctx->chunk_size > 1) {
  234. cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
  235. }
  236. if (ctx->chunk_size > 2) {
  237. cs_base64_emit_code(ctx, c & 63);
  238. }
  239. }
  240. void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
  241. void *user_data) {
  242. ctx->chunk_size = 0;
  243. ctx->b64_putc = b64_putc;
  244. ctx->user_data = user_data;
  245. }
  246. void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
  247. const unsigned char *src = (const unsigned char *) str;
  248. size_t i;
  249. for (i = 0; i < len; i++) {
  250. ctx->chunk[ctx->chunk_size++] = src[i];
  251. if (ctx->chunk_size == 3) {
  252. cs_base64_emit_chunk(ctx);
  253. ctx->chunk_size = 0;
  254. }
  255. }
  256. }
  257. void cs_base64_finish(struct cs_base64_ctx *ctx) {
  258. if (ctx->chunk_size > 0) {
  259. int i;
  260. memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
  261. cs_base64_emit_chunk(ctx);
  262. for (i = 0; i < (3 - ctx->chunk_size); i++) {
  263. ctx->b64_putc('=', ctx->user_data);
  264. }
  265. }
  266. }
  267. #define BASE64_ENCODE_BODY \
  268. static const char *b64 = \
  269. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
  270. int i, j, a, b, c; \
  271. \
  272. for (i = j = 0; i < src_len; i += 3) { \
  273. a = src[i]; \
  274. b = i + 1 >= src_len ? 0 : src[i + 1]; \
  275. c = i + 2 >= src_len ? 0 : src[i + 2]; \
  276. \
  277. BASE64_OUT(b64[a >> 2]); \
  278. BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
  279. if (i + 1 < src_len) { \
  280. BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
  281. } \
  282. if (i + 2 < src_len) { \
  283. BASE64_OUT(b64[c & 63]); \
  284. } \
  285. } \
  286. \
  287. while (j % 4 != 0) { \
  288. BASE64_OUT('='); \
  289. } \
  290. BASE64_FLUSH()
  291. #define BASE64_OUT(ch) \
  292. do { \
  293. dst[j++] = (ch); \
  294. } while (0)
  295. #define BASE64_FLUSH() \
  296. do { \
  297. dst[j++] = '\0'; \
  298. } while (0)
  299. void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
  300. BASE64_ENCODE_BODY;
  301. }
  302. #undef BASE64_OUT
  303. #undef BASE64_FLUSH
  304. #if CS_ENABLE_STDIO
  305. #define BASE64_OUT(ch) \
  306. do { \
  307. fprintf(f, "%c", (ch)); \
  308. j++; \
  309. } while (0)
  310. #define BASE64_FLUSH()
  311. void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
  312. BASE64_ENCODE_BODY;
  313. }
  314. #undef BASE64_OUT
  315. #undef BASE64_FLUSH
  316. #endif /* CS_ENABLE_STDIO */
  317. /* Convert one byte of encoded base64 input stream to 6-bit chunk */
  318. static unsigned char from_b64(unsigned char ch) {
  319. /* Inverse lookup map */
  320. static const unsigned char tab[128] = {
  321. 255, 255, 255, 255,
  322. 255, 255, 255, 255, /* 0 */
  323. 255, 255, 255, 255,
  324. 255, 255, 255, 255, /* 8 */
  325. 255, 255, 255, 255,
  326. 255, 255, 255, 255, /* 16 */
  327. 255, 255, 255, 255,
  328. 255, 255, 255, 255, /* 24 */
  329. 255, 255, 255, 255,
  330. 255, 255, 255, 255, /* 32 */
  331. 255, 255, 255, 62,
  332. 255, 255, 255, 63, /* 40 */
  333. 52, 53, 54, 55,
  334. 56, 57, 58, 59, /* 48 */
  335. 60, 61, 255, 255,
  336. 255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
  337. 255, 0, 1, 2,
  338. 3, 4, 5, 6, /* 64 */
  339. 7, 8, 9, 10,
  340. 11, 12, 13, 14, /* 72 */
  341. 15, 16, 17, 18,
  342. 19, 20, 21, 22, /* 80 */
  343. 23, 24, 25, 255,
  344. 255, 255, 255, 255, /* 88 */
  345. 255, 26, 27, 28,
  346. 29, 30, 31, 32, /* 96 */
  347. 33, 34, 35, 36,
  348. 37, 38, 39, 40, /* 104 */
  349. 41, 42, 43, 44,
  350. 45, 46, 47, 48, /* 112 */
  351. 49, 50, 51, 255,
  352. 255, 255, 255, 255, /* 120 */
  353. };
  354. return tab[ch & 127];
  355. }
  356. int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
  357. unsigned char a, b, c, d;
  358. int orig_len = len;
  359. char *orig_dst = dst;
  360. while (len >= 4 && (a = from_b64(s[0])) != 255 &&
  361. (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
  362. (d = from_b64(s[3])) != 255) {
  363. s += 4;
  364. len -= 4;
  365. if (a == 200 || b == 200) break; /* '=' can't be there */
  366. *dst++ = a << 2 | b >> 4;
  367. if (c == 200) break;
  368. *dst++ = b << 4 | c >> 2;
  369. if (d == 200) break;
  370. *dst++ = c << 6 | d;
  371. }
  372. *dst = 0;
  373. if (dec_len != NULL) *dec_len = (dst - orig_dst);
  374. return orig_len - len;
  375. }
  376. #endif /* EXCLUDE_COMMON */
  377. #ifdef MG_MODULE_LINES
  378. #line 1 "common/cs_dbg.h"
  379. #endif
  380. /*
  381. * Copyright (c) 2014-2018 Cesanta Software Limited
  382. * All rights reserved
  383. *
  384. * Licensed under the Apache License, Version 2.0 (the ""License"");
  385. * you may not use this file except in compliance with the License.
  386. * You may obtain a copy of the License at
  387. *
  388. * http://www.apache.org/licenses/LICENSE-2.0
  389. *
  390. * Unless required by applicable law or agreed to in writing, software
  391. * distributed under the License is distributed on an ""AS IS"" BASIS,
  392. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  393. * See the License for the specific language governing permissions and
  394. * limitations under the License.
  395. */
  396. #ifndef CS_COMMON_CS_DBG_H_
  397. #define CS_COMMON_CS_DBG_H_
  398. /* Amalgamated: #include "common/platform.h" */
  399. #if CS_ENABLE_STDIO
  400. #include <stdio.h>
  401. #endif
  402. #ifndef CS_ENABLE_DEBUG
  403. #define CS_ENABLE_DEBUG 0
  404. #endif
  405. #ifndef CS_LOG_PREFIX_LEN
  406. #define CS_LOG_PREFIX_LEN 24
  407. #endif
  408. #ifndef CS_LOG_ENABLE_TS_DIFF
  409. #define CS_LOG_ENABLE_TS_DIFF 0
  410. #endif
  411. #ifdef __cplusplus
  412. extern "C" {
  413. #endif /* __cplusplus */
  414. /*
  415. * Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it.
  416. */
  417. enum cs_log_level {
  418. LL_NONE = -1,
  419. LL_ERROR = 0,
  420. LL_WARN = 1,
  421. LL_INFO = 2,
  422. LL_DEBUG = 3,
  423. LL_VERBOSE_DEBUG = 4,
  424. _LL_MIN = -2,
  425. _LL_MAX = 5,
  426. };
  427. /*
  428. * Set max log level to print; messages with the level above the given one will
  429. * not be printed.
  430. */
  431. void cs_log_set_level(enum cs_log_level level);
  432. /*
  433. * A comma-separated set of prefix=level.
  434. * prefix is matched against the log prefix exactly as printed, including line
  435. * number, but partial match is ok. Check stops on first matching entry.
  436. * If nothing matches, default level is used.
  437. *
  438. * Examples:
  439. * main.c:=4 - everything from main C at verbose debug level.
  440. * mongoose.c=1,mjs.c=1,=4 - everything at verbose debug except mg_* and mjs_*
  441. *
  442. */
  443. void cs_log_set_file_level(const char *file_level);
  444. /*
  445. * Helper function which prints message prefix with the given `level`.
  446. * If message should be printed (according to the current log level
  447. * and filter), prints the prefix and returns 1, otherwise returns 0.
  448. *
  449. * Clients should typically just use `LOG()` macro.
  450. */
  451. int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line);
  452. extern enum cs_log_level cs_log_level;
  453. #if CS_ENABLE_STDIO
  454. /*
  455. * Set file to write logs into. If `NULL`, logs go to `stderr`.
  456. */
  457. void cs_log_set_file(FILE *file);
  458. /*
  459. * Prints log to the current log file, appends "\n" in the end and flushes the
  460. * stream.
  461. */
  462. void cs_log_printf(const char *fmt, ...) PRINTF_LIKE(1, 2);
  463. #if CS_ENABLE_STDIO
  464. /*
  465. * Format and print message `x` with the given level `l`. Example:
  466. *
  467. * ```c
  468. * LOG(LL_INFO, ("my info message: %d", 123));
  469. * LOG(LL_DEBUG, ("my debug message: %d", 123));
  470. * ```
  471. */
  472. #define LOG(l, x) \
  473. do { \
  474. if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \
  475. cs_log_printf x; \
  476. } \
  477. } while (0)
  478. #else
  479. #define LOG(l, x) ((void) l)
  480. #endif
  481. #ifndef CS_NDEBUG
  482. /*
  483. * Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))`
  484. */
  485. #define DBG(x) LOG(LL_VERBOSE_DEBUG, x)
  486. #else /* NDEBUG */
  487. #define DBG(x)
  488. #endif
  489. #else /* CS_ENABLE_STDIO */
  490. #define LOG(l, x)
  491. #define DBG(x)
  492. #endif
  493. #ifdef __cplusplus
  494. }
  495. #endif /* __cplusplus */
  496. #endif /* CS_COMMON_CS_DBG_H_ */
  497. #ifdef MG_MODULE_LINES
  498. #line 1 "common/cs_dbg.c"
  499. #endif
  500. /*
  501. * Copyright (c) 2014-2018 Cesanta Software Limited
  502. * All rights reserved
  503. *
  504. * Licensed under the Apache License, Version 2.0 (the ""License"");
  505. * you may not use this file except in compliance with the License.
  506. * You may obtain a copy of the License at
  507. *
  508. * http://www.apache.org/licenses/LICENSE-2.0
  509. *
  510. * Unless required by applicable law or agreed to in writing, software
  511. * distributed under the License is distributed on an ""AS IS"" BASIS,
  512. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  513. * See the License for the specific language governing permissions and
  514. * limitations under the License.
  515. */
  516. /* Amalgamated: #include "common/cs_dbg.h" */
  517. #include <stdarg.h>
  518. #include <stdio.h>
  519. #include <string.h>
  520. /* Amalgamated: #include "common/cs_time.h" */
  521. /* Amalgamated: #include "common/str_util.h" */
  522. enum cs_log_level cs_log_level WEAK =
  523. #if CS_ENABLE_DEBUG
  524. LL_VERBOSE_DEBUG;
  525. #else
  526. LL_ERROR;
  527. #endif
  528. #if CS_ENABLE_STDIO
  529. static char *s_file_level = NULL;
  530. void cs_log_set_file_level(const char *file_level) WEAK;
  531. FILE *cs_log_file WEAK = NULL;
  532. #if CS_LOG_ENABLE_TS_DIFF
  533. double cs_log_ts WEAK;
  534. #endif
  535. enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE;
  536. void cs_log_set_file_level(const char *file_level) {
  537. char *fl = s_file_level;
  538. if (file_level != NULL) {
  539. s_file_level = strdup(file_level);
  540. } else {
  541. s_file_level = NULL;
  542. }
  543. free(fl);
  544. }
  545. int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) WEAK;
  546. int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) {
  547. char prefix[CS_LOG_PREFIX_LEN], *q;
  548. const char *p;
  549. size_t fl = 0, ll = 0, pl = 0;
  550. if (level > cs_log_level && s_file_level == NULL) return 0;
  551. p = file + strlen(file);
  552. while (p != file) {
  553. const char c = *(p - 1);
  554. if (c == '/' || c == '\\') break;
  555. p--;
  556. fl++;
  557. }
  558. ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5);
  559. if (fl > (sizeof(prefix) - ll - 2)) fl = (sizeof(prefix) - ll - 2);
  560. pl = fl + 1 + ll;
  561. memcpy(prefix, p, fl);
  562. q = prefix + pl;
  563. memset(q, ' ', sizeof(prefix) - pl);
  564. do {
  565. *(--q) = '0' + (ln % 10);
  566. ln /= 10;
  567. } while (ln > 0);
  568. *(--q) = ':';
  569. if (s_file_level != NULL) {
  570. enum cs_log_level pll = cs_log_level;
  571. struct mg_str fl = mg_mk_str(s_file_level), ps = MG_MK_STR_N(prefix, pl);
  572. struct mg_str k, v;
  573. while ((fl = mg_next_comma_list_entry_n(fl, &k, &v)).p != NULL) {
  574. bool yes = !(!mg_str_starts_with(ps, k) || v.len == 0);
  575. if (!yes) continue;
  576. pll = (enum cs_log_level)(*v.p - '0');
  577. break;
  578. }
  579. if (level > pll) return 0;
  580. }
  581. if (cs_log_file == NULL) cs_log_file = stderr;
  582. cs_log_cur_msg_level = level;
  583. fwrite(prefix, 1, sizeof(prefix), cs_log_file);
  584. #if CS_LOG_ENABLE_TS_DIFF
  585. {
  586. double now = cs_time();
  587. fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
  588. cs_log_ts = now;
  589. }
  590. #endif
  591. return 1;
  592. }
  593. void cs_log_printf(const char *fmt, ...) WEAK;
  594. void cs_log_printf(const char *fmt, ...) {
  595. va_list ap;
  596. va_start(ap, fmt);
  597. vfprintf(cs_log_file, fmt, ap);
  598. va_end(ap);
  599. fputc('\n', cs_log_file);
  600. fflush(cs_log_file);
  601. cs_log_cur_msg_level = LL_NONE;
  602. }
  603. void cs_log_set_file(FILE *file) WEAK;
  604. void cs_log_set_file(FILE *file) {
  605. cs_log_file = file;
  606. }
  607. #else
  608. void cs_log_set_file_level(const char *file_level) {
  609. (void) file_level;
  610. }
  611. #endif /* CS_ENABLE_STDIO */
  612. void cs_log_set_level(enum cs_log_level level) WEAK;
  613. void cs_log_set_level(enum cs_log_level level) {
  614. cs_log_level = level;
  615. #if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
  616. cs_log_ts = cs_time();
  617. #endif
  618. }
  619. #ifdef MG_MODULE_LINES
  620. #line 1 "common/cs_dirent.h"
  621. #endif
  622. /*
  623. * Copyright (c) 2014-2018 Cesanta Software Limited
  624. * All rights reserved
  625. *
  626. * Licensed under the Apache License, Version 2.0 (the ""License"");
  627. * you may not use this file except in compliance with the License.
  628. * You may obtain a copy of the License at
  629. *
  630. * http://www.apache.org/licenses/LICENSE-2.0
  631. *
  632. * Unless required by applicable law or agreed to in writing, software
  633. * distributed under the License is distributed on an ""AS IS"" BASIS,
  634. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  635. * See the License for the specific language governing permissions and
  636. * limitations under the License.
  637. */
  638. #ifndef CS_COMMON_CS_DIRENT_H_
  639. #define CS_COMMON_CS_DIRENT_H_
  640. #include <limits.h>
  641. /* Amalgamated: #include "common/platform.h" */
  642. #ifdef __cplusplus
  643. extern "C" {
  644. #endif /* __cplusplus */
  645. #ifdef CS_DEFINE_DIRENT
  646. typedef struct { int dummy; } DIR;
  647. struct dirent {
  648. int d_ino;
  649. #ifdef _WIN32
  650. char d_name[MAX_PATH];
  651. #else
  652. /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
  653. char d_name[256];
  654. #endif
  655. };
  656. DIR *opendir(const char *dir_name);
  657. int closedir(DIR *dir);
  658. struct dirent *readdir(DIR *dir);
  659. #endif /* CS_DEFINE_DIRENT */
  660. #ifdef __cplusplus
  661. }
  662. #endif /* __cplusplus */
  663. #endif /* CS_COMMON_CS_DIRENT_H_ */
  664. #ifdef MG_MODULE_LINES
  665. #line 1 "common/cs_dirent.c"
  666. #endif
  667. /*
  668. * Copyright (c) 2014-2018 Cesanta Software Limited
  669. * All rights reserved
  670. *
  671. * Licensed under the Apache License, Version 2.0 (the ""License"");
  672. * you may not use this file except in compliance with the License.
  673. * You may obtain a copy of the License at
  674. *
  675. * http://www.apache.org/licenses/LICENSE-2.0
  676. *
  677. * Unless required by applicable law or agreed to in writing, software
  678. * distributed under the License is distributed on an ""AS IS"" BASIS,
  679. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  680. * See the License for the specific language governing permissions and
  681. * limitations under the License.
  682. */
  683. #ifndef EXCLUDE_COMMON
  684. /* Amalgamated: #include "common/mg_mem.h" */
  685. /* Amalgamated: #include "common/cs_dirent.h" */
  686. /*
  687. * This file contains POSIX opendir/closedir/readdir API implementation
  688. * for systems which do not natively support it (e.g. Windows).
  689. */
  690. #ifdef _WIN32
  691. struct win32_dir {
  692. DIR d;
  693. HANDLE handle;
  694. WIN32_FIND_DATAW info;
  695. struct dirent result;
  696. };
  697. DIR *opendir(const char *name) {
  698. struct win32_dir *dir = NULL;
  699. wchar_t wpath[MAX_PATH];
  700. DWORD attrs;
  701. if (name == NULL) {
  702. SetLastError(ERROR_BAD_ARGUMENTS);
  703. } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
  704. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  705. } else {
  706. to_wchar(name, wpath, ARRAY_SIZE(wpath));
  707. attrs = GetFileAttributesW(wpath);
  708. if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  709. (void) wcscat(wpath, L"\\*");
  710. dir->handle = FindFirstFileW(wpath, &dir->info);
  711. dir->result.d_name[0] = '\0';
  712. } else {
  713. MG_FREE(dir);
  714. dir = NULL;
  715. }
  716. }
  717. return (DIR *) dir;
  718. }
  719. int closedir(DIR *d) {
  720. struct win32_dir *dir = (struct win32_dir *) d;
  721. int result = 0;
  722. if (dir != NULL) {
  723. if (dir->handle != INVALID_HANDLE_VALUE)
  724. result = FindClose(dir->handle) ? 0 : -1;
  725. MG_FREE(dir);
  726. } else {
  727. result = -1;
  728. SetLastError(ERROR_BAD_ARGUMENTS);
  729. }
  730. return result;
  731. }
  732. struct dirent *readdir(DIR *d) {
  733. struct win32_dir *dir = (struct win32_dir *) d;
  734. struct dirent *result = NULL;
  735. if (dir) {
  736. memset(&dir->result, 0, sizeof(dir->result));
  737. if (dir->handle != INVALID_HANDLE_VALUE) {
  738. result = &dir->result;
  739. (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
  740. result->d_name, sizeof(result->d_name), NULL,
  741. NULL);
  742. if (!FindNextFileW(dir->handle, &dir->info)) {
  743. (void) FindClose(dir->handle);
  744. dir->handle = INVALID_HANDLE_VALUE;
  745. }
  746. } else {
  747. SetLastError(ERROR_FILE_NOT_FOUND);
  748. }
  749. } else {
  750. SetLastError(ERROR_BAD_ARGUMENTS);
  751. }
  752. return result;
  753. }
  754. #endif
  755. #endif /* EXCLUDE_COMMON */
  756. /* ISO C requires a translation unit to contain at least one declaration */
  757. typedef int cs_dirent_dummy;
  758. #ifdef MG_MODULE_LINES
  759. #line 1 "common/cs_time.c"
  760. #endif
  761. /*
  762. * Copyright (c) 2014-2018 Cesanta Software Limited
  763. * All rights reserved
  764. *
  765. * Licensed under the Apache License, Version 2.0 (the ""License"");
  766. * you may not use this file except in compliance with the License.
  767. * You may obtain a copy of the License at
  768. *
  769. * http://www.apache.org/licenses/LICENSE-2.0
  770. *
  771. * Unless required by applicable law or agreed to in writing, software
  772. * distributed under the License is distributed on an ""AS IS"" BASIS,
  773. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  774. * See the License for the specific language governing permissions and
  775. * limitations under the License.
  776. */
  777. /* Amalgamated: #include "common/cs_time.h" */
  778. #ifndef _WIN32
  779. #include <stddef.h>
  780. /*
  781. * There is no sys/time.h on ARMCC.
  782. */
  783. #if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
  784. !defined(__TI_COMPILER_VERSION__) && \
  785. (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
  786. #include <sys/time.h>
  787. #endif
  788. #else
  789. #include <windows.h>
  790. #endif
  791. double cs_time(void) WEAK;
  792. double cs_time(void) {
  793. double now;
  794. #ifndef _WIN32
  795. struct timeval tv;
  796. if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
  797. now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
  798. #else
  799. SYSTEMTIME sysnow;
  800. FILETIME ftime;
  801. GetLocalTime(&sysnow);
  802. SystemTimeToFileTime(&sysnow, &ftime);
  803. /*
  804. * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
  805. * This should not cause a problems in this (21th) century
  806. * 2. Windows FILETIME is a number of 100-nanosecond intervals since January
  807. * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
  808. * thus, we need to convert to seconds and adjust amount (subtract 11644473600
  809. * seconds)
  810. */
  811. now = (double) (((int64_t) ftime.dwLowDateTime +
  812. ((int64_t) ftime.dwHighDateTime << 32)) /
  813. 10000000.0) -
  814. 11644473600;
  815. #endif /* _WIN32 */
  816. return now;
  817. }
  818. double cs_timegm(const struct tm *tm) {
  819. /* Month-to-day offset for non-leap-years. */
  820. static const int month_day[12] = {0, 31, 59, 90, 120, 151,
  821. 181, 212, 243, 273, 304, 334};
  822. /* Most of the calculation is easy; leap years are the main difficulty. */
  823. int month = tm->tm_mon % 12;
  824. int year = tm->tm_year + tm->tm_mon / 12;
  825. int year_for_leap;
  826. int64_t rt;
  827. if (month < 0) { /* Negative values % 12 are still negative. */
  828. month += 12;
  829. --year;
  830. }
  831. /* This is the number of Februaries since 1900. */
  832. year_for_leap = (month > 1) ? year + 1 : year;
  833. rt =
  834. tm->tm_sec /* Seconds */
  835. +
  836. 60 *
  837. (tm->tm_min /* Minute = 60 seconds */
  838. +
  839. 60 * (tm->tm_hour /* Hour = 60 minutes */
  840. +
  841. 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */
  842. + 365 * (year - 70) /* Year = 365 days */
  843. + (year_for_leap - 69) / 4 /* Every 4 years is leap... */
  844. - (year_for_leap - 1) / 100 /* Except centuries... */
  845. + (year_for_leap + 299) / 400))); /* Except 400s. */
  846. return rt < 0 ? -1 : (double) rt;
  847. }
  848. #ifdef MG_MODULE_LINES
  849. #line 1 "common/cs_endian.h"
  850. #endif
  851. /*
  852. * Copyright (c) 2014-2018 Cesanta Software Limited
  853. * All rights reserved
  854. *
  855. * Licensed under the Apache License, Version 2.0 (the ""License"");
  856. * you may not use this file except in compliance with the License.
  857. * You may obtain a copy of the License at
  858. *
  859. * http://www.apache.org/licenses/LICENSE-2.0
  860. *
  861. * Unless required by applicable law or agreed to in writing, software
  862. * distributed under the License is distributed on an ""AS IS"" BASIS,
  863. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  864. * See the License for the specific language governing permissions and
  865. * limitations under the License.
  866. */
  867. #ifndef CS_COMMON_CS_ENDIAN_H_
  868. #define CS_COMMON_CS_ENDIAN_H_
  869. #ifdef __cplusplus
  870. extern "C" {
  871. #endif
  872. /*
  873. * clang with std=-c99 uses __LITTLE_ENDIAN, by default
  874. * while for ex, RTOS gcc - LITTLE_ENDIAN, by default
  875. * it depends on __USE_BSD, but let's have everything
  876. */
  877. #if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
  878. #define BYTE_ORDER __BYTE_ORDER
  879. #ifndef LITTLE_ENDIAN
  880. #define LITTLE_ENDIAN __LITTLE_ENDIAN
  881. #endif /* LITTLE_ENDIAN */
  882. #ifndef BIG_ENDIAN
  883. #define BIG_ENDIAN __LITTLE_ENDIAN
  884. #endif /* BIG_ENDIAN */
  885. #endif /* BYTE_ORDER */
  886. #ifdef __cplusplus
  887. }
  888. #endif
  889. #endif /* CS_COMMON_CS_ENDIAN_H_ */
  890. #ifdef MG_MODULE_LINES
  891. #line 1 "common/cs_md5.c"
  892. #endif
  893. /*
  894. * This code implements the MD5 message-digest algorithm.
  895. * The algorithm is due to Ron Rivest. This code was
  896. * written by Colin Plumb in 1993, no copyright is claimed.
  897. * This code is in the public domain; do with it what you wish.
  898. *
  899. * Equivalent code is available from RSA Data Security, Inc.
  900. * This code has been tested against that, and is equivalent,
  901. * except that you don't need to include two pages of legalese
  902. * with every copy.
  903. *
  904. * To compute the message digest of a chunk of bytes, declare an
  905. * MD5Context structure, pass it to MD5Init, call MD5Update as
  906. * needed on buffers full of bytes, and then call MD5Final, which
  907. * will fill a supplied 16-byte array with the digest.
  908. */
  909. /* Amalgamated: #include "common/cs_md5.h" */
  910. /* Amalgamated: #include "common/str_util.h" */
  911. #if !defined(EXCLUDE_COMMON)
  912. #if !CS_DISABLE_MD5
  913. /* Amalgamated: #include "common/cs_endian.h" */
  914. static void byteReverse(unsigned char *buf, unsigned longs) {
  915. /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
  916. #if BYTE_ORDER == BIG_ENDIAN
  917. do {
  918. uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
  919. ((unsigned) buf[1] << 8 | buf[0]);
  920. *(uint32_t *) buf = t;
  921. buf += 4;
  922. } while (--longs);
  923. #else
  924. (void) buf;
  925. (void) longs;
  926. #endif
  927. }
  928. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  929. #define F2(x, y, z) F1(z, x, y)
  930. #define F3(x, y, z) (x ^ y ^ z)
  931. #define F4(x, y, z) (y ^ (x | ~z))
  932. #define MD5STEP(f, w, x, y, z, data, s) \
  933. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  934. /*
  935. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  936. * initialization constants.
  937. */
  938. void cs_md5_init(cs_md5_ctx *ctx) {
  939. ctx->buf[0] = 0x67452301;
  940. ctx->buf[1] = 0xefcdab89;
  941. ctx->buf[2] = 0x98badcfe;
  942. ctx->buf[3] = 0x10325476;
  943. ctx->bits[0] = 0;
  944. ctx->bits[1] = 0;
  945. }
  946. static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
  947. register uint32_t a, b, c, d;
  948. a = buf[0];
  949. b = buf[1];
  950. c = buf[2];
  951. d = buf[3];
  952. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  953. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  954. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  955. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  956. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  957. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  958. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  959. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  960. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  961. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  962. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  963. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  964. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  965. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  966. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  967. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  968. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  969. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  970. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  971. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  972. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  973. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  974. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  975. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  976. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  977. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  978. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  979. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  980. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  981. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  982. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  983. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  984. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  985. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  986. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  987. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  988. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  989. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  990. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  991. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  992. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  993. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  994. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  995. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  996. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  997. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  998. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  999. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  1000. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  1001. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  1002. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  1003. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  1004. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  1005. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  1006. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  1007. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  1008. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  1009. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  1010. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  1011. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  1012. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  1013. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  1014. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  1015. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  1016. buf[0] += a;
  1017. buf[1] += b;
  1018. buf[2] += c;
  1019. buf[3] += d;
  1020. }
  1021. void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) {
  1022. uint32_t t;
  1023. t = ctx->bits[0];
  1024. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  1025. ctx->bits[1] += (uint32_t) len >> 29;
  1026. t = (t >> 3) & 0x3f;
  1027. if (t) {
  1028. unsigned char *p = (unsigned char *) ctx->in + t;
  1029. t = 64 - t;
  1030. if (len < t) {
  1031. memcpy(p, buf, len);
  1032. return;
  1033. }
  1034. memcpy(p, buf, t);
  1035. byteReverse(ctx->in, 16);
  1036. cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  1037. buf += t;
  1038. len -= t;
  1039. }
  1040. while (len >= 64) {
  1041. memcpy(ctx->in, buf, 64);
  1042. byteReverse(ctx->in, 16);
  1043. cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  1044. buf += 64;
  1045. len -= 64;
  1046. }
  1047. memcpy(ctx->in, buf, len);
  1048. }
  1049. void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) {
  1050. unsigned count;
  1051. unsigned char *p;
  1052. uint32_t *a;
  1053. count = (ctx->bits[0] >> 3) & 0x3F;
  1054. p = ctx->in + count;
  1055. *p++ = 0x80;
  1056. count = 64 - 1 - count;
  1057. if (count < 8) {
  1058. memset(p, 0, count);
  1059. byteReverse(ctx->in, 16);
  1060. cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  1061. memset(ctx->in, 0, 56);
  1062. } else {
  1063. memset(p, 0, count - 8);
  1064. }
  1065. byteReverse(ctx->in, 14);
  1066. a = (uint32_t *) ctx->in;
  1067. a[14] = ctx->bits[0];
  1068. a[15] = ctx->bits[1];
  1069. cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  1070. byteReverse((unsigned char *) ctx->buf, 4);
  1071. memcpy(digest, ctx->buf, 16);
  1072. memset((char *) ctx, 0, sizeof(*ctx));
  1073. }
  1074. #endif /* CS_DISABLE_MD5 */
  1075. #endif /* EXCLUDE_COMMON */
  1076. #ifdef MG_MODULE_LINES
  1077. #line 1 "common/cs_sha1.c"
  1078. #endif
  1079. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  1080. /* 100% Public Domain */
  1081. /* Amalgamated: #include "common/cs_sha1.h" */
  1082. #if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
  1083. /* Amalgamated: #include "common/cs_endian.h" */
  1084. #define SHA1HANDSOFF
  1085. #if defined(__sun)
  1086. /* Amalgamated: #include "common/solarisfixes.h" */
  1087. #endif
  1088. union char64long16 {
  1089. unsigned char c[64];
  1090. uint32_t l[16];
  1091. };
  1092. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  1093. static uint32_t blk0(union char64long16 *block, int i) {
  1094. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  1095. #if BYTE_ORDER == LITTLE_ENDIAN
  1096. block->l[i] =
  1097. (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
  1098. #endif
  1099. return block->l[i];
  1100. }
  1101. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  1102. #undef blk
  1103. #undef R0
  1104. #undef R1
  1105. #undef R2
  1106. #undef R3
  1107. #undef R4
  1108. #define blk(i) \
  1109. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  1110. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  1111. 1))
  1112. #define R0(v, w, x, y, z, i) \
  1113. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  1114. w = rol(w, 30);
  1115. #define R1(v, w, x, y, z, i) \
  1116. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  1117. w = rol(w, 30);
  1118. #define R2(v, w, x, y, z, i) \
  1119. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  1120. w = rol(w, 30);
  1121. #define R3(v, w, x, y, z, i) \
  1122. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  1123. w = rol(w, 30);
  1124. #define R4(v, w, x, y, z, i) \
  1125. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  1126. w = rol(w, 30);
  1127. void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
  1128. uint32_t a, b, c, d, e;
  1129. union char64long16 block[1];
  1130. memcpy(block, buffer, 64);
  1131. a = state[0];
  1132. b = state[1];
  1133. c = state[2];
  1134. d = state[3];
  1135. e = state[4];
  1136. R0(a, b, c, d, e, 0);
  1137. R0(e, a, b, c, d, 1);
  1138. R0(d, e, a, b, c, 2);
  1139. R0(c, d, e, a, b, 3);
  1140. R0(b, c, d, e, a, 4);
  1141. R0(a, b, c, d, e, 5);
  1142. R0(e, a, b, c, d, 6);
  1143. R0(d, e, a, b, c, 7);
  1144. R0(c, d, e, a, b, 8);
  1145. R0(b, c, d, e, a, 9);
  1146. R0(a, b, c, d, e, 10);
  1147. R0(e, a, b, c, d, 11);
  1148. R0(d, e, a, b, c, 12);
  1149. R0(c, d, e, a, b, 13);
  1150. R0(b, c, d, e, a, 14);
  1151. R0(a, b, c, d, e, 15);
  1152. R1(e, a, b, c, d, 16);
  1153. R1(d, e, a, b, c, 17);
  1154. R1(c, d, e, a, b, 18);
  1155. R1(b, c, d, e, a, 19);
  1156. R2(a, b, c, d, e, 20);
  1157. R2(e, a, b, c, d, 21);
  1158. R2(d, e, a, b, c, 22);
  1159. R2(c, d, e, a, b, 23);
  1160. R2(b, c, d, e, a, 24);
  1161. R2(a, b, c, d, e, 25);
  1162. R2(e, a, b, c, d, 26);
  1163. R2(d, e, a, b, c, 27);
  1164. R2(c, d, e, a, b, 28);
  1165. R2(b, c, d, e, a, 29);
  1166. R2(a, b, c, d, e, 30);
  1167. R2(e, a, b, c, d, 31);
  1168. R2(d, e, a, b, c, 32);
  1169. R2(c, d, e, a, b, 33);
  1170. R2(b, c, d, e, a, 34);
  1171. R2(a, b, c, d, e, 35);
  1172. R2(e, a, b, c, d, 36);
  1173. R2(d, e, a, b, c, 37);
  1174. R2(c, d, e, a, b, 38);
  1175. R2(b, c, d, e, a, 39);
  1176. R3(a, b, c, d, e, 40);
  1177. R3(e, a, b, c, d, 41);
  1178. R3(d, e, a, b, c, 42);
  1179. R3(c, d, e, a, b, 43);
  1180. R3(b, c, d, e, a, 44);
  1181. R3(a, b, c, d, e, 45);
  1182. R3(e, a, b, c, d, 46);
  1183. R3(d, e, a, b, c, 47);
  1184. R3(c, d, e, a, b, 48);
  1185. R3(b, c, d, e, a, 49);
  1186. R3(a, b, c, d, e, 50);
  1187. R3(e, a, b, c, d, 51);
  1188. R3(d, e, a, b, c, 52);
  1189. R3(c, d, e, a, b, 53);
  1190. R3(b, c, d, e, a, 54);
  1191. R3(a, b, c, d, e, 55);
  1192. R3(e, a, b, c, d, 56);
  1193. R3(d, e, a, b, c, 57);
  1194. R3(c, d, e, a, b, 58);
  1195. R3(b, c, d, e, a, 59);
  1196. R4(a, b, c, d, e, 60);
  1197. R4(e, a, b, c, d, 61);
  1198. R4(d, e, a, b, c, 62);
  1199. R4(c, d, e, a, b, 63);
  1200. R4(b, c, d, e, a, 64);
  1201. R4(a, b, c, d, e, 65);
  1202. R4(e, a, b, c, d, 66);
  1203. R4(d, e, a, b, c, 67);
  1204. R4(c, d, e, a, b, 68);
  1205. R4(b, c, d, e, a, 69);
  1206. R4(a, b, c, d, e, 70);
  1207. R4(e, a, b, c, d, 71);
  1208. R4(d, e, a, b, c, 72);
  1209. R4(c, d, e, a, b, 73);
  1210. R4(b, c, d, e, a, 74);
  1211. R4(a, b, c, d, e, 75);
  1212. R4(e, a, b, c, d, 76);
  1213. R4(d, e, a, b, c, 77);
  1214. R4(c, d, e, a, b, 78);
  1215. R4(b, c, d, e, a, 79);
  1216. state[0] += a;
  1217. state[1] += b;
  1218. state[2] += c;
  1219. state[3] += d;
  1220. state[4] += e;
  1221. /* Erase working structures. The order of operations is important,
  1222. * used to ensure that compiler doesn't optimize those out. */
  1223. memset(block, 0, sizeof(block));
  1224. a = b = c = d = e = 0;
  1225. (void) a;
  1226. (void) b;
  1227. (void) c;
  1228. (void) d;
  1229. (void) e;
  1230. }
  1231. void cs_sha1_init(cs_sha1_ctx *context) {
  1232. context->state[0] = 0x67452301;
  1233. context->state[1] = 0xEFCDAB89;
  1234. context->state[2] = 0x98BADCFE;
  1235. context->state[3] = 0x10325476;
  1236. context->state[4] = 0xC3D2E1F0;
  1237. context->count[0] = context->count[1] = 0;
  1238. }
  1239. void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
  1240. uint32_t len) {
  1241. uint32_t i, j;
  1242. j = context->count[0];
  1243. if ((context->count[0] += len << 3) < j) context->count[1]++;
  1244. context->count[1] += (len >> 29);
  1245. j = (j >> 3) & 63;
  1246. if ((j + len) > 63) {
  1247. memcpy(&context->buffer[j], data, (i = 64 - j));
  1248. cs_sha1_transform(context->state, context->buffer);
  1249. for (; i + 63 < len; i += 64) {
  1250. cs_sha1_transform(context->state, &data[i]);
  1251. }
  1252. j = 0;
  1253. } else
  1254. i = 0;
  1255. memcpy(&context->buffer[j], &data[i], len - i);
  1256. }
  1257. void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
  1258. unsigned i;
  1259. unsigned char finalcount[8], c;
  1260. for (i = 0; i < 8; i++) {
  1261. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  1262. ((3 - (i & 3)) * 8)) &
  1263. 255);
  1264. }
  1265. c = 0200;
  1266. cs_sha1_update(context, &c, 1);
  1267. while ((context->count[0] & 504) != 448) {
  1268. c = 0000;
  1269. cs_sha1_update(context, &c, 1);
  1270. }
  1271. cs_sha1_update(context, finalcount, 8);
  1272. for (i = 0; i < 20; i++) {
  1273. digest[i] =
  1274. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  1275. }
  1276. memset(context, '\0', sizeof(*context));
  1277. memset(&finalcount, '\0', sizeof(finalcount));
  1278. }
  1279. void cs_hmac_sha1(const unsigned char *key, size_t keylen,
  1280. const unsigned char *data, size_t datalen,
  1281. unsigned char out[20]) {
  1282. cs_sha1_ctx ctx;
  1283. unsigned char buf1[64], buf2[64], tmp_key[20], i;
  1284. if (keylen > sizeof(buf1)) {
  1285. cs_sha1_init(&ctx);
  1286. cs_sha1_update(&ctx, key, keylen);
  1287. cs_sha1_final(tmp_key, &ctx);
  1288. key = tmp_key;
  1289. keylen = sizeof(tmp_key);
  1290. }
  1291. memset(buf1, 0, sizeof(buf1));
  1292. memset(buf2, 0, sizeof(buf2));
  1293. memcpy(buf1, key, keylen);
  1294. memcpy(buf2, key, keylen);
  1295. for (i = 0; i < sizeof(buf1); i++) {
  1296. buf1[i] ^= 0x36;
  1297. buf2[i] ^= 0x5c;
  1298. }
  1299. cs_sha1_init(&ctx);
  1300. cs_sha1_update(&ctx, buf1, sizeof(buf1));
  1301. cs_sha1_update(&ctx, data, datalen);
  1302. cs_sha1_final(out, &ctx);
  1303. cs_sha1_init(&ctx);
  1304. cs_sha1_update(&ctx, buf2, sizeof(buf2));
  1305. cs_sha1_update(&ctx, out, 20);
  1306. cs_sha1_final(out, &ctx);
  1307. }
  1308. #endif /* EXCLUDE_COMMON */
  1309. #ifdef MG_MODULE_LINES
  1310. #line 1 "common/mbuf.c"
  1311. #endif
  1312. /*
  1313. * Copyright (c) 2014-2018 Cesanta Software Limited
  1314. * All rights reserved
  1315. *
  1316. * Licensed under the Apache License, Version 2.0 (the ""License"");
  1317. * you may not use this file except in compliance with the License.
  1318. * You may obtain a copy of the License at
  1319. *
  1320. * http://www.apache.org/licenses/LICENSE-2.0
  1321. *
  1322. * Unless required by applicable law or agreed to in writing, software
  1323. * distributed under the License is distributed on an ""AS IS"" BASIS,
  1324. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1325. * See the License for the specific language governing permissions and
  1326. * limitations under the License.
  1327. */
  1328. #ifndef EXCLUDE_COMMON
  1329. #include <assert.h>
  1330. #include <string.h>
  1331. /* Amalgamated: #include "common/mbuf.h" */
  1332. #ifndef MBUF_REALLOC
  1333. #define MBUF_REALLOC realloc
  1334. #endif
  1335. #ifndef MBUF_FREE
  1336. #define MBUF_FREE free
  1337. #endif
  1338. void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK;
  1339. void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
  1340. mbuf->len = mbuf->size = 0;
  1341. mbuf->buf = NULL;
  1342. mbuf_resize(mbuf, initial_size);
  1343. }
  1344. void mbuf_free(struct mbuf *mbuf) WEAK;
  1345. void mbuf_free(struct mbuf *mbuf) {
  1346. if (mbuf->buf != NULL) {
  1347. MBUF_FREE(mbuf->buf);
  1348. mbuf_init(mbuf, 0);
  1349. }
  1350. }
  1351. void mbuf_resize(struct mbuf *a, size_t new_size) WEAK;
  1352. void mbuf_resize(struct mbuf *a, size_t new_size) {
  1353. if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
  1354. char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
  1355. /*
  1356. * In case realloc fails, there's not much we can do, except keep things as
  1357. * they are. Note that NULL is a valid return value from realloc when
  1358. * size == 0, but that is covered too.
  1359. */
  1360. if (buf == NULL && new_size != 0) return;
  1361. a->buf = buf;
  1362. a->size = new_size;
  1363. }
  1364. }
  1365. void mbuf_trim(struct mbuf *mbuf) WEAK;
  1366. void mbuf_trim(struct mbuf *mbuf) {
  1367. mbuf_resize(mbuf, mbuf->len);
  1368. }
  1369. size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK;
  1370. size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
  1371. char *p = NULL;
  1372. assert(a != NULL);
  1373. assert(a->len <= a->size);
  1374. assert(off <= a->len);
  1375. /* check overflow */
  1376. if (~(size_t) 0 - (size_t) a->buf < len) return 0;
  1377. if (a->len + len <= a->size) {
  1378. memmove(a->buf + off + len, a->buf + off, a->len - off);
  1379. if (buf != NULL) {
  1380. memcpy(a->buf + off, buf, len);
  1381. }
  1382. a->len += len;
  1383. } else {
  1384. size_t min_size = (a->len + len);
  1385. size_t new_size = (size_t)(min_size * MBUF_SIZE_MULTIPLIER);
  1386. if (new_size - min_size > MBUF_SIZE_MAX_HEADROOM) {
  1387. new_size = min_size + MBUF_SIZE_MAX_HEADROOM;
  1388. }
  1389. p = (char *) MBUF_REALLOC(a->buf, new_size);
  1390. if (p == NULL && new_size != min_size) {
  1391. new_size = min_size;
  1392. p = (char *) MBUF_REALLOC(a->buf, new_size);
  1393. }
  1394. if (p != NULL) {
  1395. a->buf = p;
  1396. if (off != a->len) {
  1397. memmove(a->buf + off + len, a->buf + off, a->len - off);
  1398. }
  1399. if (buf != NULL) memcpy(a->buf + off, buf, len);
  1400. a->len += len;
  1401. a->size = new_size;
  1402. } else {
  1403. len = 0;
  1404. }
  1405. }
  1406. return len;
  1407. }
  1408. size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK;
  1409. size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
  1410. return mbuf_insert(a, a->len, buf, len);
  1411. }
  1412. size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK;
  1413. size_t mbuf_append_and_free(struct mbuf *a, void *data, size_t len) {
  1414. size_t ret;
  1415. /* Optimization: if the buffer is currently empty,
  1416. * take over the user-provided buffer. */
  1417. if (a->len == 0) {
  1418. if (a->buf != NULL) free(a->buf);
  1419. a->buf = (char *) data;
  1420. a->len = a->size = len;
  1421. return len;
  1422. }
  1423. ret = mbuf_insert(a, a->len, data, len);
  1424. free(data);
  1425. return ret;
  1426. }
  1427. void mbuf_remove(struct mbuf *mb, size_t n) WEAK;
  1428. void mbuf_remove(struct mbuf *mb, size_t n) {
  1429. if (n > 0 && n <= mb->len) {
  1430. memmove(mb->buf, mb->buf + n, mb->len - n);
  1431. mb->len -= n;
  1432. }
  1433. }
  1434. void mbuf_clear(struct mbuf *mb) WEAK;
  1435. void mbuf_clear(struct mbuf *mb) {
  1436. mb->len = 0;
  1437. }
  1438. void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK;
  1439. void mbuf_move(struct mbuf *from, struct mbuf *to) {
  1440. memcpy(to, from, sizeof(*to));
  1441. memset(from, 0, sizeof(*from));
  1442. }
  1443. #endif /* EXCLUDE_COMMON */
  1444. #ifdef MG_MODULE_LINES
  1445. #line 1 "common/mg_str.c"
  1446. #endif
  1447. /*
  1448. * Copyright (c) 2014-2018 Cesanta Software Limited
  1449. * All rights reserved
  1450. *
  1451. * Licensed under the Apache License, Version 2.0 (the ""License"");
  1452. * you may not use this file except in compliance with the License.
  1453. * You may obtain a copy of the License at
  1454. *
  1455. * http://www.apache.org/licenses/LICENSE-2.0
  1456. *
  1457. * Unless required by applicable law or agreed to in writing, software
  1458. * distributed under the License is distributed on an ""AS IS"" BASIS,
  1459. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1460. * See the License for the specific language governing permissions and
  1461. * limitations under the License.
  1462. */
  1463. /* Amalgamated: #include "common/mg_mem.h" */
  1464. /* Amalgamated: #include "common/mg_str.h" */
  1465. /* Amalgamated: #include "common/platform.h" */
  1466. #include <ctype.h>
  1467. #include <stdlib.h>
  1468. #include <string.h>
  1469. int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
  1470. struct mg_str mg_mk_str(const char *s) WEAK;
  1471. struct mg_str mg_mk_str(const char *s) {
  1472. struct mg_str ret = {s, 0};
  1473. if (s != NULL) ret.len = strlen(s);
  1474. return ret;
  1475. }
  1476. struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK;
  1477. struct mg_str mg_mk_str_n(const char *s, size_t len) {
  1478. struct mg_str ret = {s, len};
  1479. return ret;
  1480. }
  1481. int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK;
  1482. int mg_vcmp(const struct mg_str *str1, const char *str2) {
  1483. size_t n2 = strlen(str2), n1 = str1->len;
  1484. int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2);
  1485. if (r == 0) {
  1486. return n1 - n2;
  1487. }
  1488. return r;
  1489. }
  1490. int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK;
  1491. int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
  1492. size_t n2 = strlen(str2), n1 = str1->len;
  1493. int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
  1494. if (r == 0) {
  1495. return n1 - n2;
  1496. }
  1497. return r;
  1498. }
  1499. static struct mg_str mg_strdup_common(const struct mg_str s,
  1500. int nul_terminate) {
  1501. struct mg_str r = {NULL, 0};
  1502. if (s.len > 0 && s.p != NULL) {
  1503. char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0));
  1504. if (sc != NULL) {
  1505. memcpy(sc, s.p, s.len);
  1506. if (nul_terminate) sc[s.len] = '\0';
  1507. r.p = sc;
  1508. r.len = s.len;
  1509. }
  1510. }
  1511. return r;
  1512. }
  1513. struct mg_str mg_strdup(const struct mg_str s) WEAK;
  1514. struct mg_str mg_strdup(const struct mg_str s) {
  1515. return mg_strdup_common(s, 0 /* NUL-terminate */);
  1516. }
  1517. struct mg_str mg_strdup_nul(const struct mg_str s) WEAK;
  1518. struct mg_str mg_strdup_nul(const struct mg_str s) {
  1519. return mg_strdup_common(s, 1 /* NUL-terminate */);
  1520. }
  1521. const char *mg_strchr(const struct mg_str s, int c) WEAK;
  1522. const char *mg_strchr(const struct mg_str s, int c) {
  1523. size_t i;
  1524. for (i = 0; i < s.len; i++) {
  1525. if (s.p[i] == c) return &s.p[i];
  1526. }
  1527. return NULL;
  1528. }
  1529. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK;
  1530. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  1531. size_t i = 0;
  1532. while (i < str1.len && i < str2.len) {
  1533. if (str1.p[i] < str2.p[i]) return -1;
  1534. if (str1.p[i] > str2.p[i]) return 1;
  1535. i++;
  1536. }
  1537. if (i < str1.len) return 1;
  1538. if (i < str2.len) return -1;
  1539. return 0;
  1540. }
  1541. int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK;
  1542. int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
  1543. struct mg_str s1 = str1;
  1544. struct mg_str s2 = str2;
  1545. if (s1.len > n) {
  1546. s1.len = n;
  1547. }
  1548. if (s2.len > n) {
  1549. s2.len = n;
  1550. }
  1551. return mg_strcmp(s1, s2);
  1552. }
  1553. void mg_strfree(struct mg_str *s) WEAK;
  1554. void mg_strfree(struct mg_str *s) {
  1555. char *sp = (char *) s->p;
  1556. s->p = NULL;
  1557. s->len = 0;
  1558. if (sp != NULL) free(sp);
  1559. }
  1560. const char *mg_strstr(const struct mg_str haystack,
  1561. const struct mg_str needle) WEAK;
  1562. const char *mg_strstr(const struct mg_str haystack,
  1563. const struct mg_str needle) {
  1564. size_t i;
  1565. if (needle.len > haystack.len) return NULL;
  1566. for (i = 0; i <= haystack.len - needle.len; i++) {
  1567. if (memcmp(haystack.p + i, needle.p, needle.len) == 0) {
  1568. return haystack.p + i;
  1569. }
  1570. }
  1571. return NULL;
  1572. }
  1573. struct mg_str mg_strstrip(struct mg_str s) WEAK;
  1574. struct mg_str mg_strstrip(struct mg_str s) {
  1575. while (s.len > 0 && isspace((int) *s.p)) {
  1576. s.p++;
  1577. s.len--;
  1578. }
  1579. while (s.len > 0 && isspace((int) *(s.p + s.len - 1))) {
  1580. s.len--;
  1581. }
  1582. return s;
  1583. }
  1584. int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK;
  1585. int mg_str_starts_with(struct mg_str s, struct mg_str prefix) {
  1586. const struct mg_str sp = MG_MK_STR_N(s.p, prefix.len);
  1587. if (s.len < prefix.len) return 0;
  1588. return (mg_strcmp(sp, prefix) == 0);
  1589. }
  1590. #ifdef MG_MODULE_LINES
  1591. #line 1 "common/str_util.c"
  1592. #endif
  1593. /*
  1594. * Copyright (c) 2014-2018 Cesanta Software Limited
  1595. * All rights reserved
  1596. *
  1597. * Licensed under the Apache License, Version 2.0 (the ""License"");
  1598. * you may not use this file except in compliance with the License.
  1599. * You may obtain a copy of the License at
  1600. *
  1601. * http://www.apache.org/licenses/LICENSE-2.0
  1602. *
  1603. * Unless required by applicable law or agreed to in writing, software
  1604. * distributed under the License is distributed on an ""AS IS"" BASIS,
  1605. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  1606. * See the License for the specific language governing permissions and
  1607. * limitations under the License.
  1608. */
  1609. #ifndef EXCLUDE_COMMON
  1610. /* Amalgamated: #include "common/str_util.h" */
  1611. /* Amalgamated: #include "common/mg_mem.h" */
  1612. /* Amalgamated: #include "common/platform.h" */
  1613. #ifndef C_DISABLE_BUILTIN_SNPRINTF
  1614. #define C_DISABLE_BUILTIN_SNPRINTF 0
  1615. #endif
  1616. /* Amalgamated: #include "common/mg_mem.h" */
  1617. size_t c_strnlen(const char *s, size_t maxlen) WEAK;
  1618. size_t c_strnlen(const char *s, size_t maxlen) {
  1619. size_t l = 0;
  1620. for (; l < maxlen && s[l] != '\0'; l++) {
  1621. }
  1622. return l;
  1623. }
  1624. #define C_SNPRINTF_APPEND_CHAR(ch) \
  1625. do { \
  1626. if (i < (int) buf_size) buf[i] = ch; \
  1627. i++; \
  1628. } while (0)
  1629. #define C_SNPRINTF_FLAG_ZERO 1
  1630. #if C_DISABLE_BUILTIN_SNPRINTF
  1631. int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
  1632. int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
  1633. return vsnprintf(buf, buf_size, fmt, ap);
  1634. }
  1635. #else
  1636. static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
  1637. int field_width) {
  1638. char tmp[40];
  1639. int i = 0, k = 0, neg = 0;
  1640. if (num < 0) {
  1641. neg++;
  1642. num = -num;
  1643. }
  1644. /* Print into temporary buffer - in reverse order */
  1645. do {
  1646. int rem = num % base;
  1647. if (rem < 10) {
  1648. tmp[k++] = '0' + rem;
  1649. } else {
  1650. tmp[k++] = 'a' + (rem - 10);
  1651. }
  1652. num /= base;
  1653. } while (num > 0);
  1654. /* Zero padding */
  1655. if (flags && C_SNPRINTF_FLAG_ZERO) {
  1656. while (k < field_width && k < (int) sizeof(tmp) - 1) {
  1657. tmp[k++] = '0';
  1658. }
  1659. }
  1660. /* And sign */
  1661. if (neg) {
  1662. tmp[k++] = '-';
  1663. }
  1664. /* Now output */
  1665. while (--k >= 0) {
  1666. C_SNPRINTF_APPEND_CHAR(tmp[k]);
  1667. }
  1668. return i;
  1669. }
  1670. int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
  1671. int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
  1672. int ch, i = 0, len_mod, flags, precision, field_width;
  1673. while ((ch = *fmt++) != '\0') {
  1674. if (ch != '%') {
  1675. C_SNPRINTF_APPEND_CHAR(ch);
  1676. } else {
  1677. /*
  1678. * Conversion specification:
  1679. * zero or more flags (one of: # 0 - <space> + ')
  1680. * an optional minimum field width (digits)
  1681. * an optional precision (. followed by digits, or *)
  1682. * an optional length modifier (one of: hh h l ll L q j z t)
  1683. * conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
  1684. */
  1685. flags = field_width = precision = len_mod = 0;
  1686. /* Flags. only zero-pad flag is supported. */
  1687. if (*fmt == '0') {
  1688. flags |= C_SNPRINTF_FLAG_ZERO;
  1689. }
  1690. /* Field width */
  1691. while (*fmt >= '0' && *fmt <= '9') {
  1692. field_width *= 10;
  1693. field_width += *fmt++ - '0';
  1694. }
  1695. /* Dynamic field width */
  1696. if (*fmt == '*') {
  1697. field_width = va_arg(ap, int);
  1698. fmt++;
  1699. }
  1700. /* Precision */
  1701. if (*fmt == '.') {
  1702. fmt++;
  1703. if (*fmt == '*') {
  1704. precision = va_arg(ap, int);
  1705. fmt++;
  1706. } else {
  1707. while (*fmt >= '0' && *fmt <= '9') {
  1708. precision *= 10;
  1709. precision += *fmt++ - '0';
  1710. }
  1711. }
  1712. }
  1713. /* Length modifier */
  1714. switch (*fmt) {
  1715. case 'h':
  1716. case 'l':
  1717. case 'L':
  1718. case 'I':
  1719. case 'q':
  1720. case 'j':
  1721. case 'z':
  1722. case 't':
  1723. len_mod = *fmt++;
  1724. if (*fmt == 'h') {
  1725. len_mod = 'H';
  1726. fmt++;
  1727. }
  1728. if (*fmt == 'l') {
  1729. len_mod = 'q';
  1730. fmt++;
  1731. }
  1732. break;
  1733. }
  1734. ch = *fmt++;
  1735. if (ch == 's') {
  1736. const char *s = va_arg(ap, const char *); /* Always fetch parameter */
  1737. int j;
  1738. int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
  1739. for (j = 0; j < pad; j++) {
  1740. C_SNPRINTF_APPEND_CHAR(' ');
  1741. }
  1742. /* `s` may be NULL in case of %.*s */
  1743. if (s != NULL) {
  1744. /* Ignore negative and 0 precisions */
  1745. for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
  1746. C_SNPRINTF_APPEND_CHAR(s[j]);
  1747. }
  1748. }
  1749. } else if (ch == 'c') {
  1750. ch = va_arg(ap, int); /* Always fetch parameter */
  1751. C_SNPRINTF_APPEND_CHAR(ch);
  1752. } else if (ch == 'd' && len_mod == 0) {
  1753. i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
  1754. field_width);
  1755. } else if (ch == 'd' && len_mod == 'l') {
  1756. i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
  1757. field_width);
  1758. #ifdef SSIZE_MAX
  1759. } else if (ch == 'd' && len_mod == 'z') {
  1760. i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
  1761. field_width);
  1762. #endif
  1763. } else if (ch == 'd' && len_mod == 'q') {
  1764. i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
  1765. field_width);
  1766. } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
  1767. i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
  1768. ch == 'x' ? 16 : 10, flags, field_width);
  1769. } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
  1770. i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
  1771. ch == 'x' ? 16 : 10, flags, field_width);
  1772. } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
  1773. i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
  1774. ch == 'x' ? 16 : 10, flags, field_width);
  1775. } else if (ch == 'p') {
  1776. unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
  1777. C_SNPRINTF_APPEND_CHAR('0');
  1778. C_SNPRINTF_APPEND_CHAR('x');
  1779. i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
  1780. } else {
  1781. #ifndef NO_LIBC
  1782. /*
  1783. * TODO(lsm): abort is not nice in a library, remove it
  1784. * Also, ESP8266 SDK doesn't have it
  1785. */
  1786. abort();
  1787. #endif
  1788. }
  1789. }
  1790. }
  1791. /* Zero-terminate the result */
  1792. if (buf_size > 0) {
  1793. buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
  1794. }
  1795. return i;
  1796. }
  1797. #endif
  1798. int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK;
  1799. int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
  1800. int result;
  1801. va_list ap;
  1802. va_start(ap, fmt);
  1803. result = c_vsnprintf(buf, buf_size, fmt, ap);
  1804. va_end(ap);
  1805. return result;
  1806. }
  1807. #ifdef _WIN32
  1808. int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1809. int ret;
  1810. char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
  1811. strncpy(buf, path, sizeof(buf));
  1812. buf[sizeof(buf) - 1] = '\0';
  1813. /* Trim trailing slashes. Leave backslash for paths like "X:\" */
  1814. p = buf + strlen(buf) - 1;
  1815. while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
  1816. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1817. ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1818. /*
  1819. * Convert back to Unicode. If doubly-converted string does not match the
  1820. * original, something is fishy, reject.
  1821. */
  1822. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1823. NULL, NULL);
  1824. if (strcmp(buf, buf2) != 0) {
  1825. wbuf[0] = L'\0';
  1826. ret = 0;
  1827. }
  1828. return ret;
  1829. }
  1830. #endif /* _WIN32 */
  1831. /* The simplest O(mn) algorithm. Better implementation are GPLed */
  1832. const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK;
  1833. const char *c_strnstr(const char *s, const char *find, size_t slen) {
  1834. size_t find_length = strlen(find);
  1835. size_t i;
  1836. for (i = 0; i < slen; i++) {
  1837. if (i + find_length > slen) {
  1838. return NULL;
  1839. }
  1840. if (strncmp(&s[i], find, find_length) == 0) {
  1841. return &s[i];
  1842. }
  1843. }
  1844. return NULL;
  1845. }
  1846. #if CS_ENABLE_STRDUP
  1847. char *strdup(const char *src) WEAK;
  1848. char *strdup(const char *src) {
  1849. size_t len = strlen(src) + 1;
  1850. char *ret = MG_MALLOC(len);
  1851. if (ret != NULL) {
  1852. strcpy(ret, src);
  1853. }
  1854. return ret;
  1855. }
  1856. #endif
  1857. void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK;
  1858. void cs_to_hex(char *to, const unsigned char *p, size_t len) {
  1859. static const char *hex = "0123456789abcdef";
  1860. for (; len--; p++) {
  1861. *to++ = hex[p[0] >> 4];
  1862. *to++ = hex[p[0] & 0x0f];
  1863. }
  1864. *to = '\0';
  1865. }
  1866. static int fourbit(int ch) {
  1867. if (ch >= '0' && ch <= '9') {
  1868. return ch - '0';
  1869. } else if (ch >= 'a' && ch <= 'f') {
  1870. return ch - 'a' + 10;
  1871. } else if (ch >= 'A' && ch <= 'F') {
  1872. return ch - 'A' + 10;
  1873. }
  1874. return 0;
  1875. }
  1876. void cs_from_hex(char *to, const char *p, size_t len) WEAK;
  1877. void cs_from_hex(char *to, const char *p, size_t len) {
  1878. size_t i;
  1879. for (i = 0; i < len; i += 2) {
  1880. *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
  1881. }
  1882. *to = '\0';
  1883. }
  1884. #if CS_ENABLE_TO64
  1885. int64_t cs_to64(const char *s) WEAK;
  1886. int64_t cs_to64(const char *s) {
  1887. int64_t result = 0;
  1888. int64_t neg = 1;
  1889. while (*s && isspace((unsigned char) *s)) s++;
  1890. if (*s == '-') {
  1891. neg = -1;
  1892. s++;
  1893. }
  1894. while (isdigit((unsigned char) *s)) {
  1895. result *= 10;
  1896. result += (*s - '0');
  1897. s++;
  1898. }
  1899. return result * neg;
  1900. }
  1901. #endif
  1902. static int str_util_lowercase(const char *s) {
  1903. return tolower(*(const unsigned char *) s);
  1904. }
  1905. int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
  1906. int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  1907. int diff = 0;
  1908. if (len > 0) do {
  1909. diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
  1910. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1911. return diff;
  1912. }
  1913. int mg_casecmp(const char *s1, const char *s2) WEAK;
  1914. int mg_casecmp(const char *s1, const char *s2) {
  1915. return mg_ncasecmp(s1, s2, (size_t) ~0);
  1916. }
  1917. int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK;
  1918. int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
  1919. int ret;
  1920. va_list ap;
  1921. va_start(ap, fmt);
  1922. ret = mg_avprintf(buf, size, fmt, ap);
  1923. va_end(ap);
  1924. return ret;
  1925. }
  1926. int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK;
  1927. int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
  1928. va_list ap_copy;
  1929. int len;
  1930. va_copy(ap_copy, ap);
  1931. len = vsnprintf(*buf, size, fmt, ap_copy);
  1932. va_end(ap_copy);
  1933. if (len < 0) {
  1934. /* eCos and Windows are not standard-compliant and return -1 when
  1935. * the buffer is too small. Keep allocating larger buffers until we
  1936. * succeed or out of memory. */
  1937. *buf = NULL; /* LCOV_EXCL_START */
  1938. while (len < 0) {
  1939. MG_FREE(*buf);
  1940. if (size == 0) {
  1941. size = 5;
  1942. }
  1943. size *= 2;
  1944. if ((*buf = (char *) MG_MALLOC(size)) == NULL) {
  1945. len = -1;
  1946. break;
  1947. }
  1948. va_copy(ap_copy, ap);
  1949. len = vsnprintf(*buf, size - 1, fmt, ap_copy);
  1950. va_end(ap_copy);
  1951. }
  1952. /*
  1953. * Microsoft version of vsnprintf() is not always null-terminated, so put
  1954. * the terminator manually
  1955. */
  1956. (*buf)[len] = 0;
  1957. /* LCOV_EXCL_STOP */
  1958. } else if (len >= (int) size) {
  1959. /* Standard-compliant code path. Allocate a buffer that is large enough. */
  1960. if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
  1961. len = -1; /* LCOV_EXCL_LINE */
  1962. } else { /* LCOV_EXCL_LINE */
  1963. va_copy(ap_copy, ap);
  1964. len = vsnprintf(*buf, len + 1, fmt, ap_copy);
  1965. va_end(ap_copy);
  1966. }
  1967. }
  1968. return len;
  1969. }
  1970. const char *mg_next_comma_list_entry(const char *, struct mg_str *,
  1971. struct mg_str *) WEAK;
  1972. const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
  1973. struct mg_str *eq_val) {
  1974. struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val);
  1975. return ret.p;
  1976. }
  1977. struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
  1978. struct mg_str *eq_val) WEAK;
  1979. struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
  1980. struct mg_str *eq_val) {
  1981. if (list.len == 0) {
  1982. /* End of the list */
  1983. list = mg_mk_str(NULL);
  1984. } else {
  1985. const char *chr = NULL;
  1986. *val = list;
  1987. if ((chr = mg_strchr(*val, ',')) != NULL) {
  1988. /* Comma found. Store length and shift the list ptr */
  1989. val->len = chr - val->p;
  1990. chr++;
  1991. list.len -= (chr - list.p);
  1992. list.p = chr;
  1993. } else {
  1994. /* This value is the last one */
  1995. list = mg_mk_str_n(list.p + list.len, 0);
  1996. }
  1997. if (eq_val != NULL) {
  1998. /* Value has form "x=y", adjust pointers and lengths */
  1999. /* so that val points to "x", and eq_val points to "y". */
  2000. eq_val->len = 0;
  2001. eq_val->p = (const char *) memchr(val->p, '=', val->len);
  2002. if (eq_val->p != NULL) {
  2003. eq_val->p++; /* Skip over '=' character */
  2004. eq_val->len = val->p + val->len - eq_val->p;
  2005. val->len = (eq_val->p - val->p) - 1;
  2006. }
  2007. }
  2008. }
  2009. return list;
  2010. }
  2011. size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK;
  2012. size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
  2013. const char *or_str;
  2014. size_t res = 0, len = 0, i = 0, j = 0;
  2015. if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL ||
  2016. (or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) {
  2017. struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
  2018. res = mg_match_prefix_n(pstr, str);
  2019. if (res > 0) return res;
  2020. pstr.p = or_str + 1;
  2021. pstr.len = (pattern.p + pattern.len) - (or_str + 1);
  2022. return mg_match_prefix_n(pstr, str);
  2023. }
  2024. for (; i < pattern.len && j < str.len; i++, j++) {
  2025. if (pattern.p[i] == '?') {
  2026. continue;
  2027. } else if (pattern.p[i] == '*') {
  2028. i++;
  2029. if (i < pattern.len && pattern.p[i] == '*') {
  2030. i++;
  2031. len = str.len - j;
  2032. } else {
  2033. len = 0;
  2034. while (j + len < str.len && str.p[j + len] != '/') len++;
  2035. }
  2036. if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1))
  2037. return j + len;
  2038. do {
  2039. const struct mg_str pstr = {pattern.p + i, pattern.len - i};
  2040. const struct mg_str sstr = {str.p + j + len, str.len - j - len};
  2041. res = mg_match_prefix_n(pstr, sstr);
  2042. } while (res == 0 && len != 0 && len-- > 0);
  2043. return res == 0 ? 0 : j + res + len;
  2044. } else if (str_util_lowercase(&pattern.p[i]) !=
  2045. str_util_lowercase(&str.p[j])) {
  2046. break;
  2047. }
  2048. }
  2049. if (i < pattern.len && pattern.p[i] == '$') {
  2050. return j == str.len ? str.len : 0;
  2051. }
  2052. return i == pattern.len ? j : 0;
  2053. }
  2054. size_t mg_match_prefix(const char *, int, const char *) WEAK;
  2055. size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
  2056. const struct mg_str pstr = {pattern, (size_t) pattern_len};
  2057. struct mg_str s = {str, 0};
  2058. if (str != NULL) s.len = strlen(str);
  2059. return mg_match_prefix_n(pstr, s);
  2060. }
  2061. #endif /* EXCLUDE_COMMON */
  2062. #ifdef MG_MODULE_LINES
  2063. #line 1 "mongoose/src/mg_net.c"
  2064. #endif
  2065. /*
  2066. * Copyright (c) 2014 Cesanta Software Limited
  2067. * All rights reserved
  2068. *
  2069. * This software is dual-licensed: you can redistribute it and/or modify
  2070. * it under the terms of the GNU General Public License version 2 as
  2071. * published by the Free Software Foundation. For the terms of this
  2072. * license, see <http://www.gnu.org/licenses/>.
  2073. *
  2074. * You are free to use this software under the terms of the GNU General
  2075. * Public License, but WITHOUT ANY WARRANTY; without even the implied
  2076. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  2077. * See the GNU General Public License for more details.
  2078. *
  2079. * Alternatively, you can license this software under a commercial
  2080. * license, as set out in <https://www.cesanta.com/license>.
  2081. */
  2082. /* Amalgamated: #include "common/cs_time.h" */
  2083. /* Amalgamated: #include "mg_dns.h" */
  2084. /* Amalgamated: #include "mg_internal.h" */
  2085. /* Amalgamated: #include "mg_resolv.h" */
  2086. /* Amalgamated: #include "mg_util.h" */
  2087. #define MG_MAX_HOST_LEN 200
  2088. #ifndef MG_TCP_IO_SIZE
  2089. #define MG_TCP_IO_SIZE 1460
  2090. #endif
  2091. #ifndef MG_UDP_IO_SIZE
  2092. #define MG_UDP_IO_SIZE 1460
  2093. #endif
  2094. #define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
  2095. memcpy(dst, src, sizeof(*dst));
  2096. /* Which flags can be pre-set by the user at connection creation time. */
  2097. #define _MG_ALLOWED_CONNECT_FLAGS_MASK \
  2098. (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
  2099. MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
  2100. /* Which flags should be modifiable by user's callbacks. */
  2101. #define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
  2102. (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
  2103. MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
  2104. MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
  2105. #ifndef intptr_t
  2106. #define intptr_t long
  2107. #endif
  2108. MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
  2109. DBG(("%p %p", mgr, c));
  2110. c->mgr = mgr;
  2111. c->next = mgr->active_connections;
  2112. mgr->active_connections = c;
  2113. c->prev = NULL;
  2114. if (c->next != NULL) c->next->prev = c;
  2115. if (c->sock != INVALID_SOCKET) {
  2116. c->iface->vtable->add_conn(c);
  2117. }
  2118. }
  2119. MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
  2120. if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
  2121. if (conn->prev) conn->prev->next = conn->next;
  2122. if (conn->next) conn->next->prev = conn->prev;
  2123. conn->prev = conn->next = NULL;
  2124. conn->iface->vtable->remove_conn(conn);
  2125. }
  2126. MG_INTERNAL void mg_call(struct mg_connection *nc,
  2127. mg_event_handler_t ev_handler, void *user_data, int ev,
  2128. void *ev_data) {
  2129. if (ev_handler == NULL) {
  2130. /*
  2131. * If protocol handler is specified, call it. Otherwise, call user-specified
  2132. * event handler.
  2133. */
  2134. ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
  2135. }
  2136. if (ev != MG_EV_POLL) {
  2137. DBG(("%p %s ev=%d ev_data=%p flags=0x%lx rmbl=%d smbl=%d", nc,
  2138. ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
  2139. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  2140. }
  2141. #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
  2142. if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV &&
  2143. ev != MG_EV_SEND /* handled separately */) {
  2144. mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
  2145. }
  2146. #endif
  2147. if (ev_handler != NULL) {
  2148. unsigned long flags_before = nc->flags;
  2149. ev_handler(nc, ev, ev_data MG_UD_ARG(user_data));
  2150. /* Prevent user handler from fiddling with system flags. */
  2151. if (ev_handler == nc->handler && nc->flags != flags_before) {
  2152. nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
  2153. (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
  2154. }
  2155. }
  2156. if (ev != MG_EV_POLL) nc->mgr->num_calls++;
  2157. if (ev != MG_EV_POLL) {
  2158. DBG(("%p after %s flags=0x%lx rmbl=%d smbl=%d", nc,
  2159. ev_handler == nc->handler ? "user" : "proto", nc->flags,
  2160. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  2161. }
  2162. #if !MG_ENABLE_CALLBACK_USERDATA
  2163. (void) user_data;
  2164. #endif
  2165. }
  2166. MG_INTERNAL void mg_timer(struct mg_connection *c, double now) {
  2167. if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
  2168. double old_value = c->ev_timer_time;
  2169. c->ev_timer_time = 0;
  2170. mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value);
  2171. }
  2172. }
  2173. MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
  2174. size_t avail;
  2175. if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
  2176. avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
  2177. return avail > max ? max : avail;
  2178. }
  2179. static int mg_do_recv(struct mg_connection *nc);
  2180. int mg_if_poll(struct mg_connection *nc, double now) {
  2181. if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
  2182. mg_close_conn(nc);
  2183. return 0;
  2184. } else if (nc->flags & MG_F_SEND_AND_CLOSE) {
  2185. if (nc->send_mbuf.len == 0) {
  2186. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2187. mg_close_conn(nc);
  2188. return 0;
  2189. }
  2190. } else if (nc->flags & MG_F_RECV_AND_CLOSE) {
  2191. mg_close_conn(nc);
  2192. return 0;
  2193. }
  2194. #if MG_ENABLE_SSL
  2195. if ((nc->flags & (MG_F_SSL | MG_F_LISTENING | MG_F_CONNECTING)) == MG_F_SSL) {
  2196. /* SSL library may have data to be delivered to the app in its buffers,
  2197. * drain them. */
  2198. int recved = 0;
  2199. do {
  2200. if (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)) break;
  2201. if (recv_avail_size(nc, MG_TCP_IO_SIZE) <= 0) break;
  2202. recved = mg_do_recv(nc);
  2203. } while (recved > 0);
  2204. }
  2205. #endif /* MG_ENABLE_SSL */
  2206. mg_timer(nc, now);
  2207. {
  2208. time_t now_t = (time_t) now;
  2209. mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now_t);
  2210. }
  2211. return 1;
  2212. }
  2213. void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
  2214. if (conn->sock != INVALID_SOCKET) { /* Don't print timer-only conns */
  2215. LOG(LL_DEBUG, ("%p 0x%lx %d", conn, conn->flags, destroy_if));
  2216. }
  2217. if (destroy_if) conn->iface->vtable->destroy_conn(conn);
  2218. if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
  2219. conn->proto_data_destructor(conn->proto_data);
  2220. }
  2221. #if MG_ENABLE_SSL
  2222. mg_ssl_if_conn_free(conn);
  2223. #endif
  2224. mbuf_free(&conn->recv_mbuf);
  2225. mbuf_free(&conn->send_mbuf);
  2226. memset(conn, 0, sizeof(*conn));
  2227. MG_FREE(conn);
  2228. }
  2229. void mg_close_conn(struct mg_connection *conn) {
  2230. /* See if there's any remaining data to deliver. Skip if user completely
  2231. * throttled the connection there will be no progress anyway. */
  2232. if (conn->sock != INVALID_SOCKET && mg_do_recv(conn) == -2) {
  2233. /* Receive is throttled, wait. */
  2234. conn->flags |= MG_F_RECV_AND_CLOSE;
  2235. return;
  2236. }
  2237. #if MG_ENABLE_SSL
  2238. if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
  2239. mg_ssl_if_conn_close_notify(conn);
  2240. }
  2241. #endif
  2242. /*
  2243. * Clearly mark the connection as going away (if not already).
  2244. * Some net_if impls (LwIP) need this for cleanly handling half-dead conns.
  2245. */
  2246. conn->flags |= MG_F_CLOSE_IMMEDIATELY;
  2247. mg_remove_conn(conn);
  2248. conn->iface->vtable->destroy_conn(conn);
  2249. mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL);
  2250. mg_destroy_conn(conn, 0 /* destroy_if */);
  2251. }
  2252. void mg_mgr_init(struct mg_mgr *m, void *user_data) {
  2253. struct mg_mgr_init_opts opts;
  2254. memset(&opts, 0, sizeof(opts));
  2255. mg_mgr_init_opt(m, user_data, opts);
  2256. }
  2257. void mg_mgr_init_opt(struct mg_mgr *m, void *user_data,
  2258. struct mg_mgr_init_opts opts) {
  2259. memset(m, 0, sizeof(*m));
  2260. #if MG_ENABLE_BROADCAST
  2261. m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
  2262. #endif
  2263. m->user_data = user_data;
  2264. #ifdef _WIN32
  2265. {
  2266. WSADATA data;
  2267. WSAStartup(MAKEWORD(2, 2), &data);
  2268. }
  2269. #elif defined(__unix__)
  2270. /* Ignore SIGPIPE signal, so if client cancels the request, it
  2271. * won't kill the whole process. */
  2272. signal(SIGPIPE, SIG_IGN);
  2273. #endif
  2274. {
  2275. int i;
  2276. if (opts.num_ifaces == 0) {
  2277. opts.num_ifaces = mg_num_ifaces;
  2278. opts.ifaces = mg_ifaces;
  2279. }
  2280. if (opts.main_iface != NULL) {
  2281. opts.ifaces[MG_MAIN_IFACE] = opts.main_iface;
  2282. }
  2283. m->num_ifaces = opts.num_ifaces;
  2284. m->ifaces =
  2285. (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces);
  2286. for (i = 0; i < opts.num_ifaces; i++) {
  2287. m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m);
  2288. m->ifaces[i]->vtable->init(m->ifaces[i]);
  2289. }
  2290. }
  2291. if (opts.nameserver != NULL) {
  2292. m->nameserver = strdup(opts.nameserver);
  2293. }
  2294. DBG(("=================================="));
  2295. DBG(("init mgr=%p", m));
  2296. #if MG_ENABLE_SSL
  2297. {
  2298. static int init_done;
  2299. if (!init_done) {
  2300. mg_ssl_if_init();
  2301. init_done++;
  2302. }
  2303. }
  2304. #endif
  2305. }
  2306. void mg_mgr_free(struct mg_mgr *m) {
  2307. struct mg_connection *conn, *tmp_conn;
  2308. DBG(("%p", m));
  2309. if (m == NULL) return;
  2310. /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
  2311. mg_mgr_poll(m, 0);
  2312. #if MG_ENABLE_BROADCAST
  2313. if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
  2314. if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
  2315. m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
  2316. #endif
  2317. for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
  2318. tmp_conn = conn->next;
  2319. conn->flags |= MG_F_CLOSE_IMMEDIATELY;
  2320. mg_close_conn(conn);
  2321. }
  2322. {
  2323. int i;
  2324. for (i = 0; i < m->num_ifaces; i++) {
  2325. m->ifaces[i]->vtable->free(m->ifaces[i]);
  2326. MG_FREE(m->ifaces[i]);
  2327. }
  2328. MG_FREE(m->ifaces);
  2329. }
  2330. MG_FREE((char *) m->nameserver);
  2331. }
  2332. int mg_mgr_poll(struct mg_mgr *m, int timeout_ms) {
  2333. int i, num_calls_before = m->num_calls;
  2334. for (i = 0; i < m->num_ifaces; i++) {
  2335. m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms);
  2336. }
  2337. return (m->num_calls - num_calls_before);
  2338. }
  2339. int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
  2340. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  2341. int len;
  2342. if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  2343. mg_send(nc, buf, len);
  2344. }
  2345. if (buf != mem && buf != NULL) {
  2346. MG_FREE(buf); /* LCOV_EXCL_LINE */
  2347. } /* LCOV_EXCL_LINE */
  2348. return len;
  2349. }
  2350. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  2351. int len;
  2352. va_list ap;
  2353. va_start(ap, fmt);
  2354. len = mg_vprintf(conn, fmt, ap);
  2355. va_end(ap);
  2356. return len;
  2357. }
  2358. #if MG_ENABLE_SYNC_RESOLVER
  2359. /* TODO(lsm): use non-blocking resolver */
  2360. static int mg_resolve2(const char *host, struct in_addr *ina) {
  2361. #if MG_ENABLE_GETADDRINFO
  2362. int rv = 0;
  2363. struct addrinfo hints, *servinfo, *p;
  2364. struct sockaddr_in *h = NULL;
  2365. memset(&hints, 0, sizeof hints);
  2366. hints.ai_family = AF_INET;
  2367. hints.ai_socktype = SOCK_STREAM;
  2368. if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
  2369. DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno())));
  2370. return 0;
  2371. }
  2372. for (p = servinfo; p != NULL; p = p->ai_next) {
  2373. memcpy(&h, &p->ai_addr, sizeof(h));
  2374. memcpy(ina, &h->sin_addr, sizeof(*ina));
  2375. }
  2376. freeaddrinfo(servinfo);
  2377. return 1;
  2378. #else
  2379. struct hostent *he;
  2380. if ((he = gethostbyname(host)) == NULL) {
  2381. DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno())));
  2382. } else {
  2383. memcpy(ina, he->h_addr_list[0], sizeof(*ina));
  2384. return 1;
  2385. }
  2386. return 0;
  2387. #endif /* MG_ENABLE_GETADDRINFO */
  2388. }
  2389. int mg_resolve(const char *host, char *buf, size_t n) {
  2390. struct in_addr ad;
  2391. return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
  2392. }
  2393. #endif /* MG_ENABLE_SYNC_RESOLVER */
  2394. MG_INTERNAL struct mg_connection *mg_create_connection_base(
  2395. struct mg_mgr *mgr, mg_event_handler_t callback,
  2396. struct mg_add_sock_opts opts) {
  2397. struct mg_connection *conn;
  2398. if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
  2399. conn->sock = INVALID_SOCKET;
  2400. conn->handler = callback;
  2401. conn->mgr = mgr;
  2402. conn->last_io_time = (time_t) mg_time();
  2403. conn->iface =
  2404. (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]);
  2405. conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
  2406. conn->user_data = opts.user_data;
  2407. /*
  2408. * SIZE_MAX is defined as a long long constant in
  2409. * system headers on some platforms and so it
  2410. * doesn't compile with pedantic ansi flags.
  2411. */
  2412. conn->recv_mbuf_limit = ~0;
  2413. } else {
  2414. MG_SET_PTRPTR(opts.error_string, "failed to create connection");
  2415. }
  2416. return conn;
  2417. }
  2418. MG_INTERNAL struct mg_connection *mg_create_connection(
  2419. struct mg_mgr *mgr, mg_event_handler_t callback,
  2420. struct mg_add_sock_opts opts) {
  2421. struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
  2422. if (conn != NULL && !conn->iface->vtable->create_conn(conn)) {
  2423. MG_FREE(conn);
  2424. conn = NULL;
  2425. }
  2426. if (conn == NULL) {
  2427. MG_SET_PTRPTR(opts.error_string, "failed to init connection");
  2428. }
  2429. return conn;
  2430. }
  2431. /*
  2432. * Address format: [PROTO://][HOST]:PORT
  2433. *
  2434. * HOST could be IPv4/IPv6 address or a host name.
  2435. * `host` is a destination buffer to hold parsed HOST part. Should be at least
  2436. * MG_MAX_HOST_LEN bytes long.
  2437. * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
  2438. *
  2439. * Return:
  2440. * -1 on parse error
  2441. * 0 if HOST needs DNS lookup
  2442. * >0 length of the address string
  2443. */
  2444. MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
  2445. int *proto, char *host, size_t host_len) {
  2446. unsigned int a, b, c, d, port = 0;
  2447. int ch, len = 0;
  2448. #if MG_ENABLE_IPV6
  2449. char buf[100];
  2450. #endif
  2451. /*
  2452. * MacOS needs that. If we do not zero it, subsequent bind() will fail.
  2453. * Also, all-zeroes in the socket address means binding to all addresses
  2454. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  2455. */
  2456. memset(sa, 0, sizeof(*sa));
  2457. sa->sin.sin_family = AF_INET;
  2458. *proto = SOCK_STREAM;
  2459. if (strncmp(str, "udp://", 6) == 0) {
  2460. str += 6;
  2461. *proto = SOCK_DGRAM;
  2462. } else if (strncmp(str, "tcp://", 6) == 0) {
  2463. str += 6;
  2464. }
  2465. if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  2466. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  2467. sa->sin.sin_addr.s_addr =
  2468. htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
  2469. sa->sin.sin_port = htons((uint16_t) port);
  2470. #if MG_ENABLE_IPV6
  2471. } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
  2472. inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
  2473. /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
  2474. sa->sin6.sin6_family = AF_INET6;
  2475. sa->sin.sin_port = htons((uint16_t) port);
  2476. #endif
  2477. #if MG_ENABLE_ASYNC_RESOLVER
  2478. } else if (strlen(str) < host_len &&
  2479. sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
  2480. sa->sin.sin_port = htons((uint16_t) port);
  2481. if (mg_resolve_from_hosts_file(host, sa) != 0) {
  2482. /*
  2483. * if resolving from hosts file failed and the host
  2484. * we are trying to resolve is `localhost` - we should
  2485. * try to resolve it using `gethostbyname` and do not try
  2486. * to resolve it via DNS server if gethostbyname has failed too
  2487. */
  2488. if (mg_ncasecmp(host, "localhost", 9) != 0) {
  2489. return 0;
  2490. }
  2491. #if MG_ENABLE_SYNC_RESOLVER
  2492. if (!mg_resolve2(host, &sa->sin.sin_addr)) {
  2493. return -1;
  2494. }
  2495. #else
  2496. return -1;
  2497. #endif
  2498. }
  2499. #endif
  2500. } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
  2501. sscanf(str, "%u%n", &port, &len) == 1) {
  2502. /* If only port is specified, bind to IPv4, INADDR_ANY */
  2503. sa->sin.sin_port = htons((uint16_t) port);
  2504. } else {
  2505. return -1;
  2506. }
  2507. /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */
  2508. (void) host;
  2509. (void) host_len;
  2510. ch = str[len]; /* Character that follows the address */
  2511. return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
  2512. }
  2513. #if MG_ENABLE_SSL
  2514. MG_INTERNAL void mg_ssl_handshake(struct mg_connection *nc) {
  2515. int err = 0;
  2516. int server_side = (nc->listener != NULL);
  2517. enum mg_ssl_if_result res;
  2518. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) return;
  2519. res = mg_ssl_if_handshake(nc);
  2520. if (res == MG_SSL_OK) {
  2521. nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
  2522. nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
  2523. if (server_side) {
  2524. mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
  2525. } else {
  2526. mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
  2527. }
  2528. } else if (res == MG_SSL_WANT_READ) {
  2529. nc->flags |= MG_F_WANT_READ;
  2530. } else if (res == MG_SSL_WANT_WRITE) {
  2531. nc->flags |= MG_F_WANT_WRITE;
  2532. } else {
  2533. if (!server_side) {
  2534. err = res;
  2535. mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
  2536. }
  2537. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2538. }
  2539. }
  2540. #endif /* MG_ENABLE_SSL */
  2541. struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
  2542. struct mg_add_sock_opts opts;
  2543. struct mg_connection *nc;
  2544. memset(&opts, 0, sizeof(opts));
  2545. nc = mg_create_connection(lc->mgr, lc->handler, opts);
  2546. if (nc == NULL) return NULL;
  2547. nc->listener = lc;
  2548. nc->proto_handler = lc->proto_handler;
  2549. nc->user_data = lc->user_data;
  2550. nc->recv_mbuf_limit = lc->recv_mbuf_limit;
  2551. nc->iface = lc->iface;
  2552. if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL;
  2553. mg_add_conn(nc->mgr, nc);
  2554. LOG(LL_DEBUG, ("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags));
  2555. return nc;
  2556. }
  2557. void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
  2558. size_t sa_len) {
  2559. LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"),
  2560. inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
  2561. nc->sa = *sa;
  2562. #if MG_ENABLE_SSL
  2563. if (nc->listener->flags & MG_F_SSL) {
  2564. nc->flags |= MG_F_SSL;
  2565. if (mg_ssl_if_conn_accept(nc, nc->listener) == MG_SSL_OK) {
  2566. mg_ssl_handshake(nc);
  2567. } else {
  2568. mg_close_conn(nc);
  2569. }
  2570. } else
  2571. #endif
  2572. {
  2573. mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
  2574. }
  2575. (void) sa_len;
  2576. }
  2577. void mg_send(struct mg_connection *nc, const void *buf, int len) {
  2578. nc->last_io_time = (time_t) mg_time();
  2579. mbuf_append(&nc->send_mbuf, buf, len);
  2580. }
  2581. static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len);
  2582. static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len);
  2583. static int mg_do_recv(struct mg_connection *nc) {
  2584. int res = 0;
  2585. char *buf = NULL;
  2586. size_t len = (nc->flags & MG_F_UDP ? MG_UDP_IO_SIZE : MG_TCP_IO_SIZE);
  2587. if ((nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) ||
  2588. ((nc->flags & MG_F_LISTENING) && !(nc->flags & MG_F_UDP))) {
  2589. return -1;
  2590. }
  2591. do {
  2592. len = recv_avail_size(nc, len);
  2593. if (len == 0) {
  2594. res = -2;
  2595. break;
  2596. }
  2597. if (nc->recv_mbuf.size < nc->recv_mbuf.len + len) {
  2598. mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.len + len);
  2599. }
  2600. buf = nc->recv_mbuf.buf + nc->recv_mbuf.len;
  2601. len = nc->recv_mbuf.size - nc->recv_mbuf.len;
  2602. if (nc->flags & MG_F_UDP) {
  2603. res = mg_recv_udp(nc, buf, len);
  2604. } else {
  2605. res = mg_recv_tcp(nc, buf, len);
  2606. }
  2607. } while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP)));
  2608. return res;
  2609. }
  2610. void mg_if_can_recv_cb(struct mg_connection *nc) {
  2611. mg_do_recv(nc);
  2612. }
  2613. static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len) {
  2614. int n = 0;
  2615. #if MG_ENABLE_SSL
  2616. if (nc->flags & MG_F_SSL) {
  2617. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  2618. n = mg_ssl_if_read(nc, buf, len);
  2619. DBG(("%p <- %d bytes (SSL)", nc, n));
  2620. if (n < 0) {
  2621. if (n == MG_SSL_WANT_READ) {
  2622. nc->flags |= MG_F_WANT_READ;
  2623. n = 0;
  2624. } else {
  2625. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2626. }
  2627. } else if (n > 0) {
  2628. nc->flags &= ~MG_F_WANT_READ;
  2629. }
  2630. } else {
  2631. mg_ssl_handshake(nc);
  2632. }
  2633. } else
  2634. #endif
  2635. {
  2636. n = nc->iface->vtable->tcp_recv(nc, buf, len);
  2637. DBG(("%p <- %d bytes", nc, n));
  2638. }
  2639. if (n > 0) {
  2640. nc->recv_mbuf.len += n;
  2641. nc->last_io_time = (time_t) mg_time();
  2642. #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
  2643. if (nc->mgr && nc->mgr->hexdump_file != NULL) {
  2644. mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
  2645. }
  2646. #endif
  2647. mbuf_trim(&nc->recv_mbuf);
  2648. mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
  2649. } else if (n < 0) {
  2650. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2651. }
  2652. mbuf_trim(&nc->recv_mbuf);
  2653. return n;
  2654. }
  2655. static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) {
  2656. int n = 0;
  2657. struct mg_connection *lc = nc;
  2658. union socket_address sa;
  2659. size_t sa_len = sizeof(sa);
  2660. n = nc->iface->vtable->udp_recv(lc, buf, len, &sa, &sa_len);
  2661. if (n < 0) {
  2662. lc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2663. goto out;
  2664. }
  2665. if (nc->flags & MG_F_LISTENING) {
  2666. /*
  2667. * Do we have an existing connection for this source?
  2668. * This is very inefficient for long connection lists.
  2669. */
  2670. lc = nc;
  2671. for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
  2672. if (memcmp(&nc->sa.sa, &sa.sa, sa_len) == 0 && nc->listener == lc) {
  2673. break;
  2674. }
  2675. }
  2676. if (nc == NULL) {
  2677. struct mg_add_sock_opts opts;
  2678. memset(&opts, 0, sizeof(opts));
  2679. /* Create fake connection w/out sock initialization */
  2680. nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
  2681. if (nc != NULL) {
  2682. nc->sock = lc->sock;
  2683. nc->listener = lc;
  2684. nc->sa = sa;
  2685. nc->proto_handler = lc->proto_handler;
  2686. nc->user_data = lc->user_data;
  2687. nc->recv_mbuf_limit = lc->recv_mbuf_limit;
  2688. nc->flags = MG_F_UDP;
  2689. /*
  2690. * Long-lived UDP "connections" i.e. interactions that involve more
  2691. * than one request and response are rare, most are transactional:
  2692. * response is sent and the "connection" is closed. Or - should be.
  2693. * But users (including ourselves) tend to forget about that part,
  2694. * because UDP is connectionless and one does not think about
  2695. * processing a UDP request as handling a connection that needs to be
  2696. * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should
  2697. * be a reasonable default for most use cases, but it is possible to
  2698. * turn it off the connection should be kept alive after processing.
  2699. */
  2700. nc->flags |= MG_F_SEND_AND_CLOSE;
  2701. mg_add_conn(lc->mgr, nc);
  2702. mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
  2703. }
  2704. }
  2705. }
  2706. if (nc != NULL) {
  2707. DBG(("%p <- %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
  2708. ntohs(nc->sa.sin.sin_port)));
  2709. if (nc == lc) {
  2710. nc->recv_mbuf.len += n;
  2711. } else {
  2712. mbuf_append(&nc->recv_mbuf, buf, n);
  2713. }
  2714. mbuf_trim(&lc->recv_mbuf);
  2715. lc->last_io_time = nc->last_io_time = (time_t) mg_time();
  2716. #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
  2717. if (nc->mgr && nc->mgr->hexdump_file != NULL) {
  2718. mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
  2719. }
  2720. #endif
  2721. if (n != 0) {
  2722. mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
  2723. }
  2724. }
  2725. out:
  2726. mbuf_free(&lc->recv_mbuf);
  2727. return n;
  2728. }
  2729. void mg_if_can_send_cb(struct mg_connection *nc) {
  2730. int n = 0;
  2731. const char *buf = nc->send_mbuf.buf;
  2732. size_t len = nc->send_mbuf.len;
  2733. if (nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) {
  2734. return;
  2735. }
  2736. if (!(nc->flags & MG_F_UDP)) {
  2737. if (nc->flags & MG_F_LISTENING) return;
  2738. if (len > MG_TCP_IO_SIZE) len = MG_TCP_IO_SIZE;
  2739. }
  2740. #if MG_ENABLE_SSL
  2741. if (nc->flags & MG_F_SSL) {
  2742. if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
  2743. if (len > 0) {
  2744. n = mg_ssl_if_write(nc, buf, len);
  2745. DBG(("%p -> %d bytes (SSL)", nc, n));
  2746. }
  2747. if (n < 0) {
  2748. if (n == MG_SSL_WANT_WRITE) {
  2749. nc->flags |= MG_F_WANT_WRITE;
  2750. n = 0;
  2751. } else {
  2752. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2753. }
  2754. } else {
  2755. nc->flags &= ~MG_F_WANT_WRITE;
  2756. }
  2757. } else {
  2758. mg_ssl_handshake(nc);
  2759. }
  2760. } else
  2761. #endif
  2762. if (len > 0) {
  2763. if (nc->flags & MG_F_UDP) {
  2764. n = nc->iface->vtable->udp_send(nc, buf, len);
  2765. } else {
  2766. n = nc->iface->vtable->tcp_send(nc, buf, len);
  2767. }
  2768. DBG(("%p -> %d bytes", nc, n));
  2769. }
  2770. #if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
  2771. if (n > 0 && nc->mgr && nc->mgr->hexdump_file != NULL) {
  2772. mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_SEND);
  2773. }
  2774. #endif
  2775. if (n < 0) {
  2776. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2777. } else if (n > 0) {
  2778. nc->last_io_time = (time_t) mg_time();
  2779. mbuf_remove(&nc->send_mbuf, n);
  2780. mbuf_trim(&nc->send_mbuf);
  2781. }
  2782. if (n != 0) mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &n);
  2783. }
  2784. /*
  2785. * Schedules an async connect for a resolved address and proto.
  2786. * Called from two places: `mg_connect_opt()` and from async resolver.
  2787. * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
  2788. * with a failure flag to indicate connection failure.
  2789. */
  2790. MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
  2791. int proto,
  2792. union socket_address *sa) {
  2793. LOG(LL_DEBUG, ("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
  2794. inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
  2795. nc->flags |= MG_F_CONNECTING;
  2796. if (proto == SOCK_DGRAM) {
  2797. nc->iface->vtable->connect_udp(nc);
  2798. } else {
  2799. nc->iface->vtable->connect_tcp(nc, sa);
  2800. }
  2801. mg_add_conn(nc->mgr, nc);
  2802. return nc;
  2803. }
  2804. void mg_if_connect_cb(struct mg_connection *nc, int err) {
  2805. LOG(LL_DEBUG,
  2806. ("%p %s://%s:%hu -> %d", nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"),
  2807. inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port), err));
  2808. nc->flags &= ~MG_F_CONNECTING;
  2809. if (err != 0) {
  2810. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  2811. }
  2812. #if MG_ENABLE_SSL
  2813. if (err == 0 && (nc->flags & MG_F_SSL)) {
  2814. mg_ssl_handshake(nc);
  2815. } else
  2816. #endif
  2817. {
  2818. mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
  2819. }
  2820. }
  2821. #if MG_ENABLE_ASYNC_RESOLVER
  2822. /*
  2823. * Callback for the async resolver on mg_connect_opt() call.
  2824. * Main task of this function is to trigger MG_EV_CONNECT event with
  2825. * either failure (and dealloc the connection)
  2826. * or success (and proceed with connect()
  2827. */
  2828. static void resolve_cb(struct mg_dns_message *msg, void *data,
  2829. enum mg_resolve_err e) {
  2830. struct mg_connection *nc = (struct mg_connection *) data;
  2831. int i;
  2832. int failure = -1;
  2833. nc->flags &= ~MG_F_RESOLVING;
  2834. if (msg != NULL) {
  2835. /*
  2836. * Take the first DNS A answer and run...
  2837. */
  2838. for (i = 0; i < msg->num_answers; i++) {
  2839. if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
  2840. /*
  2841. * Async resolver guarantees that there is at least one answer.
  2842. * TODO(lsm): handle IPv6 answers too
  2843. */
  2844. mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
  2845. 4);
  2846. mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
  2847. &nc->sa);
  2848. return;
  2849. }
  2850. }
  2851. }
  2852. if (e == MG_RESOLVE_TIMEOUT) {
  2853. double now = mg_time();
  2854. mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now);
  2855. }
  2856. /*
  2857. * If we get there was no MG_DNS_A_RECORD in the answer
  2858. */
  2859. mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure);
  2860. mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL);
  2861. mg_destroy_conn(nc, 1 /* destroy_if */);
  2862. }
  2863. #endif
  2864. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
  2865. MG_CB(mg_event_handler_t callback,
  2866. void *user_data)) {
  2867. struct mg_connect_opts opts;
  2868. memset(&opts, 0, sizeof(opts));
  2869. return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts);
  2870. }
  2871. void mg_ev_handler_empty(struct mg_connection *c, int ev,
  2872. void *ev_data MG_UD_ARG(void *user_data)) {
  2873. (void) c;
  2874. (void) ev;
  2875. (void) ev_data;
  2876. #if MG_ENABLE_CALLBACK_USERDATA
  2877. (void) user_data;
  2878. #endif
  2879. }
  2880. struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
  2881. MG_CB(mg_event_handler_t callback,
  2882. void *user_data),
  2883. struct mg_connect_opts opts) {
  2884. struct mg_connection *nc = NULL;
  2885. int proto, rc;
  2886. struct mg_add_sock_opts add_sock_opts;
  2887. char host[MG_MAX_HOST_LEN];
  2888. MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
  2889. if (callback == NULL) callback = mg_ev_handler_empty;
  2890. if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
  2891. return NULL;
  2892. }
  2893. if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) <
  2894. 0) {
  2895. /* Address is malformed */
  2896. MG_SET_PTRPTR(opts.error_string, "cannot parse address");
  2897. mg_destroy_conn(nc, 1 /* destroy_if */);
  2898. return NULL;
  2899. }
  2900. nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
  2901. nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
  2902. #if MG_ENABLE_CALLBACK_USERDATA
  2903. nc->user_data = user_data;
  2904. #else
  2905. nc->user_data = opts.user_data;
  2906. #endif
  2907. #if MG_ENABLE_SSL
  2908. LOG(LL_DEBUG,
  2909. ("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
  2910. (opts.ssl_key ? opts.ssl_key : "-"),
  2911. (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
  2912. if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
  2913. opts.ssl_psk_identity != NULL) {
  2914. const char *err_msg = NULL;
  2915. struct mg_ssl_if_conn_params params;
  2916. if (nc->flags & MG_F_UDP) {
  2917. MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
  2918. mg_destroy_conn(nc, 1 /* destroy_if */);
  2919. return NULL;
  2920. }
  2921. memset(&params, 0, sizeof(params));
  2922. params.cert = opts.ssl_cert;
  2923. params.key = opts.ssl_key;
  2924. params.ca_cert = opts.ssl_ca_cert;
  2925. params.cipher_suites = opts.ssl_cipher_suites;
  2926. params.psk_identity = opts.ssl_psk_identity;
  2927. params.psk_key = opts.ssl_psk_key;
  2928. if (opts.ssl_ca_cert != NULL) {
  2929. if (opts.ssl_server_name != NULL) {
  2930. if (strcmp(opts.ssl_server_name, "*") != 0) {
  2931. params.server_name = opts.ssl_server_name;
  2932. }
  2933. } else if (rc == 0) { /* If it's a DNS name, use host. */
  2934. params.server_name = host;
  2935. }
  2936. }
  2937. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  2938. MG_SET_PTRPTR(opts.error_string, err_msg);
  2939. mg_destroy_conn(nc, 1 /* destroy_if */);
  2940. return NULL;
  2941. }
  2942. nc->flags |= MG_F_SSL;
  2943. }
  2944. #endif /* MG_ENABLE_SSL */
  2945. if (rc == 0) {
  2946. #if MG_ENABLE_ASYNC_RESOLVER
  2947. /*
  2948. * DNS resolution is required for host.
  2949. * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
  2950. */
  2951. struct mg_connection *dns_conn = NULL;
  2952. struct mg_resolve_async_opts o;
  2953. memset(&o, 0, sizeof(o));
  2954. o.dns_conn = &dns_conn;
  2955. o.nameserver = opts.nameserver;
  2956. if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
  2957. o) != 0) {
  2958. MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
  2959. mg_destroy_conn(nc, 1 /* destroy_if */);
  2960. return NULL;
  2961. }
  2962. nc->priv_2 = dns_conn;
  2963. nc->flags |= MG_F_RESOLVING;
  2964. return nc;
  2965. #else
  2966. MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
  2967. mg_destroy_conn(nc, 1 /* destroy_if */);
  2968. return NULL;
  2969. #endif
  2970. } else {
  2971. /* Address is parsed and resolved to IP. proceed with connect() */
  2972. return mg_do_connect(nc, proto, &nc->sa);
  2973. }
  2974. }
  2975. struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
  2976. MG_CB(mg_event_handler_t event_handler,
  2977. void *user_data)) {
  2978. struct mg_bind_opts opts;
  2979. memset(&opts, 0, sizeof(opts));
  2980. return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts);
  2981. }
  2982. struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
  2983. MG_CB(mg_event_handler_t callback,
  2984. void *user_data),
  2985. struct mg_bind_opts opts) {
  2986. union socket_address sa;
  2987. struct mg_connection *nc = NULL;
  2988. int proto, rc;
  2989. struct mg_add_sock_opts add_sock_opts;
  2990. char host[MG_MAX_HOST_LEN];
  2991. #if MG_ENABLE_CALLBACK_USERDATA
  2992. opts.user_data = user_data;
  2993. #endif
  2994. if (callback == NULL) callback = mg_ev_handler_empty;
  2995. MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
  2996. if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
  2997. MG_SET_PTRPTR(opts.error_string, "cannot parse address");
  2998. return NULL;
  2999. }
  3000. nc = mg_create_connection(mgr, callback, add_sock_opts);
  3001. if (nc == NULL) {
  3002. return NULL;
  3003. }
  3004. nc->sa = sa;
  3005. nc->flags |= MG_F_LISTENING;
  3006. if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP;
  3007. #if MG_ENABLE_SSL
  3008. DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
  3009. (opts.ssl_key ? opts.ssl_key : "-"),
  3010. (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
  3011. if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
  3012. const char *err_msg = NULL;
  3013. struct mg_ssl_if_conn_params params;
  3014. if (nc->flags & MG_F_UDP) {
  3015. MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
  3016. mg_destroy_conn(nc, 1 /* destroy_if */);
  3017. return NULL;
  3018. }
  3019. memset(&params, 0, sizeof(params));
  3020. params.cert = opts.ssl_cert;
  3021. params.key = opts.ssl_key;
  3022. params.ca_cert = opts.ssl_ca_cert;
  3023. params.cipher_suites = opts.ssl_cipher_suites;
  3024. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  3025. MG_SET_PTRPTR(opts.error_string, err_msg);
  3026. mg_destroy_conn(nc, 1 /* destroy_if */);
  3027. return NULL;
  3028. }
  3029. nc->flags |= MG_F_SSL;
  3030. }
  3031. #endif /* MG_ENABLE_SSL */
  3032. if (nc->flags & MG_F_UDP) {
  3033. rc = nc->iface->vtable->listen_udp(nc, &nc->sa);
  3034. } else {
  3035. rc = nc->iface->vtable->listen_tcp(nc, &nc->sa);
  3036. }
  3037. if (rc != 0) {
  3038. DBG(("Failed to open listener: %d", rc));
  3039. MG_SET_PTRPTR(opts.error_string, "failed to open listener");
  3040. mg_destroy_conn(nc, 1 /* destroy_if */);
  3041. return NULL;
  3042. }
  3043. mg_add_conn(nc->mgr, nc);
  3044. return nc;
  3045. }
  3046. struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
  3047. return conn == NULL ? s->active_connections : conn->next;
  3048. }
  3049. #if MG_ENABLE_BROADCAST
  3050. void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
  3051. size_t len) {
  3052. struct ctl_msg ctl_msg;
  3053. /*
  3054. * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
  3055. * where `mg_broadcast()` pushes the message.
  3056. * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
  3057. * specified callback for each connection. Thus the callback function executes
  3058. * in event manager thread.
  3059. */
  3060. if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
  3061. len < sizeof(ctl_msg.message)) {
  3062. size_t dummy;
  3063. ctl_msg.callback = cb;
  3064. memcpy(ctl_msg.message, data, len);
  3065. dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
  3066. offsetof(struct ctl_msg, message) + len, 0);
  3067. dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
  3068. (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
  3069. }
  3070. }
  3071. #endif /* MG_ENABLE_BROADCAST */
  3072. static int isbyte(int n) {
  3073. return n >= 0 && n <= 255;
  3074. }
  3075. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  3076. int n, a, b, c, d, slash = 32, len = 0;
  3077. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  3078. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  3079. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  3080. slash < 33) {
  3081. len = n;
  3082. *net =
  3083. ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
  3084. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  3085. }
  3086. return len;
  3087. }
  3088. int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
  3089. int allowed, flag;
  3090. uint32_t net, mask;
  3091. struct mg_str vec;
  3092. /* If any ACL is set, deny by default */
  3093. allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
  3094. while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
  3095. flag = vec.p[0];
  3096. if ((flag != '+' && flag != '-') ||
  3097. parse_net(&vec.p[1], &net, &mask) == 0) {
  3098. return -1;
  3099. }
  3100. if (net == (remote_ip & mask)) {
  3101. allowed = flag;
  3102. }
  3103. }
  3104. DBG(("%08x %c", (unsigned int) remote_ip, allowed));
  3105. return allowed == '+';
  3106. }
  3107. /* Move data from one connection to another */
  3108. void mg_forward(struct mg_connection *from, struct mg_connection *to) {
  3109. mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
  3110. mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
  3111. }
  3112. double mg_set_timer(struct mg_connection *c, double timestamp) {
  3113. double result = c->ev_timer_time;
  3114. c->ev_timer_time = timestamp;
  3115. /*
  3116. * If this connection is resolving, it's not in the list of active
  3117. * connections, so not processed yet. It has a DNS resolver connection
  3118. * linked to it. Set up a timer for the DNS connection.
  3119. */
  3120. DBG(("%p %p %d -> %lu", c, c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0),
  3121. (unsigned long) timestamp));
  3122. if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
  3123. mg_set_timer((struct mg_connection *) c->priv_2, timestamp);
  3124. }
  3125. return result;
  3126. }
  3127. void mg_sock_set(struct mg_connection *nc, sock_t sock) {
  3128. if (sock != INVALID_SOCKET) {
  3129. nc->iface->vtable->sock_set(nc, sock);
  3130. }
  3131. }
  3132. void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
  3133. union socket_address *sa) {
  3134. nc->iface->vtable->get_conn_addr(nc, remote, sa);
  3135. }
  3136. struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
  3137. MG_CB(mg_event_handler_t callback,
  3138. void *user_data),
  3139. struct mg_add_sock_opts opts) {
  3140. #if MG_ENABLE_CALLBACK_USERDATA
  3141. opts.user_data = user_data;
  3142. #endif
  3143. struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
  3144. if (nc != NULL) {
  3145. mg_sock_set(nc, sock);
  3146. mg_add_conn(nc->mgr, nc);
  3147. }
  3148. return nc;
  3149. }
  3150. struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
  3151. MG_CB(mg_event_handler_t callback,
  3152. void *user_data)) {
  3153. struct mg_add_sock_opts opts;
  3154. memset(&opts, 0, sizeof(opts));
  3155. return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts);
  3156. }
  3157. double mg_time(void) {
  3158. return cs_time();
  3159. }
  3160. #ifdef MG_MODULE_LINES
  3161. #line 1 "mongoose/src/mg_net_if_socket.h"
  3162. #endif
  3163. /*
  3164. * Copyright (c) 2014-2016 Cesanta Software Limited
  3165. * All rights reserved
  3166. */
  3167. #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
  3168. #define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
  3169. /* Amalgamated: #include "mg_net_if.h" */
  3170. #ifdef __cplusplus
  3171. extern "C" {
  3172. #endif /* __cplusplus */
  3173. #ifndef MG_ENABLE_NET_IF_SOCKET
  3174. #define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
  3175. #endif
  3176. extern const struct mg_iface_vtable mg_socket_iface_vtable;
  3177. #ifdef __cplusplus
  3178. }
  3179. #endif /* __cplusplus */
  3180. #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */
  3181. #ifdef MG_MODULE_LINES
  3182. #line 1 "mongoose/src/mg_net_if_socks.h"
  3183. #endif
  3184. /*
  3185. * Copyright (c) 2014-2017 Cesanta Software Limited
  3186. * All rights reserved
  3187. */
  3188. #ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
  3189. #define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
  3190. #if MG_ENABLE_SOCKS
  3191. /* Amalgamated: #include "mg_net_if.h" */
  3192. #ifdef __cplusplus
  3193. extern "C" {
  3194. #endif /* __cplusplus */
  3195. extern const struct mg_iface_vtable mg_socks_iface_vtable;
  3196. #ifdef __cplusplus
  3197. }
  3198. #endif /* __cplusplus */
  3199. #endif /* MG_ENABLE_SOCKS */
  3200. #endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */
  3201. #ifdef MG_MODULE_LINES
  3202. #line 1 "mongoose/src/mg_net_if.c"
  3203. #endif
  3204. /* Amalgamated: #include "mg_net_if.h" */
  3205. /* Amalgamated: #include "mg_internal.h" */
  3206. /* Amalgamated: #include "mg_net_if_socket.h" */
  3207. extern const struct mg_iface_vtable mg_default_iface_vtable;
  3208. const struct mg_iface_vtable *mg_ifaces[] = {
  3209. &mg_default_iface_vtable,
  3210. };
  3211. int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0]));
  3212. struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable,
  3213. struct mg_mgr *mgr) {
  3214. struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface));
  3215. iface->mgr = mgr;
  3216. iface->data = NULL;
  3217. iface->vtable = vtable;
  3218. return iface;
  3219. }
  3220. struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
  3221. const struct mg_iface_vtable *vtable,
  3222. struct mg_iface *from) {
  3223. int i = 0;
  3224. if (from != NULL) {
  3225. for (i = 0; i < mgr->num_ifaces; i++) {
  3226. if (mgr->ifaces[i] == from) {
  3227. i++;
  3228. break;
  3229. }
  3230. }
  3231. }
  3232. for (; i < mgr->num_ifaces; i++) {
  3233. if (mgr->ifaces[i]->vtable == vtable) {
  3234. return mgr->ifaces[i];
  3235. }
  3236. }
  3237. return NULL;
  3238. }
  3239. double mg_mgr_min_timer(const struct mg_mgr *mgr) {
  3240. double min_timer = 0;
  3241. struct mg_connection *nc;
  3242. for (nc = mgr->active_connections; nc != NULL; nc = nc->next) {
  3243. if (nc->ev_timer_time <= 0) continue;
  3244. if (min_timer == 0 || nc->ev_timer_time < min_timer) {
  3245. min_timer = nc->ev_timer_time;
  3246. }
  3247. }
  3248. return min_timer;
  3249. }
  3250. #ifdef MG_MODULE_LINES
  3251. #line 1 "mongoose/src/mg_net_if_null.c"
  3252. #endif
  3253. /*
  3254. * Copyright (c) 2018 Cesanta Software Limited
  3255. * All rights reserved
  3256. *
  3257. * This software is dual-licensed: you can redistribute it and/or modify
  3258. * it under the terms of the GNU General Public License version 2 as
  3259. * published by the Free Software Foundation. For the terms of this
  3260. * license, see <http://www.gnu.org/licenses/>.
  3261. *
  3262. * You are free to use this software under the terms of the GNU General
  3263. * Public License, but WITHOUT ANY WARRANTY; without even the implied
  3264. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  3265. * See the GNU General Public License for more details.
  3266. *
  3267. * Alternatively, you can license this software under a commercial
  3268. * license, as set out in <https://www.cesanta.com/license>.
  3269. */
  3270. static void mg_null_if_connect_tcp(struct mg_connection *c,
  3271. const union socket_address *sa) {
  3272. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  3273. (void) sa;
  3274. }
  3275. static void mg_null_if_connect_udp(struct mg_connection *c) {
  3276. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  3277. }
  3278. static int mg_null_if_listen_tcp(struct mg_connection *c,
  3279. union socket_address *sa) {
  3280. (void) c;
  3281. (void) sa;
  3282. return -1;
  3283. }
  3284. static int mg_null_if_listen_udp(struct mg_connection *c,
  3285. union socket_address *sa) {
  3286. (void) c;
  3287. (void) sa;
  3288. return -1;
  3289. }
  3290. static int mg_null_if_tcp_send(struct mg_connection *c, const void *buf,
  3291. size_t len) {
  3292. (void) c;
  3293. (void) buf;
  3294. (void) len;
  3295. return -1;
  3296. }
  3297. static int mg_null_if_udp_send(struct mg_connection *c, const void *buf,
  3298. size_t len) {
  3299. (void) c;
  3300. (void) buf;
  3301. (void) len;
  3302. return -1;
  3303. }
  3304. int mg_null_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) {
  3305. (void) c;
  3306. (void) buf;
  3307. (void) len;
  3308. return -1;
  3309. }
  3310. int mg_null_if_udp_recv(struct mg_connection *c, void *buf, size_t len,
  3311. union socket_address *sa, size_t *sa_len) {
  3312. (void) c;
  3313. (void) buf;
  3314. (void) len;
  3315. (void) sa;
  3316. (void) sa_len;
  3317. return -1;
  3318. }
  3319. static int mg_null_if_create_conn(struct mg_connection *c) {
  3320. (void) c;
  3321. return 1;
  3322. }
  3323. static void mg_null_if_destroy_conn(struct mg_connection *c) {
  3324. (void) c;
  3325. }
  3326. static void mg_null_if_sock_set(struct mg_connection *c, sock_t sock) {
  3327. (void) c;
  3328. (void) sock;
  3329. }
  3330. static void mg_null_if_init(struct mg_iface *iface) {
  3331. (void) iface;
  3332. }
  3333. static void mg_null_if_free(struct mg_iface *iface) {
  3334. (void) iface;
  3335. }
  3336. static void mg_null_if_add_conn(struct mg_connection *c) {
  3337. c->sock = INVALID_SOCKET;
  3338. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  3339. }
  3340. static void mg_null_if_remove_conn(struct mg_connection *c) {
  3341. (void) c;
  3342. }
  3343. static time_t mg_null_if_poll(struct mg_iface *iface, int timeout_ms) {
  3344. struct mg_mgr *mgr = iface->mgr;
  3345. struct mg_connection *nc, *tmp;
  3346. double now = mg_time();
  3347. /* We basically just run timers and poll. */
  3348. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  3349. tmp = nc->next;
  3350. mg_if_poll(nc, now);
  3351. }
  3352. (void) timeout_ms;
  3353. return (time_t) now;
  3354. }
  3355. static void mg_null_if_get_conn_addr(struct mg_connection *c, int remote,
  3356. union socket_address *sa) {
  3357. (void) c;
  3358. (void) remote;
  3359. (void) sa;
  3360. }
  3361. #define MG_NULL_IFACE_VTABLE \
  3362. { \
  3363. mg_null_if_init, mg_null_if_free, mg_null_if_add_conn, \
  3364. mg_null_if_remove_conn, mg_null_if_poll, mg_null_if_listen_tcp, \
  3365. mg_null_if_listen_udp, mg_null_if_connect_tcp, mg_null_if_connect_udp, \
  3366. mg_null_if_tcp_send, mg_null_if_udp_send, mg_null_if_tcp_recv, \
  3367. mg_null_if_udp_recv, mg_null_if_create_conn, mg_null_if_destroy_conn, \
  3368. mg_null_if_sock_set, mg_null_if_get_conn_addr, \
  3369. }
  3370. const struct mg_iface_vtable mg_null_iface_vtable = MG_NULL_IFACE_VTABLE;
  3371. #if MG_NET_IF == MG_NET_IF_NULL
  3372. const struct mg_iface_vtable mg_default_iface_vtable = MG_NULL_IFACE_VTABLE;
  3373. #endif /* MG_NET_IF == MG_NET_IF_NULL */
  3374. #ifdef MG_MODULE_LINES
  3375. #line 1 "mongoose/src/mg_net_if_socket.c"
  3376. #endif
  3377. /*
  3378. * Copyright (c) 2014-2016 Cesanta Software Limited
  3379. * All rights reserved
  3380. */
  3381. #if MG_ENABLE_NET_IF_SOCKET
  3382. /* Amalgamated: #include "mg_net_if_socket.h" */
  3383. /* Amalgamated: #include "mg_internal.h" */
  3384. /* Amalgamated: #include "mg_util.h" */
  3385. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  3386. int proto);
  3387. void mg_set_non_blocking_mode(sock_t sock) {
  3388. #ifdef _WIN32
  3389. unsigned long on = 1;
  3390. ioctlsocket(sock, FIONBIO, &on);
  3391. #else
  3392. int flags = fcntl(sock, F_GETFL, 0);
  3393. fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3394. #endif
  3395. }
  3396. static int mg_is_error(void) {
  3397. int err = mg_get_errno();
  3398. return err != EINPROGRESS && err != EWOULDBLOCK
  3399. #ifndef WINCE
  3400. && err != EAGAIN && err != EINTR
  3401. #endif
  3402. #ifdef _WIN32
  3403. && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
  3404. #endif
  3405. ;
  3406. }
  3407. void mg_socket_if_connect_tcp(struct mg_connection *nc,
  3408. const union socket_address *sa) {
  3409. int rc, proto = 0;
  3410. nc->sock = socket(AF_INET, SOCK_STREAM, proto);
  3411. if (nc->sock == INVALID_SOCKET) {
  3412. nc->err = mg_get_errno() ? mg_get_errno() : 1;
  3413. return;
  3414. }
  3415. #if !defined(MG_ESP8266)
  3416. mg_set_non_blocking_mode(nc->sock);
  3417. #endif
  3418. rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
  3419. nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0;
  3420. DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(),
  3421. nc->err));
  3422. }
  3423. void mg_socket_if_connect_udp(struct mg_connection *nc) {
  3424. nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
  3425. if (nc->sock == INVALID_SOCKET) {
  3426. nc->err = mg_get_errno() ? mg_get_errno() : 1;
  3427. return;
  3428. }
  3429. if (nc->flags & MG_F_ENABLE_BROADCAST) {
  3430. int optval = 1;
  3431. if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval,
  3432. sizeof(optval)) < 0) {
  3433. nc->err = mg_get_errno() ? mg_get_errno() : 1;
  3434. return;
  3435. }
  3436. }
  3437. nc->err = 0;
  3438. }
  3439. int mg_socket_if_listen_tcp(struct mg_connection *nc,
  3440. union socket_address *sa) {
  3441. int proto = 0;
  3442. sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
  3443. if (sock == INVALID_SOCKET) {
  3444. return (mg_get_errno() ? mg_get_errno() : 1);
  3445. }
  3446. mg_sock_set(nc, sock);
  3447. return 0;
  3448. }
  3449. static int mg_socket_if_listen_udp(struct mg_connection *nc,
  3450. union socket_address *sa) {
  3451. sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
  3452. if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1);
  3453. mg_sock_set(nc, sock);
  3454. return 0;
  3455. }
  3456. static int mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf,
  3457. size_t len) {
  3458. int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
  3459. if (n < 0 && !mg_is_error()) n = 0;
  3460. return n;
  3461. }
  3462. static int mg_socket_if_udp_send(struct mg_connection *nc, const void *buf,
  3463. size_t len) {
  3464. int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
  3465. if (n < 0 && !mg_is_error()) n = 0;
  3466. return n;
  3467. }
  3468. static int mg_socket_if_tcp_recv(struct mg_connection *nc, void *buf,
  3469. size_t len) {
  3470. int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
  3471. if (n == 0) {
  3472. /* Orderly shutdown of the socket, try flushing output. */
  3473. nc->flags |= MG_F_SEND_AND_CLOSE;
  3474. } else if (n < 0 && !mg_is_error()) {
  3475. n = 0;
  3476. }
  3477. return n;
  3478. }
  3479. static int mg_socket_if_udp_recv(struct mg_connection *nc, void *buf,
  3480. size_t len, union socket_address *sa,
  3481. size_t *sa_len) {
  3482. socklen_t sa_len_st = *sa_len;
  3483. int n = recvfrom(nc->sock, buf, len, 0, &sa->sa, &sa_len_st);
  3484. *sa_len = sa_len_st;
  3485. if (n < 0 && !mg_is_error()) n = 0;
  3486. return n;
  3487. }
  3488. int mg_socket_if_create_conn(struct mg_connection *nc) {
  3489. (void) nc;
  3490. return 1;
  3491. }
  3492. void mg_socket_if_destroy_conn(struct mg_connection *nc) {
  3493. if (nc->sock == INVALID_SOCKET) return;
  3494. if (!(nc->flags & MG_F_UDP)) {
  3495. closesocket(nc->sock);
  3496. } else {
  3497. /* Only close outgoing UDP sockets or listeners. */
  3498. if (nc->listener == NULL) closesocket(nc->sock);
  3499. }
  3500. nc->sock = INVALID_SOCKET;
  3501. }
  3502. static int mg_accept_conn(struct mg_connection *lc) {
  3503. struct mg_connection *nc;
  3504. union socket_address sa;
  3505. socklen_t sa_len = sizeof(sa);
  3506. /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
  3507. sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
  3508. if (sock == INVALID_SOCKET) {
  3509. if (mg_is_error()) {
  3510. DBG(("%p: failed to accept: %d", lc, mg_get_errno()));
  3511. }
  3512. return 0;
  3513. }
  3514. nc = mg_if_accept_new_conn(lc);
  3515. if (nc == NULL) {
  3516. closesocket(sock);
  3517. return 0;
  3518. }
  3519. DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
  3520. ntohs(sa.sin.sin_port)));
  3521. mg_sock_set(nc, sock);
  3522. mg_if_accept_tcp_cb(nc, &sa, sa_len);
  3523. return 1;
  3524. }
  3525. /* 'sa' must be an initialized address to bind to */
  3526. static sock_t mg_open_listening_socket(union socket_address *sa, int type,
  3527. int proto) {
  3528. socklen_t sa_len =
  3529. (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
  3530. sock_t sock = INVALID_SOCKET;
  3531. #if !MG_LWIP
  3532. int on = 1;
  3533. #endif
  3534. if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET &&
  3535. #if !MG_LWIP /* LWIP doesn't support either */
  3536. #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
  3537. /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
  3538. !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
  3539. sizeof(on)) &&
  3540. #endif
  3541. #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
  3542. /*
  3543. * SO_RESUSEADDR is not enabled on Windows because the semantics of
  3544. * SO_REUSEADDR on UNIX and Windows is different. On Windows,
  3545. * SO_REUSEADDR allows to bind a socket to a port without error even if
  3546. * the port is already open by another program. This is not the behavior
  3547. * SO_REUSEADDR was designed for, and leads to hard-to-track failure
  3548. * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
  3549. * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
  3550. */
  3551. !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
  3552. #endif
  3553. #endif /* !MG_LWIP */
  3554. !bind(sock, &sa->sa, sa_len) &&
  3555. (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
  3556. #if !MG_LWIP
  3557. mg_set_non_blocking_mode(sock);
  3558. /* In case port was set to 0, get the real port number */
  3559. (void) getsockname(sock, &sa->sa, &sa_len);
  3560. #endif
  3561. } else if (sock != INVALID_SOCKET) {
  3562. closesocket(sock);
  3563. sock = INVALID_SOCKET;
  3564. }
  3565. return sock;
  3566. }
  3567. #define _MG_F_FD_CAN_READ 1
  3568. #define _MG_F_FD_CAN_WRITE 1 << 1
  3569. #define _MG_F_FD_ERROR 1 << 2
  3570. void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
  3571. int worth_logging =
  3572. fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE));
  3573. if (worth_logging) {
  3574. DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
  3575. fd_flags, nc->flags, (int) nc->recv_mbuf.len,
  3576. (int) nc->send_mbuf.len));
  3577. }
  3578. if (!mg_if_poll(nc, now)) return;
  3579. if (nc->flags & MG_F_CONNECTING) {
  3580. if (fd_flags != 0) {
  3581. int err = 0;
  3582. #if !defined(MG_ESP8266)
  3583. if (!(nc->flags & MG_F_UDP)) {
  3584. socklen_t len = sizeof(err);
  3585. int ret =
  3586. getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
  3587. if (ret != 0) {
  3588. err = 1;
  3589. } else if (err == EAGAIN || err == EWOULDBLOCK) {
  3590. err = 0;
  3591. }
  3592. }
  3593. #else
  3594. /*
  3595. * On ESP8266 we use blocking connect.
  3596. */
  3597. err = nc->err;
  3598. #endif
  3599. mg_if_connect_cb(nc, err);
  3600. } else if (nc->err != 0) {
  3601. mg_if_connect_cb(nc, nc->err);
  3602. }
  3603. }
  3604. if (fd_flags & _MG_F_FD_CAN_READ) {
  3605. if (nc->flags & MG_F_UDP) {
  3606. mg_if_can_recv_cb(nc);
  3607. } else {
  3608. if (nc->flags & MG_F_LISTENING) {
  3609. /*
  3610. * We're not looping here, and accepting just one connection at
  3611. * a time. The reason is that eCos does not respect non-blocking
  3612. * flag on a listening socket and hangs in a loop.
  3613. */
  3614. mg_accept_conn(nc);
  3615. } else {
  3616. mg_if_can_recv_cb(nc);
  3617. }
  3618. }
  3619. }
  3620. if (fd_flags & _MG_F_FD_CAN_WRITE) mg_if_can_send_cb(nc);
  3621. if (worth_logging) {
  3622. DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
  3623. nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  3624. }
  3625. }
  3626. #if MG_ENABLE_BROADCAST
  3627. static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
  3628. struct ctl_msg ctl_msg;
  3629. int len =
  3630. (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
  3631. size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
  3632. DBG(("read %d from ctl socket", len));
  3633. (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
  3634. if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
  3635. struct mg_connection *nc;
  3636. for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
  3637. ctl_msg.callback(nc, MG_EV_POLL,
  3638. ctl_msg.message MG_UD_ARG(nc->user_data));
  3639. }
  3640. }
  3641. }
  3642. #endif
  3643. /* Associate a socket to a connection. */
  3644. void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) {
  3645. mg_set_non_blocking_mode(sock);
  3646. mg_set_close_on_exec(sock);
  3647. nc->sock = sock;
  3648. DBG(("%p %d", nc, sock));
  3649. }
  3650. void mg_socket_if_init(struct mg_iface *iface) {
  3651. (void) iface;
  3652. DBG(("%p using select()", iface->mgr));
  3653. #if MG_ENABLE_BROADCAST
  3654. mg_socketpair(iface->mgr->ctl, SOCK_DGRAM);
  3655. #endif
  3656. }
  3657. void mg_socket_if_free(struct mg_iface *iface) {
  3658. (void) iface;
  3659. }
  3660. void mg_socket_if_add_conn(struct mg_connection *nc) {
  3661. (void) nc;
  3662. }
  3663. void mg_socket_if_remove_conn(struct mg_connection *nc) {
  3664. (void) nc;
  3665. }
  3666. void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
  3667. if (sock != INVALID_SOCKET
  3668. #ifdef __unix__
  3669. && sock < (sock_t) FD_SETSIZE
  3670. #endif
  3671. ) {
  3672. FD_SET(sock, set);
  3673. if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
  3674. *max_fd = sock;
  3675. }
  3676. }
  3677. }
  3678. time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) {
  3679. struct mg_mgr *mgr = iface->mgr;
  3680. double now = mg_time();
  3681. double min_timer;
  3682. struct mg_connection *nc, *tmp;
  3683. struct timeval tv;
  3684. fd_set read_set, write_set, err_set;
  3685. sock_t max_fd = INVALID_SOCKET;
  3686. int num_fds, num_ev, num_timers = 0;
  3687. #ifdef __unix__
  3688. int try_dup = 1;
  3689. #endif
  3690. FD_ZERO(&read_set);
  3691. FD_ZERO(&write_set);
  3692. FD_ZERO(&err_set);
  3693. #if MG_ENABLE_BROADCAST
  3694. mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
  3695. #endif
  3696. /*
  3697. * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
  3698. * e.g. timer-only "connections".
  3699. */
  3700. min_timer = 0;
  3701. for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
  3702. tmp = nc->next;
  3703. if (nc->sock != INVALID_SOCKET) {
  3704. num_fds++;
  3705. #ifdef __unix__
  3706. /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */
  3707. if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) {
  3708. int new_sock = dup(nc->sock);
  3709. if (new_sock >= 0) {
  3710. if (new_sock < (sock_t) FD_SETSIZE) {
  3711. closesocket(nc->sock);
  3712. DBG(("new sock %d -> %d", nc->sock, new_sock));
  3713. nc->sock = new_sock;
  3714. } else {
  3715. closesocket(new_sock);
  3716. DBG(("new sock is still larger than FD_SETSIZE, disregard"));
  3717. try_dup = 0;
  3718. }
  3719. } else {
  3720. try_dup = 0;
  3721. }
  3722. }
  3723. #endif
  3724. if (nc->recv_mbuf.len < nc->recv_mbuf_limit &&
  3725. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
  3726. mg_add_to_set(nc->sock, &read_set, &max_fd);
  3727. }
  3728. if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
  3729. (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
  3730. mg_add_to_set(nc->sock, &write_set, &max_fd);
  3731. mg_add_to_set(nc->sock, &err_set, &max_fd);
  3732. }
  3733. }
  3734. if (nc->ev_timer_time > 0) {
  3735. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  3736. min_timer = nc->ev_timer_time;
  3737. }
  3738. num_timers++;
  3739. }
  3740. }
  3741. /*
  3742. * If there is a timer to be fired earlier than the requested timeout,
  3743. * adjust the timeout.
  3744. */
  3745. if (num_timers > 0) {
  3746. double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
  3747. if (timer_timeout_ms < timeout_ms) {
  3748. timeout_ms = (int) timer_timeout_ms;
  3749. }
  3750. }
  3751. if (timeout_ms < 0) timeout_ms = 0;
  3752. tv.tv_sec = timeout_ms / 1000;
  3753. tv.tv_usec = (timeout_ms % 1000) * 1000;
  3754. num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
  3755. now = mg_time();
  3756. #if 0
  3757. DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
  3758. timeout_ms));
  3759. #endif
  3760. #if MG_ENABLE_BROADCAST
  3761. if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
  3762. FD_ISSET(mgr->ctl[1], &read_set)) {
  3763. mg_mgr_handle_ctl_sock(mgr);
  3764. }
  3765. #endif
  3766. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  3767. int fd_flags = 0;
  3768. if (nc->sock != INVALID_SOCKET) {
  3769. if (num_ev > 0) {
  3770. fd_flags = (FD_ISSET(nc->sock, &read_set) &&
  3771. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
  3772. ? _MG_F_FD_CAN_READ
  3773. : 0) |
  3774. (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
  3775. (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
  3776. }
  3777. #if MG_LWIP
  3778. /* With LWIP socket emulation layer, we don't get write events for UDP */
  3779. if ((nc->flags & MG_F_UDP) && nc->listener == NULL) {
  3780. fd_flags |= _MG_F_FD_CAN_WRITE;
  3781. }
  3782. #endif
  3783. }
  3784. tmp = nc->next;
  3785. mg_mgr_handle_conn(nc, fd_flags, now);
  3786. }
  3787. return (time_t) now;
  3788. }
  3789. #if MG_ENABLE_BROADCAST
  3790. MG_INTERNAL void mg_socketpair_close(sock_t *sock) {
  3791. while (1) {
  3792. if (closesocket(*sock) == -1 && errno == EINTR) continue;
  3793. break;
  3794. }
  3795. *sock = INVALID_SOCKET;
  3796. }
  3797. MG_INTERNAL sock_t
  3798. mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) {
  3799. sock_t rc;
  3800. while (1) {
  3801. if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET &&
  3802. errno == EINTR)
  3803. continue;
  3804. break;
  3805. }
  3806. return rc;
  3807. }
  3808. int mg_socketpair(sock_t sp[2], int sock_type) {
  3809. union socket_address sa, sa2;
  3810. sock_t sock;
  3811. socklen_t len = sizeof(sa.sin);
  3812. int ret = 0;
  3813. sock = sp[0] = sp[1] = INVALID_SOCKET;
  3814. (void) memset(&sa, 0, sizeof(sa));
  3815. sa.sin.sin_family = AF_INET;
  3816. sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
  3817. sa2 = sa;
  3818. if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
  3819. } else if (bind(sock, &sa.sa, len) != 0) {
  3820. } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
  3821. } else if (getsockname(sock, &sa.sa, &len) != 0) {
  3822. } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
  3823. } else if (sock_type == SOCK_STREAM && connect(sp[0], &sa.sa, len) != 0) {
  3824. } else if (sock_type == SOCK_DGRAM &&
  3825. (bind(sp[0], &sa2.sa, len) != 0 ||
  3826. getsockname(sp[0], &sa2.sa, &len) != 0 ||
  3827. connect(sp[0], &sa.sa, len) != 0 ||
  3828. connect(sock, &sa2.sa, len) != 0)) {
  3829. } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept(
  3830. sock, &sa, len))) ==
  3831. INVALID_SOCKET) {
  3832. } else {
  3833. mg_set_close_on_exec(sp[0]);
  3834. mg_set_close_on_exec(sp[1]);
  3835. if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock);
  3836. ret = 1;
  3837. }
  3838. if (!ret) {
  3839. if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]);
  3840. if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]);
  3841. if (sock != INVALID_SOCKET) mg_socketpair_close(&sock);
  3842. }
  3843. return ret;
  3844. }
  3845. #endif /* MG_ENABLE_BROADCAST */
  3846. static void mg_sock_get_addr(sock_t sock, int remote,
  3847. union socket_address *sa) {
  3848. socklen_t slen = sizeof(*sa);
  3849. memset(sa, 0, slen);
  3850. if (remote) {
  3851. getpeername(sock, &sa->sa, &slen);
  3852. } else {
  3853. getsockname(sock, &sa->sa, &slen);
  3854. }
  3855. }
  3856. void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
  3857. union socket_address sa;
  3858. mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
  3859. mg_sock_addr_to_str(&sa, buf, len, flags);
  3860. }
  3861. void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote,
  3862. union socket_address *sa) {
  3863. if ((nc->flags & MG_F_UDP) && remote) {
  3864. memcpy(sa, &nc->sa, sizeof(*sa));
  3865. return;
  3866. }
  3867. mg_sock_get_addr(nc->sock, remote, sa);
  3868. }
  3869. /* clang-format off */
  3870. #define MG_SOCKET_IFACE_VTABLE \
  3871. { \
  3872. mg_socket_if_init, \
  3873. mg_socket_if_free, \
  3874. mg_socket_if_add_conn, \
  3875. mg_socket_if_remove_conn, \
  3876. mg_socket_if_poll, \
  3877. mg_socket_if_listen_tcp, \
  3878. mg_socket_if_listen_udp, \
  3879. mg_socket_if_connect_tcp, \
  3880. mg_socket_if_connect_udp, \
  3881. mg_socket_if_tcp_send, \
  3882. mg_socket_if_udp_send, \
  3883. mg_socket_if_tcp_recv, \
  3884. mg_socket_if_udp_recv, \
  3885. mg_socket_if_create_conn, \
  3886. mg_socket_if_destroy_conn, \
  3887. mg_socket_if_sock_set, \
  3888. mg_socket_if_get_conn_addr, \
  3889. }
  3890. /* clang-format on */
  3891. const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE;
  3892. #if MG_NET_IF == MG_NET_IF_SOCKET
  3893. const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE;
  3894. #endif
  3895. #endif /* MG_ENABLE_NET_IF_SOCKET */
  3896. #ifdef MG_MODULE_LINES
  3897. #line 1 "mongoose/src/mg_net_if_socks.c"
  3898. #endif
  3899. /*
  3900. * Copyright (c) 2014-2016 Cesanta Software Limited
  3901. * All rights reserved
  3902. */
  3903. #if MG_ENABLE_SOCKS
  3904. struct socksdata {
  3905. char *proxy_addr; /* HOST:PORT of the socks5 proxy server */
  3906. struct mg_connection *s; /* Respective connection to the server */
  3907. struct mg_connection *c; /* Connection to the client */
  3908. };
  3909. static void socks_if_disband(struct socksdata *d) {
  3910. LOG(LL_DEBUG, ("disbanding proxy %p %p", d->c, d->s));
  3911. if (d->c) {
  3912. d->c->flags |= MG_F_SEND_AND_CLOSE;
  3913. d->c->user_data = NULL;
  3914. d->c = NULL;
  3915. }
  3916. if (d->s) {
  3917. d->s->flags |= MG_F_SEND_AND_CLOSE;
  3918. d->s->user_data = NULL;
  3919. d->s = NULL;
  3920. }
  3921. }
  3922. static void socks_if_relay(struct mg_connection *s) {
  3923. struct socksdata *d = (struct socksdata *) s->user_data;
  3924. if (d == NULL || d->c == NULL || !(s->flags & MG_SOCKS_CONNECT_DONE) ||
  3925. d->s == NULL) {
  3926. return;
  3927. }
  3928. if (s->recv_mbuf.len > 0) mg_if_can_recv_cb(d->c);
  3929. if (d->c->send_mbuf.len > 0 && s->send_mbuf.len == 0) mg_if_can_send_cb(d->c);
  3930. }
  3931. static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) {
  3932. struct socksdata *d = (struct socksdata *) c->user_data;
  3933. if (d == NULL) return;
  3934. if (ev == MG_EV_CONNECT) {
  3935. int res = *(int *) ev_data;
  3936. if (res == 0) {
  3937. /* Send handshake to the proxy server */
  3938. unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH};
  3939. mg_send(d->s, buf, sizeof(buf));
  3940. LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr));
  3941. } else {
  3942. LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res));
  3943. d->c->flags |= MG_F_CLOSE_IMMEDIATELY;
  3944. }
  3945. } else if (ev == MG_EV_CLOSE) {
  3946. socks_if_disband(d);
  3947. } else if (ev == MG_EV_RECV) {
  3948. /* Handle handshake reply */
  3949. if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) {
  3950. /* TODO(lsm): process IPv6 too */
  3951. unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0,
  3952. MG_SOCKS_ADDR_IPV4};
  3953. if (c->recv_mbuf.len < 2) return;
  3954. if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) {
  3955. LOG(LL_ERROR, ("Server kicked us out"));
  3956. socks_if_disband(d);
  3957. return;
  3958. }
  3959. mbuf_remove(&c->recv_mbuf, 2);
  3960. c->flags |= MG_SOCKS_HANDSHAKE_DONE;
  3961. /* Send connect request */
  3962. memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4);
  3963. memcpy(buf + 8, &d->c->sa.sin.sin_port, 2);
  3964. mg_send(c, buf, sizeof(buf));
  3965. LOG(LL_DEBUG, ("%p Sent connect request", c));
  3966. }
  3967. /* Process connect request */
  3968. if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) &&
  3969. !(c->flags & MG_SOCKS_CONNECT_DONE)) {
  3970. if (c->recv_mbuf.len < 10) return;
  3971. if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) {
  3972. LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1]));
  3973. socks_if_disband(d);
  3974. return;
  3975. }
  3976. mbuf_remove(&c->recv_mbuf, 10);
  3977. c->flags |= MG_SOCKS_CONNECT_DONE;
  3978. LOG(LL_DEBUG, ("%p Connect done %p", c, d->c));
  3979. mg_if_connect_cb(d->c, 0);
  3980. }
  3981. socks_if_relay(c);
  3982. } else if (ev == MG_EV_SEND || ev == MG_EV_POLL) {
  3983. socks_if_relay(c);
  3984. }
  3985. }
  3986. static void mg_socks_if_connect_tcp(struct mg_connection *c,
  3987. const union socket_address *sa) {
  3988. struct socksdata *d = (struct socksdata *) c->iface->data;
  3989. d->c = c;
  3990. d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler);
  3991. d->s->user_data = d;
  3992. LOG(LL_DEBUG, ("%p %s %p %p", c, d->proxy_addr, d, d->s));
  3993. (void) sa;
  3994. }
  3995. static void mg_socks_if_connect_udp(struct mg_connection *c) {
  3996. (void) c;
  3997. }
  3998. static int mg_socks_if_listen_tcp(struct mg_connection *c,
  3999. union socket_address *sa) {
  4000. (void) c;
  4001. (void) sa;
  4002. return 0;
  4003. }
  4004. static int mg_socks_if_listen_udp(struct mg_connection *c,
  4005. union socket_address *sa) {
  4006. (void) c;
  4007. (void) sa;
  4008. return -1;
  4009. }
  4010. static int mg_socks_if_tcp_send(struct mg_connection *c, const void *buf,
  4011. size_t len) {
  4012. int res;
  4013. struct socksdata *d = (struct socksdata *) c->iface->data;
  4014. if (d->s == NULL) return -1;
  4015. res = (int) mbuf_append(&d->s->send_mbuf, buf, len);
  4016. DBG(("%p -> %d -> %p", c, res, d->s));
  4017. return res;
  4018. }
  4019. static int mg_socks_if_udp_send(struct mg_connection *c, const void *buf,
  4020. size_t len) {
  4021. (void) c;
  4022. (void) buf;
  4023. (void) len;
  4024. return -1;
  4025. }
  4026. int mg_socks_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) {
  4027. struct socksdata *d = (struct socksdata *) c->iface->data;
  4028. if (d->s == NULL) return -1;
  4029. if (len > d->s->recv_mbuf.len) len = d->s->recv_mbuf.len;
  4030. if (len > 0) {
  4031. memcpy(buf, d->s->recv_mbuf.buf, len);
  4032. mbuf_remove(&d->s->recv_mbuf, len);
  4033. }
  4034. DBG(("%p <- %d <- %p", c, (int) len, d->s));
  4035. return len;
  4036. }
  4037. int mg_socks_if_udp_recv(struct mg_connection *c, void *buf, size_t len,
  4038. union socket_address *sa, size_t *sa_len) {
  4039. (void) c;
  4040. (void) buf;
  4041. (void) len;
  4042. (void) sa;
  4043. (void) sa_len;
  4044. return -1;
  4045. }
  4046. static int mg_socks_if_create_conn(struct mg_connection *c) {
  4047. (void) c;
  4048. return 1;
  4049. }
  4050. static void mg_socks_if_destroy_conn(struct mg_connection *c) {
  4051. c->iface->vtable->free(c->iface);
  4052. MG_FREE(c->iface);
  4053. c->iface = NULL;
  4054. LOG(LL_DEBUG, ("%p", c));
  4055. }
  4056. static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) {
  4057. (void) c;
  4058. (void) sock;
  4059. }
  4060. static void mg_socks_if_init(struct mg_iface *iface) {
  4061. (void) iface;
  4062. }
  4063. static void mg_socks_if_free(struct mg_iface *iface) {
  4064. struct socksdata *d = (struct socksdata *) iface->data;
  4065. LOG(LL_DEBUG, ("%p", iface));
  4066. if (d != NULL) {
  4067. socks_if_disband(d);
  4068. MG_FREE(d->proxy_addr);
  4069. MG_FREE(d);
  4070. iface->data = NULL;
  4071. }
  4072. }
  4073. static void mg_socks_if_add_conn(struct mg_connection *c) {
  4074. c->sock = INVALID_SOCKET;
  4075. }
  4076. static void mg_socks_if_remove_conn(struct mg_connection *c) {
  4077. (void) c;
  4078. }
  4079. static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) {
  4080. LOG(LL_DEBUG, ("%p", iface));
  4081. (void) iface;
  4082. (void) timeout_ms;
  4083. return (time_t) cs_time();
  4084. }
  4085. static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote,
  4086. union socket_address *sa) {
  4087. LOG(LL_DEBUG, ("%p", c));
  4088. (void) c;
  4089. (void) remote;
  4090. (void) sa;
  4091. }
  4092. const struct mg_iface_vtable mg_socks_iface_vtable = {
  4093. mg_socks_if_init, mg_socks_if_free,
  4094. mg_socks_if_add_conn, mg_socks_if_remove_conn,
  4095. mg_socks_if_poll, mg_socks_if_listen_tcp,
  4096. mg_socks_if_listen_udp, mg_socks_if_connect_tcp,
  4097. mg_socks_if_connect_udp, mg_socks_if_tcp_send,
  4098. mg_socks_if_udp_send, mg_socks_if_tcp_recv,
  4099. mg_socks_if_udp_recv, mg_socks_if_create_conn,
  4100. mg_socks_if_destroy_conn, mg_socks_if_sock_set,
  4101. mg_socks_if_get_conn_addr,
  4102. };
  4103. struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) {
  4104. struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr);
  4105. iface->data = MG_CALLOC(1, sizeof(struct socksdata));
  4106. ((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr);
  4107. return iface;
  4108. }
  4109. #endif
  4110. #ifdef MG_MODULE_LINES
  4111. #line 1 "mongoose/src/mg_ssl_if_openssl.c"
  4112. #endif
  4113. /*
  4114. * Copyright (c) 2014-2016 Cesanta Software Limited
  4115. * All rights reserved
  4116. */
  4117. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
  4118. #ifdef __APPLE__
  4119. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  4120. #endif
  4121. #include <openssl/ssl.h>
  4122. #ifndef KR_VERSION
  4123. #include <openssl/tls1.h>
  4124. #endif
  4125. struct mg_ssl_if_ctx {
  4126. SSL *ssl;
  4127. SSL_CTX *ssl_ctx;
  4128. struct mbuf psk;
  4129. size_t identity_len;
  4130. };
  4131. void mg_ssl_if_init() {
  4132. SSL_library_init();
  4133. }
  4134. enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
  4135. struct mg_connection *lc) {
  4136. struct mg_ssl_if_ctx *ctx =
  4137. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  4138. struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
  4139. nc->ssl_if_data = ctx;
  4140. if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
  4141. ctx->ssl_ctx = lc_ctx->ssl_ctx;
  4142. if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
  4143. return MG_SSL_ERROR;
  4144. }
  4145. return MG_SSL_OK;
  4146. }
  4147. static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
  4148. const char *key, const char **err_msg);
  4149. static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert);
  4150. static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl);
  4151. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  4152. const char *identity,
  4153. const char *key_str);
  4154. enum mg_ssl_if_result mg_ssl_if_conn_init(
  4155. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  4156. const char **err_msg) {
  4157. struct mg_ssl_if_ctx *ctx =
  4158. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  4159. DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
  4160. (params->key ? params->key : ""),
  4161. (params->ca_cert ? params->ca_cert : "")));
  4162. if (ctx == NULL) {
  4163. MG_SET_PTRPTR(err_msg, "Out of memory");
  4164. return MG_SSL_ERROR;
  4165. }
  4166. nc->ssl_if_data = ctx;
  4167. if (nc->flags & MG_F_LISTENING) {
  4168. ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  4169. } else {
  4170. ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  4171. }
  4172. if (ctx->ssl_ctx == NULL) {
  4173. MG_SET_PTRPTR(err_msg, "Failed to create SSL context");
  4174. return MG_SSL_ERROR;
  4175. }
  4176. #ifndef KR_VERSION
  4177. /* Disable deprecated protocols. */
  4178. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
  4179. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3);
  4180. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1);
  4181. #ifdef MG_SSL_OPENSSL_NO_COMPRESSION
  4182. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  4183. #endif
  4184. #ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE
  4185. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  4186. #endif
  4187. #else
  4188. /* Krypton only supports TLSv1.2 anyway. */
  4189. #endif
  4190. if (params->cert != NULL &&
  4191. mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
  4192. MG_SSL_OK) {
  4193. return MG_SSL_ERROR;
  4194. }
  4195. if (params->ca_cert != NULL &&
  4196. mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
  4197. MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
  4198. return MG_SSL_ERROR;
  4199. }
  4200. if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
  4201. MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
  4202. return MG_SSL_ERROR;
  4203. }
  4204. mbuf_init(&ctx->psk, 0);
  4205. if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
  4206. MG_SSL_OK) {
  4207. MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
  4208. return MG_SSL_ERROR;
  4209. }
  4210. if (!(nc->flags & MG_F_LISTENING) &&
  4211. (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
  4212. MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
  4213. return MG_SSL_ERROR;
  4214. }
  4215. if (params->server_name != NULL) {
  4216. #ifdef KR_VERSION
  4217. SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
  4218. #else
  4219. SSL_set_tlsext_host_name(ctx->ssl, params->server_name);
  4220. #endif
  4221. }
  4222. nc->flags |= MG_F_SSL;
  4223. return MG_SSL_OK;
  4224. }
  4225. static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc,
  4226. int res) {
  4227. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4228. int err = SSL_get_error(ctx->ssl, res);
  4229. if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ;
  4230. if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE;
  4231. DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err));
  4232. nc->err = err;
  4233. return MG_SSL_ERROR;
  4234. }
  4235. enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
  4236. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4237. int server_side = (nc->listener != NULL);
  4238. int res;
  4239. /* If descriptor is not yet set, do it now. */
  4240. if (SSL_get_fd(ctx->ssl) < 0) {
  4241. if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR;
  4242. }
  4243. res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
  4244. if (res != 1) return mg_ssl_if_ssl_err(nc, res);
  4245. return MG_SSL_OK;
  4246. }
  4247. int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
  4248. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4249. int n = SSL_read(ctx->ssl, buf, buf_size);
  4250. DBG(("%p %d -> %d", nc, (int) buf_size, n));
  4251. if (n < 0) return mg_ssl_if_ssl_err(nc, n);
  4252. if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4253. return n;
  4254. }
  4255. int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
  4256. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4257. int n = SSL_write(ctx->ssl, data, len);
  4258. DBG(("%p %d -> %d", nc, (int) len, n));
  4259. if (n <= 0) return mg_ssl_if_ssl_err(nc, n);
  4260. return n;
  4261. }
  4262. void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
  4263. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4264. if (ctx == NULL) return;
  4265. SSL_shutdown(ctx->ssl);
  4266. }
  4267. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  4268. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4269. if (ctx == NULL) return;
  4270. nc->ssl_if_data = NULL;
  4271. if (ctx->ssl != NULL) SSL_free(ctx->ssl);
  4272. if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
  4273. mbuf_free(&ctx->psk);
  4274. memset(ctx, 0, sizeof(*ctx));
  4275. MG_FREE(ctx);
  4276. }
  4277. /*
  4278. * Cipher suite options used for TLS negotiation.
  4279. * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
  4280. */
  4281. static const char mg_s_cipher_list[] =
  4282. #if defined(MG_SSL_CRYPTO_MODERN)
  4283. "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
  4284. "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
  4285. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  4286. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  4287. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  4288. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  4289. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  4290. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
  4291. "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
  4292. #elif defined(MG_SSL_CRYPTO_OLD)
  4293. "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
  4294. "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
  4295. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  4296. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  4297. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  4298. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  4299. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  4300. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
  4301. "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
  4302. "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
  4303. "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
  4304. "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
  4305. #else /* Default - intermediate. */
  4306. "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
  4307. "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
  4308. "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
  4309. "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
  4310. "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
  4311. "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
  4312. "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
  4313. "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
  4314. "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
  4315. "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
  4316. "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
  4317. #endif
  4318. ;
  4319. /*
  4320. * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
  4321. * Will be used if none are provided by the user in the certificate file.
  4322. */
  4323. #if !MG_DISABLE_PFS && !defined(KR_VERSION)
  4324. static const char mg_s_default_dh_params[] =
  4325. "\
  4326. -----BEGIN DH PARAMETERS-----\n\
  4327. MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
  4328. Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
  4329. +E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
  4330. ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
  4331. wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
  4332. 9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
  4333. -----END DH PARAMETERS-----\n";
  4334. #endif
  4335. static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
  4336. if (cert == NULL || strcmp(cert, "*") == 0) {
  4337. return MG_SSL_OK;
  4338. }
  4339. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
  4340. return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
  4341. : MG_SSL_ERROR;
  4342. }
  4343. static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
  4344. const char *key,
  4345. const char **err_msg) {
  4346. if (key == NULL) key = cert;
  4347. if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
  4348. return MG_SSL_OK;
  4349. } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
  4350. MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
  4351. return MG_SSL_ERROR;
  4352. } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) {
  4353. MG_SET_PTRPTR(err_msg, "Invalid SSL key");
  4354. return MG_SSL_ERROR;
  4355. } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
  4356. MG_SET_PTRPTR(err_msg, "Invalid CA bundle");
  4357. return MG_SSL_ERROR;
  4358. } else {
  4359. SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  4360. #if !MG_DISABLE_PFS && !defined(KR_VERSION)
  4361. BIO *bio = NULL;
  4362. DH *dh = NULL;
  4363. /* Try to read DH parameters from the cert/key file. */
  4364. bio = BIO_new_file(cert, "r");
  4365. if (bio != NULL) {
  4366. dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  4367. BIO_free(bio);
  4368. }
  4369. /*
  4370. * If there are no DH params in the file, fall back to hard-coded ones.
  4371. * Not ideal, but better than nothing.
  4372. */
  4373. if (dh == NULL) {
  4374. bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
  4375. dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  4376. BIO_free(bio);
  4377. }
  4378. if (dh != NULL) {
  4379. SSL_CTX_set_tmp_dh(ctx, dh);
  4380. SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
  4381. DH_free(dh);
  4382. }
  4383. #if OPENSSL_VERSION_NUMBER > 0x10002000L
  4384. SSL_CTX_set_ecdh_auto(ctx, 1);
  4385. #endif
  4386. #endif
  4387. }
  4388. return MG_SSL_OK;
  4389. }
  4390. static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) {
  4391. return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
  4392. ? MG_SSL_OK
  4393. : MG_SSL_ERROR);
  4394. }
  4395. #if !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER)
  4396. static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint,
  4397. char *identity,
  4398. unsigned int max_identity_len,
  4399. unsigned char *psk,
  4400. unsigned int max_psk_len) {
  4401. struct mg_ssl_if_ctx *ctx =
  4402. (struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl));
  4403. size_t key_len = ctx->psk.len - ctx->identity_len - 1;
  4404. DBG(("hint: '%s'", (hint ? hint : "")));
  4405. if (ctx->identity_len + 1 > max_identity_len) {
  4406. DBG(("identity too long"));
  4407. return 0;
  4408. }
  4409. if (key_len > max_psk_len) {
  4410. DBG(("key too long"));
  4411. return 0;
  4412. }
  4413. memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
  4414. memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
  4415. (void) ssl;
  4416. return key_len;
  4417. }
  4418. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  4419. const char *identity,
  4420. const char *key_str) {
  4421. unsigned char key[32];
  4422. size_t key_len;
  4423. size_t i = 0;
  4424. if (identity == NULL && key_str == NULL) return MG_SSL_OK;
  4425. if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
  4426. key_len = strlen(key_str);
  4427. if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
  4428. memset(key, 0, sizeof(key));
  4429. key_len = 0;
  4430. for (i = 0; key_str[i] != '\0'; i++) {
  4431. unsigned char c;
  4432. char hc = tolower((int) key_str[i]);
  4433. if (hc >= '0' && hc <= '9') {
  4434. c = hc - '0';
  4435. } else if (hc >= 'a' && hc <= 'f') {
  4436. c = hc - 'a' + 0xa;
  4437. } else {
  4438. return MG_SSL_ERROR;
  4439. }
  4440. key_len = i / 2;
  4441. key[key_len] <<= 4;
  4442. key[key_len] |= c;
  4443. }
  4444. key_len++;
  4445. DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
  4446. ctx->identity_len = strlen(identity);
  4447. mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
  4448. mbuf_append(&ctx->psk, key, key_len);
  4449. SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
  4450. SSL_CTX_set_app_data(ctx->ssl_ctx, ctx);
  4451. return MG_SSL_OK;
  4452. }
  4453. #else
  4454. static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
  4455. const char *identity,
  4456. const char *key_str) {
  4457. (void) ctx;
  4458. (void) identity;
  4459. (void) key_str;
  4460. /* Krypton / LibreSSL does not support PSK. */
  4461. return MG_SSL_ERROR;
  4462. }
  4463. #endif /* !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER) */
  4464. const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
  4465. const char *ca_cert) {
  4466. const char *err_msg = NULL;
  4467. struct mg_ssl_if_conn_params params;
  4468. memset(&params, 0, sizeof(params));
  4469. params.cert = cert;
  4470. params.ca_cert = ca_cert;
  4471. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  4472. return err_msg;
  4473. }
  4474. return NULL;
  4475. }
  4476. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */
  4477. #ifdef MG_MODULE_LINES
  4478. #line 1 "mongoose/src/mg_ssl_if_mbedtls.c"
  4479. #endif
  4480. /*
  4481. * Copyright (c) 2014-2016 Cesanta Software Limited
  4482. * All rights reserved
  4483. */
  4484. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
  4485. #include <mbedtls/debug.h>
  4486. #include <mbedtls/ecp.h>
  4487. #include <mbedtls/net.h>
  4488. #include <mbedtls/platform.h>
  4489. #include <mbedtls/ssl.h>
  4490. #include <mbedtls/ssl_internal.h>
  4491. #include <mbedtls/x509_crt.h>
  4492. #include <mbedtls/version.h>
  4493. static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line,
  4494. const char *str) {
  4495. enum cs_log_level cs_level;
  4496. switch (level) {
  4497. case 1:
  4498. cs_level = LL_ERROR;
  4499. break;
  4500. case 2:
  4501. cs_level = LL_INFO;
  4502. break;
  4503. case 3:
  4504. cs_level = LL_DEBUG;
  4505. break;
  4506. default:
  4507. cs_level = LL_VERBOSE_DEBUG;
  4508. }
  4509. /* mbedTLS passes strings with \n at the end, strip it. */
  4510. LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str));
  4511. (void) ctx;
  4512. (void) str;
  4513. (void) file;
  4514. (void) line;
  4515. (void) cs_level;
  4516. }
  4517. struct mg_ssl_if_ctx {
  4518. mbedtls_ssl_config *conf;
  4519. mbedtls_ssl_context *ssl;
  4520. mbedtls_x509_crt *cert;
  4521. mbedtls_pk_context *key;
  4522. mbedtls_x509_crt *ca_cert;
  4523. struct mbuf cipher_suites;
  4524. size_t saved_len;
  4525. };
  4526. /* Must be provided by the platform. ctx is struct mg_connection. */
  4527. extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len);
  4528. void mg_ssl_if_init() {
  4529. LOG(LL_INFO, ("%s", MBEDTLS_VERSION_STRING_FULL));
  4530. }
  4531. enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
  4532. struct mg_connection *lc) {
  4533. struct mg_ssl_if_ctx *ctx =
  4534. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  4535. struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
  4536. nc->ssl_if_data = ctx;
  4537. if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
  4538. ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
  4539. if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
  4540. return MG_SSL_ERROR;
  4541. }
  4542. return MG_SSL_OK;
  4543. }
  4544. static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
  4545. const char *cert, const char *key,
  4546. const char **err_msg);
  4547. static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
  4548. const char *cert);
  4549. static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
  4550. const char *ciphers);
  4551. #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
  4552. static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
  4553. const char *identity,
  4554. const char *key);
  4555. #endif
  4556. enum mg_ssl_if_result mg_ssl_if_conn_init(
  4557. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  4558. const char **err_msg) {
  4559. struct mg_ssl_if_ctx *ctx =
  4560. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  4561. DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
  4562. (params->key ? params->key : ""),
  4563. (params->ca_cert ? params->ca_cert : "")));
  4564. if (ctx == NULL) {
  4565. MG_SET_PTRPTR(err_msg, "Out of memory");
  4566. return MG_SSL_ERROR;
  4567. }
  4568. nc->ssl_if_data = ctx;
  4569. ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf));
  4570. mbuf_init(&ctx->cipher_suites, 0);
  4571. mbedtls_ssl_config_init(ctx->conf);
  4572. mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
  4573. if (mbedtls_ssl_config_defaults(
  4574. ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER
  4575. : MBEDTLS_SSL_IS_CLIENT),
  4576. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
  4577. MG_SET_PTRPTR(err_msg, "Failed to init SSL config");
  4578. return MG_SSL_ERROR;
  4579. }
  4580. /* TLS 1.2 and up */
  4581. mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  4582. MBEDTLS_SSL_MINOR_VERSION_3);
  4583. mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
  4584. if (params->cert != NULL &&
  4585. mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
  4586. return MG_SSL_ERROR;
  4587. }
  4588. if (params->ca_cert != NULL &&
  4589. mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
  4590. MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
  4591. return MG_SSL_ERROR;
  4592. }
  4593. if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
  4594. MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
  4595. return MG_SSL_ERROR;
  4596. }
  4597. #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
  4598. if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
  4599. MG_SSL_OK) {
  4600. MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
  4601. return MG_SSL_ERROR;
  4602. }
  4603. #endif
  4604. if (!(nc->flags & MG_F_LISTENING)) {
  4605. ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
  4606. mbedtls_ssl_init(ctx->ssl);
  4607. if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
  4608. MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
  4609. return MG_SSL_ERROR;
  4610. }
  4611. if (params->server_name != NULL &&
  4612. mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
  4613. return MG_SSL_ERROR;
  4614. }
  4615. }
  4616. #ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
  4617. if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
  4618. #if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
  4619. MBEDTLS_SSL_MAX_FRAG_LEN_512
  4620. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
  4621. MBEDTLS_SSL_MAX_FRAG_LEN_1024
  4622. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
  4623. MBEDTLS_SSL_MAX_FRAG_LEN_2048
  4624. #elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
  4625. MBEDTLS_SSL_MAX_FRAG_LEN_4096
  4626. #else
  4627. #error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
  4628. #endif
  4629. ) != 0) {
  4630. return MG_SSL_ERROR;
  4631. }
  4632. #endif
  4633. nc->flags |= MG_F_SSL;
  4634. return MG_SSL_OK;
  4635. }
  4636. static int mg_ssl_if_mbed_send(void *ctx, const unsigned char *buf,
  4637. size_t len) {
  4638. struct mg_connection *nc = (struct mg_connection *) ctx;
  4639. int n = nc->iface->vtable->tcp_send(nc, buf, len);
  4640. if (n > 0) return n;
  4641. if (n == 0) return MBEDTLS_ERR_SSL_WANT_WRITE;
  4642. return MBEDTLS_ERR_NET_SEND_FAILED;
  4643. }
  4644. static int mg_ssl_if_mbed_recv(void *ctx, unsigned char *buf, size_t len) {
  4645. struct mg_connection *nc = (struct mg_connection *) ctx;
  4646. int n = nc->iface->vtable->tcp_recv(nc, buf, len);
  4647. if (n > 0) return n;
  4648. if (n == 0) return MBEDTLS_ERR_SSL_WANT_READ;
  4649. return MBEDTLS_ERR_NET_RECV_FAILED;
  4650. }
  4651. static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
  4652. int ret) {
  4653. enum mg_ssl_if_result res = MG_SSL_OK;
  4654. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  4655. res = MG_SSL_WANT_READ;
  4656. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  4657. res = MG_SSL_WANT_WRITE;
  4658. } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  4659. LOG(LL_DEBUG, ("%p TLS connection closed by peer", nc));
  4660. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4661. res = MG_SSL_OK;
  4662. } else {
  4663. LOG(LL_ERROR, ("%p mbedTLS error: -0x%04x", nc, -ret));
  4664. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4665. res = MG_SSL_ERROR;
  4666. }
  4667. nc->err = ret;
  4668. return res;
  4669. }
  4670. static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) {
  4671. if (ctx->cert != NULL) {
  4672. mbedtls_x509_crt_free(ctx->cert);
  4673. MG_FREE(ctx->cert);
  4674. ctx->cert = NULL;
  4675. mbedtls_pk_free(ctx->key);
  4676. MG_FREE(ctx->key);
  4677. ctx->key = NULL;
  4678. }
  4679. if (ctx->ca_cert != NULL) {
  4680. mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
  4681. #ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
  4682. if (ctx->conf->ca_chain_file != NULL) {
  4683. MG_FREE((void *) ctx->conf->ca_chain_file);
  4684. ctx->conf->ca_chain_file = NULL;
  4685. }
  4686. #endif
  4687. mbedtls_x509_crt_free(ctx->ca_cert);
  4688. MG_FREE(ctx->ca_cert);
  4689. ctx->ca_cert = NULL;
  4690. }
  4691. }
  4692. enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
  4693. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4694. int err;
  4695. /* If bio is not yet set, do it now. */
  4696. if (ctx->ssl->p_bio == NULL) {
  4697. mbedtls_ssl_set_bio(ctx->ssl, nc, mg_ssl_if_mbed_send, mg_ssl_if_mbed_recv,
  4698. NULL);
  4699. }
  4700. err = mbedtls_ssl_handshake(ctx->ssl);
  4701. if (err != 0) return mg_ssl_if_mbed_err(nc, err);
  4702. #ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
  4703. /*
  4704. * Free the peer certificate, we don't need it after handshake.
  4705. * Note that this effectively disables renegotiation.
  4706. */
  4707. mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
  4708. mbedtls_free(ctx->ssl->session->peer_cert);
  4709. ctx->ssl->session->peer_cert = NULL;
  4710. /* On a client connection we can also free our own and CA certs. */
  4711. if (nc->listener == NULL) {
  4712. if (ctx->conf->key_cert != NULL) {
  4713. /* Note that this assumes one key_cert entry, which matches our init. */
  4714. MG_FREE(ctx->conf->key_cert);
  4715. ctx->conf->key_cert = NULL;
  4716. }
  4717. mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
  4718. mg_ssl_if_mbed_free_certs_and_keys(ctx);
  4719. }
  4720. #endif
  4721. return MG_SSL_OK;
  4722. }
  4723. int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
  4724. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4725. int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, len);
  4726. DBG(("%p %d -> %d", nc, (int) len, n));
  4727. if (n < 0) return mg_ssl_if_mbed_err(nc, n);
  4728. if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  4729. return n;
  4730. }
  4731. int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
  4732. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4733. /* Per mbedTLS docs, if write returns WANT_READ or WANT_WRITE, the operation
  4734. * should be retried with the same data and length.
  4735. * Here we assume that the data being pushed will remain the same but the
  4736. * amount may grow between calls so we save the length that was used and
  4737. * retry. The assumption being that the data itself won't change and won't
  4738. * be removed. */
  4739. size_t l = len;
  4740. if (ctx->saved_len > 0 && ctx->saved_len < l) l = ctx->saved_len;
  4741. int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) buf, l);
  4742. DBG(("%p %d,%d,%d -> %d", nc, (int) len, (int) ctx->saved_len, (int) l, n));
  4743. if (n < 0) {
  4744. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) {
  4745. ctx->saved_len = len;
  4746. }
  4747. return mg_ssl_if_mbed_err(nc, n);
  4748. } else if (n > 0) {
  4749. ctx->saved_len = 0;
  4750. }
  4751. return n;
  4752. }
  4753. void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
  4754. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4755. if (ctx == NULL) return;
  4756. mbedtls_ssl_close_notify(ctx->ssl);
  4757. }
  4758. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  4759. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  4760. if (ctx == NULL) return;
  4761. nc->ssl_if_data = NULL;
  4762. if (ctx->ssl != NULL) {
  4763. mbedtls_ssl_free(ctx->ssl);
  4764. MG_FREE(ctx->ssl);
  4765. }
  4766. mg_ssl_if_mbed_free_certs_and_keys(ctx);
  4767. if (ctx->conf != NULL) {
  4768. mbedtls_ssl_config_free(ctx->conf);
  4769. MG_FREE(ctx->conf);
  4770. }
  4771. mbuf_free(&ctx->cipher_suites);
  4772. memset(ctx, 0, sizeof(*ctx));
  4773. MG_FREE(ctx);
  4774. }
  4775. static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
  4776. const char *ca_cert) {
  4777. if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) {
  4778. mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  4779. return MG_SSL_OK;
  4780. }
  4781. ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert));
  4782. mbedtls_x509_crt_init(ctx->ca_cert);
  4783. #ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
  4784. ca_cert = strdup(ca_cert);
  4785. mbedtls_ssl_conf_ca_chain_file(ctx->conf, ca_cert, NULL);
  4786. #else
  4787. if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
  4788. return MG_SSL_ERROR;
  4789. }
  4790. mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
  4791. #endif
  4792. mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  4793. return MG_SSL_OK;
  4794. }
  4795. static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
  4796. const char *cert, const char *key,
  4797. const char **err_msg) {
  4798. if (key == NULL) key = cert;
  4799. if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
  4800. return MG_SSL_OK;
  4801. }
  4802. ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert));
  4803. mbedtls_x509_crt_init(ctx->cert);
  4804. ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key));
  4805. mbedtls_pk_init(ctx->key);
  4806. if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
  4807. MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
  4808. return MG_SSL_ERROR;
  4809. }
  4810. if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) {
  4811. MG_SET_PTRPTR(err_msg, "Invalid SSL key");
  4812. return MG_SSL_ERROR;
  4813. }
  4814. if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
  4815. MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert");
  4816. return MG_SSL_ERROR;
  4817. }
  4818. return MG_SSL_OK;
  4819. }
  4820. static const int mg_s_cipher_list[] = {
  4821. #if CS_PLATFORM != CS_P_ESP8266
  4822. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  4823. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  4824. MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  4825. MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  4826. MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
  4827. MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
  4828. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
  4829. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
  4830. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
  4831. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
  4832. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
  4833. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
  4834. MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
  4835. MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
  4836. MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
  4837. #else
  4838. /*
  4839. * ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results
  4840. * in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true.
  4841. * Disable DHE completely because it's just hopelessly slow.
  4842. */
  4843. MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
  4844. MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
  4845. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  4846. MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  4847. MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  4848. MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  4849. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
  4850. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
  4851. MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
  4852. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
  4853. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
  4854. MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
  4855. MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
  4856. #endif /* CS_PLATFORM != CS_P_ESP8266 */
  4857. 0,
  4858. };
  4859. /*
  4860. * Ciphers can be specified as a colon-separated list of cipher suite names.
  4861. * These can be found in
  4862. * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267
  4863. * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM
  4864. */
  4865. static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
  4866. const char *ciphers) {
  4867. if (ciphers != NULL) {
  4868. int l, id;
  4869. const char *s = ciphers, *e;
  4870. char tmp[50];
  4871. while (s != NULL) {
  4872. e = strchr(s, ':');
  4873. l = (e != NULL ? (e - s) : (int) strlen(s));
  4874. strncpy(tmp, s, l);
  4875. tmp[l] = '\0';
  4876. id = mbedtls_ssl_get_ciphersuite_id(tmp);
  4877. DBG(("%s -> %04x", tmp, id));
  4878. if (id != 0) {
  4879. mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
  4880. }
  4881. s = (e != NULL ? e + 1 : NULL);
  4882. }
  4883. if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR;
  4884. id = 0;
  4885. mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
  4886. mbuf_trim(&ctx->cipher_suites);
  4887. mbedtls_ssl_conf_ciphersuites(ctx->conf,
  4888. (const int *) ctx->cipher_suites.buf);
  4889. } else {
  4890. mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
  4891. }
  4892. return MG_SSL_OK;
  4893. }
  4894. #ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
  4895. static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
  4896. const char *identity,
  4897. const char *key_str) {
  4898. unsigned char key[32];
  4899. size_t key_len;
  4900. if (identity == NULL && key_str == NULL) return MG_SSL_OK;
  4901. if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
  4902. key_len = strlen(key_str);
  4903. if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
  4904. size_t i = 0;
  4905. memset(key, 0, sizeof(key));
  4906. key_len = 0;
  4907. for (i = 0; key_str[i] != '\0'; i++) {
  4908. unsigned char c;
  4909. char hc = tolower((int) key_str[i]);
  4910. if (hc >= '0' && hc <= '9') {
  4911. c = hc - '0';
  4912. } else if (hc >= 'a' && hc <= 'f') {
  4913. c = hc - 'a' + 0xa;
  4914. } else {
  4915. return MG_SSL_ERROR;
  4916. }
  4917. key_len = i / 2;
  4918. key[key_len] <<= 4;
  4919. key[key_len] |= c;
  4920. }
  4921. key_len++;
  4922. DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
  4923. /* mbedTLS makes copies of psk and identity. */
  4924. if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len,
  4925. (const unsigned char *) identity,
  4926. strlen(identity)) != 0) {
  4927. return MG_SSL_ERROR;
  4928. }
  4929. return MG_SSL_OK;
  4930. }
  4931. #endif
  4932. const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
  4933. const char *ca_cert) {
  4934. const char *err_msg = NULL;
  4935. struct mg_ssl_if_conn_params params;
  4936. memset(&params, 0, sizeof(params));
  4937. params.cert = cert;
  4938. params.ca_cert = ca_cert;
  4939. if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
  4940. return err_msg;
  4941. }
  4942. return NULL;
  4943. }
  4944. /* Lazy RNG. Warning: it would be a bad idea to do this in production! */
  4945. #ifdef MG_SSL_MBED_DUMMY_RANDOM
  4946. int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) {
  4947. (void) ctx;
  4948. while (len--) *buf++ = rand();
  4949. return 0;
  4950. }
  4951. #endif
  4952. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */
  4953. #ifdef MG_MODULE_LINES
  4954. #line 1 "mongoose/src/mg_uri.c"
  4955. #endif
  4956. /*
  4957. * Copyright (c) 2014 Cesanta Software Limited
  4958. * All rights reserved
  4959. */
  4960. /* Amalgamated: #include "mg_internal.h" */
  4961. /* Amalgamated: #include "mg_uri.h" */
  4962. /*
  4963. * scan string until encountering one of `seps`, keeping track of component
  4964. * boundaries in `res`.
  4965. *
  4966. * `p` will point to the char after the separator or it will be `end`.
  4967. */
  4968. static void parse_uri_component(const char **p, const char *end,
  4969. const char *seps, struct mg_str *res) {
  4970. const char *q;
  4971. res->p = *p;
  4972. for (; *p < end; (*p)++) {
  4973. for (q = seps; *q != '\0'; q++) {
  4974. if (**p == *q) break;
  4975. }
  4976. if (*q != '\0') break;
  4977. }
  4978. res->len = (*p) - res->p;
  4979. if (*p < end) (*p)++;
  4980. }
  4981. int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme,
  4982. struct mg_str *user_info, struct mg_str *host,
  4983. unsigned int *port, struct mg_str *path, struct mg_str *query,
  4984. struct mg_str *fragment) {
  4985. struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
  4986. rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
  4987. unsigned int rport = 0;
  4988. enum {
  4989. P_START,
  4990. P_SCHEME_OR_PORT,
  4991. P_USER_INFO,
  4992. P_HOST,
  4993. P_PORT,
  4994. P_REST
  4995. } state = P_START;
  4996. const char *p = uri.p, *end = p + uri.len;
  4997. while (p < end) {
  4998. switch (state) {
  4999. case P_START:
  5000. /*
  5001. * expecting on of:
  5002. * - `scheme://xxxx`
  5003. * - `xxxx:port`
  5004. * - `[a:b:c]:port`
  5005. * - `xxxx/path`
  5006. */
  5007. if (*p == '[') {
  5008. state = P_HOST;
  5009. break;
  5010. }
  5011. for (; p < end; p++) {
  5012. if (*p == ':') {
  5013. state = P_SCHEME_OR_PORT;
  5014. break;
  5015. } else if (*p == '/') {
  5016. state = P_REST;
  5017. break;
  5018. }
  5019. }
  5020. if (state == P_START || state == P_REST) {
  5021. rhost.p = uri.p;
  5022. rhost.len = p - uri.p;
  5023. }
  5024. break;
  5025. case P_SCHEME_OR_PORT:
  5026. if (end - p >= 3 && strncmp(p, "://", 3) == 0) {
  5027. rscheme.p = uri.p;
  5028. rscheme.len = p - uri.p;
  5029. state = P_USER_INFO;
  5030. p += 3;
  5031. } else {
  5032. rhost.p = uri.p;
  5033. rhost.len = p - uri.p;
  5034. state = P_PORT;
  5035. }
  5036. break;
  5037. case P_USER_INFO:
  5038. ruser_info.p = p;
  5039. for (; p < end; p++) {
  5040. if (*p == '@' || *p == '[' || *p == '/') {
  5041. break;
  5042. }
  5043. }
  5044. if (p == end || *p == '/' || *p == '[') {
  5045. /* backtrack and parse as host */
  5046. p = ruser_info.p;
  5047. }
  5048. ruser_info.len = p - ruser_info.p;
  5049. state = P_HOST;
  5050. break;
  5051. case P_HOST:
  5052. if (*p == '@') p++;
  5053. rhost.p = p;
  5054. if (*p == '[') {
  5055. int found = 0;
  5056. for (; !found && p < end; p++) {
  5057. found = (*p == ']');
  5058. }
  5059. if (!found) return -1;
  5060. } else {
  5061. for (; p < end; p++) {
  5062. if (*p == ':' || *p == '/') break;
  5063. }
  5064. }
  5065. rhost.len = p - rhost.p;
  5066. if (p < end) {
  5067. if (*p == ':') {
  5068. state = P_PORT;
  5069. break;
  5070. } else if (*p == '/') {
  5071. state = P_REST;
  5072. break;
  5073. }
  5074. }
  5075. break;
  5076. case P_PORT:
  5077. p++;
  5078. for (; p < end; p++) {
  5079. if (*p == '/') {
  5080. state = P_REST;
  5081. break;
  5082. }
  5083. rport *= 10;
  5084. rport += *p - '0';
  5085. }
  5086. break;
  5087. case P_REST:
  5088. /* `p` points to separator. `path` includes the separator */
  5089. parse_uri_component(&p, end, "?#", &rpath);
  5090. if (p < end && *(p - 1) == '?') {
  5091. parse_uri_component(&p, end, "#", &rquery);
  5092. }
  5093. parse_uri_component(&p, end, "", &rfragment);
  5094. break;
  5095. }
  5096. }
  5097. if (scheme != 0) *scheme = rscheme;
  5098. if (user_info != 0) *user_info = ruser_info;
  5099. if (host != 0) *host = rhost;
  5100. if (port != 0) *port = rport;
  5101. if (path != 0) *path = rpath;
  5102. if (query != 0) *query = rquery;
  5103. if (fragment != 0) *fragment = rfragment;
  5104. return 0;
  5105. }
  5106. /* Normalize the URI path. Remove/resolve "." and "..". */
  5107. int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
  5108. const char *s = in->p, *se = s + in->len;
  5109. char *cp = (char *) out->p, *d;
  5110. if (in->len == 0 || *s != '/') {
  5111. out->len = 0;
  5112. return 0;
  5113. }
  5114. d = cp;
  5115. while (s < se) {
  5116. const char *next = s;
  5117. struct mg_str component;
  5118. parse_uri_component(&next, se, "/", &component);
  5119. if (mg_vcmp(&component, ".") == 0) {
  5120. /* Yum. */
  5121. } else if (mg_vcmp(&component, "..") == 0) {
  5122. /* Backtrack to previous slash. */
  5123. if (d > cp + 1 && *(d - 1) == '/') d--;
  5124. while (d > cp && *(d - 1) != '/') d--;
  5125. } else {
  5126. memmove(d, s, next - s);
  5127. d += next - s;
  5128. }
  5129. s = next;
  5130. }
  5131. if (d == cp) *d++ = '/';
  5132. out->p = cp;
  5133. out->len = d - cp;
  5134. return 1;
  5135. }
  5136. int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info,
  5137. const struct mg_str *host, unsigned int port,
  5138. const struct mg_str *path, const struct mg_str *query,
  5139. const struct mg_str *fragment, int normalize_path,
  5140. struct mg_str *uri) {
  5141. int result = -1;
  5142. struct mbuf out;
  5143. mbuf_init(&out, 0);
  5144. if (scheme != NULL && scheme->len > 0) {
  5145. mbuf_append(&out, scheme->p, scheme->len);
  5146. mbuf_append(&out, "://", 3);
  5147. }
  5148. if (user_info != NULL && user_info->len > 0) {
  5149. mbuf_append(&out, user_info->p, user_info->len);
  5150. mbuf_append(&out, "@", 1);
  5151. }
  5152. if (host != NULL && host->len > 0) {
  5153. mbuf_append(&out, host->p, host->len);
  5154. }
  5155. if (port != 0) {
  5156. char port_str[20];
  5157. int port_str_len = sprintf(port_str, ":%u", port);
  5158. mbuf_append(&out, port_str, port_str_len);
  5159. }
  5160. if (path != NULL && path->len > 0) {
  5161. if (normalize_path) {
  5162. struct mg_str npath = mg_strdup(*path);
  5163. if (npath.len != path->len) goto out;
  5164. if (!mg_normalize_uri_path(path, &npath)) {
  5165. free((void *) npath.p);
  5166. goto out;
  5167. }
  5168. mbuf_append(&out, npath.p, npath.len);
  5169. free((void *) npath.p);
  5170. } else {
  5171. mbuf_append(&out, path->p, path->len);
  5172. }
  5173. } else if (normalize_path) {
  5174. mbuf_append(&out, "/", 1);
  5175. }
  5176. if (query != NULL && query->len > 0) {
  5177. mbuf_append(&out, "?", 1);
  5178. mbuf_append(&out, query->p, query->len);
  5179. }
  5180. if (fragment != NULL && fragment->len > 0) {
  5181. mbuf_append(&out, "#", 1);
  5182. mbuf_append(&out, fragment->p, fragment->len);
  5183. }
  5184. result = 0;
  5185. out:
  5186. if (result == 0) {
  5187. uri->p = out.buf;
  5188. uri->len = out.len;
  5189. } else {
  5190. mbuf_free(&out);
  5191. uri->p = NULL;
  5192. uri->len = 0;
  5193. }
  5194. return result;
  5195. }
  5196. #ifdef MG_MODULE_LINES
  5197. #line 1 "mongoose/src/mg_http.c"
  5198. #endif
  5199. /*
  5200. * Copyright (c) 2014 Cesanta Software Limited
  5201. * All rights reserved
  5202. */
  5203. #if MG_ENABLE_HTTP
  5204. /* Amalgamated: #include "common/cs_md5.h" */
  5205. /* Amalgamated: #include "mg_internal.h" */
  5206. /* Amalgamated: #include "mg_util.h" */
  5207. /* altbuf {{{ */
  5208. /*
  5209. * Alternate buffer: fills the client-provided buffer with data; and if it's
  5210. * not large enough, allocates another buffer (via mbuf), similar to asprintf.
  5211. */
  5212. struct altbuf {
  5213. struct mbuf m;
  5214. char *user_buf;
  5215. size_t len;
  5216. size_t user_buf_size;
  5217. };
  5218. /*
  5219. * Initializes altbuf; `buf`, `buf_size` is the client-provided buffer.
  5220. */
  5221. MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) {
  5222. mbuf_init(&ab->m, 0);
  5223. ab->user_buf = buf;
  5224. ab->user_buf_size = buf_size;
  5225. ab->len = 0;
  5226. }
  5227. /*
  5228. * Appends a single char to the altbuf.
  5229. */
  5230. MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) {
  5231. if (ab->len < ab->user_buf_size) {
  5232. /* The data fits into the original buffer */
  5233. ab->user_buf[ab->len++] = c;
  5234. } else {
  5235. /* The data can't fit into the original buffer, so write it to mbuf. */
  5236. /*
  5237. * First of all, see if that's the first byte which overflows the original
  5238. * buffer: if so, copy the existing data from there to a newly allocated
  5239. * mbuf.
  5240. */
  5241. if (ab->len > 0 && ab->m.len == 0) {
  5242. mbuf_append(&ab->m, ab->user_buf, ab->len);
  5243. }
  5244. mbuf_append(&ab->m, &c, 1);
  5245. ab->len = ab->m.len;
  5246. }
  5247. }
  5248. /*
  5249. * Resets any data previously appended to altbuf.
  5250. */
  5251. MG_INTERNAL void altbuf_reset(struct altbuf *ab) {
  5252. mbuf_free(&ab->m);
  5253. ab->len = 0;
  5254. }
  5255. /*
  5256. * Returns whether the additional buffer was allocated (and thus the data
  5257. * is in the mbuf, not the client-provided buffer)
  5258. */
  5259. MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) {
  5260. return ab->len > ab->user_buf_size;
  5261. }
  5262. /*
  5263. * Returns the actual buffer with data, either the client-provided or a newly
  5264. * allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first.
  5265. */
  5266. MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) {
  5267. if (altbuf_reallocated(ab)) {
  5268. if (trim) {
  5269. mbuf_trim(&ab->m);
  5270. }
  5271. return ab->m.buf;
  5272. } else {
  5273. return ab->user_buf;
  5274. }
  5275. }
  5276. /* }}} */
  5277. static const char *mg_version_header = "Mongoose/" MG_VERSION;
  5278. enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
  5279. struct mg_http_proto_data_file {
  5280. FILE *fp; /* Opened file. */
  5281. int64_t cl; /* Content-Length. How many bytes to send. */
  5282. int64_t sent; /* How many bytes have been already sent. */
  5283. int keepalive; /* Keep connection open after sending. */
  5284. enum mg_http_proto_data_type type;
  5285. };
  5286. #if MG_ENABLE_HTTP_CGI
  5287. struct mg_http_proto_data_cgi {
  5288. struct mg_connection *cgi_nc;
  5289. };
  5290. #endif
  5291. struct mg_http_proto_data_chuncked {
  5292. int64_t body_len; /* How many bytes of chunked body was reassembled. */
  5293. };
  5294. struct mg_http_endpoint {
  5295. struct mg_http_endpoint *next;
  5296. struct mg_str uri_pattern; /* owned */
  5297. char *auth_domain; /* owned */
  5298. char *auth_file; /* owned */
  5299. mg_event_handler_t handler;
  5300. #if MG_ENABLE_CALLBACK_USERDATA
  5301. void *user_data;
  5302. #endif
  5303. };
  5304. enum mg_http_multipart_stream_state {
  5305. MPS_BEGIN,
  5306. MPS_WAITING_FOR_BOUNDARY,
  5307. MPS_WAITING_FOR_CHUNK,
  5308. MPS_GOT_BOUNDARY,
  5309. MPS_FINALIZE,
  5310. MPS_FINISHED
  5311. };
  5312. struct mg_http_multipart_stream {
  5313. const char *boundary;
  5314. int boundary_len;
  5315. const char *var_name;
  5316. const char *file_name;
  5317. void *user_data;
  5318. enum mg_http_multipart_stream_state state;
  5319. int processing_part;
  5320. int data_avail;
  5321. };
  5322. struct mg_reverse_proxy_data {
  5323. struct mg_connection *linked_conn;
  5324. };
  5325. struct mg_ws_proto_data {
  5326. /*
  5327. * Defragmented size of the frame so far.
  5328. *
  5329. * First byte of nc->recv_mbuf.buf is an op, the rest of the data is
  5330. * defragmented data.
  5331. */
  5332. size_t reass_len;
  5333. };
  5334. struct mg_http_proto_data {
  5335. #if MG_ENABLE_FILESYSTEM
  5336. struct mg_http_proto_data_file file;
  5337. #endif
  5338. #if MG_ENABLE_HTTP_CGI
  5339. struct mg_http_proto_data_cgi cgi;
  5340. #endif
  5341. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5342. struct mg_http_multipart_stream mp_stream;
  5343. #endif
  5344. #if MG_ENABLE_HTTP_WEBSOCKET
  5345. struct mg_ws_proto_data ws_data;
  5346. #endif
  5347. struct mg_http_proto_data_chuncked chunk;
  5348. struct mg_http_endpoint *endpoints;
  5349. mg_event_handler_t endpoint_handler;
  5350. struct mg_reverse_proxy_data reverse_proxy_data;
  5351. size_t rcvd; /* How many bytes we have received. */
  5352. };
  5353. static void mg_http_proto_data_destructor(void *proto_data);
  5354. struct mg_connection *mg_connect_http_base(
  5355. struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
  5356. struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
  5357. const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
  5358. struct mg_str *path, struct mg_str *user_info, struct mg_str *host);
  5359. MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
  5360. struct mg_connection *c) {
  5361. /* If we have proto data from previous connection, flush it. */
  5362. if (c->proto_data != NULL) {
  5363. void *pd = c->proto_data;
  5364. c->proto_data = NULL;
  5365. mg_http_proto_data_destructor(pd);
  5366. }
  5367. c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
  5368. c->proto_data_destructor = mg_http_proto_data_destructor;
  5369. return (struct mg_http_proto_data *) c->proto_data;
  5370. }
  5371. static struct mg_http_proto_data *mg_http_get_proto_data(
  5372. struct mg_connection *c) {
  5373. return (struct mg_http_proto_data *) c->proto_data;
  5374. }
  5375. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5376. static void mg_http_free_proto_data_mp_stream(
  5377. struct mg_http_multipart_stream *mp) {
  5378. MG_FREE((void *) mp->boundary);
  5379. MG_FREE((void *) mp->var_name);
  5380. MG_FREE((void *) mp->file_name);
  5381. memset(mp, 0, sizeof(*mp));
  5382. }
  5383. #endif
  5384. #if MG_ENABLE_FILESYSTEM
  5385. static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
  5386. if (d != NULL) {
  5387. if (d->fp != NULL) {
  5388. fclose(d->fp);
  5389. }
  5390. memset(d, 0, sizeof(struct mg_http_proto_data_file));
  5391. }
  5392. }
  5393. #endif
  5394. static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
  5395. struct mg_http_endpoint *current = *ep;
  5396. while (current != NULL) {
  5397. struct mg_http_endpoint *tmp = current->next;
  5398. MG_FREE((void *) current->uri_pattern.p);
  5399. MG_FREE((void *) current->auth_domain);
  5400. MG_FREE((void *) current->auth_file);
  5401. MG_FREE(current);
  5402. current = tmp;
  5403. }
  5404. ep = NULL;
  5405. }
  5406. static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) {
  5407. if (rpd->linked_conn != NULL) {
  5408. /*
  5409. * Connection has linked one, we have to unlink & close it
  5410. * since _this_ connection is going to die and
  5411. * it doesn't make sense to keep another one
  5412. */
  5413. struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn);
  5414. if (pd->reverse_proxy_data.linked_conn != NULL) {
  5415. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  5416. pd->reverse_proxy_data.linked_conn = NULL;
  5417. }
  5418. rpd->linked_conn = NULL;
  5419. }
  5420. }
  5421. static void mg_http_proto_data_destructor(void *proto_data) {
  5422. struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
  5423. #if MG_ENABLE_FILESYSTEM
  5424. mg_http_free_proto_data_file(&pd->file);
  5425. #endif
  5426. #if MG_ENABLE_HTTP_CGI
  5427. mg_http_free_proto_data_cgi(&pd->cgi);
  5428. #endif
  5429. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5430. mg_http_free_proto_data_mp_stream(&pd->mp_stream);
  5431. #endif
  5432. mg_http_free_proto_data_endpoints(&pd->endpoints);
  5433. mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
  5434. MG_FREE(proto_data);
  5435. }
  5436. #if MG_ENABLE_FILESYSTEM
  5437. #define MIME_ENTRY(_ext, _type) \
  5438. { _ext, sizeof(_ext) - 1, _type }
  5439. static const struct {
  5440. const char *extension;
  5441. size_t ext_len;
  5442. const char *mime_type;
  5443. } mg_static_builtin_mime_types[] = {
  5444. MIME_ENTRY("html", "text/html"),
  5445. MIME_ENTRY("html", "text/html"),
  5446. MIME_ENTRY("htm", "text/html"),
  5447. MIME_ENTRY("shtm", "text/html"),
  5448. MIME_ENTRY("shtml", "text/html"),
  5449. MIME_ENTRY("css", "text/css"),
  5450. MIME_ENTRY("js", "application/x-javascript"),
  5451. MIME_ENTRY("ico", "image/x-icon"),
  5452. MIME_ENTRY("gif", "image/gif"),
  5453. MIME_ENTRY("jpg", "image/jpeg"),
  5454. MIME_ENTRY("jpeg", "image/jpeg"),
  5455. MIME_ENTRY("png", "image/png"),
  5456. MIME_ENTRY("svg", "image/svg+xml"),
  5457. MIME_ENTRY("txt", "text/plain"),
  5458. MIME_ENTRY("torrent", "application/x-bittorrent"),
  5459. MIME_ENTRY("wav", "audio/x-wav"),
  5460. MIME_ENTRY("mp3", "audio/x-mp3"),
  5461. MIME_ENTRY("mid", "audio/mid"),
  5462. MIME_ENTRY("m3u", "audio/x-mpegurl"),
  5463. MIME_ENTRY("ogg", "application/ogg"),
  5464. MIME_ENTRY("ram", "audio/x-pn-realaudio"),
  5465. MIME_ENTRY("xml", "text/xml"),
  5466. MIME_ENTRY("ttf", "application/x-font-ttf"),
  5467. MIME_ENTRY("json", "application/json"),
  5468. MIME_ENTRY("xslt", "application/xml"),
  5469. MIME_ENTRY("xsl", "application/xml"),
  5470. MIME_ENTRY("ra", "audio/x-pn-realaudio"),
  5471. MIME_ENTRY("doc", "application/msword"),
  5472. MIME_ENTRY("exe", "application/octet-stream"),
  5473. MIME_ENTRY("zip", "application/x-zip-compressed"),
  5474. MIME_ENTRY("xls", "application/excel"),
  5475. MIME_ENTRY("tgz", "application/x-tar-gz"),
  5476. MIME_ENTRY("tar", "application/x-tar"),
  5477. MIME_ENTRY("gz", "application/x-gunzip"),
  5478. MIME_ENTRY("arj", "application/x-arj-compressed"),
  5479. MIME_ENTRY("rar", "application/x-rar-compressed"),
  5480. MIME_ENTRY("rtf", "application/rtf"),
  5481. MIME_ENTRY("pdf", "application/pdf"),
  5482. MIME_ENTRY("swf", "application/x-shockwave-flash"),
  5483. MIME_ENTRY("mpg", "video/mpeg"),
  5484. MIME_ENTRY("webm", "video/webm"),
  5485. MIME_ENTRY("mpeg", "video/mpeg"),
  5486. MIME_ENTRY("mov", "video/quicktime"),
  5487. MIME_ENTRY("mp4", "video/mp4"),
  5488. MIME_ENTRY("m4v", "video/x-m4v"),
  5489. MIME_ENTRY("asf", "video/x-ms-asf"),
  5490. MIME_ENTRY("avi", "video/x-msvideo"),
  5491. MIME_ENTRY("bmp", "image/bmp"),
  5492. {NULL, 0, NULL}};
  5493. static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
  5494. const struct mg_serve_http_opts *opts) {
  5495. const char *ext, *overrides;
  5496. size_t i, path_len;
  5497. struct mg_str r, k, v;
  5498. path_len = strlen(path);
  5499. overrides = opts->custom_mime_types;
  5500. while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
  5501. ext = path + (path_len - k.len);
  5502. if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
  5503. return v;
  5504. }
  5505. }
  5506. for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
  5507. ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
  5508. if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
  5509. mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
  5510. r.p = mg_static_builtin_mime_types[i].mime_type;
  5511. r.len = strlen(r.p);
  5512. return r;
  5513. }
  5514. }
  5515. r.p = dflt;
  5516. r.len = strlen(r.p);
  5517. return r;
  5518. }
  5519. #endif
  5520. /*
  5521. * Check whether full request is buffered. Return:
  5522. * -1 if request is malformed
  5523. * 0 if request is not yet fully buffered
  5524. * >0 actual request length, including last \r\n\r\n
  5525. */
  5526. static int mg_http_get_request_len(const char *s, int buf_len) {
  5527. const unsigned char *buf = (unsigned char *) s;
  5528. int i;
  5529. for (i = 0; i < buf_len; i++) {
  5530. if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
  5531. return -1;
  5532. } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
  5533. return i + 2;
  5534. } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
  5535. buf[i + 2] == '\n') {
  5536. return i + 3;
  5537. }
  5538. }
  5539. return 0;
  5540. }
  5541. static const char *mg_http_parse_headers(const char *s, const char *end,
  5542. int len, struct http_message *req) {
  5543. int i = 0;
  5544. while (i < (int) ARRAY_SIZE(req->header_names) - 1) {
  5545. struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
  5546. s = mg_skip(s, end, ": ", k);
  5547. s = mg_skip(s, end, "\r\n", v);
  5548. while (v->len > 0 && v->p[v->len - 1] == ' ') {
  5549. v->len--; /* Trim trailing spaces in header value */
  5550. }
  5551. /*
  5552. * If header value is empty - skip it and go to next (if any).
  5553. * NOTE: Do not add it to headers_values because such addition changes API
  5554. * behaviour
  5555. */
  5556. if (k->len != 0 && v->len == 0) {
  5557. continue;
  5558. }
  5559. if (k->len == 0 || v->len == 0) {
  5560. k->p = v->p = NULL;
  5561. k->len = v->len = 0;
  5562. break;
  5563. }
  5564. if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
  5565. req->body.len = (size_t) to64(v->p);
  5566. req->message.len = len + req->body.len;
  5567. }
  5568. i++;
  5569. }
  5570. return s;
  5571. }
  5572. int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
  5573. const char *end, *qs;
  5574. int len = mg_http_get_request_len(s, n);
  5575. if (len <= 0) return len;
  5576. memset(hm, 0, sizeof(*hm));
  5577. hm->message.p = s;
  5578. hm->body.p = s + len;
  5579. hm->message.len = hm->body.len = (size_t) ~0;
  5580. end = s + len;
  5581. /* Request is fully buffered. Skip leading whitespaces. */
  5582. while (s < end && isspace(*(unsigned char *) s)) s++;
  5583. if (is_req) {
  5584. /* Parse request line: method, URI, proto */
  5585. s = mg_skip(s, end, " ", &hm->method);
  5586. s = mg_skip(s, end, " ", &hm->uri);
  5587. s = mg_skip(s, end, "\r\n", &hm->proto);
  5588. if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
  5589. /* If URI contains '?' character, initialize query_string */
  5590. if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
  5591. hm->query_string.p = qs + 1;
  5592. hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
  5593. hm->uri.len = qs - hm->uri.p;
  5594. }
  5595. } else {
  5596. s = mg_skip(s, end, " ", &hm->proto);
  5597. if (end - s < 4 || s[3] != ' ') return -1;
  5598. hm->resp_code = atoi(s);
  5599. if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
  5600. s += 4;
  5601. s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
  5602. }
  5603. s = mg_http_parse_headers(s, end, len, hm);
  5604. /*
  5605. * mg_parse_http() is used to parse both HTTP requests and HTTP
  5606. * responses. If HTTP response does not have Content-Length set, then
  5607. * body is read until socket is closed, i.e. body.len is infinite (~0).
  5608. *
  5609. * For HTTP requests though, according to
  5610. * http://tools.ietf.org/html/rfc7231#section-8.1.3,
  5611. * only POST and PUT methods have defined body semantics.
  5612. * Therefore, if Content-Length is not specified and methods are
  5613. * not one of PUT or POST, set body length to 0.
  5614. *
  5615. * So,
  5616. * if it is HTTP request, and Content-Length is not set,
  5617. * and method is not (PUT or POST) then reset body length to zero.
  5618. */
  5619. if (hm->body.len == (size_t) ~0 && is_req &&
  5620. mg_vcasecmp(&hm->method, "PUT") != 0 &&
  5621. mg_vcasecmp(&hm->method, "POST") != 0) {
  5622. hm->body.len = 0;
  5623. hm->message.len = len;
  5624. }
  5625. return len;
  5626. }
  5627. struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
  5628. size_t i, len = strlen(name);
  5629. for (i = 0; hm->header_names[i].len > 0; i++) {
  5630. struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
  5631. if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
  5632. return v;
  5633. }
  5634. return NULL;
  5635. }
  5636. #if MG_ENABLE_FILESYSTEM
  5637. static void mg_http_transfer_file_data(struct mg_connection *nc) {
  5638. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  5639. char buf[MG_MAX_HTTP_SEND_MBUF];
  5640. size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent);
  5641. if (pd->file.type == DATA_FILE) {
  5642. struct mbuf *io = &nc->send_mbuf;
  5643. if (io->len >= MG_MAX_HTTP_SEND_MBUF) {
  5644. to_read = 0;
  5645. } else {
  5646. to_read = MG_MAX_HTTP_SEND_MBUF - io->len;
  5647. }
  5648. if (to_read > left) {
  5649. to_read = left;
  5650. }
  5651. if (to_read > 0) {
  5652. n = mg_fread(buf, 1, to_read, pd->file.fp);
  5653. if (n > 0) {
  5654. mg_send(nc, buf, n);
  5655. pd->file.sent += n;
  5656. DBG(("%p sent %d (total %d)", nc, (int) n, (int) pd->file.sent));
  5657. }
  5658. } else {
  5659. /* Rate-limited */
  5660. }
  5661. if (pd->file.sent >= pd->file.cl) {
  5662. LOG(LL_DEBUG, ("%p done, %d bytes, ka %d", nc, (int) pd->file.sent,
  5663. pd->file.keepalive));
  5664. if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
  5665. mg_http_free_proto_data_file(&pd->file);
  5666. }
  5667. } else if (pd->file.type == DATA_PUT) {
  5668. struct mbuf *io = &nc->recv_mbuf;
  5669. size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len;
  5670. size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp);
  5671. if (n > 0) {
  5672. mbuf_remove(io, n);
  5673. pd->file.sent += n;
  5674. }
  5675. if (n == 0 || pd->file.sent >= pd->file.cl) {
  5676. if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
  5677. mg_http_free_proto_data_file(&pd->file);
  5678. }
  5679. }
  5680. #if MG_ENABLE_HTTP_CGI
  5681. else if (pd->cgi.cgi_nc != NULL) {
  5682. /* This is POST data that needs to be forwarded to the CGI process */
  5683. if (pd->cgi.cgi_nc != NULL) {
  5684. mg_forward(nc, pd->cgi.cgi_nc);
  5685. } else {
  5686. nc->flags |= MG_F_SEND_AND_CLOSE;
  5687. }
  5688. }
  5689. #endif
  5690. }
  5691. #endif /* MG_ENABLE_FILESYSTEM */
  5692. /*
  5693. * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
  5694. * if it's incomplete. If the chunk is fully buffered, return total number of
  5695. * bytes in a chunk, and store data in `data`, `data_len`.
  5696. */
  5697. static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
  5698. size_t *chunk_len) {
  5699. unsigned char *s = (unsigned char *) buf;
  5700. size_t n = 0; /* scanned chunk length */
  5701. size_t i = 0; /* index in s */
  5702. /* Scan chunk length. That should be a hexadecimal number. */
  5703. while (i < len && isxdigit(s[i])) {
  5704. n *= 16;
  5705. n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
  5706. i++;
  5707. if (i > 6) {
  5708. /* Chunk size is unreasonable. */
  5709. return 0;
  5710. }
  5711. }
  5712. /* Skip new line */
  5713. if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
  5714. return 0;
  5715. }
  5716. i += 2;
  5717. /* Record where the data is */
  5718. *chunk_data = (char *) s + i;
  5719. *chunk_len = n;
  5720. /* Skip data */
  5721. i += n;
  5722. /* Skip new line */
  5723. if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
  5724. return 0;
  5725. }
  5726. return i + 2;
  5727. }
  5728. MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
  5729. struct http_message *hm, char *buf,
  5730. size_t blen) {
  5731. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  5732. char *data;
  5733. size_t i, n, data_len, body_len, zero_chunk_received = 0;
  5734. /* Find out piece of received data that is not yet reassembled */
  5735. body_len = (size_t) pd->chunk.body_len;
  5736. assert(blen >= body_len);
  5737. /* Traverse all fully buffered chunks */
  5738. for (i = body_len;
  5739. (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
  5740. i += n) {
  5741. /* Collapse chunk data to the rest of HTTP body */
  5742. memmove(buf + body_len, data, data_len);
  5743. body_len += data_len;
  5744. hm->body.len = body_len;
  5745. if (data_len == 0) {
  5746. zero_chunk_received = 1;
  5747. i += n;
  5748. break;
  5749. }
  5750. }
  5751. if (i > body_len) {
  5752. /* Shift unparsed content to the parsed body */
  5753. assert(i <= blen);
  5754. memmove(buf + body_len, buf + i, blen - i);
  5755. memset(buf + body_len + blen - i, 0, i - body_len);
  5756. nc->recv_mbuf.len -= i - body_len;
  5757. pd->chunk.body_len = body_len;
  5758. /* Send MG_EV_HTTP_CHUNK event */
  5759. nc->flags &= ~MG_F_DELETE_CHUNK;
  5760. mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm);
  5761. /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
  5762. if (nc->flags & MG_F_DELETE_CHUNK) {
  5763. memset(buf, 0, body_len);
  5764. memmove(buf, buf + body_len, blen - i);
  5765. nc->recv_mbuf.len -= body_len;
  5766. hm->body.len = 0;
  5767. pd->chunk.body_len = 0;
  5768. }
  5769. if (zero_chunk_received) {
  5770. /* Total message size is len(body) + len(headers) */
  5771. hm->message.len =
  5772. (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p);
  5773. }
  5774. }
  5775. return body_len;
  5776. }
  5777. struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc,
  5778. struct mg_str *uri_path) {
  5779. struct mg_http_proto_data *pd;
  5780. struct mg_http_endpoint *ret = NULL;
  5781. int matched, matched_max = 0;
  5782. struct mg_http_endpoint *ep;
  5783. if (nc == NULL) return NULL;
  5784. pd = mg_http_get_proto_data(nc);
  5785. if (pd == NULL) return NULL;
  5786. ep = pd->endpoints;
  5787. while (ep != NULL) {
  5788. if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) {
  5789. if (matched > matched_max) {
  5790. /* Looking for the longest suitable handler */
  5791. ret = ep;
  5792. matched_max = matched;
  5793. }
  5794. }
  5795. ep = ep->next;
  5796. }
  5797. return ret;
  5798. }
  5799. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5800. static void mg_http_multipart_continue(struct mg_connection *nc);
  5801. static void mg_http_multipart_begin(struct mg_connection *nc,
  5802. struct http_message *hm, int req_len);
  5803. #endif
  5804. static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
  5805. struct http_message *hm);
  5806. static void deliver_chunk(struct mg_connection *c, struct http_message *hm,
  5807. int req_len) {
  5808. /* Incomplete message received. Send MG_EV_HTTP_CHUNK event */
  5809. hm->body.len = c->recv_mbuf.len - req_len;
  5810. c->flags &= ~MG_F_DELETE_CHUNK;
  5811. mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm);
  5812. /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
  5813. if (c->flags & MG_F_DELETE_CHUNK) c->recv_mbuf.len = req_len;
  5814. }
  5815. /*
  5816. * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
  5817. * If a big structure is declared in a big function, lx106 gcc will make it
  5818. * even bigger (round up to 4k, from 700 bytes of actual size).
  5819. */
  5820. #ifdef __xtensa__
  5821. static void mg_http_handler2(struct mg_connection *nc, int ev,
  5822. void *ev_data MG_UD_ARG(void *user_data),
  5823. struct http_message *hm) __attribute__((noinline));
  5824. void mg_http_handler(struct mg_connection *nc, int ev,
  5825. void *ev_data MG_UD_ARG(void *user_data)) {
  5826. struct http_message hm;
  5827. mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm);
  5828. }
  5829. static void mg_http_handler2(struct mg_connection *nc, int ev,
  5830. void *ev_data MG_UD_ARG(void *user_data),
  5831. struct http_message *hm) {
  5832. #else /* !__XTENSA__ */
  5833. void mg_http_handler(struct mg_connection *nc, int ev,
  5834. void *ev_data MG_UD_ARG(void *user_data)) {
  5835. struct http_message shm, *hm = &shm;
  5836. #endif /* __XTENSA__ */
  5837. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  5838. struct mbuf *io = &nc->recv_mbuf;
  5839. int req_len;
  5840. const int is_req = (nc->listener != NULL);
  5841. #if MG_ENABLE_HTTP_WEBSOCKET
  5842. struct mg_str *vec;
  5843. #endif
  5844. if (ev == MG_EV_CLOSE) {
  5845. #if MG_ENABLE_HTTP_CGI
  5846. /* Close associated CGI forwarder connection */
  5847. if (pd != NULL && pd->cgi.cgi_nc != NULL) {
  5848. pd->cgi.cgi_nc->user_data = NULL;
  5849. pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  5850. }
  5851. #endif
  5852. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5853. if (pd != NULL && pd->mp_stream.boundary != NULL) {
  5854. /*
  5855. * Multipart message is in progress, but connection is closed.
  5856. * Finish part and request with an error flag.
  5857. */
  5858. struct mg_http_multipart_part mp;
  5859. memset(&mp, 0, sizeof(mp));
  5860. mp.status = -1;
  5861. mp.var_name = pd->mp_stream.var_name;
  5862. mp.file_name = pd->mp_stream.file_name;
  5863. mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
  5864. nc->user_data, MG_EV_HTTP_PART_END, &mp);
  5865. mp.var_name = NULL;
  5866. mp.file_name = NULL;
  5867. mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
  5868. nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
  5869. } else
  5870. #endif
  5871. if (io->len > 0 &&
  5872. (req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) {
  5873. /*
  5874. * For HTTP messages without Content-Length, always send HTTP message
  5875. * before MG_EV_CLOSE message.
  5876. */
  5877. int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
  5878. hm->message.len = io->len;
  5879. hm->body.len = io->buf + io->len - hm->body.p;
  5880. deliver_chunk(nc, hm, req_len);
  5881. mg_http_call_endpoint_handler(nc, ev2, hm);
  5882. }
  5883. if (pd != NULL && pd->endpoint_handler != NULL &&
  5884. pd->endpoint_handler != nc->handler) {
  5885. mg_call(nc, pd->endpoint_handler, nc->user_data, ev, NULL);
  5886. }
  5887. }
  5888. #if MG_ENABLE_FILESYSTEM
  5889. if (pd != NULL && pd->file.fp != NULL) {
  5890. mg_http_transfer_file_data(nc);
  5891. }
  5892. #endif
  5893. mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
  5894. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5895. if (pd != NULL && pd->mp_stream.boundary != NULL &&
  5896. (ev == MG_EV_RECV || ev == MG_EV_POLL)) {
  5897. if (ev == MG_EV_RECV) {
  5898. pd->rcvd += *(int *) ev_data;
  5899. mg_http_multipart_continue(nc);
  5900. } else if (pd->mp_stream.data_avail) {
  5901. /* Try re-delivering the data. */
  5902. mg_http_multipart_continue(nc);
  5903. }
  5904. return;
  5905. }
  5906. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  5907. if (ev == MG_EV_RECV) {
  5908. struct mg_str *s;
  5909. again:
  5910. req_len = mg_parse_http(io->buf, io->len, hm, is_req);
  5911. if (req_len > 0) {
  5912. /* New request - new proto data */
  5913. pd = mg_http_create_proto_data(nc);
  5914. pd->rcvd = io->len;
  5915. }
  5916. if (req_len > 0 &&
  5917. (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
  5918. mg_vcasecmp(s, "chunked") == 0) {
  5919. mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
  5920. }
  5921. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  5922. if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
  5923. s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
  5924. mg_http_multipart_begin(nc, hm, req_len);
  5925. mg_http_multipart_continue(nc);
  5926. return;
  5927. }
  5928. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  5929. /* TODO(alashkin): refactor this ifelseifelseifelseifelse */
  5930. if ((req_len < 0 ||
  5931. (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
  5932. DBG(("invalid request"));
  5933. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  5934. } else if (req_len == 0) {
  5935. /* Do nothing, request is not yet fully buffered */
  5936. }
  5937. #if MG_ENABLE_HTTP_WEBSOCKET
  5938. else if (nc->listener == NULL && (nc->flags & MG_F_IS_WEBSOCKET)) {
  5939. /* We're websocket client, got handshake response from server. */
  5940. DBG(("%p WebSocket upgrade code %d", nc, hm->resp_code));
  5941. if (hm->resp_code == 101 &&
  5942. mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
  5943. /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
  5944. mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
  5945. hm);
  5946. mbuf_remove(io, req_len);
  5947. nc->proto_handler = mg_ws_handler;
  5948. mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
  5949. } else {
  5950. mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
  5951. hm);
  5952. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  5953. mbuf_remove(io, req_len);
  5954. }
  5955. } else if (nc->listener != NULL &&
  5956. (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
  5957. struct mg_http_endpoint *ep;
  5958. /* This is a websocket request. Switch protocol handlers. */
  5959. mbuf_remove(io, req_len);
  5960. nc->proto_handler = mg_ws_handler;
  5961. nc->flags |= MG_F_IS_WEBSOCKET;
  5962. /*
  5963. * If we have a handler set up with mg_register_http_endpoint(),
  5964. * deliver subsequent websocket events to this handler after the
  5965. * protocol switch.
  5966. */
  5967. ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
  5968. if (ep != NULL) {
  5969. nc->handler = ep->handler;
  5970. #if MG_ENABLE_CALLBACK_USERDATA
  5971. nc->user_data = ep->user_data;
  5972. #endif
  5973. }
  5974. /* Send handshake */
  5975. mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST,
  5976. hm);
  5977. if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) {
  5978. if (nc->send_mbuf.len == 0) {
  5979. mg_ws_handshake(nc, vec, hm);
  5980. }
  5981. mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
  5982. hm);
  5983. mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
  5984. }
  5985. }
  5986. #endif /* MG_ENABLE_HTTP_WEBSOCKET */
  5987. else if (hm->message.len > pd->rcvd) {
  5988. /* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */
  5989. deliver_chunk(nc, hm, req_len);
  5990. if (nc->recv_mbuf_limit > 0 && nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
  5991. LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
  5992. "%lu bytes, and not drained, closing",
  5993. nc, (unsigned long) nc->recv_mbuf.len,
  5994. (unsigned long) nc->recv_mbuf_limit));
  5995. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  5996. }
  5997. } else {
  5998. /* We did receive all HTTP body. */
  5999. int request_done = 1;
  6000. int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
  6001. char addr[32];
  6002. mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr),
  6003. MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
  6004. DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p,
  6005. (int) hm->uri.len, hm->uri.p));
  6006. deliver_chunk(nc, hm, req_len);
  6007. /* Whole HTTP message is fully buffered, call event handler */
  6008. mg_http_call_endpoint_handler(nc, trigger_ev, hm);
  6009. mbuf_remove(io, hm->message.len);
  6010. pd->rcvd -= hm->message.len;
  6011. #if MG_ENABLE_FILESYSTEM
  6012. /* We don't have a generic mechanism of communicating that we are done
  6013. * responding to a request (should probably add one). But if we are
  6014. * serving
  6015. * a file, we are definitely not done. */
  6016. if (pd->file.fp != NULL) request_done = 0;
  6017. #endif
  6018. #if MG_ENABLE_HTTP_CGI
  6019. /* If this is a CGI request, we are not done either. */
  6020. if (pd->cgi.cgi_nc != NULL) request_done = 0;
  6021. #endif
  6022. if (request_done && io->len > 0) goto again;
  6023. }
  6024. }
  6025. }
  6026. static size_t mg_get_line_len(const char *buf, size_t buf_len) {
  6027. size_t len = 0;
  6028. while (len < buf_len && buf[len] != '\n') len++;
  6029. return len == buf_len ? 0 : len + 1;
  6030. }
  6031. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  6032. static void mg_http_multipart_begin(struct mg_connection *nc,
  6033. struct http_message *hm, int req_len) {
  6034. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  6035. struct mg_str *ct;
  6036. struct mbuf *io = &nc->recv_mbuf;
  6037. char boundary_buf[100];
  6038. char *boundary = boundary_buf;
  6039. int boundary_len;
  6040. ct = mg_get_http_header(hm, "Content-Type");
  6041. if (ct == NULL) {
  6042. /* We need more data - or it isn't multipart mesage */
  6043. goto exit_mp;
  6044. }
  6045. /* Content-type should start with "multipart" */
  6046. if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
  6047. goto exit_mp;
  6048. }
  6049. boundary_len =
  6050. mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf));
  6051. if (boundary_len == 0) {
  6052. /*
  6053. * Content type is multipart, but there is no boundary,
  6054. * probably malformed request
  6055. */
  6056. nc->flags = MG_F_CLOSE_IMMEDIATELY;
  6057. DBG(("invalid request"));
  6058. goto exit_mp;
  6059. }
  6060. /* If we reach this place - that is multipart request */
  6061. if (pd->mp_stream.boundary != NULL) {
  6062. /*
  6063. * Another streaming request was in progress,
  6064. * looks like protocol error
  6065. */
  6066. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  6067. } else {
  6068. struct mg_http_endpoint *ep = NULL;
  6069. pd->mp_stream.state = MPS_BEGIN;
  6070. pd->mp_stream.boundary = strdup(boundary);
  6071. pd->mp_stream.boundary_len = strlen(boundary);
  6072. pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
  6073. pd->endpoint_handler = nc->handler;
  6074. ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
  6075. if (ep != NULL) {
  6076. pd->endpoint_handler = ep->handler;
  6077. }
  6078. mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm);
  6079. mbuf_remove(io, req_len);
  6080. }
  6081. exit_mp:
  6082. if (boundary != boundary_buf) MG_FREE(boundary);
  6083. }
  6084. #define CONTENT_DISPOSITION "Content-Disposition: "
  6085. static size_t mg_http_multipart_call_handler(struct mg_connection *c, int ev,
  6086. const char *data,
  6087. size_t data_len) {
  6088. struct mg_http_multipart_part mp;
  6089. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  6090. memset(&mp, 0, sizeof(mp));
  6091. mp.var_name = pd->mp_stream.var_name;
  6092. mp.file_name = pd->mp_stream.file_name;
  6093. mp.user_data = pd->mp_stream.user_data;
  6094. mp.data.p = data;
  6095. mp.data.len = data_len;
  6096. mp.num_data_consumed = data_len;
  6097. mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp);
  6098. pd->mp_stream.user_data = mp.user_data;
  6099. pd->mp_stream.data_avail = (mp.num_data_consumed != data_len);
  6100. return mp.num_data_consumed;
  6101. }
  6102. static int mg_http_multipart_finalize(struct mg_connection *c) {
  6103. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  6104. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
  6105. MG_FREE((void *) pd->mp_stream.file_name);
  6106. pd->mp_stream.file_name = NULL;
  6107. MG_FREE((void *) pd->mp_stream.var_name);
  6108. pd->mp_stream.var_name = NULL;
  6109. mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
  6110. mg_http_free_proto_data_mp_stream(&pd->mp_stream);
  6111. pd->mp_stream.state = MPS_FINISHED;
  6112. return 1;
  6113. }
  6114. static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
  6115. const char *boundary;
  6116. struct mbuf *io = &c->recv_mbuf;
  6117. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  6118. if (pd->mp_stream.boundary == NULL) {
  6119. pd->mp_stream.state = MPS_FINALIZE;
  6120. DBG(("Invalid request: boundary not initialized"));
  6121. return 0;
  6122. }
  6123. if ((int) io->len < pd->mp_stream.boundary_len + 2) {
  6124. return 0;
  6125. }
  6126. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  6127. if (boundary != NULL) {
  6128. const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
  6129. if (io->len - (boundary_end - io->buf) < 4) {
  6130. return 0;
  6131. }
  6132. if (strncmp(boundary_end, "--\r\n", 4) == 0) {
  6133. pd->mp_stream.state = MPS_FINALIZE;
  6134. mbuf_remove(io, (boundary_end - io->buf) + 4);
  6135. } else {
  6136. pd->mp_stream.state = MPS_GOT_BOUNDARY;
  6137. }
  6138. } else {
  6139. return 0;
  6140. }
  6141. return 1;
  6142. }
  6143. static void mg_http_parse_header_internal(struct mg_str *hdr,
  6144. const char *var_name,
  6145. struct altbuf *ab);
  6146. static int mg_http_multipart_process_boundary(struct mg_connection *c) {
  6147. int data_size;
  6148. const char *boundary, *block_begin;
  6149. struct mbuf *io = &c->recv_mbuf;
  6150. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  6151. struct altbuf ab_file_name, ab_var_name;
  6152. int line_len;
  6153. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  6154. block_begin = boundary + pd->mp_stream.boundary_len + 2;
  6155. data_size = io->len - (block_begin - io->buf);
  6156. altbuf_init(&ab_file_name, NULL, 0);
  6157. altbuf_init(&ab_var_name, NULL, 0);
  6158. while (data_size > 0 &&
  6159. (line_len = mg_get_line_len(block_begin, data_size)) != 0) {
  6160. if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
  6161. mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
  6162. sizeof(CONTENT_DISPOSITION) - 1) == 0) {
  6163. struct mg_str header;
  6164. header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
  6165. header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
  6166. altbuf_reset(&ab_var_name);
  6167. mg_http_parse_header_internal(&header, "name", &ab_var_name);
  6168. altbuf_reset(&ab_file_name);
  6169. mg_http_parse_header_internal(&header, "filename", &ab_file_name);
  6170. block_begin += line_len;
  6171. data_size -= line_len;
  6172. continue;
  6173. }
  6174. if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
  6175. mbuf_remove(io, block_begin - io->buf + 2);
  6176. if (pd->mp_stream.processing_part != 0) {
  6177. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
  6178. }
  6179. /* Reserve 2 bytes for "\r\n" in file_name and var_name */
  6180. altbuf_append(&ab_file_name, '\0');
  6181. altbuf_append(&ab_file_name, '\0');
  6182. altbuf_append(&ab_var_name, '\0');
  6183. altbuf_append(&ab_var_name, '\0');
  6184. MG_FREE((void *) pd->mp_stream.file_name);
  6185. pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */);
  6186. MG_FREE((void *) pd->mp_stream.var_name);
  6187. pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */);
  6188. mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
  6189. pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
  6190. pd->mp_stream.processing_part++;
  6191. return 1;
  6192. }
  6193. block_begin += line_len;
  6194. }
  6195. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  6196. altbuf_reset(&ab_var_name);
  6197. altbuf_reset(&ab_file_name);
  6198. return 0;
  6199. }
  6200. static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
  6201. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  6202. struct mbuf *io = &c->recv_mbuf;
  6203. const char *boundary;
  6204. if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
  6205. return 0;
  6206. }
  6207. boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
  6208. if (boundary == NULL) {
  6209. int data_len = (io->len - (pd->mp_stream.boundary_len + 6));
  6210. if (data_len > 0) {
  6211. size_t consumed = mg_http_multipart_call_handler(
  6212. c, MG_EV_HTTP_PART_DATA, io->buf, (size_t) data_len);
  6213. mbuf_remove(io, consumed);
  6214. }
  6215. return 0;
  6216. } else if (boundary != NULL) {
  6217. size_t data_len = ((size_t)(boundary - io->buf) - 4);
  6218. size_t consumed = mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA,
  6219. io->buf, data_len);
  6220. mbuf_remove(io, consumed);
  6221. if (consumed == data_len) {
  6222. mbuf_remove(io, 4);
  6223. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  6224. return 1;
  6225. } else {
  6226. return 0;
  6227. }
  6228. } else {
  6229. return 0;
  6230. }
  6231. }
  6232. static void mg_http_multipart_continue(struct mg_connection *c) {
  6233. struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
  6234. while (1) {
  6235. switch (pd->mp_stream.state) {
  6236. case MPS_BEGIN: {
  6237. pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
  6238. break;
  6239. }
  6240. case MPS_WAITING_FOR_BOUNDARY: {
  6241. if (mg_http_multipart_wait_for_boundary(c) == 0) {
  6242. return;
  6243. }
  6244. break;
  6245. }
  6246. case MPS_GOT_BOUNDARY: {
  6247. if (mg_http_multipart_process_boundary(c) == 0) {
  6248. return;
  6249. }
  6250. break;
  6251. }
  6252. case MPS_WAITING_FOR_CHUNK: {
  6253. if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
  6254. return;
  6255. }
  6256. break;
  6257. }
  6258. case MPS_FINALIZE: {
  6259. if (mg_http_multipart_finalize(c) == 0) {
  6260. return;
  6261. }
  6262. break;
  6263. }
  6264. case MPS_FINISHED: {
  6265. return;
  6266. }
  6267. }
  6268. }
  6269. }
  6270. struct file_upload_state {
  6271. char *lfn;
  6272. size_t num_recd;
  6273. FILE *fp;
  6274. };
  6275. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  6276. void mg_set_protocol_http_websocket(struct mg_connection *nc) {
  6277. nc->proto_handler = mg_http_handler;
  6278. }
  6279. const char *mg_status_message(int status_code) {
  6280. switch (status_code) {
  6281. case 206:
  6282. return "Partial Content";
  6283. case 301:
  6284. return "Moved";
  6285. case 302:
  6286. return "Found";
  6287. case 400:
  6288. return "Bad Request";
  6289. case 401:
  6290. return "Unauthorized";
  6291. case 403:
  6292. return "Forbidden";
  6293. case 404:
  6294. return "Not Found";
  6295. case 416:
  6296. return "Requested Range Not Satisfiable";
  6297. case 418:
  6298. return "I'm a teapot";
  6299. case 500:
  6300. return "Internal Server Error";
  6301. case 502:
  6302. return "Bad Gateway";
  6303. case 503:
  6304. return "Service Unavailable";
  6305. #if MG_ENABLE_EXTRA_ERRORS_DESC
  6306. case 100:
  6307. return "Continue";
  6308. case 101:
  6309. return "Switching Protocols";
  6310. case 102:
  6311. return "Processing";
  6312. case 200:
  6313. return "OK";
  6314. case 201:
  6315. return "Created";
  6316. case 202:
  6317. return "Accepted";
  6318. case 203:
  6319. return "Non-Authoritative Information";
  6320. case 204:
  6321. return "No Content";
  6322. case 205:
  6323. return "Reset Content";
  6324. case 207:
  6325. return "Multi-Status";
  6326. case 208:
  6327. return "Already Reported";
  6328. case 226:
  6329. return "IM Used";
  6330. case 300:
  6331. return "Multiple Choices";
  6332. case 303:
  6333. return "See Other";
  6334. case 304:
  6335. return "Not Modified";
  6336. case 305:
  6337. return "Use Proxy";
  6338. case 306:
  6339. return "Switch Proxy";
  6340. case 307:
  6341. return "Temporary Redirect";
  6342. case 308:
  6343. return "Permanent Redirect";
  6344. case 402:
  6345. return "Payment Required";
  6346. case 405:
  6347. return "Method Not Allowed";
  6348. case 406:
  6349. return "Not Acceptable";
  6350. case 407:
  6351. return "Proxy Authentication Required";
  6352. case 408:
  6353. return "Request Timeout";
  6354. case 409:
  6355. return "Conflict";
  6356. case 410:
  6357. return "Gone";
  6358. case 411:
  6359. return "Length Required";
  6360. case 412:
  6361. return "Precondition Failed";
  6362. case 413:
  6363. return "Payload Too Large";
  6364. case 414:
  6365. return "URI Too Long";
  6366. case 415:
  6367. return "Unsupported Media Type";
  6368. case 417:
  6369. return "Expectation Failed";
  6370. case 422:
  6371. return "Unprocessable Entity";
  6372. case 423:
  6373. return "Locked";
  6374. case 424:
  6375. return "Failed Dependency";
  6376. case 426:
  6377. return "Upgrade Required";
  6378. case 428:
  6379. return "Precondition Required";
  6380. case 429:
  6381. return "Too Many Requests";
  6382. case 431:
  6383. return "Request Header Fields Too Large";
  6384. case 451:
  6385. return "Unavailable For Legal Reasons";
  6386. case 501:
  6387. return "Not Implemented";
  6388. case 504:
  6389. return "Gateway Timeout";
  6390. case 505:
  6391. return "HTTP Version Not Supported";
  6392. case 506:
  6393. return "Variant Also Negotiates";
  6394. case 507:
  6395. return "Insufficient Storage";
  6396. case 508:
  6397. return "Loop Detected";
  6398. case 510:
  6399. return "Not Extended";
  6400. case 511:
  6401. return "Network Authentication Required";
  6402. #endif /* MG_ENABLE_EXTRA_ERRORS_DESC */
  6403. default:
  6404. return "OK";
  6405. }
  6406. }
  6407. void mg_send_response_line_s(struct mg_connection *nc, int status_code,
  6408. const struct mg_str extra_headers) {
  6409. mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code,
  6410. mg_status_message(status_code));
  6411. #ifndef MG_HIDE_SERVER_INFO
  6412. mg_printf(nc, "Server: %s\r\n", mg_version_header);
  6413. #endif
  6414. if (extra_headers.len > 0) {
  6415. mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p);
  6416. }
  6417. }
  6418. void mg_send_response_line(struct mg_connection *nc, int status_code,
  6419. const char *extra_headers) {
  6420. mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
  6421. }
  6422. void mg_http_send_redirect(struct mg_connection *nc, int status_code,
  6423. const struct mg_str location,
  6424. const struct mg_str extra_headers) {
  6425. char bbody[100], *pbody = bbody;
  6426. int bl = mg_asprintf(&pbody, sizeof(bbody),
  6427. "<p>Moved <a href='%.*s'>here</a>.\r\n",
  6428. (int) location.len, location.p);
  6429. char bhead[150], *phead = bhead;
  6430. mg_asprintf(&phead, sizeof(bhead),
  6431. "Location: %.*s\r\n"
  6432. "Content-Type: text/html\r\n"
  6433. "Content-Length: %d\r\n"
  6434. "Cache-Control: no-cache\r\n"
  6435. "%.*s%s",
  6436. (int) location.len, location.p, bl, (int) extra_headers.len,
  6437. extra_headers.p, (extra_headers.len > 0 ? "\r\n" : ""));
  6438. mg_send_response_line(nc, status_code, phead);
  6439. if (phead != bhead) MG_FREE(phead);
  6440. mg_send(nc, pbody, bl);
  6441. if (pbody != bbody) MG_FREE(pbody);
  6442. }
  6443. void mg_send_head(struct mg_connection *c, int status_code,
  6444. int64_t content_length, const char *extra_headers) {
  6445. mg_send_response_line(c, status_code, extra_headers);
  6446. if (content_length < 0) {
  6447. mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
  6448. } else {
  6449. mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
  6450. }
  6451. mg_send(c, "\r\n", 2);
  6452. }
  6453. void mg_http_send_error(struct mg_connection *nc, int code,
  6454. const char *reason) {
  6455. if (!reason) reason = mg_status_message(code);
  6456. LOG(LL_DEBUG, ("%p %d %s", nc, code, reason));
  6457. mg_send_head(nc, code, strlen(reason),
  6458. "Content-Type: text/plain\r\nConnection: close");
  6459. mg_send(nc, reason, strlen(reason));
  6460. nc->flags |= MG_F_SEND_AND_CLOSE;
  6461. }
  6462. #if MG_ENABLE_FILESYSTEM
  6463. static void mg_http_construct_etag(char *buf, size_t buf_len,
  6464. const cs_stat_t *st) {
  6465. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
  6466. (int64_t) st->st_size);
  6467. }
  6468. #ifndef WINCE
  6469. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  6470. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  6471. }
  6472. #else
  6473. /* Look wince_lib.c for WindowsCE implementation */
  6474. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t);
  6475. #endif
  6476. static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
  6477. int64_t *b) {
  6478. /*
  6479. * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
  6480. * so we have this. Ugh.
  6481. */
  6482. int result;
  6483. char *p = (char *) MG_MALLOC(header->len + 1);
  6484. if (p == NULL) return 0;
  6485. memcpy(p, header->p, header->len);
  6486. p[header->len] = '\0';
  6487. result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6488. MG_FREE(p);
  6489. return result;
  6490. }
  6491. void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
  6492. const char *path, const struct mg_str mime_type,
  6493. const struct mg_str extra_headers) {
  6494. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  6495. cs_stat_t st;
  6496. LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p));
  6497. if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) {
  6498. int code, err = mg_get_errno();
  6499. switch (err) {
  6500. case EACCES:
  6501. code = 403;
  6502. break;
  6503. case ENOENT:
  6504. code = 404;
  6505. break;
  6506. default:
  6507. code = 500;
  6508. };
  6509. mg_http_send_error(nc, code, "Open failed");
  6510. } else {
  6511. char etag[50], current_time[50], last_modified[50], range[70];
  6512. time_t t = (time_t) mg_time();
  6513. int64_t r1 = 0, r2 = 0, cl = st.st_size;
  6514. struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
  6515. int n, status_code = 200;
  6516. /* Handle Range header */
  6517. range[0] = '\0';
  6518. if (range_hdr != NULL &&
  6519. (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  6520. r2 >= 0) {
  6521. /* If range is specified like "400-", set second limit to content len */
  6522. if (n == 1) {
  6523. r2 = cl - 1;
  6524. }
  6525. if (r1 > r2 || r2 >= cl) {
  6526. status_code = 416;
  6527. cl = 0;
  6528. snprintf(range, sizeof(range),
  6529. "Content-Range: bytes */%" INT64_FMT "\r\n",
  6530. (int64_t) st.st_size);
  6531. } else {
  6532. status_code = 206;
  6533. cl = r2 - r1 + 1;
  6534. snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
  6535. "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6536. r1, r1 + cl - 1, (int64_t) st.st_size);
  6537. #if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
  6538. _XOPEN_SOURCE >= 600
  6539. fseeko(pd->file.fp, r1, SEEK_SET);
  6540. #else
  6541. fseek(pd->file.fp, (long) r1, SEEK_SET);
  6542. #endif
  6543. }
  6544. }
  6545. #if !MG_DISABLE_HTTP_KEEP_ALIVE
  6546. {
  6547. struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection");
  6548. if (conn_hdr != NULL) {
  6549. pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0);
  6550. } else {
  6551. pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0);
  6552. }
  6553. }
  6554. #endif
  6555. mg_http_construct_etag(etag, sizeof(etag), &st);
  6556. mg_gmt_time_string(current_time, sizeof(current_time), &t);
  6557. mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime);
  6558. /*
  6559. * Content length casted to size_t because:
  6560. * 1) that's the maximum buffer size anyway
  6561. * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
  6562. * position
  6563. * TODO(mkm): fix ESP8266 RTOS SDK
  6564. */
  6565. mg_send_response_line_s(nc, status_code, extra_headers);
  6566. mg_printf(nc,
  6567. "Date: %s\r\n"
  6568. "Last-Modified: %s\r\n"
  6569. "Accept-Ranges: bytes\r\n"
  6570. "Content-Type: %.*s\r\n"
  6571. "Connection: %s\r\n"
  6572. "Content-Length: %" SIZE_T_FMT
  6573. "\r\n"
  6574. "%sEtag: %s\r\n\r\n",
  6575. current_time, last_modified, (int) mime_type.len, mime_type.p,
  6576. (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
  6577. etag);
  6578. pd->file.cl = cl;
  6579. pd->file.type = DATA_FILE;
  6580. mg_http_transfer_file_data(nc);
  6581. }
  6582. }
  6583. static void mg_http_serve_file2(struct mg_connection *nc, const char *path,
  6584. struct http_message *hm,
  6585. struct mg_serve_http_opts *opts) {
  6586. #if MG_ENABLE_HTTP_SSI
  6587. if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) {
  6588. mg_handle_ssi_request(nc, hm, path, opts);
  6589. return;
  6590. }
  6591. #endif
  6592. mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts),
  6593. mg_mk_str(opts->extra_headers));
  6594. }
  6595. #endif
  6596. int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
  6597. int is_form_url_encoded) {
  6598. int i, j, a, b;
  6599. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  6600. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  6601. if (src[i] == '%') {
  6602. if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
  6603. isxdigit(*(const unsigned char *) (src + i + 2))) {
  6604. a = tolower(*(const unsigned char *) (src + i + 1));
  6605. b = tolower(*(const unsigned char *) (src + i + 2));
  6606. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  6607. i += 2;
  6608. } else {
  6609. return -1;
  6610. }
  6611. } else if (is_form_url_encoded && src[i] == '+') {
  6612. dst[j] = ' ';
  6613. } else {
  6614. dst[j] = src[i];
  6615. }
  6616. }
  6617. dst[j] = '\0'; /* Null-terminate the destination */
  6618. return i >= src_len ? j : -1;
  6619. }
  6620. int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
  6621. size_t dst_len) {
  6622. const char *p, *e, *s;
  6623. size_t name_len;
  6624. int len;
  6625. /*
  6626. * According to the documentation function returns negative
  6627. * value in case of error. For debug purposes it returns:
  6628. * -1 - src is wrong (NUUL)
  6629. * -2 - dst is wrong (NULL)
  6630. * -3 - failed to decode url or dst is to small
  6631. * -4 - name does not exist
  6632. */
  6633. if (dst == NULL || dst_len == 0) {
  6634. len = -2;
  6635. } else if (buf->p == NULL || name == NULL || buf->len == 0) {
  6636. len = -1;
  6637. dst[0] = '\0';
  6638. } else {
  6639. name_len = strlen(name);
  6640. e = buf->p + buf->len;
  6641. len = -4;
  6642. dst[0] = '\0';
  6643. for (p = buf->p; p + name_len < e; p++) {
  6644. if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
  6645. !mg_ncasecmp(name, p, name_len)) {
  6646. p += name_len + 1;
  6647. s = (const char *) memchr(p, '&', (size_t)(e - p));
  6648. if (s == NULL) {
  6649. s = e;
  6650. }
  6651. len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
  6652. /* -1 means: failed to decode or dst is too small */
  6653. if (len == -1) {
  6654. len = -3;
  6655. }
  6656. break;
  6657. }
  6658. }
  6659. }
  6660. return len;
  6661. }
  6662. void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
  6663. char chunk_size[50];
  6664. int n;
  6665. n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
  6666. mg_send(nc, chunk_size, n);
  6667. mg_send(nc, buf, len);
  6668. mg_send(nc, "\r\n", 2);
  6669. }
  6670. void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
  6671. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  6672. int len;
  6673. va_list ap;
  6674. va_start(ap, fmt);
  6675. len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
  6676. va_end(ap);
  6677. if (len >= 0) {
  6678. mg_send_http_chunk(nc, buf, len);
  6679. }
  6680. /* LCOV_EXCL_START */
  6681. if (buf != mem && buf != NULL) {
  6682. MG_FREE(buf);
  6683. }
  6684. /* LCOV_EXCL_STOP */
  6685. }
  6686. void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
  6687. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  6688. int i, j, len;
  6689. va_list ap;
  6690. va_start(ap, fmt);
  6691. len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
  6692. va_end(ap);
  6693. if (len >= 0) {
  6694. for (i = j = 0; i < len; i++) {
  6695. if (buf[i] == '<' || buf[i] == '>') {
  6696. mg_send(nc, buf + j, i - j);
  6697. mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4);
  6698. j = i + 1;
  6699. }
  6700. }
  6701. mg_send(nc, buf + j, i - j);
  6702. }
  6703. /* LCOV_EXCL_START */
  6704. if (buf != mem && buf != NULL) {
  6705. MG_FREE(buf);
  6706. }
  6707. /* LCOV_EXCL_STOP */
  6708. }
  6709. static void mg_http_parse_header_internal(struct mg_str *hdr,
  6710. const char *var_name,
  6711. struct altbuf *ab) {
  6712. int ch = ' ', ch1 = ',', ch2 = ';', n = strlen(var_name);
  6713. const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
  6714. /* Find where variable starts */
  6715. for (s = hdr->p; s != NULL && s + n < end; s++) {
  6716. if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') &&
  6717. s[n] == '=' && !strncmp(s, var_name, n))
  6718. break;
  6719. }
  6720. if (s != NULL && &s[n + 1] < end) {
  6721. s += n + 1;
  6722. if (*s == '"' || *s == '\'') {
  6723. ch = ch1 = ch2 = *s++;
  6724. }
  6725. p = s;
  6726. while (p < end && p[0] != ch && p[0] != ch1 && p[0] != ch2) {
  6727. if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
  6728. altbuf_append(ab, *p++);
  6729. }
  6730. if (ch != ' ' && *p != ch) {
  6731. altbuf_reset(ab);
  6732. }
  6733. }
  6734. /* If there is some data, append a NUL. */
  6735. if (ab->len > 0) {
  6736. altbuf_append(ab, '\0');
  6737. }
  6738. }
  6739. int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf,
  6740. size_t buf_size) {
  6741. struct altbuf ab;
  6742. altbuf_init(&ab, *buf, buf_size);
  6743. if (hdr == NULL) return 0;
  6744. if (*buf != NULL && buf_size > 0) *buf[0] = '\0';
  6745. mg_http_parse_header_internal(hdr, var_name, &ab);
  6746. /*
  6747. * Get a (trimmed) buffer, and return a len without a NUL byte which might
  6748. * have been added.
  6749. */
  6750. *buf = altbuf_get_buf(&ab, 1 /* trim */);
  6751. return ab.len > 0 ? ab.len - 1 : 0;
  6752. }
  6753. int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
  6754. size_t buf_size) {
  6755. char *buf2 = buf;
  6756. int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size);
  6757. if (buf2 != buf) {
  6758. /* Buffer was not enough and was reallocated: free it and just return 0 */
  6759. MG_FREE(buf2);
  6760. return 0;
  6761. }
  6762. return len;
  6763. }
  6764. int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
  6765. char *pass, size_t pass_len) {
  6766. struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
  6767. if (hdr == NULL) return -1;
  6768. return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len);
  6769. }
  6770. int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
  6771. char *pass, size_t pass_len) {
  6772. char *buf = NULL;
  6773. char fmt[64];
  6774. int res = 0;
  6775. if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1;
  6776. buf = (char *) MG_MALLOC(hdr->len);
  6777. cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
  6778. /* e.g. "%123[^:]:%321[^\n]" */
  6779. snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]",
  6780. user_len - 1, pass_len - 1);
  6781. if (sscanf(buf, fmt, user, pass) == 0) {
  6782. res = -1;
  6783. }
  6784. MG_FREE(buf);
  6785. return res;
  6786. }
  6787. #if MG_ENABLE_FILESYSTEM
  6788. static int mg_is_file_hidden(const char *path,
  6789. const struct mg_serve_http_opts *opts,
  6790. int exclude_specials) {
  6791. const char *p1 = opts->per_directory_auth_file;
  6792. const char *p2 = opts->hidden_file_pattern;
  6793. /* Strip directory path from the file name */
  6794. const char *pdir = strrchr(path, DIRSEP);
  6795. if (pdir != NULL) {
  6796. path = pdir + 1;
  6797. }
  6798. return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
  6799. (p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) ||
  6800. (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
  6801. }
  6802. #if !MG_DISABLE_HTTP_DIGEST_AUTH
  6803. #ifndef MG_EXT_MD5
  6804. void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
  6805. const size_t *msg_lens, uint8_t *digest) {
  6806. size_t i;
  6807. cs_md5_ctx md5_ctx;
  6808. cs_md5_init(&md5_ctx);
  6809. for (i = 0; i < num_msgs; i++) {
  6810. cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]);
  6811. }
  6812. cs_md5_final(digest, &md5_ctx);
  6813. }
  6814. #else
  6815. extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
  6816. const size_t *msg_lens, uint8_t *digest);
  6817. #endif
  6818. void cs_md5(char buf[33], ...) {
  6819. unsigned char hash[16];
  6820. const uint8_t *msgs[20], *p;
  6821. size_t msg_lens[20];
  6822. size_t num_msgs = 0;
  6823. va_list ap;
  6824. va_start(ap, buf);
  6825. while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
  6826. msgs[num_msgs] = p;
  6827. msg_lens[num_msgs] = va_arg(ap, size_t);
  6828. num_msgs++;
  6829. }
  6830. va_end(ap);
  6831. mg_hash_md5_v(num_msgs, msgs, msg_lens, hash);
  6832. cs_to_hex(buf, hash, sizeof(hash));
  6833. }
  6834. static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
  6835. size_t uri_len, const char *ha1, size_t ha1_len,
  6836. const char *nonce, size_t nonce_len, const char *nc,
  6837. size_t nc_len, const char *cnonce, size_t cnonce_len,
  6838. const char *qop, size_t qop_len, char *resp) {
  6839. static const char colon[] = ":";
  6840. static const size_t one = 1;
  6841. char ha2[33];
  6842. cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
  6843. cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
  6844. nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
  6845. colon, one, ha2, sizeof(ha2) - 1, NULL);
  6846. }
  6847. int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
  6848. const char *method, const char *uri,
  6849. const char *auth_domain, const char *user,
  6850. const char *passwd, const char *nonce) {
  6851. static const char colon[] = ":", qop[] = "auth";
  6852. static const size_t one = 1;
  6853. char ha1[33], resp[33], cnonce[40];
  6854. snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time());
  6855. cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
  6856. (size_t) strlen(auth_domain), colon, one, passwd,
  6857. (size_t) strlen(passwd), NULL);
  6858. mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
  6859. nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop,
  6860. sizeof(qop) - 1, resp);
  6861. return snprintf(buf, buf_len,
  6862. "Authorization: Digest username=\"%s\","
  6863. "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
  6864. "nonce=%s,response=%s\r\n",
  6865. user, auth_domain, uri, qop, cnonce, nonce, resp);
  6866. }
  6867. /*
  6868. * Check for authentication timeout.
  6869. * Clients send time stamp encoded in nonce. Make sure it is not too old,
  6870. * to prevent replay attacks.
  6871. * Assumption: nonce is a hexadecimal number of seconds since 1970.
  6872. */
  6873. static int mg_check_nonce(const char *nonce) {
  6874. unsigned long now = (unsigned long) mg_time();
  6875. unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
  6876. return (now >= val) && (now - val < 60 * 60);
  6877. }
  6878. int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
  6879. FILE *fp) {
  6880. int ret = 0;
  6881. struct mg_str *hdr;
  6882. char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200],
  6883. qop_buf[20], nc_buf[20], nonce_buf[16];
  6884. char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf,
  6885. *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf;
  6886. /* Parse "Authorization:" header, fail fast on parse error */
  6887. if (hm == NULL || fp == NULL ||
  6888. (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
  6889. mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) ==
  6890. 0 ||
  6891. mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 ||
  6892. mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) ==
  6893. 0 ||
  6894. mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 ||
  6895. mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 ||
  6896. mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 ||
  6897. mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 ||
  6898. mg_check_nonce(nonce) == 0) {
  6899. ret = 0;
  6900. goto clean;
  6901. }
  6902. /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
  6903. ret = mg_check_digest_auth(
  6904. hm->method,
  6905. mg_mk_str_n(
  6906. hm->uri.p,
  6907. hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)),
  6908. mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response),
  6909. mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain),
  6910. fp);
  6911. clean:
  6912. if (username != username_buf) MG_FREE(username);
  6913. if (cnonce != cnonce_buf) MG_FREE(cnonce);
  6914. if (response != response_buf) MG_FREE(response);
  6915. if (uri != uri_buf) MG_FREE(uri);
  6916. if (qop != qop_buf) MG_FREE(qop);
  6917. if (nc != nc_buf) MG_FREE(nc);
  6918. if (nonce != nonce_buf) MG_FREE(nonce);
  6919. return ret;
  6920. }
  6921. int mg_check_digest_auth(struct mg_str method, struct mg_str uri,
  6922. struct mg_str username, struct mg_str cnonce,
  6923. struct mg_str response, struct mg_str qop,
  6924. struct mg_str nc, struct mg_str nonce,
  6925. struct mg_str auth_domain, FILE *fp) {
  6926. char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
  6927. char exp_resp[33];
  6928. /*
  6929. * Read passwords file line by line. If should have htdigest format,
  6930. * i.e. each line should be a colon-separated sequence:
  6931. * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
  6932. */
  6933. while (fgets(buf, sizeof(buf), fp) != NULL) {
  6934. if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
  6935. mg_vcmp(&username, f_user) == 0 &&
  6936. mg_vcmp(&auth_domain, f_domain) == 0) {
  6937. /* Username and domain matched, check the password */
  6938. mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1),
  6939. nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len,
  6940. qop.p, qop.len, exp_resp);
  6941. LOG(LL_DEBUG, ("%.*s %s %.*s %s", (int) username.len, username.p,
  6942. f_domain, (int) response.len, response.p, exp_resp));
  6943. return mg_ncasecmp(response.p, exp_resp, strlen(exp_resp)) == 0;
  6944. }
  6945. }
  6946. /* None of the entries in the passwords file matched - return failure */
  6947. return 0;
  6948. }
  6949. int mg_http_is_authorized(struct http_message *hm, struct mg_str path,
  6950. const char *domain, const char *passwords_file,
  6951. int flags) {
  6952. char buf[MG_MAX_PATH];
  6953. const char *p;
  6954. FILE *fp;
  6955. int authorized = 1;
  6956. if (domain != NULL && passwords_file != NULL) {
  6957. if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) {
  6958. fp = mg_fopen(passwords_file, "r");
  6959. } else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) {
  6960. snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP,
  6961. passwords_file);
  6962. fp = mg_fopen(buf, "r");
  6963. } else {
  6964. p = strrchr(path.p, DIRSEP);
  6965. if (p == NULL) p = path.p;
  6966. snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP,
  6967. passwords_file);
  6968. fp = mg_fopen(buf, "r");
  6969. }
  6970. if (fp != NULL) {
  6971. authorized = mg_http_check_digest_auth(hm, domain, fp);
  6972. fclose(fp);
  6973. } else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) {
  6974. authorized = 0;
  6975. }
  6976. }
  6977. LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p,
  6978. passwords_file ? passwords_file : "", flags, authorized));
  6979. return authorized;
  6980. }
  6981. #else
  6982. int mg_http_is_authorized(struct http_message *hm, const struct mg_str path,
  6983. const char *domain, const char *passwords_file,
  6984. int flags) {
  6985. (void) hm;
  6986. (void) path;
  6987. (void) domain;
  6988. (void) passwords_file;
  6989. (void) flags;
  6990. return 1;
  6991. }
  6992. #endif
  6993. #if MG_ENABLE_DIRECTORY_LISTING
  6994. static void mg_escape(const char *src, char *dst, size_t dst_len) {
  6995. size_t n = 0;
  6996. while (*src != '\0' && n + 5 < dst_len) {
  6997. unsigned char ch = *(unsigned char *) src++;
  6998. if (ch == '<') {
  6999. n += snprintf(dst + n, dst_len - n, "%s", "&lt;");
  7000. } else {
  7001. dst[n++] = ch;
  7002. }
  7003. }
  7004. dst[n] = '\0';
  7005. }
  7006. static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
  7007. cs_stat_t *stp) {
  7008. char size[64], mod[64], path[MG_MAX_PATH];
  7009. int64_t fsize = stp->st_size;
  7010. int is_dir = S_ISDIR(stp->st_mode);
  7011. const char *slash = is_dir ? "/" : "";
  7012. struct mg_str href;
  7013. if (is_dir) {
  7014. snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
  7015. } else {
  7016. /*
  7017. * We use (double) cast below because MSVC 6 compiler cannot
  7018. * convert unsigned __int64 to double.
  7019. */
  7020. if (fsize < 1024) {
  7021. snprintf(size, sizeof(size), "%d", (int) fsize);
  7022. } else if (fsize < 0x100000) {
  7023. snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
  7024. } else if (fsize < 0x40000000) {
  7025. snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
  7026. } else {
  7027. snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
  7028. }
  7029. }
  7030. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
  7031. mg_escape(file_name, path, sizeof(path));
  7032. href = mg_url_encode(mg_mk_str(file_name));
  7033. mg_printf_http_chunk(nc,
  7034. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7035. "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
  7036. href.p, slash, path, slash, mod, is_dir ? -1 : fsize,
  7037. size);
  7038. free((void *) href.p);
  7039. }
  7040. static void mg_scan_directory(struct mg_connection *nc, const char *dir,
  7041. const struct mg_serve_http_opts *opts,
  7042. void (*func)(struct mg_connection *, const char *,
  7043. cs_stat_t *)) {
  7044. char path[MG_MAX_PATH + 1];
  7045. cs_stat_t st;
  7046. struct dirent *dp;
  7047. DIR *dirp;
  7048. LOG(LL_DEBUG, ("%p [%s]", nc, dir));
  7049. if ((dirp = (opendir(dir))) != NULL) {
  7050. while ((dp = readdir(dirp)) != NULL) {
  7051. /* Do not show current dir and hidden files */
  7052. if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
  7053. continue;
  7054. }
  7055. snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
  7056. if (mg_stat(path, &st) == 0) {
  7057. func(nc, (const char *) dp->d_name, &st);
  7058. }
  7059. }
  7060. closedir(dirp);
  7061. } else {
  7062. LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno()));
  7063. }
  7064. }
  7065. static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
  7066. struct http_message *hm,
  7067. struct mg_serve_http_opts *opts) {
  7068. static const char *sort_js_code =
  7069. "<script>function srt(tb, sc, so, d) {"
  7070. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  7071. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  7072. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  7073. "t1 = a.cells[2].getAttribute('name'), "
  7074. "t2 = b.cells[2].getAttribute('name'); "
  7075. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  7076. "n1 ? parseInt(n2) - parseInt(n1) : "
  7077. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  7078. static const char *sort_js_code2 =
  7079. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  7080. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  7081. "};"
  7082. "window.onload = function() {"
  7083. "var tb = document.getElementById('tb');"
  7084. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  7085. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  7086. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  7087. "sc = c; ev.preventDefault();}};"
  7088. "srt(tb, sc, so, true);"
  7089. "}"
  7090. "</script>";
  7091. mg_send_response_line(nc, 200, opts->extra_headers);
  7092. mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
  7093. "Content-Type", "text/html; charset=utf-8");
  7094. mg_printf_http_chunk(
  7095. nc,
  7096. "<html><head><title>Index of %.*s</title>%s%s"
  7097. "<style>th,td {text-align: left; padding-right: 1em; "
  7098. "font-family: monospace; }</style></head>\n"
  7099. "<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>"
  7100. "<tr><th><a href=# rel=0>Name</a></th><th>"
  7101. "<a href=# rel=1>Modified</a</th>"
  7102. "<th><a href=# rel=2>Size</a></th></tr>"
  7103. "<tr><td colspan=3><hr></td></tr>\n"
  7104. "</thead>\n"
  7105. "<tbody id=tb>",
  7106. (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
  7107. (int) hm->uri.len, hm->uri.p);
  7108. mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
  7109. mg_printf_http_chunk(nc,
  7110. "</tbody><tr><td colspan=3><hr></td></tr>\n"
  7111. "</table>\n"
  7112. "<address>%s</address>\n"
  7113. "</body></html>",
  7114. mg_version_header);
  7115. mg_send_http_chunk(nc, "", 0);
  7116. /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
  7117. nc->flags |= MG_F_SEND_AND_CLOSE;
  7118. }
  7119. #endif /* MG_ENABLE_DIRECTORY_LISTING */
  7120. /*
  7121. * Given a directory path, find one of the files specified in the
  7122. * comma-separated list of index files `list`.
  7123. * First found index file wins. If an index file is found, then gets
  7124. * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
  7125. * If index file is not found, then `path` and `stp` remain unchanged.
  7126. */
  7127. MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
  7128. char **index_file, cs_stat_t *stp) {
  7129. struct mg_str vec;
  7130. size_t path_len = strlen(path);
  7131. int found = 0;
  7132. *index_file = NULL;
  7133. /* Traverse index files list. For each entry, append it to the given */
  7134. /* path and see if the file exists. If it exists, break the loop */
  7135. while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
  7136. cs_stat_t st;
  7137. size_t len = path_len + 1 + vec.len + 1;
  7138. *index_file = (char *) MG_REALLOC(*index_file, len);
  7139. if (*index_file == NULL) break;
  7140. snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
  7141. /* Does it exist? Is it a file? */
  7142. if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
  7143. /* Yes it does, break the loop */
  7144. *stp = st;
  7145. found = 1;
  7146. break;
  7147. }
  7148. }
  7149. if (!found) {
  7150. MG_FREE(*index_file);
  7151. *index_file = NULL;
  7152. }
  7153. LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : "")));
  7154. }
  7155. #if MG_ENABLE_HTTP_URL_REWRITES
  7156. static int mg_http_send_port_based_redirect(
  7157. struct mg_connection *c, struct http_message *hm,
  7158. const struct mg_serve_http_opts *opts) {
  7159. const char *rewrites = opts->url_rewrites;
  7160. struct mg_str a, b;
  7161. char local_port[20] = {'%'};
  7162. mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
  7163. MG_SOCK_STRINGIFY_PORT);
  7164. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  7165. if (mg_vcmp(&a, local_port) == 0) {
  7166. mg_send_response_line(c, 301, NULL);
  7167. mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
  7168. (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
  7169. hm->uri.p);
  7170. return 1;
  7171. }
  7172. }
  7173. return 0;
  7174. }
  7175. static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev,
  7176. void *ev_data MG_UD_ARG(void *user_data)) {
  7177. struct http_message *hm = (struct http_message *) ev_data;
  7178. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  7179. if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
  7180. DBG(("%p: upstream closed", nc));
  7181. return;
  7182. }
  7183. switch (ev) {
  7184. case MG_EV_CONNECT:
  7185. if (*(int *) ev_data != 0) {
  7186. mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL);
  7187. }
  7188. break;
  7189. /* TODO(mkm): handle streaming */
  7190. case MG_EV_HTTP_REPLY:
  7191. mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p,
  7192. hm->message.len);
  7193. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  7194. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  7195. break;
  7196. case MG_EV_CLOSE:
  7197. pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
  7198. break;
  7199. }
  7200. #if MG_ENABLE_CALLBACK_USERDATA
  7201. (void) user_data;
  7202. #endif
  7203. }
  7204. void mg_http_reverse_proxy(struct mg_connection *nc,
  7205. const struct http_message *hm, struct mg_str mount,
  7206. struct mg_str upstream) {
  7207. struct mg_connection *be;
  7208. char burl[256], *purl = burl;
  7209. int i;
  7210. const char *error;
  7211. struct mg_connect_opts opts;
  7212. struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR;
  7213. memset(&opts, 0, sizeof(opts));
  7214. opts.error_string = &error;
  7215. mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p,
  7216. (int) (hm->uri.len - mount.len), hm->uri.p + mount.len);
  7217. be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL),
  7218. opts, "http", NULL, "https", NULL, purl, &path,
  7219. &user_info, &host);
  7220. LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len,
  7221. hm->uri.p, purl, (int) mount.len, mount.p));
  7222. if (be == NULL) {
  7223. LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error));
  7224. mg_http_send_error(nc, 502, NULL);
  7225. goto cleanup;
  7226. }
  7227. /* link connections to each other, they must live and die together */
  7228. mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc;
  7229. mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be;
  7230. /* send request upstream */
  7231. mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p,
  7232. (int) path.len, path.p);
  7233. mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p);
  7234. for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) {
  7235. struct mg_str hn = hm->header_names[i];
  7236. struct mg_str hv = hm->header_values[i];
  7237. /* we rewrite the host header */
  7238. if (mg_vcasecmp(&hn, "Host") == 0) continue;
  7239. /*
  7240. * Don't pass chunked transfer encoding to the client because hm->body is
  7241. * already dechunked when we arrive here.
  7242. */
  7243. if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 &&
  7244. mg_vcasecmp(&hv, "chunked") == 0) {
  7245. mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len);
  7246. continue;
  7247. }
  7248. /* We don't support proxying Expect: 100-continue. */
  7249. if (mg_vcasecmp(&hn, "Expect") == 0 &&
  7250. mg_vcasecmp(&hv, "100-continue") == 0) {
  7251. continue;
  7252. }
  7253. mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
  7254. }
  7255. mg_send(be, "\r\n", 2);
  7256. mg_send(be, hm->body.p, hm->body.len);
  7257. cleanup:
  7258. if (purl != burl) MG_FREE(purl);
  7259. }
  7260. static int mg_http_handle_forwarding(struct mg_connection *nc,
  7261. struct http_message *hm,
  7262. const struct mg_serve_http_opts *opts) {
  7263. const char *rewrites = opts->url_rewrites;
  7264. struct mg_str a, b;
  7265. struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://");
  7266. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  7267. if (mg_strncmp(a, hm->uri, a.len) == 0) {
  7268. if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) {
  7269. mg_http_reverse_proxy(nc, hm, a, b);
  7270. return 1;
  7271. }
  7272. }
  7273. }
  7274. return 0;
  7275. }
  7276. #endif /* MG_ENABLE_FILESYSTEM */
  7277. MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
  7278. const struct mg_serve_http_opts *opts,
  7279. char **local_path,
  7280. struct mg_str *remainder) {
  7281. int ok = 1;
  7282. const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
  7283. struct mg_str root = {NULL, 0};
  7284. const char *file_uri_start = cp;
  7285. *local_path = NULL;
  7286. remainder->p = NULL;
  7287. remainder->len = 0;
  7288. { /* 1. Determine which root to use. */
  7289. #if MG_ENABLE_HTTP_URL_REWRITES
  7290. const char *rewrites = opts->url_rewrites;
  7291. #else
  7292. const char *rewrites = "";
  7293. #endif
  7294. struct mg_str *hh = mg_get_http_header(hm, "Host");
  7295. struct mg_str a, b;
  7296. /* Check rewrites first. */
  7297. while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
  7298. if (a.len > 1 && a.p[0] == '@') {
  7299. /* Host rewrite. */
  7300. if (hh != NULL && hh->len == a.len - 1 &&
  7301. mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
  7302. root = b;
  7303. break;
  7304. }
  7305. } else {
  7306. /* Regular rewrite, URI=directory */
  7307. size_t match_len = mg_match_prefix_n(a, hm->uri);
  7308. if (match_len > 0) {
  7309. file_uri_start = hm->uri.p + match_len;
  7310. if (*file_uri_start == '/' || file_uri_start == cp_end) {
  7311. /* Match ended at component boundary, ok. */
  7312. } else if (*(file_uri_start - 1) == '/') {
  7313. /* Pattern ends with '/', backtrack. */
  7314. file_uri_start--;
  7315. } else {
  7316. /* No match: must fall on the component boundary. */
  7317. continue;
  7318. }
  7319. root = b;
  7320. break;
  7321. }
  7322. }
  7323. }
  7324. /* If no rewrite rules matched, use DAV or regular document root. */
  7325. if (root.p == NULL) {
  7326. #if MG_ENABLE_HTTP_WEBDAV
  7327. if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
  7328. root.p = opts->dav_document_root;
  7329. root.len = strlen(opts->dav_document_root);
  7330. } else
  7331. #endif
  7332. {
  7333. root.p = opts->document_root;
  7334. root.len = strlen(opts->document_root);
  7335. }
  7336. }
  7337. assert(root.p != NULL && root.len > 0);
  7338. }
  7339. { /* 2. Find where in the canonical URI path the local path ends. */
  7340. const char *u = file_uri_start + 1;
  7341. char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
  7342. char *lp_end = lp + root.len + hm->uri.len + 1;
  7343. char *p = lp, *ps;
  7344. int exists = 1;
  7345. if (lp == NULL) {
  7346. ok = 0;
  7347. goto out;
  7348. }
  7349. memcpy(p, root.p, root.len);
  7350. p += root.len;
  7351. if (*(p - 1) == DIRSEP) p--;
  7352. *p = '\0';
  7353. ps = p;
  7354. /* Chop off URI path components one by one and build local path. */
  7355. while (u <= cp_end) {
  7356. const char *next = u;
  7357. struct mg_str component;
  7358. if (exists) {
  7359. cs_stat_t st;
  7360. exists = (mg_stat(lp, &st) == 0);
  7361. if (exists && S_ISREG(st.st_mode)) {
  7362. /* We found the terminal, the rest of the URI (if any) is path_info.
  7363. */
  7364. if (*(u - 1) == '/') u--;
  7365. break;
  7366. }
  7367. }
  7368. if (u >= cp_end) break;
  7369. parse_uri_component((const char **) &next, cp_end, "/", &component);
  7370. if (component.len > 0) {
  7371. int len;
  7372. memmove(p + 1, component.p, component.len);
  7373. len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
  7374. if (len <= 0) {
  7375. ok = 0;
  7376. break;
  7377. }
  7378. component.p = p + 1;
  7379. component.len = len;
  7380. if (mg_vcmp(&component, ".") == 0) {
  7381. /* Yum. */
  7382. } else if (mg_vcmp(&component, "..") == 0) {
  7383. while (p > ps && *p != DIRSEP) p--;
  7384. *p = '\0';
  7385. } else {
  7386. size_t i;
  7387. #ifdef _WIN32
  7388. /* On Windows, make sure it's valid Unicode (no funny stuff). */
  7389. wchar_t buf[MG_MAX_PATH * 2];
  7390. if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
  7391. DBG(("[%.*s] smells funny", (int) component.len, component.p));
  7392. ok = 0;
  7393. break;
  7394. }
  7395. #endif
  7396. *p++ = DIRSEP;
  7397. /* No NULs and DIRSEPs in the component (percent-encoded). */
  7398. for (i = 0; i < component.len; i++, p++) {
  7399. if (*p == '\0' || *p == DIRSEP
  7400. #ifdef _WIN32
  7401. /* On Windows, "/" is also accepted, so check for that too. */
  7402. ||
  7403. *p == '/'
  7404. #endif
  7405. ) {
  7406. ok = 0;
  7407. break;
  7408. }
  7409. }
  7410. }
  7411. }
  7412. u = next;
  7413. }
  7414. if (ok) {
  7415. *local_path = lp;
  7416. if (u > cp_end) u = cp_end;
  7417. remainder->p = u;
  7418. remainder->len = cp_end - u;
  7419. } else {
  7420. MG_FREE(lp);
  7421. }
  7422. }
  7423. out:
  7424. LOG(LL_DEBUG,
  7425. ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
  7426. *local_path ? *local_path : "", (int) remainder->len, remainder->p));
  7427. return ok;
  7428. }
  7429. static int mg_get_month_index(const char *s) {
  7430. static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  7431. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  7432. size_t i;
  7433. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  7434. if (!strcmp(s, month_names[i])) return (int) i;
  7435. return -1;
  7436. }
  7437. static int mg_num_leap_years(int year) {
  7438. return year / 4 - year / 100 + year / 400;
  7439. }
  7440. /* Parse UTC date-time string, and return the corresponding time_t value. */
  7441. MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
  7442. static const unsigned short days_before_month[] = {
  7443. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  7444. char month_str[32];
  7445. int second, minute, hour, day, month, year, leap_days, days;
  7446. time_t result = (time_t) 0;
  7447. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
  7448. &minute, &second) == 6) ||
  7449. (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
  7450. &minute, &second) == 6) ||
  7451. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
  7452. &hour, &minute, &second) == 6) ||
  7453. (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
  7454. &minute, &second) == 6)) &&
  7455. year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
  7456. leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
  7457. year -= 1970;
  7458. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  7459. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  7460. }
  7461. return result;
  7462. }
  7463. MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
  7464. struct mg_str *hdr;
  7465. if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
  7466. char etag[64];
  7467. mg_http_construct_etag(etag, sizeof(etag), st);
  7468. return mg_vcasecmp(hdr, etag) == 0;
  7469. } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
  7470. return st->st_mtime <= mg_parse_date_string(hdr->p);
  7471. } else {
  7472. return 0;
  7473. }
  7474. }
  7475. void mg_http_send_digest_auth_request(struct mg_connection *c,
  7476. const char *domain) {
  7477. mg_printf(c,
  7478. "HTTP/1.1 401 Unauthorized\r\n"
  7479. "WWW-Authenticate: Digest qop=\"auth\", "
  7480. "realm=\"%s\", nonce=\"%lx\"\r\n"
  7481. "Content-Length: 0\r\n\r\n",
  7482. domain, (unsigned long) mg_time());
  7483. }
  7484. static void mg_http_send_options(struct mg_connection *nc,
  7485. struct mg_serve_http_opts *opts) {
  7486. mg_send_response_line(nc, 200, opts->extra_headers);
  7487. mg_printf(nc, "%s",
  7488. "Allow: GET, POST, HEAD, CONNECT, OPTIONS"
  7489. #if MG_ENABLE_HTTP_WEBDAV
  7490. ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
  7491. #endif
  7492. "\r\n\r\n");
  7493. nc->flags |= MG_F_SEND_AND_CLOSE;
  7494. }
  7495. static int mg_is_creation_request(const struct http_message *hm) {
  7496. return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
  7497. }
  7498. MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
  7499. const struct mg_str *path_info,
  7500. struct http_message *hm,
  7501. struct mg_serve_http_opts *opts) {
  7502. int exists, is_directory, is_cgi;
  7503. #if MG_ENABLE_HTTP_WEBDAV
  7504. int is_dav = mg_is_dav_request(&hm->method);
  7505. #else
  7506. int is_dav = 0;
  7507. #endif
  7508. char *index_file = NULL;
  7509. cs_stat_t st;
  7510. exists = (mg_stat(path, &st) == 0);
  7511. is_directory = exists && S_ISDIR(st.st_mode);
  7512. if (is_directory)
  7513. mg_find_index_file(path, opts->index_files, &index_file, &st);
  7514. is_cgi =
  7515. (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
  7516. index_file ? index_file : path) > 0);
  7517. LOG(LL_DEBUG,
  7518. ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
  7519. (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
  7520. is_cgi, index_file ? index_file : ""));
  7521. if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
  7522. mg_printf(nc,
  7523. "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
  7524. "Content-Length: 0\r\n\r\n",
  7525. (int) hm->uri.len, hm->uri.p);
  7526. MG_FREE(index_file);
  7527. return;
  7528. }
  7529. /* If we have path_info, the only way to handle it is CGI. */
  7530. if (path_info->len > 0 && !is_cgi) {
  7531. mg_http_send_error(nc, 501, NULL);
  7532. MG_FREE(index_file);
  7533. return;
  7534. }
  7535. if (is_dav && opts->dav_document_root == NULL) {
  7536. mg_http_send_error(nc, 501, NULL);
  7537. } else if (!mg_http_is_authorized(
  7538. hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file,
  7539. ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
  7540. MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
  7541. MG_AUTH_FLAG_ALLOW_MISSING_FILE)) ||
  7542. !mg_http_is_authorized(
  7543. hm, mg_mk_str(path), opts->auth_domain,
  7544. opts->per_directory_auth_file,
  7545. ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
  7546. MG_AUTH_FLAG_ALLOW_MISSING_FILE))) {
  7547. mg_http_send_digest_auth_request(nc, opts->auth_domain);
  7548. } else if (is_cgi) {
  7549. #if MG_ENABLE_HTTP_CGI
  7550. mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
  7551. #else
  7552. mg_http_send_error(nc, 501, NULL);
  7553. #endif /* MG_ENABLE_HTTP_CGI */
  7554. } else if ((!exists ||
  7555. mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
  7556. !mg_is_creation_request(hm)) {
  7557. mg_http_send_error(nc, 404, NULL);
  7558. #if MG_ENABLE_HTTP_WEBDAV
  7559. } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
  7560. mg_handle_propfind(nc, path, &st, hm, opts);
  7561. #if !MG_DISABLE_DAV_AUTH
  7562. } else if (is_dav &&
  7563. (opts->dav_auth_file == NULL ||
  7564. (strcmp(opts->dav_auth_file, "-") != 0 &&
  7565. !mg_http_is_authorized(
  7566. hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file,
  7567. ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
  7568. MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
  7569. MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) {
  7570. mg_http_send_digest_auth_request(nc, opts->auth_domain);
  7571. #endif
  7572. } else if (!mg_vcmp(&hm->method, "MKCOL")) {
  7573. mg_handle_mkcol(nc, path, hm);
  7574. } else if (!mg_vcmp(&hm->method, "DELETE")) {
  7575. mg_handle_delete(nc, opts, path);
  7576. } else if (!mg_vcmp(&hm->method, "PUT")) {
  7577. mg_handle_put(nc, path, hm);
  7578. } else if (!mg_vcmp(&hm->method, "MOVE")) {
  7579. mg_handle_move(nc, opts, path, hm);
  7580. #if MG_ENABLE_FAKE_DAVLOCK
  7581. } else if (!mg_vcmp(&hm->method, "LOCK")) {
  7582. mg_handle_lock(nc, path);
  7583. #endif
  7584. #endif /* MG_ENABLE_HTTP_WEBDAV */
  7585. } else if (!mg_vcmp(&hm->method, "OPTIONS")) {
  7586. mg_http_send_options(nc, opts);
  7587. } else if (is_directory && index_file == NULL) {
  7588. #if MG_ENABLE_DIRECTORY_LISTING
  7589. if (strcmp(opts->enable_directory_listing, "yes") == 0) {
  7590. mg_send_directory_listing(nc, path, hm, opts);
  7591. } else {
  7592. mg_http_send_error(nc, 403, NULL);
  7593. }
  7594. #else
  7595. mg_http_send_error(nc, 501, NULL);
  7596. #endif
  7597. } else if (mg_is_not_modified(hm, &st)) {
  7598. mg_http_send_error(nc, 304, "Not Modified");
  7599. } else {
  7600. mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
  7601. }
  7602. MG_FREE(index_file);
  7603. }
  7604. void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
  7605. struct mg_serve_http_opts opts) {
  7606. char *path = NULL;
  7607. struct mg_str *hdr, path_info;
  7608. uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
  7609. if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
  7610. /* Not allowed to connect */
  7611. mg_http_send_error(nc, 403, NULL);
  7612. nc->flags |= MG_F_SEND_AND_CLOSE;
  7613. return;
  7614. }
  7615. #if MG_ENABLE_HTTP_URL_REWRITES
  7616. if (mg_http_handle_forwarding(nc, hm, &opts)) {
  7617. return;
  7618. }
  7619. if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
  7620. return;
  7621. }
  7622. #endif
  7623. if (opts.document_root == NULL) {
  7624. opts.document_root = ".";
  7625. }
  7626. if (opts.per_directory_auth_file == NULL) {
  7627. opts.per_directory_auth_file = ".htpasswd";
  7628. }
  7629. if (opts.enable_directory_listing == NULL) {
  7630. opts.enable_directory_listing = "yes";
  7631. }
  7632. if (opts.cgi_file_pattern == NULL) {
  7633. opts.cgi_file_pattern = "**.cgi$|**.php$";
  7634. }
  7635. if (opts.ssi_pattern == NULL) {
  7636. opts.ssi_pattern = "**.shtml$|**.shtm$";
  7637. }
  7638. if (opts.index_files == NULL) {
  7639. opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
  7640. }
  7641. /* Normalize path - resolve "." and ".." (in-place). */
  7642. if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
  7643. mg_http_send_error(nc, 400, NULL);
  7644. return;
  7645. }
  7646. if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
  7647. mg_http_send_error(nc, 404, NULL);
  7648. return;
  7649. }
  7650. mg_send_http_file(nc, path, &path_info, hm, &opts);
  7651. MG_FREE(path);
  7652. path = NULL;
  7653. /* Close connection for non-keep-alive requests */
  7654. if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
  7655. ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
  7656. mg_vcmp(hdr, "keep-alive") != 0)) {
  7657. #if 0
  7658. nc->flags |= MG_F_SEND_AND_CLOSE;
  7659. #endif
  7660. }
  7661. }
  7662. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  7663. void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
  7664. mg_fu_fname_fn local_name_fn
  7665. MG_UD_ARG(void *user_data)) {
  7666. switch (ev) {
  7667. case MG_EV_HTTP_PART_BEGIN: {
  7668. struct mg_http_multipart_part *mp =
  7669. (struct mg_http_multipart_part *) ev_data;
  7670. struct file_upload_state *fus;
  7671. struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
  7672. mp->user_data = NULL;
  7673. if (lfn.p == NULL || lfn.len == 0) {
  7674. LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
  7675. mg_printf(nc,
  7676. "HTTP/1.1 403 Not Allowed\r\n"
  7677. "Content-Type: text/plain\r\n"
  7678. "Connection: close\r\n\r\n"
  7679. "Not allowed to upload %s\r\n",
  7680. mp->file_name);
  7681. nc->flags |= MG_F_SEND_AND_CLOSE;
  7682. return;
  7683. }
  7684. fus = (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus));
  7685. if (fus == NULL) {
  7686. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  7687. return;
  7688. }
  7689. fus->lfn = (char *) MG_MALLOC(lfn.len + 1);
  7690. memcpy(fus->lfn, lfn.p, lfn.len);
  7691. fus->lfn[lfn.len] = '\0';
  7692. if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p);
  7693. LOG(LL_DEBUG,
  7694. ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
  7695. fus->fp = mg_fopen(fus->lfn, "wb");
  7696. if (fus->fp == NULL) {
  7697. mg_printf(nc,
  7698. "HTTP/1.1 500 Internal Server Error\r\n"
  7699. "Content-Type: text/plain\r\n"
  7700. "Connection: close\r\n\r\n");
  7701. LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno()));
  7702. mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno());
  7703. /* Do not close the connection just yet, discard remainder of the data.
  7704. * This is because at the time of writing some browsers (Chrome) fail to
  7705. * render response before all the data is sent. */
  7706. }
  7707. mp->user_data = (void *) fus;
  7708. break;
  7709. }
  7710. case MG_EV_HTTP_PART_DATA: {
  7711. struct mg_http_multipart_part *mp =
  7712. (struct mg_http_multipart_part *) ev_data;
  7713. struct file_upload_state *fus =
  7714. (struct file_upload_state *) mp->user_data;
  7715. if (fus == NULL || fus->fp == NULL) break;
  7716. if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
  7717. LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn,
  7718. mg_get_errno(), (int) fus->num_recd));
  7719. if (mg_get_errno() == ENOSPC
  7720. #ifdef SPIFFS_ERR_FULL
  7721. || mg_get_errno() == SPIFFS_ERR_FULL
  7722. #endif
  7723. ) {
  7724. mg_printf(nc,
  7725. "HTTP/1.1 413 Payload Too Large\r\n"
  7726. "Content-Type: text/plain\r\n"
  7727. "Connection: close\r\n\r\n");
  7728. mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
  7729. fus->lfn, (int) fus->num_recd);
  7730. } else {
  7731. mg_printf(nc,
  7732. "HTTP/1.1 500 Internal Server Error\r\n"
  7733. "Content-Type: text/plain\r\n"
  7734. "Connection: close\r\n\r\n");
  7735. mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
  7736. mg_get_errno(), (int) fus->num_recd);
  7737. }
  7738. fclose(fus->fp);
  7739. remove(fus->lfn);
  7740. fus->fp = NULL;
  7741. /* Do not close the connection just yet, discard remainder of the data.
  7742. * This is because at the time of writing some browsers (Chrome) fail to
  7743. * render response before all the data is sent. */
  7744. return;
  7745. }
  7746. fus->num_recd += mp->data.len;
  7747. LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
  7748. (int) fus->num_recd));
  7749. break;
  7750. }
  7751. case MG_EV_HTTP_PART_END: {
  7752. struct mg_http_multipart_part *mp =
  7753. (struct mg_http_multipart_part *) ev_data;
  7754. struct file_upload_state *fus =
  7755. (struct file_upload_state *) mp->user_data;
  7756. if (fus == NULL) break;
  7757. if (mp->status >= 0 && fus->fp != NULL) {
  7758. LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
  7759. fus->lfn, (int) fus->num_recd));
  7760. } else {
  7761. LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
  7762. /*
  7763. * mp->status < 0 means connection was terminated, so no reason to send
  7764. * HTTP reply
  7765. */
  7766. }
  7767. if (fus->fp != NULL) fclose(fus->fp);
  7768. MG_FREE(fus->lfn);
  7769. MG_FREE(fus);
  7770. mp->user_data = NULL;
  7771. /* Don't close the connection yet, there may be more files to come. */
  7772. break;
  7773. }
  7774. case MG_EV_HTTP_MULTIPART_REQUEST_END: {
  7775. mg_printf(nc,
  7776. "HTTP/1.1 200 OK\r\n"
  7777. "Content-Type: text/plain\r\n"
  7778. "Connection: close\r\n\r\n"
  7779. "Ok.\r\n");
  7780. nc->flags |= MG_F_SEND_AND_CLOSE;
  7781. break;
  7782. }
  7783. }
  7784. #if MG_ENABLE_CALLBACK_USERDATA
  7785. (void) user_data;
  7786. #endif
  7787. }
  7788. #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
  7789. #endif /* MG_ENABLE_FILESYSTEM */
  7790. struct mg_connection *mg_connect_http_base(
  7791. struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
  7792. struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
  7793. const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
  7794. struct mg_str *path, struct mg_str *user_info, struct mg_str *host) {
  7795. struct mg_connection *nc = NULL;
  7796. unsigned int port_i = 0;
  7797. int use_ssl = 0;
  7798. struct mg_str scheme, query, fragment;
  7799. char conn_addr_buf[2];
  7800. char *conn_addr = conn_addr_buf;
  7801. if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path,
  7802. &query, &fragment) != 0) {
  7803. MG_SET_PTRPTR(opts.error_string, "cannot parse url");
  7804. goto out;
  7805. }
  7806. /* If query is present, do not strip it. Pass to the caller. */
  7807. if (query.len > 0) path->len += query.len + 1;
  7808. if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 ||
  7809. (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) {
  7810. use_ssl = 0;
  7811. if (port_i == 0) port_i = 80;
  7812. } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 ||
  7813. (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) {
  7814. use_ssl = 1;
  7815. if (port_i == 0) port_i = 443;
  7816. } else {
  7817. goto out;
  7818. }
  7819. mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u",
  7820. (int) host->len, host->p, port_i);
  7821. if (conn_addr == NULL) goto out;
  7822. LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr));
  7823. if (use_ssl) {
  7824. #if MG_ENABLE_SSL
  7825. /*
  7826. * Schema requires SSL, but no SSL parameters were provided in opts.
  7827. * In order to maintain backward compatibility, use a faux-SSL with no
  7828. * verification.
  7829. */
  7830. if (opts.ssl_ca_cert == NULL) {
  7831. opts.ssl_ca_cert = "*";
  7832. }
  7833. #else
  7834. MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
  7835. goto out;
  7836. #endif
  7837. }
  7838. if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data),
  7839. opts)) != NULL) {
  7840. mg_set_protocol_http_websocket(nc);
  7841. }
  7842. out:
  7843. if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr);
  7844. return nc;
  7845. }
  7846. struct mg_connection *mg_connect_http_opt(
  7847. struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
  7848. struct mg_connect_opts opts, const char *url, const char *extra_headers,
  7849. const char *post_data) {
  7850. struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
  7851. struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
  7852. struct mbuf auth;
  7853. struct mg_connection *nc =
  7854. mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
  7855. NULL, "https", NULL, url, &path, &user, &host);
  7856. if (nc == NULL) {
  7857. return NULL;
  7858. }
  7859. mbuf_init(&auth, 0);
  7860. if (user.len > 0) {
  7861. mg_basic_auth_header(user, null_str, &auth);
  7862. }
  7863. if (post_data == NULL) post_data = "";
  7864. if (extra_headers == NULL) extra_headers = "";
  7865. if (path.len == 0) path = mg_mk_str("/");
  7866. if (host.len == 0) host = mg_mk_str("");
  7867. mg_printf(nc, "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
  7868. "\r\n%.*s%s\r\n%s",
  7869. (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p,
  7870. (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
  7871. (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
  7872. mbuf_free(&auth);
  7873. return nc;
  7874. }
  7875. struct mg_connection *mg_connect_http(
  7876. struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
  7877. const char *url, const char *extra_headers, const char *post_data) {
  7878. struct mg_connect_opts opts;
  7879. memset(&opts, 0, sizeof(opts));
  7880. return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
  7881. extra_headers, post_data);
  7882. }
  7883. size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
  7884. size_t var_name_len, char *file_name,
  7885. size_t file_name_len, const char **data,
  7886. size_t *data_len) {
  7887. static const char cd[] = "Content-Disposition: ";
  7888. size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
  7889. int shl;
  7890. if (buf == NULL || buf_len <= 0) return 0;
  7891. if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
  7892. hl = shl;
  7893. if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
  7894. /* Get boundary length */
  7895. bl = mg_get_line_len(buf, buf_len);
  7896. /* Loop through headers, fetch variable name and file name */
  7897. var_name[0] = file_name[0] = '\0';
  7898. for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
  7899. if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
  7900. struct mg_str header;
  7901. header.p = buf + n + cdl;
  7902. header.len = ll - (cdl + 2);
  7903. {
  7904. char *var_name2 = var_name;
  7905. mg_http_parse_header2(&header, "name", &var_name2, var_name_len);
  7906. /* TODO: handle reallocated buffer correctly */
  7907. if (var_name2 != var_name) {
  7908. MG_FREE(var_name2);
  7909. var_name[0] = '\0';
  7910. }
  7911. }
  7912. {
  7913. char *file_name2 = file_name;
  7914. mg_http_parse_header2(&header, "filename", &file_name2, file_name_len);
  7915. /* TODO: handle reallocated buffer correctly */
  7916. if (file_name2 != file_name) {
  7917. MG_FREE(file_name2);
  7918. file_name[0] = '\0';
  7919. }
  7920. }
  7921. }
  7922. }
  7923. /* Scan through the body, search for terminating boundary */
  7924. for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
  7925. if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
  7926. if (data_len != NULL) *data_len = (pos - 2) - hl;
  7927. if (data != NULL) *data = buf + hl;
  7928. return pos;
  7929. }
  7930. }
  7931. return 0;
  7932. }
  7933. void mg_register_http_endpoint_opt(struct mg_connection *nc,
  7934. const char *uri_path,
  7935. mg_event_handler_t handler,
  7936. struct mg_http_endpoint_opts opts) {
  7937. struct mg_http_proto_data *pd = NULL;
  7938. struct mg_http_endpoint *new_ep = NULL;
  7939. if (nc == NULL) return;
  7940. new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
  7941. if (new_ep == NULL) return;
  7942. pd = mg_http_get_proto_data(nc);
  7943. if (pd == NULL) pd = mg_http_create_proto_data(nc);
  7944. new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path));
  7945. if (opts.auth_domain != NULL && opts.auth_file != NULL) {
  7946. new_ep->auth_domain = strdup(opts.auth_domain);
  7947. new_ep->auth_file = strdup(opts.auth_file);
  7948. }
  7949. new_ep->handler = handler;
  7950. #if MG_ENABLE_CALLBACK_USERDATA
  7951. new_ep->user_data = opts.user_data;
  7952. #endif
  7953. new_ep->next = pd->endpoints;
  7954. pd->endpoints = new_ep;
  7955. }
  7956. static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
  7957. struct http_message *hm) {
  7958. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  7959. void *user_data = nc->user_data;
  7960. if (ev == MG_EV_HTTP_REQUEST
  7961. #if MG_ENABLE_HTTP_STREAMING_MULTIPART
  7962. || ev == MG_EV_HTTP_MULTIPART_REQUEST
  7963. #endif
  7964. ) {
  7965. struct mg_http_endpoint *ep =
  7966. mg_http_get_endpoint_handler(nc->listener, &hm->uri);
  7967. if (ep != NULL) {
  7968. #if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH
  7969. if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file,
  7970. MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) {
  7971. mg_http_send_digest_auth_request(nc, ep->auth_domain);
  7972. return;
  7973. }
  7974. #endif
  7975. pd->endpoint_handler = ep->handler;
  7976. #if MG_ENABLE_CALLBACK_USERDATA
  7977. user_data = ep->user_data;
  7978. #endif
  7979. }
  7980. }
  7981. mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler,
  7982. user_data, ev, hm);
  7983. }
  7984. void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
  7985. MG_CB(mg_event_handler_t handler,
  7986. void *user_data)) {
  7987. struct mg_http_endpoint_opts opts;
  7988. memset(&opts, 0, sizeof(opts));
  7989. #if MG_ENABLE_CALLBACK_USERDATA
  7990. opts.user_data = user_data;
  7991. #endif
  7992. mg_register_http_endpoint_opt(nc, uri_path, handler, opts);
  7993. }
  7994. #endif /* MG_ENABLE_HTTP */
  7995. #ifdef MG_MODULE_LINES
  7996. #line 1 "mongoose/src/mg_http_cgi.c"
  7997. #endif
  7998. /*
  7999. * Copyright (c) 2014-2016 Cesanta Software Limited
  8000. * All rights reserved
  8001. */
  8002. #ifndef _WIN32
  8003. #include <signal.h>
  8004. #endif
  8005. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
  8006. #ifndef MG_MAX_CGI_ENVIR_VARS
  8007. #define MG_MAX_CGI_ENVIR_VARS 64
  8008. #endif
  8009. #ifndef MG_ENV_EXPORT_TO_CGI
  8010. #define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
  8011. #endif
  8012. #define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1
  8013. /*
  8014. * This structure helps to create an environment for the spawned CGI program.
  8015. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8016. * last element must be NULL.
  8017. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  8018. * strings must reside in a contiguous buffer. The end of the buffer is
  8019. * marked by two '\0' characters.
  8020. * We satisfy both worlds: we create an envp array (which is vars), all
  8021. * entries are actually pointers inside buf.
  8022. */
  8023. struct mg_cgi_env_block {
  8024. struct mg_connection *nc;
  8025. char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  8026. const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
  8027. int len; /* Space taken */
  8028. int nvars; /* Number of variables in envp[] */
  8029. };
  8030. #ifdef _WIN32
  8031. struct mg_threadparam {
  8032. sock_t s;
  8033. HANDLE hPipe;
  8034. };
  8035. static int mg_wait_until_ready(sock_t sock, int for_read) {
  8036. fd_set set;
  8037. FD_ZERO(&set);
  8038. FD_SET(sock, &set);
  8039. return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
  8040. }
  8041. static void *mg_push_to_stdin(void *arg) {
  8042. struct mg_threadparam *tp = (struct mg_threadparam *) arg;
  8043. int n, sent, stop = 0;
  8044. DWORD k;
  8045. char buf[BUFSIZ];
  8046. while (!stop && mg_wait_until_ready(tp->s, 1) &&
  8047. (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
  8048. if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
  8049. for (sent = 0; !stop && sent < n; sent += k) {
  8050. if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
  8051. }
  8052. }
  8053. DBG(("%s", "FORWARED EVERYTHING TO CGI"));
  8054. CloseHandle(tp->hPipe);
  8055. MG_FREE(tp);
  8056. return NULL;
  8057. }
  8058. static void *mg_pull_from_stdout(void *arg) {
  8059. struct mg_threadparam *tp = (struct mg_threadparam *) arg;
  8060. int k = 0, stop = 0;
  8061. DWORD n, sent;
  8062. char buf[BUFSIZ];
  8063. while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
  8064. for (sent = 0; !stop && sent < n; sent += k) {
  8065. if (mg_wait_until_ready(tp->s, 0) &&
  8066. (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
  8067. stop = 1;
  8068. }
  8069. }
  8070. DBG(("%s", "EOF FROM CGI"));
  8071. CloseHandle(tp->hPipe);
  8072. shutdown(tp->s, 2); // Without this, IO thread may get truncated data
  8073. closesocket(tp->s);
  8074. MG_FREE(tp);
  8075. return NULL;
  8076. }
  8077. static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
  8078. void *(*func)(void *)) {
  8079. struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
  8080. if (tp != NULL) {
  8081. tp->s = sock;
  8082. tp->hPipe = hPipe;
  8083. mg_start_thread(func, tp);
  8084. }
  8085. }
  8086. static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
  8087. wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH];
  8088. to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
  8089. GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
  8090. WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
  8091. }
  8092. static int mg_start_process(const char *interp, const char *cmd,
  8093. const char *env, const char *envp[],
  8094. const char *dir, sock_t sock) {
  8095. STARTUPINFOW si;
  8096. PROCESS_INFORMATION pi;
  8097. HANDLE a[2], b[2], me = GetCurrentProcess();
  8098. wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH];
  8099. char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH],
  8100. buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH];
  8101. DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
  8102. FILE *fp;
  8103. memset(&si, 0, sizeof(si));
  8104. memset(&pi, 0, sizeof(pi));
  8105. si.cb = sizeof(si);
  8106. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  8107. si.wShowWindow = SW_HIDE;
  8108. si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  8109. CreatePipe(&a[0], &a[1], NULL, 0);
  8110. CreatePipe(&b[0], &b[1], NULL, 0);
  8111. DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
  8112. DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
  8113. if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
  8114. buf[0] = buf[1] = '\0';
  8115. fgets(buf, sizeof(buf), fp);
  8116. buf[sizeof(buf) - 1] = '\0';
  8117. if (buf[0] == '#' && buf[1] == '!') {
  8118. interp = buf + 2;
  8119. /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
  8120. while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
  8121. interp++;
  8122. }
  8123. }
  8124. fclose(fp);
  8125. }
  8126. snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
  8127. mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
  8128. mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
  8129. to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
  8130. if (interp != NULL) {
  8131. mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
  8132. snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
  8133. } else {
  8134. snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
  8135. }
  8136. to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
  8137. if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
  8138. (void *) env, full_dir, &si, &pi) != 0) {
  8139. mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
  8140. mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
  8141. CloseHandle(si.hStdOutput);
  8142. CloseHandle(si.hStdInput);
  8143. CloseHandle(pi.hThread);
  8144. CloseHandle(pi.hProcess);
  8145. } else {
  8146. CloseHandle(a[1]);
  8147. CloseHandle(b[0]);
  8148. closesocket(sock);
  8149. }
  8150. DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
  8151. /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
  8152. (void) envp;
  8153. return (pi.hProcess != NULL);
  8154. }
  8155. #else
  8156. static int mg_start_process(const char *interp, const char *cmd,
  8157. const char *env, const char *envp[],
  8158. const char *dir, sock_t sock) {
  8159. char buf[500];
  8160. pid_t pid = fork();
  8161. (void) env;
  8162. if (pid == 0) {
  8163. /*
  8164. * In Linux `chdir` declared with `warn_unused_result` attribute
  8165. * To shutup compiler we have yo use result in some way
  8166. */
  8167. int tmp = chdir(dir);
  8168. (void) tmp;
  8169. (void) dup2(sock, 0);
  8170. (void) dup2(sock, 1);
  8171. closesocket(sock);
  8172. /*
  8173. * After exec, all signal handlers are restored to their default values,
  8174. * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
  8175. * implementation, SIGCHLD's handler will leave unchanged after exec
  8176. * if it was set to be ignored. Restore it to default action.
  8177. */
  8178. signal(SIGCHLD, SIG_DFL);
  8179. if (interp == NULL) {
  8180. execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
  8181. } else {
  8182. execle(interp, interp, cmd, (char *) 0, envp);
  8183. }
  8184. snprintf(buf, sizeof(buf),
  8185. "Status: 500\r\n\r\n"
  8186. "500 Server Error: %s%s%s: %s",
  8187. interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
  8188. strerror(errno));
  8189. send(1, buf, strlen(buf), 0);
  8190. _exit(EXIT_FAILURE); /* exec call failed */
  8191. }
  8192. return (pid != 0);
  8193. }
  8194. #endif /* _WIN32 */
  8195. /*
  8196. * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8197. * pointer into the vars array.
  8198. */
  8199. static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
  8200. int n, space;
  8201. char *added = block->buf + block->len;
  8202. va_list ap;
  8203. /* Calculate how much space is left in the buffer */
  8204. space = sizeof(block->buf) - (block->len + 2);
  8205. if (space > 0) {
  8206. /* Copy VARIABLE=VALUE\0 string into the free space */
  8207. va_start(ap, fmt);
  8208. n = vsnprintf(added, (size_t) space, fmt, ap);
  8209. va_end(ap);
  8210. /* Make sure we do not overflow buffer and the envp array */
  8211. if (n > 0 && n + 1 < space &&
  8212. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  8213. /* Append a pointer to the added string into the envp array */
  8214. block->vars[block->nvars++] = added;
  8215. /* Bump up used length counter. Include \0 terminator */
  8216. block->len += n + 1;
  8217. }
  8218. }
  8219. return added;
  8220. }
  8221. static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
  8222. const char *s;
  8223. if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
  8224. }
  8225. static void mg_prepare_cgi_environment(struct mg_connection *nc,
  8226. const char *prog,
  8227. const struct mg_str *path_info,
  8228. const struct http_message *hm,
  8229. const struct mg_serve_http_opts *opts,
  8230. struct mg_cgi_env_block *blk) {
  8231. const char *s;
  8232. struct mg_str *h;
  8233. char *p;
  8234. size_t i;
  8235. char buf[100];
  8236. size_t path_info_len = path_info != NULL ? path_info->len : 0;
  8237. blk->len = blk->nvars = 0;
  8238. blk->nc = nc;
  8239. if ((s = getenv("SERVER_NAME")) != NULL) {
  8240. mg_addenv(blk, "SERVER_NAME=%s", s);
  8241. } else {
  8242. mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
  8243. mg_addenv(blk, "SERVER_NAME=%s", buf);
  8244. }
  8245. mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
  8246. mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
  8247. mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
  8248. /* Prepare the environment block */
  8249. mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8250. mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8251. mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8252. mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
  8253. mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
  8254. hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
  8255. hm->query_string.p);
  8256. mg_conn_addr_to_str(nc, buf, sizeof(buf),
  8257. MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
  8258. mg_addenv(blk, "REMOTE_ADDR=%s", buf);
  8259. mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
  8260. mg_addenv(blk, "SERVER_PORT=%s", buf);
  8261. s = hm->uri.p + hm->uri.len - path_info_len - 1;
  8262. if (*s == '/') {
  8263. const char *base_name = strrchr(prog, DIRSEP);
  8264. mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
  8265. (base_name != NULL ? base_name + 1 : prog));
  8266. } else {
  8267. mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
  8268. }
  8269. mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
  8270. if (path_info != NULL && path_info->len > 0) {
  8271. mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
  8272. /* Not really translated... */
  8273. mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
  8274. }
  8275. #if MG_ENABLE_SSL
  8276. mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
  8277. #else
  8278. mg_addenv(blk, "HTTPS=off");
  8279. #endif
  8280. if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
  8281. NULL) {
  8282. mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
  8283. }
  8284. if (hm->query_string.len > 0) {
  8285. mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
  8286. hm->query_string.p);
  8287. }
  8288. if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
  8289. NULL) {
  8290. mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
  8291. }
  8292. mg_addenv2(blk, "PATH");
  8293. mg_addenv2(blk, "TMP");
  8294. mg_addenv2(blk, "TEMP");
  8295. mg_addenv2(blk, "TMPDIR");
  8296. mg_addenv2(blk, "PERLLIB");
  8297. mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
  8298. #ifdef _WIN32
  8299. mg_addenv2(blk, "COMSPEC");
  8300. mg_addenv2(blk, "SYSTEMROOT");
  8301. mg_addenv2(blk, "SystemDrive");
  8302. mg_addenv2(blk, "ProgramFiles");
  8303. mg_addenv2(blk, "ProgramFiles(x86)");
  8304. mg_addenv2(blk, "CommonProgramFiles(x86)");
  8305. #else
  8306. mg_addenv2(blk, "LD_LIBRARY_PATH");
  8307. #endif /* _WIN32 */
  8308. /* Add all headers as HTTP_* variables */
  8309. for (i = 0; hm->header_names[i].len > 0; i++) {
  8310. p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
  8311. hm->header_names[i].p, (int) hm->header_values[i].len,
  8312. hm->header_values[i].p);
  8313. /* Convert variable name into uppercase, and change - to _ */
  8314. for (; *p != '=' && *p != '\0'; p++) {
  8315. if (*p == '-') *p = '_';
  8316. *p = (char) toupper(*(unsigned char *) p);
  8317. }
  8318. }
  8319. blk->vars[blk->nvars++] = NULL;
  8320. blk->buf[blk->len++] = '\0';
  8321. }
  8322. static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
  8323. void *ev_data MG_UD_ARG(void *user_data)) {
  8324. #if !MG_ENABLE_CALLBACK_USERDATA
  8325. void *user_data = cgi_nc->user_data;
  8326. #endif
  8327. struct mg_connection *nc = (struct mg_connection *) user_data;
  8328. (void) ev_data;
  8329. if (nc == NULL) {
  8330. /* The corresponding network connection was closed. */
  8331. cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  8332. return;
  8333. }
  8334. switch (ev) {
  8335. case MG_EV_RECV:
  8336. /*
  8337. * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
  8338. * It outputs headers, then body. Headers might include "Status"
  8339. * header, which changes CODE, and it might include "Location" header
  8340. * which changes CODE to 302.
  8341. *
  8342. * Therefore we do not send the output from the CGI script to the user
  8343. * until all CGI headers are received.
  8344. *
  8345. * Here we parse the output from the CGI script, and if all headers has
  8346. * been received, send appropriate reply line, and forward all
  8347. * received headers to the client.
  8348. */
  8349. if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) {
  8350. struct mbuf *io = &cgi_nc->recv_mbuf;
  8351. int len = mg_http_get_request_len(io->buf, io->len);
  8352. if (len == 0) break;
  8353. if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
  8354. cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  8355. mg_http_send_error(nc, 500, "Bad headers");
  8356. } else {
  8357. struct http_message hm;
  8358. struct mg_str *h;
  8359. mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
  8360. if (mg_get_http_header(&hm, "Location") != NULL) {
  8361. mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
  8362. } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
  8363. mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
  8364. } else {
  8365. mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
  8366. }
  8367. }
  8368. nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS;
  8369. }
  8370. if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) {
  8371. mg_forward(cgi_nc, nc);
  8372. }
  8373. break;
  8374. case MG_EV_CLOSE:
  8375. DBG(("%p CLOSE", cgi_nc));
  8376. mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
  8377. nc->flags |= MG_F_SEND_AND_CLOSE;
  8378. break;
  8379. }
  8380. }
  8381. MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
  8382. const struct mg_str *path_info,
  8383. const struct http_message *hm,
  8384. const struct mg_serve_http_opts *opts) {
  8385. struct mg_cgi_env_block blk;
  8386. char dir[MG_MAX_PATH];
  8387. const char *p;
  8388. sock_t fds[2];
  8389. DBG(("%p [%s]", nc, prog));
  8390. mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
  8391. /*
  8392. * CGI must be executed in its own directory. 'dir' must point to the
  8393. * directory containing executable program, 'p' must point to the
  8394. * executable program name relative to 'dir'.
  8395. */
  8396. if ((p = strrchr(prog, DIRSEP)) == NULL) {
  8397. snprintf(dir, sizeof(dir), "%s", ".");
  8398. } else {
  8399. snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
  8400. prog = p + 1;
  8401. }
  8402. if (!mg_socketpair(fds, SOCK_STREAM)) {
  8403. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  8404. return;
  8405. }
  8406. #ifndef _WIN32
  8407. struct sigaction sa;
  8408. sigemptyset(&sa.sa_mask);
  8409. sa.sa_handler = SIG_IGN;
  8410. sa.sa_flags = 0;
  8411. sigaction(SIGCHLD, &sa, NULL);
  8412. #endif
  8413. if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
  8414. fds[1]) != 0) {
  8415. struct mg_connection *cgi_nc =
  8416. mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc));
  8417. struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
  8418. cgi_pd->cgi.cgi_nc = cgi_nc;
  8419. #if !MG_ENABLE_CALLBACK_USERDATA
  8420. cgi_pd->cgi.cgi_nc->user_data = nc;
  8421. #endif
  8422. nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS;
  8423. /* Push POST data to the CGI */
  8424. if (hm->body.len > 0) {
  8425. mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len);
  8426. }
  8427. mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
  8428. } else {
  8429. closesocket(fds[0]);
  8430. mg_http_send_error(nc, 500, "CGI failure");
  8431. }
  8432. #ifndef _WIN32
  8433. closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
  8434. #endif
  8435. }
  8436. MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
  8437. if (d == NULL) return;
  8438. if (d->cgi_nc != NULL) {
  8439. d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  8440. d->cgi_nc->user_data = NULL;
  8441. }
  8442. memset(d, 0, sizeof(*d));
  8443. }
  8444. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
  8445. #ifdef MG_MODULE_LINES
  8446. #line 1 "mongoose/src/mg_http_ssi.c"
  8447. #endif
  8448. /*
  8449. * Copyright (c) 2014-2016 Cesanta Software Limited
  8450. * All rights reserved
  8451. */
  8452. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
  8453. static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
  8454. const char *path, FILE *fp, int include_level,
  8455. const struct mg_serve_http_opts *opts);
  8456. static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
  8457. char buf[BUFSIZ];
  8458. size_t n;
  8459. while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) {
  8460. mg_send(nc, buf, n);
  8461. }
  8462. }
  8463. static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
  8464. const char *ssi, char *tag, int include_level,
  8465. const struct mg_serve_http_opts *opts) {
  8466. char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p;
  8467. FILE *fp;
  8468. /*
  8469. * sscanf() is safe here, since send_ssi_file() also uses buffer
  8470. * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  8471. */
  8472. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  8473. /* File name is relative to the webserver root */
  8474. snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
  8475. } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
  8476. /*
  8477. * File name is relative to the webserver working directory
  8478. * or it is absolute system path
  8479. */
  8480. snprintf(path, sizeof(path), "%s", file_name);
  8481. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
  8482. sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  8483. /* File name is relative to the currect document */
  8484. snprintf(path, sizeof(path), "%s", ssi);
  8485. if ((p = strrchr(path, DIRSEP)) != NULL) {
  8486. p[1] = '\0';
  8487. }
  8488. snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
  8489. } else {
  8490. mg_printf(nc, "Bad SSI #include: [%s]", tag);
  8491. return;
  8492. }
  8493. if ((fp = mg_fopen(path, "rb")) == NULL) {
  8494. mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
  8495. strerror(mg_get_errno()));
  8496. } else {
  8497. mg_set_close_on_exec((sock_t) fileno(fp));
  8498. if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
  8499. 0) {
  8500. mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
  8501. } else {
  8502. mg_send_file_data(nc, fp);
  8503. }
  8504. fclose(fp);
  8505. }
  8506. }
  8507. #if MG_ENABLE_HTTP_SSI_EXEC
  8508. static void do_ssi_exec(struct mg_connection *nc, char *tag) {
  8509. char cmd[BUFSIZ];
  8510. FILE *fp;
  8511. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  8512. mg_printf(nc, "Bad SSI #exec: [%s]", tag);
  8513. } else if ((fp = popen(cmd, "r")) == NULL) {
  8514. mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
  8515. } else {
  8516. mg_send_file_data(nc, fp);
  8517. pclose(fp);
  8518. }
  8519. }
  8520. #endif /* MG_ENABLE_HTTP_SSI_EXEC */
  8521. /*
  8522. * SSI directive has the following format:
  8523. * <!--#directive parameter=value parameter=value -->
  8524. */
  8525. static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
  8526. const char *path, FILE *fp, int include_level,
  8527. const struct mg_serve_http_opts *opts) {
  8528. static const struct mg_str btag = MG_MK_STR("<!--#");
  8529. static const struct mg_str d_include = MG_MK_STR("include");
  8530. static const struct mg_str d_call = MG_MK_STR("call");
  8531. #if MG_ENABLE_HTTP_SSI_EXEC
  8532. static const struct mg_str d_exec = MG_MK_STR("exec");
  8533. #endif
  8534. char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
  8535. int ch, len, in_ssi_tag;
  8536. if (include_level > 10) {
  8537. mg_printf(nc, "SSI #include level is too deep (%s)", path);
  8538. return;
  8539. }
  8540. in_ssi_tag = len = 0;
  8541. while ((ch = fgetc(fp)) != EOF) {
  8542. if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  8543. size_t i = len - 2;
  8544. in_ssi_tag = 0;
  8545. /* Trim closing --> */
  8546. buf[i--] = '\0';
  8547. while (i > 0 && buf[i] == ' ') {
  8548. buf[i--] = '\0';
  8549. }
  8550. /* Handle known SSI directives */
  8551. if (strncmp(p, d_include.p, d_include.len) == 0) {
  8552. mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
  8553. opts);
  8554. } else if (strncmp(p, d_call.p, d_call.len) == 0) {
  8555. struct mg_ssi_call_ctx cctx;
  8556. memset(&cctx, 0, sizeof(cctx));
  8557. cctx.req = hm;
  8558. cctx.file = mg_mk_str(path);
  8559. cctx.arg = mg_mk_str(p + d_call.len + 1);
  8560. mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL,
  8561. (void *) cctx.arg.p); /* NUL added above */
  8562. mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx);
  8563. #if MG_ENABLE_HTTP_SSI_EXEC
  8564. } else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
  8565. do_ssi_exec(nc, p + d_exec.len + 1);
  8566. #endif
  8567. } else {
  8568. /* Silently ignore unknown SSI directive. */
  8569. }
  8570. len = 0;
  8571. } else if (ch == '<') {
  8572. in_ssi_tag = 1;
  8573. if (len > 0) {
  8574. mg_send(nc, buf, (size_t) len);
  8575. }
  8576. len = 0;
  8577. buf[len++] = ch & 0xff;
  8578. } else if (in_ssi_tag) {
  8579. if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
  8580. /* Not an SSI tag */
  8581. in_ssi_tag = 0;
  8582. } else if (len == (int) sizeof(buf) - 2) {
  8583. mg_printf(nc, "%s: SSI tag is too large", path);
  8584. len = 0;
  8585. }
  8586. buf[len++] = ch & 0xff;
  8587. } else {
  8588. buf[len++] = ch & 0xff;
  8589. if (len == (int) sizeof(buf)) {
  8590. mg_send(nc, buf, (size_t) len);
  8591. len = 0;
  8592. }
  8593. }
  8594. }
  8595. /* Send the rest of buffered data */
  8596. if (len > 0) {
  8597. mg_send(nc, buf, (size_t) len);
  8598. }
  8599. }
  8600. MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
  8601. struct http_message *hm,
  8602. const char *path,
  8603. const struct mg_serve_http_opts *opts) {
  8604. FILE *fp;
  8605. struct mg_str mime_type;
  8606. DBG(("%p %s", nc, path));
  8607. if ((fp = mg_fopen(path, "rb")) == NULL) {
  8608. mg_http_send_error(nc, 404, NULL);
  8609. } else {
  8610. mg_set_close_on_exec((sock_t) fileno(fp));
  8611. mime_type = mg_get_mime_type(path, "text/plain", opts);
  8612. mg_send_response_line(nc, 200, opts->extra_headers);
  8613. mg_printf(nc,
  8614. "Content-Type: %.*s\r\n"
  8615. "Connection: close\r\n\r\n",
  8616. (int) mime_type.len, mime_type.p);
  8617. mg_send_ssi_file(nc, hm, path, fp, 0, opts);
  8618. fclose(fp);
  8619. nc->flags |= MG_F_SEND_AND_CLOSE;
  8620. }
  8621. }
  8622. #endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
  8623. #ifdef MG_MODULE_LINES
  8624. #line 1 "mongoose/src/mg_http_webdav.c"
  8625. #endif
  8626. /*
  8627. * Copyright (c) 2014-2016 Cesanta Software Limited
  8628. * All rights reserved
  8629. */
  8630. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
  8631. MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
  8632. static const char *methods[] = {
  8633. "PUT",
  8634. "DELETE",
  8635. "MKCOL",
  8636. "PROPFIND",
  8637. "MOVE"
  8638. #if MG_ENABLE_FAKE_DAVLOCK
  8639. ,
  8640. "LOCK",
  8641. "UNLOCK"
  8642. #endif
  8643. };
  8644. size_t i;
  8645. for (i = 0; i < ARRAY_SIZE(methods); i++) {
  8646. if (mg_vcmp(s, methods[i]) == 0) {
  8647. return 1;
  8648. }
  8649. }
  8650. return 0;
  8651. }
  8652. static int mg_mkdir(const char *path, uint32_t mode) {
  8653. #ifndef _WIN32
  8654. return mkdir(path, mode);
  8655. #else
  8656. (void) mode;
  8657. return _mkdir(path);
  8658. #endif
  8659. }
  8660. static void mg_print_props(struct mg_connection *nc, const char *name,
  8661. cs_stat_t *stp) {
  8662. char mtime[64];
  8663. time_t t = stp->st_mtime; /* store in local variable for NDK compile */
  8664. struct mg_str name_esc = mg_url_encode(mg_mk_str(name));
  8665. mg_gmt_time_string(mtime, sizeof(mtime), &t);
  8666. mg_printf(nc,
  8667. "<d:response>"
  8668. "<d:href>%s</d:href>"
  8669. "<d:propstat>"
  8670. "<d:prop>"
  8671. "<d:resourcetype>%s</d:resourcetype>"
  8672. "<d:getcontentlength>%" INT64_FMT
  8673. "</d:getcontentlength>"
  8674. "<d:getlastmodified>%s</d:getlastmodified>"
  8675. "</d:prop>"
  8676. "<d:status>HTTP/1.1 200 OK</d:status>"
  8677. "</d:propstat>"
  8678. "</d:response>\n",
  8679. name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
  8680. (int64_t) stp->st_size, mtime);
  8681. free((void *) name_esc.p);
  8682. }
  8683. MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
  8684. cs_stat_t *stp, struct http_message *hm,
  8685. struct mg_serve_http_opts *opts) {
  8686. static const char header[] =
  8687. "HTTP/1.1 207 Multi-Status\r\n"
  8688. "Connection: close\r\n"
  8689. "Content-Type: text/xml; charset=utf-8\r\n\r\n"
  8690. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8691. "<d:multistatus xmlns:d='DAV:'>\n";
  8692. static const char footer[] = "</d:multistatus>\n";
  8693. const struct mg_str *depth = mg_get_http_header(hm, "Depth");
  8694. /* Print properties for the requested resource itself */
  8695. if (S_ISDIR(stp->st_mode) &&
  8696. strcmp(opts->enable_directory_listing, "yes") != 0) {
  8697. mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
  8698. } else {
  8699. char uri[MG_MAX_PATH];
  8700. mg_send(nc, header, sizeof(header) - 1);
  8701. snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
  8702. mg_print_props(nc, uri, stp);
  8703. if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
  8704. mg_scan_directory(nc, path, opts, mg_print_props);
  8705. }
  8706. mg_send(nc, footer, sizeof(footer) - 1);
  8707. nc->flags |= MG_F_SEND_AND_CLOSE;
  8708. }
  8709. }
  8710. #if MG_ENABLE_FAKE_DAVLOCK
  8711. /*
  8712. * Windows explorer (probably there are another WebDav clients like it)
  8713. * requires LOCK support in webdav. W/out this, it still works, but fails
  8714. * to save file: shows error message and offers "Save As".
  8715. * "Save as" works, but this message is very annoying.
  8716. * This is fake lock, which doesn't lock something, just returns LOCK token,
  8717. * UNLOCK always answers "OK".
  8718. * With this fake LOCK Windows Explorer looks happy and saves file.
  8719. * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
  8720. * Windows native DAV client. This is why FAKE LOCK is not enabed by default
  8721. */
  8722. MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
  8723. static const char *reply =
  8724. "HTTP/1.1 207 Multi-Status\r\n"
  8725. "Connection: close\r\n"
  8726. "Content-Type: text/xml; charset=utf-8\r\n\r\n"
  8727. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  8728. "<d:multistatus xmlns:d='DAV:'>\n"
  8729. "<D:lockdiscovery>\n"
  8730. "<D:activelock>\n"
  8731. "<D:locktoken>\n"
  8732. "<D:href>\n"
  8733. "opaquelocktoken:%s%u"
  8734. "</D:href>"
  8735. "</D:locktoken>"
  8736. "</D:activelock>\n"
  8737. "</D:lockdiscovery>"
  8738. "</d:multistatus>\n";
  8739. mg_printf(nc, reply, path, (unsigned int) mg_time());
  8740. nc->flags |= MG_F_SEND_AND_CLOSE;
  8741. }
  8742. #endif
  8743. MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
  8744. struct http_message *hm) {
  8745. int status_code = 500;
  8746. if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
  8747. status_code = 415;
  8748. } else if (!mg_mkdir(path, 0755)) {
  8749. status_code = 201;
  8750. } else if (errno == EEXIST) {
  8751. status_code = 405;
  8752. } else if (errno == EACCES) {
  8753. status_code = 403;
  8754. } else if (errno == ENOENT) {
  8755. status_code = 409;
  8756. } else {
  8757. status_code = 500;
  8758. }
  8759. mg_http_send_error(nc, status_code, NULL);
  8760. }
  8761. static int mg_remove_directory(const struct mg_serve_http_opts *opts,
  8762. const char *dir) {
  8763. char path[MG_MAX_PATH];
  8764. struct dirent *dp;
  8765. cs_stat_t st;
  8766. DIR *dirp;
  8767. if ((dirp = opendir(dir)) == NULL) return 0;
  8768. while ((dp = readdir(dirp)) != NULL) {
  8769. if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
  8770. continue;
  8771. }
  8772. snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  8773. mg_stat(path, &st);
  8774. if (S_ISDIR(st.st_mode)) {
  8775. mg_remove_directory(opts, path);
  8776. } else {
  8777. remove(path);
  8778. }
  8779. }
  8780. closedir(dirp);
  8781. rmdir(dir);
  8782. return 1;
  8783. }
  8784. MG_INTERNAL void mg_handle_move(struct mg_connection *c,
  8785. const struct mg_serve_http_opts *opts,
  8786. const char *path, struct http_message *hm) {
  8787. const struct mg_str *dest = mg_get_http_header(hm, "Destination");
  8788. if (dest == NULL) {
  8789. mg_http_send_error(c, 411, NULL);
  8790. } else {
  8791. const char *p = (char *) memchr(dest->p, '/', dest->len);
  8792. if (p != NULL && p[1] == '/' &&
  8793. (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
  8794. char buf[MG_MAX_PATH];
  8795. snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
  8796. (int) (dest->p + dest->len - p), p);
  8797. if (rename(path, buf) == 0) {
  8798. mg_http_send_error(c, 200, NULL);
  8799. } else {
  8800. mg_http_send_error(c, 418, NULL);
  8801. }
  8802. } else {
  8803. mg_http_send_error(c, 500, NULL);
  8804. }
  8805. }
  8806. }
  8807. MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
  8808. const struct mg_serve_http_opts *opts,
  8809. const char *path) {
  8810. cs_stat_t st;
  8811. if (mg_stat(path, &st) != 0) {
  8812. mg_http_send_error(nc, 404, NULL);
  8813. } else if (S_ISDIR(st.st_mode)) {
  8814. mg_remove_directory(opts, path);
  8815. mg_http_send_error(nc, 204, NULL);
  8816. } else if (remove(path) == 0) {
  8817. mg_http_send_error(nc, 204, NULL);
  8818. } else {
  8819. mg_http_send_error(nc, 423, NULL);
  8820. }
  8821. }
  8822. /* Return -1 on error, 1 on success. */
  8823. static int mg_create_itermediate_directories(const char *path) {
  8824. const char *s;
  8825. /* Create intermediate directories if they do not exist */
  8826. for (s = path + 1; *s != '\0'; s++) {
  8827. if (*s == '/') {
  8828. char buf[MG_MAX_PATH];
  8829. cs_stat_t st;
  8830. snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
  8831. buf[sizeof(buf) - 1] = '\0';
  8832. if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
  8833. return -1;
  8834. }
  8835. }
  8836. }
  8837. return 1;
  8838. }
  8839. MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
  8840. struct http_message *hm) {
  8841. struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
  8842. cs_stat_t st;
  8843. const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
  8844. int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  8845. mg_http_free_proto_data_file(&pd->file);
  8846. if ((rc = mg_create_itermediate_directories(path)) == 0) {
  8847. mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
  8848. } else if (rc == -1) {
  8849. mg_http_send_error(nc, 500, NULL);
  8850. } else if (cl_hdr == NULL) {
  8851. mg_http_send_error(nc, 411, NULL);
  8852. } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
  8853. mg_http_send_error(nc, 500, NULL);
  8854. } else {
  8855. const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
  8856. int64_t r1 = 0, r2 = 0;
  8857. pd->file.type = DATA_PUT;
  8858. mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
  8859. pd->file.cl = to64(cl_hdr->p);
  8860. if (range_hdr != NULL &&
  8861. mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
  8862. status_code = 206;
  8863. fseeko(pd->file.fp, r1, SEEK_SET);
  8864. pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
  8865. }
  8866. mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
  8867. /* Remove HTTP request from the mbuf, leave only payload */
  8868. mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
  8869. mg_http_transfer_file_data(nc);
  8870. }
  8871. }
  8872. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
  8873. #ifdef MG_MODULE_LINES
  8874. #line 1 "mongoose/src/mg_http_websocket.c"
  8875. #endif
  8876. /*
  8877. * Copyright (c) 2014 Cesanta Software Limited
  8878. * All rights reserved
  8879. */
  8880. #if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
  8881. /* Amalgamated: #include "common/cs_sha1.h" */
  8882. #ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
  8883. #define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
  8884. #endif
  8885. #define FLAGS_MASK_FIN (1 << 7)
  8886. #define FLAGS_MASK_OP 0x0f
  8887. static int mg_is_ws_fragment(unsigned char flags) {
  8888. return (flags & FLAGS_MASK_FIN) == 0 ||
  8889. (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE;
  8890. }
  8891. static int mg_is_ws_first_fragment(unsigned char flags) {
  8892. return (flags & FLAGS_MASK_FIN) == 0 &&
  8893. (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE;
  8894. }
  8895. static int mg_is_ws_control_frame(unsigned char flags) {
  8896. unsigned char op = (flags & FLAGS_MASK_OP);
  8897. return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING ||
  8898. op == WEBSOCKET_OP_PONG;
  8899. }
  8900. static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
  8901. struct websocket_message *wsm) {
  8902. if (wsm->flags & 0x8) {
  8903. mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
  8904. } else {
  8905. mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm);
  8906. }
  8907. }
  8908. static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) {
  8909. struct mg_http_proto_data *htd = mg_http_get_proto_data(nc);
  8910. return (htd != NULL ? &htd->ws_data : NULL);
  8911. }
  8912. /*
  8913. * Sends a Close websocket frame with the given data, and closes the underlying
  8914. * connection. If `len` is ~0, strlen(data) is used.
  8915. */
  8916. static void mg_ws_close(struct mg_connection *nc, const void *data,
  8917. size_t len) {
  8918. if ((int) len == ~0) {
  8919. len = strlen((const char *) data);
  8920. }
  8921. mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len);
  8922. nc->flags |= MG_F_SEND_AND_CLOSE;
  8923. }
  8924. static int mg_deliver_websocket_data(struct mg_connection *nc) {
  8925. /* Using unsigned char *, cause of integer arithmetic below */
  8926. uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len,
  8927. len, mask_len = 0, header_len = 0;
  8928. struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc);
  8929. unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf,
  8930. *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len;
  8931. uint8_t flags;
  8932. int ok, reass;
  8933. if (wsd->reass_len > 0) {
  8934. /*
  8935. * We already have some previously received data which we need to
  8936. * reassemble and deliver to the client code when we get the final
  8937. * fragment.
  8938. *
  8939. * NOTE: it doesn't mean that the current message must be a continuation:
  8940. * it might be a control frame (Close, Ping or Pong), which should be
  8941. * handled without breaking the fragmented message.
  8942. */
  8943. size_t existing_len = wsd->reass_len;
  8944. assert(new_data_len >= existing_len);
  8945. new_data += existing_len;
  8946. new_data_len -= existing_len;
  8947. }
  8948. flags = new_data[0];
  8949. reass = new_data_len > 0 && mg_is_ws_fragment(flags) &&
  8950. !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
  8951. if (reass && mg_is_ws_control_frame(flags)) {
  8952. /*
  8953. * Control frames can't be fragmented, so if we encounter fragmented
  8954. * control frame, close connection immediately.
  8955. */
  8956. mg_ws_close(nc, "fragmented control frames are illegal", ~0);
  8957. return 0;
  8958. } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) &&
  8959. wsd->reass_len > 0) {
  8960. /*
  8961. * When in the middle of a fragmented message, only the continuations
  8962. * and control frames are allowed.
  8963. */
  8964. mg_ws_close(nc, "non-continuation in the middle of a fragmented message",
  8965. ~0);
  8966. return 0;
  8967. }
  8968. if (new_data_len >= 2) {
  8969. len = new_data[1] & 0x7f;
  8970. mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0;
  8971. if (len < 126 && new_data_len >= mask_len) {
  8972. data_len = len;
  8973. header_len = 2 + mask_len;
  8974. } else if (len == 126 && new_data_len >= 4 + mask_len) {
  8975. header_len = 4 + mask_len;
  8976. data_len = ntohs(*(uint16_t *) &new_data[2]);
  8977. } else if (new_data_len >= 10 + mask_len) {
  8978. header_len = 10 + mask_len;
  8979. data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) +
  8980. ntohl(*(uint32_t *) &new_data[6]);
  8981. }
  8982. }
  8983. frame_len = header_len + data_len;
  8984. ok = (frame_len > 0 && frame_len <= new_data_len);
  8985. /* Check for overflow */
  8986. if (frame_len < header_len || frame_len < data_len) {
  8987. ok = 0;
  8988. mg_ws_close(nc, "overflowed message", ~0);
  8989. }
  8990. if (ok) {
  8991. size_t cleanup_len = 0;
  8992. struct websocket_message wsm;
  8993. wsm.size = (size_t) data_len;
  8994. wsm.data = new_data + header_len;
  8995. wsm.flags = flags;
  8996. /* Apply mask if necessary */
  8997. if (mask_len > 0) {
  8998. for (i = 0; i < data_len; i++) {
  8999. new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4];
  9000. }
  9001. }
  9002. if (reass) {
  9003. /* This is a message fragment */
  9004. if (mg_is_ws_first_fragment(flags)) {
  9005. /*
  9006. * On the first fragmented frame, skip the first byte (op) and also
  9007. * reset size to 1 (op), it'll be incremented with the data len below.
  9008. */
  9009. new_data += 1;
  9010. wsd->reass_len = 1 /* op */;
  9011. }
  9012. /* Append this frame to the reassembled buffer */
  9013. memmove(new_data, wsm.data, e - wsm.data);
  9014. wsd->reass_len += wsm.size;
  9015. nc->recv_mbuf.len -= wsm.data - new_data;
  9016. if (flags & FLAGS_MASK_FIN) {
  9017. /* On last fragmented frame - call user handler and remove data */
  9018. wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0];
  9019. wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */;
  9020. wsm.size = wsd->reass_len - 1 /* op */;
  9021. cleanup_len = wsd->reass_len;
  9022. wsd->reass_len = 0;
  9023. /* Pass reassembled message to the client code. */
  9024. mg_handle_incoming_websocket_frame(nc, &wsm);
  9025. mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */
  9026. }
  9027. } else {
  9028. /*
  9029. * This is a complete message, not a fragment. It might happen in between
  9030. * of a fragmented message (in this case, WebSocket protocol requires
  9031. * current message to be a control frame).
  9032. */
  9033. cleanup_len = (size_t) frame_len;
  9034. /* First of all, check if we need to react on a control frame. */
  9035. switch (flags & FLAGS_MASK_OP) {
  9036. case WEBSOCKET_OP_PING:
  9037. mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size);
  9038. break;
  9039. case WEBSOCKET_OP_CLOSE:
  9040. mg_ws_close(nc, wsm.data, wsm.size);
  9041. break;
  9042. }
  9043. /* Pass received message to the client code. */
  9044. mg_handle_incoming_websocket_frame(nc, &wsm);
  9045. /* Cleanup frame */
  9046. memmove(nc->recv_mbuf.buf + wsd->reass_len,
  9047. nc->recv_mbuf.buf + wsd->reass_len + cleanup_len,
  9048. nc->recv_mbuf.len - wsd->reass_len - cleanup_len);
  9049. nc->recv_mbuf.len -= cleanup_len;
  9050. }
  9051. }
  9052. return ok;
  9053. }
  9054. struct ws_mask_ctx {
  9055. size_t pos; /* zero means unmasked */
  9056. uint32_t mask;
  9057. };
  9058. static uint32_t mg_ws_random_mask(void) {
  9059. uint32_t mask;
  9060. /*
  9061. * The spec requires WS client to generate hard to
  9062. * guess mask keys. From RFC6455, Section 5.3:
  9063. *
  9064. * The unpredictability of the masking key is essential to prevent
  9065. * authors of malicious applications from selecting the bytes that appear on
  9066. * the wire.
  9067. *
  9068. * Hence this feature is essential when the actual end user of this API
  9069. * is untrusted code that wouldn't have access to a lower level net API
  9070. * anyway (e.g. web browsers). Hence this feature is low prio for most
  9071. * mongoose use cases and thus can be disabled, e.g. when porting to a platform
  9072. * that lacks rand().
  9073. */
  9074. #if MG_DISABLE_WS_RANDOM_MASK
  9075. mask = 0xefbeadde; /* generated with a random number generator, I swear */
  9076. #else
  9077. if (sizeof(long) >= 4) {
  9078. mask = (uint32_t) rand();
  9079. } else if (sizeof(long) == 2) {
  9080. mask = (uint32_t) rand() << 16 | (uint32_t) rand();
  9081. }
  9082. #endif
  9083. return mask;
  9084. }
  9085. static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
  9086. struct ws_mask_ctx *ctx) {
  9087. int header_len;
  9088. unsigned char header[10];
  9089. header[0] =
  9090. (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP);
  9091. if (len < 126) {
  9092. header[1] = (unsigned char) len;
  9093. header_len = 2;
  9094. } else if (len < 65535) {
  9095. uint16_t tmp = htons((uint16_t) len);
  9096. header[1] = 126;
  9097. memcpy(&header[2], &tmp, sizeof(tmp));
  9098. header_len = 4;
  9099. } else {
  9100. uint32_t tmp;
  9101. header[1] = 127;
  9102. tmp = htonl((uint32_t)((uint64_t) len >> 32));
  9103. memcpy(&header[2], &tmp, sizeof(tmp));
  9104. tmp = htonl((uint32_t)(len & 0xffffffff));
  9105. memcpy(&header[6], &tmp, sizeof(tmp));
  9106. header_len = 10;
  9107. }
  9108. /* client connections enable masking */
  9109. if (nc->listener == NULL) {
  9110. header[1] |= 1 << 7; /* set masking flag */
  9111. mg_send(nc, header, header_len);
  9112. ctx->mask = mg_ws_random_mask();
  9113. mg_send(nc, &ctx->mask, sizeof(ctx->mask));
  9114. ctx->pos = nc->send_mbuf.len;
  9115. } else {
  9116. mg_send(nc, header, header_len);
  9117. ctx->pos = 0;
  9118. }
  9119. }
  9120. static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
  9121. size_t i;
  9122. if (ctx->pos == 0) return;
  9123. for (i = 0; i < (mbuf->len - ctx->pos); i++) {
  9124. mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
  9125. }
  9126. }
  9127. void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
  9128. size_t len) {
  9129. struct ws_mask_ctx ctx;
  9130. DBG(("%p %d %d", nc, op, (int) len));
  9131. mg_send_ws_header(nc, op, len, &ctx);
  9132. mg_send(nc, data, len);
  9133. mg_ws_mask_frame(&nc->send_mbuf, &ctx);
  9134. if (op == WEBSOCKET_OP_CLOSE) {
  9135. nc->flags |= MG_F_SEND_AND_CLOSE;
  9136. }
  9137. }
  9138. void mg_send_websocket_framev(struct mg_connection *nc, int op,
  9139. const struct mg_str *strv, int strvcnt) {
  9140. struct ws_mask_ctx ctx;
  9141. int i;
  9142. int len = 0;
  9143. for (i = 0; i < strvcnt; i++) {
  9144. len += strv[i].len;
  9145. }
  9146. mg_send_ws_header(nc, op, len, &ctx);
  9147. for (i = 0; i < strvcnt; i++) {
  9148. mg_send(nc, strv[i].p, strv[i].len);
  9149. }
  9150. mg_ws_mask_frame(&nc->send_mbuf, &ctx);
  9151. if (op == WEBSOCKET_OP_CLOSE) {
  9152. nc->flags |= MG_F_SEND_AND_CLOSE;
  9153. }
  9154. }
  9155. void mg_printf_websocket_frame(struct mg_connection *nc, int op,
  9156. const char *fmt, ...) {
  9157. char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
  9158. va_list ap;
  9159. int len;
  9160. va_start(ap, fmt);
  9161. if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  9162. mg_send_websocket_frame(nc, op, buf, len);
  9163. }
  9164. va_end(ap);
  9165. if (buf != mem && buf != NULL) {
  9166. MG_FREE(buf);
  9167. }
  9168. }
  9169. MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
  9170. void *ev_data MG_UD_ARG(void *user_data)) {
  9171. mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
  9172. switch (ev) {
  9173. case MG_EV_RECV:
  9174. do {
  9175. } while (mg_deliver_websocket_data(nc));
  9176. break;
  9177. case MG_EV_POLL:
  9178. /* Ping idle websocket connections */
  9179. {
  9180. time_t now = *(time_t *) ev_data;
  9181. if (nc->flags & MG_F_IS_WEBSOCKET &&
  9182. now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
  9183. mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
  9184. }
  9185. }
  9186. break;
  9187. default:
  9188. break;
  9189. }
  9190. #if MG_ENABLE_CALLBACK_USERDATA
  9191. (void) user_data;
  9192. #endif
  9193. }
  9194. #ifndef MG_EXT_SHA1
  9195. void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
  9196. const size_t *msg_lens, uint8_t *digest) {
  9197. size_t i;
  9198. cs_sha1_ctx sha_ctx;
  9199. cs_sha1_init(&sha_ctx);
  9200. for (i = 0; i < num_msgs; i++) {
  9201. cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
  9202. }
  9203. cs_sha1_final(digest, &sha_ctx);
  9204. }
  9205. #else
  9206. extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
  9207. const size_t *msg_lens, uint8_t *digest);
  9208. #endif
  9209. MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
  9210. const struct mg_str *key,
  9211. struct http_message *hm) {
  9212. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9213. const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
  9214. const size_t msg_lens[2] = {key->len, 36};
  9215. unsigned char sha[20];
  9216. char b64_sha[30];
  9217. struct mg_str *s;
  9218. mg_hash_sha1_v(2, msgs, msg_lens, sha);
  9219. mg_base64_encode(sha, sizeof(sha), b64_sha);
  9220. mg_printf(nc, "%s",
  9221. "HTTP/1.1 101 Switching Protocols\r\n"
  9222. "Upgrade: websocket\r\n"
  9223. "Connection: Upgrade\r\n");
  9224. s = mg_get_http_header(hm, "Sec-WebSocket-Protocol");
  9225. if (s != NULL) {
  9226. mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p);
  9227. }
  9228. mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n");
  9229. DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
  9230. }
  9231. void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
  9232. const char *host, const char *protocol,
  9233. const char *extra_headers) {
  9234. mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
  9235. NULL);
  9236. }
  9237. void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
  9238. const char *host, const char *protocol,
  9239. const char *extra_headers, const char *user,
  9240. const char *pass) {
  9241. mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host),
  9242. mg_mk_str(protocol), mg_mk_str(extra_headers),
  9243. mg_mk_str(user), mg_mk_str(pass));
  9244. }
  9245. void mg_send_websocket_handshake3v(struct mg_connection *nc,
  9246. const struct mg_str path,
  9247. const struct mg_str host,
  9248. const struct mg_str protocol,
  9249. const struct mg_str extra_headers,
  9250. const struct mg_str user,
  9251. const struct mg_str pass) {
  9252. struct mbuf auth;
  9253. char key[25];
  9254. uint32_t nonce[4];
  9255. nonce[0] = mg_ws_random_mask();
  9256. nonce[1] = mg_ws_random_mask();
  9257. nonce[2] = mg_ws_random_mask();
  9258. nonce[3] = mg_ws_random_mask();
  9259. mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
  9260. mbuf_init(&auth, 0);
  9261. if (user.len > 0) {
  9262. mg_basic_auth_header(user, pass, &auth);
  9263. }
  9264. /*
  9265. * NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
  9266. * broken: it doesn't like zero length to be passed to %.*s
  9267. * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
  9268. * because it handles NULL specially (and incorrectly).
  9269. */
  9270. mg_printf(nc,
  9271. "GET %.*s HTTP/1.1\r\n"
  9272. "Upgrade: websocket\r\n"
  9273. "Connection: Upgrade\r\n"
  9274. "%.*s"
  9275. "Sec-WebSocket-Version: 13\r\n"
  9276. "Sec-WebSocket-Key: %s\r\n",
  9277. (int) path.len, path.p, (int) auth.len,
  9278. (auth.buf == NULL ? "" : auth.buf), key);
  9279. /* TODO(mkm): take default hostname from http proto data if host == NULL */
  9280. if (host.len > 0) {
  9281. int host_len = (int) (path.p - host.p); /* Account for possible :PORT */
  9282. mg_printf(nc, "Host: %.*s\r\n", host_len, host.p);
  9283. }
  9284. if (protocol.len > 0) {
  9285. mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len,
  9286. protocol.p);
  9287. }
  9288. if (extra_headers.len > 0) {
  9289. mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p);
  9290. }
  9291. mg_printf(nc, "\r\n");
  9292. nc->flags |= MG_F_IS_WEBSOCKET;
  9293. mbuf_free(&auth);
  9294. }
  9295. void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
  9296. const char *extra_headers) {
  9297. struct mg_str null_str = MG_NULL_STR;
  9298. mg_send_websocket_handshake3v(
  9299. nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */,
  9300. mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */);
  9301. }
  9302. struct mg_connection *mg_connect_ws_opt(
  9303. struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
  9304. struct mg_connect_opts opts, const char *url, const char *protocol,
  9305. const char *extra_headers) {
  9306. struct mg_str null_str = MG_NULL_STR;
  9307. struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR;
  9308. struct mg_connection *nc =
  9309. mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
  9310. "ws", "https", "wss", url, &path, &user_info, &host);
  9311. if (nc != NULL) {
  9312. mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol),
  9313. mg_mk_str(extra_headers), user_info,
  9314. null_str);
  9315. }
  9316. return nc;
  9317. }
  9318. struct mg_connection *mg_connect_ws(
  9319. struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
  9320. const char *url, const char *protocol, const char *extra_headers) {
  9321. struct mg_connect_opts opts;
  9322. memset(&opts, 0, sizeof(opts));
  9323. return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
  9324. protocol, extra_headers);
  9325. }
  9326. #endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
  9327. #ifdef MG_MODULE_LINES
  9328. #line 1 "mongoose/src/mg_util.c"
  9329. #endif
  9330. /*
  9331. * Copyright (c) 2014 Cesanta Software Limited
  9332. * All rights reserved
  9333. */
  9334. /* Amalgamated: #include "common/cs_base64.h" */
  9335. /* Amalgamated: #include "mg_internal.h" */
  9336. /* Amalgamated: #include "mg_util.h" */
  9337. /* For platforms with limited libc */
  9338. #ifndef MAX
  9339. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  9340. #endif
  9341. const char *mg_skip(const char *s, const char *end, const char *delims,
  9342. struct mg_str *v) {
  9343. v->p = s;
  9344. while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
  9345. v->len = s - v->p;
  9346. while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
  9347. return s;
  9348. }
  9349. #if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS)
  9350. int mg_stat(const char *path, cs_stat_t *st) {
  9351. #ifdef _WIN32
  9352. wchar_t wpath[MG_MAX_PATH];
  9353. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  9354. DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
  9355. return _wstati64(wpath, st);
  9356. #else
  9357. return stat(path, st);
  9358. #endif
  9359. }
  9360. FILE *mg_fopen(const char *path, const char *mode) {
  9361. #ifdef _WIN32
  9362. wchar_t wpath[MG_MAX_PATH], wmode[10];
  9363. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  9364. to_wchar(mode, wmode, ARRAY_SIZE(wmode));
  9365. return _wfopen(wpath, wmode);
  9366. #else
  9367. return fopen(path, mode);
  9368. #endif
  9369. }
  9370. int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
  9371. #if defined(_WIN32) && !defined(WINCE)
  9372. wchar_t wpath[MG_MAX_PATH];
  9373. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  9374. return _wopen(wpath, flag, mode);
  9375. #else
  9376. return open(path, flag, mode); /* LCOV_EXCL_LINE */
  9377. #endif
  9378. }
  9379. size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) {
  9380. return fread(ptr, size, count, f);
  9381. }
  9382. size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) {
  9383. return fwrite(ptr, size, count, f);
  9384. }
  9385. #endif
  9386. void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
  9387. cs_base64_encode(src, src_len, dst);
  9388. }
  9389. int mg_base64_decode(const unsigned char *s, int len, char *dst) {
  9390. return cs_base64_decode(s, len, dst, NULL);
  9391. }
  9392. #if MG_ENABLE_THREADS
  9393. void *mg_start_thread(void *(*f)(void *), void *p) {
  9394. #ifdef WINCE
  9395. return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
  9396. #elif defined(_WIN32)
  9397. return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
  9398. #else
  9399. pthread_t thread_id = (pthread_t) 0;
  9400. pthread_attr_t attr;
  9401. (void) pthread_attr_init(&attr);
  9402. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  9403. #if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
  9404. (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
  9405. #endif
  9406. pthread_create(&thread_id, &attr, f, p);
  9407. pthread_attr_destroy(&attr);
  9408. return (void *) thread_id;
  9409. #endif
  9410. }
  9411. #endif /* MG_ENABLE_THREADS */
  9412. /* Set close-on-exec bit for a given socket. */
  9413. void mg_set_close_on_exec(sock_t sock) {
  9414. #if defined(_WIN32) && !defined(WINCE)
  9415. (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
  9416. #elif defined(__unix__)
  9417. fcntl(sock, F_SETFD, FD_CLOEXEC);
  9418. #else
  9419. (void) sock;
  9420. #endif
  9421. }
  9422. int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
  9423. int flags) {
  9424. int is_v6;
  9425. if (buf == NULL || len <= 0) return 0;
  9426. memset(buf, 0, len);
  9427. #if MG_ENABLE_IPV6
  9428. is_v6 = sa->sa.sa_family == AF_INET6;
  9429. #else
  9430. is_v6 = 0;
  9431. #endif
  9432. if (flags & MG_SOCK_STRINGIFY_IP) {
  9433. #if MG_ENABLE_IPV6
  9434. const void *addr = NULL;
  9435. char *start = buf;
  9436. socklen_t capacity = len;
  9437. if (!is_v6) {
  9438. addr = &sa->sin.sin_addr;
  9439. } else {
  9440. addr = (void *) &sa->sin6.sin6_addr;
  9441. if (flags & MG_SOCK_STRINGIFY_PORT) {
  9442. *buf = '[';
  9443. start++;
  9444. capacity--;
  9445. }
  9446. }
  9447. if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
  9448. goto cleanup;
  9449. }
  9450. #elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
  9451. /* Only Windoze Vista (and newer) have inet_ntop() */
  9452. char *addr_str = inet_ntoa(sa->sin.sin_addr);
  9453. if (addr_str != NULL) {
  9454. strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
  9455. } else {
  9456. goto cleanup;
  9457. }
  9458. #else
  9459. if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len) == NULL) {
  9460. goto cleanup;
  9461. }
  9462. #endif
  9463. }
  9464. if (flags & MG_SOCK_STRINGIFY_PORT) {
  9465. int port = ntohs(sa->sin.sin_port);
  9466. if (flags & MG_SOCK_STRINGIFY_IP) {
  9467. int buf_len = strlen(buf);
  9468. snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
  9469. port);
  9470. } else {
  9471. snprintf(buf, len, "%d", port);
  9472. }
  9473. }
  9474. return strlen(buf);
  9475. cleanup:
  9476. *buf = '\0';
  9477. return 0;
  9478. }
  9479. int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
  9480. int flags) {
  9481. union socket_address sa;
  9482. memset(&sa, 0, sizeof(sa));
  9483. mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
  9484. return mg_sock_addr_to_str(&sa, buf, len, flags);
  9485. }
  9486. #if MG_ENABLE_HEXDUMP
  9487. static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
  9488. int offset) {
  9489. const unsigned char *p = (const unsigned char *) buf;
  9490. char ascii[17] = "";
  9491. int i, idx, n = 0;
  9492. for (i = 0; i < len; i++) {
  9493. idx = i % 16;
  9494. if (idx == 0) {
  9495. if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
  9496. n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
  9497. }
  9498. if (dst_len - n < 0) {
  9499. return n;
  9500. }
  9501. n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
  9502. ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
  9503. ascii[idx + 1] = '\0';
  9504. }
  9505. while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " ");
  9506. n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
  9507. return n;
  9508. }
  9509. int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
  9510. return mg_hexdump_n(buf, len, dst, dst_len, 0);
  9511. }
  9512. void mg_hexdumpf(FILE *fp, const void *buf, int len) {
  9513. char tmp[80];
  9514. int offset = 0, n;
  9515. while (len > 0) {
  9516. n = (len < 16 ? len : 16);
  9517. mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
  9518. fputs(tmp, fp);
  9519. offset += n;
  9520. len -= n;
  9521. }
  9522. }
  9523. void mg_hexdump_connection(struct mg_connection *nc, const char *path,
  9524. const void *buf, int num_bytes, int ev) {
  9525. FILE *fp = NULL;
  9526. char src[60], dst[60];
  9527. const char *tag = NULL;
  9528. switch (ev) {
  9529. case MG_EV_RECV:
  9530. tag = "<-";
  9531. break;
  9532. case MG_EV_SEND:
  9533. tag = "->";
  9534. break;
  9535. case MG_EV_ACCEPT:
  9536. tag = "<A";
  9537. break;
  9538. case MG_EV_CONNECT:
  9539. tag = "C>";
  9540. break;
  9541. case MG_EV_CLOSE:
  9542. tag = "XX";
  9543. break;
  9544. }
  9545. if (tag == NULL) return; /* Don't log MG_EV_TIMER, etc */
  9546. if (strcmp(path, "-") == 0) {
  9547. fp = stdout;
  9548. } else if (strcmp(path, "--") == 0) {
  9549. fp = stderr;
  9550. #if MG_ENABLE_FILESYSTEM
  9551. } else {
  9552. fp = mg_fopen(path, "a");
  9553. #endif
  9554. }
  9555. if (fp == NULL) return;
  9556. mg_conn_addr_to_str(nc, src, sizeof(src),
  9557. MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
  9558. mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
  9559. MG_SOCK_STRINGIFY_PORT |
  9560. MG_SOCK_STRINGIFY_REMOTE);
  9561. fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc,
  9562. src, tag, dst, (int) num_bytes);
  9563. if (num_bytes > 0) {
  9564. mg_hexdumpf(fp, buf, num_bytes);
  9565. }
  9566. if (fp != stdout && fp != stderr) fclose(fp);
  9567. }
  9568. #endif
  9569. int mg_is_big_endian(void) {
  9570. static const int n = 1;
  9571. /* TODO(mkm) use compiletime check with 4-byte char literal */
  9572. return ((char *) &n)[0] == 0;
  9573. }
  9574. DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
  9575. #ifndef WINCE
  9576. return errno;
  9577. #else
  9578. /* TODO(alashkin): translate error codes? */
  9579. return GetLastError();
  9580. #endif
  9581. }
  9582. void mg_mbuf_append_base64_putc(char ch, void *user_data) {
  9583. struct mbuf *mbuf = (struct mbuf *) user_data;
  9584. mbuf_append(mbuf, &ch, sizeof(ch));
  9585. }
  9586. void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
  9587. struct cs_base64_ctx ctx;
  9588. cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
  9589. cs_base64_update(&ctx, (const char *) data, len);
  9590. cs_base64_finish(&ctx);
  9591. }
  9592. void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass,
  9593. struct mbuf *buf) {
  9594. const char *header_prefix = "Authorization: Basic ";
  9595. const char *header_suffix = "\r\n";
  9596. struct cs_base64_ctx ctx;
  9597. cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
  9598. mbuf_append(buf, header_prefix, strlen(header_prefix));
  9599. cs_base64_update(&ctx, user.p, user.len);
  9600. if (pass.len > 0) {
  9601. cs_base64_update(&ctx, ":", 1);
  9602. cs_base64_update(&ctx, pass.p, pass.len);
  9603. }
  9604. cs_base64_finish(&ctx);
  9605. mbuf_append(buf, header_suffix, strlen(header_suffix));
  9606. }
  9607. struct mg_str mg_url_encode_opt(const struct mg_str src,
  9608. const struct mg_str safe, unsigned int flags) {
  9609. const char *hex =
  9610. (flags & MG_URL_ENCODE_F_UPPERCASE_HEX ? "0123456789ABCDEF"
  9611. : "0123456789abcdef");
  9612. size_t i = 0;
  9613. struct mbuf mb;
  9614. mbuf_init(&mb, src.len);
  9615. for (i = 0; i < src.len; i++) {
  9616. const unsigned char c = *((const unsigned char *) src.p + i);
  9617. if (isalnum(c) || mg_strchr(safe, c) != NULL) {
  9618. mbuf_append(&mb, &c, 1);
  9619. } else if (c == ' ' && (flags & MG_URL_ENCODE_F_SPACE_AS_PLUS)) {
  9620. mbuf_append(&mb, "+", 1);
  9621. } else {
  9622. mbuf_append(&mb, "%", 1);
  9623. mbuf_append(&mb, &hex[c >> 4], 1);
  9624. mbuf_append(&mb, &hex[c & 15], 1);
  9625. }
  9626. }
  9627. mbuf_append(&mb, "", 1);
  9628. mbuf_trim(&mb);
  9629. return mg_mk_str_n(mb.buf, mb.len - 1);
  9630. }
  9631. struct mg_str mg_url_encode(const struct mg_str src) {
  9632. return mg_url_encode_opt(src, mg_mk_str("._-$,;~()/"), 0);
  9633. }
  9634. #ifdef MG_MODULE_LINES
  9635. #line 1 "mongoose/src/mg_mqtt.c"
  9636. #endif
  9637. /*
  9638. * Copyright (c) 2014 Cesanta Software Limited
  9639. * All rights reserved
  9640. */
  9641. #if MG_ENABLE_MQTT
  9642. #include <string.h>
  9643. /* Amalgamated: #include "mg_internal.h" */
  9644. /* Amalgamated: #include "mg_mqtt.h" */
  9645. static uint16_t getu16(const char *p) {
  9646. const uint8_t *up = (const uint8_t *) p;
  9647. return (up[0] << 8) + up[1];
  9648. }
  9649. static const char *scanto(const char *p, struct mg_str *s) {
  9650. s->len = getu16(p);
  9651. s->p = p + 2;
  9652. return s->p + s->len;
  9653. }
  9654. MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
  9655. uint8_t header;
  9656. size_t len = 0, len_len = 0;
  9657. const char *p, *end, *eop = &io->buf[io->len];
  9658. unsigned char lc = 0;
  9659. int cmd;
  9660. if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG;
  9661. header = io->buf[0];
  9662. cmd = header >> 4;
  9663. /* decode mqtt variable length */
  9664. len = len_len = 0;
  9665. p = io->buf + 1;
  9666. while (p < eop) {
  9667. lc = *((const unsigned char *) p++);
  9668. len += (lc & 0x7f) << 7 * len_len;
  9669. len_len++;
  9670. if (!(lc & 0x80)) break;
  9671. if (len_len > 4) return MG_MQTT_ERROR_MALFORMED_MSG;
  9672. }
  9673. end = p + len;
  9674. if (lc & 0x80 || end > eop) return MG_MQTT_ERROR_INCOMPLETE_MSG;
  9675. mm->cmd = cmd;
  9676. mm->qos = MG_MQTT_GET_QOS(header);
  9677. switch (cmd) {
  9678. case MG_MQTT_CMD_CONNECT: {
  9679. p = scanto(p, &mm->protocol_name);
  9680. if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG;
  9681. mm->protocol_version = *(uint8_t *) p++;
  9682. mm->connect_flags = *(uint8_t *) p++;
  9683. mm->keep_alive_timer = getu16(p);
  9684. p += 2;
  9685. if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
  9686. p = scanto(p, &mm->client_id);
  9687. if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
  9688. if (mm->connect_flags & MG_MQTT_HAS_WILL) {
  9689. if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
  9690. p = scanto(p, &mm->will_topic);
  9691. }
  9692. if (mm->connect_flags & MG_MQTT_HAS_WILL) {
  9693. if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
  9694. p = scanto(p, &mm->will_message);
  9695. }
  9696. if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) {
  9697. if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
  9698. p = scanto(p, &mm->user_name);
  9699. }
  9700. if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) {
  9701. if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
  9702. p = scanto(p, &mm->password);
  9703. }
  9704. if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG;
  9705. LOG(LL_DEBUG,
  9706. ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
  9707. "will_msg [%.*s] user_name [%.*s] password [%.*s]",
  9708. (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
  9709. (int) mm->protocol_name.len, mm->protocol_name.p,
  9710. (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
  9711. mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
  9712. (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
  9713. mm->password.p));
  9714. break;
  9715. }
  9716. case MG_MQTT_CMD_CONNACK:
  9717. if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
  9718. mm->connack_ret_code = p[1];
  9719. break;
  9720. case MG_MQTT_CMD_PUBACK:
  9721. case MG_MQTT_CMD_PUBREC:
  9722. case MG_MQTT_CMD_PUBREL:
  9723. case MG_MQTT_CMD_PUBCOMP:
  9724. case MG_MQTT_CMD_SUBACK:
  9725. if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
  9726. mm->message_id = getu16(p);
  9727. p += 2;
  9728. break;
  9729. case MG_MQTT_CMD_PUBLISH: {
  9730. p = scanto(p, &mm->topic);
  9731. if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
  9732. if (mm->qos > 0) {
  9733. if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
  9734. mm->message_id = getu16(p);
  9735. p += 2;
  9736. }
  9737. mm->payload.p = p;
  9738. mm->payload.len = end - p;
  9739. break;
  9740. }
  9741. case MG_MQTT_CMD_SUBSCRIBE:
  9742. if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
  9743. mm->message_id = getu16(p);
  9744. p += 2;
  9745. /*
  9746. * topic expressions are left in the payload and can be parsed with
  9747. * `mg_mqtt_next_subscribe_topic`
  9748. */
  9749. mm->payload.p = p;
  9750. mm->payload.len = end - p;
  9751. break;
  9752. default:
  9753. /* Unhandled command */
  9754. break;
  9755. }
  9756. mm->len = end - io->buf;
  9757. return mm->len;
  9758. }
  9759. static void mqtt_handler(struct mg_connection *nc, int ev,
  9760. void *ev_data MG_UD_ARG(void *user_data)) {
  9761. struct mbuf *io = &nc->recv_mbuf;
  9762. struct mg_mqtt_message mm;
  9763. memset(&mm, 0, sizeof(mm));
  9764. nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
  9765. switch (ev) {
  9766. case MG_EV_ACCEPT:
  9767. if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
  9768. break;
  9769. case MG_EV_RECV: {
  9770. /* There can be multiple messages in the buffer, process them all. */
  9771. while (1) {
  9772. int len = parse_mqtt(io, &mm);
  9773. if (len < 0) {
  9774. if (len == MG_MQTT_ERROR_MALFORMED_MSG) {
  9775. /* Protocol error. */
  9776. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9777. } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
  9778. /* Not fully buffered, let's check if we have a chance to get more
  9779. * data later */
  9780. if (nc->recv_mbuf_limit > 0 &&
  9781. nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
  9782. LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
  9783. "%lu bytes, and not drained, closing",
  9784. nc, (unsigned long) nc->recv_mbuf.len,
  9785. (unsigned long) nc->recv_mbuf_limit));
  9786. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9787. }
  9788. } else {
  9789. /* Should never be here */
  9790. LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len));
  9791. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  9792. }
  9793. break;
  9794. }
  9795. nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
  9796. mbuf_remove(io, len);
  9797. }
  9798. break;
  9799. }
  9800. case MG_EV_POLL: {
  9801. struct mg_mqtt_proto_data *pd =
  9802. (struct mg_mqtt_proto_data *) nc->proto_data;
  9803. double now = mg_time();
  9804. if (pd->keep_alive > 0 && pd->last_control_time > 0 &&
  9805. (now - pd->last_control_time) > pd->keep_alive) {
  9806. LOG(LL_DEBUG, ("Send PINGREQ"));
  9807. mg_mqtt_ping(nc);
  9808. }
  9809. break;
  9810. }
  9811. }
  9812. }
  9813. static void mg_mqtt_proto_data_destructor(void *proto_data) {
  9814. MG_FREE(proto_data);
  9815. }
  9816. static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) {
  9817. struct mg_str res = *topic;
  9818. const char *c = mg_strchr(*topic, '/');
  9819. if (c != NULL) {
  9820. res.len = (c - topic->p);
  9821. topic->len -= (res.len + 1);
  9822. topic->p += (res.len + 1);
  9823. } else {
  9824. topic->len = 0;
  9825. }
  9826. return res;
  9827. }
  9828. /* Refernce: https://mosquitto.org/man/mqtt-7.html */
  9829. int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
  9830. struct mg_str ec, tc;
  9831. if (exp.len == 0) return 0;
  9832. while (1) {
  9833. ec = mg_mqtt_next_topic_component(&exp);
  9834. tc = mg_mqtt_next_topic_component(&topic);
  9835. if (ec.len == 0) {
  9836. if (tc.len != 0) return 0;
  9837. if (exp.len == 0) break;
  9838. continue;
  9839. }
  9840. if (mg_vcmp(&ec, "+") == 0) {
  9841. if (tc.len == 0 && topic.len == 0) return 0;
  9842. continue;
  9843. }
  9844. if (mg_vcmp(&ec, "#") == 0) {
  9845. /* Must be the last component in the expression or it's invalid. */
  9846. return (exp.len == 0);
  9847. }
  9848. if (mg_strcmp(ec, tc) != 0) {
  9849. return 0;
  9850. }
  9851. }
  9852. return (tc.len == 0 && topic.len == 0);
  9853. }
  9854. int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
  9855. return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
  9856. }
  9857. void mg_set_protocol_mqtt(struct mg_connection *nc) {
  9858. nc->proto_handler = mqtt_handler;
  9859. nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
  9860. nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
  9861. }
  9862. static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd,
  9863. uint8_t flags, size_t len) {
  9864. struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
  9865. uint8_t buf[1 + sizeof(size_t)];
  9866. uint8_t *vlen = &buf[1];
  9867. buf[0] = (cmd << 4) | flags;
  9868. /* mqtt variable length encoding */
  9869. do {
  9870. *vlen = len % 0x80;
  9871. len /= 0x80;
  9872. if (len > 0) *vlen |= 0x80;
  9873. vlen++;
  9874. } while (len > 0);
  9875. mg_send(nc, buf, vlen - buf);
  9876. pd->last_control_time = mg_time();
  9877. }
  9878. void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
  9879. static struct mg_send_mqtt_handshake_opts opts;
  9880. mg_send_mqtt_handshake_opt(nc, client_id, opts);
  9881. }
  9882. void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
  9883. struct mg_send_mqtt_handshake_opts opts) {
  9884. struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
  9885. uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0;
  9886. uint16_t netbytes;
  9887. size_t total_len;
  9888. if (client_id != NULL) {
  9889. id_len = strlen(client_id);
  9890. }
  9891. total_len = 7 + 1 + 2 + 2 + id_len;
  9892. if (opts.user_name != NULL) {
  9893. opts.flags |= MG_MQTT_HAS_USER_NAME;
  9894. }
  9895. if (opts.password != NULL) {
  9896. opts.flags |= MG_MQTT_HAS_PASSWORD;
  9897. }
  9898. if (opts.will_topic != NULL && opts.will_message != NULL) {
  9899. wt_len = strlen(opts.will_topic);
  9900. wm_len = strlen(opts.will_message);
  9901. opts.flags |= MG_MQTT_HAS_WILL;
  9902. }
  9903. if (opts.keep_alive == 0) {
  9904. opts.keep_alive = 60;
  9905. }
  9906. if (opts.flags & MG_MQTT_HAS_WILL) {
  9907. total_len += 2 + wt_len + 2 + wm_len;
  9908. }
  9909. if (opts.flags & MG_MQTT_HAS_USER_NAME) {
  9910. user_len = strlen(opts.user_name);
  9911. total_len += 2 + user_len;
  9912. }
  9913. if (opts.flags & MG_MQTT_HAS_PASSWORD) {
  9914. pw_len = strlen(opts.password);
  9915. total_len += 2 + pw_len;
  9916. }
  9917. mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len);
  9918. mg_send(nc, "\00\04MQTT\04", 7);
  9919. mg_send(nc, &opts.flags, 1);
  9920. netbytes = htons(opts.keep_alive);
  9921. mg_send(nc, &netbytes, 2);
  9922. netbytes = htons(id_len);
  9923. mg_send(nc, &netbytes, 2);
  9924. mg_send(nc, client_id, id_len);
  9925. if (opts.flags & MG_MQTT_HAS_WILL) {
  9926. netbytes = htons(wt_len);
  9927. mg_send(nc, &netbytes, 2);
  9928. mg_send(nc, opts.will_topic, wt_len);
  9929. netbytes = htons(wm_len);
  9930. mg_send(nc, &netbytes, 2);
  9931. mg_send(nc, opts.will_message, wm_len);
  9932. }
  9933. if (opts.flags & MG_MQTT_HAS_USER_NAME) {
  9934. netbytes = htons(user_len);
  9935. mg_send(nc, &netbytes, 2);
  9936. mg_send(nc, opts.user_name, user_len);
  9937. }
  9938. if (opts.flags & MG_MQTT_HAS_PASSWORD) {
  9939. netbytes = htons(pw_len);
  9940. mg_send(nc, &netbytes, 2);
  9941. mg_send(nc, opts.password, pw_len);
  9942. }
  9943. if (pd != NULL) {
  9944. pd->keep_alive = opts.keep_alive;
  9945. }
  9946. }
  9947. void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
  9948. uint16_t message_id, int flags, const void *data,
  9949. size_t len) {
  9950. uint16_t netbytes;
  9951. uint16_t topic_len = strlen(topic);
  9952. size_t total_len = 2 + topic_len + len;
  9953. if (MG_MQTT_GET_QOS(flags) > 0) {
  9954. total_len += 2;
  9955. }
  9956. mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len);
  9957. netbytes = htons(topic_len);
  9958. mg_send(nc, &netbytes, 2);
  9959. mg_send(nc, topic, topic_len);
  9960. if (MG_MQTT_GET_QOS(flags) > 0) {
  9961. netbytes = htons(message_id);
  9962. mg_send(nc, &netbytes, 2);
  9963. }
  9964. mg_send(nc, data, len);
  9965. }
  9966. void mg_mqtt_subscribe(struct mg_connection *nc,
  9967. const struct mg_mqtt_topic_expression *topics,
  9968. size_t topics_len, uint16_t message_id) {
  9969. uint16_t netbytes;
  9970. size_t i;
  9971. uint16_t topic_len;
  9972. size_t total_len = 2;
  9973. for (i = 0; i < topics_len; i++) {
  9974. total_len += 2 + strlen(topics[i].topic) + 1;
  9975. }
  9976. mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len);
  9977. netbytes = htons(message_id);
  9978. mg_send(nc, (char *) &netbytes, 2);
  9979. for (i = 0; i < topics_len; i++) {
  9980. topic_len = strlen(topics[i].topic);
  9981. netbytes = htons(topic_len);
  9982. mg_send(nc, &netbytes, 2);
  9983. mg_send(nc, topics[i].topic, topic_len);
  9984. mg_send(nc, &topics[i].qos, 1);
  9985. }
  9986. }
  9987. int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
  9988. struct mg_str *topic, uint8_t *qos, int pos) {
  9989. unsigned char *buf = (unsigned char *) msg->payload.p + pos;
  9990. int new_pos;
  9991. if ((size_t) pos >= msg->payload.len) return -1;
  9992. topic->len = buf[0] << 8 | buf[1];
  9993. topic->p = (char *) buf + 2;
  9994. new_pos = pos + 2 + topic->len + 1;
  9995. if ((size_t) new_pos > msg->payload.len) return -1;
  9996. *qos = buf[2 + topic->len];
  9997. return new_pos;
  9998. }
  9999. void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
  10000. size_t topics_len, uint16_t message_id) {
  10001. uint16_t netbytes;
  10002. size_t i;
  10003. uint16_t topic_len;
  10004. size_t total_len = 2;
  10005. for (i = 0; i < topics_len; i++) {
  10006. total_len += 2 + strlen(topics[i]);
  10007. }
  10008. mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len);
  10009. netbytes = htons(message_id);
  10010. mg_send(nc, (char *) &netbytes, 2);
  10011. for (i = 0; i < topics_len; i++) {
  10012. topic_len = strlen(topics[i]);
  10013. netbytes = htons(topic_len);
  10014. mg_send(nc, &netbytes, 2);
  10015. mg_send(nc, topics[i], topic_len);
  10016. }
  10017. }
  10018. void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
  10019. uint8_t unused = 0;
  10020. mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
  10021. mg_send(nc, &unused, 1);
  10022. mg_send(nc, &return_code, 1);
  10023. }
  10024. /*
  10025. * Sends a command which contains only a `message_id` and a QoS level of 1.
  10026. *
  10027. * Helper function.
  10028. */
  10029. static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
  10030. uint16_t message_id) {
  10031. uint16_t netbytes;
  10032. uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
  10033. mg_send_mqtt_header(nc, cmd, flags, 2 /* len */);
  10034. netbytes = htons(message_id);
  10035. mg_send(nc, &netbytes, 2);
  10036. }
  10037. void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
  10038. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
  10039. }
  10040. void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
  10041. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
  10042. }
  10043. void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
  10044. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
  10045. }
  10046. void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
  10047. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
  10048. }
  10049. void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
  10050. uint16_t message_id) {
  10051. size_t i;
  10052. uint16_t netbytes;
  10053. mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
  10054. netbytes = htons(message_id);
  10055. mg_send(nc, &netbytes, 2);
  10056. for (i = 0; i < qoss_len; i++) {
  10057. mg_send(nc, &qoss[i], 1);
  10058. }
  10059. }
  10060. void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
  10061. mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
  10062. }
  10063. void mg_mqtt_ping(struct mg_connection *nc) {
  10064. mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
  10065. }
  10066. void mg_mqtt_pong(struct mg_connection *nc) {
  10067. mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
  10068. }
  10069. void mg_mqtt_disconnect(struct mg_connection *nc) {
  10070. mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
  10071. }
  10072. #endif /* MG_ENABLE_MQTT */
  10073. #ifdef MG_MODULE_LINES
  10074. #line 1 "mongoose/src/mg_mqtt_server.c"
  10075. #endif
  10076. /*
  10077. * Copyright (c) 2014 Cesanta Software Limited
  10078. * All rights reserved
  10079. */
  10080. /* Amalgamated: #include "mg_internal.h" */
  10081. /* Amalgamated: #include "mg_mqtt_server.h" */
  10082. #if MG_ENABLE_MQTT_BROKER
  10083. static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
  10084. struct mg_mqtt_session *s,
  10085. struct mg_connection *nc) {
  10086. s->brk = brk;
  10087. s->subscriptions = NULL;
  10088. s->num_subscriptions = 0;
  10089. s->nc = nc;
  10090. }
  10091. static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
  10092. LIST_INSERT_HEAD(&s->brk->sessions, s, link);
  10093. }
  10094. static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
  10095. LIST_REMOVE(s, link);
  10096. }
  10097. static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
  10098. size_t i;
  10099. for (i = 0; i < s->num_subscriptions; i++) {
  10100. MG_FREE((void *) s->subscriptions[i].topic);
  10101. }
  10102. MG_FREE(s->subscriptions);
  10103. MG_FREE(s);
  10104. }
  10105. static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
  10106. mg_mqtt_remove_session(s);
  10107. mg_mqtt_destroy_session(s);
  10108. }
  10109. void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
  10110. LIST_INIT(&brk->sessions);
  10111. brk->user_data = user_data;
  10112. }
  10113. static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
  10114. struct mg_connection *nc) {
  10115. struct mg_mqtt_session *s =
  10116. (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
  10117. if (s == NULL) {
  10118. /* LCOV_EXCL_START */
  10119. mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
  10120. return;
  10121. /* LCOV_EXCL_STOP */
  10122. }
  10123. /* TODO(mkm): check header (magic and version) */
  10124. mg_mqtt_session_init(brk, s, nc);
  10125. nc->priv_2 = s;
  10126. mg_mqtt_add_session(s);
  10127. mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
  10128. }
  10129. static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
  10130. struct mg_mqtt_message *msg) {
  10131. struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2;
  10132. uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS];
  10133. size_t num_subs = 0;
  10134. struct mg_str topic;
  10135. uint8_t qos;
  10136. int pos;
  10137. struct mg_mqtt_topic_expression *te;
  10138. for (pos = 0;
  10139. (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
  10140. if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) ||
  10141. (ss->num_subscriptions + num_subs >=
  10142. MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) {
  10143. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10144. return;
  10145. }
  10146. qoss[num_subs++] = qos;
  10147. }
  10148. if (num_subs > 0) {
  10149. te = (struct mg_mqtt_topic_expression *) MG_REALLOC(
  10150. ss->subscriptions,
  10151. sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs));
  10152. if (te == NULL) {
  10153. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10154. return;
  10155. }
  10156. ss->subscriptions = te;
  10157. for (pos = 0;
  10158. pos < (int) msg->payload.len &&
  10159. (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
  10160. ss->num_subscriptions++) {
  10161. te = &ss->subscriptions[ss->num_subscriptions];
  10162. te->topic = (char *) MG_MALLOC(topic.len + 1);
  10163. te->qos = qos;
  10164. memcpy((char *) te->topic, topic.p, topic.len);
  10165. ((char *) te->topic)[topic.len] = '\0';
  10166. }
  10167. }
  10168. if (pos == (int) msg->payload.len) {
  10169. mg_mqtt_suback(nc, qoss, num_subs, msg->message_id);
  10170. } else {
  10171. /* We did not fully parse the payload, something must be wrong. */
  10172. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10173. }
  10174. }
  10175. static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
  10176. struct mg_mqtt_message *msg) {
  10177. struct mg_mqtt_session *s;
  10178. size_t i;
  10179. for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
  10180. for (i = 0; i < s->num_subscriptions; i++) {
  10181. if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic,
  10182. msg->topic)) {
  10183. char buf[100], *p = buf;
  10184. mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
  10185. msg->topic.p);
  10186. if (p == NULL) {
  10187. return;
  10188. }
  10189. mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
  10190. if (p != buf) {
  10191. MG_FREE(p);
  10192. }
  10193. break;
  10194. }
  10195. }
  10196. }
  10197. }
  10198. void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
  10199. struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
  10200. struct mg_mqtt_broker *brk;
  10201. if (nc->listener) {
  10202. brk = (struct mg_mqtt_broker *) nc->listener->priv_2;
  10203. } else {
  10204. brk = (struct mg_mqtt_broker *) nc->priv_2;
  10205. }
  10206. switch (ev) {
  10207. case MG_EV_ACCEPT:
  10208. if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
  10209. nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */
  10210. break;
  10211. case MG_EV_MQTT_CONNECT:
  10212. if (nc->priv_2 == NULL) {
  10213. mg_mqtt_broker_handle_connect(brk, nc);
  10214. } else {
  10215. /* Repeated CONNECT */
  10216. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10217. }
  10218. break;
  10219. case MG_EV_MQTT_SUBSCRIBE:
  10220. if (nc->priv_2 != NULL) {
  10221. mg_mqtt_broker_handle_subscribe(nc, msg);
  10222. } else {
  10223. /* Subscribe before CONNECT */
  10224. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10225. }
  10226. break;
  10227. case MG_EV_MQTT_PUBLISH:
  10228. if (nc->priv_2 != NULL) {
  10229. mg_mqtt_broker_handle_publish(brk, msg);
  10230. } else {
  10231. /* Publish before CONNECT */
  10232. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10233. }
  10234. break;
  10235. case MG_EV_CLOSE:
  10236. if (nc->listener && nc->priv_2 != NULL) {
  10237. mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2);
  10238. }
  10239. break;
  10240. }
  10241. }
  10242. struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
  10243. struct mg_mqtt_session *s) {
  10244. return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
  10245. }
  10246. #endif /* MG_ENABLE_MQTT_BROKER */
  10247. #ifdef MG_MODULE_LINES
  10248. #line 1 "mongoose/src/mg_dns.c"
  10249. #endif
  10250. /*
  10251. * Copyright (c) 2014 Cesanta Software Limited
  10252. * All rights reserved
  10253. */
  10254. #if MG_ENABLE_DNS
  10255. /* Amalgamated: #include "mg_internal.h" */
  10256. /* Amalgamated: #include "mg_dns.h" */
  10257. static int mg_dns_tid = 0xa0;
  10258. struct mg_dns_header {
  10259. uint16_t transaction_id;
  10260. uint16_t flags;
  10261. uint16_t num_questions;
  10262. uint16_t num_answers;
  10263. uint16_t num_authority_prs;
  10264. uint16_t num_other_prs;
  10265. };
  10266. struct mg_dns_resource_record *mg_dns_next_record(
  10267. struct mg_dns_message *msg, int query,
  10268. struct mg_dns_resource_record *prev) {
  10269. struct mg_dns_resource_record *rr;
  10270. for (rr = (prev == NULL ? msg->answers : prev + 1);
  10271. rr - msg->answers < msg->num_answers; rr++) {
  10272. if (rr->rtype == query) {
  10273. return rr;
  10274. }
  10275. }
  10276. return NULL;
  10277. }
  10278. int mg_dns_parse_record_data(struct mg_dns_message *msg,
  10279. struct mg_dns_resource_record *rr, void *data,
  10280. size_t data_len) {
  10281. switch (rr->rtype) {
  10282. case MG_DNS_A_RECORD:
  10283. if (data_len < sizeof(struct in_addr)) {
  10284. return -1;
  10285. }
  10286. if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
  10287. return -1;
  10288. }
  10289. memcpy(data, rr->rdata.p, data_len);
  10290. return 0;
  10291. #if MG_ENABLE_IPV6
  10292. case MG_DNS_AAAA_RECORD:
  10293. if (data_len < sizeof(struct in6_addr)) {
  10294. return -1; /* LCOV_EXCL_LINE */
  10295. }
  10296. memcpy(data, rr->rdata.p, data_len);
  10297. return 0;
  10298. #endif
  10299. case MG_DNS_CNAME_RECORD:
  10300. mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
  10301. return 0;
  10302. }
  10303. return -1;
  10304. }
  10305. int mg_dns_insert_header(struct mbuf *io, size_t pos,
  10306. struct mg_dns_message *msg) {
  10307. struct mg_dns_header header;
  10308. memset(&header, 0, sizeof(header));
  10309. header.transaction_id = msg->transaction_id;
  10310. header.flags = htons(msg->flags);
  10311. header.num_questions = htons(msg->num_questions);
  10312. header.num_answers = htons(msg->num_answers);
  10313. return mbuf_insert(io, pos, &header, sizeof(header));
  10314. }
  10315. int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
  10316. unsigned char *begin, *end;
  10317. struct mg_dns_resource_record *last_q;
  10318. if (msg->num_questions <= 0) return 0;
  10319. begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
  10320. last_q = &msg->questions[msg->num_questions - 1];
  10321. end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
  10322. return mbuf_append(io, begin, end - begin);
  10323. }
  10324. int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
  10325. const char *s;
  10326. unsigned char n;
  10327. size_t pos = io->len;
  10328. do {
  10329. if ((s = strchr(name, '.')) == NULL) {
  10330. s = name + len;
  10331. }
  10332. if (s - name > 127) {
  10333. return -1; /* TODO(mkm) cover */
  10334. }
  10335. n = s - name; /* chunk length */
  10336. mbuf_append(io, &n, 1); /* send length */
  10337. mbuf_append(io, name, n);
  10338. if (*s == '.') {
  10339. n++;
  10340. }
  10341. name += n;
  10342. len -= n;
  10343. } while (*s != '\0');
  10344. mbuf_append(io, "\0", 1); /* Mark end of host name */
  10345. return io->len - pos;
  10346. }
  10347. int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
  10348. const char *name, size_t nlen, const void *rdata,
  10349. size_t rlen) {
  10350. size_t pos = io->len;
  10351. uint16_t u16;
  10352. uint32_t u32;
  10353. if (rr->kind == MG_DNS_INVALID_RECORD) {
  10354. return -1; /* LCOV_EXCL_LINE */
  10355. }
  10356. if (mg_dns_encode_name(io, name, nlen) == -1) {
  10357. return -1;
  10358. }
  10359. u16 = htons(rr->rtype);
  10360. mbuf_append(io, &u16, 2);
  10361. u16 = htons(rr->rclass);
  10362. mbuf_append(io, &u16, 2);
  10363. if (rr->kind == MG_DNS_ANSWER) {
  10364. u32 = htonl(rr->ttl);
  10365. mbuf_append(io, &u32, 4);
  10366. if (rr->rtype == MG_DNS_CNAME_RECORD) {
  10367. int clen;
  10368. /* fill size after encoding */
  10369. size_t off = io->len;
  10370. mbuf_append(io, &u16, 2);
  10371. if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
  10372. return -1;
  10373. }
  10374. u16 = clen;
  10375. io->buf[off] = u16 >> 8;
  10376. io->buf[off + 1] = u16 & 0xff;
  10377. } else {
  10378. u16 = htons((uint16_t) rlen);
  10379. mbuf_append(io, &u16, 2);
  10380. mbuf_append(io, rdata, rlen);
  10381. }
  10382. }
  10383. return io->len - pos;
  10384. }
  10385. void mg_send_dns_query(struct mg_connection *nc, const char *name,
  10386. int query_type) {
  10387. struct mg_dns_message *msg =
  10388. (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
  10389. struct mbuf pkt;
  10390. struct mg_dns_resource_record *rr = &msg->questions[0];
  10391. DBG(("%s %d", name, query_type));
  10392. mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
  10393. msg->transaction_id = ++mg_dns_tid;
  10394. msg->flags = 0x100;
  10395. msg->num_questions = 1;
  10396. mg_dns_insert_header(&pkt, 0, msg);
  10397. rr->rtype = query_type;
  10398. rr->rclass = 1; /* Class: inet */
  10399. rr->kind = MG_DNS_QUESTION;
  10400. if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
  10401. /* TODO(mkm): return an error code */
  10402. goto cleanup; /* LCOV_EXCL_LINE */
  10403. }
  10404. /* TCP DNS requires messages to be prefixed with len */
  10405. if (!(nc->flags & MG_F_UDP)) {
  10406. uint16_t len = htons((uint16_t) pkt.len);
  10407. mbuf_insert(&pkt, 0, &len, 2);
  10408. }
  10409. mg_send(nc, pkt.buf, pkt.len);
  10410. mbuf_free(&pkt);
  10411. cleanup:
  10412. MG_FREE(msg);
  10413. }
  10414. static unsigned char *mg_parse_dns_resource_record(
  10415. unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
  10416. int reply) {
  10417. unsigned char *name = data;
  10418. int chunk_len, data_len;
  10419. while (data < end && (chunk_len = *data)) {
  10420. if (((unsigned char *) data)[0] & 0xc0) {
  10421. data += 1;
  10422. break;
  10423. }
  10424. data += chunk_len + 1;
  10425. }
  10426. if (data > end - 5) {
  10427. return NULL;
  10428. }
  10429. rr->name.p = (char *) name;
  10430. rr->name.len = data - name + 1;
  10431. data++;
  10432. rr->rtype = data[0] << 8 | data[1];
  10433. data += 2;
  10434. rr->rclass = data[0] << 8 | data[1];
  10435. data += 2;
  10436. rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
  10437. if (reply) {
  10438. if (data >= end - 6) {
  10439. return NULL;
  10440. }
  10441. rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
  10442. data[2] << 8 | data[3];
  10443. data += 4;
  10444. data_len = *data << 8 | *(data + 1);
  10445. data += 2;
  10446. rr->rdata.p = (char *) data;
  10447. rr->rdata.len = data_len;
  10448. data += data_len;
  10449. }
  10450. return data;
  10451. }
  10452. int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
  10453. struct mg_dns_header *header = (struct mg_dns_header *) buf;
  10454. unsigned char *data = (unsigned char *) buf + sizeof(*header);
  10455. unsigned char *end = (unsigned char *) buf + len;
  10456. int i;
  10457. memset(msg, 0, sizeof(*msg));
  10458. msg->pkt.p = buf;
  10459. msg->pkt.len = len;
  10460. if (len < (int) sizeof(*header)) return -1;
  10461. msg->transaction_id = header->transaction_id;
  10462. msg->flags = ntohs(header->flags);
  10463. msg->num_questions = ntohs(header->num_questions);
  10464. if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
  10465. msg->num_questions = (int) ARRAY_SIZE(msg->questions);
  10466. }
  10467. msg->num_answers = ntohs(header->num_answers);
  10468. if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
  10469. msg->num_answers = (int) ARRAY_SIZE(msg->answers);
  10470. }
  10471. for (i = 0; i < msg->num_questions; i++) {
  10472. data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
  10473. if (data == NULL) return -1;
  10474. }
  10475. for (i = 0; i < msg->num_answers; i++) {
  10476. data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
  10477. if (data == NULL) return -1;
  10478. }
  10479. return 0;
  10480. }
  10481. size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
  10482. char *dst, int dst_len) {
  10483. int chunk_len, num_ptrs = 0;
  10484. char *old_dst = dst;
  10485. const unsigned char *data = (unsigned char *) name->p;
  10486. const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
  10487. if (data >= end) {
  10488. return 0;
  10489. }
  10490. while ((chunk_len = *data++)) {
  10491. int leeway = dst_len - (dst - old_dst);
  10492. if (data >= end) {
  10493. return 0;
  10494. }
  10495. if ((chunk_len & 0xc0) == 0xc0) {
  10496. uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
  10497. if (off >= msg->pkt.len) {
  10498. return 0;
  10499. }
  10500. /* Basic circular loop avoidance: allow up to 16 pointer hops. */
  10501. if (++num_ptrs > 15) {
  10502. return 0;
  10503. }
  10504. data = (unsigned char *) msg->pkt.p + off;
  10505. continue;
  10506. }
  10507. if (chunk_len > 63) {
  10508. return 0;
  10509. }
  10510. if (chunk_len > leeway) {
  10511. chunk_len = leeway;
  10512. }
  10513. if (data + chunk_len >= end) {
  10514. return 0;
  10515. }
  10516. memcpy(dst, data, chunk_len);
  10517. data += chunk_len;
  10518. dst += chunk_len;
  10519. leeway -= chunk_len;
  10520. if (leeway == 0) {
  10521. return dst - old_dst;
  10522. }
  10523. *dst++ = '.';
  10524. }
  10525. if (dst != old_dst) {
  10526. *--dst = 0;
  10527. }
  10528. return dst - old_dst;
  10529. }
  10530. static void dns_handler(struct mg_connection *nc, int ev,
  10531. void *ev_data MG_UD_ARG(void *user_data)) {
  10532. struct mbuf *io = &nc->recv_mbuf;
  10533. struct mg_dns_message msg;
  10534. /* Pass low-level events to the user handler */
  10535. nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
  10536. switch (ev) {
  10537. case MG_EV_RECV:
  10538. if (!(nc->flags & MG_F_UDP)) {
  10539. mbuf_remove(&nc->recv_mbuf, 2);
  10540. }
  10541. if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
  10542. /* reply + recursion allowed + format error */
  10543. memset(&msg, 0, sizeof(msg));
  10544. msg.flags = 0x8081;
  10545. mg_dns_insert_header(io, 0, &msg);
  10546. if (!(nc->flags & MG_F_UDP)) {
  10547. uint16_t len = htons((uint16_t) io->len);
  10548. mbuf_insert(io, 0, &len, 2);
  10549. }
  10550. mg_send(nc, io->buf, io->len);
  10551. } else {
  10552. /* Call user handler with parsed message */
  10553. nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data));
  10554. }
  10555. mbuf_remove(io, io->len);
  10556. break;
  10557. }
  10558. }
  10559. void mg_set_protocol_dns(struct mg_connection *nc) {
  10560. nc->proto_handler = dns_handler;
  10561. }
  10562. #endif /* MG_ENABLE_DNS */
  10563. #ifdef MG_MODULE_LINES
  10564. #line 1 "mongoose/src/mg_dns_server.c"
  10565. #endif
  10566. /*
  10567. * Copyright (c) 2014 Cesanta Software Limited
  10568. * All rights reserved
  10569. */
  10570. #if MG_ENABLE_DNS_SERVER
  10571. /* Amalgamated: #include "mg_internal.h" */
  10572. /* Amalgamated: #include "dns-server.h" */
  10573. struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
  10574. struct mg_dns_message *msg) {
  10575. struct mg_dns_reply rep;
  10576. rep.msg = msg;
  10577. rep.io = io;
  10578. rep.start = io->len;
  10579. /* reply + recursion allowed */
  10580. msg->flags |= 0x8080;
  10581. mg_dns_copy_questions(io, msg);
  10582. msg->num_answers = 0;
  10583. return rep;
  10584. }
  10585. void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
  10586. size_t sent = r->io->len - r->start;
  10587. mg_dns_insert_header(r->io, r->start, r->msg);
  10588. if (!(nc->flags & MG_F_UDP)) {
  10589. uint16_t len = htons((uint16_t) sent);
  10590. mbuf_insert(r->io, r->start, &len, 2);
  10591. }
  10592. if (&nc->send_mbuf != r->io) {
  10593. mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
  10594. r->io->len = r->start;
  10595. }
  10596. }
  10597. int mg_dns_reply_record(struct mg_dns_reply *reply,
  10598. struct mg_dns_resource_record *question,
  10599. const char *name, int rtype, int ttl, const void *rdata,
  10600. size_t rdata_len) {
  10601. struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
  10602. char rname[512];
  10603. struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
  10604. if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
  10605. return -1; /* LCOV_EXCL_LINE */
  10606. }
  10607. if (name == NULL) {
  10608. name = rname;
  10609. rname[511] = 0;
  10610. mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
  10611. }
  10612. *ans = *question;
  10613. ans->kind = MG_DNS_ANSWER;
  10614. ans->rtype = rtype;
  10615. ans->ttl = ttl;
  10616. if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
  10617. rdata_len) == -1) {
  10618. return -1; /* LCOV_EXCL_LINE */
  10619. };
  10620. msg->num_answers++;
  10621. return 0;
  10622. }
  10623. #endif /* MG_ENABLE_DNS_SERVER */
  10624. #ifdef MG_MODULE_LINES
  10625. #line 1 "mongoose/src/mg_resolv.c"
  10626. #endif
  10627. /*
  10628. * Copyright (c) 2014 Cesanta Software Limited
  10629. * All rights reserved
  10630. */
  10631. #if MG_ENABLE_ASYNC_RESOLVER
  10632. /* Amalgamated: #include "mg_internal.h" */
  10633. /* Amalgamated: #include "mg_resolv.h" */
  10634. #ifndef MG_DEFAULT_NAMESERVER
  10635. #define MG_DEFAULT_NAMESERVER "8.8.8.8"
  10636. #endif
  10637. struct mg_resolve_async_request {
  10638. char name[1024];
  10639. int query;
  10640. mg_resolve_callback_t callback;
  10641. void *data;
  10642. time_t timeout;
  10643. int max_retries;
  10644. enum mg_resolve_err err;
  10645. /* state */
  10646. time_t last_time;
  10647. int retries;
  10648. };
  10649. /*
  10650. * Find what nameserver to use.
  10651. *
  10652. * Return 0 if OK, -1 if error
  10653. */
  10654. static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
  10655. int ret = -1;
  10656. #ifdef _WIN32
  10657. int i;
  10658. LONG err;
  10659. HKEY hKey, hSub;
  10660. wchar_t subkey[512], value[128],
  10661. *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
  10662. if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
  10663. ERROR_SUCCESS) {
  10664. fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
  10665. ret = -1;
  10666. } else {
  10667. for (ret = -1, i = 0; 1; i++) {
  10668. DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
  10669. if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
  10670. NULL) != ERROR_SUCCESS) {
  10671. break;
  10672. }
  10673. if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
  10674. ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
  10675. &len) == ERROR_SUCCESS &&
  10676. value[0] != '\0') ||
  10677. (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
  10678. &len) == ERROR_SUCCESS &&
  10679. value[0] != '\0'))) {
  10680. /*
  10681. * See https://github.com/cesanta/mongoose/issues/176
  10682. * The value taken from the registry can be empty, a single
  10683. * IP address, or multiple IP addresses separated by comma.
  10684. * If it's empty, check the next interface.
  10685. * If it's multiple IP addresses, take the first one.
  10686. */
  10687. wchar_t *comma = wcschr(value, ',');
  10688. if (comma != NULL) {
  10689. *comma = '\0';
  10690. }
  10691. /* %S will convert wchar_t -> char */
  10692. snprintf(name, name_len, "%S", value);
  10693. ret = 0;
  10694. RegCloseKey(hSub);
  10695. break;
  10696. }
  10697. }
  10698. RegCloseKey(hKey);
  10699. }
  10700. #elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME)
  10701. FILE *fp;
  10702. char line[512];
  10703. if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) {
  10704. ret = -1;
  10705. } else {
  10706. /* Try to figure out what nameserver to use */
  10707. for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
  10708. unsigned int a, b, c, d;
  10709. if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
  10710. snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d);
  10711. ret = 0;
  10712. break;
  10713. }
  10714. }
  10715. (void) fclose(fp);
  10716. }
  10717. #else
  10718. snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER);
  10719. #endif /* _WIN32 */
  10720. return ret;
  10721. }
  10722. int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
  10723. #if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME)
  10724. /* TODO(mkm) cache /etc/hosts */
  10725. FILE *fp;
  10726. char line[1024];
  10727. char *p;
  10728. char alias[256];
  10729. unsigned int a, b, c, d;
  10730. int len = 0;
  10731. if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) {
  10732. return -1;
  10733. }
  10734. for (; fgets(line, sizeof(line), fp) != NULL;) {
  10735. if (line[0] == '#') continue;
  10736. if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
  10737. /* TODO(mkm): handle ipv6 */
  10738. continue;
  10739. }
  10740. for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
  10741. if (strcmp(alias, name) == 0) {
  10742. usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
  10743. fclose(fp);
  10744. return 0;
  10745. }
  10746. }
  10747. }
  10748. fclose(fp);
  10749. #else
  10750. (void) name;
  10751. (void) usa;
  10752. #endif
  10753. return -1;
  10754. }
  10755. static void mg_resolve_async_eh(struct mg_connection *nc, int ev,
  10756. void *data MG_UD_ARG(void *user_data)) {
  10757. time_t now = (time_t) mg_time();
  10758. struct mg_resolve_async_request *req;
  10759. struct mg_dns_message *msg;
  10760. #if !MG_ENABLE_CALLBACK_USERDATA
  10761. void *user_data = nc->user_data;
  10762. #endif
  10763. if (ev != MG_EV_POLL) {
  10764. DBG(("ev=%d user_data=%p", ev, user_data));
  10765. }
  10766. req = (struct mg_resolve_async_request *) user_data;
  10767. if (req == NULL) {
  10768. return;
  10769. }
  10770. switch (ev) {
  10771. case MG_EV_POLL:
  10772. if (req->retries > req->max_retries) {
  10773. req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
  10774. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10775. break;
  10776. }
  10777. if (nc->flags & MG_F_CONNECTING) break;
  10778. /* fallthrough */
  10779. case MG_EV_CONNECT:
  10780. if (req->retries == 0 || now - req->last_time >= req->timeout) {
  10781. mg_send_dns_query(nc, req->name, req->query);
  10782. req->last_time = now;
  10783. req->retries++;
  10784. }
  10785. break;
  10786. case MG_EV_RECV:
  10787. msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
  10788. if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
  10789. msg->num_answers > 0) {
  10790. req->callback(msg, req->data, MG_RESOLVE_OK);
  10791. nc->user_data = NULL;
  10792. MG_FREE(req);
  10793. } else {
  10794. req->err = MG_RESOLVE_NO_ANSWERS;
  10795. }
  10796. MG_FREE(msg);
  10797. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10798. break;
  10799. case MG_EV_SEND:
  10800. /*
  10801. * If a send error occurs, prevent closing of the connection by the core.
  10802. * We will retry after timeout.
  10803. */
  10804. nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
  10805. mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
  10806. break;
  10807. case MG_EV_TIMER:
  10808. req->err = MG_RESOLVE_TIMEOUT;
  10809. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  10810. break;
  10811. case MG_EV_CLOSE:
  10812. /* If we got here with request still not done, fire an error callback. */
  10813. if (req != NULL) {
  10814. char addr[32];
  10815. mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP);
  10816. #ifdef MG_LOG_DNS_FAILURES
  10817. LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr));
  10818. #endif
  10819. req->callback(NULL, req->data, req->err);
  10820. nc->user_data = NULL;
  10821. MG_FREE(req);
  10822. }
  10823. break;
  10824. }
  10825. }
  10826. int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
  10827. mg_resolve_callback_t cb, void *data) {
  10828. struct mg_resolve_async_opts opts;
  10829. memset(&opts, 0, sizeof(opts));
  10830. return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
  10831. }
  10832. int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
  10833. mg_resolve_callback_t cb, void *data,
  10834. struct mg_resolve_async_opts opts) {
  10835. struct mg_resolve_async_request *req;
  10836. struct mg_connection *dns_nc;
  10837. const char *nameserver = opts.nameserver;
  10838. char dns_server_buff[17], nameserver_url[26];
  10839. if (nameserver == NULL) {
  10840. nameserver = mgr->nameserver;
  10841. }
  10842. DBG(("%s %d %p", name, query, opts.dns_conn));
  10843. /* resolve with DNS */
  10844. req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
  10845. if (req == NULL) {
  10846. return -1;
  10847. }
  10848. strncpy(req->name, name, sizeof(req->name));
  10849. req->name[sizeof(req->name) - 1] = '\0';
  10850. req->query = query;
  10851. req->callback = cb;
  10852. req->data = data;
  10853. /* TODO(mkm): parse defaults out of resolve.conf */
  10854. req->max_retries = opts.max_retries ? opts.max_retries : 2;
  10855. req->timeout = opts.timeout ? opts.timeout : 5;
  10856. /* Lazily initialize dns server */
  10857. if (nameserver == NULL) {
  10858. if (mg_get_ip_address_of_nameserver(dns_server_buff,
  10859. sizeof(dns_server_buff)) != -1) {
  10860. nameserver = dns_server_buff;
  10861. } else {
  10862. nameserver = MG_DEFAULT_NAMESERVER;
  10863. }
  10864. }
  10865. snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver);
  10866. dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL));
  10867. if (dns_nc == NULL) {
  10868. MG_FREE(req);
  10869. return -1;
  10870. }
  10871. dns_nc->user_data = req;
  10872. if (opts.dns_conn != NULL) {
  10873. *opts.dns_conn = dns_nc;
  10874. }
  10875. return 0;
  10876. }
  10877. void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) {
  10878. MG_FREE((char *) mgr->nameserver);
  10879. mgr->nameserver = NULL;
  10880. if (nameserver != NULL) {
  10881. mgr->nameserver = strdup(nameserver);
  10882. }
  10883. }
  10884. #endif /* MG_ENABLE_ASYNC_RESOLVER */
  10885. #ifdef MG_MODULE_LINES
  10886. #line 1 "mongoose/src/mg_coap.c"
  10887. #endif
  10888. /*
  10889. * Copyright (c) 2015 Cesanta Software Limited
  10890. * All rights reserved
  10891. * This software is dual-licensed: you can redistribute it and/or modify
  10892. * it under the terms of the GNU General Public License version 2 as
  10893. * published by the Free Software Foundation. For the terms of this
  10894. * license, see <http://www.gnu.org/licenses/>.
  10895. *
  10896. * You are free to use this software under the terms of the GNU General
  10897. * Public License, but WITHOUT ANY WARRANTY; without even the implied
  10898. * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10899. * See the GNU General Public License for more details.
  10900. *
  10901. * Alternatively, you can license this software under a commercial
  10902. * license, as set out in <https://www.cesanta.com/license>.
  10903. */
  10904. /* Amalgamated: #include "mg_internal.h" */
  10905. /* Amalgamated: #include "mg_coap.h" */
  10906. #if MG_ENABLE_COAP
  10907. void mg_coap_free_options(struct mg_coap_message *cm) {
  10908. while (cm->options != NULL) {
  10909. struct mg_coap_option *next = cm->options->next;
  10910. MG_FREE(cm->options);
  10911. cm->options = next;
  10912. }
  10913. }
  10914. struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
  10915. uint32_t number, char *value,
  10916. size_t len) {
  10917. struct mg_coap_option *new_option =
  10918. (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
  10919. new_option->number = number;
  10920. new_option->value.p = value;
  10921. new_option->value.len = len;
  10922. if (cm->options == NULL) {
  10923. cm->options = cm->optiomg_tail = new_option;
  10924. } else {
  10925. /*
  10926. * A very simple attention to help clients to compose options:
  10927. * CoAP wants to see options ASC ordered.
  10928. * Could be change by using sort in coap_compose
  10929. */
  10930. if (cm->optiomg_tail->number <= new_option->number) {
  10931. /* if option is already ordered just add it */
  10932. cm->optiomg_tail = cm->optiomg_tail->next = new_option;
  10933. } else {
  10934. /* looking for appropriate position */
  10935. struct mg_coap_option *current_opt = cm->options;
  10936. struct mg_coap_option *prev_opt = 0;
  10937. while (current_opt != NULL) {
  10938. if (current_opt->number > new_option->number) {
  10939. break;
  10940. }
  10941. prev_opt = current_opt;
  10942. current_opt = current_opt->next;
  10943. }
  10944. if (prev_opt != NULL) {
  10945. prev_opt->next = new_option;
  10946. new_option->next = current_opt;
  10947. } else {
  10948. /* insert new_option to the beginning */
  10949. new_option->next = cm->options;
  10950. cm->options = new_option;
  10951. }
  10952. }
  10953. }
  10954. return new_option;
  10955. }
  10956. /*
  10957. * Fills CoAP header in mg_coap_message.
  10958. *
  10959. * Helper function.
  10960. */
  10961. static char *coap_parse_header(char *ptr, struct mbuf *io,
  10962. struct mg_coap_message *cm) {
  10963. if (io->len < sizeof(uint32_t)) {
  10964. cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
  10965. return NULL;
  10966. }
  10967. /*
  10968. * Version (Ver): 2-bit unsigned integer. Indicates the CoAP version
  10969. * number. Implementations of this specification MUST set this field
  10970. * to 1 (01 binary). Other values are reserved for future versions.
  10971. * Messages with unknown version numbers MUST be silently ignored.
  10972. */
  10973. if (((uint8_t) *ptr >> 6) != 1) {
  10974. cm->flags |= MG_COAP_IGNORE;
  10975. return NULL;
  10976. }
  10977. /*
  10978. * Type (T): 2-bit unsigned integer. Indicates if this message is of
  10979. * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
  10980. * Reset (3).
  10981. */
  10982. cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
  10983. cm->flags |= MG_COAP_MSG_TYPE_FIELD;
  10984. /*
  10985. * Token Length (TKL): 4-bit unsigned integer. Indicates the length of
  10986. * the variable-length Token field (0-8 bytes). Lengths 9-15 are
  10987. * reserved, MUST NOT be sent, and MUST be processed as a message
  10988. * format error.
  10989. */
  10990. cm->token.len = *ptr & 0x0F;
  10991. if (cm->token.len > 8) {
  10992. cm->flags |= MG_COAP_FORMAT_ERROR;
  10993. return NULL;
  10994. }
  10995. ptr++;
  10996. /*
  10997. * Code: 8-bit unsigned integer, split into a 3-bit class (most
  10998. * significant bits) and a 5-bit detail (least significant bits)
  10999. */
  11000. cm->code_class = (uint8_t) *ptr >> 5;
  11001. cm->code_detail = *ptr & 0x1F;
  11002. cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
  11003. ptr++;
  11004. /* Message ID: 16-bit unsigned integer in network byte order. */
  11005. cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
  11006. cm->flags |= MG_COAP_MSG_ID_FIELD;
  11007. ptr += 2;
  11008. return ptr;
  11009. }
  11010. /*
  11011. * Fills token information in mg_coap_message.
  11012. *
  11013. * Helper function.
  11014. */
  11015. static char *coap_get_token(char *ptr, struct mbuf *io,
  11016. struct mg_coap_message *cm) {
  11017. if (cm->token.len != 0) {
  11018. if (ptr + cm->token.len > io->buf + io->len) {
  11019. cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
  11020. return NULL;
  11021. } else {
  11022. cm->token.p = ptr;
  11023. ptr += cm->token.len;
  11024. cm->flags |= MG_COAP_TOKEN_FIELD;
  11025. }
  11026. }
  11027. return ptr;
  11028. }
  11029. /*
  11030. * Returns Option Delta or Length.
  11031. *
  11032. * Helper function.
  11033. */
  11034. static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
  11035. int ret = 0;
  11036. if (*opt_info == 13) {
  11037. /*
  11038. * 13: An 8-bit unsigned integer follows the initial byte and
  11039. * indicates the Option Delta/Length minus 13.
  11040. */
  11041. if (ptr < io->buf + io->len) {
  11042. *opt_info = (uint8_t) *ptr + 13;
  11043. ret = sizeof(uint8_t);
  11044. } else {
  11045. ret = -1; /* LCOV_EXCL_LINE */
  11046. }
  11047. } else if (*opt_info == 14) {
  11048. /*
  11049. * 14: A 16-bit unsigned integer in network byte order follows the
  11050. * initial byte and indicates the Option Delta/Length minus 269.
  11051. */
  11052. if (ptr + sizeof(uint8_t) < io->buf + io->len) {
  11053. *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
  11054. ret = sizeof(uint16_t);
  11055. } else {
  11056. ret = -1; /* LCOV_EXCL_LINE */
  11057. }
  11058. }
  11059. return ret;
  11060. }
  11061. /*
  11062. * Fills options in mg_coap_message.
  11063. *
  11064. * Helper function.
  11065. *
  11066. * General options format:
  11067. * +---------------+---------------+
  11068. * | Option Delta | Option Length | 1 byte
  11069. * +---------------+---------------+
  11070. * \ Option Delta (extended) \ 0-2 bytes
  11071. * +-------------------------------+
  11072. * / Option Length (extended) \ 0-2 bytes
  11073. * +-------------------------------+
  11074. * \ Option Value \ 0 or more bytes
  11075. * +-------------------------------+
  11076. */
  11077. static char *coap_get_options(char *ptr, struct mbuf *io,
  11078. struct mg_coap_message *cm) {
  11079. uint16_t prev_opt = 0;
  11080. if (ptr == io->buf + io->len) {
  11081. /* end of packet, ok */
  11082. return NULL;
  11083. }
  11084. /* 0xFF is payload marker */
  11085. while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
  11086. uint16_t option_delta, option_lenght;
  11087. int optinfo_len;
  11088. /* Option Delta: 4-bit unsigned integer */
  11089. option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
  11090. /* Option Length: 4-bit unsigned integer */
  11091. option_lenght = *ptr & 0x0F;
  11092. if (option_delta == 15 || option_lenght == 15) {
  11093. /*
  11094. * 15: Reserved for future use. If the field is set to this value,
  11095. * it MUST be processed as a message format error
  11096. */
  11097. cm->flags |= MG_COAP_FORMAT_ERROR;
  11098. break;
  11099. }
  11100. ptr++;
  11101. /* check for extended option delta */
  11102. optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
  11103. if (optinfo_len == -1) {
  11104. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  11105. break; /* LCOV_EXCL_LINE */
  11106. }
  11107. ptr += optinfo_len;
  11108. /* check or extended option lenght */
  11109. optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
  11110. if (optinfo_len == -1) {
  11111. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  11112. break; /* LCOV_EXCL_LINE */
  11113. }
  11114. ptr += optinfo_len;
  11115. /*
  11116. * Instead of specifying the Option Number directly, the instances MUST
  11117. * appear in order of their Option Numbers and a delta encoding is used
  11118. * between them.
  11119. */
  11120. option_delta += prev_opt;
  11121. mg_coap_add_option(cm, option_delta, ptr, option_lenght);
  11122. prev_opt = option_delta;
  11123. if (ptr + option_lenght > io->buf + io->len) {
  11124. cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
  11125. break; /* LCOV_EXCL_LINE */
  11126. }
  11127. ptr += option_lenght;
  11128. }
  11129. if ((cm->flags & MG_COAP_ERROR) != 0) {
  11130. mg_coap_free_options(cm);
  11131. return NULL;
  11132. }
  11133. cm->flags |= MG_COAP_OPTIOMG_FIELD;
  11134. if (ptr == io->buf + io->len) {
  11135. /* end of packet, ok */
  11136. return NULL;
  11137. }
  11138. ptr++;
  11139. return ptr;
  11140. }
  11141. uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
  11142. char *ptr;
  11143. memset(cm, 0, sizeof(*cm));
  11144. if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
  11145. return cm->flags;
  11146. }
  11147. if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
  11148. return cm->flags;
  11149. }
  11150. if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
  11151. return cm->flags;
  11152. }
  11153. /* the rest is payload */
  11154. cm->payload.len = io->len - (ptr - io->buf);
  11155. if (cm->payload.len != 0) {
  11156. cm->payload.p = ptr;
  11157. cm->flags |= MG_COAP_PAYLOAD_FIELD;
  11158. }
  11159. return cm->flags;
  11160. }
  11161. /*
  11162. * Calculates extended size of given Opt Number/Length in coap message.
  11163. *
  11164. * Helper function.
  11165. */
  11166. static size_t coap_get_ext_opt_size(uint32_t value) {
  11167. int ret = 0;
  11168. if (value >= 13 && value <= 0xFF + 13) {
  11169. ret = sizeof(uint8_t);
  11170. } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
  11171. ret = sizeof(uint16_t);
  11172. }
  11173. return ret;
  11174. }
  11175. /*
  11176. * Splits given Opt Number/Length into base and ext values.
  11177. *
  11178. * Helper function.
  11179. */
  11180. static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
  11181. int ret = 0;
  11182. if (value < 13) {
  11183. *base = value;
  11184. } else if (value >= 13 && value <= 0xFF + 13) {
  11185. *base = 13;
  11186. *ext = value - 13;
  11187. ret = sizeof(uint8_t);
  11188. } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
  11189. *base = 14;
  11190. *ext = value - 269;
  11191. ret = sizeof(uint16_t);
  11192. }
  11193. return ret;
  11194. }
  11195. /*
  11196. * Puts uint16_t (in network order) into given char stream.
  11197. *
  11198. * Helper function.
  11199. */
  11200. static char *coap_add_uint16(char *ptr, uint16_t val) {
  11201. *ptr = val >> 8;
  11202. ptr++;
  11203. *ptr = val & 0x00FF;
  11204. ptr++;
  11205. return ptr;
  11206. }
  11207. /*
  11208. * Puts extended value of Opt Number/Length into given char stream.
  11209. *
  11210. * Helper function.
  11211. */
  11212. static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
  11213. if (len == sizeof(uint8_t)) {
  11214. *ptr = (char) val;
  11215. ptr++;
  11216. } else if (len == sizeof(uint16_t)) {
  11217. ptr = coap_add_uint16(ptr, val);
  11218. }
  11219. return ptr;
  11220. }
  11221. /*
  11222. * Verifies given mg_coap_message and calculates message size for it.
  11223. *
  11224. * Helper function.
  11225. */
  11226. static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
  11227. size_t *len) {
  11228. struct mg_coap_option *opt;
  11229. uint32_t prev_opt_number;
  11230. *len = 4; /* header */
  11231. if (cm->msg_type > MG_COAP_MSG_MAX) {
  11232. return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
  11233. }
  11234. if (cm->token.len > 8) {
  11235. return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
  11236. }
  11237. if (cm->code_class > 7) {
  11238. return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
  11239. }
  11240. if (cm->code_detail > 31) {
  11241. return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
  11242. }
  11243. *len += cm->token.len;
  11244. if (cm->payload.len != 0) {
  11245. *len += cm->payload.len + 1; /* ... + 1; add payload marker */
  11246. }
  11247. opt = cm->options;
  11248. prev_opt_number = 0;
  11249. while (opt != NULL) {
  11250. *len += 1; /* basic delta/length */
  11251. *len += coap_get_ext_opt_size(opt->number - prev_opt_number);
  11252. *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
  11253. /*
  11254. * Current implementation performs check if
  11255. * option_number > previous option_number and produces an error
  11256. * TODO(alashkin): write design doc with limitations
  11257. * May be resorting is more suitable solution.
  11258. */
  11259. if ((opt->next != NULL && opt->number > opt->next->number) ||
  11260. opt->value.len > 0xFFFF + 269 ||
  11261. opt->number - prev_opt_number > 0xFFFF + 269) {
  11262. return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
  11263. }
  11264. *len += opt->value.len;
  11265. prev_opt_number = opt->number;
  11266. opt = opt->next;
  11267. }
  11268. return 0;
  11269. }
  11270. uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
  11271. struct mg_coap_option *opt;
  11272. uint32_t res, prev_opt_number;
  11273. size_t prev_io_len, packet_size;
  11274. char *ptr;
  11275. res = coap_calculate_packet_size(cm, &packet_size);
  11276. if (res != 0) {
  11277. return res;
  11278. }
  11279. /* saving previous lenght to handle non-empty mbuf */
  11280. prev_io_len = io->len;
  11281. if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR;
  11282. ptr = io->buf + prev_io_len;
  11283. /*
  11284. * since cm is verified, it is possible to use bits shift operator
  11285. * without additional zeroing of unused bits
  11286. */
  11287. /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
  11288. *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
  11289. ptr++;
  11290. /* code class: 3 bits, code detail: 5 bits */
  11291. *ptr = (cm->code_class << 5) | (cm->code_detail);
  11292. ptr++;
  11293. ptr = coap_add_uint16(ptr, cm->msg_id);
  11294. if (cm->token.len != 0) {
  11295. memcpy(ptr, cm->token.p, cm->token.len);
  11296. ptr += cm->token.len;
  11297. }
  11298. opt = cm->options;
  11299. prev_opt_number = 0;
  11300. while (opt != NULL) {
  11301. uint8_t delta_base = 0, length_base = 0;
  11302. uint16_t delta_ext = 0, length_ext = 0;
  11303. size_t opt_delta_len =
  11304. coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
  11305. size_t opt_lenght_len =
  11306. coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
  11307. *ptr = (delta_base << 4) | length_base;
  11308. ptr++;
  11309. ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
  11310. ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
  11311. if (opt->value.len != 0) {
  11312. memcpy(ptr, opt->value.p, opt->value.len);
  11313. ptr += opt->value.len;
  11314. }
  11315. prev_opt_number = opt->number;
  11316. opt = opt->next;
  11317. }
  11318. if (cm->payload.len != 0) {
  11319. *ptr = (char) -1;
  11320. ptr++;
  11321. memcpy(ptr, cm->payload.p, cm->payload.len);
  11322. }
  11323. return 0;
  11324. }
  11325. uint32_t mg_coap_send_message(struct mg_connection *nc,
  11326. struct mg_coap_message *cm) {
  11327. struct mbuf packet_out;
  11328. uint32_t compose_res;
  11329. mbuf_init(&packet_out, 0);
  11330. compose_res = mg_coap_compose(cm, &packet_out);
  11331. if (compose_res != 0) {
  11332. return compose_res; /* LCOV_EXCL_LINE */
  11333. }
  11334. mg_send(nc, packet_out.buf, (int) packet_out.len);
  11335. mbuf_free(&packet_out);
  11336. return 0;
  11337. }
  11338. uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
  11339. struct mg_coap_message cm;
  11340. memset(&cm, 0, sizeof(cm));
  11341. cm.msg_type = MG_COAP_MSG_ACK;
  11342. cm.msg_id = msg_id;
  11343. return mg_coap_send_message(nc, &cm);
  11344. }
  11345. static void coap_handler(struct mg_connection *nc, int ev,
  11346. void *ev_data MG_UD_ARG(void *user_data)) {
  11347. struct mbuf *io = &nc->recv_mbuf;
  11348. struct mg_coap_message cm;
  11349. uint32_t parse_res;
  11350. memset(&cm, 0, sizeof(cm));
  11351. nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
  11352. switch (ev) {
  11353. case MG_EV_RECV:
  11354. parse_res = mg_coap_parse(io, &cm);
  11355. if ((parse_res & MG_COAP_IGNORE) == 0) {
  11356. if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
  11357. /*
  11358. * Since we support UDP only
  11359. * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
  11360. */
  11361. cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
  11362. } /* LCOV_EXCL_LINE */
  11363. nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
  11364. &cm MG_UD_ARG(user_data));
  11365. }
  11366. mg_coap_free_options(&cm);
  11367. mbuf_remove(io, io->len);
  11368. break;
  11369. }
  11370. }
  11371. /*
  11372. * Attach built-in CoAP event handler to the given connection.
  11373. *
  11374. * The user-defined event handler will receive following extra events:
  11375. *
  11376. * - MG_EV_COAP_CON
  11377. * - MG_EV_COAP_NOC
  11378. * - MG_EV_COAP_ACK
  11379. * - MG_EV_COAP_RST
  11380. */
  11381. int mg_set_protocol_coap(struct mg_connection *nc) {
  11382. /* supports UDP only */
  11383. if ((nc->flags & MG_F_UDP) == 0) {
  11384. return -1;
  11385. }
  11386. nc->proto_handler = coap_handler;
  11387. return 0;
  11388. }
  11389. #endif /* MG_ENABLE_COAP */
  11390. #ifdef MG_MODULE_LINES
  11391. #line 1 "mongoose/src/mg_sntp.c"
  11392. #endif
  11393. /*
  11394. * Copyright (c) 2016 Cesanta Software Limited
  11395. * All rights reserved
  11396. */
  11397. /* Amalgamated: #include "mg_internal.h" */
  11398. /* Amalgamated: #include "mg_sntp.h" */
  11399. /* Amalgamated: #include "mg_util.h" */
  11400. #if MG_ENABLE_SNTP
  11401. #define SNTP_TIME_OFFSET 2208988800
  11402. #ifndef SNTP_TIMEOUT
  11403. #define SNTP_TIMEOUT 10
  11404. #endif
  11405. #ifndef SNTP_ATTEMPTS
  11406. #define SNTP_ATTEMPTS 3
  11407. #endif
  11408. static uint64_t mg_get_sec(uint64_t val) {
  11409. return (val & 0xFFFFFFFF00000000) >> 32;
  11410. }
  11411. static uint64_t mg_get_usec(uint64_t val) {
  11412. uint64_t tmp = (val & 0x00000000FFFFFFFF);
  11413. tmp *= 1000000;
  11414. tmp >>= 32;
  11415. return tmp;
  11416. }
  11417. static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
  11418. uint64_t tmp;
  11419. tmp = mg_get_sec(val);
  11420. tmp -= SNTP_TIME_OFFSET;
  11421. tv->tv_sec = tmp;
  11422. tv->tv_usec = mg_get_usec(val);
  11423. }
  11424. static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
  11425. uint32_t tmp;
  11426. memcpy(&tmp, ntp, sizeof(tmp));
  11427. tmp = ntohl(tmp);
  11428. *val = (uint64_t) tmp << 32;
  11429. memcpy(&tmp, ntp + 4, sizeof(tmp));
  11430. tmp = ntohl(tmp);
  11431. *val |= tmp;
  11432. }
  11433. void mg_sntp_send_request(struct mg_connection *c) {
  11434. uint8_t buf[48] = {0};
  11435. /*
  11436. * header - 8 bit:
  11437. * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
  11438. * mode (3 bit) - 3 (client)
  11439. */
  11440. buf[0] = (3 << 6) | (4 << 3) | 3;
  11441. /*
  11442. * Next fields should be empty in client request
  11443. * stratum, 8 bit
  11444. * poll interval, 8 bit
  11445. * rrecision, 8 bit
  11446. * root delay, 32 bit
  11447. * root dispersion, 32 bit
  11448. * ref id, 32 bit
  11449. * ref timestamp, 64 bit
  11450. * originate Timestamp, 64 bit
  11451. * receive Timestamp, 64 bit
  11452. */
  11453. /*
  11454. * convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
  11455. * according to rfc868 it is 2208988800L sec
  11456. * this information is used to correct roundtrip delay
  11457. * but if local clock is absolutely broken (and doesn't work even
  11458. * as simple timer), it is better to disable it
  11459. */
  11460. #ifndef MG_SNTP_NO_DELAY_CORRECTION
  11461. uint32_t sec;
  11462. sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET));
  11463. memcpy(&buf[40], &sec, sizeof(sec));
  11464. #endif
  11465. mg_send(c, buf, sizeof(buf));
  11466. }
  11467. #ifndef MG_SNTP_NO_DELAY_CORRECTION
  11468. static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
  11469. /* roundloop delay = (T4 - T1) - (T3 - T2) */
  11470. uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
  11471. (mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
  11472. uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
  11473. (mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
  11474. return (d1 > d2) ? d1 - d2 : 0;
  11475. }
  11476. #endif
  11477. MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
  11478. struct mg_sntp_message *msg) {
  11479. uint8_t hdr;
  11480. uint64_t trsm_ts_T3, delay = 0;
  11481. int mode;
  11482. struct timeval tv;
  11483. if (len < 48) {
  11484. return -1;
  11485. }
  11486. hdr = buf[0];
  11487. if ((hdr & 0x38) >> 3 != 4) {
  11488. /* Wrong version */
  11489. return -1;
  11490. }
  11491. mode = hdr & 0x7;
  11492. if (mode != 4 && mode != 5) {
  11493. /* Not a server reply */
  11494. return -1;
  11495. }
  11496. memset(msg, 0, sizeof(*msg));
  11497. msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
  11498. mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
  11499. #ifndef MG_SNTP_NO_DELAY_CORRECTION
  11500. {
  11501. uint64_t orig_ts_T1, recv_ts_T2;
  11502. mg_get_ntp_ts(&buf[24], &orig_ts_T1);
  11503. mg_get_ntp_ts(&buf[32], &recv_ts_T2);
  11504. delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
  11505. }
  11506. #endif
  11507. mg_ntp_to_tv(trsm_ts_T3, &tv);
  11508. msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
  11509. return 0;
  11510. }
  11511. static void mg_sntp_handler(struct mg_connection *c, int ev,
  11512. void *ev_data MG_UD_ARG(void *user_data)) {
  11513. struct mbuf *io = &c->recv_mbuf;
  11514. struct mg_sntp_message msg;
  11515. c->handler(c, ev, ev_data MG_UD_ARG(user_data));
  11516. switch (ev) {
  11517. case MG_EV_RECV: {
  11518. if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
  11519. DBG(("Invalid SNTP packet received (%d)", (int) io->len));
  11520. c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data));
  11521. } else {
  11522. c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data));
  11523. }
  11524. mbuf_remove(io, io->len);
  11525. break;
  11526. }
  11527. }
  11528. }
  11529. int mg_set_protocol_sntp(struct mg_connection *c) {
  11530. if ((c->flags & MG_F_UDP) == 0) {
  11531. return -1;
  11532. }
  11533. c->proto_handler = mg_sntp_handler;
  11534. return 0;
  11535. }
  11536. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
  11537. MG_CB(mg_event_handler_t event_handler,
  11538. void *user_data),
  11539. const char *sntp_server_name) {
  11540. struct mg_connection *c = NULL;
  11541. char url[100], *p_url = url;
  11542. const char *proto = "", *port = "", *tmp;
  11543. /* If port is not specified, use default (123) */
  11544. tmp = strchr(sntp_server_name, ':');
  11545. if (tmp != NULL && *(tmp + 1) == '/') {
  11546. tmp = strchr(tmp + 1, ':');
  11547. }
  11548. if (tmp == NULL) {
  11549. port = ":123";
  11550. }
  11551. /* Add udp:// if needed */
  11552. if (strncmp(sntp_server_name, "udp://", 6) != 0) {
  11553. proto = "udp://";
  11554. }
  11555. mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
  11556. c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data));
  11557. if (c == NULL) {
  11558. goto cleanup;
  11559. }
  11560. mg_set_protocol_sntp(c);
  11561. cleanup:
  11562. if (p_url != url) {
  11563. MG_FREE(p_url);
  11564. }
  11565. return c;
  11566. }
  11567. struct sntp_data {
  11568. mg_event_handler_t hander;
  11569. int count;
  11570. };
  11571. static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
  11572. void *ev_data MG_UD_ARG(void *user_data)) {
  11573. #if !MG_ENABLE_CALLBACK_USERDATA
  11574. void *user_data = c->user_data;
  11575. #endif
  11576. struct sntp_data *sd = (struct sntp_data *) user_data;
  11577. switch (ev) {
  11578. case MG_EV_CONNECT:
  11579. if (*(int *) ev_data != 0) {
  11580. mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
  11581. break;
  11582. }
  11583. /* fallthrough */
  11584. case MG_EV_TIMER:
  11585. if (sd->count <= SNTP_ATTEMPTS) {
  11586. mg_sntp_send_request(c);
  11587. mg_set_timer(c, mg_time() + 10);
  11588. sd->count++;
  11589. } else {
  11590. mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
  11591. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  11592. }
  11593. break;
  11594. case MG_SNTP_MALFORMED_REPLY:
  11595. mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
  11596. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  11597. break;
  11598. case MG_SNTP_REPLY:
  11599. mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data);
  11600. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  11601. break;
  11602. case MG_EV_CLOSE:
  11603. MG_FREE(user_data);
  11604. c->user_data = NULL;
  11605. break;
  11606. }
  11607. }
  11608. struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
  11609. mg_event_handler_t event_handler,
  11610. const char *sntp_server_name) {
  11611. struct mg_connection *c;
  11612. struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
  11613. if (sd == NULL) {
  11614. return NULL;
  11615. }
  11616. c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd),
  11617. sntp_server_name);
  11618. if (c == NULL) {
  11619. MG_FREE(sd);
  11620. return NULL;
  11621. }
  11622. sd->hander = event_handler;
  11623. #if !MG_ENABLE_CALLBACK_USERDATA
  11624. c->user_data = sd;
  11625. #endif
  11626. return c;
  11627. }
  11628. #endif /* MG_ENABLE_SNTP */
  11629. #ifdef MG_MODULE_LINES
  11630. #line 1 "mongoose/src/mg_socks.c"
  11631. #endif
  11632. /*
  11633. * Copyright (c) 2017 Cesanta Software Limited
  11634. * All rights reserved
  11635. */
  11636. #if MG_ENABLE_SOCKS
  11637. /* Amalgamated: #include "mg_socks.h" */
  11638. /* Amalgamated: #include "mg_internal.h" */
  11639. /*
  11640. * https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake
  11641. *
  11642. * +----+----------+----------+
  11643. * |VER | NMETHODS | METHODS |
  11644. * +----+----------+----------+
  11645. * | 1 | 1 | 1 to 255 |
  11646. * +----+----------+----------+
  11647. */
  11648. static void mg_socks5_handshake(struct mg_connection *c) {
  11649. struct mbuf *r = &c->recv_mbuf;
  11650. if (r->buf[0] != MG_SOCKS_VERSION) {
  11651. c->flags |= MG_F_CLOSE_IMMEDIATELY;
  11652. } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) {
  11653. /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */
  11654. unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE};
  11655. int i;
  11656. for (i = 2; i < r->buf[1] + 2; i++) {
  11657. /* TODO(lsm): support other auth methods */
  11658. if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i];
  11659. }
  11660. mbuf_remove(r, 2 + r->buf[1]);
  11661. mg_send(c, reply, sizeof(reply));
  11662. c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */
  11663. }
  11664. }
  11665. static void disband(struct mg_connection *c) {
  11666. struct mg_connection *c2 = (struct mg_connection *) c->user_data;
  11667. if (c2 != NULL) {
  11668. c2->flags |= MG_F_SEND_AND_CLOSE;
  11669. c2->user_data = NULL;
  11670. }
  11671. c->flags |= MG_F_SEND_AND_CLOSE;
  11672. c->user_data = NULL;
  11673. }
  11674. static void relay_data(struct mg_connection *c) {
  11675. struct mg_connection *c2 = (struct mg_connection *) c->user_data;
  11676. if (c2 != NULL) {
  11677. mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len);
  11678. mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
  11679. } else {
  11680. c->flags |= MG_F_SEND_AND_CLOSE;
  11681. }
  11682. }
  11683. static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  11684. if (ev == MG_EV_CLOSE) {
  11685. disband(c);
  11686. } else if (ev == MG_EV_RECV) {
  11687. relay_data(c);
  11688. } else if (ev == MG_EV_CONNECT) {
  11689. int res = *(int *) ev_data;
  11690. if (res != 0) LOG(LL_ERROR, ("connect error: %d", res));
  11691. }
  11692. }
  11693. static void mg_socks5_connect(struct mg_connection *c, const char *addr) {
  11694. struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler);
  11695. serv->user_data = c;
  11696. c->user_data = serv;
  11697. }
  11698. /*
  11699. * Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4
  11700. *
  11701. * +----+-----+-------+------+----------+----------+
  11702. * |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
  11703. * +----+-----+-------+------+----------+----------+
  11704. * | 1 | 1 | X'00' | 1 | Variable | 2 |
  11705. * +----+-----+-------+------+----------+----------+
  11706. */
  11707. static void mg_socks5_handle_request(struct mg_connection *c) {
  11708. struct mbuf *r = &c->recv_mbuf;
  11709. unsigned char *p = (unsigned char *) r->buf;
  11710. unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS;
  11711. int ver, cmd, atyp;
  11712. char addr[300];
  11713. if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */
  11714. ver = p[0];
  11715. cmd = p[1];
  11716. atyp = p[3];
  11717. /* TODO(lsm): support other commands */
  11718. if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) {
  11719. reply = MG_SOCKS_CMD_NOT_SUPPORTED;
  11720. } else if (atyp == MG_SOCKS_ADDR_IPV4) {
  11721. addr_len = 4;
  11722. if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
  11723. snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7],
  11724. p[8] << 8 | p[9]);
  11725. mg_socks5_connect(c, addr);
  11726. } else if (atyp == MG_SOCKS_ADDR_IPV6) {
  11727. addr_len = 16;
  11728. if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
  11729. snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d",
  11730. p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9],
  11731. p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15],
  11732. p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]);
  11733. mg_socks5_connect(c, addr);
  11734. } else if (atyp == MG_SOCKS_ADDR_DOMAIN) {
  11735. addr_len = p[4] + 1;
  11736. if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
  11737. snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5,
  11738. p[4 + addr_len] << 8 | p[4 + addr_len + 1]);
  11739. mg_socks5_connect(c, addr);
  11740. } else {
  11741. reply = MG_SOCKS_ADDR_NOT_SUPPORTED;
  11742. }
  11743. /*
  11744. * Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5
  11745. *
  11746. * +----+-----+-------+------+----------+----------+
  11747. * |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
  11748. * +----+-----+-------+------+----------+----------+
  11749. * | 1 | 1 | X'00' | 1 | Variable | 2 |
  11750. * +----+-----+-------+------+----------+----------+
  11751. */
  11752. {
  11753. unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0};
  11754. mg_send(c, buf, sizeof(buf));
  11755. }
  11756. mg_send(c, r->buf + 3, addr_len + 1 + 2);
  11757. mbuf_remove(r, 6 + addr_len); /* Remove request from the input stream */
  11758. c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */
  11759. }
  11760. static void socks_handler(struct mg_connection *c, int ev, void *ev_data) {
  11761. if (ev == MG_EV_RECV) {
  11762. if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c);
  11763. if (c->flags & MG_SOCKS_HANDSHAKE_DONE &&
  11764. !(c->flags & MG_SOCKS_CONNECT_DONE)) {
  11765. mg_socks5_handle_request(c);
  11766. }
  11767. if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c);
  11768. } else if (ev == MG_EV_CLOSE) {
  11769. disband(c);
  11770. }
  11771. (void) ev_data;
  11772. }
  11773. void mg_set_protocol_socks(struct mg_connection *c) {
  11774. c->proto_handler = socks_handler;
  11775. }
  11776. #endif
  11777. #ifdef MG_MODULE_LINES
  11778. #line 1 "common/platforms/cc3200/cc3200_libc.c"
  11779. #endif
  11780. /*
  11781. * Copyright (c) 2014-2018 Cesanta Software Limited
  11782. * All rights reserved
  11783. *
  11784. * Licensed under the Apache License, Version 2.0 (the ""License"");
  11785. * you may not use this file except in compliance with the License.
  11786. * You may obtain a copy of the License at
  11787. *
  11788. * http://www.apache.org/licenses/LICENSE-2.0
  11789. *
  11790. * Unless required by applicable law or agreed to in writing, software
  11791. * distributed under the License is distributed on an ""AS IS"" BASIS,
  11792. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11793. * See the License for the specific language governing permissions and
  11794. * limitations under the License.
  11795. */
  11796. #if CS_PLATFORM == CS_P_CC3200
  11797. /* Amalgamated: #include "common/mg_mem.h" */
  11798. #include <stdio.h>
  11799. #include <string.h>
  11800. #ifndef __TI_COMPILER_VERSION__
  11801. #include <reent.h>
  11802. #include <sys/stat.h>
  11803. #include <sys/time.h>
  11804. #include <unistd.h>
  11805. #endif
  11806. #include <inc/hw_types.h>
  11807. #include <inc/hw_memmap.h>
  11808. #include <driverlib/prcm.h>
  11809. #include <driverlib/rom.h>
  11810. #include <driverlib/rom_map.h>
  11811. #include <driverlib/uart.h>
  11812. #include <driverlib/utils.h>
  11813. #define CONSOLE_UART UARTA0_BASE
  11814. #ifdef __TI_COMPILER_VERSION__
  11815. int asprintf(char **strp, const char *fmt, ...) {
  11816. va_list ap;
  11817. int len;
  11818. *strp = MG_MALLOC(BUFSIZ);
  11819. if (*strp == NULL) return -1;
  11820. va_start(ap, fmt);
  11821. len = vsnprintf(*strp, BUFSIZ, fmt, ap);
  11822. va_end(ap);
  11823. if (len > 0) {
  11824. *strp = MG_REALLOC(*strp, len + 1);
  11825. if (*strp == NULL) return -1;
  11826. }
  11827. if (len >= BUFSIZ) {
  11828. va_start(ap, fmt);
  11829. len = vsnprintf(*strp, len + 1, fmt, ap);
  11830. va_end(ap);
  11831. }
  11832. return len;
  11833. }
  11834. #if MG_TI_NO_HOST_INTERFACE
  11835. time_t HOSTtime() {
  11836. struct timeval tp;
  11837. gettimeofday(&tp, NULL);
  11838. return tp.tv_sec;
  11839. }
  11840. #endif
  11841. #endif /* __TI_COMPILER_VERSION__ */
  11842. void fprint_str(FILE *fp, const char *str) {
  11843. while (*str != '\0') {
  11844. if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
  11845. MAP_UARTCharPut(CONSOLE_UART, *str++);
  11846. }
  11847. }
  11848. void _exit(int status) {
  11849. fprint_str(stderr, "_exit\n");
  11850. /* cause an unaligned access exception, that will drop you into gdb */
  11851. *(int *) 1 = status;
  11852. while (1)
  11853. ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
  11854. }
  11855. void _not_implemented(const char *what) {
  11856. fprint_str(stderr, what);
  11857. fprint_str(stderr, " is not implemented\n");
  11858. _exit(42);
  11859. }
  11860. int _kill(int pid, int sig) {
  11861. (void) pid;
  11862. (void) sig;
  11863. _not_implemented("_kill");
  11864. return -1;
  11865. }
  11866. int _getpid() {
  11867. fprint_str(stderr, "_getpid is not implemented\n");
  11868. return 42;
  11869. }
  11870. int _isatty(int fd) {
  11871. /* 0, 1 and 2 are TTYs. */
  11872. return fd < 2;
  11873. }
  11874. #endif /* CS_PLATFORM == CS_P_CC3200 */
  11875. #ifdef MG_MODULE_LINES
  11876. #line 1 "common/platforms/msp432/msp432_libc.c"
  11877. #endif
  11878. /*
  11879. * Copyright (c) 2014-2018 Cesanta Software Limited
  11880. * All rights reserved
  11881. *
  11882. * Licensed under the Apache License, Version 2.0 (the ""License"");
  11883. * you may not use this file except in compliance with the License.
  11884. * You may obtain a copy of the License at
  11885. *
  11886. * http://www.apache.org/licenses/LICENSE-2.0
  11887. *
  11888. * Unless required by applicable law or agreed to in writing, software
  11889. * distributed under the License is distributed on an ""AS IS"" BASIS,
  11890. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11891. * See the License for the specific language governing permissions and
  11892. * limitations under the License.
  11893. */
  11894. #if CS_PLATFORM == CS_P_MSP432
  11895. #include <ti/sysbios/BIOS.h>
  11896. #include <ti/sysbios/knl/Clock.h>
  11897. int gettimeofday(struct timeval *tp, void *tzp) {
  11898. uint32_t ticks = Clock_getTicks();
  11899. tp->tv_sec = ticks / 1000;
  11900. tp->tv_usec = (ticks % 1000) * 1000;
  11901. return 0;
  11902. }
  11903. #endif /* CS_PLATFORM == CS_P_MSP432 */
  11904. #ifdef MG_MODULE_LINES
  11905. #line 1 "common/platforms/nrf5/nrf5_libc.c"
  11906. #endif
  11907. /*
  11908. * Copyright (c) 2014-2018 Cesanta Software Limited
  11909. * All rights reserved
  11910. *
  11911. * Licensed under the Apache License, Version 2.0 (the ""License"");
  11912. * you may not use this file except in compliance with the License.
  11913. * You may obtain a copy of the License at
  11914. *
  11915. * http://www.apache.org/licenses/LICENSE-2.0
  11916. *
  11917. * Unless required by applicable law or agreed to in writing, software
  11918. * distributed under the License is distributed on an ""AS IS"" BASIS,
  11919. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11920. * See the License for the specific language governing permissions and
  11921. * limitations under the License.
  11922. */
  11923. #if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
  11924. defined(__ARMCC_VERSION)
  11925. int gettimeofday(struct timeval *tp, void *tzp) {
  11926. /* TODO */
  11927. tp->tv_sec = 0;
  11928. tp->tv_usec = 0;
  11929. return 0;
  11930. }
  11931. #endif
  11932. #ifdef MG_MODULE_LINES
  11933. #line 1 "common/platforms/simplelink/sl_fs_slfs.h"
  11934. #endif
  11935. /*
  11936. * Copyright (c) 2014-2018 Cesanta Software Limited
  11937. * All rights reserved
  11938. *
  11939. * Licensed under the Apache License, Version 2.0 (the ""License"");
  11940. * you may not use this file except in compliance with the License.
  11941. * You may obtain a copy of the License at
  11942. *
  11943. * http://www.apache.org/licenses/LICENSE-2.0
  11944. *
  11945. * Unless required by applicable law or agreed to in writing, software
  11946. * distributed under the License is distributed on an ""AS IS"" BASIS,
  11947. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11948. * See the License for the specific language governing permissions and
  11949. * limitations under the License.
  11950. */
  11951. #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
  11952. #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
  11953. #if defined(MG_FS_SLFS)
  11954. #include <stdio.h>
  11955. #ifndef __TI_COMPILER_VERSION__
  11956. #include <unistd.h>
  11957. #include <sys/stat.h>
  11958. #endif
  11959. #define MAX_OPEN_SLFS_FILES 8
  11960. /* Indirect libc interface - same functions, different names. */
  11961. int fs_slfs_open(const char *pathname, int flags, mode_t mode);
  11962. int fs_slfs_close(int fd);
  11963. ssize_t fs_slfs_read(int fd, void *buf, size_t count);
  11964. ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
  11965. int fs_slfs_stat(const char *pathname, struct stat *s);
  11966. int fs_slfs_fstat(int fd, struct stat *s);
  11967. off_t fs_slfs_lseek(int fd, off_t offset, int whence);
  11968. int fs_slfs_unlink(const char *filename);
  11969. int fs_slfs_rename(const char *from, const char *to);
  11970. void fs_slfs_set_file_size(const char *name, size_t size);
  11971. void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token);
  11972. void fs_slfs_unset_file_flags(const char *name);
  11973. #endif /* defined(MG_FS_SLFS) */
  11974. #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
  11975. #ifdef MG_MODULE_LINES
  11976. #line 1 "common/platforms/simplelink/sl_fs_slfs.c"
  11977. #endif
  11978. /*
  11979. * Copyright (c) 2014-2018 Cesanta Software Limited
  11980. * All rights reserved
  11981. *
  11982. * Licensed under the Apache License, Version 2.0 (the ""License"");
  11983. * you may not use this file except in compliance with the License.
  11984. * You may obtain a copy of the License at
  11985. *
  11986. * http://www.apache.org/licenses/LICENSE-2.0
  11987. *
  11988. * Unless required by applicable law or agreed to in writing, software
  11989. * distributed under the License is distributed on an ""AS IS"" BASIS,
  11990. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11991. * See the License for the specific language governing permissions and
  11992. * limitations under the License.
  11993. */
  11994. /* Standard libc interface to TI SimpleLink FS. */
  11995. #if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
  11996. /* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
  11997. #include <errno.h>
  11998. #if CS_PLATFORM == CS_P_CC3200
  11999. #include <inc/hw_types.h>
  12000. #endif
  12001. /* Amalgamated: #include "common/cs_dbg.h" */
  12002. /* Amalgamated: #include "common/mg_mem.h" */
  12003. #if SL_MAJOR_VERSION_NUM < 2
  12004. int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
  12005. _i32 fh;
  12006. _i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh);
  12007. return (r < 0 ? r : fh);
  12008. }
  12009. #else /* SL_MAJOR_VERSION_NUM >= 2 */
  12010. int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
  12011. return sl_FsOpen(fname, flags, (unsigned long *) token);
  12012. }
  12013. #endif
  12014. /* From sl_fs.c */
  12015. int set_errno(int e);
  12016. const char *drop_dir(const char *fname, bool *is_slfs);
  12017. /*
  12018. * With SLFS, you have to pre-declare max file size. Yes. Really.
  12019. * 64K should be enough for everyone. Right?
  12020. */
  12021. #ifndef FS_SLFS_MAX_FILE_SIZE
  12022. #define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
  12023. #endif
  12024. struct sl_file_open_info {
  12025. char *name;
  12026. size_t size;
  12027. uint32_t flags;
  12028. uint32_t *token;
  12029. };
  12030. struct sl_fd_info {
  12031. _i32 fh;
  12032. _off_t pos;
  12033. size_t size;
  12034. };
  12035. static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
  12036. static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES];
  12037. static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
  12038. bool create);
  12039. static int sl_fs_to_errno(_i32 r) {
  12040. DBG(("SL error: %d", (int) r));
  12041. switch (r) {
  12042. case SL_FS_OK:
  12043. return 0;
  12044. case SL_ERROR_FS_FILE_NAME_EXIST:
  12045. return EEXIST;
  12046. case SL_ERROR_FS_WRONG_FILE_NAME:
  12047. return EINVAL;
  12048. case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX:
  12049. case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE:
  12050. return ENOSPC;
  12051. case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM:
  12052. return ENOMEM;
  12053. case SL_ERROR_FS_FILE_NOT_EXISTS:
  12054. return ENOENT;
  12055. case SL_ERROR_FS_NOT_SUPPORTED:
  12056. return ENOTSUP;
  12057. }
  12058. return ENXIO;
  12059. }
  12060. int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
  12061. int fd;
  12062. for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
  12063. if (s_sl_fds[fd].fh <= 0) break;
  12064. }
  12065. if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
  12066. struct sl_fd_info *fi = &s_sl_fds[fd];
  12067. /*
  12068. * Apply path manipulations again, in case we got here directly
  12069. * (via TI libc's "add_device").
  12070. */
  12071. pathname = drop_dir(pathname, NULL);
  12072. _u32 am = 0;
  12073. fi->size = (size_t) -1;
  12074. int rw = (flags & 3);
  12075. size_t new_size = 0;
  12076. struct sl_file_open_info *foi =
  12077. fs_slfs_find_foi(pathname, false /* create */);
  12078. if (foi != NULL) {
  12079. LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size,
  12080. (unsigned int) foi->flags, foi->token));
  12081. }
  12082. if (rw == O_RDONLY) {
  12083. SlFsFileInfo_t sl_fi;
  12084. _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
  12085. if (r == SL_FS_OK) {
  12086. fi->size = SL_FI_FILE_SIZE(sl_fi);
  12087. }
  12088. am = SL_FS_READ;
  12089. } else {
  12090. if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
  12091. // FailFS files cannot be opened for append and will be truncated
  12092. // when opened for write.
  12093. return set_errno(ENOTSUP);
  12094. }
  12095. if (flags & O_CREAT) {
  12096. if (foi->size > 0) {
  12097. new_size = foi->size;
  12098. } else {
  12099. new_size = FS_SLFS_MAX_FILE_SIZE;
  12100. }
  12101. am = FS_MODE_OPEN_CREATE(new_size, 0);
  12102. } else {
  12103. am = SL_FS_WRITE;
  12104. }
  12105. #if SL_MAJOR_VERSION_NUM >= 2
  12106. am |= SL_FS_OVERWRITE;
  12107. #endif
  12108. }
  12109. uint32_t *token = NULL;
  12110. if (foi != NULL) {
  12111. am |= foi->flags;
  12112. token = foi->token;
  12113. }
  12114. fi->fh = slfs_open((_u8 *) pathname, am, token);
  12115. LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am,
  12116. token, (unsigned int) new_size, (int) fi->fh));
  12117. int r;
  12118. if (fi->fh >= 0) {
  12119. fi->pos = 0;
  12120. r = fd;
  12121. } else {
  12122. r = set_errno(sl_fs_to_errno(fi->fh));
  12123. }
  12124. return r;
  12125. }
  12126. int fs_slfs_close(int fd) {
  12127. struct sl_fd_info *fi = &s_sl_fds[fd];
  12128. if (fi->fh <= 0) return set_errno(EBADF);
  12129. _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
  12130. LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
  12131. s_sl_fds[fd].fh = -1;
  12132. return set_errno(sl_fs_to_errno(r));
  12133. }
  12134. ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
  12135. struct sl_fd_info *fi = &s_sl_fds[fd];
  12136. if (fi->fh <= 0) return set_errno(EBADF);
  12137. /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
  12138. */
  12139. if (fi->pos == fi->size) return 0;
  12140. _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
  12141. DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
  12142. (int) r));
  12143. if (r >= 0) {
  12144. fi->pos += r;
  12145. return r;
  12146. }
  12147. return set_errno(sl_fs_to_errno(r));
  12148. }
  12149. ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
  12150. struct sl_fd_info *fi = &s_sl_fds[fd];
  12151. if (fi->fh <= 0) return set_errno(EBADF);
  12152. _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
  12153. DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
  12154. (int) r));
  12155. if (r >= 0) {
  12156. fi->pos += r;
  12157. return r;
  12158. }
  12159. return set_errno(sl_fs_to_errno(r));
  12160. }
  12161. int fs_slfs_stat(const char *pathname, struct stat *s) {
  12162. SlFsFileInfo_t sl_fi;
  12163. /*
  12164. * Apply path manipulations again, in case we got here directly
  12165. * (via TI libc's "add_device").
  12166. */
  12167. pathname = drop_dir(pathname, NULL);
  12168. _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
  12169. if (r == SL_FS_OK) {
  12170. s->st_mode = S_IFREG | 0666;
  12171. s->st_nlink = 1;
  12172. s->st_size = SL_FI_FILE_SIZE(sl_fi);
  12173. return 0;
  12174. }
  12175. return set_errno(sl_fs_to_errno(r));
  12176. }
  12177. int fs_slfs_fstat(int fd, struct stat *s) {
  12178. struct sl_fd_info *fi = &s_sl_fds[fd];
  12179. if (fi->fh <= 0) return set_errno(EBADF);
  12180. s->st_mode = 0666;
  12181. s->st_mode = S_IFREG | 0666;
  12182. s->st_nlink = 1;
  12183. s->st_size = fi->size;
  12184. return 0;
  12185. }
  12186. off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
  12187. if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
  12188. switch (whence) {
  12189. case SEEK_SET:
  12190. s_sl_fds[fd].pos = offset;
  12191. break;
  12192. case SEEK_CUR:
  12193. s_sl_fds[fd].pos += offset;
  12194. break;
  12195. case SEEK_END:
  12196. return set_errno(ENOTSUP);
  12197. }
  12198. return 0;
  12199. }
  12200. int fs_slfs_unlink(const char *pathname) {
  12201. /*
  12202. * Apply path manipulations again, in case we got here directly
  12203. * (via TI libc's "add_device").
  12204. */
  12205. pathname = drop_dir(pathname, NULL);
  12206. return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
  12207. }
  12208. int fs_slfs_rename(const char *from, const char *to) {
  12209. return set_errno(ENOTSUP);
  12210. }
  12211. static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
  12212. bool create) {
  12213. int i = 0;
  12214. for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
  12215. if (s_sl_file_open_infos[i].name != NULL &&
  12216. strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) {
  12217. break;
  12218. }
  12219. }
  12220. if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i];
  12221. if (!create) return NULL;
  12222. for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
  12223. if (s_sl_file_open_infos[i].name == NULL) break;
  12224. }
  12225. if (i == MAX_OPEN_SLFS_FILES) {
  12226. i = 0; /* Evict a random slot. */
  12227. }
  12228. if (s_sl_file_open_infos[i].name != NULL) {
  12229. free(s_sl_file_open_infos[i].name);
  12230. }
  12231. s_sl_file_open_infos[i].name = strdup(name);
  12232. return &s_sl_file_open_infos[i];
  12233. }
  12234. void fs_slfs_set_file_size(const char *name, size_t size) {
  12235. struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
  12236. foi->size = size;
  12237. }
  12238. void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) {
  12239. struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
  12240. foi->flags = flags;
  12241. foi->token = token;
  12242. }
  12243. void fs_slfs_unset_file_flags(const char *name) {
  12244. struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */);
  12245. if (foi == NULL) return;
  12246. free(foi->name);
  12247. memset(foi, 0, sizeof(*foi));
  12248. }
  12249. #endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
  12250. #ifdef MG_MODULE_LINES
  12251. #line 1 "common/platforms/simplelink/sl_fs.c"
  12252. #endif
  12253. /*
  12254. * Copyright (c) 2014-2018 Cesanta Software Limited
  12255. * All rights reserved
  12256. *
  12257. * Licensed under the Apache License, Version 2.0 (the ""License"");
  12258. * you may not use this file except in compliance with the License.
  12259. * You may obtain a copy of the License at
  12260. *
  12261. * http://www.apache.org/licenses/LICENSE-2.0
  12262. *
  12263. * Unless required by applicable law or agreed to in writing, software
  12264. * distributed under the License is distributed on an ""AS IS"" BASIS,
  12265. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12266. * See the License for the specific language governing permissions and
  12267. * limitations under the License.
  12268. */
  12269. #if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
  12270. (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
  12271. int set_errno(int e) {
  12272. errno = e;
  12273. return (e == 0 ? 0 : -1);
  12274. }
  12275. const char *drop_dir(const char *fname, bool *is_slfs) {
  12276. if (is_slfs != NULL) {
  12277. *is_slfs = (strncmp(fname, "SL:", 3) == 0);
  12278. if (*is_slfs) fname += 3;
  12279. }
  12280. /* Drop "./", if any */
  12281. if (fname[0] == '.' && fname[1] == '/') {
  12282. fname += 2;
  12283. }
  12284. /*
  12285. * Drop / if it is the only one in the path.
  12286. * This allows use of /pretend/directories but serves /file.txt as normal.
  12287. */
  12288. if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
  12289. fname++;
  12290. }
  12291. return fname;
  12292. }
  12293. #if !defined(MG_FS_NO_VFS)
  12294. #include <errno.h>
  12295. #include <stdbool.h>
  12296. #include <stdio.h>
  12297. #include <stdlib.h>
  12298. #include <string.h>
  12299. #ifdef __TI_COMPILER_VERSION__
  12300. #include <file.h>
  12301. #endif
  12302. /* Amalgamated: #include "common/cs_dbg.h" */
  12303. /* Amalgamated: #include "common/platform.h" */
  12304. #ifdef CC3200_FS_SPIFFS
  12305. /* Amalgamated: #include "cc3200_fs_spiffs.h" */
  12306. #endif
  12307. #ifdef MG_FS_SLFS
  12308. /* Amalgamated: #include "sl_fs_slfs.h" */
  12309. #endif
  12310. #define NUM_SYS_FDS 3
  12311. #define SPIFFS_FD_BASE 10
  12312. #define SLFS_FD_BASE 100
  12313. #if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE)
  12314. #if CS_PLATFORM == CS_P_CC3200
  12315. #include <inc/hw_types.h>
  12316. #include <inc/hw_memmap.h>
  12317. #include <driverlib/rom.h>
  12318. #include <driverlib/rom_map.h>
  12319. #include <driverlib/uart.h>
  12320. #define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
  12321. #else
  12322. #define MG_UART_WRITE(fd, buf, len)
  12323. #endif /* CS_PLATFORM == CS_P_CC3200 */
  12324. #endif /* !MG_UART_CHAR_PUT */
  12325. enum fd_type {
  12326. FD_INVALID,
  12327. FD_SYS,
  12328. #ifdef CC3200_FS_SPIFFS
  12329. FD_SPIFFS,
  12330. #endif
  12331. #ifdef MG_FS_SLFS
  12332. FD_SLFS
  12333. #endif
  12334. };
  12335. static int fd_type(int fd) {
  12336. if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
  12337. #ifdef CC3200_FS_SPIFFS
  12338. if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
  12339. return FD_SPIFFS;
  12340. }
  12341. #endif
  12342. #ifdef MG_FS_SLFS
  12343. if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
  12344. return FD_SLFS;
  12345. }
  12346. #endif
  12347. return FD_INVALID;
  12348. }
  12349. #if MG_TI_NO_HOST_INTERFACE
  12350. int open(const char *pathname, unsigned flags, int mode) {
  12351. #else
  12352. int _open(const char *pathname, int flags, mode_t mode) {
  12353. #endif
  12354. int fd = -1;
  12355. bool is_sl;
  12356. const char *fname = drop_dir(pathname, &is_sl);
  12357. if (is_sl) {
  12358. #ifdef MG_FS_SLFS
  12359. fd = fs_slfs_open(fname, flags, mode);
  12360. if (fd >= 0) fd += SLFS_FD_BASE;
  12361. #endif
  12362. } else {
  12363. #ifdef CC3200_FS_SPIFFS
  12364. fd = fs_spiffs_open(fname, flags, mode);
  12365. if (fd >= 0) fd += SPIFFS_FD_BASE;
  12366. #endif
  12367. }
  12368. LOG(LL_DEBUG,
  12369. ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
  12370. return fd;
  12371. }
  12372. int _stat(const char *pathname, struct stat *st) {
  12373. int res = -1;
  12374. bool is_sl;
  12375. const char *fname = drop_dir(pathname, &is_sl);
  12376. memset(st, 0, sizeof(*st));
  12377. /* Simulate statting the root directory. */
  12378. if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
  12379. st->st_ino = 0;
  12380. st->st_mode = S_IFDIR | 0777;
  12381. st->st_nlink = 1;
  12382. st->st_size = 0;
  12383. return 0;
  12384. }
  12385. if (is_sl) {
  12386. #ifdef MG_FS_SLFS
  12387. res = fs_slfs_stat(fname, st);
  12388. #endif
  12389. } else {
  12390. #ifdef CC3200_FS_SPIFFS
  12391. res = fs_spiffs_stat(fname, st);
  12392. #endif
  12393. }
  12394. LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
  12395. return res;
  12396. }
  12397. #if MG_TI_NO_HOST_INTERFACE
  12398. int close(int fd) {
  12399. #else
  12400. int _close(int fd) {
  12401. #endif
  12402. int r = -1;
  12403. switch (fd_type(fd)) {
  12404. case FD_INVALID:
  12405. r = set_errno(EBADF);
  12406. break;
  12407. case FD_SYS:
  12408. r = set_errno(EACCES);
  12409. break;
  12410. #ifdef CC3200_FS_SPIFFS
  12411. case FD_SPIFFS:
  12412. r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
  12413. break;
  12414. #endif
  12415. #ifdef MG_FS_SLFS
  12416. case FD_SLFS:
  12417. r = fs_slfs_close(fd - SLFS_FD_BASE);
  12418. break;
  12419. #endif
  12420. }
  12421. DBG(("close(%d) = %d", fd, r));
  12422. return r;
  12423. }
  12424. #if MG_TI_NO_HOST_INTERFACE
  12425. off_t lseek(int fd, off_t offset, int whence) {
  12426. #else
  12427. off_t _lseek(int fd, off_t offset, int whence) {
  12428. #endif
  12429. int r = -1;
  12430. switch (fd_type(fd)) {
  12431. case FD_INVALID:
  12432. r = set_errno(EBADF);
  12433. break;
  12434. case FD_SYS:
  12435. r = set_errno(ESPIPE);
  12436. break;
  12437. #ifdef CC3200_FS_SPIFFS
  12438. case FD_SPIFFS:
  12439. r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
  12440. break;
  12441. #endif
  12442. #ifdef MG_FS_SLFS
  12443. case FD_SLFS:
  12444. r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
  12445. break;
  12446. #endif
  12447. }
  12448. DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
  12449. return r;
  12450. }
  12451. int _fstat(int fd, struct stat *s) {
  12452. int r = -1;
  12453. memset(s, 0, sizeof(*s));
  12454. switch (fd_type(fd)) {
  12455. case FD_INVALID:
  12456. r = set_errno(EBADF);
  12457. break;
  12458. case FD_SYS: {
  12459. /* Create barely passable stats for STD{IN,OUT,ERR}. */
  12460. memset(s, 0, sizeof(*s));
  12461. s->st_ino = fd;
  12462. s->st_mode = S_IFCHR | 0666;
  12463. r = 0;
  12464. break;
  12465. }
  12466. #ifdef CC3200_FS_SPIFFS
  12467. case FD_SPIFFS:
  12468. r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
  12469. break;
  12470. #endif
  12471. #ifdef MG_FS_SLFS
  12472. case FD_SLFS:
  12473. r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
  12474. break;
  12475. #endif
  12476. }
  12477. DBG(("fstat(%d) = %d", fd, r));
  12478. return r;
  12479. }
  12480. #if MG_TI_NO_HOST_INTERFACE
  12481. int read(int fd, char *buf, unsigned count) {
  12482. #else
  12483. ssize_t _read(int fd, void *buf, size_t count) {
  12484. #endif
  12485. int r = -1;
  12486. switch (fd_type(fd)) {
  12487. case FD_INVALID:
  12488. r = set_errno(EBADF);
  12489. break;
  12490. case FD_SYS: {
  12491. if (fd != 0) {
  12492. r = set_errno(EACCES);
  12493. break;
  12494. }
  12495. /* Should we allow reading from stdin = uart? */
  12496. r = set_errno(ENOTSUP);
  12497. break;
  12498. }
  12499. #ifdef CC3200_FS_SPIFFS
  12500. case FD_SPIFFS:
  12501. r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
  12502. break;
  12503. #endif
  12504. #ifdef MG_FS_SLFS
  12505. case FD_SLFS:
  12506. r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
  12507. break;
  12508. #endif
  12509. }
  12510. DBG(("read(%d, %u) = %d", fd, count, r));
  12511. return r;
  12512. }
  12513. #if MG_TI_NO_HOST_INTERFACE
  12514. int write(int fd, const char *buf, unsigned count) {
  12515. #else
  12516. ssize_t _write(int fd, const void *buf, size_t count) {
  12517. #endif
  12518. int r = -1;
  12519. switch (fd_type(fd)) {
  12520. case FD_INVALID:
  12521. r = set_errno(EBADF);
  12522. break;
  12523. case FD_SYS: {
  12524. if (fd == 0) {
  12525. r = set_errno(EACCES);
  12526. break;
  12527. }
  12528. #ifdef MG_UART_WRITE
  12529. MG_UART_WRITE(fd, buf, count);
  12530. #elif defined(MG_UART_CHAR_PUT)
  12531. {
  12532. size_t i;
  12533. for (i = 0; i < count; i++) {
  12534. const char c = ((const char *) buf)[i];
  12535. if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
  12536. MG_UART_CHAR_PUT(fd, c);
  12537. }
  12538. }
  12539. #endif
  12540. r = count;
  12541. break;
  12542. }
  12543. #ifdef CC3200_FS_SPIFFS
  12544. case FD_SPIFFS:
  12545. r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
  12546. break;
  12547. #endif
  12548. #ifdef MG_FS_SLFS
  12549. case FD_SLFS:
  12550. r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
  12551. break;
  12552. #endif
  12553. }
  12554. return r;
  12555. }
  12556. /*
  12557. * On Newlib we override rename directly too, because the default
  12558. * implementation using _link and _unlink doesn't work for us.
  12559. */
  12560. #if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
  12561. int rename(const char *frompath, const char *topath) {
  12562. int r = -1;
  12563. bool is_sl_from, is_sl_to;
  12564. const char *from = drop_dir(frompath, &is_sl_from);
  12565. const char *to = drop_dir(topath, &is_sl_to);
  12566. if (is_sl_from || is_sl_to) {
  12567. set_errno(ENOTSUP);
  12568. } else {
  12569. #ifdef CC3200_FS_SPIFFS
  12570. r = fs_spiffs_rename(from, to);
  12571. #endif
  12572. }
  12573. DBG(("rename(%s, %s) = %d", from, to, r));
  12574. return r;
  12575. }
  12576. #endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
  12577. #if MG_TI_NO_HOST_INTERFACE
  12578. int unlink(const char *pathname) {
  12579. #else
  12580. int _unlink(const char *pathname) {
  12581. #endif
  12582. int r = -1;
  12583. bool is_sl;
  12584. const char *fname = drop_dir(pathname, &is_sl);
  12585. if (is_sl) {
  12586. #ifdef MG_FS_SLFS
  12587. r = fs_slfs_unlink(fname);
  12588. #endif
  12589. } else {
  12590. #ifdef CC3200_FS_SPIFFS
  12591. r = fs_spiffs_unlink(fname);
  12592. #endif
  12593. }
  12594. DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
  12595. return r;
  12596. }
  12597. #ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
  12598. DIR *opendir(const char *dir_name) {
  12599. DIR *r = NULL;
  12600. bool is_sl;
  12601. drop_dir(dir_name, &is_sl);
  12602. if (is_sl) {
  12603. r = NULL;
  12604. set_errno(ENOTSUP);
  12605. } else {
  12606. r = fs_spiffs_opendir(dir_name);
  12607. }
  12608. DBG(("opendir(%s) = %p", dir_name, r));
  12609. return r;
  12610. }
  12611. struct dirent *readdir(DIR *dir) {
  12612. struct dirent *res = fs_spiffs_readdir(dir);
  12613. DBG(("readdir(%p) = %p", dir, res));
  12614. return res;
  12615. }
  12616. int closedir(DIR *dir) {
  12617. int res = fs_spiffs_closedir(dir);
  12618. DBG(("closedir(%p) = %d", dir, res));
  12619. return res;
  12620. }
  12621. int rmdir(const char *path) {
  12622. return fs_spiffs_rmdir(path);
  12623. }
  12624. int mkdir(const char *path, mode_t mode) {
  12625. (void) path;
  12626. (void) mode;
  12627. /* for spiffs supports only root dir, which comes from mongoose as '.' */
  12628. return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
  12629. }
  12630. #endif
  12631. int sl_fs_init(void) {
  12632. int ret = 1;
  12633. #ifdef __TI_COMPILER_VERSION__
  12634. #ifdef MG_FS_SLFS
  12635. #pragma diag_push
  12636. #pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
  12637. */
  12638. ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
  12639. fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
  12640. fs_slfs_rename) == 0);
  12641. #pragma diag_pop
  12642. #endif
  12643. #endif
  12644. return ret;
  12645. }
  12646. #endif /* !defined(MG_FS_NO_VFS) */
  12647. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
  12648. defined(MG_FS_SPIFFS)) */
  12649. #ifdef MG_MODULE_LINES
  12650. #line 1 "common/platforms/simplelink/sl_socket.c"
  12651. #endif
  12652. /*
  12653. * Copyright (c) 2014-2018 Cesanta Software Limited
  12654. * All rights reserved
  12655. *
  12656. * Licensed under the Apache License, Version 2.0 (the ""License"");
  12657. * you may not use this file except in compliance with the License.
  12658. * You may obtain a copy of the License at
  12659. *
  12660. * http://www.apache.org/licenses/LICENSE-2.0
  12661. *
  12662. * Unless required by applicable law or agreed to in writing, software
  12663. * distributed under the License is distributed on an ""AS IS"" BASIS,
  12664. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12665. * See the License for the specific language governing permissions and
  12666. * limitations under the License.
  12667. */
  12668. #if MG_NET_IF == MG_NET_IF_SIMPLELINK
  12669. #include <errno.h>
  12670. #include <stdio.h>
  12671. /* Amalgamated: #include "common/platform.h" */
  12672. const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
  12673. int res;
  12674. struct in_addr *in = (struct in_addr *) src;
  12675. if (af != AF_INET) {
  12676. errno = ENOTSUP;
  12677. return NULL;
  12678. }
  12679. res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
  12680. SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
  12681. SL_IPV4_BYTE(in->s_addr, 3));
  12682. return res > 0 ? dst : NULL;
  12683. }
  12684. char *inet_ntoa(struct in_addr n) {
  12685. static char a[16];
  12686. return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
  12687. }
  12688. int inet_pton(int af, const char *src, void *dst) {
  12689. uint32_t a0, a1, a2, a3;
  12690. uint8_t *db = (uint8_t *) dst;
  12691. if (af != AF_INET) {
  12692. errno = ENOTSUP;
  12693. return 0;
  12694. }
  12695. if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
  12696. return 0;
  12697. }
  12698. *db = a3;
  12699. *(db + 1) = a2;
  12700. *(db + 2) = a1;
  12701. *(db + 3) = a0;
  12702. return 1;
  12703. }
  12704. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
  12705. #ifdef MG_MODULE_LINES
  12706. #line 1 "common/platforms/simplelink/sl_mg_task.c"
  12707. #endif
  12708. #if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
  12709. /* Amalgamated: #include "mg_task.h" */
  12710. #include <oslib/osi.h>
  12711. enum mg_q_msg_type {
  12712. MG_Q_MSG_CB,
  12713. };
  12714. struct mg_q_msg {
  12715. enum mg_q_msg_type type;
  12716. void (*cb)(struct mg_mgr *mgr, void *arg);
  12717. void *arg;
  12718. };
  12719. static OsiMsgQ_t s_mg_q;
  12720. static void mg_task(void *arg);
  12721. bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
  12722. if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
  12723. return false;
  12724. }
  12725. if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
  12726. (void *) mg_init, priority, NULL) != OSI_OK) {
  12727. return false;
  12728. }
  12729. return true;
  12730. }
  12731. static void mg_task(void *arg) {
  12732. struct mg_mgr mgr;
  12733. mg_init_cb mg_init = (mg_init_cb) arg;
  12734. mg_mgr_init(&mgr, NULL);
  12735. mg_init(&mgr);
  12736. while (1) {
  12737. struct mg_q_msg msg;
  12738. mg_mgr_poll(&mgr, 1);
  12739. if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
  12740. switch (msg.type) {
  12741. case MG_Q_MSG_CB: {
  12742. msg.cb(&mgr, msg.arg);
  12743. }
  12744. }
  12745. }
  12746. }
  12747. void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
  12748. struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
  12749. osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
  12750. }
  12751. #endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
  12752. */
  12753. #ifdef MG_MODULE_LINES
  12754. #line 1 "common/platforms/simplelink/sl_net_if.h"
  12755. #endif
  12756. /*
  12757. * Copyright (c) 2014-2018 Cesanta Software Limited
  12758. * All rights reserved
  12759. *
  12760. * Licensed under the Apache License, Version 2.0 (the ""License"");
  12761. * you may not use this file except in compliance with the License.
  12762. * You may obtain a copy of the License at
  12763. *
  12764. * http://www.apache.org/licenses/LICENSE-2.0
  12765. *
  12766. * Unless required by applicable law or agreed to in writing, software
  12767. * distributed under the License is distributed on an ""AS IS"" BASIS,
  12768. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12769. * See the License for the specific language governing permissions and
  12770. * limitations under the License.
  12771. */
  12772. #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
  12773. #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
  12774. /* Amalgamated: #include "mongoose/src/net_if.h" */
  12775. #ifdef __cplusplus
  12776. extern "C" {
  12777. #endif /* __cplusplus */
  12778. #ifndef MG_ENABLE_NET_IF_SIMPLELINK
  12779. #define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
  12780. #endif
  12781. extern const struct mg_iface_vtable mg_simplelink_iface_vtable;
  12782. #ifdef __cplusplus
  12783. }
  12784. #endif /* __cplusplus */
  12785. #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
  12786. #ifdef MG_MODULE_LINES
  12787. #line 1 "common/platforms/simplelink/sl_net_if.c"
  12788. #endif
  12789. /*
  12790. * Copyright (c) 2014-2018 Cesanta Software Limited
  12791. * All rights reserved
  12792. *
  12793. * Licensed under the Apache License, Version 2.0 (the ""License"");
  12794. * you may not use this file except in compliance with the License.
  12795. * You may obtain a copy of the License at
  12796. *
  12797. * http://www.apache.org/licenses/LICENSE-2.0
  12798. *
  12799. * Unless required by applicable law or agreed to in writing, software
  12800. * distributed under the License is distributed on an ""AS IS"" BASIS,
  12801. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12802. * See the License for the specific language governing permissions and
  12803. * limitations under the License.
  12804. */
  12805. /* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
  12806. #if MG_ENABLE_NET_IF_SIMPLELINK
  12807. /* Amalgamated: #include "mongoose/src/internal.h" */
  12808. /* Amalgamated: #include "mongoose/src/util.h" */
  12809. #define MG_TCP_RECV_BUFFER_SIZE 1024
  12810. #define MG_UDP_RECV_BUFFER_SIZE 1500
  12811. static sock_t mg_open_listening_socket(struct mg_connection *nc,
  12812. union socket_address *sa, int type,
  12813. int proto);
  12814. static void mg_set_non_blocking_mode(sock_t sock) {
  12815. SlSockNonblocking_t opt;
  12816. #if SL_MAJOR_VERSION_NUM < 2
  12817. opt.NonblockingEnabled = 1;
  12818. #else
  12819. opt.NonBlockingEnabled = 1;
  12820. #endif
  12821. sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
  12822. }
  12823. static int mg_is_error(int n) {
  12824. return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN);
  12825. }
  12826. static void mg_sl_if_connect_tcp(struct mg_connection *nc,
  12827. const union socket_address *sa) {
  12828. int proto = 0;
  12829. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
  12830. if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
  12831. #endif
  12832. sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
  12833. if (sock < 0) {
  12834. nc->err = sock;
  12835. goto out;
  12836. }
  12837. mg_sock_set(nc, sock);
  12838. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
  12839. nc->err = sl_set_ssl_opts(sock, nc);
  12840. if (nc->err != 0) goto out;
  12841. #endif
  12842. nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
  12843. out:
  12844. DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
  12845. ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
  12846. }
  12847. static void mg_sl_if_connect_udp(struct mg_connection *nc) {
  12848. sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
  12849. if (sock < 0) {
  12850. nc->err = sock;
  12851. return;
  12852. }
  12853. mg_sock_set(nc, sock);
  12854. nc->err = 0;
  12855. }
  12856. static int mg_sl_if_listen_tcp(struct mg_connection *nc,
  12857. union socket_address *sa) {
  12858. int proto = 0;
  12859. if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
  12860. sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto);
  12861. if (sock < 0) return sock;
  12862. mg_sock_set(nc, sock);
  12863. return 0;
  12864. }
  12865. static int mg_sl_if_listen_udp(struct mg_connection *nc,
  12866. union socket_address *sa) {
  12867. sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0);
  12868. if (sock == INVALID_SOCKET) return (errno ? errno : 1);
  12869. mg_sock_set(nc, sock);
  12870. return 0;
  12871. }
  12872. static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf,
  12873. size_t len) {
  12874. int n = (int) sl_Send(nc->sock, buf, len, 0);
  12875. if (n < 0 && !mg_is_error(n)) n = 0;
  12876. return n;
  12877. }
  12878. static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf,
  12879. size_t len) {
  12880. int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
  12881. if (n < 0 && !mg_is_error(n)) n = 0;
  12882. return n;
  12883. }
  12884. static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) {
  12885. int n = sl_Recv(nc->sock, buf, len, 0);
  12886. if (n == 0) {
  12887. /* Orderly shutdown of the socket, try flushing output. */
  12888. nc->flags |= MG_F_SEND_AND_CLOSE;
  12889. } else if (n < 0 && !mg_is_error(n)) {
  12890. n = 0;
  12891. }
  12892. return n;
  12893. }
  12894. static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
  12895. union socket_address *sa, size_t *sa_len) {
  12896. SlSocklen_t sa_len_t = *sa_len;
  12897. int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
  12898. (SlSockAddr_t *) sa, &sa_len_t);
  12899. *sa_len = sa_len_t;
  12900. if (n < 0 && !mg_is_error(n)) n = 0;
  12901. return n;
  12902. }
  12903. static int mg_sl_if_create_conn(struct mg_connection *nc) {
  12904. (void) nc;
  12905. return 1;
  12906. }
  12907. void mg_sl_if_destroy_conn(struct mg_connection *nc) {
  12908. if (nc->sock == INVALID_SOCKET) return;
  12909. /* For UDP, only close outgoing sockets or listeners. */
  12910. if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
  12911. sl_Close(nc->sock);
  12912. }
  12913. nc->sock = INVALID_SOCKET;
  12914. }
  12915. static int mg_accept_conn(struct mg_connection *lc) {
  12916. struct mg_connection *nc;
  12917. union socket_address sa;
  12918. socklen_t sa_len = sizeof(sa);
  12919. sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
  12920. if (sock < 0) {
  12921. DBG(("%p: failed to accept: %d", lc, sock));
  12922. return 0;
  12923. }
  12924. nc = mg_if_accept_new_conn(lc);
  12925. if (nc == NULL) {
  12926. sl_Close(sock);
  12927. return 0;
  12928. }
  12929. DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
  12930. ntohs(sa.sin.sin_port)));
  12931. mg_sock_set(nc, sock);
  12932. mg_if_accept_tcp_cb(nc, &sa, sa_len);
  12933. return 1;
  12934. }
  12935. /* 'sa' must be an initialized address to bind to */
  12936. static sock_t mg_open_listening_socket(struct mg_connection *nc,
  12937. union socket_address *sa, int type,
  12938. int proto) {
  12939. int r;
  12940. socklen_t sa_len =
  12941. (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
  12942. sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
  12943. if (sock < 0) return sock;
  12944. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
  12945. if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean;
  12946. #endif
  12947. if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean;
  12948. if (type != SOCK_DGRAM) {
  12949. if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean;
  12950. }
  12951. mg_set_non_blocking_mode(sock);
  12952. clean:
  12953. if (r < 0) {
  12954. sl_Close(sock);
  12955. sock = r;
  12956. }
  12957. return sock;
  12958. }
  12959. #define _MG_F_FD_CAN_READ 1
  12960. #define _MG_F_FD_CAN_WRITE 1 << 1
  12961. #define _MG_F_FD_ERROR 1 << 2
  12962. void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
  12963. DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
  12964. fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  12965. if (!mg_if_poll(nc, now)) return;
  12966. if (nc->flags & MG_F_CONNECTING) {
  12967. if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) {
  12968. mg_if_connect_cb(nc, nc->err);
  12969. } else {
  12970. /* In SimpleLink, to get status of non-blocking connect() we need to wait
  12971. * until socket is writable and repeat the call to sl_Connect again,
  12972. * which will now return the real status. */
  12973. if (fd_flags & _MG_F_FD_CAN_WRITE) {
  12974. nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
  12975. DBG(("%p conn res=%d", nc, nc->err));
  12976. if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY ||
  12977. /* TODO(rojer): Provide API to set the date for verification. */
  12978. nc->err == SL_ERROR_BSD_ESECDATEERROR
  12979. #if SL_MAJOR_VERSION_NUM >= 2
  12980. /* Per SWRU455, this error does not mean verification failed,
  12981. * it only means that the cert used is not present in the trusted
  12982. * root CA catalog. Which is perfectly fine. */
  12983. ||
  12984. nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA
  12985. #endif
  12986. ) {
  12987. nc->err = 0;
  12988. }
  12989. mg_if_connect_cb(nc, nc->err);
  12990. }
  12991. }
  12992. /* Ignore read/write in further processing, we've handled it. */
  12993. fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
  12994. }
  12995. if (fd_flags & _MG_F_FD_CAN_READ) {
  12996. if (nc->flags & MG_F_UDP) {
  12997. mg_if_can_recv_cb(nc);
  12998. } else {
  12999. if (nc->flags & MG_F_LISTENING) {
  13000. mg_accept_conn(nc);
  13001. } else {
  13002. mg_if_can_recv_cb(nc);
  13003. }
  13004. }
  13005. }
  13006. if (fd_flags & _MG_F_FD_CAN_WRITE) {
  13007. mg_if_can_send_cb(nc);
  13008. }
  13009. DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
  13010. (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
  13011. }
  13012. /* Associate a socket to a connection. */
  13013. void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
  13014. mg_set_non_blocking_mode(sock);
  13015. nc->sock = sock;
  13016. DBG(("%p %d", nc, sock));
  13017. }
  13018. void mg_sl_if_init(struct mg_iface *iface) {
  13019. (void) iface;
  13020. DBG(("%p using sl_Select()", iface->mgr));
  13021. }
  13022. void mg_sl_if_free(struct mg_iface *iface) {
  13023. (void) iface;
  13024. }
  13025. void mg_sl_if_add_conn(struct mg_connection *nc) {
  13026. (void) nc;
  13027. }
  13028. void mg_sl_if_remove_conn(struct mg_connection *nc) {
  13029. (void) nc;
  13030. }
  13031. time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
  13032. struct mg_mgr *mgr = iface->mgr;
  13033. double now = mg_time();
  13034. double min_timer;
  13035. struct mg_connection *nc, *tmp;
  13036. struct SlTimeval_t tv;
  13037. SlFdSet_t read_set, write_set, err_set;
  13038. sock_t max_fd = INVALID_SOCKET;
  13039. int num_fds, num_ev = 0, num_timers = 0;
  13040. SL_SOCKET_FD_ZERO(&read_set);
  13041. SL_SOCKET_FD_ZERO(&write_set);
  13042. SL_SOCKET_FD_ZERO(&err_set);
  13043. /*
  13044. * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
  13045. * e.g. timer-only "connections".
  13046. */
  13047. min_timer = 0;
  13048. for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
  13049. tmp = nc->next;
  13050. if (nc->sock != INVALID_SOCKET) {
  13051. num_fds++;
  13052. if (!(nc->flags & MG_F_WANT_WRITE) &&
  13053. nc->recv_mbuf.len < nc->recv_mbuf_limit &&
  13054. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
  13055. SL_SOCKET_FD_SET(nc->sock, &read_set);
  13056. if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
  13057. }
  13058. if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
  13059. (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
  13060. SL_SOCKET_FD_SET(nc->sock, &write_set);
  13061. SL_SOCKET_FD_SET(nc->sock, &err_set);
  13062. if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
  13063. }
  13064. }
  13065. if (nc->ev_timer_time > 0) {
  13066. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  13067. min_timer = nc->ev_timer_time;
  13068. }
  13069. num_timers++;
  13070. }
  13071. }
  13072. /*
  13073. * If there is a timer to be fired earlier than the requested timeout,
  13074. * adjust the timeout.
  13075. */
  13076. if (num_timers > 0) {
  13077. double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
  13078. if (timer_timeout_ms < timeout_ms) {
  13079. timeout_ms = timer_timeout_ms;
  13080. }
  13081. }
  13082. if (timeout_ms < 0) timeout_ms = 0;
  13083. tv.tv_sec = timeout_ms / 1000;
  13084. tv.tv_usec = (timeout_ms % 1000) * 1000;
  13085. if (num_fds > 0) {
  13086. num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
  13087. }
  13088. now = mg_time();
  13089. DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
  13090. num_fds, timeout_ms));
  13091. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  13092. int fd_flags = 0;
  13093. if (nc->sock != INVALID_SOCKET) {
  13094. if (num_ev > 0) {
  13095. fd_flags =
  13096. (SL_SOCKET_FD_ISSET(nc->sock, &read_set) &&
  13097. (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
  13098. ? _MG_F_FD_CAN_READ
  13099. : 0) |
  13100. (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE
  13101. : 0) |
  13102. (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
  13103. }
  13104. /* SimpleLink does not report UDP sockets as writable. */
  13105. if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
  13106. fd_flags |= _MG_F_FD_CAN_WRITE;
  13107. }
  13108. }
  13109. tmp = nc->next;
  13110. mg_mgr_handle_conn(nc, fd_flags, now);
  13111. }
  13112. return now;
  13113. }
  13114. void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
  13115. union socket_address *sa) {
  13116. /* SimpleLink does not provide a way to get socket's peer address after
  13117. * accept or connect. Address should have been preserved in the connection,
  13118. * so we do our best here by using it. */
  13119. if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
  13120. }
  13121. void sl_restart_cb(struct mg_mgr *mgr) {
  13122. /*
  13123. * SimpleLink has been restarted, meaning all sockets have been invalidated.
  13124. * We try our best - we'll restart the listeners, but for outgoing
  13125. * connections we have no option but to terminate.
  13126. */
  13127. struct mg_connection *nc;
  13128. for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
  13129. if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
  13130. if (nc->flags & MG_F_LISTENING) {
  13131. DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
  13132. ntohs(nc->sa.sin.sin_port)));
  13133. int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
  13134. : mg_sl_if_listen_tcp(nc, &nc->sa));
  13135. if (res == 0) continue;
  13136. /* Well, we tried and failed. Fall through to closing. */
  13137. }
  13138. nc->sock = INVALID_SOCKET;
  13139. DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
  13140. ntohs(nc->sa.sin.sin_port)));
  13141. /* TODO(rojer): Outgoing UDP? */
  13142. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  13143. }
  13144. }
  13145. /* clang-format off */
  13146. #define MG_SL_IFACE_VTABLE \
  13147. { \
  13148. mg_sl_if_init, \
  13149. mg_sl_if_free, \
  13150. mg_sl_if_add_conn, \
  13151. mg_sl_if_remove_conn, \
  13152. mg_sl_if_poll, \
  13153. mg_sl_if_listen_tcp, \
  13154. mg_sl_if_listen_udp, \
  13155. mg_sl_if_connect_tcp, \
  13156. mg_sl_if_connect_udp, \
  13157. mg_sl_if_tcp_send, \
  13158. mg_sl_if_udp_send, \
  13159. mg_sl_if_tcp_recv, \
  13160. mg_sl_if_udp_recv, \
  13161. mg_sl_if_create_conn, \
  13162. mg_sl_if_destroy_conn, \
  13163. mg_sl_if_sock_set, \
  13164. mg_sl_if_get_conn_addr, \
  13165. }
  13166. /* clang-format on */
  13167. const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
  13168. #if MG_NET_IF == MG_NET_IF_SIMPLELINK
  13169. const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
  13170. #endif
  13171. #endif /* MG_ENABLE_NET_IF_SIMPLELINK */
  13172. #ifdef MG_MODULE_LINES
  13173. #line 1 "common/platforms/simplelink/sl_ssl_if.c"
  13174. #endif
  13175. /*
  13176. * Copyright (c) 2014-2018 Cesanta Software Limited
  13177. * All rights reserved
  13178. *
  13179. * Licensed under the Apache License, Version 2.0 (the ""License"");
  13180. * you may not use this file except in compliance with the License.
  13181. * You may obtain a copy of the License at
  13182. *
  13183. * http://www.apache.org/licenses/LICENSE-2.0
  13184. *
  13185. * Unless required by applicable law or agreed to in writing, software
  13186. * distributed under the License is distributed on an ""AS IS"" BASIS,
  13187. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13188. * See the License for the specific language governing permissions and
  13189. * limitations under the License.
  13190. */
  13191. #if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
  13192. /* Amalgamated: #include "common/mg_mem.h" */
  13193. #ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
  13194. #define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:"
  13195. #endif
  13196. #define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \
  13197. (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1)
  13198. struct mg_ssl_if_ctx {
  13199. char *ssl_cert;
  13200. char *ssl_key;
  13201. char *ssl_ca_cert;
  13202. char *ssl_server_name;
  13203. };
  13204. void mg_ssl_if_init() {
  13205. }
  13206. enum mg_ssl_if_result mg_ssl_if_conn_init(
  13207. struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
  13208. const char **err_msg) {
  13209. struct mg_ssl_if_ctx *ctx =
  13210. (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
  13211. if (ctx == NULL) {
  13212. MG_SET_PTRPTR(err_msg, "Out of memory");
  13213. return MG_SSL_ERROR;
  13214. }
  13215. nc->ssl_if_data = ctx;
  13216. if (params->cert != NULL || params->key != NULL) {
  13217. if (params->cert != NULL && params->key != NULL) {
  13218. ctx->ssl_cert = strdup(params->cert);
  13219. ctx->ssl_key = strdup(params->key);
  13220. } else {
  13221. MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
  13222. return MG_SSL_ERROR;
  13223. }
  13224. }
  13225. if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
  13226. ctx->ssl_ca_cert = strdup(params->ca_cert);
  13227. }
  13228. /* TODO(rojer): cipher_suites. */
  13229. if (params->server_name != NULL) {
  13230. ctx->ssl_server_name = strdup(params->server_name);
  13231. }
  13232. return MG_SSL_OK;
  13233. }
  13234. enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
  13235. struct mg_connection *lc) {
  13236. /* SimpleLink does everything for us, nothing for us to do. */
  13237. (void) nc;
  13238. (void) lc;
  13239. return MG_SSL_OK;
  13240. }
  13241. enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
  13242. /* SimpleLink has already performed the handshake, nothing to do. */
  13243. return MG_SSL_OK;
  13244. }
  13245. int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
  13246. /* SimpelLink handles TLS, so this is just a pass-through. */
  13247. int n = nc->iface->vtable->tcp_recv(nc, buf, len);
  13248. if (n == 0) nc->flags |= MG_F_WANT_READ;
  13249. return n;
  13250. }
  13251. int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
  13252. /* SimpelLink handles TLS, so this is just a pass-through. */
  13253. return nc->iface->vtable->tcp_send(nc, buf, len);
  13254. }
  13255. void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
  13256. /* Nothing to do */
  13257. (void) nc;
  13258. }
  13259. void mg_ssl_if_conn_free(struct mg_connection *nc) {
  13260. struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  13261. if (ctx == NULL) return;
  13262. nc->ssl_if_data = NULL;
  13263. MG_FREE(ctx->ssl_cert);
  13264. MG_FREE(ctx->ssl_key);
  13265. MG_FREE(ctx->ssl_ca_cert);
  13266. MG_FREE(ctx->ssl_server_name);
  13267. memset(ctx, 0, sizeof(*ctx));
  13268. MG_FREE(ctx);
  13269. }
  13270. bool pem_to_der(const char *pem_file, const char *der_file) {
  13271. bool ret = false;
  13272. FILE *pf = NULL, *df = NULL;
  13273. bool writing = false;
  13274. pf = fopen(pem_file, "r");
  13275. if (pf == NULL) goto clean;
  13276. remove(der_file);
  13277. fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048);
  13278. df = fopen(der_file, "w");
  13279. fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN);
  13280. if (df == NULL) goto clean;
  13281. while (1) {
  13282. char pem_buf[70];
  13283. char der_buf[48];
  13284. if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
  13285. if (writing) {
  13286. if (strstr(pem_buf, "-----END ") != NULL) {
  13287. ret = true;
  13288. break;
  13289. }
  13290. int l = 0;
  13291. while (!isspace((unsigned int) pem_buf[l])) l++;
  13292. int der_len = 0;
  13293. cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
  13294. der_buf, &der_len);
  13295. if (der_len <= 0) break;
  13296. if (fwrite(der_buf, 1, der_len, df) != der_len) break;
  13297. } else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
  13298. writing = true;
  13299. }
  13300. }
  13301. clean:
  13302. if (pf != NULL) fclose(pf);
  13303. if (df != NULL) {
  13304. fclose(df);
  13305. if (!ret) remove(der_file);
  13306. }
  13307. return ret;
  13308. }
  13309. #if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
  13310. /* If the file's extension is .pem, convert it to DER format and put on SLFS. */
  13311. static char *sl_pem2der(const char *pem_file) {
  13312. const char *pem_ext = strstr(pem_file, ".pem");
  13313. if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
  13314. return strdup(pem_file);
  13315. }
  13316. char *der_file = NULL;
  13317. /* DER file must be located on SLFS, add prefix. */
  13318. int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der",
  13319. (int) (pem_ext - pem_file), pem_file);
  13320. if (der_file == NULL) return NULL;
  13321. bool result = false;
  13322. cs_stat_t st;
  13323. if (mg_stat(der_file, &st) != 0) {
  13324. result = pem_to_der(pem_file, der_file);
  13325. LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
  13326. } else {
  13327. /* File exists, assume it's already been converted. */
  13328. result = true;
  13329. }
  13330. if (result) {
  13331. /* Strip the SL: prefix we added since NWP does not expect it. */
  13332. memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
  13333. l - 2 /* including \0 */);
  13334. } else {
  13335. MG_FREE(der_file);
  13336. der_file = NULL;
  13337. }
  13338. return der_file;
  13339. }
  13340. #else
  13341. static char *sl_pem2der(const char *pem_file) {
  13342. return strdup(pem_file);
  13343. }
  13344. #endif
  13345. int sl_set_ssl_opts(int sock, struct mg_connection *nc) {
  13346. int err;
  13347. const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
  13348. DBG(("%p ssl ctx: %p", nc, ctx));
  13349. if (ctx == NULL) return 0;
  13350. DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
  13351. (ctx->ssl_key ? ctx->ssl_cert : "-"),
  13352. (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
  13353. (ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
  13354. if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
  13355. char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL;
  13356. if (ssl_cert != NULL) {
  13357. err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
  13358. SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
  13359. strlen(ssl_cert));
  13360. MG_FREE(ssl_cert);
  13361. LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
  13362. ssl_key = sl_pem2der(ctx->ssl_key);
  13363. if (ssl_key != NULL) {
  13364. err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
  13365. SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
  13366. strlen(ssl_key));
  13367. MG_FREE(ssl_key);
  13368. LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
  13369. } else {
  13370. err = -1;
  13371. }
  13372. } else {
  13373. err = -1;
  13374. }
  13375. if (err != 0) return err;
  13376. }
  13377. if (ctx->ssl_ca_cert != NULL) {
  13378. if (ctx->ssl_ca_cert[0] != '\0') {
  13379. char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
  13380. if (ssl_ca_cert != NULL) {
  13381. err =
  13382. sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
  13383. ssl_ca_cert, strlen(ssl_ca_cert));
  13384. LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
  13385. } else {
  13386. err = -1;
  13387. }
  13388. MG_FREE(ssl_ca_cert);
  13389. if (err != 0) return err;
  13390. }
  13391. }
  13392. if (ctx->ssl_server_name != NULL) {
  13393. err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
  13394. SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
  13395. ctx->ssl_server_name, strlen(ctx->ssl_server_name));
  13396. DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
  13397. /* Domain name verificationw as added in a NWP service pack, older
  13398. * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do
  13399. * about it,
  13400. * so we ignore the error. */
  13401. if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err;
  13402. }
  13403. return 0;
  13404. }
  13405. #endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
  13406. #ifdef MG_MODULE_LINES
  13407. #line 1 "common/platforms/lwip/mg_lwip_net_if.h"
  13408. #endif
  13409. /*
  13410. * Copyright (c) 2014-2018 Cesanta Software Limited
  13411. * All rights reserved
  13412. *
  13413. * Licensed under the Apache License, Version 2.0 (the ""License"");
  13414. * you may not use this file except in compliance with the License.
  13415. * You may obtain a copy of the License at
  13416. *
  13417. * http://www.apache.org/licenses/LICENSE-2.0
  13418. *
  13419. * Unless required by applicable law or agreed to in writing, software
  13420. * distributed under the License is distributed on an ""AS IS"" BASIS,
  13421. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13422. * See the License for the specific language governing permissions and
  13423. * limitations under the License.
  13424. */
  13425. #ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
  13426. #define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
  13427. #ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  13428. #define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  13429. #endif
  13430. #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  13431. #include <stdint.h>
  13432. extern const struct mg_iface_vtable mg_lwip_iface_vtable;
  13433. struct mg_lwip_conn_state {
  13434. struct mg_connection *nc;
  13435. struct mg_connection *lc;
  13436. union {
  13437. struct tcp_pcb *tcp;
  13438. struct udp_pcb *udp;
  13439. } pcb;
  13440. err_t err;
  13441. size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
  13442. struct pbuf *rx_chain; /* Chain of incoming data segments. */
  13443. size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
  13444. /* Last SSL write size, for retries. */
  13445. int last_ssl_write_size;
  13446. /* Whether MG_SIG_RECV is already pending for this connection */
  13447. int recv_pending;
  13448. /* Whether the connection is about to close, just `rx_chain` needs to drain */
  13449. int draining_rx_chain;
  13450. };
  13451. enum mg_sig_type {
  13452. MG_SIG_CONNECT_RESULT = 1,
  13453. MG_SIG_RECV = 2,
  13454. MG_SIG_CLOSE_CONN = 3,
  13455. MG_SIG_TOMBSTONE = 4,
  13456. MG_SIG_ACCEPT = 5,
  13457. };
  13458. void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
  13459. /* To be implemented by the platform. */
  13460. void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
  13461. #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
  13462. #endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
  13463. #ifdef MG_MODULE_LINES
  13464. #line 1 "common/platforms/lwip/mg_lwip_net_if.c"
  13465. #endif
  13466. /*
  13467. * Copyright (c) 2014-2018 Cesanta Software Limited
  13468. * All rights reserved
  13469. *
  13470. * Licensed under the Apache License, Version 2.0 (the ""License"");
  13471. * you may not use this file except in compliance with the License.
  13472. * You may obtain a copy of the License at
  13473. *
  13474. * http://www.apache.org/licenses/LICENSE-2.0
  13475. *
  13476. * Unless required by applicable law or agreed to in writing, software
  13477. * distributed under the License is distributed on an ""AS IS"" BASIS,
  13478. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13479. * See the License for the specific language governing permissions and
  13480. * limitations under the License.
  13481. */
  13482. #if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
  13483. /* Amalgamated: #include "common/mg_mem.h" */
  13484. #include <lwip/init.h>
  13485. #include <lwip/pbuf.h>
  13486. #include <lwip/tcp.h>
  13487. #include <lwip/tcpip.h>
  13488. #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
  13489. #include <lwip/priv/tcp_priv.h> /* For tcp_seg */
  13490. #include <lwip/priv/tcpip_priv.h> /* For tcpip_api_call */
  13491. #else
  13492. #include <lwip/tcp_impl.h>
  13493. #endif
  13494. #include <lwip/udp.h>
  13495. /* Amalgamated: #include "common/cs_dbg.h" */
  13496. /*
  13497. * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip,
  13498. * even older have nothing.
  13499. */
  13500. #ifndef ip_2_ip4
  13501. #ifdef ipX_2_ip
  13502. #define ip_2_ip4(addr) ipX_2_ip(addr)
  13503. #else
  13504. #define ip_2_ip4(addr) (addr)
  13505. #endif
  13506. #endif
  13507. /*
  13508. * Depending on whether Mongoose is compiled with ipv6 support, use right
  13509. * lwip functions
  13510. */
  13511. #if MG_ENABLE_IPV6
  13512. #define TCP_NEW tcp_new_ip6
  13513. #define TCP_BIND tcp_bind_ip6
  13514. #define UDP_BIND udp_bind_ip6
  13515. #define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
  13516. #define SET_ADDR(dst, src) \
  13517. memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
  13518. sizeof((dst)->sin6.sin6_addr.s6_addr))
  13519. #else
  13520. #define TCP_NEW tcp_new
  13521. #define TCP_BIND tcp_bind
  13522. #define UDP_BIND udp_bind
  13523. #define IPADDR_NTOA ipaddr_ntoa
  13524. #define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr
  13525. #endif
  13526. #if !NO_SYS
  13527. #if LWIP_TCPIP_CORE_LOCKING
  13528. /* With locking tcpip_api_call is just a function call wrapped in lock/unlock,
  13529. * so we can get away with just casting. */
  13530. void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
  13531. tcpip_api_call((tcpip_api_call_fn) fn, (struct tcpip_api_call_data *) arg);
  13532. }
  13533. #else
  13534. static sys_sem_t s_tcpip_call_lock_sem = NULL;
  13535. static sys_sem_t s_tcpip_call_sync_sem = NULL;
  13536. struct mg_lwip_netif_tcpip_call_ctx {
  13537. void (*fn)(void *);
  13538. void *arg;
  13539. };
  13540. static void xxx_tcpip(void *arg) {
  13541. struct mg_lwip_netif_tcpip_call_ctx *ctx =
  13542. (struct mg_lwip_netif_tcpip_call_ctx *) arg;
  13543. ctx->fn(ctx->arg);
  13544. sys_sem_signal(&s_tcpip_call_sync_sem);
  13545. }
  13546. void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
  13547. struct mg_lwip_netif_tcpip_call_ctx ctx = {.fn = fn, .arg = arg};
  13548. sys_arch_sem_wait(&s_tcpip_call_lock_sem, 0);
  13549. tcpip_send_msg_wait_sem(xxx_tcpip, &ctx, &s_tcpip_call_sync_sem);
  13550. sys_sem_signal(&s_tcpip_call_lock_sem);
  13551. }
  13552. #endif
  13553. #else
  13554. #define mg_lwip_netif_run_on_tcpip(fn, arg) (fn)(arg)
  13555. #endif
  13556. void mg_lwip_if_init(struct mg_iface *iface);
  13557. void mg_lwip_if_free(struct mg_iface *iface);
  13558. void mg_lwip_if_add_conn(struct mg_connection *nc);
  13559. void mg_lwip_if_remove_conn(struct mg_connection *nc);
  13560. time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
  13561. // If compiling for Mongoose OS.
  13562. #ifdef MGOS
  13563. extern void mgos_lock();
  13564. extern void mgos_unlock();
  13565. #else
  13566. #define mgos_lock()
  13567. #define mgos_unlock()
  13568. #endif
  13569. static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
  13570. #if LWIP_TCP_KEEPALIVE
  13571. void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
  13572. int interval, int count) {
  13573. if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
  13574. return;
  13575. }
  13576. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13577. struct tcp_pcb *tpcb = cs->pcb.tcp;
  13578. if (idle > 0 && interval > 0 && count > 0) {
  13579. tpcb->keep_idle = idle * 1000;
  13580. tpcb->keep_intvl = interval * 1000;
  13581. tpcb->keep_cnt = count;
  13582. tpcb->so_options |= SOF_KEEPALIVE;
  13583. } else {
  13584. tpcb->so_options &= ~SOF_KEEPALIVE;
  13585. }
  13586. }
  13587. #elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
  13588. #warning LWIP TCP keepalive is disabled. Please consider enabling it.
  13589. #endif /* LWIP_TCP_KEEPALIVE */
  13590. static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
  13591. struct mg_connection *nc = (struct mg_connection *) arg;
  13592. DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
  13593. tpcb->remote_port, err));
  13594. if (nc == NULL) {
  13595. tcp_abort(tpcb);
  13596. return ERR_ARG;
  13597. }
  13598. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13599. cs->err = err;
  13600. #if LWIP_TCP_KEEPALIVE
  13601. if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
  13602. #endif
  13603. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  13604. return ERR_OK;
  13605. }
  13606. static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
  13607. struct mg_connection *nc = (struct mg_connection *) arg;
  13608. DBG(("%p conn error %d", nc, err));
  13609. if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return;
  13610. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13611. cs->pcb.tcp = NULL; /* Has already been deallocated */
  13612. if (nc->flags & MG_F_CONNECTING) {
  13613. cs->err = err;
  13614. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  13615. } else {
  13616. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  13617. }
  13618. }
  13619. static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
  13620. struct pbuf *p, err_t err) {
  13621. struct mg_connection *nc = (struct mg_connection *) arg;
  13622. struct mg_lwip_conn_state *cs =
  13623. (nc ? (struct mg_lwip_conn_state *) nc->sock : NULL);
  13624. DBG(("%p %p %p %p %u %d", nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0),
  13625. err));
  13626. if (p == NULL) {
  13627. if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
  13628. if (cs->rx_chain != NULL) {
  13629. /*
  13630. * rx_chain still contains non-consumed data, don't close the
  13631. * connection
  13632. */
  13633. cs->draining_rx_chain = 1;
  13634. } else {
  13635. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  13636. }
  13637. } else {
  13638. /* Tombstoned connection, do nothing. */
  13639. }
  13640. return ERR_OK;
  13641. } else if (nc == NULL) {
  13642. tcp_abort(tpcb);
  13643. return ERR_ARG;
  13644. }
  13645. /*
  13646. * If we get a chain of more than one segment at once, we need to bump
  13647. * refcount on the subsequent bufs to make them independent.
  13648. */
  13649. if (p->next != NULL) {
  13650. struct pbuf *q = p->next;
  13651. for (; q != NULL; q = q->next) pbuf_ref(q);
  13652. }
  13653. mgos_lock();
  13654. if (cs->rx_chain == NULL) {
  13655. cs->rx_offset = 0;
  13656. } else if (pbuf_clen(cs->rx_chain) >= 4) {
  13657. /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
  13658. * will be completely blocked. We already have at least 4 in the chain,
  13659. * this one is the last, so we have to make a copy and release this one. */
  13660. struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
  13661. if (np != NULL) {
  13662. pbuf_copy(np, p);
  13663. pbuf_free(p);
  13664. p = np;
  13665. }
  13666. }
  13667. mg_lwip_recv_common(nc, p);
  13668. mgos_unlock();
  13669. (void) err;
  13670. return ERR_OK;
  13671. }
  13672. static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
  13673. u16_t num_sent) {
  13674. struct mg_connection *nc = (struct mg_connection *) arg;
  13675. DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked));
  13676. if (nc == NULL) return ERR_OK;
  13677. if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) &&
  13678. nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) {
  13679. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  13680. }
  13681. if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
  13682. mg_lwip_mgr_schedule_poll(nc->mgr);
  13683. }
  13684. (void) num_sent;
  13685. return ERR_OK;
  13686. }
  13687. struct mg_lwip_if_connect_tcp_ctx {
  13688. struct mg_connection *nc;
  13689. const union socket_address *sa;
  13690. };
  13691. static void mg_lwip_if_connect_tcp_tcpip(void *arg) {
  13692. struct mg_lwip_if_connect_tcp_ctx *ctx =
  13693. (struct mg_lwip_if_connect_tcp_ctx *) arg;
  13694. struct mg_connection *nc = ctx->nc;
  13695. const union socket_address *sa = ctx->sa;
  13696. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13697. struct tcp_pcb *tpcb = TCP_NEW();
  13698. cs->pcb.tcp = tpcb;
  13699. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  13700. u16_t port = ntohs(sa->sin.sin_port);
  13701. tcp_arg(tpcb, nc);
  13702. tcp_err(tpcb, mg_lwip_tcp_error_cb);
  13703. tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
  13704. tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
  13705. cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
  13706. DBG(("%p tcp_bind = %d", nc, cs->err));
  13707. if (cs->err != ERR_OK) {
  13708. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  13709. return;
  13710. }
  13711. cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
  13712. DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err));
  13713. if (cs->err != ERR_OK) {
  13714. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  13715. return;
  13716. }
  13717. }
  13718. void mg_lwip_if_connect_tcp(struct mg_connection *nc,
  13719. const union socket_address *sa) {
  13720. struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa};
  13721. mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_tcp_tcpip, &ctx);
  13722. }
  13723. /*
  13724. * Lwip included in the SDKs for nRF5x chips has different type for the
  13725. * callback of `udp_recv()`
  13726. */
  13727. #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
  13728. static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
  13729. const ip_addr_t *addr, u16_t port)
  13730. #else
  13731. static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
  13732. ip_addr_t *addr, u16_t port)
  13733. #endif
  13734. {
  13735. struct mg_connection *nc = (struct mg_connection *) arg;
  13736. DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
  13737. /* Put address in a separate pbuf and tack it onto the packet. */
  13738. struct pbuf *sap =
  13739. pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
  13740. if (sap == NULL) {
  13741. pbuf_free(p);
  13742. return;
  13743. }
  13744. union socket_address *sa = (union socket_address *) sap->payload;
  13745. #if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
  13746. sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr;
  13747. #else
  13748. sa->sin.sin_addr.s_addr = addr->addr;
  13749. #endif
  13750. sa->sin.sin_port = htons(port);
  13751. /* Logic in the recv handler requires that there be exactly one data pbuf. */
  13752. p = pbuf_coalesce(p, PBUF_RAW);
  13753. pbuf_chain(sap, p);
  13754. mgos_lock();
  13755. mg_lwip_recv_common(nc, sap);
  13756. mgos_unlock();
  13757. (void) pcb;
  13758. }
  13759. static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
  13760. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13761. if (cs->rx_chain == NULL) {
  13762. cs->rx_chain = p;
  13763. } else {
  13764. pbuf_chain(cs->rx_chain, p);
  13765. }
  13766. if (!cs->recv_pending) {
  13767. cs->recv_pending = 1;
  13768. mg_lwip_post_signal(MG_SIG_RECV, nc);
  13769. }
  13770. }
  13771. static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
  13772. union socket_address *sa, size_t *sa_len) {
  13773. /*
  13774. * For UDP, RX chain consists of interleaved address and packet bufs:
  13775. * Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
  13776. */
  13777. int res = 0;
  13778. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13779. if (nc->sock == INVALID_SOCKET) return -1;
  13780. mgos_lock();
  13781. if (cs->rx_chain != NULL) {
  13782. struct pbuf *ap = cs->rx_chain;
  13783. struct pbuf *dp = ap->next;
  13784. cs->rx_chain = pbuf_dechain(dp);
  13785. res = MIN(dp->len, len);
  13786. pbuf_copy_partial(dp, buf, res, 0);
  13787. pbuf_free(dp);
  13788. pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0);
  13789. pbuf_free(ap);
  13790. }
  13791. mgos_unlock();
  13792. return res;
  13793. }
  13794. static void mg_lwip_if_connect_udp_tcpip(void *arg) {
  13795. struct mg_connection *nc = (struct mg_connection *) arg;
  13796. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13797. struct udp_pcb *upcb = udp_new();
  13798. cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
  13799. DBG(("%p udp_bind %p = %d", nc, upcb, cs->err));
  13800. if (cs->err == ERR_OK) {
  13801. udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
  13802. cs->pcb.udp = upcb;
  13803. } else {
  13804. udp_remove(upcb);
  13805. }
  13806. mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
  13807. }
  13808. void mg_lwip_if_connect_udp(struct mg_connection *nc) {
  13809. mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_udp_tcpip, nc);
  13810. }
  13811. static void tcp_close_tcpip(void *arg) {
  13812. tcp_close((struct tcp_pcb *) arg);
  13813. }
  13814. void mg_lwip_handle_accept(struct mg_connection *nc) {
  13815. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13816. if (cs->pcb.tcp == NULL) return;
  13817. union socket_address sa;
  13818. struct tcp_pcb *tpcb = cs->pcb.tcp;
  13819. SET_ADDR(&sa, &tpcb->remote_ip);
  13820. sa.sin.sin_port = htons(tpcb->remote_port);
  13821. mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
  13822. }
  13823. static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
  13824. struct mg_connection *lc = (struct mg_connection *) arg, *nc;
  13825. struct mg_lwip_conn_state *lcs, *cs;
  13826. struct tcp_pcb_listen *lpcb;
  13827. LOG(LL_DEBUG,
  13828. ("%p conn %p from %s:%u", lc, newtpcb,
  13829. IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
  13830. if (lc == NULL) {
  13831. tcp_abort(newtpcb);
  13832. return ERR_ABRT;
  13833. }
  13834. lcs = (struct mg_lwip_conn_state *) lc->sock;
  13835. lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp;
  13836. #if TCP_LISTEN_BACKLOG
  13837. tcp_accepted(lpcb);
  13838. #endif
  13839. nc = mg_if_accept_new_conn(lc);
  13840. if (nc == NULL) {
  13841. tcp_abort(newtpcb);
  13842. return ERR_ABRT;
  13843. }
  13844. cs = (struct mg_lwip_conn_state *) nc->sock;
  13845. cs->lc = lc;
  13846. cs->pcb.tcp = newtpcb;
  13847. /* We need to set up callbacks before returning because data may start
  13848. * arriving immediately. */
  13849. tcp_arg(newtpcb, nc);
  13850. tcp_err(newtpcb, mg_lwip_tcp_error_cb);
  13851. tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
  13852. tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
  13853. #if LWIP_TCP_KEEPALIVE
  13854. mg_lwip_set_keepalive_params(nc, 60, 10, 6);
  13855. #endif
  13856. mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
  13857. (void) err;
  13858. (void) lpcb;
  13859. return ERR_OK;
  13860. }
  13861. struct mg_lwip_if_listen_ctx {
  13862. struct mg_connection *nc;
  13863. union socket_address *sa;
  13864. int ret;
  13865. };
  13866. static void mg_lwip_if_listen_tcp_tcpip(void *arg) {
  13867. struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
  13868. struct mg_connection *nc = ctx->nc;
  13869. union socket_address *sa = ctx->sa;
  13870. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13871. struct tcp_pcb *tpcb = TCP_NEW();
  13872. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  13873. u16_t port = ntohs(sa->sin.sin_port);
  13874. cs->err = TCP_BIND(tpcb, ip, port);
  13875. DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
  13876. if (cs->err != ERR_OK) {
  13877. tcp_close(tpcb);
  13878. ctx->ret = -1;
  13879. return;
  13880. }
  13881. tcp_arg(tpcb, nc);
  13882. tpcb = tcp_listen(tpcb);
  13883. cs->pcb.tcp = tpcb;
  13884. tcp_accept(tpcb, mg_lwip_accept_cb);
  13885. ctx->ret = 0;
  13886. }
  13887. int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  13888. struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
  13889. mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_tcp_tcpip, &ctx);
  13890. return ctx.ret;
  13891. }
  13892. static void mg_lwip_if_listen_udp_tcpip(void *arg) {
  13893. struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
  13894. struct mg_connection *nc = ctx->nc;
  13895. union socket_address *sa = ctx->sa;
  13896. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13897. struct udp_pcb *upcb = udp_new();
  13898. ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
  13899. u16_t port = ntohs(sa->sin.sin_port);
  13900. cs->err = UDP_BIND(upcb, ip, port);
  13901. DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
  13902. if (cs->err != ERR_OK) {
  13903. udp_remove(upcb);
  13904. ctx->ret = -1;
  13905. } else {
  13906. udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
  13907. cs->pcb.udp = upcb;
  13908. ctx->ret = 0;
  13909. }
  13910. }
  13911. int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  13912. struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
  13913. mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_udp_tcpip, &ctx);
  13914. return ctx.ret;
  13915. }
  13916. struct mg_lwip_tcp_write_ctx {
  13917. struct mg_connection *nc;
  13918. const void *data;
  13919. uint16_t len;
  13920. int ret;
  13921. };
  13922. static void tcp_output_tcpip(void *arg) {
  13923. tcp_output((struct tcp_pcb *) arg);
  13924. }
  13925. static void mg_lwip_tcp_write_tcpip(void *arg) {
  13926. struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg;
  13927. struct mg_connection *nc = ctx->nc;
  13928. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13929. struct tcp_pcb *tpcb = cs->pcb.tcp;
  13930. size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf));
  13931. size_t unsent, unacked;
  13932. if (len == 0) {
  13933. DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen,
  13934. tpcb->unsent, tpcb->unacked));
  13935. mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, tpcb);
  13936. ctx->ret = 0;
  13937. return;
  13938. }
  13939. unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
  13940. unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
  13941. /*
  13942. * On ESP8266 we only allow one TCP segment in flight at any given time.
  13943. * This may increase latency and reduce efficiency of tcp windowing,
  13944. * but memory is scarce and precious on that platform so we do this to
  13945. * reduce footprint.
  13946. */
  13947. #if CS_PLATFORM == CS_P_ESP8266
  13948. if (unacked > 0) {
  13949. ctx->ret = 0;
  13950. return;
  13951. }
  13952. len = MIN(len, (TCP_MSS - unsent));
  13953. #endif
  13954. cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY);
  13955. unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
  13956. unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
  13957. DBG(("%p tcp_write %u = %d, %u %u", tpcb, len, cs->err, unsent, unacked));
  13958. if (cs->err != ERR_OK) {
  13959. /*
  13960. * We ignore ERR_MEM because memory will be freed up when the data is sent
  13961. * and we'll retry.
  13962. */
  13963. ctx->ret = (cs->err == ERR_MEM ? 0 : -1);
  13964. return;
  13965. }
  13966. ctx->ret = len;
  13967. (void) unsent;
  13968. (void) unacked;
  13969. }
  13970. int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
  13971. struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len};
  13972. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13973. if (nc->sock == INVALID_SOCKET) return -1;
  13974. struct tcp_pcb *tpcb = cs->pcb.tcp;
  13975. if (tpcb == NULL) return -1;
  13976. if (tpcb->snd_buf <= 0) return 0;
  13977. mg_lwip_netif_run_on_tcpip(mg_lwip_tcp_write_tcpip, &ctx);
  13978. return ctx.ret;
  13979. }
  13980. struct udp_sendto_ctx {
  13981. struct udp_pcb *upcb;
  13982. struct pbuf *p;
  13983. ip_addr_t *ip;
  13984. uint16_t port;
  13985. int ret;
  13986. };
  13987. static void udp_sendto_tcpip(void *arg) {
  13988. struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg;
  13989. ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port);
  13990. }
  13991. static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data,
  13992. size_t len) {
  13993. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  13994. if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1;
  13995. struct udp_pcb *upcb = cs->pcb.udp;
  13996. struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
  13997. #if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6
  13998. ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0};
  13999. #else
  14000. ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr};
  14001. #endif
  14002. u16_t port = ntohs(nc->sa.sin.sin_port);
  14003. if (p == NULL) return 0;
  14004. memcpy(p->payload, data, len);
  14005. struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port};
  14006. mg_lwip_netif_run_on_tcpip(udp_sendto_tcpip, &ctx);
  14007. cs->err = ctx.ret;
  14008. pbuf_free(p);
  14009. return (cs->err == ERR_OK ? (int) len : -2);
  14010. }
  14011. static int mg_lwip_if_can_send(struct mg_connection *nc,
  14012. struct mg_lwip_conn_state *cs) {
  14013. int can_send = 0;
  14014. if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
  14015. /* We have stuff to send, but can we? */
  14016. if (nc->flags & MG_F_UDP) {
  14017. /* UDP is always ready for sending. */
  14018. can_send = (cs->pcb.udp != NULL);
  14019. } else {
  14020. can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
  14021. /* See comment above. */
  14022. #if CS_PLATFORM == CS_P_ESP8266
  14023. if (cs->pcb.tcp->unacked != NULL) can_send = 0;
  14024. #endif
  14025. }
  14026. }
  14027. return can_send;
  14028. }
  14029. struct tcp_recved_ctx {
  14030. struct tcp_pcb *tpcb;
  14031. size_t len;
  14032. };
  14033. void tcp_recved_tcpip(void *arg) {
  14034. struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg;
  14035. if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len);
  14036. }
  14037. static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf,
  14038. size_t len) {
  14039. int res = 0;
  14040. char *bufp = buf;
  14041. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  14042. if (nc->sock == INVALID_SOCKET) return -1;
  14043. mgos_lock();
  14044. while (cs->rx_chain != NULL && len > 0) {
  14045. struct pbuf *seg = cs->rx_chain;
  14046. size_t seg_len = (seg->len - cs->rx_offset);
  14047. size_t copy_len = MIN(len, seg_len);
  14048. pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset);
  14049. len -= copy_len;
  14050. res += copy_len;
  14051. bufp += copy_len;
  14052. cs->rx_offset += copy_len;
  14053. if (cs->rx_offset == cs->rx_chain->len) {
  14054. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  14055. pbuf_free(seg);
  14056. cs->rx_offset = 0;
  14057. }
  14058. }
  14059. mgos_unlock();
  14060. if (res > 0) {
  14061. struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res};
  14062. mg_lwip_netif_run_on_tcpip(tcp_recved_tcpip, &ctx);
  14063. }
  14064. return res;
  14065. }
  14066. int mg_lwip_if_create_conn(struct mg_connection *nc) {
  14067. struct mg_lwip_conn_state *cs =
  14068. (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
  14069. if (cs == NULL) return 0;
  14070. cs->nc = nc;
  14071. nc->sock = (intptr_t) cs;
  14072. return 1;
  14073. }
  14074. static void udp_remove_tcpip(void *arg) {
  14075. udp_remove((struct udp_pcb *) arg);
  14076. }
  14077. void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
  14078. if (nc->sock == INVALID_SOCKET) return;
  14079. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  14080. if (!(nc->flags & MG_F_UDP)) {
  14081. struct tcp_pcb *tpcb = cs->pcb.tcp;
  14082. if (tpcb != NULL) {
  14083. tcp_arg(tpcb, NULL);
  14084. DBG(("%p tcp_close %p", nc, tpcb));
  14085. tcp_arg(tpcb, NULL);
  14086. mg_lwip_netif_run_on_tcpip(tcp_close_tcpip, tpcb);
  14087. }
  14088. while (cs->rx_chain != NULL) {
  14089. struct pbuf *seg = cs->rx_chain;
  14090. cs->rx_chain = pbuf_dechain(cs->rx_chain);
  14091. pbuf_free(seg);
  14092. }
  14093. memset(cs, 0, sizeof(*cs));
  14094. MG_FREE(cs);
  14095. } else if (nc->listener == NULL) {
  14096. /* Only close outgoing UDP pcb or listeners. */
  14097. struct udp_pcb *upcb = cs->pcb.udp;
  14098. if (upcb != NULL) {
  14099. DBG(("%p udp_remove %p", nc, upcb));
  14100. mg_lwip_netif_run_on_tcpip(udp_remove_tcpip, upcb);
  14101. }
  14102. memset(cs, 0, sizeof(*cs));
  14103. MG_FREE(cs);
  14104. }
  14105. nc->sock = INVALID_SOCKET;
  14106. }
  14107. void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
  14108. union socket_address *sa) {
  14109. memset(sa, 0, sizeof(*sa));
  14110. if (nc == NULL || nc->sock == INVALID_SOCKET) return;
  14111. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  14112. if (nc->flags & MG_F_UDP) {
  14113. struct udp_pcb *upcb = cs->pcb.udp;
  14114. if (remote) {
  14115. memcpy(sa, &nc->sa, sizeof(*sa));
  14116. } else if (upcb != NULL) {
  14117. sa->sin.sin_port = htons(upcb->local_port);
  14118. SET_ADDR(sa, &upcb->local_ip);
  14119. }
  14120. } else {
  14121. struct tcp_pcb *tpcb = cs->pcb.tcp;
  14122. if (remote) {
  14123. memcpy(sa, &nc->sa, sizeof(*sa));
  14124. } else if (tpcb != NULL) {
  14125. sa->sin.sin_port = htons(tpcb->local_port);
  14126. SET_ADDR(sa, &tpcb->local_ip);
  14127. }
  14128. }
  14129. }
  14130. void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
  14131. nc->sock = sock;
  14132. }
  14133. /* clang-format off */
  14134. #define MG_LWIP_IFACE_VTABLE \
  14135. { \
  14136. mg_lwip_if_init, \
  14137. mg_lwip_if_free, \
  14138. mg_lwip_if_add_conn, \
  14139. mg_lwip_if_remove_conn, \
  14140. mg_lwip_if_poll, \
  14141. mg_lwip_if_listen_tcp, \
  14142. mg_lwip_if_listen_udp, \
  14143. mg_lwip_if_connect_tcp, \
  14144. mg_lwip_if_connect_udp, \
  14145. mg_lwip_if_tcp_send, \
  14146. mg_lwip_if_udp_send, \
  14147. mg_lwip_if_tcp_recv, \
  14148. mg_lwip_if_udp_recv, \
  14149. mg_lwip_if_create_conn, \
  14150. mg_lwip_if_destroy_conn, \
  14151. mg_lwip_if_sock_set, \
  14152. mg_lwip_if_get_conn_addr, \
  14153. }
  14154. /* clang-format on */
  14155. const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
  14156. #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  14157. const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
  14158. #endif
  14159. #endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
  14160. #ifdef MG_MODULE_LINES
  14161. #line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
  14162. #endif
  14163. /*
  14164. * Copyright (c) 2014-2018 Cesanta Software Limited
  14165. * All rights reserved
  14166. *
  14167. * Licensed under the Apache License, Version 2.0 (the ""License"");
  14168. * you may not use this file except in compliance with the License.
  14169. * You may obtain a copy of the License at
  14170. *
  14171. * http://www.apache.org/licenses/LICENSE-2.0
  14172. *
  14173. * Unless required by applicable law or agreed to in writing, software
  14174. * distributed under the License is distributed on an ""AS IS"" BASIS,
  14175. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14176. * See the License for the specific language governing permissions and
  14177. * limitations under the License.
  14178. */
  14179. #if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
  14180. #ifndef MG_SIG_QUEUE_LEN
  14181. #define MG_SIG_QUEUE_LEN 32
  14182. #endif
  14183. struct mg_ev_mgr_lwip_signal {
  14184. int sig;
  14185. struct mg_connection *nc;
  14186. };
  14187. struct mg_ev_mgr_lwip_data {
  14188. struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
  14189. int sig_queue_len;
  14190. int start_index;
  14191. };
  14192. void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
  14193. struct mg_ev_mgr_lwip_data *md =
  14194. (struct mg_ev_mgr_lwip_data *) nc->iface->data;
  14195. mgos_lock();
  14196. if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
  14197. mgos_unlock();
  14198. return;
  14199. }
  14200. int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
  14201. md->sig_queue[end_index].sig = sig;
  14202. md->sig_queue[end_index].nc = nc;
  14203. md->sig_queue_len++;
  14204. mg_lwip_mgr_schedule_poll(nc->mgr);
  14205. mgos_unlock();
  14206. }
  14207. void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
  14208. struct mg_ev_mgr_lwip_data *md =
  14209. (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
  14210. while (md->sig_queue_len > 0) {
  14211. mgos_lock();
  14212. int i = md->start_index;
  14213. int sig = md->sig_queue[i].sig;
  14214. struct mg_connection *nc = md->sig_queue[i].nc;
  14215. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  14216. md->start_index = (i + 1) % MG_SIG_QUEUE_LEN;
  14217. md->sig_queue_len--;
  14218. mgos_unlock();
  14219. if (nc->iface == NULL || nc->mgr == NULL) continue;
  14220. switch (sig) {
  14221. case MG_SIG_CONNECT_RESULT: {
  14222. mg_if_connect_cb(nc, cs->err);
  14223. break;
  14224. }
  14225. case MG_SIG_CLOSE_CONN: {
  14226. mg_close_conn(nc);
  14227. break;
  14228. }
  14229. case MG_SIG_RECV: {
  14230. cs->recv_pending = 0;
  14231. mg_if_can_recv_cb(nc);
  14232. mbuf_trim(&nc->recv_mbuf);
  14233. break;
  14234. }
  14235. case MG_SIG_TOMBSTONE: {
  14236. break;
  14237. }
  14238. case MG_SIG_ACCEPT: {
  14239. mg_lwip_handle_accept(nc);
  14240. break;
  14241. }
  14242. }
  14243. }
  14244. }
  14245. void mg_lwip_if_init(struct mg_iface *iface) {
  14246. LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR,
  14247. LWIP_VERSION_MINOR, LWIP_VERSION_REVISION));
  14248. iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
  14249. #if !NO_SYS && !LWIP_TCPIP_CORE_LOCKING
  14250. sys_sem_new(&s_tcpip_call_lock_sem, 1);
  14251. sys_sem_new(&s_tcpip_call_sync_sem, 0);
  14252. #endif
  14253. }
  14254. void mg_lwip_if_free(struct mg_iface *iface) {
  14255. MG_FREE(iface->data);
  14256. iface->data = NULL;
  14257. }
  14258. void mg_lwip_if_add_conn(struct mg_connection *nc) {
  14259. (void) nc;
  14260. }
  14261. void mg_lwip_if_remove_conn(struct mg_connection *nc) {
  14262. struct mg_ev_mgr_lwip_data *md =
  14263. (struct mg_ev_mgr_lwip_data *) nc->iface->data;
  14264. /* Walk the queue and null-out further signals for this conn. */
  14265. for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
  14266. if (md->sig_queue[i].nc == nc) {
  14267. md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
  14268. }
  14269. }
  14270. }
  14271. time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
  14272. struct mg_mgr *mgr = iface->mgr;
  14273. int n = 0;
  14274. double now = mg_time();
  14275. struct mg_connection *nc, *tmp;
  14276. double min_timer = 0;
  14277. int num_timers = 0;
  14278. #if 0
  14279. DBG(("begin poll @%u", (unsigned int) (now * 1000)));
  14280. #endif
  14281. mg_ev_mgr_lwip_process_signals(mgr);
  14282. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  14283. struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
  14284. tmp = nc->next;
  14285. n++;
  14286. if (!mg_if_poll(nc, now)) continue;
  14287. if (nc->sock != INVALID_SOCKET &&
  14288. !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
  14289. cs->pcb.tcp->unsent != NULL) {
  14290. mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, cs->pcb.tcp);
  14291. }
  14292. if (nc->ev_timer_time > 0) {
  14293. if (num_timers == 0 || nc->ev_timer_time < min_timer) {
  14294. min_timer = nc->ev_timer_time;
  14295. }
  14296. num_timers++;
  14297. }
  14298. if (nc->sock != INVALID_SOCKET) {
  14299. if (mg_lwip_if_can_send(nc, cs)) {
  14300. mg_if_can_send_cb(nc);
  14301. mbuf_trim(&nc->send_mbuf);
  14302. }
  14303. if (cs->rx_chain != NULL) {
  14304. mg_if_can_recv_cb(nc);
  14305. } else if (cs->draining_rx_chain) {
  14306. /*
  14307. * If the connection is about to close, and rx_chain is finally empty,
  14308. * send the MG_SIG_CLOSE_CONN signal
  14309. */
  14310. mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
  14311. }
  14312. }
  14313. }
  14314. #if 0
  14315. DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
  14316. (unsigned int) (now * 1000), n, num_timers,
  14317. (unsigned int) (min_timer * 1000), timeout_ms));
  14318. #endif
  14319. (void) timeout_ms;
  14320. return now;
  14321. }
  14322. #endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
  14323. #ifdef MG_MODULE_LINES
  14324. #line 1 "common/platforms/wince/wince_libc.c"
  14325. #endif
  14326. /*
  14327. * Copyright (c) 2014-2018 Cesanta Software Limited
  14328. * All rights reserved
  14329. *
  14330. * Licensed under the Apache License, Version 2.0 (the ""License"");
  14331. * you may not use this file except in compliance with the License.
  14332. * You may obtain a copy of the License at
  14333. *
  14334. * http://www.apache.org/licenses/LICENSE-2.0
  14335. *
  14336. * Unless required by applicable law or agreed to in writing, software
  14337. * distributed under the License is distributed on an ""AS IS"" BASIS,
  14338. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14339. * See the License for the specific language governing permissions and
  14340. * limitations under the License.
  14341. */
  14342. #ifdef WINCE
  14343. const char *strerror(int err) {
  14344. /*
  14345. * TODO(alashkin): there is no strerror on WinCE;
  14346. * look for similar wce_xxxx function
  14347. */
  14348. static char buf[10];
  14349. snprintf(buf, sizeof(buf), "%d", err);
  14350. return buf;
  14351. }
  14352. int open(const char *filename, int oflag, int pmode) {
  14353. /*
  14354. * TODO(alashkin): mg_open function is not used in mongoose
  14355. * but exists in documentation as utility function
  14356. * Shall we delete it at all or implement for WinCE as well?
  14357. */
  14358. DebugBreak();
  14359. return 0; /* for compiler */
  14360. }
  14361. int _wstati64(const wchar_t *path, cs_stat_t *st) {
  14362. DWORD fa = GetFileAttributesW(path);
  14363. if (fa == INVALID_FILE_ATTRIBUTES) {
  14364. return -1;
  14365. }
  14366. memset(st, 0, sizeof(*st));
  14367. if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
  14368. HANDLE h;
  14369. FILETIME ftime;
  14370. st->st_mode |= _S_IFREG;
  14371. h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
  14372. FILE_ATTRIBUTE_NORMAL, NULL);
  14373. if (h == INVALID_HANDLE_VALUE) {
  14374. return -1;
  14375. }
  14376. st->st_size = GetFileSize(h, NULL);
  14377. GetFileTime(h, NULL, NULL, &ftime);
  14378. st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
  14379. ((uint64_t) ftime.dwHighDateTime << 32)) /
  14380. 10000000.0) -
  14381. 11644473600);
  14382. CloseHandle(h);
  14383. } else {
  14384. st->st_mode |= _S_IFDIR;
  14385. }
  14386. return 0;
  14387. }
  14388. /* Windows CE doesn't have neither gmtime nor strftime */
  14389. static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  14390. FILETIME ft;
  14391. SYSTEMTIME systime;
  14392. if (t != NULL) {
  14393. uint64_t filetime = (*t + 11644473600) * 10000000;
  14394. ft.dwLowDateTime = filetime & 0xFFFFFFFF;
  14395. ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
  14396. FileTimeToSystemTime(&ft, &systime);
  14397. } else {
  14398. GetSystemTime(&systime);
  14399. }
  14400. /* There is no PRIu16 in WinCE SDK */
  14401. snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
  14402. (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
  14403. (int) systime.wMinute, (int) systime.wSecond);
  14404. }
  14405. #endif
  14406. #ifdef MG_MODULE_LINES
  14407. #line 1 "common/platforms/pic32/pic32_net_if.h"
  14408. #endif
  14409. /*
  14410. * Copyright (c) 2014-2018 Cesanta Software Limited
  14411. * All rights reserved
  14412. *
  14413. * Licensed under the Apache License, Version 2.0 (the ""License"");
  14414. * you may not use this file except in compliance with the License.
  14415. * You may obtain a copy of the License at
  14416. *
  14417. * http://www.apache.org/licenses/LICENSE-2.0
  14418. *
  14419. * Unless required by applicable law or agreed to in writing, software
  14420. * distributed under the License is distributed on an ""AS IS"" BASIS,
  14421. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14422. * See the License for the specific language governing permissions and
  14423. * limitations under the License.
  14424. */
  14425. #ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
  14426. #define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
  14427. /* Amalgamated: #include "mongoose/src/net_if.h" */
  14428. #ifdef __cplusplus
  14429. extern "C" {
  14430. #endif /* __cplusplus */
  14431. #ifndef MG_ENABLE_NET_IF_PIC32
  14432. #define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
  14433. #endif
  14434. extern const struct mg_iface_vtable mg_pic32_iface_vtable;
  14435. #ifdef __cplusplus
  14436. }
  14437. #endif /* __cplusplus */
  14438. #endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
  14439. #ifdef MG_MODULE_LINES
  14440. #line 1 "common/platforms/pic32/pic32_net_if.c"
  14441. #endif
  14442. /*
  14443. * Copyright (c) 2014-2018 Cesanta Software Limited
  14444. * All rights reserved
  14445. *
  14446. * Licensed under the Apache License, Version 2.0 (the ""License"");
  14447. * you may not use this file except in compliance with the License.
  14448. * You may obtain a copy of the License at
  14449. *
  14450. * http://www.apache.org/licenses/LICENSE-2.0
  14451. *
  14452. * Unless required by applicable law or agreed to in writing, software
  14453. * distributed under the License is distributed on an ""AS IS"" BASIS,
  14454. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14455. * See the License for the specific language governing permissions and
  14456. * limitations under the License.
  14457. */
  14458. #if MG_ENABLE_NET_IF_PIC32
  14459. int mg_pic32_if_create_conn(struct mg_connection *nc) {
  14460. (void) nc;
  14461. return 1;
  14462. }
  14463. void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
  14464. (void) nc;
  14465. (void) len;
  14466. }
  14467. void mg_pic32_if_add_conn(struct mg_connection *nc) {
  14468. (void) nc;
  14469. }
  14470. void mg_pic32_if_init(struct mg_iface *iface) {
  14471. (void) iface;
  14472. (void) mg_get_errno(); /* Shutup compiler */
  14473. }
  14474. void mg_pic32_if_free(struct mg_iface *iface) {
  14475. (void) iface;
  14476. }
  14477. void mg_pic32_if_remove_conn(struct mg_connection *nc) {
  14478. (void) nc;
  14479. }
  14480. void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
  14481. if (nc->sock == INVALID_SOCKET) return;
  14482. /* For UDP, only close outgoing sockets or listeners. */
  14483. if (!(nc->flags & MG_F_UDP)) {
  14484. /* Close TCP */
  14485. TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
  14486. } else if (nc->listener == NULL) {
  14487. /* Only close outgoing UDP or listeners. */
  14488. TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
  14489. }
  14490. nc->sock = INVALID_SOCKET;
  14491. }
  14492. int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
  14493. nc->sock = TCPIP_UDP_ServerOpen(
  14494. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  14495. : IP_ADDRESS_TYPE_IPV6,
  14496. ntohs(sa->sin.sin_port),
  14497. sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
  14498. if (nc->sock == INVALID_SOCKET) {
  14499. return -1;
  14500. }
  14501. return 0;
  14502. }
  14503. void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
  14504. size_t len) {
  14505. mbuf_append(&nc->send_mbuf, buf, len);
  14506. }
  14507. void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
  14508. size_t len) {
  14509. mbuf_append(&nc->send_mbuf, buf, len);
  14510. }
  14511. int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
  14512. nc->sock = TCPIP_TCP_ServerOpen(
  14513. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  14514. : IP_ADDRESS_TYPE_IPV6,
  14515. ntohs(sa->sin.sin_port),
  14516. sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
  14517. memcpy(&nc->sa, sa, sizeof(*sa));
  14518. if (nc->sock == INVALID_SOCKET) {
  14519. return -1;
  14520. }
  14521. return 0;
  14522. }
  14523. static int mg_accept_conn(struct mg_connection *lc) {
  14524. struct mg_connection *nc;
  14525. TCP_SOCKET_INFO si;
  14526. union socket_address sa;
  14527. nc = mg_if_accept_new_conn(lc);
  14528. if (nc == NULL) {
  14529. return 0;
  14530. }
  14531. nc->sock = lc->sock;
  14532. nc->flags &= ~MG_F_LISTENING;
  14533. if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
  14534. return 0;
  14535. }
  14536. if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
  14537. sa.sin.sin_family = AF_INET;
  14538. sa.sin.sin_port = htons(si.remotePort);
  14539. sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
  14540. } else {
  14541. /* TODO(alashkin): do something with _potential_ IPv6 */
  14542. memset(&sa, 0, sizeof(sa));
  14543. }
  14544. mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
  14545. return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
  14546. }
  14547. char *inet_ntoa(struct in_addr in) {
  14548. static char addr[17];
  14549. snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
  14550. (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
  14551. (int) in.S_un.S_un_b.s_b4);
  14552. return addr;
  14553. }
  14554. static void mg_handle_send(struct mg_connection *nc) {
  14555. uint16_t bytes_written = 0;
  14556. if (nc->flags & MG_F_UDP) {
  14557. if (!TCPIP_UDP_RemoteBind(
  14558. (UDP_SOCKET) nc->sock,
  14559. nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  14560. : IP_ADDRESS_TYPE_IPV6,
  14561. ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
  14562. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  14563. return;
  14564. }
  14565. bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
  14566. if (bytes_written >= nc->send_mbuf.len) {
  14567. if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
  14568. (uint8_t *) nc->send_mbuf.buf,
  14569. nc->send_mbuf.len) != nc->send_mbuf.len) {
  14570. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  14571. bytes_written = 0;
  14572. }
  14573. }
  14574. } else {
  14575. bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
  14576. if (bytes_written != 0) {
  14577. if (bytes_written > nc->send_mbuf.len) {
  14578. bytes_written = nc->send_mbuf.len;
  14579. }
  14580. if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
  14581. (uint8_t *) nc->send_mbuf.buf,
  14582. bytes_written) != bytes_written) {
  14583. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  14584. bytes_written = 0;
  14585. }
  14586. }
  14587. }
  14588. mg_if_sent_cb(nc, bytes_written);
  14589. }
  14590. static void mg_handle_recv(struct mg_connection *nc) {
  14591. uint16_t bytes_read = 0;
  14592. uint8_t *buf = NULL;
  14593. if (nc->flags & MG_F_UDP) {
  14594. bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
  14595. if (bytes_read != 0 &&
  14596. (nc->recv_mbuf_limit == -1 ||
  14597. nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
  14598. buf = (uint8_t *) MG_MALLOC(bytes_read);
  14599. if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
  14600. bytes_read) {
  14601. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  14602. bytes_read = 0;
  14603. MG_FREE(buf);
  14604. }
  14605. }
  14606. } else {
  14607. bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
  14608. if (bytes_read != 0) {
  14609. if (nc->recv_mbuf_limit != -1 &&
  14610. nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
  14611. bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
  14612. }
  14613. buf = (uint8_t *) MG_MALLOC(bytes_read);
  14614. if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
  14615. bytes_read) {
  14616. nc->flags |= MG_F_CLOSE_IMMEDIATELY;
  14617. MG_FREE(buf);
  14618. bytes_read = 0;
  14619. }
  14620. }
  14621. }
  14622. if (bytes_read != 0) {
  14623. mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
  14624. }
  14625. }
  14626. time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
  14627. struct mg_mgr *mgr = iface->mgr;
  14628. double now = mg_time();
  14629. struct mg_connection *nc, *tmp;
  14630. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  14631. tmp = nc->next;
  14632. if (nc->flags & MG_F_CONNECTING) {
  14633. /* processing connections */
  14634. if (nc->flags & MG_F_UDP ||
  14635. TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
  14636. mg_if_connect_cb(nc, 0);
  14637. }
  14638. } else if (nc->flags & MG_F_LISTENING) {
  14639. if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
  14640. /* accept new connections */
  14641. mg_accept_conn(nc);
  14642. }
  14643. } else {
  14644. if (nc->send_mbuf.len != 0) {
  14645. mg_handle_send(nc);
  14646. }
  14647. if (nc->recv_mbuf_limit == -1 ||
  14648. nc->recv_mbuf.len < nc->recv_mbuf_limit) {
  14649. mg_handle_recv(nc);
  14650. }
  14651. }
  14652. }
  14653. for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
  14654. tmp = nc->next;
  14655. if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
  14656. (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
  14657. mg_close_conn(nc);
  14658. }
  14659. }
  14660. return now;
  14661. }
  14662. void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
  14663. nc->sock = sock;
  14664. }
  14665. void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
  14666. union socket_address *sa) {
  14667. /* TODO(alaskin): not implemented yet */
  14668. }
  14669. void mg_pic32_if_connect_tcp(struct mg_connection *nc,
  14670. const union socket_address *sa) {
  14671. nc->sock = TCPIP_TCP_ClientOpen(
  14672. sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
  14673. : IP_ADDRESS_TYPE_IPV6,
  14674. ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
  14675. nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
  14676. }
  14677. void mg_pic32_if_connect_udp(struct mg_connection *nc) {
  14678. nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
  14679. nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
  14680. }
  14681. /* clang-format off */
  14682. #define MG_PIC32_IFACE_VTABLE \
  14683. { \
  14684. mg_pic32_if_init, \
  14685. mg_pic32_if_free, \
  14686. mg_pic32_if_add_conn, \
  14687. mg_pic32_if_remove_conn, \
  14688. mg_pic32_if_poll, \
  14689. mg_pic32_if_listen_tcp, \
  14690. mg_pic32_if_listen_udp, \
  14691. mg_pic32_if_connect_tcp, \
  14692. mg_pic32_if_connect_udp, \
  14693. mg_pic32_if_tcp_send, \
  14694. mg_pic32_if_udp_send, \
  14695. mg_pic32_if_recved, \
  14696. mg_pic32_if_create_conn, \
  14697. mg_pic32_if_destroy_conn, \
  14698. mg_pic32_if_sock_set, \
  14699. mg_pic32_if_get_conn_addr, \
  14700. }
  14701. /* clang-format on */
  14702. const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
  14703. #if MG_NET_IF == MG_NET_IF_PIC32
  14704. const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
  14705. #endif
  14706. #endif /* MG_ENABLE_NET_IF_PIC32 */
  14707. #ifdef MG_MODULE_LINES
  14708. #line 1 "common/platforms/windows/windows_direct.c"
  14709. #endif
  14710. /*
  14711. * Copyright (c) 2014-2018 Cesanta Software Limited
  14712. * All rights reserved
  14713. *
  14714. * Licensed under the Apache License, Version 2.0 (the ""License"");
  14715. * you may not use this file except in compliance with the License.
  14716. * You may obtain a copy of the License at
  14717. *
  14718. * http://www.apache.org/licenses/LICENSE-2.0
  14719. *
  14720. * Unless required by applicable law or agreed to in writing, software
  14721. * distributed under the License is distributed on an ""AS IS"" BASIS,
  14722. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14723. * See the License for the specific language governing permissions and
  14724. * limitations under the License.
  14725. */
  14726. #ifdef _WIN32
  14727. int rmdir(const char *dirname) {
  14728. return _rmdir(dirname);
  14729. }
  14730. unsigned int sleep(unsigned int seconds) {
  14731. Sleep(seconds * 1000);
  14732. return 0;
  14733. }
  14734. #endif /* _WIN32 */