mongoose.c 600 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643
  1. // Copyright (c) 2004-2013 Sergey Lyubka
  2. // Copyright (c) 2013-2024 Cesanta Software Limited
  3. // All rights reserved
  4. //
  5. // This software is dual-licensed: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License version 2 as
  7. // published by the Free Software Foundation. For the terms of this
  8. // license, see http://www.gnu.org/licenses/
  9. //
  10. // You are free to use this software under the terms of the GNU General
  11. // Public License, but WITHOUT ANY WARRANTY; without even the implied
  12. // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. // See the GNU General Public License for more details.
  14. //
  15. // Alternatively, you can license this software under a commercial
  16. // license, as set out in https://www.mongoose.ws/licensing/
  17. //
  18. // SPDX-License-Identifier: GPL-2.0-only or commercial
  19. #include "mongoose.h"
  20. #ifdef MG_ENABLE_LINES
  21. #line 1 "src/base64.c"
  22. #endif
  23. static int mg_base64_encode_single(int c) {
  24. if (c < 26) {
  25. return c + 'A';
  26. } else if (c < 52) {
  27. return c - 26 + 'a';
  28. } else if (c < 62) {
  29. return c - 52 + '0';
  30. } else {
  31. return c == 62 ? '+' : '/';
  32. }
  33. }
  34. static int mg_base64_decode_single(int c) {
  35. if (c >= 'A' && c <= 'Z') {
  36. return c - 'A';
  37. } else if (c >= 'a' && c <= 'z') {
  38. return c + 26 - 'a';
  39. } else if (c >= '0' && c <= '9') {
  40. return c + 52 - '0';
  41. } else if (c == '+') {
  42. return 62;
  43. } else if (c == '/') {
  44. return 63;
  45. } else if (c == '=') {
  46. return 64;
  47. } else {
  48. return -1;
  49. }
  50. }
  51. size_t mg_base64_update(unsigned char ch, char *to, size_t n) {
  52. unsigned long rem = (n & 3) % 3;
  53. if (rem == 0) {
  54. to[n] = (char) mg_base64_encode_single(ch >> 2);
  55. to[++n] = (char) ((ch & 3) << 4);
  56. } else if (rem == 1) {
  57. to[n] = (char) mg_base64_encode_single(to[n] | (ch >> 4));
  58. to[++n] = (char) ((ch & 15) << 2);
  59. } else {
  60. to[n] = (char) mg_base64_encode_single(to[n] | (ch >> 6));
  61. to[++n] = (char) mg_base64_encode_single(ch & 63);
  62. n++;
  63. }
  64. return n;
  65. }
  66. size_t mg_base64_final(char *to, size_t n) {
  67. size_t saved = n;
  68. // printf("---[%.*s]\n", n, to);
  69. if (n & 3) n = mg_base64_update(0, to, n);
  70. if ((saved & 3) == 2) n--;
  71. // printf(" %d[%.*s]\n", n, n, to);
  72. while (n & 3) to[n++] = '=';
  73. to[n] = '\0';
  74. return n;
  75. }
  76. size_t mg_base64_encode(const unsigned char *p, size_t n, char *to, size_t dl) {
  77. size_t i, len = 0;
  78. if (dl > 0) to[0] = '\0';
  79. if (dl < ((n / 3) + (n % 3 ? 1 : 0)) * 4 + 1) return 0;
  80. for (i = 0; i < n; i++) len = mg_base64_update(p[i], to, len);
  81. len = mg_base64_final(to, len);
  82. return len;
  83. }
  84. size_t mg_base64_decode(const char *src, size_t n, char *dst, size_t dl) {
  85. const char *end = src == NULL ? NULL : src + n; // Cannot add to NULL
  86. size_t len = 0;
  87. if (dl < n / 4 * 3 + 1) goto fail;
  88. while (src != NULL && src + 3 < end) {
  89. int a = mg_base64_decode_single(src[0]),
  90. b = mg_base64_decode_single(src[1]),
  91. c = mg_base64_decode_single(src[2]),
  92. d = mg_base64_decode_single(src[3]);
  93. if (a == 64 || a < 0 || b == 64 || b < 0 || c < 0 || d < 0) {
  94. goto fail;
  95. }
  96. dst[len++] = (char) ((a << 2) | (b >> 4));
  97. if (src[2] != '=') {
  98. dst[len++] = (char) ((b << 4) | (c >> 2));
  99. if (src[3] != '=') dst[len++] = (char) ((c << 6) | d);
  100. }
  101. src += 4;
  102. }
  103. dst[len] = '\0';
  104. return len;
  105. fail:
  106. if (dl > 0) dst[0] = '\0';
  107. return 0;
  108. }
  109. #ifdef MG_ENABLE_LINES
  110. #line 1 "src/device_ch32v307.c"
  111. #endif
  112. #if MG_DEVICE == MG_DEVICE_CH32V307
  113. // RM: https://www.wch-ic.com/downloads/CH32FV2x_V3xRM_PDF.html
  114. #define FLASH_BASE 0x40022000
  115. #define FLASH_ACTLR (FLASH_BASE + 0)
  116. #define FLASH_KEYR (FLASH_BASE + 4)
  117. #define FLASH_OBKEYR (FLASH_BASE + 8)
  118. #define FLASH_STATR (FLASH_BASE + 12)
  119. #define FLASH_CTLR (FLASH_BASE + 16)
  120. #define FLASH_ADDR (FLASH_BASE + 20)
  121. #define FLASH_OBR (FLASH_BASE + 28)
  122. #define FLASH_WPR (FLASH_BASE + 32)
  123. void *mg_flash_start(void) {
  124. return (void *) 0x08000000;
  125. }
  126. size_t mg_flash_size(void) {
  127. return 480 * 1024; // First 320k is 0-wait
  128. }
  129. size_t mg_flash_sector_size(void) {
  130. return 4096;
  131. }
  132. size_t mg_flash_write_align(void) {
  133. return 4;
  134. }
  135. int mg_flash_bank(void) {
  136. return 0;
  137. }
  138. void mg_device_reset(void) {
  139. *((volatile uint32_t *) 0xbeef0000) |= 1U << 7; // NVIC_SystemReset()
  140. }
  141. static void flash_unlock(void) {
  142. static bool unlocked;
  143. if (unlocked == false) {
  144. MG_REG(FLASH_KEYR) = 0x45670123;
  145. MG_REG(FLASH_KEYR) = 0xcdef89ab;
  146. unlocked = true;
  147. }
  148. }
  149. static void flash_wait(void) {
  150. while (MG_REG(FLASH_STATR) & MG_BIT(0)) (void) 0;
  151. }
  152. bool mg_flash_erase(void *addr) {
  153. //MG_INFO(("%p", addr));
  154. flash_unlock();
  155. flash_wait();
  156. MG_REG(FLASH_ADDR) = (uint32_t) addr;
  157. MG_REG(FLASH_CTLR) |= MG_BIT(1) | MG_BIT(6); // PER | STRT;
  158. flash_wait();
  159. return true;
  160. }
  161. static bool is_page_boundary(const void *addr) {
  162. uint32_t val = (uint32_t) addr;
  163. return (val & (mg_flash_sector_size() - 1)) == 0;
  164. }
  165. bool mg_flash_write(void *addr, const void *buf, size_t len) {
  166. //MG_INFO(("%p %p %lu", addr, buf, len));
  167. //mg_hexdump(buf, len);
  168. flash_unlock();
  169. const uint16_t *src = (uint16_t *) buf, *end = &src[len / 2];
  170. uint16_t *dst = (uint16_t *) addr;
  171. MG_REG(FLASH_CTLR) |= MG_BIT(0); // Set PG
  172. //MG_INFO(("CTLR: %#lx", MG_REG(FLASH_CTLR)));
  173. while (src < end) {
  174. if (is_page_boundary(dst)) mg_flash_erase(dst);
  175. *dst++ = *src++;
  176. flash_wait();
  177. }
  178. MG_REG(FLASH_CTLR) &= ~MG_BIT(0); // Clear PG
  179. return true;
  180. }
  181. #endif
  182. #ifdef MG_ENABLE_LINES
  183. #line 1 "src/device_dummy.c"
  184. #endif
  185. #if MG_DEVICE == MG_DEVICE_NONE
  186. void *mg_flash_start(void) {
  187. return NULL;
  188. }
  189. size_t mg_flash_size(void) {
  190. return 0;
  191. }
  192. size_t mg_flash_sector_size(void) {
  193. return 0;
  194. }
  195. size_t mg_flash_write_align(void) {
  196. return 0;
  197. }
  198. int mg_flash_bank(void) {
  199. return 0;
  200. }
  201. bool mg_flash_erase(void *location) {
  202. (void) location;
  203. return false;
  204. }
  205. bool mg_flash_swap_bank(void) {
  206. return true;
  207. }
  208. bool mg_flash_write(void *addr, const void *buf, size_t len) {
  209. (void) addr, (void) buf, (void) len;
  210. return false;
  211. }
  212. void mg_device_reset(void) {
  213. }
  214. #endif
  215. #ifdef MG_ENABLE_LINES
  216. #line 1 "src/device_flash.c"
  217. #endif
  218. #if MG_DEVICE == MG_DEVICE_STM32H7 || MG_DEVICE == MG_DEVICE_STM32H5 || \
  219. MG_DEVICE == MG_DEVICE_RT1020 || MG_DEVICE == MG_DEVICE_RT1060
  220. // Flash can be written only if it is erased. Erased flash is 0xff (all bits 1)
  221. // Writes must be mg_flash_write_align() - aligned. Thus if we want to save an
  222. // object, we pad it at the end for alignment.
  223. //
  224. // Objects in the flash sector are stored sequentially:
  225. // | 32-bit size | 32-bit KEY | ..data.. | ..pad.. | 32-bit size | ......
  226. //
  227. // In order to get to the next object, read its size, then align up.
  228. // Traverse the list of saved objects
  229. size_t mg_flash_next(char *p, char *end, uint32_t *key, size_t *size) {
  230. size_t aligned_size = 0, align = mg_flash_write_align(), left = end - p;
  231. uint32_t *p32 = (uint32_t *) p, min_size = sizeof(uint32_t) * 2;
  232. if (p32[0] != 0xffffffff && left > MG_ROUND_UP(min_size, align)) {
  233. if (size) *size = (size_t) p32[0];
  234. if (key) *key = p32[1];
  235. aligned_size = MG_ROUND_UP(p32[0] + sizeof(uint32_t) * 2, align);
  236. if (left < aligned_size) aligned_size = 0; // Out of bounds, fail
  237. }
  238. return aligned_size;
  239. }
  240. // Return the last sector of Bank 2
  241. static char *flash_last_sector(void) {
  242. size_t ss = mg_flash_sector_size(), size = mg_flash_size();
  243. char *base = (char *) mg_flash_start(), *last = base + size - ss;
  244. if (mg_flash_bank() == 2) last -= size / 2;
  245. return last;
  246. }
  247. // Find a saved object with a given key
  248. bool mg_flash_load(void *sector, uint32_t key, void *buf, size_t len) {
  249. char *base = (char *) mg_flash_start(), *s = (char *) sector, *res = NULL;
  250. size_t ss = mg_flash_sector_size(), ofs = 0, n, sz;
  251. bool ok = false;
  252. if (s == NULL) s = flash_last_sector();
  253. if (s < base || s >= base + mg_flash_size()) {
  254. MG_ERROR(("%p is outsize of flash", sector));
  255. } else if (((s - base) % ss) != 0) {
  256. MG_ERROR(("%p is not a sector boundary", sector));
  257. } else {
  258. uint32_t k, scanned = 0;
  259. while ((n = mg_flash_next(s + ofs, s + ss, &k, &sz)) > 0) {
  260. // MG_DEBUG((" > obj %lu, ofs %lu, key %x/%x", scanned, ofs, k, key));
  261. // mg_hexdump(s + ofs, n);
  262. if (k == key && sz == len) {
  263. res = s + ofs + sizeof(uint32_t) * 2;
  264. memcpy(buf, res, len); // Copy object
  265. ok = true; // Keep scanning for the newer versions of it
  266. }
  267. ofs += n, scanned++;
  268. }
  269. MG_DEBUG(("Scanned %u objects, key %x is @ %p", scanned, key, res));
  270. }
  271. return ok;
  272. }
  273. // For all saved objects in the sector, delete old versions of objects
  274. static void mg_flash_sector_cleanup(char *sector) {
  275. // Buffer all saved objects into an IO buffer (backed by RAM)
  276. // erase sector, and re-save them.
  277. struct mg_iobuf io = {0, 0, 0, 2048};
  278. size_t ss = mg_flash_sector_size();
  279. size_t n, size, size2, ofs = 0, hs = sizeof(uint32_t) * 2;
  280. uint32_t key;
  281. // Traverse all objects
  282. MG_DEBUG(("Cleaning up sector %p", sector));
  283. while ((n = mg_flash_next(sector + ofs, sector + ss, &key, &size)) > 0) {
  284. // Delete an old copy of this object in the cache
  285. for (size_t o = 0; o < io.len; o += size2 + hs) {
  286. uint32_t k = *(uint32_t *) (io.buf + o + sizeof(uint32_t));
  287. size2 = *(uint32_t *) (io.buf + o);
  288. if (k == key) {
  289. mg_iobuf_del(&io, o, size2 + hs);
  290. break;
  291. }
  292. }
  293. // And add the new copy
  294. mg_iobuf_add(&io, io.len, sector + ofs, size + hs);
  295. ofs += n;
  296. }
  297. // All objects are cached in RAM now
  298. if (mg_flash_erase(sector)) { // Erase sector. If successful,
  299. for (ofs = 0; ofs < io.len; ofs += size + hs) { // Traverse cached objects
  300. size = *(uint32_t *) (io.buf + ofs);
  301. key = *(uint32_t *) (io.buf + ofs + sizeof(uint32_t));
  302. mg_flash_save(sector, key, io.buf + ofs + hs, size); // Save to flash
  303. }
  304. }
  305. mg_iobuf_free(&io);
  306. }
  307. // Save an object with a given key - append to the end of an object list
  308. bool mg_flash_save(void *sector, uint32_t key, const void *buf, size_t len) {
  309. char *base = (char *) mg_flash_start(), *s = (char *) sector;
  310. size_t ss = mg_flash_sector_size(), ofs = 0, n;
  311. bool ok = false;
  312. if (s == NULL) s = flash_last_sector();
  313. if (s < base || s >= base + mg_flash_size()) {
  314. MG_ERROR(("%p is outsize of flash", sector));
  315. } else if (((s - base) % ss) != 0) {
  316. MG_ERROR(("%p is not a sector boundary", sector));
  317. } else {
  318. char ab[mg_flash_write_align()]; // Aligned write block
  319. uint32_t hdr[2] = {(uint32_t) len, key};
  320. size_t needed = sizeof(hdr) + len;
  321. size_t needed_aligned = MG_ROUND_UP(needed, sizeof(ab));
  322. while ((n = mg_flash_next(s + ofs, s + ss, NULL, NULL)) > 0) ofs += n;
  323. // If there is not enough space left, cleanup sector and re-eval ofs
  324. if (ofs + needed_aligned >= ss) {
  325. mg_flash_sector_cleanup(s);
  326. ofs = 0;
  327. while ((n = mg_flash_next(s + ofs, s + ss, NULL, NULL)) > 0) ofs += n;
  328. }
  329. if (ofs + needed_aligned <= ss) {
  330. // Enough space to save this object
  331. if (sizeof(ab) < sizeof(hdr)) {
  332. // Flash write granularity is 32 bit or less, write with no buffering
  333. ok = mg_flash_write(s + ofs, hdr, sizeof(hdr));
  334. if (ok) mg_flash_write(s + ofs + sizeof(hdr), buf, len);
  335. } else {
  336. // Flash granularity is sizeof(hdr) or more. We need to save in
  337. // 3 chunks: initial block, bulk, rest. This is because we have
  338. // two memory chunks to write: hdr and buf, on aligned boundaries.
  339. n = sizeof(ab) - sizeof(hdr); // Initial chunk that we write
  340. if (n > len) n = len; // is
  341. memset(ab, 0xff, sizeof(ab)); // initialized to all-one
  342. memcpy(ab, hdr, sizeof(hdr)); // contains the header (key + size)
  343. memcpy(ab + sizeof(hdr), buf, n); // and an initial part of buf
  344. MG_INFO(("saving initial block of %lu", sizeof(ab)));
  345. ok = mg_flash_write(s + ofs, ab, sizeof(ab));
  346. if (ok && len > n) {
  347. size_t n2 = MG_ROUND_DOWN(len - n, sizeof(ab));
  348. if (n2 > 0) {
  349. MG_INFO(("saving bulk, %lu", n2));
  350. ok = mg_flash_write(s + ofs + sizeof(ab), (char *) buf + n, n2);
  351. }
  352. if (ok && len > n) {
  353. size_t n3 = len - n - n2;
  354. if (n3 > sizeof(ab)) n3 = sizeof(ab);
  355. memset(ab, 0xff, sizeof(ab));
  356. memcpy(ab, (char *) buf + n + n2, n3);
  357. MG_INFO(("saving rest, %lu", n3));
  358. ok = mg_flash_write(s + ofs + sizeof(ab) + n2, ab, sizeof(ab));
  359. }
  360. }
  361. }
  362. MG_DEBUG(("Saved %lu/%lu bytes @ %p, key %x: %d", len, needed_aligned,
  363. s + ofs, key, ok));
  364. MG_DEBUG(("Sector space left: %lu bytes", ss - ofs - needed_aligned));
  365. } else {
  366. MG_ERROR(("Sector is full"));
  367. }
  368. }
  369. return ok;
  370. }
  371. #else
  372. bool mg_flash_save(void *sector, uint32_t key, const void *buf, size_t len) {
  373. (void) sector, (void) key, (void) buf, (void) len;
  374. return false;
  375. }
  376. bool mg_flash_load(void *sector, uint32_t key, void *buf, size_t len) {
  377. (void) sector, (void) key, (void) buf, (void) len;
  378. return false;
  379. }
  380. #endif
  381. #ifdef MG_ENABLE_LINES
  382. #line 1 "src/device_imxrt.c"
  383. #endif
  384. #if MG_DEVICE == MG_DEVICE_RT1020 || MG_DEVICE == MG_DEVICE_RT1060
  385. struct mg_flexspi_lut_seq {
  386. uint8_t seqNum;
  387. uint8_t seqId;
  388. uint16_t reserved;
  389. };
  390. struct mg_flexspi_mem_config {
  391. uint32_t tag;
  392. uint32_t version;
  393. uint32_t reserved0;
  394. uint8_t readSampleClkSrc;
  395. uint8_t csHoldTime;
  396. uint8_t csSetupTime;
  397. uint8_t columnAddressWidth;
  398. uint8_t deviceModeCfgEnable;
  399. uint8_t deviceModeType;
  400. uint16_t waitTimeCfgCommands;
  401. struct mg_flexspi_lut_seq deviceModeSeq;
  402. uint32_t deviceModeArg;
  403. uint8_t configCmdEnable;
  404. uint8_t configModeType[3];
  405. struct mg_flexspi_lut_seq configCmdSeqs[3];
  406. uint32_t reserved1;
  407. uint32_t configCmdArgs[3];
  408. uint32_t reserved2;
  409. uint32_t controllerMiscOption;
  410. uint8_t deviceType;
  411. uint8_t sflashPadType;
  412. uint8_t serialClkFreq;
  413. uint8_t lutCustomSeqEnable;
  414. uint32_t reserved3[2];
  415. uint32_t sflashA1Size;
  416. uint32_t sflashA2Size;
  417. uint32_t sflashB1Size;
  418. uint32_t sflashB2Size;
  419. uint32_t csPadSettingOverride;
  420. uint32_t sclkPadSettingOverride;
  421. uint32_t dataPadSettingOverride;
  422. uint32_t dqsPadSettingOverride;
  423. uint32_t timeoutInMs;
  424. uint32_t commandInterval;
  425. uint16_t dataValidTime[2];
  426. uint16_t busyOffset;
  427. uint16_t busyBitPolarity;
  428. uint32_t lookupTable[64];
  429. struct mg_flexspi_lut_seq lutCustomSeq[12];
  430. uint32_t reserved4[4];
  431. };
  432. struct mg_flexspi_nor_config {
  433. struct mg_flexspi_mem_config memConfig;
  434. uint32_t pageSize;
  435. uint32_t sectorSize;
  436. uint8_t ipcmdSerialClkFreq;
  437. uint8_t isUniformBlockSize;
  438. uint8_t reserved0[2];
  439. uint8_t serialNorType;
  440. uint8_t needExitNoCmdMode;
  441. uint8_t halfClkForNonReadCmd;
  442. uint8_t needRestoreNoCmdMode;
  443. uint32_t blockSize;
  444. uint32_t reserve2[11];
  445. };
  446. /* FLEXSPI memory config block related defintions */
  447. #define MG_FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian
  448. #define MG_FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0
  449. #define MG_FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \
  450. (MG_FLEXSPI_LUT_OPERAND0(op0) | MG_FLEXSPI_LUT_NUM_PADS0(pad0) | MG_FLEXSPI_LUT_OPCODE0(cmd0) | \
  451. MG_FLEXSPI_LUT_OPERAND1(op1) | MG_FLEXSPI_LUT_NUM_PADS1(pad1) | MG_FLEXSPI_LUT_OPCODE1(cmd1))
  452. #define MG_CMD_SDR 0x01
  453. #define MG_CMD_DDR 0x21
  454. #define MG_DUMMY_SDR 0x0C
  455. #define MG_DUMMY_DDR 0x2C
  456. #define MG_RADDR_SDR 0x02
  457. #define MG_RADDR_DDR 0x22
  458. #define MG_READ_SDR 0x09
  459. #define MG_READ_DDR 0x29
  460. #define MG_WRITE_SDR 0x08
  461. #define MG_WRITE_DDR 0x28
  462. #define MG_STOP 0
  463. #define MG_FLEXSPI_1PAD 0
  464. #define MG_FLEXSPI_2PAD 1
  465. #define MG_FLEXSPI_4PAD 2
  466. #define MG_FLEXSPI_8PAD 3
  467. #define MG_FLEXSPI_QSPI_LUT \
  468. { \
  469. [0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0xEB, MG_RADDR_SDR, MG_FLEXSPI_4PAD, \
  470. 0x18), \
  471. [1] = MG_FLEXSPI_LUT_SEQ(MG_DUMMY_SDR, MG_FLEXSPI_4PAD, 0x06, MG_READ_SDR, MG_FLEXSPI_4PAD, \
  472. 0x04), \
  473. [4 * 1 + 0] = \
  474. MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x05, MG_READ_SDR, MG_FLEXSPI_1PAD, 0x04), \
  475. [4 * 3 + 0] = \
  476. MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x06, MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  477. [4 * 5 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x20, MG_RADDR_SDR, \
  478. MG_FLEXSPI_1PAD, 0x18), \
  479. [4 * 8 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0xD8, MG_RADDR_SDR, \
  480. MG_FLEXSPI_1PAD, 0x18), \
  481. [4 * 9 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x02, MG_RADDR_SDR, \
  482. MG_FLEXSPI_1PAD, 0x18), \
  483. [4 * 9 + 1] = \
  484. MG_FLEXSPI_LUT_SEQ(MG_WRITE_SDR, MG_FLEXSPI_1PAD, 0x04, MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  485. [4 * 11 + 0] = \
  486. MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x60, MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  487. }
  488. #define MG_FLEXSPI_LUT_OPERAND0(x) (((uint32_t) (((uint32_t) (x)))) & 0xFFU)
  489. #define MG_FLEXSPI_LUT_NUM_PADS0(x) (((uint32_t) (((uint32_t) (x)) << 8U)) & 0x300U)
  490. #define MG_FLEXSPI_LUT_OPCODE0(x) (((uint32_t) (((uint32_t) (x)) << 10U)) & 0xFC00U)
  491. #define MG_FLEXSPI_LUT_OPERAND1(x) (((uint32_t) (((uint32_t) (x)) << 16U)) & 0xFF0000U)
  492. #define MG_FLEXSPI_LUT_NUM_PADS1(x) (((uint32_t) (((uint32_t) (x)) << 24U)) & 0x3000000U)
  493. #define MG_FLEXSPI_LUT_OPCODE1(x) (((uint32_t) (((uint32_t) (x)) << 26U)) & 0xFC000000U)
  494. #define FLEXSPI_NOR_INSTANCE 0
  495. #if MG_DEVICE == MG_DEVICE_RT1020
  496. struct mg_flexspi_nor_driver_interface {
  497. uint32_t version;
  498. int (*init)(uint32_t instance, struct mg_flexspi_nor_config *config);
  499. int (*program)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t dst_addr,
  500. const uint32_t *src);
  501. uint32_t reserved;
  502. int (*erase)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t start,
  503. uint32_t lengthInBytes);
  504. uint32_t reserved2;
  505. int (*update_lut)(uint32_t instance, uint32_t seqIndex, const uint32_t *lutBase,
  506. uint32_t seqNumber);
  507. int (*xfer)(uint32_t instance, char *xfer);
  508. void (*clear_cache)(uint32_t instance);
  509. };
  510. #elif MG_DEVICE == MG_DEVICE_RT1060
  511. struct mg_flexspi_nor_driver_interface {
  512. uint32_t version;
  513. int (*init)(uint32_t instance, struct mg_flexspi_nor_config *config);
  514. int (*program)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t dst_addr,
  515. const uint32_t *src);
  516. int (*erase_all)(uint32_t instance, struct mg_flexspi_nor_config *config);
  517. int (*erase)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t start,
  518. uint32_t lengthInBytes);
  519. int (*read)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t *dst, uint32_t addr,
  520. uint32_t lengthInBytes);
  521. void (*clear_cache)(uint32_t instance);
  522. int (*xfer)(uint32_t instance, char *xfer);
  523. int (*update_lut)(uint32_t instance, uint32_t seqIndex, const uint32_t *lutBase,
  524. uint32_t seqNumber);
  525. int (*get_config)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t *option);
  526. };
  527. #endif
  528. #define flexspi_nor (*((struct mg_flexspi_nor_driver_interface**) \
  529. (*(uint32_t*)0x0020001c + 16)))
  530. static bool s_flash_irq_disabled;
  531. MG_IRAM void *mg_flash_start(void) {
  532. return (void *) 0x60000000;
  533. }
  534. MG_IRAM size_t mg_flash_size(void) {
  535. return 8 * 1024 * 1024;
  536. }
  537. MG_IRAM size_t mg_flash_sector_size(void) {
  538. return 4 * 1024; // 4k
  539. }
  540. MG_IRAM size_t mg_flash_write_align(void) {
  541. return 256;
  542. }
  543. MG_IRAM int mg_flash_bank(void) {
  544. return 0;
  545. }
  546. MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
  547. char *base = (char *) mg_flash_start(), *end = base + mg_flash_size();
  548. volatile char *p = (char *) dst;
  549. return p >= base && p < end && ((p - base) % mg_flash_sector_size()) == 0;
  550. }
  551. // Note: the get_config function below works both for RT1020 and 1060
  552. #if MG_DEVICE == MG_DEVICE_RT1020
  553. MG_IRAM static int flexspi_nor_get_config(struct mg_flexspi_nor_config *config) {
  554. struct mg_flexspi_nor_config default_config = {
  555. .memConfig = {.tag = MG_FLEXSPI_CFG_BLK_TAG,
  556. .version = MG_FLEXSPI_CFG_BLK_VERSION,
  557. .readSampleClkSrc = 1, // ReadSampleClk_LoopbackFromDqsPad
  558. .csHoldTime = 3,
  559. .csSetupTime = 3,
  560. .controllerMiscOption = MG_BIT(4),
  561. .deviceType = 1, // serial NOR
  562. .sflashPadType = 4,
  563. .serialClkFreq = 7, // 133MHz
  564. .sflashA1Size = 8 * 1024 * 1024,
  565. .lookupTable = MG_FLEXSPI_QSPI_LUT},
  566. .pageSize = 256,
  567. .sectorSize = 4 * 1024,
  568. .ipcmdSerialClkFreq = 1,
  569. .blockSize = 64 * 1024,
  570. .isUniformBlockSize = false};
  571. *config = default_config;
  572. return 0;
  573. }
  574. #else
  575. MG_IRAM static int flexspi_nor_get_config(struct mg_flexspi_nor_config *config) {
  576. uint32_t options[] = {0xc0000000, 0x00};
  577. MG_ARM_DISABLE_IRQ();
  578. uint32_t status =
  579. flexspi_nor->get_config(FLEXSPI_NOR_INSTANCE, config, options);
  580. if (!s_flash_irq_disabled) {
  581. MG_ARM_ENABLE_IRQ();
  582. }
  583. if (status) {
  584. MG_ERROR(("Failed to extract flash configuration: status %u", status));
  585. }
  586. return status;
  587. }
  588. #endif
  589. MG_IRAM bool mg_flash_erase(void *addr) {
  590. struct mg_flexspi_nor_config config;
  591. if (flexspi_nor_get_config(&config) != 0) {
  592. return false;
  593. }
  594. if (flash_page_start(addr) == false) {
  595. MG_ERROR(("%p is not on a sector boundary", addr));
  596. return false;
  597. }
  598. void *dst = (void *)((char *) addr - (char *) mg_flash_start());
  599. // Note: Interrupts must be disabled before any call to the ROM API on RT1020
  600. // and 1060
  601. MG_ARM_DISABLE_IRQ();
  602. bool ok = (flexspi_nor->erase(FLEXSPI_NOR_INSTANCE, &config, (uint32_t) dst,
  603. mg_flash_sector_size()) == 0);
  604. if (!s_flash_irq_disabled) {
  605. MG_ARM_ENABLE_IRQ(); // Reenable them after the call
  606. }
  607. MG_DEBUG(("Sector starting at %p erasure: %s", addr, ok ? "ok" : "fail"));
  608. return ok;
  609. }
  610. MG_IRAM bool mg_flash_swap_bank(void) {
  611. return true;
  612. }
  613. static inline void spin(volatile uint32_t count) {
  614. while (count--) (void) 0;
  615. }
  616. static inline void flash_wait(void) {
  617. while ((*((volatile uint32_t *)(0x402A8000 + 0xE0)) & MG_BIT(1)) == 0)
  618. spin(1);
  619. }
  620. MG_IRAM static void *flash_code_location(void) {
  621. return (void *) ((char *) mg_flash_start() + 0x2000);
  622. }
  623. MG_IRAM bool mg_flash_write(void *addr, const void *buf, size_t len) {
  624. struct mg_flexspi_nor_config config;
  625. if (flexspi_nor_get_config(&config) != 0) {
  626. return false;
  627. }
  628. if ((len % mg_flash_write_align()) != 0) {
  629. MG_ERROR(("%lu is not aligned to %lu", len, mg_flash_write_align()));
  630. return false;
  631. }
  632. if ((char *) addr < (char *) mg_flash_start()) {
  633. MG_ERROR(("Invalid flash write address: %p", addr));
  634. return false;
  635. }
  636. uint32_t *dst = (uint32_t *) addr;
  637. uint32_t *src = (uint32_t *) buf;
  638. uint32_t *end = (uint32_t *) ((char *) buf + len);
  639. bool ok = true;
  640. // Note: If we overwrite the flash irq section of the image, we must also
  641. // make sure interrupts are disabled and are not reenabled until we write
  642. // this sector with another irq table.
  643. if ((char *) addr == (char *) flash_code_location()) {
  644. s_flash_irq_disabled = true;
  645. MG_ARM_DISABLE_IRQ();
  646. }
  647. while (ok && src < end) {
  648. if (flash_page_start(dst) && mg_flash_erase(dst) == false) {
  649. break;
  650. }
  651. uint32_t status;
  652. uint32_t dst_ofs = (uint32_t) dst - (uint32_t) mg_flash_start();
  653. if ((char *) buf >= (char *) mg_flash_start()) {
  654. // If we copy from FLASH to FLASH, then we first need to copy the source
  655. // to RAM
  656. size_t tmp_buf_size = mg_flash_write_align() / sizeof(uint32_t);
  657. uint32_t tmp[tmp_buf_size];
  658. for (size_t i = 0; i < tmp_buf_size; i++) {
  659. flash_wait();
  660. tmp[i] = src[i];
  661. }
  662. MG_ARM_DISABLE_IRQ();
  663. status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, &config,
  664. (uint32_t) dst_ofs, tmp);
  665. } else {
  666. MG_ARM_DISABLE_IRQ();
  667. status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, &config,
  668. (uint32_t) dst_ofs, src);
  669. }
  670. if (!s_flash_irq_disabled) {
  671. MG_ARM_ENABLE_IRQ();
  672. }
  673. src = (uint32_t *) ((char *) src + mg_flash_write_align());
  674. dst = (uint32_t *) ((char *) dst + mg_flash_write_align());
  675. if (status != 0) {
  676. ok = false;
  677. }
  678. }
  679. MG_DEBUG(("Flash write %lu bytes @ %p: %s.", len, dst, ok ? "ok" : "fail"));
  680. return ok;
  681. }
  682. MG_IRAM void mg_device_reset(void) {
  683. MG_DEBUG(("Resetting device..."));
  684. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  685. }
  686. #endif
  687. #ifdef MG_ENABLE_LINES
  688. #line 1 "src/device_stm32h5.c"
  689. #endif
  690. #if MG_DEVICE == MG_DEVICE_STM32H5
  691. #define FLASH_BASE 0x40022000 // Base address of the flash controller
  692. #define FLASH_KEYR (FLASH_BASE + 0x4) // See RM0481 7.11
  693. #define FLASH_OPTKEYR (FLASH_BASE + 0xc)
  694. #define FLASH_OPTCR (FLASH_BASE + 0x1c)
  695. #define FLASH_NSSR (FLASH_BASE + 0x20)
  696. #define FLASH_NSCR (FLASH_BASE + 0x28)
  697. #define FLASH_NSCCR (FLASH_BASE + 0x30)
  698. #define FLASH_OPTSR_CUR (FLASH_BASE + 0x50)
  699. #define FLASH_OPTSR_PRG (FLASH_BASE + 0x54)
  700. void *mg_flash_start(void) {
  701. return (void *) 0x08000000;
  702. }
  703. size_t mg_flash_size(void) {
  704. return 2 * 1024 * 1024; // 2Mb
  705. }
  706. size_t mg_flash_sector_size(void) {
  707. return 8 * 1024; // 8k
  708. }
  709. size_t mg_flash_write_align(void) {
  710. return 16; // 128 bit
  711. }
  712. int mg_flash_bank(void) {
  713. return MG_REG(FLASH_OPTCR) & MG_BIT(31) ? 2 : 1;
  714. }
  715. static void flash_unlock(void) {
  716. static bool unlocked = false;
  717. if (unlocked == false) {
  718. MG_REG(FLASH_KEYR) = 0x45670123;
  719. MG_REG(FLASH_KEYR) = 0Xcdef89ab;
  720. MG_REG(FLASH_OPTKEYR) = 0x08192a3b;
  721. MG_REG(FLASH_OPTKEYR) = 0x4c5d6e7f;
  722. unlocked = true;
  723. }
  724. }
  725. static int flash_page_start(volatile uint32_t *dst) {
  726. char *base = (char *) mg_flash_start(), *end = base + mg_flash_size();
  727. volatile char *p = (char *) dst;
  728. return p >= base && p < end && ((p - base) % mg_flash_sector_size()) == 0;
  729. }
  730. static bool flash_is_err(void) {
  731. return MG_REG(FLASH_NSSR) & ((MG_BIT(8) - 1) << 17); // RM0481 7.11.9
  732. }
  733. static void flash_wait(void) {
  734. while ((MG_REG(FLASH_NSSR) & MG_BIT(0)) &&
  735. (MG_REG(FLASH_NSSR) & MG_BIT(16)) == 0) {
  736. (void) 0;
  737. }
  738. }
  739. static void flash_clear_err(void) {
  740. flash_wait(); // Wait until ready
  741. MG_REG(FLASH_NSCCR) = ((MG_BIT(9) - 1) << 16U); // Clear all errors
  742. }
  743. static bool flash_bank_is_swapped(void) {
  744. return MG_REG(FLASH_OPTCR) & MG_BIT(31); // RM0481 7.11.8
  745. }
  746. bool mg_flash_erase(void *location) {
  747. bool ok = false;
  748. if (flash_page_start(location) == false) {
  749. MG_ERROR(("%p is not on a sector boundary"));
  750. } else {
  751. uintptr_t diff = (char *) location - (char *) mg_flash_start();
  752. uint32_t sector = diff / mg_flash_sector_size();
  753. uint32_t saved_cr = MG_REG(FLASH_NSCR); // Save CR value
  754. flash_unlock();
  755. flash_clear_err();
  756. MG_REG(FLASH_NSCR) = 0;
  757. if ((sector < 128 && flash_bank_is_swapped()) ||
  758. (sector > 127 && !flash_bank_is_swapped())) {
  759. MG_REG(FLASH_NSCR) |= MG_BIT(31); // Set FLASH_CR_BKSEL
  760. }
  761. if (sector > 127) sector -= 128;
  762. MG_REG(FLASH_NSCR) |= MG_BIT(2) | (sector << 6); // Erase | sector_num
  763. MG_REG(FLASH_NSCR) |= MG_BIT(5); // Start erasing
  764. flash_wait();
  765. ok = !flash_is_err();
  766. MG_DEBUG(("Erase sector %lu @ %p: %s. CR %#lx SR %#lx", sector, location,
  767. ok ? "ok" : "fail", MG_REG(FLASH_NSCR), MG_REG(FLASH_NSSR)));
  768. // mg_hexdump(location, 32);
  769. MG_REG(FLASH_NSCR) = saved_cr; // Restore saved CR
  770. }
  771. return ok;
  772. }
  773. bool mg_flash_swap_bank(void) {
  774. uint32_t desired = flash_bank_is_swapped() ? 0 : MG_BIT(31);
  775. flash_unlock();
  776. flash_clear_err();
  777. // printf("OPTSR_PRG 1 %#lx\n", FLASH->OPTSR_PRG);
  778. MG_SET_BITS(MG_REG(FLASH_OPTSR_PRG), MG_BIT(31), desired);
  779. // printf("OPTSR_PRG 2 %#lx\n", FLASH->OPTSR_PRG);
  780. MG_REG(FLASH_OPTCR) |= MG_BIT(1); // OPTSTART
  781. while ((MG_REG(FLASH_OPTSR_CUR) & MG_BIT(31)) != desired) (void) 0;
  782. return true;
  783. }
  784. bool mg_flash_write(void *addr, const void *buf, size_t len) {
  785. if ((len % mg_flash_write_align()) != 0) {
  786. MG_ERROR(("%lu is not aligned to %lu", len, mg_flash_write_align()));
  787. return false;
  788. }
  789. uint32_t *dst = (uint32_t *) addr;
  790. uint32_t *src = (uint32_t *) buf;
  791. uint32_t *end = (uint32_t *) ((char *) buf + len);
  792. bool ok = true;
  793. flash_unlock();
  794. flash_clear_err();
  795. MG_ARM_DISABLE_IRQ();
  796. // MG_DEBUG(("Starting flash write %lu bytes @ %p", len, addr));
  797. MG_REG(FLASH_NSCR) = MG_BIT(1); // Set programming flag
  798. while (ok && src < end) {
  799. if (flash_page_start(dst) && mg_flash_erase(dst) == false) break;
  800. *(volatile uint32_t *) dst++ = *src++;
  801. flash_wait();
  802. if (flash_is_err()) ok = false;
  803. }
  804. MG_ARM_ENABLE_IRQ();
  805. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  806. flash_is_err() ? "fail" : "ok", MG_REG(FLASH_NSCR),
  807. MG_REG(FLASH_NSSR)));
  808. MG_REG(FLASH_NSCR) = 0; // Clear flags
  809. return ok;
  810. }
  811. void mg_device_reset(void) {
  812. // SCB->AIRCR = ((0x5fa << SCB_AIRCR_VECTKEY_Pos)|SCB_AIRCR_SYSRESETREQ_Msk);
  813. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  814. }
  815. #endif
  816. #ifdef MG_ENABLE_LINES
  817. #line 1 "src/device_stm32h7.c"
  818. #endif
  819. #if MG_DEVICE == MG_DEVICE_STM32H7
  820. #define FLASH_BASE1 0x52002000 // Base address for bank1
  821. #define FLASH_BASE2 0x52002100 // Base address for bank2
  822. #define FLASH_KEYR 0x04 // See RM0433 4.9.2
  823. #define FLASH_OPTKEYR 0x08
  824. #define FLASH_OPTCR 0x18
  825. #define FLASH_SR 0x10
  826. #define FLASH_CR 0x0c
  827. #define FLASH_CCR 0x14
  828. #define FLASH_OPTSR_CUR 0x1c
  829. #define FLASH_OPTSR_PRG 0x20
  830. #define FLASH_SIZE_REG 0x1ff1e880
  831. MG_IRAM void *mg_flash_start(void) {
  832. return (void *) 0x08000000;
  833. }
  834. MG_IRAM size_t mg_flash_size(void) {
  835. return MG_REG(FLASH_SIZE_REG) * 1024;
  836. }
  837. MG_IRAM size_t mg_flash_sector_size(void) {
  838. return 128 * 1024; // 128k
  839. }
  840. MG_IRAM size_t mg_flash_write_align(void) {
  841. return 32; // 256 bit
  842. }
  843. MG_IRAM int mg_flash_bank(void) {
  844. if (mg_flash_size() < 2 * 1024 * 1024) return 0; // No dual bank support
  845. return MG_REG(FLASH_BASE1 + FLASH_OPTCR) & MG_BIT(31) ? 2 : 1;
  846. }
  847. MG_IRAM static void flash_unlock(void) {
  848. static bool unlocked = false;
  849. if (unlocked == false) {
  850. MG_REG(FLASH_BASE1 + FLASH_KEYR) = 0x45670123;
  851. MG_REG(FLASH_BASE1 + FLASH_KEYR) = 0xcdef89ab;
  852. if (mg_flash_bank() > 0) {
  853. MG_REG(FLASH_BASE2 + FLASH_KEYR) = 0x45670123;
  854. MG_REG(FLASH_BASE2 + FLASH_KEYR) = 0xcdef89ab;
  855. }
  856. MG_REG(FLASH_BASE1 + FLASH_OPTKEYR) = 0x08192a3b; // opt reg is "shared"
  857. MG_REG(FLASH_BASE1 + FLASH_OPTKEYR) = 0x4c5d6e7f; // thus unlock once
  858. unlocked = true;
  859. }
  860. }
  861. MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
  862. char *base = (char *) mg_flash_start(), *end = base + mg_flash_size();
  863. volatile char *p = (char *) dst;
  864. return p >= base && p < end && ((p - base) % mg_flash_sector_size()) == 0;
  865. }
  866. MG_IRAM static bool flash_is_err(uint32_t bank) {
  867. return MG_REG(bank + FLASH_SR) & ((MG_BIT(11) - 1) << 17); // RM0433 4.9.5
  868. }
  869. MG_IRAM static void flash_wait(uint32_t bank) {
  870. while (MG_REG(bank + FLASH_SR) & (MG_BIT(0) | MG_BIT(2))) (void) 0;
  871. }
  872. MG_IRAM static void flash_clear_err(uint32_t bank) {
  873. flash_wait(bank); // Wait until ready
  874. MG_REG(bank + FLASH_CCR) = ((MG_BIT(11) - 1) << 16U); // Clear all errors
  875. }
  876. MG_IRAM static bool flash_bank_is_swapped(uint32_t bank) {
  877. return MG_REG(bank + FLASH_OPTCR) & MG_BIT(31); // RM0433 4.9.7
  878. }
  879. // Figure out flash bank based on the address
  880. MG_IRAM static uint32_t flash_bank(void *addr) {
  881. size_t ofs = (char *) addr - (char *) mg_flash_start();
  882. if (mg_flash_bank() == 0) return FLASH_BASE1;
  883. return ofs < mg_flash_size() / 2 ? FLASH_BASE1 : FLASH_BASE2;
  884. }
  885. MG_IRAM bool mg_flash_erase(void *addr) {
  886. bool ok = false;
  887. if (flash_page_start(addr) == false) {
  888. MG_ERROR(("%p is not on a sector boundary", addr));
  889. } else {
  890. uintptr_t diff = (char *) addr - (char *) mg_flash_start();
  891. uint32_t sector = diff / mg_flash_sector_size();
  892. uint32_t bank = flash_bank(addr);
  893. uint32_t saved_cr = MG_REG(bank + FLASH_CR); // Save CR value
  894. flash_unlock();
  895. if (sector > 7) sector -= 8;
  896. flash_clear_err(bank);
  897. MG_REG(bank + FLASH_CR) = MG_BIT(5); // 32-bit write parallelism
  898. MG_REG(bank + FLASH_CR) |= (sector & 7U) << 8U; // Sector to erase
  899. MG_REG(bank + FLASH_CR) |= MG_BIT(2); // Sector erase bit
  900. MG_REG(bank + FLASH_CR) |= MG_BIT(7); // Start erasing
  901. ok = !flash_is_err(bank);
  902. MG_DEBUG(("Erase sector %lu @ %p %s. CR %#lx SR %#lx", sector, addr,
  903. ok ? "ok" : "fail", MG_REG(bank + FLASH_CR),
  904. MG_REG(bank + FLASH_SR)));
  905. MG_REG(bank + FLASH_CR) = saved_cr; // Restore CR
  906. }
  907. return ok;
  908. }
  909. MG_IRAM bool mg_flash_swap_bank(void) {
  910. if (mg_flash_bank() == 0) return true;
  911. uint32_t bank = FLASH_BASE1;
  912. uint32_t desired = flash_bank_is_swapped(bank) ? 0 : MG_BIT(31);
  913. flash_unlock();
  914. flash_clear_err(bank);
  915. // printf("OPTSR_PRG 1 %#lx\n", FLASH->OPTSR_PRG);
  916. MG_SET_BITS(MG_REG(bank + FLASH_OPTSR_PRG), MG_BIT(31), desired);
  917. // printf("OPTSR_PRG 2 %#lx\n", FLASH->OPTSR_PRG);
  918. MG_REG(bank + FLASH_OPTCR) |= MG_BIT(1); // OPTSTART
  919. while ((MG_REG(bank + FLASH_OPTSR_CUR) & MG_BIT(31)) != desired) (void) 0;
  920. return true;
  921. }
  922. MG_IRAM bool mg_flash_write(void *addr, const void *buf, size_t len) {
  923. if ((len % mg_flash_write_align()) != 0) {
  924. MG_ERROR(("%lu is not aligned to %lu", len, mg_flash_write_align()));
  925. return false;
  926. }
  927. uint32_t bank = flash_bank(addr);
  928. uint32_t *dst = (uint32_t *) addr;
  929. uint32_t *src = (uint32_t *) buf;
  930. uint32_t *end = (uint32_t *) ((char *) buf + len);
  931. bool ok = true;
  932. flash_unlock();
  933. flash_clear_err(bank);
  934. MG_REG(bank + FLASH_CR) = MG_BIT(1); // Set programming flag
  935. MG_REG(bank + FLASH_CR) |= MG_BIT(5); // 32-bit write parallelism
  936. MG_DEBUG(("Writing flash @ %p, %lu bytes", addr, len));
  937. MG_ARM_DISABLE_IRQ();
  938. while (ok && src < end) {
  939. if (flash_page_start(dst) && mg_flash_erase(dst) == false) break;
  940. *(volatile uint32_t *) dst++ = *src++;
  941. flash_wait(bank);
  942. if (flash_is_err(bank)) ok = false;
  943. }
  944. MG_ARM_ENABLE_IRQ();
  945. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  946. ok ? "ok" : "fail", MG_REG(bank + FLASH_CR),
  947. MG_REG(bank + FLASH_SR)));
  948. MG_REG(bank + FLASH_CR) &= ~MG_BIT(1); // Clear programming flag
  949. return ok;
  950. }
  951. MG_IRAM void mg_device_reset(void) {
  952. // SCB->AIRCR = ((0x5fa << SCB_AIRCR_VECTKEY_Pos)|SCB_AIRCR_SYSRESETREQ_Msk);
  953. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  954. }
  955. #endif
  956. #ifdef MG_ENABLE_LINES
  957. #line 1 "src/dns.c"
  958. #endif
  959. struct dns_data {
  960. struct dns_data *next;
  961. struct mg_connection *c;
  962. uint64_t expire;
  963. uint16_t txnid;
  964. };
  965. static void mg_sendnsreq(struct mg_connection *, struct mg_str *, int,
  966. struct mg_dns *, bool);
  967. static void mg_dns_free(struct dns_data **head, struct dns_data *d) {
  968. LIST_DELETE(struct dns_data, head, d);
  969. free(d);
  970. }
  971. void mg_resolve_cancel(struct mg_connection *c) {
  972. struct dns_data *tmp, *d;
  973. struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests;
  974. for (d = *head; d != NULL; d = tmp) {
  975. tmp = d->next;
  976. if (d->c == c) mg_dns_free(head, d);
  977. }
  978. }
  979. static size_t mg_dns_parse_name_depth(const uint8_t *s, size_t len, size_t ofs,
  980. char *to, size_t tolen, size_t j,
  981. int depth) {
  982. size_t i = 0;
  983. if (tolen > 0 && depth == 0) to[0] = '\0';
  984. if (depth > 5) return 0;
  985. // MG_INFO(("ofs %lx %x %x", (unsigned long) ofs, s[ofs], s[ofs + 1]));
  986. while (ofs + i + 1 < len) {
  987. size_t n = s[ofs + i];
  988. if (n == 0) {
  989. i++;
  990. break;
  991. }
  992. if (n & 0xc0) {
  993. size_t ptr = (((n & 0x3f) << 8) | s[ofs + i + 1]); // 12 is hdr len
  994. // MG_INFO(("PTR %lx", (unsigned long) ptr));
  995. if (ptr + 1 < len && (s[ptr] & 0xc0) == 0 &&
  996. mg_dns_parse_name_depth(s, len, ptr, to, tolen, j, depth + 1) == 0)
  997. return 0;
  998. i += 2;
  999. break;
  1000. }
  1001. if (ofs + i + n + 1 >= len) return 0;
  1002. if (j > 0) {
  1003. if (j < tolen) to[j] = '.';
  1004. j++;
  1005. }
  1006. if (j + n < tolen) memcpy(&to[j], &s[ofs + i + 1], n);
  1007. j += n;
  1008. i += n + 1;
  1009. if (j < tolen) to[j] = '\0'; // Zero-terminate this chunk
  1010. // MG_INFO(("--> [%s]", to));
  1011. }
  1012. if (tolen > 0) to[tolen - 1] = '\0'; // Make sure make sure it is nul-term
  1013. return i;
  1014. }
  1015. static size_t mg_dns_parse_name(const uint8_t *s, size_t n, size_t ofs,
  1016. char *dst, size_t dstlen) {
  1017. return mg_dns_parse_name_depth(s, n, ofs, dst, dstlen, 0, 0);
  1018. }
  1019. size_t mg_dns_parse_rr(const uint8_t *buf, size_t len, size_t ofs,
  1020. bool is_question, struct mg_dns_rr *rr) {
  1021. const uint8_t *s = buf + ofs, *e = &buf[len];
  1022. memset(rr, 0, sizeof(*rr));
  1023. if (len < sizeof(struct mg_dns_header)) return 0; // Too small
  1024. if (len > 512) return 0; // Too large, we don't expect that
  1025. if (s >= e) return 0; // Overflow
  1026. if ((rr->nlen = (uint16_t) mg_dns_parse_name(buf, len, ofs, NULL, 0)) == 0)
  1027. return 0;
  1028. s += rr->nlen + 4;
  1029. if (s > e) return 0;
  1030. rr->atype = (uint16_t) (((uint16_t) s[-4] << 8) | s[-3]);
  1031. rr->aclass = (uint16_t) (((uint16_t) s[-2] << 8) | s[-1]);
  1032. if (is_question) return (size_t) (rr->nlen + 4);
  1033. s += 6;
  1034. if (s > e) return 0;
  1035. rr->alen = (uint16_t) (((uint16_t) s[-2] << 8) | s[-1]);
  1036. if (s + rr->alen > e) return 0;
  1037. return (size_t) (rr->nlen + rr->alen + 10);
  1038. }
  1039. bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) {
  1040. const struct mg_dns_header *h = (struct mg_dns_header *) buf;
  1041. struct mg_dns_rr rr;
  1042. size_t i, n, num_answers, ofs = sizeof(*h);
  1043. memset(dm, 0, sizeof(*dm));
  1044. if (len < sizeof(*h)) return 0; // Too small, headers dont fit
  1045. if (mg_ntohs(h->num_questions) > 1) return 0; // Sanity
  1046. num_answers = mg_ntohs(h->num_answers);
  1047. if (num_answers > 10) {
  1048. MG_DEBUG(("Got %u answers, ignoring beyond 10th one", num_answers));
  1049. num_answers = 10; // Sanity cap
  1050. }
  1051. dm->txnid = mg_ntohs(h->txnid);
  1052. for (i = 0; i < mg_ntohs(h->num_questions); i++) {
  1053. if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false;
  1054. // MG_INFO(("Q %lu %lu %hu/%hu", ofs, n, rr.atype, rr.aclass));
  1055. ofs += n;
  1056. }
  1057. for (i = 0; i < num_answers; i++) {
  1058. if ((n = mg_dns_parse_rr(buf, len, ofs, false, &rr)) == 0) return false;
  1059. // MG_INFO(("A -- %lu %lu %hu/%hu %s", ofs, n, rr.atype, rr.aclass,
  1060. // dm->name));
  1061. mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name));
  1062. ofs += n;
  1063. if (rr.alen == 4 && rr.atype == 1 && rr.aclass == 1) {
  1064. dm->addr.is_ip6 = false;
  1065. memcpy(&dm->addr.ip, &buf[ofs - 4], 4);
  1066. dm->resolved = true;
  1067. break; // Return success
  1068. } else if (rr.alen == 16 && rr.atype == 28 && rr.aclass == 1) {
  1069. dm->addr.is_ip6 = true;
  1070. memcpy(&dm->addr.ip, &buf[ofs - 16], 16);
  1071. dm->resolved = true;
  1072. break; // Return success
  1073. }
  1074. }
  1075. return true;
  1076. }
  1077. static void dns_cb(struct mg_connection *c, int ev, void *ev_data) {
  1078. struct dns_data *d, *tmp;
  1079. struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests;
  1080. if (ev == MG_EV_POLL) {
  1081. uint64_t now = *(uint64_t *) ev_data;
  1082. for (d = *head; d != NULL; d = tmp) {
  1083. tmp = d->next;
  1084. // MG_DEBUG ("%lu %lu dns poll", d->expire, now));
  1085. if (now > d->expire) mg_error(d->c, "DNS timeout");
  1086. }
  1087. } else if (ev == MG_EV_READ) {
  1088. struct mg_dns_message dm;
  1089. int resolved = 0;
  1090. if (mg_dns_parse(c->recv.buf, c->recv.len, &dm) == false) {
  1091. MG_ERROR(("Unexpected DNS response:"));
  1092. mg_hexdump(c->recv.buf, c->recv.len);
  1093. } else {
  1094. // MG_VERBOSE(("%s %d", dm.name, dm.resolved));
  1095. for (d = *head; d != NULL; d = tmp) {
  1096. tmp = d->next;
  1097. // MG_INFO(("d %p %hu %hu", d, d->txnid, dm.txnid));
  1098. if (dm.txnid != d->txnid) continue;
  1099. if (d->c->is_resolving) {
  1100. if (dm.resolved) {
  1101. dm.addr.port = d->c->rem.port; // Save port
  1102. d->c->rem = dm.addr; // Copy resolved address
  1103. MG_DEBUG(
  1104. ("%lu %s is %M", d->c->id, dm.name, mg_print_ip, &d->c->rem));
  1105. mg_connect_resolved(d->c);
  1106. #if MG_ENABLE_IPV6
  1107. } else if (dm.addr.is_ip6 == false && dm.name[0] != '\0' &&
  1108. c->mgr->use_dns6 == false) {
  1109. struct mg_str x = mg_str(dm.name);
  1110. mg_sendnsreq(d->c, &x, c->mgr->dnstimeout, &c->mgr->dns6, true);
  1111. #endif
  1112. } else {
  1113. mg_error(d->c, "%s DNS lookup failed", dm.name);
  1114. }
  1115. } else {
  1116. MG_ERROR(("%lu already resolved", d->c->id));
  1117. }
  1118. mg_dns_free(head, d);
  1119. resolved = 1;
  1120. }
  1121. }
  1122. if (!resolved) MG_ERROR(("stray DNS reply"));
  1123. c->recv.len = 0;
  1124. } else if (ev == MG_EV_CLOSE) {
  1125. for (d = *head; d != NULL; d = tmp) {
  1126. tmp = d->next;
  1127. mg_error(d->c, "DNS error");
  1128. mg_dns_free(head, d);
  1129. }
  1130. }
  1131. }
  1132. static bool mg_dns_send(struct mg_connection *c, const struct mg_str *name,
  1133. uint16_t txnid, bool ipv6) {
  1134. struct {
  1135. struct mg_dns_header header;
  1136. uint8_t data[256];
  1137. } pkt;
  1138. size_t i, n;
  1139. memset(&pkt, 0, sizeof(pkt));
  1140. pkt.header.txnid = mg_htons(txnid);
  1141. pkt.header.flags = mg_htons(0x100);
  1142. pkt.header.num_questions = mg_htons(1);
  1143. for (i = n = 0; i < sizeof(pkt.data) - 5; i++) {
  1144. if (name->buf[i] == '.' || i >= name->len) {
  1145. pkt.data[n] = (uint8_t) (i - n);
  1146. memcpy(&pkt.data[n + 1], name->buf + n, i - n);
  1147. n = i + 1;
  1148. }
  1149. if (i >= name->len) break;
  1150. }
  1151. memcpy(&pkt.data[n], "\x00\x00\x01\x00\x01", 5); // A query
  1152. n += 5;
  1153. if (ipv6) pkt.data[n - 3] = 0x1c; // AAAA query
  1154. // memcpy(&pkt.data[n], "\xc0\x0c\x00\x1c\x00\x01", 6); // AAAA query
  1155. // n += 6;
  1156. return mg_send(c, &pkt, sizeof(pkt.header) + n);
  1157. }
  1158. static void mg_sendnsreq(struct mg_connection *c, struct mg_str *name, int ms,
  1159. struct mg_dns *dnsc, bool ipv6) {
  1160. struct dns_data *d = NULL;
  1161. if (dnsc->url == NULL) {
  1162. mg_error(c, "DNS server URL is NULL. Call mg_mgr_init()");
  1163. } else if (dnsc->c == NULL) {
  1164. dnsc->c = mg_connect(c->mgr, dnsc->url, NULL, NULL);
  1165. if (dnsc->c != NULL) {
  1166. dnsc->c->pfn = dns_cb;
  1167. // dnsc->c->is_hexdumping = 1;
  1168. }
  1169. }
  1170. if (dnsc->c == NULL) {
  1171. mg_error(c, "resolver");
  1172. } else if ((d = (struct dns_data *) calloc(1, sizeof(*d))) == NULL) {
  1173. mg_error(c, "resolve OOM");
  1174. } else {
  1175. struct dns_data *reqs = (struct dns_data *) c->mgr->active_dns_requests;
  1176. d->txnid = reqs ? (uint16_t) (reqs->txnid + 1) : 1;
  1177. d->next = (struct dns_data *) c->mgr->active_dns_requests;
  1178. c->mgr->active_dns_requests = d;
  1179. d->expire = mg_millis() + (uint64_t) ms;
  1180. d->c = c;
  1181. c->is_resolving = 1;
  1182. MG_VERBOSE(("%lu resolving %.*s @ %s, txnid %hu", c->id, (int) name->len,
  1183. name->buf, dnsc->url, d->txnid));
  1184. if (!mg_dns_send(dnsc->c, name, d->txnid, ipv6)) {
  1185. mg_error(dnsc->c, "DNS send");
  1186. }
  1187. }
  1188. }
  1189. void mg_resolve(struct mg_connection *c, const char *url) {
  1190. struct mg_str host = mg_url_host(url);
  1191. c->rem.port = mg_htons(mg_url_port(url));
  1192. if (mg_aton(host, &c->rem)) {
  1193. // host is an IP address, do not fire name resolution
  1194. mg_connect_resolved(c);
  1195. } else {
  1196. // host is not an IP, send DNS resolution request
  1197. struct mg_dns *dns = c->mgr->use_dns6 ? &c->mgr->dns6 : &c->mgr->dns4;
  1198. mg_sendnsreq(c, &host, c->mgr->dnstimeout, dns, c->mgr->use_dns6);
  1199. }
  1200. }
  1201. #ifdef MG_ENABLE_LINES
  1202. #line 1 "src/event.c"
  1203. #endif
  1204. void mg_call(struct mg_connection *c, int ev, void *ev_data) {
  1205. #if MG_ENABLE_PROFILE
  1206. const char *names[] = {
  1207. "EV_ERROR", "EV_OPEN", "EV_POLL", "EV_RESOLVE",
  1208. "EV_CONNECT", "EV_ACCEPT", "EV_TLS_HS", "EV_READ",
  1209. "EV_WRITE", "EV_CLOSE", "EV_HTTP_MSG", "EV_HTTP_CHUNK",
  1210. "EV_WS_OPEN", "EV_WS_MSG", "EV_WS_CTL", "EV_MQTT_CMD",
  1211. "EV_MQTT_MSG", "EV_MQTT_OPEN", "EV_SNTP_TIME", "EV_USER"};
  1212. if (ev != MG_EV_POLL && ev < (int) (sizeof(names) / sizeof(names[0]))) {
  1213. MG_PROF_ADD(c, names[ev]);
  1214. }
  1215. #endif
  1216. // Fire protocol handler first, user handler second. See #2559
  1217. if (c->pfn != NULL) c->pfn(c, ev, ev_data);
  1218. if (c->fn != NULL) c->fn(c, ev, ev_data);
  1219. }
  1220. void mg_error(struct mg_connection *c, const char *fmt, ...) {
  1221. char buf[64];
  1222. va_list ap;
  1223. va_start(ap, fmt);
  1224. mg_vsnprintf(buf, sizeof(buf), fmt, &ap);
  1225. va_end(ap);
  1226. MG_ERROR(("%lu %ld %s", c->id, c->fd, buf));
  1227. c->is_closing = 1; // Set is_closing before sending MG_EV_CALL
  1228. mg_call(c, MG_EV_ERROR, buf); // Let user handler override it
  1229. }
  1230. #ifdef MG_ENABLE_LINES
  1231. #line 1 "src/fmt.c"
  1232. #endif
  1233. static bool is_digit(int c) {
  1234. return c >= '0' && c <= '9';
  1235. }
  1236. static int addexp(char *buf, int e, int sign) {
  1237. int n = 0;
  1238. buf[n++] = 'e';
  1239. buf[n++] = (char) sign;
  1240. if (e > 400) return 0;
  1241. if (e < 10) buf[n++] = '0';
  1242. if (e >= 100) buf[n++] = (char) (e / 100 + '0'), e -= 100 * (e / 100);
  1243. if (e >= 10) buf[n++] = (char) (e / 10 + '0'), e -= 10 * (e / 10);
  1244. buf[n++] = (char) (e + '0');
  1245. return n;
  1246. }
  1247. static int xisinf(double x) {
  1248. union {
  1249. double f;
  1250. uint64_t u;
  1251. } ieee754 = {x};
  1252. return ((unsigned) (ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
  1253. ((unsigned) ieee754.u == 0);
  1254. }
  1255. static int xisnan(double x) {
  1256. union {
  1257. double f;
  1258. uint64_t u;
  1259. } ieee754 = {x};
  1260. return ((unsigned) (ieee754.u >> 32) & 0x7fffffff) +
  1261. ((unsigned) ieee754.u != 0) >
  1262. 0x7ff00000;
  1263. }
  1264. static size_t mg_dtoa(char *dst, size_t dstlen, double d, int width, bool tz) {
  1265. char buf[40];
  1266. int i, s = 0, n = 0, e = 0;
  1267. double t, mul, saved;
  1268. if (d == 0.0) return mg_snprintf(dst, dstlen, "%s", "0");
  1269. if (xisinf(d)) return mg_snprintf(dst, dstlen, "%s", d > 0 ? "inf" : "-inf");
  1270. if (xisnan(d)) return mg_snprintf(dst, dstlen, "%s", "nan");
  1271. if (d < 0.0) d = -d, buf[s++] = '-';
  1272. // Round
  1273. saved = d;
  1274. mul = 1.0;
  1275. while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0;
  1276. while (d <= 1.0 && d / mul <= 1.0) mul /= 10.0;
  1277. for (i = 0, t = mul * 5; i < width; i++) t /= 10.0;
  1278. d += t;
  1279. // Calculate exponent, and 'mul' for scientific representation
  1280. mul = 1.0;
  1281. while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0, e++;
  1282. while (d < 1.0 && d / mul < 1.0) mul /= 10.0, e--;
  1283. // printf(" --> %g %d %g %g\n", saved, e, t, mul);
  1284. if (e >= width && width > 1) {
  1285. n = (int) mg_dtoa(buf, sizeof(buf), saved / mul, width, tz);
  1286. // printf(" --> %.*g %d [%.*s]\n", 10, d / t, e, n, buf);
  1287. n += addexp(buf + s + n, e, '+');
  1288. return mg_snprintf(dst, dstlen, "%.*s", n, buf);
  1289. } else if (e <= -width && width > 1) {
  1290. n = (int) mg_dtoa(buf, sizeof(buf), saved / mul, width, tz);
  1291. // printf(" --> %.*g %d [%.*s]\n", 10, d / mul, e, n, buf);
  1292. n += addexp(buf + s + n, -e, '-');
  1293. return mg_snprintf(dst, dstlen, "%.*s", n, buf);
  1294. } else {
  1295. for (i = 0, t = mul; t >= 1.0 && s + n < (int) sizeof(buf); i++) {
  1296. int ch = (int) (d / t);
  1297. if (n > 0 || ch > 0) buf[s + n++] = (char) (ch + '0');
  1298. d -= ch * t;
  1299. t /= 10.0;
  1300. }
  1301. // printf(" --> [%g] -> %g %g (%d) [%.*s]\n", saved, d, t, n, s + n, buf);
  1302. if (n == 0) buf[s++] = '0';
  1303. while (t >= 1.0 && n + s < (int) sizeof(buf)) buf[n++] = '0', t /= 10.0;
  1304. if (s + n < (int) sizeof(buf)) buf[n + s++] = '.';
  1305. // printf(" 1--> [%g] -> [%.*s]\n", saved, s + n, buf);
  1306. for (i = 0, t = 0.1; s + n < (int) sizeof(buf) && n < width; i++) {
  1307. int ch = (int) (d / t);
  1308. buf[s + n++] = (char) (ch + '0');
  1309. d -= ch * t;
  1310. t /= 10.0;
  1311. }
  1312. }
  1313. while (tz && n > 0 && buf[s + n - 1] == '0') n--; // Trim trailing zeroes
  1314. if (n > 0 && buf[s + n - 1] == '.') n--; // Trim trailing dot
  1315. n += s;
  1316. if (n >= (int) sizeof(buf)) n = (int) sizeof(buf) - 1;
  1317. buf[n] = '\0';
  1318. return mg_snprintf(dst, dstlen, "%s", buf);
  1319. }
  1320. static size_t mg_lld(char *buf, int64_t val, bool is_signed, bool is_hex) {
  1321. const char *letters = "0123456789abcdef";
  1322. uint64_t v = (uint64_t) val;
  1323. size_t s = 0, n, i;
  1324. if (is_signed && val < 0) buf[s++] = '-', v = (uint64_t) (-val);
  1325. // This loop prints a number in reverse order. I guess this is because we
  1326. // write numbers from right to left: least significant digit comes last.
  1327. // Maybe because we use Arabic numbers, and Arabs write RTL?
  1328. if (is_hex) {
  1329. for (n = 0; v; v >>= 4) buf[s + n++] = letters[v & 15];
  1330. } else {
  1331. for (n = 0; v; v /= 10) buf[s + n++] = letters[v % 10];
  1332. }
  1333. // Reverse a string
  1334. for (i = 0; i < n / 2; i++) {
  1335. char t = buf[s + i];
  1336. buf[s + i] = buf[s + n - i - 1], buf[s + n - i - 1] = t;
  1337. }
  1338. if (val == 0) buf[n++] = '0'; // Handle special case
  1339. return n + s;
  1340. }
  1341. static size_t scpy(void (*out)(char, void *), void *ptr, char *buf,
  1342. size_t len) {
  1343. size_t i = 0;
  1344. while (i < len && buf[i] != '\0') out(buf[i++], ptr);
  1345. return i;
  1346. }
  1347. size_t mg_xprintf(void (*out)(char, void *), void *ptr, const char *fmt, ...) {
  1348. size_t len = 0;
  1349. va_list ap;
  1350. va_start(ap, fmt);
  1351. len = mg_vxprintf(out, ptr, fmt, &ap);
  1352. va_end(ap);
  1353. return len;
  1354. }
  1355. size_t mg_vxprintf(void (*out)(char, void *), void *param, const char *fmt,
  1356. va_list *ap) {
  1357. size_t i = 0, n = 0;
  1358. while (fmt[i] != '\0') {
  1359. if (fmt[i] == '%') {
  1360. size_t j, k, x = 0, is_long = 0, w = 0 /* width */, pr = ~0U /* prec */;
  1361. char pad = ' ', minus = 0, c = fmt[++i];
  1362. if (c == '#') x++, c = fmt[++i];
  1363. if (c == '-') minus++, c = fmt[++i];
  1364. if (c == '0') pad = '0', c = fmt[++i];
  1365. while (is_digit(c)) w *= 10, w += (size_t) (c - '0'), c = fmt[++i];
  1366. if (c == '.') {
  1367. c = fmt[++i];
  1368. if (c == '*') {
  1369. pr = (size_t) va_arg(*ap, int);
  1370. c = fmt[++i];
  1371. } else {
  1372. pr = 0;
  1373. while (is_digit(c)) pr *= 10, pr += (size_t) (c - '0'), c = fmt[++i];
  1374. }
  1375. }
  1376. while (c == 'h') c = fmt[++i]; // Treat h and hh as int
  1377. if (c == 'l') {
  1378. is_long++, c = fmt[++i];
  1379. if (c == 'l') is_long++, c = fmt[++i];
  1380. }
  1381. if (c == 'p') x = 1, is_long = 1;
  1382. if (c == 'd' || c == 'u' || c == 'x' || c == 'X' || c == 'p' ||
  1383. c == 'g' || c == 'f') {
  1384. bool s = (c == 'd'), h = (c == 'x' || c == 'X' || c == 'p');
  1385. char tmp[40];
  1386. size_t xl = x ? 2 : 0;
  1387. if (c == 'g' || c == 'f') {
  1388. double v = va_arg(*ap, double);
  1389. if (pr == ~0U) pr = 6;
  1390. k = mg_dtoa(tmp, sizeof(tmp), v, (int) pr, c == 'g');
  1391. } else if (is_long == 2) {
  1392. int64_t v = va_arg(*ap, int64_t);
  1393. k = mg_lld(tmp, v, s, h);
  1394. } else if (is_long == 1) {
  1395. long v = va_arg(*ap, long);
  1396. k = mg_lld(tmp, s ? (int64_t) v : (int64_t) (unsigned long) v, s, h);
  1397. } else {
  1398. int v = va_arg(*ap, int);
  1399. k = mg_lld(tmp, s ? (int64_t) v : (int64_t) (unsigned) v, s, h);
  1400. }
  1401. for (j = 0; j < xl && w > 0; j++) w--;
  1402. for (j = 0; pad == ' ' && !minus && k < w && j + k < w; j++)
  1403. n += scpy(out, param, &pad, 1);
  1404. n += scpy(out, param, (char *) "0x", xl);
  1405. for (j = 0; pad == '0' && k < w && j + k < w; j++)
  1406. n += scpy(out, param, &pad, 1);
  1407. n += scpy(out, param, tmp, k);
  1408. for (j = 0; pad == ' ' && minus && k < w && j + k < w; j++)
  1409. n += scpy(out, param, &pad, 1);
  1410. } else if (c == 'm' || c == 'M') {
  1411. mg_pm_t f = va_arg(*ap, mg_pm_t);
  1412. if (c == 'm') out('"', param);
  1413. n += f(out, param, ap);
  1414. if (c == 'm') n += 2, out('"', param);
  1415. } else if (c == 'c') {
  1416. int ch = va_arg(*ap, int);
  1417. out((char) ch, param);
  1418. n++;
  1419. } else if (c == 's') {
  1420. char *p = va_arg(*ap, char *);
  1421. if (pr == ~0U) pr = p == NULL ? 0 : strlen(p);
  1422. for (j = 0; !minus && pr < w && j + pr < w; j++)
  1423. n += scpy(out, param, &pad, 1);
  1424. n += scpy(out, param, p, pr);
  1425. for (j = 0; minus && pr < w && j + pr < w; j++)
  1426. n += scpy(out, param, &pad, 1);
  1427. } else if (c == '%') {
  1428. out('%', param);
  1429. n++;
  1430. } else {
  1431. out('%', param);
  1432. out(c, param);
  1433. n += 2;
  1434. }
  1435. i++;
  1436. } else {
  1437. out(fmt[i], param), n++, i++;
  1438. }
  1439. }
  1440. return n;
  1441. }
  1442. #ifdef MG_ENABLE_LINES
  1443. #line 1 "src/fs.c"
  1444. #endif
  1445. struct mg_fd *mg_fs_open(struct mg_fs *fs, const char *path, int flags) {
  1446. struct mg_fd *fd = (struct mg_fd *) calloc(1, sizeof(*fd));
  1447. if (fd != NULL) {
  1448. fd->fd = fs->op(path, flags);
  1449. fd->fs = fs;
  1450. if (fd->fd == NULL) {
  1451. free(fd);
  1452. fd = NULL;
  1453. }
  1454. }
  1455. return fd;
  1456. }
  1457. void mg_fs_close(struct mg_fd *fd) {
  1458. if (fd != NULL) {
  1459. fd->fs->cl(fd->fd);
  1460. free(fd);
  1461. }
  1462. }
  1463. struct mg_str mg_file_read(struct mg_fs *fs, const char *path) {
  1464. struct mg_str result = {NULL, 0};
  1465. void *fp;
  1466. fs->st(path, &result.len, NULL);
  1467. if ((fp = fs->op(path, MG_FS_READ)) != NULL) {
  1468. result.buf = (char *) calloc(1, result.len + 1);
  1469. if (result.buf != NULL &&
  1470. fs->rd(fp, (void *) result.buf, result.len) != result.len) {
  1471. free((void *) result.buf);
  1472. result.buf = NULL;
  1473. }
  1474. fs->cl(fp);
  1475. }
  1476. if (result.buf == NULL) result.len = 0;
  1477. return result;
  1478. }
  1479. bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
  1480. size_t len) {
  1481. bool result = false;
  1482. struct mg_fd *fd;
  1483. char tmp[MG_PATH_MAX];
  1484. mg_snprintf(tmp, sizeof(tmp), "%s..%d", path, rand());
  1485. if ((fd = mg_fs_open(fs, tmp, MG_FS_WRITE)) != NULL) {
  1486. result = fs->wr(fd->fd, buf, len) == len;
  1487. mg_fs_close(fd);
  1488. if (result) {
  1489. fs->rm(path);
  1490. fs->mv(tmp, path);
  1491. } else {
  1492. fs->rm(tmp);
  1493. }
  1494. }
  1495. return result;
  1496. }
  1497. bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...) {
  1498. va_list ap;
  1499. char *data;
  1500. bool result = false;
  1501. va_start(ap, fmt);
  1502. data = mg_vmprintf(fmt, &ap);
  1503. va_end(ap);
  1504. result = mg_file_write(fs, path, data, strlen(data));
  1505. free(data);
  1506. return result;
  1507. }
  1508. // This helper function allows to scan a filesystem in a sequential way,
  1509. // without using callback function:
  1510. // char buf[100] = "";
  1511. // while (mg_fs_ls(&mg_fs_posix, "./", buf, sizeof(buf))) {
  1512. // ...
  1513. static void mg_fs_ls_fn(const char *filename, void *param) {
  1514. struct mg_str *s = (struct mg_str *) param;
  1515. if (s->buf[0] == '\0') {
  1516. mg_snprintf((char *) s->buf, s->len, "%s", filename);
  1517. } else if (strcmp(s->buf, filename) == 0) {
  1518. ((char *) s->buf)[0] = '\0'; // Fetch next file
  1519. }
  1520. }
  1521. bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len) {
  1522. struct mg_str s = {buf, len};
  1523. fs->ls(path, mg_fs_ls_fn, &s);
  1524. return buf[0] != '\0';
  1525. }
  1526. #ifdef MG_ENABLE_LINES
  1527. #line 1 "src/fs_fat.c"
  1528. #endif
  1529. #if MG_ENABLE_FATFS
  1530. #include <ff.h>
  1531. static int mg_days_from_epoch(int y, int m, int d) {
  1532. y -= m <= 2;
  1533. int era = y / 400;
  1534. int yoe = y - era * 400;
  1535. int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
  1536. int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  1537. return era * 146097 + doe - 719468;
  1538. }
  1539. static time_t mg_timegm(const struct tm *t) {
  1540. int year = t->tm_year + 1900;
  1541. int month = t->tm_mon; // 0-11
  1542. if (month > 11) {
  1543. year += month / 12;
  1544. month %= 12;
  1545. } else if (month < 0) {
  1546. int years_diff = (11 - month) / 12;
  1547. year -= years_diff;
  1548. month += 12 * years_diff;
  1549. }
  1550. int x = mg_days_from_epoch(year, month + 1, t->tm_mday);
  1551. return 60 * (60 * (24L * x + t->tm_hour) + t->tm_min) + t->tm_sec;
  1552. }
  1553. static time_t ff_time_to_epoch(uint16_t fdate, uint16_t ftime) {
  1554. struct tm tm;
  1555. memset(&tm, 0, sizeof(struct tm));
  1556. tm.tm_sec = (ftime << 1) & 0x3e;
  1557. tm.tm_min = ((ftime >> 5) & 0x3f);
  1558. tm.tm_hour = ((ftime >> 11) & 0x1f);
  1559. tm.tm_mday = (fdate & 0x1f);
  1560. tm.tm_mon = ((fdate >> 5) & 0x0f) - 1;
  1561. tm.tm_year = ((fdate >> 9) & 0x7f) + 80;
  1562. return mg_timegm(&tm);
  1563. }
  1564. static int ff_stat(const char *path, size_t *size, time_t *mtime) {
  1565. FILINFO fi;
  1566. if (path[0] == '\0') {
  1567. if (size) *size = 0;
  1568. if (mtime) *mtime = 0;
  1569. return MG_FS_DIR;
  1570. } else if (f_stat(path, &fi) == 0) {
  1571. if (size) *size = (size_t) fi.fsize;
  1572. if (mtime) *mtime = ff_time_to_epoch(fi.fdate, fi.ftime);
  1573. return MG_FS_READ | MG_FS_WRITE | ((fi.fattrib & AM_DIR) ? MG_FS_DIR : 0);
  1574. } else {
  1575. return 0;
  1576. }
  1577. }
  1578. static void ff_list(const char *dir, void (*fn)(const char *, void *),
  1579. void *userdata) {
  1580. DIR d;
  1581. FILINFO fi;
  1582. if (f_opendir(&d, dir) == FR_OK) {
  1583. while (f_readdir(&d, &fi) == FR_OK && fi.fname[0] != '\0') {
  1584. if (!strcmp(fi.fname, ".") || !strcmp(fi.fname, "..")) continue;
  1585. fn(fi.fname, userdata);
  1586. }
  1587. f_closedir(&d);
  1588. }
  1589. }
  1590. static void *ff_open(const char *path, int flags) {
  1591. FIL f;
  1592. unsigned char mode = FA_READ;
  1593. if (flags & MG_FS_WRITE) mode |= FA_WRITE | FA_OPEN_ALWAYS | FA_OPEN_APPEND;
  1594. if (f_open(&f, path, mode) == 0) {
  1595. FIL *fp;
  1596. if ((fp = calloc(1, sizeof(*fp))) != NULL) {
  1597. memcpy(fp, &f, sizeof(*fp));
  1598. return fp;
  1599. }
  1600. }
  1601. return NULL;
  1602. }
  1603. static void ff_close(void *fp) {
  1604. if (fp != NULL) {
  1605. f_close((FIL *) fp);
  1606. free(fp);
  1607. }
  1608. }
  1609. static size_t ff_read(void *fp, void *buf, size_t len) {
  1610. UINT n = 0, misalign = ((size_t) buf) & 3;
  1611. if (misalign) {
  1612. char aligned[4];
  1613. f_read((FIL *) fp, aligned, len > misalign ? misalign : len, &n);
  1614. memcpy(buf, aligned, n);
  1615. } else {
  1616. f_read((FIL *) fp, buf, len, &n);
  1617. }
  1618. return n;
  1619. }
  1620. static size_t ff_write(void *fp, const void *buf, size_t len) {
  1621. UINT n = 0;
  1622. return f_write((FIL *) fp, (char *) buf, len, &n) == FR_OK ? n : 0;
  1623. }
  1624. static size_t ff_seek(void *fp, size_t offset) {
  1625. f_lseek((FIL *) fp, offset);
  1626. return offset;
  1627. }
  1628. static bool ff_rename(const char *from, const char *to) {
  1629. return f_rename(from, to) == FR_OK;
  1630. }
  1631. static bool ff_remove(const char *path) {
  1632. return f_unlink(path) == FR_OK;
  1633. }
  1634. static bool ff_mkdir(const char *path) {
  1635. return f_mkdir(path) == FR_OK;
  1636. }
  1637. struct mg_fs mg_fs_fat = {ff_stat, ff_list, ff_open, ff_close, ff_read,
  1638. ff_write, ff_seek, ff_rename, ff_remove, ff_mkdir};
  1639. #endif
  1640. #ifdef MG_ENABLE_LINES
  1641. #line 1 "src/fs_packed.c"
  1642. #endif
  1643. struct packed_file {
  1644. const char *data;
  1645. size_t size;
  1646. size_t pos;
  1647. };
  1648. #if MG_ENABLE_PACKED_FS
  1649. #else
  1650. const char *mg_unpack(const char *path, size_t *size, time_t *mtime) {
  1651. *size = 0, *mtime = 0;
  1652. (void) path;
  1653. return NULL;
  1654. }
  1655. const char *mg_unlist(size_t no) {
  1656. (void) no;
  1657. return NULL;
  1658. }
  1659. #endif
  1660. struct mg_str mg_unpacked(const char *path) {
  1661. size_t len = 0;
  1662. const char *buf = mg_unpack(path, &len, NULL);
  1663. return mg_str_n(buf, len);
  1664. }
  1665. static int is_dir_prefix(const char *prefix, size_t n, const char *path) {
  1666. // MG_INFO(("[%.*s] [%s] %c", (int) n, prefix, path, path[n]));
  1667. return n < strlen(path) && strncmp(prefix, path, n) == 0 &&
  1668. (n == 0 || path[n] == '/' || path[n - 1] == '/');
  1669. }
  1670. static int packed_stat(const char *path, size_t *size, time_t *mtime) {
  1671. const char *p;
  1672. size_t i, n = strlen(path);
  1673. if (mg_unpack(path, size, mtime)) return MG_FS_READ; // Regular file
  1674. // Scan all files. If `path` is a dir prefix for any of them, it's a dir
  1675. for (i = 0; (p = mg_unlist(i)) != NULL; i++) {
  1676. if (is_dir_prefix(path, n, p)) return MG_FS_DIR;
  1677. }
  1678. return 0;
  1679. }
  1680. static void packed_list(const char *dir, void (*fn)(const char *, void *),
  1681. void *userdata) {
  1682. char buf[MG_PATH_MAX], tmp[sizeof(buf)];
  1683. const char *path, *begin, *end;
  1684. size_t i, n = strlen(dir);
  1685. tmp[0] = '\0'; // Previously listed entry
  1686. for (i = 0; (path = mg_unlist(i)) != NULL; i++) {
  1687. if (!is_dir_prefix(dir, n, path)) continue;
  1688. begin = &path[n + 1];
  1689. end = strchr(begin, '/');
  1690. if (end == NULL) end = begin + strlen(begin);
  1691. mg_snprintf(buf, sizeof(buf), "%.*s", (int) (end - begin), begin);
  1692. buf[sizeof(buf) - 1] = '\0';
  1693. // If this entry has been already listed, skip
  1694. // NOTE: we're assuming that file list is sorted alphabetically
  1695. if (strcmp(buf, tmp) == 0) continue;
  1696. fn(buf, userdata); // Not yet listed, call user function
  1697. strcpy(tmp, buf); // And save this entry as listed
  1698. }
  1699. }
  1700. static void *packed_open(const char *path, int flags) {
  1701. size_t size = 0;
  1702. const char *data = mg_unpack(path, &size, NULL);
  1703. struct packed_file *fp = NULL;
  1704. if (data == NULL) return NULL;
  1705. if (flags & MG_FS_WRITE) return NULL;
  1706. if ((fp = (struct packed_file *) calloc(1, sizeof(*fp))) != NULL) {
  1707. fp->size = size;
  1708. fp->data = data;
  1709. }
  1710. return (void *) fp;
  1711. }
  1712. static void packed_close(void *fp) {
  1713. if (fp != NULL) free(fp);
  1714. }
  1715. static size_t packed_read(void *fd, void *buf, size_t len) {
  1716. struct packed_file *fp = (struct packed_file *) fd;
  1717. if (fp->pos + len > fp->size) len = fp->size - fp->pos;
  1718. memcpy(buf, &fp->data[fp->pos], len);
  1719. fp->pos += len;
  1720. return len;
  1721. }
  1722. static size_t packed_write(void *fd, const void *buf, size_t len) {
  1723. (void) fd, (void) buf, (void) len;
  1724. return 0;
  1725. }
  1726. static size_t packed_seek(void *fd, size_t offset) {
  1727. struct packed_file *fp = (struct packed_file *) fd;
  1728. fp->pos = offset;
  1729. if (fp->pos > fp->size) fp->pos = fp->size;
  1730. return fp->pos;
  1731. }
  1732. static bool packed_rename(const char *from, const char *to) {
  1733. (void) from, (void) to;
  1734. return false;
  1735. }
  1736. static bool packed_remove(const char *path) {
  1737. (void) path;
  1738. return false;
  1739. }
  1740. static bool packed_mkdir(const char *path) {
  1741. (void) path;
  1742. return false;
  1743. }
  1744. struct mg_fs mg_fs_packed = {
  1745. packed_stat, packed_list, packed_open, packed_close, packed_read,
  1746. packed_write, packed_seek, packed_rename, packed_remove, packed_mkdir};
  1747. #ifdef MG_ENABLE_LINES
  1748. #line 1 "src/fs_posix.c"
  1749. #endif
  1750. #if MG_ENABLE_POSIX_FS
  1751. #ifndef MG_STAT_STRUCT
  1752. #define MG_STAT_STRUCT stat
  1753. #endif
  1754. #ifndef MG_STAT_FUNC
  1755. #define MG_STAT_FUNC stat
  1756. #endif
  1757. static int p_stat(const char *path, size_t *size, time_t *mtime) {
  1758. #if !defined(S_ISDIR)
  1759. MG_ERROR(("stat() API is not supported. %p %p %p", path, size, mtime));
  1760. return 0;
  1761. #else
  1762. #if MG_ARCH == MG_ARCH_WIN32
  1763. struct _stati64 st;
  1764. wchar_t tmp[MG_PATH_MAX];
  1765. MultiByteToWideChar(CP_UTF8, 0, path, -1, tmp, sizeof(tmp) / sizeof(tmp[0]));
  1766. if (_wstati64(tmp, &st) != 0) return 0;
  1767. // If path is a symlink, windows reports 0 in st.st_size.
  1768. // Get a real file size by opening it and jumping to the end
  1769. if (st.st_size == 0 && (st.st_mode & _S_IFREG)) {
  1770. FILE *fp = _wfopen(tmp, L"rb");
  1771. if (fp != NULL) {
  1772. fseek(fp, 0, SEEK_END);
  1773. if (ftell(fp) > 0) st.st_size = ftell(fp); // Use _ftelli64 on win10+
  1774. fclose(fp);
  1775. }
  1776. }
  1777. #else
  1778. struct MG_STAT_STRUCT st;
  1779. if (MG_STAT_FUNC(path, &st) != 0) return 0;
  1780. #endif
  1781. if (size) *size = (size_t) st.st_size;
  1782. if (mtime) *mtime = st.st_mtime;
  1783. return MG_FS_READ | MG_FS_WRITE | (S_ISDIR(st.st_mode) ? MG_FS_DIR : 0);
  1784. #endif
  1785. }
  1786. #if MG_ARCH == MG_ARCH_WIN32
  1787. struct dirent {
  1788. char d_name[MAX_PATH];
  1789. };
  1790. typedef struct win32_dir {
  1791. HANDLE handle;
  1792. WIN32_FIND_DATAW info;
  1793. struct dirent result;
  1794. } DIR;
  1795. #if 0
  1796. int gettimeofday(struct timeval *tv, void *tz) {
  1797. FILETIME ft;
  1798. unsigned __int64 tmpres = 0;
  1799. if (tv != NULL) {
  1800. GetSystemTimeAsFileTime(&ft);
  1801. tmpres |= ft.dwHighDateTime;
  1802. tmpres <<= 32;
  1803. tmpres |= ft.dwLowDateTime;
  1804. tmpres /= 10; // convert into microseconds
  1805. tmpres -= (int64_t) 11644473600000000;
  1806. tv->tv_sec = (long) (tmpres / 1000000UL);
  1807. tv->tv_usec = (long) (tmpres % 1000000UL);
  1808. }
  1809. (void) tz;
  1810. return 0;
  1811. }
  1812. #endif
  1813. static int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1814. int ret;
  1815. char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
  1816. strncpy(buf, path, sizeof(buf));
  1817. buf[sizeof(buf) - 1] = '\0';
  1818. // Trim trailing slashes. Leave backslash for paths like "X:\"
  1819. p = buf + strlen(buf) - 1;
  1820. while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
  1821. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1822. ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1823. // Convert back to Unicode. If doubly-converted string does not match the
  1824. // original, something is fishy, reject.
  1825. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1826. NULL, NULL);
  1827. if (strcmp(buf, buf2) != 0) {
  1828. wbuf[0] = L'\0';
  1829. ret = 0;
  1830. }
  1831. return ret;
  1832. }
  1833. DIR *opendir(const char *name) {
  1834. DIR *d = NULL;
  1835. wchar_t wpath[MAX_PATH];
  1836. DWORD attrs;
  1837. if (name == NULL) {
  1838. SetLastError(ERROR_BAD_ARGUMENTS);
  1839. } else if ((d = (DIR *) calloc(1, sizeof(*d))) == NULL) {
  1840. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1841. } else {
  1842. to_wchar(name, wpath, sizeof(wpath) / sizeof(wpath[0]));
  1843. attrs = GetFileAttributesW(wpath);
  1844. if (attrs != 0Xffffffff && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1845. (void) wcscat(wpath, L"\\*");
  1846. d->handle = FindFirstFileW(wpath, &d->info);
  1847. d->result.d_name[0] = '\0';
  1848. } else {
  1849. free(d);
  1850. d = NULL;
  1851. }
  1852. }
  1853. return d;
  1854. }
  1855. int closedir(DIR *d) {
  1856. int result = 0;
  1857. if (d != NULL) {
  1858. if (d->handle != INVALID_HANDLE_VALUE)
  1859. result = FindClose(d->handle) ? 0 : -1;
  1860. free(d);
  1861. } else {
  1862. result = -1;
  1863. SetLastError(ERROR_BAD_ARGUMENTS);
  1864. }
  1865. return result;
  1866. }
  1867. struct dirent *readdir(DIR *d) {
  1868. struct dirent *result = NULL;
  1869. if (d != NULL) {
  1870. memset(&d->result, 0, sizeof(d->result));
  1871. if (d->handle != INVALID_HANDLE_VALUE) {
  1872. result = &d->result;
  1873. WideCharToMultiByte(CP_UTF8, 0, d->info.cFileName, -1, result->d_name,
  1874. sizeof(result->d_name), NULL, NULL);
  1875. if (!FindNextFileW(d->handle, &d->info)) {
  1876. FindClose(d->handle);
  1877. d->handle = INVALID_HANDLE_VALUE;
  1878. }
  1879. } else {
  1880. SetLastError(ERROR_FILE_NOT_FOUND);
  1881. }
  1882. } else {
  1883. SetLastError(ERROR_BAD_ARGUMENTS);
  1884. }
  1885. return result;
  1886. }
  1887. #endif
  1888. static void p_list(const char *dir, void (*fn)(const char *, void *),
  1889. void *userdata) {
  1890. #if MG_ENABLE_DIRLIST
  1891. struct dirent *dp;
  1892. DIR *dirp;
  1893. if ((dirp = (opendir(dir))) == NULL) return;
  1894. while ((dp = readdir(dirp)) != NULL) {
  1895. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
  1896. fn(dp->d_name, userdata);
  1897. }
  1898. closedir(dirp);
  1899. #else
  1900. (void) dir, (void) fn, (void) userdata;
  1901. #endif
  1902. }
  1903. static void *p_open(const char *path, int flags) {
  1904. #if MG_ARCH == MG_ARCH_WIN32
  1905. const char *mode = flags == MG_FS_READ ? "rb" : "a+b";
  1906. wchar_t b1[MG_PATH_MAX], b2[10];
  1907. MultiByteToWideChar(CP_UTF8, 0, path, -1, b1, sizeof(b1) / sizeof(b1[0]));
  1908. MultiByteToWideChar(CP_UTF8, 0, mode, -1, b2, sizeof(b2) / sizeof(b2[0]));
  1909. return (void *) _wfopen(b1, b2);
  1910. #else
  1911. const char *mode = flags == MG_FS_READ ? "rbe" : "a+be"; // e for CLOEXEC
  1912. return (void *) fopen(path, mode);
  1913. #endif
  1914. }
  1915. static void p_close(void *fp) {
  1916. fclose((FILE *) fp);
  1917. }
  1918. static size_t p_read(void *fp, void *buf, size_t len) {
  1919. return fread(buf, 1, len, (FILE *) fp);
  1920. }
  1921. static size_t p_write(void *fp, const void *buf, size_t len) {
  1922. return fwrite(buf, 1, len, (FILE *) fp);
  1923. }
  1924. static size_t p_seek(void *fp, size_t offset) {
  1925. #if (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64) || \
  1926. (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) || \
  1927. (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
  1928. if (fseeko((FILE *) fp, (off_t) offset, SEEK_SET) != 0) (void) 0;
  1929. #else
  1930. if (fseek((FILE *) fp, (long) offset, SEEK_SET) != 0) (void) 0;
  1931. #endif
  1932. return (size_t) ftell((FILE *) fp);
  1933. }
  1934. static bool p_rename(const char *from, const char *to) {
  1935. return rename(from, to) == 0;
  1936. }
  1937. static bool p_remove(const char *path) {
  1938. return remove(path) == 0;
  1939. }
  1940. static bool p_mkdir(const char *path) {
  1941. return mkdir(path, 0775) == 0;
  1942. }
  1943. #else
  1944. static int p_stat(const char *path, size_t *size, time_t *mtime) {
  1945. (void) path, (void) size, (void) mtime;
  1946. return 0;
  1947. }
  1948. static void p_list(const char *path, void (*fn)(const char *, void *),
  1949. void *userdata) {
  1950. (void) path, (void) fn, (void) userdata;
  1951. }
  1952. static void *p_open(const char *path, int flags) {
  1953. (void) path, (void) flags;
  1954. return NULL;
  1955. }
  1956. static void p_close(void *fp) {
  1957. (void) fp;
  1958. }
  1959. static size_t p_read(void *fd, void *buf, size_t len) {
  1960. (void) fd, (void) buf, (void) len;
  1961. return 0;
  1962. }
  1963. static size_t p_write(void *fd, const void *buf, size_t len) {
  1964. (void) fd, (void) buf, (void) len;
  1965. return 0;
  1966. }
  1967. static size_t p_seek(void *fd, size_t offset) {
  1968. (void) fd, (void) offset;
  1969. return (size_t) ~0;
  1970. }
  1971. static bool p_rename(const char *from, const char *to) {
  1972. (void) from, (void) to;
  1973. return false;
  1974. }
  1975. static bool p_remove(const char *path) {
  1976. (void) path;
  1977. return false;
  1978. }
  1979. static bool p_mkdir(const char *path) {
  1980. (void) path;
  1981. return false;
  1982. }
  1983. #endif
  1984. struct mg_fs mg_fs_posix = {p_stat, p_list, p_open, p_close, p_read,
  1985. p_write, p_seek, p_rename, p_remove, p_mkdir};
  1986. #ifdef MG_ENABLE_LINES
  1987. #line 1 "src/http.c"
  1988. #endif
  1989. static int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  1990. int diff = 0;
  1991. if (len > 0) do {
  1992. int c = *s1++, d = *s2++;
  1993. if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
  1994. if (d >= 'A' && d <= 'Z') d += 'a' - 'A';
  1995. diff = c - d;
  1996. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1997. return diff;
  1998. }
  1999. bool mg_to_size_t(struct mg_str str, size_t *val);
  2000. bool mg_to_size_t(struct mg_str str, size_t *val) {
  2001. size_t i = 0, max = (size_t) -1, max2 = max / 10, result = 0, ndigits = 0;
  2002. while (i < str.len && (str.buf[i] == ' ' || str.buf[i] == '\t')) i++;
  2003. if (i < str.len && str.buf[i] == '-') return false;
  2004. while (i < str.len && str.buf[i] >= '0' && str.buf[i] <= '9') {
  2005. size_t digit = (size_t) (str.buf[i] - '0');
  2006. if (result > max2) return false; // Overflow
  2007. result *= 10;
  2008. if (result > max - digit) return false; // Overflow
  2009. result += digit;
  2010. i++, ndigits++;
  2011. }
  2012. while (i < str.len && (str.buf[i] == ' ' || str.buf[i] == '\t')) i++;
  2013. if (ndigits == 0) return false; // #2322: Content-Length = 1 * DIGIT
  2014. if (i != str.len) return false; // Ditto
  2015. *val = (size_t) result;
  2016. return true;
  2017. }
  2018. // Chunk deletion marker is the MSB in the "processed" counter
  2019. #define MG_DMARK ((size_t) 1 << (sizeof(size_t) * 8 - 1))
  2020. // Multipart POST example:
  2021. // --xyz
  2022. // Content-Disposition: form-data; name="val"
  2023. //
  2024. // abcdef
  2025. // --xyz
  2026. // Content-Disposition: form-data; name="foo"; filename="a.txt"
  2027. // Content-Type: text/plain
  2028. //
  2029. // hello world
  2030. //
  2031. // --xyz--
  2032. size_t mg_http_next_multipart(struct mg_str body, size_t ofs,
  2033. struct mg_http_part *part) {
  2034. struct mg_str cd = mg_str_n("Content-Disposition", 19);
  2035. const char *s = body.buf;
  2036. size_t b = ofs, h1, h2, b1, b2, max = body.len;
  2037. // Init part params
  2038. if (part != NULL) part->name = part->filename = part->body = mg_str_n(0, 0);
  2039. // Skip boundary
  2040. while (b + 2 < max && s[b] != '\r' && s[b + 1] != '\n') b++;
  2041. if (b <= ofs || b + 2 >= max) return 0;
  2042. // MG_INFO(("B: %zu %zu [%.*s]", ofs, b - ofs, (int) (b - ofs), s));
  2043. // Skip headers
  2044. h1 = h2 = b + 2;
  2045. for (;;) {
  2046. while (h2 + 2 < max && s[h2] != '\r' && s[h2 + 1] != '\n') h2++;
  2047. if (h2 == h1) break;
  2048. if (h2 + 2 >= max) return 0;
  2049. // MG_INFO(("Header: [%.*s]", (int) (h2 - h1), &s[h1]));
  2050. if (part != NULL && h1 + cd.len + 2 < h2 && s[h1 + cd.len] == ':' &&
  2051. mg_ncasecmp(&s[h1], cd.buf, cd.len) == 0) {
  2052. struct mg_str v = mg_str_n(&s[h1 + cd.len + 2], h2 - (h1 + cd.len + 2));
  2053. part->name = mg_http_get_header_var(v, mg_str_n("name", 4));
  2054. part->filename = mg_http_get_header_var(v, mg_str_n("filename", 8));
  2055. }
  2056. h1 = h2 = h2 + 2;
  2057. }
  2058. b1 = b2 = h2 + 2;
  2059. while (b2 + 2 + (b - ofs) + 2 < max && !(s[b2] == '\r' && s[b2 + 1] == '\n' &&
  2060. memcmp(&s[b2 + 2], s, b - ofs) == 0))
  2061. b2++;
  2062. if (b2 + 2 >= max) return 0;
  2063. if (part != NULL) part->body = mg_str_n(&s[b1], b2 - b1);
  2064. // MG_INFO(("Body: [%.*s]", (int) (b2 - b1), &s[b1]));
  2065. return b2 + 2;
  2066. }
  2067. void mg_http_bauth(struct mg_connection *c, const char *user,
  2068. const char *pass) {
  2069. struct mg_str u = mg_str(user), p = mg_str(pass);
  2070. size_t need = c->send.len + 36 + (u.len + p.len) * 2;
  2071. if (c->send.size < need) mg_iobuf_resize(&c->send, need);
  2072. if (c->send.size >= need) {
  2073. size_t i, n = 0;
  2074. char *buf = (char *) &c->send.buf[c->send.len];
  2075. memcpy(buf, "Authorization: Basic ", 21); // DON'T use mg_send!
  2076. for (i = 0; i < u.len; i++) {
  2077. n = mg_base64_update(((unsigned char *) u.buf)[i], buf + 21, n);
  2078. }
  2079. if (p.len > 0) {
  2080. n = mg_base64_update(':', buf + 21, n);
  2081. for (i = 0; i < p.len; i++) {
  2082. n = mg_base64_update(((unsigned char *) p.buf)[i], buf + 21, n);
  2083. }
  2084. }
  2085. n = mg_base64_final(buf + 21, n);
  2086. c->send.len += 21 + (size_t) n + 2;
  2087. memcpy(&c->send.buf[c->send.len - 2], "\r\n", 2);
  2088. } else {
  2089. MG_ERROR(("%lu oom %d->%d ", c->id, (int) c->send.size, (int) need));
  2090. }
  2091. }
  2092. struct mg_str mg_http_var(struct mg_str buf, struct mg_str name) {
  2093. struct mg_str entry, k, v, result = mg_str_n(NULL, 0);
  2094. while (mg_span(buf, &entry, &buf, '&')) {
  2095. if (mg_span(entry, &k, &v, '=') && name.len == k.len &&
  2096. mg_ncasecmp(name.buf, k.buf, k.len) == 0) {
  2097. result = v;
  2098. break;
  2099. }
  2100. }
  2101. return result;
  2102. }
  2103. int mg_http_get_var(const struct mg_str *buf, const char *name, char *dst,
  2104. size_t dst_len) {
  2105. int len;
  2106. if (dst != NULL && dst_len > 0) {
  2107. dst[0] = '\0'; // If destination buffer is valid, always nul-terminate it
  2108. }
  2109. if (dst == NULL || dst_len == 0) {
  2110. len = -2; // Bad destination
  2111. } else if (buf->buf == NULL || name == NULL || buf->len == 0) {
  2112. len = -1; // Bad source
  2113. } else {
  2114. struct mg_str v = mg_http_var(*buf, mg_str(name));
  2115. if (v.buf == NULL) {
  2116. len = -4; // Name does not exist
  2117. } else {
  2118. len = mg_url_decode(v.buf, v.len, dst, dst_len, 1);
  2119. if (len < 0) len = -3; // Failed to decode
  2120. }
  2121. }
  2122. return len;
  2123. }
  2124. static bool isx(int c) {
  2125. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  2126. (c >= 'A' && c <= 'F');
  2127. }
  2128. int mg_url_decode(const char *src, size_t src_len, char *dst, size_t dst_len,
  2129. int is_form_url_encoded) {
  2130. size_t i, j;
  2131. for (i = j = 0; i < src_len && j + 1 < dst_len; i++, j++) {
  2132. if (src[i] == '%') {
  2133. // Use `i + 2 < src_len`, not `i < src_len - 2`, note small src_len
  2134. if (i + 2 < src_len && isx(src[i + 1]) && isx(src[i + 2])) {
  2135. mg_str_to_num(mg_str_n(src + i + 1, 2), 16, &dst[j], sizeof(uint8_t));
  2136. i += 2;
  2137. } else {
  2138. return -1;
  2139. }
  2140. } else if (is_form_url_encoded && src[i] == '+') {
  2141. dst[j] = ' ';
  2142. } else {
  2143. dst[j] = src[i];
  2144. }
  2145. }
  2146. if (j < dst_len) dst[j] = '\0'; // Null-terminate the destination
  2147. return i >= src_len && j < dst_len ? (int) j : -1;
  2148. }
  2149. static bool isok(uint8_t c) {
  2150. return c == '\n' || c == '\r' || c >= ' ';
  2151. }
  2152. int mg_http_get_request_len(const unsigned char *buf, size_t buf_len) {
  2153. size_t i;
  2154. for (i = 0; i < buf_len; i++) {
  2155. if (!isok(buf[i])) return -1;
  2156. if ((i > 0 && buf[i] == '\n' && buf[i - 1] == '\n') ||
  2157. (i > 3 && buf[i] == '\n' && buf[i - 1] == '\r' && buf[i - 2] == '\n'))
  2158. return (int) i + 1;
  2159. }
  2160. return 0;
  2161. }
  2162. struct mg_str *mg_http_get_header(struct mg_http_message *h, const char *name) {
  2163. size_t i, n = strlen(name), max = sizeof(h->headers) / sizeof(h->headers[0]);
  2164. for (i = 0; i < max && h->headers[i].name.len > 0; i++) {
  2165. struct mg_str *k = &h->headers[i].name, *v = &h->headers[i].value;
  2166. if (n == k->len && mg_ncasecmp(k->buf, name, n) == 0) return v;
  2167. }
  2168. return NULL;
  2169. }
  2170. // Is it a valid utf-8 continuation byte
  2171. static bool vcb(uint8_t c) {
  2172. return (c & 0xc0) == 0x80;
  2173. }
  2174. // Get character length (valid utf-8). Used to parse method, URI, headers
  2175. static size_t clen(const char *s, const char *end) {
  2176. const unsigned char *u = (unsigned char *) s, c = *u;
  2177. long n = (long) (end - s);
  2178. if (c > ' ' && c < '~') return 1; // Usual ascii printed char
  2179. if ((c & 0xe0) == 0xc0 && n > 1 && vcb(u[1])) return 2; // 2-byte UTF8
  2180. if ((c & 0xf0) == 0xe0 && n > 2 && vcb(u[1]) && vcb(u[2])) return 3;
  2181. if ((c & 0xf8) == 0xf0 && n > 3 && vcb(u[1]) && vcb(u[2]) && vcb(u[3]))
  2182. return 4;
  2183. return 0;
  2184. }
  2185. // Skip until the newline. Return advanced `s`, or NULL on error
  2186. static const char *skiptorn(const char *s, const char *end, struct mg_str *v) {
  2187. v->buf = (char *) s;
  2188. while (s < end && s[0] != '\n' && s[0] != '\r') s++, v->len++; // To newline
  2189. if (s >= end || (s[0] == '\r' && s[1] != '\n')) return NULL; // Stray \r
  2190. if (s < end && s[0] == '\r') s++; // Skip \r
  2191. if (s >= end || *s++ != '\n') return NULL; // Skip \n
  2192. return s;
  2193. }
  2194. static bool mg_http_parse_headers(const char *s, const char *end,
  2195. struct mg_http_header *h, size_t max_hdrs) {
  2196. size_t i, n;
  2197. for (i = 0; i < max_hdrs; i++) {
  2198. struct mg_str k = {NULL, 0}, v = {NULL, 0};
  2199. if (s >= end) return false;
  2200. if (s[0] == '\n' || (s[0] == '\r' && s[1] == '\n')) break;
  2201. k.buf = (char *) s;
  2202. while (s < end && s[0] != ':' && (n = clen(s, end)) > 0) s += n, k.len += n;
  2203. if (k.len == 0) return false; // Empty name
  2204. if (s >= end || clen(s, end) == 0) return false; // Invalid UTF-8
  2205. if (*s++ != ':') return false; // Invalid, not followed by :
  2206. // if (clen(s, end) == 0) return false; // Invalid UTF-8
  2207. while (s < end && s[0] == ' ') s++; // Skip spaces
  2208. if ((s = skiptorn(s, end, &v)) == NULL) return false;
  2209. while (v.len > 0 && v.buf[v.len - 1] == ' ') v.len--; // Trim spaces
  2210. // MG_INFO(("--HH [%.*s] [%.*s]", (int) k.len, k.buf, (int) v.len, v.buf));
  2211. h[i].name = k, h[i].value = v; // Success. Assign values
  2212. }
  2213. return true;
  2214. }
  2215. int mg_http_parse(const char *s, size_t len, struct mg_http_message *hm) {
  2216. int is_response, req_len = mg_http_get_request_len((unsigned char *) s, len);
  2217. const char *end = s == NULL ? NULL : s + req_len, *qs; // Cannot add to NULL
  2218. const struct mg_str *cl;
  2219. size_t n;
  2220. memset(hm, 0, sizeof(*hm));
  2221. if (req_len <= 0) return req_len;
  2222. hm->message.buf = hm->head.buf = (char *) s;
  2223. hm->body.buf = (char *) end;
  2224. hm->head.len = (size_t) req_len;
  2225. hm->message.len = hm->body.len = (size_t) -1; // Set body length to infinite
  2226. // Parse request line
  2227. hm->method.buf = (char *) s;
  2228. while (s < end && (n = clen(s, end)) > 0) s += n, hm->method.len += n;
  2229. while (s < end && s[0] == ' ') s++; // Skip spaces
  2230. hm->uri.buf = (char *) s;
  2231. while (s < end && (n = clen(s, end)) > 0) s += n, hm->uri.len += n;
  2232. while (s < end && s[0] == ' ') s++; // Skip spaces
  2233. if ((s = skiptorn(s, end, &hm->proto)) == NULL) return false;
  2234. // If URI contains '?' character, setup query string
  2235. if ((qs = (const char *) memchr(hm->uri.buf, '?', hm->uri.len)) != NULL) {
  2236. hm->query.buf = (char *) qs + 1;
  2237. hm->query.len = (size_t) (&hm->uri.buf[hm->uri.len] - (qs + 1));
  2238. hm->uri.len = (size_t) (qs - hm->uri.buf);
  2239. }
  2240. // Sanity check. Allow protocol/reason to be empty
  2241. // Do this check after hm->method.len and hm->uri.len are finalised
  2242. if (hm->method.len == 0 || hm->uri.len == 0) return -1;
  2243. if (!mg_http_parse_headers(s, end, hm->headers,
  2244. sizeof(hm->headers) / sizeof(hm->headers[0])))
  2245. return -1; // error when parsing
  2246. if ((cl = mg_http_get_header(hm, "Content-Length")) != NULL) {
  2247. if (mg_to_size_t(*cl, &hm->body.len) == false) return -1;
  2248. hm->message.len = (size_t) req_len + hm->body.len;
  2249. }
  2250. // mg_http_parse() is used to parse both HTTP requests and HTTP
  2251. // responses. If HTTP response does not have Content-Length set, then
  2252. // body is read until socket is closed, i.e. body.len is infinite (~0).
  2253. //
  2254. // For HTTP requests though, according to
  2255. // http://tools.ietf.org/html/rfc7231#section-8.1.3,
  2256. // only POST and PUT methods have defined body semantics.
  2257. // Therefore, if Content-Length is not specified and methods are
  2258. // not one of PUT or POST, set body length to 0.
  2259. //
  2260. // So, if it is HTTP request, and Content-Length is not set,
  2261. // and method is not (PUT or POST) then reset body length to zero.
  2262. is_response = mg_ncasecmp(hm->method.buf, "HTTP/", 5) == 0;
  2263. if (hm->body.len == (size_t) ~0 && !is_response &&
  2264. mg_strcasecmp(hm->method, mg_str("PUT")) != 0 &&
  2265. mg_strcasecmp(hm->method, mg_str("POST")) != 0) {
  2266. hm->body.len = 0;
  2267. hm->message.len = (size_t) req_len;
  2268. }
  2269. // The 204 (No content) responses also have 0 body length
  2270. if (hm->body.len == (size_t) ~0 && is_response &&
  2271. mg_strcasecmp(hm->uri, mg_str("204")) == 0) {
  2272. hm->body.len = 0;
  2273. hm->message.len = (size_t) req_len;
  2274. }
  2275. if (hm->message.len < (size_t) req_len) return -1; // Overflow protection
  2276. return req_len;
  2277. }
  2278. static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt,
  2279. va_list *ap) {
  2280. size_t len = c->send.len;
  2281. mg_send(c, " \r\n", 10);
  2282. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  2283. if (c->send.len >= len + 10) {
  2284. mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10);
  2285. c->send.buf[len + 8] = '\r';
  2286. if (c->send.len == len + 10) c->is_resp = 0; // Last chunk, reset marker
  2287. }
  2288. mg_send(c, "\r\n", 2);
  2289. }
  2290. void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) {
  2291. va_list ap;
  2292. va_start(ap, fmt);
  2293. mg_http_vprintf_chunk(c, fmt, &ap);
  2294. va_end(ap);
  2295. }
  2296. void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) {
  2297. mg_printf(c, "%lx\r\n", (unsigned long) len);
  2298. mg_send(c, buf, len);
  2299. mg_send(c, "\r\n", 2);
  2300. if (len == 0) c->is_resp = 0;
  2301. }
  2302. // clang-format off
  2303. static const char *mg_http_status_code_str(int status_code) {
  2304. switch (status_code) {
  2305. case 100: return "Continue";
  2306. case 101: return "Switching Protocols";
  2307. case 102: return "Processing";
  2308. case 200: return "OK";
  2309. case 201: return "Created";
  2310. case 202: return "Accepted";
  2311. case 203: return "Non-authoritative Information";
  2312. case 204: return "No Content";
  2313. case 205: return "Reset Content";
  2314. case 206: return "Partial Content";
  2315. case 207: return "Multi-Status";
  2316. case 208: return "Already Reported";
  2317. case 226: return "IM Used";
  2318. case 300: return "Multiple Choices";
  2319. case 301: return "Moved Permanently";
  2320. case 302: return "Found";
  2321. case 303: return "See Other";
  2322. case 304: return "Not Modified";
  2323. case 305: return "Use Proxy";
  2324. case 307: return "Temporary Redirect";
  2325. case 308: return "Permanent Redirect";
  2326. case 400: return "Bad Request";
  2327. case 401: return "Unauthorized";
  2328. case 402: return "Payment Required";
  2329. case 403: return "Forbidden";
  2330. case 404: return "Not Found";
  2331. case 405: return "Method Not Allowed";
  2332. case 406: return "Not Acceptable";
  2333. case 407: return "Proxy Authentication Required";
  2334. case 408: return "Request Timeout";
  2335. case 409: return "Conflict";
  2336. case 410: return "Gone";
  2337. case 411: return "Length Required";
  2338. case 412: return "Precondition Failed";
  2339. case 413: return "Payload Too Large";
  2340. case 414: return "Request-URI Too Long";
  2341. case 415: return "Unsupported Media Type";
  2342. case 416: return "Requested Range Not Satisfiable";
  2343. case 417: return "Expectation Failed";
  2344. case 418: return "I'm a teapot";
  2345. case 421: return "Misdirected Request";
  2346. case 422: return "Unprocessable Entity";
  2347. case 423: return "Locked";
  2348. case 424: return "Failed Dependency";
  2349. case 426: return "Upgrade Required";
  2350. case 428: return "Precondition Required";
  2351. case 429: return "Too Many Requests";
  2352. case 431: return "Request Header Fields Too Large";
  2353. case 444: return "Connection Closed Without Response";
  2354. case 451: return "Unavailable For Legal Reasons";
  2355. case 499: return "Client Closed Request";
  2356. case 500: return "Internal Server Error";
  2357. case 501: return "Not Implemented";
  2358. case 502: return "Bad Gateway";
  2359. case 503: return "Service Unavailable";
  2360. case 504: return "Gateway Timeout";
  2361. case 505: return "HTTP Version Not Supported";
  2362. case 506: return "Variant Also Negotiates";
  2363. case 507: return "Insufficient Storage";
  2364. case 508: return "Loop Detected";
  2365. case 510: return "Not Extended";
  2366. case 511: return "Network Authentication Required";
  2367. case 599: return "Network Connect Timeout Error";
  2368. default: return "";
  2369. }
  2370. }
  2371. // clang-format on
  2372. void mg_http_reply(struct mg_connection *c, int code, const char *headers,
  2373. const char *fmt, ...) {
  2374. va_list ap;
  2375. size_t len;
  2376. mg_printf(c, "HTTP/1.1 %d %s\r\n%sContent-Length: \r\n\r\n", code,
  2377. mg_http_status_code_str(code), headers == NULL ? "" : headers);
  2378. len = c->send.len;
  2379. va_start(ap, fmt);
  2380. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  2381. va_end(ap);
  2382. if (c->send.len > 16) {
  2383. size_t n = mg_snprintf((char *) &c->send.buf[len - 15], 11, "%-10lu",
  2384. (unsigned long) (c->send.len - len));
  2385. c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space
  2386. }
  2387. c->is_resp = 0;
  2388. }
  2389. int mg_http_reply2(struct mg_connection *c, int code, const char *headers,
  2390. const char *fmt, ...) {
  2391. va_list ap;
  2392. size_t len;
  2393. int r;
  2394. if (c==NULL) return -1;
  2395. mg_printf(c, "HTTP/1.1 %d %s\r\n"
  2396. "Content-Type: text/html\n"
  2397. "Content-Length: %d\n"
  2398. "Connection: Keep-Alive\n"
  2399. "Keep-Alive: timeout=30, max=396\n"
  2400. "X-Content-Type-0ptions: nosniff\n"
  2401. "X-Frame-0ptions:: SAMEORIGIN\n"
  2402. "X-Xss-Protection: 1: mode=block\n"
  2403. "Accept-Ranges: bytes\n"
  2404. "Vary: Accept-Encoding\n\n"
  2405. "%s\n", code, mg_http_status_code_str(code),strlen(fmt == NULL ? "" : fmt), fmt == NULL ? "" : fmt);
  2406. len = c->send.len;
  2407. va_start(ap, fmt);
  2408. r = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt?fmt:"", &ap);
  2409. va_end(ap);
  2410. c->is_resp = 0;
  2411. return r;
  2412. }
  2413. static void http_cb(struct mg_connection *, int, void *);
  2414. static void restore_http_cb(struct mg_connection *c) {
  2415. mg_fs_close((struct mg_fd *) c->pfn_data);
  2416. c->pfn_data = NULL;
  2417. c->pfn = http_cb;
  2418. c->is_resp = 0;
  2419. }
  2420. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
  2421. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime) {
  2422. mg_snprintf(buf, len, "\"%lld.%lld\"", (int64_t) mtime, (int64_t) size);
  2423. return buf;
  2424. }
  2425. static void static_cb(struct mg_connection *c, int ev, void *ev_data) {
  2426. if (ev == MG_EV_WRITE || ev == MG_EV_POLL) {
  2427. struct mg_fd *fd = (struct mg_fd *) c->pfn_data;
  2428. // Read to send IO buffer directly, avoid extra on-stack buffer
  2429. size_t n, max = MG_IO_SIZE, space;
  2430. size_t *cl = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2431. sizeof(size_t) * sizeof(size_t)];
  2432. if (c->send.size < max) mg_iobuf_resize(&c->send, max);
  2433. if (c->send.len >= c->send.size) return; // Rate limit
  2434. if ((space = c->send.size - c->send.len) > *cl) space = *cl;
  2435. n = fd->fs->rd(fd->fd, c->send.buf + c->send.len, space);
  2436. c->send.len += n;
  2437. *cl -= n;
  2438. if (n == 0) restore_http_cb(c);
  2439. } else if (ev == MG_EV_CLOSE) {
  2440. restore_http_cb(c);
  2441. }
  2442. (void) ev_data;
  2443. }
  2444. // Known mime types. Keep it outside guess_content_type() function, since
  2445. // some environments don't like it defined there.
  2446. // clang-format off
  2447. #define MG_C_STR(a) { (char *) (a), sizeof(a) - 1 }
  2448. static struct mg_str s_known_types[] = {
  2449. MG_C_STR("html"), MG_C_STR("text/html; charset=utf-8"),
  2450. MG_C_STR("htm"), MG_C_STR("text/html; charset=utf-8"),
  2451. MG_C_STR("css"), MG_C_STR("text/css; charset=utf-8"),
  2452. MG_C_STR("js"), MG_C_STR("text/javascript; charset=utf-8"),
  2453. MG_C_STR("gif"), MG_C_STR("image/gif"),
  2454. MG_C_STR("png"), MG_C_STR("image/png"),
  2455. MG_C_STR("jpg"), MG_C_STR("image/jpeg"),
  2456. MG_C_STR("jpeg"), MG_C_STR("image/jpeg"),
  2457. MG_C_STR("woff"), MG_C_STR("font/woff"),
  2458. MG_C_STR("ttf"), MG_C_STR("font/ttf"),
  2459. MG_C_STR("svg"), MG_C_STR("image/svg+xml"),
  2460. MG_C_STR("txt"), MG_C_STR("text/plain; charset=utf-8"),
  2461. MG_C_STR("avi"), MG_C_STR("video/x-msvideo"),
  2462. MG_C_STR("csv"), MG_C_STR("text/csv"),
  2463. MG_C_STR("doc"), MG_C_STR("application/msword"),
  2464. MG_C_STR("exe"), MG_C_STR("application/octet-stream"),
  2465. MG_C_STR("gz"), MG_C_STR("application/gzip"),
  2466. MG_C_STR("ico"), MG_C_STR("image/x-icon"),
  2467. MG_C_STR("json"), MG_C_STR("application/json"),
  2468. MG_C_STR("mov"), MG_C_STR("video/quicktime"),
  2469. MG_C_STR("mp3"), MG_C_STR("audio/mpeg"),
  2470. MG_C_STR("mp4"), MG_C_STR("video/mp4"),
  2471. MG_C_STR("mpeg"), MG_C_STR("video/mpeg"),
  2472. MG_C_STR("pdf"), MG_C_STR("application/pdf"),
  2473. MG_C_STR("shtml"), MG_C_STR("text/html; charset=utf-8"),
  2474. MG_C_STR("tgz"), MG_C_STR("application/tar-gz"),
  2475. MG_C_STR("wav"), MG_C_STR("audio/wav"),
  2476. MG_C_STR("webp"), MG_C_STR("image/webp"),
  2477. MG_C_STR("zip"), MG_C_STR("application/zip"),
  2478. MG_C_STR("3gp"), MG_C_STR("video/3gpp"),
  2479. {0, 0},
  2480. };
  2481. // clang-format on
  2482. static struct mg_str guess_content_type(struct mg_str path, const char *extra) {
  2483. struct mg_str entry, k, v, s = mg_str(extra);
  2484. size_t i = 0;
  2485. // Shrink path to its extension only
  2486. while (i < path.len && path.buf[path.len - i - 1] != '.') i++;
  2487. path.buf += path.len - i;
  2488. path.len = i;
  2489. // Process user-provided mime type overrides, if any
  2490. while (mg_span(s, &entry, &s, ',')) {
  2491. if (mg_span(entry, &k, &v, '=') && mg_strcmp(path, k) == 0) return v;
  2492. }
  2493. // Process built-in mime types
  2494. for (i = 0; s_known_types[i].buf != NULL; i += 2) {
  2495. if (mg_strcmp(path, s_known_types[i]) == 0) return s_known_types[i + 1];
  2496. }
  2497. return mg_str("text/plain; charset=utf-8");
  2498. }
  2499. static int getrange(struct mg_str *s, size_t *a, size_t *b) {
  2500. size_t i, numparsed = 0;
  2501. for (i = 0; i + 6 < s->len; i++) {
  2502. struct mg_str k, v = mg_str_n(s->buf + i + 6, s->len - i - 6);
  2503. if (memcmp(&s->buf[i], "bytes=", 6) != 0) continue;
  2504. if (mg_span(v, &k, &v, '-')) {
  2505. if (mg_to_size_t(k, a)) numparsed++;
  2506. if (v.len > 0 && mg_to_size_t(v, b)) numparsed++;
  2507. } else {
  2508. if (mg_to_size_t(v, a)) numparsed++;
  2509. }
  2510. break;
  2511. }
  2512. return (int) numparsed;
  2513. }
  2514. void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
  2515. const char *path,
  2516. const struct mg_http_serve_opts *opts) {
  2517. char etag[64], tmp[MG_PATH_MAX];
  2518. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2519. struct mg_fd *fd = NULL;
  2520. size_t size = 0;
  2521. time_t mtime = 0;
  2522. struct mg_str *inm = NULL;
  2523. struct mg_str mime = guess_content_type(mg_str(path), opts->mime_types);
  2524. bool gzip = false;
  2525. if (path != NULL) {
  2526. // If a browser sends us "Accept-Encoding: gzip", try to open .gz first
  2527. struct mg_str *ae = mg_http_get_header(hm, "Accept-Encoding");
  2528. if (ae != NULL) {
  2529. char *ae_ = mg_mprintf("%.*s", ae->len, ae->buf);
  2530. if (ae_ != NULL && strstr(ae_, "gzip") != NULL) {
  2531. mg_snprintf(tmp, sizeof(tmp), "%s.gz", path);
  2532. fd = mg_fs_open(fs, tmp, MG_FS_READ);
  2533. if (fd != NULL) gzip = true, path = tmp;
  2534. }
  2535. free(ae_);
  2536. }
  2537. // No luck opening .gz? Open what we've told to open
  2538. if (fd == NULL) fd = mg_fs_open(fs, path, MG_FS_READ);
  2539. }
  2540. // Failed to open, and page404 is configured? Open it, then
  2541. if (fd == NULL && opts->page404 != NULL) {
  2542. fd = mg_fs_open(fs, opts->page404, MG_FS_READ);
  2543. path = opts->page404;
  2544. mime = guess_content_type(mg_str(path), opts->mime_types);
  2545. }
  2546. if (fd == NULL || fs->st(path, &size, &mtime) == 0) {
  2547. mg_http_reply(c, 404, opts->extra_headers, "Not found\n");
  2548. mg_fs_close(fd);
  2549. // NOTE: mg_http_etag() call should go first!
  2550. } else if (mg_http_etag(etag, sizeof(etag), size, mtime) != NULL &&
  2551. (inm = mg_http_get_header(hm, "If-None-Match")) != NULL &&
  2552. mg_strcasecmp(*inm, mg_str(etag)) == 0) {
  2553. mg_fs_close(fd);
  2554. mg_http_reply(c, 304, opts->extra_headers, "");
  2555. } else {
  2556. int n, status = 200;
  2557. char range[100];
  2558. size_t r1 = 0, r2 = 0, cl = size;
  2559. // Handle Range header
  2560. struct mg_str *rh = mg_http_get_header(hm, "Range");
  2561. range[0] = '\0';
  2562. if (rh != NULL && (n = getrange(rh, &r1, &r2)) > 0) {
  2563. // If range is specified like "400-", set second limit to content len
  2564. if (n == 1) r2 = cl - 1;
  2565. if (r1 > r2 || r2 >= cl) {
  2566. status = 416;
  2567. cl = 0;
  2568. mg_snprintf(range, sizeof(range), "Content-Range: bytes */%lld\r\n",
  2569. (int64_t) size);
  2570. } else {
  2571. status = 206;
  2572. cl = r2 - r1 + 1;
  2573. mg_snprintf(range, sizeof(range),
  2574. "Content-Range: bytes %llu-%llu/%llu\r\n", (uint64_t) r1,
  2575. (uint64_t) (r1 + cl - 1), (uint64_t) size);
  2576. fs->sk(fd->fd, r1);
  2577. }
  2578. }
  2579. mg_printf(c,
  2580. "HTTP/1.1 %d %s\r\n"
  2581. "Content-Type: %.*s\r\n"
  2582. "Etag: %s\r\n"
  2583. "Content-Length: %llu\r\n"
  2584. "%s%s%s\r\n",
  2585. status, mg_http_status_code_str(status), (int) mime.len, mime.buf,
  2586. etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
  2587. range, opts->extra_headers ? opts->extra_headers : "");
  2588. if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0) {
  2589. c->is_draining = 1;
  2590. c->is_resp = 0;
  2591. mg_fs_close(fd);
  2592. } else {
  2593. // Track to-be-sent content length at the end of c->data, aligned
  2594. size_t *clp = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2595. sizeof(size_t) * sizeof(size_t)];
  2596. c->pfn = static_cb;
  2597. c->pfn_data = fd;
  2598. *clp = cl;
  2599. }
  2600. }
  2601. }
  2602. struct printdirentrydata {
  2603. struct mg_connection *c;
  2604. struct mg_http_message *hm;
  2605. const struct mg_http_serve_opts *opts;
  2606. const char *dir;
  2607. };
  2608. #if MG_ENABLE_DIRLIST
  2609. static void printdirentry(const char *name, void *userdata) {
  2610. struct printdirentrydata *d = (struct printdirentrydata *) userdata;
  2611. struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs;
  2612. size_t size = 0;
  2613. time_t t = 0;
  2614. char path[MG_PATH_MAX], sz[40], mod[40];
  2615. int flags, n = 0;
  2616. // MG_DEBUG(("[%s] [%s]", d->dir, name));
  2617. if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >
  2618. sizeof(path)) {
  2619. MG_ERROR(("%s truncated", name));
  2620. } else if ((flags = fs->st(path, &size, &t)) == 0) {
  2621. MG_ERROR(("%lu stat(%s): %d", d->c->id, path, errno));
  2622. } else {
  2623. const char *slash = flags & MG_FS_DIR ? "/" : "";
  2624. if (flags & MG_FS_DIR) {
  2625. mg_snprintf(sz, sizeof(sz), "%s", "[DIR]");
  2626. } else {
  2627. mg_snprintf(sz, sizeof(sz), "%lld", (uint64_t) size);
  2628. }
  2629. #if defined(MG_HTTP_DIRLIST_TIME_FMT)
  2630. {
  2631. char time_str[40];
  2632. struct tm *time_info = localtime(&t);
  2633. strftime(time_str, sizeof time_str, "%Y/%m/%d %H:%M:%S", time_info);
  2634. mg_snprintf(mod, sizeof(mod), "%s", time_str);
  2635. }
  2636. #else
  2637. mg_snprintf(mod, sizeof(mod), "%lu", (unsigned long) t);
  2638. #endif
  2639. n = (int) mg_url_encode(name, strlen(name), path, sizeof(path));
  2640. mg_printf(d->c,
  2641. " <tr><td><a href=\"%.*s%s\">%s%s</a></td>"
  2642. "<td name=%lu>%s</td><td name=%lld>%s</td></tr>\n",
  2643. n, path, slash, name, slash, (unsigned long) t, mod,
  2644. flags & MG_FS_DIR ? (int64_t) -1 : (int64_t) size, sz);
  2645. }
  2646. }
  2647. static void listdir(struct mg_connection *c, struct mg_http_message *hm,
  2648. const struct mg_http_serve_opts *opts, char *dir) {
  2649. const char *sort_js_code =
  2650. "<script>function srt(tb, sc, so, d) {"
  2651. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  2652. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  2653. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  2654. "t1 = a.cells[2].getAttribute('name'), "
  2655. "t2 = b.cells[2].getAttribute('name'); "
  2656. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  2657. "n1 ? parseInt(n2) - parseInt(n1) : "
  2658. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  2659. const char *sort_js_code2 =
  2660. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  2661. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  2662. "};"
  2663. "window.onload = function() {"
  2664. "var tb = document.getElementById('tb');"
  2665. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  2666. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  2667. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  2668. "sc = c; ev.preventDefault();}};"
  2669. "srt(tb, sc, so, true);"
  2670. "}"
  2671. "</script>";
  2672. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2673. struct printdirentrydata d = {c, hm, opts, dir};
  2674. char tmp[10], buf[MG_PATH_MAX];
  2675. size_t off, n;
  2676. int len = mg_url_decode(hm->uri.buf, hm->uri.len, buf, sizeof(buf), 0);
  2677. struct mg_str uri = len > 0 ? mg_str_n(buf, (size_t) len) : hm->uri;
  2678. mg_printf(c,
  2679. "HTTP/1.1 200 OK\r\n"
  2680. "Content-Type: text/html; charset=utf-8\r\n"
  2681. "%s"
  2682. "Content-Length: \r\n\r\n",
  2683. opts->extra_headers == NULL ? "" : opts->extra_headers);
  2684. off = c->send.len; // Start of body
  2685. mg_printf(c,
  2686. "<!DOCTYPE html><html><head><title>Index of %.*s</title>%s%s"
  2687. "<style>th,td {text-align: left; padding-right: 1em; "
  2688. "font-family: monospace; }</style></head>"
  2689. "<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>"
  2690. "<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
  2691. "<a href=\"#\" rel=\"1\">Modified</a></th>"
  2692. "<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
  2693. "<tr><td colspan=\"3\"><hr></td></tr>"
  2694. "</thead>"
  2695. "<tbody id=\"tb\">\n",
  2696. (int) uri.len, uri.buf, sort_js_code, sort_js_code2, (int) uri.len,
  2697. uri.buf);
  2698. mg_printf(c, "%s",
  2699. " <tr><td><a href=\"..\">..</a></td>"
  2700. "<td name=-1></td><td name=-1>[DIR]</td></tr>\n");
  2701. fs->ls(dir, printdirentry, &d);
  2702. mg_printf(c,
  2703. "</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
  2704. "</table><address>Mongoose v.%s</address></body></html>\n",
  2705. MG_VERSION);
  2706. n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
  2707. if (n > sizeof(tmp)) n = 0;
  2708. memcpy(c->send.buf + off - 12, tmp, n); // Set content length
  2709. c->is_resp = 0; // Mark response end
  2710. }
  2711. #endif
  2712. // Resolve requested file into `path` and return its fs->st() result
  2713. static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
  2714. struct mg_fs *fs, struct mg_str url, struct mg_str dir,
  2715. char *path, size_t path_size) {
  2716. int flags, tmp;
  2717. // Append URI to the root_dir, and sanitize it
  2718. size_t n = mg_snprintf(path, path_size, "%.*s", (int) dir.len, dir.buf);
  2719. if (n + 2 >= path_size) {
  2720. mg_http_reply(c, 400, "", "Exceeded path size");
  2721. return -1;
  2722. }
  2723. path[path_size - 1] = '\0';
  2724. // Terminate root dir with slash
  2725. if (n > 0 && path[n - 1] != '/') path[n++] = '/', path[n] = '\0';
  2726. if (url.len < hm->uri.len) {
  2727. mg_url_decode(hm->uri.buf + url.len, hm->uri.len - url.len, path + n,
  2728. path_size - n, 0);
  2729. }
  2730. path[path_size - 1] = '\0'; // Double-check
  2731. if (!mg_path_is_sane(mg_str_n(path, path_size))) {
  2732. mg_http_reply(c, 400, "", "Invalid path");
  2733. return -1;
  2734. }
  2735. n = strlen(path);
  2736. while (n > 1 && path[n - 1] == '/') path[--n] = 0; // Trim trailing slashes
  2737. flags = mg_strcmp(hm->uri, mg_str("/")) == 0 ? MG_FS_DIR
  2738. : fs->st(path, NULL, NULL);
  2739. MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.buf, path,
  2740. flags));
  2741. if (flags == 0) {
  2742. // Do nothing - let's caller decide
  2743. } else if ((flags & MG_FS_DIR) && hm->uri.len > 0 &&
  2744. hm->uri.buf[hm->uri.len - 1] != '/') {
  2745. mg_printf(c,
  2746. "HTTP/1.1 301 Moved\r\n"
  2747. "Location: %.*s/\r\n"
  2748. "Content-Length: 0\r\n"
  2749. "\r\n",
  2750. (int) hm->uri.len, hm->uri.buf);
  2751. c->is_resp = 0;
  2752. flags = -1;
  2753. } else if (flags & MG_FS_DIR) {
  2754. if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
  2755. (tmp = fs->st(path, NULL, NULL)) != 0) ||
  2756. (mg_snprintf(path + n, path_size - n, "/index.shtml") > 0 &&
  2757. (tmp = fs->st(path, NULL, NULL)) != 0))) {
  2758. flags = tmp;
  2759. } else if ((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX ".gz") >
  2760. 0 &&
  2761. (tmp = fs->st(path, NULL, NULL)) !=
  2762. 0)) { // check for gzipped index
  2763. flags = tmp;
  2764. path[n + 1 + strlen(MG_HTTP_INDEX)] =
  2765. '\0'; // Remove appended .gz in index file name
  2766. } else {
  2767. path[n] = '\0'; // Remove appended index file name
  2768. }
  2769. }
  2770. return flags;
  2771. }
  2772. static int uri_to_path(struct mg_connection *c, struct mg_http_message *hm,
  2773. const struct mg_http_serve_opts *opts, char *path,
  2774. size_t path_size) {
  2775. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2776. struct mg_str k, v, part, s = mg_str(opts->root_dir), u = {NULL, 0}, p = u;
  2777. while (mg_span(s, &part, &s, ',')) {
  2778. if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
  2779. if (v.len == 0) v = k, k = mg_str("/"), u = k, p = v;
  2780. if (hm->uri.len < k.len) continue;
  2781. if (mg_strcmp(k, mg_str_n(hm->uri.buf, k.len)) != 0) continue;
  2782. u = k, p = v;
  2783. }
  2784. return uri_to_path2(c, hm, fs, u, p, path, path_size);
  2785. }
  2786. void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
  2787. const struct mg_http_serve_opts *opts) {
  2788. char path[MG_PATH_MAX];
  2789. const char *sp = opts->ssi_pattern;
  2790. int flags = uri_to_path(c, hm, opts, path, sizeof(path));
  2791. if (flags < 0) {
  2792. // Do nothing: the response has already been sent by uri_to_path()
  2793. } else if (flags & MG_FS_DIR) {
  2794. #if MG_ENABLE_DIRLIST
  2795. listdir(c, hm, opts, path);
  2796. #else
  2797. mg_http_reply(c, 403, "", "Forbidden\n");
  2798. #endif
  2799. } else if (flags && sp != NULL && mg_match(mg_str(path), mg_str(sp), NULL)) {
  2800. mg_http_serve_ssi(c, opts->root_dir, path);
  2801. } else {
  2802. mg_http_serve_file(c, hm, path, opts);
  2803. }
  2804. }
  2805. static bool mg_is_url_safe(int c) {
  2806. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
  2807. (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~';
  2808. }
  2809. size_t mg_url_encode(const char *s, size_t sl, char *buf, size_t len) {
  2810. size_t i, n = 0;
  2811. for (i = 0; i < sl; i++) {
  2812. int c = *(unsigned char *) &s[i];
  2813. if (n + 4 >= len) return 0;
  2814. if (mg_is_url_safe(c)) {
  2815. buf[n++] = s[i];
  2816. } else {
  2817. mg_snprintf(&buf[n], 4, "%%%M", mg_print_hex, 1, &s[i]);
  2818. n += 3;
  2819. }
  2820. }
  2821. if (len > 0 && n < len - 1) buf[n] = '\0'; // Null-terminate the destination
  2822. if (len > 0) buf[len - 1] = '\0'; // Always.
  2823. return n;
  2824. }
  2825. void mg_http_creds(struct mg_http_message *hm, char *user, size_t userlen,
  2826. char *pass, size_t passlen) {
  2827. struct mg_str *v = mg_http_get_header(hm, "Authorization");
  2828. user[0] = pass[0] = '\0';
  2829. if (v != NULL && v->len > 6 && memcmp(v->buf, "Basic ", 6) == 0) {
  2830. char buf[256];
  2831. size_t n = mg_base64_decode(v->buf + 6, v->len - 6, buf, sizeof(buf));
  2832. const char *p = (const char *) memchr(buf, ':', n > 0 ? n : 0);
  2833. if (p != NULL) {
  2834. mg_snprintf(user, userlen, "%.*s", p - buf, buf);
  2835. mg_snprintf(pass, passlen, "%.*s", n - (size_t) (p - buf) - 1, p + 1);
  2836. }
  2837. } else if (v != NULL && v->len > 7 && memcmp(v->buf, "Bearer ", 7) == 0) {
  2838. mg_snprintf(pass, passlen, "%.*s", (int) v->len - 7, v->buf + 7);
  2839. } else if ((v = mg_http_get_header(hm, "Cookie")) != NULL) {
  2840. struct mg_str t = mg_http_get_header_var(*v, mg_str_n("access_token", 12));
  2841. if (t.len > 0) mg_snprintf(pass, passlen, "%.*s", (int) t.len, t.buf);
  2842. } else {
  2843. mg_http_get_var(&hm->query, "access_token", pass, passlen);
  2844. }
  2845. }
  2846. static struct mg_str stripquotes(struct mg_str s) {
  2847. return s.len > 1 && s.buf[0] == '"' && s.buf[s.len - 1] == '"'
  2848. ? mg_str_n(s.buf + 1, s.len - 2)
  2849. : s;
  2850. }
  2851. struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v) {
  2852. size_t i;
  2853. for (i = 0; v.len > 0 && i + v.len + 2 < s.len; i++) {
  2854. if (s.buf[i + v.len] == '=' && memcmp(&s.buf[i], v.buf, v.len) == 0) {
  2855. const char *p = &s.buf[i + v.len + 1], *b = p, *x = &s.buf[s.len];
  2856. int q = p < x && *p == '"' ? 1 : 0;
  2857. while (p < x &&
  2858. (q ? p == b || *p != '"' : *p != ';' && *p != ' ' && *p != ','))
  2859. p++;
  2860. // MG_INFO(("[%.*s] [%.*s] [%.*s]", (int) s.len, s.buf, (int) v.len,
  2861. // v.buf, (int) (p - b), b));
  2862. return stripquotes(mg_str_n(b, (size_t) (p - b + q)));
  2863. }
  2864. }
  2865. return mg_str_n(NULL, 0);
  2866. }
  2867. long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
  2868. struct mg_fs *fs, const char *dir, size_t max_size) {
  2869. char buf[20] = "0", file[MG_PATH_MAX], path[MG_PATH_MAX];
  2870. long res = 0, offset;
  2871. mg_http_get_var(&hm->query, "offset", buf, sizeof(buf));
  2872. mg_http_get_var(&hm->query, "file", file, sizeof(file));
  2873. offset = strtol(buf, NULL, 0);
  2874. mg_snprintf(path, sizeof(path), "%s%c%s", dir, MG_DIRSEP, file);
  2875. if (hm->body.len == 0) {
  2876. mg_http_reply(c, 200, "", "%ld", res); // Nothing to write
  2877. } else if (file[0] == '\0') {
  2878. mg_http_reply(c, 400, "", "file required");
  2879. res = -1;
  2880. } else if (mg_path_is_sane(mg_str(file)) == false) {
  2881. mg_http_reply(c, 400, "", "%s: invalid file", file);
  2882. res = -2;
  2883. } else if (offset < 0) {
  2884. mg_http_reply(c, 400, "", "offset required");
  2885. res = -3;
  2886. } else if ((size_t) offset + hm->body.len > max_size) {
  2887. mg_http_reply(c, 400, "", "%s: over max size of %lu", path,
  2888. (unsigned long) max_size);
  2889. res = -4;
  2890. } else {
  2891. struct mg_fd *fd;
  2892. size_t current_size = 0;
  2893. MG_DEBUG(("%s -> %lu bytes @ %ld", path, hm->body.len, offset));
  2894. if (offset == 0) fs->rm(path); // If offset if 0, truncate file
  2895. fs->st(path, &current_size, NULL);
  2896. if (offset > 0 && current_size != (size_t) offset) {
  2897. mg_http_reply(c, 400, "", "%s: offset mismatch", path);
  2898. res = -5;
  2899. } else if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
  2900. mg_http_reply(c, 400, "", "open(%s): %d", path, errno);
  2901. res = -6;
  2902. } else {
  2903. res = offset + (long) fs->wr(fd->fd, hm->body.buf, hm->body.len);
  2904. mg_fs_close(fd);
  2905. mg_http_reply(c, 200, "", "%ld", res);
  2906. }
  2907. }
  2908. return res;
  2909. }
  2910. int mg_http_status(const struct mg_http_message *hm) {
  2911. return atoi(hm->uri.buf);
  2912. }
  2913. static bool is_hex_digit(int c) {
  2914. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  2915. (c >= 'A' && c <= 'F');
  2916. }
  2917. static int skip_chunk(const char *buf, int len, int *pl, int *dl) {
  2918. int i = 0, n = 0;
  2919. if (len < 3) return 0;
  2920. while (i < len && is_hex_digit(buf[i])) i++;
  2921. if (i == 0) return -1; // Error, no length specified
  2922. if (i > (int) sizeof(int) * 2) return -1; // Chunk length is too big
  2923. if (len < i + 1 || buf[i] != '\r' || buf[i + 1] != '\n') return -1; // Error
  2924. if (mg_str_to_num(mg_str_n(buf, (size_t) i), 16, &n, sizeof(int)) == false)
  2925. return -1; // Decode chunk length, overflow
  2926. if (n < 0) return -1; // Error. TODO(): some checks now redundant
  2927. if (n > len - i - 4) return 0; // Chunk not yet fully buffered
  2928. if (buf[i + n + 2] != '\r' || buf[i + n + 3] != '\n') return -1; // Error
  2929. *pl = i + 2, *dl = n;
  2930. return i + 2 + n + 2;
  2931. }
  2932. static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
  2933. if (ev == MG_EV_READ || ev == MG_EV_CLOSE) {
  2934. struct mg_http_message hm;
  2935. size_t ofs = 0; // Parsing offset
  2936. while (c->is_resp == 0 && ofs < c->recv.len) {
  2937. const char *buf = (char *) c->recv.buf + ofs;
  2938. int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
  2939. struct mg_str *te; // Transfer - encoding header
  2940. bool is_chunked = false;
  2941. if (n < 0) {
  2942. // We don't use mg_error() here, to avoid closing pipelined requests
  2943. // prematurely, see #2592
  2944. MG_ERROR(("HTTP parse, %lu bytes", c->recv.len));
  2945. c->is_draining = 1;
  2946. mg_hexdump(buf, c->recv.len - ofs > 16 ? 16 : c->recv.len - ofs);
  2947. c->recv.len = 0;
  2948. return;
  2949. }
  2950. if (n == 0) break; // Request is not buffered yet
  2951. mg_call(c, MG_EV_HTTP_HDRS, &hm); // Got all HTTP headers
  2952. if (ev == MG_EV_CLOSE) { // If client did not set Content-Length
  2953. hm.message.len = c->recv.len - ofs; // and closes now, deliver MSG
  2954. hm.body.len = hm.message.len - (size_t) (hm.body.buf - hm.message.buf);
  2955. }
  2956. if ((te = mg_http_get_header(&hm, "Transfer-Encoding")) != NULL) {
  2957. if (mg_strcasecmp(*te, mg_str("chunked")) == 0) {
  2958. is_chunked = true;
  2959. } else {
  2960. mg_error(c, "Invalid Transfer-Encoding"); // See #2460
  2961. return;
  2962. }
  2963. } else if (mg_http_get_header(&hm, "Content-length") == NULL) {
  2964. // #2593: HTTP packets must contain either Transfer-Encoding or
  2965. // Content-length
  2966. bool is_response = mg_ncasecmp(hm.method.buf, "HTTP/", 5) == 0;
  2967. bool require_content_len = false;
  2968. if (!is_response && (mg_strcasecmp(hm.method, mg_str("POST")) == 0 ||
  2969. mg_strcasecmp(hm.method, mg_str("PUT")) == 0)) {
  2970. // POST and PUT should include an entity body. Therefore, they should
  2971. // contain a Content-length header. Other requests can also contain a
  2972. // body, but their content has no defined semantics (RFC 7231)
  2973. require_content_len = true;
  2974. } else if (is_response) {
  2975. // HTTP spec 7.2 Entity body: All other responses must include a body
  2976. // or Content-Length header field defined with a value of 0.
  2977. int status = mg_http_status(&hm);
  2978. require_content_len = status >= 200 && status != 204 && status != 304;
  2979. }
  2980. if (require_content_len) {
  2981. mg_http_reply(c, 411, "", "");
  2982. MG_ERROR(("%s", "Content length missing from request"));
  2983. }
  2984. }
  2985. if (is_chunked) {
  2986. // For chunked data, strip off prefixes and suffixes from chunks
  2987. // and relocate them right after the headers, then report a message
  2988. char *s = (char *) c->recv.buf + ofs + n;
  2989. int o = 0, pl, dl, cl, len = (int) (c->recv.len - ofs - (size_t) n);
  2990. // Find zero-length chunk (the end of the body)
  2991. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0 && dl) o += cl;
  2992. if (cl == 0) break; // No zero-len chunk, buffer more data
  2993. if (cl < 0) {
  2994. mg_error(c, "Invalid chunk");
  2995. break;
  2996. }
  2997. // Zero chunk found. Second pass: strip + relocate
  2998. o = 0, hm.body.len = 0, hm.message.len = (size_t) n;
  2999. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0) {
  3000. memmove(s + hm.body.len, s + o + pl, (size_t) dl);
  3001. o += cl, hm.body.len += (size_t) dl, hm.message.len += (size_t) dl;
  3002. if (dl == 0) break;
  3003. }
  3004. ofs += (size_t) (n + o);
  3005. } else { // Normal, non-chunked data
  3006. size_t len = c->recv.len - ofs - (size_t) n;
  3007. if (hm.body.len > len) break; // Buffer more data
  3008. ofs += (size_t) n + hm.body.len;
  3009. }
  3010. if (c->is_accepted) c->is_resp = 1; // Start generating response
  3011. mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp
  3012. }
  3013. if (ofs > 0) mg_iobuf_del(&c->recv, 0, ofs); // Delete processed data
  3014. }
  3015. (void) ev_data;
  3016. }
  3017. static void mg_hfn(struct mg_connection *c, int ev, void *ev_data) {
  3018. if (ev == MG_EV_HTTP_MSG) {
  3019. struct mg_http_message *hm = (struct mg_http_message *) ev_data;
  3020. if (mg_match(hm->uri, mg_str("/quit"), NULL)) {
  3021. mg_http_reply(c, 200, "", "ok\n");
  3022. c->is_draining = 1;
  3023. c->data[0] = 'X';
  3024. } else if (mg_match(hm->uri, mg_str("/debug"), NULL)) {
  3025. int level = (int) mg_json_get_long(hm->body, "$.level", MG_LL_DEBUG);
  3026. mg_log_set(level);
  3027. mg_http_reply(c, 200, "", "Debug level set to %d\n", level);
  3028. } else {
  3029. mg_http_reply(c, 200, "", "hi\n");
  3030. }
  3031. } else if (ev == MG_EV_CLOSE) {
  3032. if (c->data[0] == 'X') *(bool *) c->fn_data = true;
  3033. }
  3034. }
  3035. void mg_hello(const char *url) {
  3036. struct mg_mgr mgr;
  3037. bool done = false;
  3038. mg_mgr_init(&mgr);
  3039. if (mg_http_listen(&mgr, url, mg_hfn, &done) == NULL) done = true;
  3040. while (done == false) mg_mgr_poll(&mgr, 100);
  3041. mg_mgr_free(&mgr);
  3042. }
  3043. struct mg_connection *mg_http_connect(struct mg_mgr *mgr, const char *url,
  3044. mg_event_handler_t fn, void *fn_data) {
  3045. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  3046. if (c != NULL) c->pfn = http_cb;
  3047. return c;
  3048. }
  3049. struct mg_connection *mg_http_listen(struct mg_mgr *mgr, const char *url,
  3050. mg_event_handler_t fn, void *fn_data) {
  3051. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  3052. if (c != NULL) c->pfn = http_cb;
  3053. return c;
  3054. }
  3055. #ifdef MG_ENABLE_LINES
  3056. #line 1 "src/iobuf.c"
  3057. #endif
  3058. static size_t roundup(size_t size, size_t align) {
  3059. return align == 0 ? size : (size + align - 1) / align * align;
  3060. }
  3061. int mg_iobuf_resize(struct mg_iobuf *io, size_t new_size) {
  3062. int ok = 1;
  3063. new_size = roundup(new_size, io->align);
  3064. if (new_size == 0) {
  3065. mg_bzero(io->buf, io->size);
  3066. free(io->buf);
  3067. io->buf = NULL;
  3068. io->len = io->size = 0;
  3069. } else if (new_size != io->size) {
  3070. // NOTE(lsm): do not use realloc here. Use calloc/free only, to ease the
  3071. // porting to some obscure platforms like FreeRTOS
  3072. void *p = calloc(1, new_size);
  3073. if (p != NULL) {
  3074. size_t len = new_size < io->len ? new_size : io->len;
  3075. if (len > 0 && io->buf != NULL) memmove(p, io->buf, len);
  3076. mg_bzero(io->buf, io->size);
  3077. free(io->buf);
  3078. io->buf = (unsigned char *) p;
  3079. io->size = new_size;
  3080. } else {
  3081. ok = 0;
  3082. MG_ERROR(("%lld->%lld", (uint64_t) io->size, (uint64_t) new_size));
  3083. }
  3084. }
  3085. return ok;
  3086. }
  3087. int mg_iobuf_init(struct mg_iobuf *io, size_t size, size_t align) {
  3088. io->buf = NULL;
  3089. io->align = align;
  3090. io->size = io->len = 0;
  3091. return mg_iobuf_resize(io, size);
  3092. }
  3093. size_t mg_iobuf_add(struct mg_iobuf *io, size_t ofs, const void *buf,
  3094. size_t len) {
  3095. size_t new_size = roundup(io->len + len, io->align);
  3096. mg_iobuf_resize(io, new_size); // Attempt to resize
  3097. if (new_size != io->size) len = 0; // Resize failure, append nothing
  3098. if (ofs < io->len) memmove(io->buf + ofs + len, io->buf + ofs, io->len - ofs);
  3099. if (buf != NULL) memmove(io->buf + ofs, buf, len);
  3100. if (ofs > io->len) io->len += ofs - io->len;
  3101. io->len += len;
  3102. return len;
  3103. }
  3104. size_t mg_iobuf_del(struct mg_iobuf *io, size_t ofs, size_t len) {
  3105. if (ofs > io->len) ofs = io->len;
  3106. if (ofs + len > io->len) len = io->len - ofs;
  3107. if (io->buf) memmove(io->buf + ofs, io->buf + ofs + len, io->len - ofs - len);
  3108. if (io->buf) mg_bzero(io->buf + io->len - len, len);
  3109. io->len -= len;
  3110. return len;
  3111. }
  3112. void mg_iobuf_free(struct mg_iobuf *io) {
  3113. mg_iobuf_resize(io, 0);
  3114. }
  3115. #ifdef MG_ENABLE_LINES
  3116. #line 1 "src/json.c"
  3117. #endif
  3118. static const char *escapeseq(int esc) {
  3119. return esc ? "\b\f\n\r\t\\\"" : "bfnrt\\\"";
  3120. }
  3121. static char json_esc(int c, int esc) {
  3122. const char *p, *esc1 = escapeseq(esc), *esc2 = escapeseq(!esc);
  3123. for (p = esc1; *p != '\0'; p++) {
  3124. if (*p == c) return esc2[p - esc1];
  3125. }
  3126. return 0;
  3127. }
  3128. static int mg_pass_string(const char *s, int len) {
  3129. int i;
  3130. for (i = 0; i < len; i++) {
  3131. if (s[i] == '\\' && i + 1 < len && json_esc(s[i + 1], 1)) {
  3132. i++;
  3133. } else if (s[i] == '\0') {
  3134. return MG_JSON_INVALID;
  3135. } else if (s[i] == '"') {
  3136. return i;
  3137. }
  3138. }
  3139. return MG_JSON_INVALID;
  3140. }
  3141. static double mg_atod(const char *p, int len, int *numlen) {
  3142. double d = 0.0;
  3143. int i = 0, sign = 1;
  3144. // Sign
  3145. if (i < len && *p == '-') {
  3146. sign = -1, i++;
  3147. } else if (i < len && *p == '+') {
  3148. i++;
  3149. }
  3150. // Decimal
  3151. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  3152. d *= 10.0;
  3153. d += p[i] - '0';
  3154. }
  3155. d *= sign;
  3156. // Fractional
  3157. if (i < len && p[i] == '.') {
  3158. double frac = 0.0, base = 0.1;
  3159. i++;
  3160. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  3161. frac += base * (p[i] - '0');
  3162. base /= 10.0;
  3163. }
  3164. d += frac * sign;
  3165. }
  3166. // Exponential
  3167. if (i < len && (p[i] == 'e' || p[i] == 'E')) {
  3168. int j, exp = 0, minus = 0;
  3169. i++;
  3170. if (i < len && p[i] == '-') minus = 1, i++;
  3171. if (i < len && p[i] == '+') i++;
  3172. while (i < len && p[i] >= '0' && p[i] <= '9' && exp < 308)
  3173. exp = exp * 10 + (p[i++] - '0');
  3174. if (minus) exp = -exp;
  3175. for (j = 0; j < exp; j++) d *= 10.0;
  3176. for (j = 0; j < -exp; j++) d /= 10.0;
  3177. }
  3178. if (numlen != NULL) *numlen = i;
  3179. return d;
  3180. }
  3181. // Iterate over object or array elements
  3182. size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key,
  3183. struct mg_str *val) {
  3184. if (ofs >= obj.len) {
  3185. ofs = 0; // Out of boundaries, stop scanning
  3186. } else if (obj.len < 2 || (*obj.buf != '{' && *obj.buf != '[')) {
  3187. ofs = 0; // Not an array or object, stop
  3188. } else {
  3189. struct mg_str sub = mg_str_n(obj.buf + ofs, obj.len - ofs);
  3190. if (ofs == 0) ofs++, sub.buf++, sub.len--;
  3191. if (*obj.buf == '[') { // Iterate over an array
  3192. int n = 0, o = mg_json_get(sub, "$", &n);
  3193. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3194. ofs = 0; // Error parsing key, stop scanning
  3195. } else {
  3196. if (key) *key = mg_str_n(NULL, 0);
  3197. if (val) *val = mg_str_n(sub.buf + o, (size_t) n);
  3198. ofs = (size_t) (&sub.buf[o + n] - obj.buf);
  3199. }
  3200. } else { // Iterate over an object
  3201. int n = 0, o = mg_json_get(sub, "$", &n);
  3202. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3203. ofs = 0; // Error parsing key, stop scanning
  3204. } else {
  3205. if (key) *key = mg_str_n(sub.buf + o, (size_t) n);
  3206. sub.buf += o + n, sub.len -= (size_t) (o + n);
  3207. while (sub.len > 0 && *sub.buf != ':') sub.len--, sub.buf++;
  3208. if (sub.len > 0 && *sub.buf == ':') sub.len--, sub.buf++;
  3209. n = 0, o = mg_json_get(sub, "$", &n);
  3210. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3211. ofs = 0; // Error parsing value, stop scanning
  3212. } else {
  3213. if (val) *val = mg_str_n(sub.buf + o, (size_t) n);
  3214. ofs = (size_t) (&sub.buf[o + n] - obj.buf);
  3215. }
  3216. }
  3217. }
  3218. // MG_INFO(("SUB ofs %u %.*s", ofs, sub.len, sub.buf));
  3219. while (ofs && ofs < obj.len &&
  3220. (obj.buf[ofs] == ' ' || obj.buf[ofs] == '\t' ||
  3221. obj.buf[ofs] == '\n' || obj.buf[ofs] == '\r')) {
  3222. ofs++;
  3223. }
  3224. if (ofs && ofs < obj.len && obj.buf[ofs] == ',') ofs++;
  3225. if (ofs > obj.len) ofs = 0;
  3226. }
  3227. return ofs;
  3228. }
  3229. int mg_json_get(struct mg_str json, const char *path, int *toklen) {
  3230. const char *s = json.buf;
  3231. int len = (int) json.len;
  3232. enum { S_VALUE, S_KEY, S_COLON, S_COMMA_OR_EOO } expecting = S_VALUE;
  3233. unsigned char nesting[MG_JSON_MAX_DEPTH];
  3234. int i = 0; // Current offset in `s`
  3235. int j = 0; // Offset in `s` we're looking for (return value)
  3236. int depth = 0; // Current depth (nesting level)
  3237. int ed = 0; // Expected depth
  3238. int pos = 1; // Current position in `path`
  3239. int ci = -1, ei = -1; // Current and expected index in array
  3240. if (toklen) *toklen = 0;
  3241. if (path[0] != '$') return MG_JSON_INVALID;
  3242. #define MG_CHECKRET(x) \
  3243. do { \
  3244. if (depth == ed && path[pos] == '\0' && ci == ei) { \
  3245. if (toklen) *toklen = i - j + 1; \
  3246. return j; \
  3247. } \
  3248. } while (0)
  3249. // In the ascii table, the distance between `[` and `]` is 2.
  3250. // Ditto for `{` and `}`. Hence +2 in the code below.
  3251. #define MG_EOO(x) \
  3252. do { \
  3253. if (depth == ed && ci != ei) return MG_JSON_NOT_FOUND; \
  3254. if (c != nesting[depth - 1] + 2) return MG_JSON_INVALID; \
  3255. depth--; \
  3256. MG_CHECKRET(x); \
  3257. } while (0)
  3258. for (i = 0; i < len; i++) {
  3259. unsigned char c = ((unsigned char *) s)[i];
  3260. if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
  3261. switch (expecting) {
  3262. case S_VALUE:
  3263. // p("V %s [%.*s] %d %d %d %d\n", path, pos, path, depth, ed, ci, ei);
  3264. if (depth == ed) j = i;
  3265. if (c == '{') {
  3266. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  3267. if (depth == ed && path[pos] == '.' && ci == ei) {
  3268. // If we start the object, reset array indices
  3269. ed++, pos++, ci = ei = -1;
  3270. }
  3271. nesting[depth++] = c;
  3272. expecting = S_KEY;
  3273. break;
  3274. } else if (c == '[') {
  3275. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  3276. if (depth == ed && path[pos] == '[' && ei == ci) {
  3277. ed++, pos++, ci = 0;
  3278. for (ei = 0; path[pos] != ']' && path[pos] != '\0'; pos++) {
  3279. ei *= 10;
  3280. ei += path[pos] - '0';
  3281. }
  3282. if (path[pos] != 0) pos++;
  3283. }
  3284. nesting[depth++] = c;
  3285. break;
  3286. } else if (c == ']' && depth > 0) { // Empty array
  3287. MG_EOO(']');
  3288. } else if (c == 't' && i + 3 < len && memcmp(&s[i], "true", 4) == 0) {
  3289. i += 3;
  3290. } else if (c == 'n' && i + 3 < len && memcmp(&s[i], "null", 4) == 0) {
  3291. i += 3;
  3292. } else if (c == 'f' && i + 4 < len && memcmp(&s[i], "false", 5) == 0) {
  3293. i += 4;
  3294. } else if (c == '-' || ((c >= '0' && c <= '9'))) {
  3295. int numlen = 0;
  3296. mg_atod(&s[i], len - i, &numlen);
  3297. i += numlen - 1;
  3298. } else if (c == '"') {
  3299. int n = mg_pass_string(&s[i + 1], len - i - 1);
  3300. if (n < 0) return n;
  3301. i += n + 1;
  3302. } else {
  3303. return MG_JSON_INVALID;
  3304. }
  3305. MG_CHECKRET('V');
  3306. if (depth == ed && ei >= 0) ci++;
  3307. expecting = S_COMMA_OR_EOO;
  3308. break;
  3309. case S_KEY:
  3310. if (c == '"') {
  3311. int n = mg_pass_string(&s[i + 1], len - i - 1);
  3312. if (n < 0) return n;
  3313. if (i + 1 + n >= len) return MG_JSON_NOT_FOUND;
  3314. if (depth < ed) return MG_JSON_NOT_FOUND;
  3315. if (depth == ed && path[pos - 1] != '.') return MG_JSON_NOT_FOUND;
  3316. // printf("K %s [%.*s] [%.*s] %d %d %d %d %d\n", path, pos, path, n,
  3317. // &s[i + 1], n, depth, ed, ci, ei);
  3318. // NOTE(cpq): in the check sequence below is important.
  3319. // strncmp() must go first: it fails fast if the remaining length
  3320. // of the path is smaller than `n`.
  3321. if (depth == ed && path[pos - 1] == '.' &&
  3322. strncmp(&s[i + 1], &path[pos], (size_t) n) == 0 &&
  3323. (path[pos + n] == '\0' || path[pos + n] == '.' ||
  3324. path[pos + n] == '[')) {
  3325. pos += n;
  3326. }
  3327. i += n + 1;
  3328. expecting = S_COLON;
  3329. } else if (c == '}') { // Empty object
  3330. MG_EOO('}');
  3331. expecting = S_COMMA_OR_EOO;
  3332. if (depth == ed && ei >= 0) ci++;
  3333. } else {
  3334. return MG_JSON_INVALID;
  3335. }
  3336. break;
  3337. case S_COLON:
  3338. if (c == ':') {
  3339. expecting = S_VALUE;
  3340. } else {
  3341. return MG_JSON_INVALID;
  3342. }
  3343. break;
  3344. case S_COMMA_OR_EOO:
  3345. if (depth <= 0) {
  3346. return MG_JSON_INVALID;
  3347. } else if (c == ',') {
  3348. expecting = (nesting[depth - 1] == '{') ? S_KEY : S_VALUE;
  3349. } else if (c == ']' || c == '}') {
  3350. if (depth == ed && c == '}' && path[pos - 1] == '.')
  3351. return MG_JSON_NOT_FOUND;
  3352. if (depth == ed && c == ']' && path[pos - 1] == ',')
  3353. return MG_JSON_NOT_FOUND;
  3354. MG_EOO('O');
  3355. if (depth == ed && ei >= 0) ci++;
  3356. } else {
  3357. return MG_JSON_INVALID;
  3358. }
  3359. break;
  3360. }
  3361. }
  3362. return MG_JSON_NOT_FOUND;
  3363. }
  3364. struct mg_str mg_json_get_tok(struct mg_str json, const char *path) {
  3365. int len = 0, ofs = mg_json_get(json, path, &len);
  3366. return mg_str_n(ofs < 0 ? NULL : json.buf + ofs,
  3367. (size_t) (len < 0 ? 0 : len));
  3368. }
  3369. bool mg_json_get_num(struct mg_str json, const char *path, double *v) {
  3370. int n, toklen, found = 0;
  3371. if ((n = mg_json_get(json, path, &toklen)) >= 0 &&
  3372. (json.buf[n] == '-' || (json.buf[n] >= '0' && json.buf[n] <= '9'))) {
  3373. if (v != NULL) *v = mg_atod(json.buf + n, toklen, NULL);
  3374. found = 1;
  3375. }
  3376. return found;
  3377. }
  3378. bool mg_json_get_bool(struct mg_str json, const char *path, bool *v) {
  3379. int found = 0, off = mg_json_get(json, path, NULL);
  3380. if (off >= 0 && (json.buf[off] == 't' || json.buf[off] == 'f')) {
  3381. if (v != NULL) *v = json.buf[off] == 't';
  3382. found = 1;
  3383. }
  3384. return found;
  3385. }
  3386. bool mg_json_unescape(struct mg_str s, char *to, size_t n) {
  3387. size_t i, j;
  3388. for (i = 0, j = 0; i < s.len && j < n; i++, j++) {
  3389. if (s.buf[i] == '\\' && i + 5 < s.len && s.buf[i + 1] == 'u') {
  3390. // \uXXXX escape. We process simple one-byte chars \u00xx within ASCII
  3391. // range. More complex chars would require dragging in a UTF8 library,
  3392. // which is too much for us
  3393. if (mg_str_to_num(mg_str_n(s.buf + i + 2, 4), 16, &to[j],
  3394. sizeof(uint8_t)) == false)
  3395. return false;
  3396. i += 5;
  3397. } else if (s.buf[i] == '\\' && i + 1 < s.len) {
  3398. char c = json_esc(s.buf[i + 1], 0);
  3399. if (c == 0) return false;
  3400. to[j] = c;
  3401. i++;
  3402. } else {
  3403. to[j] = s.buf[i];
  3404. }
  3405. }
  3406. if (j >= n) return false;
  3407. if (n > 0) to[j] = '\0';
  3408. return true;
  3409. }
  3410. char *mg_json_get_str(struct mg_str json, const char *path) {
  3411. char *result = NULL;
  3412. int len = 0, off = mg_json_get(json, path, &len);
  3413. if (off >= 0 && len > 1 && json.buf[off] == '"') {
  3414. if ((result = (char *) calloc(1, (size_t) len)) != NULL &&
  3415. !mg_json_unescape(mg_str_n(json.buf + off + 1, (size_t) (len - 2)),
  3416. result, (size_t) len)) {
  3417. free(result);
  3418. result = NULL;
  3419. }
  3420. }
  3421. return result;
  3422. }
  3423. char *mg_json_get_b64(struct mg_str json, const char *path, int *slen) {
  3424. char *result = NULL;
  3425. int len = 0, off = mg_json_get(json, path, &len);
  3426. if (off >= 0 && json.buf[off] == '"' && len > 1 &&
  3427. (result = (char *) calloc(1, (size_t) len)) != NULL) {
  3428. size_t k = mg_base64_decode(json.buf + off + 1, (size_t) (len - 2), result,
  3429. (size_t) len);
  3430. if (slen != NULL) *slen = (int) k;
  3431. }
  3432. return result;
  3433. }
  3434. char *mg_json_get_hex(struct mg_str json, const char *path, int *slen) {
  3435. char *result = NULL;
  3436. int len = 0, off = mg_json_get(json, path, &len);
  3437. if (off >= 0 && json.buf[off] == '"' && len > 1 &&
  3438. (result = (char *) calloc(1, (size_t) len / 2)) != NULL) {
  3439. int i;
  3440. for (i = 0; i < len - 2; i += 2) {
  3441. mg_str_to_num(mg_str_n(json.buf + off + 1 + i, 2), 16, &result[i >> 1],
  3442. sizeof(uint8_t));
  3443. }
  3444. result[len / 2 - 1] = '\0';
  3445. if (slen != NULL) *slen = len / 2 - 1;
  3446. }
  3447. return result;
  3448. }
  3449. long mg_json_get_long(struct mg_str json, const char *path, long dflt) {
  3450. double dv;
  3451. long result = dflt;
  3452. if (mg_json_get_num(json, path, &dv)) result = (long) dv;
  3453. return result;
  3454. }
  3455. #ifdef MG_ENABLE_LINES
  3456. #line 1 "src/log.c"
  3457. #endif
  3458. int mg_log_level = MG_LL_INFO;
  3459. static mg_pfn_t s_log_func = mg_pfn_stdout;
  3460. static void *s_log_func_param = NULL;
  3461. void mg_log_set_fn(mg_pfn_t fn, void *param) {
  3462. s_log_func = fn;
  3463. s_log_func_param = param;
  3464. }
  3465. static void logc(unsigned char c) {
  3466. s_log_func((char) c, s_log_func_param);
  3467. }
  3468. static void logs(const char *buf, size_t len) {
  3469. size_t i;
  3470. for (i = 0; i < len; i++) logc(((unsigned char *) buf)[i]);
  3471. }
  3472. #if MG_ENABLE_CUSTOM_LOG
  3473. // Let user define their own mg_log_prefix() and mg_log()
  3474. #else
  3475. void mg_log_prefix(int level, const char *file, int line, const char *fname) {
  3476. const char *p = strrchr(file, '/');
  3477. char buf[41];
  3478. size_t n;
  3479. if (p == NULL) p = strrchr(file, '\\');
  3480. n = mg_snprintf(buf, sizeof(buf), "%-6llx %d %s:%d:%s", mg_millis(), level,
  3481. p == NULL ? file : p + 1, line, fname);
  3482. if (n > sizeof(buf) - 2) n = sizeof(buf) - 2;
  3483. while (n < sizeof(buf)) buf[n++] = ' ';
  3484. logs(buf, n - 1);
  3485. }
  3486. void mg_log(const char *fmt, ...) {
  3487. va_list ap;
  3488. va_start(ap, fmt);
  3489. mg_vxprintf(s_log_func, s_log_func_param, fmt, &ap);
  3490. va_end(ap);
  3491. logs("\r\n", 2);
  3492. }
  3493. #endif
  3494. static unsigned char nibble(unsigned c) {
  3495. return (unsigned char) (c < 10 ? c + '0' : c + 'W');
  3496. }
  3497. #define ISPRINT(x) ((x) >= ' ' && (x) <= '~')
  3498. void mg_hexdump(const void *buf, size_t len) {
  3499. const unsigned char *p = (const unsigned char *) buf;
  3500. unsigned char ascii[16], alen = 0;
  3501. size_t i;
  3502. for (i = 0; i < len; i++) {
  3503. if ((i % 16) == 0) {
  3504. // Print buffered ascii chars
  3505. if (i > 0) logs(" ", 2), logs((char *) ascii, 16), logc('\n'), alen = 0;
  3506. // Print hex address, then \t
  3507. logc(nibble((i >> 12) & 15)), logc(nibble((i >> 8) & 15)),
  3508. logc(nibble((i >> 4) & 15)), logc('0'), logs(" ", 3);
  3509. }
  3510. logc(nibble(p[i] >> 4)), logc(nibble(p[i] & 15)); // Two nibbles, e.g. c5
  3511. logc(' '); // Space after hex number
  3512. ascii[alen++] = ISPRINT(p[i]) ? p[i] : '.'; // Add to the ascii buf
  3513. }
  3514. while (alen < 16) logs(" ", 3), ascii[alen++] = ' ';
  3515. logs(" ", 2), logs((char *) ascii, 16), logc('\n');
  3516. }
  3517. #ifdef MG_ENABLE_LINES
  3518. #line 1 "src/md5.c"
  3519. #endif
  3520. // This code implements the MD5 message-digest algorithm.
  3521. // The algorithm is due to Ron Rivest. This code was
  3522. // written by Colin Plumb in 1993, no copyright is claimed.
  3523. // This code is in the public domain; do with it what you wish.
  3524. //
  3525. // Equivalent code is available from RSA Data Security, Inc.
  3526. // This code has been tested against that, and is equivalent,
  3527. // except that you don't need to include two pages of legalese
  3528. // with every copy.
  3529. //
  3530. // To compute the message digest of a chunk of bytes, declare an
  3531. // MD5Context structure, pass it to MD5Init, call MD5Update as
  3532. // needed on buffers full of bytes, and then call MD5Final, which
  3533. // will fill a supplied 16-byte array with the digest.
  3534. #if defined(MG_ENABLE_MD5) && MG_ENABLE_MD5
  3535. static void mg_byte_reverse(unsigned char *buf, unsigned longs) {
  3536. if (MG_BIG_ENDIAN) {
  3537. do {
  3538. uint32_t t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  3539. ((unsigned) buf[1] << 8 | buf[0]);
  3540. *(uint32_t *) buf = t;
  3541. buf += 4;
  3542. } while (--longs);
  3543. } else {
  3544. (void) buf, (void) longs; // Little endian. Do nothing
  3545. }
  3546. }
  3547. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  3548. #define F2(x, y, z) F1(z, x, y)
  3549. #define F3(x, y, z) (x ^ y ^ z)
  3550. #define F4(x, y, z) (y ^ (x | ~z))
  3551. #define MD5STEP(f, w, x, y, z, data, s) \
  3552. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  3553. /*
  3554. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  3555. * initialization constants.
  3556. */
  3557. void mg_md5_init(mg_md5_ctx *ctx) {
  3558. ctx->buf[0] = 0x67452301;
  3559. ctx->buf[1] = 0xefcdab89;
  3560. ctx->buf[2] = 0x98badcfe;
  3561. ctx->buf[3] = 0x10325476;
  3562. ctx->bits[0] = 0;
  3563. ctx->bits[1] = 0;
  3564. }
  3565. static void mg_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
  3566. uint32_t a, b, c, d;
  3567. a = buf[0];
  3568. b = buf[1];
  3569. c = buf[2];
  3570. d = buf[3];
  3571. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  3572. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  3573. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  3574. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  3575. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  3576. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  3577. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  3578. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  3579. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  3580. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  3581. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  3582. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  3583. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  3584. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  3585. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  3586. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  3587. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  3588. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  3589. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  3590. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  3591. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  3592. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  3593. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  3594. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  3595. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  3596. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  3597. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  3598. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  3599. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  3600. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  3601. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  3602. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  3603. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  3604. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  3605. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  3606. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  3607. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  3608. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  3609. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  3610. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  3611. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  3612. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  3613. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  3614. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  3615. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  3616. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  3617. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  3618. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  3619. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  3620. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  3621. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  3622. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  3623. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  3624. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  3625. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  3626. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  3627. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  3628. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  3629. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  3630. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  3631. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  3632. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  3633. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  3634. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  3635. buf[0] += a;
  3636. buf[1] += b;
  3637. buf[2] += c;
  3638. buf[3] += d;
  3639. }
  3640. void mg_md5_update(mg_md5_ctx *ctx, const unsigned char *buf, size_t len) {
  3641. uint32_t t;
  3642. t = ctx->bits[0];
  3643. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  3644. ctx->bits[1] += (uint32_t) len >> 29;
  3645. t = (t >> 3) & 0x3f;
  3646. if (t) {
  3647. unsigned char *p = (unsigned char *) ctx->in + t;
  3648. t = 64 - t;
  3649. if (len < t) {
  3650. memcpy(p, buf, len);
  3651. return;
  3652. }
  3653. memcpy(p, buf, t);
  3654. mg_byte_reverse(ctx->in, 16);
  3655. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3656. buf += t;
  3657. len -= t;
  3658. }
  3659. while (len >= 64) {
  3660. memcpy(ctx->in, buf, 64);
  3661. mg_byte_reverse(ctx->in, 16);
  3662. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3663. buf += 64;
  3664. len -= 64;
  3665. }
  3666. memcpy(ctx->in, buf, len);
  3667. }
  3668. void mg_md5_final(mg_md5_ctx *ctx, unsigned char digest[16]) {
  3669. unsigned count;
  3670. unsigned char *p;
  3671. uint32_t *a;
  3672. count = (ctx->bits[0] >> 3) & 0x3F;
  3673. p = ctx->in + count;
  3674. *p++ = 0x80;
  3675. count = 64 - 1 - count;
  3676. if (count < 8) {
  3677. memset(p, 0, count);
  3678. mg_byte_reverse(ctx->in, 16);
  3679. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3680. memset(ctx->in, 0, 56);
  3681. } else {
  3682. memset(p, 0, count - 8);
  3683. }
  3684. mg_byte_reverse(ctx->in, 14);
  3685. a = (uint32_t *) ctx->in;
  3686. a[14] = ctx->bits[0];
  3687. a[15] = ctx->bits[1];
  3688. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3689. mg_byte_reverse((unsigned char *) ctx->buf, 4);
  3690. memcpy(digest, ctx->buf, 16);
  3691. memset((char *) ctx, 0, sizeof(*ctx));
  3692. }
  3693. #endif
  3694. #ifdef MG_ENABLE_LINES
  3695. #line 1 "src/mqtt.c"
  3696. #endif
  3697. #define MQTT_CLEAN_SESSION 0x02
  3698. #define MQTT_HAS_WILL 0x04
  3699. #define MQTT_WILL_RETAIN 0x20
  3700. #define MQTT_HAS_PASSWORD 0x40
  3701. #define MQTT_HAS_USER_NAME 0x80
  3702. struct mg_mqtt_pmap {
  3703. uint8_t id;
  3704. uint8_t type;
  3705. };
  3706. static const struct mg_mqtt_pmap s_prop_map[] = {
  3707. {MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, MQTT_PROP_TYPE_BYTE},
  3708. {MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3709. {MQTT_PROP_CONTENT_TYPE, MQTT_PROP_TYPE_STRING},
  3710. {MQTT_PROP_RESPONSE_TOPIC, MQTT_PROP_TYPE_STRING},
  3711. {MQTT_PROP_CORRELATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3712. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER, MQTT_PROP_TYPE_VARIABLE_INT},
  3713. {MQTT_PROP_SESSION_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3714. {MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, MQTT_PROP_TYPE_STRING},
  3715. {MQTT_PROP_SERVER_KEEP_ALIVE, MQTT_PROP_TYPE_SHORT},
  3716. {MQTT_PROP_AUTHENTICATION_METHOD, MQTT_PROP_TYPE_STRING},
  3717. {MQTT_PROP_AUTHENTICATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3718. {MQTT_PROP_REQUEST_PROBLEM_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3719. {MQTT_PROP_WILL_DELAY_INTERVAL, MQTT_PROP_TYPE_INT},
  3720. {MQTT_PROP_REQUEST_RESPONSE_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3721. {MQTT_PROP_RESPONSE_INFORMATION, MQTT_PROP_TYPE_STRING},
  3722. {MQTT_PROP_SERVER_REFERENCE, MQTT_PROP_TYPE_STRING},
  3723. {MQTT_PROP_REASON_STRING, MQTT_PROP_TYPE_STRING},
  3724. {MQTT_PROP_RECEIVE_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3725. {MQTT_PROP_TOPIC_ALIAS_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3726. {MQTT_PROP_TOPIC_ALIAS, MQTT_PROP_TYPE_SHORT},
  3727. {MQTT_PROP_MAXIMUM_QOS, MQTT_PROP_TYPE_BYTE},
  3728. {MQTT_PROP_RETAIN_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3729. {MQTT_PROP_USER_PROPERTY, MQTT_PROP_TYPE_STRING_PAIR},
  3730. {MQTT_PROP_MAXIMUM_PACKET_SIZE, MQTT_PROP_TYPE_INT},
  3731. {MQTT_PROP_WILDCARD_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3732. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3733. {MQTT_PROP_SHARED_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE}};
  3734. void mg_mqtt_send_header(struct mg_connection *c, uint8_t cmd, uint8_t flags,
  3735. uint32_t len) {
  3736. uint8_t buf[1 + sizeof(len)], *vlen = &buf[1];
  3737. buf[0] = (uint8_t) ((cmd << 4) | flags);
  3738. do {
  3739. *vlen = len % 0x80;
  3740. len /= 0x80;
  3741. if (len > 0) *vlen |= 0x80;
  3742. vlen++;
  3743. } while (len > 0 && vlen < &buf[sizeof(buf)]);
  3744. mg_send(c, buf, (size_t) (vlen - buf));
  3745. }
  3746. static void mg_send_u16(struct mg_connection *c, uint16_t value) {
  3747. mg_send(c, &value, sizeof(value));
  3748. }
  3749. static void mg_send_u32(struct mg_connection *c, uint32_t value) {
  3750. mg_send(c, &value, sizeof(value));
  3751. }
  3752. static uint8_t varint_size(size_t length) {
  3753. uint8_t bytes_needed = 0;
  3754. do {
  3755. bytes_needed++;
  3756. length /= 0x80;
  3757. } while (length > 0);
  3758. return bytes_needed;
  3759. }
  3760. static size_t encode_varint(uint8_t *buf, size_t value) {
  3761. size_t len = 0;
  3762. do {
  3763. uint8_t b = (uint8_t) (value % 128);
  3764. value /= 128;
  3765. if (value > 0) b |= 0x80;
  3766. buf[len++] = b;
  3767. } while (value > 0);
  3768. return len;
  3769. }
  3770. static size_t decode_varint(const uint8_t *buf, size_t len, size_t *value) {
  3771. size_t multiplier = 1, offset;
  3772. *value = 0;
  3773. for (offset = 0; offset < 4 && offset < len; offset++) {
  3774. uint8_t encoded_byte = buf[offset];
  3775. *value += (encoded_byte & 0x7f) * multiplier;
  3776. multiplier *= 128;
  3777. if ((encoded_byte & 0x80) == 0) return offset + 1;
  3778. }
  3779. return 0;
  3780. }
  3781. static int mqtt_prop_type_by_id(uint8_t prop_id) {
  3782. size_t i, num_properties = sizeof(s_prop_map) / sizeof(s_prop_map[0]);
  3783. for (i = 0; i < num_properties; ++i) {
  3784. if (s_prop_map[i].id == prop_id) return s_prop_map[i].type;
  3785. }
  3786. return -1; // Property ID not found
  3787. }
  3788. // Returns the size of the properties section, without the
  3789. // size of the content's length
  3790. static size_t get_properties_length(struct mg_mqtt_prop *props, size_t count) {
  3791. size_t i, size = 0;
  3792. for (i = 0; i < count; i++) {
  3793. size++; // identifier
  3794. switch (mqtt_prop_type_by_id(props[i].id)) {
  3795. case MQTT_PROP_TYPE_STRING_PAIR:
  3796. size += (uint32_t) (props[i].val.len + props[i].key.len +
  3797. 2 * sizeof(uint16_t));
  3798. break;
  3799. case MQTT_PROP_TYPE_STRING:
  3800. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3801. break;
  3802. case MQTT_PROP_TYPE_BINARY_DATA:
  3803. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3804. break;
  3805. case MQTT_PROP_TYPE_VARIABLE_INT:
  3806. size += varint_size((uint32_t) props[i].iv);
  3807. break;
  3808. case MQTT_PROP_TYPE_INT:
  3809. size += (uint32_t) sizeof(uint32_t);
  3810. break;
  3811. case MQTT_PROP_TYPE_SHORT:
  3812. size += (uint32_t) sizeof(uint16_t);
  3813. break;
  3814. case MQTT_PROP_TYPE_BYTE:
  3815. size += (uint32_t) sizeof(uint8_t);
  3816. break;
  3817. default:
  3818. return size; // cannot parse further down
  3819. }
  3820. }
  3821. return size;
  3822. }
  3823. // returns the entire size of the properties section, including the
  3824. // size of the variable length of the content
  3825. static size_t get_props_size(struct mg_mqtt_prop *props, size_t count) {
  3826. size_t size = get_properties_length(props, count);
  3827. size += varint_size(size);
  3828. return size;
  3829. }
  3830. static void mg_send_mqtt_properties(struct mg_connection *c,
  3831. struct mg_mqtt_prop *props, size_t nprops) {
  3832. size_t total_size = get_properties_length(props, nprops);
  3833. uint8_t buf_v[4] = {0, 0, 0, 0};
  3834. uint8_t buf[4] = {0, 0, 0, 0};
  3835. size_t i, len = encode_varint(buf, total_size);
  3836. mg_send(c, buf, (size_t) len);
  3837. for (i = 0; i < nprops; i++) {
  3838. mg_send(c, &props[i].id, sizeof(props[i].id));
  3839. switch (mqtt_prop_type_by_id(props[i].id)) {
  3840. case MQTT_PROP_TYPE_STRING_PAIR:
  3841. mg_send_u16(c, mg_htons((uint16_t) props[i].key.len));
  3842. mg_send(c, props[i].key.buf, props[i].key.len);
  3843. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3844. mg_send(c, props[i].val.buf, props[i].val.len);
  3845. break;
  3846. case MQTT_PROP_TYPE_BYTE:
  3847. mg_send(c, &props[i].iv, sizeof(uint8_t));
  3848. break;
  3849. case MQTT_PROP_TYPE_SHORT:
  3850. mg_send_u16(c, mg_htons((uint16_t) props[i].iv));
  3851. break;
  3852. case MQTT_PROP_TYPE_INT:
  3853. mg_send_u32(c, mg_htonl((uint32_t) props[i].iv));
  3854. break;
  3855. case MQTT_PROP_TYPE_STRING:
  3856. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3857. mg_send(c, props[i].val.buf, props[i].val.len);
  3858. break;
  3859. case MQTT_PROP_TYPE_BINARY_DATA:
  3860. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3861. mg_send(c, props[i].val.buf, props[i].val.len);
  3862. break;
  3863. case MQTT_PROP_TYPE_VARIABLE_INT:
  3864. len = encode_varint(buf_v, props[i].iv);
  3865. mg_send(c, buf_v, (size_t) len);
  3866. break;
  3867. }
  3868. }
  3869. }
  3870. size_t mg_mqtt_next_prop(struct mg_mqtt_message *msg, struct mg_mqtt_prop *prop,
  3871. size_t ofs) {
  3872. uint8_t *i = (uint8_t *) msg->dgram.buf + msg->props_start + ofs;
  3873. uint8_t *end = (uint8_t *) msg->dgram.buf + msg->dgram.len;
  3874. size_t new_pos = ofs, len;
  3875. prop->id = i[0];
  3876. if (ofs >= msg->dgram.len || ofs >= msg->props_start + msg->props_size)
  3877. return 0;
  3878. i++, new_pos++;
  3879. switch (mqtt_prop_type_by_id(prop->id)) {
  3880. case MQTT_PROP_TYPE_STRING_PAIR:
  3881. prop->key.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3882. prop->key.buf = (char *) i + 2;
  3883. i += 2 + prop->key.len;
  3884. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3885. prop->val.buf = (char *) i + 2;
  3886. new_pos += 2 * sizeof(uint16_t) + prop->val.len + prop->key.len;
  3887. break;
  3888. case MQTT_PROP_TYPE_BYTE:
  3889. prop->iv = (uint8_t) i[0];
  3890. new_pos++;
  3891. break;
  3892. case MQTT_PROP_TYPE_SHORT:
  3893. prop->iv = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3894. new_pos += sizeof(uint16_t);
  3895. break;
  3896. case MQTT_PROP_TYPE_INT:
  3897. prop->iv = ((uint32_t) i[0] << 24) | ((uint32_t) i[1] << 16) |
  3898. ((uint32_t) i[2] << 8) | i[3];
  3899. new_pos += sizeof(uint32_t);
  3900. break;
  3901. case MQTT_PROP_TYPE_STRING:
  3902. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3903. prop->val.buf = (char *) i + 2;
  3904. new_pos += 2 + prop->val.len;
  3905. break;
  3906. case MQTT_PROP_TYPE_BINARY_DATA:
  3907. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3908. prop->val.buf = (char *) i + 2;
  3909. new_pos += 2 + prop->val.len;
  3910. break;
  3911. case MQTT_PROP_TYPE_VARIABLE_INT:
  3912. len = decode_varint(i, (size_t) (end - i), (size_t *) &prop->iv);
  3913. new_pos = (!len) ? 0 : new_pos + len;
  3914. break;
  3915. default:
  3916. new_pos = 0;
  3917. }
  3918. return new_pos;
  3919. }
  3920. void mg_mqtt_login(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3921. char client_id[21];
  3922. struct mg_str cid = opts->client_id;
  3923. size_t total_len = 7 + 1 + 2 + 2;
  3924. uint8_t hdr[8] = {0, 4, 'M', 'Q', 'T', 'T', opts->version, 0};
  3925. if (cid.len == 0) {
  3926. mg_random_str(client_id, sizeof(client_id) - 1);
  3927. client_id[sizeof(client_id) - 1] = '\0';
  3928. cid = mg_str(client_id);
  3929. }
  3930. if (hdr[6] == 0) hdr[6] = 4; // If version is not set, use 4 (3.1.1)
  3931. c->is_mqtt5 = hdr[6] == 5; // Set version 5 flag
  3932. hdr[7] = (uint8_t) ((opts->qos & 3) << 3); // Connection flags
  3933. if (opts->user.len > 0) {
  3934. total_len += 2 + (uint32_t) opts->user.len;
  3935. hdr[7] |= MQTT_HAS_USER_NAME;
  3936. }
  3937. if (opts->pass.len > 0) {
  3938. total_len += 2 + (uint32_t) opts->pass.len;
  3939. hdr[7] |= MQTT_HAS_PASSWORD;
  3940. }
  3941. if (opts->topic.len > 0) { // allow zero-length msgs, message.len is size_t
  3942. total_len += 4 + (uint32_t) opts->topic.len + (uint32_t) opts->message.len;
  3943. hdr[7] |= MQTT_HAS_WILL;
  3944. }
  3945. if (opts->clean || cid.len == 0) hdr[7] |= MQTT_CLEAN_SESSION;
  3946. if (opts->retain) hdr[7] |= MQTT_WILL_RETAIN;
  3947. total_len += (uint32_t) cid.len;
  3948. if (c->is_mqtt5) {
  3949. total_len += get_props_size(opts->props, opts->num_props);
  3950. if (hdr[7] & MQTT_HAS_WILL)
  3951. total_len += get_props_size(opts->will_props, opts->num_will_props);
  3952. }
  3953. mg_mqtt_send_header(c, MQTT_CMD_CONNECT, 0, (uint32_t) total_len);
  3954. mg_send(c, hdr, sizeof(hdr));
  3955. // keepalive == 0 means "do not disconnect us!"
  3956. mg_send_u16(c, mg_htons((uint16_t) opts->keepalive));
  3957. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3958. mg_send_u16(c, mg_htons((uint16_t) cid.len));
  3959. mg_send(c, cid.buf, cid.len);
  3960. if (hdr[7] & MQTT_HAS_WILL) {
  3961. if (c->is_mqtt5)
  3962. mg_send_mqtt_properties(c, opts->will_props, opts->num_will_props);
  3963. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3964. mg_send(c, opts->topic.buf, opts->topic.len);
  3965. mg_send_u16(c, mg_htons((uint16_t) opts->message.len));
  3966. mg_send(c, opts->message.buf, opts->message.len);
  3967. }
  3968. if (opts->user.len > 0) {
  3969. mg_send_u16(c, mg_htons((uint16_t) opts->user.len));
  3970. mg_send(c, opts->user.buf, opts->user.len);
  3971. }
  3972. if (opts->pass.len > 0) {
  3973. mg_send_u16(c, mg_htons((uint16_t) opts->pass.len));
  3974. mg_send(c, opts->pass.buf, opts->pass.len);
  3975. }
  3976. }
  3977. uint16_t mg_mqtt_pub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3978. uint16_t id = opts->retransmit_id;
  3979. uint8_t flags = (uint8_t) (((opts->qos & 3) << 1) | (opts->retain ? 1 : 0));
  3980. size_t len = 2 + opts->topic.len + opts->message.len;
  3981. MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) opts->topic.len,
  3982. (char *) opts->topic.buf, (int) opts->message.len,
  3983. (char *) opts->message.buf));
  3984. if (opts->qos > 0) len += 2;
  3985. if (c->is_mqtt5) len += get_props_size(opts->props, opts->num_props);
  3986. if (opts->qos > 0 && id != 0) flags |= 1 << 3;
  3987. mg_mqtt_send_header(c, MQTT_CMD_PUBLISH, flags, (uint32_t) len);
  3988. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3989. mg_send(c, opts->topic.buf, opts->topic.len);
  3990. if (opts->qos > 0) { // need to send 'id' field
  3991. if (id == 0) { // generate new one if not resending
  3992. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  3993. id = c->mgr->mqtt_id;
  3994. }
  3995. mg_send_u16(c, mg_htons(id));
  3996. }
  3997. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3998. if (opts->message.len > 0) mg_send(c, opts->message.buf, opts->message.len);
  3999. return id;
  4000. }
  4001. void mg_mqtt_sub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  4002. uint8_t qos_ = opts->qos & 3;
  4003. size_t plen = c->is_mqtt5 ? get_props_size(opts->props, opts->num_props) : 0;
  4004. size_t len = 2 + opts->topic.len + 2 + 1 + plen;
  4005. mg_mqtt_send_header(c, MQTT_CMD_SUBSCRIBE, 2, (uint32_t) len);
  4006. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  4007. mg_send_u16(c, mg_htons(c->mgr->mqtt_id));
  4008. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4009. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  4010. mg_send(c, opts->topic.buf, opts->topic.len);
  4011. mg_send(c, &qos_, sizeof(qos_));
  4012. }
  4013. int mg_mqtt_parse(const uint8_t *buf, size_t len, uint8_t version,
  4014. struct mg_mqtt_message *m) {
  4015. uint8_t lc = 0, *p, *end;
  4016. uint32_t n = 0, len_len = 0;
  4017. memset(m, 0, sizeof(*m));
  4018. m->dgram.buf = (char *) buf;
  4019. if (len < 2) return MQTT_INCOMPLETE;
  4020. m->cmd = (uint8_t) (buf[0] >> 4);
  4021. m->qos = (buf[0] >> 1) & 3;
  4022. n = len_len = 0;
  4023. p = (uint8_t *) buf + 1;
  4024. while ((size_t) (p - buf) < len) {
  4025. lc = *((uint8_t *) p++);
  4026. n += (uint32_t) ((lc & 0x7f) << 7 * len_len);
  4027. len_len++;
  4028. if (!(lc & 0x80)) break;
  4029. if (len_len >= 4) return MQTT_MALFORMED;
  4030. }
  4031. end = p + n;
  4032. if ((lc & 0x80) || (end > buf + len)) return MQTT_INCOMPLETE;
  4033. m->dgram.len = (size_t) (end - buf);
  4034. switch (m->cmd) {
  4035. case MQTT_CMD_CONNACK:
  4036. if (end - p < 2) return MQTT_MALFORMED;
  4037. m->ack = p[1];
  4038. break;
  4039. case MQTT_CMD_PUBACK:
  4040. case MQTT_CMD_PUBREC:
  4041. case MQTT_CMD_PUBREL:
  4042. case MQTT_CMD_PUBCOMP:
  4043. case MQTT_CMD_SUBSCRIBE:
  4044. case MQTT_CMD_SUBACK:
  4045. case MQTT_CMD_UNSUBSCRIBE:
  4046. case MQTT_CMD_UNSUBACK:
  4047. if (p + 2 > end) return MQTT_MALFORMED;
  4048. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4049. p += 2;
  4050. break;
  4051. case MQTT_CMD_PUBLISH: {
  4052. if (p + 2 > end) return MQTT_MALFORMED;
  4053. m->topic.len = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4054. m->topic.buf = (char *) p + 2;
  4055. p += 2 + m->topic.len;
  4056. if (p > end) return MQTT_MALFORMED;
  4057. if (m->qos > 0) {
  4058. if (p + 2 > end) return MQTT_MALFORMED;
  4059. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4060. p += 2;
  4061. }
  4062. if (p > end) return MQTT_MALFORMED;
  4063. if (version == 5 && p + 2 < end) {
  4064. len_len =
  4065. (uint32_t) decode_varint(p, (size_t) (end - p), &m->props_size);
  4066. if (!len_len) return MQTT_MALFORMED;
  4067. m->props_start = (size_t) (p + len_len - buf);
  4068. p += len_len + m->props_size;
  4069. }
  4070. if (p > end) return MQTT_MALFORMED;
  4071. m->data.buf = (char *) p;
  4072. m->data.len = (size_t) (end - p);
  4073. break;
  4074. }
  4075. default:
  4076. break;
  4077. }
  4078. return MQTT_OK;
  4079. }
  4080. static void mqtt_cb(struct mg_connection *c, int ev, void *ev_data) {
  4081. if (ev == MG_EV_READ) {
  4082. for (;;) {
  4083. uint8_t version = c->is_mqtt5 ? 5 : 4;
  4084. struct mg_mqtt_message mm;
  4085. int rc = mg_mqtt_parse(c->recv.buf, c->recv.len, version, &mm);
  4086. if (rc == MQTT_MALFORMED) {
  4087. MG_ERROR(("%lu MQTT malformed message", c->id));
  4088. c->is_closing = 1;
  4089. break;
  4090. } else if (rc == MQTT_OK) {
  4091. MG_VERBOSE(("%lu MQTT CMD %d len %d [%.*s]", c->id, mm.cmd,
  4092. (int) mm.dgram.len, (int) mm.data.len, mm.data.buf));
  4093. switch (mm.cmd) {
  4094. case MQTT_CMD_CONNACK:
  4095. mg_call(c, MG_EV_MQTT_OPEN, &mm.ack);
  4096. if (mm.ack == 0) {
  4097. MG_DEBUG(("%lu Connected", c->id));
  4098. } else {
  4099. MG_ERROR(("%lu MQTT auth failed, code %d", c->id, mm.ack));
  4100. c->is_closing = 1;
  4101. }
  4102. break;
  4103. case MQTT_CMD_PUBLISH: {
  4104. /*MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) mm.topic.len,
  4105. mm.topic.buf, (int) mm.data.len, mm.data.buf));*/
  4106. if (mm.qos > 0) {
  4107. uint16_t id = mg_ntohs(mm.id);
  4108. uint32_t remaining_len = sizeof(id);
  4109. if (c->is_mqtt5) remaining_len += 2; // 3.4.2
  4110. mg_mqtt_send_header(
  4111. c,
  4112. (uint8_t) (mm.qos == 2 ? MQTT_CMD_PUBREC : MQTT_CMD_PUBACK),
  4113. 0, remaining_len);
  4114. mg_send(c, &id, sizeof(id));
  4115. if (c->is_mqtt5) {
  4116. uint16_t zero = 0;
  4117. mg_send(c, &zero, sizeof(zero));
  4118. }
  4119. }
  4120. mg_call(c, MG_EV_MQTT_MSG, &mm); // let the app handle qos stuff
  4121. break;
  4122. }
  4123. case MQTT_CMD_PUBREC: { // MQTT5: 3.5.2-1 TODO(): variable header rc
  4124. uint16_t id = mg_ntohs(mm.id);
  4125. uint32_t remaining_len = sizeof(id); // MQTT5 3.6.2-1
  4126. mg_mqtt_send_header(c, MQTT_CMD_PUBREL, 2, remaining_len);
  4127. mg_send(c, &id, sizeof(id)); // MQTT5 3.6.1-1, flags = 2
  4128. break;
  4129. }
  4130. case MQTT_CMD_PUBREL: { // MQTT5: 3.6.2-1 TODO(): variable header rc
  4131. uint16_t id = mg_ntohs(mm.id);
  4132. uint32_t remaining_len = sizeof(id); // MQTT5 3.7.2-1
  4133. mg_mqtt_send_header(c, MQTT_CMD_PUBCOMP, 0, remaining_len);
  4134. mg_send(c, &id, sizeof(id));
  4135. break;
  4136. }
  4137. }
  4138. mg_call(c, MG_EV_MQTT_CMD, &mm);
  4139. mg_iobuf_del(&c->recv, 0, mm.dgram.len);
  4140. } else {
  4141. break;
  4142. }
  4143. }
  4144. }
  4145. (void) ev_data;
  4146. }
  4147. void mg_mqtt_ping(struct mg_connection *nc) {
  4148. mg_mqtt_send_header(nc, MQTT_CMD_PINGREQ, 0, 0);
  4149. }
  4150. void mg_mqtt_pong(struct mg_connection *nc) {
  4151. mg_mqtt_send_header(nc, MQTT_CMD_PINGRESP, 0, 0);
  4152. }
  4153. void mg_mqtt_disconnect(struct mg_connection *c,
  4154. const struct mg_mqtt_opts *opts) {
  4155. size_t len = 0;
  4156. if (c->is_mqtt5) len = 1 + get_props_size(opts->props, opts->num_props);
  4157. mg_mqtt_send_header(c, MQTT_CMD_DISCONNECT, 0, (uint32_t) len);
  4158. if (c->is_mqtt5) {
  4159. uint8_t zero = 0;
  4160. mg_send(c, &zero, sizeof(zero)); // reason code
  4161. mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4162. }
  4163. }
  4164. struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url,
  4165. const struct mg_mqtt_opts *opts,
  4166. mg_event_handler_t fn, void *fn_data) {
  4167. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  4168. if (c != NULL) {
  4169. struct mg_mqtt_opts empty;
  4170. memset(&empty, 0, sizeof(empty));
  4171. mg_mqtt_login(c, opts == NULL ? &empty : opts);
  4172. c->pfn = mqtt_cb;
  4173. }
  4174. return c;
  4175. }
  4176. struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url,
  4177. mg_event_handler_t fn, void *fn_data) {
  4178. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  4179. if (c != NULL) c->pfn = mqtt_cb, c->pfn_data = mgr;
  4180. return c;
  4181. }
  4182. #ifdef MG_ENABLE_LINES
  4183. #line 1 "src/net.c"
  4184. #endif
  4185. size_t mg_vprintf(struct mg_connection *c, const char *fmt, va_list *ap) {
  4186. size_t old = c->send.len;
  4187. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  4188. return c->send.len - old;
  4189. }
  4190. size_t mg_printf(struct mg_connection *c, const char *fmt, ...) {
  4191. size_t len = 0;
  4192. va_list ap;
  4193. va_start(ap, fmt);
  4194. len = mg_vprintf(c, fmt, &ap);
  4195. va_end(ap);
  4196. return len;
  4197. }
  4198. static bool mg_atonl(struct mg_str str, struct mg_addr *addr) {
  4199. uint32_t localhost = mg_htonl(0x7f000001);
  4200. if (mg_strcasecmp(str, mg_str("localhost")) != 0) return false;
  4201. memcpy(addr->ip, &localhost, sizeof(uint32_t));
  4202. addr->is_ip6 = false;
  4203. return true;
  4204. }
  4205. static bool mg_atone(struct mg_str str, struct mg_addr *addr) {
  4206. if (str.len > 0) return false;
  4207. memset(addr->ip, 0, sizeof(addr->ip));
  4208. addr->is_ip6 = false;
  4209. return true;
  4210. }
  4211. static bool mg_aton4(struct mg_str str, struct mg_addr *addr) {
  4212. uint8_t data[4] = {0, 0, 0, 0};
  4213. size_t i, num_dots = 0;
  4214. for (i = 0; i < str.len; i++) {
  4215. if (str.buf[i] >= '0' && str.buf[i] <= '9') {
  4216. int octet = data[num_dots] * 10 + (str.buf[i] - '0');
  4217. if (octet > 255) return false;
  4218. data[num_dots] = (uint8_t) octet;
  4219. } else if (str.buf[i] == '.') {
  4220. if (num_dots >= 3 || i == 0 || str.buf[i - 1] == '.') return false;
  4221. num_dots++;
  4222. } else {
  4223. return false;
  4224. }
  4225. }
  4226. if (num_dots != 3 || str.buf[i - 1] == '.') return false;
  4227. memcpy(&addr->ip, data, sizeof(data));
  4228. addr->is_ip6 = false;
  4229. return true;
  4230. }
  4231. static bool mg_v4mapped(struct mg_str str, struct mg_addr *addr) {
  4232. int i;
  4233. uint32_t ipv4;
  4234. if (str.len < 14) return false;
  4235. if (str.buf[0] != ':' || str.buf[1] != ':' || str.buf[6] != ':') return false;
  4236. for (i = 2; i < 6; i++) {
  4237. if (str.buf[i] != 'f' && str.buf[i] != 'F') return false;
  4238. }
  4239. // struct mg_str s = mg_str_n(&str.buf[7], str.len - 7);
  4240. if (!mg_aton4(mg_str_n(&str.buf[7], str.len - 7), addr)) return false;
  4241. memcpy(&ipv4, addr->ip, sizeof(ipv4));
  4242. memset(addr->ip, 0, sizeof(addr->ip));
  4243. addr->ip[10] = addr->ip[11] = 255;
  4244. memcpy(&addr->ip[12], &ipv4, 4);
  4245. addr->is_ip6 = true;
  4246. return true;
  4247. }
  4248. static bool mg_aton6(struct mg_str str, struct mg_addr *addr) {
  4249. size_t i, j = 0, n = 0, dc = 42;
  4250. addr->scope_id = 0;
  4251. if (str.len > 2 && str.buf[0] == '[') str.buf++, str.len -= 2;
  4252. if (mg_v4mapped(str, addr)) return true;
  4253. for (i = 0; i < str.len; i++) {
  4254. if ((str.buf[i] >= '0' && str.buf[i] <= '9') ||
  4255. (str.buf[i] >= 'a' && str.buf[i] <= 'f') ||
  4256. (str.buf[i] >= 'A' && str.buf[i] <= 'F')) {
  4257. unsigned long val; // TODO(): This loops on chars, refactor
  4258. if (i > j + 3) return false;
  4259. // MG_DEBUG(("%lu %lu [%.*s]", i, j, (int) (i - j + 1), &str.buf[j]));
  4260. mg_str_to_num(mg_str_n(&str.buf[j], i - j + 1), 16, &val, sizeof(val));
  4261. addr->ip[n] = (uint8_t) ((val >> 8) & 255);
  4262. addr->ip[n + 1] = (uint8_t) (val & 255);
  4263. } else if (str.buf[i] == ':') {
  4264. j = i + 1;
  4265. if (i > 0 && str.buf[i - 1] == ':') {
  4266. dc = n; // Double colon
  4267. if (i > 1 && str.buf[i - 2] == ':') return false;
  4268. } else if (i > 0) {
  4269. n += 2;
  4270. }
  4271. if (n > 14) return false;
  4272. addr->ip[n] = addr->ip[n + 1] = 0; // For trailing ::
  4273. } else if (str.buf[i] == '%') { // Scope ID, last in string
  4274. return mg_str_to_num(mg_str_n(&str.buf[i + 1], str.len - i - 1), 10,
  4275. &addr->scope_id, sizeof(uint8_t));
  4276. } else {
  4277. return false;
  4278. }
  4279. }
  4280. if (n < 14 && dc == 42) return false;
  4281. if (n < 14) {
  4282. memmove(&addr->ip[dc + (14 - n)], &addr->ip[dc], n - dc + 2);
  4283. memset(&addr->ip[dc], 0, 14 - n);
  4284. }
  4285. addr->is_ip6 = true;
  4286. return true;
  4287. }
  4288. bool mg_aton(struct mg_str str, struct mg_addr *addr) {
  4289. // MG_INFO(("[%.*s]", (int) str.len, str.buf));
  4290. return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) ||
  4291. mg_aton6(str, addr);
  4292. }
  4293. struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) {
  4294. struct mg_connection *c =
  4295. (struct mg_connection *) calloc(1, sizeof(*c) + mgr->extraconnsize);
  4296. if (c != NULL) {
  4297. c->mgr = mgr;
  4298. c->send.align = c->recv.align = c->rtls.align = MG_IO_SIZE;
  4299. c->id = ++mgr->nextid;
  4300. MG_PROF_INIT(c);
  4301. }
  4302. return c;
  4303. }
  4304. void mg_close_conn(struct mg_connection *c) {
  4305. mg_resolve_cancel(c); // Close any pending DNS query
  4306. LIST_DELETE(struct mg_connection, &c->mgr->conns, c);
  4307. if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL;
  4308. if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL;
  4309. // Order of operations is important. `MG_EV_CLOSE` event must be fired
  4310. // before we deallocate received data, see #1331
  4311. mg_call(c, MG_EV_CLOSE, NULL);
  4312. MG_DEBUG(("%lu %ld closed", c->id, c->fd));
  4313. MG_PROF_DUMP(c);
  4314. MG_PROF_FREE(c);
  4315. mg_tls_free(c);
  4316. mg_iobuf_free(&c->recv);
  4317. mg_iobuf_free(&c->send);
  4318. mg_iobuf_free(&c->rtls);
  4319. mg_bzero((unsigned char *) c, sizeof(*c));
  4320. free(c);
  4321. }
  4322. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url,
  4323. mg_event_handler_t fn, void *fn_data) {
  4324. struct mg_connection *c = NULL;
  4325. if (url == NULL || url[0] == '\0') {
  4326. MG_ERROR(("null url"));
  4327. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  4328. MG_ERROR(("OOM"));
  4329. } else {
  4330. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4331. c->is_udp = (strncmp(url, "udp:", 4) == 0);
  4332. c->fd = (void *) (size_t) MG_INVALID_SOCKET;
  4333. c->fn = fn;
  4334. c->is_client = true;
  4335. c->fn_data = fn_data;
  4336. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  4337. mg_call(c, MG_EV_OPEN, (void *) url);
  4338. mg_resolve(c, url);
  4339. }
  4340. return c;
  4341. }
  4342. struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url,
  4343. mg_event_handler_t fn, void *fn_data) {
  4344. struct mg_connection *c = NULL;
  4345. if ((c = mg_alloc_conn(mgr)) == NULL) {
  4346. MG_ERROR(("OOM %s", url));
  4347. } else if (!mg_open_listener(c, url)) {
  4348. MG_ERROR(("Failed: %s, errno %d", url, errno));
  4349. MG_PROF_FREE(c);
  4350. free(c);
  4351. c = NULL;
  4352. } else {
  4353. c->is_listening = 1;
  4354. c->is_udp = strncmp(url, "udp:", 4) == 0;
  4355. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4356. c->fn = fn;
  4357. c->fn_data = fn_data;
  4358. mg_call(c, MG_EV_OPEN, NULL);
  4359. if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must
  4360. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  4361. }
  4362. return c;
  4363. }
  4364. struct mg_connection *mg_wrapfd(struct mg_mgr *mgr, int fd,
  4365. mg_event_handler_t fn, void *fn_data) {
  4366. struct mg_connection *c = mg_alloc_conn(mgr);
  4367. if (c != NULL) {
  4368. c->fd = (void *) (size_t) fd;
  4369. c->fn = fn;
  4370. c->fn_data = fn_data;
  4371. MG_EPOLL_ADD(c);
  4372. mg_call(c, MG_EV_OPEN, NULL);
  4373. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4374. }
  4375. return c;
  4376. }
  4377. struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds,
  4378. unsigned flags, void (*fn)(void *), void *arg) {
  4379. struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t));
  4380. if (t != NULL) {
  4381. mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg);
  4382. t->id = mgr->timerid++;
  4383. }
  4384. return t;
  4385. }
  4386. long mg_io_recv(struct mg_connection *c, void *buf, size_t len) {
  4387. if (c->rtls.len == 0) return MG_IO_WAIT;
  4388. if (len > c->rtls.len) len = c->rtls.len;
  4389. memcpy(buf, c->rtls.buf, len);
  4390. mg_iobuf_del(&c->rtls, 0, len);
  4391. return (long) len;
  4392. }
  4393. void mg_mgr_free(struct mg_mgr *mgr) {
  4394. struct mg_connection *c;
  4395. struct mg_timer *tmp, *t = mgr->timers;
  4396. while (t != NULL) tmp = t->next, free(t), t = tmp;
  4397. mgr->timers = NULL; // Important. Next call to poll won't touch timers
  4398. for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1;
  4399. mg_mgr_poll(mgr, 0);
  4400. #if MG_ENABLE_FREERTOS_TCP
  4401. FreeRTOS_DeleteSocketSet(mgr->ss);
  4402. #endif
  4403. MG_DEBUG(("All connections closed"));
  4404. #if MG_ENABLE_EPOLL
  4405. if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1;
  4406. #endif
  4407. mg_tls_ctx_free(mgr);
  4408. }
  4409. void mg_mgr_init(struct mg_mgr *mgr) {
  4410. memset(mgr, 0, sizeof(*mgr));
  4411. #if MG_ENABLE_EPOLL
  4412. if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
  4413. MG_ERROR(("epoll_create1 errno %d", errno));
  4414. #else
  4415. mgr->epoll_fd = -1;
  4416. #endif
  4417. #if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  4418. // clang-format off
  4419. { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
  4420. // clang-format on
  4421. #elif MG_ENABLE_FREERTOS_TCP
  4422. mgr->ss = FreeRTOS_CreateSocketSet();
  4423. #elif defined(__unix) || defined(__unix__) || defined(__APPLE__)
  4424. // Ignore SIGPIPE signal, so if client cancels the request, it
  4425. // won't kill the whole process.
  4426. signal(SIGPIPE, SIG_IGN);
  4427. #elif MG_ENABLE_TCPIP_DRIVER_INIT && defined(MG_TCPIP_DRIVER_INIT)
  4428. MG_TCPIP_DRIVER_INIT(mgr);
  4429. #endif
  4430. mgr->pipe = MG_INVALID_SOCKET;
  4431. mgr->dnstimeout = 3000;
  4432. mgr->dns4.url = "udp://8.8.8.8:53";
  4433. mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
  4434. mg_tls_ctx_init(mgr);
  4435. }
  4436. #ifdef MG_ENABLE_LINES
  4437. #line 1 "src/net_builtin.c"
  4438. #endif
  4439. #if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP
  4440. #define MG_EPHEMERAL_PORT_BASE 32768
  4441. #define PDIFF(a, b) ((size_t) (((char *) (b)) - ((char *) (a))))
  4442. #ifndef MIP_TCP_KEEPALIVE_MS
  4443. #define MIP_TCP_KEEPALIVE_MS 45000 // TCP keep-alive period, ms
  4444. #endif
  4445. #define MIP_TCP_ACK_MS 150 // Timeout for ACKing
  4446. #define MIP_TCP_ARP_MS 100 // Timeout for ARP response
  4447. #define MIP_TCP_SYN_MS 15000 // Timeout for connection establishment
  4448. #define MIP_TCP_FIN_MS 1000 // Timeout for closing connection
  4449. #define MIP_TCP_WIN 6000 // TCP window size
  4450. struct connstate {
  4451. uint32_t seq, ack; // TCP seq/ack counters
  4452. uint64_t timer; // TCP keep-alive / ACK timer
  4453. uint32_t acked; // Last ACK-ed number
  4454. size_t unacked; // Not acked bytes
  4455. uint8_t mac[6]; // Peer MAC address
  4456. uint8_t ttype; // Timer type. 0: ack, 1: keep-alive
  4457. #define MIP_TTYPE_KEEPALIVE 0 // Connection is idle for long, send keepalive
  4458. #define MIP_TTYPE_ACK 1 // Peer sent us data, we have to ack it soon
  4459. #define MIP_TTYPE_ARP 2 // ARP resolve sent, waiting for response
  4460. #define MIP_TTYPE_SYN 3 // SYN sent, waiting for response
  4461. #define MIP_TTYPE_FIN 4 // FIN sent, waiting until terminating the connection
  4462. uint8_t tmiss; // Number of keep-alive misses
  4463. struct mg_iobuf raw; // For TLS only. Incoming raw data
  4464. };
  4465. #pragma pack(push, 1)
  4466. struct lcp {
  4467. uint8_t addr, ctrl, proto[2], code, id, len[2];
  4468. };
  4469. struct eth {
  4470. uint8_t dst[6]; // Destination MAC address
  4471. uint8_t src[6]; // Source MAC address
  4472. uint16_t type; // Ethernet type
  4473. };
  4474. struct ip {
  4475. uint8_t ver; // Version
  4476. uint8_t tos; // Unused
  4477. uint16_t len; // Length
  4478. uint16_t id; // Unused
  4479. uint16_t frag; // Fragmentation
  4480. #define IP_FRAG_OFFSET_MSK 0xFF1F
  4481. #define IP_MORE_FRAGS_MSK 0x20
  4482. uint8_t ttl; // Time to live
  4483. uint8_t proto; // Upper level protocol
  4484. uint16_t csum; // Checksum
  4485. uint32_t src; // Source IP
  4486. uint32_t dst; // Destination IP
  4487. };
  4488. struct ip6 {
  4489. uint8_t ver; // Version
  4490. uint8_t opts[3]; // Options
  4491. uint16_t len; // Length
  4492. uint8_t proto; // Upper level protocol
  4493. uint8_t ttl; // Time to live
  4494. uint8_t src[16]; // Source IP
  4495. uint8_t dst[16]; // Destination IP
  4496. };
  4497. struct icmp {
  4498. uint8_t type;
  4499. uint8_t code;
  4500. uint16_t csum;
  4501. };
  4502. struct arp {
  4503. uint16_t fmt; // Format of hardware address
  4504. uint16_t pro; // Format of protocol address
  4505. uint8_t hlen; // Length of hardware address
  4506. uint8_t plen; // Length of protocol address
  4507. uint16_t op; // Operation
  4508. uint8_t sha[6]; // Sender hardware address
  4509. uint32_t spa; // Sender protocol address
  4510. uint8_t tha[6]; // Target hardware address
  4511. uint32_t tpa; // Target protocol address
  4512. };
  4513. struct tcp {
  4514. uint16_t sport; // Source port
  4515. uint16_t dport; // Destination port
  4516. uint32_t seq; // Sequence number
  4517. uint32_t ack; // Acknowledgement number
  4518. uint8_t off; // Data offset
  4519. uint8_t flags; // TCP flags
  4520. #define TH_FIN 0x01
  4521. #define TH_SYN 0x02
  4522. #define TH_RST 0x04
  4523. #define TH_PUSH 0x08
  4524. #define TH_ACK 0x10
  4525. #define TH_URG 0x20
  4526. #define TH_ECE 0x40
  4527. #define TH_CWR 0x80
  4528. uint16_t win; // Window
  4529. uint16_t csum; // Checksum
  4530. uint16_t urp; // Urgent pointer
  4531. };
  4532. struct udp {
  4533. uint16_t sport; // Source port
  4534. uint16_t dport; // Destination port
  4535. uint16_t len; // UDP length
  4536. uint16_t csum; // UDP checksum
  4537. };
  4538. struct dhcp {
  4539. uint8_t op, htype, hlen, hops;
  4540. uint32_t xid;
  4541. uint16_t secs, flags;
  4542. uint32_t ciaddr, yiaddr, siaddr, giaddr;
  4543. uint8_t hwaddr[208];
  4544. uint32_t magic;
  4545. uint8_t options[32];
  4546. };
  4547. #pragma pack(pop)
  4548. struct pkt {
  4549. struct mg_str raw; // Raw packet data
  4550. struct mg_str pay; // Payload data
  4551. struct eth *eth;
  4552. struct llc *llc;
  4553. struct arp *arp;
  4554. struct ip *ip;
  4555. struct ip6 *ip6;
  4556. struct icmp *icmp;
  4557. struct tcp *tcp;
  4558. struct udp *udp;
  4559. struct dhcp *dhcp;
  4560. };
  4561. static void send_syn(struct mg_connection *c);
  4562. static void mkpay(struct pkt *pkt, void *p) {
  4563. pkt->pay =
  4564. mg_str_n((char *) p, (size_t) (&pkt->raw.buf[pkt->raw.len] - (char *) p));
  4565. }
  4566. static uint32_t csumup(uint32_t sum, const void *buf, size_t len) {
  4567. size_t i;
  4568. const uint8_t *p = (const uint8_t *) buf;
  4569. for (i = 0; i < len; i++) sum += i & 1 ? p[i] : (uint32_t) (p[i] << 8);
  4570. return sum;
  4571. }
  4572. static uint16_t csumfin(uint32_t sum) {
  4573. while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
  4574. return mg_htons(~sum & 0xffff);
  4575. }
  4576. static uint16_t ipcsum(const void *buf, size_t len) {
  4577. uint32_t sum = csumup(0, buf, len);
  4578. return csumfin(sum);
  4579. }
  4580. static void settmout(struct mg_connection *c, uint8_t type) {
  4581. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4582. struct connstate *s = (struct connstate *) (c + 1);
  4583. unsigned n = type == MIP_TTYPE_ACK ? MIP_TCP_ACK_MS
  4584. : type == MIP_TTYPE_ARP ? MIP_TCP_ARP_MS
  4585. : type == MIP_TTYPE_SYN ? MIP_TCP_SYN_MS
  4586. : type == MIP_TTYPE_FIN ? MIP_TCP_FIN_MS
  4587. : MIP_TCP_KEEPALIVE_MS;
  4588. s->timer = ifp->now + n;
  4589. s->ttype = type;
  4590. MG_VERBOSE(("%lu %d -> %llx", c->id, type, s->timer));
  4591. }
  4592. static size_t ether_output(struct mg_tcpip_if *ifp, size_t len) {
  4593. size_t n = ifp->driver->tx(ifp->tx.buf, len, ifp);
  4594. if (n == len) ifp->nsent++;
  4595. return n;
  4596. }
  4597. static void arp_ask(struct mg_tcpip_if *ifp, uint32_t ip) {
  4598. struct eth *eth = (struct eth *) ifp->tx.buf;
  4599. struct arp *arp = (struct arp *) (eth + 1);
  4600. memset(eth->dst, 255, sizeof(eth->dst));
  4601. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4602. eth->type = mg_htons(0x806);
  4603. memset(arp, 0, sizeof(*arp));
  4604. arp->fmt = mg_htons(1), arp->pro = mg_htons(0x800), arp->hlen = 6,
  4605. arp->plen = 4;
  4606. arp->op = mg_htons(1), arp->tpa = ip, arp->spa = ifp->ip;
  4607. memcpy(arp->sha, ifp->mac, sizeof(arp->sha));
  4608. ether_output(ifp, PDIFF(eth, arp + 1));
  4609. }
  4610. static void onstatechange(struct mg_tcpip_if *ifp) {
  4611. if (ifp->state == MG_TCPIP_STATE_READY) {
  4612. MG_INFO(("READY, IP: %M", mg_print_ip4, &ifp->ip));
  4613. MG_INFO((" GW: %M", mg_print_ip4, &ifp->gw));
  4614. MG_INFO((" MAC: %M", mg_print_mac, &ifp->mac));
  4615. arp_ask(ifp, ifp->gw);
  4616. } else if (ifp->state == MG_TCPIP_STATE_UP) {
  4617. MG_ERROR(("Link up"));
  4618. srand((unsigned int) mg_millis());
  4619. } else if (ifp->state == MG_TCPIP_STATE_DOWN) {
  4620. MG_ERROR(("Link down"));
  4621. }
  4622. }
  4623. static struct ip *tx_ip(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4624. uint8_t proto, uint32_t ip_src, uint32_t ip_dst,
  4625. size_t plen) {
  4626. struct eth *eth = (struct eth *) ifp->tx.buf;
  4627. struct ip *ip = (struct ip *) (eth + 1);
  4628. memcpy(eth->dst, mac_dst, sizeof(eth->dst));
  4629. memcpy(eth->src, ifp->mac, sizeof(eth->src)); // Use our MAC
  4630. eth->type = mg_htons(0x800);
  4631. memset(ip, 0, sizeof(*ip));
  4632. ip->ver = 0x45; // Version 4, header length 5 words
  4633. ip->frag = 0x40; // Don't fragment
  4634. ip->len = mg_htons((uint16_t) (sizeof(*ip) + plen));
  4635. ip->ttl = 64;
  4636. ip->proto = proto;
  4637. ip->src = ip_src;
  4638. ip->dst = ip_dst;
  4639. ip->csum = ipcsum(ip, sizeof(*ip));
  4640. return ip;
  4641. }
  4642. static void tx_udp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4643. uint16_t sport, uint32_t ip_dst, uint16_t dport,
  4644. const void *buf, size_t len) {
  4645. struct ip *ip =
  4646. tx_ip(ifp, mac_dst, 17, ip_src, ip_dst, len + sizeof(struct udp));
  4647. struct udp *udp = (struct udp *) (ip + 1);
  4648. // MG_DEBUG(("UDP XX LEN %d %d", (int) len, (int) ifp->tx.len));
  4649. udp->sport = sport;
  4650. udp->dport = dport;
  4651. udp->len = mg_htons((uint16_t) (sizeof(*udp) + len));
  4652. udp->csum = 0;
  4653. uint32_t cs = csumup(0, udp, sizeof(*udp));
  4654. cs = csumup(cs, buf, len);
  4655. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4656. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4657. cs += (uint32_t) (ip->proto + sizeof(*udp) + len);
  4658. udp->csum = csumfin(cs);
  4659. memmove(udp + 1, buf, len);
  4660. // MG_DEBUG(("UDP LEN %d %d", (int) len, (int) ifp->frame_len));
  4661. ether_output(ifp, sizeof(struct eth) + sizeof(*ip) + sizeof(*udp) + len);
  4662. }
  4663. static void tx_dhcp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4664. uint32_t ip_dst, uint8_t *opts, size_t optslen,
  4665. bool ciaddr) {
  4666. // https://datatracker.ietf.org/doc/html/rfc2132#section-9.6
  4667. struct dhcp dhcp = {1, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4668. dhcp.magic = mg_htonl(0x63825363);
  4669. memcpy(&dhcp.hwaddr, ifp->mac, sizeof(ifp->mac));
  4670. memcpy(&dhcp.xid, ifp->mac + 2, sizeof(dhcp.xid));
  4671. memcpy(&dhcp.options, opts, optslen);
  4672. if (ciaddr) dhcp.ciaddr = ip_src;
  4673. tx_udp(ifp, mac_dst, ip_src, mg_htons(68), ip_dst, mg_htons(67), &dhcp,
  4674. sizeof(dhcp));
  4675. }
  4676. static const uint8_t broadcast[] = {255, 255, 255, 255, 255, 255};
  4677. // RFC-2131 #4.3.6, #4.4.1
  4678. static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
  4679. uint32_t ip_srv) {
  4680. uint8_t opts[] = {
  4681. 53, 1, 3, // Type: DHCP request
  4682. 55, 2, 1, 3, // GW and mask
  4683. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4684. 54, 4, 0, 0, 0, 0, // DHCP server ID
  4685. 50, 4, 0, 0, 0, 0, // Requested IP
  4686. 255 // End of options
  4687. };
  4688. memcpy(opts + 14, &ip_srv, sizeof(ip_srv));
  4689. memcpy(opts + 20, &ip_req, sizeof(ip_req));
  4690. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4691. MG_DEBUG(("DHCP req sent"));
  4692. }
  4693. // RFC-2131 #4.3.6, #4.4.5 (renewing: unicast, rebinding: bcast)
  4694. static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4695. uint32_t ip_src, uint32_t ip_dst) {
  4696. uint8_t opts[] = {
  4697. 53, 1, 3, // Type: DHCP request
  4698. 255 // End of options
  4699. };
  4700. tx_dhcp(ifp, mac_dst, ip_src, ip_dst, opts, sizeof(opts), true);
  4701. MG_DEBUG(("DHCP req sent"));
  4702. }
  4703. static void tx_dhcp_discover(struct mg_tcpip_if *ifp) {
  4704. uint8_t opts[] = {
  4705. 53, 1, 1, // Type: DHCP discover
  4706. 55, 2, 1, 3, // Parameters: ip, mask
  4707. 255 // End of options
  4708. };
  4709. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4710. MG_DEBUG(("DHCP discover sent. Our MAC: %M", mg_print_mac, ifp->mac));
  4711. }
  4712. static struct mg_connection *getpeer(struct mg_mgr *mgr, struct pkt *pkt,
  4713. bool lsn) {
  4714. struct mg_connection *c = NULL;
  4715. for (c = mgr->conns; c != NULL; c = c->next) {
  4716. if (c->is_arplooking && pkt->arp &&
  4717. memcmp(&pkt->arp->spa, c->rem.ip, sizeof(pkt->arp->spa)) == 0)
  4718. break;
  4719. if (c->is_udp && pkt->udp && c->loc.port == pkt->udp->dport) break;
  4720. if (!c->is_udp && pkt->tcp && c->loc.port == pkt->tcp->dport &&
  4721. lsn == c->is_listening && (lsn || c->rem.port == pkt->tcp->sport))
  4722. break;
  4723. }
  4724. return c;
  4725. }
  4726. static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4727. if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) {
  4728. // ARP request. Make a response, then send
  4729. // MG_DEBUG(("ARP op %d %M: %M", mg_ntohs(pkt->arp->op), mg_print_ip4,
  4730. // &pkt->arp->spa, mg_print_ip4, &pkt->arp->tpa));
  4731. struct eth *eth = (struct eth *) ifp->tx.buf;
  4732. struct arp *arp = (struct arp *) (eth + 1);
  4733. memcpy(eth->dst, pkt->eth->src, sizeof(eth->dst));
  4734. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4735. eth->type = mg_htons(0x806);
  4736. *arp = *pkt->arp;
  4737. arp->op = mg_htons(2);
  4738. memcpy(arp->tha, pkt->arp->sha, sizeof(pkt->arp->tha));
  4739. memcpy(arp->sha, ifp->mac, sizeof(pkt->arp->sha));
  4740. arp->tpa = pkt->arp->spa;
  4741. arp->spa = ifp->ip;
  4742. MG_DEBUG(("ARP: tell %M we're %M", mg_print_ip4, &arp->tpa, mg_print_mac,
  4743. &ifp->mac));
  4744. ether_output(ifp, PDIFF(eth, arp + 1));
  4745. } else if (pkt->arp->op == mg_htons(2)) {
  4746. if (memcmp(pkt->arp->tha, ifp->mac, sizeof(pkt->arp->tha)) != 0) return;
  4747. if (pkt->arp->spa == ifp->gw) {
  4748. // Got response for the GW ARP request. Set ifp->gwmac
  4749. memcpy(ifp->gwmac, pkt->arp->sha, sizeof(ifp->gwmac));
  4750. } else {
  4751. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4752. if (c != NULL && c->is_arplooking) {
  4753. struct connstate *s = (struct connstate *) (c + 1);
  4754. memcpy(s->mac, pkt->arp->sha, sizeof(s->mac));
  4755. MG_DEBUG(("%lu ARP resolved %M -> %M", c->id, mg_print_ip4, c->rem.ip,
  4756. mg_print_mac, s->mac));
  4757. c->is_arplooking = 0;
  4758. send_syn(c);
  4759. settmout(c, MIP_TTYPE_SYN);
  4760. }
  4761. }
  4762. }
  4763. }
  4764. static void rx_icmp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4765. // MG_DEBUG(("ICMP %d", (int) len));
  4766. if (pkt->icmp->type == 8 && pkt->ip != NULL && pkt->ip->dst == ifp->ip) {
  4767. size_t hlen = sizeof(struct eth) + sizeof(struct ip) + sizeof(struct icmp);
  4768. size_t space = ifp->tx.len - hlen, plen = pkt->pay.len;
  4769. if (plen > space) plen = space;
  4770. struct ip *ip = tx_ip(ifp, pkt->eth->src, 1, ifp->ip, pkt->ip->src,
  4771. sizeof(struct icmp) + plen);
  4772. struct icmp *icmp = (struct icmp *) (ip + 1);
  4773. memset(icmp, 0, sizeof(*icmp)); // Set csum to 0
  4774. memcpy(icmp + 1, pkt->pay.buf, plen); // Copy RX payload to TX
  4775. icmp->csum = ipcsum(icmp, sizeof(*icmp) + plen);
  4776. ether_output(ifp, hlen + plen);
  4777. }
  4778. }
  4779. static void rx_dhcp_client(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4780. uint32_t ip = 0, gw = 0, mask = 0, lease = 0;
  4781. uint8_t msgtype = 0, state = ifp->state;
  4782. // perform size check first, then access fields
  4783. uint8_t *p = pkt->dhcp->options,
  4784. *end = (uint8_t *) &pkt->raw.buf[pkt->raw.len];
  4785. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4786. if (memcmp(&pkt->dhcp->xid, ifp->mac + 2, sizeof(pkt->dhcp->xid))) return;
  4787. while (p + 1 < end && p[0] != 255) { // Parse options RFC-1533 #9
  4788. if (p[0] == 1 && p[1] == sizeof(ifp->mask) && p + 6 < end) { // Mask
  4789. memcpy(&mask, p + 2, sizeof(mask));
  4790. } else if (p[0] == 3 && p[1] == sizeof(ifp->gw) && p + 6 < end) { // GW
  4791. memcpy(&gw, p + 2, sizeof(gw));
  4792. ip = pkt->dhcp->yiaddr;
  4793. } else if (p[0] == 51 && p[1] == 4 && p + 6 < end) { // Lease
  4794. memcpy(&lease, p + 2, sizeof(lease));
  4795. lease = mg_ntohl(lease);
  4796. } else if (p[0] == 53 && p[1] == 1 && p + 6 < end) { // Msg Type
  4797. msgtype = p[2];
  4798. }
  4799. p += p[1] + 2;
  4800. }
  4801. // Process message type, RFC-1533 (9.4); RFC-2131 (3.1, 4)
  4802. if (msgtype == 6 && ifp->ip == ip) { // DHCPNACK, release IP
  4803. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0;
  4804. } else if (msgtype == 2 && ifp->state == MG_TCPIP_STATE_UP && ip && gw &&
  4805. lease) { // DHCPOFFER
  4806. // select IP, (4.4.1) (fallback to IP source addr on foul play)
  4807. tx_dhcp_request_sel(ifp, ip,
  4808. pkt->dhcp->siaddr ? pkt->dhcp->siaddr : pkt->ip->src);
  4809. ifp->state = MG_TCPIP_STATE_REQ; // REQUESTING state
  4810. } else if (msgtype == 5) { // DHCPACK
  4811. if (ifp->state == MG_TCPIP_STATE_REQ && ip && gw && lease) { // got an IP
  4812. ifp->lease_expire = ifp->now + lease * 1000;
  4813. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4814. // assume DHCP server = router until ARP resolves
  4815. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4816. ifp->ip = ip, ifp->gw = gw, ifp->mask = mask;
  4817. ifp->state = MG_TCPIP_STATE_READY; // BOUND state
  4818. uint64_t rand;
  4819. mg_random(&rand, sizeof(rand));
  4820. srand((unsigned int) (rand + mg_millis()));
  4821. } else if (ifp->state == MG_TCPIP_STATE_READY && ifp->ip == ip) { // renew
  4822. ifp->lease_expire = ifp->now + lease * 1000;
  4823. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4824. } // TODO(): accept provided T1/T2 and store server IP for renewal (4.4)
  4825. }
  4826. if (ifp->state != state) onstatechange(ifp);
  4827. }
  4828. // Simple DHCP server that assigns a next IP address: ifp->ip + 1
  4829. static void rx_dhcp_server(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4830. uint8_t op = 0, *p = pkt->dhcp->options,
  4831. *end = (uint8_t *) &pkt->raw.buf[pkt->raw.len];
  4832. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4833. // struct dhcp *req = pkt->dhcp;
  4834. struct dhcp res = {2, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4835. res.yiaddr = ifp->ip;
  4836. ((uint8_t *) (&res.yiaddr))[3]++; // Offer our IP + 1
  4837. while (p + 1 < end && p[0] != 255) { // Parse options
  4838. if (p[0] == 53 && p[1] == 1 && p + 2 < end) { // Message type
  4839. op = p[2];
  4840. }
  4841. p += p[1] + 2;
  4842. }
  4843. if (op == 1 || op == 3) { // DHCP Discover or DHCP Request
  4844. uint8_t msg = op == 1 ? 2 : 5; // Message type: DHCP OFFER or DHCP ACK
  4845. uint8_t opts[] = {
  4846. 53, 1, msg, // Message type
  4847. 1, 4, 0, 0, 0, 0, // Subnet mask
  4848. 54, 4, 0, 0, 0, 0, // Server ID
  4849. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4850. 51, 4, 255, 255, 255, 255, // Lease time
  4851. 255 // End of options
  4852. };
  4853. memcpy(&res.hwaddr, pkt->dhcp->hwaddr, 6);
  4854. memcpy(opts + 5, &ifp->mask, sizeof(ifp->mask));
  4855. memcpy(opts + 11, &ifp->ip, sizeof(ifp->ip));
  4856. memcpy(&res.options, opts, sizeof(opts));
  4857. res.magic = pkt->dhcp->magic;
  4858. res.xid = pkt->dhcp->xid;
  4859. if (ifp->enable_get_gateway) {
  4860. ifp->gw = res.yiaddr;
  4861. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4862. }
  4863. tx_udp(ifp, pkt->eth->src, ifp->ip, mg_htons(67),
  4864. op == 1 ? ~0U : res.yiaddr, mg_htons(68), &res, sizeof(res));
  4865. }
  4866. }
  4867. static void rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4868. struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
  4869. if (c == NULL) {
  4870. // No UDP listener on this port. Should send ICMP, but keep silent.
  4871. } else {
  4872. c->rem.port = pkt->udp->sport;
  4873. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4874. struct connstate *s = (struct connstate *) (c + 1);
  4875. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4876. if (c->recv.len >= MG_MAX_RECV_SIZE) {
  4877. mg_error(c, "max_recv_buf_size reached");
  4878. } else if (c->recv.size - c->recv.len < pkt->pay.len &&
  4879. !mg_iobuf_resize(&c->recv, c->recv.len + pkt->pay.len)) {
  4880. mg_error(c, "oom");
  4881. } else {
  4882. memcpy(&c->recv.buf[c->recv.len], pkt->pay.buf, pkt->pay.len);
  4883. c->recv.len += pkt->pay.len;
  4884. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4885. }
  4886. }
  4887. }
  4888. static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *dst_mac, uint32_t dst_ip,
  4889. uint8_t flags, uint16_t sport, uint16_t dport,
  4890. uint32_t seq, uint32_t ack, const void *buf, size_t len) {
  4891. #if 0
  4892. uint8_t opts[] = {2, 4, 5, 0xb4, 4, 2, 0, 0}; // MSS = 1460, SACK permitted
  4893. if (flags & TH_SYN) {
  4894. // Handshake? Set MSS
  4895. buf = opts;
  4896. len = sizeof(opts);
  4897. }
  4898. #endif
  4899. struct ip *ip =
  4900. tx_ip(ifp, dst_mac, 6, ifp->ip, dst_ip, sizeof(struct tcp) + len);
  4901. struct tcp *tcp = (struct tcp *) (ip + 1);
  4902. memset(tcp, 0, sizeof(*tcp));
  4903. if (buf != NULL && len) memmove(tcp + 1, buf, len);
  4904. tcp->sport = sport;
  4905. tcp->dport = dport;
  4906. tcp->seq = seq;
  4907. tcp->ack = ack;
  4908. tcp->flags = flags;
  4909. tcp->win = mg_htons(MIP_TCP_WIN);
  4910. tcp->off = (uint8_t) (sizeof(*tcp) / 4 << 4);
  4911. // if (flags & TH_SYN) tcp->off = 0x70; // Handshake? header size 28 bytes
  4912. uint32_t cs = 0;
  4913. uint16_t n = (uint16_t) (sizeof(*tcp) + len);
  4914. uint8_t pseudo[] = {0, ip->proto, (uint8_t) (n >> 8), (uint8_t) (n & 255)};
  4915. cs = csumup(cs, tcp, n);
  4916. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4917. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4918. cs = csumup(cs, pseudo, sizeof(pseudo));
  4919. tcp->csum = csumfin(cs);
  4920. MG_VERBOSE(("TCP %M:%hu -> %M:%hu fl %x len %u", mg_print_ip4, &ip->src,
  4921. mg_ntohs(tcp->sport), mg_print_ip4, &ip->dst,
  4922. mg_ntohs(tcp->dport), tcp->flags, len));
  4923. // mg_hexdump(ifp->tx.buf, PDIFF(ifp->tx.buf, tcp + 1) + len);
  4924. return ether_output(ifp, PDIFF(ifp->tx.buf, tcp + 1) + len);
  4925. }
  4926. static size_t tx_tcp_pkt(struct mg_tcpip_if *ifp, struct pkt *pkt,
  4927. uint8_t flags, uint32_t seq, const void *buf,
  4928. size_t len) {
  4929. uint32_t delta = (pkt->tcp->flags & (TH_SYN | TH_FIN)) ? 1 : 0;
  4930. return tx_tcp(ifp, pkt->eth->src, pkt->ip->src, flags, pkt->tcp->dport,
  4931. pkt->tcp->sport, seq, mg_htonl(mg_ntohl(pkt->tcp->seq) + delta),
  4932. buf, len);
  4933. }
  4934. static struct mg_connection *accept_conn(struct mg_connection *lsn,
  4935. struct pkt *pkt) {
  4936. struct mg_connection *c = mg_alloc_conn(lsn->mgr);
  4937. if (c == NULL) {
  4938. MG_ERROR(("OOM"));
  4939. return NULL;
  4940. }
  4941. struct connstate *s = (struct connstate *) (c + 1);
  4942. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq);
  4943. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4944. settmout(c, MIP_TTYPE_KEEPALIVE);
  4945. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4946. c->rem.port = pkt->tcp->sport;
  4947. MG_DEBUG(("%lu accepted %M", c->id, mg_print_ip_port, &c->rem));
  4948. LIST_ADD_HEAD(struct mg_connection, &lsn->mgr->conns, c);
  4949. c->is_accepted = 1;
  4950. c->is_hexdumping = lsn->is_hexdumping;
  4951. c->pfn = lsn->pfn;
  4952. c->loc = lsn->loc;
  4953. c->pfn_data = lsn->pfn_data;
  4954. c->fn = lsn->fn;
  4955. c->fn_data = lsn->fn_data;
  4956. mg_call(c, MG_EV_OPEN, NULL);
  4957. mg_call(c, MG_EV_ACCEPT, NULL);
  4958. return c;
  4959. }
  4960. static size_t trim_len(struct mg_connection *c, size_t len) {
  4961. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4962. size_t eth_h_len = 14, ip_max_h_len = 24, tcp_max_h_len = 60, udp_h_len = 8;
  4963. size_t max_headers_len =
  4964. eth_h_len + ip_max_h_len + (c->is_udp ? udp_h_len : tcp_max_h_len);
  4965. size_t min_mtu = c->is_udp ? 68 /* RFC-791 */ : max_headers_len - eth_h_len;
  4966. // If the frame exceeds the available buffer, trim the length
  4967. if (len + max_headers_len > ifp->tx.len) {
  4968. len = ifp->tx.len - max_headers_len;
  4969. }
  4970. // Ensure the MTU isn't lower than the minimum allowed value
  4971. if (ifp->mtu < min_mtu) {
  4972. MG_ERROR(("MTU is lower than minimum, capping to %lu", min_mtu));
  4973. ifp->mtu = (uint16_t) min_mtu;
  4974. }
  4975. // If the total packet size exceeds the MTU, trim the length
  4976. if (len + max_headers_len - eth_h_len > ifp->mtu) {
  4977. len = ifp->mtu - max_headers_len + eth_h_len;
  4978. if (c->is_udp) {
  4979. MG_ERROR(("UDP datagram exceeds MTU. Truncating it."));
  4980. }
  4981. }
  4982. return len;
  4983. }
  4984. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  4985. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4986. struct connstate *s = (struct connstate *) (c + 1);
  4987. uint32_t dst_ip = *(uint32_t *) c->rem.ip;
  4988. len = trim_len(c, len);
  4989. if (c->is_udp) {
  4990. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, dst_ip, c->rem.port, buf, len);
  4991. } else {
  4992. size_t sent =
  4993. tx_tcp(ifp, s->mac, dst_ip, TH_PUSH | TH_ACK, c->loc.port, c->rem.port,
  4994. mg_htonl(s->seq), mg_htonl(s->ack), buf, len);
  4995. if (sent == 0) {
  4996. return MG_IO_WAIT;
  4997. } else if (sent == (size_t) -1) {
  4998. return MG_IO_ERR;
  4999. } else {
  5000. s->seq += (uint32_t) len;
  5001. if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
  5002. }
  5003. }
  5004. return (long) len;
  5005. }
  5006. static void handle_tls_recv(struct mg_connection *c, struct mg_iobuf *io) {
  5007. long n = mg_tls_recv(c, &io->buf[io->len], io->size - io->len);
  5008. if (n == MG_IO_ERR) {
  5009. mg_error(c, "TLS recv error");
  5010. } else if (n > 0) {
  5011. // Decrypted successfully - trigger MG_EV_READ
  5012. io->len += (size_t) n;
  5013. mg_call(c, MG_EV_READ, &n);
  5014. }
  5015. }
  5016. static void read_conn(struct mg_connection *c, struct pkt *pkt) {
  5017. struct connstate *s = (struct connstate *) (c + 1);
  5018. struct mg_iobuf *io = c->is_tls ? &c->rtls : &c->recv;
  5019. uint32_t seq = mg_ntohl(pkt->tcp->seq);
  5020. uint32_t rem_ip;
  5021. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5022. if (pkt->tcp->flags & TH_FIN) {
  5023. // If we initiated the closure, we reply with ACK upon receiving FIN
  5024. // If we didn't initiate it, we reply with FIN as part of the normal TCP
  5025. // closure process
  5026. uint8_t flags = TH_ACK;
  5027. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len + 1);
  5028. if (c->is_draining && s->ttype == MIP_TTYPE_FIN) {
  5029. if (s->seq == mg_htonl(pkt->tcp->ack)) { // Simultaneous closure ?
  5030. s->seq++; // Yes. Increment our SEQ
  5031. } else { // Otherwise,
  5032. s->seq = mg_htonl(pkt->tcp->ack); // Set to peer's ACK
  5033. }
  5034. } else {
  5035. flags |= TH_FIN;
  5036. c->is_draining = 1;
  5037. settmout(c, MIP_TTYPE_FIN);
  5038. }
  5039. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, flags,
  5040. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  5041. } else if (pkt->pay.len == 0) {
  5042. // TODO(cpq): handle this peer's ACK
  5043. } else if (seq != s->ack) {
  5044. uint32_t ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  5045. if (s->ack == ack) {
  5046. MG_VERBOSE(("ignoring duplicate pkt"));
  5047. } else {
  5048. MG_VERBOSE(("SEQ != ACK: %x %x %x", seq, s->ack, ack));
  5049. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  5050. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "",
  5051. 0);
  5052. }
  5053. } else if (io->size - io->len < pkt->pay.len &&
  5054. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  5055. mg_error(c, "oom");
  5056. } else {
  5057. // Copy TCP payload into the IO buffer. If the connection is plain text,
  5058. // we copy to c->recv. If the connection is TLS, this data is encrypted,
  5059. // therefore we copy that encrypted data to the c->rtls iobuffer instead,
  5060. // and then call mg_tls_recv() to decrypt it. NOTE: mg_tls_recv() will
  5061. // call back mg_io_recv() which grabs raw data from c->rtls
  5062. memcpy(&io->buf[io->len], pkt->pay.buf, pkt->pay.len);
  5063. io->len += pkt->pay.len;
  5064. MG_VERBOSE(("%lu SEQ %x -> %x", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  5065. // Advance ACK counter
  5066. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  5067. s->unacked += pkt->pay.len;
  5068. // size_t diff = s->acked <= s->ack ? s->ack - s->acked : s->ack;
  5069. if (s->unacked > MIP_TCP_WIN / 2 && s->acked != s->ack) {
  5070. // Send ACK immediately
  5071. MG_VERBOSE(("%lu imm ACK %lu", c->id, s->acked));
  5072. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  5073. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), NULL,
  5074. 0);
  5075. s->unacked = 0;
  5076. s->acked = s->ack;
  5077. if (s->ttype != MIP_TTYPE_KEEPALIVE) settmout(c, MIP_TTYPE_KEEPALIVE);
  5078. } else {
  5079. // if not already running, setup a timer to send an ACK later
  5080. if (s->ttype != MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_ACK);
  5081. }
  5082. if (c->is_tls && c->is_tls_hs) {
  5083. mg_tls_handshake(c);
  5084. } else if (c->is_tls) {
  5085. // TLS connection. Make room for decrypted data in c->recv
  5086. io = &c->recv;
  5087. if (io->size - io->len < pkt->pay.len &&
  5088. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  5089. mg_error(c, "oom");
  5090. } else {
  5091. // Decrypt data directly into c->recv
  5092. handle_tls_recv(c, io);
  5093. }
  5094. } else {
  5095. // Plain text connection, data is already in c->recv, trigger
  5096. // MG_EV_READ
  5097. mg_call(c, MG_EV_READ, &pkt->pay.len);
  5098. }
  5099. }
  5100. }
  5101. static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5102. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  5103. struct connstate *s = c == NULL ? NULL : (struct connstate *) (c + 1);
  5104. #if 0
  5105. MG_INFO(("%lu %hhu %d", c ? c->id : 0, pkt->tcp->flags, (int) pkt->pay.len));
  5106. #endif
  5107. if (c != NULL && c->is_connecting && pkt->tcp->flags == (TH_SYN | TH_ACK)) {
  5108. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq) + 1;
  5109. tx_tcp_pkt(ifp, pkt, TH_ACK, pkt->tcp->ack, NULL, 0);
  5110. c->is_connecting = 0; // Client connected
  5111. settmout(c, MIP_TTYPE_KEEPALIVE);
  5112. mg_call(c, MG_EV_CONNECT, NULL); // Let user know
  5113. } else if (c != NULL && c->is_connecting && pkt->tcp->flags != TH_ACK) {
  5114. // mg_hexdump(pkt->raw.buf, pkt->raw.len);
  5115. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5116. } else if (c != NULL && pkt->tcp->flags & TH_RST) {
  5117. mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  5118. } else if (c != NULL) {
  5119. #if 0
  5120. MG_DEBUG(("%lu %d %M:%hu -> %M:%hu", c->id, (int) pkt->raw.len,
  5121. mg_print_ip4, &pkt->ip->src, mg_ntohs(pkt->tcp->sport),
  5122. mg_print_ip4, &pkt->ip->dst, mg_ntohs(pkt->tcp->dport)));
  5123. mg_hexdump(pkt->pay.buf, pkt->pay.len);
  5124. #endif
  5125. s->tmiss = 0; // Reset missed keep-alive counter
  5126. if (s->ttype == MIP_TTYPE_KEEPALIVE) // Advance keep-alive timer
  5127. settmout(c,
  5128. MIP_TTYPE_KEEPALIVE); // unless a former ACK timeout is pending
  5129. read_conn(c, pkt); // Override timer with ACK timeout if needed
  5130. } else if ((c = getpeer(ifp->mgr, pkt, true)) == NULL) {
  5131. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5132. } else if (pkt->tcp->flags & TH_RST) {
  5133. if (c->is_accepted) mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  5134. // ignore RST if not connected
  5135. } else if (pkt->tcp->flags & TH_SYN) {
  5136. // Use peer's source port as ISN, in order to recognise the handshake
  5137. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(pkt->tcp->sport));
  5138. tx_tcp_pkt(ifp, pkt, TH_SYN | TH_ACK, isn, NULL, 0);
  5139. } else if (pkt->tcp->flags & TH_FIN) {
  5140. tx_tcp_pkt(ifp, pkt, TH_FIN | TH_ACK, pkt->tcp->ack, NULL, 0);
  5141. } else if (mg_htonl(pkt->tcp->ack) == mg_htons(pkt->tcp->sport) + 1U) {
  5142. accept_conn(c, pkt);
  5143. } else if (!c->is_accepted) { // no peer
  5144. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5145. } else {
  5146. // MG_VERBOSE(("dropped silently.."));
  5147. }
  5148. }
  5149. static void rx_ip(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5150. if (pkt->ip->frag & IP_MORE_FRAGS_MSK || pkt->ip->frag & IP_FRAG_OFFSET_MSK) {
  5151. if (pkt->ip->proto == 17) pkt->udp = (struct udp *) (pkt->ip + 1);
  5152. if (pkt->ip->proto == 6) pkt->tcp = (struct tcp *) (pkt->ip + 1);
  5153. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  5154. if (c) mg_error(c, "Received fragmented packet");
  5155. } else if (pkt->ip->proto == 1) {
  5156. pkt->icmp = (struct icmp *) (pkt->ip + 1);
  5157. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  5158. mkpay(pkt, pkt->icmp + 1);
  5159. rx_icmp(ifp, pkt);
  5160. } else if (pkt->ip->proto == 17) {
  5161. pkt->udp = (struct udp *) (pkt->ip + 1);
  5162. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  5163. mkpay(pkt, pkt->udp + 1);
  5164. MG_VERBOSE(("UDP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  5165. mg_ntohs(pkt->udp->sport), mg_print_ip4, &pkt->ip->dst,
  5166. mg_ntohs(pkt->udp->dport), (int) pkt->pay.len));
  5167. if (ifp->enable_dhcp_client && pkt->udp->dport == mg_htons(68)) {
  5168. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  5169. mkpay(pkt, pkt->dhcp + 1);
  5170. rx_dhcp_client(ifp, pkt);
  5171. } else if (ifp->enable_dhcp_server && pkt->udp->dport == mg_htons(67)) {
  5172. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  5173. mkpay(pkt, pkt->dhcp + 1);
  5174. rx_dhcp_server(ifp, pkt);
  5175. } else {
  5176. rx_udp(ifp, pkt);
  5177. }
  5178. } else if (pkt->ip->proto == 6) {
  5179. pkt->tcp = (struct tcp *) (pkt->ip + 1);
  5180. if (pkt->pay.len < sizeof(*pkt->tcp)) return;
  5181. mkpay(pkt, pkt->tcp + 1);
  5182. uint16_t iplen = mg_ntohs(pkt->ip->len);
  5183. uint16_t off = (uint16_t) (sizeof(*pkt->ip) + ((pkt->tcp->off >> 4) * 4U));
  5184. if (iplen >= off) pkt->pay.len = (size_t) (iplen - off);
  5185. MG_VERBOSE(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  5186. mg_ntohs(pkt->tcp->sport), mg_print_ip4, &pkt->ip->dst,
  5187. mg_ntohs(pkt->tcp->dport), (int) pkt->pay.len));
  5188. rx_tcp(ifp, pkt);
  5189. }
  5190. }
  5191. static void rx_ip6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5192. // MG_DEBUG(("IP %d", (int) len));
  5193. if (pkt->ip6->proto == 1 || pkt->ip6->proto == 58) {
  5194. pkt->icmp = (struct icmp *) (pkt->ip6 + 1);
  5195. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  5196. mkpay(pkt, pkt->icmp + 1);
  5197. rx_icmp(ifp, pkt);
  5198. } else if (pkt->ip6->proto == 17) {
  5199. pkt->udp = (struct udp *) (pkt->ip6 + 1);
  5200. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  5201. // MG_DEBUG((" UDP %u %u -> %u", len, mg_htons(udp->sport),
  5202. // mg_htons(udp->dport)));
  5203. mkpay(pkt, pkt->udp + 1);
  5204. }
  5205. }
  5206. static void mg_tcpip_rx(struct mg_tcpip_if *ifp, void *buf, size_t len) {
  5207. struct pkt pkt;
  5208. memset(&pkt, 0, sizeof(pkt));
  5209. pkt.raw.buf = (char *) buf;
  5210. pkt.raw.len = len;
  5211. pkt.eth = (struct eth *) buf;
  5212. // mg_hexdump(buf, len > 16 ? 16: len);
  5213. if (pkt.raw.len < sizeof(*pkt.eth)) return; // Truncated - runt?
  5214. if (ifp->enable_mac_check &&
  5215. memcmp(pkt.eth->dst, ifp->mac, sizeof(pkt.eth->dst)) != 0 &&
  5216. memcmp(pkt.eth->dst, broadcast, sizeof(pkt.eth->dst)) != 0)
  5217. return;
  5218. if (ifp->enable_crc32_check && len > 4) {
  5219. len -= 4; // TODO(scaprile): check on bigendian
  5220. uint32_t crc = mg_crc32(0, (const char *) buf, len);
  5221. if (memcmp((void *) ((size_t) buf + len), &crc, sizeof(crc))) return;
  5222. }
  5223. if (pkt.eth->type == mg_htons(0x806)) {
  5224. pkt.arp = (struct arp *) (pkt.eth + 1);
  5225. if (sizeof(*pkt.eth) + sizeof(*pkt.arp) > pkt.raw.len) return; // Truncated
  5226. rx_arp(ifp, &pkt);
  5227. } else if (pkt.eth->type == mg_htons(0x86dd)) {
  5228. pkt.ip6 = (struct ip6 *) (pkt.eth + 1);
  5229. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip6)) return; // Truncated
  5230. if ((pkt.ip6->ver >> 4) != 0x6) return; // Not IP
  5231. mkpay(&pkt, pkt.ip6 + 1);
  5232. rx_ip6(ifp, &pkt);
  5233. } else if (pkt.eth->type == mg_htons(0x800)) {
  5234. pkt.ip = (struct ip *) (pkt.eth + 1);
  5235. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  5236. // Truncate frame to what IP header tells us
  5237. if ((size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth) < pkt.raw.len) {
  5238. pkt.raw.len = (size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth);
  5239. }
  5240. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  5241. if ((pkt.ip->ver >> 4) != 4) return; // Not IP
  5242. mkpay(&pkt, pkt.ip + 1);
  5243. rx_ip(ifp, &pkt);
  5244. } else {
  5245. MG_DEBUG(("Unknown eth type %x", mg_htons(pkt.eth->type)));
  5246. if (mg_log_level >= MG_LL_VERBOSE) mg_hexdump(buf, len >= 32 ? 32 : len);
  5247. }
  5248. }
  5249. static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t now) {
  5250. struct mg_connection *c;
  5251. bool expired_1000ms = mg_timer_expired(&ifp->timer_1000ms, 1000, now);
  5252. ifp->now = now;
  5253. #if MG_ENABLE_TCPIP_PRINT_DEBUG_STATS
  5254. if (expired_1000ms) {
  5255. const char *names[] = {"down", "up", "req", "ready"};
  5256. MG_INFO(("Status: %s, IP: %M, rx:%u, tx:%u, dr:%u, er:%u",
  5257. names[ifp->state], mg_print_ip4, &ifp->ip, ifp->nrecv, ifp->nsent,
  5258. ifp->ndrop, ifp->nerr));
  5259. }
  5260. #endif
  5261. // Handle physical interface up/down status
  5262. if (expired_1000ms && ifp->driver->up) {
  5263. bool up = ifp->driver->up(ifp);
  5264. bool current = ifp->state != MG_TCPIP_STATE_DOWN;
  5265. if (up != current) {
  5266. ifp->state = up == false ? MG_TCPIP_STATE_DOWN
  5267. : ifp->enable_dhcp_client ? MG_TCPIP_STATE_UP
  5268. : MG_TCPIP_STATE_READY;
  5269. if (!up && ifp->enable_dhcp_client) ifp->ip = 0;
  5270. onstatechange(ifp);
  5271. }
  5272. if (ifp->state == MG_TCPIP_STATE_DOWN) MG_ERROR(("Network is down"));
  5273. }
  5274. if (ifp->state == MG_TCPIP_STATE_DOWN) return;
  5275. // DHCP RFC-2131 (4.4)
  5276. if (ifp->state == MG_TCPIP_STATE_UP && expired_1000ms) {
  5277. tx_dhcp_discover(ifp); // INIT (4.4.1)
  5278. } else if (expired_1000ms && ifp->state == MG_TCPIP_STATE_READY &&
  5279. ifp->lease_expire > 0) { // BOUND / RENEWING / REBINDING
  5280. if (ifp->now >= ifp->lease_expire) {
  5281. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0; // expired, release IP
  5282. onstatechange(ifp);
  5283. } else if (ifp->now + 30UL * 60UL * 1000UL > ifp->lease_expire &&
  5284. ((ifp->now / 1000) % 60) == 0) {
  5285. // hack: 30 min before deadline, try to rebind (4.3.6) every min
  5286. tx_dhcp_request_re(ifp, (uint8_t *) broadcast, ifp->ip, 0xffffffff);
  5287. } // TODO(): Handle T1 (RENEWING) and T2 (REBINDING) (4.4.5)
  5288. }
  5289. // Read data from the network
  5290. if (ifp->driver->rx != NULL) { // Polling driver. We must call it
  5291. size_t len =
  5292. ifp->driver->rx(ifp->recv_queue.buf, ifp->recv_queue.size, ifp);
  5293. if (len > 0) {
  5294. ifp->nrecv++;
  5295. mg_tcpip_rx(ifp, ifp->recv_queue.buf, len);
  5296. }
  5297. } else { // Interrupt-based driver. Fills recv queue itself
  5298. char *buf;
  5299. size_t len = mg_queue_next(&ifp->recv_queue, &buf);
  5300. if (len > 0) {
  5301. mg_tcpip_rx(ifp, buf, len);
  5302. mg_queue_del(&ifp->recv_queue, len);
  5303. }
  5304. }
  5305. // Process timeouts
  5306. for (c = ifp->mgr->conns; c != NULL; c = c->next) {
  5307. if (c->is_udp || c->is_listening || c->is_resolving) continue;
  5308. struct connstate *s = (struct connstate *) (c + 1);
  5309. uint32_t rem_ip;
  5310. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5311. if (now > s->timer) {
  5312. if (s->ttype == MIP_TTYPE_ACK && s->acked != s->ack) {
  5313. MG_VERBOSE(("%lu ack %x %x", c->id, s->seq, s->ack));
  5314. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  5315. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5316. s->acked = s->ack;
  5317. } else if (s->ttype == MIP_TTYPE_ARP) {
  5318. mg_error(c, "ARP timeout");
  5319. } else if (s->ttype == MIP_TTYPE_SYN) {
  5320. mg_error(c, "Connection timeout");
  5321. } else if (s->ttype == MIP_TTYPE_FIN) {
  5322. c->is_closing = 1;
  5323. continue;
  5324. } else {
  5325. if (s->tmiss++ > 2) {
  5326. mg_error(c, "keepalive");
  5327. } else {
  5328. MG_VERBOSE(("%lu keepalive", c->id));
  5329. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  5330. mg_htonl(s->seq - 1), mg_htonl(s->ack), NULL, 0);
  5331. }
  5332. }
  5333. settmout(c, MIP_TTYPE_KEEPALIVE);
  5334. }
  5335. }
  5336. }
  5337. // This function executes in interrupt context, thus it should copy data
  5338. // somewhere fast. Note that newlib's malloc is not thread safe, thus use
  5339. // our lock-free queue with preallocated buffer to copy data and return asap
  5340. void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) {
  5341. char *p;
  5342. if (mg_queue_book(&ifp->recv_queue, &p, len) >= len) {
  5343. memcpy(p, buf, len);
  5344. mg_queue_add(&ifp->recv_queue, len);
  5345. ifp->nrecv++;
  5346. } else {
  5347. ifp->ndrop++;
  5348. }
  5349. }
  5350. void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
  5351. // If MAC address is not set, make a random one
  5352. if (ifp->mac[0] == 0 && ifp->mac[1] == 0 && ifp->mac[2] == 0 &&
  5353. ifp->mac[3] == 0 && ifp->mac[4] == 0 && ifp->mac[5] == 0) {
  5354. ifp->mac[0] = 0x02; // Locally administered, unicast
  5355. mg_random(&ifp->mac[1], sizeof(ifp->mac) - 1);
  5356. MG_INFO(("MAC not set. Generated random: %M", mg_print_mac, ifp->mac));
  5357. }
  5358. if (ifp->driver->init && !ifp->driver->init(ifp)) {
  5359. MG_ERROR(("driver init failed"));
  5360. } else {
  5361. size_t framesize = 1540;
  5362. ifp->tx.buf = (char *) calloc(1, framesize), ifp->tx.len = framesize;
  5363. if (ifp->recv_queue.size == 0)
  5364. ifp->recv_queue.size = ifp->driver->rx ? framesize : 8192;
  5365. ifp->recv_queue.buf = (char *) calloc(1, ifp->recv_queue.size);
  5366. ifp->timer_1000ms = mg_millis();
  5367. mgr->priv = ifp;
  5368. ifp->mgr = mgr;
  5369. ifp->mtu = MG_TCPIP_MTU_DEFAULT;
  5370. mgr->extraconnsize = sizeof(struct connstate);
  5371. if (ifp->ip == 0) ifp->enable_dhcp_client = true;
  5372. memset(ifp->gwmac, 255, sizeof(ifp->gwmac)); // Set to broadcast
  5373. mg_random(&ifp->eport, sizeof(ifp->eport)); // Random from 0 to 65535
  5374. ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
  5375. // MG_EPHEMERAL_PORT_BASE to 65535
  5376. if (ifp->tx.buf == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
  5377. }
  5378. }
  5379. void mg_tcpip_free(struct mg_tcpip_if *ifp) {
  5380. free(ifp->recv_queue.buf);
  5381. free(ifp->tx.buf);
  5382. }
  5383. static void send_syn(struct mg_connection *c) {
  5384. struct connstate *s = (struct connstate *) (c + 1);
  5385. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(c->loc.port));
  5386. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5387. uint32_t rem_ip;
  5388. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5389. tx_tcp(ifp, s->mac, rem_ip, TH_SYN, c->loc.port, c->rem.port, isn, 0, NULL,
  5390. 0);
  5391. }
  5392. void mg_connect_resolved(struct mg_connection *c) {
  5393. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5394. uint32_t rem_ip;
  5395. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5396. c->is_resolving = 0;
  5397. if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
  5398. memcpy(c->loc.ip, &ifp->ip, sizeof(uint32_t));
  5399. c->loc.port = mg_htons(ifp->eport++);
  5400. MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
  5401. &c->rem));
  5402. mg_call(c, MG_EV_RESOLVE, NULL);
  5403. if (c->is_udp && (rem_ip == 0xffffffff || rem_ip == (ifp->ip | ~ifp->mask))) {
  5404. struct connstate *s = (struct connstate *) (c + 1);
  5405. memset(s->mac, 0xFF, sizeof(s->mac)); // global or local broadcast
  5406. } else if (ifp->ip && ((rem_ip & ifp->mask) == (ifp->ip & ifp->mask))) {
  5407. // If we're in the same LAN, fire an ARP lookup.
  5408. MG_DEBUG(("%lu ARP lookup...", c->id));
  5409. arp_ask(ifp, rem_ip);
  5410. settmout(c, MIP_TTYPE_ARP);
  5411. c->is_arplooking = 1;
  5412. c->is_connecting = 1;
  5413. } else if ((*((uint8_t *) &rem_ip) & 0xE0) == 0xE0) {
  5414. struct connstate *s = (struct connstate *) (c + 1); // 224 to 239, E0 to EF
  5415. uint8_t mcastp[3] = {0x01, 0x00, 0x5E}; // multicast group
  5416. memcpy(s->mac, mcastp, 3);
  5417. memcpy(s->mac + 3, ((uint8_t *) &rem_ip) + 1, 3); // 23 LSb
  5418. s->mac[3] &= 0x7F;
  5419. } else {
  5420. struct connstate *s = (struct connstate *) (c + 1);
  5421. memcpy(s->mac, ifp->gwmac, sizeof(ifp->gwmac));
  5422. if (c->is_udp) {
  5423. mg_call(c, MG_EV_CONNECT, NULL);
  5424. } else {
  5425. send_syn(c);
  5426. settmout(c, MIP_TTYPE_SYN);
  5427. c->is_connecting = 1;
  5428. }
  5429. }
  5430. }
  5431. bool mg_open_listener(struct mg_connection *c, const char *url) {
  5432. c->loc.port = mg_htons(mg_url_port(url));
  5433. return true;
  5434. }
  5435. static void write_conn(struct mg_connection *c) {
  5436. long len = c->is_tls ? mg_tls_send(c, c->send.buf, c->send.len)
  5437. : mg_io_send(c, c->send.buf, c->send.len);
  5438. if (len == MG_IO_ERR) {
  5439. mg_error(c, "tx err");
  5440. } else if (len > 0) {
  5441. mg_iobuf_del(&c->send, 0, (size_t) len);
  5442. mg_call(c, MG_EV_WRITE, &len);
  5443. }
  5444. }
  5445. static void init_closure(struct mg_connection *c) {
  5446. struct connstate *s = (struct connstate *) (c + 1);
  5447. if (c->is_udp == false && c->is_listening == false &&
  5448. c->is_connecting == false) { // For TCP conns,
  5449. struct mg_tcpip_if *ifp =
  5450. (struct mg_tcpip_if *) c->mgr->priv; // send TCP FIN
  5451. uint32_t rem_ip;
  5452. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5453. tx_tcp(ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port, c->rem.port,
  5454. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5455. settmout(c, MIP_TTYPE_FIN);
  5456. }
  5457. }
  5458. static void close_conn(struct mg_connection *c) {
  5459. struct connstate *s = (struct connstate *) (c + 1);
  5460. mg_iobuf_free(&s->raw); // For TLS connections, release raw data
  5461. mg_close_conn(c);
  5462. }
  5463. static bool can_write(struct mg_connection *c) {
  5464. return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 &&
  5465. c->is_tls_hs == 0 && c->is_arplooking == 0;
  5466. }
  5467. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  5468. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) mgr->priv;
  5469. struct mg_connection *c, *tmp;
  5470. uint64_t now = mg_millis();
  5471. mg_timer_poll(&mgr->timers, now);
  5472. if (ifp == NULL || ifp->driver == NULL) return;
  5473. mg_tcpip_poll(ifp, now);
  5474. for (c = mgr->conns; c != NULL; c = tmp) {
  5475. tmp = c->next;
  5476. struct connstate *s = (struct connstate *) (c + 1);
  5477. mg_call(c, MG_EV_POLL, &now);
  5478. MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't',
  5479. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  5480. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  5481. if (c->is_tls && mg_tls_pending(c) > 0)
  5482. handle_tls_recv(c, (struct mg_iobuf *) &c->rtls);
  5483. if (can_write(c)) write_conn(c);
  5484. if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN)
  5485. init_closure(c);
  5486. if (c->is_closing) close_conn(c);
  5487. }
  5488. (void) ms;
  5489. }
  5490. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  5491. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5492. bool res = false;
  5493. uint32_t rem_ip;
  5494. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5495. if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) {
  5496. mg_error(c, "net down");
  5497. } else if (c->is_udp) {
  5498. struct connstate *s = (struct connstate *) (c + 1);
  5499. len = trim_len(c, len); // Trimming length if necessary
  5500. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len);
  5501. res = true;
  5502. } else {
  5503. res = mg_iobuf_add(&c->send, c->send.len, buf, len);
  5504. }
  5505. return res;
  5506. }
  5507. #endif // MG_ENABLE_TCPIP
  5508. #ifdef MG_ENABLE_LINES
  5509. #line 1 "src/ota_dummy.c"
  5510. #endif
  5511. #if MG_OTA == MG_OTA_NONE
  5512. bool mg_ota_begin(size_t new_firmware_size) {
  5513. (void) new_firmware_size;
  5514. return true;
  5515. }
  5516. bool mg_ota_write(const void *buf, size_t len) {
  5517. (void) buf, (void) len;
  5518. return true;
  5519. }
  5520. bool mg_ota_end(void) {
  5521. return true;
  5522. }
  5523. bool mg_ota_commit(void) {
  5524. return true;
  5525. }
  5526. bool mg_ota_rollback(void) {
  5527. return true;
  5528. }
  5529. int mg_ota_status(int fw) {
  5530. (void) fw;
  5531. return 0;
  5532. }
  5533. uint32_t mg_ota_crc32(int fw) {
  5534. (void) fw;
  5535. return 0;
  5536. }
  5537. uint32_t mg_ota_timestamp(int fw) {
  5538. (void) fw;
  5539. return 0;
  5540. }
  5541. size_t mg_ota_size(int fw) {
  5542. (void) fw;
  5543. return 0;
  5544. }
  5545. MG_IRAM void mg_ota_boot(void) {
  5546. }
  5547. #endif
  5548. #ifdef MG_ENABLE_LINES
  5549. #line 1 "src/ota_esp32.c"
  5550. #endif
  5551. #if MG_ARCH == MG_ARCH_ESP32 && MG_OTA == MG_OTA_ESP32
  5552. static const esp_partition_t *s_ota_update_partition;
  5553. static esp_ota_handle_t s_ota_update_handle;
  5554. static bool s_ota_success;
  5555. // Those empty macros do nothing, but mark places in the code which could
  5556. // potentially trigger a watchdog reboot due to the log flash erase operation
  5557. #define disable_wdt()
  5558. #define enable_wdt()
  5559. bool mg_ota_begin(size_t new_firmware_size) {
  5560. if (s_ota_update_partition != NULL) {
  5561. MG_ERROR(("Update in progress. Call mg_ota_end() ?"));
  5562. return false;
  5563. } else {
  5564. s_ota_success = false;
  5565. disable_wdt();
  5566. s_ota_update_partition = esp_ota_get_next_update_partition(NULL);
  5567. esp_err_t err = esp_ota_begin(s_ota_update_partition, new_firmware_size,
  5568. &s_ota_update_handle);
  5569. enable_wdt();
  5570. MG_DEBUG(("esp_ota_begin(): %d", err));
  5571. s_ota_success = (err == ESP_OK);
  5572. }
  5573. return s_ota_success;
  5574. }
  5575. bool mg_ota_write(const void *buf, size_t len) {
  5576. disable_wdt();
  5577. esp_err_t err = esp_ota_write(s_ota_update_handle, buf, len);
  5578. enable_wdt();
  5579. MG_INFO(("esp_ota_write(): %d", err));
  5580. s_ota_success = err == ESP_OK;
  5581. return s_ota_success;
  5582. }
  5583. bool mg_ota_end(void) {
  5584. esp_err_t err = esp_ota_end(s_ota_update_handle);
  5585. MG_DEBUG(("esp_ota_end(%p): %d", s_ota_update_handle, err));
  5586. if (s_ota_success && err == ESP_OK) {
  5587. err = esp_ota_set_boot_partition(s_ota_update_partition);
  5588. s_ota_success = (err == ESP_OK);
  5589. }
  5590. MG_DEBUG(("Finished ESP32 OTA, success: %d", s_ota_success));
  5591. s_ota_update_partition = NULL;
  5592. return s_ota_success;
  5593. }
  5594. #endif
  5595. #ifdef MG_ENABLE_LINES
  5596. #line 1 "src/ota_flash.c"
  5597. #endif
  5598. // This OTA implementation uses the internal flash API outlined in device.h
  5599. // It splits flash into 2 equal partitions, and stores OTA status in the
  5600. // last sector of the partition.
  5601. #if MG_OTA == MG_OTA_FLASH
  5602. #define MG_OTADATA_KEY 0xb07afed0
  5603. static char *s_addr; // Current address to write to
  5604. static size_t s_size; // Firmware size to flash. In-progress indicator
  5605. static uint32_t s_crc32; // Firmware checksum
  5606. struct mg_otadata {
  5607. uint32_t crc32, size, timestamp, status;
  5608. };
  5609. bool mg_ota_begin(size_t new_firmware_size) {
  5610. bool ok = false;
  5611. if (s_size) {
  5612. MG_ERROR(("OTA already in progress. Call mg_ota_end()"));
  5613. } else {
  5614. size_t half = mg_flash_size() / 2, max = half - mg_flash_sector_size();
  5615. s_crc32 = 0;
  5616. s_addr = (char *) mg_flash_start() + half;
  5617. MG_DEBUG(("Firmware %lu bytes, max %lu", new_firmware_size, max));
  5618. if (new_firmware_size < max) {
  5619. ok = true;
  5620. s_size = new_firmware_size;
  5621. MG_INFO(("Starting OTA, firmware size %lu", s_size));
  5622. } else {
  5623. MG_ERROR(("Firmware %lu is too big to fit %lu", new_firmware_size, max));
  5624. }
  5625. }
  5626. return ok;
  5627. }
  5628. bool mg_ota_write(const void *buf, size_t len) {
  5629. bool ok = false;
  5630. if (s_size == 0) {
  5631. MG_ERROR(("OTA is not started, call mg_ota_begin()"));
  5632. } else {
  5633. size_t align = mg_flash_write_align();
  5634. size_t len_aligned_down = MG_ROUND_DOWN(len, align);
  5635. if (len_aligned_down) ok = mg_flash_write(s_addr, buf, len_aligned_down);
  5636. if (len_aligned_down < len) {
  5637. size_t left = len - len_aligned_down;
  5638. char tmp[align];
  5639. memset(tmp, 0xff, sizeof(tmp));
  5640. memcpy(tmp, (char *) buf + len_aligned_down, left);
  5641. ok = mg_flash_write(s_addr + len_aligned_down, tmp, sizeof(tmp));
  5642. }
  5643. s_crc32 = mg_crc32(s_crc32, (char *) buf, len); // Update CRC
  5644. MG_DEBUG(("%#x %p %lu -> %d", s_addr - len, buf, len, ok));
  5645. s_addr += len;
  5646. }
  5647. return ok;
  5648. }
  5649. MG_IRAM static uint32_t mg_fwkey(int fw) {
  5650. uint32_t key = MG_OTADATA_KEY + fw;
  5651. int bank = mg_flash_bank();
  5652. if (bank == 2 && fw == MG_FIRMWARE_PREVIOUS) key--;
  5653. if (bank == 2 && fw == MG_FIRMWARE_CURRENT) key++;
  5654. return key;
  5655. }
  5656. bool mg_ota_end(void) {
  5657. char *base = (char *) mg_flash_start() + mg_flash_size() / 2;
  5658. bool ok = false;
  5659. if (s_size) {
  5660. size_t size = s_addr - base;
  5661. uint32_t crc32 = mg_crc32(0, base, s_size);
  5662. if (size == s_size && crc32 == s_crc32) {
  5663. uint32_t now = (uint32_t) (mg_now() / 1000);
  5664. struct mg_otadata od = {crc32, size, now, MG_OTA_FIRST_BOOT};
  5665. uint32_t key = mg_fwkey(MG_FIRMWARE_PREVIOUS);
  5666. ok = mg_flash_save(NULL, key, &od, sizeof(od));
  5667. }
  5668. MG_DEBUG(("CRC: %x/%x, size: %lu/%lu, status: %s", s_crc32, crc32, s_size,
  5669. size, ok ? "ok" : "fail"));
  5670. s_size = 0;
  5671. if (ok) ok = mg_flash_swap_bank();
  5672. }
  5673. MG_INFO(("Finishing OTA: %s", ok ? "ok" : "fail"));
  5674. return ok;
  5675. }
  5676. MG_IRAM static struct mg_otadata mg_otadata(int fw) {
  5677. uint32_t key = mg_fwkey(fw);
  5678. struct mg_otadata od = {};
  5679. MG_INFO(("Loading %s OTA data", fw == MG_FIRMWARE_CURRENT ? "curr" : "prev"));
  5680. mg_flash_load(NULL, key, &od, sizeof(od));
  5681. // MG_DEBUG(("Loaded OTA data. fw %d, bank %d, key %p", fw, bank, key));
  5682. // mg_hexdump(&od, sizeof(od));
  5683. return od;
  5684. }
  5685. int mg_ota_status(int fw) {
  5686. struct mg_otadata od = mg_otadata(fw);
  5687. return od.status;
  5688. }
  5689. uint32_t mg_ota_crc32(int fw) {
  5690. struct mg_otadata od = mg_otadata(fw);
  5691. return od.crc32;
  5692. }
  5693. uint32_t mg_ota_timestamp(int fw) {
  5694. struct mg_otadata od = mg_otadata(fw);
  5695. return od.timestamp;
  5696. }
  5697. size_t mg_ota_size(int fw) {
  5698. struct mg_otadata od = mg_otadata(fw);
  5699. return od.size;
  5700. }
  5701. MG_IRAM bool mg_ota_commit(void) {
  5702. bool ok = true;
  5703. struct mg_otadata od = mg_otadata(MG_FIRMWARE_CURRENT);
  5704. if (od.status != MG_OTA_COMMITTED) {
  5705. od.status = MG_OTA_COMMITTED;
  5706. MG_INFO(("Committing current firmware, OD size %lu", sizeof(od)));
  5707. ok = mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &od, sizeof(od));
  5708. }
  5709. return ok;
  5710. }
  5711. bool mg_ota_rollback(void) {
  5712. MG_DEBUG(("Rolling firmware back"));
  5713. if (mg_flash_bank() == 0) {
  5714. // No dual bank support. Mark previous firmware as FIRST_BOOT
  5715. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5716. prev.status = MG_OTA_FIRST_BOOT;
  5717. return mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &prev,
  5718. sizeof(prev));
  5719. } else {
  5720. return mg_flash_swap_bank();
  5721. }
  5722. }
  5723. MG_IRAM void mg_ota_boot(void) {
  5724. MG_INFO(("Booting. Flash bank: %d", mg_flash_bank()));
  5725. struct mg_otadata curr = mg_otadata(MG_FIRMWARE_CURRENT);
  5726. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5727. if (curr.status == MG_OTA_FIRST_BOOT) {
  5728. if (prev.status == MG_OTA_UNAVAILABLE) {
  5729. MG_INFO(("Setting previous firmware state to committed"));
  5730. prev.status = MG_OTA_COMMITTED;
  5731. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_PREVIOUS), &prev, sizeof(prev));
  5732. }
  5733. curr.status = MG_OTA_UNCOMMITTED;
  5734. MG_INFO(("First boot, setting status to UNCOMMITTED"));
  5735. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &curr, sizeof(curr));
  5736. } else if (prev.status == MG_OTA_FIRST_BOOT && mg_flash_bank() == 0) {
  5737. // Swap paritions. Pray power does not disappear
  5738. size_t fs = mg_flash_size(), ss = mg_flash_sector_size();
  5739. char *partition1 = mg_flash_start();
  5740. char *partition2 = mg_flash_start() + fs / 2;
  5741. size_t ofs, max = fs / 2 - ss; // Set swap size to the whole partition
  5742. if (curr.status != MG_OTA_UNAVAILABLE &&
  5743. prev.status != MG_OTA_UNAVAILABLE) {
  5744. // We know exact sizes of both firmwares.
  5745. // Shrink swap size to the MAX(firmware1, firmware2)
  5746. size_t sz = curr.size > prev.size ? curr.size : prev.size;
  5747. if (sz > 0 && sz < max) max = sz;
  5748. }
  5749. // MG_OTA_FIRST_BOOT -> MG_OTA_UNCOMMITTED
  5750. prev.status = MG_OTA_UNCOMMITTED;
  5751. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_CURRENT, &prev,
  5752. sizeof(prev));
  5753. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &curr,
  5754. sizeof(curr));
  5755. MG_INFO(("Swapping partitions, size %u (%u sectors)", max, max / ss));
  5756. MG_INFO(("Do NOT power off..."));
  5757. mg_log_level = MG_LL_NONE;
  5758. // We use the last sector of partition2 for OTA data/config storage
  5759. // Therefore we can use last sector of partition1 for swapping
  5760. char *tmpsector = partition1 + fs / 2 - ss; // Last sector of partition1
  5761. (void) tmpsector;
  5762. for (ofs = 0; ofs < max; ofs += ss) {
  5763. // mg_flash_erase(tmpsector);
  5764. mg_flash_write(tmpsector, partition1 + ofs, ss);
  5765. // mg_flash_erase(partition1 + ofs);
  5766. mg_flash_write(partition1 + ofs, partition2 + ofs, ss);
  5767. // mg_flash_erase(partition2 + ofs);
  5768. mg_flash_write(partition2 + ofs, tmpsector, ss);
  5769. }
  5770. mg_device_reset();
  5771. }
  5772. }
  5773. #endif
  5774. #ifdef MG_ENABLE_LINES
  5775. #line 1 "src/printf.c"
  5776. #endif
  5777. size_t mg_queue_vprintf(struct mg_queue *q, const char *fmt, va_list *ap) {
  5778. size_t len = mg_snprintf(NULL, 0, fmt, ap);
  5779. char *buf;
  5780. if (len == 0 || mg_queue_book(q, &buf, len + 1) < len + 1) {
  5781. len = 0; // Nah. Not enough space
  5782. } else {
  5783. len = mg_vsnprintf((char *) buf, len + 1, fmt, ap);
  5784. mg_queue_add(q, len);
  5785. }
  5786. return len;
  5787. }
  5788. size_t mg_queue_printf(struct mg_queue *q, const char *fmt, ...) {
  5789. va_list ap;
  5790. size_t len;
  5791. va_start(ap, fmt);
  5792. len = mg_queue_vprintf(q, fmt, &ap);
  5793. va_end(ap);
  5794. return len;
  5795. }
  5796. static void mg_pfn_iobuf_private(char ch, void *param, bool expand) {
  5797. struct mg_iobuf *io = (struct mg_iobuf *) param;
  5798. if (expand && io->len + 2 > io->size) mg_iobuf_resize(io, io->len + 2);
  5799. if (io->len + 2 <= io->size) {
  5800. io->buf[io->len++] = (uint8_t) ch;
  5801. io->buf[io->len] = 0;
  5802. } else if (io->len < io->size) {
  5803. io->buf[io->len++] = 0; // Guarantee to 0-terminate
  5804. }
  5805. }
  5806. static void mg_putchar_iobuf_static(char ch, void *param) {
  5807. mg_pfn_iobuf_private(ch, param, false);
  5808. }
  5809. void mg_pfn_iobuf(char ch, void *param) {
  5810. mg_pfn_iobuf_private(ch, param, true);
  5811. }
  5812. size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap) {
  5813. struct mg_iobuf io = {(uint8_t *) buf, len, 0, 0};
  5814. size_t n = mg_vxprintf(mg_putchar_iobuf_static, &io, fmt, ap);
  5815. if (n < len) buf[n] = '\0';
  5816. return n;
  5817. }
  5818. size_t mg_snprintf(char *buf, size_t len, const char *fmt, ...) {
  5819. va_list ap;
  5820. size_t n;
  5821. va_start(ap, fmt);
  5822. n = mg_vsnprintf(buf, len, fmt, &ap);
  5823. va_end(ap);
  5824. return n;
  5825. }
  5826. char *mg_vmprintf(const char *fmt, va_list *ap) {
  5827. struct mg_iobuf io = {0, 0, 0, 256};
  5828. mg_vxprintf(mg_pfn_iobuf, &io, fmt, ap);
  5829. return (char *) io.buf;
  5830. }
  5831. char *mg_mprintf(const char *fmt, ...) {
  5832. char *s;
  5833. va_list ap;
  5834. va_start(ap, fmt);
  5835. s = mg_vmprintf(fmt, &ap);
  5836. va_end(ap);
  5837. return s;
  5838. }
  5839. void mg_pfn_stdout(char c, void *param) {
  5840. putchar(c);
  5841. (void) param;
  5842. }
  5843. static size_t print_ip4(void (*out)(char, void *), void *arg, uint8_t *p) {
  5844. return mg_xprintf(out, arg, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  5845. }
  5846. static size_t print_ip6(void (*out)(char, void *), void *arg, uint16_t *p) {
  5847. return mg_xprintf(out, arg, "[%x:%x:%x:%x:%x:%x:%x:%x]", mg_ntohs(p[0]),
  5848. mg_ntohs(p[1]), mg_ntohs(p[2]), mg_ntohs(p[3]),
  5849. mg_ntohs(p[4]), mg_ntohs(p[5]), mg_ntohs(p[6]),
  5850. mg_ntohs(p[7]));
  5851. }
  5852. size_t mg_print_ip4(void (*out)(char, void *), void *arg, va_list *ap) {
  5853. uint8_t *p = va_arg(*ap, uint8_t *);
  5854. return print_ip4(out, arg, p);
  5855. }
  5856. size_t mg_print_ip6(void (*out)(char, void *), void *arg, va_list *ap) {
  5857. uint16_t *p = va_arg(*ap, uint16_t *);
  5858. return print_ip6(out, arg, p);
  5859. }
  5860. size_t mg_print_ip(void (*out)(char, void *), void *arg, va_list *ap) {
  5861. struct mg_addr *addr = va_arg(*ap, struct mg_addr *);
  5862. if (addr->is_ip6) return print_ip6(out, arg, (uint16_t *) addr->ip);
  5863. return print_ip4(out, arg, (uint8_t *) &addr->ip);
  5864. }
  5865. size_t mg_print_ip_port(void (*out)(char, void *), void *arg, va_list *ap) {
  5866. struct mg_addr *a = va_arg(*ap, struct mg_addr *);
  5867. return mg_xprintf(out, arg, "%M:%hu", mg_print_ip, a, mg_ntohs(a->port));
  5868. }
  5869. size_t mg_print_mac(void (*out)(char, void *), void *arg, va_list *ap) {
  5870. uint8_t *p = va_arg(*ap, uint8_t *);
  5871. return mg_xprintf(out, arg, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2],
  5872. p[3], p[4], p[5]);
  5873. }
  5874. static char mg_esc(int c, bool esc) {
  5875. const char *p, *esc1 = "\b\f\n\r\t\\\"", *esc2 = "bfnrt\\\"";
  5876. for (p = esc ? esc1 : esc2; *p != '\0'; p++) {
  5877. if (*p == c) return esc ? esc2[p - esc1] : esc1[p - esc2];
  5878. }
  5879. return 0;
  5880. }
  5881. static char mg_escape(int c) {
  5882. return mg_esc(c, true);
  5883. }
  5884. static size_t qcpy(void (*out)(char, void *), void *ptr, char *buf,
  5885. size_t len) {
  5886. size_t i = 0, extra = 0;
  5887. for (i = 0; i < len && buf[i] != '\0'; i++) {
  5888. char c = mg_escape(buf[i]);
  5889. if (c) {
  5890. out('\\', ptr), out(c, ptr), extra++;
  5891. } else {
  5892. out(buf[i], ptr);
  5893. }
  5894. }
  5895. return i + extra;
  5896. }
  5897. static size_t bcpy(void (*out)(char, void *), void *arg, uint8_t *buf,
  5898. size_t len) {
  5899. size_t i, j, n = 0;
  5900. const char *t =
  5901. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5902. for (i = 0; i < len; i += 3) {
  5903. uint8_t c1 = buf[i], c2 = i + 1 < len ? buf[i + 1] : 0,
  5904. c3 = i + 2 < len ? buf[i + 2] : 0;
  5905. char tmp[4] = {t[c1 >> 2], t[(c1 & 3) << 4 | (c2 >> 4)], '=', '='};
  5906. if (i + 1 < len) tmp[2] = t[(c2 & 15) << 2 | (c3 >> 6)];
  5907. if (i + 2 < len) tmp[3] = t[c3 & 63];
  5908. for (j = 0; j < sizeof(tmp) && tmp[j] != '\0'; j++) out(tmp[j], arg);
  5909. n += j;
  5910. }
  5911. return n;
  5912. }
  5913. size_t mg_print_hex(void (*out)(char, void *), void *arg, va_list *ap) {
  5914. size_t bl = (size_t) va_arg(*ap, int);
  5915. uint8_t *p = va_arg(*ap, uint8_t *);
  5916. const char *hex = "0123456789abcdef";
  5917. size_t j;
  5918. for (j = 0; j < bl; j++) {
  5919. out(hex[(p[j] >> 4) & 0x0F], arg);
  5920. out(hex[p[j] & 0x0F], arg);
  5921. }
  5922. return 2 * bl;
  5923. }
  5924. size_t mg_print_base64(void (*out)(char, void *), void *arg, va_list *ap) {
  5925. size_t len = (size_t) va_arg(*ap, int);
  5926. uint8_t *buf = va_arg(*ap, uint8_t *);
  5927. return bcpy(out, arg, buf, len);
  5928. }
  5929. size_t mg_print_esc(void (*out)(char, void *), void *arg, va_list *ap) {
  5930. size_t len = (size_t) va_arg(*ap, int);
  5931. char *p = va_arg(*ap, char *);
  5932. if (len == 0) len = p == NULL ? 0 : strlen(p);
  5933. return qcpy(out, arg, p, len);
  5934. }
  5935. #ifdef MG_ENABLE_LINES
  5936. #line 1 "src/queue.c"
  5937. #endif
  5938. #if (defined(__GNUC__) && (__GNUC__ > 4) || \
  5939. (defined(__GNUC_MINOR__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
  5940. defined(__clang__)
  5941. #define MG_MEMORY_BARRIER() __sync_synchronize()
  5942. #elif defined(_MSC_VER) && _MSC_VER >= 1700
  5943. #define MG_MEMORY_BARRIER() MemoryBarrier()
  5944. #elif !defined(MG_MEMORY_BARRIER)
  5945. #define MG_MEMORY_BARRIER()
  5946. #endif
  5947. // Every message in a queue is prepended by a 32-bit message length (ML).
  5948. // If ML is 0, then it is the end, and reader must wrap to the beginning.
  5949. //
  5950. // Queue when q->tail <= q->head:
  5951. // |----- free -----| ML | message1 | ML | message2 | ----- free ------|
  5952. // ^ ^ ^ ^
  5953. // buf tail head len
  5954. //
  5955. // Queue when q->tail > q->head:
  5956. // | ML | message2 |----- free ------| ML | message1 | 0 |---- free ----|
  5957. // ^ ^ ^ ^
  5958. // buf head tail len
  5959. void mg_queue_init(struct mg_queue *q, char *buf, size_t size) {
  5960. q->size = size;
  5961. q->buf = buf;
  5962. q->head = q->tail = 0;
  5963. }
  5964. static size_t mg_queue_read_len(struct mg_queue *q) {
  5965. uint32_t n = 0;
  5966. MG_MEMORY_BARRIER();
  5967. memcpy(&n, q->buf + q->tail, sizeof(n));
  5968. assert(q->tail + n + sizeof(n) <= q->size);
  5969. return n;
  5970. }
  5971. static void mg_queue_write_len(struct mg_queue *q, size_t len) {
  5972. uint32_t n = (uint32_t) len;
  5973. memcpy(q->buf + q->head, &n, sizeof(n));
  5974. MG_MEMORY_BARRIER();
  5975. }
  5976. size_t mg_queue_book(struct mg_queue *q, char **buf, size_t len) {
  5977. size_t space = 0, hs = sizeof(uint32_t) * 2; // *2 is for the 0 marker
  5978. if (q->head >= q->tail && q->head + len + hs <= q->size) {
  5979. space = q->size - q->head - hs; // There is enough space
  5980. } else if (q->head >= q->tail && q->tail > hs) {
  5981. mg_queue_write_len(q, 0); // Not enough space ahead
  5982. q->head = 0; // Wrap head to the beginning
  5983. }
  5984. if (q->head + hs + len < q->tail) space = q->tail - q->head - hs;
  5985. if (buf != NULL) *buf = q->buf + q->head + sizeof(uint32_t);
  5986. return space;
  5987. }
  5988. size_t mg_queue_next(struct mg_queue *q, char **buf) {
  5989. size_t len = 0;
  5990. if (q->tail != q->head) {
  5991. len = mg_queue_read_len(q);
  5992. if (len == 0) { // Zero (head wrapped) ?
  5993. q->tail = 0; // Reset tail to the start
  5994. if (q->head > q->tail) len = mg_queue_read_len(q); // Read again
  5995. }
  5996. }
  5997. if (buf != NULL) *buf = q->buf + q->tail + sizeof(uint32_t);
  5998. assert(q->tail + len <= q->size);
  5999. return len;
  6000. }
  6001. void mg_queue_add(struct mg_queue *q, size_t len) {
  6002. assert(len > 0);
  6003. mg_queue_write_len(q, len);
  6004. assert(q->head + sizeof(uint32_t) * 2 + len <= q->size);
  6005. q->head += len + sizeof(uint32_t);
  6006. }
  6007. void mg_queue_del(struct mg_queue *q, size_t len) {
  6008. q->tail += len + sizeof(uint32_t);
  6009. assert(q->tail + sizeof(uint32_t) <= q->size);
  6010. }
  6011. #ifdef MG_ENABLE_LINES
  6012. #line 1 "src/rpc.c"
  6013. #endif
  6014. void mg_rpc_add(struct mg_rpc **head, struct mg_str method,
  6015. void (*fn)(struct mg_rpc_req *), void *fn_data) {
  6016. struct mg_rpc *rpc = (struct mg_rpc *) calloc(1, sizeof(*rpc));
  6017. if (rpc != NULL) {
  6018. rpc->method.buf = mg_mprintf("%.*s", method.len, method.buf);
  6019. rpc->method.len = method.len;
  6020. rpc->fn = fn;
  6021. rpc->fn_data = fn_data;
  6022. rpc->next = *head, *head = rpc;
  6023. }
  6024. }
  6025. void mg_rpc_del(struct mg_rpc **head, void (*fn)(struct mg_rpc_req *)) {
  6026. struct mg_rpc *r;
  6027. while ((r = *head) != NULL) {
  6028. if (r->fn == fn || fn == NULL) {
  6029. *head = r->next;
  6030. free((void *) r->method.buf);
  6031. free(r);
  6032. } else {
  6033. head = &(*head)->next;
  6034. }
  6035. }
  6036. }
  6037. static void mg_rpc_call(struct mg_rpc_req *r, struct mg_str method) {
  6038. struct mg_rpc *h = r->head == NULL ? NULL : *r->head;
  6039. while (h != NULL && !mg_match(method, h->method, NULL)) h = h->next;
  6040. if (h != NULL) {
  6041. r->rpc = h;
  6042. h->fn(r);
  6043. } else {
  6044. mg_rpc_err(r, -32601, "\"%.*s not found\"", (int) method.len, method.buf);
  6045. }
  6046. }
  6047. void mg_rpc_process(struct mg_rpc_req *r) {
  6048. int len, off = mg_json_get(r->frame, "$.method", &len);
  6049. if (off > 0 && r->frame.buf[off] == '"') {
  6050. struct mg_str method = mg_str_n(&r->frame.buf[off + 1], (size_t) len - 2);
  6051. mg_rpc_call(r, method);
  6052. } else if ((off = mg_json_get(r->frame, "$.result", &len)) > 0 ||
  6053. (off = mg_json_get(r->frame, "$.error", &len)) > 0) {
  6054. mg_rpc_call(r, mg_str("")); // JSON response! call "" method handler
  6055. } else {
  6056. mg_rpc_err(r, -32700, "%m", mg_print_esc, (int) r->frame.len,
  6057. r->frame.buf); // Invalid
  6058. }
  6059. }
  6060. void mg_rpc_vok(struct mg_rpc_req *r, const char *fmt, va_list *ap) {
  6061. int len, off = mg_json_get(r->frame, "$.id", &len);
  6062. if (off > 0) {
  6063. mg_xprintf(r->pfn, r->pfn_data, "{%m:%.*s,%m:", mg_print_esc, 0, "id", len,
  6064. &r->frame.buf[off], mg_print_esc, 0, "result");
  6065. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  6066. mg_xprintf(r->pfn, r->pfn_data, "}");
  6067. }
  6068. }
  6069. void mg_rpc_ok(struct mg_rpc_req *r, const char *fmt, ...) {
  6070. va_list ap;
  6071. va_start(ap, fmt);
  6072. mg_rpc_vok(r, fmt, &ap);
  6073. va_end(ap);
  6074. }
  6075. void mg_rpc_verr(struct mg_rpc_req *r, int code, const char *fmt, va_list *ap) {
  6076. int len, off = mg_json_get(r->frame, "$.id", &len);
  6077. mg_xprintf(r->pfn, r->pfn_data, "{");
  6078. if (off > 0) {
  6079. mg_xprintf(r->pfn, r->pfn_data, "%m:%.*s,", mg_print_esc, 0, "id", len,
  6080. &r->frame.buf[off]);
  6081. }
  6082. mg_xprintf(r->pfn, r->pfn_data, "%m:{%m:%d,%m:", mg_print_esc, 0, "error",
  6083. mg_print_esc, 0, "code", code, mg_print_esc, 0, "message");
  6084. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  6085. mg_xprintf(r->pfn, r->pfn_data, "}}");
  6086. }
  6087. void mg_rpc_err(struct mg_rpc_req *r, int code, const char *fmt, ...) {
  6088. va_list ap;
  6089. va_start(ap, fmt);
  6090. mg_rpc_verr(r, code, fmt, &ap);
  6091. va_end(ap);
  6092. }
  6093. static size_t print_methods(mg_pfn_t pfn, void *pfn_data, va_list *ap) {
  6094. struct mg_rpc *h, **head = (struct mg_rpc **) va_arg(*ap, void **);
  6095. size_t len = 0;
  6096. for (h = *head; h != NULL; h = h->next) {
  6097. if (h->method.len == 0) continue; // Ignore response handler
  6098. len += mg_xprintf(pfn, pfn_data, "%s%m", h == *head ? "" : ",",
  6099. mg_print_esc, (int) h->method.len, h->method.buf);
  6100. }
  6101. return len;
  6102. }
  6103. void mg_rpc_list(struct mg_rpc_req *r) {
  6104. mg_rpc_ok(r, "[%M]", print_methods, r->head);
  6105. }
  6106. #ifdef MG_ENABLE_LINES
  6107. #line 1 "src/sha1.c"
  6108. #endif
  6109. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  6110. /* 100% Public Domain */
  6111. union char64long16 {
  6112. unsigned char c[64];
  6113. uint32_t l[16];
  6114. };
  6115. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6116. static uint32_t blk0(union char64long16 *block, int i) {
  6117. if (MG_BIG_ENDIAN) {
  6118. } else {
  6119. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  6120. (rol(block->l[i], 8) & 0x00FF00FF);
  6121. }
  6122. return block->l[i];
  6123. }
  6124. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  6125. #undef blk
  6126. #undef R0
  6127. #undef R1
  6128. #undef R2
  6129. #undef R3
  6130. #undef R4
  6131. #define blk(i) \
  6132. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  6133. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6134. 1))
  6135. #define R0(v, w, x, y, z, i) \
  6136. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6137. w = rol(w, 30);
  6138. #define R1(v, w, x, y, z, i) \
  6139. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6140. w = rol(w, 30);
  6141. #define R2(v, w, x, y, z, i) \
  6142. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6143. w = rol(w, 30);
  6144. #define R3(v, w, x, y, z, i) \
  6145. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6146. w = rol(w, 30);
  6147. #define R4(v, w, x, y, z, i) \
  6148. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6149. w = rol(w, 30);
  6150. static void mg_sha1_transform(uint32_t state[5],
  6151. const unsigned char *buffer) {
  6152. uint32_t a, b, c, d, e;
  6153. union char64long16 block[1];
  6154. memcpy(block, buffer, 64);
  6155. a = state[0];
  6156. b = state[1];
  6157. c = state[2];
  6158. d = state[3];
  6159. e = state[4];
  6160. R0(a, b, c, d, e, 0);
  6161. R0(e, a, b, c, d, 1);
  6162. R0(d, e, a, b, c, 2);
  6163. R0(c, d, e, a, b, 3);
  6164. R0(b, c, d, e, a, 4);
  6165. R0(a, b, c, d, e, 5);
  6166. R0(e, a, b, c, d, 6);
  6167. R0(d, e, a, b, c, 7);
  6168. R0(c, d, e, a, b, 8);
  6169. R0(b, c, d, e, a, 9);
  6170. R0(a, b, c, d, e, 10);
  6171. R0(e, a, b, c, d, 11);
  6172. R0(d, e, a, b, c, 12);
  6173. R0(c, d, e, a, b, 13);
  6174. R0(b, c, d, e, a, 14);
  6175. R0(a, b, c, d, e, 15);
  6176. R1(e, a, b, c, d, 16);
  6177. R1(d, e, a, b, c, 17);
  6178. R1(c, d, e, a, b, 18);
  6179. R1(b, c, d, e, a, 19);
  6180. R2(a, b, c, d, e, 20);
  6181. R2(e, a, b, c, d, 21);
  6182. R2(d, e, a, b, c, 22);
  6183. R2(c, d, e, a, b, 23);
  6184. R2(b, c, d, e, a, 24);
  6185. R2(a, b, c, d, e, 25);
  6186. R2(e, a, b, c, d, 26);
  6187. R2(d, e, a, b, c, 27);
  6188. R2(c, d, e, a, b, 28);
  6189. R2(b, c, d, e, a, 29);
  6190. R2(a, b, c, d, e, 30);
  6191. R2(e, a, b, c, d, 31);
  6192. R2(d, e, a, b, c, 32);
  6193. R2(c, d, e, a, b, 33);
  6194. R2(b, c, d, e, a, 34);
  6195. R2(a, b, c, d, e, 35);
  6196. R2(e, a, b, c, d, 36);
  6197. R2(d, e, a, b, c, 37);
  6198. R2(c, d, e, a, b, 38);
  6199. R2(b, c, d, e, a, 39);
  6200. R3(a, b, c, d, e, 40);
  6201. R3(e, a, b, c, d, 41);
  6202. R3(d, e, a, b, c, 42);
  6203. R3(c, d, e, a, b, 43);
  6204. R3(b, c, d, e, a, 44);
  6205. R3(a, b, c, d, e, 45);
  6206. R3(e, a, b, c, d, 46);
  6207. R3(d, e, a, b, c, 47);
  6208. R3(c, d, e, a, b, 48);
  6209. R3(b, c, d, e, a, 49);
  6210. R3(a, b, c, d, e, 50);
  6211. R3(e, a, b, c, d, 51);
  6212. R3(d, e, a, b, c, 52);
  6213. R3(c, d, e, a, b, 53);
  6214. R3(b, c, d, e, a, 54);
  6215. R3(a, b, c, d, e, 55);
  6216. R3(e, a, b, c, d, 56);
  6217. R3(d, e, a, b, c, 57);
  6218. R3(c, d, e, a, b, 58);
  6219. R3(b, c, d, e, a, 59);
  6220. R4(a, b, c, d, e, 60);
  6221. R4(e, a, b, c, d, 61);
  6222. R4(d, e, a, b, c, 62);
  6223. R4(c, d, e, a, b, 63);
  6224. R4(b, c, d, e, a, 64);
  6225. R4(a, b, c, d, e, 65);
  6226. R4(e, a, b, c, d, 66);
  6227. R4(d, e, a, b, c, 67);
  6228. R4(c, d, e, a, b, 68);
  6229. R4(b, c, d, e, a, 69);
  6230. R4(a, b, c, d, e, 70);
  6231. R4(e, a, b, c, d, 71);
  6232. R4(d, e, a, b, c, 72);
  6233. R4(c, d, e, a, b, 73);
  6234. R4(b, c, d, e, a, 74);
  6235. R4(a, b, c, d, e, 75);
  6236. R4(e, a, b, c, d, 76);
  6237. R4(d, e, a, b, c, 77);
  6238. R4(c, d, e, a, b, 78);
  6239. R4(b, c, d, e, a, 79);
  6240. state[0] += a;
  6241. state[1] += b;
  6242. state[2] += c;
  6243. state[3] += d;
  6244. state[4] += e;
  6245. /* Erase working structures. The order of operations is important,
  6246. * used to ensure that compiler doesn't optimize those out. */
  6247. memset(block, 0, sizeof(block));
  6248. a = b = c = d = e = 0;
  6249. (void) a;
  6250. (void) b;
  6251. (void) c;
  6252. (void) d;
  6253. (void) e;
  6254. }
  6255. void mg_sha1_init(mg_sha1_ctx *context) {
  6256. context->state[0] = 0x67452301;
  6257. context->state[1] = 0xEFCDAB89;
  6258. context->state[2] = 0x98BADCFE;
  6259. context->state[3] = 0x10325476;
  6260. context->state[4] = 0xC3D2E1F0;
  6261. context->count[0] = context->count[1] = 0;
  6262. }
  6263. void mg_sha1_update(mg_sha1_ctx *context, const unsigned char *data,
  6264. size_t len) {
  6265. size_t i, j;
  6266. j = context->count[0];
  6267. if ((context->count[0] += (uint32_t) len << 3) < j) context->count[1]++;
  6268. context->count[1] += (uint32_t) (len >> 29);
  6269. j = (j >> 3) & 63;
  6270. if ((j + len) > 63) {
  6271. memcpy(&context->buffer[j], data, (i = 64 - j));
  6272. mg_sha1_transform(context->state, context->buffer);
  6273. for (; i + 63 < len; i += 64) {
  6274. mg_sha1_transform(context->state, &data[i]);
  6275. }
  6276. j = 0;
  6277. } else
  6278. i = 0;
  6279. memcpy(&context->buffer[j], &data[i], len - i);
  6280. }
  6281. void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *context) {
  6282. unsigned i;
  6283. unsigned char finalcount[8], c;
  6284. for (i = 0; i < 8; i++) {
  6285. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  6286. ((3 - (i & 3)) * 8)) &
  6287. 255);
  6288. }
  6289. c = 0200;
  6290. mg_sha1_update(context, &c, 1);
  6291. while ((context->count[0] & 504) != 448) {
  6292. c = 0000;
  6293. mg_sha1_update(context, &c, 1);
  6294. }
  6295. mg_sha1_update(context, finalcount, 8);
  6296. for (i = 0; i < 20; i++) {
  6297. digest[i] =
  6298. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  6299. }
  6300. memset(context, '\0', sizeof(*context));
  6301. memset(&finalcount, '\0', sizeof(finalcount));
  6302. }
  6303. #ifdef MG_ENABLE_LINES
  6304. #line 1 "src/sha256.c"
  6305. #endif
  6306. // https://github.com/B-Con/crypto-algorithms
  6307. // Author: Brad Conte (brad AT bradconte.com)
  6308. // Disclaimer: This code is presented "as is" without any guarantees.
  6309. // Details: Defines the API for the corresponding SHA1 implementation.
  6310. // Copyright: public domain
  6311. #define ror(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
  6312. #define ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
  6313. #define maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
  6314. #define ep0(x) (ror(x, 2) ^ ror(x, 13) ^ ror(x, 22))
  6315. #define ep1(x) (ror(x, 6) ^ ror(x, 11) ^ ror(x, 25))
  6316. #define sig0(x) (ror(x, 7) ^ ror(x, 18) ^ ((x) >> 3))
  6317. #define sig1(x) (ror(x, 17) ^ ror(x, 19) ^ ((x) >> 10))
  6318. static const uint32_t mg_sha256_k[64] = {
  6319. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
  6320. 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  6321. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
  6322. 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  6323. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
  6324. 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  6325. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
  6326. 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  6327. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
  6328. 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  6329. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
  6330. void mg_sha256_init(mg_sha256_ctx *ctx) {
  6331. ctx->len = 0;
  6332. ctx->bits = 0;
  6333. ctx->state[0] = 0x6a09e667;
  6334. ctx->state[1] = 0xbb67ae85;
  6335. ctx->state[2] = 0x3c6ef372;
  6336. ctx->state[3] = 0xa54ff53a;
  6337. ctx->state[4] = 0x510e527f;
  6338. ctx->state[5] = 0x9b05688c;
  6339. ctx->state[6] = 0x1f83d9ab;
  6340. ctx->state[7] = 0x5be0cd19;
  6341. }
  6342. static void mg_sha256_chunk(mg_sha256_ctx *ctx) {
  6343. int i, j;
  6344. uint32_t a, b, c, d, e, f, g, h;
  6345. uint32_t m[64];
  6346. for (i = 0, j = 0; i < 16; ++i, j += 4)
  6347. m[i] = (uint32_t) (((uint32_t) ctx->buffer[j] << 24) |
  6348. ((uint32_t) ctx->buffer[j + 1] << 16) |
  6349. ((uint32_t) ctx->buffer[j + 2] << 8) |
  6350. ((uint32_t) ctx->buffer[j + 3]));
  6351. for (; i < 64; ++i)
  6352. m[i] = sig1(m[i - 2]) + m[i - 7] + sig0(m[i - 15]) + m[i - 16];
  6353. a = ctx->state[0];
  6354. b = ctx->state[1];
  6355. c = ctx->state[2];
  6356. d = ctx->state[3];
  6357. e = ctx->state[4];
  6358. f = ctx->state[5];
  6359. g = ctx->state[6];
  6360. h = ctx->state[7];
  6361. for (i = 0; i < 64; ++i) {
  6362. uint32_t t1 = h + ep1(e) + ch(e, f, g) + mg_sha256_k[i] + m[i];
  6363. uint32_t t2 = ep0(a) + maj(a, b, c);
  6364. h = g;
  6365. g = f;
  6366. f = e;
  6367. e = d + t1;
  6368. d = c;
  6369. c = b;
  6370. b = a;
  6371. a = t1 + t2;
  6372. }
  6373. ctx->state[0] += a;
  6374. ctx->state[1] += b;
  6375. ctx->state[2] += c;
  6376. ctx->state[3] += d;
  6377. ctx->state[4] += e;
  6378. ctx->state[5] += f;
  6379. ctx->state[6] += g;
  6380. ctx->state[7] += h;
  6381. }
  6382. void mg_sha256_update(mg_sha256_ctx *ctx, const unsigned char *data,
  6383. size_t len) {
  6384. size_t i;
  6385. for (i = 0; i < len; i++) {
  6386. ctx->buffer[ctx->len] = data[i];
  6387. if ((++ctx->len) == 64) {
  6388. mg_sha256_chunk(ctx);
  6389. ctx->bits += 512;
  6390. ctx->len = 0;
  6391. }
  6392. }
  6393. }
  6394. // TODO: make final reusable (remove side effects)
  6395. void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *ctx) {
  6396. uint32_t i = ctx->len;
  6397. if (i < 56) {
  6398. ctx->buffer[i++] = 0x80;
  6399. while (i < 56) {
  6400. ctx->buffer[i++] = 0x00;
  6401. }
  6402. } else {
  6403. ctx->buffer[i++] = 0x80;
  6404. while (i < 64) {
  6405. ctx->buffer[i++] = 0x00;
  6406. }
  6407. mg_sha256_chunk(ctx);
  6408. memset(ctx->buffer, 0, 56);
  6409. }
  6410. ctx->bits += ctx->len * 8;
  6411. ctx->buffer[63] = (uint8_t) ((ctx->bits) & 0xff);
  6412. ctx->buffer[62] = (uint8_t) ((ctx->bits >> 8) & 0xff);
  6413. ctx->buffer[61] = (uint8_t) ((ctx->bits >> 16) & 0xff);
  6414. ctx->buffer[60] = (uint8_t) ((ctx->bits >> 24) & 0xff);
  6415. ctx->buffer[59] = (uint8_t) ((ctx->bits >> 32) & 0xff);
  6416. ctx->buffer[58] = (uint8_t) ((ctx->bits >> 40) & 0xff);
  6417. ctx->buffer[57] = (uint8_t) ((ctx->bits >> 48) & 0xff);
  6418. ctx->buffer[56] = (uint8_t) ((ctx->bits >> 56) & 0xff);
  6419. mg_sha256_chunk(ctx);
  6420. for (i = 0; i < 4; ++i) {
  6421. digest[i] = (uint8_t) ((ctx->state[0] >> (24 - i * 8)) & 0xff);
  6422. digest[i + 4] = (uint8_t) ((ctx->state[1] >> (24 - i * 8)) & 0xff);
  6423. digest[i + 8] = (uint8_t) ((ctx->state[2] >> (24 - i * 8)) & 0xff);
  6424. digest[i + 12] = (uint8_t) ((ctx->state[3] >> (24 - i * 8)) & 0xff);
  6425. digest[i + 16] = (uint8_t) ((ctx->state[4] >> (24 - i * 8)) & 0xff);
  6426. digest[i + 20] = (uint8_t) ((ctx->state[5] >> (24 - i * 8)) & 0xff);
  6427. digest[i + 24] = (uint8_t) ((ctx->state[6] >> (24 - i * 8)) & 0xff);
  6428. digest[i + 28] = (uint8_t) ((ctx->state[7] >> (24 - i * 8)) & 0xff);
  6429. }
  6430. }
  6431. void mg_hmac_sha256(uint8_t dst[32], uint8_t *key, size_t keysz, uint8_t *data,
  6432. size_t datasz) {
  6433. mg_sha256_ctx ctx;
  6434. uint8_t k[64] = {0};
  6435. uint8_t o_pad[64], i_pad[64];
  6436. unsigned int i;
  6437. memset(i_pad, 0x36, sizeof(i_pad));
  6438. memset(o_pad, 0x5c, sizeof(o_pad));
  6439. if (keysz < 64) {
  6440. if (keysz > 0) memmove(k, key, keysz);
  6441. } else {
  6442. mg_sha256_init(&ctx);
  6443. mg_sha256_update(&ctx, key, keysz);
  6444. mg_sha256_final(k, &ctx);
  6445. }
  6446. for (i = 0; i < sizeof(k); i++) {
  6447. i_pad[i] ^= k[i];
  6448. o_pad[i] ^= k[i];
  6449. }
  6450. mg_sha256_init(&ctx);
  6451. mg_sha256_update(&ctx, i_pad, sizeof(i_pad));
  6452. mg_sha256_update(&ctx, data, datasz);
  6453. mg_sha256_final(dst, &ctx);
  6454. mg_sha256_init(&ctx);
  6455. mg_sha256_update(&ctx, o_pad, sizeof(o_pad));
  6456. mg_sha256_update(&ctx, dst, 32);
  6457. mg_sha256_final(dst, &ctx);
  6458. }
  6459. #ifdef MG_ENABLE_LINES
  6460. #line 1 "src/sntp.c"
  6461. #endif
  6462. #define SNTP_TIME_OFFSET 2208988800U // (1970 - 1900) in seconds
  6463. #define SNTP_MAX_FRAC 4294967295.0 // 2 ** 32 - 1
  6464. static int64_t gettimestamp(const uint32_t *data) {
  6465. uint32_t sec = mg_ntohl(data[0]), frac = mg_ntohl(data[1]);
  6466. if (sec) sec -= SNTP_TIME_OFFSET;
  6467. return ((int64_t) sec) * 1000 + (int64_t) (frac / SNTP_MAX_FRAC * 1000.0);
  6468. }
  6469. int64_t mg_sntp_parse(const unsigned char *buf, size_t len) {
  6470. int64_t res = -1;
  6471. int mode = len > 0 ? buf[0] & 7 : 0;
  6472. int version = len > 0 ? (buf[0] >> 3) & 7 : 0;
  6473. if (len < 48) {
  6474. MG_ERROR(("%s", "corrupt packet"));
  6475. } else if (mode != 4 && mode != 5) {
  6476. MG_ERROR(("%s", "not a server reply"));
  6477. } else if (buf[1] == 0) {
  6478. MG_ERROR(("%s", "server sent a kiss of death"));
  6479. } else if (version == 4 || version == 3) {
  6480. // int64_t ref = gettimestamp((uint32_t *) &buf[16]);
  6481. int64_t t0 = gettimestamp((uint32_t *) &buf[24]);
  6482. int64_t t1 = gettimestamp((uint32_t *) &buf[32]);
  6483. int64_t t2 = gettimestamp((uint32_t *) &buf[40]);
  6484. int64_t t3 = (int64_t) mg_millis();
  6485. int64_t delta = (t3 - t0) - (t2 - t1);
  6486. MG_VERBOSE(("%lld %lld %lld %lld delta:%lld", t0, t1, t2, t3, delta));
  6487. res = t2 + delta / 2;
  6488. } else {
  6489. MG_ERROR(("unexpected version: %d", version));
  6490. }
  6491. return res;
  6492. }
  6493. static void sntp_cb(struct mg_connection *c, int ev, void *ev_data) {
  6494. if (ev == MG_EV_READ) {
  6495. int64_t milliseconds = mg_sntp_parse(c->recv.buf, c->recv.len);
  6496. if (milliseconds > 0) {
  6497. MG_DEBUG(("%lu got time: %lld ms from epoch", c->id, milliseconds));
  6498. mg_call(c, MG_EV_SNTP_TIME, (uint64_t *) &milliseconds);
  6499. MG_VERBOSE(("%u.%u", (unsigned) (milliseconds / 1000),
  6500. (unsigned) (milliseconds % 1000)));
  6501. }
  6502. mg_iobuf_del(&c->recv, 0, c->recv.len); // Free receive buffer
  6503. } else if (ev == MG_EV_CONNECT) {
  6504. mg_sntp_request(c);
  6505. } else if (ev == MG_EV_CLOSE) {
  6506. }
  6507. (void) ev_data;
  6508. }
  6509. void mg_sntp_request(struct mg_connection *c) {
  6510. if (c->is_resolving) {
  6511. MG_ERROR(("%lu wait until resolved", c->id));
  6512. } else {
  6513. int64_t now = (int64_t) mg_millis(); // Use int64_t, for vc98
  6514. uint8_t buf[48] = {0};
  6515. uint32_t *t = (uint32_t *) &buf[40];
  6516. double frac = ((double) (now % 1000)) / 1000.0 * SNTP_MAX_FRAC;
  6517. buf[0] = (0 << 6) | (4 << 3) | 3;
  6518. t[0] = mg_htonl((uint32_t) (now / 1000) + SNTP_TIME_OFFSET);
  6519. t[1] = mg_htonl((uint32_t) frac);
  6520. mg_send(c, buf, sizeof(buf));
  6521. }
  6522. }
  6523. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url,
  6524. mg_event_handler_t fn, void *fnd) {
  6525. struct mg_connection *c = NULL;
  6526. if (url == NULL) url = "udp://time.google.com:123";
  6527. if ((c = mg_connect(mgr, url, fn, fnd)) != NULL) c->pfn = sntp_cb;
  6528. return c;
  6529. }
  6530. #ifdef MG_ENABLE_LINES
  6531. #line 1 "src/sock.c"
  6532. #endif
  6533. #if MG_ENABLE_SOCKET
  6534. #ifndef closesocket
  6535. #define closesocket(x) close(x)
  6536. #endif
  6537. #define FD(c_) ((MG_SOCKET_TYPE) (size_t) (c_)->fd)
  6538. #define S2PTR(s_) ((void *) (size_t) (s_))
  6539. #ifndef MSG_NONBLOCKING
  6540. #define MSG_NONBLOCKING 0
  6541. #endif
  6542. #ifndef AF_INET6
  6543. #define AF_INET6 10
  6544. #endif
  6545. #ifndef MG_SOCK_ERR
  6546. #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? errno : 0)
  6547. #endif
  6548. #ifndef MG_SOCK_INTR
  6549. #define MG_SOCK_INTR(fd) (fd == MG_INVALID_SOCKET && MG_SOCK_ERR(-1) == EINTR)
  6550. #endif
  6551. #ifndef MG_SOCK_PENDING
  6552. #define MG_SOCK_PENDING(errcode) \
  6553. (((errcode) < 0) && (errno == EINPROGRESS || errno == EWOULDBLOCK))
  6554. #endif
  6555. #ifndef MG_SOCK_RESET
  6556. #define MG_SOCK_RESET(errcode) \
  6557. (((errcode) < 0) && (errno == EPIPE || errno == ECONNRESET))
  6558. #endif
  6559. union usa {
  6560. struct sockaddr sa;
  6561. struct sockaddr_in sin;
  6562. #if MG_ENABLE_IPV6
  6563. struct sockaddr_in6 sin6;
  6564. #endif
  6565. };
  6566. static socklen_t tousa(struct mg_addr *a, union usa *usa) {
  6567. socklen_t len = sizeof(usa->sin);
  6568. memset(usa, 0, sizeof(*usa));
  6569. usa->sin.sin_family = AF_INET;
  6570. usa->sin.sin_port = a->port;
  6571. memcpy(&usa->sin.sin_addr, a->ip, sizeof(uint32_t));
  6572. #if MG_ENABLE_IPV6
  6573. if (a->is_ip6) {
  6574. usa->sin.sin_family = AF_INET6;
  6575. usa->sin6.sin6_port = a->port;
  6576. usa->sin6.sin6_scope_id = a->scope_id;
  6577. memcpy(&usa->sin6.sin6_addr, a->ip, sizeof(a->ip));
  6578. len = sizeof(usa->sin6);
  6579. }
  6580. #endif
  6581. return len;
  6582. }
  6583. static void tomgaddr(union usa *usa, struct mg_addr *a, bool is_ip6) {
  6584. a->is_ip6 = is_ip6;
  6585. a->port = usa->sin.sin_port;
  6586. memcpy(&a->ip, &usa->sin.sin_addr, sizeof(uint32_t));
  6587. #if MG_ENABLE_IPV6
  6588. if (is_ip6) {
  6589. memcpy(a->ip, &usa->sin6.sin6_addr, sizeof(a->ip));
  6590. a->port = usa->sin6.sin6_port;
  6591. a->scope_id = (uint8_t) usa->sin6.sin6_scope_id;
  6592. }
  6593. #endif
  6594. }
  6595. static void setlocaddr(MG_SOCKET_TYPE fd, struct mg_addr *addr) {
  6596. union usa usa;
  6597. socklen_t n = sizeof(usa);
  6598. if (getsockname(fd, &usa.sa, &n) == 0) {
  6599. tomgaddr(&usa, addr, n != sizeof(usa.sin));
  6600. }
  6601. }
  6602. static void iolog(struct mg_connection *c, char *buf, long n, bool r) {
  6603. if (n == MG_IO_WAIT) {
  6604. // Do nothing
  6605. } else if (n <= 0) {
  6606. c->is_closing = 1; // Termination. Don't call mg_error(): #1529
  6607. } else if (n > 0) {
  6608. if (c->is_hexdumping) {
  6609. MG_INFO(("\n-- %lu %M %s %M %ld", c->id, mg_print_ip_port, &c->loc,
  6610. r ? "<-" : "->", mg_print_ip_port, &c->rem, n));
  6611. mg_hexdump(buf, (size_t) n);
  6612. }
  6613. if (r) {
  6614. c->recv.len += (size_t) n;
  6615. mg_call(c, MG_EV_READ, &n);
  6616. } else {
  6617. mg_iobuf_del(&c->send, 0, (size_t) n);
  6618. // if (c->send.len == 0) mg_iobuf_resize(&c->send, 0);
  6619. if (c->send.len == 0) {
  6620. MG_EPOLL_MOD(c, 0);
  6621. }
  6622. mg_call(c, MG_EV_WRITE, &n);
  6623. }
  6624. }
  6625. }
  6626. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  6627. long n;
  6628. if (c->is_udp) {
  6629. union usa usa;
  6630. socklen_t slen = tousa(&c->rem, &usa);
  6631. n = sendto(FD(c), (char *) buf, len, 0, &usa.sa, slen);
  6632. if (n > 0) setlocaddr(FD(c), &c->loc);
  6633. } else {
  6634. n = send(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6635. }
  6636. MG_VERBOSE(("%lu %ld %d", c->id, n, MG_SOCK_ERR(n)));
  6637. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6638. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6639. if (n <= 0) return MG_IO_ERR;
  6640. return n;
  6641. }
  6642. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  6643. if (c->is_udp) {
  6644. long n = mg_io_send(c, buf, len);
  6645. MG_DEBUG(("%lu %ld %lu:%lu:%lu %ld err %d", c->id, c->fd, c->send.len,
  6646. c->recv.len, c->rtls.len, n, MG_SOCK_ERR(n)));
  6647. iolog(c, (char *) buf, n, false);
  6648. return n > 0;
  6649. } else {
  6650. return mg_iobuf_add(&c->send, c->send.len, buf, len);
  6651. }
  6652. }
  6653. static void mg_set_non_blocking_mode(MG_SOCKET_TYPE fd) {
  6654. #if defined(MG_CUSTOM_NONBLOCK)
  6655. MG_CUSTOM_NONBLOCK(fd);
  6656. #elif MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  6657. unsigned long on = 1;
  6658. ioctlsocket(fd, FIONBIO, &on);
  6659. #elif MG_ENABLE_RL
  6660. unsigned long on = 1;
  6661. ioctlsocket(fd, FIONBIO, &on);
  6662. #elif MG_ENABLE_FREERTOS_TCP
  6663. const BaseType_t off = 0;
  6664. if (setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6665. if (setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6666. #elif MG_ENABLE_LWIP
  6667. lwip_fcntl(fd, F_SETFL, O_NONBLOCK);
  6668. #elif MG_ARCH == MG_ARCH_AZURERTOS
  6669. fcntl(fd, F_SETFL, O_NONBLOCK);
  6670. #elif MG_ARCH == MG_ARCH_TIRTOS
  6671. int val = 0;
  6672. setsockopt(fd, SOL_SOCKET, SO_BLOCKING, &val, sizeof(val));
  6673. // SPRU524J section 3.3.3 page 63, SO_SNDLOWAT
  6674. int sz = sizeof(val);
  6675. getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &val, &sz);
  6676. val /= 2; // set send low-water mark at half send buffer size
  6677. setsockopt(fd, SOL_SOCKET, SO_SNDLOWAT, &val, sizeof(val));
  6678. #else
  6679. fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); // Non-blocking mode
  6680. fcntl(fd, F_SETFD, FD_CLOEXEC); // Set close-on-exec
  6681. #endif
  6682. }
  6683. bool mg_open_listener(struct mg_connection *c, const char *url) {
  6684. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6685. bool success = false;
  6686. c->loc.port = mg_htons(mg_url_port(url));
  6687. if (!mg_aton(mg_url_host(url), &c->loc)) {
  6688. MG_ERROR(("invalid listening URL: %s", url));
  6689. } else {
  6690. union usa usa;
  6691. socklen_t slen = tousa(&c->loc, &usa);
  6692. int rc, on = 1, af = c->loc.is_ip6 ? AF_INET6 : AF_INET;
  6693. int type = strncmp(url, "udp:", 4) == 0 ? SOCK_DGRAM : SOCK_STREAM;
  6694. int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP;
  6695. (void) on;
  6696. if ((fd = socket(af, type, proto)) == MG_INVALID_SOCKET) {
  6697. MG_ERROR(("socket: %d", MG_SOCK_ERR(-1)));
  6698. #if defined(SO_EXCLUSIVEADDRUSE)
  6699. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  6700. (char *) &on, sizeof(on))) != 0) {
  6701. // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE"
  6702. MG_ERROR(("setsockopt(SO_EXCLUSIVEADDRUSE): %d %d", on, MG_SOCK_ERR(rc)));
  6703. #elif defined(SO_REUSEADDR) && (!defined(LWIP_SOCKET) || SO_REUSE)
  6704. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on,
  6705. sizeof(on))) != 0) {
  6706. // 1. SO_REUSEADDR semantics on UNIX and Windows is different. On
  6707. // Windows, SO_REUSEADDR allows to bind a socket to a port without error
  6708. // even if the port is already open by another program. This is not the
  6709. // behavior SO_REUSEADDR was designed for, and leads to hard-to-track
  6710. // failure scenarios.
  6711. //
  6712. // 2. For LWIP, SO_REUSEADDR should be explicitly enabled by defining
  6713. // SO_REUSE = 1 in lwipopts.h, otherwise the code below will compile but
  6714. // won't work! (setsockopt will return EINVAL)
  6715. MG_ERROR(("setsockopt(SO_REUSEADDR): %d", MG_SOCK_ERR(rc)));
  6716. #endif
  6717. #if MG_IPV6_V6ONLY
  6718. // Bind only to the V6 address, not V4 address on this port
  6719. } else if (c->loc.is_ip6 &&
  6720. (rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &on,
  6721. sizeof(on))) != 0) {
  6722. // See #2089. Allow to bind v4 and v6 sockets on the same port
  6723. MG_ERROR(("setsockopt(IPV6_V6ONLY): %d", MG_SOCK_ERR(rc)));
  6724. #endif
  6725. } else if ((rc = bind(fd, &usa.sa, slen)) != 0) {
  6726. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6727. } else if ((type == SOCK_STREAM &&
  6728. (rc = listen(fd, MG_SOCK_LISTEN_BACKLOG_SIZE)) != 0)) {
  6729. // NOTE(lsm): FreeRTOS uses backlog value as a connection limit
  6730. // In case port was set to 0, get the real port number
  6731. MG_ERROR(("listen: %d", MG_SOCK_ERR(rc)));
  6732. } else {
  6733. setlocaddr(fd, &c->loc);
  6734. mg_set_non_blocking_mode(fd);
  6735. c->fd = S2PTR(fd);
  6736. MG_EPOLL_ADD(c);
  6737. success = true;
  6738. }
  6739. }
  6740. if (success == false && fd != MG_INVALID_SOCKET) closesocket(fd);
  6741. return success;
  6742. }
  6743. static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
  6744. long n = 0;
  6745. if (c->is_udp) {
  6746. union usa usa;
  6747. socklen_t slen = tousa(&c->rem, &usa);
  6748. n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
  6749. if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
  6750. } else {
  6751. n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6752. }
  6753. MG_VERBOSE(("%lu %ld %d", c->id, n, MG_SOCK_ERR(n)));
  6754. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6755. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6756. if (n <= 0) return MG_IO_ERR;
  6757. return n;
  6758. }
  6759. static bool ioalloc(struct mg_connection *c, struct mg_iobuf *io) {
  6760. bool res = false;
  6761. if (io->len >= MG_MAX_RECV_SIZE) {
  6762. mg_error(c, "MG_MAX_RECV_SIZE");
  6763. } else if (io->size <= io->len &&
  6764. !mg_iobuf_resize(io, io->size + MG_IO_SIZE)) {
  6765. mg_error(c, "OOM");
  6766. } else {
  6767. res = true;
  6768. }
  6769. return res;
  6770. }
  6771. // NOTE(lsm): do only one iteration of reads, cause some systems
  6772. // (e.g. FreeRTOS stack) return 0 instead of -1/EWOULDBLOCK when no data
  6773. static void read_conn(struct mg_connection *c) {
  6774. if (ioalloc(c, &c->recv)) {
  6775. char *buf = (char *) &c->recv.buf[c->recv.len];
  6776. size_t len = c->recv.size - c->recv.len;
  6777. long n = -1;
  6778. if (c->is_tls) {
  6779. if (!ioalloc(c, &c->rtls)) return;
  6780. n = recv_raw(c, (char *) &c->rtls.buf[c->rtls.len],
  6781. c->rtls.size - c->rtls.len);
  6782. if (n == MG_IO_ERR && c->rtls.len == 0) {
  6783. // Close only if we have fully drained both raw (rtls) and TLS buffers
  6784. c->is_closing = 1;
  6785. } else {
  6786. if (n > 0) c->rtls.len += (size_t) n;
  6787. if (c->is_tls_hs) mg_tls_handshake(c);
  6788. n = c->is_tls_hs ? (long) MG_IO_WAIT : mg_tls_recv(c, buf, len);
  6789. }
  6790. } else {
  6791. n = recv_raw(c, buf, len);
  6792. }
  6793. MG_DEBUG(("%lu %ld %lu:%lu:%lu %ld err %d", c->id, c->fd, c->send.len,
  6794. c->recv.len, c->rtls.len, n, MG_SOCK_ERR(n)));
  6795. iolog(c, buf, n, true);
  6796. }
  6797. }
  6798. static void write_conn(struct mg_connection *c) {
  6799. char *buf = (char *) c->send.buf;
  6800. size_t len = c->send.len;
  6801. long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len);
  6802. MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6803. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6804. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6805. iolog(c, buf, n, false);
  6806. }
  6807. static void close_conn(struct mg_connection *c) {
  6808. if (FD(c) != MG_INVALID_SOCKET) {
  6809. #if MG_ENABLE_EPOLL
  6810. epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_DEL, FD(c), NULL);
  6811. #endif
  6812. closesocket(FD(c));
  6813. #if MG_ENABLE_FREERTOS_TCP
  6814. FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL);
  6815. #endif
  6816. }
  6817. mg_close_conn(c);
  6818. }
  6819. static void connect_conn(struct mg_connection *c) {
  6820. union usa usa;
  6821. socklen_t n = sizeof(usa);
  6822. // Use getpeername() to test whether we have connected
  6823. if (getpeername(FD(c), &usa.sa, &n) == 0) {
  6824. c->is_connecting = 0;
  6825. setlocaddr(FD(c), &c->loc);
  6826. mg_call(c, MG_EV_CONNECT, NULL);
  6827. MG_EPOLL_MOD(c, 0);
  6828. if (c->is_tls_hs) mg_tls_handshake(c);
  6829. } else {
  6830. mg_error(c, "socket error");
  6831. }
  6832. }
  6833. static void setsockopts(struct mg_connection *c) {
  6834. #if MG_ENABLE_FREERTOS_TCP || MG_ARCH == MG_ARCH_AZURERTOS || \
  6835. MG_ARCH == MG_ARCH_TIRTOS
  6836. (void) c;
  6837. #else
  6838. int on = 1;
  6839. #if !defined(SOL_TCP)
  6840. #define SOL_TCP IPPROTO_TCP
  6841. #endif
  6842. if (setsockopt(FD(c), SOL_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) != 0)
  6843. (void) 0;
  6844. if (setsockopt(FD(c), SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) !=
  6845. 0)
  6846. (void) 0;
  6847. #endif
  6848. }
  6849. void mg_connect_resolved(struct mg_connection *c) {
  6850. int type = c->is_udp ? SOCK_DGRAM : SOCK_STREAM;
  6851. int rc, af = c->rem.is_ip6 ? AF_INET6 : AF_INET; // c->rem has resolved IP
  6852. c->fd = S2PTR(socket(af, type, 0)); // Create outbound socket
  6853. c->is_resolving = 0; // Clear resolving flag
  6854. if (FD(c) == MG_INVALID_SOCKET) {
  6855. mg_error(c, "socket(): %d", MG_SOCK_ERR(-1));
  6856. } else if (c->is_udp) {
  6857. MG_EPOLL_ADD(c);
  6858. #if MG_ARCH == MG_ARCH_TIRTOS
  6859. union usa usa; // TI-RTOS NDK requires binding to receive on UDP sockets
  6860. socklen_t slen = tousa(&c->loc, &usa);
  6861. if ((rc = bind(c->fd, &usa.sa, slen)) != 0)
  6862. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6863. #endif
  6864. setlocaddr(FD(c), &c->loc);
  6865. mg_call(c, MG_EV_RESOLVE, NULL);
  6866. mg_call(c, MG_EV_CONNECT, NULL);
  6867. } else {
  6868. union usa usa;
  6869. socklen_t slen = tousa(&c->rem, &usa);
  6870. mg_set_non_blocking_mode(FD(c));
  6871. setsockopts(c);
  6872. MG_EPOLL_ADD(c);
  6873. mg_call(c, MG_EV_RESOLVE, NULL);
  6874. rc = connect(FD(c), &usa.sa, slen); // Attempt to connect
  6875. if (rc == 0) { // Success
  6876. setlocaddr(FD(c), &c->loc);
  6877. mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user
  6878. } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake
  6879. MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem));
  6880. c->is_connecting = 1;
  6881. } else {
  6882. mg_error(c, "connect: %d", MG_SOCK_ERR(rc));
  6883. }
  6884. }
  6885. }
  6886. static MG_SOCKET_TYPE raccept(MG_SOCKET_TYPE sock, union usa *usa,
  6887. socklen_t *len) {
  6888. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6889. do {
  6890. memset(usa, 0, sizeof(*usa));
  6891. fd = accept(sock, &usa->sa, len);
  6892. } while (MG_SOCK_INTR(fd));
  6893. return fd;
  6894. }
  6895. static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) {
  6896. struct mg_connection *c = NULL;
  6897. union usa usa;
  6898. socklen_t sa_len = sizeof(usa);
  6899. MG_SOCKET_TYPE fd = raccept(FD(lsn), &usa, &sa_len);
  6900. if (fd == MG_INVALID_SOCKET) {
  6901. #if MG_ARCH == MG_ARCH_AZURERTOS || defined(__ECOS)
  6902. // AzureRTOS, in non-block socket mode can mark listening socket readable
  6903. // even it is not. See comment for 'select' func implementation in
  6904. // nx_bsd.c That's not an error, just should try later
  6905. if (errno != EAGAIN)
  6906. #endif
  6907. MG_ERROR(("%lu accept failed, errno %d", lsn->id, MG_SOCK_ERR(-1)));
  6908. #if (MG_ARCH != MG_ARCH_WIN32) && !MG_ENABLE_FREERTOS_TCP && \
  6909. (MG_ARCH != MG_ARCH_TIRTOS) && !MG_ENABLE_POLL && !MG_ENABLE_EPOLL
  6910. } else if ((long) fd >= FD_SETSIZE) {
  6911. MG_ERROR(("%ld > %ld", (long) fd, (long) FD_SETSIZE));
  6912. closesocket(fd);
  6913. #endif
  6914. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  6915. MG_ERROR(("%lu OOM", lsn->id));
  6916. closesocket(fd);
  6917. } else {
  6918. tomgaddr(&usa, &c->rem, sa_len != sizeof(usa.sin));
  6919. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  6920. c->fd = S2PTR(fd);
  6921. MG_EPOLL_ADD(c);
  6922. mg_set_non_blocking_mode(FD(c));
  6923. setsockopts(c);
  6924. c->is_accepted = 1;
  6925. c->is_hexdumping = lsn->is_hexdumping;
  6926. c->loc = lsn->loc;
  6927. c->pfn = lsn->pfn;
  6928. c->pfn_data = lsn->pfn_data;
  6929. c->fn = lsn->fn;
  6930. c->fn_data = lsn->fn_data;
  6931. MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port,
  6932. &c->rem, mg_print_ip_port, &c->loc));
  6933. mg_call(c, MG_EV_OPEN, NULL);
  6934. mg_call(c, MG_EV_ACCEPT, NULL);
  6935. }
  6936. }
  6937. static bool can_read(const struct mg_connection *c) {
  6938. return c->is_full == false;
  6939. }
  6940. static bool can_write(const struct mg_connection *c) {
  6941. return c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0);
  6942. }
  6943. static bool skip_iotest(const struct mg_connection *c) {
  6944. return (c->is_closing || c->is_resolving || FD(c) == MG_INVALID_SOCKET) ||
  6945. (can_read(c) == false && can_write(c) == false);
  6946. }
  6947. static void mg_iotest(struct mg_mgr *mgr, int ms) {
  6948. #if MG_ENABLE_FREERTOS_TCP
  6949. struct mg_connection *c;
  6950. for (c = mgr->conns; c != NULL; c = c->next) {
  6951. c->is_readable = c->is_writable = 0;
  6952. if (skip_iotest(c)) continue;
  6953. if (can_read(c))
  6954. FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_READ | eSELECT_EXCEPT);
  6955. if (can_write(c)) FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_WRITE);
  6956. if (c->is_closing) ms = 1;
  6957. }
  6958. FreeRTOS_select(mgr->ss, pdMS_TO_TICKS(ms));
  6959. for (c = mgr->conns; c != NULL; c = c->next) {
  6960. EventBits_t bits = FreeRTOS_FD_ISSET(c->fd, mgr->ss);
  6961. c->is_readable = bits & (eSELECT_READ | eSELECT_EXCEPT) ? 1U : 0;
  6962. c->is_writable = bits & eSELECT_WRITE ? 1U : 0;
  6963. if (c->fd != MG_INVALID_SOCKET)
  6964. FreeRTOS_FD_CLR(c->fd, mgr->ss,
  6965. eSELECT_READ | eSELECT_EXCEPT | eSELECT_WRITE);
  6966. }
  6967. #elif MG_ENABLE_EPOLL
  6968. size_t max = 1;
  6969. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6970. c->is_readable = c->is_writable = 0;
  6971. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) ms = 1, c->is_readable = 1;
  6972. if (can_write(c)) MG_EPOLL_MOD(c, 1);
  6973. if (c->is_closing) ms = 1;
  6974. max++;
  6975. }
  6976. struct epoll_event *evs = (struct epoll_event *) alloca(max * sizeof(evs[0]));
  6977. int n = epoll_wait(mgr->epoll_fd, evs, (int) max, ms);
  6978. for (int i = 0; i < n; i++) {
  6979. struct mg_connection *c = (struct mg_connection *) evs[i].data.ptr;
  6980. if (evs[i].events & EPOLLERR) {
  6981. mg_error(c, "socket error");
  6982. } else if (c->is_readable == 0) {
  6983. bool rd = evs[i].events & (EPOLLIN | EPOLLHUP);
  6984. bool wr = evs[i].events & EPOLLOUT;
  6985. c->is_readable = can_read(c) && rd ? 1U : 0;
  6986. c->is_writable = can_write(c) && wr ? 1U : 0;
  6987. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  6988. }
  6989. }
  6990. (void) skip_iotest;
  6991. #elif MG_ENABLE_POLL
  6992. nfds_t n = 0;
  6993. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) n++;
  6994. struct pollfd *fds = (struct pollfd *) alloca(n * sizeof(fds[0]));
  6995. memset(fds, 0, n * sizeof(fds[0]));
  6996. n = 0;
  6997. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6998. c->is_readable = c->is_writable = 0;
  6999. if (skip_iotest(c)) {
  7000. // Socket not valid, ignore
  7001. } else if (c->rtls.len > 0 || mg_tls_pending(c) > 0) {
  7002. ms = 1; // Don't wait if TLS is ready
  7003. } else {
  7004. fds[n].fd = FD(c);
  7005. if (can_read(c)) fds[n].events |= POLLIN;
  7006. if (can_write(c)) fds[n].events |= POLLOUT;
  7007. if (c->is_closing) ms = 1;
  7008. n++;
  7009. }
  7010. }
  7011. // MG_INFO(("poll n=%d ms=%d", (int) n, ms));
  7012. if (poll(fds, n, ms) < 0) {
  7013. #if MG_ARCH == MG_ARCH_WIN32
  7014. if (n == 0) Sleep(ms); // On Windows, poll fails if no sockets
  7015. #endif
  7016. memset(fds, 0, n * sizeof(fds[0]));
  7017. }
  7018. n = 0;
  7019. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7020. if (skip_iotest(c)) {
  7021. // Socket not valid, ignore
  7022. } else if (c->rtls.len > 0 || mg_tls_pending(c) > 0) {
  7023. c->is_readable = 1;
  7024. } else {
  7025. if (fds[n].revents & POLLERR) {
  7026. mg_error(c, "socket error");
  7027. } else {
  7028. c->is_readable =
  7029. (unsigned) (fds[n].revents & (POLLIN | POLLHUP) ? 1 : 0);
  7030. c->is_writable = (unsigned) (fds[n].revents & POLLOUT ? 1 : 0);
  7031. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7032. }
  7033. n++;
  7034. }
  7035. }
  7036. #else
  7037. struct timeval tv = {ms / 1000, (ms % 1000) * 1000}, tv_zero = {0, 0}, *tvp;
  7038. struct mg_connection *c;
  7039. fd_set rset, wset, eset;
  7040. MG_SOCKET_TYPE maxfd = 0;
  7041. int rc;
  7042. FD_ZERO(&rset);
  7043. FD_ZERO(&wset);
  7044. FD_ZERO(&eset);
  7045. tvp = ms < 0 ? NULL : &tv;
  7046. for (c = mgr->conns; c != NULL; c = c->next) {
  7047. c->is_readable = c->is_writable = 0;
  7048. if (skip_iotest(c)) continue;
  7049. FD_SET(FD(c), &eset);
  7050. if (can_read(c)) FD_SET(FD(c), &rset);
  7051. if (can_write(c)) FD_SET(FD(c), &wset);
  7052. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) tvp = &tv_zero;
  7053. if (FD(c) > maxfd) maxfd = FD(c);
  7054. if (c->is_closing) ms = 1;
  7055. }
  7056. if ((rc = select((int) maxfd + 1, &rset, &wset, &eset, tvp)) < 0) {
  7057. #if MG_ARCH == MG_ARCH_WIN32
  7058. if (maxfd == 0) Sleep(ms); // On Windows, select fails if no sockets
  7059. #else
  7060. MG_ERROR(("select: %d %d", rc, MG_SOCK_ERR(rc)));
  7061. #endif
  7062. FD_ZERO(&rset);
  7063. FD_ZERO(&wset);
  7064. FD_ZERO(&eset);
  7065. }
  7066. for (c = mgr->conns; c != NULL; c = c->next) {
  7067. if (FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &eset)) {
  7068. mg_error(c, "socket error");
  7069. } else {
  7070. c->is_readable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &rset);
  7071. c->is_writable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &wset);
  7072. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7073. }
  7074. }
  7075. #endif
  7076. }
  7077. static bool mg_socketpair(MG_SOCKET_TYPE sp[2], union usa usa[2]) {
  7078. socklen_t n = sizeof(usa[0].sin);
  7079. bool success = false;
  7080. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7081. (void) memset(&usa[0], 0, sizeof(usa[0]));
  7082. usa[0].sin.sin_family = AF_INET;
  7083. *(uint32_t *) &usa->sin.sin_addr = mg_htonl(0x7f000001U); // 127.0.0.1
  7084. usa[1] = usa[0];
  7085. if ((sp[0] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  7086. (sp[1] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  7087. bind(sp[0], &usa[0].sa, n) == 0 && //
  7088. bind(sp[1], &usa[1].sa, n) == 0 && //
  7089. getsockname(sp[0], &usa[0].sa, &n) == 0 && //
  7090. getsockname(sp[1], &usa[1].sa, &n) == 0 && //
  7091. connect(sp[0], &usa[1].sa, n) == 0 && //
  7092. connect(sp[1], &usa[0].sa, n) == 0) { //
  7093. success = true;
  7094. }
  7095. if (!success) {
  7096. if (sp[0] != MG_INVALID_SOCKET) closesocket(sp[0]);
  7097. if (sp[1] != MG_INVALID_SOCKET) closesocket(sp[1]);
  7098. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7099. }
  7100. return success;
  7101. }
  7102. // mg_wakeup() event handler
  7103. static void wufn(struct mg_connection *c, int ev, void *ev_data) {
  7104. if (ev == MG_EV_READ) {
  7105. unsigned long *id = (unsigned long *) c->recv.buf;
  7106. // MG_INFO(("Got data"));
  7107. // mg_hexdump(c->recv.buf, c->recv.len);
  7108. if (c->recv.len >= sizeof(*id)) {
  7109. struct mg_connection *t;
  7110. for (t = c->mgr->conns; t != NULL; t = t->next) {
  7111. if (t->id == *id) {
  7112. struct mg_str data = mg_str_n((char *) c->recv.buf + sizeof(*id),
  7113. c->recv.len - sizeof(*id));
  7114. mg_call(t, MG_EV_WAKEUP, &data);
  7115. }
  7116. }
  7117. }
  7118. c->recv.len = 0; // Consume received data
  7119. } else if (ev == MG_EV_CLOSE) {
  7120. closesocket(c->mgr->pipe); // When we're closing, close the other
  7121. c->mgr->pipe = MG_INVALID_SOCKET; // side of the socketpair, too
  7122. }
  7123. (void) ev_data;
  7124. }
  7125. bool mg_wakeup_init(struct mg_mgr *mgr) {
  7126. bool ok = false;
  7127. if (mgr->pipe == MG_INVALID_SOCKET) {
  7128. union usa usa[2];
  7129. MG_SOCKET_TYPE sp[2] = {MG_INVALID_SOCKET, MG_INVALID_SOCKET};
  7130. struct mg_connection *c = NULL;
  7131. if (!mg_socketpair(sp, usa)) {
  7132. MG_ERROR(("Cannot create socket pair"));
  7133. } else if ((c = mg_wrapfd(mgr, (int) sp[1], wufn, NULL)) == NULL) {
  7134. closesocket(sp[0]);
  7135. closesocket(sp[1]);
  7136. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7137. } else {
  7138. tomgaddr(&usa[0], &c->rem, false);
  7139. MG_DEBUG(("%lu %p pipe %lu", c->id, c->fd, (unsigned long) sp[0]));
  7140. mgr->pipe = sp[0];
  7141. ok = true;
  7142. }
  7143. }
  7144. return ok;
  7145. }
  7146. bool mg_wakeup(struct mg_mgr *mgr, unsigned long conn_id, const void *buf,
  7147. size_t len) {
  7148. if (mgr->pipe != MG_INVALID_SOCKET && conn_id > 0) {
  7149. char *extended_buf = (char *) alloca(len + sizeof(conn_id));
  7150. memcpy(extended_buf, &conn_id, sizeof(conn_id));
  7151. memcpy(extended_buf + sizeof(conn_id), buf, len);
  7152. send(mgr->pipe, extended_buf, len + sizeof(conn_id), MSG_NONBLOCKING);
  7153. return true;
  7154. }
  7155. return false;
  7156. }
  7157. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  7158. struct mg_connection *c, *tmp;
  7159. uint64_t now;
  7160. mg_iotest(mgr, ms);
  7161. now = mg_millis();
  7162. mg_timer_poll(&mgr->timers, now);
  7163. for (c = mgr->conns; c != NULL; c = tmp) {
  7164. bool is_resp = c->is_resp;
  7165. tmp = c->next;
  7166. mg_call(c, MG_EV_POLL, &now);
  7167. if (is_resp && !c->is_resp) {
  7168. long n = 0;
  7169. mg_call(c, MG_EV_READ, &n);
  7170. }
  7171. MG_VERBOSE(("%lu %c%c %c%c%c%c%c %lu %lu", c->id,
  7172. c->is_readable ? 'r' : '-', c->is_writable ? 'w' : '-',
  7173. c->is_tls ? 'T' : 't', c->is_connecting ? 'C' : 'c',
  7174. c->is_tls_hs ? 'H' : 'h', c->is_resolving ? 'R' : 'r',
  7175. c->is_closing ? 'C' : 'c', mg_tls_pending(c), c->rtls.len));
  7176. if (c->is_resolving || c->is_closing) {
  7177. // Do nothing
  7178. } else if (c->is_listening && c->is_udp == 0) {
  7179. if (c->is_readable) accept_conn(mgr, c);
  7180. } else if (c->is_connecting) {
  7181. if (c->is_readable || c->is_writable) connect_conn(c);
  7182. //} else if (c->is_tls_hs) {
  7183. // if ((c->is_readable || c->is_writable)) mg_tls_handshake(c);
  7184. } else {
  7185. if (c->is_readable) read_conn(c);
  7186. if (c->is_writable) write_conn(c);
  7187. }
  7188. if (c->is_draining && c->send.len == 0) c->is_closing = 1;
  7189. if (c->is_closing) close_conn(c);
  7190. }
  7191. }
  7192. #endif
  7193. #ifdef MG_ENABLE_LINES
  7194. #line 1 "src/ssi.c"
  7195. #endif
  7196. #ifndef MG_MAX_SSI_DEPTH
  7197. #define MG_MAX_SSI_DEPTH 5
  7198. #endif
  7199. #ifndef MG_SSI_BUFSIZ
  7200. #define MG_SSI_BUFSIZ 1024
  7201. #endif
  7202. #if MG_ENABLE_SSI
  7203. static char *mg_ssi(const char *path, const char *root, int depth) {
  7204. struct mg_iobuf b = {NULL, 0, 0, MG_IO_SIZE};
  7205. FILE *fp = fopen(path, "rb");
  7206. if (fp != NULL) {
  7207. char buf[MG_SSI_BUFSIZ], arg[sizeof(buf)];
  7208. int ch, intag = 0;
  7209. size_t len = 0;
  7210. buf[0] = arg[0] = '\0';
  7211. while ((ch = fgetc(fp)) != EOF) {
  7212. if (intag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  7213. buf[len++] = (char) (ch & 0xff);
  7214. buf[len] = '\0';
  7215. if (sscanf(buf, "<!--#include file=\"%[^\"]", arg)) {
  7216. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10],
  7217. *p = (char *) path + strlen(path), *data;
  7218. while (p > path && p[-1] != MG_DIRSEP && p[-1] != '/') p--;
  7219. mg_snprintf(tmp, sizeof(tmp), "%.*s%s", (int) (p - path), path, arg);
  7220. if (depth < MG_MAX_SSI_DEPTH &&
  7221. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  7222. mg_iobuf_add(&b, b.len, data, strlen(data));
  7223. free(data);
  7224. } else {
  7225. MG_ERROR(("%s: file=%s error or too deep", path, arg));
  7226. }
  7227. } else if (sscanf(buf, "<!--#include virtual=\"%[^\"]", arg)) {
  7228. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10], *data;
  7229. mg_snprintf(tmp, sizeof(tmp), "%s%s", root, arg);
  7230. if (depth < MG_MAX_SSI_DEPTH &&
  7231. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  7232. mg_iobuf_add(&b, b.len, data, strlen(data));
  7233. free(data);
  7234. } else {
  7235. MG_ERROR(("%s: virtual=%s error or too deep", path, arg));
  7236. }
  7237. } else {
  7238. // Unknown SSI tag
  7239. MG_ERROR(("Unknown SSI tag: %.*s", (int) len, buf));
  7240. mg_iobuf_add(&b, b.len, buf, len);
  7241. }
  7242. intag = 0;
  7243. len = 0;
  7244. } else if (ch == '<') {
  7245. intag = 1;
  7246. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  7247. len = 0;
  7248. buf[len++] = (char) (ch & 0xff);
  7249. } else if (intag) {
  7250. if (len == 5 && strncmp(buf, "<!--#", 5) != 0) {
  7251. intag = 0;
  7252. } else if (len >= sizeof(buf) - 2) {
  7253. MG_ERROR(("%s: SSI tag is too large", path));
  7254. len = 0;
  7255. }
  7256. buf[len++] = (char) (ch & 0xff);
  7257. } else {
  7258. buf[len++] = (char) (ch & 0xff);
  7259. if (len >= sizeof(buf)) {
  7260. mg_iobuf_add(&b, b.len, buf, len);
  7261. len = 0;
  7262. }
  7263. }
  7264. }
  7265. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  7266. if (b.len > 0) mg_iobuf_add(&b, b.len, "", 1); // nul-terminate
  7267. fclose(fp);
  7268. }
  7269. (void) depth;
  7270. (void) root;
  7271. return (char *) b.buf;
  7272. }
  7273. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  7274. const char *fullpath) {
  7275. const char *headers = "Content-Type: text/html; charset=utf-8\r\n";
  7276. char *data = mg_ssi(fullpath, root, 0);
  7277. mg_http_reply(c, 200, headers, "%s", data == NULL ? "" : data);
  7278. free(data);
  7279. }
  7280. #else
  7281. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  7282. const char *fullpath) {
  7283. mg_http_reply(c, 501, NULL, "SSI not enabled");
  7284. (void) root, (void) fullpath;
  7285. }
  7286. #endif
  7287. #ifdef MG_ENABLE_LINES
  7288. #line 1 "src/str.c"
  7289. #endif
  7290. struct mg_str mg_str_s(const char *s) {
  7291. struct mg_str str = {(char *) s, s == NULL ? 0 : strlen(s)};
  7292. return str;
  7293. }
  7294. struct mg_str mg_str_n(const char *s, size_t n) {
  7295. struct mg_str str = {(char *) s, n};
  7296. return str;
  7297. }
  7298. static int mg_tolc(char c) {
  7299. return (c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c;
  7300. }
  7301. int mg_casecmp(const char *s1, const char *s2) {
  7302. int diff = 0;
  7303. do {
  7304. int c = mg_tolc(*s1++), d = mg_tolc(*s2++);
  7305. diff = c - d;
  7306. } while (diff == 0 && s1[-1] != '\0');
  7307. return diff;
  7308. }
  7309. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  7310. size_t i = 0;
  7311. while (i < str1.len && i < str2.len) {
  7312. int c1 = str1.buf[i];
  7313. int c2 = str2.buf[i];
  7314. if (c1 < c2) return -1;
  7315. if (c1 > c2) return 1;
  7316. i++;
  7317. }
  7318. if (i < str1.len) return 1;
  7319. if (i < str2.len) return -1;
  7320. return 0;
  7321. }
  7322. int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2) {
  7323. size_t i = 0;
  7324. while (i < str1.len && i < str2.len) {
  7325. int c1 = mg_tolc(str1.buf[i]);
  7326. int c2 = mg_tolc(str2.buf[i]);
  7327. if (c1 < c2) return -1;
  7328. if (c1 > c2) return 1;
  7329. i++;
  7330. }
  7331. if (i < str1.len) return 1;
  7332. if (i < str2.len) return -1;
  7333. return 0;
  7334. }
  7335. bool mg_match(struct mg_str s, struct mg_str p, struct mg_str *caps) {
  7336. size_t i = 0, j = 0, ni = 0, nj = 0;
  7337. if (caps) caps->buf = NULL, caps->len = 0;
  7338. while (i < p.len || j < s.len) {
  7339. if (i < p.len && j < s.len && (p.buf[i] == '?' || s.buf[j] == p.buf[i])) {
  7340. if (caps == NULL) {
  7341. } else if (p.buf[i] == '?') {
  7342. caps->buf = &s.buf[j], caps->len = 1; // Finalize `?` cap
  7343. caps++, caps->buf = NULL, caps->len = 0; // Init next cap
  7344. } else if (caps->buf != NULL && caps->len == 0) {
  7345. caps->len = (size_t) (&s.buf[j] - caps->buf); // Finalize current cap
  7346. caps++, caps->len = 0, caps->buf = NULL; // Init next cap
  7347. }
  7348. i++, j++;
  7349. } else if (i < p.len && (p.buf[i] == '*' || p.buf[i] == '#')) {
  7350. if (caps && !caps->buf) caps->len = 0, caps->buf = &s.buf[j]; // Init cap
  7351. ni = i++, nj = j + 1;
  7352. } else if (nj > 0 && nj <= s.len && (p.buf[ni] == '#' || s.buf[j] != '/')) {
  7353. i = ni, j = nj;
  7354. if (caps && caps->buf == NULL && caps->len == 0) {
  7355. caps--, caps->len = 0; // Restart previous cap
  7356. }
  7357. } else {
  7358. return false;
  7359. }
  7360. }
  7361. if (caps && caps->buf && caps->len == 0) {
  7362. caps->len = (size_t) (&s.buf[j] - caps->buf);
  7363. }
  7364. return true;
  7365. }
  7366. bool mg_span(struct mg_str s, struct mg_str *a, struct mg_str *b, char sep) {
  7367. if (s.len == 0 || s.buf == NULL) {
  7368. return false; // Empty string, nothing to span - fail
  7369. } else {
  7370. size_t len = 0;
  7371. while (len < s.len && s.buf[len] != sep) len++; // Find separator
  7372. if (a) *a = mg_str_n(s.buf, len); // Init a
  7373. if (b) *b = mg_str_n(s.buf + len, s.len - len); // Init b
  7374. if (b && len < s.len) b->buf++, b->len--; // Skip separator
  7375. return true;
  7376. }
  7377. }
  7378. bool mg_str_to_num(struct mg_str str, int base, void *val, size_t val_len) {
  7379. size_t i = 0, ndigits = 0;
  7380. uint64_t max = val_len == sizeof(uint8_t) ? 0xFF
  7381. : val_len == sizeof(uint16_t) ? 0xFFFF
  7382. : val_len == sizeof(uint32_t) ? 0xFFFFFFFF
  7383. : (uint64_t) ~0;
  7384. uint64_t result = 0;
  7385. if (max == (uint64_t) ~0 && val_len != sizeof(uint64_t)) return false;
  7386. if (base == 0 && str.len >= 2) {
  7387. if (str.buf[i] == '0') {
  7388. i++;
  7389. base = str.buf[i] == 'b' ? 2 : str.buf[i] == 'x' ? 16 : 10;
  7390. if (base != 10) ++i;
  7391. } else {
  7392. base = 10;
  7393. }
  7394. }
  7395. switch (base) {
  7396. case 2:
  7397. while (i < str.len && (str.buf[i] == '0' || str.buf[i] == '1')) {
  7398. uint64_t digit = (uint64_t) (str.buf[i] - '0');
  7399. if (result > max/2) return false; // Overflow
  7400. result *= 2;
  7401. if (result > max - digit) return false; // Overflow
  7402. result += digit;
  7403. i++, ndigits++;
  7404. }
  7405. break;
  7406. case 10:
  7407. while (i < str.len && str.buf[i] >= '0' && str.buf[i] <= '9') {
  7408. uint64_t digit = (uint64_t) (str.buf[i] - '0');
  7409. if (result > max/10) return false; // Overflow
  7410. result *= 10;
  7411. if (result > max - digit) return false; // Overflow
  7412. result += digit;
  7413. i++, ndigits++;
  7414. }
  7415. break;
  7416. case 16:
  7417. while (i < str.len) {
  7418. char c = str.buf[i];
  7419. uint64_t digit = (c >= '0' && c <= '9') ? (uint64_t) (c - '0')
  7420. : (c >= 'A' && c <= 'F') ? (uint64_t) (c - '7')
  7421. : (c >= 'a' && c <= 'f') ? (uint64_t) (c - 'W')
  7422. : (uint64_t) ~0;
  7423. if (digit == (uint64_t) ~0) break;
  7424. if (result > max/16) return false; // Overflow
  7425. result *= 16;
  7426. if (result > max - digit) return false; // Overflow
  7427. result += digit;
  7428. i++, ndigits++;
  7429. }
  7430. break;
  7431. default:
  7432. return false;
  7433. }
  7434. if (ndigits == 0) return false;
  7435. if (i != str.len) return false;
  7436. if (val_len == 1) {
  7437. *((uint8_t *) val) = (uint8_t) result;
  7438. } else if (val_len == 2) {
  7439. *((uint16_t *) val) = (uint16_t) result;
  7440. } else if (val_len == 4) {
  7441. *((uint32_t *) val) = (uint32_t) result;
  7442. } else {
  7443. *((uint64_t *) val) = (uint64_t) result;
  7444. }
  7445. return true;
  7446. }
  7447. #ifdef MG_ENABLE_LINES
  7448. #line 1 "src/timer.c"
  7449. #endif
  7450. #define MG_TIMER_CALLED 4
  7451. void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
  7452. unsigned flags, void (*fn)(void *), void *arg) {
  7453. t->id = 0, t->period_ms = ms, t->expire = 0;
  7454. t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
  7455. *head = t;
  7456. }
  7457. void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
  7458. while (*head && *head != t) head = &(*head)->next;
  7459. if (*head) *head = t->next;
  7460. }
  7461. // t: expiration time, prd: period, now: current time. Return true if expired
  7462. bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
  7463. if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
  7464. if (*t == 0) *t = now + prd; // Firt poll? Set expiration
  7465. if (*t > now) return false; // Not expired yet, return
  7466. *t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
  7467. return true; // Expired, return true
  7468. }
  7469. void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
  7470. struct mg_timer *t, *tmp;
  7471. for (t = *head; t != NULL; t = tmp) {
  7472. bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
  7473. !(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
  7474. bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
  7475. tmp = t->next;
  7476. if (!once && !expired) continue;
  7477. if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
  7478. t->fn(t->arg);
  7479. }
  7480. t->flags |= MG_TIMER_CALLED;
  7481. }
  7482. }
  7483. #ifdef MG_ENABLE_LINES
  7484. #line 1 "src/tls_aes128.c"
  7485. #endif
  7486. /******************************************************************************
  7487. *
  7488. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7489. *
  7490. * This is a simple and straightforward implementation of the AES Rijndael
  7491. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7492. * of this work was correctness & accuracy. It is written in 'C' without any
  7493. * particular focus upon optimization or speed. It should be endian (memory
  7494. * byte order) neutral since the few places that care are handled explicitly.
  7495. *
  7496. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7497. *
  7498. * It is intended for general purpose use, but was written in support of GRC's
  7499. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7500. *
  7501. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7502. *
  7503. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7504. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7505. *
  7506. *******************************************************************************/
  7507. /******************************************************************************/
  7508. #define AES_DECRYPTION 1 // whether AES decryption is supported
  7509. /******************************************************************************/
  7510. #define MG_ENCRYPT 1 // specify whether we're encrypting
  7511. #define MG_DECRYPT 0 // or decrypting
  7512. #if MG_TLS == MG_TLS_BUILTIN
  7513. /******************************************************************************
  7514. * AES_INIT_KEYGEN_TABLES : MUST be called once before any AES use
  7515. ******************************************************************************/
  7516. static void aes_init_keygen_tables(void);
  7517. /******************************************************************************
  7518. * AES_SETKEY : called to expand the key for encryption or decryption
  7519. ******************************************************************************/
  7520. static int aes_setkey(aes_context *ctx, // pointer to context
  7521. int mode, // 1 or 0 for Encrypt/Decrypt
  7522. const uchar *key, // AES input key
  7523. uint keysize); // size in bytes (must be 16, 24, 32 for
  7524. // 128, 192 or 256-bit keys respectively)
  7525. // returns 0 for success
  7526. /******************************************************************************
  7527. * AES_CIPHER : called to encrypt or decrypt ONE 128-bit block of data
  7528. ******************************************************************************/
  7529. static int aes_cipher(aes_context *ctx, // pointer to context
  7530. const uchar input[16], // 128-bit block to en/decipher
  7531. uchar output[16]); // 128-bit output result block
  7532. // returns 0 for success
  7533. /******************************************************************************
  7534. * GCM_CONTEXT : GCM context / holds keytables, instance data, and AES ctx
  7535. ******************************************************************************/
  7536. typedef struct {
  7537. int mode; // cipher direction: encrypt/decrypt
  7538. uint64_t len; // cipher data length processed so far
  7539. uint64_t add_len; // total add data length
  7540. uint64_t HL[16]; // precalculated lo-half HTable
  7541. uint64_t HH[16]; // precalculated hi-half HTable
  7542. uchar base_ectr[16]; // first counter-mode cipher output for tag
  7543. uchar y[16]; // the current cipher-input IV|Counter value
  7544. uchar buf[16]; // buf working value
  7545. aes_context aes_ctx; // cipher context used
  7546. } gcm_context;
  7547. /******************************************************************************
  7548. * GCM_SETKEY : sets the GCM (and AES) keying material for use
  7549. ******************************************************************************/
  7550. static int gcm_setkey(
  7551. gcm_context *ctx, // caller-provided context ptr
  7552. const uchar *key, // pointer to cipher key
  7553. const uint keysize // size in bytes (must be 16, 24, 32 for
  7554. // 128, 192 or 256-bit keys respectively)
  7555. ); // returns 0 for success
  7556. /******************************************************************************
  7557. *
  7558. * GCM_CRYPT_AND_TAG
  7559. *
  7560. * This either encrypts or decrypts the user-provided data and, either
  7561. * way, generates an authentication tag of the requested length. It must be
  7562. * called with a GCM context whose key has already been set with GCM_SETKEY.
  7563. *
  7564. * The user would typically call this explicitly to ENCRYPT a buffer of data
  7565. * and optional associated data, and produce its an authentication tag.
  7566. *
  7567. * To reverse the process the user would typically call the companion
  7568. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  7569. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  7570. * to perform its decryption and tag generation, which it then compares.
  7571. *
  7572. ******************************************************************************/
  7573. static int gcm_crypt_and_tag(
  7574. gcm_context *ctx, // gcm context with key already setup
  7575. int mode, // cipher direction: MG_ENCRYPT (1) or MG_DECRYPT (0)
  7576. const uchar *iv, // pointer to the 12-byte initialization vector
  7577. size_t iv_len, // byte length if the IV. should always be 12
  7578. const uchar *add, // pointer to the non-ciphered additional data
  7579. size_t add_len, // byte length of the additional AEAD data
  7580. const uchar *input, // pointer to the cipher data source
  7581. uchar *output, // pointer to the cipher data destination
  7582. size_t length, // byte length of the cipher data
  7583. uchar *tag, // pointer to the tag to be generated
  7584. size_t tag_len); // byte length of the tag to be generated
  7585. /******************************************************************************
  7586. *
  7587. * GCM_START
  7588. *
  7589. * Given a user-provided GCM context, this initializes it, sets the encryption
  7590. * mode, and preprocesses the initialization vector and additional AEAD data.
  7591. *
  7592. ******************************************************************************/
  7593. static int gcm_start(
  7594. gcm_context *ctx, // pointer to user-provided GCM context
  7595. int mode, // MG_ENCRYPT (1) or MG_DECRYPT (0)
  7596. const uchar *iv, // pointer to initialization vector
  7597. size_t iv_len, // IV length in bytes (should == 12)
  7598. const uchar *add, // pointer to additional AEAD data (NULL if none)
  7599. size_t add_len); // length of additional AEAD data (bytes)
  7600. /******************************************************************************
  7601. *
  7602. * GCM_UPDATE
  7603. *
  7604. * This is called once or more to process bulk plaintext or ciphertext data.
  7605. * We give this some number of bytes of input and it returns the same number
  7606. * of output bytes. If called multiple times (which is fine) all but the final
  7607. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  7608. * have a partial block length of < 128 bits.)
  7609. *
  7610. ******************************************************************************/
  7611. static int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  7612. size_t length, // length, in bytes, of data to process
  7613. const uchar *input, // pointer to source data
  7614. uchar *output); // pointer to destination data
  7615. /******************************************************************************
  7616. *
  7617. * GCM_FINISH
  7618. *
  7619. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  7620. * It performs the final GHASH to produce the resulting authentication TAG.
  7621. *
  7622. ******************************************************************************/
  7623. static int gcm_finish(
  7624. gcm_context *ctx, // pointer to user-provided GCM context
  7625. uchar *tag, // ptr to tag buffer - NULL if tag_len = 0
  7626. size_t tag_len); // length, in bytes, of the tag-receiving buf
  7627. /******************************************************************************
  7628. *
  7629. * GCM_ZERO_CTX
  7630. *
  7631. * The GCM context contains both the GCM context and the AES context.
  7632. * This includes keying and key-related material which is security-
  7633. * sensitive, so it MUST be zeroed after use. This function does that.
  7634. *
  7635. ******************************************************************************/
  7636. static void gcm_zero_ctx(gcm_context *ctx);
  7637. /******************************************************************************
  7638. *
  7639. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7640. *
  7641. * This is a simple and straightforward implementation of the AES Rijndael
  7642. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7643. * of this work was correctness & accuracy. It is written in 'C' without any
  7644. * particular focus upon optimization or speed. It should be endian (memory
  7645. * byte order) neutral since the few places that care are handled explicitly.
  7646. *
  7647. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7648. *
  7649. * It is intended for general purpose use, but was written in support of GRC's
  7650. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7651. *
  7652. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7653. *
  7654. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7655. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7656. *
  7657. *******************************************************************************/
  7658. static int aes_tables_inited = 0; // run-once flag for performing key
  7659. // expasion table generation (see below)
  7660. /*
  7661. * The following static local tables must be filled-in before the first use of
  7662. * the GCM or AES ciphers. They are used for the AES key expansion/scheduling
  7663. * and once built are read-only and thread safe. The "gcm_initialize" function
  7664. * must be called once during system initialization to populate these arrays
  7665. * for subsequent use by the AES key scheduler. If they have not been built
  7666. * before attempted use, an error will be returned to the caller.
  7667. *
  7668. * NOTE: GCM Encryption/Decryption does NOT REQUIRE AES decryption. Since
  7669. * GCM uses AES in counter-mode, where the AES cipher output is XORed with
  7670. * the GCM input, we ONLY NEED AES encryption. Thus, to save space AES
  7671. * decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.
  7672. */
  7673. // We always need our forward tables
  7674. static uchar FSb[256]; // Forward substitution box (FSb)
  7675. static uint32_t FT0[256]; // Forward key schedule assembly tables
  7676. static uint32_t FT1[256];
  7677. static uint32_t FT2[256];
  7678. static uint32_t FT3[256];
  7679. #if AES_DECRYPTION // We ONLY need reverse for decryption
  7680. static uchar RSb[256]; // Reverse substitution box (RSb)
  7681. static uint32_t RT0[256]; // Reverse key schedule assembly tables
  7682. static uint32_t RT1[256];
  7683. static uint32_t RT2[256];
  7684. static uint32_t RT3[256];
  7685. #endif /* AES_DECRYPTION */
  7686. static uint32_t RCON[10]; // AES round constants
  7687. /*
  7688. * Platform Endianness Neutralizing Load and Store Macro definitions
  7689. * AES wants platform-neutral Little Endian (LE) byte ordering
  7690. */
  7691. #define GET_UINT32_LE(n, b, i) \
  7692. { \
  7693. (n) = ((uint32_t) (b)[(i)]) | ((uint32_t) (b)[(i) + 1] << 8) | \
  7694. ((uint32_t) (b)[(i) + 2] << 16) | ((uint32_t) (b)[(i) + 3] << 24); \
  7695. }
  7696. #define PUT_UINT32_LE(n, b, i) \
  7697. { \
  7698. (b)[(i)] = (uchar) ((n)); \
  7699. (b)[(i) + 1] = (uchar) ((n) >> 8); \
  7700. (b)[(i) + 2] = (uchar) ((n) >> 16); \
  7701. (b)[(i) + 3] = (uchar) ((n) >> 24); \
  7702. }
  7703. /*
  7704. * AES forward and reverse encryption round processing macros
  7705. */
  7706. #define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7707. { \
  7708. X0 = *RK++ ^ FT0[(Y0) & 0xFF] ^ FT1[(Y1 >> 8) & 0xFF] ^ \
  7709. FT2[(Y2 >> 16) & 0xFF] ^ FT3[(Y3 >> 24) & 0xFF]; \
  7710. \
  7711. X1 = *RK++ ^ FT0[(Y1) & 0xFF] ^ FT1[(Y2 >> 8) & 0xFF] ^ \
  7712. FT2[(Y3 >> 16) & 0xFF] ^ FT3[(Y0 >> 24) & 0xFF]; \
  7713. \
  7714. X2 = *RK++ ^ FT0[(Y2) & 0xFF] ^ FT1[(Y3 >> 8) & 0xFF] ^ \
  7715. FT2[(Y0 >> 16) & 0xFF] ^ FT3[(Y1 >> 24) & 0xFF]; \
  7716. \
  7717. X3 = *RK++ ^ FT0[(Y3) & 0xFF] ^ FT1[(Y0 >> 8) & 0xFF] ^ \
  7718. FT2[(Y1 >> 16) & 0xFF] ^ FT3[(Y2 >> 24) & 0xFF]; \
  7719. }
  7720. #define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7721. { \
  7722. X0 = *RK++ ^ RT0[(Y0) & 0xFF] ^ RT1[(Y3 >> 8) & 0xFF] ^ \
  7723. RT2[(Y2 >> 16) & 0xFF] ^ RT3[(Y1 >> 24) & 0xFF]; \
  7724. \
  7725. X1 = *RK++ ^ RT0[(Y1) & 0xFF] ^ RT1[(Y0 >> 8) & 0xFF] ^ \
  7726. RT2[(Y3 >> 16) & 0xFF] ^ RT3[(Y2 >> 24) & 0xFF]; \
  7727. \
  7728. X2 = *RK++ ^ RT0[(Y2) & 0xFF] ^ RT1[(Y1 >> 8) & 0xFF] ^ \
  7729. RT2[(Y0 >> 16) & 0xFF] ^ RT3[(Y3 >> 24) & 0xFF]; \
  7730. \
  7731. X3 = *RK++ ^ RT0[(Y3) & 0xFF] ^ RT1[(Y2 >> 8) & 0xFF] ^ \
  7732. RT2[(Y1 >> 16) & 0xFF] ^ RT3[(Y0 >> 24) & 0xFF]; \
  7733. }
  7734. /*
  7735. * These macros improve the readability of the key
  7736. * generation initialization code by collapsing
  7737. * repetitive common operations into logical pieces.
  7738. */
  7739. #define ROTL8(x) ((x << 8) & 0xFFFFFFFF) | (x >> 24)
  7740. #define XTIME(x) ((x << 1) ^ ((x & 0x80) ? 0x1B : 0x00))
  7741. #define MUL(x, y) ((x && y) ? pow[(log[x] + log[y]) % 255] : 0)
  7742. #define MIX(x, y) \
  7743. { \
  7744. y = ((y << 1) | (y >> 7)) & 0xFF; \
  7745. x ^= y; \
  7746. }
  7747. #define CPY128 \
  7748. { \
  7749. *RK++ = *SK++; \
  7750. *RK++ = *SK++; \
  7751. *RK++ = *SK++; \
  7752. *RK++ = *SK++; \
  7753. }
  7754. /******************************************************************************
  7755. *
  7756. * AES_INIT_KEYGEN_TABLES
  7757. *
  7758. * Fills the AES key expansion tables allocated above with their static
  7759. * data. This is not "per key" data, but static system-wide read-only
  7760. * table data. THIS FUNCTION IS NOT THREAD SAFE. It must be called once
  7761. * at system initialization to setup the tables for all subsequent use.
  7762. *
  7763. ******************************************************************************/
  7764. void aes_init_keygen_tables(void) {
  7765. int i, x, y, z; // general purpose iteration and computation locals
  7766. int pow[256];
  7767. int log[256];
  7768. if (aes_tables_inited) return;
  7769. // fill the 'pow' and 'log' tables over GF(2^8)
  7770. for (i = 0, x = 1; i < 256; i++) {
  7771. pow[i] = x;
  7772. log[x] = i;
  7773. x = (x ^ XTIME(x)) & 0xFF;
  7774. }
  7775. // compute the round constants
  7776. for (i = 0, x = 1; i < 10; i++) {
  7777. RCON[i] = (uint32_t) x;
  7778. x = XTIME(x) & 0xFF;
  7779. }
  7780. // fill the forward and reverse substitution boxes
  7781. FSb[0x00] = 0x63;
  7782. #if AES_DECRYPTION // whether AES decryption is supported
  7783. RSb[0x63] = 0x00;
  7784. #endif /* AES_DECRYPTION */
  7785. for (i = 1; i < 256; i++) {
  7786. x = y = pow[255 - log[i]];
  7787. MIX(x, y);
  7788. MIX(x, y);
  7789. MIX(x, y);
  7790. MIX(x, y);
  7791. FSb[i] = (uchar) (x ^= 0x63);
  7792. #if AES_DECRYPTION // whether AES decryption is supported
  7793. RSb[x] = (uchar) i;
  7794. #endif /* AES_DECRYPTION */
  7795. }
  7796. // generate the forward and reverse key expansion tables
  7797. for (i = 0; i < 256; i++) {
  7798. x = FSb[i];
  7799. y = XTIME(x) & 0xFF;
  7800. z = (y ^ x) & 0xFF;
  7801. FT0[i] = ((uint32_t) y) ^ ((uint32_t) x << 8) ^ ((uint32_t) x << 16) ^
  7802. ((uint32_t) z << 24);
  7803. FT1[i] = ROTL8(FT0[i]);
  7804. FT2[i] = ROTL8(FT1[i]);
  7805. FT3[i] = ROTL8(FT2[i]);
  7806. #if AES_DECRYPTION // whether AES decryption is supported
  7807. x = RSb[i];
  7808. RT0[i] = ((uint32_t) MUL(0x0E, x)) ^ ((uint32_t) MUL(0x09, x) << 8) ^
  7809. ((uint32_t) MUL(0x0D, x) << 16) ^ ((uint32_t) MUL(0x0B, x) << 24);
  7810. RT1[i] = ROTL8(RT0[i]);
  7811. RT2[i] = ROTL8(RT1[i]);
  7812. RT3[i] = ROTL8(RT2[i]);
  7813. #endif /* AES_DECRYPTION */
  7814. }
  7815. aes_tables_inited = 1; // flag that the tables have been generated
  7816. } // to permit subsequent use of the AES cipher
  7817. /******************************************************************************
  7818. *
  7819. * AES_SET_ENCRYPTION_KEY
  7820. *
  7821. * This is called by 'aes_setkey' when we're establishing a key for
  7822. * subsequent encryption. We give it a pointer to the encryption
  7823. * context, a pointer to the key, and the key's length in bytes.
  7824. * Valid lengths are: 16, 24 or 32 bytes (128, 192, 256 bits).
  7825. *
  7826. ******************************************************************************/
  7827. static int aes_set_encryption_key(aes_context *ctx, const uchar *key,
  7828. uint keysize) {
  7829. uint i; // general purpose iteration local
  7830. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7831. for (i = 0; i < (keysize >> 2); i++) {
  7832. GET_UINT32_LE(RK[i], key, i << 2);
  7833. }
  7834. switch (ctx->rounds) {
  7835. case 10:
  7836. for (i = 0; i < 10; i++, RK += 4) {
  7837. RK[4] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[3] >> 8) & 0xFF]) ^
  7838. ((uint32_t) FSb[(RK[3] >> 16) & 0xFF] << 8) ^
  7839. ((uint32_t) FSb[(RK[3] >> 24) & 0xFF] << 16) ^
  7840. ((uint32_t) FSb[(RK[3]) & 0xFF] << 24);
  7841. RK[5] = RK[1] ^ RK[4];
  7842. RK[6] = RK[2] ^ RK[5];
  7843. RK[7] = RK[3] ^ RK[6];
  7844. }
  7845. break;
  7846. case 12:
  7847. for (i = 0; i < 8; i++, RK += 6) {
  7848. RK[6] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[5] >> 8) & 0xFF]) ^
  7849. ((uint32_t) FSb[(RK[5] >> 16) & 0xFF] << 8) ^
  7850. ((uint32_t) FSb[(RK[5] >> 24) & 0xFF] << 16) ^
  7851. ((uint32_t) FSb[(RK[5]) & 0xFF] << 24);
  7852. RK[7] = RK[1] ^ RK[6];
  7853. RK[8] = RK[2] ^ RK[7];
  7854. RK[9] = RK[3] ^ RK[8];
  7855. RK[10] = RK[4] ^ RK[9];
  7856. RK[11] = RK[5] ^ RK[10];
  7857. }
  7858. break;
  7859. case 14:
  7860. for (i = 0; i < 7; i++, RK += 8) {
  7861. RK[8] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[7] >> 8) & 0xFF]) ^
  7862. ((uint32_t) FSb[(RK[7] >> 16) & 0xFF] << 8) ^
  7863. ((uint32_t) FSb[(RK[7] >> 24) & 0xFF] << 16) ^
  7864. ((uint32_t) FSb[(RK[7]) & 0xFF] << 24);
  7865. RK[9] = RK[1] ^ RK[8];
  7866. RK[10] = RK[2] ^ RK[9];
  7867. RK[11] = RK[3] ^ RK[10];
  7868. RK[12] = RK[4] ^ ((uint32_t) FSb[(RK[11]) & 0xFF]) ^
  7869. ((uint32_t) FSb[(RK[11] >> 8) & 0xFF] << 8) ^
  7870. ((uint32_t) FSb[(RK[11] >> 16) & 0xFF] << 16) ^
  7871. ((uint32_t) FSb[(RK[11] >> 24) & 0xFF] << 24);
  7872. RK[13] = RK[5] ^ RK[12];
  7873. RK[14] = RK[6] ^ RK[13];
  7874. RK[15] = RK[7] ^ RK[14];
  7875. }
  7876. break;
  7877. default:
  7878. return -1;
  7879. }
  7880. return (0);
  7881. }
  7882. #if AES_DECRYPTION // whether AES decryption is supported
  7883. /******************************************************************************
  7884. *
  7885. * AES_SET_DECRYPTION_KEY
  7886. *
  7887. * This is called by 'aes_setkey' when we're establishing a
  7888. * key for subsequent decryption. We give it a pointer to
  7889. * the encryption context, a pointer to the key, and the key's
  7890. * length in bits. Valid lengths are: 128, 192, or 256 bits.
  7891. *
  7892. ******************************************************************************/
  7893. static int aes_set_decryption_key(aes_context *ctx, const uchar *key,
  7894. uint keysize) {
  7895. int i, j;
  7896. aes_context cty; // a calling aes context for set_encryption_key
  7897. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7898. uint32_t *SK;
  7899. int ret;
  7900. cty.rounds = ctx->rounds; // initialize our local aes context
  7901. cty.rk = cty.buf; // round count and key buf pointer
  7902. if ((ret = aes_set_encryption_key(&cty, key, keysize)) != 0) return (ret);
  7903. SK = cty.rk + cty.rounds * 4;
  7904. CPY128 // copy a 128-bit block from *SK to *RK
  7905. for (i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8) {
  7906. for (j = 0; j < 4; j++, SK++) {
  7907. *RK++ = RT0[FSb[(*SK) & 0xFF]] ^ RT1[FSb[(*SK >> 8) & 0xFF]] ^
  7908. RT2[FSb[(*SK >> 16) & 0xFF]] ^ RT3[FSb[(*SK >> 24) & 0xFF]];
  7909. }
  7910. }
  7911. CPY128 // copy a 128-bit block from *SK to *RK
  7912. memset(&cty, 0, sizeof(aes_context)); // clear local aes context
  7913. return (0);
  7914. }
  7915. #endif /* AES_DECRYPTION */
  7916. /******************************************************************************
  7917. *
  7918. * AES_SETKEY
  7919. *
  7920. * Invoked to establish the key schedule for subsequent encryption/decryption
  7921. *
  7922. ******************************************************************************/
  7923. static int aes_setkey(aes_context *ctx, // AES context provided by our caller
  7924. int mode, // ENCRYPT or DECRYPT flag
  7925. const uchar *key, // pointer to the key
  7926. uint keysize) // key length in bytes
  7927. {
  7928. // since table initialization is not thread safe, we could either add
  7929. // system-specific mutexes and init the AES key generation tables on
  7930. // demand, or ask the developer to simply call "gcm_initialize" once during
  7931. // application startup before threading begins. That's what we choose.
  7932. if (!aes_tables_inited) return (-1); // fail the call when not inited.
  7933. ctx->mode = mode; // capture the key type we're creating
  7934. ctx->rk = ctx->buf; // initialize our round key pointer
  7935. switch (keysize) // set the rounds count based upon the keysize
  7936. {
  7937. case 16:
  7938. ctx->rounds = 10;
  7939. break; // 16-byte, 128-bit key
  7940. case 24:
  7941. ctx->rounds = 12;
  7942. break; // 24-byte, 192-bit key
  7943. case 32:
  7944. ctx->rounds = 14;
  7945. break; // 32-byte, 256-bit key
  7946. default:
  7947. return (-1);
  7948. }
  7949. #if AES_DECRYPTION
  7950. if (mode == MG_DECRYPT) // expand our key for encryption or decryption
  7951. return (aes_set_decryption_key(ctx, key, keysize));
  7952. else /* MG_ENCRYPT */
  7953. #endif /* AES_DECRYPTION */
  7954. return (aes_set_encryption_key(ctx, key, keysize));
  7955. }
  7956. /******************************************************************************
  7957. *
  7958. * AES_CIPHER
  7959. *
  7960. * Perform AES encryption and decryption.
  7961. * The AES context will have been setup with the encryption mode
  7962. * and all keying information appropriate for the task.
  7963. *
  7964. ******************************************************************************/
  7965. static int aes_cipher(aes_context *ctx, const uchar input[16],
  7966. uchar output[16]) {
  7967. int i;
  7968. uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; // general purpose locals
  7969. RK = ctx->rk;
  7970. GET_UINT32_LE(X0, input, 0);
  7971. X0 ^= *RK++; // load our 128-bit
  7972. GET_UINT32_LE(X1, input, 4);
  7973. X1 ^= *RK++; // input buffer in a storage
  7974. GET_UINT32_LE(X2, input, 8);
  7975. X2 ^= *RK++; // memory endian-neutral way
  7976. GET_UINT32_LE(X3, input, 12);
  7977. X3 ^= *RK++;
  7978. #if AES_DECRYPTION // whether AES decryption is supported
  7979. if (ctx->mode == MG_DECRYPT) {
  7980. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  7981. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7982. AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  7983. }
  7984. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7985. X0 = *RK++ ^ ((uint32_t) RSb[(Y0) & 0xFF]) ^
  7986. ((uint32_t) RSb[(Y3 >> 8) & 0xFF] << 8) ^
  7987. ((uint32_t) RSb[(Y2 >> 16) & 0xFF] << 16) ^
  7988. ((uint32_t) RSb[(Y1 >> 24) & 0xFF] << 24);
  7989. X1 = *RK++ ^ ((uint32_t) RSb[(Y1) & 0xFF]) ^
  7990. ((uint32_t) RSb[(Y0 >> 8) & 0xFF] << 8) ^
  7991. ((uint32_t) RSb[(Y3 >> 16) & 0xFF] << 16) ^
  7992. ((uint32_t) RSb[(Y2 >> 24) & 0xFF] << 24);
  7993. X2 = *RK++ ^ ((uint32_t) RSb[(Y2) & 0xFF]) ^
  7994. ((uint32_t) RSb[(Y1 >> 8) & 0xFF] << 8) ^
  7995. ((uint32_t) RSb[(Y0 >> 16) & 0xFF] << 16) ^
  7996. ((uint32_t) RSb[(Y3 >> 24) & 0xFF] << 24);
  7997. X3 = *RK++ ^ ((uint32_t) RSb[(Y3) & 0xFF]) ^
  7998. ((uint32_t) RSb[(Y2 >> 8) & 0xFF] << 8) ^
  7999. ((uint32_t) RSb[(Y1 >> 16) & 0xFF] << 16) ^
  8000. ((uint32_t) RSb[(Y0 >> 24) & 0xFF] << 24);
  8001. } else /* MG_ENCRYPT */
  8002. {
  8003. #endif /* AES_DECRYPTION */
  8004. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  8005. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8006. AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  8007. }
  8008. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8009. X0 = *RK++ ^ ((uint32_t) FSb[(Y0) & 0xFF]) ^
  8010. ((uint32_t) FSb[(Y1 >> 8) & 0xFF] << 8) ^
  8011. ((uint32_t) FSb[(Y2 >> 16) & 0xFF] << 16) ^
  8012. ((uint32_t) FSb[(Y3 >> 24) & 0xFF] << 24);
  8013. X1 = *RK++ ^ ((uint32_t) FSb[(Y1) & 0xFF]) ^
  8014. ((uint32_t) FSb[(Y2 >> 8) & 0xFF] << 8) ^
  8015. ((uint32_t) FSb[(Y3 >> 16) & 0xFF] << 16) ^
  8016. ((uint32_t) FSb[(Y0 >> 24) & 0xFF] << 24);
  8017. X2 = *RK++ ^ ((uint32_t) FSb[(Y2) & 0xFF]) ^
  8018. ((uint32_t) FSb[(Y3 >> 8) & 0xFF] << 8) ^
  8019. ((uint32_t) FSb[(Y0 >> 16) & 0xFF] << 16) ^
  8020. ((uint32_t) FSb[(Y1 >> 24) & 0xFF] << 24);
  8021. X3 = *RK++ ^ ((uint32_t) FSb[(Y3) & 0xFF]) ^
  8022. ((uint32_t) FSb[(Y0 >> 8) & 0xFF] << 8) ^
  8023. ((uint32_t) FSb[(Y1 >> 16) & 0xFF] << 16) ^
  8024. ((uint32_t) FSb[(Y2 >> 24) & 0xFF] << 24);
  8025. #if AES_DECRYPTION // whether AES decryption is supported
  8026. }
  8027. #endif /* AES_DECRYPTION */
  8028. PUT_UINT32_LE(X0, output, 0);
  8029. PUT_UINT32_LE(X1, output, 4);
  8030. PUT_UINT32_LE(X2, output, 8);
  8031. PUT_UINT32_LE(X3, output, 12);
  8032. return (0);
  8033. }
  8034. /* end of aes.c */
  8035. /******************************************************************************
  8036. *
  8037. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  8038. *
  8039. * This is a simple and straightforward implementation of AES-GCM authenticated
  8040. * encryption. The focus of this work was correctness & accuracy. It is written
  8041. * in straight 'C' without any particular focus upon optimization or speed. It
  8042. * should be endian (memory byte order) neutral since the few places that care
  8043. * are handled explicitly.
  8044. *
  8045. * This implementation of AES-GCM was created by Steven M. Gibson of GRC.com.
  8046. *
  8047. * It is intended for general purpose use, but was written in support of GRC's
  8048. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  8049. *
  8050. * See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  8051. * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/
  8052. * gcm/gcm-revised-spec.pdf
  8053. *
  8054. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  8055. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  8056. *
  8057. *******************************************************************************/
  8058. /******************************************************************************
  8059. * ==== IMPLEMENTATION WARNING ====
  8060. *
  8061. * This code was developed for use within SQRL's fixed environmnent. Thus, it
  8062. * is somewhat less "general purpose" than it would be if it were designed as
  8063. * a general purpose AES-GCM library. Specifically, it bothers with almost NO
  8064. * error checking on parameter limits, buffer bounds, etc. It assumes that it
  8065. * is being invoked by its author or by someone who understands the values it
  8066. * expects to receive. Its behavior will be undefined otherwise.
  8067. *
  8068. * All functions that might fail are defined to return 'ints' to indicate a
  8069. * problem. Most do not do so now. But this allows for error propagation out
  8070. * of internal functions if robust error checking should ever be desired.
  8071. *
  8072. ******************************************************************************/
  8073. /* Calculating the "GHASH"
  8074. *
  8075. * There are many ways of calculating the so-called GHASH in software, each with
  8076. * a traditional size vs performance tradeoff. The GHASH (Galois field hash) is
  8077. * an intriguing construction which takes two 128-bit strings (also the cipher's
  8078. * block size and the fundamental operation size for the system) and hashes them
  8079. * into a third 128-bit result.
  8080. *
  8081. * Many implementation solutions have been worked out that use large precomputed
  8082. * table lookups in place of more time consuming bit fiddling, and this approach
  8083. * can be scaled easily upward or downward as needed to change the time/space
  8084. * tradeoff. It's been studied extensively and there's a solid body of theory
  8085. * and practice. For example, without using any lookup tables an implementation
  8086. * might obtain 119 cycles per byte throughput, whereas using a simple, though
  8087. * large, key-specific 64 kbyte 8-bit lookup table the performance jumps to 13
  8088. * cycles per byte.
  8089. *
  8090. * And Intel's processors have, since 2010, included an instruction which does
  8091. * the entire 128x128->128 bit job in just several 64x64->128 bit pieces.
  8092. *
  8093. * Since SQRL is interactive, and only processing a few 128-bit blocks, I've
  8094. * settled upon a relatively slower but appealing small-table compromise which
  8095. * folds a bunch of not only time consuming but also bit twiddling into a simple
  8096. * 16-entry table which is attributed to Victor Shoup's 1996 work while at
  8097. * Bellcore: "On Fast and Provably Secure MessageAuthentication Based on
  8098. * Universal Hashing." See: http://www.shoup.net/papers/macs.pdf
  8099. * See, also section 4.1 of the "gcm-revised-spec" cited above.
  8100. */
  8101. /*
  8102. * This 16-entry table of pre-computed constants is used by the
  8103. * GHASH multiplier to improve over a strictly table-free but
  8104. * significantly slower 128x128 bit multiple within GF(2^128).
  8105. */
  8106. static const uint64_t last4[16] = {
  8107. 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
  8108. 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0};
  8109. /*
  8110. * Platform Endianness Neutralizing Load and Store Macro definitions
  8111. * GCM wants platform-neutral Big Endian (BE) byte ordering
  8112. */
  8113. #define GET_UINT32_BE(n, b, i) \
  8114. { \
  8115. (n) = ((uint32_t) (b)[(i)] << 24) | ((uint32_t) (b)[(i) + 1] << 16) | \
  8116. ((uint32_t) (b)[(i) + 2] << 8) | ((uint32_t) (b)[(i) + 3]); \
  8117. }
  8118. #define PUT_UINT32_BE(n, b, i) \
  8119. { \
  8120. (b)[(i)] = (uchar) ((n) >> 24); \
  8121. (b)[(i) + 1] = (uchar) ((n) >> 16); \
  8122. (b)[(i) + 2] = (uchar) ((n) >> 8); \
  8123. (b)[(i) + 3] = (uchar) ((n)); \
  8124. }
  8125. /******************************************************************************
  8126. *
  8127. * GCM_INITIALIZE
  8128. *
  8129. * Must be called once to initialize the GCM library.
  8130. *
  8131. * At present, this only calls the AES keygen table generator, which expands
  8132. * the AES keying tables for use. This is NOT A THREAD-SAFE function, so it
  8133. * MUST be called during system initialization before a multi-threading
  8134. * environment is running.
  8135. *
  8136. ******************************************************************************/
  8137. int mg_gcm_initialize(void) {
  8138. aes_init_keygen_tables();
  8139. return (0);
  8140. }
  8141. /******************************************************************************
  8142. *
  8143. * GCM_MULT
  8144. *
  8145. * Performs a GHASH operation on the 128-bit input vector 'x', setting
  8146. * the 128-bit output vector to 'x' times H using our precomputed tables.
  8147. * 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  8148. *
  8149. ******************************************************************************/
  8150. static void gcm_mult(gcm_context *ctx, // pointer to established context
  8151. const uchar x[16], // pointer to 128-bit input vector
  8152. uchar output[16]) // pointer to 128-bit output vector
  8153. {
  8154. int i;
  8155. uchar lo, hi, rem;
  8156. uint64_t zh, zl;
  8157. lo = (uchar) (x[15] & 0x0f);
  8158. hi = (uchar) (x[15] >> 4);
  8159. zh = ctx->HH[lo];
  8160. zl = ctx->HL[lo];
  8161. for (i = 15; i >= 0; i--) {
  8162. lo = (uchar) (x[i] & 0x0f);
  8163. hi = (uchar) (x[i] >> 4);
  8164. if (i != 15) {
  8165. rem = (uchar) (zl & 0x0f);
  8166. zl = (zh << 60) | (zl >> 4);
  8167. zh = (zh >> 4);
  8168. zh ^= (uint64_t) last4[rem] << 48;
  8169. zh ^= ctx->HH[lo];
  8170. zl ^= ctx->HL[lo];
  8171. }
  8172. rem = (uchar) (zl & 0x0f);
  8173. zl = (zh << 60) | (zl >> 4);
  8174. zh = (zh >> 4);
  8175. zh ^= (uint64_t) last4[rem] << 48;
  8176. zh ^= ctx->HH[hi];
  8177. zl ^= ctx->HL[hi];
  8178. }
  8179. PUT_UINT32_BE(zh >> 32, output, 0);
  8180. PUT_UINT32_BE(zh, output, 4);
  8181. PUT_UINT32_BE(zl >> 32, output, 8);
  8182. PUT_UINT32_BE(zl, output, 12);
  8183. }
  8184. /******************************************************************************
  8185. *
  8186. * GCM_SETKEY
  8187. *
  8188. * This is called to set the AES-GCM key. It initializes the AES key
  8189. * and populates the gcm context's pre-calculated HTables.
  8190. *
  8191. ******************************************************************************/
  8192. static int gcm_setkey(
  8193. gcm_context *ctx, // pointer to caller-provided gcm context
  8194. const uchar *key, // pointer to the AES encryption key
  8195. const uint keysize) // size in bytes (must be 16, 24, 32 for
  8196. // 128, 192 or 256-bit keys respectively)
  8197. {
  8198. int ret, i, j;
  8199. uint64_t hi, lo;
  8200. uint64_t vl, vh;
  8201. unsigned char h[16];
  8202. memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
  8203. memset(h, 0, 16); // initialize the block to encrypt
  8204. // encrypt the null 128-bit block to generate a key-based value
  8205. // which is then used to initialize our GHASH lookup tables
  8206. if ((ret = aes_setkey(&ctx->aes_ctx, MG_ENCRYPT, key, keysize)) != 0)
  8207. return (ret);
  8208. if ((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
  8209. GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
  8210. GET_UINT32_BE(lo, h, 4);
  8211. vh = (uint64_t) hi << 32 | lo;
  8212. GET_UINT32_BE(hi, h, 8);
  8213. GET_UINT32_BE(lo, h, 12);
  8214. vl = (uint64_t) hi << 32 | lo;
  8215. ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
  8216. ctx->HH[8] = vh;
  8217. ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
  8218. ctx->HL[0] = 0;
  8219. for (i = 4; i > 0; i >>= 1) {
  8220. uint32_t T = (uint32_t) (vl & 1) * 0xe1000000U;
  8221. vl = (vh << 63) | (vl >> 1);
  8222. vh = (vh >> 1) ^ ((uint64_t) T << 32);
  8223. ctx->HL[i] = vl;
  8224. ctx->HH[i] = vh;
  8225. }
  8226. for (i = 2; i < 16; i <<= 1) {
  8227. uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
  8228. vh = *HiH;
  8229. vl = *HiL;
  8230. for (j = 1; j < i; j++) {
  8231. HiH[j] = vh ^ ctx->HH[j];
  8232. HiL[j] = vl ^ ctx->HL[j];
  8233. }
  8234. }
  8235. return (0);
  8236. }
  8237. /******************************************************************************
  8238. *
  8239. * GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
  8240. *
  8241. * SETKEY:
  8242. *
  8243. * START: Sets the Encryption/Decryption mode.
  8244. * Accepts the initialization vector and additional data.
  8245. *
  8246. * UPDATE: Encrypts or decrypts the plaintext or ciphertext.
  8247. *
  8248. * FINISH: Performs a final GHASH to generate the authentication tag.
  8249. *
  8250. ******************************************************************************
  8251. *
  8252. * GCM_START
  8253. *
  8254. * Given a user-provided GCM context, this initializes it, sets the encryption
  8255. * mode, and preprocesses the initialization vector and additional AEAD data.
  8256. *
  8257. ******************************************************************************/
  8258. int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context
  8259. int mode, // GCM_ENCRYPT or GCM_DECRYPT
  8260. const uchar *iv, // pointer to initialization vector
  8261. size_t iv_len, // IV length in bytes (should == 12)
  8262. const uchar *add, // ptr to additional AEAD data (NULL if none)
  8263. size_t add_len) // length of additional AEAD data (bytes)
  8264. {
  8265. int ret; // our error return if the AES encrypt fails
  8266. uchar work_buf[16]; // XOR source built from provided IV if len != 16
  8267. const uchar *p; // general purpose array pointer
  8268. size_t use_len; // byte count to process, up to 16 bytes
  8269. size_t i; // local loop iterator
  8270. // since the context might be reused under the same key
  8271. // we zero the working buffers for this next new process
  8272. memset(ctx->y, 0x00, sizeof(ctx->y));
  8273. memset(ctx->buf, 0x00, sizeof(ctx->buf));
  8274. ctx->len = 0;
  8275. ctx->add_len = 0;
  8276. ctx->mode = mode; // set the GCM encryption/decryption mode
  8277. ctx->aes_ctx.mode = MG_ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
  8278. if (iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
  8279. memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
  8280. ctx->y[15] = 1; // start "counting" from 1 (not 0)
  8281. } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
  8282. {
  8283. memset(work_buf, 0x00, 16); // clear the working buffer
  8284. PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
  8285. p = iv;
  8286. while (iv_len > 0) {
  8287. use_len = (iv_len < 16) ? iv_len : 16;
  8288. for (i = 0; i < use_len; i++) ctx->y[i] ^= p[i];
  8289. gcm_mult(ctx, ctx->y, ctx->y);
  8290. iv_len -= use_len;
  8291. p += use_len;
  8292. }
  8293. for (i = 0; i < 16; i++) ctx->y[i] ^= work_buf[i];
  8294. gcm_mult(ctx, ctx->y, ctx->y);
  8295. }
  8296. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0)
  8297. return (ret);
  8298. ctx->add_len = add_len;
  8299. p = add;
  8300. while (add_len > 0) {
  8301. use_len = (add_len < 16) ? add_len : 16;
  8302. for (i = 0; i < use_len; i++) ctx->buf[i] ^= p[i];
  8303. gcm_mult(ctx, ctx->buf, ctx->buf);
  8304. add_len -= use_len;
  8305. p += use_len;
  8306. }
  8307. return (0);
  8308. }
  8309. /******************************************************************************
  8310. *
  8311. * GCM_UPDATE
  8312. *
  8313. * This is called once or more to process bulk plaintext or ciphertext data.
  8314. * We give this some number of bytes of input and it returns the same number
  8315. * of output bytes. If called multiple times (which is fine) all but the final
  8316. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  8317. * have a partial block length of < 128 bits.)
  8318. *
  8319. ******************************************************************************/
  8320. int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  8321. size_t length, // length, in bytes, of data to process
  8322. const uchar *input, // pointer to source data
  8323. uchar *output) // pointer to destination data
  8324. {
  8325. int ret; // our error return if the AES encrypt fails
  8326. uchar ectr[16]; // counter-mode cipher output for XORing
  8327. size_t use_len; // byte count to process, up to 16 bytes
  8328. size_t i; // local loop iterator
  8329. ctx->len += length; // bump the GCM context's running length count
  8330. while (length > 0) {
  8331. // clamp the length to process at 16 bytes
  8332. use_len = (length < 16) ? length : 16;
  8333. // increment the context's 128-bit IV||Counter 'y' vector
  8334. for (i = 16; i > 12; i--)
  8335. if (++ctx->y[i - 1] != 0) break;
  8336. // encrypt the context's 'y' vector under the established key
  8337. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
  8338. // encrypt or decrypt the input to the output
  8339. if (ctx->mode == MG_ENCRYPT) {
  8340. for (i = 0; i < use_len; i++) {
  8341. // XOR the cipher's ouptut vector (ectr) with our input
  8342. output[i] = (uchar) (ectr[i] ^ input[i]);
  8343. // now we mix in our data into the authentication hash.
  8344. // if we're ENcrypting we XOR in the post-XOR (output)
  8345. // results, but if we're DEcrypting we XOR in the input
  8346. // data
  8347. ctx->buf[i] ^= output[i];
  8348. }
  8349. } else {
  8350. for (i = 0; i < use_len; i++) {
  8351. // but if we're DEcrypting we XOR in the input data first,
  8352. // i.e. before saving to ouput data, otherwise if the input
  8353. // and output buffer are the same (inplace decryption) we
  8354. // would not get the correct auth tag
  8355. ctx->buf[i] ^= input[i];
  8356. // XOR the cipher's ouptut vector (ectr) with our input
  8357. output[i] = (uchar) (ectr[i] ^ input[i]);
  8358. }
  8359. }
  8360. gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
  8361. length -= use_len; // drop the remaining byte count to process
  8362. input += use_len; // bump our input pointer forward
  8363. output += use_len; // bump our output pointer forward
  8364. }
  8365. return (0);
  8366. }
  8367. /******************************************************************************
  8368. *
  8369. * GCM_FINISH
  8370. *
  8371. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  8372. * It performs the final GHASH to produce the resulting authentication TAG.
  8373. *
  8374. ******************************************************************************/
  8375. int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context
  8376. uchar *tag, // pointer to buffer which receives the tag
  8377. size_t tag_len) // length, in bytes, of the tag-receiving buf
  8378. {
  8379. uchar work_buf[16];
  8380. uint64_t orig_len = ctx->len * 8;
  8381. uint64_t orig_add_len = ctx->add_len * 8;
  8382. size_t i;
  8383. if (tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
  8384. if (orig_len || orig_add_len) {
  8385. memset(work_buf, 0x00, 16);
  8386. PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
  8387. PUT_UINT32_BE((orig_add_len), work_buf, 4);
  8388. PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
  8389. PUT_UINT32_BE((orig_len), work_buf, 12);
  8390. for (i = 0; i < 16; i++) ctx->buf[i] ^= work_buf[i];
  8391. gcm_mult(ctx, ctx->buf, ctx->buf);
  8392. for (i = 0; i < tag_len; i++) tag[i] ^= ctx->buf[i];
  8393. }
  8394. return (0);
  8395. }
  8396. /******************************************************************************
  8397. *
  8398. * GCM_CRYPT_AND_TAG
  8399. *
  8400. * This either encrypts or decrypts the user-provided data and, either
  8401. * way, generates an authentication tag of the requested length. It must be
  8402. * called with a GCM context whose key has already been set with GCM_SETKEY.
  8403. *
  8404. * The user would typically call this explicitly to ENCRYPT a buffer of data
  8405. * and optional associated data, and produce its an authentication tag.
  8406. *
  8407. * To reverse the process the user would typically call the companion
  8408. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  8409. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  8410. * to perform its decryption and tag generation, which it then compares.
  8411. *
  8412. ******************************************************************************/
  8413. int gcm_crypt_and_tag(
  8414. gcm_context *ctx, // gcm context with key already setup
  8415. int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
  8416. const uchar *iv, // pointer to the 12-byte initialization vector
  8417. size_t iv_len, // byte length if the IV. should always be 12
  8418. const uchar *add, // pointer to the non-ciphered additional data
  8419. size_t add_len, // byte length of the additional AEAD data
  8420. const uchar *input, // pointer to the cipher data source
  8421. uchar *output, // pointer to the cipher data destination
  8422. size_t length, // byte length of the cipher data
  8423. uchar *tag, // pointer to the tag to be generated
  8424. size_t tag_len) // byte length of the tag to be generated
  8425. { /*
  8426. assuming that the caller has already invoked gcm_setkey to
  8427. prepare the gcm context with the keying material, we simply
  8428. invoke each of the three GCM sub-functions in turn...
  8429. */
  8430. gcm_start(ctx, mode, iv, iv_len, add, add_len);
  8431. gcm_update(ctx, length, input, output);
  8432. gcm_finish(ctx, tag, tag_len);
  8433. return (0);
  8434. }
  8435. /******************************************************************************
  8436. *
  8437. * GCM_ZERO_CTX
  8438. *
  8439. * The GCM context contains both the GCM context and the AES context.
  8440. * This includes keying and key-related material which is security-
  8441. * sensitive, so it MUST be zeroed after use. This function does that.
  8442. *
  8443. ******************************************************************************/
  8444. void gcm_zero_ctx(gcm_context *ctx) {
  8445. // zero the context originally provided to us
  8446. memset(ctx, 0, sizeof(gcm_context));
  8447. }
  8448. //
  8449. // aes-gcm.c
  8450. // Pods
  8451. //
  8452. // Created by Markus Kosmal on 20/11/14.
  8453. //
  8454. //
  8455. int mg_aes_gcm_encrypt(unsigned char *output, //
  8456. const unsigned char *input, size_t input_length,
  8457. const unsigned char *key, const size_t key_len,
  8458. const unsigned char *iv, const size_t iv_len,
  8459. unsigned char *aead, size_t aead_len, unsigned char *tag,
  8460. const size_t tag_len) {
  8461. int ret = 0; // our return value
  8462. gcm_context ctx; // includes the AES context structure
  8463. gcm_setkey(&ctx, key, (uint) key_len);
  8464. ret = gcm_crypt_and_tag(&ctx, MG_ENCRYPT, iv, iv_len, aead, aead_len, input,
  8465. output, input_length, tag, tag_len);
  8466. gcm_zero_ctx(&ctx);
  8467. return (ret);
  8468. }
  8469. int mg_aes_gcm_decrypt(unsigned char *output, const unsigned char *input,
  8470. size_t input_length, const unsigned char *key,
  8471. const size_t key_len, const unsigned char *iv,
  8472. const size_t iv_len) {
  8473. int ret = 0; // our return value
  8474. gcm_context ctx; // includes the AES context structure
  8475. size_t tag_len = 0;
  8476. unsigned char *tag_buf = NULL;
  8477. gcm_setkey(&ctx, key, (uint) key_len);
  8478. ret = gcm_crypt_and_tag(&ctx, MG_DECRYPT, iv, iv_len, NULL, 0, input, output,
  8479. input_length, tag_buf, tag_len);
  8480. gcm_zero_ctx(&ctx);
  8481. return (ret);
  8482. }
  8483. #endif
  8484. // End of aes128 PD
  8485. #ifdef MG_ENABLE_LINES
  8486. #line 1 "src/tls_builtin.c"
  8487. #endif
  8488. #if MG_TLS == MG_TLS_BUILTIN
  8489. /* TLS 1.3 Record Content Type (RFC8446 B.1) */
  8490. #define MG_TLS_CHANGE_CIPHER 20
  8491. #define MG_TLS_ALERT 21
  8492. #define MG_TLS_HANDSHAKE 22
  8493. #define MG_TLS_APP_DATA 23
  8494. #define MG_TLS_HEARTBEAT 24
  8495. /* TLS 1.3 Handshake Message Type (RFC8446 B.3) */
  8496. #define MG_TLS_CLIENT_HELLO 1
  8497. #define MG_TLS_SERVER_HELLO 2
  8498. #define MG_TLS_ENCRYPTED_EXTENSIONS 8
  8499. #define MG_TLS_CERTIFICATE 11
  8500. #define MG_TLS_CERTIFICATE_VERIFY 15
  8501. #define MG_TLS_FINISHED 20
  8502. // handshake is re-entrant, so we need to keep track of its state state names
  8503. // refer to RFC8446#A.1
  8504. enum mg_tls_hs_state {
  8505. // Client state machine:
  8506. MG_TLS_STATE_CLIENT_START, // Send ClientHello
  8507. MG_TLS_STATE_CLIENT_WAIT_SH, // Wait for ServerHello
  8508. MG_TLS_STATE_CLIENT_WAIT_EE, // Wait for EncryptedExtensions
  8509. MG_TLS_STATE_CLIENT_WAIT_CERT, // Wait for Certificate
  8510. MG_TLS_STATE_CLIENT_WAIT_CV, // Wait for CertificateVerify
  8511. MG_TLS_STATE_CLIENT_WAIT_FINISHED, // Wait for Finished
  8512. MG_TLS_STATE_CLIENT_CONNECTED, // Done
  8513. // Server state machine:
  8514. MG_TLS_STATE_SERVER_START, // Wait for ClientHello
  8515. MG_TLS_STATE_SERVER_NEGOTIATED, // Wait for Finished
  8516. MG_TLS_STATE_SERVER_CONNECTED // Done
  8517. };
  8518. // per-connection TLS data
  8519. struct tls_data {
  8520. enum mg_tls_hs_state state; // keep track of connection handshake progress
  8521. struct mg_iobuf send; // For the receive path, we're reusing c->rtls
  8522. struct mg_iobuf recv; // While c->rtls contains full records, recv reuses
  8523. // the same underlying buffer but points at individual
  8524. // decrypted messages
  8525. uint8_t content_type; // Last received record content type
  8526. mg_sha256_ctx sha256; // incremental SHA-256 hash for TLS handshake
  8527. uint32_t sseq; // server sequence number, used in encryption
  8528. uint32_t cseq; // client sequence number, used in decryption
  8529. uint8_t random[32]; // client random from ClientHello
  8530. uint8_t session_id[32]; // client session ID between the handshake states
  8531. uint8_t x25519_cli[32]; // client X25519 key between the handshake states
  8532. uint8_t x25519_sec[32]; // x25519 secret between the handshake states
  8533. int skip_verification; // perform checks on server certificate?
  8534. struct mg_str server_cert_der; // server certificate in DER format
  8535. uint8_t server_key[32]; // server EC private key
  8536. char hostname[254]; // server hostname (client extension)
  8537. uint8_t certhash[32]; // certificate message hash
  8538. uint8_t pubkey[64]; // server EC public key to verify cert
  8539. uint8_t sighash[32]; // server EC public key to verify cert
  8540. // keys for AES encryption
  8541. uint8_t handshake_secret[32];
  8542. uint8_t server_write_key[16];
  8543. uint8_t server_write_iv[12];
  8544. uint8_t server_finished_key[32];
  8545. uint8_t client_write_key[16];
  8546. uint8_t client_write_iv[12];
  8547. uint8_t client_finished_key[32];
  8548. };
  8549. #define MG_LOAD_BE16(p) ((uint16_t) ((MG_U8P(p)[0] << 8U) | MG_U8P(p)[1]))
  8550. #define MG_LOAD_BE24(p) \
  8551. ((uint32_t) ((MG_U8P(p)[0] << 16U) | (MG_U8P(p)[1] << 8U) | MG_U8P(p)[2]))
  8552. #define MG_STORE_BE16(p, n) \
  8553. do { \
  8554. MG_U8P(p)[0] = ((n) >> 8U) & 255; \
  8555. MG_U8P(p)[1] = (n) & 255; \
  8556. } while (0)
  8557. #define TLS_RECHDR_SIZE 5 // 1 byte type, 2 bytes version, 2 bytes length
  8558. #define TLS_MSGHDR_SIZE 4 // 1 byte type, 3 bytes length
  8559. #if 1
  8560. static void mg_ssl_key_log(const char *label, uint8_t client_random[32],
  8561. uint8_t *secret, size_t secretsz) {
  8562. (void) label;
  8563. (void) client_random;
  8564. (void) secret;
  8565. (void) secretsz;
  8566. }
  8567. #else
  8568. #include <stdio.h>
  8569. static void mg_ssl_key_log(const char *label, uint8_t client_random[32],
  8570. uint8_t *secret, size_t secretsz) {
  8571. char *keylogfile = getenv("SSLKEYLOGFILE");
  8572. if (keylogfile == NULL) {
  8573. return;
  8574. }
  8575. FILE *f = fopen(keylogfile, "a");
  8576. fprintf(f, "%s ", label);
  8577. for (int i = 0; i < 32; i++) {
  8578. fprintf(f, "%02x", client_random[i]);
  8579. }
  8580. fprintf(f, " ");
  8581. for (unsigned int i = 0; i < secretsz; i++) {
  8582. fprintf(f, "%02x", secret[i]);
  8583. }
  8584. fprintf(f, "\n");
  8585. fclose(f);
  8586. }
  8587. #endif
  8588. // for derived tls keys we need SHA256([0]*32)
  8589. static uint8_t zeros[32] = {0};
  8590. static uint8_t zeros_sha256_digest[32] = {
  8591. 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4,
  8592. 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b,
  8593. 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55};
  8594. // helper to hexdump buffers inline
  8595. static void mg_tls_hexdump(const char *msg, uint8_t *buf, size_t bufsz) {
  8596. MG_VERBOSE(("%s: %M", msg, mg_print_hex, bufsz, buf));
  8597. }
  8598. // helper utilities to parse ASN.1 DER
  8599. struct mg_der_tlv {
  8600. uint8_t type;
  8601. uint32_t len;
  8602. uint8_t *value;
  8603. };
  8604. // parse DER into a TLV record
  8605. static int mg_der_to_tlv(uint8_t *der, size_t dersz, struct mg_der_tlv *tlv) {
  8606. if (dersz < 2) {
  8607. return -1;
  8608. }
  8609. tlv->type = der[0];
  8610. tlv->len = der[1];
  8611. tlv->value = der + 2;
  8612. if (tlv->len > 0x7f) {
  8613. uint32_t i, n = tlv->len - 0x80;
  8614. tlv->len = 0;
  8615. for (i = 0; i < n; i++) {
  8616. tlv->len = (tlv->len << 8) | (der[2 + i]);
  8617. }
  8618. tlv->value = der + 2 + n;
  8619. }
  8620. if (der + dersz < tlv->value + tlv->len) {
  8621. return -1;
  8622. }
  8623. return 0;
  8624. }
  8625. static int mg_der_find(uint8_t *der, size_t dersz, uint8_t *oid, size_t oidsz,
  8626. struct mg_der_tlv *tlv) {
  8627. uint8_t *p, *end;
  8628. struct mg_der_tlv child = {0, 0, NULL};
  8629. if (mg_der_to_tlv(der, dersz, tlv) < 0) {
  8630. return -1; // invalid DER
  8631. } else if (tlv->type == 6) { // found OID, check value
  8632. return (tlv->len == oidsz && memcmp(tlv->value, oid, oidsz) == 0);
  8633. } else if ((tlv->type & 0x20) == 0) {
  8634. return 0; // Primitive, but not OID: not found
  8635. }
  8636. // Constructed object: scan children
  8637. p = tlv->value;
  8638. end = tlv->value + tlv->len;
  8639. while (end > p) {
  8640. int r;
  8641. mg_der_to_tlv(p, (size_t) (end - p), &child);
  8642. r = mg_der_find(p, (size_t) (end - p), oid, oidsz, tlv);
  8643. if (r < 0) return -1; // error
  8644. if (r > 0) return 1; // found OID!
  8645. p = child.value + child.len;
  8646. }
  8647. return 0; // not found
  8648. }
  8649. // Did we receive a full TLS record in the c->rtls buffer?
  8650. static bool mg_tls_got_record(struct mg_connection *c) {
  8651. return c->rtls.len >= (size_t) TLS_RECHDR_SIZE &&
  8652. c->rtls.len >=
  8653. (size_t) (TLS_RECHDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
  8654. }
  8655. // Remove a single TLS record from the recv buffer
  8656. static void mg_tls_drop_record(struct mg_connection *c) {
  8657. struct mg_iobuf *rio = &c->rtls;
  8658. uint16_t n = MG_LOAD_BE16(rio->buf + 3) + TLS_RECHDR_SIZE;
  8659. mg_iobuf_del(rio, 0, n);
  8660. }
  8661. // Remove a single TLS message from decrypted buffer, remove the wrapping
  8662. // record if it was the last message within a record
  8663. static void mg_tls_drop_message(struct mg_connection *c) {
  8664. uint32_t len;
  8665. struct tls_data *tls = (struct tls_data *) c->tls;
  8666. if (tls->recv.len == 0) {
  8667. return;
  8668. }
  8669. len = MG_LOAD_BE24(tls->recv.buf + 1);
  8670. mg_sha256_update(&tls->sha256, tls->recv.buf, len + TLS_MSGHDR_SIZE);
  8671. tls->recv.buf += len + TLS_MSGHDR_SIZE;
  8672. tls->recv.len -= len + TLS_MSGHDR_SIZE;
  8673. if (tls->recv.len == 0) {
  8674. mg_tls_drop_record(c);
  8675. }
  8676. }
  8677. // TLS1.3 secret derivation based on the key label
  8678. static void mg_tls_derive_secret(const char *label, uint8_t *key, size_t keysz,
  8679. uint8_t *data, size_t datasz, uint8_t *hash,
  8680. size_t hashsz) {
  8681. size_t labelsz = strlen(label);
  8682. uint8_t secret[32];
  8683. uint8_t packed[256] = {0, (uint8_t) hashsz, (uint8_t) labelsz};
  8684. // TODO: assert lengths of label, key, data and hash
  8685. if (labelsz > 0) memmove(packed + 3, label, labelsz);
  8686. packed[3 + labelsz] = (uint8_t) datasz;
  8687. if (datasz > 0) memmove(packed + labelsz + 4, data, datasz);
  8688. packed[4 + labelsz + datasz] = 1;
  8689. mg_hmac_sha256(secret, key, keysz, packed, 5 + labelsz + datasz);
  8690. memmove(hash, secret, hashsz);
  8691. }
  8692. // at this point we have x25519 shared secret, we can generate a set of derived
  8693. // handshake encryption keys
  8694. static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
  8695. struct tls_data *tls = (struct tls_data *) c->tls;
  8696. mg_sha256_ctx sha256;
  8697. uint8_t early_secret[32];
  8698. uint8_t pre_extract_secret[32];
  8699. uint8_t hello_hash[32];
  8700. uint8_t server_hs_secret[32];
  8701. uint8_t client_hs_secret[32];
  8702. mg_hmac_sha256(early_secret, NULL, 0, zeros, sizeof(zeros));
  8703. mg_tls_derive_secret("tls13 derived", early_secret, 32, zeros_sha256_digest,
  8704. 32, pre_extract_secret, 32);
  8705. mg_hmac_sha256(tls->handshake_secret, pre_extract_secret,
  8706. sizeof(pre_extract_secret), tls->x25519_sec,
  8707. sizeof(tls->x25519_sec));
  8708. mg_tls_hexdump("hs secret", tls->handshake_secret, 32);
  8709. // mg_sha256_final is not idempotent, need to copy sha256 context to calculate
  8710. // the digest
  8711. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8712. mg_sha256_final(hello_hash, &sha256);
  8713. mg_tls_hexdump("hello hash", hello_hash, 32);
  8714. // derive keys needed for the rest of the handshake
  8715. mg_tls_derive_secret("tls13 s hs traffic", tls->handshake_secret, 32,
  8716. hello_hash, 32, server_hs_secret, 32);
  8717. mg_tls_derive_secret("tls13 key", server_hs_secret, 32, NULL, 0,
  8718. tls->server_write_key, 16);
  8719. mg_tls_derive_secret("tls13 iv", server_hs_secret, 32, NULL, 0,
  8720. tls->server_write_iv, 12);
  8721. mg_tls_derive_secret("tls13 finished", server_hs_secret, 32, NULL, 0,
  8722. tls->server_finished_key, 32);
  8723. mg_tls_derive_secret("tls13 c hs traffic", tls->handshake_secret, 32,
  8724. hello_hash, 32, client_hs_secret, 32);
  8725. mg_tls_derive_secret("tls13 key", client_hs_secret, 32, NULL, 0,
  8726. tls->client_write_key, 16);
  8727. mg_tls_derive_secret("tls13 iv", client_hs_secret, 32, NULL, 0,
  8728. tls->client_write_iv, 12);
  8729. mg_tls_derive_secret("tls13 finished", client_hs_secret, 32, NULL, 0,
  8730. tls->client_finished_key, 32);
  8731. mg_tls_hexdump("s hs traffic", server_hs_secret, 32);
  8732. mg_tls_hexdump("s key", tls->server_write_key, 16);
  8733. mg_tls_hexdump("s iv", tls->server_write_iv, 12);
  8734. mg_tls_hexdump("s finished", tls->server_finished_key, 32);
  8735. mg_tls_hexdump("c hs traffic", client_hs_secret, 32);
  8736. mg_tls_hexdump("c key", tls->client_write_key, 16);
  8737. mg_tls_hexdump("c iv", tls->client_write_iv, 16);
  8738. mg_tls_hexdump("c finished", tls->client_finished_key, 32);
  8739. mg_ssl_key_log("SERVER_HANDSHAKE_TRAFFIC_SECRET", tls->random,
  8740. server_hs_secret, 32);
  8741. mg_ssl_key_log("CLIENT_HANDSHAKE_TRAFFIC_SECRET", tls->random,
  8742. client_hs_secret, 32);
  8743. }
  8744. static void mg_tls_generate_application_keys(struct mg_connection *c) {
  8745. struct tls_data *tls = (struct tls_data *) c->tls;
  8746. uint8_t hash[32];
  8747. uint8_t premaster_secret[32];
  8748. uint8_t master_secret[32];
  8749. uint8_t server_secret[32];
  8750. uint8_t client_secret[32];
  8751. mg_sha256_ctx sha256;
  8752. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8753. mg_sha256_final(hash, &sha256);
  8754. mg_tls_derive_secret("tls13 derived", tls->handshake_secret, 32,
  8755. zeros_sha256_digest, 32, premaster_secret, 32);
  8756. mg_hmac_sha256(master_secret, premaster_secret, 32, zeros, 32);
  8757. mg_tls_derive_secret("tls13 s ap traffic", master_secret, 32, hash, 32,
  8758. server_secret, 32);
  8759. mg_tls_derive_secret("tls13 key", server_secret, 32, NULL, 0,
  8760. tls->server_write_key, 16);
  8761. mg_tls_derive_secret("tls13 iv", server_secret, 32, NULL, 0,
  8762. tls->server_write_iv, 12);
  8763. mg_tls_derive_secret("tls13 c ap traffic", master_secret, 32, hash, 32,
  8764. client_secret, 32);
  8765. mg_tls_derive_secret("tls13 key", client_secret, 32, NULL, 0,
  8766. tls->client_write_key, 16);
  8767. mg_tls_derive_secret("tls13 iv", client_secret, 32, NULL, 0,
  8768. tls->client_write_iv, 12);
  8769. mg_tls_hexdump("s ap traffic", server_secret, 32);
  8770. mg_tls_hexdump("s key", tls->server_write_key, 16);
  8771. mg_tls_hexdump("s iv", tls->server_write_iv, 12);
  8772. mg_tls_hexdump("s finished", tls->server_finished_key, 32);
  8773. mg_tls_hexdump("c ap traffic", client_secret, 32);
  8774. mg_tls_hexdump("c key", tls->client_write_key, 16);
  8775. mg_tls_hexdump("c iv", tls->client_write_iv, 16);
  8776. mg_tls_hexdump("c finished", tls->client_finished_key, 32);
  8777. tls->sseq = tls->cseq = 0;
  8778. mg_ssl_key_log("SERVER_TRAFFIC_SECRET_0", tls->random, server_secret, 32);
  8779. mg_ssl_key_log("CLIENT_TRAFFIC_SECRET_0", tls->random, client_secret, 32);
  8780. }
  8781. // AES GCM encryption of the message + put encoded data into the write buffer
  8782. static void mg_tls_encrypt(struct mg_connection *c, const uint8_t *msg,
  8783. size_t msgsz, uint8_t msgtype) {
  8784. struct tls_data *tls = (struct tls_data *) c->tls;
  8785. struct mg_iobuf *wio = &tls->send;
  8786. uint8_t *outmsg;
  8787. uint8_t *tag;
  8788. size_t encsz = msgsz + 16 + 1;
  8789. uint8_t hdr[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
  8790. (uint8_t) ((encsz >> 8) & 0xff), (uint8_t) (encsz & 0xff)};
  8791. uint8_t associated_data[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
  8792. (uint8_t) ((encsz >> 8) & 0xff),
  8793. (uint8_t) (encsz & 0xff)};
  8794. uint8_t nonce[12];
  8795. mg_gcm_initialize();
  8796. if (c->is_client) {
  8797. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  8798. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  8799. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  8800. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  8801. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  8802. } else {
  8803. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8804. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8805. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8806. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8807. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8808. }
  8809. mg_iobuf_add(wio, wio->len, hdr, sizeof(hdr));
  8810. mg_iobuf_resize(wio, wio->len + encsz);
  8811. outmsg = wio->buf + wio->len;
  8812. tag = wio->buf + wio->len + msgsz + 1;
  8813. memmove(outmsg, msg, msgsz);
  8814. outmsg[msgsz] = msgtype;
  8815. if (c->is_client) {
  8816. mg_aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->client_write_key,
  8817. sizeof(tls->client_write_key), nonce, sizeof(nonce),
  8818. associated_data, sizeof(associated_data), tag, 16);
  8819. tls->cseq++;
  8820. } else {
  8821. mg_aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->server_write_key,
  8822. sizeof(tls->server_write_key), nonce, sizeof(nonce),
  8823. associated_data, sizeof(associated_data), tag, 16);
  8824. tls->sseq++;
  8825. }
  8826. wio->len += encsz;
  8827. }
  8828. // read an encrypted record, decrypt it in place
  8829. static int mg_tls_recv_record(struct mg_connection *c) {
  8830. struct tls_data *tls = (struct tls_data *) c->tls;
  8831. struct mg_iobuf *rio = &c->rtls;
  8832. uint16_t msgsz;
  8833. uint8_t *msg;
  8834. uint8_t nonce[12];
  8835. int r;
  8836. if (tls->recv.len > 0) {
  8837. return 0; /* some data from previous record is still present */
  8838. }
  8839. for (;;) {
  8840. if (!mg_tls_got_record(c)) {
  8841. return MG_IO_WAIT;
  8842. }
  8843. if (rio->buf[0] == MG_TLS_APP_DATA) {
  8844. break;
  8845. } else if (rio->buf[0] ==
  8846. MG_TLS_CHANGE_CIPHER) { // Skip ChangeCipher messages
  8847. mg_tls_drop_record(c);
  8848. } else if (rio->buf[0] == MG_TLS_ALERT) { // Skip Alerts
  8849. MG_INFO(("TLS ALERT packet received"));
  8850. mg_tls_drop_record(c);
  8851. } else {
  8852. mg_error(c, "unexpected packet");
  8853. return -1;
  8854. }
  8855. }
  8856. mg_gcm_initialize();
  8857. msgsz = MG_LOAD_BE16(rio->buf + 3);
  8858. msg = rio->buf + 5;
  8859. if (c->is_client) {
  8860. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8861. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8862. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8863. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8864. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8865. mg_aes_gcm_decrypt(msg, msg, msgsz - 16, tls->server_write_key,
  8866. sizeof(tls->server_write_key), nonce, sizeof(nonce));
  8867. tls->sseq++;
  8868. } else {
  8869. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  8870. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  8871. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  8872. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  8873. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  8874. mg_aes_gcm_decrypt(msg, msg, msgsz - 16, tls->client_write_key,
  8875. sizeof(tls->client_write_key), nonce, sizeof(nonce));
  8876. tls->cseq++;
  8877. }
  8878. r = msgsz - 16 - 1;
  8879. tls->content_type = msg[msgsz - 16 - 1];
  8880. tls->recv.buf = msg;
  8881. tls->recv.size = tls->recv.len = msgsz - 16 - 1;
  8882. return r;
  8883. }
  8884. static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
  8885. uint8_t hash[32]) {
  8886. struct tls_data *tls = (struct tls_data *) c->tls;
  8887. uint8_t sig_content[130] = {
  8888. " "
  8889. " "
  8890. "TLS 1.3, server CertificateVerify\0"};
  8891. mg_sha256_ctx sha256;
  8892. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8893. mg_sha256_final(sig_content + 98, &sha256);
  8894. mg_sha256_init(&sha256);
  8895. mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
  8896. mg_sha256_final(hash, &sha256);
  8897. }
  8898. // read and parse ClientHello record
  8899. static int mg_tls_server_recv_hello(struct mg_connection *c) {
  8900. struct tls_data *tls = (struct tls_data *) c->tls;
  8901. struct mg_iobuf *rio = &c->rtls;
  8902. uint8_t session_id_len;
  8903. uint16_t j;
  8904. uint16_t cipher_suites_len;
  8905. uint16_t ext_len;
  8906. uint8_t *ext;
  8907. uint16_t msgsz;
  8908. if (!mg_tls_got_record(c)) {
  8909. return MG_IO_WAIT;
  8910. }
  8911. if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_CLIENT_HELLO) {
  8912. mg_error(c, "not a client hello packet");
  8913. return -1;
  8914. }
  8915. msgsz = MG_LOAD_BE16(rio->buf + 3);
  8916. mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
  8917. // store client random
  8918. memmove(tls->random, rio->buf + 11, sizeof(tls->random));
  8919. // store session_id
  8920. session_id_len = rio->buf[43];
  8921. if (session_id_len == sizeof(tls->session_id)) {
  8922. memmove(tls->session_id, rio->buf + 44, session_id_len);
  8923. } else if (session_id_len != 0) {
  8924. MG_INFO(("bad session id len"));
  8925. }
  8926. cipher_suites_len = MG_LOAD_BE16(rio->buf + 44 + session_id_len);
  8927. ext_len = MG_LOAD_BE16(rio->buf + 48 + session_id_len + cipher_suites_len);
  8928. ext = rio->buf + 50 + session_id_len + cipher_suites_len;
  8929. for (j = 0; j < ext_len;) {
  8930. uint16_t k;
  8931. uint16_t key_exchange_len;
  8932. uint8_t *key_exchange;
  8933. uint16_t n = MG_LOAD_BE16(ext + j + 2);
  8934. if (ext[j] != 0x00 ||
  8935. ext[j + 1] != 0x33) { // not a key share extension, ignore
  8936. j += (uint16_t) (n + 4);
  8937. continue;
  8938. }
  8939. key_exchange_len = MG_LOAD_BE16(ext + j + 5);
  8940. key_exchange = ext + j + 6;
  8941. for (k = 0; k < key_exchange_len;) {
  8942. uint16_t m = MG_LOAD_BE16(key_exchange + k + 2);
  8943. if (m == 32 && key_exchange[k] == 0x00 && key_exchange[k + 1] == 0x1d) {
  8944. memmove(tls->x25519_cli, key_exchange + k + 4, m);
  8945. mg_tls_drop_record(c);
  8946. return 0;
  8947. }
  8948. k += (uint16_t) (m + 4);
  8949. }
  8950. j += (uint16_t) (n + 4);
  8951. }
  8952. mg_error(c, "bad client hello");
  8953. return -1;
  8954. }
  8955. #define PLACEHOLDER_8B 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'
  8956. #define PLACEHOLDER_16B PLACEHOLDER_8B, PLACEHOLDER_8B
  8957. #define PLACEHOLDER_32B PLACEHOLDER_16B, PLACEHOLDER_16B
  8958. // put ServerHello record into wio buffer
  8959. static void mg_tls_server_send_hello(struct mg_connection *c) {
  8960. struct tls_data *tls = (struct tls_data *) c->tls;
  8961. struct mg_iobuf *wio = &tls->send;
  8962. uint8_t msg_server_hello[122] = {
  8963. // server hello, tls 1.2
  8964. 0x02,
  8965. 0x00,
  8966. 0x00,
  8967. 0x76,
  8968. 0x03,
  8969. 0x03,
  8970. // random (32 bytes)
  8971. PLACEHOLDER_32B,
  8972. // session ID length + session ID (32 bytes)
  8973. 0x20,
  8974. PLACEHOLDER_32B,
  8975. #if defined(CHACHA20) && CHACHA20
  8976. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  8977. 0x13,
  8978. 0x03,
  8979. 0x00,
  8980. #else
  8981. // TLS_AES_128_GCM_SHA256 + no compression
  8982. 0x13,
  8983. 0x01,
  8984. 0x00,
  8985. #endif
  8986. // extensions + keyshare
  8987. 0x00,
  8988. 0x2e,
  8989. 0x00,
  8990. 0x33,
  8991. 0x00,
  8992. 0x24,
  8993. 0x00,
  8994. 0x1d,
  8995. 0x00,
  8996. 0x20,
  8997. // x25519 keyshare
  8998. PLACEHOLDER_32B,
  8999. // supported versions (tls1.3 == 0x304)
  9000. 0x00,
  9001. 0x2b,
  9002. 0x00,
  9003. 0x02,
  9004. 0x03,
  9005. 0x04
  9006. };
  9007. // calculate keyshare
  9008. uint8_t x25519_pub[X25519_BYTES];
  9009. uint8_t x25519_prv[X25519_BYTES];
  9010. mg_random(x25519_prv, sizeof(x25519_prv));
  9011. mg_tls_x25519(x25519_pub, x25519_prv, X25519_BASE_POINT, 1);
  9012. mg_tls_x25519(tls->x25519_sec, x25519_prv, tls->x25519_cli, 1);
  9013. mg_tls_hexdump("s x25519 sec", tls->x25519_sec, sizeof(tls->x25519_sec));
  9014. // fill in the gaps: random + session ID + keyshare
  9015. memmove(msg_server_hello + 6, tls->random, sizeof(tls->random));
  9016. memmove(msg_server_hello + 39, tls->session_id, sizeof(tls->session_id));
  9017. memmove(msg_server_hello + 84, x25519_pub, sizeof(x25519_pub));
  9018. // server hello message
  9019. mg_iobuf_add(wio, wio->len, "\x16\x03\x03\x00\x7a", 5);
  9020. mg_iobuf_add(wio, wio->len, msg_server_hello, sizeof(msg_server_hello));
  9021. mg_sha256_update(&tls->sha256, msg_server_hello, sizeof(msg_server_hello));
  9022. // change cipher message
  9023. mg_iobuf_add(wio, wio->len, "\x14\x03\x03\x00\x01\x01", 6);
  9024. }
  9025. static void mg_tls_server_send_ext(struct mg_connection *c) {
  9026. struct tls_data *tls = (struct tls_data *) c->tls;
  9027. // server extensions
  9028. uint8_t ext[6] = {0x08, 0, 0, 2, 0, 0};
  9029. mg_sha256_update(&tls->sha256, ext, sizeof(ext));
  9030. mg_tls_encrypt(c, ext, sizeof(ext), MG_TLS_HANDSHAKE);
  9031. }
  9032. static void mg_tls_server_send_cert(struct mg_connection *c) {
  9033. struct tls_data *tls = (struct tls_data *) c->tls;
  9034. // server DER certificate (empty)
  9035. size_t n = tls->server_cert_der.len;
  9036. uint8_t *cert = (uint8_t *) calloc(1, 13 + n);
  9037. if (cert == NULL) {
  9038. mg_error(c, "tls cert oom");
  9039. return;
  9040. }
  9041. cert[0] = 0x0b; // handshake header
  9042. cert[1] = (uint8_t) (((n + 9) >> 16) & 255U); // 3 bytes: payload length
  9043. cert[2] = (uint8_t) (((n + 9) >> 8) & 255U);
  9044. cert[3] = (uint8_t) ((n + 9) & 255U);
  9045. cert[4] = 0; // request context
  9046. cert[5] = (uint8_t) (((n + 5) >> 16) & 255U); // 3 bytes: cert (s) length
  9047. cert[6] = (uint8_t) (((n + 5) >> 8) & 255U);
  9048. cert[7] = (uint8_t) ((n + 5) & 255U);
  9049. cert[8] =
  9050. (uint8_t) (((n) >> 16) & 255U); // 3 bytes: first (and only) cert len
  9051. cert[9] = (uint8_t) (((n) >> 8) & 255U);
  9052. cert[10] = (uint8_t) (n & 255U);
  9053. // bytes 11+ are certificate in DER format
  9054. memmove(cert + 11, tls->server_cert_der.buf, n);
  9055. cert[11 + n] = cert[12 + n] = 0; // certificate extensions (none)
  9056. mg_sha256_update(&tls->sha256, cert, 13 + n);
  9057. mg_tls_encrypt(c, cert, 13 + n, MG_TLS_HANDSHAKE);
  9058. free(cert);
  9059. }
  9060. // type adapter between uECC hash context and our sha256 implementation
  9061. typedef struct SHA256_HashContext {
  9062. MG_UECC_HashContext uECC;
  9063. mg_sha256_ctx ctx;
  9064. } SHA256_HashContext;
  9065. static void init_SHA256(const MG_UECC_HashContext *base) {
  9066. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9067. mg_sha256_init(&c->ctx);
  9068. }
  9069. static void update_SHA256(const MG_UECC_HashContext *base,
  9070. const uint8_t *message, unsigned message_size) {
  9071. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9072. mg_sha256_update(&c->ctx, message, message_size);
  9073. }
  9074. static void finish_SHA256(const MG_UECC_HashContext *base,
  9075. uint8_t *hash_result) {
  9076. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9077. mg_sha256_final(hash_result, &c->ctx);
  9078. }
  9079. static void mg_tls_server_send_cert_verify(struct mg_connection *c) {
  9080. struct tls_data *tls = (struct tls_data *) c->tls;
  9081. // server certificate verify packet
  9082. uint8_t verify[82] = {0x0f, 0x00, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00};
  9083. size_t sigsz, verifysz = 0;
  9084. uint8_t hash[32] = {0}, tmp[2 * 32 + 64] = {0};
  9085. struct SHA256_HashContext ctx = {
  9086. {&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp},
  9087. {{0}, 0, 0, {0}}};
  9088. int neg1, neg2;
  9089. uint8_t sig[64] = {0};
  9090. mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash);
  9091. mg_uecc_sign_deterministic(tls->server_key, hash, sizeof(hash), &ctx.uECC,
  9092. sig, mg_uecc_secp256r1());
  9093. neg1 = !!(sig[0] & 0x80);
  9094. neg2 = !!(sig[32] & 0x80);
  9095. verify[8] = 0x30; // ASN.1 SEQUENCE
  9096. verify[9] = (uint8_t) (68 + neg1 + neg2);
  9097. verify[10] = 0x02; // ASN.1 INTEGER
  9098. verify[11] = (uint8_t) (32 + neg1);
  9099. memmove(verify + 12 + neg1, sig, 32);
  9100. verify[12 + 32 + neg1] = 0x02; // ASN.1 INTEGER
  9101. verify[13 + 32 + neg1] = (uint8_t) (32 + neg2);
  9102. memmove(verify + 14 + 32 + neg1 + neg2, sig + 32, 32);
  9103. sigsz = (size_t) (70 + neg1 + neg2);
  9104. verifysz = 8U + sigsz;
  9105. verify[3] = (uint8_t) (sigsz + 4);
  9106. verify[7] = (uint8_t) sigsz;
  9107. mg_sha256_update(&tls->sha256, verify, verifysz);
  9108. mg_tls_encrypt(c, verify, verifysz, MG_TLS_HANDSHAKE);
  9109. }
  9110. static void mg_tls_server_send_finish(struct mg_connection *c) {
  9111. struct tls_data *tls = (struct tls_data *) c->tls;
  9112. struct mg_iobuf *wio = &tls->send;
  9113. mg_sha256_ctx sha256;
  9114. uint8_t hash[32];
  9115. uint8_t finish[36] = {0x14, 0, 0, 32};
  9116. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9117. mg_sha256_final(hash, &sha256);
  9118. mg_hmac_sha256(finish + 4, tls->server_finished_key, 32, hash, 32);
  9119. mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
  9120. mg_io_send(c, wio->buf, wio->len);
  9121. wio->len = 0;
  9122. mg_sha256_update(&tls->sha256, finish, sizeof(finish));
  9123. }
  9124. static int mg_tls_server_recv_finish(struct mg_connection *c) {
  9125. struct tls_data *tls = (struct tls_data *) c->tls;
  9126. // we have to backup sha256 value to restore it later, since Finished record
  9127. // is exceptional and is not supposed to be added to the rolling hash
  9128. // calculation.
  9129. mg_sha256_ctx sha256 = tls->sha256;
  9130. if (mg_tls_recv_record(c) < 0) {
  9131. return -1;
  9132. }
  9133. if (tls->recv.buf[0] != MG_TLS_FINISHED) {
  9134. mg_error(c, "expected Finish but got msg 0x%02x", tls->recv.buf[0]);
  9135. return -1;
  9136. }
  9137. mg_tls_drop_message(c);
  9138. // restore hash
  9139. tls->sha256 = sha256;
  9140. return 0;
  9141. }
  9142. static void mg_tls_client_send_hello(struct mg_connection *c) {
  9143. struct tls_data *tls = (struct tls_data *) c->tls;
  9144. struct mg_iobuf *wio = &tls->send;
  9145. const char *hostname = tls->hostname;
  9146. size_t hostnamesz = strlen(tls->hostname);
  9147. uint8_t x25519_pub[X25519_BYTES];
  9148. uint8_t msg_client_hello[162 + 32] = {
  9149. // TLS Client Hello header reported as TLS1.2 (5)
  9150. 0x16,
  9151. 0x03,
  9152. 0x01,
  9153. 0x00,
  9154. 0xfe,
  9155. // server hello, tls 1.2 (6)
  9156. 0x01,
  9157. 0x00,
  9158. 0x00,
  9159. 0x8c,
  9160. 0x03,
  9161. 0x03,
  9162. // random (32 bytes)
  9163. PLACEHOLDER_32B,
  9164. // session ID length + session ID (32 bytes)
  9165. 0x20,
  9166. PLACEHOLDER_32B,
  9167. #if defined(CHACHA20) && CHACHA20
  9168. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  9169. 0x13,
  9170. 0x03,
  9171. 0x00,
  9172. #else
  9173. 0x00,
  9174. 0x02, // size = 2 bytes
  9175. 0x13,
  9176. 0x01, // TLS_AES_128_GCM_SHA256
  9177. 0x01,
  9178. 0x00, // no compression
  9179. #endif
  9180. // extensions + keyshare
  9181. 0x00,
  9182. 0xfe,
  9183. // x25519 keyshare
  9184. 0x00,
  9185. 0x33,
  9186. 0x00,
  9187. 0x26,
  9188. 0x00,
  9189. 0x24,
  9190. 0x00,
  9191. 0x1d,
  9192. 0x00,
  9193. 0x20,
  9194. PLACEHOLDER_32B,
  9195. // supported groups (x25519)
  9196. 0x00,
  9197. 0x0a,
  9198. 0x00,
  9199. 0x04,
  9200. 0x00,
  9201. 0x02,
  9202. 0x00,
  9203. 0x1d,
  9204. // supported versions (tls1.3 == 0x304)
  9205. 0x00,
  9206. 0x2b,
  9207. 0x00,
  9208. 0x03,
  9209. 0x02,
  9210. 0x03,
  9211. 0x04,
  9212. // session ticket (none)
  9213. 0x00,
  9214. 0x23,
  9215. 0x00,
  9216. 0x00,
  9217. // signature algorithms (we don't care, so list all the common ones)
  9218. 0x00,
  9219. 0x0d,
  9220. 0x00,
  9221. 0x24,
  9222. 0x00,
  9223. 0x22,
  9224. 0x04,
  9225. 0x03,
  9226. 0x05,
  9227. 0x03,
  9228. 0x06,
  9229. 0x03,
  9230. 0x08,
  9231. 0x07,
  9232. 0x08,
  9233. 0x08,
  9234. 0x08,
  9235. 0x1a,
  9236. 0x08,
  9237. 0x1b,
  9238. 0x08,
  9239. 0x1c,
  9240. 0x08,
  9241. 0x09,
  9242. 0x08,
  9243. 0x0a,
  9244. 0x08,
  9245. 0x0b,
  9246. 0x08,
  9247. 0x04,
  9248. 0x08,
  9249. 0x05,
  9250. 0x08,
  9251. 0x06,
  9252. 0x04,
  9253. 0x01,
  9254. 0x05,
  9255. 0x01,
  9256. 0x06,
  9257. 0x01,
  9258. // server name
  9259. 0x00,
  9260. 0x00,
  9261. 0x00,
  9262. 0xfe,
  9263. 0x00,
  9264. 0xfe,
  9265. 0x00,
  9266. 0x00,
  9267. 0xfe
  9268. };
  9269. // patch ClientHello with correct hostname length + offset:
  9270. MG_STORE_BE16(msg_client_hello + 3, hostnamesz + 189);
  9271. MG_STORE_BE16(msg_client_hello + 7, hostnamesz + 185);
  9272. MG_STORE_BE16(msg_client_hello + 82, hostnamesz + 110);
  9273. MG_STORE_BE16(msg_client_hello + 187, hostnamesz + 5);
  9274. MG_STORE_BE16(msg_client_hello + 189, hostnamesz + 3);
  9275. MG_STORE_BE16(msg_client_hello + 192, hostnamesz);
  9276. // calculate keyshare
  9277. mg_random(tls->x25519_cli, sizeof(tls->x25519_cli));
  9278. mg_tls_x25519(x25519_pub, tls->x25519_cli, X25519_BASE_POINT, 1);
  9279. // fill in the gaps: random + session ID + keyshare
  9280. mg_random(tls->session_id, sizeof(tls->session_id));
  9281. mg_random(tls->random, sizeof(tls->random));
  9282. memmove(msg_client_hello + 11, tls->random, sizeof(tls->random));
  9283. memmove(msg_client_hello + 44, tls->session_id, sizeof(tls->session_id));
  9284. memmove(msg_client_hello + 94, x25519_pub, sizeof(x25519_pub));
  9285. // server hello message
  9286. mg_iobuf_add(wio, wio->len, msg_client_hello, sizeof(msg_client_hello));
  9287. mg_iobuf_add(wio, wio->len, hostname, strlen(hostname));
  9288. mg_sha256_update(&tls->sha256, msg_client_hello + 5,
  9289. sizeof(msg_client_hello) - 5);
  9290. mg_sha256_update(&tls->sha256, (uint8_t *) hostname, strlen(hostname));
  9291. // change cipher message
  9292. mg_iobuf_add(wio, wio->len, (const char *) "\x14\x03\x03\x00\x01\x01", 6);
  9293. mg_io_send(c, wio->buf, wio->len);
  9294. wio->len = 0;
  9295. }
  9296. static int mg_tls_client_recv_hello(struct mg_connection *c) {
  9297. struct tls_data *tls = (struct tls_data *) c->tls;
  9298. struct mg_iobuf *rio = &c->rtls;
  9299. uint16_t msgsz;
  9300. uint8_t *ext;
  9301. uint16_t ext_len;
  9302. int j;
  9303. if (!mg_tls_got_record(c)) {
  9304. return MG_IO_WAIT;
  9305. }
  9306. if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_SERVER_HELLO) {
  9307. if (rio->buf[0] == MG_TLS_ALERT && rio->len >= 7) {
  9308. mg_error(c, "tls alert %d", rio->buf[6]);
  9309. return -1;
  9310. }
  9311. MG_INFO(("got packet type 0x%02x/0x%02x", rio->buf[0], rio->buf[5]));
  9312. mg_error(c, "not a server hello packet");
  9313. return -1;
  9314. }
  9315. msgsz = MG_LOAD_BE16(rio->buf + 3);
  9316. mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
  9317. ext_len = MG_LOAD_BE16(rio->buf + 5 + 39 + 32 + 3);
  9318. ext = rio->buf + 5 + 39 + 32 + 3 + 2;
  9319. for (j = 0; j < ext_len;) {
  9320. uint16_t ext_type = MG_LOAD_BE16(ext + j);
  9321. uint16_t ext_len2 = MG_LOAD_BE16(ext + j + 2);
  9322. uint16_t group;
  9323. uint8_t *key_exchange;
  9324. uint16_t key_exchange_len;
  9325. if (ext_type != 0x0033) { // not a key share extension, ignore
  9326. j += (uint16_t) (ext_len2 + 4);
  9327. continue;
  9328. }
  9329. group = MG_LOAD_BE16(ext + j + 4);
  9330. if (group != 0x001d) {
  9331. mg_error(c, "bad key exchange group");
  9332. return -1;
  9333. }
  9334. key_exchange_len = MG_LOAD_BE16(ext + j + 6);
  9335. key_exchange = ext + j + 8;
  9336. if (key_exchange_len != 32) {
  9337. mg_error(c, "bad key exchange length");
  9338. return -1;
  9339. }
  9340. mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1);
  9341. mg_tls_hexdump("c x25519 sec", tls->x25519_sec, 32);
  9342. mg_tls_drop_record(c);
  9343. /* generate handshake keys */
  9344. mg_tls_generate_handshake_keys(c);
  9345. return 0;
  9346. }
  9347. mg_error(c, "bad client hello");
  9348. return -1;
  9349. }
  9350. static int mg_tls_client_recv_ext(struct mg_connection *c) {
  9351. struct tls_data *tls = (struct tls_data *) c->tls;
  9352. if (mg_tls_recv_record(c) < 0) {
  9353. return -1;
  9354. }
  9355. if (tls->recv.buf[0] != MG_TLS_ENCRYPTED_EXTENSIONS) {
  9356. mg_error(c, "expected server extensions but got msg 0x%02x",
  9357. tls->recv.buf[0]);
  9358. return -1;
  9359. }
  9360. mg_tls_drop_message(c);
  9361. return 0;
  9362. }
  9363. static int mg_tls_client_recv_cert(struct mg_connection *c) {
  9364. uint8_t *cert;
  9365. uint32_t certsz;
  9366. struct mg_der_tlv oid, pubkey, seq, subj;
  9367. int subj_match = 0;
  9368. struct tls_data *tls = (struct tls_data *) c->tls;
  9369. if (mg_tls_recv_record(c) < 0) {
  9370. return -1;
  9371. }
  9372. if (tls->recv.buf[0] != MG_TLS_CERTIFICATE) {
  9373. mg_error(c, "expected server certificate but got msg 0x%02x",
  9374. tls->recv.buf[0]);
  9375. return -1;
  9376. }
  9377. if (tls->skip_verification) {
  9378. mg_tls_drop_message(c);
  9379. return 0;
  9380. }
  9381. if (tls->recv.len < 11) {
  9382. mg_error(c, "certificate list too short");
  9383. return -1;
  9384. }
  9385. cert = tls->recv.buf + 11;
  9386. certsz = MG_LOAD_BE24(tls->recv.buf + 8);
  9387. if (certsz > tls->recv.len - 11) {
  9388. mg_error(c, "certificate too long: %d vs %d", certsz, tls->recv.len - 11);
  9389. return -1;
  9390. }
  9391. do {
  9392. // secp256r1 public key
  9393. if (mg_der_find(cert, certsz,
  9394. (uint8_t *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8,
  9395. &oid) < 0) {
  9396. mg_error(c, "certificate secp256r1 public key OID not found");
  9397. return -1;
  9398. }
  9399. if (mg_der_to_tlv(oid.value + oid.len,
  9400. (size_t) (cert + certsz - (oid.value + oid.len)),
  9401. &pubkey) < 0) {
  9402. mg_error(c, "certificate secp256r1 public key not found");
  9403. return -1;
  9404. }
  9405. // expect BIT STRING, unpadded, uncompressed: [0]+[4]+32+32 content bytes
  9406. if (pubkey.type != 3 || pubkey.len != 66 || pubkey.value[0] != 0 ||
  9407. pubkey.value[1] != 4) {
  9408. mg_error(c, "unsupported public key bitstring encoding");
  9409. return -1;
  9410. }
  9411. memmove(tls->pubkey, pubkey.value + 2, pubkey.len - 2);
  9412. } while (0);
  9413. // Subject Alternative Names
  9414. do {
  9415. if (mg_der_find(cert, certsz, (uint8_t *) "\x55\x1d\x11", 3, &oid) < 0) {
  9416. mg_error(c, "certificate does not contain subject alternative names");
  9417. return -1;
  9418. }
  9419. if (mg_der_to_tlv(oid.value + oid.len,
  9420. (size_t) (cert + certsz - (oid.value + oid.len)),
  9421. &seq) < 0) {
  9422. mg_error(c, "certificate subject alternative names not found");
  9423. return -1;
  9424. }
  9425. if (mg_der_to_tlv(seq.value, seq.len, &seq) < 0) {
  9426. mg_error(
  9427. c,
  9428. "certificate subject alternative names is not a constructed object");
  9429. return -1;
  9430. }
  9431. MG_VERBOSE(("verify hostname %s", tls->hostname));
  9432. while (seq.len > 0) {
  9433. if (mg_der_to_tlv(seq.value, seq.len, &subj) < 0) {
  9434. mg_error(c, "bad subject alternative name");
  9435. return -1;
  9436. }
  9437. MG_VERBOSE(("subj=%.*s", subj.len, subj.value));
  9438. if (mg_match(mg_str((const char *) tls->hostname),
  9439. mg_str_n((const char *) subj.value, subj.len), NULL)) {
  9440. subj_match = 1;
  9441. break;
  9442. }
  9443. seq.len = (uint32_t) (seq.value + seq.len - (subj.value + subj.len));
  9444. seq.value = subj.value + subj.len;
  9445. }
  9446. if (!subj_match) {
  9447. mg_error(c, "certificate did not match the hostname");
  9448. return -1;
  9449. }
  9450. } while (0);
  9451. mg_tls_drop_message(c);
  9452. mg_tls_calc_cert_verify_hash(c, tls->sighash);
  9453. return 0;
  9454. }
  9455. static int mg_tls_client_recv_cert_verify(struct mg_connection *c) {
  9456. struct tls_data *tls = (struct tls_data *) c->tls;
  9457. if (mg_tls_recv_record(c) < 0) {
  9458. return -1;
  9459. }
  9460. if (tls->recv.buf[0] != MG_TLS_CERTIFICATE_VERIFY) {
  9461. mg_error(c, "expected server certificate verify but got msg 0x%02x",
  9462. tls->recv.buf[0]);
  9463. return -1;
  9464. }
  9465. // Ignore CertificateVerify is strict checks are not required
  9466. if (tls->skip_verification) {
  9467. mg_tls_drop_message(c);
  9468. return 0;
  9469. }
  9470. // Extract certificate signature and verify it using pubkey and sighash
  9471. do {
  9472. uint8_t sig[64];
  9473. struct mg_der_tlv seq, a, b;
  9474. if (mg_der_to_tlv(tls->recv.buf + 8, tls->recv.len - 8, &seq) < 0) {
  9475. mg_error(c, "verification message is not an ASN.1 DER sequence");
  9476. return -1;
  9477. }
  9478. if (mg_der_to_tlv(seq.value, seq.len, &a) < 0) {
  9479. mg_error(c, "missing first part of the signature");
  9480. return -1;
  9481. }
  9482. if (mg_der_to_tlv(a.value + a.len, seq.len - a.len, &b) < 0) {
  9483. mg_error(c, "missing second part of the signature");
  9484. return -1;
  9485. }
  9486. // Integers may be padded with zeroes
  9487. if (a.len > 32) {
  9488. a.value = a.value + (a.len - 32);
  9489. a.len = 32;
  9490. }
  9491. if (b.len > 32) {
  9492. b.value = b.value + (b.len - 32);
  9493. b.len = 32;
  9494. }
  9495. memmove(sig, a.value, a.len);
  9496. memmove(sig + 32, b.value, b.len);
  9497. if (mg_uecc_verify(tls->pubkey, tls->sighash, sizeof(tls->sighash), sig,
  9498. mg_uecc_secp256r1()) != 1) {
  9499. mg_error(c, "failed to verify certificate");
  9500. return -1;
  9501. }
  9502. } while (0);
  9503. mg_tls_drop_message(c);
  9504. return 0;
  9505. }
  9506. static int mg_tls_client_recv_finish(struct mg_connection *c) {
  9507. struct tls_data *tls = (struct tls_data *) c->tls;
  9508. if (mg_tls_recv_record(c) < 0) {
  9509. return -1;
  9510. }
  9511. if (tls->recv.buf[0] != MG_TLS_FINISHED) {
  9512. mg_error(c, "expected server finished but got msg 0x%02x",
  9513. tls->recv.buf[0]);
  9514. return -1;
  9515. }
  9516. mg_tls_drop_message(c);
  9517. return 0;
  9518. }
  9519. static void mg_tls_client_send_finish(struct mg_connection *c) {
  9520. struct tls_data *tls = (struct tls_data *) c->tls;
  9521. struct mg_iobuf *wio = &tls->send;
  9522. mg_sha256_ctx sha256;
  9523. uint8_t hash[32];
  9524. uint8_t finish[36] = {0x14, 0, 0, 32};
  9525. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9526. mg_sha256_final(hash, &sha256);
  9527. mg_hmac_sha256(finish + 4, tls->client_finished_key, 32, hash, 32);
  9528. mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
  9529. mg_io_send(c, wio->buf, wio->len);
  9530. wio->len = 0;
  9531. }
  9532. static void mg_tls_client_handshake(struct mg_connection *c) {
  9533. struct tls_data *tls = (struct tls_data *) c->tls;
  9534. switch (tls->state) {
  9535. case MG_TLS_STATE_CLIENT_START:
  9536. mg_tls_client_send_hello(c);
  9537. tls->state = MG_TLS_STATE_CLIENT_WAIT_SH;
  9538. // Fallthrough
  9539. case MG_TLS_STATE_CLIENT_WAIT_SH:
  9540. if (mg_tls_client_recv_hello(c) < 0) {
  9541. break;
  9542. }
  9543. tls->state = MG_TLS_STATE_CLIENT_WAIT_EE;
  9544. // Fallthrough
  9545. case MG_TLS_STATE_CLIENT_WAIT_EE:
  9546. if (mg_tls_client_recv_ext(c) < 0) {
  9547. break;
  9548. }
  9549. tls->state = MG_TLS_STATE_CLIENT_WAIT_CERT;
  9550. // Fallthrough
  9551. case MG_TLS_STATE_CLIENT_WAIT_CERT:
  9552. if (mg_tls_client_recv_cert(c) < 0) {
  9553. break;
  9554. }
  9555. tls->state = MG_TLS_STATE_CLIENT_WAIT_CV;
  9556. // Fallthrough
  9557. case MG_TLS_STATE_CLIENT_WAIT_CV:
  9558. if (mg_tls_client_recv_cert_verify(c) < 0) {
  9559. break;
  9560. }
  9561. tls->state = MG_TLS_STATE_CLIENT_WAIT_FINISHED;
  9562. // Fallthrough
  9563. case MG_TLS_STATE_CLIENT_WAIT_FINISHED:
  9564. if (mg_tls_client_recv_finish(c) < 0) {
  9565. break;
  9566. }
  9567. mg_tls_client_send_finish(c);
  9568. mg_tls_generate_application_keys(c);
  9569. tls->state = MG_TLS_STATE_CLIENT_CONNECTED;
  9570. c->is_tls_hs = 0;
  9571. break;
  9572. default: mg_error(c, "unexpected client state: %d", tls->state); break;
  9573. }
  9574. }
  9575. static void mg_tls_server_handshake(struct mg_connection *c) {
  9576. struct tls_data *tls = (struct tls_data *) c->tls;
  9577. switch (tls->state) {
  9578. case MG_TLS_STATE_SERVER_START:
  9579. if (mg_tls_server_recv_hello(c) < 0) {
  9580. return;
  9581. }
  9582. mg_tls_server_send_hello(c);
  9583. mg_tls_generate_handshake_keys(c);
  9584. mg_tls_server_send_ext(c);
  9585. mg_tls_server_send_cert(c);
  9586. mg_tls_server_send_cert_verify(c);
  9587. mg_tls_server_send_finish(c);
  9588. tls->state = MG_TLS_STATE_SERVER_NEGOTIATED;
  9589. // fallthrough
  9590. case MG_TLS_STATE_SERVER_NEGOTIATED:
  9591. if (mg_tls_server_recv_finish(c) < 0) {
  9592. return;
  9593. }
  9594. mg_tls_generate_application_keys(c);
  9595. tls->state = MG_TLS_STATE_SERVER_CONNECTED;
  9596. c->is_tls_hs = 0;
  9597. return;
  9598. default: mg_error(c, "unexpected server state: %d", tls->state); break;
  9599. }
  9600. }
  9601. void mg_tls_handshake(struct mg_connection *c) {
  9602. if (c->is_client) {
  9603. mg_tls_client_handshake(c);
  9604. } else {
  9605. mg_tls_server_handshake(c);
  9606. }
  9607. }
  9608. static int mg_parse_pem(const struct mg_str pem, const struct mg_str label,
  9609. struct mg_str *der) {
  9610. size_t n = 0, m = 0;
  9611. char *s;
  9612. const char *c;
  9613. struct mg_str caps[5];
  9614. if (!mg_match(pem, mg_str("#-----BEGIN #-----#-----END #-----#"), caps)) {
  9615. der->buf = mg_mprintf("%.*s", pem.len, pem.buf);
  9616. der->len = pem.len;
  9617. return 0;
  9618. }
  9619. if (mg_strcmp(caps[1], label) != 0 || mg_strcmp(caps[3], label) != 0) {
  9620. return -1; // bad label
  9621. }
  9622. if ((s = (char *) calloc(1, caps[2].len)) == NULL) {
  9623. return -1;
  9624. }
  9625. for (c = caps[2].buf; c < caps[2].buf + caps[2].len; c++) {
  9626. if (*c == ' ' || *c == '\n' || *c == '\r' || *c == '\t') {
  9627. continue;
  9628. }
  9629. s[n++] = *c;
  9630. }
  9631. m = mg_base64_decode(s, n, s, n);
  9632. if (m == 0) {
  9633. free(s);
  9634. return -1;
  9635. }
  9636. der->buf = s;
  9637. der->len = m;
  9638. return 0;
  9639. }
  9640. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9641. struct mg_str key;
  9642. struct tls_data *tls = (struct tls_data *) calloc(1, sizeof(struct tls_data));
  9643. if (tls == NULL) {
  9644. mg_error(c, "tls oom");
  9645. return;
  9646. }
  9647. tls->state =
  9648. c->is_client ? MG_TLS_STATE_CLIENT_START : MG_TLS_STATE_SERVER_START;
  9649. tls->skip_verification = opts->skip_verification;
  9650. tls->send.align = MG_IO_SIZE;
  9651. c->tls = tls;
  9652. c->is_tls = c->is_tls_hs = 1;
  9653. mg_sha256_init(&tls->sha256);
  9654. // save hostname (client extension)
  9655. if (opts->name.len > 0) {
  9656. if (opts->name.len >= sizeof(tls->hostname) - 1) {
  9657. mg_error(c, "hostname too long");
  9658. }
  9659. strncpy((char *) tls->hostname, opts->name.buf, sizeof(tls->hostname) - 1);
  9660. tls->hostname[opts->name.len] = 0;
  9661. }
  9662. if (c->is_client) {
  9663. tls->server_cert_der.buf = NULL;
  9664. return;
  9665. }
  9666. // parse PEM or DER certificate
  9667. if (mg_parse_pem(opts->cert, mg_str_s("CERTIFICATE"), &tls->server_cert_der) <
  9668. 0) {
  9669. MG_ERROR(("Failed to load certificate"));
  9670. return;
  9671. }
  9672. // parse PEM or DER EC key
  9673. if (opts->key.buf == NULL) {
  9674. mg_error(c, "certificate provided without a private key");
  9675. return;
  9676. }
  9677. if (mg_parse_pem(opts->key, mg_str_s("EC PRIVATE KEY"), &key) == 0) {
  9678. if (key.len < 39) {
  9679. MG_ERROR(("EC private key too short"));
  9680. return;
  9681. }
  9682. // expect ASN.1 SEQUENCE=[INTEGER=1, BITSTRING of 32 bytes, ...]
  9683. // 30 nn 02 01 01 04 20 [key] ...
  9684. if (key.buf[0] != 0x30 || (key.buf[1] & 0x80) != 0) {
  9685. MG_ERROR(("EC private key: ASN.1 bad sequence"));
  9686. return;
  9687. }
  9688. if (memcmp(key.buf + 2, "\x02\x01\x01\x04\x20", 5) != 0) {
  9689. MG_ERROR(("EC private key: ASN.1 bad data"));
  9690. }
  9691. memmove(tls->server_key, key.buf + 7, 32);
  9692. free((void *) key.buf);
  9693. } else if (mg_parse_pem(opts->key, mg_str_s("PRIVATE KEY"), &key) == 0) {
  9694. mg_error(c, "PKCS8 private key format is not supported");
  9695. } else {
  9696. mg_error(c, "expected EC PRIVATE KEY or PRIVATE KEY");
  9697. }
  9698. }
  9699. void mg_tls_free(struct mg_connection *c) {
  9700. struct tls_data *tls = (struct tls_data *) c->tls;
  9701. if (tls != NULL) {
  9702. mg_iobuf_free(&tls->send);
  9703. free((void *) tls->server_cert_der.buf);
  9704. }
  9705. free(c->tls);
  9706. c->tls = NULL;
  9707. }
  9708. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9709. struct tls_data *tls = (struct tls_data *) c->tls;
  9710. long n = MG_IO_WAIT;
  9711. if (len > MG_IO_SIZE) len = MG_IO_SIZE;
  9712. mg_tls_encrypt(c, (const uint8_t *) buf, len, MG_TLS_APP_DATA);
  9713. while (tls->send.len > 0 &&
  9714. (n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {
  9715. mg_iobuf_del(&tls->send, 0, (size_t) n);
  9716. }
  9717. if (n == MG_IO_ERR || n == MG_IO_WAIT) return n;
  9718. return (long) len;
  9719. }
  9720. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9721. int r = 0;
  9722. struct tls_data *tls = (struct tls_data *) c->tls;
  9723. size_t minlen;
  9724. r = mg_tls_recv_record(c);
  9725. if (r < 0) {
  9726. return r;
  9727. }
  9728. if (tls->content_type != MG_TLS_APP_DATA) {
  9729. tls->recv.len = 0;
  9730. mg_tls_drop_record(c);
  9731. return MG_IO_WAIT;
  9732. }
  9733. minlen = len < tls->recv.len ? len : tls->recv.len;
  9734. memmove(buf, tls->recv.buf, minlen);
  9735. tls->recv.buf += minlen;
  9736. tls->recv.len -= minlen;
  9737. if (tls->recv.len == 0) {
  9738. mg_tls_drop_record(c);
  9739. }
  9740. return (long) minlen;
  9741. }
  9742. size_t mg_tls_pending(struct mg_connection *c) {
  9743. return mg_tls_got_record(c) ? 1 : 0;
  9744. }
  9745. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9746. (void) mgr;
  9747. }
  9748. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9749. (void) mgr;
  9750. }
  9751. #endif
  9752. #ifdef MG_ENABLE_LINES
  9753. #line 1 "src/tls_dummy.c"
  9754. #endif
  9755. #if MG_TLS == MG_TLS_NONE
  9756. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9757. (void) opts;
  9758. mg_error(c, "TLS is not enabled");
  9759. }
  9760. void mg_tls_handshake(struct mg_connection *c) {
  9761. (void) c;
  9762. }
  9763. void mg_tls_free(struct mg_connection *c) {
  9764. (void) c;
  9765. }
  9766. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9767. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  9768. }
  9769. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9770. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  9771. }
  9772. size_t mg_tls_pending(struct mg_connection *c) {
  9773. (void) c;
  9774. return 0;
  9775. }
  9776. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9777. (void) mgr;
  9778. }
  9779. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9780. (void) mgr;
  9781. }
  9782. #endif
  9783. #ifdef MG_ENABLE_LINES
  9784. #line 1 "src/tls_mbed.c"
  9785. #endif
  9786. #if MG_TLS == MG_TLS_MBED
  9787. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000
  9788. #define MG_MBEDTLS_RNG_GET , mg_mbed_rng, NULL
  9789. #else
  9790. #define MG_MBEDTLS_RNG_GET
  9791. #endif
  9792. static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) {
  9793. mg_random(buf, len);
  9794. (void) ctx;
  9795. return 0;
  9796. }
  9797. static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *p) {
  9798. int rc;
  9799. if (str.buf == NULL || str.buf[0] == '\0' || str.buf[0] == '*') return true;
  9800. if (str.buf[0] == '-') str.len++; // PEM, include trailing NUL
  9801. if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.buf, str.len)) != 0) {
  9802. MG_ERROR(("cert err %#x", -rc));
  9803. return false;
  9804. }
  9805. return true;
  9806. }
  9807. static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) {
  9808. int rc;
  9809. if (str.buf == NULL || str.buf[0] == '\0' || str.buf[0] == '*') return true;
  9810. if (str.buf[0] == '-') str.len++; // PEM, include trailing NUL
  9811. if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.buf, str.len, NULL,
  9812. 0 MG_MBEDTLS_RNG_GET)) != 0) {
  9813. MG_ERROR(("key err %#x", -rc));
  9814. return false;
  9815. }
  9816. return true;
  9817. }
  9818. void mg_tls_free(struct mg_connection *c) {
  9819. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9820. if (tls != NULL) {
  9821. mbedtls_ssl_free(&tls->ssl);
  9822. mbedtls_pk_free(&tls->pk);
  9823. mbedtls_x509_crt_free(&tls->ca);
  9824. mbedtls_x509_crt_free(&tls->cert);
  9825. mbedtls_ssl_config_free(&tls->conf);
  9826. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  9827. mbedtls_ssl_ticket_free(&tls->ticket);
  9828. #endif
  9829. free(tls);
  9830. c->tls = NULL;
  9831. }
  9832. }
  9833. static int mg_net_send(void *ctx, const unsigned char *buf, size_t len) {
  9834. long n = mg_io_send((struct mg_connection *) ctx, buf, len);
  9835. MG_VERBOSE(("%lu n=%ld e=%d", ((struct mg_connection *) ctx)->id, n, errno));
  9836. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  9837. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  9838. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_SEND_FAILED;
  9839. return (int) n;
  9840. }
  9841. static int mg_net_recv(void *ctx, unsigned char *buf, size_t len) {
  9842. long n = mg_io_recv((struct mg_connection *) ctx, buf, len);
  9843. MG_VERBOSE(("%lu n=%ld", ((struct mg_connection *) ctx)->id, n));
  9844. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  9845. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  9846. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_RECV_FAILED;
  9847. return (int) n;
  9848. }
  9849. void mg_tls_handshake(struct mg_connection *c) {
  9850. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9851. int rc = mbedtls_ssl_handshake(&tls->ssl);
  9852. if (rc == 0) { // Success
  9853. MG_DEBUG(("%lu success", c->id));
  9854. c->is_tls_hs = 0;
  9855. mg_call(c, MG_EV_TLS_HS, NULL);
  9856. } else if (rc == MBEDTLS_ERR_SSL_WANT_READ ||
  9857. rc == MBEDTLS_ERR_SSL_WANT_WRITE) { // Still pending
  9858. MG_VERBOSE(("%lu pending, %d%d %d (-%#x)", c->id, c->is_connecting,
  9859. c->is_tls_hs, rc, -rc));
  9860. } else {
  9861. mg_error(c, "TLS handshake: -%#x", -rc); // Error
  9862. }
  9863. }
  9864. static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) {
  9865. n = (int) strlen(s2) - 1;
  9866. MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2));
  9867. (void) s;
  9868. }
  9869. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9870. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  9871. int rc = 0;
  9872. c->tls = tls;
  9873. if (c->tls == NULL) {
  9874. mg_error(c, "TLS OOM");
  9875. goto fail;
  9876. }
  9877. if (c->is_listening) goto fail;
  9878. MG_DEBUG(("%lu Setting TLS", c->id));
  9879. MG_PROF_ADD(c, "mbedtls_init_start");
  9880. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000 && \
  9881. defined(MBEDTLS_PSA_CRYPTO_C)
  9882. psa_crypto_init(); // https://github.com/Mbed-TLS/mbedtls/issues/9072#issuecomment-2084845711
  9883. #endif
  9884. mbedtls_ssl_init(&tls->ssl);
  9885. mbedtls_ssl_config_init(&tls->conf);
  9886. mbedtls_x509_crt_init(&tls->ca);
  9887. mbedtls_x509_crt_init(&tls->cert);
  9888. mbedtls_pk_init(&tls->pk);
  9889. mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c);
  9890. #if defined(MG_MBEDTLS_DEBUG_LEVEL)
  9891. mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL);
  9892. #endif
  9893. if ((rc = mbedtls_ssl_config_defaults(
  9894. &tls->conf,
  9895. c->is_client ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
  9896. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  9897. mg_error(c, "tls defaults %#x", -rc);
  9898. goto fail;
  9899. }
  9900. mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c);
  9901. if (opts->ca.len == 0 || mg_strcmp(opts->ca, mg_str("*")) == 0) {
  9902. // NOTE: MBEDTLS_SSL_VERIFY_NONE is not supported for TLS1.3 on client side
  9903. // See https://github.com/Mbed-TLS/mbedtls/issues/7075
  9904. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
  9905. } else {
  9906. if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail;
  9907. mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL);
  9908. if (c->is_client && opts->name.buf != NULL && opts->name.buf[0] != '\0') {
  9909. char *host = mg_mprintf("%.*s", opts->name.len, opts->name.buf);
  9910. mbedtls_ssl_set_hostname(&tls->ssl, host);
  9911. MG_DEBUG(("%lu hostname verification: %s", c->id, host));
  9912. free(host);
  9913. }
  9914. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  9915. }
  9916. if (!mg_load_cert(opts->cert, &tls->cert)) goto fail;
  9917. if (!mg_load_key(opts->key, &tls->pk)) goto fail;
  9918. if (tls->cert.version &&
  9919. (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) {
  9920. mg_error(c, "own cert %#x", -rc);
  9921. goto fail;
  9922. }
  9923. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  9924. mbedtls_ssl_conf_session_tickets_cb(
  9925. &tls->conf, mbedtls_ssl_ticket_write, mbedtls_ssl_ticket_parse,
  9926. &((struct mg_tls_ctx *) c->mgr->tls_ctx)->tickets);
  9927. #endif
  9928. if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) {
  9929. mg_error(c, "setup err %#x", -rc);
  9930. goto fail;
  9931. }
  9932. c->is_tls = 1;
  9933. c->is_tls_hs = 1;
  9934. mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0);
  9935. MG_PROF_ADD(c, "mbedtls_init_end");
  9936. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  9937. mg_tls_handshake(c);
  9938. }
  9939. return;
  9940. fail:
  9941. mg_tls_free(c);
  9942. }
  9943. size_t mg_tls_pending(struct mg_connection *c) {
  9944. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9945. return tls == NULL ? 0 : mbedtls_ssl_get_bytes_avail(&tls->ssl);
  9946. }
  9947. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9948. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9949. long n = mbedtls_ssl_read(&tls->ssl, (unsigned char *) buf, len);
  9950. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  9951. return MG_IO_WAIT;
  9952. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  9953. if (n == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) {
  9954. return MG_IO_WAIT;
  9955. }
  9956. #endif
  9957. if (n <= 0) return MG_IO_ERR;
  9958. return n;
  9959. }
  9960. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9961. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9962. long n = mbedtls_ssl_write(&tls->ssl, (unsigned char *) buf, len);
  9963. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  9964. return MG_IO_WAIT;
  9965. if (n <= 0) return MG_IO_ERR;
  9966. return n;
  9967. }
  9968. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9969. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx));
  9970. if (ctx == NULL) {
  9971. MG_ERROR(("TLS context init OOM"));
  9972. } else {
  9973. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  9974. int rc;
  9975. mbedtls_ssl_ticket_init(&ctx->tickets);
  9976. if ((rc = mbedtls_ssl_ticket_setup(&ctx->tickets, mg_mbed_rng, NULL,
  9977. MBEDTLS_CIPHER_AES_128_GCM, 86400)) !=
  9978. 0) {
  9979. MG_ERROR((" mbedtls_ssl_ticket_setup %#x", -rc));
  9980. }
  9981. #endif
  9982. mgr->tls_ctx = ctx;
  9983. }
  9984. }
  9985. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9986. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx;
  9987. if (ctx != NULL) {
  9988. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  9989. mbedtls_ssl_ticket_free(&ctx->tickets);
  9990. #endif
  9991. free(ctx);
  9992. mgr->tls_ctx = NULL;
  9993. }
  9994. }
  9995. #endif
  9996. #ifdef MG_ENABLE_LINES
  9997. #line 1 "src/tls_openssl.c"
  9998. #endif
  9999. #if MG_TLS == MG_TLS_OPENSSL || MG_TLS == MG_TLS_WOLFSSL
  10000. static int tls_err_cb(const char *s, size_t len, void *c) {
  10001. int n = (int) len - 1;
  10002. MG_ERROR(("%lu %.*s", ((struct mg_connection *) c)->id, n, s));
  10003. return 0; // undocumented
  10004. }
  10005. static int mg_tls_err(struct mg_connection *c, struct mg_tls *tls, int res) {
  10006. int err = SSL_get_error(tls->ssl, res);
  10007. // We've just fetched the last error from the queue.
  10008. // Now we need to clear the error queue. If we do not, then the following
  10009. // can happen (actually reported):
  10010. // - A new connection is accept()-ed with cert error (e.g. self-signed cert)
  10011. // - Since all accept()-ed connections share listener's context,
  10012. // - *ALL* SSL accepted connection report read error on the next poll cycle.
  10013. // Thus a single errored connection can close all the rest, unrelated ones.
  10014. // Clearing the error keeps the shared SSL_CTX in an OK state.
  10015. if (err != 0) ERR_print_errors_cb(tls_err_cb, c);
  10016. ERR_clear_error();
  10017. if (err == SSL_ERROR_WANT_READ) return 0;
  10018. if (err == SSL_ERROR_WANT_WRITE) return 0;
  10019. return err;
  10020. }
  10021. static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) {
  10022. BIO *bio = BIO_new_mem_buf(ca.buf, (int) ca.len);
  10023. STACK_OF(X509_INFO) *certs =
  10024. bio ? PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL) : NULL;
  10025. if (bio) BIO_free(bio);
  10026. return certs;
  10027. }
  10028. static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) {
  10029. X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx);
  10030. for (int i = 0; i < sk_X509_INFO_num(certs); i++) {
  10031. X509_INFO *cert_info = sk_X509_INFO_value(certs, i);
  10032. if (cert_info->x509 && !X509_STORE_add_cert(cert_store, cert_info->x509))
  10033. return false;
  10034. }
  10035. return true;
  10036. }
  10037. static EVP_PKEY *load_key(struct mg_str s) {
  10038. BIO *bio = BIO_new_mem_buf(s.buf, (int) (long) s.len);
  10039. EVP_PKEY *key = bio ? PEM_read_bio_PrivateKey(bio, NULL, 0, NULL) : NULL;
  10040. if (bio) BIO_free(bio);
  10041. return key;
  10042. }
  10043. static X509 *load_cert(struct mg_str s) {
  10044. BIO *bio = BIO_new_mem_buf(s.buf, (int) (long) s.len);
  10045. X509 *cert = bio == NULL ? NULL
  10046. : s.buf[0] == '-'
  10047. ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM
  10048. : d2i_X509_bio(bio, NULL); // DER
  10049. if (bio) BIO_free(bio);
  10050. return cert;
  10051. }
  10052. static long mg_bio_ctrl(BIO *b, int cmd, long larg, void *pargs) {
  10053. long ret = 0;
  10054. if (cmd == BIO_CTRL_PUSH) ret = 1;
  10055. if (cmd == BIO_CTRL_POP) ret = 1;
  10056. if (cmd == BIO_CTRL_FLUSH) ret = 1;
  10057. #if MG_TLS == MG_TLS_OPENSSL
  10058. if (cmd == BIO_C_SET_NBIO) ret = 1;
  10059. #endif
  10060. // MG_DEBUG(("%d -> %ld", cmd, ret));
  10061. (void) b, (void) cmd, (void) larg, (void) pargs;
  10062. return ret;
  10063. }
  10064. static int mg_bio_read(BIO *bio, char *buf, int len) {
  10065. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  10066. long res = mg_io_recv(c, buf, (size_t) len);
  10067. // MG_DEBUG(("%p %d %ld", buf, len, res));
  10068. len = res > 0 ? (int) res : -1;
  10069. if (res == MG_IO_WAIT) BIO_set_retry_read(bio);
  10070. return len;
  10071. }
  10072. static int mg_bio_write(BIO *bio, const char *buf, int len) {
  10073. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  10074. long res = mg_io_send(c, buf, (size_t) len);
  10075. // MG_DEBUG(("%p %d %ld", buf, len, res));
  10076. len = res > 0 ? (int) res : -1;
  10077. if (res == MG_IO_WAIT) BIO_set_retry_write(bio);
  10078. return len;
  10079. }
  10080. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  10081. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  10082. const char *id = "mongoose";
  10083. static unsigned char s_initialised = 0;
  10084. BIO *bio = NULL;
  10085. int rc;
  10086. if (tls == NULL) {
  10087. mg_error(c, "TLS OOM");
  10088. goto fail;
  10089. }
  10090. if (!s_initialised) {
  10091. SSL_library_init();
  10092. s_initialised++;
  10093. }
  10094. MG_DEBUG(("%lu Setting TLS", c->id));
  10095. tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method())
  10096. : SSL_CTX_new(SSLv23_server_method());
  10097. if ((tls->ssl = SSL_new(tls->ctx)) == NULL) {
  10098. mg_error(c, "SSL_new");
  10099. goto fail;
  10100. }
  10101. SSL_set_session_id_context(tls->ssl, (const uint8_t *) id,
  10102. (unsigned) strlen(id));
  10103. // Disable deprecated protocols
  10104. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2);
  10105. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3);
  10106. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1);
  10107. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1);
  10108. #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION
  10109. SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION);
  10110. #endif
  10111. #ifdef MG_ENABLE_OPENSSL_CIPHER_SERVER_PREFERENCE
  10112. SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10113. #endif
  10114. #if MG_TLS == MG_TLS_WOLFSSL && !defined(OPENSSL_COMPATIBLE_DEFAULTS)
  10115. if (opts->ca.len == 0 || mg_strcmp(opts->ca, mg_str("*")) == 0) {
  10116. // Older versions require that either the CA is loaded or SSL_VERIFY_NONE
  10117. // explicitly set
  10118. SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, NULL);
  10119. }
  10120. #endif
  10121. if (opts->ca.buf != NULL && opts->ca.buf[0] != '\0') {
  10122. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10123. NULL);
  10124. STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca);
  10125. rc = add_ca_certs(tls->ctx, certs);
  10126. sk_X509_INFO_pop_free(certs, X509_INFO_free);
  10127. if (!rc) {
  10128. mg_error(c, "CA err");
  10129. goto fail;
  10130. }
  10131. }
  10132. if (opts->cert.buf != NULL && opts->cert.buf[0] != '\0') {
  10133. X509 *cert = load_cert(opts->cert);
  10134. rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert);
  10135. X509_free(cert);
  10136. if (cert == NULL || rc != 1) {
  10137. mg_error(c, "CERT err %d", mg_tls_err(c, tls, rc));
  10138. goto fail;
  10139. }
  10140. }
  10141. if (opts->key.buf != NULL && opts->key.buf[0] != '\0') {
  10142. EVP_PKEY *key = load_key(opts->key);
  10143. rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key);
  10144. EVP_PKEY_free(key);
  10145. if (key == NULL || rc != 1) {
  10146. mg_error(c, "KEY err %d", mg_tls_err(c, tls, rc));
  10147. goto fail;
  10148. }
  10149. }
  10150. SSL_set_mode(tls->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  10151. #if MG_TLS == MG_TLS_OPENSSL && OPENSSL_VERSION_NUMBER > 0x10002000L
  10152. (void) SSL_set_ecdh_auto(tls->ssl, 1);
  10153. #endif
  10154. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  10155. if (opts->name.len > 0) {
  10156. char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.buf);
  10157. #if MG_TLS != MG_TLS_WOLFSSL || LIBWOLFSSL_VERSION_HEX >= 0x05005002
  10158. SSL_set1_host(tls->ssl, s);
  10159. #else
  10160. X509_VERIFY_PARAM_set1_host(SSL_get0_param(tls->ssl), s, 0);
  10161. #endif
  10162. SSL_set_tlsext_host_name(tls->ssl, s);
  10163. free(s);
  10164. }
  10165. #endif
  10166. #if MG_TLS == MG_TLS_WOLFSSL
  10167. tls->bm = BIO_meth_new(0, "bio_mg");
  10168. #else
  10169. tls->bm = BIO_meth_new(BIO_get_new_index() | BIO_TYPE_SOURCE_SINK, "bio_mg");
  10170. #endif
  10171. BIO_meth_set_write(tls->bm, mg_bio_write);
  10172. BIO_meth_set_read(tls->bm, mg_bio_read);
  10173. BIO_meth_set_ctrl(tls->bm, mg_bio_ctrl);
  10174. bio = BIO_new(tls->bm);
  10175. BIO_set_data(bio, c);
  10176. SSL_set_bio(tls->ssl, bio, bio);
  10177. c->tls = tls;
  10178. c->is_tls = 1;
  10179. c->is_tls_hs = 1;
  10180. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  10181. mg_tls_handshake(c);
  10182. }
  10183. MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client"));
  10184. return;
  10185. fail:
  10186. free(tls);
  10187. }
  10188. void mg_tls_handshake(struct mg_connection *c) {
  10189. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10190. int rc = c->is_client ? SSL_connect(tls->ssl) : SSL_accept(tls->ssl);
  10191. if (rc == 1) {
  10192. MG_DEBUG(("%lu success", c->id));
  10193. c->is_tls_hs = 0;
  10194. mg_call(c, MG_EV_TLS_HS, NULL);
  10195. } else {
  10196. int code = mg_tls_err(c, tls, rc);
  10197. if (code != 0) mg_error(c, "tls hs: rc %d, err %d", rc, code);
  10198. }
  10199. }
  10200. void mg_tls_free(struct mg_connection *c) {
  10201. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10202. if (tls == NULL) return;
  10203. SSL_free(tls->ssl);
  10204. SSL_CTX_free(tls->ctx);
  10205. BIO_meth_free(tls->bm);
  10206. free(tls);
  10207. c->tls = NULL;
  10208. }
  10209. size_t mg_tls_pending(struct mg_connection *c) {
  10210. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10211. return tls == NULL ? 0 : (size_t) SSL_pending(tls->ssl);
  10212. }
  10213. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  10214. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10215. int n = SSL_read(tls->ssl, buf, (int) len);
  10216. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  10217. if (n <= 0) return MG_IO_ERR;
  10218. return n;
  10219. }
  10220. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  10221. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10222. int n = SSL_write(tls->ssl, buf, (int) len);
  10223. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  10224. if (n <= 0) return MG_IO_ERR;
  10225. return n;
  10226. }
  10227. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  10228. (void) mgr;
  10229. }
  10230. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  10231. (void) mgr;
  10232. }
  10233. #endif
  10234. #ifdef MG_ENABLE_LINES
  10235. #line 1 "src/tls_uecc.c"
  10236. #endif
  10237. /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  10238. #if MG_TLS == MG_TLS_BUILTIN
  10239. #ifndef MG_UECC_RNG_MAX_TRIES
  10240. #define MG_UECC_RNG_MAX_TRIES 64
  10241. #endif
  10242. #if MG_UECC_ENABLE_VLI_API
  10243. #define MG_UECC_VLI_API
  10244. #else
  10245. #define MG_UECC_VLI_API static
  10246. #endif
  10247. #if (MG_UECC_PLATFORM == mg_uecc_avr) || (MG_UECC_PLATFORM == mg_uecc_arm) || \
  10248. (MG_UECC_PLATFORM == mg_uecc_arm_thumb) || \
  10249. (MG_UECC_PLATFORM == mg_uecc_arm_thumb2)
  10250. #define CONCATX(a, ...) a##__VA_ARGS__
  10251. #define CONCAT(a, ...) CONCATX(a, __VA_ARGS__)
  10252. #define STRX(a) #a
  10253. #define STR(a) STRX(a)
  10254. #define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__))))
  10255. #define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__))))
  10256. #define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__))))
  10257. #define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__))))
  10258. #define EVAL4(...) __VA_ARGS__
  10259. #define DEC_1 0
  10260. #define DEC_2 1
  10261. #define DEC_3 2
  10262. #define DEC_4 3
  10263. #define DEC_5 4
  10264. #define DEC_6 5
  10265. #define DEC_7 6
  10266. #define DEC_8 7
  10267. #define DEC_9 8
  10268. #define DEC_10 9
  10269. #define DEC_11 10
  10270. #define DEC_12 11
  10271. #define DEC_13 12
  10272. #define DEC_14 13
  10273. #define DEC_15 14
  10274. #define DEC_16 15
  10275. #define DEC_17 16
  10276. #define DEC_18 17
  10277. #define DEC_19 18
  10278. #define DEC_20 19
  10279. #define DEC_21 20
  10280. #define DEC_22 21
  10281. #define DEC_23 22
  10282. #define DEC_24 23
  10283. #define DEC_25 24
  10284. #define DEC_26 25
  10285. #define DEC_27 26
  10286. #define DEC_28 27
  10287. #define DEC_29 28
  10288. #define DEC_30 29
  10289. #define DEC_31 30
  10290. #define DEC_32 31
  10291. #define DEC(N) CONCAT(DEC_, N)
  10292. #define SECOND_ARG(_, val, ...) val
  10293. #define SOME_CHECK_0 ~, 0
  10294. #define GET_SECOND_ARG(...) SECOND_ARG(__VA_ARGS__, SOME, )
  10295. #define SOME_OR_0(N) GET_SECOND_ARG(CONCAT(SOME_CHECK_, N))
  10296. #define EMPTY(...)
  10297. #define DEFER(...) __VA_ARGS__ EMPTY()
  10298. #define REPEAT_NAME_0() REPEAT_0
  10299. #define REPEAT_NAME_SOME() REPEAT_SOME
  10300. #define REPEAT_0(...)
  10301. #define REPEAT_SOME(N, stuff) \
  10302. DEFER(CONCAT(REPEAT_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), stuff) stuff
  10303. #define REPEAT(N, stuff) EVAL(REPEAT_SOME(N, stuff))
  10304. #define REPEATM_NAME_0() REPEATM_0
  10305. #define REPEATM_NAME_SOME() REPEATM_SOME
  10306. #define REPEATM_0(...)
  10307. #define REPEATM_SOME(N, macro) \
  10308. macro(N) DEFER(CONCAT(REPEATM_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), macro)
  10309. #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro))
  10310. #endif
  10311. //
  10312. #if (MG_UECC_WORD_SIZE == 1)
  10313. #if MG_UECC_SUPPORTS_secp160r1
  10314. #define MG_UECC_MAX_WORDS 21 /* Due to the size of curve_n. */
  10315. #endif
  10316. #if MG_UECC_SUPPORTS_secp192r1
  10317. #undef MG_UECC_MAX_WORDS
  10318. #define MG_UECC_MAX_WORDS 24
  10319. #endif
  10320. #if MG_UECC_SUPPORTS_secp224r1
  10321. #undef MG_UECC_MAX_WORDS
  10322. #define MG_UECC_MAX_WORDS 28
  10323. #endif
  10324. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10325. #undef MG_UECC_MAX_WORDS
  10326. #define MG_UECC_MAX_WORDS 32
  10327. #endif
  10328. #elif (MG_UECC_WORD_SIZE == 4)
  10329. #if MG_UECC_SUPPORTS_secp160r1
  10330. #define MG_UECC_MAX_WORDS 6 /* Due to the size of curve_n. */
  10331. #endif
  10332. #if MG_UECC_SUPPORTS_secp192r1
  10333. #undef MG_UECC_MAX_WORDS
  10334. #define MG_UECC_MAX_WORDS 6
  10335. #endif
  10336. #if MG_UECC_SUPPORTS_secp224r1
  10337. #undef MG_UECC_MAX_WORDS
  10338. #define MG_UECC_MAX_WORDS 7
  10339. #endif
  10340. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10341. #undef MG_UECC_MAX_WORDS
  10342. #define MG_UECC_MAX_WORDS 8
  10343. #endif
  10344. #elif (MG_UECC_WORD_SIZE == 8)
  10345. #if MG_UECC_SUPPORTS_secp160r1
  10346. #define MG_UECC_MAX_WORDS 3
  10347. #endif
  10348. #if MG_UECC_SUPPORTS_secp192r1
  10349. #undef MG_UECC_MAX_WORDS
  10350. #define MG_UECC_MAX_WORDS 3
  10351. #endif
  10352. #if MG_UECC_SUPPORTS_secp224r1
  10353. #undef MG_UECC_MAX_WORDS
  10354. #define MG_UECC_MAX_WORDS 4
  10355. #endif
  10356. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10357. #undef MG_UECC_MAX_WORDS
  10358. #define MG_UECC_MAX_WORDS 4
  10359. #endif
  10360. #endif /* MG_UECC_WORD_SIZE */
  10361. #define BITS_TO_WORDS(num_bits) \
  10362. ((wordcount_t) ((num_bits + ((MG_UECC_WORD_SIZE * 8) - 1)) / \
  10363. (MG_UECC_WORD_SIZE * 8)))
  10364. #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
  10365. struct MG_UECC_Curve_t {
  10366. wordcount_t num_words;
  10367. wordcount_t num_bytes;
  10368. bitcount_t num_n_bits;
  10369. mg_uecc_word_t p[MG_UECC_MAX_WORDS];
  10370. mg_uecc_word_t n[MG_UECC_MAX_WORDS];
  10371. mg_uecc_word_t G[MG_UECC_MAX_WORDS * 2];
  10372. mg_uecc_word_t b[MG_UECC_MAX_WORDS];
  10373. void (*double_jacobian)(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  10374. mg_uecc_word_t *Z1, MG_UECC_Curve curve);
  10375. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  10376. void (*mod_sqrt)(mg_uecc_word_t *a, MG_UECC_Curve curve);
  10377. #endif
  10378. void (*x_side)(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  10379. MG_UECC_Curve curve);
  10380. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10381. void (*mmod_fast)(mg_uecc_word_t *result, mg_uecc_word_t *product);
  10382. #endif
  10383. };
  10384. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  10385. static void bcopy(uint8_t *dst, const uint8_t *src, unsigned num_bytes) {
  10386. while (0 != num_bytes) {
  10387. num_bytes--;
  10388. dst[num_bytes] = src[num_bytes];
  10389. }
  10390. }
  10391. #endif
  10392. static cmpresult_t mg_uecc_vli_cmp_unsafe(const mg_uecc_word_t *left,
  10393. const mg_uecc_word_t *right,
  10394. wordcount_t num_words);
  10395. #if (MG_UECC_PLATFORM == mg_uecc_arm || \
  10396. MG_UECC_PLATFORM == mg_uecc_arm_thumb || \
  10397. MG_UECC_PLATFORM == mg_uecc_arm_thumb2)
  10398. #endif
  10399. #if (MG_UECC_PLATFORM == mg_uecc_avr)
  10400. #endif
  10401. #ifndef asm_clear
  10402. #define asm_clear 0
  10403. #endif
  10404. #ifndef asm_set
  10405. #define asm_set 0
  10406. #endif
  10407. #ifndef asm_add
  10408. #define asm_add 0
  10409. #endif
  10410. #ifndef asm_sub
  10411. #define asm_sub 0
  10412. #endif
  10413. #ifndef asm_mult
  10414. #define asm_mult 0
  10415. #endif
  10416. #ifndef asm_rshift1
  10417. #define asm_rshift1 0
  10418. #endif
  10419. #ifndef asm_mmod_fast_secp256r1
  10420. #define asm_mmod_fast_secp256r1 0
  10421. #endif
  10422. #if defined(default_RNG_defined) && default_RNG_defined
  10423. static MG_UECC_RNG_Function g_rng_function = &default_RNG;
  10424. #else
  10425. static MG_UECC_RNG_Function g_rng_function = 0;
  10426. #endif
  10427. void mg_uecc_set_rng(MG_UECC_RNG_Function rng_function) {
  10428. g_rng_function = rng_function;
  10429. }
  10430. MG_UECC_RNG_Function mg_uecc_get_rng(void) {
  10431. return g_rng_function;
  10432. }
  10433. int mg_uecc_curve_private_key_size(MG_UECC_Curve curve) {
  10434. return BITS_TO_BYTES(curve->num_n_bits);
  10435. }
  10436. int mg_uecc_curve_public_key_size(MG_UECC_Curve curve) {
  10437. return 2 * curve->num_bytes;
  10438. }
  10439. #if !asm_clear
  10440. MG_UECC_VLI_API void mg_uecc_vli_clear(mg_uecc_word_t *vli,
  10441. wordcount_t num_words) {
  10442. wordcount_t i;
  10443. for (i = 0; i < num_words; ++i) {
  10444. vli[i] = 0;
  10445. }
  10446. }
  10447. #endif /* !asm_clear */
  10448. /* Constant-time comparison to zero - secure way to compare long integers */
  10449. /* Returns 1 if vli == 0, 0 otherwise. */
  10450. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_isZero(const mg_uecc_word_t *vli,
  10451. wordcount_t num_words) {
  10452. mg_uecc_word_t bits = 0;
  10453. wordcount_t i;
  10454. for (i = 0; i < num_words; ++i) {
  10455. bits |= vli[i];
  10456. }
  10457. return (bits == 0);
  10458. }
  10459. /* Returns nonzero if bit 'bit' of vli is set. */
  10460. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_testBit(const mg_uecc_word_t *vli,
  10461. bitcount_t bit) {
  10462. return (vli[bit >> MG_UECC_WORD_BITS_SHIFT] &
  10463. ((mg_uecc_word_t) 1 << (bit & MG_UECC_WORD_BITS_MASK)));
  10464. }
  10465. /* Counts the number of words in vli. */
  10466. static wordcount_t vli_numDigits(const mg_uecc_word_t *vli,
  10467. const wordcount_t max_words) {
  10468. wordcount_t i;
  10469. /* Search from the end until we find a non-zero digit.
  10470. We do it in reverse because we expect that most digits will be nonzero. */
  10471. for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
  10472. }
  10473. return (i + 1);
  10474. }
  10475. /* Counts the number of bits required to represent vli. */
  10476. MG_UECC_VLI_API bitcount_t mg_uecc_vli_numBits(const mg_uecc_word_t *vli,
  10477. const wordcount_t max_words) {
  10478. mg_uecc_word_t i;
  10479. mg_uecc_word_t digit;
  10480. wordcount_t num_digits = vli_numDigits(vli, max_words);
  10481. if (num_digits == 0) {
  10482. return 0;
  10483. }
  10484. digit = vli[num_digits - 1];
  10485. for (i = 0; digit; ++i) {
  10486. digit >>= 1;
  10487. }
  10488. return (((bitcount_t) ((num_digits - 1) << MG_UECC_WORD_BITS_SHIFT)) +
  10489. (bitcount_t) i);
  10490. }
  10491. /* Sets dest = src. */
  10492. #if !asm_set
  10493. MG_UECC_VLI_API void mg_uecc_vli_set(mg_uecc_word_t *dest,
  10494. const mg_uecc_word_t *src,
  10495. wordcount_t num_words) {
  10496. wordcount_t i;
  10497. for (i = 0; i < num_words; ++i) {
  10498. dest[i] = src[i];
  10499. }
  10500. }
  10501. #endif /* !asm_set */
  10502. /* Returns sign of left - right. */
  10503. static cmpresult_t mg_uecc_vli_cmp_unsafe(const mg_uecc_word_t *left,
  10504. const mg_uecc_word_t *right,
  10505. wordcount_t num_words) {
  10506. wordcount_t i;
  10507. for (i = num_words - 1; i >= 0; --i) {
  10508. if (left[i] > right[i]) {
  10509. return 1;
  10510. } else if (left[i] < right[i]) {
  10511. return -1;
  10512. }
  10513. }
  10514. return 0;
  10515. }
  10516. /* Constant-time comparison function - secure way to compare long integers */
  10517. /* Returns one if left == right, zero otherwise. */
  10518. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_equal(const mg_uecc_word_t *left,
  10519. const mg_uecc_word_t *right,
  10520. wordcount_t num_words) {
  10521. mg_uecc_word_t diff = 0;
  10522. wordcount_t i;
  10523. for (i = num_words - 1; i >= 0; --i) {
  10524. diff |= (left[i] ^ right[i]);
  10525. }
  10526. return (diff == 0);
  10527. }
  10528. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_sub(mg_uecc_word_t *result,
  10529. const mg_uecc_word_t *left,
  10530. const mg_uecc_word_t *right,
  10531. wordcount_t num_words);
  10532. /* Returns sign of left - right, in constant time. */
  10533. MG_UECC_VLI_API cmpresult_t mg_uecc_vli_cmp(const mg_uecc_word_t *left,
  10534. const mg_uecc_word_t *right,
  10535. wordcount_t num_words) {
  10536. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  10537. mg_uecc_word_t neg = !!mg_uecc_vli_sub(tmp, left, right, num_words);
  10538. mg_uecc_word_t equal = mg_uecc_vli_isZero(tmp, num_words);
  10539. return (cmpresult_t) (!equal - 2 * neg);
  10540. }
  10541. /* Computes vli = vli >> 1. */
  10542. #if !asm_rshift1
  10543. MG_UECC_VLI_API void mg_uecc_vli_rshift1(mg_uecc_word_t *vli,
  10544. wordcount_t num_words) {
  10545. mg_uecc_word_t *end = vli;
  10546. mg_uecc_word_t carry = 0;
  10547. vli += num_words;
  10548. while (vli-- > end) {
  10549. mg_uecc_word_t temp = *vli;
  10550. *vli = (temp >> 1) | carry;
  10551. carry = temp << (MG_UECC_WORD_BITS - 1);
  10552. }
  10553. }
  10554. #endif /* !asm_rshift1 */
  10555. /* Computes result = left + right, returning carry. Can modify in place. */
  10556. #if !asm_add
  10557. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_add(mg_uecc_word_t *result,
  10558. const mg_uecc_word_t *left,
  10559. const mg_uecc_word_t *right,
  10560. wordcount_t num_words) {
  10561. mg_uecc_word_t carry = 0;
  10562. wordcount_t i;
  10563. for (i = 0; i < num_words; ++i) {
  10564. mg_uecc_word_t sum = left[i] + right[i] + carry;
  10565. if (sum != left[i]) {
  10566. carry = (sum < left[i]);
  10567. }
  10568. result[i] = sum;
  10569. }
  10570. return carry;
  10571. }
  10572. #endif /* !asm_add */
  10573. /* Computes result = left - right, returning borrow. Can modify in place. */
  10574. #if !asm_sub
  10575. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_sub(mg_uecc_word_t *result,
  10576. const mg_uecc_word_t *left,
  10577. const mg_uecc_word_t *right,
  10578. wordcount_t num_words) {
  10579. mg_uecc_word_t borrow = 0;
  10580. wordcount_t i;
  10581. for (i = 0; i < num_words; ++i) {
  10582. mg_uecc_word_t diff = left[i] - right[i] - borrow;
  10583. if (diff != left[i]) {
  10584. borrow = (diff > left[i]);
  10585. }
  10586. result[i] = diff;
  10587. }
  10588. return borrow;
  10589. }
  10590. #endif /* !asm_sub */
  10591. #if !asm_mult || (MG_UECC_SQUARE_FUNC && !asm_square) || \
  10592. (MG_UECC_SUPPORTS_secp256k1 && (MG_UECC_OPTIMIZATION_LEVEL > 0) && \
  10593. ((MG_UECC_WORD_SIZE == 1) || (MG_UECC_WORD_SIZE == 8)))
  10594. static void muladd(mg_uecc_word_t a, mg_uecc_word_t b, mg_uecc_word_t *r0,
  10595. mg_uecc_word_t *r1, mg_uecc_word_t *r2) {
  10596. #if MG_UECC_WORD_SIZE == 8
  10597. uint64_t a0 = a & 0xffffffff;
  10598. uint64_t a1 = a >> 32;
  10599. uint64_t b0 = b & 0xffffffff;
  10600. uint64_t b1 = b >> 32;
  10601. uint64_t i0 = a0 * b0;
  10602. uint64_t i1 = a0 * b1;
  10603. uint64_t i2 = a1 * b0;
  10604. uint64_t i3 = a1 * b1;
  10605. uint64_t p0, p1;
  10606. i2 += (i0 >> 32);
  10607. i2 += i1;
  10608. if (i2 < i1) { /* overflow */
  10609. i3 += 0x100000000;
  10610. }
  10611. p0 = (i0 & 0xffffffff) | (i2 << 32);
  10612. p1 = i3 + (i2 >> 32);
  10613. *r0 += p0;
  10614. *r1 += (p1 + (*r0 < p0));
  10615. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  10616. #else
  10617. mg_uecc_dword_t p = (mg_uecc_dword_t) a * b;
  10618. mg_uecc_dword_t r01 = ((mg_uecc_dword_t) (*r1) << MG_UECC_WORD_BITS) | *r0;
  10619. r01 += p;
  10620. *r2 += (r01 < p);
  10621. *r1 = (mg_uecc_word_t) (r01 >> MG_UECC_WORD_BITS);
  10622. *r0 = (mg_uecc_word_t) r01;
  10623. #endif
  10624. }
  10625. #endif /* muladd needed */
  10626. #if !asm_mult
  10627. MG_UECC_VLI_API void mg_uecc_vli_mult(mg_uecc_word_t *result,
  10628. const mg_uecc_word_t *left,
  10629. const mg_uecc_word_t *right,
  10630. wordcount_t num_words) {
  10631. mg_uecc_word_t r0 = 0;
  10632. mg_uecc_word_t r1 = 0;
  10633. mg_uecc_word_t r2 = 0;
  10634. wordcount_t i, k;
  10635. /* Compute each digit of result in sequence, maintaining the carries. */
  10636. for (k = 0; k < num_words; ++k) {
  10637. for (i = 0; i <= k; ++i) {
  10638. muladd(left[i], right[k - i], &r0, &r1, &r2);
  10639. }
  10640. result[k] = r0;
  10641. r0 = r1;
  10642. r1 = r2;
  10643. r2 = 0;
  10644. }
  10645. for (k = num_words; k < num_words * 2 - 1; ++k) {
  10646. for (i = (wordcount_t) ((k + 1) - num_words); i < num_words; ++i) {
  10647. muladd(left[i], right[k - i], &r0, &r1, &r2);
  10648. }
  10649. result[k] = r0;
  10650. r0 = r1;
  10651. r1 = r2;
  10652. r2 = 0;
  10653. }
  10654. result[num_words * 2 - 1] = r0;
  10655. }
  10656. #endif /* !asm_mult */
  10657. #if MG_UECC_SQUARE_FUNC
  10658. #if !asm_square
  10659. static void mul2add(mg_uecc_word_t a, mg_uecc_word_t b, mg_uecc_word_t *r0,
  10660. mg_uecc_word_t *r1, mg_uecc_word_t *r2) {
  10661. #if MG_UECC_WORD_SIZE == 8
  10662. uint64_t a0 = a & 0xffffffffull;
  10663. uint64_t a1 = a >> 32;
  10664. uint64_t b0 = b & 0xffffffffull;
  10665. uint64_t b1 = b >> 32;
  10666. uint64_t i0 = a0 * b0;
  10667. uint64_t i1 = a0 * b1;
  10668. uint64_t i2 = a1 * b0;
  10669. uint64_t i3 = a1 * b1;
  10670. uint64_t p0, p1;
  10671. i2 += (i0 >> 32);
  10672. i2 += i1;
  10673. if (i2 < i1) { /* overflow */
  10674. i3 += 0x100000000ull;
  10675. }
  10676. p0 = (i0 & 0xffffffffull) | (i2 << 32);
  10677. p1 = i3 + (i2 >> 32);
  10678. *r2 += (p1 >> 63);
  10679. p1 = (p1 << 1) | (p0 >> 63);
  10680. p0 <<= 1;
  10681. *r0 += p0;
  10682. *r1 += (p1 + (*r0 < p0));
  10683. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  10684. #else
  10685. mg_uecc_dword_t p = (mg_uecc_dword_t) a * b;
  10686. mg_uecc_dword_t r01 = ((mg_uecc_dword_t) (*r1) << MG_UECC_WORD_BITS) | *r0;
  10687. *r2 += (p >> (MG_UECC_WORD_BITS * 2 - 1));
  10688. p *= 2;
  10689. r01 += p;
  10690. *r2 += (r01 < p);
  10691. *r1 = r01 >> MG_UECC_WORD_BITS;
  10692. *r0 = (mg_uecc_word_t) r01;
  10693. #endif
  10694. }
  10695. MG_UECC_VLI_API void mg_uecc_vli_square(mg_uecc_word_t *result,
  10696. const mg_uecc_word_t *left,
  10697. wordcount_t num_words) {
  10698. mg_uecc_word_t r0 = 0;
  10699. mg_uecc_word_t r1 = 0;
  10700. mg_uecc_word_t r2 = 0;
  10701. wordcount_t i, k;
  10702. for (k = 0; k < num_words * 2 - 1; ++k) {
  10703. mg_uecc_word_t min = (k < num_words ? 0 : (k + 1) - num_words);
  10704. for (i = min; i <= k && i <= k - i; ++i) {
  10705. if (i < k - i) {
  10706. mul2add(left[i], left[k - i], &r0, &r1, &r2);
  10707. } else {
  10708. muladd(left[i], left[k - i], &r0, &r1, &r2);
  10709. }
  10710. }
  10711. result[k] = r0;
  10712. r0 = r1;
  10713. r1 = r2;
  10714. r2 = 0;
  10715. }
  10716. result[num_words * 2 - 1] = r0;
  10717. }
  10718. #endif /* !asm_square */
  10719. #else /* MG_UECC_SQUARE_FUNC */
  10720. #if MG_UECC_ENABLE_VLI_API
  10721. MG_UECC_VLI_API void mg_uecc_vli_square(mg_uecc_word_t *result,
  10722. const mg_uecc_word_t *left,
  10723. wordcount_t num_words) {
  10724. mg_uecc_vli_mult(result, left, left, num_words);
  10725. }
  10726. #endif /* MG_UECC_ENABLE_VLI_API */
  10727. #endif /* MG_UECC_SQUARE_FUNC */
  10728. /* Computes result = (left + right) % mod.
  10729. Assumes that left < mod and right < mod, and that result does not overlap
  10730. mod. */
  10731. MG_UECC_VLI_API void mg_uecc_vli_modAdd(mg_uecc_word_t *result,
  10732. const mg_uecc_word_t *left,
  10733. const mg_uecc_word_t *right,
  10734. const mg_uecc_word_t *mod,
  10735. wordcount_t num_words) {
  10736. mg_uecc_word_t carry = mg_uecc_vli_add(result, left, right, num_words);
  10737. if (carry || mg_uecc_vli_cmp_unsafe(mod, result, num_words) != 1) {
  10738. /* result > mod (result = mod + remainder), so subtract mod to get
  10739. * remainder. */
  10740. mg_uecc_vli_sub(result, result, mod, num_words);
  10741. }
  10742. }
  10743. /* Computes result = (left - right) % mod.
  10744. Assumes that left < mod and right < mod, and that result does not overlap
  10745. mod. */
  10746. MG_UECC_VLI_API void mg_uecc_vli_modSub(mg_uecc_word_t *result,
  10747. const mg_uecc_word_t *left,
  10748. const mg_uecc_word_t *right,
  10749. const mg_uecc_word_t *mod,
  10750. wordcount_t num_words) {
  10751. mg_uecc_word_t l_borrow = mg_uecc_vli_sub(result, left, right, num_words);
  10752. if (l_borrow) {
  10753. /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
  10754. we can get the correct result from result + mod (with overflow). */
  10755. mg_uecc_vli_add(result, result, mod, num_words);
  10756. }
  10757. }
  10758. /* Computes result = product % mod, where product is 2N words long. */
  10759. /* Currently only designed to work for curve_p or curve_n. */
  10760. MG_UECC_VLI_API void mg_uecc_vli_mmod(mg_uecc_word_t *result,
  10761. mg_uecc_word_t *product,
  10762. const mg_uecc_word_t *mod,
  10763. wordcount_t num_words) {
  10764. mg_uecc_word_t mod_multiple[2 * MG_UECC_MAX_WORDS];
  10765. mg_uecc_word_t tmp[2 * MG_UECC_MAX_WORDS];
  10766. mg_uecc_word_t *v[2] = {tmp, product};
  10767. mg_uecc_word_t index;
  10768. /* Shift mod so its highest set bit is at the maximum position. */
  10769. bitcount_t shift = (bitcount_t) ((num_words * 2 * MG_UECC_WORD_BITS) -
  10770. mg_uecc_vli_numBits(mod, num_words));
  10771. wordcount_t word_shift = (wordcount_t) (shift / MG_UECC_WORD_BITS);
  10772. wordcount_t bit_shift = (wordcount_t) (shift % MG_UECC_WORD_BITS);
  10773. mg_uecc_word_t carry = 0;
  10774. mg_uecc_vli_clear(mod_multiple, word_shift);
  10775. if (bit_shift > 0) {
  10776. for (index = 0; index < (mg_uecc_word_t) num_words; ++index) {
  10777. mod_multiple[(mg_uecc_word_t) word_shift + index] =
  10778. (mg_uecc_word_t) (mod[index] << bit_shift) | carry;
  10779. carry = mod[index] >> (MG_UECC_WORD_BITS - bit_shift);
  10780. }
  10781. } else {
  10782. mg_uecc_vli_set(mod_multiple + word_shift, mod, num_words);
  10783. }
  10784. for (index = 1; shift >= 0; --shift) {
  10785. mg_uecc_word_t borrow = 0;
  10786. wordcount_t i;
  10787. for (i = 0; i < num_words * 2; ++i) {
  10788. mg_uecc_word_t diff = v[index][i] - mod_multiple[i] - borrow;
  10789. if (diff != v[index][i]) {
  10790. borrow = (diff > v[index][i]);
  10791. }
  10792. v[1 - index][i] = diff;
  10793. }
  10794. index = !(index ^ borrow); /* Swap the index if there was no borrow */
  10795. mg_uecc_vli_rshift1(mod_multiple, num_words);
  10796. mod_multiple[num_words - 1] |= mod_multiple[num_words]
  10797. << (MG_UECC_WORD_BITS - 1);
  10798. mg_uecc_vli_rshift1(mod_multiple + num_words, num_words);
  10799. }
  10800. mg_uecc_vli_set(result, v[index], num_words);
  10801. }
  10802. /* Computes result = (left * right) % mod. */
  10803. MG_UECC_VLI_API void mg_uecc_vli_modMult(mg_uecc_word_t *result,
  10804. const mg_uecc_word_t *left,
  10805. const mg_uecc_word_t *right,
  10806. const mg_uecc_word_t *mod,
  10807. wordcount_t num_words) {
  10808. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10809. mg_uecc_vli_mult(product, left, right, num_words);
  10810. mg_uecc_vli_mmod(result, product, mod, num_words);
  10811. }
  10812. MG_UECC_VLI_API void mg_uecc_vli_modMult_fast(mg_uecc_word_t *result,
  10813. const mg_uecc_word_t *left,
  10814. const mg_uecc_word_t *right,
  10815. MG_UECC_Curve curve) {
  10816. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10817. mg_uecc_vli_mult(product, left, right, curve->num_words);
  10818. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10819. curve->mmod_fast(result, product);
  10820. #else
  10821. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  10822. #endif
  10823. }
  10824. #if MG_UECC_SQUARE_FUNC
  10825. #if MG_UECC_ENABLE_VLI_API
  10826. /* Computes result = left^2 % mod. */
  10827. MG_UECC_VLI_API void mg_uecc_vli_modSquare(mg_uecc_word_t *result,
  10828. const mg_uecc_word_t *left,
  10829. const mg_uecc_word_t *mod,
  10830. wordcount_t num_words) {
  10831. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10832. mg_uecc_vli_square(product, left, num_words);
  10833. mg_uecc_vli_mmod(result, product, mod, num_words);
  10834. }
  10835. #endif /* MG_UECC_ENABLE_VLI_API */
  10836. MG_UECC_VLI_API void mg_uecc_vli_modSquare_fast(mg_uecc_word_t *result,
  10837. const mg_uecc_word_t *left,
  10838. MG_UECC_Curve curve) {
  10839. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10840. mg_uecc_vli_square(product, left, curve->num_words);
  10841. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10842. curve->mmod_fast(result, product);
  10843. #else
  10844. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  10845. #endif
  10846. }
  10847. #else /* MG_UECC_SQUARE_FUNC */
  10848. #if MG_UECC_ENABLE_VLI_API
  10849. MG_UECC_VLI_API void mg_uecc_vli_modSquare(mg_uecc_word_t *result,
  10850. const mg_uecc_word_t *left,
  10851. const mg_uecc_word_t *mod,
  10852. wordcount_t num_words) {
  10853. mg_uecc_vli_modMult(result, left, left, mod, num_words);
  10854. }
  10855. #endif /* MG_UECC_ENABLE_VLI_API */
  10856. MG_UECC_VLI_API void mg_uecc_vli_modSquare_fast(mg_uecc_word_t *result,
  10857. const mg_uecc_word_t *left,
  10858. MG_UECC_Curve curve) {
  10859. mg_uecc_vli_modMult_fast(result, left, left, curve);
  10860. }
  10861. #endif /* MG_UECC_SQUARE_FUNC */
  10862. #define EVEN(vli) (!(vli[0] & 1))
  10863. static void vli_modInv_update(mg_uecc_word_t *uv, const mg_uecc_word_t *mod,
  10864. wordcount_t num_words) {
  10865. mg_uecc_word_t carry = 0;
  10866. if (!EVEN(uv)) {
  10867. carry = mg_uecc_vli_add(uv, uv, mod, num_words);
  10868. }
  10869. mg_uecc_vli_rshift1(uv, num_words);
  10870. if (carry) {
  10871. uv[num_words - 1] |= HIGH_BIT_SET;
  10872. }
  10873. }
  10874. /* Computes result = (1 / input) % mod. All VLIs are the same size.
  10875. See "From Euclid's GCD to Montgomery Multiplication to the Great Divide" */
  10876. MG_UECC_VLI_API void mg_uecc_vli_modInv(mg_uecc_word_t *result,
  10877. const mg_uecc_word_t *input,
  10878. const mg_uecc_word_t *mod,
  10879. wordcount_t num_words) {
  10880. mg_uecc_word_t a[MG_UECC_MAX_WORDS], b[MG_UECC_MAX_WORDS],
  10881. u[MG_UECC_MAX_WORDS], v[MG_UECC_MAX_WORDS];
  10882. cmpresult_t cmpResult;
  10883. if (mg_uecc_vli_isZero(input, num_words)) {
  10884. mg_uecc_vli_clear(result, num_words);
  10885. return;
  10886. }
  10887. mg_uecc_vli_set(a, input, num_words);
  10888. mg_uecc_vli_set(b, mod, num_words);
  10889. mg_uecc_vli_clear(u, num_words);
  10890. u[0] = 1;
  10891. mg_uecc_vli_clear(v, num_words);
  10892. while ((cmpResult = mg_uecc_vli_cmp_unsafe(a, b, num_words)) != 0) {
  10893. if (EVEN(a)) {
  10894. mg_uecc_vli_rshift1(a, num_words);
  10895. vli_modInv_update(u, mod, num_words);
  10896. } else if (EVEN(b)) {
  10897. mg_uecc_vli_rshift1(b, num_words);
  10898. vli_modInv_update(v, mod, num_words);
  10899. } else if (cmpResult > 0) {
  10900. mg_uecc_vli_sub(a, a, b, num_words);
  10901. mg_uecc_vli_rshift1(a, num_words);
  10902. if (mg_uecc_vli_cmp_unsafe(u, v, num_words) < 0) {
  10903. mg_uecc_vli_add(u, u, mod, num_words);
  10904. }
  10905. mg_uecc_vli_sub(u, u, v, num_words);
  10906. vli_modInv_update(u, mod, num_words);
  10907. } else {
  10908. mg_uecc_vli_sub(b, b, a, num_words);
  10909. mg_uecc_vli_rshift1(b, num_words);
  10910. if (mg_uecc_vli_cmp_unsafe(v, u, num_words) < 0) {
  10911. mg_uecc_vli_add(v, v, mod, num_words);
  10912. }
  10913. mg_uecc_vli_sub(v, v, u, num_words);
  10914. vli_modInv_update(v, mod, num_words);
  10915. }
  10916. }
  10917. mg_uecc_vli_set(result, u, num_words);
  10918. }
  10919. /* ------ Point operations ------ */
  10920. /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  10921. #ifndef _UECC_CURVE_SPECIFIC_H_
  10922. #define _UECC_CURVE_SPECIFIC_H_
  10923. #define num_bytes_secp160r1 20
  10924. #define num_bytes_secp192r1 24
  10925. #define num_bytes_secp224r1 28
  10926. #define num_bytes_secp256r1 32
  10927. #define num_bytes_secp256k1 32
  10928. #if (MG_UECC_WORD_SIZE == 1)
  10929. #define num_words_secp160r1 20
  10930. #define num_words_secp192r1 24
  10931. #define num_words_secp224r1 28
  10932. #define num_words_secp256r1 32
  10933. #define num_words_secp256k1 32
  10934. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) \
  10935. 0x##a, 0x##b, 0x##c, 0x##d, 0x##e, 0x##f, 0x##g, 0x##h
  10936. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##a, 0x##b, 0x##c, 0x##d
  10937. #elif (MG_UECC_WORD_SIZE == 4)
  10938. #define num_words_secp160r1 5
  10939. #define num_words_secp192r1 6
  10940. #define num_words_secp224r1 7
  10941. #define num_words_secp256r1 8
  10942. #define num_words_secp256k1 8
  10943. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
  10944. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
  10945. #elif (MG_UECC_WORD_SIZE == 8)
  10946. #define num_words_secp160r1 3
  10947. #define num_words_secp192r1 3
  10948. #define num_words_secp224r1 4
  10949. #define num_words_secp256r1 4
  10950. #define num_words_secp256k1 4
  10951. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##h##g##f##e##d##c##b##a##U
  10952. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a##U
  10953. #endif /* MG_UECC_WORD_SIZE */
  10954. #if MG_UECC_SUPPORTS_secp160r1 || MG_UECC_SUPPORTS_secp192r1 || \
  10955. MG_UECC_SUPPORTS_secp224r1 || MG_UECC_SUPPORTS_secp256r1
  10956. static void double_jacobian_default(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  10957. mg_uecc_word_t *Z1, MG_UECC_Curve curve) {
  10958. /* t1 = X, t2 = Y, t3 = Z */
  10959. mg_uecc_word_t t4[MG_UECC_MAX_WORDS];
  10960. mg_uecc_word_t t5[MG_UECC_MAX_WORDS];
  10961. wordcount_t num_words = curve->num_words;
  10962. if (mg_uecc_vli_isZero(Z1, num_words)) {
  10963. return;
  10964. }
  10965. mg_uecc_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */
  10966. mg_uecc_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
  10967. mg_uecc_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */
  10968. mg_uecc_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
  10969. mg_uecc_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */
  10970. mg_uecc_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
  10971. mg_uecc_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
  10972. mg_uecc_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
  10973. mg_uecc_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */
  10974. mg_uecc_vli_modAdd(Z1, X1, X1, curve->p,
  10975. num_words); /* t3 = 2*(x1^2 - z1^4) */
  10976. mg_uecc_vli_modAdd(X1, X1, Z1, curve->p,
  10977. num_words); /* t1 = 3*(x1^2 - z1^4) */
  10978. if (mg_uecc_vli_testBit(X1, 0)) {
  10979. mg_uecc_word_t l_carry = mg_uecc_vli_add(X1, X1, curve->p, num_words);
  10980. mg_uecc_vli_rshift1(X1, num_words);
  10981. X1[num_words - 1] |= l_carry << (MG_UECC_WORD_BITS - 1);
  10982. } else {
  10983. mg_uecc_vli_rshift1(X1, num_words);
  10984. }
  10985. /* t1 = 3/2*(x1^2 - z1^4) = B */
  10986. mg_uecc_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */
  10987. mg_uecc_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
  10988. mg_uecc_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
  10989. mg_uecc_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
  10990. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */
  10991. mg_uecc_vli_modSub(t4, X1, t4, curve->p,
  10992. num_words); /* t4 = B * (A - x3) - y1^4 = y3 */
  10993. mg_uecc_vli_set(X1, Z1, num_words);
  10994. mg_uecc_vli_set(Z1, Y1, num_words);
  10995. mg_uecc_vli_set(Y1, t4, num_words);
  10996. }
  10997. /* Computes result = x^3 + ax + b. result must not overlap x. */
  10998. static void x_side_default(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  10999. MG_UECC_Curve curve) {
  11000. mg_uecc_word_t _3[MG_UECC_MAX_WORDS] = {3}; /* -a = 3 */
  11001. wordcount_t num_words = curve->num_words;
  11002. mg_uecc_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  11003. mg_uecc_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
  11004. mg_uecc_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */
  11005. mg_uecc_vli_modAdd(result, result, curve->b, curve->p,
  11006. num_words); /* r = x^3 - 3x + b */
  11007. }
  11008. #endif /* MG_UECC_SUPPORTS_secp... */
  11009. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11010. #if MG_UECC_SUPPORTS_secp160r1 || MG_UECC_SUPPORTS_secp192r1 || \
  11011. MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1
  11012. /* Compute a = sqrt(a) (mod curve_p). */
  11013. static void mod_sqrt_default(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  11014. bitcount_t i;
  11015. mg_uecc_word_t p1[MG_UECC_MAX_WORDS] = {1};
  11016. mg_uecc_word_t l_result[MG_UECC_MAX_WORDS] = {1};
  11017. wordcount_t num_words = curve->num_words;
  11018. /* When curve->p == 3 (mod 4), we can compute
  11019. sqrt(a) = a^((curve->p + 1) / 4) (mod curve->p). */
  11020. mg_uecc_vli_add(p1, curve->p, p1, num_words); /* p1 = curve_p + 1 */
  11021. for (i = mg_uecc_vli_numBits(p1, num_words) - 1; i > 1; --i) {
  11022. mg_uecc_vli_modSquare_fast(l_result, l_result, curve);
  11023. if (mg_uecc_vli_testBit(p1, i)) {
  11024. mg_uecc_vli_modMult_fast(l_result, l_result, a, curve);
  11025. }
  11026. }
  11027. mg_uecc_vli_set(a, l_result, num_words);
  11028. }
  11029. #endif /* MG_UECC_SUPPORTS_secp... */
  11030. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  11031. #if MG_UECC_SUPPORTS_secp160r1
  11032. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11033. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11034. mg_uecc_word_t *product);
  11035. #endif
  11036. static const struct MG_UECC_Curve_t curve_secp160r1 = {
  11037. num_words_secp160r1,
  11038. num_bytes_secp160r1,
  11039. 161, /* num_n_bits */
  11040. {BYTES_TO_WORDS_8(FF, FF, FF, 7F, FF, FF, FF, FF),
  11041. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11042. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11043. {BYTES_TO_WORDS_8(57, 22, 75, CA, D3, AE, 27, F9),
  11044. BYTES_TO_WORDS_8(C8, F4, 01, 00, 00, 00, 00, 00),
  11045. BYTES_TO_WORDS_8(00, 00, 00, 00, 01, 00, 00, 00)},
  11046. {BYTES_TO_WORDS_8(82, FC, CB, 13, B9, 8B, C3, 68),
  11047. BYTES_TO_WORDS_8(89, 69, 64, 46, 28, 73, F5, 8E),
  11048. BYTES_TO_WORDS_4(68, B5, 96, 4A),
  11049. BYTES_TO_WORDS_8(32, FB, C5, 7A, 37, 51, 23, 04),
  11050. BYTES_TO_WORDS_8(12, C9, DC, 59, 7D, 94, 68, 31),
  11051. BYTES_TO_WORDS_4(55, 28, A6, 23)},
  11052. {BYTES_TO_WORDS_8(45, FA, 65, C5, AD, D4, D4, 81),
  11053. BYTES_TO_WORDS_8(9F, F8, AC, 65, 8B, 7A, BD, 54),
  11054. BYTES_TO_WORDS_4(FC, BE, 97, 1C)},
  11055. &double_jacobian_default,
  11056. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11057. &mod_sqrt_default,
  11058. #endif
  11059. &x_side_default,
  11060. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11061. &vli_mmod_fast_secp160r1
  11062. #endif
  11063. };
  11064. MG_UECC_Curve mg_uecc_secp160r1(void) {
  11065. return &curve_secp160r1;
  11066. }
  11067. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1)
  11068. /* Computes result = product % curve_p
  11069. see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
  11070. Note that this only works if log2(omega) < log2(p) / 2 */
  11071. static void omega_mult_secp160r1(mg_uecc_word_t *result,
  11072. const mg_uecc_word_t *right);
  11073. #if MG_UECC_WORD_SIZE == 8
  11074. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11075. mg_uecc_word_t *product) {
  11076. mg_uecc_word_t tmp[2 * num_words_secp160r1];
  11077. mg_uecc_word_t copy;
  11078. mg_uecc_vli_clear(tmp, num_words_secp160r1);
  11079. mg_uecc_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  11080. omega_mult_secp160r1(tmp,
  11081. product + num_words_secp160r1 - 1); /* (Rq, q) = q * c */
  11082. product[num_words_secp160r1 - 1] &= 0xffffffff;
  11083. copy = tmp[num_words_secp160r1 - 1];
  11084. tmp[num_words_secp160r1 - 1] &= 0xffffffff;
  11085. mg_uecc_vli_add(result, product, tmp,
  11086. num_words_secp160r1); /* (C, r) = r + q */
  11087. mg_uecc_vli_clear(product, num_words_secp160r1);
  11088. tmp[num_words_secp160r1 - 1] = copy;
  11089. omega_mult_secp160r1(product, tmp + num_words_secp160r1 - 1); /* Rq*c */
  11090. mg_uecc_vli_add(result, result, product,
  11091. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  11092. while (mg_uecc_vli_cmp_unsafe(result, curve_secp160r1.p,
  11093. num_words_secp160r1) > 0) {
  11094. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11095. }
  11096. }
  11097. static void omega_mult_secp160r1(uint64_t *result, const uint64_t *right) {
  11098. uint32_t carry;
  11099. unsigned i;
  11100. /* Multiply by (2^31 + 1). */
  11101. carry = 0;
  11102. for (i = 0; i < num_words_secp160r1; ++i) {
  11103. uint64_t tmp = (right[i] >> 32) | (right[i + 1] << 32);
  11104. result[i] = (tmp << 31) + tmp + carry;
  11105. carry = (tmp >> 33) + (result[i] < tmp || (carry && result[i] == tmp));
  11106. }
  11107. result[i] = carry;
  11108. }
  11109. #else
  11110. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11111. mg_uecc_word_t *product) {
  11112. mg_uecc_word_t tmp[2 * num_words_secp160r1];
  11113. mg_uecc_word_t carry;
  11114. mg_uecc_vli_clear(tmp, num_words_secp160r1);
  11115. mg_uecc_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  11116. omega_mult_secp160r1(tmp,
  11117. product + num_words_secp160r1); /* (Rq, q) = q * c */
  11118. carry = mg_uecc_vli_add(result, product, tmp,
  11119. num_words_secp160r1); /* (C, r) = r + q */
  11120. mg_uecc_vli_clear(product, num_words_secp160r1);
  11121. omega_mult_secp160r1(product, tmp + num_words_secp160r1); /* Rq*c */
  11122. carry += mg_uecc_vli_add(result, result, product,
  11123. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  11124. while (carry > 0) {
  11125. --carry;
  11126. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11127. }
  11128. if (mg_uecc_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) >
  11129. 0) {
  11130. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11131. }
  11132. }
  11133. #endif
  11134. #if MG_UECC_WORD_SIZE == 1
  11135. static void omega_mult_secp160r1(uint8_t *result, const uint8_t *right) {
  11136. uint8_t carry;
  11137. uint8_t i;
  11138. /* Multiply by (2^31 + 1). */
  11139. mg_uecc_vli_set(result + 4, right, num_words_secp160r1); /* 2^32 */
  11140. mg_uecc_vli_rshift1(result + 4, num_words_secp160r1); /* 2^31 */
  11141. result[3] = right[0] << 7; /* get last bit from shift */
  11142. carry = mg_uecc_vli_add(result, result, right,
  11143. num_words_secp160r1); /* 2^31 + 1 */
  11144. for (i = num_words_secp160r1; carry; ++i) {
  11145. uint16_t sum = (uint16_t) result[i] + carry;
  11146. result[i] = (uint8_t) sum;
  11147. carry = sum >> 8;
  11148. }
  11149. }
  11150. #elif MG_UECC_WORD_SIZE == 4
  11151. static void omega_mult_secp160r1(uint32_t *result, const uint32_t *right) {
  11152. uint32_t carry;
  11153. unsigned i;
  11154. /* Multiply by (2^31 + 1). */
  11155. mg_uecc_vli_set(result + 1, right, num_words_secp160r1); /* 2^32 */
  11156. mg_uecc_vli_rshift1(result + 1, num_words_secp160r1); /* 2^31 */
  11157. result[0] = right[0] << 31; /* get last bit from shift */
  11158. carry = mg_uecc_vli_add(result, result, right,
  11159. num_words_secp160r1); /* 2^31 + 1 */
  11160. for (i = num_words_secp160r1; carry; ++i) {
  11161. uint64_t sum = (uint64_t) result[i] + carry;
  11162. result[i] = (uint32_t) sum;
  11163. carry = sum >> 32;
  11164. }
  11165. }
  11166. #endif /* MG_UECC_WORD_SIZE */
  11167. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) */
  11168. #endif /* MG_UECC_SUPPORTS_secp160r1 */
  11169. #if MG_UECC_SUPPORTS_secp192r1
  11170. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11171. static void vli_mmod_fast_secp192r1(mg_uecc_word_t *result,
  11172. mg_uecc_word_t *product);
  11173. #endif
  11174. static const struct MG_UECC_Curve_t curve_secp192r1 = {
  11175. num_words_secp192r1,
  11176. num_bytes_secp192r1,
  11177. 192, /* num_n_bits */
  11178. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11179. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  11180. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11181. {BYTES_TO_WORDS_8(31, 28, D2, B4, B1, C9, 6B, 14),
  11182. BYTES_TO_WORDS_8(36, F8, DE, 99, FF, FF, FF, FF),
  11183. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11184. {BYTES_TO_WORDS_8(12, 10, FF, 82, FD, 0A, FF, F4),
  11185. BYTES_TO_WORDS_8(00, 88, A1, 43, EB, 20, BF, 7C),
  11186. BYTES_TO_WORDS_8(F6, 90, 30, B0, 0E, A8, 8D, 18),
  11187. BYTES_TO_WORDS_8(11, 48, 79, 1E, A1, 77, F9, 73),
  11188. BYTES_TO_WORDS_8(D5, CD, 24, 6B, ED, 11, 10, 63),
  11189. BYTES_TO_WORDS_8(78, DA, C8, FF, 95, 2B, 19, 07)},
  11190. {BYTES_TO_WORDS_8(B1, B9, 46, C1, EC, DE, B8, FE),
  11191. BYTES_TO_WORDS_8(49, 30, 24, 72, AB, E9, A7, 0F),
  11192. BYTES_TO_WORDS_8(E7, 80, 9C, E5, 19, 05, 21, 64)},
  11193. &double_jacobian_default,
  11194. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11195. &mod_sqrt_default,
  11196. #endif
  11197. &x_side_default,
  11198. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11199. &vli_mmod_fast_secp192r1
  11200. #endif
  11201. };
  11202. MG_UECC_Curve mg_uecc_secp192r1(void) {
  11203. return &curve_secp192r1;
  11204. }
  11205. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11206. /* Computes result = product % curve_p.
  11207. See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf
  11208. */
  11209. #if MG_UECC_WORD_SIZE == 1
  11210. static void vli_mmod_fast_secp192r1(uint8_t *result, uint8_t *product) {
  11211. uint8_t tmp[num_words_secp192r1];
  11212. uint8_t carry;
  11213. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11214. mg_uecc_vli_set(tmp, &product[24], num_words_secp192r1);
  11215. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11216. tmp[0] = tmp[1] = tmp[2] = tmp[3] = tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11217. tmp[8] = product[24];
  11218. tmp[9] = product[25];
  11219. tmp[10] = product[26];
  11220. tmp[11] = product[27];
  11221. tmp[12] = product[28];
  11222. tmp[13] = product[29];
  11223. tmp[14] = product[30];
  11224. tmp[15] = product[31];
  11225. tmp[16] = product[32];
  11226. tmp[17] = product[33];
  11227. tmp[18] = product[34];
  11228. tmp[19] = product[35];
  11229. tmp[20] = product[36];
  11230. tmp[21] = product[37];
  11231. tmp[22] = product[38];
  11232. tmp[23] = product[39];
  11233. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11234. tmp[0] = tmp[8] = product[40];
  11235. tmp[1] = tmp[9] = product[41];
  11236. tmp[2] = tmp[10] = product[42];
  11237. tmp[3] = tmp[11] = product[43];
  11238. tmp[4] = tmp[12] = product[44];
  11239. tmp[5] = tmp[13] = product[45];
  11240. tmp[6] = tmp[14] = product[46];
  11241. tmp[7] = tmp[15] = product[47];
  11242. tmp[16] = tmp[17] = tmp[18] = tmp[19] = tmp[20] = tmp[21] = tmp[22] =
  11243. tmp[23] = 0;
  11244. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11245. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11246. num_words_secp192r1) != 1) {
  11247. carry -=
  11248. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11249. }
  11250. }
  11251. #elif MG_UECC_WORD_SIZE == 4
  11252. static void vli_mmod_fast_secp192r1(uint32_t *result, uint32_t *product) {
  11253. uint32_t tmp[num_words_secp192r1];
  11254. int carry;
  11255. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11256. mg_uecc_vli_set(tmp, &product[6], num_words_secp192r1);
  11257. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11258. tmp[0] = tmp[1] = 0;
  11259. tmp[2] = product[6];
  11260. tmp[3] = product[7];
  11261. tmp[4] = product[8];
  11262. tmp[5] = product[9];
  11263. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11264. tmp[0] = tmp[2] = product[10];
  11265. tmp[1] = tmp[3] = product[11];
  11266. tmp[4] = tmp[5] = 0;
  11267. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11268. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11269. num_words_secp192r1) != 1) {
  11270. carry -=
  11271. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11272. }
  11273. }
  11274. #else
  11275. static void vli_mmod_fast_secp192r1(uint64_t *result, uint64_t *product) {
  11276. uint64_t tmp[num_words_secp192r1];
  11277. int carry;
  11278. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11279. mg_uecc_vli_set(tmp, &product[3], num_words_secp192r1);
  11280. carry = (int) mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11281. tmp[0] = 0;
  11282. tmp[1] = product[3];
  11283. tmp[2] = product[4];
  11284. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11285. tmp[0] = tmp[1] = product[5];
  11286. tmp[2] = 0;
  11287. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11288. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11289. num_words_secp192r1) != 1) {
  11290. carry -=
  11291. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11292. }
  11293. }
  11294. #endif /* MG_UECC_WORD_SIZE */
  11295. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0) */
  11296. #endif /* MG_UECC_SUPPORTS_secp192r1 */
  11297. #if MG_UECC_SUPPORTS_secp224r1
  11298. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11299. static void mod_sqrt_secp224r1(mg_uecc_word_t *a, MG_UECC_Curve curve);
  11300. #endif
  11301. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11302. static void vli_mmod_fast_secp224r1(mg_uecc_word_t *result,
  11303. mg_uecc_word_t *product);
  11304. #endif
  11305. static const struct MG_UECC_Curve_t curve_secp224r1 = {
  11306. num_words_secp224r1,
  11307. num_bytes_secp224r1,
  11308. 224, /* num_n_bits */
  11309. {BYTES_TO_WORDS_8(01, 00, 00, 00, 00, 00, 00, 00),
  11310. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF),
  11311. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11312. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11313. {BYTES_TO_WORDS_8(3D, 2A, 5C, 5C, 45, 29, DD, 13),
  11314. BYTES_TO_WORDS_8(3E, F0, B8, E0, A2, 16, FF, FF),
  11315. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11316. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11317. {BYTES_TO_WORDS_8(21, 1D, 5C, 11, D6, 80, 32, 34),
  11318. BYTES_TO_WORDS_8(22, 11, C2, 56, D3, C1, 03, 4A),
  11319. BYTES_TO_WORDS_8(B9, 90, 13, 32, 7F, BF, B4, 6B),
  11320. BYTES_TO_WORDS_4(BD, 0C, 0E, B7),
  11321. BYTES_TO_WORDS_8(34, 7E, 00, 85, 99, 81, D5, 44),
  11322. BYTES_TO_WORDS_8(64, 47, 07, 5A, A0, 75, 43, CD),
  11323. BYTES_TO_WORDS_8(E6, DF, 22, 4C, FB, 23, F7, B5),
  11324. BYTES_TO_WORDS_4(88, 63, 37, BD)},
  11325. {BYTES_TO_WORDS_8(B4, FF, 55, 23, 43, 39, 0B, 27),
  11326. BYTES_TO_WORDS_8(BA, D8, BF, D7, B7, B0, 44, 50),
  11327. BYTES_TO_WORDS_8(56, 32, 41, F5, AB, B3, 04, 0C),
  11328. BYTES_TO_WORDS_4(85, 0A, 05, B4)},
  11329. &double_jacobian_default,
  11330. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11331. &mod_sqrt_secp224r1,
  11332. #endif
  11333. &x_side_default,
  11334. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11335. &vli_mmod_fast_secp224r1
  11336. #endif
  11337. };
  11338. MG_UECC_Curve mg_uecc_secp224r1(void) {
  11339. return &curve_secp224r1;
  11340. }
  11341. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11342. /* Routine 3.2.4 RS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11343. static void mod_sqrt_secp224r1_rs(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11344. mg_uecc_word_t *f1, const mg_uecc_word_t *d0,
  11345. const mg_uecc_word_t *e0,
  11346. const mg_uecc_word_t *f0) {
  11347. mg_uecc_word_t t[num_words_secp224r1];
  11348. mg_uecc_vli_modSquare_fast(t, d0, &curve_secp224r1); /* t <-- d0 ^ 2 */
  11349. mg_uecc_vli_modMult_fast(e1, d0, e0, &curve_secp224r1); /* e1 <-- d0 * e0 */
  11350. mg_uecc_vli_modAdd(d1, t, f0, curve_secp224r1.p,
  11351. num_words_secp224r1); /* d1 <-- t + f0 */
  11352. mg_uecc_vli_modAdd(e1, e1, e1, curve_secp224r1.p,
  11353. num_words_secp224r1); /* e1 <-- e1 + e1 */
  11354. mg_uecc_vli_modMult_fast(f1, t, f0, &curve_secp224r1); /* f1 <-- t * f0 */
  11355. mg_uecc_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  11356. num_words_secp224r1); /* f1 <-- f1 + f1 */
  11357. mg_uecc_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  11358. num_words_secp224r1); /* f1 <-- f1 + f1 */
  11359. }
  11360. /* Routine 3.2.5 RSS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11361. static void mod_sqrt_secp224r1_rss(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11362. mg_uecc_word_t *f1, const mg_uecc_word_t *d0,
  11363. const mg_uecc_word_t *e0,
  11364. const mg_uecc_word_t *f0,
  11365. const bitcount_t j) {
  11366. bitcount_t i;
  11367. mg_uecc_vli_set(d1, d0, num_words_secp224r1); /* d1 <-- d0 */
  11368. mg_uecc_vli_set(e1, e0, num_words_secp224r1); /* e1 <-- e0 */
  11369. mg_uecc_vli_set(f1, f0, num_words_secp224r1); /* f1 <-- f0 */
  11370. for (i = 1; i <= j; i++) {
  11371. mod_sqrt_secp224r1_rs(d1, e1, f1, d1, e1, f1); /* RS (d1,e1,f1,d1,e1,f1) */
  11372. }
  11373. }
  11374. /* Routine 3.2.6 RM; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11375. static void mod_sqrt_secp224r1_rm(mg_uecc_word_t *d2, mg_uecc_word_t *e2,
  11376. mg_uecc_word_t *f2, const mg_uecc_word_t *c,
  11377. const mg_uecc_word_t *d0,
  11378. const mg_uecc_word_t *e0,
  11379. const mg_uecc_word_t *d1,
  11380. const mg_uecc_word_t *e1) {
  11381. mg_uecc_word_t t1[num_words_secp224r1];
  11382. mg_uecc_word_t t2[num_words_secp224r1];
  11383. mg_uecc_vli_modMult_fast(t1, e0, e1, &curve_secp224r1); /* t1 <-- e0 * e1 */
  11384. mg_uecc_vli_modMult_fast(t1, t1, c, &curve_secp224r1); /* t1 <-- t1 * c */
  11385. /* t1 <-- p - t1 */
  11386. mg_uecc_vli_modSub(t1, curve_secp224r1.p, t1, curve_secp224r1.p,
  11387. num_words_secp224r1);
  11388. mg_uecc_vli_modMult_fast(t2, d0, d1, &curve_secp224r1); /* t2 <-- d0 * d1 */
  11389. mg_uecc_vli_modAdd(t2, t2, t1, curve_secp224r1.p,
  11390. num_words_secp224r1); /* t2 <-- t2 + t1 */
  11391. mg_uecc_vli_modMult_fast(t1, d0, e1, &curve_secp224r1); /* t1 <-- d0 * e1 */
  11392. mg_uecc_vli_modMult_fast(e2, d1, e0, &curve_secp224r1); /* e2 <-- d1 * e0 */
  11393. mg_uecc_vli_modAdd(e2, e2, t1, curve_secp224r1.p,
  11394. num_words_secp224r1); /* e2 <-- e2 + t1 */
  11395. mg_uecc_vli_modSquare_fast(f2, e2, &curve_secp224r1); /* f2 <-- e2^2 */
  11396. mg_uecc_vli_modMult_fast(f2, f2, c, &curve_secp224r1); /* f2 <-- f2 * c */
  11397. /* f2 <-- p - f2 */
  11398. mg_uecc_vli_modSub(f2, curve_secp224r1.p, f2, curve_secp224r1.p,
  11399. num_words_secp224r1);
  11400. mg_uecc_vli_set(d2, t2, num_words_secp224r1); /* d2 <-- t2 */
  11401. }
  11402. /* Routine 3.2.7 RP; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11403. static void mod_sqrt_secp224r1_rp(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11404. mg_uecc_word_t *f1, const mg_uecc_word_t *c,
  11405. const mg_uecc_word_t *r) {
  11406. wordcount_t i;
  11407. wordcount_t pow2i = 1;
  11408. mg_uecc_word_t d0[num_words_secp224r1];
  11409. mg_uecc_word_t e0[num_words_secp224r1] = {1}; /* e0 <-- 1 */
  11410. mg_uecc_word_t f0[num_words_secp224r1];
  11411. mg_uecc_vli_set(d0, r, num_words_secp224r1); /* d0 <-- r */
  11412. /* f0 <-- p - c */
  11413. mg_uecc_vli_modSub(f0, curve_secp224r1.p, c, curve_secp224r1.p,
  11414. num_words_secp224r1);
  11415. for (i = 0; i <= 6; i++) {
  11416. mod_sqrt_secp224r1_rss(d1, e1, f1, d0, e0, f0,
  11417. pow2i); /* RSS (d1,e1,f1,d0,e0,f0,2^i) */
  11418. mod_sqrt_secp224r1_rm(d1, e1, f1, c, d1, e1, d0,
  11419. e0); /* RM (d1,e1,f1,c,d1,e1,d0,e0) */
  11420. mg_uecc_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  11421. mg_uecc_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  11422. mg_uecc_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  11423. pow2i *= 2;
  11424. }
  11425. }
  11426. /* Compute a = sqrt(a) (mod curve_p). */
  11427. /* Routine 3.2.8 mp_mod_sqrt_224; from
  11428. * http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11429. static void mod_sqrt_secp224r1(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  11430. (void) curve;
  11431. bitcount_t i;
  11432. mg_uecc_word_t e1[num_words_secp224r1];
  11433. mg_uecc_word_t f1[num_words_secp224r1];
  11434. mg_uecc_word_t d0[num_words_secp224r1];
  11435. mg_uecc_word_t e0[num_words_secp224r1];
  11436. mg_uecc_word_t f0[num_words_secp224r1];
  11437. mg_uecc_word_t d1[num_words_secp224r1];
  11438. /* s = a; using constant instead of random value */
  11439. mod_sqrt_secp224r1_rp(d0, e0, f0, a, a); /* RP (d0, e0, f0, c, s) */
  11440. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  11441. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  11442. for (i = 1; i <= 95; i++) {
  11443. mg_uecc_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  11444. mg_uecc_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  11445. mg_uecc_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  11446. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  11447. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  11448. if (mg_uecc_vli_isZero(d1, num_words_secp224r1)) { /* if d1 == 0 */
  11449. break;
  11450. }
  11451. }
  11452. mg_uecc_vli_modInv(f1, e0, curve_secp224r1.p,
  11453. num_words_secp224r1); /* f1 <-- 1 / e0 */
  11454. mg_uecc_vli_modMult_fast(a, d0, f1, &curve_secp224r1); /* a <-- d0 / e0 */
  11455. }
  11456. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  11457. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11458. /* Computes result = product % curve_p
  11459. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11460. #if MG_UECC_WORD_SIZE == 1
  11461. static void vli_mmod_fast_secp224r1(uint8_t *result, uint8_t *product) {
  11462. uint8_t tmp[num_words_secp224r1];
  11463. int8_t carry;
  11464. /* t */
  11465. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11466. /* s1 */
  11467. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  11468. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11469. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  11470. tmp[12] = product[28];
  11471. tmp[13] = product[29];
  11472. tmp[14] = product[30];
  11473. tmp[15] = product[31];
  11474. tmp[16] = product[32];
  11475. tmp[17] = product[33];
  11476. tmp[18] = product[34];
  11477. tmp[19] = product[35];
  11478. tmp[20] = product[36];
  11479. tmp[21] = product[37];
  11480. tmp[22] = product[38];
  11481. tmp[23] = product[39];
  11482. tmp[24] = product[40];
  11483. tmp[25] = product[41];
  11484. tmp[26] = product[42];
  11485. tmp[27] = product[43];
  11486. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11487. /* s2 */
  11488. tmp[12] = product[44];
  11489. tmp[13] = product[45];
  11490. tmp[14] = product[46];
  11491. tmp[15] = product[47];
  11492. tmp[16] = product[48];
  11493. tmp[17] = product[49];
  11494. tmp[18] = product[50];
  11495. tmp[19] = product[51];
  11496. tmp[20] = product[52];
  11497. tmp[21] = product[53];
  11498. tmp[22] = product[54];
  11499. tmp[23] = product[55];
  11500. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  11501. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11502. /* d1 */
  11503. tmp[0] = product[28];
  11504. tmp[1] = product[29];
  11505. tmp[2] = product[30];
  11506. tmp[3] = product[31];
  11507. tmp[4] = product[32];
  11508. tmp[5] = product[33];
  11509. tmp[6] = product[34];
  11510. tmp[7] = product[35];
  11511. tmp[8] = product[36];
  11512. tmp[9] = product[37];
  11513. tmp[10] = product[38];
  11514. tmp[11] = product[39];
  11515. tmp[12] = product[40];
  11516. tmp[13] = product[41];
  11517. tmp[14] = product[42];
  11518. tmp[15] = product[43];
  11519. tmp[16] = product[44];
  11520. tmp[17] = product[45];
  11521. tmp[18] = product[46];
  11522. tmp[19] = product[47];
  11523. tmp[20] = product[48];
  11524. tmp[21] = product[49];
  11525. tmp[22] = product[50];
  11526. tmp[23] = product[51];
  11527. tmp[24] = product[52];
  11528. tmp[25] = product[53];
  11529. tmp[26] = product[54];
  11530. tmp[27] = product[55];
  11531. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11532. /* d2 */
  11533. tmp[0] = product[44];
  11534. tmp[1] = product[45];
  11535. tmp[2] = product[46];
  11536. tmp[3] = product[47];
  11537. tmp[4] = product[48];
  11538. tmp[5] = product[49];
  11539. tmp[6] = product[50];
  11540. tmp[7] = product[51];
  11541. tmp[8] = product[52];
  11542. tmp[9] = product[53];
  11543. tmp[10] = product[54];
  11544. tmp[11] = product[55];
  11545. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11546. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11547. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11548. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  11549. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11550. if (carry < 0) {
  11551. do {
  11552. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11553. num_words_secp224r1);
  11554. } while (carry < 0);
  11555. } else {
  11556. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11557. num_words_secp224r1) != 1) {
  11558. carry -= mg_uecc_vli_sub(result, result, curve_secp224r1.p,
  11559. num_words_secp224r1);
  11560. }
  11561. }
  11562. }
  11563. #elif MG_UECC_WORD_SIZE == 4
  11564. static void vli_mmod_fast_secp224r1(uint32_t *result, uint32_t *product) {
  11565. uint32_t tmp[num_words_secp224r1];
  11566. int carry;
  11567. /* t */
  11568. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11569. /* s1 */
  11570. tmp[0] = tmp[1] = tmp[2] = 0;
  11571. tmp[3] = product[7];
  11572. tmp[4] = product[8];
  11573. tmp[5] = product[9];
  11574. tmp[6] = product[10];
  11575. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11576. /* s2 */
  11577. tmp[3] = product[11];
  11578. tmp[4] = product[12];
  11579. tmp[5] = product[13];
  11580. tmp[6] = 0;
  11581. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11582. /* d1 */
  11583. tmp[0] = product[7];
  11584. tmp[1] = product[8];
  11585. tmp[2] = product[9];
  11586. tmp[3] = product[10];
  11587. tmp[4] = product[11];
  11588. tmp[5] = product[12];
  11589. tmp[6] = product[13];
  11590. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11591. /* d2 */
  11592. tmp[0] = product[11];
  11593. tmp[1] = product[12];
  11594. tmp[2] = product[13];
  11595. tmp[3] = tmp[4] = tmp[5] = tmp[6] = 0;
  11596. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11597. if (carry < 0) {
  11598. do {
  11599. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11600. num_words_secp224r1);
  11601. } while (carry < 0);
  11602. } else {
  11603. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11604. num_words_secp224r1) != 1) {
  11605. carry -= mg_uecc_vli_sub(result, result, curve_secp224r1.p,
  11606. num_words_secp224r1);
  11607. }
  11608. }
  11609. }
  11610. #else
  11611. static void vli_mmod_fast_secp224r1(uint64_t *result, uint64_t *product) {
  11612. uint64_t tmp[num_words_secp224r1];
  11613. int carry = 0;
  11614. /* t */
  11615. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11616. result[num_words_secp224r1 - 1] &= 0xffffffff;
  11617. /* s1 */
  11618. tmp[0] = 0;
  11619. tmp[1] = product[3] & 0xffffffff00000000ull;
  11620. tmp[2] = product[4];
  11621. tmp[3] = product[5] & 0xffffffff;
  11622. mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11623. /* s2 */
  11624. tmp[1] = product[5] & 0xffffffff00000000ull;
  11625. tmp[2] = product[6];
  11626. tmp[3] = 0;
  11627. mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11628. /* d1 */
  11629. tmp[0] = (product[3] >> 32) | (product[4] << 32);
  11630. tmp[1] = (product[4] >> 32) | (product[5] << 32);
  11631. tmp[2] = (product[5] >> 32) | (product[6] << 32);
  11632. tmp[3] = product[6] >> 32;
  11633. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11634. /* d2 */
  11635. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  11636. tmp[1] = product[6] >> 32;
  11637. tmp[2] = tmp[3] = 0;
  11638. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11639. if (carry < 0) {
  11640. do {
  11641. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11642. num_words_secp224r1);
  11643. } while (carry < 0);
  11644. } else {
  11645. while (mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11646. num_words_secp224r1) != 1) {
  11647. mg_uecc_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  11648. }
  11649. }
  11650. }
  11651. #endif /* MG_UECC_WORD_SIZE */
  11652. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0) */
  11653. #endif /* MG_UECC_SUPPORTS_secp224r1 */
  11654. #if MG_UECC_SUPPORTS_secp256r1
  11655. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11656. static void vli_mmod_fast_secp256r1(mg_uecc_word_t *result,
  11657. mg_uecc_word_t *product);
  11658. #endif
  11659. static const struct MG_UECC_Curve_t curve_secp256r1 = {
  11660. num_words_secp256r1,
  11661. num_bytes_secp256r1,
  11662. 256, /* num_n_bits */
  11663. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11664. BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00),
  11665. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  11666. BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF)},
  11667. {BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3),
  11668. BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC),
  11669. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11670. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF)},
  11671. {BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4),
  11672. BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77),
  11673. BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8),
  11674. BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B),
  11675. BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB),
  11676. BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B),
  11677. BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E),
  11678. BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F)},
  11679. {BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B),
  11680. BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65),
  11681. BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3),
  11682. BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A)},
  11683. &double_jacobian_default,
  11684. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11685. &mod_sqrt_default,
  11686. #endif
  11687. &x_side_default,
  11688. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11689. &vli_mmod_fast_secp256r1
  11690. #endif
  11691. };
  11692. MG_UECC_Curve mg_uecc_secp256r1(void) {
  11693. return &curve_secp256r1;
  11694. }
  11695. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1)
  11696. /* Computes result = product % curve_p
  11697. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11698. #if MG_UECC_WORD_SIZE == 1
  11699. static void vli_mmod_fast_secp256r1(uint8_t *result, uint8_t *product) {
  11700. uint8_t tmp[num_words_secp256r1];
  11701. int8_t carry;
  11702. /* t */
  11703. mg_uecc_vli_set(result, product, num_words_secp256r1);
  11704. /* s1 */
  11705. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  11706. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11707. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  11708. tmp[12] = product[44];
  11709. tmp[13] = product[45];
  11710. tmp[14] = product[46];
  11711. tmp[15] = product[47];
  11712. tmp[16] = product[48];
  11713. tmp[17] = product[49];
  11714. tmp[18] = product[50];
  11715. tmp[19] = product[51];
  11716. tmp[20] = product[52];
  11717. tmp[21] = product[53];
  11718. tmp[22] = product[54];
  11719. tmp[23] = product[55];
  11720. tmp[24] = product[56];
  11721. tmp[25] = product[57];
  11722. tmp[26] = product[58];
  11723. tmp[27] = product[59];
  11724. tmp[28] = product[60];
  11725. tmp[29] = product[61];
  11726. tmp[30] = product[62];
  11727. tmp[31] = product[63];
  11728. carry = mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  11729. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11730. /* s2 */
  11731. tmp[12] = product[48];
  11732. tmp[13] = product[49];
  11733. tmp[14] = product[50];
  11734. tmp[15] = product[51];
  11735. tmp[16] = product[52];
  11736. tmp[17] = product[53];
  11737. tmp[18] = product[54];
  11738. tmp[19] = product[55];
  11739. tmp[20] = product[56];
  11740. tmp[21] = product[57];
  11741. tmp[22] = product[58];
  11742. tmp[23] = product[59];
  11743. tmp[24] = product[60];
  11744. tmp[25] = product[61];
  11745. tmp[26] = product[62];
  11746. tmp[27] = product[63];
  11747. tmp[28] = tmp[29] = tmp[30] = tmp[31] = 0;
  11748. carry += mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  11749. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11750. /* s3 */
  11751. tmp[0] = product[32];
  11752. tmp[1] = product[33];
  11753. tmp[2] = product[34];
  11754. tmp[3] = product[35];
  11755. tmp[4] = product[36];
  11756. tmp[5] = product[37];
  11757. tmp[6] = product[38];
  11758. tmp[7] = product[39];
  11759. tmp[8] = product[40];
  11760. tmp[9] = product[41];
  11761. tmp[10] = product[42];
  11762. tmp[11] = product[43];
  11763. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11764. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11765. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11766. tmp[24] = product[56];
  11767. tmp[25] = product[57];
  11768. tmp[26] = product[58];
  11769. tmp[27] = product[59];
  11770. tmp[28] = product[60];
  11771. tmp[29] = product[61];
  11772. tmp[30] = product[62];
  11773. tmp[31] = product[63];
  11774. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11775. /* s4 */
  11776. tmp[0] = product[36];
  11777. tmp[1] = product[37];
  11778. tmp[2] = product[38];
  11779. tmp[3] = product[39];
  11780. tmp[4] = product[40];
  11781. tmp[5] = product[41];
  11782. tmp[6] = product[42];
  11783. tmp[7] = product[43];
  11784. tmp[8] = product[44];
  11785. tmp[9] = product[45];
  11786. tmp[10] = product[46];
  11787. tmp[11] = product[47];
  11788. tmp[12] = product[52];
  11789. tmp[13] = product[53];
  11790. tmp[14] = product[54];
  11791. tmp[15] = product[55];
  11792. tmp[16] = product[56];
  11793. tmp[17] = product[57];
  11794. tmp[18] = product[58];
  11795. tmp[19] = product[59];
  11796. tmp[20] = product[60];
  11797. tmp[21] = product[61];
  11798. tmp[22] = product[62];
  11799. tmp[23] = product[63];
  11800. tmp[24] = product[52];
  11801. tmp[25] = product[53];
  11802. tmp[26] = product[54];
  11803. tmp[27] = product[55];
  11804. tmp[28] = product[32];
  11805. tmp[29] = product[33];
  11806. tmp[30] = product[34];
  11807. tmp[31] = product[35];
  11808. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11809. /* d1 */
  11810. tmp[0] = product[44];
  11811. tmp[1] = product[45];
  11812. tmp[2] = product[46];
  11813. tmp[3] = product[47];
  11814. tmp[4] = product[48];
  11815. tmp[5] = product[49];
  11816. tmp[6] = product[50];
  11817. tmp[7] = product[51];
  11818. tmp[8] = product[52];
  11819. tmp[9] = product[53];
  11820. tmp[10] = product[54];
  11821. tmp[11] = product[55];
  11822. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11823. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11824. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11825. tmp[24] = product[32];
  11826. tmp[25] = product[33];
  11827. tmp[26] = product[34];
  11828. tmp[27] = product[35];
  11829. tmp[28] = product[40];
  11830. tmp[29] = product[41];
  11831. tmp[30] = product[42];
  11832. tmp[31] = product[43];
  11833. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11834. /* d2 */
  11835. tmp[0] = product[48];
  11836. tmp[1] = product[49];
  11837. tmp[2] = product[50];
  11838. tmp[3] = product[51];
  11839. tmp[4] = product[52];
  11840. tmp[5] = product[53];
  11841. tmp[6] = product[54];
  11842. tmp[7] = product[55];
  11843. tmp[8] = product[56];
  11844. tmp[9] = product[57];
  11845. tmp[10] = product[58];
  11846. tmp[11] = product[59];
  11847. tmp[12] = product[60];
  11848. tmp[13] = product[61];
  11849. tmp[14] = product[62];
  11850. tmp[15] = product[63];
  11851. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11852. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11853. tmp[24] = product[36];
  11854. tmp[25] = product[37];
  11855. tmp[26] = product[38];
  11856. tmp[27] = product[39];
  11857. tmp[28] = product[44];
  11858. tmp[29] = product[45];
  11859. tmp[30] = product[46];
  11860. tmp[31] = product[47];
  11861. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11862. /* d3 */
  11863. tmp[0] = product[52];
  11864. tmp[1] = product[53];
  11865. tmp[2] = product[54];
  11866. tmp[3] = product[55];
  11867. tmp[4] = product[56];
  11868. tmp[5] = product[57];
  11869. tmp[6] = product[58];
  11870. tmp[7] = product[59];
  11871. tmp[8] = product[60];
  11872. tmp[9] = product[61];
  11873. tmp[10] = product[62];
  11874. tmp[11] = product[63];
  11875. tmp[12] = product[32];
  11876. tmp[13] = product[33];
  11877. tmp[14] = product[34];
  11878. tmp[15] = product[35];
  11879. tmp[16] = product[36];
  11880. tmp[17] = product[37];
  11881. tmp[18] = product[38];
  11882. tmp[19] = product[39];
  11883. tmp[20] = product[40];
  11884. tmp[21] = product[41];
  11885. tmp[22] = product[42];
  11886. tmp[23] = product[43];
  11887. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  11888. tmp[28] = product[48];
  11889. tmp[29] = product[49];
  11890. tmp[30] = product[50];
  11891. tmp[31] = product[51];
  11892. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11893. /* d4 */
  11894. tmp[0] = product[56];
  11895. tmp[1] = product[57];
  11896. tmp[2] = product[58];
  11897. tmp[3] = product[59];
  11898. tmp[4] = product[60];
  11899. tmp[5] = product[61];
  11900. tmp[6] = product[62];
  11901. tmp[7] = product[63];
  11902. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  11903. tmp[12] = product[36];
  11904. tmp[13] = product[37];
  11905. tmp[14] = product[38];
  11906. tmp[15] = product[39];
  11907. tmp[16] = product[40];
  11908. tmp[17] = product[41];
  11909. tmp[18] = product[42];
  11910. tmp[19] = product[43];
  11911. tmp[20] = product[44];
  11912. tmp[21] = product[45];
  11913. tmp[22] = product[46];
  11914. tmp[23] = product[47];
  11915. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  11916. tmp[28] = product[52];
  11917. tmp[29] = product[53];
  11918. tmp[30] = product[54];
  11919. tmp[31] = product[55];
  11920. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11921. if (carry < 0) {
  11922. do {
  11923. carry += mg_uecc_vli_add(result, result, curve_secp256r1.p,
  11924. num_words_secp256r1);
  11925. } while (carry < 0);
  11926. } else {
  11927. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  11928. num_words_secp256r1) != 1) {
  11929. carry -= mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  11930. num_words_secp256r1);
  11931. }
  11932. }
  11933. }
  11934. #elif MG_UECC_WORD_SIZE == 4
  11935. static void vli_mmod_fast_secp256r1(uint32_t *result, uint32_t *product) {
  11936. uint32_t tmp[num_words_secp256r1];
  11937. int carry;
  11938. /* t */
  11939. mg_uecc_vli_set(result, product, num_words_secp256r1);
  11940. /* s1 */
  11941. tmp[0] = tmp[1] = tmp[2] = 0;
  11942. tmp[3] = product[11];
  11943. tmp[4] = product[12];
  11944. tmp[5] = product[13];
  11945. tmp[6] = product[14];
  11946. tmp[7] = product[15];
  11947. carry = (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  11948. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11949. /* s2 */
  11950. tmp[3] = product[12];
  11951. tmp[4] = product[13];
  11952. tmp[5] = product[14];
  11953. tmp[6] = product[15];
  11954. tmp[7] = 0;
  11955. carry += (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  11956. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11957. /* s3 */
  11958. tmp[0] = product[8];
  11959. tmp[1] = product[9];
  11960. tmp[2] = product[10];
  11961. tmp[3] = tmp[4] = tmp[5] = 0;
  11962. tmp[6] = product[14];
  11963. tmp[7] = product[15];
  11964. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11965. /* s4 */
  11966. tmp[0] = product[9];
  11967. tmp[1] = product[10];
  11968. tmp[2] = product[11];
  11969. tmp[3] = product[13];
  11970. tmp[4] = product[14];
  11971. tmp[5] = product[15];
  11972. tmp[6] = product[13];
  11973. tmp[7] = product[8];
  11974. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11975. /* d1 */
  11976. tmp[0] = product[11];
  11977. tmp[1] = product[12];
  11978. tmp[2] = product[13];
  11979. tmp[3] = tmp[4] = tmp[5] = 0;
  11980. tmp[6] = product[8];
  11981. tmp[7] = product[10];
  11982. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11983. /* d2 */
  11984. tmp[0] = product[12];
  11985. tmp[1] = product[13];
  11986. tmp[2] = product[14];
  11987. tmp[3] = product[15];
  11988. tmp[4] = tmp[5] = 0;
  11989. tmp[6] = product[9];
  11990. tmp[7] = product[11];
  11991. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11992. /* d3 */
  11993. tmp[0] = product[13];
  11994. tmp[1] = product[14];
  11995. tmp[2] = product[15];
  11996. tmp[3] = product[8];
  11997. tmp[4] = product[9];
  11998. tmp[5] = product[10];
  11999. tmp[6] = 0;
  12000. tmp[7] = product[12];
  12001. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12002. /* d4 */
  12003. tmp[0] = product[14];
  12004. tmp[1] = product[15];
  12005. tmp[2] = 0;
  12006. tmp[3] = product[9];
  12007. tmp[4] = product[10];
  12008. tmp[5] = product[11];
  12009. tmp[6] = 0;
  12010. tmp[7] = product[13];
  12011. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12012. if (carry < 0) {
  12013. do {
  12014. carry += (int) mg_uecc_vli_add(result, result, curve_secp256r1.p,
  12015. num_words_secp256r1);
  12016. } while (carry < 0);
  12017. } else {
  12018. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  12019. num_words_secp256r1) != 1) {
  12020. carry -= (int) mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  12021. num_words_secp256r1);
  12022. }
  12023. }
  12024. }
  12025. #else
  12026. static void vli_mmod_fast_secp256r1(uint64_t *result, uint64_t *product) {
  12027. uint64_t tmp[num_words_secp256r1];
  12028. int carry;
  12029. /* t */
  12030. mg_uecc_vli_set(result, product, num_words_secp256r1);
  12031. /* s1 */
  12032. tmp[0] = 0;
  12033. tmp[1] = product[5] & 0xffffffff00000000U;
  12034. tmp[2] = product[6];
  12035. tmp[3] = product[7];
  12036. carry = (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12037. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12038. /* s2 */
  12039. tmp[1] = product[6] << 32;
  12040. tmp[2] = (product[6] >> 32) | (product[7] << 32);
  12041. tmp[3] = product[7] >> 32;
  12042. carry += (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12043. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12044. /* s3 */
  12045. tmp[0] = product[4];
  12046. tmp[1] = product[5] & 0xffffffff;
  12047. tmp[2] = 0;
  12048. tmp[3] = product[7];
  12049. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12050. /* s4 */
  12051. tmp[0] = (product[4] >> 32) | (product[5] << 32);
  12052. tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000U);
  12053. tmp[2] = product[7];
  12054. tmp[3] = (product[6] >> 32) | (product[4] << 32);
  12055. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12056. /* d1 */
  12057. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  12058. tmp[1] = (product[6] >> 32);
  12059. tmp[2] = 0;
  12060. tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32);
  12061. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12062. /* d2 */
  12063. tmp[0] = product[6];
  12064. tmp[1] = product[7];
  12065. tmp[2] = 0;
  12066. tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000);
  12067. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12068. /* d3 */
  12069. tmp[0] = (product[6] >> 32) | (product[7] << 32);
  12070. tmp[1] = (product[7] >> 32) | (product[4] << 32);
  12071. tmp[2] = (product[4] >> 32) | (product[5] << 32);
  12072. tmp[3] = (product[6] << 32);
  12073. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12074. /* d4 */
  12075. tmp[0] = product[7];
  12076. tmp[1] = product[4] & 0xffffffff00000000U;
  12077. tmp[2] = product[5];
  12078. tmp[3] = product[6] & 0xffffffff00000000U;
  12079. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12080. if (carry < 0) {
  12081. do {
  12082. carry += (int) mg_uecc_vli_add(result, result, curve_secp256r1.p,
  12083. num_words_secp256r1);
  12084. } while (carry < 0);
  12085. } else {
  12086. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  12087. num_words_secp256r1) != 1) {
  12088. carry -= (int) mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  12089. num_words_secp256r1);
  12090. }
  12091. }
  12092. }
  12093. #endif /* MG_UECC_WORD_SIZE */
  12094. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) */
  12095. #endif /* MG_UECC_SUPPORTS_secp256r1 */
  12096. #if MG_UECC_SUPPORTS_secp256k1
  12097. static void double_jacobian_secp256k1(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12098. mg_uecc_word_t *Z1, MG_UECC_Curve curve);
  12099. static void x_side_secp256k1(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  12100. MG_UECC_Curve curve);
  12101. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12102. static void vli_mmod_fast_secp256k1(mg_uecc_word_t *result,
  12103. mg_uecc_word_t *product);
  12104. #endif
  12105. static const struct MG_UECC_Curve_t curve_secp256k1 = {
  12106. num_words_secp256k1,
  12107. num_bytes_secp256k1,
  12108. 256, /* num_n_bits */
  12109. {BYTES_TO_WORDS_8(2F, FC, FF, FF, FE, FF, FF, FF),
  12110. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12111. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12112. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  12113. {BYTES_TO_WORDS_8(41, 41, 36, D0, 8C, 5E, D2, BF),
  12114. BYTES_TO_WORDS_8(3B, A0, 48, AF, E6, DC, AE, BA),
  12115. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  12116. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  12117. {BYTES_TO_WORDS_8(98, 17, F8, 16, 5B, 81, F2, 59),
  12118. BYTES_TO_WORDS_8(D9, 28, CE, 2D, DB, FC, 9B, 02),
  12119. BYTES_TO_WORDS_8(07, 0B, 87, CE, 95, 62, A0, 55),
  12120. BYTES_TO_WORDS_8(AC, BB, DC, F9, 7E, 66, BE, 79),
  12121. BYTES_TO_WORDS_8(B8, D4, 10, FB, 8F, D0, 47, 9C),
  12122. BYTES_TO_WORDS_8(19, 54, 85, A6, 48, B4, 17, FD),
  12123. BYTES_TO_WORDS_8(A8, 08, 11, 0E, FC, FB, A4, 5D),
  12124. BYTES_TO_WORDS_8(65, C4, A3, 26, 77, DA, 3A, 48)},
  12125. {BYTES_TO_WORDS_8(07, 00, 00, 00, 00, 00, 00, 00),
  12126. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  12127. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  12128. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00)},
  12129. &double_jacobian_secp256k1,
  12130. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12131. &mod_sqrt_default,
  12132. #endif
  12133. &x_side_secp256k1,
  12134. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12135. &vli_mmod_fast_secp256k1
  12136. #endif
  12137. };
  12138. MG_UECC_Curve mg_uecc_secp256k1(void) {
  12139. return &curve_secp256k1;
  12140. }
  12141. /* Double in place */
  12142. static void double_jacobian_secp256k1(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12143. mg_uecc_word_t *Z1, MG_UECC_Curve curve) {
  12144. /* t1 = X, t2 = Y, t3 = Z */
  12145. mg_uecc_word_t t4[num_words_secp256k1];
  12146. mg_uecc_word_t t5[num_words_secp256k1];
  12147. if (mg_uecc_vli_isZero(Z1, num_words_secp256k1)) {
  12148. return;
  12149. }
  12150. mg_uecc_vli_modSquare_fast(t5, Y1, curve); /* t5 = y1^2 */
  12151. mg_uecc_vli_modMult_fast(t4, X1, t5, curve); /* t4 = x1*y1^2 = A */
  12152. mg_uecc_vli_modSquare_fast(X1, X1, curve); /* t1 = x1^2 */
  12153. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = y1^4 */
  12154. mg_uecc_vli_modMult_fast(Z1, Y1, Z1, curve); /* t3 = y1*z1 = z3 */
  12155. mg_uecc_vli_modAdd(Y1, X1, X1, curve->p,
  12156. num_words_secp256k1); /* t2 = 2*x1^2 */
  12157. mg_uecc_vli_modAdd(Y1, Y1, X1, curve->p,
  12158. num_words_secp256k1); /* t2 = 3*x1^2 */
  12159. if (mg_uecc_vli_testBit(Y1, 0)) {
  12160. mg_uecc_word_t carry =
  12161. mg_uecc_vli_add(Y1, Y1, curve->p, num_words_secp256k1);
  12162. mg_uecc_vli_rshift1(Y1, num_words_secp256k1);
  12163. Y1[num_words_secp256k1 - 1] |= carry << (MG_UECC_WORD_BITS - 1);
  12164. } else {
  12165. mg_uecc_vli_rshift1(Y1, num_words_secp256k1);
  12166. }
  12167. /* t2 = 3/2*(x1^2) = B */
  12168. mg_uecc_vli_modSquare_fast(X1, Y1, curve); /* t1 = B^2 */
  12169. mg_uecc_vli_modSub(X1, X1, t4, curve->p,
  12170. num_words_secp256k1); /* t1 = B^2 - A */
  12171. mg_uecc_vli_modSub(X1, X1, t4, curve->p,
  12172. num_words_secp256k1); /* t1 = B^2 - 2A = x3 */
  12173. mg_uecc_vli_modSub(t4, t4, X1, curve->p,
  12174. num_words_secp256k1); /* t4 = A - x3 */
  12175. mg_uecc_vli_modMult_fast(Y1, Y1, t4, curve); /* t2 = B * (A - x3) */
  12176. mg_uecc_vli_modSub(Y1, Y1, t5, curve->p,
  12177. num_words_secp256k1); /* t2 = B * (A - x3) - y1^4 = y3 */
  12178. }
  12179. /* Computes result = x^3 + b. result must not overlap x. */
  12180. static void x_side_secp256k1(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  12181. MG_UECC_Curve curve) {
  12182. mg_uecc_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  12183. mg_uecc_vli_modMult_fast(result, result, x, curve); /* r = x^3 */
  12184. mg_uecc_vli_modAdd(result, result, curve->b, curve->p,
  12185. num_words_secp256k1); /* r = x^3 + b */
  12186. }
  12187. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256k1)
  12188. static void omega_mult_secp256k1(mg_uecc_word_t *result,
  12189. const mg_uecc_word_t *right);
  12190. static void vli_mmod_fast_secp256k1(mg_uecc_word_t *result,
  12191. mg_uecc_word_t *product) {
  12192. mg_uecc_word_t tmp[2 * num_words_secp256k1];
  12193. mg_uecc_word_t carry;
  12194. mg_uecc_vli_clear(tmp, num_words_secp256k1);
  12195. mg_uecc_vli_clear(tmp + num_words_secp256k1, num_words_secp256k1);
  12196. omega_mult_secp256k1(tmp,
  12197. product + num_words_secp256k1); /* (Rq, q) = q * c */
  12198. carry = mg_uecc_vli_add(result, product, tmp,
  12199. num_words_secp256k1); /* (C, r) = r + q */
  12200. mg_uecc_vli_clear(product, num_words_secp256k1);
  12201. omega_mult_secp256k1(product, tmp + num_words_secp256k1); /* Rq*c */
  12202. carry += mg_uecc_vli_add(result, result, product,
  12203. num_words_secp256k1); /* (C1, r) = r + Rq*c */
  12204. while (carry > 0) {
  12205. --carry;
  12206. mg_uecc_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  12207. }
  12208. if (mg_uecc_vli_cmp_unsafe(result, curve_secp256k1.p, num_words_secp256k1) >
  12209. 0) {
  12210. mg_uecc_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  12211. }
  12212. }
  12213. #if MG_UECC_WORD_SIZE == 1
  12214. static void omega_mult_secp256k1(uint8_t *result, const uint8_t *right) {
  12215. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12216. mg_uecc_word_t r0 = 0;
  12217. mg_uecc_word_t r1 = 0;
  12218. mg_uecc_word_t r2 = 0;
  12219. wordcount_t k;
  12220. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12221. muladd(0xD1, right[0], &r0, &r1, &r2);
  12222. result[0] = r0;
  12223. r0 = r1;
  12224. r1 = r2;
  12225. /* r2 is still 0 */
  12226. for (k = 1; k < num_words_secp256k1; ++k) {
  12227. muladd(0x03, right[k - 1], &r0, &r1, &r2);
  12228. muladd(0xD1, right[k], &r0, &r1, &r2);
  12229. result[k] = r0;
  12230. r0 = r1;
  12231. r1 = r2;
  12232. r2 = 0;
  12233. }
  12234. muladd(0x03, right[num_words_secp256k1 - 1], &r0, &r1, &r2);
  12235. result[num_words_secp256k1] = r0;
  12236. result[num_words_secp256k1 + 1] = r1;
  12237. /* add the 2^32 multiple */
  12238. result[4 + num_words_secp256k1] =
  12239. mg_uecc_vli_add(result + 4, result + 4, right, num_words_secp256k1);
  12240. }
  12241. #elif MG_UECC_WORD_SIZE == 4
  12242. static void omega_mult_secp256k1(uint32_t *result, const uint32_t *right) {
  12243. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12244. uint32_t carry = 0;
  12245. wordcount_t k;
  12246. for (k = 0; k < num_words_secp256k1; ++k) {
  12247. uint64_t p = (uint64_t) 0x3D1 * right[k] + carry;
  12248. result[k] = (uint32_t) p;
  12249. carry = p >> 32;
  12250. }
  12251. result[num_words_secp256k1] = carry;
  12252. /* add the 2^32 multiple */
  12253. result[1 + num_words_secp256k1] =
  12254. mg_uecc_vli_add(result + 1, result + 1, right, num_words_secp256k1);
  12255. }
  12256. #else
  12257. static void omega_mult_secp256k1(uint64_t *result, const uint64_t *right) {
  12258. mg_uecc_word_t r0 = 0;
  12259. mg_uecc_word_t r1 = 0;
  12260. mg_uecc_word_t r2 = 0;
  12261. wordcount_t k;
  12262. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12263. for (k = 0; k < num_words_secp256k1; ++k) {
  12264. muladd(0x1000003D1ull, right[k], &r0, &r1, &r2);
  12265. result[k] = r0;
  12266. r0 = r1;
  12267. r1 = r2;
  12268. r2 = 0;
  12269. }
  12270. result[num_words_secp256k1] = r0;
  12271. }
  12272. #endif /* MG_UECC_WORD_SIZE */
  12273. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && && !asm_mmod_fast_secp256k1) */
  12274. #endif /* MG_UECC_SUPPORTS_secp256k1 */
  12275. #endif /* _UECC_CURVE_SPECIFIC_H_ */
  12276. /* Returns 1 if 'point' is the point at infinity, 0 otherwise. */
  12277. #define EccPoint_isZero(point, curve) \
  12278. mg_uecc_vli_isZero((point), (wordcount_t) ((curve)->num_words * 2))
  12279. /* Point multiplication algorithm using Montgomery's ladder with co-Z
  12280. coordinates. From http://eprint.iacr.org/2011/338.pdf
  12281. */
  12282. /* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
  12283. static void apply_z(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12284. const mg_uecc_word_t *const Z, MG_UECC_Curve curve) {
  12285. mg_uecc_word_t t1[MG_UECC_MAX_WORDS];
  12286. mg_uecc_vli_modSquare_fast(t1, Z, curve); /* z^2 */
  12287. mg_uecc_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
  12288. mg_uecc_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */
  12289. mg_uecc_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
  12290. }
  12291. /* P = (x1, y1) => 2P, (x2, y2) => P' */
  12292. static void XYcZ_initial_double(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12293. mg_uecc_word_t *X2, mg_uecc_word_t *Y2,
  12294. const mg_uecc_word_t *const initial_Z,
  12295. MG_UECC_Curve curve) {
  12296. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  12297. wordcount_t num_words = curve->num_words;
  12298. if (initial_Z) {
  12299. mg_uecc_vli_set(z, initial_Z, num_words);
  12300. } else {
  12301. mg_uecc_vli_clear(z, num_words);
  12302. z[0] = 1;
  12303. }
  12304. mg_uecc_vli_set(X2, X1, num_words);
  12305. mg_uecc_vli_set(Y2, Y1, num_words);
  12306. apply_z(X1, Y1, z, curve);
  12307. curve->double_jacobian(X1, Y1, z, curve);
  12308. apply_z(X2, Y2, z, curve);
  12309. }
  12310. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  12311. Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
  12312. or P => P', Q => P + Q
  12313. */
  12314. static void XYcZ_add(mg_uecc_word_t *X1, mg_uecc_word_t *Y1, mg_uecc_word_t *X2,
  12315. mg_uecc_word_t *Y2, MG_UECC_Curve curve) {
  12316. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  12317. mg_uecc_word_t t5[MG_UECC_MAX_WORDS] = {0};
  12318. wordcount_t num_words = curve->num_words;
  12319. mg_uecc_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  12320. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  12321. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  12322. mg_uecc_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  12323. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  12324. mg_uecc_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */
  12325. mg_uecc_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
  12326. mg_uecc_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
  12327. mg_uecc_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
  12328. mg_uecc_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */
  12329. mg_uecc_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
  12330. mg_uecc_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */
  12331. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
  12332. mg_uecc_vli_set(X2, t5, num_words);
  12333. }
  12334. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  12335. Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
  12336. or P => P - Q, Q => P + Q
  12337. */
  12338. static void XYcZ_addC(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12339. mg_uecc_word_t *X2, mg_uecc_word_t *Y2,
  12340. MG_UECC_Curve curve) {
  12341. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  12342. mg_uecc_word_t t5[MG_UECC_MAX_WORDS] = {0};
  12343. mg_uecc_word_t t6[MG_UECC_MAX_WORDS];
  12344. mg_uecc_word_t t7[MG_UECC_MAX_WORDS];
  12345. wordcount_t num_words = curve->num_words;
  12346. mg_uecc_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  12347. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  12348. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  12349. mg_uecc_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  12350. mg_uecc_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
  12351. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  12352. mg_uecc_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
  12353. mg_uecc_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */
  12354. mg_uecc_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
  12355. mg_uecc_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */
  12356. mg_uecc_vli_modSub(X2, X2, t6, curve->p,
  12357. num_words); /* t3 = D - (B + C) = x3 */
  12358. mg_uecc_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
  12359. mg_uecc_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */
  12360. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p,
  12361. num_words); /* t4 = (y2 - y1)*(B - x3) - E = y3 */
  12362. mg_uecc_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */
  12363. mg_uecc_vli_modSub(t7, t7, t6, curve->p,
  12364. num_words); /* t7 = F - (B + C) = x3' */
  12365. mg_uecc_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
  12366. mg_uecc_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */
  12367. mg_uecc_vli_modSub(Y1, t6, Y1, curve->p,
  12368. num_words); /* t2 = (y2+y1)*(x3' - B) - E = y3' */
  12369. mg_uecc_vli_set(X1, t7, num_words);
  12370. }
  12371. /* result may overlap point. */
  12372. static void EccPoint_mult(mg_uecc_word_t *result, const mg_uecc_word_t *point,
  12373. const mg_uecc_word_t *scalar,
  12374. const mg_uecc_word_t *initial_Z, bitcount_t num_bits,
  12375. MG_UECC_Curve curve) {
  12376. /* R0 and R1 */
  12377. mg_uecc_word_t Rx[2][MG_UECC_MAX_WORDS];
  12378. mg_uecc_word_t Ry[2][MG_UECC_MAX_WORDS];
  12379. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  12380. bitcount_t i;
  12381. mg_uecc_word_t nb;
  12382. wordcount_t num_words = curve->num_words;
  12383. mg_uecc_vli_set(Rx[1], point, num_words);
  12384. mg_uecc_vli_set(Ry[1], point + num_words, num_words);
  12385. XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
  12386. for (i = num_bits - 2; i > 0; --i) {
  12387. nb = !mg_uecc_vli_testBit(scalar, i);
  12388. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  12389. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  12390. }
  12391. nb = !mg_uecc_vli_testBit(scalar, 0);
  12392. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  12393. /* Find final 1/Z value. */
  12394. mg_uecc_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
  12395. mg_uecc_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */
  12396. mg_uecc_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */
  12397. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0)) */
  12398. /* yP / (xP * Yb * (X1 - X0)) */
  12399. mg_uecc_vli_modMult_fast(z, z, point + num_words, curve);
  12400. mg_uecc_vli_modMult_fast(z, z, Rx[1 - nb],
  12401. curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */
  12402. /* End 1/Z calculation */
  12403. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  12404. apply_z(Rx[0], Ry[0], z, curve);
  12405. mg_uecc_vli_set(result, Rx[0], num_words);
  12406. mg_uecc_vli_set(result + num_words, Ry[0], num_words);
  12407. }
  12408. static mg_uecc_word_t regularize_k(const mg_uecc_word_t *const k,
  12409. mg_uecc_word_t *k0, mg_uecc_word_t *k1,
  12410. MG_UECC_Curve curve) {
  12411. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12412. bitcount_t num_n_bits = curve->num_n_bits;
  12413. mg_uecc_word_t carry =
  12414. mg_uecc_vli_add(k0, k, curve->n, num_n_words) ||
  12415. (num_n_bits < ((bitcount_t) num_n_words * MG_UECC_WORD_SIZE * 8) &&
  12416. mg_uecc_vli_testBit(k0, num_n_bits));
  12417. mg_uecc_vli_add(k1, k0, curve->n, num_n_words);
  12418. return carry;
  12419. }
  12420. /* Generates a random integer in the range 0 < random < top.
  12421. Both random and top have num_words words. */
  12422. MG_UECC_VLI_API int mg_uecc_generate_random_int(mg_uecc_word_t *random,
  12423. const mg_uecc_word_t *top,
  12424. wordcount_t num_words) {
  12425. mg_uecc_word_t mask = (mg_uecc_word_t) -1;
  12426. mg_uecc_word_t tries;
  12427. bitcount_t num_bits = mg_uecc_vli_numBits(top, num_words);
  12428. if (!g_rng_function) {
  12429. return 0;
  12430. }
  12431. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12432. if (!g_rng_function((uint8_t *) random,
  12433. (unsigned int) (num_words * MG_UECC_WORD_SIZE))) {
  12434. return 0;
  12435. }
  12436. random[num_words - 1] &=
  12437. mask >> ((bitcount_t) (num_words * MG_UECC_WORD_SIZE * 8 - num_bits));
  12438. if (!mg_uecc_vli_isZero(random, num_words) &&
  12439. mg_uecc_vli_cmp(top, random, num_words) == 1) {
  12440. return 1;
  12441. }
  12442. }
  12443. return 0;
  12444. }
  12445. static mg_uecc_word_t EccPoint_compute_public_key(mg_uecc_word_t *result,
  12446. mg_uecc_word_t *private_key,
  12447. MG_UECC_Curve curve) {
  12448. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  12449. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  12450. mg_uecc_word_t *p2[2] = {tmp1, tmp2};
  12451. mg_uecc_word_t *initial_Z = 0;
  12452. mg_uecc_word_t carry;
  12453. /* Regularize the bitcount for the private key so that attackers cannot use a
  12454. side channel attack to learn the number of leading zeros. */
  12455. carry = regularize_k(private_key, tmp1, tmp2, curve);
  12456. /* If an RNG function was specified, try to get a random initial Z value to
  12457. improve protection against side-channel attacks. */
  12458. if (g_rng_function) {
  12459. if (!mg_uecc_generate_random_int(p2[carry], curve->p, curve->num_words)) {
  12460. return 0;
  12461. }
  12462. initial_Z = p2[carry];
  12463. }
  12464. EccPoint_mult(result, curve->G, p2[!carry], initial_Z,
  12465. (bitcount_t) (curve->num_n_bits + 1), curve);
  12466. if (EccPoint_isZero(result, curve)) {
  12467. return 0;
  12468. }
  12469. return 1;
  12470. }
  12471. #if MG_UECC_WORD_SIZE == 1
  12472. MG_UECC_VLI_API void mg_uecc_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  12473. const uint8_t *native) {
  12474. wordcount_t i;
  12475. for (i = 0; i < num_bytes; ++i) {
  12476. bytes[i] = native[(num_bytes - 1) - i];
  12477. }
  12478. }
  12479. MG_UECC_VLI_API void mg_uecc_vli_bytesToNative(uint8_t *native,
  12480. const uint8_t *bytes,
  12481. int num_bytes) {
  12482. mg_uecc_vli_nativeToBytes(native, num_bytes, bytes);
  12483. }
  12484. #else
  12485. MG_UECC_VLI_API void mg_uecc_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  12486. const mg_uecc_word_t *native) {
  12487. int i;
  12488. for (i = 0; i < num_bytes; ++i) {
  12489. unsigned b = (unsigned) (num_bytes - 1 - i);
  12490. bytes[i] = (uint8_t) (native[b / MG_UECC_WORD_SIZE] >>
  12491. (8 * (b % MG_UECC_WORD_SIZE)));
  12492. }
  12493. }
  12494. MG_UECC_VLI_API void mg_uecc_vli_bytesToNative(mg_uecc_word_t *native,
  12495. const uint8_t *bytes,
  12496. int num_bytes) {
  12497. int i;
  12498. mg_uecc_vli_clear(native,
  12499. (wordcount_t) ((num_bytes + (MG_UECC_WORD_SIZE - 1)) /
  12500. MG_UECC_WORD_SIZE));
  12501. for (i = 0; i < num_bytes; ++i) {
  12502. unsigned b = (unsigned) (num_bytes - 1 - i);
  12503. native[b / MG_UECC_WORD_SIZE] |= (mg_uecc_word_t) bytes[i]
  12504. << (8 * (b % MG_UECC_WORD_SIZE));
  12505. }
  12506. }
  12507. #endif /* MG_UECC_WORD_SIZE */
  12508. int mg_uecc_make_key(uint8_t *public_key, uint8_t *private_key,
  12509. MG_UECC_Curve curve) {
  12510. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12511. mg_uecc_word_t *_private = (mg_uecc_word_t *) private_key;
  12512. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12513. #else
  12514. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12515. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12516. #endif
  12517. mg_uecc_word_t tries;
  12518. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12519. if (!mg_uecc_generate_random_int(_private, curve->n,
  12520. BITS_TO_WORDS(curve->num_n_bits))) {
  12521. return 0;
  12522. }
  12523. if (EccPoint_compute_public_key(_public, _private, curve)) {
  12524. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12525. mg_uecc_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits),
  12526. _private);
  12527. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  12528. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  12529. _public + curve->num_words);
  12530. #endif
  12531. return 1;
  12532. }
  12533. }
  12534. return 0;
  12535. }
  12536. int mg_uecc_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
  12537. uint8_t *secret, MG_UECC_Curve curve) {
  12538. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12539. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12540. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  12541. mg_uecc_word_t *p2[2] = {_private, tmp};
  12542. mg_uecc_word_t *initial_Z = 0;
  12543. mg_uecc_word_t carry;
  12544. wordcount_t num_words = curve->num_words;
  12545. wordcount_t num_bytes = curve->num_bytes;
  12546. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12547. bcopy((uint8_t *) _private, private_key, num_bytes);
  12548. bcopy((uint8_t *) _public, public_key, num_bytes * 2);
  12549. #else
  12550. mg_uecc_vli_bytesToNative(_private, private_key,
  12551. BITS_TO_BYTES(curve->num_n_bits));
  12552. mg_uecc_vli_bytesToNative(_public, public_key, num_bytes);
  12553. mg_uecc_vli_bytesToNative(_public + num_words, public_key + num_bytes,
  12554. num_bytes);
  12555. #endif
  12556. /* Regularize the bitcount for the private key so that attackers cannot use a
  12557. side channel attack to learn the number of leading zeros. */
  12558. carry = regularize_k(_private, _private, tmp, curve);
  12559. /* If an RNG function was specified, try to get a random initial Z value to
  12560. improve protection against side-channel attacks. */
  12561. if (g_rng_function) {
  12562. if (!mg_uecc_generate_random_int(p2[carry], curve->p, num_words)) {
  12563. return 0;
  12564. }
  12565. initial_Z = p2[carry];
  12566. }
  12567. EccPoint_mult(_public, _public, p2[!carry], initial_Z,
  12568. (bitcount_t) (curve->num_n_bits + 1), curve);
  12569. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12570. bcopy((uint8_t *) secret, (uint8_t *) _public, num_bytes);
  12571. #else
  12572. mg_uecc_vli_nativeToBytes(secret, num_bytes, _public);
  12573. #endif
  12574. return !EccPoint_isZero(_public, curve);
  12575. }
  12576. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12577. void mg_uecc_compress(const uint8_t *public_key, uint8_t *compressed,
  12578. MG_UECC_Curve curve) {
  12579. wordcount_t i;
  12580. for (i = 0; i < curve->num_bytes; ++i) {
  12581. compressed[i + 1] = public_key[i];
  12582. }
  12583. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12584. compressed[0] = 2 + (public_key[curve->num_bytes] & 0x01);
  12585. #else
  12586. compressed[0] = 2 + (public_key[curve->num_bytes * 2 - 1] & 0x01);
  12587. #endif
  12588. }
  12589. void mg_uecc_decompress(const uint8_t *compressed, uint8_t *public_key,
  12590. MG_UECC_Curve curve) {
  12591. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12592. mg_uecc_word_t *point = (mg_uecc_word_t *) public_key;
  12593. #else
  12594. mg_uecc_word_t point[MG_UECC_MAX_WORDS * 2];
  12595. #endif
  12596. mg_uecc_word_t *y = point + curve->num_words;
  12597. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12598. bcopy(public_key, compressed + 1, curve->num_bytes);
  12599. #else
  12600. mg_uecc_vli_bytesToNative(point, compressed + 1, curve->num_bytes);
  12601. #endif
  12602. curve->x_side(y, point, curve);
  12603. curve->mod_sqrt(y, curve);
  12604. if ((uint8_t) (y[0] & 0x01) != (compressed[0] & 0x01)) {
  12605. mg_uecc_vli_sub(y, curve->p, y, curve->num_words);
  12606. }
  12607. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12608. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, point);
  12609. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, y);
  12610. #endif
  12611. }
  12612. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  12613. MG_UECC_VLI_API int mg_uecc_valid_point(const mg_uecc_word_t *point,
  12614. MG_UECC_Curve curve) {
  12615. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  12616. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  12617. wordcount_t num_words = curve->num_words;
  12618. /* The point at infinity is invalid. */
  12619. if (EccPoint_isZero(point, curve)) {
  12620. return 0;
  12621. }
  12622. /* x and y must be smaller than p. */
  12623. if (mg_uecc_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
  12624. mg_uecc_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
  12625. return 0;
  12626. }
  12627. mg_uecc_vli_modSquare_fast(tmp1, point + num_words, curve);
  12628. curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
  12629. /* Make sure that y^2 == x^3 + ax + b */
  12630. return (int) (mg_uecc_vli_equal(tmp1, tmp2, num_words));
  12631. }
  12632. int mg_uecc_valid_public_key(const uint8_t *public_key, MG_UECC_Curve curve) {
  12633. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12634. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12635. #else
  12636. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12637. #endif
  12638. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12639. mg_uecc_vli_bytesToNative(_public, public_key, curve->num_bytes);
  12640. mg_uecc_vli_bytesToNative(_public + curve->num_words,
  12641. public_key + curve->num_bytes, curve->num_bytes);
  12642. #endif
  12643. return mg_uecc_valid_point(_public, curve);
  12644. }
  12645. int mg_uecc_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
  12646. MG_UECC_Curve curve) {
  12647. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12648. mg_uecc_word_t *_private = (mg_uecc_word_t *) private_key;
  12649. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12650. #else
  12651. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12652. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12653. #endif
  12654. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12655. mg_uecc_vli_bytesToNative(_private, private_key,
  12656. BITS_TO_BYTES(curve->num_n_bits));
  12657. #endif
  12658. /* Make sure the private key is in the range [1, n-1]. */
  12659. if (mg_uecc_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
  12660. return 0;
  12661. }
  12662. if (mg_uecc_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) !=
  12663. 1) {
  12664. return 0;
  12665. }
  12666. /* Compute public key. */
  12667. if (!EccPoint_compute_public_key(_public, _private, curve)) {
  12668. return 0;
  12669. }
  12670. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12671. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  12672. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  12673. _public + curve->num_words);
  12674. #endif
  12675. return 1;
  12676. }
  12677. /* -------- ECDSA code -------- */
  12678. static void bits2int(mg_uecc_word_t *native, const uint8_t *bits,
  12679. unsigned bits_size, MG_UECC_Curve curve) {
  12680. unsigned num_n_bytes = (unsigned) BITS_TO_BYTES(curve->num_n_bits);
  12681. unsigned num_n_words = (unsigned) BITS_TO_WORDS(curve->num_n_bits);
  12682. int shift;
  12683. mg_uecc_word_t carry;
  12684. mg_uecc_word_t *ptr;
  12685. if (bits_size > num_n_bytes) {
  12686. bits_size = num_n_bytes;
  12687. }
  12688. mg_uecc_vli_clear(native, (wordcount_t) num_n_words);
  12689. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12690. bcopy((uint8_t *) native, bits, bits_size);
  12691. #else
  12692. mg_uecc_vli_bytesToNative(native, bits, (int) bits_size);
  12693. #endif
  12694. if (bits_size * 8 <= (unsigned) curve->num_n_bits) {
  12695. return;
  12696. }
  12697. shift = (int) bits_size * 8 - curve->num_n_bits;
  12698. carry = 0;
  12699. ptr = native + num_n_words;
  12700. while (ptr-- > native) {
  12701. mg_uecc_word_t temp = *ptr;
  12702. *ptr = (temp >> shift) | carry;
  12703. carry = temp << (MG_UECC_WORD_BITS - shift);
  12704. }
  12705. /* Reduce mod curve_n */
  12706. if (mg_uecc_vli_cmp_unsafe(curve->n, native, (wordcount_t) num_n_words) !=
  12707. 1) {
  12708. mg_uecc_vli_sub(native, native, curve->n, (wordcount_t) num_n_words);
  12709. }
  12710. }
  12711. static int mg_uecc_sign_with_k_internal(const uint8_t *private_key,
  12712. const uint8_t *message_hash,
  12713. unsigned hash_size, mg_uecc_word_t *k,
  12714. uint8_t *signature,
  12715. MG_UECC_Curve curve) {
  12716. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  12717. mg_uecc_word_t s[MG_UECC_MAX_WORDS];
  12718. mg_uecc_word_t *k2[2] = {tmp, s};
  12719. mg_uecc_word_t *initial_Z = 0;
  12720. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12721. mg_uecc_word_t *p = (mg_uecc_word_t *) signature;
  12722. #else
  12723. mg_uecc_word_t p[MG_UECC_MAX_WORDS * 2];
  12724. #endif
  12725. mg_uecc_word_t carry;
  12726. wordcount_t num_words = curve->num_words;
  12727. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12728. bitcount_t num_n_bits = curve->num_n_bits;
  12729. /* Make sure 0 < k < curve_n */
  12730. if (mg_uecc_vli_isZero(k, num_words) ||
  12731. mg_uecc_vli_cmp(curve->n, k, num_n_words) != 1) {
  12732. return 0;
  12733. }
  12734. carry = regularize_k(k, tmp, s, curve);
  12735. /* If an RNG function was specified, try to get a random initial Z value to
  12736. improve protection against side-channel attacks. */
  12737. if (g_rng_function) {
  12738. if (!mg_uecc_generate_random_int(k2[carry], curve->p, num_words)) {
  12739. return 0;
  12740. }
  12741. initial_Z = k2[carry];
  12742. }
  12743. EccPoint_mult(p, curve->G, k2[!carry], initial_Z,
  12744. (bitcount_t) (num_n_bits + 1), curve);
  12745. if (mg_uecc_vli_isZero(p, num_words)) {
  12746. return 0;
  12747. }
  12748. /* If an RNG function was specified, get a random number
  12749. to prevent side channel analysis of k. */
  12750. if (!g_rng_function) {
  12751. mg_uecc_vli_clear(tmp, num_n_words);
  12752. tmp[0] = 1;
  12753. } else if (!mg_uecc_generate_random_int(tmp, curve->n, num_n_words)) {
  12754. return 0;
  12755. }
  12756. /* Prevent side channel analysis of mg_uecc_vli_modInv() to determine
  12757. bits of k / the private key by premultiplying by a random number */
  12758. mg_uecc_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
  12759. mg_uecc_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */
  12760. mg_uecc_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
  12761. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12762. mg_uecc_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
  12763. #endif
  12764. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12765. bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
  12766. #else
  12767. mg_uecc_vli_bytesToNative(tmp, private_key,
  12768. BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */
  12769. #endif
  12770. s[num_n_words - 1] = 0;
  12771. mg_uecc_vli_set(s, p, num_words);
  12772. mg_uecc_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
  12773. bits2int(tmp, message_hash, hash_size, curve);
  12774. mg_uecc_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
  12775. mg_uecc_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */
  12776. if (mg_uecc_vli_numBits(s, num_n_words) > (bitcount_t) curve->num_bytes * 8) {
  12777. return 0;
  12778. }
  12779. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12780. bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s,
  12781. curve->num_bytes);
  12782. #else
  12783. mg_uecc_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
  12784. #endif
  12785. return 1;
  12786. }
  12787. #if 0
  12788. /* For testing - sign with an explicitly specified k value */
  12789. int mg_uecc_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
  12790. unsigned hash_size, const uint8_t *k, uint8_t *signature,
  12791. MG_UECC_Curve curve) {
  12792. mg_uecc_word_t k2[MG_UECC_MAX_WORDS];
  12793. bits2int(k2, k, (unsigned) BITS_TO_BYTES(curve->num_n_bits), curve);
  12794. return mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, k2,
  12795. signature, curve);
  12796. }
  12797. #endif
  12798. int mg_uecc_sign(const uint8_t *private_key, const uint8_t *message_hash,
  12799. unsigned hash_size, uint8_t *signature, MG_UECC_Curve curve) {
  12800. mg_uecc_word_t k[MG_UECC_MAX_WORDS];
  12801. mg_uecc_word_t tries;
  12802. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12803. if (!mg_uecc_generate_random_int(k, curve->n,
  12804. BITS_TO_WORDS(curve->num_n_bits))) {
  12805. return 0;
  12806. }
  12807. if (mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, k,
  12808. signature, curve)) {
  12809. return 1;
  12810. }
  12811. }
  12812. return 0;
  12813. }
  12814. /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always
  12815. the same size as the hash result size. */
  12816. static void HMAC_init(const MG_UECC_HashContext *hash_context,
  12817. const uint8_t *K) {
  12818. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  12819. unsigned i;
  12820. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x36;
  12821. for (; i < hash_context->block_size; ++i) pad[i] = 0x36;
  12822. hash_context->init_hash(hash_context);
  12823. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  12824. }
  12825. static void HMAC_update(const MG_UECC_HashContext *hash_context,
  12826. const uint8_t *message, unsigned message_size) {
  12827. hash_context->update_hash(hash_context, message, message_size);
  12828. }
  12829. static void HMAC_finish(const MG_UECC_HashContext *hash_context,
  12830. const uint8_t *K, uint8_t *result) {
  12831. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  12832. unsigned i;
  12833. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x5c;
  12834. for (; i < hash_context->block_size; ++i) pad[i] = 0x5c;
  12835. hash_context->finish_hash(hash_context, result);
  12836. hash_context->init_hash(hash_context);
  12837. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  12838. hash_context->update_hash(hash_context, result, hash_context->result_size);
  12839. hash_context->finish_hash(hash_context, result);
  12840. }
  12841. /* V = HMAC_K(V) */
  12842. static void update_V(const MG_UECC_HashContext *hash_context, uint8_t *K,
  12843. uint8_t *V) {
  12844. HMAC_init(hash_context, K);
  12845. HMAC_update(hash_context, V, hash_context->result_size);
  12846. HMAC_finish(hash_context, K, V);
  12847. }
  12848. /* Deterministic signing, similar to RFC 6979. Differences are:
  12849. * We just use H(m) directly rather than bits2octets(H(m))
  12850. (it is not reduced modulo curve_n).
  12851. * We generate a value for k (aka T) directly rather than converting
  12852. endianness.
  12853. Layout of hash_context->tmp: <K> | <V> | (1 byte overlapped 0x00 or 0x01) /
  12854. <HMAC pad> */
  12855. int mg_uecc_sign_deterministic(const uint8_t *private_key,
  12856. const uint8_t *message_hash, unsigned hash_size,
  12857. const MG_UECC_HashContext *hash_context,
  12858. uint8_t *signature, MG_UECC_Curve curve) {
  12859. uint8_t *K = hash_context->tmp;
  12860. uint8_t *V = K + hash_context->result_size;
  12861. wordcount_t num_bytes = curve->num_bytes;
  12862. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12863. bitcount_t num_n_bits = curve->num_n_bits;
  12864. mg_uecc_word_t tries;
  12865. unsigned i;
  12866. for (i = 0; i < hash_context->result_size; ++i) {
  12867. V[i] = 0x01;
  12868. K[i] = 0;
  12869. }
  12870. /* K = HMAC_K(V || 0x00 || int2octets(x) || h(m)) */
  12871. HMAC_init(hash_context, K);
  12872. V[hash_context->result_size] = 0x00;
  12873. HMAC_update(hash_context, V, hash_context->result_size + 1);
  12874. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  12875. HMAC_update(hash_context, message_hash, hash_size);
  12876. HMAC_finish(hash_context, K, K);
  12877. update_V(hash_context, K, V);
  12878. /* K = HMAC_K(V || 0x01 || int2octets(x) || h(m)) */
  12879. HMAC_init(hash_context, K);
  12880. V[hash_context->result_size] = 0x01;
  12881. HMAC_update(hash_context, V, hash_context->result_size + 1);
  12882. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  12883. HMAC_update(hash_context, message_hash, hash_size);
  12884. HMAC_finish(hash_context, K, K);
  12885. update_V(hash_context, K, V);
  12886. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12887. mg_uecc_word_t T[MG_UECC_MAX_WORDS];
  12888. uint8_t *T_ptr = (uint8_t *) T;
  12889. wordcount_t T_bytes = 0;
  12890. for (;;) {
  12891. update_V(hash_context, K, V);
  12892. for (i = 0; i < hash_context->result_size; ++i) {
  12893. T_ptr[T_bytes++] = V[i];
  12894. if (T_bytes >= num_n_words * MG_UECC_WORD_SIZE) {
  12895. goto filled;
  12896. }
  12897. }
  12898. }
  12899. filled:
  12900. if ((bitcount_t) num_n_words * MG_UECC_WORD_SIZE * 8 > num_n_bits) {
  12901. mg_uecc_word_t mask = (mg_uecc_word_t) -1;
  12902. T[num_n_words - 1] &=
  12903. mask >>
  12904. ((bitcount_t) (num_n_words * MG_UECC_WORD_SIZE * 8 - num_n_bits));
  12905. }
  12906. if (mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, T,
  12907. signature, curve)) {
  12908. return 1;
  12909. }
  12910. /* K = HMAC_K(V || 0x00) */
  12911. HMAC_init(hash_context, K);
  12912. V[hash_context->result_size] = 0x00;
  12913. HMAC_update(hash_context, V, hash_context->result_size + 1);
  12914. HMAC_finish(hash_context, K, K);
  12915. update_V(hash_context, K, V);
  12916. }
  12917. return 0;
  12918. }
  12919. static bitcount_t smax(bitcount_t a, bitcount_t b) {
  12920. return (a > b ? a : b);
  12921. }
  12922. int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash,
  12923. unsigned hash_size, const uint8_t *signature,
  12924. MG_UECC_Curve curve) {
  12925. mg_uecc_word_t u1[MG_UECC_MAX_WORDS], u2[MG_UECC_MAX_WORDS];
  12926. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  12927. mg_uecc_word_t sum[MG_UECC_MAX_WORDS * 2];
  12928. mg_uecc_word_t rx[MG_UECC_MAX_WORDS];
  12929. mg_uecc_word_t ry[MG_UECC_MAX_WORDS];
  12930. mg_uecc_word_t tx[MG_UECC_MAX_WORDS];
  12931. mg_uecc_word_t ty[MG_UECC_MAX_WORDS];
  12932. mg_uecc_word_t tz[MG_UECC_MAX_WORDS];
  12933. const mg_uecc_word_t *points[4];
  12934. const mg_uecc_word_t *point;
  12935. bitcount_t num_bits;
  12936. bitcount_t i;
  12937. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12938. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12939. #else
  12940. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12941. #endif
  12942. mg_uecc_word_t r[MG_UECC_MAX_WORDS], s[MG_UECC_MAX_WORDS];
  12943. wordcount_t num_words = curve->num_words;
  12944. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12945. rx[num_n_words - 1] = 0;
  12946. r[num_n_words - 1] = 0;
  12947. s[num_n_words - 1] = 0;
  12948. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12949. bcopy((uint8_t *) r, signature, curve->num_bytes);
  12950. bcopy((uint8_t *) s, signature + curve->num_bytes, curve->num_bytes);
  12951. #else
  12952. mg_uecc_vli_bytesToNative(_public, public_key, curve->num_bytes);
  12953. mg_uecc_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
  12954. curve->num_bytes);
  12955. mg_uecc_vli_bytesToNative(r, signature, curve->num_bytes);
  12956. mg_uecc_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
  12957. #endif
  12958. /* r, s must not be 0. */
  12959. if (mg_uecc_vli_isZero(r, num_words) || mg_uecc_vli_isZero(s, num_words)) {
  12960. return 0;
  12961. }
  12962. /* r, s must be < n. */
  12963. if (mg_uecc_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
  12964. mg_uecc_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
  12965. return 0;
  12966. }
  12967. /* Calculate u1 and u2. */
  12968. mg_uecc_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
  12969. u1[num_n_words - 1] = 0;
  12970. bits2int(u1, message_hash, hash_size, curve);
  12971. mg_uecc_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
  12972. mg_uecc_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */
  12973. /* Calculate sum = G + Q. */
  12974. mg_uecc_vli_set(sum, _public, num_words);
  12975. mg_uecc_vli_set(sum + num_words, _public + num_words, num_words);
  12976. mg_uecc_vli_set(tx, curve->G, num_words);
  12977. mg_uecc_vli_set(ty, curve->G + num_words, num_words);
  12978. mg_uecc_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
  12979. XYcZ_add(tx, ty, sum, sum + num_words, curve);
  12980. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
  12981. apply_z(sum, sum + num_words, z, curve);
  12982. /* Use Shamir's trick to calculate u1*G + u2*Q */
  12983. points[0] = 0;
  12984. points[1] = curve->G;
  12985. points[2] = _public;
  12986. points[3] = sum;
  12987. num_bits = smax(mg_uecc_vli_numBits(u1, num_n_words),
  12988. mg_uecc_vli_numBits(u2, num_n_words));
  12989. point =
  12990. points[(!!mg_uecc_vli_testBit(u1, (bitcount_t) (num_bits - 1))) |
  12991. ((!!mg_uecc_vli_testBit(u2, (bitcount_t) (num_bits - 1))) << 1)];
  12992. mg_uecc_vli_set(rx, point, num_words);
  12993. mg_uecc_vli_set(ry, point + num_words, num_words);
  12994. mg_uecc_vli_clear(z, num_words);
  12995. z[0] = 1;
  12996. for (i = num_bits - 2; i >= 0; --i) {
  12997. mg_uecc_word_t index;
  12998. curve->double_jacobian(rx, ry, z, curve);
  12999. index = (!!mg_uecc_vli_testBit(u1, i)) |
  13000. (mg_uecc_word_t) ((!!mg_uecc_vli_testBit(u2, i)) << 1);
  13001. point = points[index];
  13002. if (point) {
  13003. mg_uecc_vli_set(tx, point, num_words);
  13004. mg_uecc_vli_set(ty, point + num_words, num_words);
  13005. apply_z(tx, ty, z, curve);
  13006. mg_uecc_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
  13007. XYcZ_add(tx, ty, rx, ry, curve);
  13008. mg_uecc_vli_modMult_fast(z, z, tz, curve);
  13009. }
  13010. }
  13011. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
  13012. apply_z(rx, ry, z, curve);
  13013. /* v = x1 (mod n) */
  13014. if (mg_uecc_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
  13015. mg_uecc_vli_sub(rx, rx, curve->n, num_n_words);
  13016. }
  13017. /* Accept only if v == r. */
  13018. return (int) (mg_uecc_vli_equal(rx, r, num_words));
  13019. }
  13020. #if MG_UECC_ENABLE_VLI_API
  13021. unsigned mg_uecc_curve_num_words(MG_UECC_Curve curve) {
  13022. return curve->num_words;
  13023. }
  13024. unsigned mg_uecc_curve_num_bytes(MG_UECC_Curve curve) {
  13025. return curve->num_bytes;
  13026. }
  13027. unsigned mg_uecc_curve_num_bits(MG_UECC_Curve curve) {
  13028. return curve->num_bytes * 8;
  13029. }
  13030. unsigned mg_uecc_curve_num_n_words(MG_UECC_Curve curve) {
  13031. return BITS_TO_WORDS(curve->num_n_bits);
  13032. }
  13033. unsigned mg_uecc_curve_num_n_bytes(MG_UECC_Curve curve) {
  13034. return BITS_TO_BYTES(curve->num_n_bits);
  13035. }
  13036. unsigned mg_uecc_curve_num_n_bits(MG_UECC_Curve curve) {
  13037. return curve->num_n_bits;
  13038. }
  13039. const mg_uecc_word_t *mg_uecc_curve_p(MG_UECC_Curve curve) {
  13040. return curve->p;
  13041. }
  13042. const mg_uecc_word_t *mg_uecc_curve_n(MG_UECC_Curve curve) {
  13043. return curve->n;
  13044. }
  13045. const mg_uecc_word_t *mg_uecc_curve_G(MG_UECC_Curve curve) {
  13046. return curve->G;
  13047. }
  13048. const mg_uecc_word_t *mg_uecc_curve_b(MG_UECC_Curve curve) {
  13049. return curve->b;
  13050. }
  13051. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  13052. void mg_uecc_vli_mod_sqrt(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  13053. curve->mod_sqrt(a, curve);
  13054. }
  13055. #endif
  13056. void mg_uecc_vli_mmod_fast(mg_uecc_word_t *result, mg_uecc_word_t *product,
  13057. MG_UECC_Curve curve) {
  13058. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  13059. curve->mmod_fast(result, product);
  13060. #else
  13061. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  13062. #endif
  13063. }
  13064. void mg_uecc_point_mult(mg_uecc_word_t *result, const mg_uecc_word_t *point,
  13065. const mg_uecc_word_t *scalar, MG_UECC_Curve curve) {
  13066. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  13067. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  13068. mg_uecc_word_t *p2[2] = {tmp1, tmp2};
  13069. mg_uecc_word_t carry = regularize_k(scalar, tmp1, tmp2, curve);
  13070. EccPoint_mult(result, point, p2[!carry], 0, curve->num_n_bits + 1, curve);
  13071. }
  13072. #endif /* MG_UECC_ENABLE_VLI_API */
  13073. #endif // MG_TLS_BUILTIN
  13074. // End of uecc BSD-2
  13075. #ifdef MG_ENABLE_LINES
  13076. #line 1 "src/tls_x25519.c"
  13077. #endif
  13078. /**
  13079. * Adapted from STROBE: https://strobe.sourceforge.io/
  13080. * Copyright (c) 2015-2016 Cryptography Research, Inc.
  13081. * Author: Mike Hamburg
  13082. * License: MIT License
  13083. */
  13084. const uint8_t X25519_BASE_POINT[X25519_BYTES] = {9};
  13085. #define X25519_WBITS 32
  13086. typedef uint32_t limb_t;
  13087. typedef uint64_t dlimb_t;
  13088. typedef int64_t sdlimb_t;
  13089. #define NLIMBS (256 / X25519_WBITS)
  13090. typedef limb_t mg_fe[NLIMBS];
  13091. static limb_t umaal(limb_t *carry, limb_t acc, limb_t mand, limb_t mier) {
  13092. dlimb_t tmp = (dlimb_t) mand * mier + acc + *carry;
  13093. *carry = (limb_t) (tmp >> X25519_WBITS);
  13094. return (limb_t) tmp;
  13095. }
  13096. // These functions are implemented in terms of umaal on ARM
  13097. static limb_t adc(limb_t *carry, limb_t acc, limb_t mand) {
  13098. dlimb_t total = (dlimb_t) *carry + acc + mand;
  13099. *carry = (limb_t) (total >> X25519_WBITS);
  13100. return (limb_t) total;
  13101. }
  13102. static limb_t adc0(limb_t *carry, limb_t acc) {
  13103. dlimb_t total = (dlimb_t) *carry + acc;
  13104. *carry = (limb_t) (total >> X25519_WBITS);
  13105. return (limb_t) total;
  13106. }
  13107. // - Precondition: carry is small.
  13108. // - Invariant: result of propagate is < 2^255 + 1 word
  13109. // - In particular, always less than 2p.
  13110. // - Also, output x >= min(x,19)
  13111. static void propagate(mg_fe x, limb_t over) {
  13112. unsigned i;
  13113. limb_t carry;
  13114. over = x[NLIMBS - 1] >> (X25519_WBITS - 1) | over << 1;
  13115. x[NLIMBS - 1] &= ~((limb_t) 1 << (X25519_WBITS - 1));
  13116. carry = over * 19;
  13117. for (i = 0; i < NLIMBS; i++) {
  13118. x[i] = adc0(&carry, x[i]);
  13119. }
  13120. }
  13121. static void add(mg_fe out, const mg_fe a, const mg_fe b) {
  13122. unsigned i;
  13123. limb_t carry = 0;
  13124. for (i = 0; i < NLIMBS; i++) {
  13125. out[i] = adc(&carry, a[i], b[i]);
  13126. }
  13127. propagate(out, carry);
  13128. }
  13129. static void sub(mg_fe out, const mg_fe a, const mg_fe b) {
  13130. unsigned i;
  13131. sdlimb_t carry = -38;
  13132. for (i = 0; i < NLIMBS; i++) {
  13133. carry = carry + a[i] - b[i];
  13134. out[i] = (limb_t) carry;
  13135. carry >>= X25519_WBITS;
  13136. }
  13137. propagate(out, (limb_t) (1 + carry));
  13138. }
  13139. // `b` can contain less than 8 limbs, thus we use `limb_t *` instead of `mg_fe`
  13140. // to avoid build warnings
  13141. static void mul(mg_fe out, const mg_fe a, const limb_t *b, unsigned nb) {
  13142. limb_t accum[2 * NLIMBS] = {0};
  13143. unsigned i, j;
  13144. limb_t carry2;
  13145. for (i = 0; i < nb; i++) {
  13146. limb_t mand = b[i];
  13147. carry2 = 0;
  13148. for (j = 0; j < NLIMBS; j++) {
  13149. limb_t tmp; // "a" may be misaligned
  13150. memcpy(&tmp, &a[j], sizeof(tmp)); // So make an aligned copy
  13151. accum[i + j] = umaal(&carry2, accum[i + j], mand, tmp);
  13152. }
  13153. accum[i + j] = carry2;
  13154. }
  13155. carry2 = 0;
  13156. for (j = 0; j < NLIMBS; j++) {
  13157. out[j] = umaal(&carry2, accum[j], 38, accum[j + NLIMBS]);
  13158. }
  13159. propagate(out, carry2);
  13160. }
  13161. static void sqr(mg_fe out, const mg_fe a) {
  13162. mul(out, a, a, NLIMBS);
  13163. }
  13164. static void mul1(mg_fe out, const mg_fe a) {
  13165. mul(out, a, out, NLIMBS);
  13166. }
  13167. static void sqr1(mg_fe a) {
  13168. mul1(a, a);
  13169. }
  13170. static void condswap(limb_t a[2 * NLIMBS], limb_t b[2 * NLIMBS],
  13171. limb_t doswap) {
  13172. unsigned i;
  13173. for (i = 0; i < 2 * NLIMBS; i++) {
  13174. limb_t xor_ab = (a[i] ^ b[i]) & doswap;
  13175. a[i] ^= xor_ab;
  13176. b[i] ^= xor_ab;
  13177. }
  13178. }
  13179. // Canonicalize a field element x, reducing it to the least residue which is
  13180. // congruent to it mod 2^255-19
  13181. // - Precondition: x < 2^255 + 1 word
  13182. static limb_t canon(mg_fe x) {
  13183. // First, add 19.
  13184. unsigned i;
  13185. limb_t carry0 = 19;
  13186. limb_t res;
  13187. sdlimb_t carry;
  13188. for (i = 0; i < NLIMBS; i++) {
  13189. x[i] = adc0(&carry0, x[i]);
  13190. }
  13191. propagate(x, carry0);
  13192. // Here, 19 <= x2 < 2^255
  13193. // - This is because we added 19, so before propagate it can't be less
  13194. // than 19. After propagate, it still can't be less than 19, because if
  13195. // propagate does anything it adds 19.
  13196. // - We know that the high bit must be clear, because either the input was ~
  13197. // 2^255 + one word + 19 (in which case it propagates to at most 2 words) or
  13198. // it was < 2^255. So now, if we subtract 19, we will get back to something in
  13199. // [0,2^255-19).
  13200. carry = -19;
  13201. res = 0;
  13202. for (i = 0; i < NLIMBS; i++) {
  13203. carry += x[i];
  13204. res |= x[i] = (limb_t) carry;
  13205. carry >>= X25519_WBITS;
  13206. }
  13207. return (limb_t) (((dlimb_t) res - 1) >> X25519_WBITS);
  13208. }
  13209. static const limb_t a24[1] = {121665};
  13210. static void ladder_part1(mg_fe xs[5]) {
  13211. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  13212. add(t1, x2, z2); // t1 = A
  13213. sub(z2, x2, z2); // z2 = B
  13214. add(x2, x3, z3); // x2 = C
  13215. sub(z3, x3, z3); // z3 = D
  13216. mul1(z3, t1); // z3 = DA
  13217. mul1(x2, z2); // x3 = BC
  13218. add(x3, z3, x2); // x3 = DA+CB
  13219. sub(z3, z3, x2); // z3 = DA-CB
  13220. sqr1(t1); // t1 = AA
  13221. sqr1(z2); // z2 = BB
  13222. sub(x2, t1, z2); // x2 = E = AA-BB
  13223. mul(z2, x2, a24, sizeof(a24) / sizeof(a24[0])); // z2 = E*a24
  13224. add(z2, z2, t1); // z2 = E*a24 + AA
  13225. }
  13226. static void ladder_part2(mg_fe xs[5], const mg_fe x1) {
  13227. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  13228. sqr1(z3); // z3 = (DA-CB)^2
  13229. mul1(z3, x1); // z3 = x1 * (DA-CB)^2
  13230. sqr1(x3); // x3 = (DA+CB)^2
  13231. mul1(z2, x2); // z2 = AA*(E*a24+AA)
  13232. sub(x2, t1, x2); // x2 = BB again
  13233. mul1(x2, t1); // x2 = AA*BB
  13234. }
  13235. static void x25519_core(mg_fe xs[5], const uint8_t scalar[X25519_BYTES],
  13236. const uint8_t *x1, int clamp) {
  13237. int i;
  13238. mg_fe x1_limbs;
  13239. limb_t swap = 0;
  13240. limb_t *x2 = xs[0], *x3 = xs[2], *z3 = xs[3];
  13241. memset(xs, 0, 4 * sizeof(mg_fe));
  13242. x2[0] = z3[0] = 1;
  13243. for (i = 0; i < NLIMBS; i++) {
  13244. x3[i] = x1_limbs[i] =
  13245. MG_U32(x1[i * 4 + 3], x1[i * 4 + 2], x1[i * 4 + 1], x1[i * 4]);
  13246. }
  13247. for (i = 255; i >= 0; i--) {
  13248. uint8_t bytei = scalar[i / 8];
  13249. limb_t doswap;
  13250. if (clamp) {
  13251. if (i / 8 == 0) {
  13252. bytei &= (uint8_t) ~7U;
  13253. } else if (i / 8 == X25519_BYTES - 1) {
  13254. bytei &= 0x7F;
  13255. bytei |= 0x40;
  13256. }
  13257. }
  13258. doswap = 0 - (limb_t) ((bytei >> (i % 8)) & 1);
  13259. condswap(x2, x3, swap ^ doswap);
  13260. swap = doswap;
  13261. ladder_part1(xs);
  13262. ladder_part2(xs, (const limb_t *) x1_limbs);
  13263. }
  13264. condswap(x2, x3, swap);
  13265. }
  13266. int mg_tls_x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES],
  13267. const uint8_t x1[X25519_BYTES], int clamp) {
  13268. int i, ret;
  13269. mg_fe xs[5], out_limbs;
  13270. limb_t *x2, *z2, *z3, *prev;
  13271. static const struct {
  13272. uint8_t a, c, n;
  13273. } steps[13] = {{2, 1, 1}, {2, 1, 1}, {4, 2, 3}, {2, 4, 6}, {3, 1, 1},
  13274. {3, 2, 12}, {4, 3, 25}, {2, 3, 25}, {2, 4, 50}, {3, 2, 125},
  13275. {3, 1, 2}, {3, 1, 2}, {3, 1, 1}};
  13276. x25519_core(xs, scalar, x1, clamp);
  13277. // Precomputed inversion chain
  13278. x2 = xs[0];
  13279. z2 = xs[1];
  13280. z3 = xs[3];
  13281. prev = z2;
  13282. for (i = 0; i < 13; i++) {
  13283. int j;
  13284. limb_t *a = xs[steps[i].a];
  13285. for (j = steps[i].n; j > 0; j--) {
  13286. sqr(a, prev);
  13287. prev = a;
  13288. }
  13289. mul1(a, xs[steps[i].c]);
  13290. }
  13291. // Here prev = z3
  13292. // x2 /= z2
  13293. mul(out_limbs, x2, z3, NLIMBS);
  13294. ret = (int) canon(out_limbs);
  13295. if (!clamp) ret = 0;
  13296. for (i = 0; i < NLIMBS; i++) {
  13297. uint32_t n = out_limbs[i];
  13298. out[i * 4] = (uint8_t) (n & 0xff);
  13299. out[i * 4 + 1] = (uint8_t) ((n >> 8) & 0xff);
  13300. out[i * 4 + 2] = (uint8_t) ((n >> 16) & 0xff);
  13301. out[i * 4 + 3] = (uint8_t) ((n >> 24) & 0xff);
  13302. }
  13303. return ret;
  13304. }
  13305. #ifdef MG_ENABLE_LINES
  13306. #line 1 "src/url.c"
  13307. #endif
  13308. struct url {
  13309. size_t key, user, pass, host, port, uri, end;
  13310. };
  13311. int mg_url_is_ssl(const char *url) {
  13312. return strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0 ||
  13313. strncmp(url, "mqtts:", 6) == 0 || strncmp(url, "ssl:", 4) == 0 ||
  13314. strncmp(url, "tls:", 4) == 0 || strncmp(url, "tcps:", 5) == 0;
  13315. }
  13316. static struct url urlparse(const char *url) {
  13317. size_t i;
  13318. struct url u;
  13319. memset(&u, 0, sizeof(u));
  13320. for (i = 0; url[i] != '\0'; i++) {
  13321. if (url[i] == '/' && i > 0 && u.host == 0 && url[i - 1] == '/') {
  13322. u.host = i + 1;
  13323. u.port = 0;
  13324. } else if (url[i] == ']') {
  13325. u.port = 0; // IPv6 URLs, like http://[::1]/bar
  13326. } else if (url[i] == ':' && u.port == 0 && u.uri == 0) {
  13327. u.port = i + 1;
  13328. } else if (url[i] == '@' && u.user == 0 && u.pass == 0 && u.uri == 0) {
  13329. u.user = u.host;
  13330. u.pass = u.port;
  13331. u.host = i + 1;
  13332. u.port = 0;
  13333. } else if (url[i] == '/' && u.host && u.uri == 0) {
  13334. u.uri = i;
  13335. }
  13336. }
  13337. u.end = i;
  13338. #if 0
  13339. printf("[%s] %d %d %d %d %d\n", url, u.user, u.pass, u.host, u.port, u.uri);
  13340. #endif
  13341. return u;
  13342. }
  13343. struct mg_str mg_url_host(const char *url) {
  13344. struct url u = urlparse(url);
  13345. size_t n = u.port ? u.port - u.host - 1
  13346. : u.uri ? u.uri - u.host
  13347. : u.end - u.host;
  13348. struct mg_str s = mg_str_n(url + u.host, n);
  13349. return s;
  13350. }
  13351. const char *mg_url_uri(const char *url) {
  13352. struct url u = urlparse(url);
  13353. return u.uri ? url + u.uri : "/";
  13354. }
  13355. unsigned short mg_url_port(const char *url) {
  13356. struct url u = urlparse(url);
  13357. unsigned short port = 0;
  13358. if (strncmp(url, "http:", 5) == 0 || strncmp(url, "ws:", 3) == 0) port = 80;
  13359. if (strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0)
  13360. port = 443;
  13361. if (strncmp(url, "mqtt:", 5) == 0) port = 1883;
  13362. if (strncmp(url, "mqtts:", 6) == 0) port = 8883;
  13363. if (u.port) port = (unsigned short) atoi(url + u.port);
  13364. return port;
  13365. }
  13366. struct mg_str mg_url_user(const char *url) {
  13367. struct url u = urlparse(url);
  13368. struct mg_str s = mg_str("");
  13369. if (u.user && (u.pass || u.host)) {
  13370. size_t n = u.pass ? u.pass - u.user - 1 : u.host - u.user - 1;
  13371. s = mg_str_n(url + u.user, n);
  13372. }
  13373. return s;
  13374. }
  13375. struct mg_str mg_url_pass(const char *url) {
  13376. struct url u = urlparse(url);
  13377. struct mg_str s = mg_str_n("", 0UL);
  13378. if (u.pass && u.host) {
  13379. size_t n = u.host - u.pass - 1;
  13380. s = mg_str_n(url + u.pass, n);
  13381. }
  13382. return s;
  13383. }
  13384. #ifdef MG_ENABLE_LINES
  13385. #line 1 "src/util.c"
  13386. #endif
  13387. // Not using memset for zeroing memory, cause it can be dropped by compiler
  13388. // See https://github.com/cesanta/mongoose/pull/1265
  13389. void mg_bzero(volatile unsigned char *buf, size_t len) {
  13390. if (buf != NULL) {
  13391. while (len--) *buf++ = 0;
  13392. }
  13393. }
  13394. #if MG_ENABLE_CUSTOM_RANDOM
  13395. #else
  13396. void mg_random(void *buf, size_t len) {
  13397. bool done = false;
  13398. unsigned char *p = (unsigned char *) buf;
  13399. #if MG_ARCH == MG_ARCH_ESP32
  13400. while (len--) *p++ = (unsigned char) (esp_random() & 255);
  13401. done = true;
  13402. #elif MG_ARCH == MG_ARCH_WIN32
  13403. #elif MG_ARCH == MG_ARCH_UNIX
  13404. FILE *fp = fopen("/dev/urandom", "rb");
  13405. if (fp != NULL) {
  13406. if (fread(buf, 1, len, fp) == len) done = true;
  13407. fclose(fp);
  13408. }
  13409. #endif
  13410. // If everything above did not work, fallback to a pseudo random generator
  13411. while (!done && len--) *p++ = (unsigned char) (rand() & 255);
  13412. }
  13413. #endif
  13414. char *mg_random_str(char *buf, size_t len) {
  13415. size_t i;
  13416. mg_random(buf, len);
  13417. for (i = 0; i < len; i++) {
  13418. uint8_t c = ((uint8_t *) buf)[i] % 62U;
  13419. buf[i] = i == len - 1 ? (char) '\0' // 0-terminate last byte
  13420. : c < 26 ? (char) ('a' + c) // lowercase
  13421. : c < 52 ? (char) ('A' + c - 26) // uppercase
  13422. : (char) ('0' + c - 52); // numeric
  13423. }
  13424. return buf;
  13425. }
  13426. uint32_t mg_ntohl(uint32_t net) {
  13427. uint8_t data[4] = {0, 0, 0, 0};
  13428. memcpy(&data, &net, sizeof(data));
  13429. return (((uint32_t) data[3]) << 0) | (((uint32_t) data[2]) << 8) |
  13430. (((uint32_t) data[1]) << 16) | (((uint32_t) data[0]) << 24);
  13431. }
  13432. uint16_t mg_ntohs(uint16_t net) {
  13433. uint8_t data[2] = {0, 0};
  13434. memcpy(&data, &net, sizeof(data));
  13435. return (uint16_t) ((uint16_t) data[1] | (((uint16_t) data[0]) << 8));
  13436. }
  13437. uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len) {
  13438. static const uint32_t crclut[16] = {
  13439. // table for polynomial 0xEDB88320 (reflected)
  13440. 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
  13441. 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
  13442. 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
  13443. crc = ~crc;
  13444. while (len--) {
  13445. uint8_t b = *(uint8_t *) buf++;
  13446. crc = crclut[(crc ^ b) & 0x0F] ^ (crc >> 4);
  13447. crc = crclut[(crc ^ (b >> 4)) & 0x0F] ^ (crc >> 4);
  13448. }
  13449. return ~crc;
  13450. }
  13451. static int isbyte(int n) {
  13452. return n >= 0 && n <= 255;
  13453. }
  13454. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  13455. int n, a, b, c, d, slash = 32, len = 0;
  13456. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  13457. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  13458. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  13459. slash < 33) {
  13460. len = n;
  13461. *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) |
  13462. (uint32_t) d;
  13463. *mask = slash ? (uint32_t) (0xffffffffU << (32 - slash)) : (uint32_t) 0;
  13464. }
  13465. return len;
  13466. }
  13467. int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) {
  13468. struct mg_str entry;
  13469. int allowed = acl.len == 0 ? '+' : '-'; // If any ACL is set, deny by default
  13470. uint32_t remote_ip4;
  13471. if (remote_ip->is_ip6) {
  13472. return -1; // TODO(): handle IPv6 ACL and addresses
  13473. } else { // IPv4
  13474. memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4));
  13475. while (mg_span(acl, &entry, &acl, ',')) {
  13476. uint32_t net, mask;
  13477. if (entry.buf[0] != '+' && entry.buf[0] != '-') return -1;
  13478. if (parse_net(&entry.buf[1], &net, &mask) == 0) return -2;
  13479. if ((mg_ntohl(remote_ip4) & mask) == net) allowed = entry.buf[0];
  13480. }
  13481. }
  13482. return allowed == '+';
  13483. }
  13484. bool mg_path_is_sane(const struct mg_str path) {
  13485. const char *s = path.buf;
  13486. size_t n = path.len;
  13487. if (path.buf[0] == '.' && path.buf[1] == '.') return false; // Starts with ..
  13488. for (; s[0] != '\0' && n > 0; s++, n--) {
  13489. if ((s[0] == '/' || s[0] == '\\') && n >= 2) { // Subdir?
  13490. if (s[1] == '.' && s[2] == '.') return false; // Starts with ..
  13491. }
  13492. }
  13493. return true;
  13494. }
  13495. #if MG_ENABLE_CUSTOM_MILLIS
  13496. #else
  13497. uint64_t mg_millis(void) {
  13498. #if MG_ARCH == MG_ARCH_WIN32
  13499. return GetTickCount();
  13500. #elif MG_ARCH == MG_ARCH_RP2040
  13501. return time_us_64() / 1000;
  13502. #elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \
  13503. MG_ARCH == MG_ARCH_FREERTOS
  13504. return xTaskGetTickCount() * portTICK_PERIOD_MS;
  13505. #elif MG_ARCH == MG_ARCH_AZURERTOS
  13506. return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND);
  13507. #elif MG_ARCH == MG_ARCH_TIRTOS
  13508. return (uint64_t) Clock_getTicks();
  13509. #elif MG_ARCH == MG_ARCH_ZEPHYR
  13510. return (uint64_t) k_uptime_get();
  13511. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
  13512. return (uint64_t) rt_time_get();
  13513. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
  13514. return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq());
  13515. #elif MG_ARCH == MG_ARCH_RTTHREAD
  13516. return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND);
  13517. #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
  13518. // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
  13519. // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
  13520. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000;
  13521. #elif MG_ARCH == MG_ARCH_UNIX
  13522. struct timespec ts = {0, 0};
  13523. // See #1615 - prefer monotonic clock
  13524. #if defined(CLOCK_MONOTONIC_RAW)
  13525. // Raw hardware-based time that is not subject to NTP adjustment
  13526. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  13527. #elif defined(CLOCK_MONOTONIC)
  13528. // Affected by the incremental adjustments performed by adjtime and NTP
  13529. clock_gettime(CLOCK_MONOTONIC, &ts);
  13530. #else
  13531. // Affected by discontinuous jumps in the system time and by the incremental
  13532. // adjustments performed by adjtime and NTP
  13533. clock_gettime(CLOCK_REALTIME, &ts);
  13534. #endif
  13535. return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000);
  13536. #elif defined(ARDUINO)
  13537. return (uint64_t) millis();
  13538. #else
  13539. return (uint64_t) (time(NULL) * 1000);
  13540. #endif
  13541. }
  13542. #endif
  13543. #ifdef MG_ENABLE_LINES
  13544. #line 1 "src/ws.c"
  13545. #endif
  13546. struct ws_msg {
  13547. uint8_t flags;
  13548. size_t header_len;
  13549. size_t data_len;
  13550. };
  13551. size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
  13552. va_list *ap) {
  13553. size_t len = c->send.len;
  13554. size_t n = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  13555. mg_ws_wrap(c, c->send.len - len, op);
  13556. return n;
  13557. }
  13558. size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...) {
  13559. size_t len = 0;
  13560. va_list ap;
  13561. va_start(ap, fmt);
  13562. len = mg_ws_vprintf(c, op, fmt, &ap);
  13563. va_end(ap);
  13564. return len;
  13565. }
  13566. static void ws_handshake(struct mg_connection *c, const struct mg_str *wskey,
  13567. const struct mg_str *wsproto, const char *fmt,
  13568. va_list *ap) {
  13569. const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  13570. unsigned char sha[20], b64_sha[30];
  13571. mg_sha1_ctx sha_ctx;
  13572. mg_sha1_init(&sha_ctx);
  13573. mg_sha1_update(&sha_ctx, (unsigned char *) wskey->buf, wskey->len);
  13574. mg_sha1_update(&sha_ctx, (unsigned char *) magic, 36);
  13575. mg_sha1_final(sha, &sha_ctx);
  13576. mg_base64_encode(sha, sizeof(sha), (char *) b64_sha, sizeof(b64_sha));
  13577. mg_xprintf(mg_pfn_iobuf, &c->send,
  13578. "HTTP/1.1 101 Switching Protocols\r\n"
  13579. "Upgrade: websocket\r\n"
  13580. "Connection: Upgrade\r\n"
  13581. "Sec-WebSocket-Accept: %s\r\n",
  13582. b64_sha);
  13583. if (fmt != NULL) mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  13584. if (wsproto != NULL) {
  13585. mg_printf(c, "Sec-WebSocket-Protocol: %.*s\r\n", (int) wsproto->len,
  13586. wsproto->buf);
  13587. }
  13588. mg_send(c, "\r\n", 2);
  13589. }
  13590. static uint32_t be32(const uint8_t *p) {
  13591. return (((uint32_t) p[3]) << 0) | (((uint32_t) p[2]) << 8) |
  13592. (((uint32_t) p[1]) << 16) | (((uint32_t) p[0]) << 24);
  13593. }
  13594. static size_t ws_process(uint8_t *buf, size_t len, struct ws_msg *msg) {
  13595. size_t i, n = 0, mask_len = 0;
  13596. memset(msg, 0, sizeof(*msg));
  13597. if (len >= 2) {
  13598. n = buf[1] & 0x7f; // Frame length
  13599. mask_len = buf[1] & 128 ? 4 : 0; // last bit is a mask bit
  13600. msg->flags = buf[0];
  13601. if (n < 126 && len >= mask_len) {
  13602. msg->data_len = n;
  13603. msg->header_len = 2 + mask_len;
  13604. } else if (n == 126 && len >= 4 + mask_len) {
  13605. msg->header_len = 4 + mask_len;
  13606. msg->data_len = (((size_t) buf[2]) << 8) | buf[3];
  13607. } else if (len >= 10 + mask_len) {
  13608. msg->header_len = 10 + mask_len;
  13609. msg->data_len =
  13610. (size_t) (((uint64_t) be32(buf + 2) << 32) + be32(buf + 6));
  13611. }
  13612. }
  13613. // Sanity check, and integer overflow protection for the boundary check below
  13614. // data_len should not be larger than 1 Gb
  13615. if (msg->data_len > 1024 * 1024 * 1024) return 0;
  13616. if (msg->header_len + msg->data_len > len) return 0;
  13617. if (mask_len > 0) {
  13618. uint8_t *p = buf + msg->header_len, *m = p - mask_len;
  13619. for (i = 0; i < msg->data_len; i++) p[i] ^= m[i & 3];
  13620. }
  13621. return msg->header_len + msg->data_len;
  13622. }
  13623. static size_t mkhdr(size_t len, int op, bool is_client, uint8_t *buf) {
  13624. size_t n = 0;
  13625. buf[0] = (uint8_t) (op | 128);
  13626. if (len < 126) {
  13627. buf[1] = (unsigned char) len;
  13628. n = 2;
  13629. } else if (len < 65536) {
  13630. uint16_t tmp = mg_htons((uint16_t) len);
  13631. buf[1] = 126;
  13632. memcpy(&buf[2], &tmp, sizeof(tmp));
  13633. n = 4;
  13634. } else {
  13635. uint32_t tmp;
  13636. buf[1] = 127;
  13637. tmp = mg_htonl((uint32_t) (((uint64_t) len) >> 32));
  13638. memcpy(&buf[2], &tmp, sizeof(tmp));
  13639. tmp = mg_htonl((uint32_t) (len & 0xffffffffU));
  13640. memcpy(&buf[6], &tmp, sizeof(tmp));
  13641. n = 10;
  13642. }
  13643. if (is_client) {
  13644. buf[1] |= 1 << 7; // Set masking flag
  13645. mg_random(&buf[n], 4);
  13646. n += 4;
  13647. }
  13648. return n;
  13649. }
  13650. static void mg_ws_mask(struct mg_connection *c, size_t len) {
  13651. if (c->is_client && c->send.buf != NULL) {
  13652. size_t i;
  13653. uint8_t *p = c->send.buf + c->send.len - len, *mask = p - 4;
  13654. for (i = 0; i < len; i++) p[i] ^= mask[i & 3];
  13655. }
  13656. }
  13657. size_t mg_ws_send(struct mg_connection *c, const void *buf, size_t len,
  13658. int op) {
  13659. uint8_t header[14];
  13660. size_t header_len = mkhdr(len, op, c->is_client, header);
  13661. mg_send(c, header, header_len);
  13662. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  13663. mg_send(c, buf, len);
  13664. mg_ws_mask(c, len);
  13665. return header_len + len;
  13666. }
  13667. static void my_mask(uint8_t *data, size_t len) {
  13668. size_t i;
  13669. uint8_t *p=data, *mask=p-4;
  13670. for (i = 0; i < len; i++) p[i] ^= mask[i & 3];
  13671. }
  13672. size_t mg_ws_send2(struct mg_connection *c, const void *buf, size_t len,
  13673. int op) {
  13674. uint8_t *p=malloc(len+100);
  13675. if(!p) return -1;
  13676. uint8_t header[14];
  13677. size_t header_len = mkhdr(len, op, c->is_client, p);
  13678. memcpy(p+header_len, buf, len);
  13679. //my_mask(p+header_len, len);
  13680. mg_io_send(c, p, header_len+len);
  13681. free(p);
  13682. return header_len + len;
  13683. }
  13684. static bool mg_ws_client_handshake(struct mg_connection *c) {
  13685. int n = mg_http_get_request_len(c->recv.buf, c->recv.len);
  13686. if (n < 0) {
  13687. mg_error(c, "not http"); // Some just, not an HTTP request
  13688. } else if (n > 0) {
  13689. if (n < 15 || memcmp(c->recv.buf + 9, "101", 3) != 0) {
  13690. mg_error(c, "ws handshake error");
  13691. } else {
  13692. struct mg_http_message hm;
  13693. if (mg_http_parse((char *) c->recv.buf, c->recv.len, &hm)) {
  13694. c->is_websocket = 1;
  13695. mg_call(c, MG_EV_WS_OPEN, &hm);
  13696. } else {
  13697. mg_error(c, "ws handshake error");
  13698. }
  13699. }
  13700. mg_iobuf_del(&c->recv, 0, (size_t) n);
  13701. } else {
  13702. return true; // Request is not yet received, quit event handler
  13703. }
  13704. return false; // Continue event handler
  13705. }
  13706. static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
  13707. struct ws_msg msg;
  13708. size_t ofs = (size_t) c->pfn_data;
  13709. // assert(ofs < c->recv.len);
  13710. if (ev == MG_EV_READ) {
  13711. if (c->is_client && !c->is_websocket && mg_ws_client_handshake(c)) return;
  13712. while (ws_process(c->recv.buf + ofs, c->recv.len - ofs, &msg) > 0) {
  13713. char *s = (char *) c->recv.buf + ofs + msg.header_len;
  13714. struct mg_ws_message m = {{s, msg.data_len}, msg.flags};
  13715. size_t len = msg.header_len + msg.data_len;
  13716. uint8_t final = msg.flags & 128, op = msg.flags & 15;
  13717. // MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
  13718. // (int) m.data.len, (int) m.data.len, m.data.buf));
  13719. switch (op) {
  13720. case WEBSOCKET_OP_CONTINUE:
  13721. mg_call(c, MG_EV_WS_CTL, &m);
  13722. break;
  13723. case WEBSOCKET_OP_PING:
  13724. MG_DEBUG(("%s", "WS PONG"));
  13725. mg_ws_send(c, s, msg.data_len, WEBSOCKET_OP_PONG);
  13726. mg_call(c, MG_EV_WS_CTL, &m);
  13727. break;
  13728. case WEBSOCKET_OP_PONG:
  13729. mg_call(c, MG_EV_WS_CTL, &m);
  13730. break;
  13731. case WEBSOCKET_OP_TEXT:
  13732. case WEBSOCKET_OP_BINARY:
  13733. if (final) mg_call(c, MG_EV_WS_MSG, &m);
  13734. break;
  13735. case WEBSOCKET_OP_CLOSE:
  13736. MG_DEBUG(("%lu WS CLOSE", c->id));
  13737. mg_call(c, MG_EV_WS_CTL, &m);
  13738. // Echo the payload of the received CLOSE message back to the sender
  13739. mg_ws_send(c, m.data.buf, m.data.len, WEBSOCKET_OP_CLOSE);
  13740. c->is_draining = 1;
  13741. break;
  13742. default:
  13743. // Per RFC6455, close conn when an unknown op is recvd
  13744. mg_error(c, "unknown WS op %d", op);
  13745. break;
  13746. }
  13747. // Handle fragmented frames: strip header, keep in c->recv
  13748. if (final == 0 || op == 0) {
  13749. if (op) ofs++, len--, msg.header_len--; // First frame
  13750. mg_iobuf_del(&c->recv, ofs, msg.header_len); // Strip header
  13751. len -= msg.header_len;
  13752. ofs += len;
  13753. c->pfn_data = (void *) ofs;
  13754. // MG_INFO(("FRAG %d [%.*s]", (int) ofs, (int) ofs, c->recv.buf));
  13755. }
  13756. // Remove non-fragmented frame
  13757. if (final && op) mg_iobuf_del(&c->recv, ofs, len);
  13758. // Last chunk of the fragmented frame
  13759. if (final && !op) {
  13760. m.flags = c->recv.buf[0];
  13761. m.data = mg_str_n((char *) &c->recv.buf[1], (size_t) (ofs - 1));
  13762. mg_call(c, MG_EV_WS_MSG, &m);
  13763. mg_iobuf_del(&c->recv, 0, ofs);
  13764. ofs = 0;
  13765. c->pfn_data = NULL;
  13766. }
  13767. }
  13768. }
  13769. (void) ev_data;
  13770. }
  13771. struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
  13772. mg_event_handler_t fn, void *fn_data,
  13773. const char *fmt, ...) {
  13774. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  13775. if (c != NULL) {
  13776. char nonce[16], key[30];
  13777. struct mg_str host = mg_url_host(url);
  13778. mg_random(nonce, sizeof(nonce));
  13779. mg_base64_encode((unsigned char *) nonce, sizeof(nonce), key, sizeof(key));
  13780. mg_xprintf(mg_pfn_iobuf, &c->send,
  13781. "GET %s HTTP/1.1\r\n"
  13782. "Upgrade: websocket\r\n"
  13783. "Host: %.*s\r\n"
  13784. "Connection: Upgrade\r\n"
  13785. "Sec-WebSocket-Version: 13\r\n"
  13786. "Sec-WebSocket-Key: %s\r\n",
  13787. mg_url_uri(url), (int) host.len, host.buf, key);
  13788. if (fmt != NULL) {
  13789. va_list ap;
  13790. va_start(ap, fmt);
  13791. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  13792. va_end(ap);
  13793. }
  13794. mg_xprintf(mg_pfn_iobuf, &c->send, "\r\n");
  13795. c->pfn = mg_ws_cb;
  13796. c->pfn_data = NULL;
  13797. }
  13798. return c;
  13799. }
  13800. void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
  13801. const char *fmt, ...) {
  13802. struct mg_str *wskey = mg_http_get_header(hm, "Sec-WebSocket-Key");
  13803. c->pfn = mg_ws_cb;
  13804. c->pfn_data = NULL;
  13805. if (wskey == NULL) {
  13806. mg_http_reply(c, 426, "", "WS upgrade expected\n");
  13807. c->is_draining = 1;
  13808. } else {
  13809. struct mg_str *wsproto = mg_http_get_header(hm, "Sec-WebSocket-Protocol");
  13810. va_list ap;
  13811. va_start(ap, fmt);
  13812. ws_handshake(c, wskey, wsproto, fmt, &ap);
  13813. va_end(ap);
  13814. c->is_websocket = 1;
  13815. c->is_resp = 0;
  13816. mg_call(c, MG_EV_WS_OPEN, hm);
  13817. }
  13818. }
  13819. size_t mg_ws_wrap(struct mg_connection *c, size_t len, int op) {
  13820. uint8_t header[14], *p;
  13821. size_t header_len = mkhdr(len, op, c->is_client, header);
  13822. // NOTE: order of operations is important!
  13823. mg_iobuf_add(&c->send, c->send.len, NULL, header_len);
  13824. p = &c->send.buf[c->send.len - len]; // p points to data
  13825. memmove(p, p - header_len, len); // Shift data
  13826. memcpy(p - header_len, header, header_len); // Prepend header
  13827. mg_ws_mask(c, len); // Mask data
  13828. return c->send.len;
  13829. }
  13830. #ifdef MG_ENABLE_LINES
  13831. #line 1 "src/drivers/cmsis.c"
  13832. #endif
  13833. // https://arm-software.github.io/CMSIS_5/Driver/html/index.html
  13834. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
  13835. extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0;
  13836. extern ARM_DRIVER_ETH_PHY Driver_ETH_PHY0;
  13837. static struct mg_tcpip_if *s_ifp;
  13838. static void mac_cb(uint32_t);
  13839. static bool cmsis_init(struct mg_tcpip_if *);
  13840. static bool cmsis_up(struct mg_tcpip_if *);
  13841. static size_t cmsis_tx(const void *, size_t, struct mg_tcpip_if *);
  13842. static size_t cmsis_rx(void *, size_t, struct mg_tcpip_if *);
  13843. struct mg_tcpip_driver mg_tcpip_driver_cmsis = {cmsis_init, cmsis_tx, NULL,
  13844. cmsis_up};
  13845. static bool cmsis_init(struct mg_tcpip_if *ifp) {
  13846. ARM_ETH_MAC_ADDR addr;
  13847. s_ifp = ifp;
  13848. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  13849. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  13850. ARM_ETH_MAC_CAPABILITIES cap = mac->GetCapabilities();
  13851. if (mac->Initialize(mac_cb) != ARM_DRIVER_OK) return false;
  13852. if (phy->Initialize(mac->PHY_Read, mac->PHY_Write) != ARM_DRIVER_OK)
  13853. return false;
  13854. if (cap.event_rx_frame == 0) // polled mode driver
  13855. mg_tcpip_driver_cmsis.rx = cmsis_rx;
  13856. mac->PowerControl(ARM_POWER_FULL);
  13857. if (cap.mac_address) { // driver provides MAC address
  13858. mac->GetMacAddress(&addr);
  13859. memcpy(ifp->mac, &addr, sizeof(ifp->mac));
  13860. } else { // we provide MAC address
  13861. memcpy(&addr, ifp->mac, sizeof(addr));
  13862. mac->SetMacAddress(&addr);
  13863. }
  13864. phy->PowerControl(ARM_POWER_FULL);
  13865. phy->SetInterface(cap.media_interface);
  13866. phy->SetMode(ARM_ETH_PHY_AUTO_NEGOTIATE);
  13867. return true;
  13868. }
  13869. static size_t cmsis_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
  13870. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  13871. if (mac->SendFrame(buf, (uint32_t) len, 0) != ARM_DRIVER_OK) {
  13872. ifp->nerr++;
  13873. return 0;
  13874. }
  13875. ifp->nsent++;
  13876. return len;
  13877. }
  13878. static bool cmsis_up(struct mg_tcpip_if *ifp) {
  13879. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  13880. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  13881. bool up = (phy->GetLinkState() == ARM_ETH_LINK_UP) ? 1 : 0; // link state
  13882. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // just went up
  13883. ARM_ETH_LINK_INFO st = phy->GetLinkInfo();
  13884. mac->Control(ARM_ETH_MAC_CONFIGURE,
  13885. (st.speed << ARM_ETH_MAC_SPEED_Pos) |
  13886. (st.duplex << ARM_ETH_MAC_DUPLEX_Pos) |
  13887. ARM_ETH_MAC_ADDRESS_BROADCAST);
  13888. MG_DEBUG(("Link is %uM %s-duplex",
  13889. (st.speed == 2) ? 1000
  13890. : st.speed ? 100
  13891. : 10,
  13892. st.duplex ? "full" : "half"));
  13893. mac->Control(ARM_ETH_MAC_CONTROL_TX, 1);
  13894. mac->Control(ARM_ETH_MAC_CONTROL_RX, 1);
  13895. } else if ((ifp->state != MG_TCPIP_STATE_DOWN) && !up) { // just went down
  13896. mac->Control(ARM_ETH_MAC_FLUSH,
  13897. ARM_ETH_MAC_FLUSH_TX | ARM_ETH_MAC_FLUSH_RX);
  13898. mac->Control(ARM_ETH_MAC_CONTROL_TX, 0);
  13899. mac->Control(ARM_ETH_MAC_CONTROL_RX, 0);
  13900. }
  13901. return up;
  13902. }
  13903. static void mac_cb(uint32_t ev) {
  13904. if ((ev & ARM_ETH_MAC_EVENT_RX_FRAME) == 0) return;
  13905. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  13906. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  13907. if (len >= 60 && len <= 1518) { // proper frame
  13908. char *p;
  13909. if (mg_queue_book(&s_ifp->recv_queue, &p, len) >= len) { // have room
  13910. if ((len = mac->ReadFrame((uint8_t *) p, len)) > 0) { // copy succeeds
  13911. mg_queue_add(&s_ifp->recv_queue, len);
  13912. s_ifp->nrecv++;
  13913. }
  13914. return;
  13915. }
  13916. s_ifp->ndrop++;
  13917. }
  13918. mac->ReadFrame(NULL, 0); // otherwise, discard
  13919. }
  13920. static size_t cmsis_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  13921. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  13922. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  13923. if (len >= 60 && len <= 1518 &&
  13924. ((len = mac->ReadFrame(buf, (uint32_t) buflen)) > 0))
  13925. return len;
  13926. if (len > 0) mac->ReadFrame(NULL, 0); // discard bad frames
  13927. (void) ifp;
  13928. return 0;
  13929. }
  13930. #endif
  13931. #ifdef MG_ENABLE_LINES
  13932. #line 1 "src/drivers/imxrt.c"
  13933. #endif
  13934. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_IMXRT) && MG_ENABLE_DRIVER_IMXRT
  13935. struct imxrt_enet {
  13936. volatile uint32_t RESERVED0, EIR, EIMR, RESERVED1, RDAR, TDAR, RESERVED2[3],
  13937. ECR, RESERVED3[6], MMFR, MSCR, RESERVED4[7], MIBC, RESERVED5[7], RCR,
  13938. RESERVED6[15], TCR, RESERVED7[7], PALR, PAUR, OPD, TXIC0, TXIC1, TXIC2,
  13939. RESERVED8, RXIC0, RXIC1, RXIC2, RESERVED9[3], IAUR, IALR, GAUR, GALR,
  13940. RESERVED10[7], TFWR, RESERVED11[14], RDSR, TDSR, MRBR[2], RSFL, RSEM,
  13941. RAEM, RAFL, TSEM, TAEM, TAFL, TIPG, FTRL, RESERVED12[3], TACC, RACC,
  13942. RESERVED13[15], RMON_T_PACKETS, RMON_T_BC_PKT, RMON_T_MC_PKT,
  13943. RMON_T_CRC_ALIGN, RMON_T_UNDERSIZE, RMON_T_OVERSIZE, RMON_T_FRAG,
  13944. RMON_T_JAB, RMON_T_COL, RMON_T_P64, RMON_T_P65TO127, RMON_T_P128TO255,
  13945. RMON_T_P256TO511, RMON_T_P512TO1023, RMON_T_P1024TO2048, RMON_T_GTE2048,
  13946. RMON_T_OCTETS, IEEE_T_DROP, IEEE_T_FRAME_OK, IEEE_T_1COL, IEEE_T_MCOL,
  13947. IEEE_T_DEF, IEEE_T_LCOL, IEEE_T_EXCOL, IEEE_T_MACERR, IEEE_T_CSERR,
  13948. IEEE_T_SQE, IEEE_T_FDXFC, IEEE_T_OCTETS_OK, RESERVED14[3], RMON_R_PACKETS,
  13949. RMON_R_BC_PKT, RMON_R_MC_PKT, RMON_R_CRC_ALIGN, RMON_R_UNDERSIZE,
  13950. RMON_R_OVERSIZE, RMON_R_FRAG, RMON_R_JAB, RESERVED15, RMON_R_P64,
  13951. RMON_R_P65TO127, RMON_R_P128TO255, RMON_R_P256TO511, RMON_R_P512TO1023,
  13952. RMON_R_P1024TO2047, RMON_R_GTE2048, RMON_R_OCTETS, IEEE_R_DROP,
  13953. IEEE_R_FRAME_OK, IEEE_R_CRC, IEEE_R_ALIGN, IEEE_R_MACERR, IEEE_R_FDXFC,
  13954. IEEE_R_OCTETS_OK, RESERVED16[71], ATCR, ATVR, ATOFF, ATPER, ATCOR, ATINC,
  13955. ATSTMP, RESERVED17[122], TGSR, TCSR0, TCCR0, TCSR1, TCCR1, TCSR2, TCCR2,
  13956. TCSR3;
  13957. };
  13958. #undef ENET
  13959. #if defined(MG_DRIVER_IMXRT_RT11) && MG_DRIVER_IMXRT_RT11
  13960. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x40424000U)
  13961. #define ETH_DESC_CNT 5 // Descriptors count
  13962. #else
  13963. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x402D8000U)
  13964. #define ETH_DESC_CNT 4 // Descriptors count
  13965. #endif
  13966. #define ETH_PKT_SIZE 1536 // Max frame size, 64-bit aligned
  13967. struct enet_desc {
  13968. uint16_t length; // Data length
  13969. uint16_t control; // Control and status
  13970. uint32_t *buffer; // Data ptr
  13971. };
  13972. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  13973. #define MG_64BYTE_ALIGNED __attribute__((aligned((64U))))
  13974. // Descriptors: in non-cached area (TODO(scaprile)), (37.5.1.22.2 37.5.1.23.2)
  13975. // Buffers: 64-byte aligned (37.3.14)
  13976. static volatile struct enet_desc s_rxdesc[ETH_DESC_CNT] MG_64BYTE_ALIGNED;
  13977. static volatile struct enet_desc s_txdesc[ETH_DESC_CNT] MG_64BYTE_ALIGNED;
  13978. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BYTE_ALIGNED;
  13979. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BYTE_ALIGNED;
  13980. static struct mg_tcpip_if *s_ifp; // MIP interface
  13981. static uint16_t enet_read_phy(uint8_t addr, uint8_t reg) {
  13982. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  13983. ENET->MMFR = (1 << 30) | (2 << 28) | (addr << 23) | (reg << 18) | (2 << 16);
  13984. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  13985. return ENET->MMFR & 0xffff;
  13986. }
  13987. static void enet_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  13988. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  13989. ENET->MMFR =
  13990. (1 << 30) | (1 << 28) | (addr << 23) | (reg << 18) | (2 << 16) | val;
  13991. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  13992. }
  13993. // MDC clock is generated from IPS Bus clock (ipg_clk); as per 802.3,
  13994. // it must not exceed 2.5MHz
  13995. // The PHY receives the PLL6-generated 50MHz clock
  13996. static bool mg_tcpip_driver_imxrt_init(struct mg_tcpip_if *ifp) {
  13997. struct mg_tcpip_driver_imxrt_data *d =
  13998. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  13999. s_ifp = ifp;
  14000. // Init RX descriptors
  14001. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14002. s_rxdesc[i].control = MG_BIT(15); // Own (E)
  14003. s_rxdesc[i].buffer = (uint32_t *) s_rxbuf[i]; // Point to data buffer
  14004. }
  14005. s_rxdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  14006. // Init TX descriptors
  14007. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14008. // s_txdesc[i].control = MG_BIT(10); // Own (TC)
  14009. s_txdesc[i].buffer = (uint32_t *) s_txbuf[i];
  14010. }
  14011. s_txdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  14012. ENET->ECR = MG_BIT(0); // Software reset, disable
  14013. while ((ENET->ECR & MG_BIT(0))) (void) 0; // Wait until done
  14014. // Set MDC clock divider. If user told us the value, use it.
  14015. // TODO(): Otherwise, guess (currently assuming max freq)
  14016. int cr = (d == NULL || d->mdc_cr < 0) ? 24 : d->mdc_cr;
  14017. ENET->MSCR = (1 << 8) | ((cr & 0x3f) << 1); // HOLDTIME 2 clks
  14018. struct mg_phy phy = {enet_read_phy, enet_write_phy};
  14019. mg_phy_init(&phy, d->phy_addr, MG_PHY_LEDS_ACTIVE_HIGH); // MAC clocks PHY
  14020. // Select RMII mode, 100M, keep CRC, set max rx length, disable loop
  14021. ENET->RCR = (1518 << 16) | MG_BIT(8) | MG_BIT(2);
  14022. // ENET->RCR |= MG_BIT(3); // Receive all
  14023. ENET->TCR = MG_BIT(2); // Full-duplex
  14024. ENET->RDSR = (uint32_t) (uintptr_t) s_rxdesc;
  14025. ENET->TDSR = (uint32_t) (uintptr_t) s_txdesc;
  14026. ENET->MRBR[0] = ETH_PKT_SIZE; // Same size for RX/TX buffers
  14027. // MAC address filtering (bytes in reversed order)
  14028. ENET->PAUR = ((uint32_t) ifp->mac[4] << 24U) | (uint32_t) ifp->mac[5] << 16U;
  14029. ENET->PALR = (uint32_t) (ifp->mac[0] << 24U) |
  14030. ((uint32_t) ifp->mac[1] << 16U) |
  14031. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  14032. ENET->ECR = MG_BIT(8) | MG_BIT(1); // Little-endian CPU, Enable
  14033. ENET->EIMR = MG_BIT(25); // Set interrupt mask
  14034. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  14035. ENET->TDAR = MG_BIT(24); // Transmit Descriptors have changed
  14036. // ENET->OPD = 0x10014;
  14037. return true;
  14038. }
  14039. // Transmit frame
  14040. static size_t mg_tcpip_driver_imxrt_tx(const void *buf, size_t len,
  14041. struct mg_tcpip_if *ifp) {
  14042. static int s_txno; // Current descriptor index
  14043. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  14044. MG_ERROR(("Frame too big, %ld", (long) len));
  14045. len = (size_t) -1; // fail
  14046. } else if ((s_txdesc[s_txno].control & MG_BIT(15))) {
  14047. ifp->nerr++;
  14048. MG_ERROR(("No descriptors available"));
  14049. len = 0; // retry later
  14050. } else {
  14051. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14052. s_txdesc[s_txno].length = (uint16_t) len; // Set data len
  14053. // Table 37-34, R, L, TC (Ready, last, transmit CRC after frame
  14054. s_txdesc[s_txno].control |=
  14055. (uint16_t) (MG_BIT(15) | MG_BIT(11) | MG_BIT(10));
  14056. ENET->TDAR = MG_BIT(24); // Descriptor ring updated
  14057. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14058. }
  14059. (void) ifp;
  14060. return len;
  14061. }
  14062. static bool mg_tcpip_driver_imxrt_up(struct mg_tcpip_if *ifp) {
  14063. struct mg_tcpip_driver_imxrt_data *d =
  14064. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  14065. uint8_t speed = MG_PHY_SPEED_10M;
  14066. bool up = false, full_duplex = false;
  14067. struct mg_phy phy = {enet_read_phy, enet_write_phy};
  14068. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  14069. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14070. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14071. // if(link is slow or half) set flags otherwise
  14072. // reg = tmp
  14073. uint32_t tcr = ENET->TCR | MG_BIT(2); // Full-duplex
  14074. uint32_t rcr = ENET->RCR & ~MG_BIT(9); // 100M
  14075. if (speed == MG_PHY_SPEED_10M) rcr |= MG_BIT(9); // 10M
  14076. if (full_duplex == false) tcr &= ~MG_BIT(2); // Half-duplex
  14077. ENET->TCR = tcr; // IRQ handler does not fiddle with these registers
  14078. ENET->RCR = rcr;
  14079. MG_DEBUG(("Link is %uM %s-duplex", rcr & MG_BIT(9) ? 10 : 100,
  14080. tcr & MG_BIT(2) ? "full" : "half"));
  14081. }
  14082. return up;
  14083. }
  14084. void ENET_IRQHandler(void);
  14085. static uint32_t s_rxno;
  14086. void ENET_IRQHandler(void) {
  14087. ENET->EIR = MG_BIT(25); // Ack IRQ
  14088. // Frame received, loop
  14089. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14090. uint32_t r = s_rxdesc[s_rxno].control;
  14091. if (r & MG_BIT(15)) break; // exit when done
  14092. // skip partial/errored frames (Table 37-32)
  14093. if ((r & MG_BIT(11)) &&
  14094. !(r & (MG_BIT(5) | MG_BIT(4) | MG_BIT(2) | MG_BIT(1) | MG_BIT(0)))) {
  14095. size_t len = s_rxdesc[s_rxno].length;
  14096. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  14097. }
  14098. s_rxdesc[s_rxno].control |= MG_BIT(15);
  14099. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14100. }
  14101. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  14102. // If b24 == 0, descriptors were exhausted and probably frames were dropped
  14103. }
  14104. struct mg_tcpip_driver mg_tcpip_driver_imxrt = {mg_tcpip_driver_imxrt_init,
  14105. mg_tcpip_driver_imxrt_tx, NULL,
  14106. mg_tcpip_driver_imxrt_up};
  14107. #endif
  14108. #ifdef MG_ENABLE_LINES
  14109. #line 1 "src/drivers/phy.c"
  14110. #endif
  14111. enum { // ID1 ID2
  14112. MG_PHY_KSZ8x = 0x22, // 0022 1561 - KSZ8081RNB
  14113. MG_PHY_DP83x = 0x2000, // 2000 a140 - TI DP83825I
  14114. MG_PHY_DP83867 = 0xa231, // 2000 a231 - TI DP83867I
  14115. MG_PHY_LAN87x = 0x7, // 0007 c0fx - LAN8720
  14116. MG_PHY_RTL8201 = 0x1C // 001c c816 - RTL8201
  14117. };
  14118. enum {
  14119. MG_PHY_REG_BCR = 0,
  14120. MG_PHY_REG_BSR = 1,
  14121. MG_PHY_REG_ID1 = 2,
  14122. MG_PHY_REG_ID2 = 3,
  14123. MG_PHY_DP83x_REG_PHYSTS = 16,
  14124. MG_PHY_DP83867_REG_PHYSTS = 17,
  14125. MG_PHY_DP83x_REG_RCSR = 23,
  14126. MG_PHY_DP83x_REG_LEDCR = 24,
  14127. MG_PHY_KSZ8x_REG_PC1R = 30,
  14128. MG_PHY_KSZ8x_REG_PC2R = 31,
  14129. MG_PHY_LAN87x_REG_SCSR = 31,
  14130. MG_PHY_RTL8201_REG_RMSR = 16, // in page 7
  14131. MG_PHY_RTL8201_REG_PAGESEL = 31
  14132. };
  14133. static const char *mg_phy_id_to_str(uint16_t id1, uint16_t id2) {
  14134. switch (id1) {
  14135. case MG_PHY_DP83x:
  14136. switch (id2) {
  14137. case MG_PHY_DP83867:
  14138. return "DP83867";
  14139. default:
  14140. return "DP83x";
  14141. }
  14142. case MG_PHY_KSZ8x:
  14143. return "KSZ8x";
  14144. case MG_PHY_LAN87x:
  14145. return "LAN87x";
  14146. case MG_PHY_RTL8201:
  14147. return "RTL8201";
  14148. default:
  14149. return "unknown";
  14150. }
  14151. (void) id2;
  14152. }
  14153. void mg_phy_init(struct mg_phy *phy, uint8_t phy_addr, uint8_t config) {
  14154. uint16_t id1, id2;
  14155. phy->write_reg(phy_addr, MG_PHY_REG_BCR, MG_BIT(15)); // Reset PHY
  14156. while (phy->read_reg(phy_addr, MG_PHY_REG_BCR) & MG_BIT(15)) (void) 0;
  14157. // MG_PHY_REG_BCR[12]: Autonegotiation is default unless hw says otherwise
  14158. id1 = phy->read_reg(phy_addr, MG_PHY_REG_ID1);
  14159. id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
  14160. MG_INFO(("PHY ID: %#04x %#04x (%s)", id1, id2, mg_phy_id_to_str(id1, id2)));
  14161. if (id1 == MG_PHY_DP83x && id2 == MG_PHY_DP83867) {
  14162. phy->write_reg(phy_addr, 0x0d, 0x1f); // write 0x10d to IO_MUX_CFG (0x0170)
  14163. phy->write_reg(phy_addr, 0x0e, 0x170);
  14164. phy->write_reg(phy_addr, 0x0d, 0x401f);
  14165. phy->write_reg(phy_addr, 0x0e, 0x10d);
  14166. }
  14167. if (config & MG_PHY_CLOCKS_MAC) {
  14168. // Use PHY crystal oscillator (preserve defaults)
  14169. // nothing to do
  14170. } else { // MAC clocks PHY, PHY has no xtal
  14171. // Enable 50 MHz external ref clock at XI (preserve defaults)
  14172. if (id1 == MG_PHY_DP83x && id2 != MG_PHY_DP83867) {
  14173. phy->write_reg(phy_addr, MG_PHY_DP83x_REG_RCSR, MG_BIT(7) | MG_BIT(0));
  14174. } else if (id1 == MG_PHY_KSZ8x) {
  14175. phy->write_reg(phy_addr, MG_PHY_KSZ8x_REG_PC2R,
  14176. MG_BIT(15) | MG_BIT(8) | MG_BIT(7));
  14177. } else if (id1 == MG_PHY_LAN87x) {
  14178. // nothing to do
  14179. } else if (id1 == MG_PHY_RTL8201) {
  14180. // assume PHY has been hardware strapped properly
  14181. #if 0
  14182. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_PAGESEL, 7); // Select page 7
  14183. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_RMSR, 0x1ffa);
  14184. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_PAGESEL, 0); // Select page 0
  14185. #endif
  14186. }
  14187. }
  14188. if (config & MG_PHY_LEDS_ACTIVE_HIGH && id1 == MG_PHY_DP83x) {
  14189. phy->write_reg(phy_addr, MG_PHY_DP83x_REG_LEDCR,
  14190. MG_BIT(9) | MG_BIT(7)); // LED status, active high
  14191. } // Other PHYs do not support this feature
  14192. }
  14193. bool mg_phy_up(struct mg_phy *phy, uint8_t phy_addr, bool *full_duplex,
  14194. uint8_t *speed) {
  14195. bool up = false;
  14196. uint16_t bsr = phy->read_reg(phy_addr, MG_PHY_REG_BSR);
  14197. if ((bsr & MG_BIT(5)) && !(bsr & MG_BIT(2))) // some PHYs latch down events
  14198. bsr = phy->read_reg(phy_addr, MG_PHY_REG_BSR); // read again
  14199. up = bsr & MG_BIT(2);
  14200. if (up && full_duplex != NULL && speed != NULL) {
  14201. uint16_t id1 = phy->read_reg(phy_addr, MG_PHY_REG_ID1);
  14202. if (id1 == MG_PHY_DP83x) {
  14203. uint16_t id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
  14204. if (id2 == MG_PHY_DP83867) {
  14205. uint16_t physts = phy->read_reg(phy_addr, MG_PHY_DP83867_REG_PHYSTS);
  14206. *full_duplex = physts & MG_BIT(13);
  14207. *speed = (physts & MG_BIT(15)) ? MG_PHY_SPEED_1000M
  14208. : (physts & MG_BIT(14)) ? MG_PHY_SPEED_100M
  14209. : MG_PHY_SPEED_10M;
  14210. } else {
  14211. uint16_t physts = phy->read_reg(phy_addr, MG_PHY_DP83x_REG_PHYSTS);
  14212. *full_duplex = physts & MG_BIT(2);
  14213. *speed = (physts & MG_BIT(1)) ? MG_PHY_SPEED_10M : MG_PHY_SPEED_100M;
  14214. }
  14215. } else if (id1 == MG_PHY_KSZ8x) {
  14216. uint16_t pc1r = phy->read_reg(phy_addr, MG_PHY_KSZ8x_REG_PC1R);
  14217. *full_duplex = pc1r & MG_BIT(2);
  14218. *speed = (pc1r & 3) == 1 ? MG_PHY_SPEED_10M : MG_PHY_SPEED_100M;
  14219. } else if (id1 == MG_PHY_LAN87x) {
  14220. uint16_t scsr = phy->read_reg(phy_addr, MG_PHY_LAN87x_REG_SCSR);
  14221. *full_duplex = scsr & MG_BIT(4);
  14222. *speed = (scsr & MG_BIT(3)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
  14223. } else if (id1 == MG_PHY_RTL8201) {
  14224. uint16_t bcr = phy->read_reg(phy_addr, MG_PHY_REG_BCR);
  14225. *full_duplex = bcr & MG_BIT(8);
  14226. *speed = (bcr & MG_BIT(13)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
  14227. }
  14228. }
  14229. return up;
  14230. }
  14231. #ifdef MG_ENABLE_LINES
  14232. #line 1 "src/drivers/ra.c"
  14233. #endif
  14234. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RA) && MG_ENABLE_DRIVER_RA
  14235. struct ra_etherc {
  14236. volatile uint32_t ECMR, RESERVED, RFLR, RESERVED1, ECSR, RESERVED2, ECSIPR,
  14237. RESERVED3, PIR, RESERVED4, PSR, RESERVED5[5], RDMLR, RESERVED6[3], IPGR,
  14238. APR, MPR, RESERVED7, RFCF, TPAUSER, TPAUSECR, BCFRR, RESERVED8[20], MAHR,
  14239. RESERVED9, MALR, RESERVED10, TROCR, CDCR, LCCR, CNDCR, RESERVED11, CEFCR,
  14240. FRECR, TSFRCR, TLFRCR, RFCR, MAFCR;
  14241. };
  14242. struct ra_edmac {
  14243. volatile uint32_t EDMR, RESERVED, EDTRR, RESERVED1, EDRRR, RESERVED2, TDLAR,
  14244. RESERVED3, RDLAR, RESERVED4, EESR, RESERVED5, EESIPR, RESERVED6, TRSCER,
  14245. RESERVED7, RMFCR, RESERVED8, TFTR, RESERVED9, FDR, RESERVED10, RMCR,
  14246. RESERVED11[2], TFUCR, RFOCR, IOSR, FCFTR, RESERVED12, RPADIR, TRIMD,
  14247. RESERVED13[18], RBWAR, RDFAR, RESERVED14, TBRAR, TDFAR;
  14248. };
  14249. #undef ETHERC
  14250. #define ETHERC ((struct ra_etherc *) (uintptr_t) 0x40114100U)
  14251. #undef EDMAC
  14252. #define EDMAC ((struct ra_edmac *) (uintptr_t) 0x40114000U)
  14253. #undef RASYSC
  14254. #define RASYSC ((uint32_t *) (uintptr_t) 0x4001E000U)
  14255. #undef ICU_IELSR
  14256. #define ICU_IELSR ((uint32_t *) (uintptr_t) 0x40006300U)
  14257. #define ETH_PKT_SIZE 1536 // Max frame size, multiple of 32
  14258. #define ETH_DESC_CNT 4 // Descriptors count
  14259. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  14260. #define MG_16BYTE_ALIGNED __attribute__((aligned((16U))))
  14261. #define MG_32BYTE_ALIGNED __attribute__((aligned((32U))))
  14262. // Descriptors: 16-byte aligned
  14263. // Buffers: 32-byte aligned (27.3.1)
  14264. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][4] MG_16BYTE_ALIGNED;
  14265. static volatile uint32_t s_txdesc[ETH_DESC_CNT][4] MG_16BYTE_ALIGNED;
  14266. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_32BYTE_ALIGNED;
  14267. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_32BYTE_ALIGNED;
  14268. static struct mg_tcpip_if *s_ifp; // MIP interface
  14269. // fastest is 3 cycles (SUB + BNE) on a 3-stage pipeline or equivalent
  14270. static inline void raspin(volatile uint32_t count) {
  14271. while (count--) (void) 0;
  14272. }
  14273. // count to get the 200ns SMC semi-cycle period (2.5MHz) calling raspin():
  14274. // SYS_FREQUENCY * 200ns / 3 = SYS_FREQUENCY / 15000000
  14275. static uint32_t s_smispin;
  14276. // Bit-banged SMI
  14277. static void smi_preamble(void) {
  14278. unsigned int i = 32;
  14279. uint32_t pir = MG_BIT(1) | MG_BIT(2); // write, mdio = 1, mdc = 0
  14280. ETHERC->PIR = pir;
  14281. while (i--) {
  14282. pir &= ~MG_BIT(0); // mdc = 0
  14283. ETHERC->PIR = pir;
  14284. raspin(s_smispin);
  14285. pir |= MG_BIT(0); // mdc = 1
  14286. ETHERC->PIR = pir;
  14287. raspin(s_smispin);
  14288. }
  14289. }
  14290. static void smi_wr(uint16_t header, uint16_t data) {
  14291. uint32_t word = (header << 16) | data;
  14292. smi_preamble();
  14293. unsigned int i = 32;
  14294. while (i--) {
  14295. uint32_t pir = MG_BIT(1) |
  14296. (word & 0x80000000 ? MG_BIT(2) : 0); // write, mdc = 0, data
  14297. ETHERC->PIR = pir;
  14298. raspin(s_smispin);
  14299. pir |= MG_BIT(0); // mdc = 1
  14300. ETHERC->PIR = pir;
  14301. raspin(s_smispin);
  14302. word <<= 1;
  14303. }
  14304. }
  14305. static uint16_t smi_rd(uint16_t header) {
  14306. smi_preamble();
  14307. unsigned int i = 16; // 2 LSb as turnaround
  14308. uint32_t pir;
  14309. while (i--) {
  14310. pir = (i > 1 ? MG_BIT(1) : 0) |
  14311. (header & 0x8000
  14312. ? MG_BIT(2)
  14313. : 0); // mdc = 0, header, set read direction at turnaround
  14314. ETHERC->PIR = pir;
  14315. raspin(s_smispin);
  14316. pir |= MG_BIT(0); // mdc = 1
  14317. ETHERC->PIR = pir;
  14318. raspin(s_smispin);
  14319. header <<= 1;
  14320. }
  14321. i = 16;
  14322. uint16_t data = 0;
  14323. while (i--) {
  14324. data <<= 1;
  14325. pir = 0; // read, mdc = 0
  14326. ETHERC->PIR = pir;
  14327. raspin(s_smispin / 2); // 1/4 clock period, 300ns max access time
  14328. data |= (uint16_t)(ETHERC->PIR & MG_BIT(3) ? 1 : 0); // read mdio
  14329. raspin(s_smispin / 2); // 1/4 clock period
  14330. pir |= MG_BIT(0); // mdc = 1
  14331. ETHERC->PIR = pir;
  14332. raspin(s_smispin);
  14333. }
  14334. return data;
  14335. }
  14336. static uint16_t raeth_read_phy(uint8_t addr, uint8_t reg) {
  14337. return smi_rd((uint16_t)((1 << 14) | (2 << 12) | (addr << 7) | (reg << 2) | (2 << 0)));
  14338. }
  14339. static void raeth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14340. smi_wr((uint16_t)((1 << 14) | (1 << 12) | (addr << 7) | (reg << 2) | (2 << 0)), val);
  14341. }
  14342. // MDC clock is generated manually; as per 802.3, it must not exceed 2.5MHz
  14343. static bool mg_tcpip_driver_ra_init(struct mg_tcpip_if *ifp) {
  14344. struct mg_tcpip_driver_ra_data *d =
  14345. (struct mg_tcpip_driver_ra_data *) ifp->driver_data;
  14346. s_ifp = ifp;
  14347. // Init SMI clock timing. If user told us the clock value, use it.
  14348. // TODO(): Otherwise, guess
  14349. s_smispin = d->clock / 15000000;
  14350. // Init RX descriptors
  14351. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14352. s_rxdesc[i][0] = MG_BIT(31); // RACT
  14353. s_rxdesc[i][1] = ETH_PKT_SIZE << 16; // RBL
  14354. s_rxdesc[i][2] = (uint32_t) s_rxbuf[i]; // Point to data buffer
  14355. }
  14356. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(30); // Wrap last descriptor
  14357. // Init TX descriptors
  14358. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14359. // TACT = 0
  14360. s_txdesc[i][2] = (uint32_t) s_txbuf[i];
  14361. }
  14362. s_txdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(30); // Wrap last descriptor
  14363. EDMAC->EDMR = MG_BIT(0); // Software reset, wait 64 PCLKA clocks (27.2.1)
  14364. uint32_t sckdivcr = RASYSC[8]; // get divisors from SCKDIVCR (8.2.2)
  14365. uint32_t ick = 1 << ((sckdivcr >> 24) & 7); // sys_clock div
  14366. uint32_t pcka = 1 << ((sckdivcr >> 12) & 7); // pclka div
  14367. raspin((64U * pcka) / (3U * ick));
  14368. EDMAC->EDMR = MG_BIT(6); // Initialize, little-endian (27.2.1)
  14369. MG_DEBUG(("PHY addr: %d, smispin: %d", d->phy_addr, s_smispin));
  14370. struct mg_phy phy = {raeth_read_phy, raeth_write_phy};
  14371. mg_phy_init(&phy, d->phy_addr, 0); // MAC clocks PHY
  14372. // Select RMII mode,
  14373. ETHERC->ECMR = MG_BIT(2) | MG_BIT(1); // 100M, Full-duplex, CRC
  14374. // ETHERC->ECMR |= MG_BIT(0); // Receive all
  14375. ETHERC->RFLR = 1518; // Set max rx length
  14376. EDMAC->RDLAR = (uint32_t) (uintptr_t) s_rxdesc;
  14377. EDMAC->TDLAR = (uint32_t) (uintptr_t) s_txdesc;
  14378. // MAC address filtering (bytes in reversed order)
  14379. ETHERC->MAHR = (uint32_t) (ifp->mac[0] << 24U) |
  14380. ((uint32_t) ifp->mac[1] << 16U) |
  14381. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  14382. ETHERC->MALR = ((uint32_t) ifp->mac[4] << 8U) | ifp->mac[5];
  14383. EDMAC->TFTR = 0; // Store and forward (27.2.10)
  14384. EDMAC->FDR = 0x070f; // (27.2.11)
  14385. EDMAC->RMCR = MG_BIT(0); // (27.2.12)
  14386. ETHERC->ECMR |= MG_BIT(6) | MG_BIT(5); // TE RE
  14387. EDMAC->EESIPR = MG_BIT(18); // Enable Rx IRQ
  14388. EDMAC->EDRRR = MG_BIT(0); // Receive Descriptors have changed
  14389. EDMAC->EDTRR = MG_BIT(0); // Transmit Descriptors have changed
  14390. return true;
  14391. }
  14392. // Transmit frame
  14393. static size_t mg_tcpip_driver_ra_tx(const void *buf, size_t len,
  14394. struct mg_tcpip_if *ifp) {
  14395. static int s_txno; // Current descriptor index
  14396. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  14397. MG_ERROR(("Frame too big, %ld", (long) len));
  14398. len = (size_t) -1; // fail
  14399. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  14400. ifp->nerr++;
  14401. MG_ERROR(("No descriptors available"));
  14402. len = 0; // retry later
  14403. } else {
  14404. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14405. s_txdesc[s_txno][1] = len << 16; // Set data len
  14406. s_txdesc[s_txno][0] |= MG_BIT(31) | 3 << 28; // (27.3.1.1) mark valid
  14407. EDMAC->EDTRR = MG_BIT(0); // Transmit request
  14408. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14409. }
  14410. return len;
  14411. }
  14412. static bool mg_tcpip_driver_ra_up(struct mg_tcpip_if *ifp) {
  14413. struct mg_tcpip_driver_ra_data *d =
  14414. (struct mg_tcpip_driver_ra_data *) ifp->driver_data;
  14415. uint8_t speed = MG_PHY_SPEED_10M;
  14416. bool up = false, full_duplex = false;
  14417. struct mg_phy phy = {raeth_read_phy, raeth_write_phy};
  14418. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  14419. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14420. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14421. // if(link is slow or half) set flags otherwise
  14422. // reg = tmp
  14423. uint32_t ecmr = ETHERC->ECMR | MG_BIT(2) | MG_BIT(1); // 100M Full-duplex
  14424. if (speed == MG_PHY_SPEED_10M) ecmr &= ~MG_BIT(2); // 10M
  14425. if (full_duplex == false) ecmr &= ~MG_BIT(1); // Half-duplex
  14426. ETHERC->ECMR = ecmr; // IRQ handler does not fiddle with these registers
  14427. MG_DEBUG(("Link is %uM %s-duplex", ecmr & MG_BIT(2) ? 100 : 10,
  14428. ecmr & MG_BIT(1) ? "full" : "half"));
  14429. }
  14430. return up;
  14431. }
  14432. void EDMAC_IRQHandler(void);
  14433. static uint32_t s_rxno;
  14434. void EDMAC_IRQHandler(void) {
  14435. struct mg_tcpip_driver_ra_data *d =
  14436. (struct mg_tcpip_driver_ra_data *) s_ifp->driver_data;
  14437. EDMAC->EESR = MG_BIT(18); // Ack IRQ in EDMAC 1st
  14438. ICU_IELSR[d->irqno] &= ~MG_BIT(16); // Ack IRQ in ICU last
  14439. // Frame received, loop
  14440. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14441. uint32_t r = s_rxdesc[s_rxno][0];
  14442. if (r & MG_BIT(31)) break; // exit when done
  14443. // skip partial/errored frames (27.3.1.2)
  14444. if ((r & (MG_BIT(29) | MG_BIT(28)) && !(r & MG_BIT(27)))) {
  14445. size_t len = s_rxdesc[s_rxno][1] & 0xffff;
  14446. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp); // CRC already stripped
  14447. }
  14448. s_rxdesc[s_rxno][0] |= MG_BIT(31);
  14449. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14450. }
  14451. EDMAC->EDRRR = MG_BIT(0); // Receive Descriptors have changed
  14452. // If b0 == 0, descriptors were exhausted and probably frames were dropped,
  14453. // (27.2.9 RMFCR counts them)
  14454. }
  14455. struct mg_tcpip_driver mg_tcpip_driver_ra = {mg_tcpip_driver_ra_init,
  14456. mg_tcpip_driver_ra_tx, NULL,
  14457. mg_tcpip_driver_ra_up};
  14458. #endif
  14459. #ifdef MG_ENABLE_LINES
  14460. #line 1 "src/drivers/same54.c"
  14461. #endif
  14462. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && MG_ENABLE_DRIVER_SAME54
  14463. #include <sam.h>
  14464. #define ETH_PKT_SIZE 1536 // Max frame size
  14465. #define ETH_DESC_CNT 4 // Descriptors count
  14466. #define ETH_DS 2 // Descriptor size (words)
  14467. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  14468. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  14469. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  14470. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  14471. static uint8_t s_txno; // Current TX descriptor
  14472. static uint8_t s_rxno; // Current RX descriptor
  14473. static struct mg_tcpip_if *s_ifp; // MIP interface
  14474. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  14475. #define MG_PHYREGBIT_BCR_DUPLEX_MODE MG_BIT(8)
  14476. #define MG_PHYREGBIT_BCR_SPEED MG_BIT(13)
  14477. #define MG_PHYREGBIT_BSR_LINK_STATUS MG_BIT(2)
  14478. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  14479. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk |
  14480. GMAC_MAN_OP(2) | // Setting the read operation
  14481. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  14482. GMAC_MAN_REGA(reg); // Setting the register
  14483. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)) (void) 0;
  14484. return GMAC_REGS->GMAC_MAN & GMAC_MAN_DATA_Msk; // Getting the read value
  14485. }
  14486. #if 0
  14487. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14488. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk | GMAC_MAN_OP(1) | // Setting the write operation
  14489. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  14490. GMAC_MAN_REGA(reg) | GMAC_MAN_DATA(val); // Setting the register
  14491. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)); // Waiting until the write op is complete
  14492. }
  14493. #endif
  14494. int get_clock_rate(struct mg_tcpip_driver_same54_data *d) {
  14495. if (d && d->mdc_cr >= 0 && d->mdc_cr <= 5) {
  14496. return d->mdc_cr;
  14497. } else {
  14498. // get MCLK from GCLK_GENERATOR 0
  14499. uint32_t div = 512;
  14500. uint32_t mclk;
  14501. if (!(GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_DIVSEL_Msk)) {
  14502. div = ((GCLK_REGS->GCLK_GENCTRL[0] & 0x00FF0000) >> 16);
  14503. if (div == 0) div = 1;
  14504. }
  14505. switch (GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_SRC_Msk) {
  14506. case GCLK_GENCTRL_SRC_XOSC0_Val:
  14507. mclk = 32000000UL; /* 32MHz */
  14508. break;
  14509. case GCLK_GENCTRL_SRC_XOSC1_Val:
  14510. mclk = 32000000UL; /* 32MHz */
  14511. break;
  14512. case GCLK_GENCTRL_SRC_OSCULP32K_Val:
  14513. mclk = 32000UL;
  14514. break;
  14515. case GCLK_GENCTRL_SRC_XOSC32K_Val:
  14516. mclk = 32000UL;
  14517. break;
  14518. case GCLK_GENCTRL_SRC_DFLL_Val:
  14519. mclk = 48000000UL; /* 48MHz */
  14520. break;
  14521. case GCLK_GENCTRL_SRC_DPLL0_Val:
  14522. mclk = 200000000UL; /* 200MHz */
  14523. break;
  14524. case GCLK_GENCTRL_SRC_DPLL1_Val:
  14525. mclk = 200000000UL; /* 200MHz */
  14526. break;
  14527. default:
  14528. mclk = 200000000UL; /* 200MHz */
  14529. }
  14530. mclk /= div;
  14531. uint8_t crs[] = {0, 1, 2, 3, 4, 5}; // GMAC->NCFGR::CLK values
  14532. uint8_t dividers[] = {8, 16, 32, 48, 64, 96}; // Respective CLK dividers
  14533. for (int i = 0; i < 6; i++) {
  14534. if (mclk / dividers[i] <= 2375000UL /* 2.5MHz - 5% */) {
  14535. return crs[i];
  14536. }
  14537. }
  14538. return 5;
  14539. }
  14540. }
  14541. static bool mg_tcpip_driver_same54_init(struct mg_tcpip_if *ifp) {
  14542. struct mg_tcpip_driver_same54_data *d =
  14543. (struct mg_tcpip_driver_same54_data *) ifp->driver_data;
  14544. s_ifp = ifp;
  14545. MCLK_REGS->MCLK_APBCMASK |= MCLK_APBCMASK_GMAC_Msk;
  14546. MCLK_REGS->MCLK_AHBMASK |= MCLK_AHBMASK_GMAC_Msk;
  14547. GMAC_REGS->GMAC_NCFGR = GMAC_NCFGR_CLK(get_clock_rate(d)); // Set MDC divider
  14548. GMAC_REGS->GMAC_NCR = 0; // Disable RX & TX
  14549. GMAC_REGS->GMAC_NCR |= GMAC_NCR_MPE_Msk; // Enable MDC & MDIO
  14550. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init TX descriptors
  14551. s_txdesc[i][0] = (uint32_t) s_txbuf[i]; // Point to data buffer
  14552. s_txdesc[i][1] = MG_BIT(31); // OWN bit
  14553. }
  14554. s_txdesc[ETH_DESC_CNT - 1][1] |= MG_BIT(30); // Last tx descriptor - wrap
  14555. GMAC_REGS->GMAC_DCFGR = GMAC_DCFGR_DRBS(0x18) // DMA recv buf 1536
  14556. | GMAC_DCFGR_RXBMS(GMAC_DCFGR_RXBMS_FULL_Val) |
  14557. GMAC_DCFGR_TXPBMS(1); // See #2487
  14558. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init RX descriptors
  14559. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i]; // Address of the data buffer
  14560. s_rxdesc[i][1] = 0; // Clear status
  14561. }
  14562. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(1); // Last rx descriptor - wrap
  14563. GMAC_REGS->GMAC_TBQB = (uint32_t) s_txdesc; // about the descriptor addresses
  14564. GMAC_REGS->GMAC_RBQB = (uint32_t) s_rxdesc; // Let the controller know
  14565. GMAC_REGS->SA[0].GMAC_SAB =
  14566. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  14567. GMAC_REGS->SA[0].GMAC_SAT = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  14568. GMAC_REGS->GMAC_UR &= ~GMAC_UR_MII_Msk; // Disable MII, use RMII
  14569. GMAC_REGS->GMAC_NCFGR |= GMAC_NCFGR_MAXFS_Msk | GMAC_NCFGR_MTIHEN_Msk |
  14570. GMAC_NCFGR_EFRHD_Msk | GMAC_NCFGR_CAF_Msk;
  14571. GMAC_REGS->GMAC_TSR = GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk |
  14572. GMAC_TSR_TXCOMP_Msk | GMAC_TSR_TFC_Msk |
  14573. GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  14574. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk;
  14575. GMAC_REGS->GMAC_RSR = GMAC_RSR_HNO_Msk | GMAC_RSR_RXOVR_Msk |
  14576. GMAC_RSR_REC_Msk | GMAC_RSR_BNA_Msk;
  14577. GMAC_REGS->GMAC_IDR = ~0U; // Disable interrupts, then enable required
  14578. GMAC_REGS->GMAC_IER = GMAC_IER_HRESP_Msk | GMAC_IER_ROVR_Msk |
  14579. GMAC_IER_TCOMP_Msk | GMAC_IER_TFC_Msk |
  14580. GMAC_IER_RLEX_Msk | GMAC_IER_TUR_Msk |
  14581. GMAC_IER_RXUBR_Msk | GMAC_IER_RCOMP_Msk;
  14582. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TXEN_Msk | GMAC_NCR_RXEN_Msk;
  14583. NVIC_EnableIRQ(GMAC_IRQn);
  14584. return true;
  14585. }
  14586. static size_t mg_tcpip_driver_same54_tx(const void *buf, size_t len,
  14587. struct mg_tcpip_if *ifp) {
  14588. if (len > sizeof(s_txbuf[s_txno])) {
  14589. MG_ERROR(("Frame too big, %ld", (long) len));
  14590. len = 0; // Frame is too big
  14591. } else if ((s_txdesc[s_txno][1] & MG_BIT(31)) == 0) {
  14592. ifp->nerr++;
  14593. MG_ERROR(("No free descriptors"));
  14594. len = 0; // All descriptors are busy, fail
  14595. } else {
  14596. uint32_t status = len | MG_BIT(15); // Frame length, last chunk
  14597. if (s_txno == ETH_DESC_CNT - 1) status |= MG_BIT(30); // wrap
  14598. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14599. s_txdesc[s_txno][1] = status;
  14600. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14601. }
  14602. __DSB(); // Ensure descriptors have been written
  14603. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TSTART_Msk; // Enable transmission
  14604. return len;
  14605. }
  14606. static bool mg_tcpip_driver_same54_up(struct mg_tcpip_if *ifp) {
  14607. uint16_t bsr = eth_read_phy(MG_PHY_ADDR, MG_PHYREG_BSR);
  14608. bool up = bsr & MG_PHYREGBIT_BSR_LINK_STATUS ? 1 : 0;
  14609. // If PHY is ready, update NCFGR accordingly
  14610. if (ifp->state == MG_TCPIP_STATE_DOWN && up) {
  14611. uint16_t bcr = eth_read_phy(MG_PHY_ADDR, MG_PHYREG_BCR);
  14612. bool fd = bcr & MG_PHYREGBIT_BCR_DUPLEX_MODE ? 1 : 0;
  14613. bool spd = bcr & MG_PHYREGBIT_BCR_SPEED ? 1 : 0;
  14614. GMAC_REGS->GMAC_NCFGR = (GMAC_REGS->GMAC_NCFGR &
  14615. ~(GMAC_NCFGR_SPD_Msk | MG_PHYREGBIT_BCR_SPEED)) |
  14616. GMAC_NCFGR_SPD(spd) | GMAC_NCFGR_FD(fd);
  14617. }
  14618. return up;
  14619. }
  14620. void GMAC_Handler(void);
  14621. void GMAC_Handler(void) {
  14622. uint32_t isr = GMAC_REGS->GMAC_ISR;
  14623. uint32_t rsr = GMAC_REGS->GMAC_RSR;
  14624. uint32_t tsr = GMAC_REGS->GMAC_TSR;
  14625. if (isr & GMAC_ISR_RCOMP_Msk) {
  14626. if (rsr & GMAC_ISR_RCOMP_Msk) {
  14627. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  14628. if ((s_rxdesc[s_rxno][0] & MG_BIT(0)) == 0) break;
  14629. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  14630. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  14631. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // Disown
  14632. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14633. }
  14634. }
  14635. }
  14636. if ((tsr & (GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk | GMAC_TSR_TXCOMP_Msk |
  14637. GMAC_TSR_TFC_Msk | GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  14638. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk)) != 0) {
  14639. // MG_INFO((" --> %#x %#x", s_txdesc[s_txno][1], tsr));
  14640. if (!(s_txdesc[s_txno][1] & MG_BIT(31))) s_txdesc[s_txno][1] |= MG_BIT(31);
  14641. }
  14642. GMAC_REGS->GMAC_RSR = rsr;
  14643. GMAC_REGS->GMAC_TSR = tsr;
  14644. }
  14645. struct mg_tcpip_driver mg_tcpip_driver_same54 = {
  14646. mg_tcpip_driver_same54_init, mg_tcpip_driver_same54_tx, NULL,
  14647. mg_tcpip_driver_same54_up};
  14648. #endif
  14649. #ifdef MG_ENABLE_LINES
  14650. #line 1 "src/drivers/stm32f.c"
  14651. #endif
  14652. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
  14653. MG_ENABLE_DRIVER_STM32F
  14654. struct stm32f_eth {
  14655. volatile uint32_t MACCR, MACFFR, MACHTHR, MACHTLR, MACMIIAR, MACMIIDR, MACFCR,
  14656. MACVLANTR, RESERVED0[2], MACRWUFFR, MACPMTCSR, RESERVED1, MACDBGR, MACSR,
  14657. MACIMR, MACA0HR, MACA0LR, MACA1HR, MACA1LR, MACA2HR, MACA2LR, MACA3HR,
  14658. MACA3LR, RESERVED2[40], MMCCR, MMCRIR, MMCTIR, MMCRIMR, MMCTIMR,
  14659. RESERVED3[14], MMCTGFSCCR, MMCTGFMSCCR, RESERVED4[5], MMCTGFCR,
  14660. RESERVED5[10], MMCRFCECR, MMCRFAECR, RESERVED6[10], MMCRGUFCR,
  14661. RESERVED7[334], PTPTSCR, PTPSSIR, PTPTSHR, PTPTSLR, PTPTSHUR, PTPTSLUR,
  14662. PTPTSAR, PTPTTHR, PTPTTLR, RESERVED8, PTPTSSR, PTPPPSCR, RESERVED9[564],
  14663. DMABMR, DMATPDR, DMARPDR, DMARDLAR, DMATDLAR, DMASR, DMAOMR, DMAIER,
  14664. DMAMFBOCR, DMARSWTR, RESERVED10[8], DMACHTDR, DMACHRDR, DMACHTBAR,
  14665. DMACHRBAR;
  14666. };
  14667. #undef ETH
  14668. #define ETH ((struct stm32f_eth *) (uintptr_t) 0x40028000)
  14669. #define ETH_PKT_SIZE 1540 // Max frame size
  14670. #define ETH_DESC_CNT 4 // Descriptors count
  14671. #define ETH_DS 4 // Descriptor size (words)
  14672. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  14673. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  14674. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  14675. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  14676. static uint8_t s_txno; // Current TX descriptor
  14677. static uint8_t s_rxno; // Current RX descriptor
  14678. static struct mg_tcpip_if *s_ifp; // MIP interface
  14679. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  14680. ETH->MACMIIAR &= (7 << 2);
  14681. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  14682. ETH->MACMIIAR |= MG_BIT(0);
  14683. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  14684. return ETH->MACMIIDR & 0xffff;
  14685. }
  14686. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14687. ETH->MACMIIDR = val;
  14688. ETH->MACMIIAR &= (7 << 2);
  14689. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  14690. ETH->MACMIIAR |= MG_BIT(0);
  14691. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  14692. }
  14693. static uint32_t get_hclk(void) {
  14694. struct rcc {
  14695. volatile uint32_t CR, PLLCFGR, CFGR;
  14696. } *rcc = (struct rcc *) 0x40023800;
  14697. uint32_t clk = 0, hsi = 16000000 /* 16 MHz */, hse = 8000000 /* 8MHz */;
  14698. if (rcc->CFGR & (1 << 2)) {
  14699. clk = hse;
  14700. } else if (rcc->CFGR & (1 << 3)) {
  14701. uint32_t vco, m, n, p;
  14702. m = (rcc->PLLCFGR & (0x3f << 0)) >> 0;
  14703. n = (rcc->PLLCFGR & (0x1ff << 6)) >> 6;
  14704. p = (((rcc->PLLCFGR & (3 << 16)) >> 16) + 1) * 2;
  14705. clk = (rcc->PLLCFGR & (1 << 22)) ? hse : hsi;
  14706. vco = (uint32_t) ((uint64_t) clk * n / m);
  14707. clk = vco / p;
  14708. } else {
  14709. clk = hsi;
  14710. }
  14711. uint32_t hpre = (rcc->CFGR & (15 << 4)) >> 4;
  14712. if (hpre < 8) return clk;
  14713. uint8_t ahbptab[8] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  14714. return ((uint32_t) clk) >> ahbptab[hpre - 8];
  14715. }
  14716. // Guess CR from HCLK. MDC clock is generated from HCLK (AHB); as per 802.3,
  14717. // it must not exceed 2.5MHz As the AHB clock can be (and usually is) derived
  14718. // from the HSI (internal RC), and it can go above specs, the datasheets
  14719. // specify a range of frequencies and activate one of a series of dividers to
  14720. // keep the MDC clock safely below 2.5MHz. We guess a divider setting based on
  14721. // HCLK with a +5% drift. If the user uses a different clock from our
  14722. // defaults, needs to set the macros on top Valid for STM32F74xxx/75xxx
  14723. // (38.8.1) and STM32F42xxx/43xxx (33.8.1) (both 4.5% worst case drift)
  14724. static int guess_mdc_cr(void) {
  14725. uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMIIAR::CR values
  14726. uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  14727. uint32_t hclk = get_hclk(); // Guess system HCLK
  14728. int result = -1; // Invalid CR value
  14729. if (hclk < 25000000) {
  14730. MG_ERROR(("HCLK too low"));
  14731. } else {
  14732. for (int i = 0; i < 6; i++) {
  14733. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  14734. result = crs[i];
  14735. break;
  14736. }
  14737. }
  14738. if (result < 0) MG_ERROR(("HCLK too high"));
  14739. }
  14740. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  14741. return result;
  14742. }
  14743. static bool mg_tcpip_driver_stm32f_init(struct mg_tcpip_if *ifp) {
  14744. struct mg_tcpip_driver_stm32f_data *d =
  14745. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  14746. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  14747. s_ifp = ifp;
  14748. // Init RX descriptors
  14749. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14750. s_rxdesc[i][0] = MG_BIT(31); // Own
  14751. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  14752. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  14753. s_rxdesc[i][3] =
  14754. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  14755. }
  14756. // Init TX descriptors
  14757. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14758. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  14759. s_txdesc[i][3] =
  14760. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  14761. }
  14762. ETH->DMABMR |= MG_BIT(0); // Software reset
  14763. while ((ETH->DMABMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  14764. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  14765. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  14766. ETH->MACMIIAR = ((uint32_t) cr & 7) << 2;
  14767. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  14768. // hardware checksum. Therefore, descriptor size is 4, not 8
  14769. // ETH->DMABMR = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) |
  14770. // MG_BIT(25);
  14771. ETH->MACIMR = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  14772. ETH->MACFCR = MG_BIT(7); // Disable zero quarta pause
  14773. // ETH->MACFFR = MG_BIT(31); // Receive all
  14774. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  14775. mg_phy_init(&phy, phy_addr, MG_PHY_CLOCKS_MAC);
  14776. ETH->DMARDLAR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  14777. ETH->DMATDLAR = (uint32_t) (uintptr_t) s_txdesc; // RX descriptors
  14778. ETH->DMAIER = MG_BIT(6) | MG_BIT(16); // RIE, NISE
  14779. ETH->MACCR =
  14780. MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  14781. ETH->DMAOMR =
  14782. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  14783. // MAC address filtering
  14784. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  14785. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  14786. ((uint32_t) ifp->mac[2] << 16) |
  14787. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  14788. return true;
  14789. }
  14790. static size_t mg_tcpip_driver_stm32f_tx(const void *buf, size_t len,
  14791. struct mg_tcpip_if *ifp) {
  14792. if (len > sizeof(s_txbuf[s_txno])) {
  14793. MG_ERROR(("Frame too big, %ld", (long) len));
  14794. len = 0; // Frame is too big
  14795. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  14796. ifp->nerr++;
  14797. MG_ERROR(("No free descriptors"));
  14798. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long) ETH->DMASR);
  14799. len = 0; // All descriptors are busy, fail
  14800. } else {
  14801. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14802. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  14803. s_txdesc[s_txno][0] = MG_BIT(20) | MG_BIT(28) | MG_BIT(29); // Chain,FS,LS
  14804. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  14805. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14806. }
  14807. MG_DSB(); // ensure descriptors have been written
  14808. ETH->DMASR = MG_BIT(2) | MG_BIT(5); // Clear any prior TBUS/TUS
  14809. ETH->DMATPDR = 0; // and resume
  14810. return len;
  14811. }
  14812. static bool mg_tcpip_driver_stm32f_up(struct mg_tcpip_if *ifp) {
  14813. struct mg_tcpip_driver_stm32f_data *d =
  14814. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  14815. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  14816. uint8_t speed = MG_PHY_SPEED_10M;
  14817. bool up = false, full_duplex = false;
  14818. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  14819. up = mg_phy_up(&phy, phy_addr, &full_duplex, &speed);
  14820. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14821. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14822. // if(link is slow or half) set flags otherwise
  14823. // reg = tmp
  14824. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  14825. if (speed == MG_PHY_SPEED_10M) maccr &= ~MG_BIT(14); // 10M
  14826. if (full_duplex == false) maccr &= ~MG_BIT(11); // Half-duplex
  14827. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  14828. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  14829. maccr & MG_BIT(11) ? "full" : "half"));
  14830. }
  14831. return up;
  14832. }
  14833. #ifdef __riscv
  14834. __attribute__((interrupt())) // For RISCV CH32V307, which share the same MAC
  14835. #endif
  14836. void ETH_IRQHandler(void);
  14837. void ETH_IRQHandler(void) {
  14838. if (ETH->DMASR & MG_BIT(6)) { // Frame received, loop
  14839. ETH->DMASR = MG_BIT(16) | MG_BIT(6); // Clear flag
  14840. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14841. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  14842. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) ==
  14843. (MG_BIT(8) | MG_BIT(9))) &&
  14844. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  14845. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  14846. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  14847. // ETH->DMASR);
  14848. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  14849. }
  14850. s_rxdesc[s_rxno][0] = MG_BIT(31);
  14851. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14852. }
  14853. }
  14854. // Cleanup flags
  14855. ETH->DMASR = MG_BIT(16) // NIS, normal interrupt summary
  14856. | MG_BIT(7); // Clear possible RBUS while processing
  14857. ETH->DMARPDR = 0; // and resume RX
  14858. }
  14859. struct mg_tcpip_driver mg_tcpip_driver_stm32f = {
  14860. mg_tcpip_driver_stm32f_init, mg_tcpip_driver_stm32f_tx, NULL,
  14861. mg_tcpip_driver_stm32f_up};
  14862. #endif
  14863. #ifdef MG_ENABLE_LINES
  14864. #line 1 "src/drivers/stm32h.c"
  14865. #endif
  14866. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32H) && \
  14867. MG_ENABLE_DRIVER_STM32H
  14868. struct stm32h_eth {
  14869. volatile uint32_t MACCR, MACECR, MACPFR, MACWTR, MACHT0R, MACHT1R,
  14870. RESERVED1[14], MACVTR, RESERVED2, MACVHTR, RESERVED3, MACVIR, MACIVIR,
  14871. RESERVED4[2], MACTFCR, RESERVED5[7], MACRFCR, RESERVED6[7], MACISR,
  14872. MACIER, MACRXTXSR, RESERVED7, MACPCSR, MACRWKPFR, RESERVED8[2], MACLCSR,
  14873. MACLTCR, MACLETR, MAC1USTCR, RESERVED9[12], MACVR, MACDR, RESERVED10,
  14874. MACHWF0R, MACHWF1R, MACHWF2R, RESERVED11[54], MACMDIOAR, MACMDIODR,
  14875. RESERVED12[2], MACARPAR, RESERVED13[59], MACA0HR, MACA0LR, MACA1HR,
  14876. MACA1LR, MACA2HR, MACA2LR, MACA3HR, MACA3LR, RESERVED14[248], MMCCR,
  14877. MMCRIR, MMCTIR, MMCRIMR, MMCTIMR, RESERVED15[14], MMCTSCGPR, MMCTMCGPR,
  14878. RESERVED16[5], MMCTPCGR, RESERVED17[10], MMCRCRCEPR, MMCRAEPR,
  14879. RESERVED18[10], MMCRUPGR, RESERVED19[9], MMCTLPIMSTR, MMCTLPITCR,
  14880. MMCRLPIMSTR, MMCRLPITCR, RESERVED20[65], MACL3L4C0R, MACL4A0R,
  14881. RESERVED21[2], MACL3A0R0R, MACL3A1R0R, MACL3A2R0R, MACL3A3R0R,
  14882. RESERVED22[4], MACL3L4C1R, MACL4A1R, RESERVED23[2], MACL3A0R1R,
  14883. MACL3A1R1R, MACL3A2R1R, MACL3A3R1R, RESERVED24[108], MACTSCR, MACSSIR,
  14884. MACSTSR, MACSTNR, MACSTSUR, MACSTNUR, MACTSAR, RESERVED25, MACTSSR,
  14885. RESERVED26[3], MACTTSSNR, MACTTSSSR, RESERVED27[2], MACACR, RESERVED28,
  14886. MACATSNR, MACATSSR, MACTSIACR, MACTSEACR, MACTSICNR, MACTSECNR,
  14887. RESERVED29[4], MACPPSCR, RESERVED30[3], MACPPSTTSR, MACPPSTTNR, MACPPSIR,
  14888. MACPPSWR, RESERVED31[12], MACPOCR, MACSPI0R, MACSPI1R, MACSPI2R, MACLMIR,
  14889. RESERVED32[11], MTLOMR, RESERVED33[7], MTLISR, RESERVED34[55], MTLTQOMR,
  14890. MTLTQUR, MTLTQDR, RESERVED35[8], MTLQICSR, MTLRQOMR, MTLRQMPOCR, MTLRQDR,
  14891. RESERVED36[177], DMAMR, DMASBMR, DMAISR, DMADSR, RESERVED37[60], DMACCR,
  14892. DMACTCR, DMACRCR, RESERVED38[2], DMACTDLAR, RESERVED39, DMACRDLAR,
  14893. DMACTDTPR, RESERVED40, DMACRDTPR, DMACTDRLR, DMACRDRLR, DMACIER,
  14894. DMACRIWTR, DMACSFCSR, RESERVED41, DMACCATDR, RESERVED42, DMACCARDR,
  14895. RESERVED43, DMACCATBR, RESERVED44, DMACCARBR, DMACSR, RESERVED45[2],
  14896. DMACMFCR;
  14897. };
  14898. #undef ETH
  14899. #define ETH \
  14900. ((struct stm32h_eth *) (uintptr_t) (0x40000000UL + 0x00020000UL + 0x8000UL))
  14901. #define ETH_PKT_SIZE 1540 // Max frame size
  14902. #define ETH_DESC_CNT 4 // Descriptors count
  14903. #define ETH_DS 4 // Descriptor size (words)
  14904. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  14905. static volatile uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  14906. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  14907. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  14908. static struct mg_tcpip_if *s_ifp; // MIP interface
  14909. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  14910. ETH->MACMDIOAR &= (0xF << 8);
  14911. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 3 << 2;
  14912. ETH->MACMDIOAR |= MG_BIT(0);
  14913. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  14914. return (uint16_t) ETH->MACMDIODR;
  14915. }
  14916. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14917. ETH->MACMDIODR = val;
  14918. ETH->MACMDIOAR &= (0xF << 8);
  14919. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 1 << 2;
  14920. ETH->MACMDIOAR |= MG_BIT(0);
  14921. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  14922. }
  14923. static uint32_t get_hclk(void) {
  14924. struct rcc {
  14925. volatile uint32_t CR, HSICFGR, CRRCR, CSICFGR, CFGR, RESERVED1, D1CFGR,
  14926. D2CFGR, D3CFGR, RESERVED2, PLLCKSELR, PLLCFGR, PLL1DIVR, PLL1FRACR,
  14927. PLL2DIVR, PLL2FRACR, PLL3DIVR, PLL3FRACR, RESERVED3, D1CCIPR, D2CCIP1R,
  14928. D2CCIP2R, D3CCIPR, RESERVED4, CIER, CIFR, CICR, RESERVED5, BDCR, CSR,
  14929. RESERVED6, AHB3RSTR, AHB1RSTR, AHB2RSTR, AHB4RSTR, APB3RSTR, APB1LRSTR,
  14930. APB1HRSTR, APB2RSTR, APB4RSTR, GCR, RESERVED8, D3AMR, RESERVED11[9],
  14931. RSR, AHB3ENR, AHB1ENR, AHB2ENR, AHB4ENR, APB3ENR, APB1LENR, APB1HENR,
  14932. APB2ENR, APB4ENR, RESERVED12, AHB3LPENR, AHB1LPENR, AHB2LPENR,
  14933. AHB4LPENR, APB3LPENR, APB1LLPENR, APB1HLPENR, APB2LPENR, APB4LPENR,
  14934. RESERVED13[4];
  14935. } *rcc = ((struct rcc *) (0x40000000 + 0x18020000 + 0x4400));
  14936. uint32_t clk = 0, hsi = 64000000 /* 64 MHz */, hse = 8000000 /* 8MHz */,
  14937. csi = 4000000 /* 4MHz */;
  14938. unsigned int sel = (rcc->CFGR & (7 << 3)) >> 3;
  14939. if (sel == 1) {
  14940. clk = csi;
  14941. } else if (sel == 2) {
  14942. clk = hse;
  14943. } else if (sel == 3) {
  14944. uint32_t vco, m, n, p;
  14945. unsigned int src = (rcc->PLLCKSELR & (3 << 0)) >> 0;
  14946. m = ((rcc->PLLCKSELR & (0x3F << 4)) >> 4);
  14947. n = ((rcc->PLL1DIVR & (0x1FF << 0)) >> 0) + 1 +
  14948. ((rcc->PLLCFGR & MG_BIT(0)) ? 1 : 0); // round-up in fractional mode
  14949. p = ((rcc->PLL1DIVR & (0x7F << 9)) >> 9) + 1;
  14950. if (src == 1) {
  14951. clk = csi;
  14952. } else if (src == 2) {
  14953. clk = hse;
  14954. } else {
  14955. clk = hsi;
  14956. clk >>= ((rcc->CR & 3) >> 3);
  14957. }
  14958. vco = (uint32_t) ((uint64_t) clk * n / m);
  14959. clk = vco / p;
  14960. } else {
  14961. clk = hsi;
  14962. clk >>= ((rcc->CR & 3) >> 3);
  14963. }
  14964. const uint8_t cptab[12] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  14965. uint32_t d1cpre = (rcc->D1CFGR & (0x0F << 8)) >> 8;
  14966. if (d1cpre >= 8) clk >>= cptab[d1cpre - 8];
  14967. MG_DEBUG(("D1 CLK: %u", clk));
  14968. uint32_t hpre = (rcc->D1CFGR & (0x0F << 0)) >> 0;
  14969. if (hpre < 8) return clk;
  14970. return ((uint32_t) clk) >> cptab[hpre - 8];
  14971. }
  14972. // Guess CR from AHB1 clock. MDC clock is generated from the ETH peripheral
  14973. // clock (AHB1); as per 802.3, it must not exceed 2. As the AHB clock can
  14974. // be derived from HSI or CSI (internal RC) clocks, and those can go above
  14975. // specs, the datasheets specify a range of frequencies and activate one of a
  14976. // series of dividers to keep the MDC clock safely below 2.5MHz. We guess a
  14977. // divider setting based on HCLK with some drift. If the user uses a different
  14978. // clock from our defaults, needs to set the macros on top. Valid for
  14979. // STM32H74xxx/75xxx (58.11.4)(4.5% worst case drift)(CSI clock has a 7.5 %
  14980. // worst case drift @ max temp)
  14981. static int guess_mdc_cr(void) {
  14982. const uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMDIOAR::CR values
  14983. const uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  14984. uint32_t hclk = get_hclk(); // Guess system HCLK
  14985. int result = -1; // Invalid CR value
  14986. for (int i = 0; i < 6; i++) {
  14987. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  14988. result = crs[i];
  14989. break;
  14990. }
  14991. }
  14992. if (result < 0) MG_ERROR(("HCLK too high"));
  14993. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  14994. return result;
  14995. }
  14996. static bool mg_tcpip_driver_stm32h_init(struct mg_tcpip_if *ifp) {
  14997. struct mg_tcpip_driver_stm32h_data *d =
  14998. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  14999. s_ifp = ifp;
  15000. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  15001. uint8_t phy_conf = d == NULL ? MG_PHY_CLOCKS_MAC : d->phy_conf;
  15002. // Init RX descriptors
  15003. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15004. s_rxdesc[i][0] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  15005. s_rxdesc[i][3] = MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  15006. }
  15007. // Init TX descriptors
  15008. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15009. s_txdesc[i][0] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  15010. }
  15011. ETH->DMAMR |= MG_BIT(0); // Software reset
  15012. while ((ETH->DMAMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  15013. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  15014. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  15015. ETH->MACMDIOAR = ((uint32_t) cr & 0xF) << 8;
  15016. // NOTE(scaprile): We do not use timing facilities so the DMA engine does not
  15017. // re-write buffer address
  15018. ETH->DMAMR = 0 << 16; // use interrupt mode 0 (58.8.1) (reset value)
  15019. ETH->DMASBMR |= MG_BIT(12); // AAL NOTE(scaprile): is this actually needed
  15020. ETH->MACIER = 0; // Do not enable additional irq sources (reset value)
  15021. ETH->MACTFCR = MG_BIT(7); // Disable zero-quanta pause
  15022. // ETH->MACPFR = MG_BIT(31); // Receive all
  15023. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15024. mg_phy_init(&phy, phy_addr, phy_conf);
  15025. ETH->DMACRDLAR =
  15026. (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors start address
  15027. ETH->DMACRDRLR = ETH_DESC_CNT - 1; // ring length
  15028. ETH->DMACRDTPR =
  15029. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT -
  15030. 1]; // last valid descriptor address
  15031. ETH->DMACTDLAR =
  15032. (uint32_t) (uintptr_t) s_txdesc; // TX descriptors start address
  15033. ETH->DMACTDRLR = ETH_DESC_CNT - 1; // ring length
  15034. ETH->DMACTDTPR =
  15035. (uint32_t) (uintptr_t) s_txdesc; // first available descriptor address
  15036. ETH->DMACCR = 0; // DSL = 0 (contiguous descriptor table) (reset value)
  15037. ETH->DMACIER = MG_BIT(6) | MG_BIT(15); // RIE, NIE
  15038. ETH->MACCR = MG_BIT(0) | MG_BIT(1) | MG_BIT(13) | MG_BIT(14) |
  15039. MG_BIT(15); // RE, TE, Duplex, Fast, Reserved
  15040. ETH->MTLTQOMR |= MG_BIT(1); // TSF
  15041. ETH->MTLRQOMR |= MG_BIT(5); // RSF
  15042. ETH->DMACTCR |= MG_BIT(0); // ST
  15043. ETH->DMACRCR |= MG_BIT(0); // SR
  15044. // MAC address filtering
  15045. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  15046. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  15047. ((uint32_t) ifp->mac[2] << 16) |
  15048. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  15049. return true;
  15050. }
  15051. static uint32_t s_txno;
  15052. static size_t mg_tcpip_driver_stm32h_tx(const void *buf, size_t len,
  15053. struct mg_tcpip_if *ifp) {
  15054. if (len > sizeof(s_txbuf[s_txno])) {
  15055. MG_ERROR(("Frame too big, %ld", (long) len));
  15056. len = 0; // Frame is too big
  15057. } else if ((s_txdesc[s_txno][3] & MG_BIT(31))) {
  15058. ifp->nerr++;
  15059. MG_ERROR(("No free descriptors: %u %08X %08X %08X", s_txno,
  15060. s_txdesc[s_txno][3], ETH->DMACSR, ETH->DMACTCR));
  15061. for (int i = 0; i < ETH_DESC_CNT; i++) MG_ERROR(("%08X", s_txdesc[i][3]));
  15062. len = 0; // All descriptors are busy, fail
  15063. } else {
  15064. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  15065. s_txdesc[s_txno][2] = (uint32_t) len; // Set data len
  15066. s_txdesc[s_txno][3] = MG_BIT(28) | MG_BIT(29); // FD, LD
  15067. s_txdesc[s_txno][3] |= MG_BIT(31); // Set OWN bit - let DMA take over
  15068. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15069. }
  15070. ETH->DMACSR |= MG_BIT(2) | MG_BIT(1); // Clear any prior TBU, TPS
  15071. ETH->DMACTDTPR = (uint32_t) (uintptr_t) &s_txdesc[s_txno]; // and resume
  15072. return len;
  15073. (void) ifp;
  15074. }
  15075. static bool mg_tcpip_driver_stm32h_up(struct mg_tcpip_if *ifp) {
  15076. struct mg_tcpip_driver_stm32h_data *d =
  15077. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  15078. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  15079. uint8_t speed = MG_PHY_SPEED_10M;
  15080. bool up = false, full_duplex = false;
  15081. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15082. up = mg_phy_up(&phy, phy_addr, &full_duplex, &speed);
  15083. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15084. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  15085. // if(link is slow or half) set flags otherwise
  15086. // reg = tmp
  15087. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(13); // 100M, Full-duplex
  15088. if (speed == MG_PHY_SPEED_10M) maccr &= ~MG_BIT(14); // 10M
  15089. if (full_duplex == false) maccr &= ~MG_BIT(13); // Half-duplex
  15090. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  15091. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  15092. maccr & MG_BIT(13) ? "full" : "half"));
  15093. }
  15094. return up;
  15095. }
  15096. void ETH_IRQHandler(void);
  15097. static uint32_t s_rxno;
  15098. void ETH_IRQHandler(void) {
  15099. if (ETH->DMACSR & MG_BIT(6)) { // Frame received, loop
  15100. ETH->DMACSR = MG_BIT(15) | MG_BIT(6); // Clear flag
  15101. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  15102. if (s_rxdesc[s_rxno][3] & MG_BIT(31)) break; // exit when done
  15103. if (((s_rxdesc[s_rxno][3] & (MG_BIT(28) | MG_BIT(29))) ==
  15104. (MG_BIT(28) | MG_BIT(29))) &&
  15105. !(s_rxdesc[s_rxno][3] & MG_BIT(15))) { // skip partial/errored frames
  15106. uint32_t len = s_rxdesc[s_rxno][3] & (MG_BIT(15) - 1);
  15107. // MG_DEBUG(("%lx %lu %lx %08lx", s_rxno, len, s_rxdesc[s_rxno][3],
  15108. // ETH->DMACSR));
  15109. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  15110. }
  15111. s_rxdesc[s_rxno][3] =
  15112. MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  15113. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15114. }
  15115. }
  15116. ETH->DMACSR =
  15117. MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing
  15118. ETH->DMACRDTPR =
  15119. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT - 1]; // and resume RX
  15120. }
  15121. struct mg_tcpip_driver mg_tcpip_driver_stm32h = {
  15122. mg_tcpip_driver_stm32h_init, mg_tcpip_driver_stm32h_tx, NULL,
  15123. mg_tcpip_driver_stm32h_up};
  15124. #endif
  15125. #ifdef MG_ENABLE_LINES
  15126. #line 1 "src/drivers/tm4c.c"
  15127. #endif
  15128. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
  15129. struct tm4c_emac {
  15130. volatile uint32_t EMACCFG, EMACFRAMEFLTR, EMACHASHTBLH, EMACHASHTBLL,
  15131. EMACMIIADDR, EMACMIIDATA, EMACFLOWCTL, EMACVLANTG, RESERVED0, EMACSTATUS,
  15132. EMACRWUFF, EMACPMTCTLSTAT, RESERVED1[2], EMACRIS, EMACIM, EMACADDR0H,
  15133. EMACADDR0L, EMACADDR1H, EMACADDR1L, EMACADDR2H, EMACADDR2L, EMACADDR3H,
  15134. EMACADDR3L, RESERVED2[31], EMACWDOGTO, RESERVED3[8], EMACMMCCTRL,
  15135. EMACMMCRXRIS, EMACMMCTXRIS, EMACMMCRXIM, EMACMMCTXIM, RESERVED4,
  15136. EMACTXCNTGB, RESERVED5[12], EMACTXCNTSCOL, EMACTXCNTMCOL, RESERVED6[4],
  15137. EMACTXOCTCNTG, RESERVED7[6], EMACRXCNTGB, RESERVED8[4], EMACRXCNTCRCERR,
  15138. EMACRXCNTALGNERR, RESERVED9[10], EMACRXCNTGUNI, RESERVED10[239],
  15139. EMACVLNINCREP, EMACVLANHASH, RESERVED11[93], EMACTIMSTCTRL, EMACSUBSECINC,
  15140. EMACTIMSEC, EMACTIMNANO, EMACTIMSECU, EMACTIMNANOU, EMACTIMADD,
  15141. EMACTARGSEC, EMACTARGNANO, EMACHWORDSEC, EMACTIMSTAT, EMACPPSCTRL,
  15142. RESERVED12[12], EMACPPS0INTVL, EMACPPS0WIDTH, RESERVED13[294],
  15143. EMACDMABUSMOD, EMACTXPOLLD, EMACRXPOLLD, EMACRXDLADDR, EMACTXDLADDR,
  15144. EMACDMARIS, EMACDMAOPMODE, EMACDMAIM, EMACMFBOC, EMACRXINTWDT,
  15145. RESERVED14[8], EMACHOSTXDESC, EMACHOSRXDESC, EMACHOSTXBA, EMACHOSRXBA,
  15146. RESERVED15[218], EMACPP, EMACPC, EMACCC, RESERVED16, EMACEPHYRIS,
  15147. EMACEPHYIM, EMACEPHYIMSC;
  15148. };
  15149. #undef EMAC
  15150. #define EMAC ((struct tm4c_emac *) (uintptr_t) 0x400EC000)
  15151. #define ETH_PKT_SIZE 1540 // Max frame size
  15152. #define ETH_DESC_CNT 4 // Descriptors count
  15153. #define ETH_DS 4 // Descriptor size (words)
  15154. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15155. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15156. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  15157. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  15158. static struct mg_tcpip_if *s_ifp; // MIP interface
  15159. enum {
  15160. EPHY_ADDR = 0,
  15161. EPHYBMCR = 0,
  15162. EPHYBMSR = 1,
  15163. EPHYSTS = 16
  15164. }; // PHY constants
  15165. static inline void tm4cspin(volatile uint32_t count) {
  15166. while (count--) (void) 0;
  15167. }
  15168. static uint32_t emac_read_phy(uint8_t addr, uint8_t reg) {
  15169. EMAC->EMACMIIADDR &= (0xf << 2);
  15170. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  15171. EMAC->EMACMIIADDR |= MG_BIT(0);
  15172. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  15173. return EMAC->EMACMIIDATA;
  15174. }
  15175. static void emac_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  15176. EMAC->EMACMIIDATA = val;
  15177. EMAC->EMACMIIADDR &= (0xf << 2);
  15178. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  15179. EMAC->EMACMIIADDR |= MG_BIT(0);
  15180. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  15181. }
  15182. static uint32_t get_sysclk(void) {
  15183. struct sysctl {
  15184. volatile uint32_t DONTCARE0[44], RSCLKCFG, DONTCARE1[43], PLLFREQ0,
  15185. PLLFREQ1;
  15186. } *sysctl = (struct sysctl *) 0x400FE000;
  15187. uint32_t clk = 0, piosc = 16000000 /* 16 MHz */, mosc = 25000000 /* 25MHz */;
  15188. if (sysctl->RSCLKCFG & (1 << 28)) { // USEPLL
  15189. uint32_t fin, vco, mdiv, n, q, psysdiv;
  15190. uint32_t pllsrc = (sysctl->RSCLKCFG & (0xf << 24)) >> 24;
  15191. if (pllsrc == 0) {
  15192. clk = piosc;
  15193. } else if (pllsrc == 3) {
  15194. clk = mosc;
  15195. } else {
  15196. MG_ERROR(("Unsupported clock source"));
  15197. }
  15198. q = (sysctl->PLLFREQ1 & (0x1f << 8)) >> 8;
  15199. n = (sysctl->PLLFREQ1 & (0x1f << 0)) >> 0;
  15200. fin = clk / ((q + 1) * (n + 1));
  15201. mdiv = (sysctl->PLLFREQ0 & (0x3ff << 0)) >>
  15202. 0; // mint + (mfrac / 1024); MFRAC not supported
  15203. psysdiv = (sysctl->RSCLKCFG & (0x3f << 0)) >> 0;
  15204. vco = (uint32_t) ((uint64_t) fin * mdiv);
  15205. return vco / (psysdiv + 1);
  15206. }
  15207. uint32_t oscsrc = (sysctl->RSCLKCFG & (0xf << 20)) >> 20;
  15208. if (oscsrc == 0) {
  15209. clk = piosc;
  15210. } else if (oscsrc == 3) {
  15211. clk = mosc;
  15212. } else {
  15213. MG_ERROR(("Unsupported clock source"));
  15214. }
  15215. uint32_t osysdiv = (sysctl->RSCLKCFG & (0xf << 16)) >> 16;
  15216. return clk / (osysdiv + 1);
  15217. }
  15218. // Guess CR from SYSCLK. MDC clock is generated from SYSCLK (AHB); as per
  15219. // 802.3, it must not exceed 2.5MHz (also 20.4.2.6) As the AHB clock can be
  15220. // derived from the PIOSC (internal RC), and it can go above specs, the
  15221. // datasheets specify a range of frequencies and activate one of a series of
  15222. // dividers to keep the MDC clock safely below 2.5MHz. We guess a divider
  15223. // setting based on SYSCLK with a +5% drift. If the user uses a different clock
  15224. // from our defaults, needs to set the macros on top Valid for TM4C129x (20.7)
  15225. // (4.5% worst case drift)
  15226. // The PHY receives the main oscillator (MOSC) (20.3.1)
  15227. static int guess_mdc_cr(void) {
  15228. uint8_t crs[] = {2, 3, 0, 1}; // EMAC->MACMIIAR::CR values
  15229. uint8_t div[] = {16, 26, 42, 62}; // Respective HCLK dividers
  15230. uint32_t sysclk = get_sysclk(); // Guess system SYSCLK
  15231. int result = -1; // Invalid CR value
  15232. if (sysclk < 25000000) {
  15233. MG_ERROR(("SYSCLK too low"));
  15234. } else {
  15235. for (int i = 0; i < 4; i++) {
  15236. if (sysclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  15237. result = crs[i];
  15238. break;
  15239. }
  15240. }
  15241. if (result < 0) MG_ERROR(("SYSCLK too high"));
  15242. }
  15243. MG_DEBUG(("SYSCLK: %u, CR: %d", sysclk, result));
  15244. return result;
  15245. }
  15246. static bool mg_tcpip_driver_tm4c_init(struct mg_tcpip_if *ifp) {
  15247. struct mg_tcpip_driver_tm4c_data *d =
  15248. (struct mg_tcpip_driver_tm4c_data *) ifp->driver_data;
  15249. s_ifp = ifp;
  15250. // Init RX descriptors
  15251. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15252. s_rxdesc[i][0] = MG_BIT(31); // Own
  15253. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  15254. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  15255. s_rxdesc[i][3] =
  15256. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  15257. // MG_DEBUG(("%d %p", i, s_rxdesc[i]));
  15258. }
  15259. // Init TX descriptors
  15260. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15261. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  15262. s_txdesc[i][3] =
  15263. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  15264. }
  15265. EMAC->EMACDMABUSMOD |= MG_BIT(0); // Software reset
  15266. while ((EMAC->EMACDMABUSMOD & MG_BIT(0)) != 0) tm4cspin(1); // Wait until done
  15267. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  15268. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  15269. EMAC->EMACMIIADDR = ((uint32_t) cr & 0xf) << 2;
  15270. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  15271. // hardware checksum. Therefore, descriptor size is 4, not 8
  15272. // EMAC->EMACDMABUSMOD = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) | MG_BIT(25);
  15273. EMAC->EMACIM = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  15274. EMAC->EMACFLOWCTL = MG_BIT(7); // Disable zero-quanta pause
  15275. // EMAC->EMACFRAMEFLTR = MG_BIT(31); // Receive all
  15276. // EMAC->EMACPC defaults to internal PHY (EPHY) in MMI mode
  15277. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(15)); // Reset internal PHY (EPHY)
  15278. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(12)); // Set autonegotiation
  15279. EMAC->EMACRXDLADDR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  15280. EMAC->EMACTXDLADDR = (uint32_t) (uintptr_t) s_txdesc; // TX descriptors
  15281. EMAC->EMACDMAIM = MG_BIT(6) | MG_BIT(16); // RIE, NIE
  15282. EMAC->EMACCFG = MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  15283. EMAC->EMACDMAOPMODE =
  15284. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  15285. EMAC->EMACADDR0H = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  15286. EMAC->EMACADDR0L = (uint32_t) (ifp->mac[3] << 24) |
  15287. ((uint32_t) ifp->mac[2] << 16) |
  15288. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  15289. // NOTE(scaprile) There are 3 additional slots for filtering, disabled by
  15290. // default. This also applies to the STM32 driver (at least for F7)
  15291. return true;
  15292. }
  15293. static uint32_t s_txno;
  15294. static size_t mg_tcpip_driver_tm4c_tx(const void *buf, size_t len,
  15295. struct mg_tcpip_if *ifp) {
  15296. if (len > sizeof(s_txbuf[s_txno])) {
  15297. MG_ERROR(("Frame too big, %ld", (long) len));
  15298. len = 0; // fail
  15299. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  15300. ifp->nerr++;
  15301. MG_ERROR(("No descriptors available"));
  15302. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long)
  15303. // EMAC->EMACDMARIS);
  15304. len = 0; // fail
  15305. } else {
  15306. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  15307. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  15308. s_txdesc[s_txno][0] =
  15309. MG_BIT(20) | MG_BIT(28) | MG_BIT(29) | MG_BIT(30); // Chain,FS,LS,IC
  15310. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  15311. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15312. }
  15313. EMAC->EMACDMARIS = MG_BIT(2) | MG_BIT(5); // Clear any prior TU/UNF
  15314. EMAC->EMACTXPOLLD = 0; // and resume
  15315. return len;
  15316. (void) ifp;
  15317. }
  15318. static bool mg_tcpip_driver_tm4c_up(struct mg_tcpip_if *ifp) {
  15319. uint32_t bmsr = emac_read_phy(EPHY_ADDR, EPHYBMSR);
  15320. bool up = (bmsr & MG_BIT(2)) ? 1 : 0;
  15321. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15322. uint32_t sts = emac_read_phy(EPHY_ADDR, EPHYSTS);
  15323. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  15324. // if(link is slow or half) set flags otherwise
  15325. // reg = tmp
  15326. uint32_t emaccfg = EMAC->EMACCFG | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  15327. if (sts & MG_BIT(1)) emaccfg &= ~MG_BIT(14); // 10M
  15328. if ((sts & MG_BIT(2)) == 0) emaccfg &= ~MG_BIT(11); // Half-duplex
  15329. EMAC->EMACCFG = emaccfg; // IRQ handler does not fiddle with this register
  15330. MG_DEBUG(("Link is %uM %s-duplex", emaccfg & MG_BIT(14) ? 100 : 10,
  15331. emaccfg & MG_BIT(11) ? "full" : "half"));
  15332. }
  15333. return up;
  15334. }
  15335. void EMAC0_IRQHandler(void);
  15336. static uint32_t s_rxno;
  15337. void EMAC0_IRQHandler(void) {
  15338. if (EMAC->EMACDMARIS & MG_BIT(6)) { // Frame received, loop
  15339. EMAC->EMACDMARIS = MG_BIT(16) | MG_BIT(6); // Clear flag
  15340. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  15341. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  15342. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) == (MG_BIT(8) | MG_BIT(9))) &&
  15343. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  15344. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  15345. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  15346. // EMAC->EMACDMARIS);
  15347. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  15348. }
  15349. s_rxdesc[s_rxno][0] = MG_BIT(31);
  15350. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15351. }
  15352. }
  15353. EMAC->EMACDMARIS = MG_BIT(7); // Clear possible RU while processing
  15354. EMAC->EMACRXPOLLD = 0; // and resume RX
  15355. }
  15356. struct mg_tcpip_driver mg_tcpip_driver_tm4c = {mg_tcpip_driver_tm4c_init,
  15357. mg_tcpip_driver_tm4c_tx, NULL,
  15358. mg_tcpip_driver_tm4c_up};
  15359. #endif
  15360. #ifdef MG_ENABLE_LINES
  15361. #line 1 "src/drivers/w5500.c"
  15362. #endif
  15363. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5500) && MG_ENABLE_DRIVER_W5500
  15364. enum { W5500_CR = 0, W5500_S0 = 1, W5500_TX0 = 2, W5500_RX0 = 3 };
  15365. static void w5500_txn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr,
  15366. bool wr, void *buf, size_t len) {
  15367. size_t i;
  15368. uint8_t *p = (uint8_t *) buf;
  15369. uint8_t cmd[] = {(uint8_t) (addr >> 8), (uint8_t) (addr & 255),
  15370. (uint8_t) ((block << 3) | (wr ? 4 : 0))};
  15371. s->begin(s->spi);
  15372. for (i = 0; i < sizeof(cmd); i++) s->txn(s->spi, cmd[i]);
  15373. for (i = 0; i < len; i++) {
  15374. uint8_t r = s->txn(s->spi, p[i]);
  15375. if (!wr) p[i] = r;
  15376. }
  15377. s->end(s->spi);
  15378. }
  15379. // clang-format off
  15380. static void w5500_wn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr, void *buf, size_t len) { w5500_txn(s, block, addr, true, buf, len); }
  15381. static void w5500_w1(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr, uint8_t val) { w5500_wn(s, block, addr, &val, 1); }
  15382. static void w5500_w2(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr, uint16_t val) { uint8_t buf[2] = {(uint8_t) (val >> 8), (uint8_t) (val & 255)}; w5500_wn(s, block, addr, buf, sizeof(buf)); }
  15383. static void w5500_rn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr, void *buf, size_t len) { w5500_txn(s, block, addr, false, buf, len); }
  15384. static uint8_t w5500_r1(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr) { uint8_t r = 0; w5500_rn(s, block, addr, &r, 1); return r; }
  15385. static uint16_t w5500_r2(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr) { uint8_t buf[2] = {0, 0}; w5500_rn(s, block, addr, buf, sizeof(buf)); return (uint16_t) ((buf[0] << 8) | buf[1]); }
  15386. // clang-format on
  15387. static size_t w5500_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  15388. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15389. uint16_t r = 0, n = 0, len = (uint16_t) buflen, n2; // Read recv len
  15390. while ((n2 = w5500_r2(s, W5500_S0, 0x26)) > n) n = n2; // Until it is stable
  15391. // printf("RSR: %d\n", (int) n);
  15392. if (n > 0) {
  15393. uint16_t ptr = w5500_r2(s, W5500_S0, 0x28); // Get read pointer
  15394. n = w5500_r2(s, W5500_RX0, ptr); // Read frame length
  15395. if (n <= len + 2 && n > 1) {
  15396. r = (uint16_t) (n - 2);
  15397. w5500_rn(s, W5500_RX0, (uint16_t) (ptr + 2), buf, r);
  15398. }
  15399. w5500_w2(s, W5500_S0, 0x28, (uint16_t) (ptr + n)); // Advance read pointer
  15400. w5500_w1(s, W5500_S0, 1, 0x40); // Sock0 CR -> RECV
  15401. // printf(" RX_RD: tot=%u n=%u r=%u\n", n2, n, r);
  15402. }
  15403. return r;
  15404. }
  15405. static size_t w5500_tx(const void *buf, size_t buflen,
  15406. struct mg_tcpip_if *ifp) {
  15407. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15408. uint16_t i, ptr, n = 0, len = (uint16_t) buflen;
  15409. while (n < len) n = w5500_r2(s, W5500_S0, 0x20); // Wait for space
  15410. ptr = w5500_r2(s, W5500_S0, 0x24); // Get write pointer
  15411. w5500_wn(s, W5500_TX0, ptr, (void *) buf, len); // Write data
  15412. w5500_w2(s, W5500_S0, 0x24, (uint16_t) (ptr + len)); // Advance write pointer
  15413. w5500_w1(s, W5500_S0, 1, 0x20); // Sock0 CR -> SEND
  15414. for (i = 0; i < 40; i++) {
  15415. uint8_t ir = w5500_r1(s, W5500_S0, 2); // Read S0 IR
  15416. if (ir == 0) continue;
  15417. // printf("IR %d, len=%d, free=%d, ptr %d\n", ir, (int) len, (int) n, ptr);
  15418. w5500_w1(s, W5500_S0, 2, ir); // Write S0 IR: clear it!
  15419. if (ir & 8) len = 0; // Timeout. Report error
  15420. if (ir & (16 | 8)) break; // Stop on SEND_OK or timeout
  15421. }
  15422. return len;
  15423. }
  15424. static bool w5500_init(struct mg_tcpip_if *ifp) {
  15425. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15426. s->end(s->spi);
  15427. w5500_w1(s, W5500_CR, 0, 0x80); // Reset chip: CR -> 0x80
  15428. w5500_w1(s, W5500_CR, 0x2e, 0); // CR PHYCFGR -> reset
  15429. w5500_w1(s, W5500_CR, 0x2e, 0xf8); // CR PHYCFGR -> set
  15430. // w5500_wn(s, W5500_CR, 9, s->mac, 6); // Set source MAC
  15431. w5500_w1(s, W5500_S0, 0x1e, 16); // Sock0 RX buf size
  15432. w5500_w1(s, W5500_S0, 0x1f, 16); // Sock0 TX buf size
  15433. w5500_w1(s, W5500_S0, 0, 4); // Sock0 MR -> MACRAW
  15434. w5500_w1(s, W5500_S0, 1, 1); // Sock0 CR -> OPEN
  15435. return w5500_r1(s, W5500_S0, 3) == 0x42; // Sock0 SR == MACRAW
  15436. }
  15437. static bool w5500_up(struct mg_tcpip_if *ifp) {
  15438. struct mg_tcpip_spi *spi = (struct mg_tcpip_spi *) ifp->driver_data;
  15439. uint8_t phycfgr = w5500_r1(spi, W5500_CR, 0x2e);
  15440. return phycfgr & 1; // Bit 0 of PHYCFGR is LNK (0 - down, 1 - up)
  15441. }
  15442. struct mg_tcpip_driver mg_tcpip_driver_w5500 = {w5500_init, w5500_tx, w5500_rx,
  15443. w5500_up};
  15444. #endif
  15445. #ifdef MG_ENABLE_LINES
  15446. #line 1 "src/drivers/xmc.c"
  15447. #endif
  15448. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC
  15449. struct ETH_GLOBAL_TypeDef {
  15450. volatile uint32_t MAC_CONFIGURATION, MAC_FRAME_FILTER, HASH_TABLE_HIGH,
  15451. HASH_TABLE_LOW, GMII_ADDRESS, GMII_DATA, FLOW_CONTROL, VLAN_TAG, VERSION,
  15452. DEBUG, REMOTE_WAKE_UP_FRAME_FILTER, PMT_CONTROL_STATUS, RESERVED[2],
  15453. INTERRUPT_STATUS, INTERRUPT_MASK, MAC_ADDRESS0_HIGH, MAC_ADDRESS0_LOW,
  15454. MAC_ADDRESS1_HIGH, MAC_ADDRESS1_LOW, MAC_ADDRESS2_HIGH, MAC_ADDRESS2_LOW,
  15455. MAC_ADDRESS3_HIGH, MAC_ADDRESS3_LOW, RESERVED1[40], MMC_CONTROL,
  15456. MMC_RECEIVE_INTERRUPT, MMC_TRANSMIT_INTERRUPT, MMC_RECEIVE_INTERRUPT_MASK,
  15457. MMC_TRANSMIT_INTERRUPT_MASK, TX_STATISTICS[26], RESERVED2,
  15458. RX_STATISTICS_1[26], RESERVED3[6], MMC_IPC_RECEIVE_INTERRUPT_MASK,
  15459. RESERVED4, MMC_IPC_RECEIVE_INTERRUPT, RESERVED5, RX_STATISTICS_2[30],
  15460. RESERVED7[286], TIMESTAMP_CONTROL, SUB_SECOND_INCREMENT,
  15461. SYSTEM_TIME_SECONDS, SYSTEM_TIME_NANOSECONDS,
  15462. SYSTEM_TIME_SECONDS_UPDATE, SYSTEM_TIME_NANOSECONDS_UPDATE,
  15463. TIMESTAMP_ADDEND, TARGET_TIME_SECONDS, TARGET_TIME_NANOSECONDS,
  15464. SYSTEM_TIME_HIGHER_WORD_SECONDS, TIMESTAMP_STATUS,
  15465. PPS_CONTROL, RESERVED8[564], BUS_MODE, TRANSMIT_POLL_DEMAND,
  15466. RECEIVE_POLL_DEMAND, RECEIVE_DESCRIPTOR_LIST_ADDRESS,
  15467. TRANSMIT_DESCRIPTOR_LIST_ADDRESS, STATUS, OPERATION_MODE,
  15468. INTERRUPT_ENABLE, MISSED_FRAME_AND_BUFFER_OVERFLOW_COUNTER,
  15469. RECEIVE_INTERRUPT_WATCHDOG_TIMER, RESERVED9, AHB_STATUS,
  15470. RESERVED10[6], CURRENT_HOST_TRANSMIT_DESCRIPTOR,
  15471. CURRENT_HOST_RECEIVE_DESCRIPTOR, CURRENT_HOST_TRANSMIT_BUFFER_ADDRESS,
  15472. CURRENT_HOST_RECEIVE_BUFFER_ADDRESS, HW_FEATURE;
  15473. };
  15474. #undef ETH0
  15475. #define ETH0 ((struct ETH_GLOBAL_TypeDef*) 0x5000C000UL)
  15476. #define ETH_PKT_SIZE 1536 // Max frame size
  15477. #define ETH_DESC_CNT 4 // Descriptors count
  15478. #define ETH_DS 4 // Descriptor size (words)
  15479. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15480. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15481. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15482. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15483. static uint8_t s_txno; // Current TX descriptor
  15484. static uint8_t s_rxno; // Current RX descriptor
  15485. static struct mg_tcpip_if *s_ifp; // MIP interface
  15486. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  15487. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  15488. ETH0->GMII_ADDRESS = (ETH0->GMII_ADDRESS & 0x3c) |
  15489. ((uint32_t)addr << 11) |
  15490. ((uint32_t)reg << 6) | 1;
  15491. while ((ETH0->GMII_ADDRESS & 1) != 0) (void) 0;
  15492. return (uint16_t)(ETH0->GMII_DATA & 0xffff);
  15493. }
  15494. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15495. ETH0->GMII_DATA = val;
  15496. ETH0->GMII_ADDRESS = (ETH0->GMII_ADDRESS & 0x3c) |
  15497. ((uint32_t)addr << 11) |
  15498. ((uint32_t)reg << 6) | 3;
  15499. while ((ETH0->GMII_ADDRESS & 1) != 0) (void) 0;
  15500. }
  15501. static uint32_t get_clock_rate(struct mg_tcpip_driver_xmc_data *d) {
  15502. if (d->mdc_cr == -1) {
  15503. // assume ETH clock is 60MHz by default
  15504. // then according to 13.2.8.1, we need to set value 3
  15505. return 3;
  15506. }
  15507. return d->mdc_cr;
  15508. }
  15509. static bool mg_tcpip_driver_xmc_init(struct mg_tcpip_if *ifp) {
  15510. struct mg_tcpip_driver_xmc_data *d =
  15511. (struct mg_tcpip_driver_xmc_data *) ifp->driver_data;
  15512. s_ifp = ifp;
  15513. // reset MAC
  15514. ETH0->BUS_MODE |= 1;
  15515. while (ETH0->BUS_MODE & 1) (void) 0;
  15516. // set clock rate
  15517. ETH0->GMII_ADDRESS = get_clock_rate(d) << 2;
  15518. // init phy
  15519. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15520. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  15521. // configure MAC: DO, DM, FES, TC
  15522. ETH0->MAC_CONFIGURATION = MG_BIT(13) | MG_BIT(11) | MG_BIT(14) | MG_BIT(24);
  15523. // set the MAC address
  15524. ETH0->MAC_ADDRESS0_HIGH = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  15525. ETH0->MAC_ADDRESS0_LOW =
  15526. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  15527. // Configure the receive filter
  15528. ETH0->MAC_FRAME_FILTER = MG_BIT(10) | MG_BIT(2); // HFP, HMC
  15529. // Disable flow control
  15530. ETH0->FLOW_CONTROL = 0;
  15531. // Enable store and forward mode
  15532. ETH0->OPERATION_MODE = MG_BIT(25) | MG_BIT(21); // RSF, TSF
  15533. // Configure DMA bus mode (AAL, USP, RPBL, PBL)
  15534. ETH0->BUS_MODE = MG_BIT(25) | MG_BIT(23) | (32 << 17) | (32 << 8);
  15535. // init RX descriptors
  15536. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15537. s_rxdesc[i][0] = MG_BIT(31); // OWN descriptor
  15538. s_rxdesc[i][1] = MG_BIT(14) | ETH_PKT_SIZE;
  15539. s_rxdesc[i][2] = (uint32_t) s_rxbuf[i];
  15540. if (i == ETH_DESC_CNT - 1) {
  15541. s_rxdesc[i][3] = (uint32_t) &s_rxdesc[0][0];
  15542. } else {
  15543. s_rxdesc[i][3] = (uint32_t) &s_rxdesc[i + 1][0];
  15544. }
  15545. }
  15546. ETH0->RECEIVE_DESCRIPTOR_LIST_ADDRESS = (uint32_t) &s_rxdesc[0][0];
  15547. // init TX descriptors
  15548. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15549. s_txdesc[i][0] = MG_BIT(30) | MG_BIT(20);
  15550. s_txdesc[i][2] = (uint32_t) s_txbuf[i];
  15551. if (i == ETH_DESC_CNT - 1) {
  15552. s_txdesc[i][3] = (uint32_t) &s_txdesc[0][0];
  15553. } else {
  15554. s_txdesc[i][3] = (uint32_t) &s_txdesc[i + 1][0];
  15555. }
  15556. }
  15557. ETH0->TRANSMIT_DESCRIPTOR_LIST_ADDRESS = (uint32_t) &s_txdesc[0][0];
  15558. // Clear interrupts
  15559. ETH0->STATUS = 0xFFFFFFFF;
  15560. // Disable MAC interrupts
  15561. ETH0->MMC_TRANSMIT_INTERRUPT_MASK = 0xFFFFFFFF;
  15562. ETH0->MMC_RECEIVE_INTERRUPT_MASK = 0xFFFFFFFF;
  15563. ETH0->MMC_IPC_RECEIVE_INTERRUPT_MASK = 0xFFFFFFFF;
  15564. ETH0->INTERRUPT_MASK = MG_BIT(9) | MG_BIT(3); // TSIM, PMTIM
  15565. //Enable interrupts (NIE, RIE, TIE)
  15566. ETH0->INTERRUPT_ENABLE = MG_BIT(16) | MG_BIT(6) | MG_BIT(0);
  15567. // Enable MAC transmission and reception (TE, RE)
  15568. ETH0->MAC_CONFIGURATION |= MG_BIT(3) | MG_BIT(2);
  15569. // Enable DMA transmission and reception (ST, SR)
  15570. ETH0->OPERATION_MODE |= MG_BIT(13) | MG_BIT(1);
  15571. return true;
  15572. }
  15573. static size_t mg_tcpip_driver_xmc_tx(const void *buf, size_t len,
  15574. struct mg_tcpip_if *ifp) {
  15575. if (len > sizeof(s_txbuf[s_txno])) {
  15576. MG_ERROR(("Frame too big, %ld", (long) len));
  15577. len = 0; // Frame is too big
  15578. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  15579. ifp->nerr++;
  15580. MG_ERROR(("No free descriptors"));
  15581. len = 0; // All descriptors are busy, fail
  15582. } else {
  15583. memcpy(s_txbuf[s_txno], buf, len);
  15584. s_txdesc[s_txno][1] = len;
  15585. // Table 13-19 Transmit Descriptor Word 0 (IC, LS, FS, TCH)
  15586. s_txdesc[s_txno][0] = MG_BIT(30) | MG_BIT(29) | MG_BIT(28) | MG_BIT(20);
  15587. s_txdesc[s_txno][0] |= MG_BIT(31); // OWN bit: handle control to DMA
  15588. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15589. }
  15590. // Resume processing
  15591. ETH0->STATUS = MG_BIT(2); // clear Transmit unavailable
  15592. ETH0->TRANSMIT_POLL_DEMAND = 0;
  15593. return len;
  15594. }
  15595. static bool mg_tcpip_driver_xmc_up(struct mg_tcpip_if *ifp) {
  15596. struct mg_tcpip_driver_xmc_data *d =
  15597. (struct mg_tcpip_driver_xmc_data *) ifp->driver_data;
  15598. uint8_t speed = MG_PHY_SPEED_10M;
  15599. bool up = false, full_duplex = false;
  15600. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15601. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  15602. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15603. MG_DEBUG(("Link is %uM %s-duplex", speed == MG_PHY_SPEED_10M ? 10 : 100,
  15604. full_duplex ? "full" : "half"));
  15605. }
  15606. return up;
  15607. }
  15608. void ETH0_IRQHandler(void);
  15609. void ETH0_IRQHandler(void) {
  15610. uint32_t irq_status = ETH0->STATUS;
  15611. // check if a frame was received
  15612. if (irq_status & MG_BIT(6)) {
  15613. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  15614. if ((s_rxdesc[s_rxno][0] & MG_BIT(31)) == 0) {
  15615. size_t len = (s_rxdesc[s_rxno][0] & 0x3fff0000) >> 16;
  15616. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  15617. s_rxdesc[s_rxno][0] = MG_BIT(31); // OWN bit: handle control to DMA
  15618. // Resume processing
  15619. ETH0->STATUS = MG_BIT(7) | MG_BIT(6); // clear RU and RI
  15620. ETH0->RECEIVE_POLL_DEMAND = 0;
  15621. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15622. }
  15623. }
  15624. ETH0->STATUS = MG_BIT(6);
  15625. }
  15626. // clear Successful transmission interrupt
  15627. if (irq_status & 1) {
  15628. ETH0->STATUS = 1;
  15629. }
  15630. // clear normal interrupt
  15631. if (irq_status & MG_BIT(16)) {
  15632. ETH0->STATUS = MG_BIT(16);
  15633. }
  15634. }
  15635. struct mg_tcpip_driver mg_tcpip_driver_xmc = {
  15636. mg_tcpip_driver_xmc_init, mg_tcpip_driver_xmc_tx, NULL,
  15637. mg_tcpip_driver_xmc_up};
  15638. #endif
  15639. #ifdef MG_ENABLE_LINES
  15640. #line 1 "src/drivers/xmc7.c"
  15641. #endif
  15642. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7
  15643. struct ETH_Type {
  15644. volatile uint32_t CTL, STATUS, RESERVED[1022], NETWORK_CONTROL,
  15645. NETWORK_CONFIG, NETWORK_STATUS, USER_IO_REGISTER, DMA_CONFIG,
  15646. TRANSMIT_STATUS, RECEIVE_Q_PTR, TRANSMIT_Q_PTR, RECEIVE_STATUS,
  15647. INT_STATUS, INT_ENABLE, INT_DISABLE, INT_MASK, PHY_MANAGEMENT, PAUSE_TIME,
  15648. TX_PAUSE_QUANTUM, PBUF_TXCUTTHRU, PBUF_RXCUTTHRU, JUMBO_MAX_LENGTH,
  15649. EXTERNAL_FIFO_INTERFACE, RESERVED1, AXI_MAX_PIPELINE, RSC_CONTROL,
  15650. INT_MODERATION, SYS_WAKE_TIME, RESERVED2[7], HASH_BOTTOM, HASH_TOP,
  15651. SPEC_ADD1_BOTTOM, SPEC_ADD1_TOP, SPEC_ADD2_BOTTOM, SPEC_ADD2_TOP,
  15652. SPEC_ADD3_BOTTOM, SPEC_ADD3_TOP, SPEC_ADD4_BOTTOM, SPEC_ADD4_TOP,
  15653. SPEC_TYPE1, SPEC_TYPE2, SPEC_TYPE3, SPEC_TYPE4, WOL_REGISTER,
  15654. STRETCH_RATIO, STACKED_VLAN, TX_PFC_PAUSE, MASK_ADD1_BOTTOM,
  15655. MASK_ADD1_TOP, DMA_ADDR_OR_MASK, RX_PTP_UNICAST, TX_PTP_UNICAST,
  15656. TSU_NSEC_CMP, TSU_SEC_CMP, TSU_MSB_SEC_CMP, TSU_PTP_TX_MSB_SEC,
  15657. TSU_PTP_RX_MSB_SEC, TSU_PEER_TX_MSB_SEC, TSU_PEER_RX_MSB_SEC,
  15658. DPRAM_FILL_DBG, REVISION_REG, OCTETS_TXED_BOTTOM, OCTETS_TXED_TOP,
  15659. FRAMES_TXED_OK, BROADCAST_TXED, MULTICAST_TXED, PAUSE_FRAMES_TXED,
  15660. FRAMES_TXED_64, FRAMES_TXED_65, FRAMES_TXED_128, FRAMES_TXED_256,
  15661. FRAMES_TXED_512, FRAMES_TXED_1024, FRAMES_TXED_1519, TX_UNDERRUNS,
  15662. SINGLE_COLLISIONS, MULTIPLE_COLLISIONS, EXCESSIVE_COLLISIONS,
  15663. LATE_COLLISIONS, DEFERRED_FRAMES, CRS_ERRORS, OCTETS_RXED_BOTTOM,
  15664. OCTETS_RXED_TOP, FRAMES_RXED_OK, BROADCAST_RXED, MULTICAST_RXED,
  15665. PAUSE_FRAMES_RXED, FRAMES_RXED_64, FRAMES_RXED_65, FRAMES_RXED_128,
  15666. FRAMES_RXED_256, FRAMES_RXED_512, FRAMES_RXED_1024, FRAMES_RXED_1519,
  15667. UNDERSIZE_FRAMES, EXCESSIVE_RX_LENGTH, RX_JABBERS, FCS_ERRORS,
  15668. RX_LENGTH_ERRORS, RX_SYMBOL_ERRORS, ALIGNMENT_ERRORS, RX_RESOURCE_ERRORS,
  15669. RX_OVERRUNS, RX_IP_CK_ERRORS, RX_TCP_CK_ERRORS, RX_UDP_CK_ERRORS,
  15670. AUTO_FLUSHED_PKTS, RESERVED3, TSU_TIMER_INCR_SUB_NSEC, TSU_TIMER_MSB_SEC,
  15671. TSU_STROBE_MSB_SEC, TSU_STROBE_SEC, TSU_STROBE_NSEC, TSU_TIMER_SEC,
  15672. TSU_TIMER_NSEC, TSU_TIMER_ADJUST, TSU_TIMER_INCR, TSU_PTP_TX_SEC,
  15673. TSU_PTP_TX_NSEC, TSU_PTP_RX_SEC, TSU_PTP_RX_NSEC, TSU_PEER_TX_SEC,
  15674. TSU_PEER_TX_NSEC, TSU_PEER_RX_SEC, TSU_PEER_RX_NSEC, PCS_CONTROL,
  15675. PCS_STATUS, RESERVED4[2], PCS_AN_ADV, PCS_AN_LP_BASE, PCS_AN_EXP,
  15676. PCS_AN_NP_TX, PCS_AN_LP_NP, RESERVED5[6], PCS_AN_EXT_STATUS, RESERVED6[8],
  15677. TX_PAUSE_QUANTUM1, TX_PAUSE_QUANTUM2, TX_PAUSE_QUANTUM3, RESERVED7,
  15678. RX_LPI, RX_LPI_TIME, TX_LPI, TX_LPI_TIME, DESIGNCFG_DEBUG1,
  15679. DESIGNCFG_DEBUG2, DESIGNCFG_DEBUG3, DESIGNCFG_DEBUG4, DESIGNCFG_DEBUG5,
  15680. DESIGNCFG_DEBUG6, DESIGNCFG_DEBUG7, DESIGNCFG_DEBUG8, DESIGNCFG_DEBUG9,
  15681. DESIGNCFG_DEBUG10, RESERVED8[22], SPEC_ADD5_BOTTOM, SPEC_ADD5_TOP,
  15682. RESERVED9[60], SPEC_ADD36_BOTTOM, SPEC_ADD36_TOP, INT_Q1_STATUS,
  15683. INT_Q2_STATUS, INT_Q3_STATUS, RESERVED10[11], INT_Q15_STATUS, RESERVED11,
  15684. TRANSMIT_Q1_PTR, TRANSMIT_Q2_PTR, TRANSMIT_Q3_PTR, RESERVED12[11],
  15685. TRANSMIT_Q15_PTR, RESERVED13, RECEIVE_Q1_PTR, RECEIVE_Q2_PTR,
  15686. RECEIVE_Q3_PTR, RESERVED14[3], RECEIVE_Q7_PTR, RESERVED15,
  15687. DMA_RXBUF_SIZE_Q1, DMA_RXBUF_SIZE_Q2, DMA_RXBUF_SIZE_Q3, RESERVED16[3],
  15688. DMA_RXBUF_SIZE_Q7, CBS_CONTROL, CBS_IDLESLOPE_Q_A, CBS_IDLESLOPE_Q_B,
  15689. UPPER_TX_Q_BASE_ADDR, TX_BD_CONTROL, RX_BD_CONTROL, UPPER_RX_Q_BASE_ADDR,
  15690. RESERVED17[2], HIDDEN_REG0, HIDDEN_REG1, HIDDEN_REG2, HIDDEN_REG3,
  15691. RESERVED18[2], HIDDEN_REG4, HIDDEN_REG5;
  15692. };
  15693. #define ETH0 ((struct ETH_Type *) 0x40490000)
  15694. #define ETH_PKT_SIZE 1536 // Max frame size
  15695. #define ETH_DESC_CNT 4 // Descriptors count
  15696. #define ETH_DS 2 // Descriptor size (words)
  15697. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15698. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15699. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15700. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15701. static uint8_t s_txno; // Current TX descriptor
  15702. static uint8_t s_rxno; // Current RX descriptor
  15703. static struct mg_tcpip_if *s_ifp; // MIP interface
  15704. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  15705. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  15706. // WRITE1, READ OPERATION, PHY, REG, WRITE10
  15707. ETH0->PHY_MANAGEMENT = MG_BIT(30) | MG_BIT(29) | ((addr & 0xf) << 24) |
  15708. ((reg & 0x1f) << 18) | MG_BIT(17);
  15709. while ((ETH0->NETWORK_STATUS & MG_BIT(2)) == 0) (void) 0;
  15710. return ETH0->PHY_MANAGEMENT & 0xffff;
  15711. }
  15712. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15713. ETH0->PHY_MANAGEMENT = MG_BIT(30) | MG_BIT(28) | ((addr & 0xf) << 24) |
  15714. ((reg & 0x1f) << 18) | MG_BIT(17) | val;
  15715. while ((ETH0->NETWORK_STATUS & MG_BIT(2)) == 0) (void) 0;
  15716. }
  15717. static uint32_t get_clock_rate(struct mg_tcpip_driver_xmc7_data *d) {
  15718. // see ETH0 -> NETWORK_CONFIG register
  15719. (void) d;
  15720. return 3;
  15721. }
  15722. static bool mg_tcpip_driver_xmc7_init(struct mg_tcpip_if *ifp) {
  15723. struct mg_tcpip_driver_xmc7_data *d =
  15724. (struct mg_tcpip_driver_xmc7_data *) ifp->driver_data;
  15725. s_ifp = ifp;
  15726. // enable controller, set RGMII mode
  15727. ETH0->CTL = MG_BIT(31) | 2;
  15728. uint32_t cr = get_clock_rate(d);
  15729. // set NSP change, ignore RX FCS, data bus width, clock rate
  15730. // frame length 1536, full duplex, speed
  15731. ETH0->NETWORK_CONFIG = MG_BIT(29) | MG_BIT(26) | MG_BIT(21) |
  15732. ((cr & 7) << 18) | MG_BIT(8) | MG_BIT(4) |
  15733. MG_BIT(1) | MG_BIT(0);
  15734. // config DMA settings: Force TX burst, Discard on Error, set RX buffer size
  15735. // to 1536, TX_PBUF_SIZE, RX_PBUF_SIZE, AMBA_BURST_LENGTH
  15736. ETH0->DMA_CONFIG =
  15737. MG_BIT(26) | MG_BIT(24) | (0x18 << 16) | MG_BIT(10) | (3 << 8) | 4;
  15738. // initialize descriptors
  15739. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15740. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i];
  15741. if (i == ETH_DESC_CNT - 1) {
  15742. s_rxdesc[i][0] |= MG_BIT(1); // mark last descriptor
  15743. }
  15744. s_txdesc[i][0] = (uint32_t) s_txbuf[i];
  15745. s_txdesc[i][1] = MG_BIT(31); // OWN descriptor
  15746. if (i == ETH_DESC_CNT - 1) {
  15747. s_txdesc[i][1] |= MG_BIT(30); // mark last descriptor
  15748. }
  15749. }
  15750. ETH0->RECEIVE_Q_PTR = (uint32_t) s_rxdesc;
  15751. ETH0->TRANSMIT_Q_PTR = (uint32_t) s_txdesc;
  15752. // disable other queues
  15753. ETH0->TRANSMIT_Q2_PTR = 1;
  15754. ETH0->TRANSMIT_Q1_PTR = 1;
  15755. ETH0->RECEIVE_Q2_PTR = 1;
  15756. ETH0->RECEIVE_Q1_PTR = 1;
  15757. // enable interrupts (TX and RX complete)
  15758. ETH0->INT_ENABLE = MG_BIT(7) | MG_BIT(1);
  15759. // set MAC address
  15760. ETH0->SPEC_ADD1_BOTTOM =
  15761. ifp->mac[3] << 24 | ifp->mac[2] << 16 | ifp->mac[1] << 8 | ifp->mac[0];
  15762. ETH0->SPEC_ADD1_TOP = ifp->mac[5] << 8 | ifp->mac[4];
  15763. // enable MDIO, TX, RX
  15764. ETH0->NETWORK_CONTROL = MG_BIT(4) | MG_BIT(3) | MG_BIT(2);
  15765. // start transmission
  15766. ETH0->NETWORK_CONTROL |= MG_BIT(9);
  15767. // init phy
  15768. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15769. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  15770. (void) d;
  15771. return true;
  15772. }
  15773. static size_t mg_tcpip_driver_xmc7_tx(const void *buf, size_t len,
  15774. struct mg_tcpip_if *ifp) {
  15775. if (len > sizeof(s_txbuf[s_txno])) {
  15776. MG_ERROR(("Frame too big, %ld", (long) len));
  15777. len = 0; // Frame is too big
  15778. } else if (((s_txdesc[s_txno][1] & MG_BIT(31)) == 0)) {
  15779. ifp->nerr++;
  15780. MG_ERROR(("No free descriptors"));
  15781. len = 0; // All descriptors are busy, fail
  15782. } else {
  15783. memcpy(s_txbuf[s_txno], buf, len);
  15784. s_txdesc[s_txno][1] = (s_txno == ETH_DESC_CNT - 1 ? MG_BIT(30) : 0) |
  15785. MG_BIT(15) | len; // Last buffer and length
  15786. ETH0->NETWORK_CONTROL |= MG_BIT(9); // enable transmission
  15787. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15788. }
  15789. MG_DSB();
  15790. ETH0->TRANSMIT_STATUS = ETH0->TRANSMIT_STATUS;
  15791. ETH0->NETWORK_CONTROL |= MG_BIT(9); // enable transmission
  15792. return len;
  15793. }
  15794. static bool mg_tcpip_driver_xmc7_up(struct mg_tcpip_if *ifp) {
  15795. struct mg_tcpip_driver_xmc7_data *d =
  15796. (struct mg_tcpip_driver_xmc7_data *) ifp->driver_data;
  15797. uint8_t speed = MG_PHY_SPEED_10M;
  15798. bool up = false, full_duplex = false;
  15799. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15800. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  15801. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15802. if (speed == MG_PHY_SPEED_1000M) {
  15803. ETH0->NETWORK_CONFIG |= MG_BIT(10);
  15804. }
  15805. MG_DEBUG(("Link is %uM %s-duplex",
  15806. speed == MG_PHY_SPEED_10M ? 10 :
  15807. (speed == MG_PHY_SPEED_100M ? 100 : 1000),
  15808. full_duplex ? "full" : "half"));
  15809. }
  15810. (void) d;
  15811. return up;
  15812. }
  15813. void ETH_IRQHandler(void) {
  15814. uint32_t irq_status = ETH0->INT_STATUS;
  15815. if (irq_status & MG_BIT(1)) {
  15816. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  15817. if (s_rxdesc[s_rxno][0] & MG_BIT(0)) {
  15818. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  15819. //MG_INFO(("Receive complete: %ld bytes", len));
  15820. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  15821. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // OWN bit: handle control to DMA
  15822. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15823. }
  15824. }
  15825. }
  15826. ETH0->INT_STATUS = irq_status;
  15827. }
  15828. struct mg_tcpip_driver mg_tcpip_driver_xmc7 = {mg_tcpip_driver_xmc7_init,
  15829. mg_tcpip_driver_xmc7_tx, NULL,
  15830. mg_tcpip_driver_xmc7_up};
  15831. #endif