mongoose.c 688 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301
  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/dns.c"
  111. #endif
  112. struct dns_data {
  113. struct dns_data *next;
  114. struct mg_connection *c;
  115. uint64_t expire;
  116. uint16_t txnid;
  117. };
  118. static void mg_sendnsreq(struct mg_connection *, struct mg_str *, int,
  119. struct mg_dns *, bool);
  120. static void mg_dns_free(struct dns_data **head, struct dns_data *d) {
  121. LIST_DELETE(struct dns_data, head, d);
  122. free(d);
  123. }
  124. void mg_resolve_cancel(struct mg_connection *c) {
  125. struct dns_data *tmp, *d;
  126. struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests;
  127. for (d = *head; d != NULL; d = tmp) {
  128. tmp = d->next;
  129. if (d->c == c) mg_dns_free(head, d);
  130. }
  131. }
  132. static size_t mg_dns_parse_name_depth(const uint8_t *s, size_t len, size_t ofs,
  133. char *to, size_t tolen, size_t j,
  134. int depth) {
  135. size_t i = 0;
  136. if (tolen > 0 && depth == 0) to[0] = '\0';
  137. if (depth > 5) return 0;
  138. // MG_INFO(("ofs %lx %x %x", (unsigned long) ofs, s[ofs], s[ofs + 1]));
  139. while (ofs + i + 1 < len) {
  140. size_t n = s[ofs + i];
  141. if (n == 0) {
  142. i++;
  143. break;
  144. }
  145. if (n & 0xc0) {
  146. size_t ptr = (((n & 0x3f) << 8) | s[ofs + i + 1]); // 12 is hdr len
  147. // MG_INFO(("PTR %lx", (unsigned long) ptr));
  148. if (ptr + 1 < len && (s[ptr] & 0xc0) == 0 &&
  149. mg_dns_parse_name_depth(s, len, ptr, to, tolen, j, depth + 1) == 0)
  150. return 0;
  151. i += 2;
  152. break;
  153. }
  154. if (ofs + i + n + 1 >= len) return 0;
  155. if (j > 0) {
  156. if (j < tolen) to[j] = '.';
  157. j++;
  158. }
  159. if (j + n < tolen) memcpy(&to[j], &s[ofs + i + 1], n);
  160. j += n;
  161. i += n + 1;
  162. if (j < tolen) to[j] = '\0'; // Zero-terminate this chunk
  163. // MG_INFO(("--> [%s]", to));
  164. }
  165. if (tolen > 0) to[tolen - 1] = '\0'; // Make sure make sure it is nul-term
  166. return i;
  167. }
  168. static size_t mg_dns_parse_name(const uint8_t *s, size_t n, size_t ofs,
  169. char *dst, size_t dstlen) {
  170. return mg_dns_parse_name_depth(s, n, ofs, dst, dstlen, 0, 0);
  171. }
  172. size_t mg_dns_parse_rr(const uint8_t *buf, size_t len, size_t ofs,
  173. bool is_question, struct mg_dns_rr *rr) {
  174. const uint8_t *s = buf + ofs, *e = &buf[len];
  175. memset(rr, 0, sizeof(*rr));
  176. if (len < sizeof(struct mg_dns_header)) return 0; // Too small
  177. if (len > 512) return 0; // Too large, we don't expect that
  178. if (s >= e) return 0; // Overflow
  179. if ((rr->nlen = (uint16_t) mg_dns_parse_name(buf, len, ofs, NULL, 0)) == 0)
  180. return 0;
  181. s += rr->nlen + 4;
  182. if (s > e) return 0;
  183. rr->atype = (uint16_t) (((uint16_t) s[-4] << 8) | s[-3]);
  184. rr->aclass = (uint16_t) (((uint16_t) s[-2] << 8) | s[-1]);
  185. if (is_question) return (size_t) (rr->nlen + 4);
  186. s += 6;
  187. if (s > e) return 0;
  188. rr->alen = (uint16_t) (((uint16_t) s[-2] << 8) | s[-1]);
  189. if (s + rr->alen > e) return 0;
  190. return (size_t) (rr->nlen + rr->alen + 10);
  191. }
  192. bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) {
  193. const struct mg_dns_header *h = (struct mg_dns_header *) buf;
  194. struct mg_dns_rr rr;
  195. size_t i, n, num_answers, ofs = sizeof(*h);
  196. memset(dm, 0, sizeof(*dm));
  197. if (len < sizeof(*h)) return 0; // Too small, headers dont fit
  198. if (mg_ntohs(h->num_questions) > 1) return 0; // Sanity
  199. num_answers = mg_ntohs(h->num_answers);
  200. if (num_answers > 10) {
  201. MG_DEBUG(("Got %u answers, ignoring beyond 10th one", num_answers));
  202. num_answers = 10; // Sanity cap
  203. }
  204. dm->txnid = mg_ntohs(h->txnid);
  205. for (i = 0; i < mg_ntohs(h->num_questions); i++) {
  206. if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false;
  207. // MG_INFO(("Q %lu %lu %hu/%hu", ofs, n, rr.atype, rr.aclass));
  208. ofs += n;
  209. }
  210. for (i = 0; i < num_answers; i++) {
  211. if ((n = mg_dns_parse_rr(buf, len, ofs, false, &rr)) == 0) return false;
  212. // MG_INFO(("A -- %lu %lu %hu/%hu %s", ofs, n, rr.atype, rr.aclass,
  213. // dm->name));
  214. mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name));
  215. ofs += n;
  216. if (rr.alen == 4 && rr.atype == 1 && rr.aclass == 1) {
  217. dm->addr.is_ip6 = false;
  218. memcpy(&dm->addr.ip, &buf[ofs - 4], 4);
  219. dm->resolved = true;
  220. break; // Return success
  221. } else if (rr.alen == 16 && rr.atype == 28 && rr.aclass == 1) {
  222. dm->addr.is_ip6 = true;
  223. memcpy(&dm->addr.ip, &buf[ofs - 16], 16);
  224. dm->resolved = true;
  225. break; // Return success
  226. }
  227. }
  228. return true;
  229. }
  230. static void dns_cb(struct mg_connection *c, int ev, void *ev_data) {
  231. struct dns_data *d, *tmp;
  232. struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests;
  233. if (ev == MG_EV_POLL) {
  234. uint64_t now = *(uint64_t *) ev_data;
  235. for (d = *head; d != NULL; d = tmp) {
  236. tmp = d->next;
  237. // MG_DEBUG ("%lu %lu dns poll", d->expire, now));
  238. if (now > d->expire) mg_error(d->c, "DNS timeout");
  239. }
  240. } else if (ev == MG_EV_READ) {
  241. struct mg_dns_message dm;
  242. int resolved = 0;
  243. if (mg_dns_parse(c->recv.buf, c->recv.len, &dm) == false) {
  244. MG_ERROR(("Unexpected DNS response:"));
  245. mg_hexdump(c->recv.buf, c->recv.len);
  246. } else {
  247. // MG_VERBOSE(("%s %d", dm.name, dm.resolved));
  248. for (d = *head; d != NULL; d = tmp) {
  249. tmp = d->next;
  250. // MG_INFO(("d %p %hu %hu", d, d->txnid, dm.txnid));
  251. if (dm.txnid != d->txnid) continue;
  252. if (d->c->is_resolving) {
  253. if (dm.resolved) {
  254. dm.addr.port = d->c->rem.port; // Save port
  255. d->c->rem = dm.addr; // Copy resolved address
  256. MG_DEBUG(
  257. ("%lu %s is %M", d->c->id, dm.name, mg_print_ip, &d->c->rem));
  258. mg_connect_resolved(d->c);
  259. #if MG_ENABLE_IPV6
  260. } else if (dm.addr.is_ip6 == false && dm.name[0] != '\0' &&
  261. c->mgr->use_dns6 == false) {
  262. struct mg_str x = mg_str(dm.name);
  263. mg_sendnsreq(d->c, &x, c->mgr->dnstimeout, &c->mgr->dns6, true);
  264. #endif
  265. } else {
  266. mg_error(d->c, "%s DNS lookup failed", dm.name);
  267. }
  268. } else {
  269. MG_ERROR(("%lu already resolved", d->c->id));
  270. }
  271. mg_dns_free(head, d);
  272. resolved = 1;
  273. }
  274. }
  275. if (!resolved) MG_ERROR(("stray DNS reply"));
  276. c->recv.len = 0;
  277. } else if (ev == MG_EV_CLOSE) {
  278. for (d = *head; d != NULL; d = tmp) {
  279. tmp = d->next;
  280. mg_error(d->c, "DNS error");
  281. mg_dns_free(head, d);
  282. }
  283. }
  284. }
  285. static bool mg_dns_send(struct mg_connection *c, const struct mg_str *name,
  286. uint16_t txnid, bool ipv6) {
  287. struct {
  288. struct mg_dns_header header;
  289. uint8_t data[256];
  290. } pkt;
  291. size_t i, n;
  292. memset(&pkt, 0, sizeof(pkt));
  293. pkt.header.txnid = mg_htons(txnid);
  294. pkt.header.flags = mg_htons(0x100);
  295. pkt.header.num_questions = mg_htons(1);
  296. for (i = n = 0; i < sizeof(pkt.data) - 5; i++) {
  297. if (name->buf[i] == '.' || i >= name->len) {
  298. pkt.data[n] = (uint8_t) (i - n);
  299. memcpy(&pkt.data[n + 1], name->buf + n, i - n);
  300. n = i + 1;
  301. }
  302. if (i >= name->len) break;
  303. }
  304. memcpy(&pkt.data[n], "\x00\x00\x01\x00\x01", 5); // A query
  305. n += 5;
  306. if (ipv6) pkt.data[n - 3] = 0x1c; // AAAA query
  307. // memcpy(&pkt.data[n], "\xc0\x0c\x00\x1c\x00\x01", 6); // AAAA query
  308. // n += 6;
  309. return mg_send(c, &pkt, sizeof(pkt.header) + n);
  310. }
  311. static void mg_sendnsreq(struct mg_connection *c, struct mg_str *name, int ms,
  312. struct mg_dns *dnsc, bool ipv6) {
  313. struct dns_data *d = NULL;
  314. if (dnsc->url == NULL) {
  315. mg_error(c, "DNS server URL is NULL. Call mg_mgr_init()");
  316. } else if (dnsc->c == NULL) {
  317. dnsc->c = mg_connect(c->mgr, dnsc->url, NULL, NULL);
  318. if (dnsc->c != NULL) {
  319. dnsc->c->pfn = dns_cb;
  320. // dnsc->c->is_hexdumping = 1;
  321. }
  322. }
  323. if (dnsc->c == NULL) {
  324. mg_error(c, "resolver");
  325. } else if ((d = (struct dns_data *) calloc(1, sizeof(*d))) == NULL) {
  326. mg_error(c, "resolve OOM");
  327. } else {
  328. struct dns_data *reqs = (struct dns_data *) c->mgr->active_dns_requests;
  329. d->txnid = reqs ? (uint16_t) (reqs->txnid + 1) : 1;
  330. d->next = (struct dns_data *) c->mgr->active_dns_requests;
  331. c->mgr->active_dns_requests = d;
  332. d->expire = mg_millis() + (uint64_t) ms;
  333. d->c = c;
  334. c->is_resolving = 1;
  335. MG_VERBOSE(("%lu resolving %.*s @ %s, txnid %hu", c->id, (int) name->len,
  336. name->buf, dnsc->url, d->txnid));
  337. if (!mg_dns_send(dnsc->c, name, d->txnid, ipv6)) {
  338. mg_error(dnsc->c, "DNS send");
  339. }
  340. }
  341. }
  342. void mg_resolve(struct mg_connection *c, const char *url) {
  343. struct mg_str host = mg_url_host(url);
  344. c->rem.port = mg_htons(mg_url_port(url));
  345. if (mg_aton(host, &c->rem)) {
  346. // host is an IP address, do not fire name resolution
  347. mg_connect_resolved(c);
  348. } else {
  349. // host is not an IP, send DNS resolution request
  350. struct mg_dns *dns = c->mgr->use_dns6 ? &c->mgr->dns6 : &c->mgr->dns4;
  351. mg_sendnsreq(c, &host, c->mgr->dnstimeout, dns, c->mgr->use_dns6);
  352. }
  353. }
  354. #ifdef MG_ENABLE_LINES
  355. #line 1 "src/event.c"
  356. #endif
  357. void mg_call(struct mg_connection *c, int ev, void *ev_data) {
  358. #if MG_ENABLE_PROFILE
  359. const char *names[] = {
  360. "EV_ERROR", "EV_OPEN", "EV_POLL", "EV_RESOLVE",
  361. "EV_CONNECT", "EV_ACCEPT", "EV_TLS_HS", "EV_READ",
  362. "EV_WRITE", "EV_CLOSE", "EV_HTTP_MSG", "EV_HTTP_CHUNK",
  363. "EV_WS_OPEN", "EV_WS_MSG", "EV_WS_CTL", "EV_MQTT_CMD",
  364. "EV_MQTT_MSG", "EV_MQTT_OPEN", "EV_SNTP_TIME", "EV_USER"};
  365. if (ev != MG_EV_POLL && ev < (int) (sizeof(names) / sizeof(names[0]))) {
  366. MG_PROF_ADD(c, names[ev]);
  367. }
  368. #endif
  369. // Fire protocol handler first, user handler second. See #2559
  370. if (c->pfn != NULL) c->pfn(c, ev, ev_data);
  371. if (c->fn != NULL) c->fn(c, ev, ev_data);
  372. }
  373. void mg_error(struct mg_connection *c, const char *fmt, ...) {
  374. char buf[64];
  375. va_list ap;
  376. va_start(ap, fmt);
  377. mg_vsnprintf(buf, sizeof(buf), fmt, &ap);
  378. va_end(ap);
  379. MG_ERROR(("%lu %ld %s", c->id, c->fd, buf));
  380. c->is_closing = 1; // Set is_closing before sending MG_EV_CALL
  381. mg_call(c, MG_EV_ERROR, buf); // Let user handler override it
  382. }
  383. #ifdef MG_ENABLE_LINES
  384. #line 1 "src/flash.c"
  385. #endif
  386. #if MG_OTA != MG_OTA_NONE && MG_OTA != MG_OTA_CUSTOM
  387. static char *s_addr; // Current address to write to
  388. static size_t s_size; // Firmware size to flash. In-progress indicator
  389. static uint32_t s_crc32; // Firmware checksum
  390. bool mg_ota_flash_begin(size_t new_firmware_size, struct mg_flash *flash) {
  391. bool ok = false;
  392. if (s_size) {
  393. MG_ERROR(("OTA already in progress. Call mg_ota_end()"));
  394. } else {
  395. size_t half = flash->size / 2;
  396. s_crc32 = 0;
  397. s_addr = (char *) flash->start + half;
  398. MG_DEBUG(("FW %lu bytes, max %lu", new_firmware_size, half));
  399. if (new_firmware_size < half) {
  400. ok = true;
  401. s_size = new_firmware_size;
  402. MG_INFO(("Starting OTA, firmware size %lu", s_size));
  403. } else {
  404. MG_ERROR(("Firmware %lu is too big to fit %lu", new_firmware_size, half));
  405. }
  406. }
  407. return ok;
  408. }
  409. bool mg_ota_flash_write(const void *buf, size_t len, struct mg_flash *flash) {
  410. bool ok = false;
  411. if (s_size == 0) {
  412. MG_ERROR(("OTA is not started, call mg_ota_begin()"));
  413. } else {
  414. size_t len_aligned_down = MG_ROUND_DOWN(len, flash->align);
  415. if (len_aligned_down) ok = flash->write_fn(s_addr, buf, len_aligned_down);
  416. if (len_aligned_down < len) {
  417. size_t left = len - len_aligned_down;
  418. char tmp[flash->align];
  419. memset(tmp, 0xff, sizeof(tmp));
  420. memcpy(tmp, (char *) buf + len_aligned_down, left);
  421. ok = flash->write_fn(s_addr + len_aligned_down, tmp, sizeof(tmp));
  422. }
  423. s_crc32 = mg_crc32(s_crc32, (char *) buf, len); // Update CRC
  424. MG_DEBUG(("%#x %p %lu -> %d", s_addr - len, buf, len, ok));
  425. s_addr += len;
  426. }
  427. return ok;
  428. }
  429. bool mg_ota_flash_end(struct mg_flash *flash) {
  430. char *base = (char *) flash->start + flash->size / 2;
  431. bool ok = false;
  432. if (s_size) {
  433. size_t size = (size_t) (s_addr - base);
  434. uint32_t crc32 = mg_crc32(0, base, s_size);
  435. if (size == s_size && crc32 == s_crc32) ok = true;
  436. MG_DEBUG(("CRC: %x/%x, size: %lu/%lu, status: %s", s_crc32, crc32, s_size,
  437. size, ok ? "ok" : "fail"));
  438. s_size = 0;
  439. if (ok) ok = flash->swap_fn();
  440. }
  441. MG_INFO(("Finishing OTA: %s", ok ? "ok" : "fail"));
  442. return ok;
  443. }
  444. #endif
  445. #ifdef MG_ENABLE_LINES
  446. #line 1 "src/fmt.c"
  447. #endif
  448. static bool is_digit(int c) {
  449. return c >= '0' && c <= '9';
  450. }
  451. static int addexp(char *buf, int e, int sign) {
  452. int n = 0;
  453. buf[n++] = 'e';
  454. buf[n++] = (char) sign;
  455. if (e > 400) return 0;
  456. if (e < 10) buf[n++] = '0';
  457. if (e >= 100) buf[n++] = (char) (e / 100 + '0'), e -= 100 * (e / 100);
  458. if (e >= 10) buf[n++] = (char) (e / 10 + '0'), e -= 10 * (e / 10);
  459. buf[n++] = (char) (e + '0');
  460. return n;
  461. }
  462. static int xisinf(double x) {
  463. union {
  464. double f;
  465. uint64_t u;
  466. } ieee754 = {x};
  467. return ((unsigned) (ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
  468. ((unsigned) ieee754.u == 0);
  469. }
  470. static int xisnan(double x) {
  471. union {
  472. double f;
  473. uint64_t u;
  474. } ieee754 = {x};
  475. return ((unsigned) (ieee754.u >> 32) & 0x7fffffff) +
  476. ((unsigned) ieee754.u != 0) >
  477. 0x7ff00000;
  478. }
  479. static size_t mg_dtoa(char *dst, size_t dstlen, double d, int width, bool tz) {
  480. char buf[40];
  481. int i, s = 0, n = 0, e = 0;
  482. double t, mul, saved;
  483. if (d == 0.0) return mg_snprintf(dst, dstlen, "%s", "0");
  484. if (xisinf(d)) return mg_snprintf(dst, dstlen, "%s", d > 0 ? "inf" : "-inf");
  485. if (xisnan(d)) return mg_snprintf(dst, dstlen, "%s", "nan");
  486. if (d < 0.0) d = -d, buf[s++] = '-';
  487. // Round
  488. saved = d;
  489. if (tz) {
  490. mul = 1.0;
  491. while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0;
  492. } else {
  493. mul = 0.1;
  494. }
  495. while (d <= 1.0 && d / mul <= 1.0) mul /= 10.0;
  496. for (i = 0, t = mul * 5; i < width; i++) t /= 10.0;
  497. d += t;
  498. // Calculate exponent, and 'mul' for scientific representation
  499. mul = 1.0;
  500. while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0, e++;
  501. while (d < 1.0 && d / mul < 1.0) mul /= 10.0, e--;
  502. // printf(" --> %g %d %g %g\n", saved, e, t, mul);
  503. if (tz && e >= width && width > 1) {
  504. n = (int) mg_dtoa(buf, sizeof(buf), saved / mul, width, tz);
  505. // printf(" --> %.*g %d [%.*s]\n", 10, d / t, e, n, buf);
  506. n += addexp(buf + s + n, e, '+');
  507. return mg_snprintf(dst, dstlen, "%.*s", n, buf);
  508. } else if (tz && e <= -width && width > 1) {
  509. n = (int) mg_dtoa(buf, sizeof(buf), saved / mul, width, tz);
  510. // printf(" --> %.*g %d [%.*s]\n", 10, d / mul, e, n, buf);
  511. n += addexp(buf + s + n, -e, '-');
  512. return mg_snprintf(dst, dstlen, "%.*s", n, buf);
  513. } else {
  514. int targ_width = width;
  515. for (i = 0, t = mul; t >= 1.0 && s + n < (int) sizeof(buf); i++) {
  516. int ch = (int) (d / t);
  517. if (n > 0 || ch > 0) buf[s + n++] = (char) (ch + '0');
  518. d -= ch * t;
  519. t /= 10.0;
  520. }
  521. // printf(" --> [%g] -> %g %g (%d) [%.*s]\n", saved, d, t, n, s + n, buf);
  522. if (n == 0) buf[s++] = '0';
  523. while (t >= 1.0 && n + s < (int) sizeof(buf)) buf[n++] = '0', t /= 10.0;
  524. if (s + n < (int) sizeof(buf)) buf[n + s++] = '.';
  525. // printf(" 1--> [%g] -> [%.*s]\n", saved, s + n, buf);
  526. if (!tz && n > 0) targ_width = width + n;
  527. for (i = 0, t = 0.1; s + n < (int) sizeof(buf) && n < targ_width; i++) {
  528. int ch = (int) (d / t);
  529. buf[s + n++] = (char) (ch + '0');
  530. d -= ch * t;
  531. t /= 10.0;
  532. }
  533. }
  534. while (tz && n > 0 && buf[s + n - 1] == '0') n--; // Trim trailing zeroes
  535. if (tz && n > 0 && buf[s + n - 1] == '.') n--; // Trim trailing dot
  536. n += s;
  537. if (n >= (int) sizeof(buf)) n = (int) sizeof(buf) - 1;
  538. buf[n] = '\0';
  539. return mg_snprintf(dst, dstlen, "%s", buf);
  540. }
  541. static size_t mg_lld(char *buf, int64_t val, bool is_signed, bool is_hex) {
  542. const char *letters = "0123456789abcdef";
  543. uint64_t v = (uint64_t) val;
  544. size_t s = 0, n, i;
  545. if (is_signed && val < 0) buf[s++] = '-', v = (uint64_t) (-val);
  546. // This loop prints a number in reverse order. I guess this is because we
  547. // write numbers from right to left: least significant digit comes last.
  548. // Maybe because we use Arabic numbers, and Arabs write RTL?
  549. if (is_hex) {
  550. for (n = 0; v; v >>= 4) buf[s + n++] = letters[v & 15];
  551. } else {
  552. for (n = 0; v; v /= 10) buf[s + n++] = letters[v % 10];
  553. }
  554. // Reverse a string
  555. for (i = 0; i < n / 2; i++) {
  556. char t = buf[s + i];
  557. buf[s + i] = buf[s + n - i - 1], buf[s + n - i - 1] = t;
  558. }
  559. if (val == 0) buf[n++] = '0'; // Handle special case
  560. return n + s;
  561. }
  562. static size_t scpy(void (*out)(char, void *), void *ptr, char *buf,
  563. size_t len) {
  564. size_t i = 0;
  565. while (i < len && buf[i] != '\0') out(buf[i++], ptr);
  566. return i;
  567. }
  568. size_t mg_xprintf(void (*out)(char, void *), void *ptr, const char *fmt, ...) {
  569. size_t len = 0;
  570. va_list ap;
  571. va_start(ap, fmt);
  572. len = mg_vxprintf(out, ptr, fmt, &ap);
  573. va_end(ap);
  574. return len;
  575. }
  576. size_t mg_vxprintf(void (*out)(char, void *), void *param, const char *fmt,
  577. va_list *ap) {
  578. size_t i = 0, n = 0;
  579. while (fmt[i] != '\0') {
  580. if (fmt[i] == '%') {
  581. size_t j, k, x = 0, is_long = 0, w = 0 /* width */, pr = ~0U /* prec */;
  582. char pad = ' ', minus = 0, c = fmt[++i];
  583. if (c == '#') x++, c = fmt[++i];
  584. if (c == '-') minus++, c = fmt[++i];
  585. if (c == '0') pad = '0', c = fmt[++i];
  586. while (is_digit(c)) w *= 10, w += (size_t) (c - '0'), c = fmt[++i];
  587. if (c == '.') {
  588. c = fmt[++i];
  589. if (c == '*') {
  590. pr = (size_t) va_arg(*ap, int);
  591. c = fmt[++i];
  592. } else {
  593. pr = 0;
  594. while (is_digit(c)) pr *= 10, pr += (size_t) (c - '0'), c = fmt[++i];
  595. }
  596. }
  597. while (c == 'h') c = fmt[++i]; // Treat h and hh as int
  598. if (c == 'l') {
  599. is_long++, c = fmt[++i];
  600. if (c == 'l') is_long++, c = fmt[++i];
  601. }
  602. if (c == 'p') x = 1, is_long = 1;
  603. if (c == 'd' || c == 'u' || c == 'x' || c == 'X' || c == 'p' ||
  604. c == 'g' || c == 'f') {
  605. bool s = (c == 'd'), h = (c == 'x' || c == 'X' || c == 'p');
  606. char tmp[40];
  607. size_t xl = x ? 2 : 0;
  608. if (c == 'g' || c == 'f') {
  609. double v = va_arg(*ap, double);
  610. if (pr == ~0U) pr = 6;
  611. k = mg_dtoa(tmp, sizeof(tmp), v, (int) pr, c == 'g');
  612. } else if (is_long == 2) {
  613. int64_t v = va_arg(*ap, int64_t);
  614. k = mg_lld(tmp, v, s, h);
  615. } else if (is_long == 1) {
  616. long v = va_arg(*ap, long);
  617. k = mg_lld(tmp, s ? (int64_t) v : (int64_t) (unsigned long) v, s, h);
  618. } else {
  619. int v = va_arg(*ap, int);
  620. k = mg_lld(tmp, s ? (int64_t) v : (int64_t) (unsigned) v, s, h);
  621. }
  622. for (j = 0; j < xl && w > 0; j++) w--;
  623. for (j = 0; pad == ' ' && !minus && k < w && j + k < w; j++)
  624. n += scpy(out, param, &pad, 1);
  625. n += scpy(out, param, (char *) "0x", xl);
  626. for (j = 0; pad == '0' && k < w && j + k < w; j++)
  627. n += scpy(out, param, &pad, 1);
  628. n += scpy(out, param, tmp, k);
  629. for (j = 0; pad == ' ' && minus && k < w && j + k < w; j++)
  630. n += scpy(out, param, &pad, 1);
  631. } else if (c == 'm' || c == 'M') {
  632. mg_pm_t f = va_arg(*ap, mg_pm_t);
  633. if (c == 'm') out('"', param);
  634. n += f(out, param, ap);
  635. if (c == 'm') n += 2, out('"', param);
  636. } else if (c == 'c') {
  637. int ch = va_arg(*ap, int);
  638. out((char) ch, param);
  639. n++;
  640. } else if (c == 's') {
  641. char *p = va_arg(*ap, char *);
  642. if (pr == ~0U) pr = p == NULL ? 0 : strlen(p);
  643. for (j = 0; !minus && pr < w && j + pr < w; j++)
  644. n += scpy(out, param, &pad, 1);
  645. n += scpy(out, param, p, pr);
  646. for (j = 0; minus && pr < w && j + pr < w; j++)
  647. n += scpy(out, param, &pad, 1);
  648. } else if (c == '%') {
  649. out('%', param);
  650. n++;
  651. } else {
  652. out('%', param);
  653. out(c, param);
  654. n += 2;
  655. }
  656. i++;
  657. } else {
  658. out(fmt[i], param), n++, i++;
  659. }
  660. }
  661. return n;
  662. }
  663. #ifdef MG_ENABLE_LINES
  664. #line 1 "src/fs.c"
  665. #endif
  666. struct mg_fd *mg_fs_open(struct mg_fs *fs, const char *path, int flags) {
  667. struct mg_fd *fd = (struct mg_fd *) calloc(1, sizeof(*fd));
  668. if (fd != NULL) {
  669. fd->fd = fs->op(path, flags);
  670. fd->fs = fs;
  671. if (fd->fd == NULL) {
  672. free(fd);
  673. fd = NULL;
  674. }
  675. }
  676. return fd;
  677. }
  678. void mg_fs_close(struct mg_fd *fd) {
  679. if (fd != NULL) {
  680. fd->fs->cl(fd->fd);
  681. free(fd);
  682. }
  683. }
  684. struct mg_str mg_file_read(struct mg_fs *fs, const char *path) {
  685. struct mg_str result = {NULL, 0};
  686. void *fp;
  687. fs->st(path, &result.len, NULL);
  688. if ((fp = fs->op(path, MG_FS_READ)) != NULL) {
  689. result.buf = (char *) calloc(1, result.len + 1);
  690. if (result.buf != NULL &&
  691. fs->rd(fp, (void *) result.buf, result.len) != result.len) {
  692. free((void *) result.buf);
  693. result.buf = NULL;
  694. }
  695. fs->cl(fp);
  696. }
  697. if (result.buf == NULL) result.len = 0;
  698. return result;
  699. }
  700. bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
  701. size_t len) {
  702. bool result = false;
  703. struct mg_fd *fd;
  704. char tmp[MG_PATH_MAX];
  705. mg_snprintf(tmp, sizeof(tmp), "%s..%d", path, rand());
  706. if ((fd = mg_fs_open(fs, tmp, MG_FS_WRITE)) != NULL) {
  707. result = fs->wr(fd->fd, buf, len) == len;
  708. mg_fs_close(fd);
  709. if (result) {
  710. fs->rm(path);
  711. fs->mv(tmp, path);
  712. } else {
  713. fs->rm(tmp);
  714. }
  715. }
  716. return result;
  717. }
  718. bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...) {
  719. va_list ap;
  720. char *data;
  721. bool result = false;
  722. va_start(ap, fmt);
  723. data = mg_vmprintf(fmt, &ap);
  724. va_end(ap);
  725. result = mg_file_write(fs, path, data, strlen(data));
  726. free(data);
  727. return result;
  728. }
  729. // This helper function allows to scan a filesystem in a sequential way,
  730. // without using callback function:
  731. // char buf[100] = "";
  732. // while (mg_fs_ls(&mg_fs_posix, "./", buf, sizeof(buf))) {
  733. // ...
  734. static void mg_fs_ls_fn(const char *filename, void *param) {
  735. struct mg_str *s = (struct mg_str *) param;
  736. if (s->buf[0] == '\0') {
  737. mg_snprintf((char *) s->buf, s->len, "%s", filename);
  738. } else if (strcmp(s->buf, filename) == 0) {
  739. ((char *) s->buf)[0] = '\0'; // Fetch next file
  740. }
  741. }
  742. bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len) {
  743. struct mg_str s = {buf, len};
  744. fs->ls(path, mg_fs_ls_fn, &s);
  745. return buf[0] != '\0';
  746. }
  747. #ifdef MG_ENABLE_LINES
  748. #line 1 "src/fs_fat.c"
  749. #endif
  750. #if MG_ENABLE_FATFS
  751. #include <ff.h>
  752. static int mg_days_from_epoch(int y, int m, int d) {
  753. y -= m <= 2;
  754. int era = y / 400;
  755. int yoe = y - era * 400;
  756. int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
  757. int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  758. return era * 146097 + doe - 719468;
  759. }
  760. static time_t mg_timegm(const struct tm *t) {
  761. int year = t->tm_year + 1900;
  762. int month = t->tm_mon; // 0-11
  763. if (month > 11) {
  764. year += month / 12;
  765. month %= 12;
  766. } else if (month < 0) {
  767. int years_diff = (11 - month) / 12;
  768. year -= years_diff;
  769. month += 12 * years_diff;
  770. }
  771. int x = mg_days_from_epoch(year, month + 1, t->tm_mday);
  772. return 60 * (60 * (24L * x + t->tm_hour) + t->tm_min) + t->tm_sec;
  773. }
  774. static time_t ff_time_to_epoch(uint16_t fdate, uint16_t ftime) {
  775. struct tm tm;
  776. memset(&tm, 0, sizeof(struct tm));
  777. tm.tm_sec = (ftime << 1) & 0x3e;
  778. tm.tm_min = ((ftime >> 5) & 0x3f);
  779. tm.tm_hour = ((ftime >> 11) & 0x1f);
  780. tm.tm_mday = (fdate & 0x1f);
  781. tm.tm_mon = ((fdate >> 5) & 0x0f) - 1;
  782. tm.tm_year = ((fdate >> 9) & 0x7f) + 80;
  783. return mg_timegm(&tm);
  784. }
  785. static int ff_stat(const char *path, size_t *size, time_t *mtime) {
  786. FILINFO fi;
  787. if (path[0] == '\0') {
  788. if (size) *size = 0;
  789. if (mtime) *mtime = 0;
  790. return MG_FS_DIR;
  791. } else if (f_stat(path, &fi) == 0) {
  792. if (size) *size = (size_t) fi.fsize;
  793. if (mtime) *mtime = ff_time_to_epoch(fi.fdate, fi.ftime);
  794. return MG_FS_READ | MG_FS_WRITE | ((fi.fattrib & AM_DIR) ? MG_FS_DIR : 0);
  795. } else {
  796. return 0;
  797. }
  798. }
  799. static void ff_list(const char *dir, void (*fn)(const char *, void *),
  800. void *userdata) {
  801. DIR d;
  802. FILINFO fi;
  803. if (f_opendir(&d, dir) == FR_OK) {
  804. while (f_readdir(&d, &fi) == FR_OK && fi.fname[0] != '\0') {
  805. if (!strcmp(fi.fname, ".") || !strcmp(fi.fname, "..")) continue;
  806. fn(fi.fname, userdata);
  807. }
  808. f_closedir(&d);
  809. }
  810. }
  811. static void *ff_open(const char *path, int flags) {
  812. FIL f;
  813. unsigned char mode = FA_READ;
  814. if (flags & MG_FS_WRITE) mode |= FA_WRITE | FA_OPEN_ALWAYS | FA_OPEN_APPEND;
  815. if (f_open(&f, path, mode) == 0) {
  816. FIL *fp;
  817. if ((fp = calloc(1, sizeof(*fp))) != NULL) {
  818. memcpy(fp, &f, sizeof(*fp));
  819. return fp;
  820. }
  821. }
  822. return NULL;
  823. }
  824. static void ff_close(void *fp) {
  825. if (fp != NULL) {
  826. f_close((FIL *) fp);
  827. free(fp);
  828. }
  829. }
  830. static size_t ff_read(void *fp, void *buf, size_t len) {
  831. UINT n = 0, misalign = ((size_t) buf) & 3;
  832. if (misalign) {
  833. char aligned[4];
  834. f_read((FIL *) fp, aligned, len > misalign ? misalign : len, &n);
  835. memcpy(buf, aligned, n);
  836. } else {
  837. f_read((FIL *) fp, buf, len, &n);
  838. }
  839. return n;
  840. }
  841. static size_t ff_write(void *fp, const void *buf, size_t len) {
  842. UINT n = 0;
  843. return f_write((FIL *) fp, (char *) buf, len, &n) == FR_OK ? n : 0;
  844. }
  845. static size_t ff_seek(void *fp, size_t offset) {
  846. f_lseek((FIL *) fp, offset);
  847. return offset;
  848. }
  849. static bool ff_rename(const char *from, const char *to) {
  850. return f_rename(from, to) == FR_OK;
  851. }
  852. static bool ff_remove(const char *path) {
  853. return f_unlink(path) == FR_OK;
  854. }
  855. static bool ff_mkdir(const char *path) {
  856. return f_mkdir(path) == FR_OK;
  857. }
  858. struct mg_fs mg_fs_fat = {ff_stat, ff_list, ff_open, ff_close, ff_read,
  859. ff_write, ff_seek, ff_rename, ff_remove, ff_mkdir};
  860. #endif
  861. #ifdef MG_ENABLE_LINES
  862. #line 1 "src/fs_packed.c"
  863. #endif
  864. struct packed_file {
  865. const char *data;
  866. size_t size;
  867. size_t pos;
  868. };
  869. #if MG_ENABLE_PACKED_FS
  870. #else
  871. const char *mg_unpack(const char *path, size_t *size, time_t *mtime) {
  872. if (size != NULL) *size = 0;
  873. if (mtime != NULL) *mtime = 0;
  874. (void) path;
  875. return NULL;
  876. }
  877. const char *mg_unlist(size_t no) {
  878. (void) no;
  879. return NULL;
  880. }
  881. #endif
  882. struct mg_str mg_unpacked(const char *path) {
  883. size_t len = 0;
  884. const char *buf = mg_unpack(path, &len, NULL);
  885. return mg_str_n(buf, len);
  886. }
  887. static int is_dir_prefix(const char *prefix, size_t n, const char *path) {
  888. // MG_INFO(("[%.*s] [%s] %c", (int) n, prefix, path, path[n]));
  889. return n < strlen(path) && strncmp(prefix, path, n) == 0 &&
  890. (n == 0 || path[n] == '/' || path[n - 1] == '/');
  891. }
  892. static int packed_stat(const char *path, size_t *size, time_t *mtime) {
  893. const char *p;
  894. size_t i, n = strlen(path);
  895. if (mg_unpack(path, size, mtime)) return MG_FS_READ; // Regular file
  896. // Scan all files. If `path` is a dir prefix for any of them, it's a dir
  897. for (i = 0; (p = mg_unlist(i)) != NULL; i++) {
  898. if (is_dir_prefix(path, n, p)) return MG_FS_DIR;
  899. }
  900. return 0;
  901. }
  902. static void packed_list(const char *dir, void (*fn)(const char *, void *),
  903. void *userdata) {
  904. char buf[MG_PATH_MAX], tmp[sizeof(buf)];
  905. const char *path, *begin, *end;
  906. size_t i, n = strlen(dir);
  907. tmp[0] = '\0'; // Previously listed entry
  908. for (i = 0; (path = mg_unlist(i)) != NULL; i++) {
  909. if (!is_dir_prefix(dir, n, path)) continue;
  910. begin = &path[n + 1];
  911. end = strchr(begin, '/');
  912. if (end == NULL) end = begin + strlen(begin);
  913. mg_snprintf(buf, sizeof(buf), "%.*s", (int) (end - begin), begin);
  914. buf[sizeof(buf) - 1] = '\0';
  915. // If this entry has been already listed, skip
  916. // NOTE: we're assuming that file list is sorted alphabetically
  917. if (strcmp(buf, tmp) == 0) continue;
  918. fn(buf, userdata); // Not yet listed, call user function
  919. strcpy(tmp, buf); // And save this entry as listed
  920. }
  921. }
  922. static void *packed_open(const char *path, int flags) {
  923. size_t size = 0;
  924. const char *data = mg_unpack(path, &size, NULL);
  925. struct packed_file *fp = NULL;
  926. if (data == NULL) return NULL;
  927. if (flags & MG_FS_WRITE) return NULL;
  928. if ((fp = (struct packed_file *) calloc(1, sizeof(*fp))) != NULL) {
  929. fp->size = size;
  930. fp->data = data;
  931. }
  932. return (void *) fp;
  933. }
  934. static void packed_close(void *fp) {
  935. if (fp != NULL) free(fp);
  936. }
  937. static size_t packed_read(void *fd, void *buf, size_t len) {
  938. struct packed_file *fp = (struct packed_file *) fd;
  939. if (fp->pos + len > fp->size) len = fp->size - fp->pos;
  940. memcpy(buf, &fp->data[fp->pos], len);
  941. fp->pos += len;
  942. return len;
  943. }
  944. static size_t packed_write(void *fd, const void *buf, size_t len) {
  945. (void) fd, (void) buf, (void) len;
  946. return 0;
  947. }
  948. static size_t packed_seek(void *fd, size_t offset) {
  949. struct packed_file *fp = (struct packed_file *) fd;
  950. fp->pos = offset;
  951. if (fp->pos > fp->size) fp->pos = fp->size;
  952. return fp->pos;
  953. }
  954. static bool packed_rename(const char *from, const char *to) {
  955. (void) from, (void) to;
  956. return false;
  957. }
  958. static bool packed_remove(const char *path) {
  959. (void) path;
  960. return false;
  961. }
  962. static bool packed_mkdir(const char *path) {
  963. (void) path;
  964. return false;
  965. }
  966. struct mg_fs mg_fs_packed = {
  967. packed_stat, packed_list, packed_open, packed_close, packed_read,
  968. packed_write, packed_seek, packed_rename, packed_remove, packed_mkdir};
  969. #ifdef MG_ENABLE_LINES
  970. #line 1 "src/fs_posix.c"
  971. #endif
  972. #if MG_ENABLE_POSIX_FS
  973. #ifndef MG_STAT_STRUCT
  974. #define MG_STAT_STRUCT stat
  975. #endif
  976. #ifndef MG_STAT_FUNC
  977. #define MG_STAT_FUNC stat
  978. #endif
  979. static int p_stat(const char *path, size_t *size, time_t *mtime) {
  980. #if !defined(S_ISDIR)
  981. MG_ERROR(("stat() API is not supported. %p %p %p", path, size, mtime));
  982. return 0;
  983. #else
  984. #if MG_ARCH == MG_ARCH_WIN32
  985. struct _stati64 st;
  986. wchar_t tmp[MG_PATH_MAX];
  987. MultiByteToWideChar(CP_UTF8, 0, path, -1, tmp, sizeof(tmp) / sizeof(tmp[0]));
  988. if (_wstati64(tmp, &st) != 0) return 0;
  989. // If path is a symlink, windows reports 0 in st.st_size.
  990. // Get a real file size by opening it and jumping to the end
  991. if (st.st_size == 0 && (st.st_mode & _S_IFREG)) {
  992. FILE *fp = _wfopen(tmp, L"rb");
  993. if (fp != NULL) {
  994. fseek(fp, 0, SEEK_END);
  995. if (ftell(fp) > 0) st.st_size = ftell(fp); // Use _ftelli64 on win10+
  996. fclose(fp);
  997. }
  998. }
  999. #else
  1000. struct MG_STAT_STRUCT st;
  1001. if (MG_STAT_FUNC(path, &st) != 0) return 0;
  1002. #endif
  1003. if (size) *size = (size_t) st.st_size;
  1004. if (mtime) *mtime = st.st_mtime;
  1005. return MG_FS_READ | MG_FS_WRITE | (S_ISDIR(st.st_mode) ? MG_FS_DIR : 0);
  1006. #endif
  1007. }
  1008. #if MG_ARCH == MG_ARCH_WIN32
  1009. struct dirent {
  1010. char d_name[MAX_PATH];
  1011. };
  1012. typedef struct win32_dir {
  1013. HANDLE handle;
  1014. WIN32_FIND_DATAW info;
  1015. struct dirent result;
  1016. } DIR;
  1017. #if 0
  1018. int gettimeofday(struct timeval *tv, void *tz) {
  1019. FILETIME ft;
  1020. unsigned __int64 tmpres = 0;
  1021. if (tv != NULL) {
  1022. GetSystemTimeAsFileTime(&ft);
  1023. tmpres |= ft.dwHighDateTime;
  1024. tmpres <<= 32;
  1025. tmpres |= ft.dwLowDateTime;
  1026. tmpres /= 10; // convert into microseconds
  1027. tmpres -= (int64_t) 11644473600000000;
  1028. tv->tv_sec = (long) (tmpres / 1000000UL);
  1029. tv->tv_usec = (long) (tmpres % 1000000UL);
  1030. }
  1031. (void) tz;
  1032. return 0;
  1033. }
  1034. #endif
  1035. static int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1036. int ret;
  1037. char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
  1038. strncpy(buf, path, sizeof(buf));
  1039. buf[sizeof(buf) - 1] = '\0';
  1040. // Trim trailing slashes. Leave backslash for paths like "X:\"
  1041. p = buf + strlen(buf) - 1;
  1042. while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
  1043. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1044. ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1045. // Convert back to Unicode. If doubly-converted string does not match the
  1046. // original, something is fishy, reject.
  1047. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1048. NULL, NULL);
  1049. if (strcmp(buf, buf2) != 0) {
  1050. wbuf[0] = L'\0';
  1051. ret = 0;
  1052. }
  1053. return ret;
  1054. }
  1055. DIR *opendir(const char *name) {
  1056. DIR *d = NULL;
  1057. wchar_t wpath[MAX_PATH];
  1058. DWORD attrs;
  1059. if (name == NULL) {
  1060. SetLastError(ERROR_BAD_ARGUMENTS);
  1061. } else if ((d = (DIR *) calloc(1, sizeof(*d))) == NULL) {
  1062. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1063. } else {
  1064. to_wchar(name, wpath, sizeof(wpath) / sizeof(wpath[0]));
  1065. attrs = GetFileAttributesW(wpath);
  1066. if (attrs != 0Xffffffff && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1067. (void) wcscat(wpath, L"\\*");
  1068. d->handle = FindFirstFileW(wpath, &d->info);
  1069. d->result.d_name[0] = '\0';
  1070. } else {
  1071. free(d);
  1072. d = NULL;
  1073. }
  1074. }
  1075. return d;
  1076. }
  1077. int closedir(DIR *d) {
  1078. int result = 0;
  1079. if (d != NULL) {
  1080. if (d->handle != INVALID_HANDLE_VALUE)
  1081. result = FindClose(d->handle) ? 0 : -1;
  1082. free(d);
  1083. } else {
  1084. result = -1;
  1085. SetLastError(ERROR_BAD_ARGUMENTS);
  1086. }
  1087. return result;
  1088. }
  1089. struct dirent *readdir(DIR *d) {
  1090. struct dirent *result = NULL;
  1091. if (d != NULL) {
  1092. memset(&d->result, 0, sizeof(d->result));
  1093. if (d->handle != INVALID_HANDLE_VALUE) {
  1094. result = &d->result;
  1095. WideCharToMultiByte(CP_UTF8, 0, d->info.cFileName, -1, result->d_name,
  1096. sizeof(result->d_name), NULL, NULL);
  1097. if (!FindNextFileW(d->handle, &d->info)) {
  1098. FindClose(d->handle);
  1099. d->handle = INVALID_HANDLE_VALUE;
  1100. }
  1101. } else {
  1102. SetLastError(ERROR_FILE_NOT_FOUND);
  1103. }
  1104. } else {
  1105. SetLastError(ERROR_BAD_ARGUMENTS);
  1106. }
  1107. return result;
  1108. }
  1109. #endif
  1110. static void p_list(const char *dir, void (*fn)(const char *, void *),
  1111. void *userdata) {
  1112. #if MG_ENABLE_DIRLIST
  1113. struct dirent *dp;
  1114. DIR *dirp;
  1115. if ((dirp = (opendir(dir))) == NULL) return;
  1116. while ((dp = readdir(dirp)) != NULL) {
  1117. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
  1118. fn(dp->d_name, userdata);
  1119. }
  1120. closedir(dirp);
  1121. #else
  1122. (void) dir, (void) fn, (void) userdata;
  1123. #endif
  1124. }
  1125. static void *p_open(const char *path, int flags) {
  1126. #if MG_ARCH == MG_ARCH_WIN32
  1127. const char *mode = flags == MG_FS_READ ? "rb" : "a+b";
  1128. wchar_t b1[MG_PATH_MAX], b2[10];
  1129. MultiByteToWideChar(CP_UTF8, 0, path, -1, b1, sizeof(b1) / sizeof(b1[0]));
  1130. MultiByteToWideChar(CP_UTF8, 0, mode, -1, b2, sizeof(b2) / sizeof(b2[0]));
  1131. return (void *) _wfopen(b1, b2);
  1132. #else
  1133. const char *mode = flags == MG_FS_READ ? "rbe" : "a+be"; // e for CLOEXEC
  1134. return (void *) fopen(path, mode);
  1135. #endif
  1136. }
  1137. static void p_close(void *fp) {
  1138. fclose((FILE *) fp);
  1139. }
  1140. static size_t p_read(void *fp, void *buf, size_t len) {
  1141. return fread(buf, 1, len, (FILE *) fp);
  1142. }
  1143. static size_t p_write(void *fp, const void *buf, size_t len) {
  1144. return fwrite(buf, 1, len, (FILE *) fp);
  1145. }
  1146. static size_t p_seek(void *fp, size_t offset) {
  1147. #if (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64) || \
  1148. (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) || \
  1149. (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
  1150. if (fseeko((FILE *) fp, (off_t) offset, SEEK_SET) != 0) (void) 0;
  1151. #else
  1152. if (fseek((FILE *) fp, (long) offset, SEEK_SET) != 0) (void) 0;
  1153. #endif
  1154. return (size_t) ftell((FILE *) fp);
  1155. }
  1156. static bool p_rename(const char *from, const char *to) {
  1157. return rename(from, to) == 0;
  1158. }
  1159. static bool p_remove(const char *path) {
  1160. return remove(path) == 0;
  1161. }
  1162. static bool p_mkdir(const char *path) {
  1163. return mkdir(path, 0775) == 0;
  1164. }
  1165. #else
  1166. static int p_stat(const char *path, size_t *size, time_t *mtime) {
  1167. (void) path, (void) size, (void) mtime;
  1168. return 0;
  1169. }
  1170. static void p_list(const char *path, void (*fn)(const char *, void *),
  1171. void *userdata) {
  1172. (void) path, (void) fn, (void) userdata;
  1173. }
  1174. static void *p_open(const char *path, int flags) {
  1175. (void) path, (void) flags;
  1176. return NULL;
  1177. }
  1178. static void p_close(void *fp) {
  1179. (void) fp;
  1180. }
  1181. static size_t p_read(void *fd, void *buf, size_t len) {
  1182. (void) fd, (void) buf, (void) len;
  1183. return 0;
  1184. }
  1185. static size_t p_write(void *fd, const void *buf, size_t len) {
  1186. (void) fd, (void) buf, (void) len;
  1187. return 0;
  1188. }
  1189. static size_t p_seek(void *fd, size_t offset) {
  1190. (void) fd, (void) offset;
  1191. return (size_t) ~0;
  1192. }
  1193. static bool p_rename(const char *from, const char *to) {
  1194. (void) from, (void) to;
  1195. return false;
  1196. }
  1197. static bool p_remove(const char *path) {
  1198. (void) path;
  1199. return false;
  1200. }
  1201. static bool p_mkdir(const char *path) {
  1202. (void) path;
  1203. return false;
  1204. }
  1205. #endif
  1206. struct mg_fs mg_fs_posix = {p_stat, p_list, p_open, p_close, p_read,
  1207. p_write, p_seek, p_rename, p_remove, p_mkdir};
  1208. #ifdef MG_ENABLE_LINES
  1209. #line 1 "src/http.c"
  1210. #endif
  1211. static int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  1212. int diff = 0;
  1213. if (len > 0) do {
  1214. int c = *s1++, d = *s2++;
  1215. if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
  1216. if (d >= 'A' && d <= 'Z') d += 'a' - 'A';
  1217. diff = c - d;
  1218. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1219. return diff;
  1220. }
  1221. bool mg_to_size_t(struct mg_str str, size_t *val);
  1222. bool mg_to_size_t(struct mg_str str, size_t *val) {
  1223. size_t i = 0, max = (size_t) -1, max2 = max / 10, result = 0, ndigits = 0;
  1224. while (i < str.len && (str.buf[i] == ' ' || str.buf[i] == '\t')) i++;
  1225. if (i < str.len && str.buf[i] == '-') return false;
  1226. while (i < str.len && str.buf[i] >= '0' && str.buf[i] <= '9') {
  1227. size_t digit = (size_t) (str.buf[i] - '0');
  1228. if (result > max2) return false; // Overflow
  1229. result *= 10;
  1230. if (result > max - digit) return false; // Overflow
  1231. result += digit;
  1232. i++, ndigits++;
  1233. }
  1234. while (i < str.len && (str.buf[i] == ' ' || str.buf[i] == '\t')) i++;
  1235. if (ndigits == 0) return false; // #2322: Content-Length = 1 * DIGIT
  1236. if (i != str.len) return false; // Ditto
  1237. *val = (size_t) result;
  1238. return true;
  1239. }
  1240. // Chunk deletion marker is the MSB in the "processed" counter
  1241. #define MG_DMARK ((size_t) 1 << (sizeof(size_t) * 8 - 1))
  1242. // Multipart POST example:
  1243. // --xyz
  1244. // Content-Disposition: form-data; name="val"
  1245. //
  1246. // abcdef
  1247. // --xyz
  1248. // Content-Disposition: form-data; name="foo"; filename="a.txt"
  1249. // Content-Type: text/plain
  1250. //
  1251. // hello world
  1252. //
  1253. // --xyz--
  1254. size_t mg_http_next_multipart(struct mg_str body, size_t ofs,
  1255. struct mg_http_part *part) {
  1256. struct mg_str cd = mg_str_n("Content-Disposition", 19);
  1257. const char *s = body.buf;
  1258. size_t b = ofs, h1, h2, b1, b2, max = body.len;
  1259. // Init part params
  1260. if (part != NULL) part->name = part->filename = part->body = mg_str_n(0, 0);
  1261. // Skip boundary
  1262. while (b + 2 < max && s[b] != '\r' && s[b + 1] != '\n') b++;
  1263. if (b <= ofs || b + 2 >= max) return 0;
  1264. // MG_INFO(("B: %zu %zu [%.*s]", ofs, b - ofs, (int) (b - ofs), s));
  1265. // Skip headers
  1266. h1 = h2 = b + 2;
  1267. for (;;) {
  1268. while (h2 + 2 < max && s[h2] != '\r' && s[h2 + 1] != '\n') h2++;
  1269. if (h2 == h1) break;
  1270. if (h2 + 2 >= max) return 0;
  1271. // MG_INFO(("Header: [%.*s]", (int) (h2 - h1), &s[h1]));
  1272. if (part != NULL && h1 + cd.len + 2 < h2 && s[h1 + cd.len] == ':' &&
  1273. mg_ncasecmp(&s[h1], cd.buf, cd.len) == 0) {
  1274. struct mg_str v = mg_str_n(&s[h1 + cd.len + 2], h2 - (h1 + cd.len + 2));
  1275. part->name = mg_http_get_header_var(v, mg_str_n("name", 4));
  1276. part->filename = mg_http_get_header_var(v, mg_str_n("filename", 8));
  1277. }
  1278. h1 = h2 = h2 + 2;
  1279. }
  1280. b1 = b2 = h2 + 2;
  1281. while (b2 + 2 + (b - ofs) + 2 < max && !(s[b2] == '\r' && s[b2 + 1] == '\n' &&
  1282. memcmp(&s[b2 + 2], s, b - ofs) == 0))
  1283. b2++;
  1284. if (b2 + 2 >= max) return 0;
  1285. if (part != NULL) part->body = mg_str_n(&s[b1], b2 - b1);
  1286. // MG_INFO(("Body: [%.*s]", (int) (b2 - b1), &s[b1]));
  1287. return b2 + 2;
  1288. }
  1289. void mg_http_bauth(struct mg_connection *c, const char *user,
  1290. const char *pass) {
  1291. struct mg_str u = mg_str(user), p = mg_str(pass);
  1292. size_t need = c->send.len + 36 + (u.len + p.len) * 2;
  1293. if (c->send.size < need) mg_iobuf_resize(&c->send, need);
  1294. if (c->send.size >= need) {
  1295. size_t i, n = 0;
  1296. char *buf = (char *) &c->send.buf[c->send.len];
  1297. memcpy(buf, "Authorization: Basic ", 21); // DON'T use mg_send!
  1298. for (i = 0; i < u.len; i++) {
  1299. n = mg_base64_update(((unsigned char *) u.buf)[i], buf + 21, n);
  1300. }
  1301. if (p.len > 0) {
  1302. n = mg_base64_update(':', buf + 21, n);
  1303. for (i = 0; i < p.len; i++) {
  1304. n = mg_base64_update(((unsigned char *) p.buf)[i], buf + 21, n);
  1305. }
  1306. }
  1307. n = mg_base64_final(buf + 21, n);
  1308. c->send.len += 21 + (size_t) n + 2;
  1309. memcpy(&c->send.buf[c->send.len - 2], "\r\n", 2);
  1310. } else {
  1311. MG_ERROR(("%lu oom %d->%d ", c->id, (int) c->send.size, (int) need));
  1312. }
  1313. }
  1314. struct mg_str mg_http_var(struct mg_str buf, struct mg_str name) {
  1315. struct mg_str entry, k, v, result = mg_str_n(NULL, 0);
  1316. while (mg_span(buf, &entry, &buf, '&')) {
  1317. if (mg_span(entry, &k, &v, '=') && name.len == k.len &&
  1318. mg_ncasecmp(name.buf, k.buf, k.len) == 0) {
  1319. result = v;
  1320. break;
  1321. }
  1322. }
  1323. return result;
  1324. }
  1325. int mg_http_get_var(const struct mg_str *buf, const char *name, char *dst,
  1326. size_t dst_len) {
  1327. int len;
  1328. if (dst != NULL && dst_len > 0) {
  1329. dst[0] = '\0'; // If destination buffer is valid, always nul-terminate it
  1330. }
  1331. if (dst == NULL || dst_len == 0) {
  1332. len = -2; // Bad destination
  1333. } else if (buf->buf == NULL || name == NULL || buf->len == 0) {
  1334. len = -1; // Bad source
  1335. } else {
  1336. struct mg_str v = mg_http_var(*buf, mg_str(name));
  1337. if (v.buf == NULL) {
  1338. len = -4; // Name does not exist
  1339. } else {
  1340. len = mg_url_decode(v.buf, v.len, dst, dst_len, 1);
  1341. if (len < 0) len = -3; // Failed to decode
  1342. }
  1343. }
  1344. return len;
  1345. }
  1346. static bool isx(int c) {
  1347. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  1348. (c >= 'A' && c <= 'F');
  1349. }
  1350. int mg_url_decode(const char *src, size_t src_len, char *dst, size_t dst_len,
  1351. int is_form_url_encoded) {
  1352. size_t i, j;
  1353. for (i = j = 0; i < src_len && j + 1 < dst_len; i++, j++) {
  1354. if (src[i] == '%') {
  1355. // Use `i + 2 < src_len`, not `i < src_len - 2`, note small src_len
  1356. if (i + 2 < src_len && isx(src[i + 1]) && isx(src[i + 2])) {
  1357. mg_str_to_num(mg_str_n(src + i + 1, 2), 16, &dst[j], sizeof(uint8_t));
  1358. i += 2;
  1359. } else {
  1360. return -1;
  1361. }
  1362. } else if (is_form_url_encoded && src[i] == '+') {
  1363. dst[j] = ' ';
  1364. } else {
  1365. dst[j] = src[i];
  1366. }
  1367. }
  1368. if (j < dst_len) dst[j] = '\0'; // Null-terminate the destination
  1369. return i >= src_len && j < dst_len ? (int) j : -1;
  1370. }
  1371. static bool isok(uint8_t c) {
  1372. return c == '\n' || c == '\r' || c == '\t' || c >= ' ';
  1373. }
  1374. int mg_http_get_request_len(const unsigned char *buf, size_t buf_len) {
  1375. size_t i;
  1376. for (i = 0; i < buf_len; i++) {
  1377. if (!isok(buf[i])) return -1;
  1378. if ((i > 0 && buf[i] == '\n' && buf[i - 1] == '\n') ||
  1379. (i > 3 && buf[i] == '\n' && buf[i - 1] == '\r' && buf[i - 2] == '\n'))
  1380. return (int) i + 1;
  1381. }
  1382. return 0;
  1383. }
  1384. struct mg_str *mg_http_get_header(struct mg_http_message *h, const char *name) {
  1385. size_t i, n = strlen(name), max = sizeof(h->headers) / sizeof(h->headers[0]);
  1386. for (i = 0; i < max && h->headers[i].name.len > 0; i++) {
  1387. struct mg_str *k = &h->headers[i].name, *v = &h->headers[i].value;
  1388. if (n == k->len && mg_ncasecmp(k->buf, name, n) == 0) return v;
  1389. }
  1390. return NULL;
  1391. }
  1392. // Is it a valid utf-8 continuation byte
  1393. static bool vcb(uint8_t c) {
  1394. return (c & 0xc0) == 0x80;
  1395. }
  1396. // Get character length (valid utf-8). Used to parse method, URI, headers
  1397. static size_t clen(const char *s, const char *end) {
  1398. const unsigned char *u = (unsigned char *) s, c = *u;
  1399. long n = (long) (end - s);
  1400. if (c > ' ' && c < '~') return 1; // Usual ascii printed char
  1401. if ((c & 0xe0) == 0xc0 && n > 1 && vcb(u[1])) return 2; // 2-byte UTF8
  1402. if ((c & 0xf0) == 0xe0 && n > 2 && vcb(u[1]) && vcb(u[2])) return 3;
  1403. if ((c & 0xf8) == 0xf0 && n > 3 && vcb(u[1]) && vcb(u[2]) && vcb(u[3]))
  1404. return 4;
  1405. return 0;
  1406. }
  1407. // Skip until the newline. Return advanced `s`, or NULL on error
  1408. static const char *skiptorn(const char *s, const char *end, struct mg_str *v) {
  1409. v->buf = (char *) s;
  1410. while (s < end && s[0] != '\n' && s[0] != '\r') s++, v->len++; // To newline
  1411. if (s >= end || (s[0] == '\r' && s[1] != '\n')) return NULL; // Stray \r
  1412. if (s < end && s[0] == '\r') s++; // Skip \r
  1413. if (s >= end || *s++ != '\n') return NULL; // Skip \n
  1414. return s;
  1415. }
  1416. static bool mg_http_parse_headers(const char *s, const char *end,
  1417. struct mg_http_header *h, size_t max_hdrs) {
  1418. size_t i, n;
  1419. for (i = 0; i < max_hdrs; i++) {
  1420. struct mg_str k = {NULL, 0}, v = {NULL, 0};
  1421. if (s >= end) return false;
  1422. if (s[0] == '\n' || (s[0] == '\r' && s[1] == '\n')) break;
  1423. k.buf = (char *) s;
  1424. while (s < end && s[0] != ':' && (n = clen(s, end)) > 0) s += n, k.len += n;
  1425. if (k.len == 0) return false; // Empty name
  1426. if (s >= end || clen(s, end) == 0) return false; // Invalid UTF-8
  1427. if (*s++ != ':') return false; // Invalid, not followed by :
  1428. // if (clen(s, end) == 0) return false; // Invalid UTF-8
  1429. while (s < end && (s[0] == ' ' || s[0] == '\t')) s++; // Skip spaces
  1430. if ((s = skiptorn(s, end, &v)) == NULL) return false;
  1431. while (v.len > 0 && (v.buf[v.len - 1] == ' ' || v.buf[v.len - 1] == '\t')) {
  1432. v.len--; // Trim spaces
  1433. }
  1434. // MG_INFO(("--HH [%.*s] [%.*s]", (int) k.len, k.buf, (int) v.len, v.buf));
  1435. h[i].name = k, h[i].value = v; // Success. Assign values
  1436. }
  1437. return true;
  1438. }
  1439. int mg_http_parse(const char *s, size_t len, struct mg_http_message *hm) {
  1440. int is_response, req_len = mg_http_get_request_len((unsigned char *) s, len);
  1441. const char *end = s == NULL ? NULL : s + req_len, *qs; // Cannot add to NULL
  1442. const struct mg_str *cl;
  1443. size_t n;
  1444. bool version_prefix_valid;
  1445. memset(hm, 0, sizeof(*hm));
  1446. if (req_len <= 0) return req_len;
  1447. hm->message.buf = hm->head.buf = (char *) s;
  1448. hm->body.buf = (char *) end;
  1449. hm->head.len = (size_t) req_len;
  1450. hm->message.len = hm->body.len = (size_t) -1; // Set body length to infinite
  1451. // Parse request line
  1452. hm->method.buf = (char *) s;
  1453. while (s < end && (n = clen(s, end)) > 0) s += n, hm->method.len += n;
  1454. while (s < end && s[0] == ' ') s++; // Skip spaces
  1455. hm->uri.buf = (char *) s;
  1456. while (s < end && (n = clen(s, end)) > 0) s += n, hm->uri.len += n;
  1457. while (s < end && s[0] == ' ') s++; // Skip spaces
  1458. is_response = hm->method.len > 5 &&
  1459. (mg_ncasecmp(hm->method.buf, "HTTP/", 5) == 0);
  1460. if ((s = skiptorn(s, end, &hm->proto)) == NULL) return false;
  1461. // If we're given a version, check that it is HTTP/x.x
  1462. version_prefix_valid = hm->proto.len > 5 &&
  1463. (mg_ncasecmp(hm->proto.buf, "HTTP/", 5) == 0);
  1464. if (!is_response && hm->proto.len > 0 &&
  1465. (!version_prefix_valid || hm->proto.len != 8 ||
  1466. (hm->proto.buf[5] < '0' || hm->proto.buf[5] > '9') ||
  1467. (hm->proto.buf[6] != '.') ||
  1468. (hm->proto.buf[7] < '0' || hm->proto.buf[7] > '9'))) {
  1469. return -1;
  1470. }
  1471. // If URI contains '?' character, setup query string
  1472. if ((qs = (const char *) memchr(hm->uri.buf, '?', hm->uri.len)) != NULL) {
  1473. hm->query.buf = (char *) qs + 1;
  1474. hm->query.len = (size_t) (&hm->uri.buf[hm->uri.len] - (qs + 1));
  1475. hm->uri.len = (size_t) (qs - hm->uri.buf);
  1476. }
  1477. // Sanity check. Allow protocol/reason to be empty
  1478. // Do this check after hm->method.len and hm->uri.len are finalised
  1479. if (hm->method.len == 0 || hm->uri.len == 0) return -1;
  1480. if (!mg_http_parse_headers(s, end, hm->headers,
  1481. sizeof(hm->headers) / sizeof(hm->headers[0])))
  1482. return -1; // error when parsing
  1483. if ((cl = mg_http_get_header(hm, "Content-Length")) != NULL) {
  1484. if (mg_to_size_t(*cl, &hm->body.len) == false) return -1;
  1485. hm->message.len = (size_t) req_len + hm->body.len;
  1486. }
  1487. // mg_http_parse() is used to parse both HTTP requests and HTTP
  1488. // responses. If HTTP response does not have Content-Length set, then
  1489. // body is read until socket is closed, i.e. body.len is infinite (~0).
  1490. //
  1491. // For HTTP requests though, according to
  1492. // http://tools.ietf.org/html/rfc7231#section-8.1.3,
  1493. // only POST and PUT methods have defined body semantics.
  1494. // Therefore, if Content-Length is not specified and methods are
  1495. // not one of PUT or POST, set body length to 0.
  1496. //
  1497. // So, if it is HTTP request, and Content-Length is not set,
  1498. // and method is not (PUT or POST) then reset body length to zero.
  1499. if (hm->body.len == (size_t) ~0 && !is_response &&
  1500. mg_strcasecmp(hm->method, mg_str("PUT")) != 0 &&
  1501. mg_strcasecmp(hm->method, mg_str("POST")) != 0) {
  1502. hm->body.len = 0;
  1503. hm->message.len = (size_t) req_len;
  1504. }
  1505. // The 204 (No content) responses also have 0 body length
  1506. if (hm->body.len == (size_t) ~0 && is_response &&
  1507. mg_strcasecmp(hm->uri, mg_str("204")) == 0) {
  1508. hm->body.len = 0;
  1509. hm->message.len = (size_t) req_len;
  1510. }
  1511. if (hm->message.len < (size_t) req_len) return -1; // Overflow protection
  1512. return req_len;
  1513. }
  1514. static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt,
  1515. va_list *ap) {
  1516. size_t len = c->send.len;
  1517. mg_send(c, " \r\n", 10);
  1518. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  1519. if (c->send.len >= len + 10) {
  1520. mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10);
  1521. c->send.buf[len + 8] = '\r';
  1522. if (c->send.len == len + 10) c->is_resp = 0; // Last chunk, reset marker
  1523. }
  1524. mg_send(c, "\r\n", 2);
  1525. }
  1526. void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) {
  1527. va_list ap;
  1528. va_start(ap, fmt);
  1529. mg_http_vprintf_chunk(c, fmt, &ap);
  1530. va_end(ap);
  1531. }
  1532. void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) {
  1533. mg_printf(c, "%lx\r\n", (unsigned long) len);
  1534. mg_send(c, buf, len);
  1535. mg_send(c, "\r\n", 2);
  1536. if (len == 0) c->is_resp = 0;
  1537. }
  1538. // clang-format off
  1539. static const char *mg_http_status_code_str(int status_code) {
  1540. switch (status_code) {
  1541. case 100: return "Continue";
  1542. case 101: return "Switching Protocols";
  1543. case 102: return "Processing";
  1544. case 200: return "OK";
  1545. case 201: return "Created";
  1546. case 202: return "Accepted";
  1547. case 203: return "Non-authoritative Information";
  1548. case 204: return "No Content";
  1549. case 205: return "Reset Content";
  1550. case 206: return "Partial Content";
  1551. case 207: return "Multi-Status";
  1552. case 208: return "Already Reported";
  1553. case 226: return "IM Used";
  1554. case 300: return "Multiple Choices";
  1555. case 301: return "Moved Permanently";
  1556. case 302: return "Found";
  1557. case 303: return "See Other";
  1558. case 304: return "Not Modified";
  1559. case 305: return "Use Proxy";
  1560. case 307: return "Temporary Redirect";
  1561. case 308: return "Permanent Redirect";
  1562. case 400: return "Bad Request";
  1563. case 401: return "Unauthorized";
  1564. case 402: return "Payment Required";
  1565. case 403: return "Forbidden";
  1566. case 404: return "Not Found";
  1567. case 405: return "Method Not Allowed";
  1568. case 406: return "Not Acceptable";
  1569. case 407: return "Proxy Authentication Required";
  1570. case 408: return "Request Timeout";
  1571. case 409: return "Conflict";
  1572. case 410: return "Gone";
  1573. case 411: return "Length Required";
  1574. case 412: return "Precondition Failed";
  1575. case 413: return "Payload Too Large";
  1576. case 414: return "Request-URI Too Long";
  1577. case 415: return "Unsupported Media Type";
  1578. case 416: return "Requested Range Not Satisfiable";
  1579. case 417: return "Expectation Failed";
  1580. case 418: return "I'm a teapot";
  1581. case 421: return "Misdirected Request";
  1582. case 422: return "Unprocessable Entity";
  1583. case 423: return "Locked";
  1584. case 424: return "Failed Dependency";
  1585. case 426: return "Upgrade Required";
  1586. case 428: return "Precondition Required";
  1587. case 429: return "Too Many Requests";
  1588. case 431: return "Request Header Fields Too Large";
  1589. case 444: return "Connection Closed Without Response";
  1590. case 451: return "Unavailable For Legal Reasons";
  1591. case 499: return "Client Closed Request";
  1592. case 500: return "Internal Server Error";
  1593. case 501: return "Not Implemented";
  1594. case 502: return "Bad Gateway";
  1595. case 503: return "Service Unavailable";
  1596. case 504: return "Gateway Timeout";
  1597. case 505: return "HTTP Version Not Supported";
  1598. case 506: return "Variant Also Negotiates";
  1599. case 507: return "Insufficient Storage";
  1600. case 508: return "Loop Detected";
  1601. case 510: return "Not Extended";
  1602. case 511: return "Network Authentication Required";
  1603. case 599: return "Network Connect Timeout Error";
  1604. default: return "";
  1605. }
  1606. }
  1607. // clang-format on
  1608. void mg_http_reply(struct mg_connection *c, int code, const char *headers,
  1609. const char *fmt, ...) {
  1610. va_list ap;
  1611. size_t len;
  1612. mg_printf(c, "HTTP/1.1 %d %s\r\n%sContent-Length: \r\n\r\n", code,
  1613. mg_http_status_code_str(code), headers == NULL ? "" : headers);
  1614. len = c->send.len;
  1615. va_start(ap, fmt);
  1616. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  1617. va_end(ap);
  1618. if (c->send.len > 16) {
  1619. size_t n = mg_snprintf((char *) &c->send.buf[len - 15], 11, "%-10lu",
  1620. (unsigned long) (c->send.len - len));
  1621. c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space
  1622. }
  1623. c->is_resp = 0;
  1624. }
  1625. static void http_cb(struct mg_connection *, int, void *);
  1626. static void restore_http_cb(struct mg_connection *c) {
  1627. mg_fs_close((struct mg_fd *) c->pfn_data);
  1628. c->pfn_data = NULL;
  1629. c->pfn = http_cb;
  1630. c->is_resp = 0;
  1631. }
  1632. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
  1633. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime) {
  1634. mg_snprintf(buf, len, "\"%lld.%lld\"", (int64_t) mtime, (int64_t) size);
  1635. return buf;
  1636. }
  1637. static void static_cb(struct mg_connection *c, int ev, void *ev_data) {
  1638. if (ev == MG_EV_WRITE || ev == MG_EV_POLL) {
  1639. struct mg_fd *fd = (struct mg_fd *) c->pfn_data;
  1640. // Read to send IO buffer directly, avoid extra on-stack buffer
  1641. size_t n, max = MG_IO_SIZE, space;
  1642. size_t *cl = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  1643. sizeof(size_t) * sizeof(size_t)];
  1644. if (c->send.size < max) mg_iobuf_resize(&c->send, max);
  1645. if (c->send.len >= c->send.size) return; // Rate limit
  1646. if ((space = c->send.size - c->send.len) > *cl) space = *cl;
  1647. n = fd->fs->rd(fd->fd, c->send.buf + c->send.len, space);
  1648. c->send.len += n;
  1649. *cl -= n;
  1650. if (n == 0) restore_http_cb(c);
  1651. } else if (ev == MG_EV_CLOSE) {
  1652. restore_http_cb(c);
  1653. }
  1654. (void) ev_data;
  1655. }
  1656. // Known mime types. Keep it outside guess_content_type() function, since
  1657. // some environments don't like it defined there.
  1658. // clang-format off
  1659. #define MG_C_STR(a) { (char *) (a), sizeof(a) - 1 }
  1660. static struct mg_str s_known_types[] = {
  1661. MG_C_STR("html"), MG_C_STR("text/html; charset=utf-8"),
  1662. MG_C_STR("htm"), MG_C_STR("text/html; charset=utf-8"),
  1663. MG_C_STR("css"), MG_C_STR("text/css; charset=utf-8"),
  1664. MG_C_STR("js"), MG_C_STR("text/javascript; charset=utf-8"),
  1665. MG_C_STR("gif"), MG_C_STR("image/gif"),
  1666. MG_C_STR("png"), MG_C_STR("image/png"),
  1667. MG_C_STR("jpg"), MG_C_STR("image/jpeg"),
  1668. MG_C_STR("jpeg"), MG_C_STR("image/jpeg"),
  1669. MG_C_STR("woff"), MG_C_STR("font/woff"),
  1670. MG_C_STR("ttf"), MG_C_STR("font/ttf"),
  1671. MG_C_STR("svg"), MG_C_STR("image/svg+xml"),
  1672. MG_C_STR("txt"), MG_C_STR("text/plain; charset=utf-8"),
  1673. MG_C_STR("avi"), MG_C_STR("video/x-msvideo"),
  1674. MG_C_STR("csv"), MG_C_STR("text/csv"),
  1675. MG_C_STR("doc"), MG_C_STR("application/msword"),
  1676. MG_C_STR("exe"), MG_C_STR("application/octet-stream"),
  1677. MG_C_STR("gz"), MG_C_STR("application/gzip"),
  1678. MG_C_STR("ico"), MG_C_STR("image/x-icon"),
  1679. MG_C_STR("json"), MG_C_STR("application/json"),
  1680. MG_C_STR("mov"), MG_C_STR("video/quicktime"),
  1681. MG_C_STR("mp3"), MG_C_STR("audio/mpeg"),
  1682. MG_C_STR("mp4"), MG_C_STR("video/mp4"),
  1683. MG_C_STR("mpeg"), MG_C_STR("video/mpeg"),
  1684. MG_C_STR("pdf"), MG_C_STR("application/pdf"),
  1685. MG_C_STR("shtml"), MG_C_STR("text/html; charset=utf-8"),
  1686. MG_C_STR("tgz"), MG_C_STR("application/tar-gz"),
  1687. MG_C_STR("wav"), MG_C_STR("audio/wav"),
  1688. MG_C_STR("webp"), MG_C_STR("image/webp"),
  1689. MG_C_STR("zip"), MG_C_STR("application/zip"),
  1690. MG_C_STR("3gp"), MG_C_STR("video/3gpp"),
  1691. {0, 0},
  1692. };
  1693. // clang-format on
  1694. static struct mg_str guess_content_type(struct mg_str path, const char *extra) {
  1695. struct mg_str entry, k, v, s = mg_str(extra), asterisk = mg_str_n("*", 1);
  1696. size_t i = 0;
  1697. // Shrink path to its extension only
  1698. while (i < path.len && path.buf[path.len - i - 1] != '.') i++;
  1699. path.buf += path.len - i;
  1700. path.len = i;
  1701. // Process user-provided mime type overrides, if any
  1702. while (mg_span(s, &entry, &s, ',')) {
  1703. if (mg_span(entry, &k, &v, '=') &&
  1704. (mg_strcmp(asterisk, k) == 0 || mg_strcmp(path, k) == 0))
  1705. return v;
  1706. }
  1707. // Process built-in mime types
  1708. for (i = 0; s_known_types[i].buf != NULL; i += 2) {
  1709. if (mg_strcmp(path, s_known_types[i]) == 0) return s_known_types[i + 1];
  1710. }
  1711. return mg_str("text/plain; charset=utf-8");
  1712. }
  1713. static int getrange(struct mg_str *s, size_t *a, size_t *b) {
  1714. size_t i, numparsed = 0;
  1715. for (i = 0; i + 6 < s->len; i++) {
  1716. struct mg_str k, v = mg_str_n(s->buf + i + 6, s->len - i - 6);
  1717. if (memcmp(&s->buf[i], "bytes=", 6) != 0) continue;
  1718. if (mg_span(v, &k, &v, '-')) {
  1719. if (mg_to_size_t(k, a)) numparsed++;
  1720. if (v.len > 0 && mg_to_size_t(v, b)) numparsed++;
  1721. } else {
  1722. if (mg_to_size_t(v, a)) numparsed++;
  1723. }
  1724. break;
  1725. }
  1726. return (int) numparsed;
  1727. }
  1728. void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
  1729. const char *path,
  1730. const struct mg_http_serve_opts *opts) {
  1731. char etag[64], tmp[MG_PATH_MAX];
  1732. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  1733. struct mg_fd *fd = NULL;
  1734. size_t size = 0;
  1735. time_t mtime = 0;
  1736. struct mg_str *inm = NULL;
  1737. struct mg_str mime = guess_content_type(mg_str(path), opts->mime_types);
  1738. bool gzip = false;
  1739. if (path != NULL) {
  1740. // If a browser sends us "Accept-Encoding: gzip", try to open .gz first
  1741. struct mg_str *ae = mg_http_get_header(hm, "Accept-Encoding");
  1742. if (ae != NULL) {
  1743. char *ae_ = mg_mprintf("%.*s", ae->len, ae->buf);
  1744. if (ae_ != NULL && strstr(ae_, "gzip") != NULL) {
  1745. mg_snprintf(tmp, sizeof(tmp), "%s.gz", path);
  1746. fd = mg_fs_open(fs, tmp, MG_FS_READ);
  1747. if (fd != NULL) gzip = true, path = tmp;
  1748. }
  1749. free(ae_);
  1750. }
  1751. // No luck opening .gz? Open what we've told to open
  1752. if (fd == NULL) fd = mg_fs_open(fs, path, MG_FS_READ);
  1753. }
  1754. // Failed to open, and page404 is configured? Open it, then
  1755. if (fd == NULL && opts->page404 != NULL) {
  1756. fd = mg_fs_open(fs, opts->page404, MG_FS_READ);
  1757. path = opts->page404;
  1758. mime = guess_content_type(mg_str(path), opts->mime_types);
  1759. }
  1760. if (fd == NULL || fs->st(path, &size, &mtime) == 0) {
  1761. mg_http_reply(c, 404, opts->extra_headers, "Not found\n");
  1762. mg_fs_close(fd);
  1763. // NOTE: mg_http_etag() call should go first!
  1764. } else if (mg_http_etag(etag, sizeof(etag), size, mtime) != NULL &&
  1765. (inm = mg_http_get_header(hm, "If-None-Match")) != NULL &&
  1766. mg_strcasecmp(*inm, mg_str(etag)) == 0) {
  1767. mg_fs_close(fd);
  1768. mg_http_reply(c, 304, opts->extra_headers, "");
  1769. } else {
  1770. int n, status = 200;
  1771. char range[100];
  1772. size_t r1 = 0, r2 = 0, cl = size;
  1773. // Handle Range header
  1774. struct mg_str *rh = mg_http_get_header(hm, "Range");
  1775. range[0] = '\0';
  1776. if (rh != NULL && (n = getrange(rh, &r1, &r2)) > 0) {
  1777. // If range is specified like "400-", set second limit to content len
  1778. if (n == 1) r2 = cl - 1;
  1779. if (r1 > r2 || r2 >= cl) {
  1780. status = 416;
  1781. cl = 0;
  1782. mg_snprintf(range, sizeof(range), "Content-Range: bytes */%lld\r\n",
  1783. (int64_t) size);
  1784. } else {
  1785. status = 206;
  1786. cl = r2 - r1 + 1;
  1787. mg_snprintf(range, sizeof(range),
  1788. "Content-Range: bytes %llu-%llu/%llu\r\n", (uint64_t) r1,
  1789. (uint64_t) (r1 + cl - 1), (uint64_t) size);
  1790. fs->sk(fd->fd, r1);
  1791. }
  1792. }
  1793. mg_printf(c,
  1794. "HTTP/1.1 %d %s\r\n"
  1795. "Content-Type: %.*s\r\n"
  1796. "Etag: %s\r\n"
  1797. "Content-Length: %llu\r\n"
  1798. "%s%s%s\r\n",
  1799. status, mg_http_status_code_str(status), (int) mime.len, mime.buf,
  1800. etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
  1801. range, opts->extra_headers ? opts->extra_headers : "");
  1802. if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0) {
  1803. c->is_resp = 0;
  1804. mg_fs_close(fd);
  1805. } else {
  1806. // Track to-be-sent content length at the end of c->data, aligned
  1807. size_t *clp = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  1808. sizeof(size_t) * sizeof(size_t)];
  1809. c->pfn = static_cb;
  1810. c->pfn_data = fd;
  1811. *clp = cl;
  1812. }
  1813. }
  1814. }
  1815. struct printdirentrydata {
  1816. struct mg_connection *c;
  1817. struct mg_http_message *hm;
  1818. const struct mg_http_serve_opts *opts;
  1819. const char *dir;
  1820. };
  1821. #if MG_ENABLE_DIRLIST
  1822. static void printdirentry(const char *name, void *userdata) {
  1823. struct printdirentrydata *d = (struct printdirentrydata *) userdata;
  1824. struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs;
  1825. size_t size = 0;
  1826. time_t t = 0;
  1827. char path[MG_PATH_MAX], sz[40], mod[40];
  1828. int flags, n = 0;
  1829. // MG_DEBUG(("[%s] [%s]", d->dir, name));
  1830. if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >
  1831. sizeof(path)) {
  1832. MG_ERROR(("%s truncated", name));
  1833. } else if ((flags = fs->st(path, &size, &t)) == 0) {
  1834. MG_ERROR(("%lu stat(%s): %d", d->c->id, path, errno));
  1835. } else {
  1836. const char *slash = flags & MG_FS_DIR ? "/" : "";
  1837. if (flags & MG_FS_DIR) {
  1838. mg_snprintf(sz, sizeof(sz), "%s", "[DIR]");
  1839. } else {
  1840. mg_snprintf(sz, sizeof(sz), "%lld", (uint64_t) size);
  1841. }
  1842. #if defined(MG_HTTP_DIRLIST_TIME_FMT)
  1843. {
  1844. char time_str[40];
  1845. struct tm *time_info = localtime(&t);
  1846. strftime(time_str, sizeof time_str, "%Y/%m/%d %H:%M:%S", time_info);
  1847. mg_snprintf(mod, sizeof(mod), "%s", time_str);
  1848. }
  1849. #else
  1850. mg_snprintf(mod, sizeof(mod), "%lu", (unsigned long) t);
  1851. #endif
  1852. n = (int) mg_url_encode(name, strlen(name), path, sizeof(path));
  1853. mg_printf(d->c,
  1854. " <tr><td><a href=\"%.*s%s\">%s%s</a></td>"
  1855. "<td name=%lu>%s</td><td name=%lld>%s</td></tr>\n",
  1856. n, path, slash, name, slash, (unsigned long) t, mod,
  1857. flags & MG_FS_DIR ? (int64_t) -1 : (int64_t) size, sz);
  1858. }
  1859. }
  1860. static void listdir(struct mg_connection *c, struct mg_http_message *hm,
  1861. const struct mg_http_serve_opts *opts, char *dir) {
  1862. const char *sort_js_code =
  1863. "<script>function srt(tb, sc, so, d) {"
  1864. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  1865. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  1866. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  1867. "t1 = a.cells[2].getAttribute('name'), "
  1868. "t2 = b.cells[2].getAttribute('name'); "
  1869. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  1870. "n1 ? parseInt(n2) - parseInt(n1) : "
  1871. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  1872. const char *sort_js_code2 =
  1873. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  1874. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  1875. "};"
  1876. "window.onload = function() {"
  1877. "var tb = document.getElementById('tb');"
  1878. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  1879. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  1880. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  1881. "sc = c; ev.preventDefault();}};"
  1882. "srt(tb, sc, so, true);"
  1883. "}"
  1884. "</script>";
  1885. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  1886. struct printdirentrydata d = {c, hm, opts, dir};
  1887. char tmp[10], buf[MG_PATH_MAX];
  1888. size_t off, n;
  1889. int len = mg_url_decode(hm->uri.buf, hm->uri.len, buf, sizeof(buf), 0);
  1890. struct mg_str uri = len > 0 ? mg_str_n(buf, (size_t) len) : hm->uri;
  1891. mg_printf(c,
  1892. "HTTP/1.1 200 OK\r\n"
  1893. "Content-Type: text/html; charset=utf-8\r\n"
  1894. "%s"
  1895. "Content-Length: \r\n\r\n",
  1896. opts->extra_headers == NULL ? "" : opts->extra_headers);
  1897. off = c->send.len; // Start of body
  1898. mg_printf(c,
  1899. "<!DOCTYPE html><html><head><title>Index of %.*s</title>%s%s"
  1900. "<style>th,td {text-align: left; padding-right: 1em; "
  1901. "font-family: monospace; }</style></head>"
  1902. "<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>"
  1903. "<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
  1904. "<a href=\"#\" rel=\"1\">Modified</a></th>"
  1905. "<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
  1906. "<tr><td colspan=\"3\"><hr></td></tr>"
  1907. "</thead>"
  1908. "<tbody id=\"tb\">\n",
  1909. (int) uri.len, uri.buf, sort_js_code, sort_js_code2, (int) uri.len,
  1910. uri.buf);
  1911. mg_printf(c, "%s",
  1912. " <tr><td><a href=\"..\">..</a></td>"
  1913. "<td name=-1></td><td name=-1>[DIR]</td></tr>\n");
  1914. fs->ls(dir, printdirentry, &d);
  1915. mg_printf(c,
  1916. "</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
  1917. "</table><address>Mongoose v.%s</address></body></html>\n",
  1918. MG_VERSION);
  1919. n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
  1920. if (n > sizeof(tmp)) n = 0;
  1921. memcpy(c->send.buf + off - 12, tmp, n); // Set content length
  1922. c->is_resp = 0; // Mark response end
  1923. }
  1924. #endif
  1925. // Resolve requested file into `path` and return its fs->st() result
  1926. static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
  1927. struct mg_fs *fs, struct mg_str url, struct mg_str dir,
  1928. char *path, size_t path_size) {
  1929. int flags, tmp;
  1930. // Append URI to the root_dir, and sanitize it
  1931. size_t n = mg_snprintf(path, path_size, "%.*s", (int) dir.len, dir.buf);
  1932. if (n + 2 >= path_size) {
  1933. mg_http_reply(c, 400, "", "Exceeded path size");
  1934. return -1;
  1935. }
  1936. path[path_size - 1] = '\0';
  1937. // Terminate root dir with slash
  1938. if (n > 0 && path[n - 1] != '/') path[n++] = '/', path[n] = '\0';
  1939. if (url.len < hm->uri.len) {
  1940. mg_url_decode(hm->uri.buf + url.len, hm->uri.len - url.len, path + n,
  1941. path_size - n, 0);
  1942. }
  1943. path[path_size - 1] = '\0'; // Double-check
  1944. if (!mg_path_is_sane(mg_str_n(path, path_size))) {
  1945. mg_http_reply(c, 400, "", "Invalid path");
  1946. return -1;
  1947. }
  1948. n = strlen(path);
  1949. while (n > 1 && path[n - 1] == '/') path[--n] = 0; // Trim trailing slashes
  1950. flags = mg_strcmp(hm->uri, mg_str("/")) == 0 ? MG_FS_DIR
  1951. : fs->st(path, NULL, NULL);
  1952. MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.buf, path,
  1953. flags));
  1954. if (flags == 0) {
  1955. // Do nothing - let's caller decide
  1956. } else if ((flags & MG_FS_DIR) && hm->uri.len > 0 &&
  1957. hm->uri.buf[hm->uri.len - 1] != '/') {
  1958. mg_printf(c,
  1959. "HTTP/1.1 301 Moved\r\n"
  1960. "Location: %.*s/\r\n"
  1961. "Content-Length: 0\r\n"
  1962. "\r\n",
  1963. (int) hm->uri.len, hm->uri.buf);
  1964. c->is_resp = 0;
  1965. flags = -1;
  1966. } else if (flags & MG_FS_DIR) {
  1967. if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
  1968. (tmp = fs->st(path, NULL, NULL)) != 0) ||
  1969. (mg_snprintf(path + n, path_size - n, "/index.shtml") > 0 &&
  1970. (tmp = fs->st(path, NULL, NULL)) != 0))) {
  1971. flags = tmp;
  1972. } else if ((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX ".gz") >
  1973. 0 &&
  1974. (tmp = fs->st(path, NULL, NULL)) !=
  1975. 0)) { // check for gzipped index
  1976. flags = tmp;
  1977. path[n + 1 + strlen(MG_HTTP_INDEX)] =
  1978. '\0'; // Remove appended .gz in index file name
  1979. } else {
  1980. path[n] = '\0'; // Remove appended index file name
  1981. }
  1982. }
  1983. return flags;
  1984. }
  1985. static int uri_to_path(struct mg_connection *c, struct mg_http_message *hm,
  1986. const struct mg_http_serve_opts *opts, char *path,
  1987. size_t path_size) {
  1988. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  1989. struct mg_str k, v, part, s = mg_str(opts->root_dir), u = {NULL, 0}, p = u;
  1990. while (mg_span(s, &part, &s, ',')) {
  1991. if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
  1992. if (v.len == 0) v = k, k = mg_str("/"), u = k, p = v;
  1993. if (hm->uri.len < k.len) continue;
  1994. if (mg_strcmp(k, mg_str_n(hm->uri.buf, k.len)) != 0) continue;
  1995. u = k, p = v;
  1996. }
  1997. return uri_to_path2(c, hm, fs, u, p, path, path_size);
  1998. }
  1999. void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
  2000. const struct mg_http_serve_opts *opts) {
  2001. char path[MG_PATH_MAX];
  2002. const char *sp = opts->ssi_pattern;
  2003. int flags = uri_to_path(c, hm, opts, path, sizeof(path));
  2004. if (flags < 0) {
  2005. // Do nothing: the response has already been sent by uri_to_path()
  2006. } else if (flags & MG_FS_DIR) {
  2007. #if MG_ENABLE_DIRLIST
  2008. listdir(c, hm, opts, path);
  2009. #else
  2010. mg_http_reply(c, 403, "", "Forbidden\n");
  2011. #endif
  2012. } else if (flags && sp != NULL && mg_match(mg_str(path), mg_str(sp), NULL)) {
  2013. mg_http_serve_ssi(c, opts->root_dir, path);
  2014. } else {
  2015. mg_http_serve_file(c, hm, path, opts);
  2016. }
  2017. }
  2018. static bool mg_is_url_safe(int c) {
  2019. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
  2020. (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~';
  2021. }
  2022. size_t mg_url_encode(const char *s, size_t sl, char *buf, size_t len) {
  2023. size_t i, n = 0;
  2024. for (i = 0; i < sl; i++) {
  2025. int c = *(unsigned char *) &s[i];
  2026. if (n + 4 >= len) return 0;
  2027. if (mg_is_url_safe(c)) {
  2028. buf[n++] = s[i];
  2029. } else {
  2030. mg_snprintf(&buf[n], 4, "%%%M", mg_print_hex, 1, &s[i]);
  2031. n += 3;
  2032. }
  2033. }
  2034. if (len > 0 && n < len - 1) buf[n] = '\0'; // Null-terminate the destination
  2035. if (len > 0) buf[len - 1] = '\0'; // Always.
  2036. return n;
  2037. }
  2038. void mg_http_creds(struct mg_http_message *hm, char *user, size_t userlen,
  2039. char *pass, size_t passlen) {
  2040. struct mg_str *v = mg_http_get_header(hm, "Authorization");
  2041. user[0] = pass[0] = '\0';
  2042. if (v != NULL && v->len > 6 && memcmp(v->buf, "Basic ", 6) == 0) {
  2043. char buf[256];
  2044. size_t n = mg_base64_decode(v->buf + 6, v->len - 6, buf, sizeof(buf));
  2045. const char *p = (const char *) memchr(buf, ':', n > 0 ? n : 0);
  2046. if (p != NULL) {
  2047. mg_snprintf(user, userlen, "%.*s", p - buf, buf);
  2048. mg_snprintf(pass, passlen, "%.*s", n - (size_t) (p - buf) - 1, p + 1);
  2049. }
  2050. } else if (v != NULL && v->len > 7 && memcmp(v->buf, "Bearer ", 7) == 0) {
  2051. mg_snprintf(pass, passlen, "%.*s", (int) v->len - 7, v->buf + 7);
  2052. } else if ((v = mg_http_get_header(hm, "Cookie")) != NULL) {
  2053. struct mg_str t = mg_http_get_header_var(*v, mg_str_n("access_token", 12));
  2054. if (t.len > 0) mg_snprintf(pass, passlen, "%.*s", (int) t.len, t.buf);
  2055. } else {
  2056. mg_http_get_var(&hm->query, "access_token", pass, passlen);
  2057. }
  2058. }
  2059. static struct mg_str stripquotes(struct mg_str s) {
  2060. return s.len > 1 && s.buf[0] == '"' && s.buf[s.len - 1] == '"'
  2061. ? mg_str_n(s.buf + 1, s.len - 2)
  2062. : s;
  2063. }
  2064. struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v) {
  2065. size_t i;
  2066. for (i = 0; v.len > 0 && i + v.len + 2 < s.len; i++) {
  2067. if (s.buf[i + v.len] == '=' && memcmp(&s.buf[i], v.buf, v.len) == 0) {
  2068. const char *p = &s.buf[i + v.len + 1], *b = p, *x = &s.buf[s.len];
  2069. int q = p < x && *p == '"' ? 1 : 0;
  2070. while (p < x &&
  2071. (q ? p == b || *p != '"' : *p != ';' && *p != ' ' && *p != ','))
  2072. p++;
  2073. // MG_INFO(("[%.*s] [%.*s] [%.*s]", (int) s.len, s.buf, (int) v.len,
  2074. // v.buf, (int) (p - b), b));
  2075. return stripquotes(mg_str_n(b, (size_t) (p - b + q)));
  2076. }
  2077. }
  2078. return mg_str_n(NULL, 0);
  2079. }
  2080. long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
  2081. struct mg_fs *fs, const char *dir, size_t max_size) {
  2082. char buf[20] = "0", file[MG_PATH_MAX], path[MG_PATH_MAX];
  2083. long res = 0, offset;
  2084. mg_http_get_var(&hm->query, "offset", buf, sizeof(buf));
  2085. mg_http_get_var(&hm->query, "file", file, sizeof(file));
  2086. offset = strtol(buf, NULL, 0);
  2087. mg_snprintf(path, sizeof(path), "%s%c%s", dir, MG_DIRSEP, file);
  2088. if (hm->body.len == 0) {
  2089. mg_http_reply(c, 200, "", "%ld", res); // Nothing to write
  2090. } else if (file[0] == '\0') {
  2091. mg_http_reply(c, 400, "", "file required");
  2092. res = -1;
  2093. } else if (mg_path_is_sane(mg_str(file)) == false) {
  2094. mg_http_reply(c, 400, "", "%s: invalid file", file);
  2095. res = -2;
  2096. } else if (offset < 0) {
  2097. mg_http_reply(c, 400, "", "offset required");
  2098. res = -3;
  2099. } else if ((size_t) offset + hm->body.len > max_size) {
  2100. mg_http_reply(c, 400, "", "%s: over max size of %lu", path,
  2101. (unsigned long) max_size);
  2102. res = -4;
  2103. } else {
  2104. struct mg_fd *fd;
  2105. size_t current_size = 0;
  2106. MG_DEBUG(("%s -> %lu bytes @ %ld", path, hm->body.len, offset));
  2107. if (offset == 0) fs->rm(path); // If offset if 0, truncate file
  2108. fs->st(path, &current_size, NULL);
  2109. if (offset > 0 && current_size != (size_t) offset) {
  2110. mg_http_reply(c, 400, "", "%s: offset mismatch", path);
  2111. res = -5;
  2112. } else if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
  2113. mg_http_reply(c, 400, "", "open(%s): %d", path, errno);
  2114. res = -6;
  2115. } else {
  2116. res = offset + (long) fs->wr(fd->fd, hm->body.buf, hm->body.len);
  2117. mg_fs_close(fd);
  2118. mg_http_reply(c, 200, "", "%ld", res);
  2119. }
  2120. }
  2121. return res;
  2122. }
  2123. int mg_http_status(const struct mg_http_message *hm) {
  2124. return atoi(hm->uri.buf);
  2125. }
  2126. static bool is_hex_digit(int c) {
  2127. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  2128. (c >= 'A' && c <= 'F');
  2129. }
  2130. static int skip_chunk(const char *buf, int len, int *pl, int *dl) {
  2131. int i = 0, n = 0;
  2132. if (len < 3) return 0;
  2133. while (i < len && is_hex_digit(buf[i])) i++;
  2134. if (i == 0) return -1; // Error, no length specified
  2135. if (i > (int) sizeof(int) * 2) return -1; // Chunk length is too big
  2136. if (len < i + 1 || buf[i] != '\r' || buf[i + 1] != '\n') return -1; // Error
  2137. if (mg_str_to_num(mg_str_n(buf, (size_t) i), 16, &n, sizeof(int)) == false)
  2138. return -1; // Decode chunk length, overflow
  2139. if (n < 0) return -1; // Error. TODO(): some checks now redundant
  2140. if (n > len - i - 4) return 0; // Chunk not yet fully buffered
  2141. if (buf[i + n + 2] != '\r' || buf[i + n + 3] != '\n') return -1; // Error
  2142. *pl = i + 2, *dl = n;
  2143. return i + 2 + n + 2;
  2144. }
  2145. static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
  2146. if (ev == MG_EV_READ || ev == MG_EV_CLOSE ||
  2147. (ev == MG_EV_POLL && c->is_accepted && !c->is_draining &&
  2148. c->recv.len > 0)) { // see #2796
  2149. struct mg_http_message hm;
  2150. size_t ofs = 0; // Parsing offset
  2151. while (c->is_resp == 0 && ofs < c->recv.len) {
  2152. const char *buf = (char *) c->recv.buf + ofs;
  2153. int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
  2154. struct mg_str *te; // Transfer - encoding header
  2155. bool is_chunked = false;
  2156. size_t old_len = c->recv.len;
  2157. if (n < 0) {
  2158. // We don't use mg_error() here, to avoid closing pipelined requests
  2159. // prematurely, see #2592
  2160. MG_ERROR(("HTTP parse, %lu bytes", c->recv.len));
  2161. c->is_draining = 1;
  2162. mg_hexdump(buf, c->recv.len - ofs > 16 ? 16 : c->recv.len - ofs);
  2163. c->recv.len = 0;
  2164. return;
  2165. }
  2166. if (n == 0) break; // Request is not buffered yet
  2167. mg_call(c, MG_EV_HTTP_HDRS, &hm); // Got all HTTP headers
  2168. if (c->recv.len != old_len) {
  2169. // User manipulated received data. Wash our hands
  2170. MG_DEBUG(("%lu detaching HTTP handler", c->id));
  2171. c->pfn = NULL;
  2172. return;
  2173. }
  2174. if (ev == MG_EV_CLOSE) { // If client did not set Content-Length
  2175. hm.message.len = c->recv.len - ofs; // and closes now, deliver MSG
  2176. hm.body.len = hm.message.len - (size_t) (hm.body.buf - hm.message.buf);
  2177. }
  2178. if ((te = mg_http_get_header(&hm, "Transfer-Encoding")) != NULL) {
  2179. if (mg_strcasecmp(*te, mg_str("chunked")) == 0) {
  2180. is_chunked = true;
  2181. } else {
  2182. mg_error(c, "Invalid Transfer-Encoding"); // See #2460
  2183. return;
  2184. }
  2185. } else if (mg_http_get_header(&hm, "Content-length") == NULL) {
  2186. // #2593: HTTP packets must contain either Transfer-Encoding or
  2187. // Content-length
  2188. bool is_response = mg_ncasecmp(hm.method.buf, "HTTP/", 5) == 0;
  2189. bool require_content_len = false;
  2190. if (!is_response && (mg_strcasecmp(hm.method, mg_str("POST")) == 0 ||
  2191. mg_strcasecmp(hm.method, mg_str("PUT")) == 0)) {
  2192. // POST and PUT should include an entity body. Therefore, they should
  2193. // contain a Content-length header. Other requests can also contain a
  2194. // body, but their content has no defined semantics (RFC 7231)
  2195. require_content_len = true;
  2196. ofs += (size_t) n; // this request has been processed
  2197. } else if (is_response) {
  2198. // HTTP spec 7.2 Entity body: All other responses must include a body
  2199. // or Content-Length header field defined with a value of 0.
  2200. int status = mg_http_status(&hm);
  2201. require_content_len = status >= 200 && status != 204 && status != 304;
  2202. }
  2203. if (require_content_len) {
  2204. if (!c->is_client) mg_http_reply(c, 411, "", "");
  2205. MG_ERROR(("Content length missing from %s", is_response ? "response" : "request"));
  2206. }
  2207. }
  2208. if (is_chunked) {
  2209. // For chunked data, strip off prefixes and suffixes from chunks
  2210. // and relocate them right after the headers, then report a message
  2211. char *s = (char *) c->recv.buf + ofs + n;
  2212. int o = 0, pl, dl, cl, len = (int) (c->recv.len - ofs - (size_t) n);
  2213. // Find zero-length chunk (the end of the body)
  2214. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0 && dl) o += cl;
  2215. if (cl == 0) break; // No zero-len chunk, buffer more data
  2216. if (cl < 0) {
  2217. mg_error(c, "Invalid chunk");
  2218. break;
  2219. }
  2220. // Zero chunk found. Second pass: strip + relocate
  2221. o = 0, hm.body.len = 0, hm.message.len = (size_t) n;
  2222. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0) {
  2223. memmove(s + hm.body.len, s + o + pl, (size_t) dl);
  2224. o += cl, hm.body.len += (size_t) dl, hm.message.len += (size_t) dl;
  2225. if (dl == 0) break;
  2226. }
  2227. ofs += (size_t) (n + o);
  2228. } else { // Normal, non-chunked data
  2229. size_t len = c->recv.len - ofs - (size_t) n;
  2230. if (hm.body.len > len) break; // Buffer more data
  2231. ofs += (size_t) n + hm.body.len;
  2232. }
  2233. if (c->is_accepted) c->is_resp = 1; // Start generating response
  2234. mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp
  2235. if (c->is_accepted && !c->is_resp) {
  2236. struct mg_str *cc = mg_http_get_header(&hm, "Connection");
  2237. if (cc != NULL && mg_strcasecmp(*cc, mg_str("close")) == 0) {
  2238. c->is_draining = 1; // honor "Connection: close"
  2239. break;
  2240. }
  2241. }
  2242. }
  2243. if (ofs > 0) mg_iobuf_del(&c->recv, 0, ofs); // Delete processed data
  2244. }
  2245. (void) ev_data;
  2246. }
  2247. static void mg_hfn(struct mg_connection *c, int ev, void *ev_data) {
  2248. if (ev == MG_EV_HTTP_MSG) {
  2249. struct mg_http_message *hm = (struct mg_http_message *) ev_data;
  2250. if (mg_match(hm->uri, mg_str("/quit"), NULL)) {
  2251. mg_http_reply(c, 200, "", "ok\n");
  2252. c->is_draining = 1;
  2253. c->data[0] = 'X';
  2254. } else if (mg_match(hm->uri, mg_str("/debug"), NULL)) {
  2255. int level = (int) mg_json_get_long(hm->body, "$.level", MG_LL_DEBUG);
  2256. mg_log_set(level);
  2257. mg_http_reply(c, 200, "", "Debug level set to %d\n", level);
  2258. } else {
  2259. mg_http_reply(c, 200, "", "hi\n");
  2260. }
  2261. } else if (ev == MG_EV_CLOSE) {
  2262. if (c->data[0] == 'X') *(bool *) c->fn_data = true;
  2263. }
  2264. }
  2265. void mg_hello(const char *url) {
  2266. struct mg_mgr mgr;
  2267. bool done = false;
  2268. mg_mgr_init(&mgr);
  2269. if (mg_http_listen(&mgr, url, mg_hfn, &done) == NULL) done = true;
  2270. while (done == false) mg_mgr_poll(&mgr, 100);
  2271. mg_mgr_free(&mgr);
  2272. }
  2273. struct mg_connection *mg_http_connect(struct mg_mgr *mgr, const char *url,
  2274. mg_event_handler_t fn, void *fn_data) {
  2275. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  2276. if (c != NULL) c->pfn = http_cb;
  2277. return c;
  2278. }
  2279. struct mg_connection *mg_http_listen(struct mg_mgr *mgr, const char *url,
  2280. mg_event_handler_t fn, void *fn_data) {
  2281. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  2282. if (c != NULL) c->pfn = http_cb;
  2283. return c;
  2284. }
  2285. #ifdef MG_ENABLE_LINES
  2286. #line 1 "src/iobuf.c"
  2287. #endif
  2288. static size_t roundup(size_t size, size_t align) {
  2289. return align == 0 ? size : (size + align - 1) / align * align;
  2290. }
  2291. int mg_iobuf_resize(struct mg_iobuf *io, size_t new_size) {
  2292. int ok = 1;
  2293. new_size = roundup(new_size, io->align);
  2294. if (new_size == 0) {
  2295. mg_bzero(io->buf, io->size);
  2296. free(io->buf);
  2297. io->buf = NULL;
  2298. io->len = io->size = 0;
  2299. } else if (new_size != io->size) {
  2300. // NOTE(lsm): do not use realloc here. Use calloc/free only, to ease the
  2301. // porting to some obscure platforms like FreeRTOS
  2302. void *p = calloc(1, new_size);
  2303. if (p != NULL) {
  2304. size_t len = new_size < io->len ? new_size : io->len;
  2305. if (len > 0 && io->buf != NULL) memmove(p, io->buf, len);
  2306. mg_bzero(io->buf, io->size);
  2307. free(io->buf);
  2308. io->buf = (unsigned char *) p;
  2309. io->size = new_size;
  2310. } else {
  2311. ok = 0;
  2312. MG_ERROR(("%lld->%lld", (uint64_t) io->size, (uint64_t) new_size));
  2313. }
  2314. }
  2315. return ok;
  2316. }
  2317. int mg_iobuf_init(struct mg_iobuf *io, size_t size, size_t align) {
  2318. io->buf = NULL;
  2319. io->align = align;
  2320. io->size = io->len = 0;
  2321. return mg_iobuf_resize(io, size);
  2322. }
  2323. size_t mg_iobuf_add(struct mg_iobuf *io, size_t ofs, const void *buf,
  2324. size_t len) {
  2325. size_t new_size = roundup(io->len + len, io->align);
  2326. mg_iobuf_resize(io, new_size); // Attempt to resize
  2327. if (new_size != io->size) len = 0; // Resize failure, append nothing
  2328. if (ofs < io->len) memmove(io->buf + ofs + len, io->buf + ofs, io->len - ofs);
  2329. if (buf != NULL) memmove(io->buf + ofs, buf, len);
  2330. if (ofs > io->len) io->len += ofs - io->len;
  2331. io->len += len;
  2332. return len;
  2333. }
  2334. size_t mg_iobuf_del(struct mg_iobuf *io, size_t ofs, size_t len) {
  2335. if (ofs > io->len) ofs = io->len;
  2336. if (ofs + len > io->len) len = io->len - ofs;
  2337. if (io->buf) memmove(io->buf + ofs, io->buf + ofs + len, io->len - ofs - len);
  2338. if (io->buf) mg_bzero(io->buf + io->len - len, len);
  2339. io->len -= len;
  2340. return len;
  2341. }
  2342. void mg_iobuf_free(struct mg_iobuf *io) {
  2343. mg_iobuf_resize(io, 0);
  2344. }
  2345. #ifdef MG_ENABLE_LINES
  2346. #line 1 "src/json.c"
  2347. #endif
  2348. static const char *escapeseq(int esc) {
  2349. return esc ? "\b\f\n\r\t\\\"" : "bfnrt\\\"";
  2350. }
  2351. static char json_esc(int c, int esc) {
  2352. const char *p, *esc1 = escapeseq(esc), *esc2 = escapeseq(!esc);
  2353. for (p = esc1; *p != '\0'; p++) {
  2354. if (*p == c) return esc2[p - esc1];
  2355. }
  2356. return 0;
  2357. }
  2358. static int mg_pass_string(const char *s, int len) {
  2359. int i;
  2360. for (i = 0; i < len; i++) {
  2361. if (s[i] == '\\' && i + 1 < len && json_esc(s[i + 1], 1)) {
  2362. i++;
  2363. } else if (s[i] == '\0') {
  2364. return MG_JSON_INVALID;
  2365. } else if (s[i] == '"') {
  2366. return i;
  2367. }
  2368. }
  2369. return MG_JSON_INVALID;
  2370. }
  2371. static double mg_atod(const char *p, int len, int *numlen) {
  2372. double d = 0.0;
  2373. int i = 0, sign = 1;
  2374. // Sign
  2375. if (i < len && *p == '-') {
  2376. sign = -1, i++;
  2377. } else if (i < len && *p == '+') {
  2378. i++;
  2379. }
  2380. // Decimal
  2381. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  2382. d *= 10.0;
  2383. d += p[i] - '0';
  2384. }
  2385. d *= sign;
  2386. // Fractional
  2387. if (i < len && p[i] == '.') {
  2388. double frac = 0.0, base = 0.1;
  2389. i++;
  2390. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  2391. frac += base * (p[i] - '0');
  2392. base /= 10.0;
  2393. }
  2394. d += frac * sign;
  2395. }
  2396. // Exponential
  2397. if (i < len && (p[i] == 'e' || p[i] == 'E')) {
  2398. int j, exp = 0, minus = 0;
  2399. i++;
  2400. if (i < len && p[i] == '-') minus = 1, i++;
  2401. if (i < len && p[i] == '+') i++;
  2402. while (i < len && p[i] >= '0' && p[i] <= '9' && exp < 308)
  2403. exp = exp * 10 + (p[i++] - '0');
  2404. if (minus) exp = -exp;
  2405. for (j = 0; j < exp; j++) d *= 10.0;
  2406. for (j = 0; j < -exp; j++) d /= 10.0;
  2407. }
  2408. if (numlen != NULL) *numlen = i;
  2409. return d;
  2410. }
  2411. // Iterate over object or array elements
  2412. size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key,
  2413. struct mg_str *val) {
  2414. if (ofs >= obj.len) {
  2415. ofs = 0; // Out of boundaries, stop scanning
  2416. } else if (obj.len < 2 || (*obj.buf != '{' && *obj.buf != '[')) {
  2417. ofs = 0; // Not an array or object, stop
  2418. } else {
  2419. struct mg_str sub = mg_str_n(obj.buf + ofs, obj.len - ofs);
  2420. if (ofs == 0) ofs++, sub.buf++, sub.len--;
  2421. if (*obj.buf == '[') { // Iterate over an array
  2422. int n = 0, o = mg_json_get(sub, "$", &n);
  2423. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2424. ofs = 0; // Error parsing key, stop scanning
  2425. } else {
  2426. if (key) *key = mg_str_n(NULL, 0);
  2427. if (val) *val = mg_str_n(sub.buf + o, (size_t) n);
  2428. ofs = (size_t) (&sub.buf[o + n] - obj.buf);
  2429. }
  2430. } else { // Iterate over an object
  2431. int n = 0, o = mg_json_get(sub, "$", &n);
  2432. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2433. ofs = 0; // Error parsing key, stop scanning
  2434. } else {
  2435. if (key) *key = mg_str_n(sub.buf + o, (size_t) n);
  2436. sub.buf += o + n, sub.len -= (size_t) (o + n);
  2437. while (sub.len > 0 && *sub.buf != ':') sub.len--, sub.buf++;
  2438. if (sub.len > 0 && *sub.buf == ':') sub.len--, sub.buf++;
  2439. n = 0, o = mg_json_get(sub, "$", &n);
  2440. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2441. ofs = 0; // Error parsing value, stop scanning
  2442. } else {
  2443. if (val) *val = mg_str_n(sub.buf + o, (size_t) n);
  2444. ofs = (size_t) (&sub.buf[o + n] - obj.buf);
  2445. }
  2446. }
  2447. }
  2448. // MG_INFO(("SUB ofs %u %.*s", ofs, sub.len, sub.buf));
  2449. while (ofs && ofs < obj.len &&
  2450. (obj.buf[ofs] == ' ' || obj.buf[ofs] == '\t' ||
  2451. obj.buf[ofs] == '\n' || obj.buf[ofs] == '\r')) {
  2452. ofs++;
  2453. }
  2454. if (ofs && ofs < obj.len && obj.buf[ofs] == ',') ofs++;
  2455. if (ofs > obj.len) ofs = 0;
  2456. }
  2457. return ofs;
  2458. }
  2459. int mg_json_get(struct mg_str json, const char *path, int *toklen) {
  2460. const char *s = json.buf;
  2461. int len = (int) json.len;
  2462. enum { S_VALUE, S_KEY, S_COLON, S_COMMA_OR_EOO } expecting = S_VALUE;
  2463. unsigned char nesting[MG_JSON_MAX_DEPTH];
  2464. int i = 0; // Current offset in `s`
  2465. int j = 0; // Offset in `s` we're looking for (return value)
  2466. int depth = 0; // Current depth (nesting level)
  2467. int ed = 0; // Expected depth
  2468. int pos = 1; // Current position in `path`
  2469. int ci = -1, ei = -1; // Current and expected index in array
  2470. if (toklen) *toklen = 0;
  2471. if (path[0] != '$') return MG_JSON_INVALID;
  2472. #define MG_CHECKRET(x) \
  2473. do { \
  2474. if (depth == ed && path[pos] == '\0' && ci == ei) { \
  2475. if (toklen) *toklen = i - j + 1; \
  2476. return j; \
  2477. } \
  2478. } while (0)
  2479. // In the ascii table, the distance between `[` and `]` is 2.
  2480. // Ditto for `{` and `}`. Hence +2 in the code below.
  2481. #define MG_EOO(x) \
  2482. do { \
  2483. if (depth == ed && ci != ei) return MG_JSON_NOT_FOUND; \
  2484. if (c != nesting[depth - 1] + 2) return MG_JSON_INVALID; \
  2485. depth--; \
  2486. MG_CHECKRET(x); \
  2487. } while (0)
  2488. for (i = 0; i < len; i++) {
  2489. unsigned char c = ((unsigned char *) s)[i];
  2490. if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
  2491. switch (expecting) {
  2492. case S_VALUE:
  2493. // p("V %s [%.*s] %d %d %d %d\n", path, pos, path, depth, ed, ci, ei);
  2494. if (depth == ed) j = i;
  2495. if (c == '{') {
  2496. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  2497. if (depth == ed && path[pos] == '.' && ci == ei) {
  2498. // If we start the object, reset array indices
  2499. ed++, pos++, ci = ei = -1;
  2500. }
  2501. nesting[depth++] = c;
  2502. expecting = S_KEY;
  2503. break;
  2504. } else if (c == '[') {
  2505. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  2506. if (depth == ed && path[pos] == '[' && ei == ci) {
  2507. ed++, pos++, ci = 0;
  2508. for (ei = 0; path[pos] != ']' && path[pos] != '\0'; pos++) {
  2509. ei *= 10;
  2510. ei += path[pos] - '0';
  2511. }
  2512. if (path[pos] != 0) pos++;
  2513. }
  2514. nesting[depth++] = c;
  2515. break;
  2516. } else if (c == ']' && depth > 0) { // Empty array
  2517. MG_EOO(']');
  2518. } else if (c == 't' && i + 3 < len && memcmp(&s[i], "true", 4) == 0) {
  2519. i += 3;
  2520. } else if (c == 'n' && i + 3 < len && memcmp(&s[i], "null", 4) == 0) {
  2521. i += 3;
  2522. } else if (c == 'f' && i + 4 < len && memcmp(&s[i], "false", 5) == 0) {
  2523. i += 4;
  2524. } else if (c == '-' || ((c >= '0' && c <= '9'))) {
  2525. int numlen = 0;
  2526. mg_atod(&s[i], len - i, &numlen);
  2527. i += numlen - 1;
  2528. } else if (c == '"') {
  2529. int n = mg_pass_string(&s[i + 1], len - i - 1);
  2530. if (n < 0) return n;
  2531. i += n + 1;
  2532. } else {
  2533. return MG_JSON_INVALID;
  2534. }
  2535. MG_CHECKRET('V');
  2536. if (depth == ed && ei >= 0) ci++;
  2537. expecting = S_COMMA_OR_EOO;
  2538. break;
  2539. case S_KEY:
  2540. if (c == '"') {
  2541. int n = mg_pass_string(&s[i + 1], len - i - 1);
  2542. if (n < 0) return n;
  2543. if (i + 1 + n >= len) return MG_JSON_NOT_FOUND;
  2544. if (depth < ed) return MG_JSON_NOT_FOUND;
  2545. if (depth == ed && path[pos - 1] != '.') return MG_JSON_NOT_FOUND;
  2546. // printf("K %s [%.*s] [%.*s] %d %d %d %d %d\n", path, pos, path, n,
  2547. // &s[i + 1], n, depth, ed, ci, ei);
  2548. // NOTE(cpq): in the check sequence below is important.
  2549. // strncmp() must go first: it fails fast if the remaining length
  2550. // of the path is smaller than `n`.
  2551. if (depth == ed && path[pos - 1] == '.' &&
  2552. strncmp(&s[i + 1], &path[pos], (size_t) n) == 0 &&
  2553. (path[pos + n] == '\0' || path[pos + n] == '.' ||
  2554. path[pos + n] == '[')) {
  2555. pos += n;
  2556. }
  2557. i += n + 1;
  2558. expecting = S_COLON;
  2559. } else if (c == '}') { // Empty object
  2560. MG_EOO('}');
  2561. expecting = S_COMMA_OR_EOO;
  2562. if (depth == ed && ei >= 0) ci++;
  2563. } else {
  2564. return MG_JSON_INVALID;
  2565. }
  2566. break;
  2567. case S_COLON:
  2568. if (c == ':') {
  2569. expecting = S_VALUE;
  2570. } else {
  2571. return MG_JSON_INVALID;
  2572. }
  2573. break;
  2574. case S_COMMA_OR_EOO:
  2575. if (depth <= 0) {
  2576. return MG_JSON_INVALID;
  2577. } else if (c == ',') {
  2578. expecting = (nesting[depth - 1] == '{') ? S_KEY : S_VALUE;
  2579. } else if (c == ']' || c == '}') {
  2580. if (depth == ed && c == '}' && path[pos - 1] == '.')
  2581. return MG_JSON_NOT_FOUND;
  2582. if (depth == ed && c == ']' && path[pos - 1] == ',')
  2583. return MG_JSON_NOT_FOUND;
  2584. MG_EOO('O');
  2585. if (depth == ed && ei >= 0) ci++;
  2586. } else {
  2587. return MG_JSON_INVALID;
  2588. }
  2589. break;
  2590. }
  2591. }
  2592. return MG_JSON_NOT_FOUND;
  2593. }
  2594. struct mg_str mg_json_get_tok(struct mg_str json, const char *path) {
  2595. int len = 0, ofs = mg_json_get(json, path, &len);
  2596. return mg_str_n(ofs < 0 ? NULL : json.buf + ofs,
  2597. (size_t) (len < 0 ? 0 : len));
  2598. }
  2599. bool mg_json_get_num(struct mg_str json, const char *path, double *v) {
  2600. int n, toklen, found = 0;
  2601. if ((n = mg_json_get(json, path, &toklen)) >= 0 &&
  2602. (json.buf[n] == '-' || (json.buf[n] >= '0' && json.buf[n] <= '9'))) {
  2603. if (v != NULL) *v = mg_atod(json.buf + n, toklen, NULL);
  2604. found = 1;
  2605. }
  2606. return found;
  2607. }
  2608. bool mg_json_get_bool(struct mg_str json, const char *path, bool *v) {
  2609. int found = 0, off = mg_json_get(json, path, NULL);
  2610. if (off >= 0 && (json.buf[off] == 't' || json.buf[off] == 'f')) {
  2611. if (v != NULL) *v = json.buf[off] == 't';
  2612. found = 1;
  2613. }
  2614. return found;
  2615. }
  2616. bool mg_json_unescape(struct mg_str s, char *to, size_t n) {
  2617. size_t i, j;
  2618. for (i = 0, j = 0; i < s.len && j < n; i++, j++) {
  2619. if (s.buf[i] == '\\' && i + 5 < s.len && s.buf[i + 1] == 'u') {
  2620. // \uXXXX escape. We process simple one-byte chars \u00xx within ASCII
  2621. // range. More complex chars would require dragging in a UTF8 library,
  2622. // which is too much for us
  2623. if (mg_str_to_num(mg_str_n(s.buf + i + 2, 4), 16, &to[j],
  2624. sizeof(uint8_t)) == false)
  2625. return false;
  2626. i += 5;
  2627. } else if (s.buf[i] == '\\' && i + 1 < s.len) {
  2628. char c = json_esc(s.buf[i + 1], 0);
  2629. if (c == 0) return false;
  2630. to[j] = c;
  2631. i++;
  2632. } else {
  2633. to[j] = s.buf[i];
  2634. }
  2635. }
  2636. if (j >= n) return false;
  2637. if (n > 0) to[j] = '\0';
  2638. return true;
  2639. }
  2640. char *mg_json_get_str(struct mg_str json, const char *path) {
  2641. char *result = NULL;
  2642. int len = 0, off = mg_json_get(json, path, &len);
  2643. if (off >= 0 && len > 1 && json.buf[off] == '"') {
  2644. if ((result = (char *) calloc(1, (size_t) len)) != NULL &&
  2645. !mg_json_unescape(mg_str_n(json.buf + off + 1, (size_t) (len - 2)),
  2646. result, (size_t) len)) {
  2647. free(result);
  2648. result = NULL;
  2649. }
  2650. }
  2651. return result;
  2652. }
  2653. char *mg_json_get_b64(struct mg_str json, const char *path, int *slen) {
  2654. char *result = NULL;
  2655. int len = 0, off = mg_json_get(json, path, &len);
  2656. if (off >= 0 && json.buf[off] == '"' && len > 1 &&
  2657. (result = (char *) calloc(1, (size_t) len)) != NULL) {
  2658. size_t k = mg_base64_decode(json.buf + off + 1, (size_t) (len - 2), result,
  2659. (size_t) len);
  2660. if (slen != NULL) *slen = (int) k;
  2661. }
  2662. return result;
  2663. }
  2664. char *mg_json_get_hex(struct mg_str json, const char *path, int *slen) {
  2665. char *result = NULL;
  2666. int len = 0, off = mg_json_get(json, path, &len);
  2667. if (off >= 0 && json.buf[off] == '"' && len > 1 &&
  2668. (result = (char *) calloc(1, (size_t) len / 2)) != NULL) {
  2669. int i;
  2670. for (i = 0; i < len - 2; i += 2) {
  2671. mg_str_to_num(mg_str_n(json.buf + off + 1 + i, 2), 16, &result[i >> 1],
  2672. sizeof(uint8_t));
  2673. }
  2674. result[len / 2 - 1] = '\0';
  2675. if (slen != NULL) *slen = len / 2 - 1;
  2676. }
  2677. return result;
  2678. }
  2679. long mg_json_get_long(struct mg_str json, const char *path, long dflt) {
  2680. double dv;
  2681. long result = dflt;
  2682. if (mg_json_get_num(json, path, &dv)) result = (long) dv;
  2683. return result;
  2684. }
  2685. #ifdef MG_ENABLE_LINES
  2686. #line 1 "src/log.c"
  2687. #endif
  2688. int mg_log_level = MG_LL_INFO;
  2689. static mg_pfn_t s_log_func = mg_pfn_stdout;
  2690. static void *s_log_func_param = NULL;
  2691. void mg_log_set_fn(mg_pfn_t fn, void *param) {
  2692. s_log_func = fn;
  2693. s_log_func_param = param;
  2694. }
  2695. static void logc(unsigned char c) {
  2696. s_log_func((char) c, s_log_func_param);
  2697. }
  2698. static void logs(const char *buf, size_t len) {
  2699. size_t i;
  2700. for (i = 0; i < len; i++) logc(((unsigned char *) buf)[i]);
  2701. }
  2702. #if MG_ENABLE_CUSTOM_LOG
  2703. // Let user define their own mg_log_prefix() and mg_log()
  2704. #else
  2705. void mg_log_prefix(int level, const char *file, int line, const char *fname) {
  2706. const char *p = strrchr(file, '/');
  2707. char buf[41];
  2708. size_t n;
  2709. if (p == NULL) p = strrchr(file, '\\');
  2710. n = mg_snprintf(buf, sizeof(buf), "%-6llx %d %s:%d:%s", mg_millis(), level,
  2711. p == NULL ? file : p + 1, line, fname);
  2712. if (n > sizeof(buf) - 2) n = sizeof(buf) - 2;
  2713. while (n < sizeof(buf)) buf[n++] = ' ';
  2714. logs(buf, n - 1);
  2715. }
  2716. void mg_log(const char *fmt, ...) {
  2717. va_list ap;
  2718. va_start(ap, fmt);
  2719. mg_vxprintf(s_log_func, s_log_func_param, fmt, &ap);
  2720. va_end(ap);
  2721. logs("\r\n", 2);
  2722. }
  2723. #endif
  2724. static unsigned char nibble(unsigned c) {
  2725. return (unsigned char) (c < 10 ? c + '0' : c + 'W');
  2726. }
  2727. #define ISPRINT(x) ((x) >= ' ' && (x) <= '~')
  2728. void mg_hexdump(const void *buf, size_t len) {
  2729. const unsigned char *p = (const unsigned char *) buf;
  2730. unsigned char ascii[16], alen = 0;
  2731. size_t i;
  2732. for (i = 0; i < len; i++) {
  2733. if ((i % 16) == 0) {
  2734. // Print buffered ascii chars
  2735. if (i > 0) logs(" ", 2), logs((char *) ascii, 16), logc('\n'), alen = 0;
  2736. // Print hex address, then \t
  2737. logc(nibble((i >> 12) & 15)), logc(nibble((i >> 8) & 15)),
  2738. logc(nibble((i >> 4) & 15)), logc('0'), logs(" ", 3);
  2739. }
  2740. logc(nibble(p[i] >> 4)), logc(nibble(p[i] & 15)); // Two nibbles, e.g. c5
  2741. logc(' '); // Space after hex number
  2742. ascii[alen++] = ISPRINT(p[i]) ? p[i] : '.'; // Add to the ascii buf
  2743. }
  2744. while (alen < 16) logs(" ", 3), ascii[alen++] = ' ';
  2745. logs(" ", 2), logs((char *) ascii, 16), logc('\n');
  2746. }
  2747. #ifdef MG_ENABLE_LINES
  2748. #line 1 "src/md5.c"
  2749. #endif
  2750. // This code implements the MD5 message-digest algorithm.
  2751. // The algorithm is due to Ron Rivest. This code was
  2752. // written by Colin Plumb in 1993, no copyright is claimed.
  2753. // This code is in the public domain; do with it what you wish.
  2754. //
  2755. // Equivalent code is available from RSA Data Security, Inc.
  2756. // This code has been tested against that, and is equivalent,
  2757. // except that you don't need to include two pages of legalese
  2758. // with every copy.
  2759. //
  2760. // To compute the message digest of a chunk of bytes, declare an
  2761. // MD5Context structure, pass it to MD5Init, call MD5Update as
  2762. // needed on buffers full of bytes, and then call MD5Final, which
  2763. // will fill a supplied 16-byte array with the digest.
  2764. #if defined(MG_ENABLE_MD5) && MG_ENABLE_MD5
  2765. static void mg_byte_reverse(unsigned char *buf, unsigned longs) {
  2766. if (MG_BIG_ENDIAN) {
  2767. do {
  2768. uint32_t t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  2769. ((unsigned) buf[1] << 8 | buf[0]);
  2770. *(uint32_t *) buf = t;
  2771. buf += 4;
  2772. } while (--longs);
  2773. } else {
  2774. (void) buf, (void) longs; // Little endian. Do nothing
  2775. }
  2776. }
  2777. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  2778. #define F2(x, y, z) F1(z, x, y)
  2779. #define F3(x, y, z) (x ^ y ^ z)
  2780. #define F4(x, y, z) (y ^ (x | ~z))
  2781. #define MD5STEP(f, w, x, y, z, data, s) \
  2782. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  2783. /*
  2784. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  2785. * initialization constants.
  2786. */
  2787. void mg_md5_init(mg_md5_ctx *ctx) {
  2788. ctx->buf[0] = 0x67452301;
  2789. ctx->buf[1] = 0xefcdab89;
  2790. ctx->buf[2] = 0x98badcfe;
  2791. ctx->buf[3] = 0x10325476;
  2792. ctx->bits[0] = 0;
  2793. ctx->bits[1] = 0;
  2794. }
  2795. static void mg_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
  2796. uint32_t a, b, c, d;
  2797. a = buf[0];
  2798. b = buf[1];
  2799. c = buf[2];
  2800. d = buf[3];
  2801. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  2802. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  2803. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  2804. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  2805. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  2806. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  2807. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  2808. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  2809. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  2810. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  2811. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  2812. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  2813. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  2814. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  2815. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  2816. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  2817. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  2818. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  2819. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  2820. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  2821. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  2822. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  2823. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  2824. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  2825. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  2826. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  2827. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  2828. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  2829. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  2830. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  2831. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  2832. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  2833. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  2834. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  2835. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  2836. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  2837. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  2838. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  2839. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  2840. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  2841. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  2842. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  2843. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  2844. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  2845. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  2846. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  2847. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  2848. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  2849. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  2850. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  2851. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  2852. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  2853. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  2854. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  2855. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  2856. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  2857. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  2858. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  2859. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  2860. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  2861. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  2862. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  2863. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  2864. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  2865. buf[0] += a;
  2866. buf[1] += b;
  2867. buf[2] += c;
  2868. buf[3] += d;
  2869. }
  2870. void mg_md5_update(mg_md5_ctx *ctx, const unsigned char *buf, size_t len) {
  2871. uint32_t t;
  2872. t = ctx->bits[0];
  2873. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  2874. ctx->bits[1] += (uint32_t) len >> 29;
  2875. t = (t >> 3) & 0x3f;
  2876. if (t) {
  2877. unsigned char *p = (unsigned char *) ctx->in + t;
  2878. t = 64 - t;
  2879. if (len < t) {
  2880. memcpy(p, buf, len);
  2881. return;
  2882. }
  2883. memcpy(p, buf, t);
  2884. mg_byte_reverse(ctx->in, 16);
  2885. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  2886. buf += t;
  2887. len -= t;
  2888. }
  2889. while (len >= 64) {
  2890. memcpy(ctx->in, buf, 64);
  2891. mg_byte_reverse(ctx->in, 16);
  2892. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  2893. buf += 64;
  2894. len -= 64;
  2895. }
  2896. memcpy(ctx->in, buf, len);
  2897. }
  2898. void mg_md5_final(mg_md5_ctx *ctx, unsigned char digest[16]) {
  2899. unsigned count;
  2900. unsigned char *p;
  2901. uint32_t *a;
  2902. count = (ctx->bits[0] >> 3) & 0x3F;
  2903. p = ctx->in + count;
  2904. *p++ = 0x80;
  2905. count = 64 - 1 - count;
  2906. if (count < 8) {
  2907. memset(p, 0, count);
  2908. mg_byte_reverse(ctx->in, 16);
  2909. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  2910. memset(ctx->in, 0, 56);
  2911. } else {
  2912. memset(p, 0, count - 8);
  2913. }
  2914. mg_byte_reverse(ctx->in, 14);
  2915. a = (uint32_t *) ctx->in;
  2916. a[14] = ctx->bits[0];
  2917. a[15] = ctx->bits[1];
  2918. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  2919. mg_byte_reverse((unsigned char *) ctx->buf, 4);
  2920. memcpy(digest, ctx->buf, 16);
  2921. memset((char *) ctx, 0, sizeof(*ctx));
  2922. }
  2923. #endif
  2924. #ifdef MG_ENABLE_LINES
  2925. #line 1 "src/mqtt.c"
  2926. #endif
  2927. #define MQTT_CLEAN_SESSION 0x02
  2928. #define MQTT_HAS_WILL 0x04
  2929. #define MQTT_WILL_RETAIN 0x20
  2930. #define MQTT_HAS_PASSWORD 0x40
  2931. #define MQTT_HAS_USER_NAME 0x80
  2932. struct mg_mqtt_pmap {
  2933. uint8_t id;
  2934. uint8_t type;
  2935. };
  2936. static const struct mg_mqtt_pmap s_prop_map[] = {
  2937. {MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, MQTT_PROP_TYPE_BYTE},
  2938. {MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  2939. {MQTT_PROP_CONTENT_TYPE, MQTT_PROP_TYPE_STRING},
  2940. {MQTT_PROP_RESPONSE_TOPIC, MQTT_PROP_TYPE_STRING},
  2941. {MQTT_PROP_CORRELATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  2942. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER, MQTT_PROP_TYPE_VARIABLE_INT},
  2943. {MQTT_PROP_SESSION_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  2944. {MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, MQTT_PROP_TYPE_STRING},
  2945. {MQTT_PROP_SERVER_KEEP_ALIVE, MQTT_PROP_TYPE_SHORT},
  2946. {MQTT_PROP_AUTHENTICATION_METHOD, MQTT_PROP_TYPE_STRING},
  2947. {MQTT_PROP_AUTHENTICATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  2948. {MQTT_PROP_REQUEST_PROBLEM_INFORMATION, MQTT_PROP_TYPE_BYTE},
  2949. {MQTT_PROP_WILL_DELAY_INTERVAL, MQTT_PROP_TYPE_INT},
  2950. {MQTT_PROP_REQUEST_RESPONSE_INFORMATION, MQTT_PROP_TYPE_BYTE},
  2951. {MQTT_PROP_RESPONSE_INFORMATION, MQTT_PROP_TYPE_STRING},
  2952. {MQTT_PROP_SERVER_REFERENCE, MQTT_PROP_TYPE_STRING},
  2953. {MQTT_PROP_REASON_STRING, MQTT_PROP_TYPE_STRING},
  2954. {MQTT_PROP_RECEIVE_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  2955. {MQTT_PROP_TOPIC_ALIAS_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  2956. {MQTT_PROP_TOPIC_ALIAS, MQTT_PROP_TYPE_SHORT},
  2957. {MQTT_PROP_MAXIMUM_QOS, MQTT_PROP_TYPE_BYTE},
  2958. {MQTT_PROP_RETAIN_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  2959. {MQTT_PROP_USER_PROPERTY, MQTT_PROP_TYPE_STRING_PAIR},
  2960. {MQTT_PROP_MAXIMUM_PACKET_SIZE, MQTT_PROP_TYPE_INT},
  2961. {MQTT_PROP_WILDCARD_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  2962. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  2963. {MQTT_PROP_SHARED_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE}};
  2964. void mg_mqtt_send_header(struct mg_connection *c, uint8_t cmd, uint8_t flags,
  2965. uint32_t len) {
  2966. uint8_t buf[1 + sizeof(len)], *vlen = &buf[1];
  2967. buf[0] = (uint8_t) ((cmd << 4) | flags);
  2968. do {
  2969. *vlen = len % 0x80;
  2970. len /= 0x80;
  2971. if (len > 0) *vlen |= 0x80;
  2972. vlen++;
  2973. } while (len > 0 && vlen < &buf[sizeof(buf)]);
  2974. mg_send(c, buf, (size_t) (vlen - buf));
  2975. }
  2976. static void mg_send_u16(struct mg_connection *c, uint16_t value) {
  2977. mg_send(c, &value, sizeof(value));
  2978. }
  2979. static void mg_send_u32(struct mg_connection *c, uint32_t value) {
  2980. mg_send(c, &value, sizeof(value));
  2981. }
  2982. static uint8_t varint_size(size_t length) {
  2983. uint8_t bytes_needed = 0;
  2984. do {
  2985. bytes_needed++;
  2986. length /= 0x80;
  2987. } while (length > 0);
  2988. return bytes_needed;
  2989. }
  2990. static size_t encode_varint(uint8_t *buf, size_t value) {
  2991. size_t len = 0;
  2992. do {
  2993. uint8_t b = (uint8_t) (value % 128);
  2994. value /= 128;
  2995. if (value > 0) b |= 0x80;
  2996. buf[len++] = b;
  2997. } while (value > 0);
  2998. return len;
  2999. }
  3000. static size_t decode_varint(const uint8_t *buf, size_t len, size_t *value) {
  3001. size_t multiplier = 1, offset;
  3002. *value = 0;
  3003. for (offset = 0; offset < 4 && offset < len; offset++) {
  3004. uint8_t encoded_byte = buf[offset];
  3005. *value += (encoded_byte & 0x7f) * multiplier;
  3006. multiplier *= 128;
  3007. if ((encoded_byte & 0x80) == 0) return offset + 1;
  3008. }
  3009. return 0;
  3010. }
  3011. static int mqtt_prop_type_by_id(uint8_t prop_id) {
  3012. size_t i, num_properties = sizeof(s_prop_map) / sizeof(s_prop_map[0]);
  3013. for (i = 0; i < num_properties; ++i) {
  3014. if (s_prop_map[i].id == prop_id) return s_prop_map[i].type;
  3015. }
  3016. return -1; // Property ID not found
  3017. }
  3018. // Returns the size of the properties section, without the
  3019. // size of the content's length
  3020. static size_t get_properties_length(struct mg_mqtt_prop *props, size_t count) {
  3021. size_t i, size = 0;
  3022. for (i = 0; i < count; i++) {
  3023. size++; // identifier
  3024. switch (mqtt_prop_type_by_id(props[i].id)) {
  3025. case MQTT_PROP_TYPE_STRING_PAIR:
  3026. size += (uint32_t) (props[i].val.len + props[i].key.len +
  3027. 2 * sizeof(uint16_t));
  3028. break;
  3029. case MQTT_PROP_TYPE_STRING:
  3030. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3031. break;
  3032. case MQTT_PROP_TYPE_BINARY_DATA:
  3033. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3034. break;
  3035. case MQTT_PROP_TYPE_VARIABLE_INT:
  3036. size += varint_size((uint32_t) props[i].iv);
  3037. break;
  3038. case MQTT_PROP_TYPE_INT:
  3039. size += (uint32_t) sizeof(uint32_t);
  3040. break;
  3041. case MQTT_PROP_TYPE_SHORT:
  3042. size += (uint32_t) sizeof(uint16_t);
  3043. break;
  3044. case MQTT_PROP_TYPE_BYTE:
  3045. size += (uint32_t) sizeof(uint8_t);
  3046. break;
  3047. default:
  3048. return size; // cannot parse further down
  3049. }
  3050. }
  3051. return size;
  3052. }
  3053. // returns the entire size of the properties section, including the
  3054. // size of the variable length of the content
  3055. static size_t get_props_size(struct mg_mqtt_prop *props, size_t count) {
  3056. size_t size = get_properties_length(props, count);
  3057. size += varint_size(size);
  3058. return size;
  3059. }
  3060. static void mg_send_mqtt_properties(struct mg_connection *c,
  3061. struct mg_mqtt_prop *props, size_t nprops) {
  3062. size_t total_size = get_properties_length(props, nprops);
  3063. uint8_t buf_v[4] = {0, 0, 0, 0};
  3064. uint8_t buf[4] = {0, 0, 0, 0};
  3065. size_t i, len = encode_varint(buf, total_size);
  3066. mg_send(c, buf, (size_t) len);
  3067. for (i = 0; i < nprops; i++) {
  3068. mg_send(c, &props[i].id, sizeof(props[i].id));
  3069. switch (mqtt_prop_type_by_id(props[i].id)) {
  3070. case MQTT_PROP_TYPE_STRING_PAIR:
  3071. mg_send_u16(c, mg_htons((uint16_t) props[i].key.len));
  3072. mg_send(c, props[i].key.buf, props[i].key.len);
  3073. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3074. mg_send(c, props[i].val.buf, props[i].val.len);
  3075. break;
  3076. case MQTT_PROP_TYPE_BYTE:
  3077. mg_send(c, &props[i].iv, sizeof(uint8_t));
  3078. break;
  3079. case MQTT_PROP_TYPE_SHORT:
  3080. mg_send_u16(c, mg_htons((uint16_t) props[i].iv));
  3081. break;
  3082. case MQTT_PROP_TYPE_INT:
  3083. mg_send_u32(c, mg_htonl((uint32_t) props[i].iv));
  3084. break;
  3085. case MQTT_PROP_TYPE_STRING:
  3086. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3087. mg_send(c, props[i].val.buf, props[i].val.len);
  3088. break;
  3089. case MQTT_PROP_TYPE_BINARY_DATA:
  3090. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3091. mg_send(c, props[i].val.buf, props[i].val.len);
  3092. break;
  3093. case MQTT_PROP_TYPE_VARIABLE_INT:
  3094. len = encode_varint(buf_v, props[i].iv);
  3095. mg_send(c, buf_v, (size_t) len);
  3096. break;
  3097. }
  3098. }
  3099. }
  3100. size_t mg_mqtt_next_prop(struct mg_mqtt_message *msg, struct mg_mqtt_prop *prop,
  3101. size_t ofs) {
  3102. uint8_t *i = (uint8_t *) msg->dgram.buf + msg->props_start + ofs;
  3103. uint8_t *end = (uint8_t *) msg->dgram.buf + msg->dgram.len;
  3104. size_t new_pos = ofs, len;
  3105. prop->id = i[0];
  3106. if (ofs >= msg->dgram.len || ofs >= msg->props_start + msg->props_size)
  3107. return 0;
  3108. i++, new_pos++;
  3109. switch (mqtt_prop_type_by_id(prop->id)) {
  3110. case MQTT_PROP_TYPE_STRING_PAIR:
  3111. prop->key.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3112. prop->key.buf = (char *) i + 2;
  3113. i += 2 + prop->key.len;
  3114. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3115. prop->val.buf = (char *) i + 2;
  3116. new_pos += 2 * sizeof(uint16_t) + prop->val.len + prop->key.len;
  3117. break;
  3118. case MQTT_PROP_TYPE_BYTE:
  3119. prop->iv = (uint8_t) i[0];
  3120. new_pos++;
  3121. break;
  3122. case MQTT_PROP_TYPE_SHORT:
  3123. prop->iv = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3124. new_pos += sizeof(uint16_t);
  3125. break;
  3126. case MQTT_PROP_TYPE_INT:
  3127. prop->iv = ((uint32_t) i[0] << 24) | ((uint32_t) i[1] << 16) |
  3128. ((uint32_t) i[2] << 8) | i[3];
  3129. new_pos += sizeof(uint32_t);
  3130. break;
  3131. case MQTT_PROP_TYPE_STRING:
  3132. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3133. prop->val.buf = (char *) i + 2;
  3134. new_pos += 2 + prop->val.len;
  3135. break;
  3136. case MQTT_PROP_TYPE_BINARY_DATA:
  3137. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3138. prop->val.buf = (char *) i + 2;
  3139. new_pos += 2 + prop->val.len;
  3140. break;
  3141. case MQTT_PROP_TYPE_VARIABLE_INT:
  3142. len = decode_varint(i, (size_t) (end - i), (size_t *) &prop->iv);
  3143. new_pos = (!len) ? 0 : new_pos + len;
  3144. break;
  3145. default:
  3146. new_pos = 0;
  3147. }
  3148. return new_pos;
  3149. }
  3150. void mg_mqtt_login(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3151. char client_id[21];
  3152. struct mg_str cid = opts->client_id;
  3153. size_t total_len = 7 + 1 + 2 + 2;
  3154. uint8_t hdr[8] = {0, 4, 'M', 'Q', 'T', 'T', opts->version, 0};
  3155. if (cid.len == 0) {
  3156. mg_random_str(client_id, sizeof(client_id) - 1);
  3157. client_id[sizeof(client_id) - 1] = '\0';
  3158. cid = mg_str(client_id);
  3159. }
  3160. if (hdr[6] == 0) hdr[6] = 4; // If version is not set, use 4 (3.1.1)
  3161. c->is_mqtt5 = hdr[6] == 5; // Set version 5 flag
  3162. hdr[7] = (uint8_t) ((opts->qos & 3) << 3); // Connection flags
  3163. if (opts->user.len > 0) {
  3164. total_len += 2 + (uint32_t) opts->user.len;
  3165. hdr[7] |= MQTT_HAS_USER_NAME;
  3166. }
  3167. if (opts->pass.len > 0) {
  3168. total_len += 2 + (uint32_t) opts->pass.len;
  3169. hdr[7] |= MQTT_HAS_PASSWORD;
  3170. }
  3171. if (opts->topic.len > 0) { // allow zero-length msgs, message.len is size_t
  3172. total_len += 4 + (uint32_t) opts->topic.len + (uint32_t) opts->message.len;
  3173. hdr[7] |= MQTT_HAS_WILL;
  3174. }
  3175. if (opts->clean || cid.len == 0) hdr[7] |= MQTT_CLEAN_SESSION;
  3176. if (opts->retain) hdr[7] |= MQTT_WILL_RETAIN;
  3177. total_len += (uint32_t) cid.len;
  3178. if (c->is_mqtt5) {
  3179. total_len += get_props_size(opts->props, opts->num_props);
  3180. if (hdr[7] & MQTT_HAS_WILL)
  3181. total_len += get_props_size(opts->will_props, opts->num_will_props);
  3182. }
  3183. mg_mqtt_send_header(c, MQTT_CMD_CONNECT, 0, (uint32_t) total_len);
  3184. mg_send(c, hdr, sizeof(hdr));
  3185. // keepalive == 0 means "do not disconnect us!"
  3186. mg_send_u16(c, mg_htons((uint16_t) opts->keepalive));
  3187. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3188. mg_send_u16(c, mg_htons((uint16_t) cid.len));
  3189. mg_send(c, cid.buf, cid.len);
  3190. if (hdr[7] & MQTT_HAS_WILL) {
  3191. if (c->is_mqtt5)
  3192. mg_send_mqtt_properties(c, opts->will_props, opts->num_will_props);
  3193. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3194. mg_send(c, opts->topic.buf, opts->topic.len);
  3195. mg_send_u16(c, mg_htons((uint16_t) opts->message.len));
  3196. mg_send(c, opts->message.buf, opts->message.len);
  3197. }
  3198. if (opts->user.len > 0) {
  3199. mg_send_u16(c, mg_htons((uint16_t) opts->user.len));
  3200. mg_send(c, opts->user.buf, opts->user.len);
  3201. }
  3202. if (opts->pass.len > 0) {
  3203. mg_send_u16(c, mg_htons((uint16_t) opts->pass.len));
  3204. mg_send(c, opts->pass.buf, opts->pass.len);
  3205. }
  3206. }
  3207. uint16_t mg_mqtt_pub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3208. uint16_t id = opts->retransmit_id;
  3209. uint8_t flags = (uint8_t) (((opts->qos & 3) << 1) | (opts->retain ? 1 : 0));
  3210. size_t len = 2 + opts->topic.len + opts->message.len;
  3211. MG_DEBUG(("%lu [%.*s] <- [%.*s%c", c->id, (int) opts->topic.len,
  3212. (char *) opts->topic.buf,
  3213. (int) (opts->message.len <= 10 ? opts->message.len : 10),
  3214. (char *) opts->message.buf, opts->message.len <= 10 ? ']' : ' '));
  3215. if (opts->qos > 0) len += 2;
  3216. if (c->is_mqtt5) len += get_props_size(opts->props, opts->num_props);
  3217. if (opts->qos > 0 && id != 0) flags |= 1 << 3;
  3218. mg_mqtt_send_header(c, MQTT_CMD_PUBLISH, flags, (uint32_t) len);
  3219. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3220. mg_send(c, opts->topic.buf, opts->topic.len);
  3221. if (opts->qos > 0) { // need to send 'id' field
  3222. if (id == 0) { // generate new one if not resending
  3223. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  3224. id = c->mgr->mqtt_id;
  3225. }
  3226. mg_send_u16(c, mg_htons(id));
  3227. }
  3228. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3229. if (opts->message.len > 0) mg_send(c, opts->message.buf, opts->message.len);
  3230. return id;
  3231. }
  3232. void mg_mqtt_sub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3233. uint8_t qos_ = opts->qos & 3;
  3234. size_t plen = c->is_mqtt5 ? get_props_size(opts->props, opts->num_props) : 0;
  3235. size_t len = 2 + opts->topic.len + 2 + 1 + plen;
  3236. mg_mqtt_send_header(c, MQTT_CMD_SUBSCRIBE, 2, (uint32_t) len);
  3237. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  3238. mg_send_u16(c, mg_htons(c->mgr->mqtt_id));
  3239. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3240. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3241. mg_send(c, opts->topic.buf, opts->topic.len);
  3242. mg_send(c, &qos_, sizeof(qos_));
  3243. }
  3244. int mg_mqtt_parse(const uint8_t *buf, size_t len, uint8_t version,
  3245. struct mg_mqtt_message *m) {
  3246. uint8_t lc = 0, *p, *end;
  3247. uint32_t n = 0, len_len = 0;
  3248. memset(m, 0, sizeof(*m));
  3249. m->dgram.buf = (char *) buf;
  3250. if (len < 2) return MQTT_INCOMPLETE;
  3251. m->cmd = (uint8_t) (buf[0] >> 4);
  3252. m->qos = (buf[0] >> 1) & 3;
  3253. n = len_len = 0;
  3254. p = (uint8_t *) buf + 1;
  3255. while ((size_t) (p - buf) < len) {
  3256. lc = *((uint8_t *) p++);
  3257. n += (uint32_t) ((lc & 0x7f) << 7 * len_len);
  3258. len_len++;
  3259. if (!(lc & 0x80)) break;
  3260. if (len_len >= 4) return MQTT_MALFORMED;
  3261. }
  3262. end = p + n;
  3263. if ((lc & 0x80) || (end > buf + len)) return MQTT_INCOMPLETE;
  3264. m->dgram.len = (size_t) (end - buf);
  3265. switch (m->cmd) {
  3266. case MQTT_CMD_CONNACK:
  3267. if (end - p < 2) return MQTT_MALFORMED;
  3268. m->ack = p[1];
  3269. break;
  3270. case MQTT_CMD_PUBACK:
  3271. case MQTT_CMD_PUBREC:
  3272. case MQTT_CMD_PUBREL:
  3273. case MQTT_CMD_PUBCOMP:
  3274. case MQTT_CMD_SUBSCRIBE:
  3275. case MQTT_CMD_SUBACK:
  3276. case MQTT_CMD_UNSUBSCRIBE:
  3277. case MQTT_CMD_UNSUBACK:
  3278. if (p + 2 > end) return MQTT_MALFORMED;
  3279. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3280. p += 2;
  3281. break;
  3282. case MQTT_CMD_PUBLISH: {
  3283. if (p + 2 > end) return MQTT_MALFORMED;
  3284. m->topic.len = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3285. m->topic.buf = (char *) p + 2;
  3286. p += 2 + m->topic.len;
  3287. if (p > end) return MQTT_MALFORMED;
  3288. if (m->qos > 0) {
  3289. if (p + 2 > end) return MQTT_MALFORMED;
  3290. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3291. p += 2;
  3292. }
  3293. if (p > end) return MQTT_MALFORMED;
  3294. if (version == 5 && p + 2 < end) {
  3295. len_len =
  3296. (uint32_t) decode_varint(p, (size_t) (end - p), &m->props_size);
  3297. if (!len_len) return MQTT_MALFORMED;
  3298. m->props_start = (size_t) (p + len_len - buf);
  3299. p += len_len + m->props_size;
  3300. }
  3301. if (p > end) return MQTT_MALFORMED;
  3302. m->data.buf = (char *) p;
  3303. m->data.len = (size_t) (end - p);
  3304. break;
  3305. }
  3306. default:
  3307. break;
  3308. }
  3309. return MQTT_OK;
  3310. }
  3311. static void mqtt_cb(struct mg_connection *c, int ev, void *ev_data) {
  3312. if (ev == MG_EV_READ) {
  3313. for (;;) {
  3314. uint8_t version = c->is_mqtt5 ? 5 : 4;
  3315. struct mg_mqtt_message mm;
  3316. int rc = mg_mqtt_parse(c->recv.buf, c->recv.len, version, &mm);
  3317. if (rc == MQTT_MALFORMED) {
  3318. MG_ERROR(("%lu MQTT malformed message", c->id));
  3319. c->is_closing = 1;
  3320. break;
  3321. } else if (rc == MQTT_OK) {
  3322. MG_VERBOSE(("%lu MQTT CMD %d len %d [%.*s]", c->id, mm.cmd,
  3323. (int) mm.dgram.len, (int) mm.data.len, mm.data.buf));
  3324. switch (mm.cmd) {
  3325. case MQTT_CMD_CONNACK:
  3326. mg_call(c, MG_EV_MQTT_OPEN, &mm.ack);
  3327. if (mm.ack == 0) {
  3328. MG_DEBUG(("%lu Connected", c->id));
  3329. } else {
  3330. MG_ERROR(("%lu MQTT auth failed, code %d", c->id, mm.ack));
  3331. c->is_closing = 1;
  3332. }
  3333. break;
  3334. case MQTT_CMD_PUBLISH: {
  3335. MG_DEBUG(("%lu [%.*s] -> [%.*s%c", c->id, (int) mm.topic.len,
  3336. mm.topic.buf,
  3337. (int) (mm.data.len <= 10 ? mm.data.len : 10), mm.data.buf,
  3338. mm.data.len <= 10 ? ']' : ' '));
  3339. if (mm.qos > 0) {
  3340. uint16_t id = mg_ntohs(mm.id);
  3341. uint32_t remaining_len = sizeof(id);
  3342. if (c->is_mqtt5) remaining_len += 2; // 3.4.2
  3343. mg_mqtt_send_header(
  3344. c,
  3345. (uint8_t) (mm.qos == 2 ? MQTT_CMD_PUBREC : MQTT_CMD_PUBACK),
  3346. 0, remaining_len);
  3347. mg_send(c, &id, sizeof(id));
  3348. if (c->is_mqtt5) {
  3349. uint16_t zero = 0;
  3350. mg_send(c, &zero, sizeof(zero));
  3351. }
  3352. }
  3353. mg_call(c, MG_EV_MQTT_MSG, &mm); // let the app handle qos stuff
  3354. break;
  3355. }
  3356. case MQTT_CMD_PUBREC: { // MQTT5: 3.5.2-1 TODO(): variable header rc
  3357. uint16_t id = mg_ntohs(mm.id);
  3358. uint32_t remaining_len = sizeof(id); // MQTT5 3.6.2-1
  3359. mg_mqtt_send_header(c, MQTT_CMD_PUBREL, 2, remaining_len);
  3360. mg_send(c, &id, sizeof(id)); // MQTT5 3.6.1-1, flags = 2
  3361. break;
  3362. }
  3363. case MQTT_CMD_PUBREL: { // MQTT5: 3.6.2-1 TODO(): variable header rc
  3364. uint16_t id = mg_ntohs(mm.id);
  3365. uint32_t remaining_len = sizeof(id); // MQTT5 3.7.2-1
  3366. mg_mqtt_send_header(c, MQTT_CMD_PUBCOMP, 0, remaining_len);
  3367. mg_send(c, &id, sizeof(id));
  3368. break;
  3369. }
  3370. }
  3371. mg_call(c, MG_EV_MQTT_CMD, &mm);
  3372. mg_iobuf_del(&c->recv, 0, mm.dgram.len);
  3373. } else {
  3374. break;
  3375. }
  3376. }
  3377. }
  3378. (void) ev_data;
  3379. }
  3380. void mg_mqtt_ping(struct mg_connection *nc) {
  3381. mg_mqtt_send_header(nc, MQTT_CMD_PINGREQ, 0, 0);
  3382. }
  3383. void mg_mqtt_pong(struct mg_connection *nc) {
  3384. mg_mqtt_send_header(nc, MQTT_CMD_PINGRESP, 0, 0);
  3385. }
  3386. void mg_mqtt_disconnect(struct mg_connection *c,
  3387. const struct mg_mqtt_opts *opts) {
  3388. size_t len = 0;
  3389. if (c->is_mqtt5) len = 1 + get_props_size(opts->props, opts->num_props);
  3390. mg_mqtt_send_header(c, MQTT_CMD_DISCONNECT, 0, (uint32_t) len);
  3391. if (c->is_mqtt5) {
  3392. uint8_t zero = 0;
  3393. mg_send(c, &zero, sizeof(zero)); // reason code
  3394. mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3395. }
  3396. }
  3397. struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url,
  3398. const struct mg_mqtt_opts *opts,
  3399. mg_event_handler_t fn, void *fn_data) {
  3400. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  3401. if (c != NULL) {
  3402. struct mg_mqtt_opts empty;
  3403. memset(&empty, 0, sizeof(empty));
  3404. mg_mqtt_login(c, opts == NULL ? &empty : opts);
  3405. c->pfn = mqtt_cb;
  3406. }
  3407. return c;
  3408. }
  3409. struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url,
  3410. mg_event_handler_t fn, void *fn_data) {
  3411. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  3412. if (c != NULL) c->pfn = mqtt_cb, c->pfn_data = mgr;
  3413. return c;
  3414. }
  3415. #ifdef MG_ENABLE_LINES
  3416. #line 1 "src/net.c"
  3417. #endif
  3418. size_t mg_vprintf(struct mg_connection *c, const char *fmt, va_list *ap) {
  3419. size_t old = c->send.len;
  3420. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  3421. return c->send.len - old;
  3422. }
  3423. size_t mg_printf(struct mg_connection *c, const char *fmt, ...) {
  3424. size_t len = 0;
  3425. va_list ap;
  3426. va_start(ap, fmt);
  3427. len = mg_vprintf(c, fmt, &ap);
  3428. va_end(ap);
  3429. return len;
  3430. }
  3431. static bool mg_atonl(struct mg_str str, struct mg_addr *addr) {
  3432. uint32_t localhost = mg_htonl(0x7f000001);
  3433. if (mg_strcasecmp(str, mg_str("localhost")) != 0) return false;
  3434. memcpy(addr->ip, &localhost, sizeof(uint32_t));
  3435. addr->is_ip6 = false;
  3436. return true;
  3437. }
  3438. static bool mg_atone(struct mg_str str, struct mg_addr *addr) {
  3439. if (str.len > 0) return false;
  3440. memset(addr->ip, 0, sizeof(addr->ip));
  3441. addr->is_ip6 = false;
  3442. return true;
  3443. }
  3444. static bool mg_aton4(struct mg_str str, struct mg_addr *addr) {
  3445. uint8_t data[4] = {0, 0, 0, 0};
  3446. size_t i, num_dots = 0;
  3447. for (i = 0; i < str.len; i++) {
  3448. if (str.buf[i] >= '0' && str.buf[i] <= '9') {
  3449. int octet = data[num_dots] * 10 + (str.buf[i] - '0');
  3450. if (octet > 255) return false;
  3451. data[num_dots] = (uint8_t) octet;
  3452. } else if (str.buf[i] == '.') {
  3453. if (num_dots >= 3 || i == 0 || str.buf[i - 1] == '.') return false;
  3454. num_dots++;
  3455. } else {
  3456. return false;
  3457. }
  3458. }
  3459. if (num_dots != 3 || str.buf[i - 1] == '.') return false;
  3460. memcpy(&addr->ip, data, sizeof(data));
  3461. addr->is_ip6 = false;
  3462. return true;
  3463. }
  3464. static bool mg_v4mapped(struct mg_str str, struct mg_addr *addr) {
  3465. int i;
  3466. uint32_t ipv4;
  3467. if (str.len < 14) return false;
  3468. if (str.buf[0] != ':' || str.buf[1] != ':' || str.buf[6] != ':') return false;
  3469. for (i = 2; i < 6; i++) {
  3470. if (str.buf[i] != 'f' && str.buf[i] != 'F') return false;
  3471. }
  3472. // struct mg_str s = mg_str_n(&str.buf[7], str.len - 7);
  3473. if (!mg_aton4(mg_str_n(&str.buf[7], str.len - 7), addr)) return false;
  3474. memcpy(&ipv4, addr->ip, sizeof(ipv4));
  3475. memset(addr->ip, 0, sizeof(addr->ip));
  3476. addr->ip[10] = addr->ip[11] = 255;
  3477. memcpy(&addr->ip[12], &ipv4, 4);
  3478. addr->is_ip6 = true;
  3479. return true;
  3480. }
  3481. static bool mg_aton6(struct mg_str str, struct mg_addr *addr) {
  3482. size_t i, j = 0, n = 0, dc = 42;
  3483. addr->scope_id = 0;
  3484. if (str.len > 2 && str.buf[0] == '[') str.buf++, str.len -= 2;
  3485. if (mg_v4mapped(str, addr)) return true;
  3486. for (i = 0; i < str.len; i++) {
  3487. if ((str.buf[i] >= '0' && str.buf[i] <= '9') ||
  3488. (str.buf[i] >= 'a' && str.buf[i] <= 'f') ||
  3489. (str.buf[i] >= 'A' && str.buf[i] <= 'F')) {
  3490. unsigned long val = 0; // TODO(): This loops on chars, refactor
  3491. if (i > j + 3) return false;
  3492. // MG_DEBUG(("%lu %lu [%.*s]", i, j, (int) (i - j + 1), &str.buf[j]));
  3493. mg_str_to_num(mg_str_n(&str.buf[j], i - j + 1), 16, &val, sizeof(val));
  3494. addr->ip[n] = (uint8_t) ((val >> 8) & 255);
  3495. addr->ip[n + 1] = (uint8_t) (val & 255);
  3496. } else if (str.buf[i] == ':') {
  3497. j = i + 1;
  3498. if (i > 0 && str.buf[i - 1] == ':') {
  3499. dc = n; // Double colon
  3500. if (i > 1 && str.buf[i - 2] == ':') return false;
  3501. } else if (i > 0) {
  3502. n += 2;
  3503. }
  3504. if (n > 14) return false;
  3505. addr->ip[n] = addr->ip[n + 1] = 0; // For trailing ::
  3506. } else if (str.buf[i] == '%') { // Scope ID, last in string
  3507. return mg_str_to_num(mg_str_n(&str.buf[i + 1], str.len - i - 1), 10,
  3508. &addr->scope_id, sizeof(uint8_t));
  3509. } else {
  3510. return false;
  3511. }
  3512. }
  3513. if (n < 14 && dc == 42) return false;
  3514. if (n < 14) {
  3515. memmove(&addr->ip[dc + (14 - n)], &addr->ip[dc], n - dc + 2);
  3516. memset(&addr->ip[dc], 0, 14 - n);
  3517. }
  3518. addr->is_ip6 = true;
  3519. return true;
  3520. }
  3521. bool mg_aton(struct mg_str str, struct mg_addr *addr) {
  3522. // MG_INFO(("[%.*s]", (int) str.len, str.buf));
  3523. return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) ||
  3524. mg_aton6(str, addr);
  3525. }
  3526. struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) {
  3527. struct mg_connection *c =
  3528. (struct mg_connection *) calloc(1, sizeof(*c) + mgr->extraconnsize);
  3529. if (c != NULL) {
  3530. c->mgr = mgr;
  3531. c->send.align = c->recv.align = c->rtls.align = MG_IO_SIZE;
  3532. c->id = ++mgr->nextid;
  3533. MG_PROF_INIT(c);
  3534. }
  3535. return c;
  3536. }
  3537. void mg_close_conn(struct mg_connection *c) {
  3538. mg_resolve_cancel(c); // Close any pending DNS query
  3539. LIST_DELETE(struct mg_connection, &c->mgr->conns, c);
  3540. if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL;
  3541. if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL;
  3542. // Order of operations is important. `MG_EV_CLOSE` event must be fired
  3543. // before we deallocate received data, see #1331
  3544. mg_call(c, MG_EV_CLOSE, NULL);
  3545. MG_DEBUG(("%lu %ld closed", c->id, c->fd));
  3546. MG_PROF_DUMP(c);
  3547. MG_PROF_FREE(c);
  3548. mg_tls_free(c);
  3549. mg_iobuf_free(&c->recv);
  3550. mg_iobuf_free(&c->send);
  3551. mg_iobuf_free(&c->rtls);
  3552. mg_bzero((unsigned char *) c, sizeof(*c));
  3553. free(c);
  3554. }
  3555. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url,
  3556. mg_event_handler_t fn, void *fn_data) {
  3557. struct mg_connection *c = NULL;
  3558. if (url == NULL || url[0] == '\0') {
  3559. MG_ERROR(("null url"));
  3560. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  3561. MG_ERROR(("OOM"));
  3562. } else {
  3563. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3564. c->is_udp = (strncmp(url, "udp:", 4) == 0);
  3565. c->fd = (void *) (size_t) MG_INVALID_SOCKET;
  3566. c->fn = fn;
  3567. c->is_client = true;
  3568. c->fn_data = fn_data;
  3569. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  3570. mg_call(c, MG_EV_OPEN, (void *) url);
  3571. mg_resolve(c, url);
  3572. }
  3573. return c;
  3574. }
  3575. struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url,
  3576. mg_event_handler_t fn, void *fn_data) {
  3577. struct mg_connection *c = NULL;
  3578. if ((c = mg_alloc_conn(mgr)) == NULL) {
  3579. MG_ERROR(("OOM %s", url));
  3580. } else if (!mg_open_listener(c, url)) {
  3581. MG_ERROR(("Failed: %s, errno %d", url, errno));
  3582. MG_PROF_FREE(c);
  3583. free(c);
  3584. c = NULL;
  3585. } else {
  3586. c->is_listening = 1;
  3587. c->is_udp = strncmp(url, "udp:", 4) == 0;
  3588. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3589. c->fn = fn;
  3590. c->fn_data = fn_data;
  3591. mg_call(c, MG_EV_OPEN, NULL);
  3592. if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must
  3593. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  3594. }
  3595. return c;
  3596. }
  3597. struct mg_connection *mg_wrapfd(struct mg_mgr *mgr, int fd,
  3598. mg_event_handler_t fn, void *fn_data) {
  3599. struct mg_connection *c = mg_alloc_conn(mgr);
  3600. if (c != NULL) {
  3601. c->fd = (void *) (size_t) fd;
  3602. c->fn = fn;
  3603. c->fn_data = fn_data;
  3604. MG_EPOLL_ADD(c);
  3605. mg_call(c, MG_EV_OPEN, NULL);
  3606. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3607. }
  3608. return c;
  3609. }
  3610. struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds,
  3611. unsigned flags, void (*fn)(void *), void *arg) {
  3612. struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t));
  3613. if (t != NULL) {
  3614. mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg);
  3615. t->id = mgr->timerid++;
  3616. }
  3617. return t;
  3618. }
  3619. long mg_io_recv(struct mg_connection *c, void *buf, size_t len) {
  3620. if (c->rtls.len == 0) return MG_IO_WAIT;
  3621. if (len > c->rtls.len) len = c->rtls.len;
  3622. memcpy(buf, c->rtls.buf, len);
  3623. mg_iobuf_del(&c->rtls, 0, len);
  3624. return (long) len;
  3625. }
  3626. void mg_mgr_free(struct mg_mgr *mgr) {
  3627. struct mg_connection *c;
  3628. struct mg_timer *tmp, *t = mgr->timers;
  3629. while (t != NULL) tmp = t->next, free(t), t = tmp;
  3630. mgr->timers = NULL; // Important. Next call to poll won't touch timers
  3631. for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1;
  3632. mg_mgr_poll(mgr, 0);
  3633. #if MG_ENABLE_FREERTOS_TCP
  3634. FreeRTOS_DeleteSocketSet(mgr->ss);
  3635. #endif
  3636. MG_DEBUG(("All connections closed"));
  3637. #if MG_ENABLE_EPOLL
  3638. if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1;
  3639. #endif
  3640. mg_tls_ctx_free(mgr);
  3641. }
  3642. void mg_mgr_init(struct mg_mgr *mgr) {
  3643. memset(mgr, 0, sizeof(*mgr));
  3644. #if MG_ENABLE_EPOLL
  3645. if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
  3646. MG_ERROR(("epoll_create1 errno %d", errno));
  3647. #else
  3648. mgr->epoll_fd = -1;
  3649. #endif
  3650. #if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  3651. // clang-format off
  3652. { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
  3653. // clang-format on
  3654. #elif MG_ENABLE_FREERTOS_TCP
  3655. mgr->ss = FreeRTOS_CreateSocketSet();
  3656. #elif defined(__unix) || defined(__unix__) || defined(__APPLE__)
  3657. // Ignore SIGPIPE signal, so if client cancels the request, it
  3658. // won't kill the whole process.
  3659. signal(SIGPIPE, SIG_IGN);
  3660. #elif MG_ENABLE_TCPIP_DRIVER_INIT && defined(MG_TCPIP_DRIVER_INIT)
  3661. MG_TCPIP_DRIVER_INIT(mgr);
  3662. #endif
  3663. mgr->pipe = MG_INVALID_SOCKET;
  3664. mgr->dnstimeout = 3000;
  3665. mgr->dns4.url = "udp://8.8.8.8:53";
  3666. mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
  3667. mg_tls_ctx_init(mgr);
  3668. }
  3669. #ifdef MG_ENABLE_LINES
  3670. #line 1 "src/net_builtin.c"
  3671. #endif
  3672. #if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP
  3673. #define MG_EPHEMERAL_PORT_BASE 32768
  3674. #define PDIFF(a, b) ((size_t) (((char *) (b)) - ((char *) (a))))
  3675. #ifndef MIP_TCP_KEEPALIVE_MS
  3676. #define MIP_TCP_KEEPALIVE_MS 45000 // TCP keep-alive period, ms
  3677. #endif
  3678. #define MIP_TCP_ACK_MS 150 // Timeout for ACKing
  3679. #define MIP_ARP_RESP_MS 100 // Timeout for ARP response
  3680. #define MIP_TCP_SYN_MS 15000 // Timeout for connection establishment
  3681. #define MIP_TCP_FIN_MS 1000 // Timeout for closing connection
  3682. #define MIP_TCP_WIN 6000 // TCP window size
  3683. struct connstate {
  3684. uint32_t seq, ack; // TCP seq/ack counters
  3685. uint64_t timer; // TCP keep-alive / ACK timer
  3686. uint32_t acked; // Last ACK-ed number
  3687. size_t unacked; // Not acked bytes
  3688. uint8_t mac[6]; // Peer MAC address
  3689. uint8_t ttype; // Timer type. 0: ack, 1: keep-alive
  3690. #define MIP_TTYPE_KEEPALIVE 0 // Connection is idle for long, send keepalive
  3691. #define MIP_TTYPE_ACK 1 // Peer sent us data, we have to ack it soon
  3692. #define MIP_TTYPE_ARP 2 // ARP resolve sent, waiting for response
  3693. #define MIP_TTYPE_SYN 3 // SYN sent, waiting for response
  3694. #define MIP_TTYPE_FIN 4 // FIN sent, waiting until terminating the connection
  3695. uint8_t tmiss; // Number of keep-alive misses
  3696. struct mg_iobuf raw; // For TLS only. Incoming raw data
  3697. };
  3698. #pragma pack(push, 1)
  3699. struct lcp {
  3700. uint8_t addr, ctrl, proto[2], code, id, len[2];
  3701. };
  3702. struct eth {
  3703. uint8_t dst[6]; // Destination MAC address
  3704. uint8_t src[6]; // Source MAC address
  3705. uint16_t type; // Ethernet type
  3706. };
  3707. struct ip {
  3708. uint8_t ver; // Version
  3709. uint8_t tos; // Unused
  3710. uint16_t len; // Length
  3711. uint16_t id; // Unused
  3712. uint16_t frag; // Fragmentation
  3713. #define IP_FRAG_OFFSET_MSK 0x1fff
  3714. #define IP_MORE_FRAGS_MSK 0x2000
  3715. uint8_t ttl; // Time to live
  3716. uint8_t proto; // Upper level protocol
  3717. uint16_t csum; // Checksum
  3718. uint32_t src; // Source IP
  3719. uint32_t dst; // Destination IP
  3720. };
  3721. struct ip6 {
  3722. uint8_t ver; // Version
  3723. uint8_t opts[3]; // Options
  3724. uint16_t len; // Length
  3725. uint8_t proto; // Upper level protocol
  3726. uint8_t ttl; // Time to live
  3727. uint8_t src[16]; // Source IP
  3728. uint8_t dst[16]; // Destination IP
  3729. };
  3730. struct icmp {
  3731. uint8_t type;
  3732. uint8_t code;
  3733. uint16_t csum;
  3734. };
  3735. struct arp {
  3736. uint16_t fmt; // Format of hardware address
  3737. uint16_t pro; // Format of protocol address
  3738. uint8_t hlen; // Length of hardware address
  3739. uint8_t plen; // Length of protocol address
  3740. uint16_t op; // Operation
  3741. uint8_t sha[6]; // Sender hardware address
  3742. uint32_t spa; // Sender protocol address
  3743. uint8_t tha[6]; // Target hardware address
  3744. uint32_t tpa; // Target protocol address
  3745. };
  3746. struct tcp {
  3747. uint16_t sport; // Source port
  3748. uint16_t dport; // Destination port
  3749. uint32_t seq; // Sequence number
  3750. uint32_t ack; // Acknowledgement number
  3751. uint8_t off; // Data offset
  3752. uint8_t flags; // TCP flags
  3753. #define TH_FIN 0x01
  3754. #define TH_SYN 0x02
  3755. #define TH_RST 0x04
  3756. #define TH_PUSH 0x08
  3757. #define TH_ACK 0x10
  3758. #define TH_URG 0x20
  3759. #define TH_ECE 0x40
  3760. #define TH_CWR 0x80
  3761. uint16_t win; // Window
  3762. uint16_t csum; // Checksum
  3763. uint16_t urp; // Urgent pointer
  3764. };
  3765. struct udp {
  3766. uint16_t sport; // Source port
  3767. uint16_t dport; // Destination port
  3768. uint16_t len; // UDP length
  3769. uint16_t csum; // UDP checksum
  3770. };
  3771. struct dhcp {
  3772. uint8_t op, htype, hlen, hops;
  3773. uint32_t xid;
  3774. uint16_t secs, flags;
  3775. uint32_t ciaddr, yiaddr, siaddr, giaddr;
  3776. uint8_t hwaddr[208];
  3777. uint32_t magic;
  3778. uint8_t options[32];
  3779. };
  3780. #pragma pack(pop)
  3781. struct pkt {
  3782. struct mg_str raw; // Raw packet data
  3783. struct mg_str pay; // Payload data
  3784. struct eth *eth;
  3785. struct llc *llc;
  3786. struct arp *arp;
  3787. struct ip *ip;
  3788. struct ip6 *ip6;
  3789. struct icmp *icmp;
  3790. struct tcp *tcp;
  3791. struct udp *udp;
  3792. struct dhcp *dhcp;
  3793. };
  3794. static void mg_tcpip_call(struct mg_tcpip_if *ifp, int ev, void *ev_data) {
  3795. if (ifp->fn != NULL) ifp->fn(ifp, ev, ev_data);
  3796. }
  3797. static void send_syn(struct mg_connection *c);
  3798. static void mkpay(struct pkt *pkt, void *p) {
  3799. pkt->pay =
  3800. mg_str_n((char *) p, (size_t) (&pkt->raw.buf[pkt->raw.len] - (char *) p));
  3801. }
  3802. static uint32_t csumup(uint32_t sum, const void *buf, size_t len) {
  3803. size_t i;
  3804. const uint8_t *p = (const uint8_t *) buf;
  3805. for (i = 0; i < len; i++) sum += i & 1 ? p[i] : ((uint32_t) p[i]) << 8;
  3806. return sum;
  3807. }
  3808. static uint16_t csumfin(uint32_t sum) {
  3809. while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
  3810. return mg_htons(~sum & 0xffff);
  3811. }
  3812. static uint16_t ipcsum(const void *buf, size_t len) {
  3813. uint32_t sum = csumup(0, buf, len);
  3814. return csumfin(sum);
  3815. }
  3816. static void settmout(struct mg_connection *c, uint8_t type) {
  3817. struct mg_tcpip_if *ifp = c->mgr->ifp;
  3818. struct connstate *s = (struct connstate *) (c + 1);
  3819. unsigned n = type == MIP_TTYPE_ACK ? MIP_TCP_ACK_MS
  3820. : type == MIP_TTYPE_ARP ? MIP_ARP_RESP_MS
  3821. : type == MIP_TTYPE_SYN ? MIP_TCP_SYN_MS
  3822. : type == MIP_TTYPE_FIN ? MIP_TCP_FIN_MS
  3823. : MIP_TCP_KEEPALIVE_MS;
  3824. s->timer = ifp->now + n;
  3825. s->ttype = type;
  3826. MG_VERBOSE(("%lu %d -> %llx", c->id, type, s->timer));
  3827. }
  3828. static size_t ether_output(struct mg_tcpip_if *ifp, size_t len) {
  3829. size_t n = ifp->driver->tx(ifp->tx.buf, len, ifp);
  3830. if (n == len) ifp->nsent++;
  3831. return n;
  3832. }
  3833. void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac) {
  3834. struct eth *eth = (struct eth *) ifp->tx.buf;
  3835. struct arp *arp = (struct arp *) (eth + 1);
  3836. memset(eth->dst, 255, sizeof(eth->dst));
  3837. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  3838. eth->type = mg_htons(0x806);
  3839. memset(arp, 0, sizeof(*arp));
  3840. arp->fmt = mg_htons(1), arp->pro = mg_htons(0x800), arp->hlen = 6,
  3841. arp->plen = 4;
  3842. arp->op = mg_htons(1), arp->tpa = ip, arp->spa = ifp->ip;
  3843. memcpy(arp->sha, ifp->mac, sizeof(arp->sha));
  3844. if (mac != NULL) memcpy(arp->tha, mac, sizeof(arp->tha));
  3845. ether_output(ifp, PDIFF(eth, arp + 1));
  3846. }
  3847. static void onstatechange(struct mg_tcpip_if *ifp) {
  3848. if (ifp->state == MG_TCPIP_STATE_READY) {
  3849. MG_INFO(("READY, IP: %M", mg_print_ip4, &ifp->ip));
  3850. MG_INFO((" GW: %M", mg_print_ip4, &ifp->gw));
  3851. MG_INFO((" MAC: %M", mg_print_mac, &ifp->mac));
  3852. } else if (ifp->state == MG_TCPIP_STATE_IP) {
  3853. MG_ERROR(("Got IP"));
  3854. mg_tcpip_arp_request(ifp, ifp->gw, NULL); // unsolicited GW ARP request
  3855. } else if (ifp->state == MG_TCPIP_STATE_UP) {
  3856. MG_ERROR(("Link up"));
  3857. srand((unsigned int) mg_millis());
  3858. } else if (ifp->state == MG_TCPIP_STATE_DOWN) {
  3859. MG_ERROR(("Link down"));
  3860. }
  3861. mg_tcpip_call(ifp, MG_TCPIP_EV_ST_CHG, &ifp->state);
  3862. }
  3863. static struct ip *tx_ip(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  3864. uint8_t proto, uint32_t ip_src, uint32_t ip_dst,
  3865. size_t plen) {
  3866. struct eth *eth = (struct eth *) ifp->tx.buf;
  3867. struct ip *ip = (struct ip *) (eth + 1);
  3868. memcpy(eth->dst, mac_dst, sizeof(eth->dst));
  3869. memcpy(eth->src, ifp->mac, sizeof(eth->src)); // Use our MAC
  3870. eth->type = mg_htons(0x800);
  3871. memset(ip, 0, sizeof(*ip));
  3872. ip->ver = 0x45; // Version 4, header length 5 words
  3873. ip->frag = mg_htons(0x4000); // Don't fragment
  3874. ip->len = mg_htons((uint16_t) (sizeof(*ip) + plen));
  3875. ip->ttl = 64;
  3876. ip->proto = proto;
  3877. ip->src = ip_src;
  3878. ip->dst = ip_dst;
  3879. ip->csum = ipcsum(ip, sizeof(*ip));
  3880. return ip;
  3881. }
  3882. static void tx_udp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  3883. uint16_t sport, uint32_t ip_dst, uint16_t dport,
  3884. const void *buf, size_t len) {
  3885. struct ip *ip =
  3886. tx_ip(ifp, mac_dst, 17, ip_src, ip_dst, len + sizeof(struct udp));
  3887. struct udp *udp = (struct udp *) (ip + 1);
  3888. // MG_DEBUG(("UDP XX LEN %d %d", (int) len, (int) ifp->tx.len));
  3889. udp->sport = sport;
  3890. udp->dport = dport;
  3891. udp->len = mg_htons((uint16_t) (sizeof(*udp) + len));
  3892. udp->csum = 0;
  3893. uint32_t cs = csumup(0, udp, sizeof(*udp));
  3894. cs = csumup(cs, buf, len);
  3895. cs = csumup(cs, &ip->src, sizeof(ip->src));
  3896. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  3897. cs += (uint32_t) (ip->proto + sizeof(*udp) + len);
  3898. udp->csum = csumfin(cs);
  3899. memmove(udp + 1, buf, len);
  3900. // MG_DEBUG(("UDP LEN %d %d", (int) len, (int) ifp->frame_len));
  3901. ether_output(ifp, sizeof(struct eth) + sizeof(*ip) + sizeof(*udp) + len);
  3902. }
  3903. static void tx_dhcp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  3904. uint32_t ip_dst, uint8_t *opts, size_t optslen,
  3905. bool ciaddr) {
  3906. // https://datatracker.ietf.org/doc/html/rfc2132#section-9.6
  3907. struct dhcp dhcp = {1, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  3908. dhcp.magic = mg_htonl(0x63825363);
  3909. memcpy(&dhcp.hwaddr, ifp->mac, sizeof(ifp->mac));
  3910. memcpy(&dhcp.xid, ifp->mac + 2, sizeof(dhcp.xid));
  3911. memcpy(&dhcp.options, opts, optslen);
  3912. if (ciaddr) dhcp.ciaddr = ip_src;
  3913. tx_udp(ifp, mac_dst, ip_src, mg_htons(68), ip_dst, mg_htons(67), &dhcp,
  3914. sizeof(dhcp));
  3915. }
  3916. static const uint8_t broadcast[] = {255, 255, 255, 255, 255, 255};
  3917. // RFC-2131 #4.3.6, #4.4.1; RFC-2132 #9.8
  3918. static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
  3919. uint32_t ip_srv) {
  3920. uint8_t opts[] = {
  3921. 53, 1, 3, // Type: DHCP request
  3922. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  3923. 54, 4, 0, 0, 0, 0, // DHCP server ID
  3924. 50, 4, 0, 0, 0, 0, // Requested IP
  3925. 55, 2, 1, 3, 255, 255, // GW, mask [DNS] [SNTP]
  3926. 255 // End of options
  3927. };
  3928. uint8_t addopts = 0;
  3929. memcpy(opts + 10, &ip_srv, sizeof(ip_srv));
  3930. memcpy(opts + 16, &ip_req, sizeof(ip_req));
  3931. if (ifp->enable_req_dns) opts[24 + addopts++] = 6; // DNS
  3932. if (ifp->enable_req_sntp) opts[24 + addopts++] = 42; // SNTP
  3933. opts[21] += addopts;
  3934. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts,
  3935. sizeof(opts) + addopts - 2, false);
  3936. MG_DEBUG(("DHCP req sent"));
  3937. }
  3938. // RFC-2131 #4.3.6, #4.4.5 (renewing: unicast, rebinding: bcast)
  3939. static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  3940. uint32_t ip_src, uint32_t ip_dst) {
  3941. uint8_t opts[] = {
  3942. 53, 1, 3, // Type: DHCP request
  3943. 255 // End of options
  3944. };
  3945. tx_dhcp(ifp, mac_dst, ip_src, ip_dst, opts, sizeof(opts), true);
  3946. MG_DEBUG(("DHCP req sent"));
  3947. }
  3948. static void tx_dhcp_discover(struct mg_tcpip_if *ifp) {
  3949. uint8_t opts[] = {
  3950. 53, 1, 1, // Type: DHCP discover
  3951. 55, 2, 1, 3, // Parameters: ip, mask
  3952. 255 // End of options
  3953. };
  3954. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  3955. MG_DEBUG(("DHCP discover sent. Our MAC: %M", mg_print_mac, ifp->mac));
  3956. }
  3957. static struct mg_connection *getpeer(struct mg_mgr *mgr, struct pkt *pkt,
  3958. bool lsn) {
  3959. struct mg_connection *c = NULL;
  3960. for (c = mgr->conns; c != NULL; c = c->next) {
  3961. if (c->is_arplooking && pkt->arp &&
  3962. memcmp(&pkt->arp->spa, c->rem.ip, sizeof(pkt->arp->spa)) == 0)
  3963. break;
  3964. if (c->is_udp && pkt->udp && c->loc.port == pkt->udp->dport) break;
  3965. if (!c->is_udp && pkt->tcp && c->loc.port == pkt->tcp->dport &&
  3966. lsn == c->is_listening && (lsn || c->rem.port == pkt->tcp->sport))
  3967. break;
  3968. }
  3969. return c;
  3970. }
  3971. static void mac_resolved(struct mg_connection *c);
  3972. static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  3973. if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) {
  3974. // ARP request. Make a response, then send
  3975. // MG_DEBUG(("ARP op %d %M: %M", mg_ntohs(pkt->arp->op), mg_print_ip4,
  3976. // &pkt->arp->spa, mg_print_ip4, &pkt->arp->tpa));
  3977. struct eth *eth = (struct eth *) ifp->tx.buf;
  3978. struct arp *arp = (struct arp *) (eth + 1);
  3979. memcpy(eth->dst, pkt->eth->src, sizeof(eth->dst));
  3980. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  3981. eth->type = mg_htons(0x806);
  3982. *arp = *pkt->arp;
  3983. arp->op = mg_htons(2);
  3984. memcpy(arp->tha, pkt->arp->sha, sizeof(pkt->arp->tha));
  3985. memcpy(arp->sha, ifp->mac, sizeof(pkt->arp->sha));
  3986. arp->tpa = pkt->arp->spa;
  3987. arp->spa = ifp->ip;
  3988. MG_DEBUG(("ARP: tell %M we're %M", mg_print_ip4, &arp->tpa, mg_print_mac,
  3989. &ifp->mac));
  3990. ether_output(ifp, PDIFF(eth, arp + 1));
  3991. } else if (pkt->arp->op == mg_htons(2)) {
  3992. if (memcmp(pkt->arp->tha, ifp->mac, sizeof(pkt->arp->tha)) != 0) return;
  3993. if (pkt->arp->spa == ifp->gw) {
  3994. // Got response for the GW ARP request. Set ifp->gwmac and IP -> READY
  3995. memcpy(ifp->gwmac, pkt->arp->sha, sizeof(ifp->gwmac));
  3996. if (ifp->state == MG_TCPIP_STATE_IP) {
  3997. ifp->state = MG_TCPIP_STATE_READY;
  3998. onstatechange(ifp);
  3999. }
  4000. } else {
  4001. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4002. if (c != NULL && c->is_arplooking) {
  4003. struct connstate *s = (struct connstate *) (c + 1);
  4004. memcpy(s->mac, pkt->arp->sha, sizeof(s->mac));
  4005. MG_DEBUG(("%lu ARP resolved %M -> %M", c->id, mg_print_ip4, c->rem.ip,
  4006. mg_print_mac, s->mac));
  4007. c->is_arplooking = 0;
  4008. mac_resolved(c);
  4009. }
  4010. }
  4011. }
  4012. }
  4013. static void rx_icmp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4014. // MG_DEBUG(("ICMP %d", (int) len));
  4015. if (pkt->icmp->type == 8 && pkt->ip != NULL && pkt->ip->dst == ifp->ip) {
  4016. size_t hlen = sizeof(struct eth) + sizeof(struct ip) + sizeof(struct icmp);
  4017. size_t space = ifp->tx.len - hlen, plen = pkt->pay.len;
  4018. if (plen > space) plen = space;
  4019. struct ip *ip = tx_ip(ifp, pkt->eth->src, 1, ifp->ip, pkt->ip->src,
  4020. sizeof(struct icmp) + plen);
  4021. struct icmp *icmp = (struct icmp *) (ip + 1);
  4022. memset(icmp, 0, sizeof(*icmp)); // Set csum to 0
  4023. memcpy(icmp + 1, pkt->pay.buf, plen); // Copy RX payload to TX
  4024. icmp->csum = ipcsum(icmp, sizeof(*icmp) + plen);
  4025. ether_output(ifp, hlen + plen);
  4026. }
  4027. }
  4028. static void rx_dhcp_client(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4029. uint32_t ip = 0, gw = 0, mask = 0, lease = 0, dns = 0, sntp = 0;
  4030. uint8_t msgtype = 0, state = ifp->state;
  4031. // perform size check first, then access fields
  4032. uint8_t *p = pkt->dhcp->options,
  4033. *end = (uint8_t *) &pkt->raw.buf[pkt->raw.len];
  4034. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4035. if (memcmp(&pkt->dhcp->xid, ifp->mac + 2, sizeof(pkt->dhcp->xid))) return;
  4036. while (p + 1 < end && p[0] != 255) { // Parse options RFC-1533 #9
  4037. if (p[0] == 1 && p[1] == sizeof(ifp->mask) && p + 6 < end) { // Mask
  4038. memcpy(&mask, p + 2, sizeof(mask));
  4039. } else if (p[0] == 3 && p[1] == sizeof(ifp->gw) && p + 6 < end) { // GW
  4040. memcpy(&gw, p + 2, sizeof(gw));
  4041. ip = pkt->dhcp->yiaddr;
  4042. } else if (ifp->enable_req_dns && p[0] == 6 && p[1] == sizeof(dns) &&
  4043. p + 6 < end) { // DNS
  4044. memcpy(&dns, p + 2, sizeof(dns));
  4045. } else if (ifp->enable_req_sntp && p[0] == 42 && p[1] == sizeof(sntp) &&
  4046. p + 6 < end) { // SNTP
  4047. memcpy(&sntp, p + 2, sizeof(sntp));
  4048. } else if (p[0] == 51 && p[1] == 4 && p + 6 < end) { // Lease
  4049. memcpy(&lease, p + 2, sizeof(lease));
  4050. lease = mg_ntohl(lease);
  4051. } else if (p[0] == 53 && p[1] == 1 && p + 6 < end) { // Msg Type
  4052. msgtype = p[2];
  4053. }
  4054. p += p[1] + 2;
  4055. }
  4056. // Process message type, RFC-1533 (9.4); RFC-2131 (3.1, 4)
  4057. if (msgtype == 6 && ifp->ip == ip) { // DHCPNACK, release IP
  4058. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0;
  4059. } else if (msgtype == 2 && ifp->state == MG_TCPIP_STATE_UP && ip && gw &&
  4060. lease) { // DHCPOFFER
  4061. // select IP, (4.4.1) (fallback to IP source addr on foul play)
  4062. tx_dhcp_request_sel(ifp, ip,
  4063. pkt->dhcp->siaddr ? pkt->dhcp->siaddr : pkt->ip->src);
  4064. ifp->state = MG_TCPIP_STATE_REQ; // REQUESTING state
  4065. } else if (msgtype == 5) { // DHCPACK
  4066. if (ifp->state == MG_TCPIP_STATE_REQ && ip && gw && lease) { // got an IP
  4067. ifp->lease_expire = ifp->now + lease * 1000;
  4068. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4069. // assume DHCP server = router until ARP resolves
  4070. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4071. ifp->ip = ip, ifp->gw = gw, ifp->mask = mask;
  4072. ifp->state = MG_TCPIP_STATE_IP; // BOUND state
  4073. uint64_t rand;
  4074. mg_random(&rand, sizeof(rand));
  4075. srand((unsigned int) (rand + mg_millis()));
  4076. if (ifp->enable_req_dns && dns != 0)
  4077. mg_tcpip_call(ifp, MG_TCPIP_EV_DHCP_DNS, &dns);
  4078. if (ifp->enable_req_sntp && sntp != 0)
  4079. mg_tcpip_call(ifp, MG_TCPIP_EV_DHCP_SNTP, &sntp);
  4080. } else if (ifp->state == MG_TCPIP_STATE_READY && ifp->ip == ip) { // renew
  4081. ifp->lease_expire = ifp->now + lease * 1000;
  4082. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4083. } // TODO(): accept provided T1/T2 and store server IP for renewal (4.4)
  4084. }
  4085. if (ifp->state != state) onstatechange(ifp);
  4086. }
  4087. // Simple DHCP server that assigns a next IP address: ifp->ip + 1
  4088. static void rx_dhcp_server(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4089. uint8_t op = 0, *p = pkt->dhcp->options,
  4090. *end = (uint8_t *) &pkt->raw.buf[pkt->raw.len];
  4091. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4092. // struct dhcp *req = pkt->dhcp;
  4093. struct dhcp res = {2, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4094. res.yiaddr = ifp->ip;
  4095. ((uint8_t *) (&res.yiaddr))[3]++; // Offer our IP + 1
  4096. while (p + 1 < end && p[0] != 255) { // Parse options
  4097. if (p[0] == 53 && p[1] == 1 && p + 2 < end) { // Message type
  4098. op = p[2];
  4099. }
  4100. p += p[1] + 2;
  4101. }
  4102. if (op == 1 || op == 3) { // DHCP Discover or DHCP Request
  4103. uint8_t msg = op == 1 ? 2 : 5; // Message type: DHCP OFFER or DHCP ACK
  4104. uint8_t opts[] = {
  4105. 53, 1, msg, // Message type
  4106. 1, 4, 0, 0, 0, 0, // Subnet mask
  4107. 54, 4, 0, 0, 0, 0, // Server ID
  4108. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4109. 51, 4, 255, 255, 255, 255, // Lease time
  4110. 255 // End of options
  4111. };
  4112. memcpy(&res.hwaddr, pkt->dhcp->hwaddr, 6);
  4113. memcpy(opts + 5, &ifp->mask, sizeof(ifp->mask));
  4114. memcpy(opts + 11, &ifp->ip, sizeof(ifp->ip));
  4115. memcpy(&res.options, opts, sizeof(opts));
  4116. res.magic = pkt->dhcp->magic;
  4117. res.xid = pkt->dhcp->xid;
  4118. if (ifp->enable_get_gateway) {
  4119. ifp->gw = res.yiaddr; // set gw IP, best-effort gwmac as DHCP server's
  4120. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4121. }
  4122. tx_udp(ifp, pkt->eth->src, ifp->ip, mg_htons(67),
  4123. op == 1 ? ~0U : res.yiaddr, mg_htons(68), &res, sizeof(res));
  4124. }
  4125. }
  4126. static void rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4127. struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
  4128. if (c == NULL) {
  4129. // No UDP listener on this port. Should send ICMP, but keep silent.
  4130. } else {
  4131. c->rem.port = pkt->udp->sport;
  4132. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4133. struct connstate *s = (struct connstate *) (c + 1);
  4134. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4135. if (c->recv.len >= MG_MAX_RECV_SIZE) {
  4136. mg_error(c, "max_recv_buf_size reached");
  4137. } else if (c->recv.size - c->recv.len < pkt->pay.len &&
  4138. !mg_iobuf_resize(&c->recv, c->recv.len + pkt->pay.len)) {
  4139. mg_error(c, "oom");
  4140. } else {
  4141. memcpy(&c->recv.buf[c->recv.len], pkt->pay.buf, pkt->pay.len);
  4142. c->recv.len += pkt->pay.len;
  4143. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4144. }
  4145. }
  4146. }
  4147. static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *dst_mac, uint32_t dst_ip,
  4148. uint8_t flags, uint16_t sport, uint16_t dport,
  4149. uint32_t seq, uint32_t ack, const void *buf, size_t len) {
  4150. #if 0
  4151. uint8_t opts[] = {2, 4, 5, 0xb4, 4, 2, 0, 0}; // MSS = 1460, SACK permitted
  4152. if (flags & TH_SYN) {
  4153. // Handshake? Set MSS
  4154. buf = opts;
  4155. len = sizeof(opts);
  4156. }
  4157. #endif
  4158. struct ip *ip =
  4159. tx_ip(ifp, dst_mac, 6, ifp->ip, dst_ip, sizeof(struct tcp) + len);
  4160. struct tcp *tcp = (struct tcp *) (ip + 1);
  4161. memset(tcp, 0, sizeof(*tcp));
  4162. if (buf != NULL && len) memmove(tcp + 1, buf, len);
  4163. tcp->sport = sport;
  4164. tcp->dport = dport;
  4165. tcp->seq = seq;
  4166. tcp->ack = ack;
  4167. tcp->flags = flags;
  4168. tcp->win = mg_htons(MIP_TCP_WIN);
  4169. tcp->off = (uint8_t) (sizeof(*tcp) / 4 << 4);
  4170. // if (flags & TH_SYN) tcp->off = 0x70; // Handshake? header size 28 bytes
  4171. uint32_t cs = 0;
  4172. uint16_t n = (uint16_t) (sizeof(*tcp) + len);
  4173. uint8_t pseudo[] = {0, ip->proto, (uint8_t) (n >> 8), (uint8_t) (n & 255)};
  4174. cs = csumup(cs, tcp, n);
  4175. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4176. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4177. cs = csumup(cs, pseudo, sizeof(pseudo));
  4178. tcp->csum = csumfin(cs);
  4179. MG_VERBOSE(("TCP %M:%hu -> %M:%hu fl %x len %u", mg_print_ip4, &ip->src,
  4180. mg_ntohs(tcp->sport), mg_print_ip4, &ip->dst,
  4181. mg_ntohs(tcp->dport), tcp->flags, len));
  4182. // mg_hexdump(ifp->tx.buf, PDIFF(ifp->tx.buf, tcp + 1) + len);
  4183. return ether_output(ifp, PDIFF(ifp->tx.buf, tcp + 1) + len);
  4184. }
  4185. static size_t tx_tcp_pkt(struct mg_tcpip_if *ifp, struct pkt *pkt,
  4186. uint8_t flags, uint32_t seq, const void *buf,
  4187. size_t len) {
  4188. uint32_t delta = (pkt->tcp->flags & (TH_SYN | TH_FIN)) ? 1 : 0;
  4189. return tx_tcp(ifp, pkt->eth->src, pkt->ip->src, flags, pkt->tcp->dport,
  4190. pkt->tcp->sport, seq, mg_htonl(mg_ntohl(pkt->tcp->seq) + delta),
  4191. buf, len);
  4192. }
  4193. static struct mg_connection *accept_conn(struct mg_connection *lsn,
  4194. struct pkt *pkt) {
  4195. struct mg_connection *c = mg_alloc_conn(lsn->mgr);
  4196. if (c == NULL) {
  4197. MG_ERROR(("OOM"));
  4198. return NULL;
  4199. }
  4200. struct connstate *s = (struct connstate *) (c + 1);
  4201. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq);
  4202. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4203. settmout(c, MIP_TTYPE_KEEPALIVE);
  4204. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4205. c->rem.port = pkt->tcp->sport;
  4206. MG_DEBUG(("%lu accepted %M", c->id, mg_print_ip_port, &c->rem));
  4207. LIST_ADD_HEAD(struct mg_connection, &lsn->mgr->conns, c);
  4208. c->is_accepted = 1;
  4209. c->is_hexdumping = lsn->is_hexdumping;
  4210. c->pfn = lsn->pfn;
  4211. c->loc = lsn->loc;
  4212. c->pfn_data = lsn->pfn_data;
  4213. c->fn = lsn->fn;
  4214. c->fn_data = lsn->fn_data;
  4215. mg_call(c, MG_EV_OPEN, NULL);
  4216. mg_call(c, MG_EV_ACCEPT, NULL);
  4217. return c;
  4218. }
  4219. static size_t trim_len(struct mg_connection *c, size_t len) {
  4220. struct mg_tcpip_if *ifp = c->mgr->ifp;
  4221. size_t eth_h_len = 14, ip_max_h_len = 24, tcp_max_h_len = 60, udp_h_len = 8;
  4222. size_t max_headers_len =
  4223. eth_h_len + ip_max_h_len + (c->is_udp ? udp_h_len : tcp_max_h_len);
  4224. size_t min_mtu = c->is_udp ? 68 /* RFC-791 */ : max_headers_len - eth_h_len;
  4225. // If the frame exceeds the available buffer, trim the length
  4226. if (len + max_headers_len > ifp->tx.len) {
  4227. len = ifp->tx.len - max_headers_len;
  4228. }
  4229. // Ensure the MTU isn't lower than the minimum allowed value
  4230. if (ifp->mtu < min_mtu) {
  4231. MG_ERROR(("MTU is lower than minimum, capping to %lu", min_mtu));
  4232. ifp->mtu = (uint16_t) min_mtu;
  4233. }
  4234. // If the total packet size exceeds the MTU, trim the length
  4235. if (len + max_headers_len - eth_h_len > ifp->mtu) {
  4236. len = ifp->mtu - max_headers_len + eth_h_len;
  4237. if (c->is_udp) {
  4238. MG_ERROR(("UDP datagram exceeds MTU. Truncating it."));
  4239. }
  4240. }
  4241. return len;
  4242. }
  4243. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  4244. struct mg_tcpip_if *ifp = c->mgr->ifp;
  4245. struct connstate *s = (struct connstate *) (c + 1);
  4246. uint32_t dst_ip = *(uint32_t *) c->rem.ip;
  4247. len = trim_len(c, len);
  4248. if (c->is_udp) {
  4249. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, dst_ip, c->rem.port, buf, len);
  4250. } else {
  4251. size_t sent =
  4252. tx_tcp(ifp, s->mac, dst_ip, TH_PUSH | TH_ACK, c->loc.port, c->rem.port,
  4253. mg_htonl(s->seq), mg_htonl(s->ack), buf, len);
  4254. if (sent == 0) {
  4255. return MG_IO_WAIT;
  4256. } else if (sent == (size_t) -1) {
  4257. return MG_IO_ERR;
  4258. } else {
  4259. s->seq += (uint32_t) len;
  4260. if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
  4261. }
  4262. }
  4263. return (long) len;
  4264. }
  4265. static void handle_tls_recv(struct mg_connection *c) {
  4266. size_t avail = mg_tls_pending(c);
  4267. size_t min = avail > MG_MAX_RECV_SIZE ? MG_MAX_RECV_SIZE : avail;
  4268. struct mg_iobuf *io = &c->recv;
  4269. if (io->size - io->len < min && !mg_iobuf_resize(io, io->len + min)) {
  4270. mg_error(c, "oom");
  4271. } else {
  4272. // Decrypt data directly into c->recv
  4273. long n = mg_tls_recv(c, &io->buf[io->len], io->size - io->len);
  4274. if (n == MG_IO_ERR) {
  4275. mg_error(c, "TLS recv error");
  4276. } else if (n > 0) {
  4277. // Decrypted successfully - trigger MG_EV_READ
  4278. io->len += (size_t) n;
  4279. mg_call(c, MG_EV_READ, &n);
  4280. } // else n < 0: outstanding data to be moved to c->recv
  4281. }
  4282. }
  4283. static void read_conn(struct mg_connection *c, struct pkt *pkt) {
  4284. struct connstate *s = (struct connstate *) (c + 1);
  4285. struct mg_iobuf *io = c->is_tls ? &c->rtls : &c->recv;
  4286. uint32_t seq = mg_ntohl(pkt->tcp->seq);
  4287. uint32_t rem_ip;
  4288. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4289. if (pkt->tcp->flags & TH_FIN) {
  4290. // If we initiated the closure, we reply with ACK upon receiving FIN
  4291. // If we didn't initiate it, we reply with FIN as part of the normal TCP
  4292. // closure process
  4293. uint8_t flags = TH_ACK;
  4294. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len + 1);
  4295. if (c->is_draining && s->ttype == MIP_TTYPE_FIN) {
  4296. if (s->seq == mg_htonl(pkt->tcp->ack)) { // Simultaneous closure ?
  4297. s->seq++; // Yes. Increment our SEQ
  4298. } else { // Otherwise,
  4299. s->seq = mg_htonl(pkt->tcp->ack); // Set to peer's ACK
  4300. }
  4301. } else {
  4302. flags |= TH_FIN;
  4303. c->is_draining = 1;
  4304. settmout(c, MIP_TTYPE_FIN);
  4305. }
  4306. tx_tcp(c->mgr->ifp, s->mac, rem_ip, flags, c->loc.port, c->rem.port,
  4307. mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4308. } else if (pkt->pay.len == 0) {
  4309. // TODO(cpq): handle this peer's ACK
  4310. } else if (seq != s->ack) {
  4311. uint32_t ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  4312. if (s->ack == ack) {
  4313. MG_VERBOSE(("ignoring duplicate pkt"));
  4314. } else {
  4315. MG_VERBOSE(("SEQ != ACK: %x %x %x", seq, s->ack, ack));
  4316. tx_tcp(c->mgr->ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4317. mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4318. }
  4319. } else if (io->size - io->len < pkt->pay.len &&
  4320. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  4321. mg_error(c, "oom");
  4322. } else {
  4323. // Copy TCP payload into the IO buffer. If the connection is plain text,
  4324. // we copy to c->recv. If the connection is TLS, this data is encrypted,
  4325. // therefore we copy that encrypted data to the c->rtls iobuffer instead,
  4326. // and then call mg_tls_recv() to decrypt it. NOTE: mg_tls_recv() will
  4327. // call back mg_io_recv() which grabs raw data from c->rtls
  4328. memcpy(&io->buf[io->len], pkt->pay.buf, pkt->pay.len);
  4329. io->len += pkt->pay.len;
  4330. MG_VERBOSE(("%lu SEQ %x -> %x", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  4331. // Advance ACK counter
  4332. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  4333. s->unacked += pkt->pay.len;
  4334. // size_t diff = s->acked <= s->ack ? s->ack - s->acked : s->ack;
  4335. if (s->unacked > MIP_TCP_WIN / 2 && s->acked != s->ack) {
  4336. // Send ACK immediately
  4337. MG_VERBOSE(("%lu imm ACK %lu", c->id, s->acked));
  4338. tx_tcp(c->mgr->ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4339. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  4340. s->unacked = 0;
  4341. s->acked = s->ack;
  4342. if (s->ttype != MIP_TTYPE_KEEPALIVE) settmout(c, MIP_TTYPE_KEEPALIVE);
  4343. } else {
  4344. // if not already running, setup a timer to send an ACK later
  4345. if (s->ttype != MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_ACK);
  4346. }
  4347. if (c->is_tls && c->is_tls_hs) {
  4348. mg_tls_handshake(c);
  4349. } else if (c->is_tls) {
  4350. handle_tls_recv(c);
  4351. } else {
  4352. // Plain text connection, data is already in c->recv, trigger MG_EV_READ
  4353. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4354. }
  4355. }
  4356. }
  4357. static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4358. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4359. struct connstate *s = c == NULL ? NULL : (struct connstate *) (c + 1);
  4360. #if 0
  4361. MG_INFO(("%lu %hhu %d", c ? c->id : 0, pkt->tcp->flags, (int) pkt->pay.len));
  4362. #endif
  4363. if (c != NULL && c->is_connecting && pkt->tcp->flags == (TH_SYN | TH_ACK)) {
  4364. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq) + 1;
  4365. tx_tcp_pkt(ifp, pkt, TH_ACK, pkt->tcp->ack, NULL, 0);
  4366. c->is_connecting = 0; // Client connected
  4367. settmout(c, MIP_TTYPE_KEEPALIVE);
  4368. mg_call(c, MG_EV_CONNECT, NULL); // Let user know
  4369. if (c->is_tls_hs) mg_tls_handshake(c);
  4370. } else if (c != NULL && c->is_connecting && pkt->tcp->flags != TH_ACK) {
  4371. // mg_hexdump(pkt->raw.buf, pkt->raw.len);
  4372. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4373. } else if (c != NULL && pkt->tcp->flags & TH_RST) {
  4374. mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  4375. } else if (c != NULL) {
  4376. #if 0
  4377. MG_DEBUG(("%lu %d %M:%hu -> %M:%hu", c->id, (int) pkt->raw.len,
  4378. mg_print_ip4, &pkt->ip->src, mg_ntohs(pkt->tcp->sport),
  4379. mg_print_ip4, &pkt->ip->dst, mg_ntohs(pkt->tcp->dport)));
  4380. mg_hexdump(pkt->pay.buf, pkt->pay.len);
  4381. #endif
  4382. s->tmiss = 0; // Reset missed keep-alive counter
  4383. if (s->ttype == MIP_TTYPE_KEEPALIVE) // Advance keep-alive timer
  4384. settmout(c,
  4385. MIP_TTYPE_KEEPALIVE); // unless a former ACK timeout is pending
  4386. read_conn(c, pkt); // Override timer with ACK timeout if needed
  4387. } else if ((c = getpeer(ifp->mgr, pkt, true)) == NULL) {
  4388. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4389. } else if (pkt->tcp->flags & TH_RST) {
  4390. if (c->is_accepted) mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  4391. // ignore RST if not connected
  4392. } else if (pkt->tcp->flags & TH_SYN) {
  4393. // Use peer's source port as ISN, in order to recognise the handshake
  4394. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(pkt->tcp->sport));
  4395. tx_tcp_pkt(ifp, pkt, TH_SYN | TH_ACK, isn, NULL, 0);
  4396. } else if (pkt->tcp->flags & TH_FIN) {
  4397. tx_tcp_pkt(ifp, pkt, TH_FIN | TH_ACK, pkt->tcp->ack, NULL, 0);
  4398. } else if (mg_htonl(pkt->tcp->ack) == mg_htons(pkt->tcp->sport) + 1U) {
  4399. accept_conn(c, pkt);
  4400. } else if (!c->is_accepted) { // no peer
  4401. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4402. } else {
  4403. // MG_VERBOSE(("dropped silently.."));
  4404. }
  4405. }
  4406. static void rx_ip(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4407. uint16_t frag = mg_ntohs(pkt->ip->frag);
  4408. if (frag & IP_MORE_FRAGS_MSK || frag & IP_FRAG_OFFSET_MSK) {
  4409. if (pkt->ip->proto == 17) pkt->udp = (struct udp *) (pkt->ip + 1);
  4410. if (pkt->ip->proto == 6) pkt->tcp = (struct tcp *) (pkt->ip + 1);
  4411. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4412. if (c) mg_error(c, "Received fragmented packet");
  4413. } else if (pkt->ip->proto == 1) {
  4414. pkt->icmp = (struct icmp *) (pkt->ip + 1);
  4415. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  4416. mkpay(pkt, pkt->icmp + 1);
  4417. rx_icmp(ifp, pkt);
  4418. } else if (pkt->ip->proto == 17) {
  4419. pkt->udp = (struct udp *) (pkt->ip + 1);
  4420. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  4421. mkpay(pkt, pkt->udp + 1);
  4422. MG_VERBOSE(("UDP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  4423. mg_ntohs(pkt->udp->sport), mg_print_ip4, &pkt->ip->dst,
  4424. mg_ntohs(pkt->udp->dport), (int) pkt->pay.len));
  4425. if (ifp->enable_dhcp_client && pkt->udp->dport == mg_htons(68)) {
  4426. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  4427. mkpay(pkt, pkt->dhcp + 1);
  4428. rx_dhcp_client(ifp, pkt);
  4429. } else if (ifp->enable_dhcp_server && pkt->udp->dport == mg_htons(67)) {
  4430. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  4431. mkpay(pkt, pkt->dhcp + 1);
  4432. rx_dhcp_server(ifp, pkt);
  4433. } else {
  4434. rx_udp(ifp, pkt);
  4435. }
  4436. } else if (pkt->ip->proto == 6) {
  4437. pkt->tcp = (struct tcp *) (pkt->ip + 1);
  4438. if (pkt->pay.len < sizeof(*pkt->tcp)) return;
  4439. mkpay(pkt, pkt->tcp + 1);
  4440. uint16_t iplen = mg_ntohs(pkt->ip->len);
  4441. uint16_t off = (uint16_t) (sizeof(*pkt->ip) + ((pkt->tcp->off >> 4) * 4U));
  4442. if (iplen >= off) pkt->pay.len = (size_t) (iplen - off);
  4443. MG_VERBOSE(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  4444. mg_ntohs(pkt->tcp->sport), mg_print_ip4, &pkt->ip->dst,
  4445. mg_ntohs(pkt->tcp->dport), (int) pkt->pay.len));
  4446. rx_tcp(ifp, pkt);
  4447. }
  4448. }
  4449. static void rx_ip6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4450. // MG_DEBUG(("IP %d", (int) len));
  4451. if (pkt->ip6->proto == 1 || pkt->ip6->proto == 58) {
  4452. pkt->icmp = (struct icmp *) (pkt->ip6 + 1);
  4453. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  4454. mkpay(pkt, pkt->icmp + 1);
  4455. rx_icmp(ifp, pkt);
  4456. } else if (pkt->ip6->proto == 17) {
  4457. pkt->udp = (struct udp *) (pkt->ip6 + 1);
  4458. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  4459. // MG_DEBUG((" UDP %u %u -> %u", len, mg_htons(udp->sport),
  4460. // mg_htons(udp->dport)));
  4461. mkpay(pkt, pkt->udp + 1);
  4462. }
  4463. }
  4464. static void mg_tcpip_rx(struct mg_tcpip_if *ifp, void *buf, size_t len) {
  4465. struct pkt pkt;
  4466. memset(&pkt, 0, sizeof(pkt));
  4467. pkt.raw.buf = (char *) buf;
  4468. pkt.raw.len = len;
  4469. pkt.eth = (struct eth *) buf;
  4470. // mg_hexdump(buf, len > 16 ? 16: len);
  4471. if (pkt.raw.len < sizeof(*pkt.eth)) return; // Truncated - runt?
  4472. if (ifp->enable_mac_check &&
  4473. memcmp(pkt.eth->dst, ifp->mac, sizeof(pkt.eth->dst)) != 0 &&
  4474. memcmp(pkt.eth->dst, broadcast, sizeof(pkt.eth->dst)) != 0)
  4475. return;
  4476. if (ifp->enable_crc32_check && len > 4) {
  4477. len -= 4; // TODO(scaprile): check on bigendian
  4478. uint32_t crc = mg_crc32(0, (const char *) buf, len);
  4479. if (memcmp((void *) ((size_t) buf + len), &crc, sizeof(crc))) return;
  4480. }
  4481. if (pkt.eth->type == mg_htons(0x806)) {
  4482. pkt.arp = (struct arp *) (pkt.eth + 1);
  4483. if (sizeof(*pkt.eth) + sizeof(*pkt.arp) > pkt.raw.len) return; // Truncated
  4484. mg_tcpip_call(ifp, MG_TCPIP_EV_ARP, &pkt.raw);
  4485. rx_arp(ifp, &pkt);
  4486. } else if (pkt.eth->type == mg_htons(0x86dd)) {
  4487. pkt.ip6 = (struct ip6 *) (pkt.eth + 1);
  4488. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip6)) return; // Truncated
  4489. if ((pkt.ip6->ver >> 4) != 0x6) return; // Not IP
  4490. mkpay(&pkt, pkt.ip6 + 1);
  4491. rx_ip6(ifp, &pkt);
  4492. } else if (pkt.eth->type == mg_htons(0x800)) {
  4493. pkt.ip = (struct ip *) (pkt.eth + 1);
  4494. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  4495. // Truncate frame to what IP header tells us
  4496. if ((size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth) < pkt.raw.len) {
  4497. pkt.raw.len = (size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth);
  4498. }
  4499. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  4500. if ((pkt.ip->ver >> 4) != 4) return; // Not IP
  4501. mkpay(&pkt, pkt.ip + 1);
  4502. rx_ip(ifp, &pkt);
  4503. } else {
  4504. MG_DEBUG(("Unknown eth type %x", mg_htons(pkt.eth->type)));
  4505. if (mg_log_level >= MG_LL_VERBOSE) mg_hexdump(buf, len >= 32 ? 32 : len);
  4506. }
  4507. }
  4508. static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t now) {
  4509. struct mg_connection *c;
  4510. bool expired_1000ms = mg_timer_expired(&ifp->timer_1000ms, 1000, now);
  4511. ifp->now = now;
  4512. if (expired_1000ms) {
  4513. #if MG_ENABLE_TCPIP_PRINT_DEBUG_STATS
  4514. const char *names[] = {"down", "up", "req", "ip", "ready"};
  4515. MG_INFO(("Status: %s, IP: %M, rx:%u, tx:%u, dr:%u, er:%u",
  4516. names[ifp->state], mg_print_ip4, &ifp->ip, ifp->nrecv, ifp->nsent,
  4517. ifp->ndrop, ifp->nerr));
  4518. #endif
  4519. }
  4520. // Handle gw ARP request timeout, order is important
  4521. if (expired_1000ms && ifp->state == MG_TCPIP_STATE_IP) {
  4522. ifp->state = MG_TCPIP_STATE_READY; // keep best-effort MAC
  4523. onstatechange(ifp);
  4524. }
  4525. // Handle physical interface up/down status
  4526. if (expired_1000ms && ifp->driver->up) {
  4527. bool up = ifp->driver->up(ifp);
  4528. bool current = ifp->state != MG_TCPIP_STATE_DOWN;
  4529. if (!up && ifp->enable_dhcp_client) ifp->ip = 0;
  4530. if (up != current) { // link state has changed
  4531. ifp->state = up == false ? MG_TCPIP_STATE_DOWN
  4532. : ifp->enable_dhcp_client || ifp->ip == 0
  4533. ? MG_TCPIP_STATE_UP
  4534. : MG_TCPIP_STATE_IP;
  4535. onstatechange(ifp);
  4536. } else if (!ifp->enable_dhcp_client && ifp->state == MG_TCPIP_STATE_UP &&
  4537. ifp->ip) {
  4538. ifp->state = MG_TCPIP_STATE_IP; // ifp->fn has set an IP
  4539. onstatechange(ifp);
  4540. }
  4541. if (ifp->state == MG_TCPIP_STATE_DOWN) MG_ERROR(("Network is down"));
  4542. mg_tcpip_call(ifp, MG_TCPIP_EV_TIMER_1S, NULL);
  4543. }
  4544. if (ifp->state == MG_TCPIP_STATE_DOWN) return;
  4545. // DHCP RFC-2131 (4.4)
  4546. if (ifp->enable_dhcp_client && expired_1000ms) {
  4547. if (ifp->state == MG_TCPIP_STATE_UP) {
  4548. tx_dhcp_discover(ifp); // INIT (4.4.1)
  4549. } else if (ifp->state == MG_TCPIP_STATE_READY &&
  4550. ifp->lease_expire > 0) { // BOUND / RENEWING / REBINDING
  4551. if (ifp->now >= ifp->lease_expire) {
  4552. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0; // expired, release IP
  4553. onstatechange(ifp);
  4554. } else if (ifp->now + 30UL * 60UL * 1000UL > ifp->lease_expire &&
  4555. ((ifp->now / 1000) % 60) == 0) {
  4556. // hack: 30 min before deadline, try to rebind (4.3.6) every min
  4557. tx_dhcp_request_re(ifp, (uint8_t *) broadcast, ifp->ip, 0xffffffff);
  4558. } // TODO(): Handle T1 (RENEWING) and T2 (REBINDING) (4.4.5)
  4559. }
  4560. }
  4561. // Read data from the network
  4562. if (ifp->driver->rx != NULL) { // Polling driver. We must call it
  4563. size_t len =
  4564. ifp->driver->rx(ifp->recv_queue.buf, ifp->recv_queue.size, ifp);
  4565. if (len > 0) {
  4566. ifp->nrecv++;
  4567. mg_tcpip_rx(ifp, ifp->recv_queue.buf, len);
  4568. }
  4569. } else { // Interrupt-based driver. Fills recv queue itself
  4570. char *buf;
  4571. size_t len = mg_queue_next(&ifp->recv_queue, &buf);
  4572. if (len > 0) {
  4573. mg_tcpip_rx(ifp, buf, len);
  4574. mg_queue_del(&ifp->recv_queue, len);
  4575. }
  4576. }
  4577. // Process timeouts
  4578. for (c = ifp->mgr->conns; c != NULL; c = c->next) {
  4579. if ((c->is_udp && !c->is_arplooking) || c->is_listening || c->is_resolving)
  4580. continue;
  4581. struct connstate *s = (struct connstate *) (c + 1);
  4582. uint32_t rem_ip;
  4583. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4584. if (now > s->timer) {
  4585. if (s->ttype == MIP_TTYPE_ARP) {
  4586. mg_error(c, "ARP timeout");
  4587. } else if (c->is_udp) {
  4588. continue;
  4589. } else if (s->ttype == MIP_TTYPE_ACK && s->acked != s->ack) {
  4590. MG_VERBOSE(("%lu ack %x %x", c->id, s->seq, s->ack));
  4591. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4592. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  4593. s->acked = s->ack;
  4594. } else if (s->ttype == MIP_TTYPE_SYN) {
  4595. mg_error(c, "Connection timeout");
  4596. } else if (s->ttype == MIP_TTYPE_FIN) {
  4597. c->is_closing = 1;
  4598. continue;
  4599. } else {
  4600. if (s->tmiss++ > 2) {
  4601. mg_error(c, "keepalive");
  4602. } else {
  4603. MG_VERBOSE(("%lu keepalive", c->id));
  4604. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4605. mg_htonl(s->seq - 1), mg_htonl(s->ack), NULL, 0);
  4606. }
  4607. }
  4608. settmout(c, MIP_TTYPE_KEEPALIVE);
  4609. }
  4610. }
  4611. }
  4612. // This function executes in interrupt context, thus it should copy data
  4613. // somewhere fast. Note that newlib's malloc is not thread safe, thus use
  4614. // our lock-free queue with preallocated buffer to copy data and return asap
  4615. void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) {
  4616. char *p;
  4617. if (mg_queue_book(&ifp->recv_queue, &p, len) >= len) {
  4618. memcpy(p, buf, len);
  4619. mg_queue_add(&ifp->recv_queue, len);
  4620. ifp->nrecv++;
  4621. } else {
  4622. ifp->ndrop++;
  4623. }
  4624. }
  4625. void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
  4626. // If MAC address is not set, make a random one
  4627. if (ifp->mac[0] == 0 && ifp->mac[1] == 0 && ifp->mac[2] == 0 &&
  4628. ifp->mac[3] == 0 && ifp->mac[4] == 0 && ifp->mac[5] == 0) {
  4629. ifp->mac[0] = 0x02; // Locally administered, unicast
  4630. mg_random(&ifp->mac[1], sizeof(ifp->mac) - 1);
  4631. MG_INFO(("MAC not set. Generated random: %M", mg_print_mac, ifp->mac));
  4632. }
  4633. if (ifp->driver->init && !ifp->driver->init(ifp)) {
  4634. MG_ERROR(("driver init failed"));
  4635. } else {
  4636. size_t framesize = 1540;
  4637. ifp->tx.buf = (char *) calloc(1, framesize), ifp->tx.len = framesize;
  4638. if (ifp->recv_queue.size == 0)
  4639. ifp->recv_queue.size = ifp->driver->rx ? framesize : 8192;
  4640. ifp->recv_queue.buf = (char *) calloc(1, ifp->recv_queue.size);
  4641. ifp->timer_1000ms = mg_millis();
  4642. mgr->ifp = ifp;
  4643. ifp->mgr = mgr;
  4644. ifp->mtu = MG_TCPIP_MTU_DEFAULT;
  4645. mgr->extraconnsize = sizeof(struct connstate);
  4646. if (ifp->ip == 0) ifp->enable_dhcp_client = true;
  4647. memset(ifp->gwmac, 255, sizeof(ifp->gwmac)); // Set best-effort to bcast
  4648. mg_random(&ifp->eport, sizeof(ifp->eport)); // Random from 0 to 65535
  4649. ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
  4650. // MG_EPHEMERAL_PORT_BASE to 65535
  4651. if (ifp->tx.buf == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
  4652. }
  4653. }
  4654. void mg_tcpip_free(struct mg_tcpip_if *ifp) {
  4655. free(ifp->recv_queue.buf);
  4656. free(ifp->tx.buf);
  4657. }
  4658. static void send_syn(struct mg_connection *c) {
  4659. struct connstate *s = (struct connstate *) (c + 1);
  4660. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(c->loc.port));
  4661. uint32_t rem_ip;
  4662. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4663. tx_tcp(c->mgr->ifp, s->mac, rem_ip, TH_SYN, c->loc.port, c->rem.port, isn, 0,
  4664. NULL, 0);
  4665. }
  4666. static void mac_resolved(struct mg_connection *c) {
  4667. if (c->is_udp) {
  4668. c->is_connecting = 0;
  4669. mg_call(c, MG_EV_CONNECT, NULL);
  4670. } else {
  4671. send_syn(c);
  4672. settmout(c, MIP_TTYPE_SYN);
  4673. }
  4674. }
  4675. void mg_connect_resolved(struct mg_connection *c) {
  4676. struct mg_tcpip_if *ifp = c->mgr->ifp;
  4677. uint32_t rem_ip;
  4678. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4679. c->is_resolving = 0;
  4680. if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
  4681. memcpy(c->loc.ip, &ifp->ip, sizeof(uint32_t));
  4682. c->loc.port = mg_htons(ifp->eport++);
  4683. MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
  4684. &c->rem));
  4685. mg_call(c, MG_EV_RESOLVE, NULL);
  4686. c->is_connecting = 1;
  4687. if (c->is_udp && (rem_ip == 0xffffffff || rem_ip == (ifp->ip | ~ifp->mask))) {
  4688. struct connstate *s = (struct connstate *) (c + 1);
  4689. memset(s->mac, 0xFF, sizeof(s->mac)); // global or local broadcast
  4690. mac_resolved(c);
  4691. } else if (ifp->ip && ((rem_ip & ifp->mask) == (ifp->ip & ifp->mask)) &&
  4692. rem_ip != ifp->gw) { // skip if gw (onstatechange -> READY -> ARP)
  4693. // If we're in the same LAN, fire an ARP lookup.
  4694. MG_DEBUG(("%lu ARP lookup...", c->id));
  4695. mg_tcpip_arp_request(ifp, rem_ip, NULL);
  4696. settmout(c, MIP_TTYPE_ARP);
  4697. c->is_arplooking = 1;
  4698. } else if ((*((uint8_t *) &rem_ip) & 0xE0) == 0xE0) {
  4699. struct connstate *s = (struct connstate *) (c + 1); // 224 to 239, E0 to EF
  4700. uint8_t mcastp[3] = {0x01, 0x00, 0x5E}; // multicast group
  4701. memcpy(s->mac, mcastp, 3);
  4702. memcpy(s->mac + 3, ((uint8_t *) &rem_ip) + 1, 3); // 23 LSb
  4703. s->mac[3] &= 0x7F;
  4704. mac_resolved(c);
  4705. } else {
  4706. struct connstate *s = (struct connstate *) (c + 1);
  4707. memcpy(s->mac, ifp->gwmac, sizeof(ifp->gwmac));
  4708. mac_resolved(c);
  4709. }
  4710. }
  4711. bool mg_open_listener(struct mg_connection *c, const char *url) {
  4712. c->loc.port = mg_htons(mg_url_port(url));
  4713. return true;
  4714. }
  4715. static void write_conn(struct mg_connection *c) {
  4716. long len = c->is_tls ? mg_tls_send(c, c->send.buf, c->send.len)
  4717. : mg_io_send(c, c->send.buf, c->send.len);
  4718. if (len == MG_IO_ERR) {
  4719. mg_error(c, "tx err");
  4720. } else if (len > 0) {
  4721. mg_iobuf_del(&c->send, 0, (size_t) len);
  4722. mg_call(c, MG_EV_WRITE, &len);
  4723. }
  4724. }
  4725. static void init_closure(struct mg_connection *c) {
  4726. struct connstate *s = (struct connstate *) (c + 1);
  4727. if (c->is_udp == false && c->is_listening == false &&
  4728. c->is_connecting == false) { // For TCP conns,
  4729. uint32_t rem_ip;
  4730. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4731. tx_tcp(c->mgr->ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port,
  4732. c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  4733. settmout(c, MIP_TTYPE_FIN);
  4734. }
  4735. }
  4736. static void close_conn(struct mg_connection *c) {
  4737. struct connstate *s = (struct connstate *) (c + 1);
  4738. mg_iobuf_free(&s->raw); // For TLS connections, release raw data
  4739. mg_close_conn(c);
  4740. }
  4741. static bool can_write(struct mg_connection *c) {
  4742. return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 &&
  4743. c->is_tls_hs == 0 && c->is_arplooking == 0;
  4744. }
  4745. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  4746. struct mg_connection *c, *tmp;
  4747. uint64_t now = mg_millis();
  4748. mg_timer_poll(&mgr->timers, now);
  4749. if (mgr->ifp == NULL || mgr->ifp->driver == NULL) return;
  4750. mg_tcpip_poll(mgr->ifp, now);
  4751. for (c = mgr->conns; c != NULL; c = tmp) {
  4752. tmp = c->next;
  4753. struct connstate *s = (struct connstate *) (c + 1);
  4754. mg_call(c, MG_EV_POLL, &now);
  4755. MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't',
  4756. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  4757. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  4758. if (c->is_tls && mg_tls_pending(c) > 0) handle_tls_recv(c);
  4759. if (can_write(c)) write_conn(c);
  4760. if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN)
  4761. init_closure(c);
  4762. if (c->is_closing) close_conn(c);
  4763. }
  4764. (void) ms;
  4765. }
  4766. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  4767. struct mg_tcpip_if *ifp = c->mgr->ifp;
  4768. bool res = false;
  4769. uint32_t rem_ip;
  4770. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4771. if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) {
  4772. mg_error(c, "net down");
  4773. } else if (c->is_udp && (c->is_arplooking || c->is_resolving)) {
  4774. // Fail to send, no target MAC or IP
  4775. MG_VERBOSE(("still resolving..."));
  4776. } else if (c->is_udp) {
  4777. struct connstate *s = (struct connstate *) (c + 1);
  4778. len = trim_len(c, len); // Trimming length if necessary
  4779. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len);
  4780. res = true;
  4781. } else {
  4782. res = mg_iobuf_add(&c->send, c->send.len, buf, len);
  4783. }
  4784. return res;
  4785. }
  4786. #endif // MG_ENABLE_TCPIP
  4787. #ifdef MG_ENABLE_LINES
  4788. #line 1 "src/ota_ch32v307.c"
  4789. #endif
  4790. #if MG_OTA == MG_OTA_CH32V307
  4791. // RM: https://www.wch-ic.com/downloads/CH32FV2x_V3xRM_PDF.html
  4792. static bool mg_ch32v307_write(void *, const void *, size_t);
  4793. static bool mg_ch32v307_swap(void);
  4794. static struct mg_flash s_mg_flash_ch32v307 = {
  4795. (void *) 0x08000000, // Start
  4796. 480 * 1024, // Size, first 320k is 0-wait
  4797. 4 * 1024, // Sector size, 4k
  4798. 4, // Align, 32 bit
  4799. mg_ch32v307_write,
  4800. mg_ch32v307_swap,
  4801. };
  4802. #define FLASH_BASE 0x40022000
  4803. #define FLASH_ACTLR (FLASH_BASE + 0)
  4804. #define FLASH_KEYR (FLASH_BASE + 4)
  4805. #define FLASH_OBKEYR (FLASH_BASE + 8)
  4806. #define FLASH_STATR (FLASH_BASE + 12)
  4807. #define FLASH_CTLR (FLASH_BASE + 16)
  4808. #define FLASH_ADDR (FLASH_BASE + 20)
  4809. #define FLASH_OBR (FLASH_BASE + 28)
  4810. #define FLASH_WPR (FLASH_BASE + 32)
  4811. MG_IRAM static void flash_unlock(void) {
  4812. static bool unlocked;
  4813. if (unlocked == false) {
  4814. MG_REG(FLASH_KEYR) = 0x45670123;
  4815. MG_REG(FLASH_KEYR) = 0xcdef89ab;
  4816. unlocked = true;
  4817. }
  4818. }
  4819. MG_IRAM static void flash_wait(void) {
  4820. while (MG_REG(FLASH_STATR) & MG_BIT(0)) (void) 0;
  4821. }
  4822. MG_IRAM static void mg_ch32v307_erase(void *addr) {
  4823. // MG_INFO(("%p", addr));
  4824. flash_unlock();
  4825. flash_wait();
  4826. MG_REG(FLASH_ADDR) = (uint32_t) addr;
  4827. MG_REG(FLASH_CTLR) |= MG_BIT(1) | MG_BIT(6); // PER | STRT;
  4828. flash_wait();
  4829. }
  4830. MG_IRAM static bool is_page_boundary(const void *addr) {
  4831. uint32_t val = (uint32_t) addr;
  4832. return (val & (s_mg_flash_ch32v307.secsz - 1)) == 0;
  4833. }
  4834. MG_IRAM static bool mg_ch32v307_write(void *addr, const void *buf, size_t len) {
  4835. // MG_INFO(("%p %p %lu", addr, buf, len));
  4836. // mg_hexdump(buf, len);
  4837. flash_unlock();
  4838. const uint16_t *src = (uint16_t *) buf, *end = &src[len / 2];
  4839. uint16_t *dst = (uint16_t *) addr;
  4840. MG_REG(FLASH_CTLR) |= MG_BIT(0); // Set PG
  4841. // MG_INFO(("CTLR: %#lx", MG_REG(FLASH_CTLR)));
  4842. while (src < end) {
  4843. if (is_page_boundary(dst)) mg_ch32v307_erase(dst);
  4844. *dst++ = *src++;
  4845. flash_wait();
  4846. }
  4847. MG_REG(FLASH_CTLR) &= ~MG_BIT(0); // Clear PG
  4848. return true;
  4849. }
  4850. MG_IRAM bool mg_ch32v307_swap(void) {
  4851. return true;
  4852. }
  4853. // just overwrite instead of swap
  4854. MG_IRAM static void single_bank_swap(char *p1, char *p2, size_t s, size_t ss) {
  4855. // no stdlib calls here
  4856. for (size_t ofs = 0; ofs < s; ofs += ss) {
  4857. mg_ch32v307_write(p1 + ofs, p2 + ofs, ss);
  4858. }
  4859. *((volatile uint32_t *) 0xbeef0000) |= 1U << 7; // NVIC_SystemReset()
  4860. }
  4861. bool mg_ota_begin(size_t new_firmware_size) {
  4862. return mg_ota_flash_begin(new_firmware_size, &s_mg_flash_ch32v307);
  4863. }
  4864. bool mg_ota_write(const void *buf, size_t len) {
  4865. return mg_ota_flash_write(buf, len, &s_mg_flash_ch32v307);
  4866. }
  4867. bool mg_ota_end(void) {
  4868. if (mg_ota_flash_end(&s_mg_flash_ch32v307)) {
  4869. // Swap partitions. Pray power does not go away
  4870. MG_INFO(("Swapping partitions, size %u (%u sectors)",
  4871. s_mg_flash_ch32v307.size,
  4872. s_mg_flash_ch32v307.size / s_mg_flash_ch32v307.secsz));
  4873. MG_INFO(("Do NOT power off..."));
  4874. mg_log_level = MG_LL_NONE;
  4875. // TODO() disable IRQ, s_flash_irq_disabled = true;
  4876. // Runs in RAM, will reset when finished
  4877. single_bank_swap(
  4878. (char *) s_mg_flash_ch32v307.start,
  4879. (char *) s_mg_flash_ch32v307.start + s_mg_flash_ch32v307.size / 2,
  4880. s_mg_flash_ch32v307.size / 2, s_mg_flash_ch32v307.secsz);
  4881. }
  4882. return false;
  4883. }
  4884. #endif
  4885. #ifdef MG_ENABLE_LINES
  4886. #line 1 "src/ota_dummy.c"
  4887. #endif
  4888. #if MG_OTA == MG_OTA_NONE
  4889. bool mg_ota_begin(size_t new_firmware_size) {
  4890. (void) new_firmware_size;
  4891. return true;
  4892. }
  4893. bool mg_ota_write(const void *buf, size_t len) {
  4894. (void) buf, (void) len;
  4895. return true;
  4896. }
  4897. bool mg_ota_end(void) {
  4898. return true;
  4899. }
  4900. #endif
  4901. #ifdef MG_ENABLE_LINES
  4902. #line 1 "src/ota_esp32.c"
  4903. #endif
  4904. #if MG_ARCH == MG_ARCH_ESP32 && MG_OTA == MG_OTA_ESP32
  4905. static const esp_partition_t *s_ota_update_partition;
  4906. static esp_ota_handle_t s_ota_update_handle;
  4907. static bool s_ota_success;
  4908. // Those empty macros do nothing, but mark places in the code which could
  4909. // potentially trigger a watchdog reboot due to the log flash erase operation
  4910. #define disable_wdt()
  4911. #define enable_wdt()
  4912. bool mg_ota_begin(size_t new_firmware_size) {
  4913. if (s_ota_update_partition != NULL) {
  4914. MG_ERROR(("Update in progress. Call mg_ota_end() ?"));
  4915. return false;
  4916. } else {
  4917. s_ota_success = false;
  4918. disable_wdt();
  4919. s_ota_update_partition = esp_ota_get_next_update_partition(NULL);
  4920. esp_err_t err = esp_ota_begin(s_ota_update_partition, new_firmware_size,
  4921. &s_ota_update_handle);
  4922. enable_wdt();
  4923. MG_DEBUG(("esp_ota_begin(): %d", err));
  4924. s_ota_success = (err == ESP_OK);
  4925. }
  4926. return s_ota_success;
  4927. }
  4928. bool mg_ota_write(const void *buf, size_t len) {
  4929. disable_wdt();
  4930. esp_err_t err = esp_ota_write(s_ota_update_handle, buf, len);
  4931. enable_wdt();
  4932. MG_INFO(("esp_ota_write(): %d", err));
  4933. s_ota_success = err == ESP_OK;
  4934. return s_ota_success;
  4935. }
  4936. bool mg_ota_end(void) {
  4937. esp_err_t err = esp_ota_end(s_ota_update_handle);
  4938. MG_DEBUG(("esp_ota_end(%p): %d", s_ota_update_handle, err));
  4939. if (s_ota_success && err == ESP_OK) {
  4940. err = esp_ota_set_boot_partition(s_ota_update_partition);
  4941. s_ota_success = (err == ESP_OK);
  4942. }
  4943. MG_DEBUG(("Finished ESP32 OTA, success: %d", s_ota_success));
  4944. s_ota_update_partition = NULL;
  4945. return s_ota_success;
  4946. }
  4947. #endif
  4948. #ifdef MG_ENABLE_LINES
  4949. #line 1 "src/ota_imxrt.c"
  4950. #endif
  4951. #if MG_OTA >= MG_OTA_RT1020 && MG_OTA <= MG_OTA_RT1170
  4952. static bool mg_imxrt_write(void *, const void *, size_t);
  4953. static bool mg_imxrt_swap(void);
  4954. #if MG_OTA <= MG_OTA_RT1060
  4955. #define MG_IMXRT_FLASH_START 0x60000000
  4956. #define FLEXSPI_NOR_INSTANCE 0
  4957. #elif MG_OTA == MG_OTA_RT1064
  4958. #define MG_IMXRT_FLASH_START 0x70000000
  4959. #define FLEXSPI_NOR_INSTANCE 1
  4960. #else // RT1170
  4961. #define MG_IMXRT_FLASH_START 0x30000000
  4962. #define FLEXSPI_NOR_INSTANCE 1
  4963. #endif
  4964. // TODO(): fill at init, support more devices in a dynamic way
  4965. // TODO(): then, check alignment is <= 256, see Wizard's #251
  4966. static struct mg_flash s_mg_flash_imxrt = {
  4967. (void *) MG_IMXRT_FLASH_START, // Start,
  4968. 4 * 1024 * 1024, // Size, 4mb
  4969. 4 * 1024, // Sector size, 4k
  4970. 256, // Align,
  4971. mg_imxrt_write,
  4972. mg_imxrt_swap,
  4973. };
  4974. struct mg_flexspi_lut_seq {
  4975. uint8_t seqNum;
  4976. uint8_t seqId;
  4977. uint16_t reserved;
  4978. };
  4979. struct mg_flexspi_mem_config {
  4980. uint32_t tag;
  4981. uint32_t version;
  4982. uint32_t reserved0;
  4983. uint8_t readSampleClkSrc;
  4984. uint8_t csHoldTime;
  4985. uint8_t csSetupTime;
  4986. uint8_t columnAddressWidth;
  4987. uint8_t deviceModeCfgEnable;
  4988. uint8_t deviceModeType;
  4989. uint16_t waitTimeCfgCommands;
  4990. struct mg_flexspi_lut_seq deviceModeSeq;
  4991. uint32_t deviceModeArg;
  4992. uint8_t configCmdEnable;
  4993. uint8_t configModeType[3];
  4994. struct mg_flexspi_lut_seq configCmdSeqs[3];
  4995. uint32_t reserved1;
  4996. uint32_t configCmdArgs[3];
  4997. uint32_t reserved2;
  4998. uint32_t controllerMiscOption;
  4999. uint8_t deviceType;
  5000. uint8_t sflashPadType;
  5001. uint8_t serialClkFreq;
  5002. uint8_t lutCustomSeqEnable;
  5003. uint32_t reserved3[2];
  5004. uint32_t sflashA1Size;
  5005. uint32_t sflashA2Size;
  5006. uint32_t sflashB1Size;
  5007. uint32_t sflashB2Size;
  5008. uint32_t csPadSettingOverride;
  5009. uint32_t sclkPadSettingOverride;
  5010. uint32_t dataPadSettingOverride;
  5011. uint32_t dqsPadSettingOverride;
  5012. uint32_t timeoutInMs;
  5013. uint32_t commandInterval;
  5014. uint16_t dataValidTime[2];
  5015. uint16_t busyOffset;
  5016. uint16_t busyBitPolarity;
  5017. uint32_t lookupTable[64];
  5018. struct mg_flexspi_lut_seq lutCustomSeq[12];
  5019. uint32_t reserved4[4];
  5020. };
  5021. struct mg_flexspi_nor_config {
  5022. struct mg_flexspi_mem_config memConfig;
  5023. uint32_t pageSize;
  5024. uint32_t sectorSize;
  5025. uint8_t ipcmdSerialClkFreq;
  5026. uint8_t isUniformBlockSize;
  5027. uint8_t reserved0[2];
  5028. uint8_t serialNorType;
  5029. uint8_t needExitNoCmdMode;
  5030. uint8_t halfClkForNonReadCmd;
  5031. uint8_t needRestoreNoCmdMode;
  5032. uint32_t blockSize;
  5033. uint32_t reserve2[11];
  5034. };
  5035. /* FLEXSPI memory config block related defintions */
  5036. #define MG_FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian
  5037. #define MG_FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0
  5038. #define MG_FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \
  5039. (MG_FLEXSPI_LUT_OPERAND0(op0) | MG_FLEXSPI_LUT_NUM_PADS0(pad0) | \
  5040. MG_FLEXSPI_LUT_OPCODE0(cmd0) | MG_FLEXSPI_LUT_OPERAND1(op1) | \
  5041. MG_FLEXSPI_LUT_NUM_PADS1(pad1) | MG_FLEXSPI_LUT_OPCODE1(cmd1))
  5042. #define MG_CMD_SDR 0x01
  5043. #define MG_CMD_DDR 0x21
  5044. #define MG_DUMMY_SDR 0x0C
  5045. #define MG_DUMMY_DDR 0x2C
  5046. #define MG_RADDR_SDR 0x02
  5047. #define MG_RADDR_DDR 0x22
  5048. #define MG_READ_SDR 0x09
  5049. #define MG_READ_DDR 0x29
  5050. #define MG_WRITE_SDR 0x08
  5051. #define MG_WRITE_DDR 0x28
  5052. #define MG_STOP 0
  5053. #define MG_FLEXSPI_1PAD 0
  5054. #define MG_FLEXSPI_2PAD 1
  5055. #define MG_FLEXSPI_4PAD 2
  5056. #define MG_FLEXSPI_8PAD 3
  5057. #define MG_FLEXSPI_QSPI_LUT \
  5058. { \
  5059. [0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0xEB, MG_RADDR_SDR, \
  5060. MG_FLEXSPI_4PAD, 0x18), \
  5061. [1] = MG_FLEXSPI_LUT_SEQ(MG_DUMMY_SDR, MG_FLEXSPI_4PAD, 0x06, MG_READ_SDR, \
  5062. MG_FLEXSPI_4PAD, 0x04), \
  5063. [4 * 1 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x05, \
  5064. MG_READ_SDR, MG_FLEXSPI_1PAD, 0x04), \
  5065. [4 * 3 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x06, \
  5066. MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  5067. [4 * 5 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x20, \
  5068. MG_RADDR_SDR, MG_FLEXSPI_1PAD, 0x18), \
  5069. [4 * 8 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0xD8, \
  5070. MG_RADDR_SDR, MG_FLEXSPI_1PAD, 0x18), \
  5071. [4 * 9 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x02, \
  5072. MG_RADDR_SDR, MG_FLEXSPI_1PAD, 0x18), \
  5073. [4 * 9 + 1] = MG_FLEXSPI_LUT_SEQ(MG_WRITE_SDR, MG_FLEXSPI_1PAD, 0x04, \
  5074. MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  5075. [4 * 11 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x60, \
  5076. MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  5077. }
  5078. #define MG_FLEXSPI_LUT_OPERAND0(x) (((uint32_t) (((uint32_t) (x)))) & 0xFFU)
  5079. #define MG_FLEXSPI_LUT_NUM_PADS0(x) \
  5080. (((uint32_t) (((uint32_t) (x)) << 8U)) & 0x300U)
  5081. #define MG_FLEXSPI_LUT_OPCODE0(x) \
  5082. (((uint32_t) (((uint32_t) (x)) << 10U)) & 0xFC00U)
  5083. #define MG_FLEXSPI_LUT_OPERAND1(x) \
  5084. (((uint32_t) (((uint32_t) (x)) << 16U)) & 0xFF0000U)
  5085. #define MG_FLEXSPI_LUT_NUM_PADS1(x) \
  5086. (((uint32_t) (((uint32_t) (x)) << 24U)) & 0x3000000U)
  5087. #define MG_FLEXSPI_LUT_OPCODE1(x) \
  5088. (((uint32_t) (((uint32_t) (x)) << 26U)) & 0xFC000000U)
  5089. #if MG_OTA == MG_OTA_RT1020
  5090. // RT102X boards support ROM API version 1.4
  5091. struct mg_flexspi_nor_driver_interface {
  5092. uint32_t version;
  5093. int (*init)(uint32_t instance, struct mg_flexspi_nor_config *config);
  5094. int (*program)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5095. uint32_t dst_addr, const uint32_t *src);
  5096. uint32_t reserved;
  5097. int (*erase)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5098. uint32_t start, uint32_t lengthInBytes);
  5099. uint32_t reserved2;
  5100. int (*update_lut)(uint32_t instance, uint32_t seqIndex,
  5101. const uint32_t *lutBase, uint32_t seqNumber);
  5102. int (*xfer)(uint32_t instance, char *xfer);
  5103. void (*clear_cache)(uint32_t instance);
  5104. };
  5105. #elif MG_OTA <= MG_OTA_RT1064
  5106. // RT104x and RT106x support ROM API version 1.5
  5107. struct mg_flexspi_nor_driver_interface {
  5108. uint32_t version;
  5109. int (*init)(uint32_t instance, struct mg_flexspi_nor_config *config);
  5110. int (*program)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5111. uint32_t dst_addr, const uint32_t *src);
  5112. int (*erase_all)(uint32_t instance, struct mg_flexspi_nor_config *config);
  5113. int (*erase)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5114. uint32_t start, uint32_t lengthInBytes);
  5115. int (*read)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5116. uint32_t *dst, uint32_t addr, uint32_t lengthInBytes);
  5117. void (*clear_cache)(uint32_t instance);
  5118. int (*xfer)(uint32_t instance, char *xfer);
  5119. int (*update_lut)(uint32_t instance, uint32_t seqIndex,
  5120. const uint32_t *lutBase, uint32_t seqNumber);
  5121. int (*get_config)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5122. uint32_t *option);
  5123. };
  5124. #else
  5125. // RT117x support ROM API version 1.7
  5126. struct mg_flexspi_nor_driver_interface {
  5127. uint32_t version;
  5128. int (*init)(uint32_t instance, struct mg_flexspi_nor_config *config);
  5129. int (*program)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5130. uint32_t dst_addr, const uint32_t *src);
  5131. int (*erase_all)(uint32_t instance, struct mg_flexspi_nor_config *config);
  5132. int (*erase)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5133. uint32_t start, uint32_t lengthInBytes);
  5134. int (*read)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5135. uint32_t *dst, uint32_t addr, uint32_t lengthInBytes);
  5136. uint32_t reserved;
  5137. int (*xfer)(uint32_t instance, char *xfer);
  5138. int (*update_lut)(uint32_t instance, uint32_t seqIndex,
  5139. const uint32_t *lutBase, uint32_t seqNumber);
  5140. int (*get_config)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5141. uint32_t *option);
  5142. int (*erase_sector)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5143. uint32_t address);
  5144. int (*erase_block)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5145. uint32_t address);
  5146. void (*hw_reset)(uint32_t instance, uint32_t resetLogic);
  5147. int (*wait_busy)(uint32_t instance, struct mg_flexspi_nor_config *config,
  5148. bool isParallelMode, uint32_t address);
  5149. int (*set_clock_source)(uint32_t instance, uint32_t clockSrc);
  5150. void (*config_clock)(uint32_t instance, uint32_t freqOption,
  5151. uint32_t sampleClkMode);
  5152. };
  5153. #endif
  5154. #if MG_OTA <= MG_OTA_RT1064
  5155. #define MG_FLEXSPI_BASE 0x402A8000
  5156. #define flexspi_nor \
  5157. (*((struct mg_flexspi_nor_driver_interface **) (*(uint32_t *) 0x0020001c + \
  5158. 16)))
  5159. #else
  5160. #define MG_FLEXSPI_BASE 0x400CC000
  5161. #define flexspi_nor \
  5162. (*((struct mg_flexspi_nor_driver_interface **) (*(uint32_t *) 0x0021001c + \
  5163. 12)))
  5164. #endif
  5165. static bool s_flash_irq_disabled;
  5166. MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
  5167. char *base = (char *) s_mg_flash_imxrt.start, *end = base + s_mg_flash_imxrt.size;
  5168. volatile char *p = (char *) dst;
  5169. return p >= base && p < end && ((p - base) % s_mg_flash_imxrt.secsz) == 0;
  5170. }
  5171. // Note: the get_config function below works both for RT1020 and 1060
  5172. // must reside in RAM, as flash will be erased
  5173. static struct mg_flexspi_nor_config default_config = {
  5174. .memConfig = {.tag = MG_FLEXSPI_CFG_BLK_TAG,
  5175. .version = MG_FLEXSPI_CFG_BLK_VERSION,
  5176. .readSampleClkSrc = 1, // ReadSampleClk_LoopbackFromDqsPad
  5177. .csHoldTime = 3,
  5178. .csSetupTime = 3,
  5179. .controllerMiscOption = MG_BIT(4),
  5180. .deviceType = 1, // serial NOR
  5181. .sflashPadType = 4,
  5182. .serialClkFreq = 7, // 133MHz
  5183. .sflashA1Size = 8 * 1024 * 1024,
  5184. .lookupTable = MG_FLEXSPI_QSPI_LUT},
  5185. .pageSize = 256,
  5186. .sectorSize = 4 * 1024,
  5187. .ipcmdSerialClkFreq = 1,
  5188. .blockSize = 64 * 1024,
  5189. .isUniformBlockSize = false
  5190. };
  5191. MG_IRAM static int flexspi_nor_get_config(
  5192. struct mg_flexspi_nor_config **config) {
  5193. *config = &default_config;
  5194. return 0;
  5195. }
  5196. #if 0
  5197. // ROM API get_config call (ROM version >= 1.5)
  5198. MG_IRAM static int flexspi_nor_get_config(
  5199. struct mg_flexspi_nor_config **config) {
  5200. uint32_t options[] = {0xc0000000, 0x00};
  5201. MG_ARM_DISABLE_IRQ();
  5202. uint32_t status =
  5203. flexspi_nor->get_config(FLEXSPI_NOR_INSTANCE, *config, options);
  5204. if (!s_flash_irq_disabled) {
  5205. MG_ARM_ENABLE_IRQ();
  5206. }
  5207. if (status) {
  5208. MG_ERROR(("Failed to extract flash configuration: status %u", status));
  5209. }
  5210. return status;
  5211. }
  5212. #endif
  5213. MG_IRAM static void mg_spin(volatile uint32_t count) {
  5214. while (count--) (void) 0;
  5215. }
  5216. MG_IRAM static void flash_wait(void) {
  5217. while ((*((volatile uint32_t *) (MG_FLEXSPI_BASE + 0xE0)) & MG_BIT(1)) == 0)
  5218. mg_spin(1);
  5219. }
  5220. MG_IRAM static bool flash_erase(struct mg_flexspi_nor_config *config,
  5221. void *addr) {
  5222. if (flash_page_start(addr) == false) {
  5223. MG_ERROR(("%p is not on a sector boundary", addr));
  5224. return false;
  5225. }
  5226. void *dst = (void *) ((char *) addr - (char *) s_mg_flash_imxrt.start);
  5227. bool ok = (flexspi_nor->erase(FLEXSPI_NOR_INSTANCE, config, (uint32_t) dst,
  5228. s_mg_flash_imxrt.secsz) == 0);
  5229. MG_DEBUG(("Sector starting at %p erasure: %s", addr, ok ? "ok" : "fail"));
  5230. return ok;
  5231. }
  5232. #if 0
  5233. // standalone erase call
  5234. MG_IRAM static bool mg_imxrt_erase(void *addr) {
  5235. struct mg_flexspi_nor_config config, *config_ptr = &config;
  5236. bool ret;
  5237. // Interrupts must be disabled before calls to ROM API in RT1020 and 1060
  5238. MG_ARM_DISABLE_IRQ();
  5239. ret = (flexspi_nor_get_config(&config_ptr) == 0);
  5240. if (ret) ret = flash_erase(config_ptr, addr);
  5241. MG_ARM_ENABLE_IRQ();
  5242. return ret;
  5243. }
  5244. #endif
  5245. MG_IRAM bool mg_imxrt_swap(void) {
  5246. return true;
  5247. }
  5248. MG_IRAM static bool mg_imxrt_write(void *addr, const void *buf, size_t len) {
  5249. struct mg_flexspi_nor_config config, *config_ptr = &config;
  5250. bool ok = false;
  5251. // Interrupts must be disabled before calls to ROM API in RT1020 and 1060
  5252. MG_ARM_DISABLE_IRQ();
  5253. if (flexspi_nor_get_config(&config_ptr) != 0) goto fwxit;
  5254. if ((len % s_mg_flash_imxrt.align) != 0) {
  5255. MG_ERROR(("%lu is not aligned to %lu", len, s_mg_flash_imxrt.align));
  5256. goto fwxit;
  5257. }
  5258. if ((char *) addr < (char *) s_mg_flash_imxrt.start) {
  5259. MG_ERROR(("Invalid flash write address: %p", addr));
  5260. goto fwxit;
  5261. }
  5262. uint32_t *dst = (uint32_t *) addr;
  5263. uint32_t *src = (uint32_t *) buf;
  5264. uint32_t *end = (uint32_t *) ((char *) buf + len);
  5265. ok = true;
  5266. while (ok && src < end) {
  5267. if (flash_page_start(dst) && flash_erase(config_ptr, dst) == false) {
  5268. ok = false;
  5269. break;
  5270. }
  5271. uint32_t status;
  5272. uint32_t dst_ofs = (uint32_t) dst - (uint32_t) s_mg_flash_imxrt.start;
  5273. if ((char *) buf >= (char *) s_mg_flash_imxrt.start) {
  5274. // If we copy from FLASH to FLASH, then we first need to copy the source
  5275. // to RAM
  5276. size_t tmp_buf_size = s_mg_flash_imxrt.align / sizeof(uint32_t);
  5277. uint32_t tmp[tmp_buf_size];
  5278. for (size_t i = 0; i < tmp_buf_size; i++) {
  5279. flash_wait();
  5280. tmp[i] = src[i];
  5281. }
  5282. status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, config_ptr,
  5283. (uint32_t) dst_ofs, tmp);
  5284. } else {
  5285. status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, config_ptr,
  5286. (uint32_t) dst_ofs, src);
  5287. }
  5288. src = (uint32_t *) ((char *) src + s_mg_flash_imxrt.align);
  5289. dst = (uint32_t *) ((char *) dst + s_mg_flash_imxrt.align);
  5290. if (status != 0) {
  5291. ok = false;
  5292. }
  5293. }
  5294. MG_DEBUG(("Flash write %lu bytes @ %p: %s.", len, dst, ok ? "ok" : "fail"));
  5295. fwxit:
  5296. if (!s_flash_irq_disabled) MG_ARM_ENABLE_IRQ();
  5297. return ok;
  5298. }
  5299. // just overwrite instead of swap
  5300. MG_IRAM static void single_bank_swap(char *p1, char *p2, size_t s, size_t ss) {
  5301. // no stdlib calls here
  5302. for (size_t ofs = 0; ofs < s; ofs += ss) {
  5303. mg_imxrt_write(p1 + ofs, p2 + ofs, ss);
  5304. }
  5305. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  5306. }
  5307. bool mg_ota_begin(size_t new_firmware_size) {
  5308. return mg_ota_flash_begin(new_firmware_size, &s_mg_flash_imxrt);
  5309. }
  5310. bool mg_ota_write(const void *buf, size_t len) {
  5311. return mg_ota_flash_write(buf, len, &s_mg_flash_imxrt);
  5312. }
  5313. bool mg_ota_end(void) {
  5314. if (mg_ota_flash_end(&s_mg_flash_imxrt)) {
  5315. if (0) { // is_dualbank()
  5316. // TODO(): no devices so far
  5317. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  5318. } else {
  5319. // Swap partitions. Pray power does not go away
  5320. MG_INFO(("Swapping partitions, size %u (%u sectors)",
  5321. s_mg_flash_imxrt.size,
  5322. s_mg_flash_imxrt.size / s_mg_flash_imxrt.secsz));
  5323. MG_INFO(("Do NOT power off..."));
  5324. mg_log_level = MG_LL_NONE;
  5325. s_flash_irq_disabled = true;
  5326. // Runs in RAM, will reset when finished
  5327. single_bank_swap(
  5328. (char *) s_mg_flash_imxrt.start,
  5329. (char *) s_mg_flash_imxrt.start + s_mg_flash_imxrt.size / 2,
  5330. s_mg_flash_imxrt.size / 2, s_mg_flash_imxrt.secsz);
  5331. }
  5332. }
  5333. return false;
  5334. }
  5335. #endif
  5336. #ifdef MG_ENABLE_LINES
  5337. #line 1 "src/ota_mcxn.c"
  5338. #endif
  5339. #if MG_OTA == MG_OTA_MCXN
  5340. // - Flash phrase: 16 bytes; smallest portion programmed in one operation.
  5341. // - Flash page: 128 bytes; largest portion programmed in one operation.
  5342. // - Flash sector: 8 KB; smallest portion that can be erased in one operation.
  5343. // - Flash API mg_flash_driver->program: "start" and "len" must be page-size
  5344. // aligned; to use 'phrase', FMU register access is needed. Using ROM
  5345. static bool mg_mcxn_write(void *, const void *, size_t);
  5346. static bool mg_mcxn_swap(void);
  5347. static struct mg_flash s_mg_flash_mcxn = {
  5348. (void *) 0, // Start, filled at init
  5349. 0, // Size, filled at init
  5350. 0, // Sector size, filled at init
  5351. 0, // Align, filled at init
  5352. mg_mcxn_write,
  5353. mg_mcxn_swap,
  5354. };
  5355. struct mg_flash_config {
  5356. uint32_t addr;
  5357. uint32_t size;
  5358. uint32_t blocks;
  5359. uint32_t page_size;
  5360. uint32_t sector_size;
  5361. uint32_t ffr[6];
  5362. uint32_t reserved0[5];
  5363. uint32_t *bootctx;
  5364. bool useahb;
  5365. };
  5366. struct mg_flash_driver_interface {
  5367. uint32_t version;
  5368. uint32_t (*init)(struct mg_flash_config *);
  5369. uint32_t (*erase)(struct mg_flash_config *, uint32_t start, uint32_t len,
  5370. uint32_t key);
  5371. uint32_t (*program)(struct mg_flash_config *, uint32_t start, uint8_t *src,
  5372. uint32_t len);
  5373. uint32_t (*verify_erase)(struct mg_flash_config *, uint32_t start,
  5374. uint32_t len);
  5375. uint32_t (*verify_program)(struct mg_flash_config *, uint32_t start,
  5376. uint32_t len, const uint8_t *expected,
  5377. uint32_t *addr, uint32_t *failed);
  5378. uint32_t reserved1[12];
  5379. uint32_t (*read)(struct mg_flash_config *, uint32_t start, uint8_t *dest,
  5380. uint32_t len);
  5381. uint32_t reserved2[4];
  5382. uint32_t (*deinit)(struct mg_flash_config *);
  5383. };
  5384. #define mg_flash_driver \
  5385. ((struct mg_flash_driver_interface *) (*((uint32_t *) 0x1303fc00 + 4)))
  5386. #define MG_MCXN_FLASK_KEY (('k' << 24) | ('e' << 16) | ('f' << 8) | 'l')
  5387. MG_IRAM static bool flash_sector_start(volatile uint32_t *dst) {
  5388. char *base = (char *) s_mg_flash_mcxn.start,
  5389. *end = base + s_mg_flash_mcxn.size;
  5390. volatile char *p = (char *) dst;
  5391. return p >= base && p < end && ((p - base) % s_mg_flash_mcxn.secsz) == 0;
  5392. }
  5393. MG_IRAM static bool flash_erase(struct mg_flash_config *config, void *addr) {
  5394. if (flash_sector_start(addr) == false) {
  5395. MG_ERROR(("%p is not on a sector boundary", addr));
  5396. return false;
  5397. }
  5398. uint32_t dst =
  5399. (uint32_t) addr - (uint32_t) s_mg_flash_mcxn.start; // future-proof
  5400. uint32_t status = mg_flash_driver->erase(config, dst, s_mg_flash_mcxn.secsz,
  5401. MG_MCXN_FLASK_KEY);
  5402. bool ok = (status == 0);
  5403. if (!ok) MG_ERROR(("Flash write error: %lu", status));
  5404. MG_DEBUG(("Sector starting at %p erasure: %s", addr, ok ? "ok" : "fail"));
  5405. return ok;
  5406. }
  5407. #if 0
  5408. // read-while-write, no need to disable IRQs for standalone usage
  5409. MG_IRAM static bool mg_mcxn_erase(void *addr) {
  5410. uint32_t status;
  5411. struct mg_flash_config config;
  5412. if ((status = mg_flash_driver->init(&config)) != 0) {
  5413. MG_ERROR(("Flash driver init error: %lu", status));
  5414. return false;
  5415. }
  5416. bool ok = flash_erase(&config, addr);
  5417. mg_flash_driver->deinit(&config);
  5418. return ok;
  5419. }
  5420. #endif
  5421. MG_IRAM static bool mg_mcxn_swap(void) {
  5422. // TODO(): no devices so far
  5423. return true;
  5424. }
  5425. static bool s_flash_irq_disabled;
  5426. MG_IRAM static bool mg_mcxn_write(void *addr, const void *buf, size_t len) {
  5427. bool ok = false;
  5428. uint32_t status;
  5429. struct mg_flash_config config;
  5430. if ((status = mg_flash_driver->init(&config)) != 0) {
  5431. MG_ERROR(("Flash driver init error: %lu", status));
  5432. return false;
  5433. }
  5434. if ((len % s_mg_flash_mcxn.align) != 0) {
  5435. MG_ERROR(("%lu is not aligned to %lu", len, s_mg_flash_mcxn.align));
  5436. goto fwxit;
  5437. }
  5438. if ((((size_t) addr - (size_t) s_mg_flash_mcxn.start) %
  5439. s_mg_flash_mcxn.align) != 0) {
  5440. MG_ERROR(("%p is not on a page boundary", addr));
  5441. goto fwxit;
  5442. }
  5443. uint32_t *dst = (uint32_t *) addr;
  5444. uint32_t *src = (uint32_t *) buf;
  5445. uint32_t *end = (uint32_t *) ((char *) buf + len);
  5446. ok = true;
  5447. MG_ARM_DISABLE_IRQ();
  5448. while (ok && src < end) {
  5449. if (flash_sector_start(dst) && flash_erase(&config, dst) == false) {
  5450. ok = false;
  5451. break;
  5452. }
  5453. uint32_t dst_ofs = (uint32_t) dst - (uint32_t) s_mg_flash_mcxn.start;
  5454. // assume source is in RAM or in a different bank or read-while-write
  5455. status = mg_flash_driver->program(&config, dst_ofs, (uint8_t *) src,
  5456. s_mg_flash_mcxn.align);
  5457. src = (uint32_t *) ((char *) src + s_mg_flash_mcxn.align);
  5458. dst = (uint32_t *) ((char *) dst + s_mg_flash_mcxn.align);
  5459. if (status != 0) {
  5460. MG_ERROR(("Flash write error: %lu", status));
  5461. ok = false;
  5462. }
  5463. }
  5464. if (!s_flash_irq_disabled) MG_ARM_ENABLE_IRQ();
  5465. MG_DEBUG(("Flash write %lu bytes @ %p: %s.", len, dst, ok ? "ok" : "fail"));
  5466. fwxit:
  5467. mg_flash_driver->deinit(&config);
  5468. return ok;
  5469. }
  5470. // try to swap (honor dual image), otherwise just overwrite
  5471. MG_IRAM static void single_bank_swap(char *p1, char *p2, size_t s, size_t ss) {
  5472. char *tmp = malloc(ss);
  5473. // no stdlib calls here
  5474. for (size_t ofs = 0; ofs < s; ofs += ss) {
  5475. if (tmp != NULL)
  5476. for (size_t i = 0; i < ss; i++) tmp[i] = p1[ofs + i];
  5477. mg_mcxn_write(p1 + ofs, p2 + ofs, ss);
  5478. if (tmp != NULL) mg_mcxn_write(p2 + ofs, tmp, ss);
  5479. }
  5480. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  5481. }
  5482. bool mg_ota_begin(size_t new_firmware_size) {
  5483. uint32_t status;
  5484. struct mg_flash_config config;
  5485. if ((status = mg_flash_driver->init(&config)) != 0) {
  5486. MG_ERROR(("Flash driver init error: %lu", status));
  5487. return false;
  5488. }
  5489. s_mg_flash_mcxn.start = (void *) config.addr;
  5490. s_mg_flash_mcxn.size = config.size;
  5491. s_mg_flash_mcxn.secsz = config.sector_size;
  5492. s_mg_flash_mcxn.align = config.page_size;
  5493. mg_flash_driver->deinit(&config);
  5494. MG_DEBUG(
  5495. ("%lu-byte flash @%p, using %lu-byte sectors with %lu-byte-aligned pages",
  5496. s_mg_flash_mcxn.size, s_mg_flash_mcxn.start, s_mg_flash_mcxn.secsz,
  5497. s_mg_flash_mcxn.align));
  5498. return mg_ota_flash_begin(new_firmware_size, &s_mg_flash_mcxn);
  5499. }
  5500. bool mg_ota_write(const void *buf, size_t len) {
  5501. return mg_ota_flash_write(buf, len, &s_mg_flash_mcxn);
  5502. }
  5503. bool mg_ota_end(void) {
  5504. if (mg_ota_flash_end(&s_mg_flash_mcxn)) {
  5505. if (0) { // is_dualbank()
  5506. // TODO(): no devices so far
  5507. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  5508. } else {
  5509. // Swap partitions. Pray power does not go away
  5510. MG_INFO(("Swapping partitions, size %u (%u sectors)",
  5511. s_mg_flash_mcxn.size,
  5512. s_mg_flash_mcxn.size / s_mg_flash_mcxn.secsz));
  5513. MG_INFO(("Do NOT power off..."));
  5514. mg_log_level = MG_LL_NONE;
  5515. s_flash_irq_disabled = true;
  5516. // Runs in RAM, will reset when finished
  5517. single_bank_swap(
  5518. (char *) s_mg_flash_mcxn.start,
  5519. (char *) s_mg_flash_mcxn.start + s_mg_flash_mcxn.size / 2,
  5520. s_mg_flash_mcxn.size / 2, s_mg_flash_mcxn.secsz);
  5521. }
  5522. }
  5523. return false;
  5524. }
  5525. #endif
  5526. #ifdef MG_ENABLE_LINES
  5527. #line 1 "src/ota_picosdk.c"
  5528. #endif
  5529. #if MG_OTA == MG_OTA_PICOSDK
  5530. // Both RP2040 and RP2350 have no flash, low-level flash access support in
  5531. // bootrom, and high-level support in Pico-SDK (2.0+ for the RP2350)
  5532. // - The RP2350 in RISC-V mode is not yet (fully) supported (nor tested)
  5533. static bool mg_picosdk_write(void *, const void *, size_t);
  5534. static bool mg_picosdk_swap(void);
  5535. static struct mg_flash s_mg_flash_picosdk = {
  5536. (void *) 0x10000000, // Start, not used here; functions handle offset
  5537. #ifdef PICO_FLASH_SIZE_BYTES
  5538. PICO_FLASH_SIZE_BYTES, // Size, from board definitions
  5539. #else
  5540. 0x200000, // Size, guess... is 2M enough ?
  5541. #endif
  5542. FLASH_SECTOR_SIZE, // Sector size, from hardware_flash
  5543. FLASH_PAGE_SIZE, // Align, from hardware_flash
  5544. mg_picosdk_write, mg_picosdk_swap,
  5545. };
  5546. #define MG_MODULO2(x, m) ((x) & ((m) -1))
  5547. static bool __no_inline_not_in_flash_func(flash_sector_start)(
  5548. volatile uint32_t *dst) {
  5549. char *base = (char *) s_mg_flash_picosdk.start,
  5550. *end = base + s_mg_flash_picosdk.size;
  5551. volatile char *p = (char *) dst;
  5552. return p >= base && p < end &&
  5553. MG_MODULO2(p - base, s_mg_flash_picosdk.secsz) == 0;
  5554. }
  5555. static bool __no_inline_not_in_flash_func(flash_erase)(void *addr) {
  5556. if (flash_sector_start(addr) == false) {
  5557. MG_ERROR(("%p is not on a sector boundary", addr));
  5558. return false;
  5559. }
  5560. void *dst = (void *) ((char *) addr - (char *) s_mg_flash_picosdk.start);
  5561. flash_range_erase((uint32_t) dst, s_mg_flash_picosdk.secsz);
  5562. MG_DEBUG(("Sector starting at %p erasure", addr));
  5563. return true;
  5564. }
  5565. static bool __no_inline_not_in_flash_func(mg_picosdk_swap)(void) {
  5566. // TODO(): RP2350 might have some A/B functionality (DS 5.1)
  5567. return true;
  5568. }
  5569. static bool s_flash_irq_disabled;
  5570. static bool __no_inline_not_in_flash_func(mg_picosdk_write)(void *addr,
  5571. const void *buf,
  5572. size_t len) {
  5573. if ((len % s_mg_flash_picosdk.align) != 0) {
  5574. MG_ERROR(("%lu is not aligned to %lu", len, s_mg_flash_picosdk.align));
  5575. return false;
  5576. }
  5577. if ((((size_t) addr - (size_t) s_mg_flash_picosdk.start) %
  5578. s_mg_flash_picosdk.align) != 0) {
  5579. MG_ERROR(("%p is not on a page boundary", addr));
  5580. return false;
  5581. }
  5582. uint32_t *dst = (uint32_t *) addr;
  5583. uint32_t *src = (uint32_t *) buf;
  5584. uint32_t *end = (uint32_t *) ((char *) buf + len);
  5585. #ifndef __riscv
  5586. MG_ARM_DISABLE_IRQ();
  5587. #else
  5588. asm volatile("csrrc zero, mstatus, %0" : : "i"(1 << 3) : "memory");
  5589. #endif
  5590. while (src < end) {
  5591. uint32_t dst_ofs = (uint32_t) dst - (uint32_t) s_mg_flash_picosdk.start;
  5592. if (flash_sector_start(dst) && flash_erase(dst) == false) break;
  5593. // flash_range_program() runs in RAM and handles writing up to
  5594. // FLASH_PAGE_SIZE bytes. Source must not be in flash
  5595. flash_range_program((uint32_t) dst_ofs, (uint8_t *) src,
  5596. s_mg_flash_picosdk.align);
  5597. src = (uint32_t *) ((char *) src + s_mg_flash_picosdk.align);
  5598. dst = (uint32_t *) ((char *) dst + s_mg_flash_picosdk.align);
  5599. }
  5600. if (!s_flash_irq_disabled) {
  5601. #ifndef __riscv
  5602. MG_ARM_ENABLE_IRQ();
  5603. #else
  5604. asm volatile("csrrs mstatus, %0" : : "i"(1 << 3) : "memory");
  5605. #endif
  5606. }
  5607. MG_DEBUG(("Flash write %lu bytes @ %p.", len, dst));
  5608. return true;
  5609. }
  5610. // just overwrite instead of swap
  5611. static void __no_inline_not_in_flash_func(single_bank_swap)(char *p1, char *p2,
  5612. size_t s,
  5613. size_t ss) {
  5614. char *tmp = malloc(ss);
  5615. if (tmp == NULL) return;
  5616. #if PICO_RP2040
  5617. uint32_t xip[256 / sizeof(uint32_t)];
  5618. void *dst = (void *) ((char *) p1 - (char *) s_mg_flash_picosdk.start);
  5619. size_t count = MG_ROUND_UP(s, ss);
  5620. // use SDK function calls to get BootROM function pointers
  5621. rom_connect_internal_flash_fn connect = (rom_connect_internal_flash_fn) rom_func_lookup_inline(ROM_FUNC_CONNECT_INTERNAL_FLASH);
  5622. rom_flash_exit_xip_fn xit = (rom_flash_exit_xip_fn) rom_func_lookup_inline(ROM_FUNC_FLASH_EXIT_XIP);
  5623. rom_flash_range_program_fn program = (rom_flash_range_program_fn) rom_func_lookup_inline(ROM_FUNC_FLASH_RANGE_PROGRAM);
  5624. rom_flash_flush_cache_fn flush = (rom_flash_flush_cache_fn) rom_func_lookup_inline(ROM_FUNC_FLASH_FLUSH_CACHE);
  5625. // no stdlib calls here.
  5626. MG_ARM_DISABLE_IRQ();
  5627. // 2nd bootloader (XIP) is in flash, SDK functions copy it to RAM on entry
  5628. for (size_t i = 0; i < 256 / sizeof(uint32_t); i++)
  5629. xip[i] = ((uint32_t *) (s_mg_flash_picosdk.start))[i];
  5630. flash_range_erase((uint32_t) dst, count);
  5631. // flash has been erased, no XIP to copy. Only BootROM calls possible
  5632. for (uint32_t ofs = 0; ofs < s; ofs += ss) {
  5633. for (size_t i = 0; i < ss; i++) tmp[i] = p2[ofs + i];
  5634. __compiler_memory_barrier();
  5635. connect();
  5636. xit();
  5637. program((uint32_t) dst + ofs, tmp, ss);
  5638. flush();
  5639. ((void (*)(void))((intptr_t) xip + 1))(); // enter XIP again
  5640. }
  5641. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004; // AIRCR = SYSRESETREQ
  5642. #else
  5643. // RP2350 has bootram and copies second bootloader there, SDK uses that copy,
  5644. // It might also be able to take advantage of partition swapping
  5645. for (size_t ofs = 0; ofs < s; ofs += ss) {
  5646. for (size_t i = 0; i < ss; i++) tmp[i] = p2[ofs + i];
  5647. mg_picosdk_write(p1 + ofs, tmp, ss);
  5648. }
  5649. #ifndef __riscv
  5650. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004; // AIRCR = SYSRESETREQ
  5651. #else
  5652. // TODO(): find a way to do a system reset, like block resets and watchdog
  5653. #endif
  5654. #endif
  5655. }
  5656. bool mg_ota_begin(size_t new_firmware_size) {
  5657. return mg_ota_flash_begin(new_firmware_size, &s_mg_flash_picosdk);
  5658. }
  5659. bool mg_ota_write(const void *buf, size_t len) {
  5660. return mg_ota_flash_write(buf, len, &s_mg_flash_picosdk);
  5661. }
  5662. bool mg_ota_end(void) {
  5663. if (mg_ota_flash_end(&s_mg_flash_picosdk)) {
  5664. // Swap partitions. Pray power does not go away
  5665. MG_INFO(("Swapping partitions, size %u (%u sectors)",
  5666. s_mg_flash_picosdk.size,
  5667. s_mg_flash_picosdk.size / s_mg_flash_picosdk.secsz));
  5668. MG_INFO(("Do NOT power off..."));
  5669. mg_log_level = MG_LL_NONE;
  5670. s_flash_irq_disabled = true;
  5671. // Runs in RAM, will reset when finished or return on failure
  5672. single_bank_swap(
  5673. (char *) s_mg_flash_picosdk.start,
  5674. (char *) s_mg_flash_picosdk.start + s_mg_flash_picosdk.size / 2,
  5675. s_mg_flash_picosdk.size / 2, s_mg_flash_picosdk.secsz);
  5676. }
  5677. return false;
  5678. }
  5679. #endif
  5680. #ifdef MG_ENABLE_LINES
  5681. #line 1 "src/ota_stm32f.c"
  5682. #endif
  5683. #if MG_OTA == MG_OTA_STM32F
  5684. static bool mg_stm32f_write(void *, const void *, size_t);
  5685. static bool mg_stm32f_swap(void);
  5686. static struct mg_flash s_mg_flash_stm32f = {
  5687. (void *) 0x08000000, // Start
  5688. 0, // Size, FLASH_SIZE_REG
  5689. 0, // Irregular sector size
  5690. 32, // Align, 256 bit
  5691. mg_stm32f_write,
  5692. mg_stm32f_swap,
  5693. };
  5694. #define MG_FLASH_BASE 0x40023c00
  5695. #define MG_FLASH_KEYR 0x04
  5696. #define MG_FLASH_SR 0x0c
  5697. #define MG_FLASH_CR 0x10
  5698. #define MG_FLASH_OPTCR 0x14
  5699. #define MG_FLASH_SIZE_REG_F7 0x1FF0F442
  5700. #define MG_FLASH_SIZE_REG_F4 0x1FFF7A22
  5701. #define STM_DBGMCU_IDCODE 0xE0042000
  5702. #define STM_DEV_ID (MG_REG(STM_DBGMCU_IDCODE) & (MG_BIT(12) - 1))
  5703. #define SYSCFG_MEMRMP 0x40013800
  5704. #define MG_FLASH_SIZE_REG_LOCATION \
  5705. ((STM_DEV_ID >= 0x449) ? MG_FLASH_SIZE_REG_F7 : MG_FLASH_SIZE_REG_F4)
  5706. static size_t flash_size(void) {
  5707. return (MG_REG(MG_FLASH_SIZE_REG_LOCATION) & 0xFFFF) * 1024;
  5708. }
  5709. MG_IRAM static int is_dualbank(void) {
  5710. // only F42x/F43x series (0x419) support dual bank
  5711. return STM_DEV_ID == 0x419;
  5712. }
  5713. MG_IRAM static void flash_unlock(void) {
  5714. static bool unlocked = false;
  5715. if (unlocked == false) {
  5716. MG_REG(MG_FLASH_BASE + MG_FLASH_KEYR) = 0x45670123;
  5717. MG_REG(MG_FLASH_BASE + MG_FLASH_KEYR) = 0xcdef89ab;
  5718. unlocked = true;
  5719. }
  5720. }
  5721. #define MG_FLASH_CONFIG_16_64_128 1 // used by STM32F7
  5722. #define MG_FLASH_CONFIG_32_128_256 2 // used by STM32F4 and F2
  5723. MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
  5724. char *base = (char *) s_mg_flash_stm32f.start;
  5725. char *end = base + s_mg_flash_stm32f.size;
  5726. if (is_dualbank() && dst >= (uint32_t *) (base + (end - base) / 2)) {
  5727. dst = (uint32_t *) ((uint32_t) dst - (end - base) / 2);
  5728. }
  5729. uint32_t flash_config = MG_FLASH_CONFIG_16_64_128;
  5730. if (STM_DEV_ID >= 0x449) {
  5731. flash_config = MG_FLASH_CONFIG_32_128_256;
  5732. }
  5733. volatile char *p = (char *) dst;
  5734. if (p >= base && p < end) {
  5735. if (p < base + 16 * 1024 * 4 * flash_config) {
  5736. if ((p - base) % (16 * 1024 * flash_config) == 0) return true;
  5737. } else if (p == base + 16 * 1024 * 4 * flash_config) {
  5738. return true;
  5739. } else if ((p - base) % (128 * 1024 * flash_config) == 0) {
  5740. return true;
  5741. }
  5742. }
  5743. return false;
  5744. }
  5745. MG_IRAM static int flash_sector(volatile uint32_t *addr) {
  5746. char *base = (char *) s_mg_flash_stm32f.start;
  5747. char *end = base + s_mg_flash_stm32f.size;
  5748. bool addr_in_bank_2 = false;
  5749. if (is_dualbank() && addr >= (uint32_t *) (base + (end - base) / 2)) {
  5750. addr = (uint32_t *) ((uint32_t) addr - (end - base) / 2);
  5751. addr_in_bank_2 = true;
  5752. }
  5753. volatile char *p = (char *) addr;
  5754. uint32_t flash_config = MG_FLASH_CONFIG_16_64_128;
  5755. if (STM_DEV_ID >= 0x449) {
  5756. flash_config = MG_FLASH_CONFIG_32_128_256;
  5757. }
  5758. int sector = -1;
  5759. if (p >= base && p < end) {
  5760. if (p < base + 16 * 1024 * 4 * flash_config) {
  5761. sector = (p - base) / (16 * 1024 * flash_config);
  5762. } else if (p >= base + 64 * 1024 * flash_config &&
  5763. p < base + 128 * 1024 * flash_config) {
  5764. sector = 4;
  5765. } else {
  5766. sector = (p - base) / (128 * 1024 * flash_config) + 4;
  5767. }
  5768. }
  5769. if (sector == -1) return -1;
  5770. if (addr_in_bank_2) sector += 12; // a bank has 12 sectors
  5771. return sector;
  5772. }
  5773. MG_IRAM static bool flash_is_err(void) {
  5774. return MG_REG(MG_FLASH_BASE + MG_FLASH_SR) & ((MG_BIT(7) - 1) << 1);
  5775. }
  5776. MG_IRAM static void flash_wait(void) {
  5777. while (MG_REG(MG_FLASH_BASE + MG_FLASH_SR) & (MG_BIT(16))) (void) 0;
  5778. }
  5779. MG_IRAM static void flash_clear_err(void) {
  5780. flash_wait(); // Wait until ready
  5781. MG_REG(MG_FLASH_BASE + MG_FLASH_SR) = 0xf2; // Clear all errors
  5782. }
  5783. MG_IRAM static bool mg_stm32f_erase(void *addr) {
  5784. bool ok = false;
  5785. if (flash_page_start(addr) == false) {
  5786. MG_ERROR(("%p is not on a sector boundary", addr));
  5787. } else {
  5788. int sector = flash_sector(addr);
  5789. if (sector < 0) return false;
  5790. uint32_t sector_reg = sector;
  5791. if (is_dualbank() && sector >= 12) {
  5792. // 3.9.8 Flash control register (FLASH_CR) for F42xxx and F43xxx
  5793. // BITS[7:3]
  5794. sector_reg -= 12;
  5795. sector_reg |= MG_BIT(4);
  5796. }
  5797. flash_unlock();
  5798. flash_wait();
  5799. uint32_t cr = MG_BIT(1); // SER
  5800. cr |= MG_BIT(16); // STRT
  5801. cr |= (sector_reg & 31) << 3; // sector
  5802. MG_REG(MG_FLASH_BASE + MG_FLASH_CR) = cr;
  5803. ok = !flash_is_err();
  5804. MG_DEBUG(("Erase sector %lu @ %p %s. CR %#lx SR %#lx", sector, addr,
  5805. ok ? "ok" : "fail", MG_REG(MG_FLASH_BASE + MG_FLASH_CR),
  5806. MG_REG(MG_FLASH_BASE + MG_FLASH_SR)));
  5807. // After we have erased the sector, set CR flags for programming
  5808. // 2 << 8 is word write parallelism, bit(0) is PG. RM0385, section 3.7.5
  5809. MG_REG(MG_FLASH_BASE + MG_FLASH_CR) = MG_BIT(0) | (2 << 8);
  5810. flash_clear_err();
  5811. }
  5812. return ok;
  5813. }
  5814. MG_IRAM static bool mg_stm32f_swap(void) {
  5815. // STM32 F42x/F43x support dual bank, however, the memory mapping
  5816. // change will not be carried through a hard reset. Therefore, we will use
  5817. // the single bank approach for this family as well.
  5818. return true;
  5819. }
  5820. static bool s_flash_irq_disabled;
  5821. MG_IRAM static bool mg_stm32f_write(void *addr, const void *buf, size_t len) {
  5822. if ((len % s_mg_flash_stm32f.align) != 0) {
  5823. MG_ERROR(("%lu is not aligned to %lu", len, s_mg_flash_stm32f.align));
  5824. return false;
  5825. }
  5826. uint32_t *dst = (uint32_t *) addr;
  5827. uint32_t *src = (uint32_t *) buf;
  5828. uint32_t *end = (uint32_t *) ((char *) buf + len);
  5829. bool ok = true;
  5830. MG_ARM_DISABLE_IRQ();
  5831. flash_unlock();
  5832. flash_clear_err();
  5833. MG_REG(MG_FLASH_BASE + MG_FLASH_CR) = MG_BIT(0) | MG_BIT(9); // PG, 32-bit
  5834. flash_wait();
  5835. MG_DEBUG(("Writing flash @ %p, %lu bytes", addr, len));
  5836. while (ok && src < end) {
  5837. if (flash_page_start(dst) && mg_stm32f_erase(dst) == false) break;
  5838. *(volatile uint32_t *) dst++ = *src++;
  5839. MG_DSB(); // ensure flash is written with no errors
  5840. flash_wait();
  5841. if (flash_is_err()) ok = false;
  5842. }
  5843. if (!s_flash_irq_disabled) MG_ARM_ENABLE_IRQ();
  5844. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  5845. ok ? "ok" : "fail", MG_REG(MG_FLASH_BASE + MG_FLASH_CR),
  5846. MG_REG(MG_FLASH_BASE + MG_FLASH_SR)));
  5847. MG_REG(MG_FLASH_BASE + MG_FLASH_CR) &= ~MG_BIT(0); // Clear programming flag
  5848. return ok;
  5849. }
  5850. // just overwrite instead of swap
  5851. MG_IRAM void single_bank_swap(char *p1, char *p2, size_t size) {
  5852. // no stdlib calls here
  5853. mg_stm32f_write(p1, p2, size);
  5854. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  5855. }
  5856. bool mg_ota_begin(size_t new_firmware_size) {
  5857. s_mg_flash_stm32f.size = flash_size();
  5858. return mg_ota_flash_begin(new_firmware_size, &s_mg_flash_stm32f);
  5859. }
  5860. bool mg_ota_write(const void *buf, size_t len) {
  5861. return mg_ota_flash_write(buf, len, &s_mg_flash_stm32f);
  5862. }
  5863. bool mg_ota_end(void) {
  5864. if (mg_ota_flash_end(&s_mg_flash_stm32f)) {
  5865. // Swap partitions. Pray power does not go away
  5866. MG_INFO(("Swapping partitions, size %u (%u sectors)",
  5867. s_mg_flash_stm32f.size, STM_DEV_ID == 0x449 ? 8 : 12));
  5868. MG_INFO(("Do NOT power off..."));
  5869. mg_log_level = MG_LL_NONE;
  5870. s_flash_irq_disabled = true;
  5871. char *p1 = (char *) s_mg_flash_stm32f.start;
  5872. char *p2 = p1 + s_mg_flash_stm32f.size / 2;
  5873. size_t size = s_mg_flash_stm32f.size / 2;
  5874. // Runs in RAM, will reset when finished
  5875. single_bank_swap(p1, p2, size);
  5876. }
  5877. return false;
  5878. }
  5879. #endif
  5880. #ifdef MG_ENABLE_LINES
  5881. #line 1 "src/ota_stm32h5.c"
  5882. #endif
  5883. #if MG_OTA == MG_OTA_STM32H5
  5884. static bool mg_stm32h5_write(void *, const void *, size_t);
  5885. static bool mg_stm32h5_swap(void);
  5886. static struct mg_flash s_mg_flash_stm32h5 = {
  5887. (void *) 0x08000000, // Start
  5888. 2 * 1024 * 1024, // Size, 2Mb
  5889. 8 * 1024, // Sector size, 8k
  5890. 16, // Align, 128 bit
  5891. mg_stm32h5_write,
  5892. mg_stm32h5_swap,
  5893. };
  5894. #define MG_FLASH_BASE 0x40022000 // Base address of the flash controller
  5895. #define FLASH_KEYR (MG_FLASH_BASE + 0x4) // See RM0481 7.11
  5896. #define FLASH_OPTKEYR (MG_FLASH_BASE + 0xc)
  5897. #define FLASH_OPTCR (MG_FLASH_BASE + 0x1c)
  5898. #define FLASH_NSSR (MG_FLASH_BASE + 0x20)
  5899. #define FLASH_NSCR (MG_FLASH_BASE + 0x28)
  5900. #define FLASH_NSCCR (MG_FLASH_BASE + 0x30)
  5901. #define FLASH_OPTSR_CUR (MG_FLASH_BASE + 0x50)
  5902. #define FLASH_OPTSR_PRG (MG_FLASH_BASE + 0x54)
  5903. static void flash_unlock(void) {
  5904. static bool unlocked = false;
  5905. if (unlocked == false) {
  5906. MG_REG(FLASH_KEYR) = 0x45670123;
  5907. MG_REG(FLASH_KEYR) = 0Xcdef89ab;
  5908. MG_REG(FLASH_OPTKEYR) = 0x08192a3b;
  5909. MG_REG(FLASH_OPTKEYR) = 0x4c5d6e7f;
  5910. unlocked = true;
  5911. }
  5912. }
  5913. static int flash_page_start(volatile uint32_t *dst) {
  5914. char *base = (char *) s_mg_flash_stm32h5.start,
  5915. *end = base + s_mg_flash_stm32h5.size;
  5916. volatile char *p = (char *) dst;
  5917. return p >= base && p < end && ((p - base) % s_mg_flash_stm32h5.secsz) == 0;
  5918. }
  5919. static bool flash_is_err(void) {
  5920. return MG_REG(FLASH_NSSR) & ((MG_BIT(8) - 1) << 17); // RM0481 7.11.9
  5921. }
  5922. static void flash_wait(void) {
  5923. while ((MG_REG(FLASH_NSSR) & MG_BIT(0)) &&
  5924. (MG_REG(FLASH_NSSR) & MG_BIT(16)) == 0) {
  5925. (void) 0;
  5926. }
  5927. }
  5928. static void flash_clear_err(void) {
  5929. flash_wait(); // Wait until ready
  5930. MG_REG(FLASH_NSCCR) = ((MG_BIT(9) - 1) << 16U); // Clear all errors
  5931. }
  5932. static bool flash_bank_is_swapped(void) {
  5933. return MG_REG(FLASH_OPTCR) & MG_BIT(31); // RM0481 7.11.8
  5934. }
  5935. static bool mg_stm32h5_erase(void *location) {
  5936. bool ok = false;
  5937. if (flash_page_start(location) == false) {
  5938. MG_ERROR(("%p is not on a sector boundary"));
  5939. } else {
  5940. uintptr_t diff = (char *) location - (char *) s_mg_flash_stm32h5.start;
  5941. uint32_t sector = diff / s_mg_flash_stm32h5.secsz;
  5942. uint32_t saved_cr = MG_REG(FLASH_NSCR); // Save CR value
  5943. flash_unlock();
  5944. flash_clear_err();
  5945. MG_REG(FLASH_NSCR) = 0;
  5946. if ((sector < 128 && flash_bank_is_swapped()) ||
  5947. (sector > 127 && !flash_bank_is_swapped())) {
  5948. MG_REG(FLASH_NSCR) |= MG_BIT(31); // Set FLASH_CR_BKSEL
  5949. }
  5950. if (sector > 127) sector -= 128;
  5951. MG_REG(FLASH_NSCR) |= MG_BIT(2) | (sector << 6); // Erase | sector_num
  5952. MG_REG(FLASH_NSCR) |= MG_BIT(5); // Start erasing
  5953. flash_wait();
  5954. ok = !flash_is_err();
  5955. MG_DEBUG(("Erase sector %lu @ %p: %s. CR %#lx SR %#lx", sector, location,
  5956. ok ? "ok" : "fail", MG_REG(FLASH_NSCR), MG_REG(FLASH_NSSR)));
  5957. // mg_hexdump(location, 32);
  5958. MG_REG(FLASH_NSCR) = saved_cr; // Restore saved CR
  5959. }
  5960. return ok;
  5961. }
  5962. static bool mg_stm32h5_swap(void) {
  5963. uint32_t desired = flash_bank_is_swapped() ? 0 : MG_BIT(31);
  5964. flash_unlock();
  5965. flash_clear_err();
  5966. // printf("OPTSR_PRG 1 %#lx\n", FLASH->OPTSR_PRG);
  5967. MG_SET_BITS(MG_REG(FLASH_OPTSR_PRG), MG_BIT(31), desired);
  5968. // printf("OPTSR_PRG 2 %#lx\n", FLASH->OPTSR_PRG);
  5969. MG_REG(FLASH_OPTCR) |= MG_BIT(1); // OPTSTART
  5970. while ((MG_REG(FLASH_OPTSR_CUR) & MG_BIT(31)) != desired) (void) 0;
  5971. return true;
  5972. }
  5973. static bool mg_stm32h5_write(void *addr, const void *buf, size_t len) {
  5974. if ((len % s_mg_flash_stm32h5.align) != 0) {
  5975. MG_ERROR(("%lu is not aligned to %lu", len, s_mg_flash_stm32h5.align));
  5976. return false;
  5977. }
  5978. uint32_t *dst = (uint32_t *) addr;
  5979. uint32_t *src = (uint32_t *) buf;
  5980. uint32_t *end = (uint32_t *) ((char *) buf + len);
  5981. bool ok = true;
  5982. MG_ARM_DISABLE_IRQ();
  5983. flash_unlock();
  5984. flash_clear_err();
  5985. MG_REG(FLASH_NSCR) = MG_BIT(1); // Set programming flag
  5986. while (ok && src < end) {
  5987. if (flash_page_start(dst) && mg_stm32h5_erase(dst) == false) {
  5988. ok = false;
  5989. break;
  5990. }
  5991. *(volatile uint32_t *) dst++ = *src++;
  5992. flash_wait();
  5993. if (flash_is_err()) ok = false;
  5994. }
  5995. MG_ARM_ENABLE_IRQ();
  5996. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  5997. flash_is_err() ? "fail" : "ok", MG_REG(FLASH_NSCR),
  5998. MG_REG(FLASH_NSSR)));
  5999. MG_REG(FLASH_NSCR) = 0; // Clear flags
  6000. return ok;
  6001. }
  6002. bool mg_ota_begin(size_t new_firmware_size) {
  6003. return mg_ota_flash_begin(new_firmware_size, &s_mg_flash_stm32h5);
  6004. }
  6005. bool mg_ota_write(const void *buf, size_t len) {
  6006. return mg_ota_flash_write(buf, len, &s_mg_flash_stm32h5);
  6007. }
  6008. // Actual bank swap is deferred until reset, it is safe to execute in flash
  6009. bool mg_ota_end(void) {
  6010. if(!mg_ota_flash_end(&s_mg_flash_stm32h5)) return false;
  6011. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  6012. return true;
  6013. }
  6014. #endif
  6015. #ifdef MG_ENABLE_LINES
  6016. #line 1 "src/ota_stm32h7.c"
  6017. #endif
  6018. #if MG_OTA == MG_OTA_STM32H7 || MG_OTA == MG_OTA_STM32H7_DUAL_CORE
  6019. // - H723/735 RM 4.3.3: Note: The application can simultaneously request a read
  6020. // and a write operation through the AXI interface.
  6021. // - We only need IRAM for partition swapping in the H723, however, all
  6022. // related functions must reside in IRAM for this to be possible.
  6023. // - Linker files for other devices won't define a .iram section so there's no
  6024. // associated penalty
  6025. static bool mg_stm32h7_write(void *, const void *, size_t);
  6026. static bool mg_stm32h7_swap(void);
  6027. static struct mg_flash s_mg_flash_stm32h7 = {
  6028. (void *) 0x08000000, // Start
  6029. 0, // Size, FLASH_SIZE_REG
  6030. 128 * 1024, // Sector size, 128k
  6031. 32, // Align, 256 bit
  6032. mg_stm32h7_write,
  6033. mg_stm32h7_swap,
  6034. };
  6035. #define FLASH_BASE1 0x52002000 // Base address for bank1
  6036. #define FLASH_BASE2 0x52002100 // Base address for bank2
  6037. #define FLASH_KEYR 0x04 // See RM0433 4.9.2
  6038. #define FLASH_OPTKEYR 0x08
  6039. #define FLASH_OPTCR 0x18
  6040. #define FLASH_SR 0x10
  6041. #define FLASH_CR 0x0c
  6042. #define FLASH_CCR 0x14
  6043. #define FLASH_OPTSR_CUR 0x1c
  6044. #define FLASH_OPTSR_PRG 0x20
  6045. #define FLASH_SIZE_REG 0x1ff1e880
  6046. #define IS_DUALCORE() (MG_OTA == MG_OTA_STM32H7_DUAL_CORE)
  6047. MG_IRAM static bool is_dualbank(void) {
  6048. if (IS_DUALCORE()) {
  6049. // H745/H755 and H747/H757 are running on dual core.
  6050. // Using only the 1st bank (mapped to CM7), in order not to interfere
  6051. // with the 2nd bank (CM4), possibly causing CM4 to boot unexpectedly.
  6052. return false;
  6053. }
  6054. return (s_mg_flash_stm32h7.size < 2 * 1024 * 1024) ? false : true;
  6055. }
  6056. MG_IRAM static void flash_unlock(void) {
  6057. static bool unlocked = false;
  6058. if (unlocked == false) {
  6059. MG_REG(FLASH_BASE1 + FLASH_KEYR) = 0x45670123;
  6060. MG_REG(FLASH_BASE1 + FLASH_KEYR) = 0xcdef89ab;
  6061. if (is_dualbank()) {
  6062. MG_REG(FLASH_BASE2 + FLASH_KEYR) = 0x45670123;
  6063. MG_REG(FLASH_BASE2 + FLASH_KEYR) = 0xcdef89ab;
  6064. }
  6065. MG_REG(FLASH_BASE1 + FLASH_OPTKEYR) = 0x08192a3b; // opt reg is "shared"
  6066. MG_REG(FLASH_BASE1 + FLASH_OPTKEYR) = 0x4c5d6e7f; // thus unlock once
  6067. unlocked = true;
  6068. }
  6069. }
  6070. MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
  6071. char *base = (char *) s_mg_flash_stm32h7.start,
  6072. *end = base + s_mg_flash_stm32h7.size;
  6073. volatile char *p = (char *) dst;
  6074. return p >= base && p < end && ((p - base) % s_mg_flash_stm32h7.secsz) == 0;
  6075. }
  6076. MG_IRAM static bool flash_is_err(uint32_t bank) {
  6077. return MG_REG(bank + FLASH_SR) & ((MG_BIT(11) - 1) << 17); // RM0433 4.9.5
  6078. }
  6079. MG_IRAM static void flash_wait(uint32_t bank) {
  6080. while (MG_REG(bank + FLASH_SR) & (MG_BIT(0) | MG_BIT(2))) (void) 0;
  6081. }
  6082. MG_IRAM static void flash_clear_err(uint32_t bank) {
  6083. flash_wait(bank); // Wait until ready
  6084. MG_REG(bank + FLASH_CCR) = ((MG_BIT(11) - 1) << 16U); // Clear all errors
  6085. }
  6086. MG_IRAM static bool flash_bank_is_swapped(uint32_t bank) {
  6087. return MG_REG(bank + FLASH_OPTCR) & MG_BIT(31); // RM0433 4.9.7
  6088. }
  6089. // Figure out flash bank based on the address
  6090. MG_IRAM static uint32_t flash_bank(void *addr) {
  6091. size_t ofs = (char *) addr - (char *) s_mg_flash_stm32h7.start;
  6092. if (!is_dualbank()) return FLASH_BASE1;
  6093. return ofs < s_mg_flash_stm32h7.size / 2 ? FLASH_BASE1 : FLASH_BASE2;
  6094. }
  6095. // read-while-write, no need to disable IRQs for standalone usage
  6096. MG_IRAM static bool mg_stm32h7_erase(void *addr) {
  6097. bool ok = false;
  6098. if (flash_page_start(addr) == false) {
  6099. MG_ERROR(("%p is not on a sector boundary", addr));
  6100. } else {
  6101. uintptr_t diff = (char *) addr - (char *) s_mg_flash_stm32h7.start;
  6102. uint32_t sector = diff / s_mg_flash_stm32h7.secsz;
  6103. uint32_t bank = flash_bank(addr);
  6104. uint32_t saved_cr = MG_REG(bank + FLASH_CR); // Save CR value
  6105. flash_unlock();
  6106. if (sector > 7) sector -= 8;
  6107. flash_clear_err(bank);
  6108. MG_REG(bank + FLASH_CR) = MG_BIT(5); // 32-bit write parallelism
  6109. MG_REG(bank + FLASH_CR) |= (sector & 7U) << 8U; // Sector to erase
  6110. MG_REG(bank + FLASH_CR) |= MG_BIT(2); // Sector erase bit
  6111. MG_REG(bank + FLASH_CR) |= MG_BIT(7); // Start erasing
  6112. ok = !flash_is_err(bank);
  6113. MG_DEBUG(("Erase sector %lu @ %p %s. CR %#lx SR %#lx", sector, addr,
  6114. ok ? "ok" : "fail", MG_REG(bank + FLASH_CR),
  6115. MG_REG(bank + FLASH_SR)));
  6116. MG_REG(bank + FLASH_CR) = saved_cr; // Restore CR
  6117. }
  6118. return ok;
  6119. }
  6120. MG_IRAM static bool mg_stm32h7_swap(void) {
  6121. if (!is_dualbank()) return true;
  6122. uint32_t bank = FLASH_BASE1;
  6123. uint32_t desired = flash_bank_is_swapped(bank) ? 0 : MG_BIT(31);
  6124. flash_unlock();
  6125. flash_clear_err(bank);
  6126. // printf("OPTSR_PRG 1 %#lx\n", FLASH->OPTSR_PRG);
  6127. MG_SET_BITS(MG_REG(bank + FLASH_OPTSR_PRG), MG_BIT(31), desired);
  6128. // printf("OPTSR_PRG 2 %#lx\n", FLASH->OPTSR_PRG);
  6129. MG_REG(bank + FLASH_OPTCR) |= MG_BIT(1); // OPTSTART
  6130. while ((MG_REG(bank + FLASH_OPTSR_CUR) & MG_BIT(31)) != desired) (void) 0;
  6131. return true;
  6132. }
  6133. static bool s_flash_irq_disabled;
  6134. MG_IRAM static bool mg_stm32h7_write(void *addr, const void *buf, size_t len) {
  6135. if ((len % s_mg_flash_stm32h7.align) != 0) {
  6136. MG_ERROR(("%lu is not aligned to %lu", len, s_mg_flash_stm32h7.align));
  6137. return false;
  6138. }
  6139. uint32_t bank = flash_bank(addr);
  6140. uint32_t *dst = (uint32_t *) addr;
  6141. uint32_t *src = (uint32_t *) buf;
  6142. uint32_t *end = (uint32_t *) ((char *) buf + len);
  6143. bool ok = true;
  6144. MG_ARM_DISABLE_IRQ();
  6145. flash_unlock();
  6146. flash_clear_err(bank);
  6147. MG_REG(bank + FLASH_CR) = MG_BIT(1); // Set programming flag
  6148. MG_REG(bank + FLASH_CR) |= MG_BIT(5); // 32-bit write parallelism
  6149. while (ok && src < end) {
  6150. if (flash_page_start(dst) && mg_stm32h7_erase(dst) == false) {
  6151. ok = false;
  6152. break;
  6153. }
  6154. *(volatile uint32_t *) dst++ = *src++;
  6155. flash_wait(bank);
  6156. if (flash_is_err(bank)) ok = false;
  6157. }
  6158. if (!s_flash_irq_disabled) MG_ARM_ENABLE_IRQ();
  6159. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  6160. ok ? "ok" : "fail", MG_REG(bank + FLASH_CR),
  6161. MG_REG(bank + FLASH_SR)));
  6162. MG_REG(bank + FLASH_CR) &= ~MG_BIT(1); // Clear programming flag
  6163. return ok;
  6164. }
  6165. // just overwrite instead of swap
  6166. MG_IRAM static void single_bank_swap(char *p1, char *p2, size_t s, size_t ss) {
  6167. // no stdlib calls here
  6168. for (size_t ofs = 0; ofs < s; ofs += ss) {
  6169. mg_stm32h7_write(p1 + ofs, p2 + ofs, ss);
  6170. }
  6171. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  6172. }
  6173. bool mg_ota_begin(size_t new_firmware_size) {
  6174. s_mg_flash_stm32h7.size = MG_REG(FLASH_SIZE_REG) * 1024;
  6175. if (IS_DUALCORE()) {
  6176. // Using only the 1st bank (mapped to CM7)
  6177. s_mg_flash_stm32h7.size /= 2;
  6178. }
  6179. return mg_ota_flash_begin(new_firmware_size, &s_mg_flash_stm32h7);
  6180. }
  6181. bool mg_ota_write(const void *buf, size_t len) {
  6182. return mg_ota_flash_write(buf, len, &s_mg_flash_stm32h7);
  6183. }
  6184. bool mg_ota_end(void) {
  6185. if (mg_ota_flash_end(&s_mg_flash_stm32h7)) {
  6186. if (is_dualbank()) {
  6187. // Bank swap is deferred until reset, been executing in flash, reset
  6188. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  6189. } else {
  6190. // Swap partitions. Pray power does not go away
  6191. MG_INFO(("Swapping partitions, size %u (%u sectors)",
  6192. s_mg_flash_stm32h7.size,
  6193. s_mg_flash_stm32h7.size / s_mg_flash_stm32h7.secsz));
  6194. MG_INFO(("Do NOT power off..."));
  6195. mg_log_level = MG_LL_NONE;
  6196. s_flash_irq_disabled = true;
  6197. // Runs in RAM, will reset when finished
  6198. single_bank_swap(
  6199. (char *) s_mg_flash_stm32h7.start,
  6200. (char *) s_mg_flash_stm32h7.start + s_mg_flash_stm32h7.size / 2,
  6201. s_mg_flash_stm32h7.size / 2, s_mg_flash_stm32h7.secsz);
  6202. }
  6203. }
  6204. return false;
  6205. }
  6206. #endif
  6207. #ifdef MG_ENABLE_LINES
  6208. #line 1 "src/printf.c"
  6209. #endif
  6210. size_t mg_queue_vprintf(struct mg_queue *q, const char *fmt, va_list *ap) {
  6211. size_t len = mg_snprintf(NULL, 0, fmt, ap);
  6212. char *buf;
  6213. if (len == 0 || mg_queue_book(q, &buf, len + 1) < len + 1) {
  6214. len = 0; // Nah. Not enough space
  6215. } else {
  6216. len = mg_vsnprintf((char *) buf, len + 1, fmt, ap);
  6217. mg_queue_add(q, len);
  6218. }
  6219. return len;
  6220. }
  6221. size_t mg_queue_printf(struct mg_queue *q, const char *fmt, ...) {
  6222. va_list ap;
  6223. size_t len;
  6224. va_start(ap, fmt);
  6225. len = mg_queue_vprintf(q, fmt, &ap);
  6226. va_end(ap);
  6227. return len;
  6228. }
  6229. static void mg_pfn_iobuf_private(char ch, void *param, bool expand) {
  6230. struct mg_iobuf *io = (struct mg_iobuf *) param;
  6231. if (expand && io->len + 2 > io->size) mg_iobuf_resize(io, io->len + 2);
  6232. if (io->len + 2 <= io->size) {
  6233. io->buf[io->len++] = (uint8_t) ch;
  6234. io->buf[io->len] = 0;
  6235. } else if (io->len < io->size) {
  6236. io->buf[io->len++] = 0; // Guarantee to 0-terminate
  6237. }
  6238. }
  6239. static void mg_putchar_iobuf_static(char ch, void *param) {
  6240. mg_pfn_iobuf_private(ch, param, false);
  6241. }
  6242. void mg_pfn_iobuf(char ch, void *param) {
  6243. mg_pfn_iobuf_private(ch, param, true);
  6244. }
  6245. size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap) {
  6246. struct mg_iobuf io = {(uint8_t *) buf, len, 0, 0};
  6247. size_t n = mg_vxprintf(mg_putchar_iobuf_static, &io, fmt, ap);
  6248. if (n < len) buf[n] = '\0';
  6249. return n;
  6250. }
  6251. size_t mg_snprintf(char *buf, size_t len, const char *fmt, ...) {
  6252. va_list ap;
  6253. size_t n;
  6254. va_start(ap, fmt);
  6255. n = mg_vsnprintf(buf, len, fmt, &ap);
  6256. va_end(ap);
  6257. return n;
  6258. }
  6259. char *mg_vmprintf(const char *fmt, va_list *ap) {
  6260. struct mg_iobuf io = {0, 0, 0, 256};
  6261. mg_vxprintf(mg_pfn_iobuf, &io, fmt, ap);
  6262. return (char *) io.buf;
  6263. }
  6264. char *mg_mprintf(const char *fmt, ...) {
  6265. char *s;
  6266. va_list ap;
  6267. va_start(ap, fmt);
  6268. s = mg_vmprintf(fmt, &ap);
  6269. va_end(ap);
  6270. return s;
  6271. }
  6272. void mg_pfn_stdout(char c, void *param) {
  6273. putchar(c);
  6274. (void) param;
  6275. }
  6276. static size_t print_ip4(void (*out)(char, void *), void *arg, uint8_t *p) {
  6277. return mg_xprintf(out, arg, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  6278. }
  6279. static size_t print_ip6(void (*out)(char, void *), void *arg, uint16_t *p) {
  6280. return mg_xprintf(out, arg, "[%x:%x:%x:%x:%x:%x:%x:%x]", mg_ntohs(p[0]),
  6281. mg_ntohs(p[1]), mg_ntohs(p[2]), mg_ntohs(p[3]),
  6282. mg_ntohs(p[4]), mg_ntohs(p[5]), mg_ntohs(p[6]),
  6283. mg_ntohs(p[7]));
  6284. }
  6285. size_t mg_print_ip4(void (*out)(char, void *), void *arg, va_list *ap) {
  6286. uint8_t *p = va_arg(*ap, uint8_t *);
  6287. return print_ip4(out, arg, p);
  6288. }
  6289. size_t mg_print_ip6(void (*out)(char, void *), void *arg, va_list *ap) {
  6290. uint16_t *p = va_arg(*ap, uint16_t *);
  6291. return print_ip6(out, arg, p);
  6292. }
  6293. size_t mg_print_ip(void (*out)(char, void *), void *arg, va_list *ap) {
  6294. struct mg_addr *addr = va_arg(*ap, struct mg_addr *);
  6295. if (addr->is_ip6) return print_ip6(out, arg, (uint16_t *) addr->ip);
  6296. return print_ip4(out, arg, (uint8_t *) &addr->ip);
  6297. }
  6298. size_t mg_print_ip_port(void (*out)(char, void *), void *arg, va_list *ap) {
  6299. struct mg_addr *a = va_arg(*ap, struct mg_addr *);
  6300. return mg_xprintf(out, arg, "%M:%hu", mg_print_ip, a, mg_ntohs(a->port));
  6301. }
  6302. size_t mg_print_mac(void (*out)(char, void *), void *arg, va_list *ap) {
  6303. uint8_t *p = va_arg(*ap, uint8_t *);
  6304. return mg_xprintf(out, arg, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2],
  6305. p[3], p[4], p[5]);
  6306. }
  6307. static char mg_esc(int c, bool esc) {
  6308. const char *p, *esc1 = "\b\f\n\r\t\\\"", *esc2 = "bfnrt\\\"";
  6309. for (p = esc ? esc1 : esc2; *p != '\0'; p++) {
  6310. if (*p == c) return esc ? esc2[p - esc1] : esc1[p - esc2];
  6311. }
  6312. return 0;
  6313. }
  6314. static char mg_escape(int c) {
  6315. return mg_esc(c, true);
  6316. }
  6317. static size_t qcpy(void (*out)(char, void *), void *ptr, char *buf,
  6318. size_t len) {
  6319. size_t i = 0, extra = 0;
  6320. for (i = 0; i < len && buf[i] != '\0'; i++) {
  6321. char c = mg_escape(buf[i]);
  6322. if (c) {
  6323. out('\\', ptr), out(c, ptr), extra++;
  6324. } else {
  6325. out(buf[i], ptr);
  6326. }
  6327. }
  6328. return i + extra;
  6329. }
  6330. static size_t bcpy(void (*out)(char, void *), void *arg, uint8_t *buf,
  6331. size_t len) {
  6332. size_t i, j, n = 0;
  6333. const char *t =
  6334. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6335. for (i = 0; i < len; i += 3) {
  6336. uint8_t c1 = buf[i], c2 = i + 1 < len ? buf[i + 1] : 0,
  6337. c3 = i + 2 < len ? buf[i + 2] : 0;
  6338. char tmp[4] = {t[c1 >> 2], t[(c1 & 3) << 4 | (c2 >> 4)], '=', '='};
  6339. if (i + 1 < len) tmp[2] = t[(c2 & 15) << 2 | (c3 >> 6)];
  6340. if (i + 2 < len) tmp[3] = t[c3 & 63];
  6341. for (j = 0; j < sizeof(tmp) && tmp[j] != '\0'; j++) out(tmp[j], arg);
  6342. n += j;
  6343. }
  6344. return n;
  6345. }
  6346. size_t mg_print_hex(void (*out)(char, void *), void *arg, va_list *ap) {
  6347. size_t bl = (size_t) va_arg(*ap, int);
  6348. uint8_t *p = va_arg(*ap, uint8_t *);
  6349. const char *hex = "0123456789abcdef";
  6350. size_t j;
  6351. for (j = 0; j < bl; j++) {
  6352. out(hex[(p[j] >> 4) & 0x0F], arg);
  6353. out(hex[p[j] & 0x0F], arg);
  6354. }
  6355. return 2 * bl;
  6356. }
  6357. size_t mg_print_base64(void (*out)(char, void *), void *arg, va_list *ap) {
  6358. size_t len = (size_t) va_arg(*ap, int);
  6359. uint8_t *buf = va_arg(*ap, uint8_t *);
  6360. return bcpy(out, arg, buf, len);
  6361. }
  6362. size_t mg_print_esc(void (*out)(char, void *), void *arg, va_list *ap) {
  6363. size_t len = (size_t) va_arg(*ap, int);
  6364. char *p = va_arg(*ap, char *);
  6365. if (len == 0) len = p == NULL ? 0 : strlen(p);
  6366. return qcpy(out, arg, p, len);
  6367. }
  6368. #ifdef MG_ENABLE_LINES
  6369. #line 1 "src/queue.c"
  6370. #endif
  6371. #if (defined(__GNUC__) && (__GNUC__ > 4) || \
  6372. (defined(__GNUC_MINOR__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
  6373. defined(__clang__)
  6374. #define MG_MEMORY_BARRIER() __sync_synchronize()
  6375. #elif defined(_MSC_VER) && _MSC_VER >= 1700
  6376. #define MG_MEMORY_BARRIER() MemoryBarrier()
  6377. #elif !defined(MG_MEMORY_BARRIER)
  6378. #define MG_MEMORY_BARRIER()
  6379. #endif
  6380. // Every message in a queue is prepended by a 32-bit message length (ML).
  6381. // If ML is 0, then it is the end, and reader must wrap to the beginning.
  6382. //
  6383. // Queue when q->tail <= q->head:
  6384. // |----- free -----| ML | message1 | ML | message2 | ----- free ------|
  6385. // ^ ^ ^ ^
  6386. // buf tail head len
  6387. //
  6388. // Queue when q->tail > q->head:
  6389. // | ML | message2 |----- free ------| ML | message1 | 0 |---- free ----|
  6390. // ^ ^ ^ ^
  6391. // buf head tail len
  6392. void mg_queue_init(struct mg_queue *q, char *buf, size_t size) {
  6393. q->size = size;
  6394. q->buf = buf;
  6395. q->head = q->tail = 0;
  6396. }
  6397. static size_t mg_queue_read_len(struct mg_queue *q) {
  6398. uint32_t n = 0;
  6399. MG_MEMORY_BARRIER();
  6400. memcpy(&n, q->buf + q->tail, sizeof(n));
  6401. assert(q->tail + n + sizeof(n) <= q->size);
  6402. return n;
  6403. }
  6404. static void mg_queue_write_len(struct mg_queue *q, size_t len) {
  6405. uint32_t n = (uint32_t) len;
  6406. memcpy(q->buf + q->head, &n, sizeof(n));
  6407. MG_MEMORY_BARRIER();
  6408. }
  6409. size_t mg_queue_book(struct mg_queue *q, char **buf, size_t len) {
  6410. size_t space = 0, hs = sizeof(uint32_t) * 2; // *2 is for the 0 marker
  6411. if (q->head >= q->tail && q->head + len + hs <= q->size) {
  6412. space = q->size - q->head - hs; // There is enough space
  6413. } else if (q->head >= q->tail && q->tail > hs) {
  6414. mg_queue_write_len(q, 0); // Not enough space ahead
  6415. q->head = 0; // Wrap head to the beginning
  6416. }
  6417. if (q->head + hs + len < q->tail) space = q->tail - q->head - hs;
  6418. if (buf != NULL) *buf = q->buf + q->head + sizeof(uint32_t);
  6419. return space;
  6420. }
  6421. size_t mg_queue_next(struct mg_queue *q, char **buf) {
  6422. size_t len = 0;
  6423. if (q->tail != q->head) {
  6424. len = mg_queue_read_len(q);
  6425. if (len == 0) { // Zero (head wrapped) ?
  6426. q->tail = 0; // Reset tail to the start
  6427. if (q->head > q->tail) len = mg_queue_read_len(q); // Read again
  6428. }
  6429. }
  6430. if (buf != NULL) *buf = q->buf + q->tail + sizeof(uint32_t);
  6431. assert(q->tail + len <= q->size);
  6432. return len;
  6433. }
  6434. void mg_queue_add(struct mg_queue *q, size_t len) {
  6435. assert(len > 0);
  6436. mg_queue_write_len(q, len);
  6437. assert(q->head + sizeof(uint32_t) * 2 + len <= q->size);
  6438. q->head += len + sizeof(uint32_t);
  6439. }
  6440. void mg_queue_del(struct mg_queue *q, size_t len) {
  6441. q->tail += len + sizeof(uint32_t);
  6442. assert(q->tail + sizeof(uint32_t) <= q->size);
  6443. }
  6444. #ifdef MG_ENABLE_LINES
  6445. #line 1 "src/rpc.c"
  6446. #endif
  6447. void mg_rpc_add(struct mg_rpc **head, struct mg_str method,
  6448. void (*fn)(struct mg_rpc_req *), void *fn_data) {
  6449. struct mg_rpc *rpc = (struct mg_rpc *) calloc(1, sizeof(*rpc));
  6450. if (rpc != NULL) {
  6451. rpc->method = mg_strdup(method);
  6452. rpc->fn = fn;
  6453. rpc->fn_data = fn_data;
  6454. rpc->next = *head, *head = rpc;
  6455. }
  6456. }
  6457. void mg_rpc_del(struct mg_rpc **head, void (*fn)(struct mg_rpc_req *)) {
  6458. struct mg_rpc *r;
  6459. while ((r = *head) != NULL) {
  6460. if (r->fn == fn || fn == NULL) {
  6461. *head = r->next;
  6462. free((void *) r->method.buf);
  6463. free(r);
  6464. } else {
  6465. head = &(*head)->next;
  6466. }
  6467. }
  6468. }
  6469. static void mg_rpc_call(struct mg_rpc_req *r, struct mg_str method) {
  6470. struct mg_rpc *h = r->head == NULL ? NULL : *r->head;
  6471. while (h != NULL && !mg_match(method, h->method, NULL)) h = h->next;
  6472. if (h != NULL) {
  6473. r->rpc = h;
  6474. h->fn(r);
  6475. } else {
  6476. mg_rpc_err(r, -32601, "\"%.*s not found\"", (int) method.len, method.buf);
  6477. }
  6478. }
  6479. void mg_rpc_process(struct mg_rpc_req *r) {
  6480. int len, off = mg_json_get(r->frame, "$.method", &len);
  6481. if (off > 0 && r->frame.buf[off] == '"') {
  6482. struct mg_str method = mg_str_n(&r->frame.buf[off + 1], (size_t) len - 2);
  6483. mg_rpc_call(r, method);
  6484. } else if ((off = mg_json_get(r->frame, "$.result", &len)) > 0 ||
  6485. (off = mg_json_get(r->frame, "$.error", &len)) > 0) {
  6486. mg_rpc_call(r, mg_str("")); // JSON response! call "" method handler
  6487. } else {
  6488. mg_rpc_err(r, -32700, "%m", mg_print_esc, (int) r->frame.len,
  6489. r->frame.buf); // Invalid
  6490. }
  6491. }
  6492. void mg_rpc_vok(struct mg_rpc_req *r, const char *fmt, va_list *ap) {
  6493. int len, off = mg_json_get(r->frame, "$.id", &len);
  6494. if (off > 0) {
  6495. mg_xprintf(r->pfn, r->pfn_data, "{%m:%.*s,%m:", mg_print_esc, 0, "id", len,
  6496. &r->frame.buf[off], mg_print_esc, 0, "result");
  6497. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  6498. mg_xprintf(r->pfn, r->pfn_data, "}");
  6499. }
  6500. }
  6501. void mg_rpc_ok(struct mg_rpc_req *r, const char *fmt, ...) {
  6502. va_list ap;
  6503. va_start(ap, fmt);
  6504. mg_rpc_vok(r, fmt, &ap);
  6505. va_end(ap);
  6506. }
  6507. void mg_rpc_verr(struct mg_rpc_req *r, int code, const char *fmt, va_list *ap) {
  6508. int len, off = mg_json_get(r->frame, "$.id", &len);
  6509. mg_xprintf(r->pfn, r->pfn_data, "{");
  6510. if (off > 0) {
  6511. mg_xprintf(r->pfn, r->pfn_data, "%m:%.*s,", mg_print_esc, 0, "id", len,
  6512. &r->frame.buf[off]);
  6513. }
  6514. mg_xprintf(r->pfn, r->pfn_data, "%m:{%m:%d,%m:", mg_print_esc, 0, "error",
  6515. mg_print_esc, 0, "code", code, mg_print_esc, 0, "message");
  6516. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  6517. mg_xprintf(r->pfn, r->pfn_data, "}}");
  6518. }
  6519. void mg_rpc_err(struct mg_rpc_req *r, int code, const char *fmt, ...) {
  6520. va_list ap;
  6521. va_start(ap, fmt);
  6522. mg_rpc_verr(r, code, fmt, &ap);
  6523. va_end(ap);
  6524. }
  6525. static size_t print_methods(mg_pfn_t pfn, void *pfn_data, va_list *ap) {
  6526. struct mg_rpc *h, **head = (struct mg_rpc **) va_arg(*ap, void **);
  6527. size_t len = 0;
  6528. for (h = *head; h != NULL; h = h->next) {
  6529. if (h->method.len == 0) continue; // Ignore response handler
  6530. len += mg_xprintf(pfn, pfn_data, "%s%m", h == *head ? "" : ",",
  6531. mg_print_esc, (int) h->method.len, h->method.buf);
  6532. }
  6533. return len;
  6534. }
  6535. void mg_rpc_list(struct mg_rpc_req *r) {
  6536. mg_rpc_ok(r, "[%M]", print_methods, r->head);
  6537. }
  6538. #ifdef MG_ENABLE_LINES
  6539. #line 1 "src/sha1.c"
  6540. #endif
  6541. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  6542. /* 100% Public Domain */
  6543. union char64long16 {
  6544. unsigned char c[64];
  6545. uint32_t l[16];
  6546. };
  6547. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6548. static uint32_t blk0(union char64long16 *block, int i) {
  6549. if (MG_BIG_ENDIAN) {
  6550. } else {
  6551. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  6552. (rol(block->l[i], 8) & 0x00FF00FF);
  6553. }
  6554. return block->l[i];
  6555. }
  6556. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  6557. #undef blk
  6558. #undef R0
  6559. #undef R1
  6560. #undef R2
  6561. #undef R3
  6562. #undef R4
  6563. #define blk(i) \
  6564. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  6565. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6566. 1))
  6567. #define R0(v, w, x, y, z, i) \
  6568. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6569. w = rol(w, 30);
  6570. #define R1(v, w, x, y, z, i) \
  6571. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6572. w = rol(w, 30);
  6573. #define R2(v, w, x, y, z, i) \
  6574. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6575. w = rol(w, 30);
  6576. #define R3(v, w, x, y, z, i) \
  6577. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6578. w = rol(w, 30);
  6579. #define R4(v, w, x, y, z, i) \
  6580. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6581. w = rol(w, 30);
  6582. static void mg_sha1_transform(uint32_t state[5],
  6583. const unsigned char *buffer) {
  6584. uint32_t a, b, c, d, e;
  6585. union char64long16 block[1];
  6586. memcpy(block, buffer, 64);
  6587. a = state[0];
  6588. b = state[1];
  6589. c = state[2];
  6590. d = state[3];
  6591. e = state[4];
  6592. R0(a, b, c, d, e, 0);
  6593. R0(e, a, b, c, d, 1);
  6594. R0(d, e, a, b, c, 2);
  6595. R0(c, d, e, a, b, 3);
  6596. R0(b, c, d, e, a, 4);
  6597. R0(a, b, c, d, e, 5);
  6598. R0(e, a, b, c, d, 6);
  6599. R0(d, e, a, b, c, 7);
  6600. R0(c, d, e, a, b, 8);
  6601. R0(b, c, d, e, a, 9);
  6602. R0(a, b, c, d, e, 10);
  6603. R0(e, a, b, c, d, 11);
  6604. R0(d, e, a, b, c, 12);
  6605. R0(c, d, e, a, b, 13);
  6606. R0(b, c, d, e, a, 14);
  6607. R0(a, b, c, d, e, 15);
  6608. R1(e, a, b, c, d, 16);
  6609. R1(d, e, a, b, c, 17);
  6610. R1(c, d, e, a, b, 18);
  6611. R1(b, c, d, e, a, 19);
  6612. R2(a, b, c, d, e, 20);
  6613. R2(e, a, b, c, d, 21);
  6614. R2(d, e, a, b, c, 22);
  6615. R2(c, d, e, a, b, 23);
  6616. R2(b, c, d, e, a, 24);
  6617. R2(a, b, c, d, e, 25);
  6618. R2(e, a, b, c, d, 26);
  6619. R2(d, e, a, b, c, 27);
  6620. R2(c, d, e, a, b, 28);
  6621. R2(b, c, d, e, a, 29);
  6622. R2(a, b, c, d, e, 30);
  6623. R2(e, a, b, c, d, 31);
  6624. R2(d, e, a, b, c, 32);
  6625. R2(c, d, e, a, b, 33);
  6626. R2(b, c, d, e, a, 34);
  6627. R2(a, b, c, d, e, 35);
  6628. R2(e, a, b, c, d, 36);
  6629. R2(d, e, a, b, c, 37);
  6630. R2(c, d, e, a, b, 38);
  6631. R2(b, c, d, e, a, 39);
  6632. R3(a, b, c, d, e, 40);
  6633. R3(e, a, b, c, d, 41);
  6634. R3(d, e, a, b, c, 42);
  6635. R3(c, d, e, a, b, 43);
  6636. R3(b, c, d, e, a, 44);
  6637. R3(a, b, c, d, e, 45);
  6638. R3(e, a, b, c, d, 46);
  6639. R3(d, e, a, b, c, 47);
  6640. R3(c, d, e, a, b, 48);
  6641. R3(b, c, d, e, a, 49);
  6642. R3(a, b, c, d, e, 50);
  6643. R3(e, a, b, c, d, 51);
  6644. R3(d, e, a, b, c, 52);
  6645. R3(c, d, e, a, b, 53);
  6646. R3(b, c, d, e, a, 54);
  6647. R3(a, b, c, d, e, 55);
  6648. R3(e, a, b, c, d, 56);
  6649. R3(d, e, a, b, c, 57);
  6650. R3(c, d, e, a, b, 58);
  6651. R3(b, c, d, e, a, 59);
  6652. R4(a, b, c, d, e, 60);
  6653. R4(e, a, b, c, d, 61);
  6654. R4(d, e, a, b, c, 62);
  6655. R4(c, d, e, a, b, 63);
  6656. R4(b, c, d, e, a, 64);
  6657. R4(a, b, c, d, e, 65);
  6658. R4(e, a, b, c, d, 66);
  6659. R4(d, e, a, b, c, 67);
  6660. R4(c, d, e, a, b, 68);
  6661. R4(b, c, d, e, a, 69);
  6662. R4(a, b, c, d, e, 70);
  6663. R4(e, a, b, c, d, 71);
  6664. R4(d, e, a, b, c, 72);
  6665. R4(c, d, e, a, b, 73);
  6666. R4(b, c, d, e, a, 74);
  6667. R4(a, b, c, d, e, 75);
  6668. R4(e, a, b, c, d, 76);
  6669. R4(d, e, a, b, c, 77);
  6670. R4(c, d, e, a, b, 78);
  6671. R4(b, c, d, e, a, 79);
  6672. state[0] += a;
  6673. state[1] += b;
  6674. state[2] += c;
  6675. state[3] += d;
  6676. state[4] += e;
  6677. /* Erase working structures. The order of operations is important,
  6678. * used to ensure that compiler doesn't optimize those out. */
  6679. memset(block, 0, sizeof(block));
  6680. a = b = c = d = e = 0;
  6681. (void) a;
  6682. (void) b;
  6683. (void) c;
  6684. (void) d;
  6685. (void) e;
  6686. }
  6687. void mg_sha1_init(mg_sha1_ctx *context) {
  6688. context->state[0] = 0x67452301;
  6689. context->state[1] = 0xEFCDAB89;
  6690. context->state[2] = 0x98BADCFE;
  6691. context->state[3] = 0x10325476;
  6692. context->state[4] = 0xC3D2E1F0;
  6693. context->count[0] = context->count[1] = 0;
  6694. }
  6695. void mg_sha1_update(mg_sha1_ctx *context, const unsigned char *data,
  6696. size_t len) {
  6697. size_t i, j;
  6698. j = context->count[0];
  6699. if ((context->count[0] += (uint32_t) len << 3) < j) context->count[1]++;
  6700. context->count[1] += (uint32_t) (len >> 29);
  6701. j = (j >> 3) & 63;
  6702. if ((j + len) > 63) {
  6703. memcpy(&context->buffer[j], data, (i = 64 - j));
  6704. mg_sha1_transform(context->state, context->buffer);
  6705. for (; i + 63 < len; i += 64) {
  6706. mg_sha1_transform(context->state, &data[i]);
  6707. }
  6708. j = 0;
  6709. } else
  6710. i = 0;
  6711. memcpy(&context->buffer[j], &data[i], len - i);
  6712. }
  6713. void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *context) {
  6714. unsigned i;
  6715. unsigned char finalcount[8], c;
  6716. for (i = 0; i < 8; i++) {
  6717. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  6718. ((3 - (i & 3)) * 8)) &
  6719. 255);
  6720. }
  6721. c = 0200;
  6722. mg_sha1_update(context, &c, 1);
  6723. while ((context->count[0] & 504) != 448) {
  6724. c = 0000;
  6725. mg_sha1_update(context, &c, 1);
  6726. }
  6727. mg_sha1_update(context, finalcount, 8);
  6728. for (i = 0; i < 20; i++) {
  6729. digest[i] =
  6730. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  6731. }
  6732. memset(context, '\0', sizeof(*context));
  6733. memset(&finalcount, '\0', sizeof(finalcount));
  6734. }
  6735. #ifdef MG_ENABLE_LINES
  6736. #line 1 "src/sha256.c"
  6737. #endif
  6738. // https://github.com/B-Con/crypto-algorithms
  6739. // Author: Brad Conte (brad AT bradconte.com)
  6740. // Disclaimer: This code is presented "as is" without any guarantees.
  6741. // Details: Defines the API for the corresponding SHA1 implementation.
  6742. // Copyright: public domain
  6743. #define ror(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
  6744. #define ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
  6745. #define maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
  6746. #define ep0(x) (ror(x, 2) ^ ror(x, 13) ^ ror(x, 22))
  6747. #define ep1(x) (ror(x, 6) ^ ror(x, 11) ^ ror(x, 25))
  6748. #define sig0(x) (ror(x, 7) ^ ror(x, 18) ^ ((x) >> 3))
  6749. #define sig1(x) (ror(x, 17) ^ ror(x, 19) ^ ((x) >> 10))
  6750. static const uint32_t mg_sha256_k[64] = {
  6751. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
  6752. 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  6753. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
  6754. 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  6755. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
  6756. 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  6757. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
  6758. 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  6759. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
  6760. 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  6761. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
  6762. void mg_sha256_init(mg_sha256_ctx *ctx) {
  6763. ctx->len = 0;
  6764. ctx->bits = 0;
  6765. ctx->state[0] = 0x6a09e667;
  6766. ctx->state[1] = 0xbb67ae85;
  6767. ctx->state[2] = 0x3c6ef372;
  6768. ctx->state[3] = 0xa54ff53a;
  6769. ctx->state[4] = 0x510e527f;
  6770. ctx->state[5] = 0x9b05688c;
  6771. ctx->state[6] = 0x1f83d9ab;
  6772. ctx->state[7] = 0x5be0cd19;
  6773. }
  6774. static void mg_sha256_chunk(mg_sha256_ctx *ctx) {
  6775. int i, j;
  6776. uint32_t a, b, c, d, e, f, g, h;
  6777. uint32_t m[64];
  6778. for (i = 0, j = 0; i < 16; ++i, j += 4)
  6779. m[i] = (uint32_t) (((uint32_t) ctx->buffer[j] << 24) |
  6780. ((uint32_t) ctx->buffer[j + 1] << 16) |
  6781. ((uint32_t) ctx->buffer[j + 2] << 8) |
  6782. ((uint32_t) ctx->buffer[j + 3]));
  6783. for (; i < 64; ++i)
  6784. m[i] = sig1(m[i - 2]) + m[i - 7] + sig0(m[i - 15]) + m[i - 16];
  6785. a = ctx->state[0];
  6786. b = ctx->state[1];
  6787. c = ctx->state[2];
  6788. d = ctx->state[3];
  6789. e = ctx->state[4];
  6790. f = ctx->state[5];
  6791. g = ctx->state[6];
  6792. h = ctx->state[7];
  6793. for (i = 0; i < 64; ++i) {
  6794. uint32_t t1 = h + ep1(e) + ch(e, f, g) + mg_sha256_k[i] + m[i];
  6795. uint32_t t2 = ep0(a) + maj(a, b, c);
  6796. h = g;
  6797. g = f;
  6798. f = e;
  6799. e = d + t1;
  6800. d = c;
  6801. c = b;
  6802. b = a;
  6803. a = t1 + t2;
  6804. }
  6805. ctx->state[0] += a;
  6806. ctx->state[1] += b;
  6807. ctx->state[2] += c;
  6808. ctx->state[3] += d;
  6809. ctx->state[4] += e;
  6810. ctx->state[5] += f;
  6811. ctx->state[6] += g;
  6812. ctx->state[7] += h;
  6813. }
  6814. void mg_sha256_update(mg_sha256_ctx *ctx, const unsigned char *data,
  6815. size_t len) {
  6816. size_t i;
  6817. for (i = 0; i < len; i++) {
  6818. ctx->buffer[ctx->len] = data[i];
  6819. if ((++ctx->len) == 64) {
  6820. mg_sha256_chunk(ctx);
  6821. ctx->bits += 512;
  6822. ctx->len = 0;
  6823. }
  6824. }
  6825. }
  6826. // TODO: make final reusable (remove side effects)
  6827. void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *ctx) {
  6828. uint32_t i = ctx->len;
  6829. if (i < 56) {
  6830. ctx->buffer[i++] = 0x80;
  6831. while (i < 56) {
  6832. ctx->buffer[i++] = 0x00;
  6833. }
  6834. } else {
  6835. ctx->buffer[i++] = 0x80;
  6836. while (i < 64) {
  6837. ctx->buffer[i++] = 0x00;
  6838. }
  6839. mg_sha256_chunk(ctx);
  6840. memset(ctx->buffer, 0, 56);
  6841. }
  6842. ctx->bits += ctx->len * 8;
  6843. ctx->buffer[63] = (uint8_t) ((ctx->bits) & 0xff);
  6844. ctx->buffer[62] = (uint8_t) ((ctx->bits >> 8) & 0xff);
  6845. ctx->buffer[61] = (uint8_t) ((ctx->bits >> 16) & 0xff);
  6846. ctx->buffer[60] = (uint8_t) ((ctx->bits >> 24) & 0xff);
  6847. ctx->buffer[59] = (uint8_t) ((ctx->bits >> 32) & 0xff);
  6848. ctx->buffer[58] = (uint8_t) ((ctx->bits >> 40) & 0xff);
  6849. ctx->buffer[57] = (uint8_t) ((ctx->bits >> 48) & 0xff);
  6850. ctx->buffer[56] = (uint8_t) ((ctx->bits >> 56) & 0xff);
  6851. mg_sha256_chunk(ctx);
  6852. for (i = 0; i < 4; ++i) {
  6853. digest[i] = (uint8_t) ((ctx->state[0] >> (24 - i * 8)) & 0xff);
  6854. digest[i + 4] = (uint8_t) ((ctx->state[1] >> (24 - i * 8)) & 0xff);
  6855. digest[i + 8] = (uint8_t) ((ctx->state[2] >> (24 - i * 8)) & 0xff);
  6856. digest[i + 12] = (uint8_t) ((ctx->state[3] >> (24 - i * 8)) & 0xff);
  6857. digest[i + 16] = (uint8_t) ((ctx->state[4] >> (24 - i * 8)) & 0xff);
  6858. digest[i + 20] = (uint8_t) ((ctx->state[5] >> (24 - i * 8)) & 0xff);
  6859. digest[i + 24] = (uint8_t) ((ctx->state[6] >> (24 - i * 8)) & 0xff);
  6860. digest[i + 28] = (uint8_t) ((ctx->state[7] >> (24 - i * 8)) & 0xff);
  6861. }
  6862. }
  6863. void mg_hmac_sha256(uint8_t dst[32], uint8_t *key, size_t keysz, uint8_t *data,
  6864. size_t datasz) {
  6865. mg_sha256_ctx ctx;
  6866. uint8_t k[64] = {0};
  6867. uint8_t o_pad[64], i_pad[64];
  6868. unsigned int i;
  6869. memset(i_pad, 0x36, sizeof(i_pad));
  6870. memset(o_pad, 0x5c, sizeof(o_pad));
  6871. if (keysz < 64) {
  6872. if (keysz > 0) memmove(k, key, keysz);
  6873. } else {
  6874. mg_sha256_init(&ctx);
  6875. mg_sha256_update(&ctx, key, keysz);
  6876. mg_sha256_final(k, &ctx);
  6877. }
  6878. for (i = 0; i < sizeof(k); i++) {
  6879. i_pad[i] ^= k[i];
  6880. o_pad[i] ^= k[i];
  6881. }
  6882. mg_sha256_init(&ctx);
  6883. mg_sha256_update(&ctx, i_pad, sizeof(i_pad));
  6884. mg_sha256_update(&ctx, data, datasz);
  6885. mg_sha256_final(dst, &ctx);
  6886. mg_sha256_init(&ctx);
  6887. mg_sha256_update(&ctx, o_pad, sizeof(o_pad));
  6888. mg_sha256_update(&ctx, dst, 32);
  6889. mg_sha256_final(dst, &ctx);
  6890. }
  6891. #ifdef MG_ENABLE_LINES
  6892. #line 1 "src/sntp.c"
  6893. #endif
  6894. #define SNTP_TIME_OFFSET 2208988800U // (1970 - 1900) in seconds
  6895. #define SNTP_MAX_FRAC 4294967295.0 // 2 ** 32 - 1
  6896. static uint64_t s_boot_timestamp = 0; // Updated by SNTP
  6897. uint64_t mg_now(void) {
  6898. return mg_millis() + s_boot_timestamp;
  6899. }
  6900. static int64_t gettimestamp(const uint32_t *data) {
  6901. uint32_t sec = mg_ntohl(data[0]), frac = mg_ntohl(data[1]);
  6902. if (sec) sec -= SNTP_TIME_OFFSET;
  6903. return ((int64_t) sec) * 1000 + (int64_t) (frac / SNTP_MAX_FRAC * 1000.0);
  6904. }
  6905. int64_t mg_sntp_parse(const unsigned char *buf, size_t len) {
  6906. int64_t epoch_milliseconds = -1;
  6907. int mode = len > 0 ? buf[0] & 7 : 0;
  6908. int version = len > 0 ? (buf[0] >> 3) & 7 : 0;
  6909. if (len < 48) {
  6910. MG_ERROR(("%s", "corrupt packet"));
  6911. } else if (mode != 4 && mode != 5) {
  6912. MG_ERROR(("%s", "not a server reply"));
  6913. } else if (buf[1] == 0) {
  6914. MG_ERROR(("%s", "server sent a kiss of death"));
  6915. } else if (version == 4 || version == 3) {
  6916. // int64_t ref = gettimestamp((uint32_t *) &buf[16]);
  6917. int64_t origin_time = gettimestamp((uint32_t *) &buf[24]);
  6918. int64_t receive_time = gettimestamp((uint32_t *) &buf[32]);
  6919. int64_t transmit_time = gettimestamp((uint32_t *) &buf[40]);
  6920. int64_t now = (int64_t) mg_millis();
  6921. int64_t latency = (now - origin_time) - (transmit_time - receive_time);
  6922. epoch_milliseconds = transmit_time + latency / 2;
  6923. s_boot_timestamp = (uint64_t) (epoch_milliseconds - now);
  6924. } else {
  6925. MG_ERROR(("unexpected version: %d", version));
  6926. }
  6927. return epoch_milliseconds;
  6928. }
  6929. static void sntp_cb(struct mg_connection *c, int ev, void *ev_data) {
  6930. uint64_t *expiration_time = (uint64_t *) c->data;
  6931. if (ev == MG_EV_OPEN) {
  6932. *expiration_time = mg_millis() + 3000; // Store expiration time in 3s
  6933. } else if (ev == MG_EV_CONNECT) {
  6934. mg_sntp_request(c);
  6935. } else if (ev == MG_EV_READ) {
  6936. int64_t milliseconds = mg_sntp_parse(c->recv.buf, c->recv.len);
  6937. if (milliseconds > 0) {
  6938. s_boot_timestamp = (uint64_t) milliseconds - mg_millis();
  6939. mg_call(c, MG_EV_SNTP_TIME, (uint64_t *) &milliseconds);
  6940. MG_DEBUG(("%lu got time: %lld ms from epoch", c->id, milliseconds));
  6941. }
  6942. // mg_iobuf_del(&c->recv, 0, c->recv.len); // Free receive buffer
  6943. c->is_closing = 1;
  6944. } else if (ev == MG_EV_POLL) {
  6945. if (mg_millis() > *expiration_time) c->is_closing = 1;
  6946. } else if (ev == MG_EV_CLOSE) {
  6947. }
  6948. (void) ev_data;
  6949. }
  6950. void mg_sntp_request(struct mg_connection *c) {
  6951. if (c->is_resolving) {
  6952. MG_ERROR(("%lu wait until resolved", c->id));
  6953. } else {
  6954. int64_t now = (int64_t) mg_millis(); // Use int64_t, for vc98
  6955. uint8_t buf[48] = {0};
  6956. uint32_t *t = (uint32_t *) &buf[40];
  6957. double frac = ((double) (now % 1000)) / 1000.0 * SNTP_MAX_FRAC;
  6958. buf[0] = (0 << 6) | (4 << 3) | 3;
  6959. t[0] = mg_htonl((uint32_t) (now / 1000) + SNTP_TIME_OFFSET);
  6960. t[1] = mg_htonl((uint32_t) frac);
  6961. mg_send(c, buf, sizeof(buf));
  6962. }
  6963. }
  6964. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url,
  6965. mg_event_handler_t fn, void *fnd) {
  6966. struct mg_connection *c = NULL;
  6967. if (url == NULL) url = "udp://time.google.com:123";
  6968. if ((c = mg_connect(mgr, url, fn, fnd)) != NULL) {
  6969. c->pfn = sntp_cb;
  6970. sntp_cb(c, MG_EV_OPEN, (void *) url);
  6971. }
  6972. return c;
  6973. }
  6974. #ifdef MG_ENABLE_LINES
  6975. #line 1 "src/sock.c"
  6976. #endif
  6977. #if MG_ENABLE_SOCKET
  6978. #ifndef closesocket
  6979. #define closesocket(x) close(x)
  6980. #endif
  6981. #define FD(c_) ((MG_SOCKET_TYPE) (size_t) (c_)->fd)
  6982. #define S2PTR(s_) ((void *) (size_t) (s_))
  6983. #ifndef MSG_NONBLOCKING
  6984. #define MSG_NONBLOCKING 0
  6985. #endif
  6986. #ifndef AF_INET6
  6987. #define AF_INET6 10
  6988. #endif
  6989. #ifndef MG_SOCK_ERR
  6990. #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? errno : 0)
  6991. #endif
  6992. #ifndef MG_SOCK_INTR
  6993. #define MG_SOCK_INTR(fd) (fd == MG_INVALID_SOCKET && MG_SOCK_ERR(-1) == EINTR)
  6994. #endif
  6995. #ifndef MG_SOCK_PENDING
  6996. #define MG_SOCK_PENDING(errcode) \
  6997. (((errcode) < 0) && (errno == EINPROGRESS || errno == EWOULDBLOCK))
  6998. #endif
  6999. #ifndef MG_SOCK_RESET
  7000. #define MG_SOCK_RESET(errcode) \
  7001. (((errcode) < 0) && (errno == EPIPE || errno == ECONNRESET))
  7002. #endif
  7003. union usa {
  7004. struct sockaddr sa;
  7005. struct sockaddr_in sin;
  7006. #if MG_ENABLE_IPV6
  7007. struct sockaddr_in6 sin6;
  7008. #endif
  7009. };
  7010. static socklen_t tousa(struct mg_addr *a, union usa *usa) {
  7011. socklen_t len = sizeof(usa->sin);
  7012. memset(usa, 0, sizeof(*usa));
  7013. usa->sin.sin_family = AF_INET;
  7014. usa->sin.sin_port = a->port;
  7015. memcpy(&usa->sin.sin_addr, a->ip, sizeof(uint32_t));
  7016. #if MG_ENABLE_IPV6
  7017. if (a->is_ip6) {
  7018. usa->sin.sin_family = AF_INET6;
  7019. usa->sin6.sin6_port = a->port;
  7020. usa->sin6.sin6_scope_id = a->scope_id;
  7021. memcpy(&usa->sin6.sin6_addr, a->ip, sizeof(a->ip));
  7022. len = sizeof(usa->sin6);
  7023. }
  7024. #endif
  7025. return len;
  7026. }
  7027. static void tomgaddr(union usa *usa, struct mg_addr *a, bool is_ip6) {
  7028. a->is_ip6 = is_ip6;
  7029. a->port = usa->sin.sin_port;
  7030. memcpy(&a->ip, &usa->sin.sin_addr, sizeof(uint32_t));
  7031. #if MG_ENABLE_IPV6
  7032. if (is_ip6) {
  7033. memcpy(a->ip, &usa->sin6.sin6_addr, sizeof(a->ip));
  7034. a->port = usa->sin6.sin6_port;
  7035. a->scope_id = (uint8_t) usa->sin6.sin6_scope_id;
  7036. }
  7037. #endif
  7038. }
  7039. static void setlocaddr(MG_SOCKET_TYPE fd, struct mg_addr *addr) {
  7040. union usa usa;
  7041. socklen_t n = sizeof(usa);
  7042. if (getsockname(fd, &usa.sa, &n) == 0) {
  7043. tomgaddr(&usa, addr, n != sizeof(usa.sin));
  7044. }
  7045. }
  7046. static void iolog(struct mg_connection *c, char *buf, long n, bool r) {
  7047. if (n == MG_IO_WAIT) {
  7048. // Do nothing
  7049. } else if (n <= 0) {
  7050. c->is_closing = 1; // Termination. Don't call mg_error(): #1529
  7051. } else if (n > 0) {
  7052. if (c->is_hexdumping) {
  7053. MG_INFO(("\n-- %lu %M %s %M %ld", c->id, mg_print_ip_port, &c->loc,
  7054. r ? "<-" : "->", mg_print_ip_port, &c->rem, n));
  7055. mg_hexdump(buf, (size_t) n);
  7056. }
  7057. if (r) {
  7058. c->recv.len += (size_t) n;
  7059. mg_call(c, MG_EV_READ, &n);
  7060. } else {
  7061. mg_iobuf_del(&c->send, 0, (size_t) n);
  7062. // if (c->send.len == 0) mg_iobuf_resize(&c->send, 0);
  7063. if (c->send.len == 0) {
  7064. MG_EPOLL_MOD(c, 0);
  7065. }
  7066. mg_call(c, MG_EV_WRITE, &n);
  7067. }
  7068. }
  7069. }
  7070. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  7071. long n;
  7072. if (c->is_udp) {
  7073. union usa usa;
  7074. socklen_t slen = tousa(&c->rem, &usa);
  7075. n = sendto(FD(c), (char *) buf, len, 0, &usa.sa, slen);
  7076. if (n > 0) setlocaddr(FD(c), &c->loc);
  7077. } else {
  7078. n = send(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  7079. }
  7080. MG_VERBOSE(("%lu %ld %d", c->id, n, MG_SOCK_ERR(n)));
  7081. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  7082. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  7083. if (n <= 0) return MG_IO_ERR;
  7084. return n;
  7085. }
  7086. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  7087. if (c->is_udp) {
  7088. long n = mg_io_send(c, buf, len);
  7089. MG_DEBUG(("%lu %ld %lu:%lu:%lu %ld err %d", c->id, c->fd, c->send.len,
  7090. c->recv.len, c->rtls.len, n, MG_SOCK_ERR(n)));
  7091. iolog(c, (char *) buf, n, false);
  7092. return n > 0;
  7093. } else {
  7094. return mg_iobuf_add(&c->send, c->send.len, buf, len);
  7095. }
  7096. }
  7097. static void mg_set_non_blocking_mode(MG_SOCKET_TYPE fd) {
  7098. #if defined(MG_CUSTOM_NONBLOCK)
  7099. MG_CUSTOM_NONBLOCK(fd);
  7100. #elif MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  7101. unsigned long on = 1;
  7102. ioctlsocket(fd, FIONBIO, &on);
  7103. #elif MG_ENABLE_RL
  7104. unsigned long on = 1;
  7105. ioctlsocket(fd, FIONBIO, &on);
  7106. #elif MG_ENABLE_FREERTOS_TCP
  7107. const BaseType_t off = 0;
  7108. if (setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)) != 0) (void) 0;
  7109. if (setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)) != 0) (void) 0;
  7110. #elif MG_ENABLE_LWIP
  7111. lwip_fcntl(fd, F_SETFL, O_NONBLOCK);
  7112. #elif MG_ARCH == MG_ARCH_AZURERTOS
  7113. fcntl(fd, F_SETFL, O_NONBLOCK);
  7114. #elif MG_ARCH == MG_ARCH_TIRTOS
  7115. int val = 0;
  7116. setsockopt(fd, SOL_SOCKET, SO_BLOCKING, &val, sizeof(val));
  7117. // SPRU524J section 3.3.3 page 63, SO_SNDLOWAT
  7118. int sz = sizeof(val);
  7119. getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &val, &sz);
  7120. val /= 2; // set send low-water mark at half send buffer size
  7121. setsockopt(fd, SOL_SOCKET, SO_SNDLOWAT, &val, sizeof(val));
  7122. #else
  7123. fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); // Non-blocking mode
  7124. fcntl(fd, F_SETFD, FD_CLOEXEC); // Set close-on-exec
  7125. #endif
  7126. }
  7127. bool mg_open_listener(struct mg_connection *c, const char *url) {
  7128. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  7129. bool success = false;
  7130. c->loc.port = mg_htons(mg_url_port(url));
  7131. if (!mg_aton(mg_url_host(url), &c->loc)) {
  7132. MG_ERROR(("invalid listening URL: %s", url));
  7133. } else {
  7134. union usa usa;
  7135. socklen_t slen = tousa(&c->loc, &usa);
  7136. int rc, on = 1, af = c->loc.is_ip6 ? AF_INET6 : AF_INET;
  7137. int type = strncmp(url, "udp:", 4) == 0 ? SOCK_DGRAM : SOCK_STREAM;
  7138. int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP;
  7139. (void) on;
  7140. if ((fd = socket(af, type, proto)) == MG_INVALID_SOCKET) {
  7141. MG_ERROR(("socket: %d", MG_SOCK_ERR(-1)));
  7142. #if defined(SO_EXCLUSIVEADDRUSE)
  7143. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  7144. (char *) &on, sizeof(on))) != 0) {
  7145. // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE"
  7146. MG_ERROR(("setsockopt(SO_EXCLUSIVEADDRUSE): %d %d", on, MG_SOCK_ERR(rc)));
  7147. #elif defined(SO_REUSEADDR) && (!defined(LWIP_SOCKET) || SO_REUSE)
  7148. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on,
  7149. sizeof(on))) != 0) {
  7150. // 1. SO_REUSEADDR semantics on UNIX and Windows is different. On
  7151. // Windows, SO_REUSEADDR allows to bind a socket to a port without error
  7152. // even if the port is already open by another program. This is not the
  7153. // behavior SO_REUSEADDR was designed for, and leads to hard-to-track
  7154. // failure scenarios.
  7155. //
  7156. // 2. For LWIP, SO_REUSEADDR should be explicitly enabled by defining
  7157. // SO_REUSE = 1 in lwipopts.h, otherwise the code below will compile but
  7158. // won't work! (setsockopt will return EINVAL)
  7159. MG_ERROR(("setsockopt(SO_REUSEADDR): %d", MG_SOCK_ERR(rc)));
  7160. #endif
  7161. #if MG_IPV6_V6ONLY
  7162. // Bind only to the V6 address, not V4 address on this port
  7163. } else if (c->loc.is_ip6 &&
  7164. (rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &on,
  7165. sizeof(on))) != 0) {
  7166. // See #2089. Allow to bind v4 and v6 sockets on the same port
  7167. MG_ERROR(("setsockopt(IPV6_V6ONLY): %d", MG_SOCK_ERR(rc)));
  7168. #endif
  7169. } else if ((rc = bind(fd, &usa.sa, slen)) != 0) {
  7170. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  7171. } else if ((type == SOCK_STREAM &&
  7172. (rc = listen(fd, MG_SOCK_LISTEN_BACKLOG_SIZE)) != 0)) {
  7173. // NOTE(lsm): FreeRTOS uses backlog value as a connection limit
  7174. // In case port was set to 0, get the real port number
  7175. MG_ERROR(("listen: %d", MG_SOCK_ERR(rc)));
  7176. } else {
  7177. setlocaddr(fd, &c->loc);
  7178. mg_set_non_blocking_mode(fd);
  7179. c->fd = S2PTR(fd);
  7180. MG_EPOLL_ADD(c);
  7181. success = true;
  7182. }
  7183. }
  7184. if (success == false && fd != MG_INVALID_SOCKET) closesocket(fd);
  7185. return success;
  7186. }
  7187. static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
  7188. long n = 0;
  7189. if (c->is_udp) {
  7190. union usa usa;
  7191. socklen_t slen = tousa(&c->rem, &usa);
  7192. n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
  7193. if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
  7194. } else {
  7195. n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  7196. }
  7197. MG_VERBOSE(("%lu %ld %d", c->id, n, MG_SOCK_ERR(n)));
  7198. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  7199. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  7200. if (n <= 0) return MG_IO_ERR;
  7201. return n;
  7202. }
  7203. static bool ioalloc(struct mg_connection *c, struct mg_iobuf *io) {
  7204. bool res = false;
  7205. if (io->len >= MG_MAX_RECV_SIZE) {
  7206. mg_error(c, "MG_MAX_RECV_SIZE");
  7207. } else if (io->size <= io->len &&
  7208. !mg_iobuf_resize(io, io->size + MG_IO_SIZE)) {
  7209. mg_error(c, "OOM");
  7210. } else {
  7211. res = true;
  7212. }
  7213. return res;
  7214. }
  7215. // NOTE(lsm): do only one iteration of reads, cause some systems
  7216. // (e.g. FreeRTOS stack) return 0 instead of -1/EWOULDBLOCK when no data
  7217. static void read_conn(struct mg_connection *c) {
  7218. if (ioalloc(c, &c->recv)) {
  7219. char *buf = (char *) &c->recv.buf[c->recv.len];
  7220. size_t len = c->recv.size - c->recv.len;
  7221. long n = -1;
  7222. if (c->is_tls) {
  7223. // Do not read to the raw TLS buffer if it already has enough.
  7224. // This is to prevent overflowing c->rtls if our reads are slow
  7225. long m;
  7226. if (c->rtls.len < 16 * 1024 + 40) { // TLS record, header, MAC, padding
  7227. if (!ioalloc(c, &c->rtls)) return;
  7228. n = recv_raw(c, (char *) &c->rtls.buf[c->rtls.len],
  7229. c->rtls.size - c->rtls.len);
  7230. if (n > 0) c->rtls.len += (size_t) n;
  7231. }
  7232. // there can still be > 16K from last iteration, always mg_tls_recv()
  7233. m = c->is_tls_hs ? (long) MG_IO_WAIT : mg_tls_recv(c, buf, len);
  7234. if (n == MG_IO_ERR) {
  7235. if (c->rtls.len == 0 || m < 0) {
  7236. // Close only when we have fully drained both rtls and TLS buffers
  7237. c->is_closing = 1; // or there's nothing we can do about it.
  7238. m = MG_IO_ERR;
  7239. } else { // see #2885
  7240. // TLS buffer is capped to max record size, even though, there can
  7241. // be more than one record, give TLS a chance to process them.
  7242. }
  7243. } else if (c->is_tls_hs) {
  7244. mg_tls_handshake(c);
  7245. }
  7246. n = m;
  7247. } else {
  7248. n = recv_raw(c, buf, len);
  7249. }
  7250. MG_DEBUG(("%lu %ld %lu:%lu:%lu %ld err %d", c->id, c->fd, c->send.len,
  7251. c->recv.len, c->rtls.len, n, MG_SOCK_ERR(n)));
  7252. iolog(c, buf, n, true);
  7253. }
  7254. }
  7255. static void write_conn(struct mg_connection *c) {
  7256. char *buf = (char *) c->send.buf;
  7257. size_t len = c->send.len;
  7258. long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len);
  7259. MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  7260. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  7261. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  7262. iolog(c, buf, n, false);
  7263. }
  7264. static void close_conn(struct mg_connection *c) {
  7265. if (FD(c) != MG_INVALID_SOCKET) {
  7266. #if MG_ENABLE_EPOLL
  7267. epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_DEL, FD(c), NULL);
  7268. #endif
  7269. closesocket(FD(c));
  7270. #if MG_ENABLE_FREERTOS_TCP
  7271. FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL);
  7272. #endif
  7273. }
  7274. mg_close_conn(c);
  7275. }
  7276. static void connect_conn(struct mg_connection *c) {
  7277. union usa usa;
  7278. socklen_t n = sizeof(usa);
  7279. // Use getpeername() to test whether we have connected
  7280. if (getpeername(FD(c), &usa.sa, &n) == 0) {
  7281. c->is_connecting = 0;
  7282. setlocaddr(FD(c), &c->loc);
  7283. mg_call(c, MG_EV_CONNECT, NULL);
  7284. MG_EPOLL_MOD(c, 0);
  7285. if (c->is_tls_hs) mg_tls_handshake(c);
  7286. } else {
  7287. mg_error(c, "socket error");
  7288. }
  7289. }
  7290. static void setsockopts(struct mg_connection *c) {
  7291. #if MG_ENABLE_FREERTOS_TCP || MG_ARCH == MG_ARCH_AZURERTOS || \
  7292. MG_ARCH == MG_ARCH_TIRTOS
  7293. (void) c;
  7294. #else
  7295. int on = 1;
  7296. #if !defined(SOL_TCP)
  7297. #define SOL_TCP IPPROTO_TCP
  7298. #endif
  7299. if (setsockopt(FD(c), SOL_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) != 0)
  7300. (void) 0;
  7301. if (setsockopt(FD(c), SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) !=
  7302. 0)
  7303. (void) 0;
  7304. #endif
  7305. }
  7306. void mg_connect_resolved(struct mg_connection *c) {
  7307. int type = c->is_udp ? SOCK_DGRAM : SOCK_STREAM;
  7308. int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP;
  7309. int rc, af = c->rem.is_ip6 ? AF_INET6 : AF_INET; // c->rem has resolved IP
  7310. c->fd = S2PTR(socket(af, type, proto)); // Create outbound socket
  7311. c->is_resolving = 0; // Clear resolving flag
  7312. if (FD(c) == MG_INVALID_SOCKET) {
  7313. mg_error(c, "socket(): %d", MG_SOCK_ERR(-1));
  7314. } else if (c->is_udp) {
  7315. MG_EPOLL_ADD(c);
  7316. #if MG_ARCH == MG_ARCH_TIRTOS
  7317. union usa usa; // TI-RTOS NDK requires binding to receive on UDP sockets
  7318. socklen_t slen = tousa(&c->loc, &usa);
  7319. if ((rc = bind(c->fd, &usa.sa, slen)) != 0)
  7320. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  7321. #endif
  7322. setlocaddr(FD(c), &c->loc);
  7323. mg_call(c, MG_EV_RESOLVE, NULL);
  7324. mg_call(c, MG_EV_CONNECT, NULL);
  7325. } else {
  7326. union usa usa;
  7327. socklen_t slen = tousa(&c->rem, &usa);
  7328. mg_set_non_blocking_mode(FD(c));
  7329. setsockopts(c);
  7330. MG_EPOLL_ADD(c);
  7331. mg_call(c, MG_EV_RESOLVE, NULL);
  7332. rc = connect(FD(c), &usa.sa, slen); // Attempt to connect
  7333. if (rc == 0) { // Success
  7334. setlocaddr(FD(c), &c->loc);
  7335. mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user
  7336. } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake
  7337. MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem));
  7338. c->is_connecting = 1;
  7339. } else {
  7340. mg_error(c, "connect: %d", MG_SOCK_ERR(rc));
  7341. }
  7342. }
  7343. }
  7344. static MG_SOCKET_TYPE raccept(MG_SOCKET_TYPE sock, union usa *usa,
  7345. socklen_t *len) {
  7346. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  7347. do {
  7348. memset(usa, 0, sizeof(*usa));
  7349. fd = accept(sock, &usa->sa, len);
  7350. } while (MG_SOCK_INTR(fd));
  7351. return fd;
  7352. }
  7353. static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) {
  7354. struct mg_connection *c = NULL;
  7355. union usa usa;
  7356. socklen_t sa_len = sizeof(usa);
  7357. MG_SOCKET_TYPE fd = raccept(FD(lsn), &usa, &sa_len);
  7358. if (fd == MG_INVALID_SOCKET) {
  7359. #if MG_ARCH == MG_ARCH_AZURERTOS || defined(__ECOS)
  7360. // AzureRTOS, in non-block socket mode can mark listening socket readable
  7361. // even it is not. See comment for 'select' func implementation in
  7362. // nx_bsd.c That's not an error, just should try later
  7363. if (errno != EAGAIN)
  7364. #endif
  7365. MG_ERROR(("%lu accept failed, errno %d", lsn->id, MG_SOCK_ERR(-1)));
  7366. #if (MG_ARCH != MG_ARCH_WIN32) && !MG_ENABLE_FREERTOS_TCP && \
  7367. (MG_ARCH != MG_ARCH_TIRTOS) && !MG_ENABLE_POLL && !MG_ENABLE_EPOLL
  7368. } else if ((long) fd >= FD_SETSIZE) {
  7369. MG_ERROR(("%ld > %ld", (long) fd, (long) FD_SETSIZE));
  7370. closesocket(fd);
  7371. #endif
  7372. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  7373. MG_ERROR(("%lu OOM", lsn->id));
  7374. closesocket(fd);
  7375. } else {
  7376. tomgaddr(&usa, &c->rem, sa_len != sizeof(usa.sin));
  7377. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  7378. c->fd = S2PTR(fd);
  7379. MG_EPOLL_ADD(c);
  7380. mg_set_non_blocking_mode(FD(c));
  7381. setsockopts(c);
  7382. c->is_accepted = 1;
  7383. c->is_hexdumping = lsn->is_hexdumping;
  7384. c->loc = lsn->loc;
  7385. c->pfn = lsn->pfn;
  7386. c->pfn_data = lsn->pfn_data;
  7387. c->fn = lsn->fn;
  7388. c->fn_data = lsn->fn_data;
  7389. MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port,
  7390. &c->rem, mg_print_ip_port, &c->loc));
  7391. mg_call(c, MG_EV_OPEN, NULL);
  7392. mg_call(c, MG_EV_ACCEPT, NULL);
  7393. }
  7394. }
  7395. static bool can_read(const struct mg_connection *c) {
  7396. return c->is_full == false;
  7397. }
  7398. static bool can_write(const struct mg_connection *c) {
  7399. return c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0);
  7400. }
  7401. static bool skip_iotest(const struct mg_connection *c) {
  7402. return (c->is_closing || c->is_resolving || FD(c) == MG_INVALID_SOCKET) ||
  7403. (can_read(c) == false && can_write(c) == false);
  7404. }
  7405. static void mg_iotest(struct mg_mgr *mgr, int ms) {
  7406. #if MG_ENABLE_FREERTOS_TCP
  7407. struct mg_connection *c;
  7408. for (c = mgr->conns; c != NULL; c = c->next) {
  7409. c->is_readable = c->is_writable = 0;
  7410. if (skip_iotest(c)) continue;
  7411. if (can_read(c))
  7412. FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_READ | eSELECT_EXCEPT);
  7413. if (can_write(c)) FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_WRITE);
  7414. if (c->is_closing) ms = 1;
  7415. }
  7416. FreeRTOS_select(mgr->ss, pdMS_TO_TICKS(ms));
  7417. for (c = mgr->conns; c != NULL; c = c->next) {
  7418. EventBits_t bits = FreeRTOS_FD_ISSET(c->fd, mgr->ss);
  7419. c->is_readable = bits & (eSELECT_READ | eSELECT_EXCEPT) ? 1U : 0;
  7420. c->is_writable = bits & eSELECT_WRITE ? 1U : 0;
  7421. if (c->fd != MG_INVALID_SOCKET)
  7422. FreeRTOS_FD_CLR(c->fd, mgr->ss,
  7423. eSELECT_READ | eSELECT_EXCEPT | eSELECT_WRITE);
  7424. }
  7425. #elif MG_ENABLE_EPOLL
  7426. size_t max = 1;
  7427. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7428. c->is_readable = c->is_writable = 0;
  7429. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) ms = 1, c->is_readable = 1;
  7430. if (can_write(c)) MG_EPOLL_MOD(c, 1);
  7431. if (c->is_closing) ms = 1;
  7432. max++;
  7433. }
  7434. struct epoll_event *evs = (struct epoll_event *) alloca(max * sizeof(evs[0]));
  7435. int n = epoll_wait(mgr->epoll_fd, evs, (int) max, ms);
  7436. for (int i = 0; i < n; i++) {
  7437. struct mg_connection *c = (struct mg_connection *) evs[i].data.ptr;
  7438. if (evs[i].events & EPOLLERR) {
  7439. mg_error(c, "socket error");
  7440. } else if (c->is_readable == 0) {
  7441. bool rd = evs[i].events & (EPOLLIN | EPOLLHUP);
  7442. bool wr = evs[i].events & EPOLLOUT;
  7443. c->is_readable = can_read(c) && rd ? 1U : 0;
  7444. c->is_writable = can_write(c) && wr ? 1U : 0;
  7445. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7446. }
  7447. }
  7448. (void) skip_iotest;
  7449. #elif MG_ENABLE_POLL
  7450. nfds_t n = 0;
  7451. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) n++;
  7452. struct pollfd *fds = (struct pollfd *) alloca(n * sizeof(fds[0]));
  7453. memset(fds, 0, n * sizeof(fds[0]));
  7454. n = 0;
  7455. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7456. c->is_readable = c->is_writable = 0;
  7457. if (c->is_closing) ms = 1;
  7458. if (skip_iotest(c)) {
  7459. // Socket not valid, ignore
  7460. } else {
  7461. // Don't wait if TLS is ready
  7462. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) ms = 1;
  7463. fds[n].fd = FD(c);
  7464. if (can_read(c)) fds[n].events |= POLLIN;
  7465. if (can_write(c)) fds[n].events |= POLLOUT;
  7466. n++;
  7467. }
  7468. }
  7469. // MG_INFO(("poll n=%d ms=%d", (int) n, ms));
  7470. if (poll(fds, n, ms) < 0) {
  7471. #if MG_ARCH == MG_ARCH_WIN32
  7472. if (n == 0) Sleep(ms); // On Windows, poll fails if no sockets
  7473. #endif
  7474. memset(fds, 0, n * sizeof(fds[0]));
  7475. }
  7476. n = 0;
  7477. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7478. if (skip_iotest(c)) {
  7479. // Socket not valid, ignore
  7480. } else {
  7481. if (fds[n].revents & POLLERR) {
  7482. mg_error(c, "socket error");
  7483. } else {
  7484. c->is_readable =
  7485. (unsigned) (fds[n].revents & (POLLIN | POLLHUP) ? 1 : 0);
  7486. c->is_writable = (unsigned) (fds[n].revents & POLLOUT ? 1 : 0);
  7487. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7488. }
  7489. n++;
  7490. }
  7491. }
  7492. #else
  7493. struct timeval tv = {ms / 1000, (ms % 1000) * 1000}, tv_zero = {0, 0}, *tvp;
  7494. struct mg_connection *c;
  7495. fd_set rset, wset, eset;
  7496. MG_SOCKET_TYPE maxfd = 0;
  7497. int rc;
  7498. FD_ZERO(&rset);
  7499. FD_ZERO(&wset);
  7500. FD_ZERO(&eset);
  7501. tvp = ms < 0 ? NULL : &tv;
  7502. for (c = mgr->conns; c != NULL; c = c->next) {
  7503. c->is_readable = c->is_writable = 0;
  7504. if (skip_iotest(c)) continue;
  7505. FD_SET(FD(c), &eset);
  7506. if (can_read(c)) FD_SET(FD(c), &rset);
  7507. if (can_write(c)) FD_SET(FD(c), &wset);
  7508. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) tvp = &tv_zero;
  7509. if (FD(c) > maxfd) maxfd = FD(c);
  7510. if (c->is_closing) tvp = &tv_zero;
  7511. }
  7512. if ((rc = select((int) maxfd + 1, &rset, &wset, &eset, tvp)) < 0) {
  7513. #if MG_ARCH == MG_ARCH_WIN32
  7514. if (maxfd == 0) Sleep(ms); // On Windows, select fails if no sockets
  7515. #else
  7516. MG_ERROR(("select: %d %d", rc, MG_SOCK_ERR(rc)));
  7517. #endif
  7518. FD_ZERO(&rset);
  7519. FD_ZERO(&wset);
  7520. FD_ZERO(&eset);
  7521. }
  7522. for (c = mgr->conns; c != NULL; c = c->next) {
  7523. if (FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &eset)) {
  7524. mg_error(c, "socket error");
  7525. } else {
  7526. c->is_readable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &rset);
  7527. c->is_writable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &wset);
  7528. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7529. }
  7530. }
  7531. #endif
  7532. }
  7533. static bool mg_socketpair(MG_SOCKET_TYPE sp[2], union usa usa[2]) {
  7534. socklen_t n = sizeof(usa[0].sin);
  7535. bool success = false;
  7536. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7537. (void) memset(&usa[0], 0, sizeof(usa[0]));
  7538. usa[0].sin.sin_family = AF_INET;
  7539. *(uint32_t *) &usa->sin.sin_addr = mg_htonl(0x7f000001U); // 127.0.0.1
  7540. usa[1] = usa[0];
  7541. if ((sp[0] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) != MG_INVALID_SOCKET &&
  7542. (sp[1] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) != MG_INVALID_SOCKET &&
  7543. bind(sp[0], &usa[0].sa, n) == 0 && //
  7544. bind(sp[1], &usa[1].sa, n) == 0 && //
  7545. getsockname(sp[0], &usa[0].sa, &n) == 0 && //
  7546. getsockname(sp[1], &usa[1].sa, &n) == 0 && //
  7547. connect(sp[0], &usa[1].sa, n) == 0 && //
  7548. connect(sp[1], &usa[0].sa, n) == 0) { //
  7549. success = true;
  7550. }
  7551. if (!success) {
  7552. if (sp[0] != MG_INVALID_SOCKET) closesocket(sp[0]);
  7553. if (sp[1] != MG_INVALID_SOCKET) closesocket(sp[1]);
  7554. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7555. }
  7556. return success;
  7557. }
  7558. // mg_wakeup() event handler
  7559. static void wufn(struct mg_connection *c, int ev, void *ev_data) {
  7560. if (ev == MG_EV_READ) {
  7561. unsigned long *id = (unsigned long *) c->recv.buf;
  7562. // MG_INFO(("Got data"));
  7563. // mg_hexdump(c->recv.buf, c->recv.len);
  7564. if (c->recv.len >= sizeof(*id)) {
  7565. struct mg_connection *t;
  7566. for (t = c->mgr->conns; t != NULL; t = t->next) {
  7567. if (t->id == *id) {
  7568. struct mg_str data = mg_str_n((char *) c->recv.buf + sizeof(*id),
  7569. c->recv.len - sizeof(*id));
  7570. mg_call(t, MG_EV_WAKEUP, &data);
  7571. }
  7572. }
  7573. }
  7574. c->recv.len = 0; // Consume received data
  7575. } else if (ev == MG_EV_CLOSE) {
  7576. closesocket(c->mgr->pipe); // When we're closing, close the other
  7577. c->mgr->pipe = MG_INVALID_SOCKET; // side of the socketpair, too
  7578. }
  7579. (void) ev_data;
  7580. }
  7581. bool mg_wakeup_init(struct mg_mgr *mgr) {
  7582. bool ok = false;
  7583. if (mgr->pipe == MG_INVALID_SOCKET) {
  7584. union usa usa[2];
  7585. MG_SOCKET_TYPE sp[2] = {MG_INVALID_SOCKET, MG_INVALID_SOCKET};
  7586. struct mg_connection *c = NULL;
  7587. if (!mg_socketpair(sp, usa)) {
  7588. MG_ERROR(("Cannot create socket pair"));
  7589. } else if ((c = mg_wrapfd(mgr, (int) sp[1], wufn, NULL)) == NULL) {
  7590. closesocket(sp[0]);
  7591. closesocket(sp[1]);
  7592. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7593. } else {
  7594. tomgaddr(&usa[0], &c->rem, false);
  7595. MG_DEBUG(("%lu %p pipe %lu", c->id, c->fd, (unsigned long) sp[0]));
  7596. mgr->pipe = sp[0];
  7597. ok = true;
  7598. }
  7599. }
  7600. return ok;
  7601. }
  7602. bool mg_wakeup(struct mg_mgr *mgr, unsigned long conn_id, const void *buf,
  7603. size_t len) {
  7604. if (mgr->pipe != MG_INVALID_SOCKET && conn_id > 0) {
  7605. char *extended_buf = (char *) alloca(len + sizeof(conn_id));
  7606. memcpy(extended_buf, &conn_id, sizeof(conn_id));
  7607. memcpy(extended_buf + sizeof(conn_id), buf, len);
  7608. send(mgr->pipe, extended_buf, len + sizeof(conn_id), MSG_NONBLOCKING);
  7609. return true;
  7610. }
  7611. return false;
  7612. }
  7613. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  7614. struct mg_connection *c, *tmp;
  7615. uint64_t now;
  7616. mg_iotest(mgr, ms);
  7617. now = mg_millis();
  7618. mg_timer_poll(&mgr->timers, now);
  7619. for (c = mgr->conns; c != NULL; c = tmp) {
  7620. bool is_resp = c->is_resp;
  7621. tmp = c->next;
  7622. mg_call(c, MG_EV_POLL, &now);
  7623. if (is_resp && !c->is_resp) {
  7624. long n = 0;
  7625. mg_call(c, MG_EV_READ, &n);
  7626. }
  7627. MG_VERBOSE(("%lu %c%c %c%c%c%c%c %lu %lu", c->id,
  7628. c->is_readable ? 'r' : '-', c->is_writable ? 'w' : '-',
  7629. c->is_tls ? 'T' : 't', c->is_connecting ? 'C' : 'c',
  7630. c->is_tls_hs ? 'H' : 'h', c->is_resolving ? 'R' : 'r',
  7631. c->is_closing ? 'C' : 'c', mg_tls_pending(c), c->rtls.len));
  7632. if (c->is_resolving || c->is_closing) {
  7633. // Do nothing
  7634. } else if (c->is_listening && c->is_udp == 0) {
  7635. if (c->is_readable) accept_conn(mgr, c);
  7636. } else if (c->is_connecting) {
  7637. if (c->is_readable || c->is_writable) connect_conn(c);
  7638. //} else if (c->is_tls_hs) {
  7639. // if ((c->is_readable || c->is_writable)) mg_tls_handshake(c);
  7640. } else {
  7641. if (c->is_readable) read_conn(c);
  7642. if (c->is_writable) write_conn(c);
  7643. }
  7644. if (c->is_draining && c->send.len == 0) c->is_closing = 1;
  7645. if (c->is_closing) close_conn(c);
  7646. }
  7647. }
  7648. #endif
  7649. #ifdef MG_ENABLE_LINES
  7650. #line 1 "src/ssi.c"
  7651. #endif
  7652. #ifndef MG_MAX_SSI_DEPTH
  7653. #define MG_MAX_SSI_DEPTH 5
  7654. #endif
  7655. #ifndef MG_SSI_BUFSIZ
  7656. #define MG_SSI_BUFSIZ 1024
  7657. #endif
  7658. #if MG_ENABLE_SSI
  7659. static char *mg_ssi(const char *path, const char *root, int depth) {
  7660. struct mg_iobuf b = {NULL, 0, 0, MG_IO_SIZE};
  7661. FILE *fp = fopen(path, "rb");
  7662. if (fp != NULL) {
  7663. char buf[MG_SSI_BUFSIZ], arg[sizeof(buf)];
  7664. int ch, intag = 0;
  7665. size_t len = 0;
  7666. buf[0] = arg[0] = '\0';
  7667. while ((ch = fgetc(fp)) != EOF) {
  7668. if (intag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  7669. buf[len++] = (char) (ch & 0xff);
  7670. buf[len] = '\0';
  7671. if (sscanf(buf, "<!--#include file=\"%[^\"]", arg) > 0) {
  7672. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10],
  7673. *p = (char *) path + strlen(path), *data;
  7674. while (p > path && p[-1] != MG_DIRSEP && p[-1] != '/') p--;
  7675. mg_snprintf(tmp, sizeof(tmp), "%.*s%s", (int) (p - path), path, arg);
  7676. if (depth < MG_MAX_SSI_DEPTH &&
  7677. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  7678. mg_iobuf_add(&b, b.len, data, strlen(data));
  7679. free(data);
  7680. } else {
  7681. MG_ERROR(("%s: file=%s error or too deep", path, arg));
  7682. }
  7683. } else if (sscanf(buf, "<!--#include virtual=\"%[^\"]", arg) > 0) {
  7684. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10], *data;
  7685. mg_snprintf(tmp, sizeof(tmp), "%s%s", root, arg);
  7686. if (depth < MG_MAX_SSI_DEPTH &&
  7687. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  7688. mg_iobuf_add(&b, b.len, data, strlen(data));
  7689. free(data);
  7690. } else {
  7691. MG_ERROR(("%s: virtual=%s error or too deep", path, arg));
  7692. }
  7693. } else {
  7694. // Unknown SSI tag
  7695. MG_ERROR(("Unknown SSI tag: %.*s", (int) len, buf));
  7696. mg_iobuf_add(&b, b.len, buf, len);
  7697. }
  7698. intag = 0;
  7699. len = 0;
  7700. } else if (ch == '<') {
  7701. intag = 1;
  7702. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  7703. len = 0;
  7704. buf[len++] = (char) (ch & 0xff);
  7705. } else if (intag) {
  7706. if (len == 5 && strncmp(buf, "<!--#", 5) != 0) {
  7707. intag = 0;
  7708. } else if (len >= sizeof(buf) - 2) {
  7709. MG_ERROR(("%s: SSI tag is too large", path));
  7710. len = 0;
  7711. }
  7712. buf[len++] = (char) (ch & 0xff);
  7713. } else {
  7714. buf[len++] = (char) (ch & 0xff);
  7715. if (len >= sizeof(buf)) {
  7716. mg_iobuf_add(&b, b.len, buf, len);
  7717. len = 0;
  7718. }
  7719. }
  7720. }
  7721. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  7722. if (b.len > 0) mg_iobuf_add(&b, b.len, "", 1); // nul-terminate
  7723. fclose(fp);
  7724. }
  7725. (void) depth;
  7726. (void) root;
  7727. return (char *) b.buf;
  7728. }
  7729. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  7730. const char *fullpath) {
  7731. const char *headers = "Content-Type: text/html; charset=utf-8\r\n";
  7732. char *data = mg_ssi(fullpath, root, 0);
  7733. mg_http_reply(c, 200, headers, "%s", data == NULL ? "" : data);
  7734. free(data);
  7735. }
  7736. #else
  7737. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  7738. const char *fullpath) {
  7739. mg_http_reply(c, 501, NULL, "SSI not enabled");
  7740. (void) root, (void) fullpath;
  7741. }
  7742. #endif
  7743. #ifdef MG_ENABLE_LINES
  7744. #line 1 "src/str.c"
  7745. #endif
  7746. struct mg_str mg_str_s(const char *s) {
  7747. struct mg_str str = {(char *) s, s == NULL ? 0 : strlen(s)};
  7748. return str;
  7749. }
  7750. struct mg_str mg_str_n(const char *s, size_t n) {
  7751. struct mg_str str = {(char *) s, n};
  7752. return str;
  7753. }
  7754. static int mg_tolc(char c) {
  7755. return (c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c;
  7756. }
  7757. int mg_casecmp(const char *s1, const char *s2) {
  7758. int diff = 0;
  7759. do {
  7760. int c = mg_tolc(*s1++), d = mg_tolc(*s2++);
  7761. diff = c - d;
  7762. } while (diff == 0 && s1[-1] != '\0');
  7763. return diff;
  7764. }
  7765. struct mg_str mg_strdup(const struct mg_str s) {
  7766. struct mg_str r = {NULL, 0};
  7767. if (s.len > 0 && s.buf != NULL) {
  7768. char *sc = (char *) calloc(1, s.len + 1);
  7769. if (sc != NULL) {
  7770. memcpy(sc, s.buf, s.len);
  7771. sc[s.len] = '\0';
  7772. r.buf = sc;
  7773. r.len = s.len;
  7774. }
  7775. }
  7776. return r;
  7777. }
  7778. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  7779. size_t i = 0;
  7780. while (i < str1.len && i < str2.len) {
  7781. int c1 = str1.buf[i];
  7782. int c2 = str2.buf[i];
  7783. if (c1 < c2) return -1;
  7784. if (c1 > c2) return 1;
  7785. i++;
  7786. }
  7787. if (i < str1.len) return 1;
  7788. if (i < str2.len) return -1;
  7789. return 0;
  7790. }
  7791. int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2) {
  7792. size_t i = 0;
  7793. while (i < str1.len && i < str2.len) {
  7794. int c1 = mg_tolc(str1.buf[i]);
  7795. int c2 = mg_tolc(str2.buf[i]);
  7796. if (c1 < c2) return -1;
  7797. if (c1 > c2) return 1;
  7798. i++;
  7799. }
  7800. if (i < str1.len) return 1;
  7801. if (i < str2.len) return -1;
  7802. return 0;
  7803. }
  7804. bool mg_match(struct mg_str s, struct mg_str p, struct mg_str *caps) {
  7805. size_t i = 0, j = 0, ni = 0, nj = 0;
  7806. if (caps) caps->buf = NULL, caps->len = 0;
  7807. while (i < p.len || j < s.len) {
  7808. if (i < p.len && j < s.len &&
  7809. (p.buf[i] == '?' ||
  7810. (p.buf[i] != '*' && p.buf[i] != '#' && s.buf[j] == p.buf[i]))) {
  7811. if (caps == NULL) {
  7812. } else if (p.buf[i] == '?') {
  7813. caps->buf = &s.buf[j], caps->len = 1; // Finalize `?` cap
  7814. caps++, caps->buf = NULL, caps->len = 0; // Init next cap
  7815. } else if (caps->buf != NULL && caps->len == 0) {
  7816. caps->len = (size_t) (&s.buf[j] - caps->buf); // Finalize current cap
  7817. caps++, caps->len = 0, caps->buf = NULL; // Init next cap
  7818. }
  7819. i++, j++;
  7820. } else if (i < p.len && (p.buf[i] == '*' || p.buf[i] == '#')) {
  7821. if (caps && !caps->buf) caps->len = 0, caps->buf = &s.buf[j]; // Init cap
  7822. ni = i++, nj = j + 1;
  7823. } else if (nj > 0 && nj <= s.len && (p.buf[ni] == '#' || s.buf[j] != '/')) {
  7824. i = ni, j = nj;
  7825. if (caps && caps->buf == NULL && caps->len == 0) {
  7826. caps--, caps->len = 0; // Restart previous cap
  7827. }
  7828. } else {
  7829. return false;
  7830. }
  7831. }
  7832. if (caps && caps->buf && caps->len == 0) {
  7833. caps->len = (size_t) (&s.buf[j] - caps->buf);
  7834. }
  7835. return true;
  7836. }
  7837. bool mg_span(struct mg_str s, struct mg_str *a, struct mg_str *b, char sep) {
  7838. if (s.len == 0 || s.buf == NULL) {
  7839. return false; // Empty string, nothing to span - fail
  7840. } else {
  7841. size_t len = 0;
  7842. while (len < s.len && s.buf[len] != sep) len++; // Find separator
  7843. if (a) *a = mg_str_n(s.buf, len); // Init a
  7844. if (b) *b = mg_str_n(s.buf + len, s.len - len); // Init b
  7845. if (b && len < s.len) b->buf++, b->len--; // Skip separator
  7846. return true;
  7847. }
  7848. }
  7849. bool mg_str_to_num(struct mg_str str, int base, void *val, size_t val_len) {
  7850. size_t i = 0, ndigits = 0;
  7851. uint64_t max = val_len == sizeof(uint8_t) ? 0xFF
  7852. : val_len == sizeof(uint16_t) ? 0xFFFF
  7853. : val_len == sizeof(uint32_t) ? 0xFFFFFFFF
  7854. : (uint64_t) ~0;
  7855. uint64_t result = 0;
  7856. if (max == (uint64_t) ~0 && val_len != sizeof(uint64_t)) return false;
  7857. if (base == 0 && str.len >= 2) {
  7858. if (str.buf[i] == '0') {
  7859. i++;
  7860. base = str.buf[i] == 'b' ? 2 : str.buf[i] == 'x' ? 16 : 10;
  7861. if (base != 10) ++i;
  7862. } else {
  7863. base = 10;
  7864. }
  7865. }
  7866. switch (base) {
  7867. case 2:
  7868. while (i < str.len && (str.buf[i] == '0' || str.buf[i] == '1')) {
  7869. uint64_t digit = (uint64_t) (str.buf[i] - '0');
  7870. if (result > max / 2) return false; // Overflow
  7871. result *= 2;
  7872. if (result > max - digit) return false; // Overflow
  7873. result += digit;
  7874. i++, ndigits++;
  7875. }
  7876. break;
  7877. case 10:
  7878. while (i < str.len && str.buf[i] >= '0' && str.buf[i] <= '9') {
  7879. uint64_t digit = (uint64_t) (str.buf[i] - '0');
  7880. if (result > max / 10) return false; // Overflow
  7881. result *= 10;
  7882. if (result > max - digit) return false; // Overflow
  7883. result += digit;
  7884. i++, ndigits++;
  7885. }
  7886. break;
  7887. case 16:
  7888. while (i < str.len) {
  7889. char c = str.buf[i];
  7890. uint64_t digit = (c >= '0' && c <= '9') ? (uint64_t) (c - '0')
  7891. : (c >= 'A' && c <= 'F') ? (uint64_t) (c - '7')
  7892. : (c >= 'a' && c <= 'f') ? (uint64_t) (c - 'W')
  7893. : (uint64_t) ~0;
  7894. if (digit == (uint64_t) ~0) break;
  7895. if (result > max / 16) return false; // Overflow
  7896. result *= 16;
  7897. if (result > max - digit) return false; // Overflow
  7898. result += digit;
  7899. i++, ndigits++;
  7900. }
  7901. break;
  7902. default:
  7903. return false;
  7904. }
  7905. if (ndigits == 0) return false;
  7906. if (i != str.len) return false;
  7907. if (val_len == 1) {
  7908. *((uint8_t *) val) = (uint8_t) result;
  7909. } else if (val_len == 2) {
  7910. *((uint16_t *) val) = (uint16_t) result;
  7911. } else if (val_len == 4) {
  7912. *((uint32_t *) val) = (uint32_t) result;
  7913. } else {
  7914. *((uint64_t *) val) = (uint64_t) result;
  7915. }
  7916. return true;
  7917. }
  7918. #ifdef MG_ENABLE_LINES
  7919. #line 1 "src/timer.c"
  7920. #endif
  7921. #define MG_TIMER_CALLED 4
  7922. void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
  7923. unsigned flags, void (*fn)(void *), void *arg) {
  7924. t->id = 0, t->period_ms = ms, t->expire = 0;
  7925. t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
  7926. *head = t;
  7927. }
  7928. void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
  7929. while (*head && *head != t) head = &(*head)->next;
  7930. if (*head) *head = t->next;
  7931. }
  7932. // t: expiration time, prd: period, now: current time. Return true if expired
  7933. bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
  7934. if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
  7935. if (*t == 0) *t = now + prd; // Firt poll? Set expiration
  7936. if (*t > now) return false; // Not expired yet, return
  7937. *t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
  7938. return true; // Expired, return true
  7939. }
  7940. void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
  7941. struct mg_timer *t, *tmp;
  7942. for (t = *head; t != NULL; t = tmp) {
  7943. bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
  7944. !(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
  7945. bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
  7946. tmp = t->next;
  7947. if (!once && !expired) continue;
  7948. if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
  7949. t->fn(t->arg);
  7950. }
  7951. t->flags |= MG_TIMER_CALLED;
  7952. }
  7953. }
  7954. #ifdef MG_ENABLE_LINES
  7955. #line 1 "src/tls_aes128.c"
  7956. #endif
  7957. /******************************************************************************
  7958. *
  7959. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7960. *
  7961. * This is a simple and straightforward implementation of the AES Rijndael
  7962. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7963. * of this work was correctness & accuracy. It is written in 'C' without any
  7964. * particular focus upon optimization or speed. It should be endian (memory
  7965. * byte order) neutral since the few places that care are handled explicitly.
  7966. *
  7967. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7968. *
  7969. * It is intended for general purpose use, but was written in support of GRC's
  7970. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7971. *
  7972. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7973. *
  7974. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7975. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7976. *
  7977. *******************************************************************************/
  7978. /******************************************************************************/
  7979. #define AES_DECRYPTION 1 // whether AES decryption is supported
  7980. /******************************************************************************/
  7981. #define MG_ENCRYPT 1 // specify whether we're encrypting
  7982. #define MG_DECRYPT 0 // or decrypting
  7983. #if MG_TLS == MG_TLS_BUILTIN
  7984. /******************************************************************************
  7985. * AES_INIT_KEYGEN_TABLES : MUST be called once before any AES use
  7986. ******************************************************************************/
  7987. static void aes_init_keygen_tables(void);
  7988. /******************************************************************************
  7989. * AES_SETKEY : called to expand the key for encryption or decryption
  7990. ******************************************************************************/
  7991. static int aes_setkey(aes_context *ctx, // pointer to context
  7992. int mode, // 1 or 0 for Encrypt/Decrypt
  7993. const unsigned char *key, // AES input key
  7994. unsigned int keysize); // size in bytes (must be 16, 24, 32 for
  7995. // 128, 192 or 256-bit keys respectively)
  7996. // returns 0 for success
  7997. /******************************************************************************
  7998. * AES_CIPHER : called to encrypt or decrypt ONE 128-bit block of data
  7999. ******************************************************************************/
  8000. static int aes_cipher(aes_context *ctx, // pointer to context
  8001. const unsigned char input[16], // 128-bit block to en/decipher
  8002. unsigned char output[16]); // 128-bit output result block
  8003. // returns 0 for success
  8004. /******************************************************************************
  8005. * GCM_CONTEXT : GCM context / holds keytables, instance data, and AES ctx
  8006. ******************************************************************************/
  8007. typedef struct {
  8008. int mode; // cipher direction: encrypt/decrypt
  8009. uint64_t len; // cipher data length processed so far
  8010. uint64_t add_len; // total add data length
  8011. uint64_t HL[16]; // precalculated lo-half HTable
  8012. uint64_t HH[16]; // precalculated hi-half HTable
  8013. unsigned char base_ectr[16]; // first counter-mode cipher output for tag
  8014. unsigned char y[16]; // the current cipher-input IV|Counter value
  8015. unsigned char buf[16]; // buf working value
  8016. aes_context aes_ctx; // cipher context used
  8017. } gcm_context;
  8018. /******************************************************************************
  8019. * GCM_SETKEY : sets the GCM (and AES) keying material for use
  8020. ******************************************************************************/
  8021. static int gcm_setkey(
  8022. gcm_context *ctx, // caller-provided context ptr
  8023. const unsigned char *key, // pointer to cipher key
  8024. const unsigned int keysize // size in bytes (must be 16, 24, 32 for
  8025. // 128, 192 or 256-bit keys respectively)
  8026. ); // returns 0 for success
  8027. /******************************************************************************
  8028. *
  8029. * GCM_CRYPT_AND_TAG
  8030. *
  8031. * This either encrypts or decrypts the user-provided data and, either
  8032. * way, generates an authentication tag of the requested length. It must be
  8033. * called with a GCM context whose key has already been set with GCM_SETKEY.
  8034. *
  8035. * The user would typically call this explicitly to ENCRYPT a buffer of data
  8036. * and optional associated data, and produce its an authentication tag.
  8037. *
  8038. * To reverse the process the user would typically call the companion
  8039. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  8040. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  8041. * to perform its decryption and tag generation, which it then compares.
  8042. *
  8043. ******************************************************************************/
  8044. static int gcm_crypt_and_tag(
  8045. gcm_context *ctx, // gcm context with key already setup
  8046. int mode, // cipher direction: MG_ENCRYPT (1) or MG_DECRYPT (0)
  8047. const unsigned char *iv, // pointer to the 12-byte initialization vector
  8048. size_t iv_len, // byte length if the IV. should always be 12
  8049. const unsigned char *add, // pointer to the non-ciphered additional data
  8050. size_t add_len, // byte length of the additional AEAD data
  8051. const unsigned char *input, // pointer to the cipher data source
  8052. unsigned char *output, // pointer to the cipher data destination
  8053. size_t length, // byte length of the cipher data
  8054. unsigned char *tag, // pointer to the tag to be generated
  8055. size_t tag_len); // byte length of the tag to be generated
  8056. /******************************************************************************
  8057. *
  8058. * GCM_START
  8059. *
  8060. * Given a user-provided GCM context, this initializes it, sets the encryption
  8061. * mode, and preprocesses the initialization vector and additional AEAD data.
  8062. *
  8063. ******************************************************************************/
  8064. static int gcm_start(
  8065. gcm_context *ctx, // pointer to user-provided GCM context
  8066. int mode, // MG_ENCRYPT (1) or MG_DECRYPT (0)
  8067. const unsigned char *iv, // pointer to initialization vector
  8068. size_t iv_len, // IV length in bytes (should == 12)
  8069. const unsigned char *add, // pointer to additional AEAD data (NULL if none)
  8070. size_t add_len); // length of additional AEAD data (bytes)
  8071. /******************************************************************************
  8072. *
  8073. * GCM_UPDATE
  8074. *
  8075. * This is called once or more to process bulk plaintext or ciphertext data.
  8076. * We give this some number of bytes of input and it returns the same number
  8077. * of output bytes. If called multiple times (which is fine) all but the final
  8078. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  8079. * have a partial block length of < 128 bits.)
  8080. *
  8081. ******************************************************************************/
  8082. static int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  8083. size_t length, // length, in bytes, of data to process
  8084. const unsigned char *input, // pointer to source data
  8085. unsigned char *output); // pointer to destination data
  8086. /******************************************************************************
  8087. *
  8088. * GCM_FINISH
  8089. *
  8090. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  8091. * It performs the final GHASH to produce the resulting authentication TAG.
  8092. *
  8093. ******************************************************************************/
  8094. static int gcm_finish(
  8095. gcm_context *ctx, // pointer to user-provided GCM context
  8096. unsigned char *tag, // ptr to tag buffer - NULL if tag_len = 0
  8097. size_t tag_len); // length, in bytes, of the tag-receiving buf
  8098. /******************************************************************************
  8099. *
  8100. * GCM_ZERO_CTX
  8101. *
  8102. * The GCM context contains both the GCM context and the AES context.
  8103. * This includes keying and key-related material which is security-
  8104. * sensitive, so it MUST be zeroed after use. This function does that.
  8105. *
  8106. ******************************************************************************/
  8107. static void gcm_zero_ctx(gcm_context *ctx);
  8108. /******************************************************************************
  8109. *
  8110. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  8111. *
  8112. * This is a simple and straightforward implementation of the AES Rijndael
  8113. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  8114. * of this work was correctness & accuracy. It is written in 'C' without any
  8115. * particular focus upon optimization or speed. It should be endian (memory
  8116. * byte order) neutral since the few places that care are handled explicitly.
  8117. *
  8118. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  8119. *
  8120. * It is intended for general purpose use, but was written in support of GRC's
  8121. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  8122. *
  8123. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  8124. *
  8125. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  8126. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  8127. *
  8128. *******************************************************************************/
  8129. static int aes_tables_inited = 0; // run-once flag for performing key
  8130. // expasion table generation (see below)
  8131. /*
  8132. * The following static local tables must be filled-in before the first use of
  8133. * the GCM or AES ciphers. They are used for the AES key expansion/scheduling
  8134. * and once built are read-only and thread safe. The "gcm_initialize" function
  8135. * must be called once during system initialization to populate these arrays
  8136. * for subsequent use by the AES key scheduler. If they have not been built
  8137. * before attempted use, an error will be returned to the caller.
  8138. *
  8139. * NOTE: GCM Encryption/Decryption does NOT REQUIRE AES decryption. Since
  8140. * GCM uses AES in counter-mode, where the AES cipher output is XORed with
  8141. * the GCM input, we ONLY NEED AES encryption. Thus, to save space AES
  8142. * decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.
  8143. */
  8144. // We always need our forward tables
  8145. static unsigned char FSb[256]; // Forward substitution box (FSb)
  8146. static uint32_t FT0[256]; // Forward key schedule assembly tables
  8147. static uint32_t FT1[256];
  8148. static uint32_t FT2[256];
  8149. static uint32_t FT3[256];
  8150. #if AES_DECRYPTION // We ONLY need reverse for decryption
  8151. static unsigned char RSb[256]; // Reverse substitution box (RSb)
  8152. static uint32_t RT0[256]; // Reverse key schedule assembly tables
  8153. static uint32_t RT1[256];
  8154. static uint32_t RT2[256];
  8155. static uint32_t RT3[256];
  8156. #endif /* AES_DECRYPTION */
  8157. static uint32_t RCON[10]; // AES round constants
  8158. /*
  8159. * Platform Endianness Neutralizing Load and Store Macro definitions
  8160. * AES wants platform-neutral Little Endian (LE) byte ordering
  8161. */
  8162. #define GET_UINT32_LE(n, b, i) \
  8163. { \
  8164. (n) = ((uint32_t) (b)[(i)]) | ((uint32_t) (b)[(i) + 1] << 8) | \
  8165. ((uint32_t) (b)[(i) + 2] << 16) | ((uint32_t) (b)[(i) + 3] << 24); \
  8166. }
  8167. #define PUT_UINT32_LE(n, b, i) \
  8168. { \
  8169. (b)[(i)] = (unsigned char) ((n)); \
  8170. (b)[(i) + 1] = (unsigned char) ((n) >> 8); \
  8171. (b)[(i) + 2] = (unsigned char) ((n) >> 16); \
  8172. (b)[(i) + 3] = (unsigned char) ((n) >> 24); \
  8173. }
  8174. /*
  8175. * AES forward and reverse encryption round processing macros
  8176. */
  8177. #define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  8178. { \
  8179. X0 = *RK++ ^ FT0[(Y0) & 0xFF] ^ FT1[(Y1 >> 8) & 0xFF] ^ \
  8180. FT2[(Y2 >> 16) & 0xFF] ^ FT3[(Y3 >> 24) & 0xFF]; \
  8181. \
  8182. X1 = *RK++ ^ FT0[(Y1) & 0xFF] ^ FT1[(Y2 >> 8) & 0xFF] ^ \
  8183. FT2[(Y3 >> 16) & 0xFF] ^ FT3[(Y0 >> 24) & 0xFF]; \
  8184. \
  8185. X2 = *RK++ ^ FT0[(Y2) & 0xFF] ^ FT1[(Y3 >> 8) & 0xFF] ^ \
  8186. FT2[(Y0 >> 16) & 0xFF] ^ FT3[(Y1 >> 24) & 0xFF]; \
  8187. \
  8188. X3 = *RK++ ^ FT0[(Y3) & 0xFF] ^ FT1[(Y0 >> 8) & 0xFF] ^ \
  8189. FT2[(Y1 >> 16) & 0xFF] ^ FT3[(Y2 >> 24) & 0xFF]; \
  8190. }
  8191. #define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  8192. { \
  8193. X0 = *RK++ ^ RT0[(Y0) & 0xFF] ^ RT1[(Y3 >> 8) & 0xFF] ^ \
  8194. RT2[(Y2 >> 16) & 0xFF] ^ RT3[(Y1 >> 24) & 0xFF]; \
  8195. \
  8196. X1 = *RK++ ^ RT0[(Y1) & 0xFF] ^ RT1[(Y0 >> 8) & 0xFF] ^ \
  8197. RT2[(Y3 >> 16) & 0xFF] ^ RT3[(Y2 >> 24) & 0xFF]; \
  8198. \
  8199. X2 = *RK++ ^ RT0[(Y2) & 0xFF] ^ RT1[(Y1 >> 8) & 0xFF] ^ \
  8200. RT2[(Y0 >> 16) & 0xFF] ^ RT3[(Y3 >> 24) & 0xFF]; \
  8201. \
  8202. X3 = *RK++ ^ RT0[(Y3) & 0xFF] ^ RT1[(Y2 >> 8) & 0xFF] ^ \
  8203. RT2[(Y1 >> 16) & 0xFF] ^ RT3[(Y0 >> 24) & 0xFF]; \
  8204. }
  8205. /*
  8206. * These macros improve the readability of the key
  8207. * generation initialization code by collapsing
  8208. * repetitive common operations into logical pieces.
  8209. */
  8210. #define ROTL8(x) ((x << 8) & 0xFFFFFFFF) | (x >> 24)
  8211. #define XTIME(x) ((x << 1) ^ ((x & 0x80) ? 0x1B : 0x00))
  8212. #define MUL(x, y) ((x && y) ? pow[(log[x] + log[y]) % 255] : 0)
  8213. #define MIX(x, y) \
  8214. { \
  8215. y = ((y << 1) | (y >> 7)) & 0xFF; \
  8216. x ^= y; \
  8217. }
  8218. #define CPY128 \
  8219. { \
  8220. *RK++ = *SK++; \
  8221. *RK++ = *SK++; \
  8222. *RK++ = *SK++; \
  8223. *RK++ = *SK++; \
  8224. }
  8225. /******************************************************************************
  8226. *
  8227. * AES_INIT_KEYGEN_TABLES
  8228. *
  8229. * Fills the AES key expansion tables allocated above with their static
  8230. * data. This is not "per key" data, but static system-wide read-only
  8231. * table data. THIS FUNCTION IS NOT THREAD SAFE. It must be called once
  8232. * at system initialization to setup the tables for all subsequent use.
  8233. *
  8234. ******************************************************************************/
  8235. void aes_init_keygen_tables(void) {
  8236. int i, x, y, z; // general purpose iteration and computation locals
  8237. int pow[256];
  8238. int log[256];
  8239. if (aes_tables_inited) return;
  8240. // fill the 'pow' and 'log' tables over GF(2^8)
  8241. for (i = 0, x = 1; i < 256; i++) {
  8242. pow[i] = x;
  8243. log[x] = i;
  8244. x = (x ^ XTIME(x)) & 0xFF;
  8245. }
  8246. // compute the round constants
  8247. for (i = 0, x = 1; i < 10; i++) {
  8248. RCON[i] = (uint32_t) x;
  8249. x = XTIME(x) & 0xFF;
  8250. }
  8251. // fill the forward and reverse substitution boxes
  8252. FSb[0x00] = 0x63;
  8253. #if AES_DECRYPTION // whether AES decryption is supported
  8254. RSb[0x63] = 0x00;
  8255. #endif /* AES_DECRYPTION */
  8256. for (i = 1; i < 256; i++) {
  8257. x = y = pow[255 - log[i]];
  8258. MIX(x, y);
  8259. MIX(x, y);
  8260. MIX(x, y);
  8261. MIX(x, y);
  8262. FSb[i] = (unsigned char) (x ^= 0x63);
  8263. #if AES_DECRYPTION // whether AES decryption is supported
  8264. RSb[x] = (unsigned char) i;
  8265. #endif /* AES_DECRYPTION */
  8266. }
  8267. // generate the forward and reverse key expansion tables
  8268. for (i = 0; i < 256; i++) {
  8269. x = FSb[i];
  8270. y = XTIME(x) & 0xFF;
  8271. z = (y ^ x) & 0xFF;
  8272. FT0[i] = ((uint32_t) y) ^ ((uint32_t) x << 8) ^ ((uint32_t) x << 16) ^
  8273. ((uint32_t) z << 24);
  8274. FT1[i] = ROTL8(FT0[i]);
  8275. FT2[i] = ROTL8(FT1[i]);
  8276. FT3[i] = ROTL8(FT2[i]);
  8277. #if AES_DECRYPTION // whether AES decryption is supported
  8278. x = RSb[i];
  8279. RT0[i] = ((uint32_t) MUL(0x0E, x)) ^ ((uint32_t) MUL(0x09, x) << 8) ^
  8280. ((uint32_t) MUL(0x0D, x) << 16) ^ ((uint32_t) MUL(0x0B, x) << 24);
  8281. RT1[i] = ROTL8(RT0[i]);
  8282. RT2[i] = ROTL8(RT1[i]);
  8283. RT3[i] = ROTL8(RT2[i]);
  8284. #endif /* AES_DECRYPTION */
  8285. }
  8286. aes_tables_inited = 1; // flag that the tables have been generated
  8287. } // to permit subsequent use of the AES cipher
  8288. /******************************************************************************
  8289. *
  8290. * AES_SET_ENCRYPTION_KEY
  8291. *
  8292. * This is called by 'aes_setkey' when we're establishing a key for
  8293. * subsequent encryption. We give it a pointer to the encryption
  8294. * context, a pointer to the key, and the key's length in bytes.
  8295. * Valid lengths are: 16, 24 or 32 bytes (128, 192, 256 bits).
  8296. *
  8297. ******************************************************************************/
  8298. static int aes_set_encryption_key(aes_context *ctx, const unsigned char *key,
  8299. unsigned int keysize) {
  8300. unsigned int i; // general purpose iteration local
  8301. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  8302. for (i = 0; i < (keysize >> 2); i++) {
  8303. GET_UINT32_LE(RK[i], key, i << 2);
  8304. }
  8305. switch (ctx->rounds) {
  8306. case 10:
  8307. for (i = 0; i < 10; i++, RK += 4) {
  8308. RK[4] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[3] >> 8) & 0xFF]) ^
  8309. ((uint32_t) FSb[(RK[3] >> 16) & 0xFF] << 8) ^
  8310. ((uint32_t) FSb[(RK[3] >> 24) & 0xFF] << 16) ^
  8311. ((uint32_t) FSb[(RK[3]) & 0xFF] << 24);
  8312. RK[5] = RK[1] ^ RK[4];
  8313. RK[6] = RK[2] ^ RK[5];
  8314. RK[7] = RK[3] ^ RK[6];
  8315. }
  8316. break;
  8317. case 12:
  8318. for (i = 0; i < 8; i++, RK += 6) {
  8319. RK[6] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[5] >> 8) & 0xFF]) ^
  8320. ((uint32_t) FSb[(RK[5] >> 16) & 0xFF] << 8) ^
  8321. ((uint32_t) FSb[(RK[5] >> 24) & 0xFF] << 16) ^
  8322. ((uint32_t) FSb[(RK[5]) & 0xFF] << 24);
  8323. RK[7] = RK[1] ^ RK[6];
  8324. RK[8] = RK[2] ^ RK[7];
  8325. RK[9] = RK[3] ^ RK[8];
  8326. RK[10] = RK[4] ^ RK[9];
  8327. RK[11] = RK[5] ^ RK[10];
  8328. }
  8329. break;
  8330. case 14:
  8331. for (i = 0; i < 7; i++, RK += 8) {
  8332. RK[8] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[7] >> 8) & 0xFF]) ^
  8333. ((uint32_t) FSb[(RK[7] >> 16) & 0xFF] << 8) ^
  8334. ((uint32_t) FSb[(RK[7] >> 24) & 0xFF] << 16) ^
  8335. ((uint32_t) FSb[(RK[7]) & 0xFF] << 24);
  8336. RK[9] = RK[1] ^ RK[8];
  8337. RK[10] = RK[2] ^ RK[9];
  8338. RK[11] = RK[3] ^ RK[10];
  8339. RK[12] = RK[4] ^ ((uint32_t) FSb[(RK[11]) & 0xFF]) ^
  8340. ((uint32_t) FSb[(RK[11] >> 8) & 0xFF] << 8) ^
  8341. ((uint32_t) FSb[(RK[11] >> 16) & 0xFF] << 16) ^
  8342. ((uint32_t) FSb[(RK[11] >> 24) & 0xFF] << 24);
  8343. RK[13] = RK[5] ^ RK[12];
  8344. RK[14] = RK[6] ^ RK[13];
  8345. RK[15] = RK[7] ^ RK[14];
  8346. }
  8347. break;
  8348. default:
  8349. return -1;
  8350. }
  8351. return (0);
  8352. }
  8353. #if AES_DECRYPTION // whether AES decryption is supported
  8354. /******************************************************************************
  8355. *
  8356. * AES_SET_DECRYPTION_KEY
  8357. *
  8358. * This is called by 'aes_setkey' when we're establishing a
  8359. * key for subsequent decryption. We give it a pointer to
  8360. * the encryption context, a pointer to the key, and the key's
  8361. * length in bits. Valid lengths are: 128, 192, or 256 bits.
  8362. *
  8363. ******************************************************************************/
  8364. static int aes_set_decryption_key(aes_context *ctx, const unsigned char *key,
  8365. unsigned int keysize) {
  8366. int i, j;
  8367. aes_context cty; // a calling aes context for set_encryption_key
  8368. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  8369. uint32_t *SK;
  8370. int ret;
  8371. cty.rounds = ctx->rounds; // initialize our local aes context
  8372. cty.rk = cty.buf; // round count and key buf pointer
  8373. if ((ret = aes_set_encryption_key(&cty, key, keysize)) != 0) return (ret);
  8374. SK = cty.rk + cty.rounds * 4;
  8375. CPY128 // copy a 128-bit block from *SK to *RK
  8376. for (i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8) {
  8377. for (j = 0; j < 4; j++, SK++) {
  8378. *RK++ = RT0[FSb[(*SK) & 0xFF]] ^ RT1[FSb[(*SK >> 8) & 0xFF]] ^
  8379. RT2[FSb[(*SK >> 16) & 0xFF]] ^ RT3[FSb[(*SK >> 24) & 0xFF]];
  8380. }
  8381. }
  8382. CPY128 // copy a 128-bit block from *SK to *RK
  8383. memset(&cty, 0, sizeof(aes_context)); // clear local aes context
  8384. return (0);
  8385. }
  8386. #endif /* AES_DECRYPTION */
  8387. /******************************************************************************
  8388. *
  8389. * AES_SETKEY
  8390. *
  8391. * Invoked to establish the key schedule for subsequent encryption/decryption
  8392. *
  8393. ******************************************************************************/
  8394. static int aes_setkey(aes_context *ctx, // AES context provided by our caller
  8395. int mode, // ENCRYPT or DECRYPT flag
  8396. const unsigned char *key, // pointer to the key
  8397. unsigned int keysize) // key length in bytes
  8398. {
  8399. // since table initialization is not thread safe, we could either add
  8400. // system-specific mutexes and init the AES key generation tables on
  8401. // demand, or ask the developer to simply call "gcm_initialize" once during
  8402. // application startup before threading begins. That's what we choose.
  8403. if (!aes_tables_inited) return (-1); // fail the call when not inited.
  8404. ctx->mode = mode; // capture the key type we're creating
  8405. ctx->rk = ctx->buf; // initialize our round key pointer
  8406. switch (keysize) // set the rounds count based upon the keysize
  8407. {
  8408. case 16:
  8409. ctx->rounds = 10;
  8410. break; // 16-byte, 128-bit key
  8411. case 24:
  8412. ctx->rounds = 12;
  8413. break; // 24-byte, 192-bit key
  8414. case 32:
  8415. ctx->rounds = 14;
  8416. break; // 32-byte, 256-bit key
  8417. default:
  8418. return (-1);
  8419. }
  8420. #if AES_DECRYPTION
  8421. if (mode == MG_DECRYPT) // expand our key for encryption or decryption
  8422. return (aes_set_decryption_key(ctx, key, keysize));
  8423. else /* MG_ENCRYPT */
  8424. #endif /* AES_DECRYPTION */
  8425. return (aes_set_encryption_key(ctx, key, keysize));
  8426. }
  8427. /******************************************************************************
  8428. *
  8429. * AES_CIPHER
  8430. *
  8431. * Perform AES encryption and decryption.
  8432. * The AES context will have been setup with the encryption mode
  8433. * and all keying information appropriate for the task.
  8434. *
  8435. ******************************************************************************/
  8436. static int aes_cipher(aes_context *ctx, const unsigned char input[16],
  8437. unsigned char output[16]) {
  8438. int i;
  8439. uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; // general purpose locals
  8440. RK = ctx->rk;
  8441. GET_UINT32_LE(X0, input, 0);
  8442. X0 ^= *RK++; // load our 128-bit
  8443. GET_UINT32_LE(X1, input, 4);
  8444. X1 ^= *RK++; // input buffer in a storage
  8445. GET_UINT32_LE(X2, input, 8);
  8446. X2 ^= *RK++; // memory endian-neutral way
  8447. GET_UINT32_LE(X3, input, 12);
  8448. X3 ^= *RK++;
  8449. #if AES_DECRYPTION // whether AES decryption is supported
  8450. if (ctx->mode == MG_DECRYPT) {
  8451. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  8452. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8453. AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  8454. }
  8455. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8456. X0 = *RK++ ^ ((uint32_t) RSb[(Y0) & 0xFF]) ^
  8457. ((uint32_t) RSb[(Y3 >> 8) & 0xFF] << 8) ^
  8458. ((uint32_t) RSb[(Y2 >> 16) & 0xFF] << 16) ^
  8459. ((uint32_t) RSb[(Y1 >> 24) & 0xFF] << 24);
  8460. X1 = *RK++ ^ ((uint32_t) RSb[(Y1) & 0xFF]) ^
  8461. ((uint32_t) RSb[(Y0 >> 8) & 0xFF] << 8) ^
  8462. ((uint32_t) RSb[(Y3 >> 16) & 0xFF] << 16) ^
  8463. ((uint32_t) RSb[(Y2 >> 24) & 0xFF] << 24);
  8464. X2 = *RK++ ^ ((uint32_t) RSb[(Y2) & 0xFF]) ^
  8465. ((uint32_t) RSb[(Y1 >> 8) & 0xFF] << 8) ^
  8466. ((uint32_t) RSb[(Y0 >> 16) & 0xFF] << 16) ^
  8467. ((uint32_t) RSb[(Y3 >> 24) & 0xFF] << 24);
  8468. X3 = *RK++ ^ ((uint32_t) RSb[(Y3) & 0xFF]) ^
  8469. ((uint32_t) RSb[(Y2 >> 8) & 0xFF] << 8) ^
  8470. ((uint32_t) RSb[(Y1 >> 16) & 0xFF] << 16) ^
  8471. ((uint32_t) RSb[(Y0 >> 24) & 0xFF] << 24);
  8472. } else /* MG_ENCRYPT */
  8473. {
  8474. #endif /* AES_DECRYPTION */
  8475. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  8476. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8477. AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  8478. }
  8479. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8480. X0 = *RK++ ^ ((uint32_t) FSb[(Y0) & 0xFF]) ^
  8481. ((uint32_t) FSb[(Y1 >> 8) & 0xFF] << 8) ^
  8482. ((uint32_t) FSb[(Y2 >> 16) & 0xFF] << 16) ^
  8483. ((uint32_t) FSb[(Y3 >> 24) & 0xFF] << 24);
  8484. X1 = *RK++ ^ ((uint32_t) FSb[(Y1) & 0xFF]) ^
  8485. ((uint32_t) FSb[(Y2 >> 8) & 0xFF] << 8) ^
  8486. ((uint32_t) FSb[(Y3 >> 16) & 0xFF] << 16) ^
  8487. ((uint32_t) FSb[(Y0 >> 24) & 0xFF] << 24);
  8488. X2 = *RK++ ^ ((uint32_t) FSb[(Y2) & 0xFF]) ^
  8489. ((uint32_t) FSb[(Y3 >> 8) & 0xFF] << 8) ^
  8490. ((uint32_t) FSb[(Y0 >> 16) & 0xFF] << 16) ^
  8491. ((uint32_t) FSb[(Y1 >> 24) & 0xFF] << 24);
  8492. X3 = *RK++ ^ ((uint32_t) FSb[(Y3) & 0xFF]) ^
  8493. ((uint32_t) FSb[(Y0 >> 8) & 0xFF] << 8) ^
  8494. ((uint32_t) FSb[(Y1 >> 16) & 0xFF] << 16) ^
  8495. ((uint32_t) FSb[(Y2 >> 24) & 0xFF] << 24);
  8496. #if AES_DECRYPTION // whether AES decryption is supported
  8497. }
  8498. #endif /* AES_DECRYPTION */
  8499. PUT_UINT32_LE(X0, output, 0);
  8500. PUT_UINT32_LE(X1, output, 4);
  8501. PUT_UINT32_LE(X2, output, 8);
  8502. PUT_UINT32_LE(X3, output, 12);
  8503. return (0);
  8504. }
  8505. /* end of aes.c */
  8506. /******************************************************************************
  8507. *
  8508. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  8509. *
  8510. * This is a simple and straightforward implementation of AES-GCM authenticated
  8511. * encryption. The focus of this work was correctness & accuracy. It is written
  8512. * in straight 'C' without any particular focus upon optimization or speed. It
  8513. * should be endian (memory byte order) neutral since the few places that care
  8514. * are handled explicitly.
  8515. *
  8516. * This implementation of AES-GCM was created by Steven M. Gibson of GRC.com.
  8517. *
  8518. * It is intended for general purpose use, but was written in support of GRC's
  8519. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  8520. *
  8521. * See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  8522. * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/
  8523. * gcm/gcm-revised-spec.pdf
  8524. *
  8525. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  8526. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  8527. *
  8528. *******************************************************************************/
  8529. /******************************************************************************
  8530. * ==== IMPLEMENTATION WARNING ====
  8531. *
  8532. * This code was developed for use within SQRL's fixed environmnent. Thus, it
  8533. * is somewhat less "general purpose" than it would be if it were designed as
  8534. * a general purpose AES-GCM library. Specifically, it bothers with almost NO
  8535. * error checking on parameter limits, buffer bounds, etc. It assumes that it
  8536. * is being invoked by its author or by someone who understands the values it
  8537. * expects to receive. Its behavior will be undefined otherwise.
  8538. *
  8539. * All functions that might fail are defined to return 'ints' to indicate a
  8540. * problem. Most do not do so now. But this allows for error propagation out
  8541. * of internal functions if robust error checking should ever be desired.
  8542. *
  8543. ******************************************************************************/
  8544. /* Calculating the "GHASH"
  8545. *
  8546. * There are many ways of calculating the so-called GHASH in software, each with
  8547. * a traditional size vs performance tradeoff. The GHASH (Galois field hash) is
  8548. * an intriguing construction which takes two 128-bit strings (also the cipher's
  8549. * block size and the fundamental operation size for the system) and hashes them
  8550. * into a third 128-bit result.
  8551. *
  8552. * Many implementation solutions have been worked out that use large precomputed
  8553. * table lookups in place of more time consuming bit fiddling, and this approach
  8554. * can be scaled easily upward or downward as needed to change the time/space
  8555. * tradeoff. It's been studied extensively and there's a solid body of theory
  8556. * and practice. For example, without using any lookup tables an implementation
  8557. * might obtain 119 cycles per byte throughput, whereas using a simple, though
  8558. * large, key-specific 64 kbyte 8-bit lookup table the performance jumps to 13
  8559. * cycles per byte.
  8560. *
  8561. * And Intel's processors have, since 2010, included an instruction which does
  8562. * the entire 128x128->128 bit job in just several 64x64->128 bit pieces.
  8563. *
  8564. * Since SQRL is interactive, and only processing a few 128-bit blocks, I've
  8565. * settled upon a relatively slower but appealing small-table compromise which
  8566. * folds a bunch of not only time consuming but also bit twiddling into a simple
  8567. * 16-entry table which is attributed to Victor Shoup's 1996 work while at
  8568. * Bellcore: "On Fast and Provably Secure MessageAuthentication Based on
  8569. * Universal Hashing." See: http://www.shoup.net/papers/macs.pdf
  8570. * See, also section 4.1 of the "gcm-revised-spec" cited above.
  8571. */
  8572. /*
  8573. * This 16-entry table of pre-computed constants is used by the
  8574. * GHASH multiplier to improve over a strictly table-free but
  8575. * significantly slower 128x128 bit multiple within GF(2^128).
  8576. */
  8577. static const uint64_t last4[16] = {
  8578. 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
  8579. 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0};
  8580. /*
  8581. * Platform Endianness Neutralizing Load and Store Macro definitions
  8582. * GCM wants platform-neutral Big Endian (BE) byte ordering
  8583. */
  8584. #define GET_UINT32_BE(n, b, i) \
  8585. { \
  8586. (n) = ((uint32_t) (b)[(i)] << 24) | ((uint32_t) (b)[(i) + 1] << 16) | \
  8587. ((uint32_t) (b)[(i) + 2] << 8) | ((uint32_t) (b)[(i) + 3]); \
  8588. }
  8589. #define PUT_UINT32_BE(n, b, i) \
  8590. { \
  8591. (b)[(i)] = (unsigned char) ((n) >> 24); \
  8592. (b)[(i) + 1] = (unsigned char) ((n) >> 16); \
  8593. (b)[(i) + 2] = (unsigned char) ((n) >> 8); \
  8594. (b)[(i) + 3] = (unsigned char) ((n)); \
  8595. }
  8596. /******************************************************************************
  8597. *
  8598. * GCM_INITIALIZE
  8599. *
  8600. * Must be called once to initialize the GCM library.
  8601. *
  8602. * At present, this only calls the AES keygen table generator, which expands
  8603. * the AES keying tables for use. This is NOT A THREAD-SAFE function, so it
  8604. * MUST be called during system initialization before a multi-threading
  8605. * environment is running.
  8606. *
  8607. ******************************************************************************/
  8608. int mg_gcm_initialize(void) {
  8609. aes_init_keygen_tables();
  8610. return (0);
  8611. }
  8612. /******************************************************************************
  8613. *
  8614. * GCM_MULT
  8615. *
  8616. * Performs a GHASH operation on the 128-bit input vector 'x', setting
  8617. * the 128-bit output vector to 'x' times H using our precomputed tables.
  8618. * 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  8619. *
  8620. ******************************************************************************/
  8621. static void gcm_mult(gcm_context *ctx, // pointer to established context
  8622. const unsigned char x[16], // pointer to 128-bit input vector
  8623. unsigned char output[16]) // pointer to 128-bit output vector
  8624. {
  8625. int i;
  8626. unsigned char lo, hi, rem;
  8627. uint64_t zh, zl;
  8628. lo = (unsigned char) (x[15] & 0x0f);
  8629. hi = (unsigned char) (x[15] >> 4);
  8630. zh = ctx->HH[lo];
  8631. zl = ctx->HL[lo];
  8632. for (i = 15; i >= 0; i--) {
  8633. lo = (unsigned char) (x[i] & 0x0f);
  8634. hi = (unsigned char) (x[i] >> 4);
  8635. if (i != 15) {
  8636. rem = (unsigned char) (zl & 0x0f);
  8637. zl = (zh << 60) | (zl >> 4);
  8638. zh = (zh >> 4);
  8639. zh ^= (uint64_t) last4[rem] << 48;
  8640. zh ^= ctx->HH[lo];
  8641. zl ^= ctx->HL[lo];
  8642. }
  8643. rem = (unsigned char) (zl & 0x0f);
  8644. zl = (zh << 60) | (zl >> 4);
  8645. zh = (zh >> 4);
  8646. zh ^= (uint64_t) last4[rem] << 48;
  8647. zh ^= ctx->HH[hi];
  8648. zl ^= ctx->HL[hi];
  8649. }
  8650. PUT_UINT32_BE(zh >> 32, output, 0);
  8651. PUT_UINT32_BE(zh, output, 4);
  8652. PUT_UINT32_BE(zl >> 32, output, 8);
  8653. PUT_UINT32_BE(zl, output, 12);
  8654. }
  8655. /******************************************************************************
  8656. *
  8657. * GCM_SETKEY
  8658. *
  8659. * This is called to set the AES-GCM key. It initializes the AES key
  8660. * and populates the gcm context's pre-calculated HTables.
  8661. *
  8662. ******************************************************************************/
  8663. static int gcm_setkey(
  8664. gcm_context *ctx, // pointer to caller-provided gcm context
  8665. const unsigned char *key, // pointer to the AES encryption key
  8666. const unsigned int keysize) // size in bytes (must be 16, 24, 32 for
  8667. // 128, 192 or 256-bit keys respectively)
  8668. {
  8669. int ret, i, j;
  8670. uint64_t hi, lo;
  8671. uint64_t vl, vh;
  8672. unsigned char h[16];
  8673. memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
  8674. memset(h, 0, 16); // initialize the block to encrypt
  8675. // encrypt the null 128-bit block to generate a key-based value
  8676. // which is then used to initialize our GHASH lookup tables
  8677. if ((ret = aes_setkey(&ctx->aes_ctx, MG_ENCRYPT, key, keysize)) != 0)
  8678. return (ret);
  8679. if ((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
  8680. GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
  8681. GET_UINT32_BE(lo, h, 4);
  8682. vh = (uint64_t) hi << 32 | lo;
  8683. GET_UINT32_BE(hi, h, 8);
  8684. GET_UINT32_BE(lo, h, 12);
  8685. vl = (uint64_t) hi << 32 | lo;
  8686. ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
  8687. ctx->HH[8] = vh;
  8688. ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
  8689. ctx->HL[0] = 0;
  8690. for (i = 4; i > 0; i >>= 1) {
  8691. uint32_t T = (uint32_t) (vl & 1) * 0xe1000000U;
  8692. vl = (vh << 63) | (vl >> 1);
  8693. vh = (vh >> 1) ^ ((uint64_t) T << 32);
  8694. ctx->HL[i] = vl;
  8695. ctx->HH[i] = vh;
  8696. }
  8697. for (i = 2; i < 16; i <<= 1) {
  8698. uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
  8699. vh = *HiH;
  8700. vl = *HiL;
  8701. for (j = 1; j < i; j++) {
  8702. HiH[j] = vh ^ ctx->HH[j];
  8703. HiL[j] = vl ^ ctx->HL[j];
  8704. }
  8705. }
  8706. return (0);
  8707. }
  8708. /******************************************************************************
  8709. *
  8710. * GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
  8711. *
  8712. * SETKEY:
  8713. *
  8714. * START: Sets the Encryption/Decryption mode.
  8715. * Accepts the initialization vector and additional data.
  8716. *
  8717. * UPDATE: Encrypts or decrypts the plaintext or ciphertext.
  8718. *
  8719. * FINISH: Performs a final GHASH to generate the authentication tag.
  8720. *
  8721. ******************************************************************************
  8722. *
  8723. * GCM_START
  8724. *
  8725. * Given a user-provided GCM context, this initializes it, sets the encryption
  8726. * mode, and preprocesses the initialization vector and additional AEAD data.
  8727. *
  8728. ******************************************************************************/
  8729. int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context
  8730. int mode, // GCM_ENCRYPT or GCM_DECRYPT
  8731. const unsigned char *iv, // pointer to initialization vector
  8732. size_t iv_len, // IV length in bytes (should == 12)
  8733. const unsigned char *add, // ptr to additional AEAD data (NULL if none)
  8734. size_t add_len) // length of additional AEAD data (bytes)
  8735. {
  8736. int ret; // our error return if the AES encrypt fails
  8737. unsigned char work_buf[16]; // XOR source built from provided IV if len != 16
  8738. const unsigned char *p; // general purpose array pointer
  8739. size_t use_len; // byte count to process, up to 16 bytes
  8740. size_t i; // local loop iterator
  8741. // since the context might be reused under the same key
  8742. // we zero the working buffers for this next new process
  8743. memset(ctx->y, 0x00, sizeof(ctx->y));
  8744. memset(ctx->buf, 0x00, sizeof(ctx->buf));
  8745. ctx->len = 0;
  8746. ctx->add_len = 0;
  8747. ctx->mode = mode; // set the GCM encryption/decryption mode
  8748. ctx->aes_ctx.mode = MG_ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
  8749. if (iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
  8750. memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
  8751. ctx->y[15] = 1; // start "counting" from 1 (not 0)
  8752. } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
  8753. {
  8754. memset(work_buf, 0x00, 16); // clear the working buffer
  8755. PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
  8756. p = iv;
  8757. while (iv_len > 0) {
  8758. use_len = (iv_len < 16) ? iv_len : 16;
  8759. for (i = 0; i < use_len; i++) ctx->y[i] ^= p[i];
  8760. gcm_mult(ctx, ctx->y, ctx->y);
  8761. iv_len -= use_len;
  8762. p += use_len;
  8763. }
  8764. for (i = 0; i < 16; i++) ctx->y[i] ^= work_buf[i];
  8765. gcm_mult(ctx, ctx->y, ctx->y);
  8766. }
  8767. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0)
  8768. return (ret);
  8769. ctx->add_len = add_len;
  8770. p = add;
  8771. while (add_len > 0) {
  8772. use_len = (add_len < 16) ? add_len : 16;
  8773. for (i = 0; i < use_len; i++) ctx->buf[i] ^= p[i];
  8774. gcm_mult(ctx, ctx->buf, ctx->buf);
  8775. add_len -= use_len;
  8776. p += use_len;
  8777. }
  8778. return (0);
  8779. }
  8780. /******************************************************************************
  8781. *
  8782. * GCM_UPDATE
  8783. *
  8784. * This is called once or more to process bulk plaintext or ciphertext data.
  8785. * We give this some number of bytes of input and it returns the same number
  8786. * of output bytes. If called multiple times (which is fine) all but the final
  8787. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  8788. * have a partial block length of < 128 bits.)
  8789. *
  8790. ******************************************************************************/
  8791. int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  8792. size_t length, // length, in bytes, of data to process
  8793. const unsigned char *input, // pointer to source data
  8794. unsigned char *output) // pointer to destination data
  8795. {
  8796. int ret; // our error return if the AES encrypt fails
  8797. unsigned char ectr[16]; // counter-mode cipher output for XORing
  8798. size_t use_len; // byte count to process, up to 16 bytes
  8799. size_t i; // local loop iterator
  8800. ctx->len += length; // bump the GCM context's running length count
  8801. while (length > 0) {
  8802. // clamp the length to process at 16 bytes
  8803. use_len = (length < 16) ? length : 16;
  8804. // increment the context's 128-bit IV||Counter 'y' vector
  8805. for (i = 16; i > 12; i--)
  8806. if (++ctx->y[i - 1] != 0) break;
  8807. // encrypt the context's 'y' vector under the established key
  8808. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
  8809. // encrypt or decrypt the input to the output
  8810. if (ctx->mode == MG_ENCRYPT) {
  8811. for (i = 0; i < use_len; i++) {
  8812. // XOR the cipher's ouptut vector (ectr) with our input
  8813. output[i] = (unsigned char) (ectr[i] ^ input[i]);
  8814. // now we mix in our data into the authentication hash.
  8815. // if we're ENcrypting we XOR in the post-XOR (output)
  8816. // results, but if we're DEcrypting we XOR in the input
  8817. // data
  8818. ctx->buf[i] ^= output[i];
  8819. }
  8820. } else {
  8821. for (i = 0; i < use_len; i++) {
  8822. // but if we're DEcrypting we XOR in the input data first,
  8823. // i.e. before saving to ouput data, otherwise if the input
  8824. // and output buffer are the same (inplace decryption) we
  8825. // would not get the correct auth tag
  8826. ctx->buf[i] ^= input[i];
  8827. // XOR the cipher's ouptut vector (ectr) with our input
  8828. output[i] = (unsigned char) (ectr[i] ^ input[i]);
  8829. }
  8830. }
  8831. gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
  8832. length -= use_len; // drop the remaining byte count to process
  8833. input += use_len; // bump our input pointer forward
  8834. output += use_len; // bump our output pointer forward
  8835. }
  8836. return (0);
  8837. }
  8838. /******************************************************************************
  8839. *
  8840. * GCM_FINISH
  8841. *
  8842. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  8843. * It performs the final GHASH to produce the resulting authentication TAG.
  8844. *
  8845. ******************************************************************************/
  8846. int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context
  8847. unsigned char *tag, // pointer to buffer which receives the tag
  8848. size_t tag_len) // length, in bytes, of the tag-receiving buf
  8849. {
  8850. unsigned char work_buf[16];
  8851. uint64_t orig_len = ctx->len * 8;
  8852. uint64_t orig_add_len = ctx->add_len * 8;
  8853. size_t i;
  8854. if (tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
  8855. if (orig_len || orig_add_len) {
  8856. memset(work_buf, 0x00, 16);
  8857. PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
  8858. PUT_UINT32_BE((orig_add_len), work_buf, 4);
  8859. PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
  8860. PUT_UINT32_BE((orig_len), work_buf, 12);
  8861. for (i = 0; i < 16; i++) ctx->buf[i] ^= work_buf[i];
  8862. gcm_mult(ctx, ctx->buf, ctx->buf);
  8863. for (i = 0; i < tag_len; i++) tag[i] ^= ctx->buf[i];
  8864. }
  8865. return (0);
  8866. }
  8867. /******************************************************************************
  8868. *
  8869. * GCM_CRYPT_AND_TAG
  8870. *
  8871. * This either encrypts or decrypts the user-provided data and, either
  8872. * way, generates an authentication tag of the requested length. It must be
  8873. * called with a GCM context whose key has already been set with GCM_SETKEY.
  8874. *
  8875. * The user would typically call this explicitly to ENCRYPT a buffer of data
  8876. * and optional associated data, and produce its an authentication tag.
  8877. *
  8878. * To reverse the process the user would typically call the companion
  8879. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  8880. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  8881. * to perform its decryption and tag generation, which it then compares.
  8882. *
  8883. ******************************************************************************/
  8884. int gcm_crypt_and_tag(
  8885. gcm_context *ctx, // gcm context with key already setup
  8886. int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
  8887. const unsigned char *iv, // pointer to the 12-byte initialization vector
  8888. size_t iv_len, // byte length if the IV. should always be 12
  8889. const unsigned char *add, // pointer to the non-ciphered additional data
  8890. size_t add_len, // byte length of the additional AEAD data
  8891. const unsigned char *input, // pointer to the cipher data source
  8892. unsigned char *output, // pointer to the cipher data destination
  8893. size_t length, // byte length of the cipher data
  8894. unsigned char *tag, // pointer to the tag to be generated
  8895. size_t tag_len) // byte length of the tag to be generated
  8896. { /*
  8897. assuming that the caller has already invoked gcm_setkey to
  8898. prepare the gcm context with the keying material, we simply
  8899. invoke each of the three GCM sub-functions in turn...
  8900. */
  8901. gcm_start(ctx, mode, iv, iv_len, add, add_len);
  8902. gcm_update(ctx, length, input, output);
  8903. gcm_finish(ctx, tag, tag_len);
  8904. return (0);
  8905. }
  8906. /******************************************************************************
  8907. *
  8908. * GCM_ZERO_CTX
  8909. *
  8910. * The GCM context contains both the GCM context and the AES context.
  8911. * This includes keying and key-related material which is security-
  8912. * sensitive, so it MUST be zeroed after use. This function does that.
  8913. *
  8914. ******************************************************************************/
  8915. void gcm_zero_ctx(gcm_context *ctx) {
  8916. // zero the context originally provided to us
  8917. memset(ctx, 0, sizeof(gcm_context));
  8918. }
  8919. //
  8920. // aes-gcm.c
  8921. // Pods
  8922. //
  8923. // Created by Markus Kosmal on 20/11/14.
  8924. //
  8925. //
  8926. int mg_aes_gcm_encrypt(unsigned char *output, //
  8927. const unsigned char *input, size_t input_length,
  8928. const unsigned char *key, const size_t key_len,
  8929. const unsigned char *iv, const size_t iv_len,
  8930. unsigned char *aead, size_t aead_len, unsigned char *tag,
  8931. const size_t tag_len) {
  8932. int ret = 0; // our return value
  8933. gcm_context ctx; // includes the AES context structure
  8934. gcm_setkey(&ctx, key, (unsigned int) key_len);
  8935. ret = gcm_crypt_and_tag(&ctx, MG_ENCRYPT, iv, iv_len, aead, aead_len, input,
  8936. output, input_length, tag, tag_len);
  8937. gcm_zero_ctx(&ctx);
  8938. return (ret);
  8939. }
  8940. int mg_aes_gcm_decrypt(unsigned char *output, const unsigned char *input,
  8941. size_t input_length, const unsigned char *key,
  8942. const size_t key_len, const unsigned char *iv,
  8943. const size_t iv_len) {
  8944. int ret = 0; // our return value
  8945. gcm_context ctx; // includes the AES context structure
  8946. size_t tag_len = 0;
  8947. unsigned char *tag_buf = NULL;
  8948. gcm_setkey(&ctx, key, (unsigned int) key_len);
  8949. ret = gcm_crypt_and_tag(&ctx, MG_DECRYPT, iv, iv_len, NULL, 0, input, output,
  8950. input_length, tag_buf, tag_len);
  8951. gcm_zero_ctx(&ctx);
  8952. return (ret);
  8953. }
  8954. #endif
  8955. // End of aes128 PD
  8956. #ifdef MG_ENABLE_LINES
  8957. #line 1 "src/tls_builtin.c"
  8958. #endif
  8959. #if MG_TLS == MG_TLS_BUILTIN
  8960. #define CHACHA20 1
  8961. /* TLS 1.3 Record Content Type (RFC8446 B.1) */
  8962. #define MG_TLS_CHANGE_CIPHER 20
  8963. #define MG_TLS_ALERT 21
  8964. #define MG_TLS_HANDSHAKE 22
  8965. #define MG_TLS_APP_DATA 23
  8966. #define MG_TLS_HEARTBEAT 24
  8967. /* TLS 1.3 Handshake Message Type (RFC8446 B.3) */
  8968. #define MG_TLS_CLIENT_HELLO 1
  8969. #define MG_TLS_SERVER_HELLO 2
  8970. #define MG_TLS_ENCRYPTED_EXTENSIONS 8
  8971. #define MG_TLS_CERTIFICATE 11
  8972. #define MG_TLS_CERTIFICATE_REQUEST 13
  8973. #define MG_TLS_CERTIFICATE_VERIFY 15
  8974. #define MG_TLS_FINISHED 20
  8975. // handshake is re-entrant, so we need to keep track of its state state names
  8976. // refer to RFC8446#A.1
  8977. enum mg_tls_hs_state {
  8978. // Client state machine:
  8979. MG_TLS_STATE_CLIENT_START, // Send ClientHello
  8980. MG_TLS_STATE_CLIENT_WAIT_SH, // Wait for ServerHello
  8981. MG_TLS_STATE_CLIENT_WAIT_EE, // Wait for EncryptedExtensions
  8982. MG_TLS_STATE_CLIENT_WAIT_CERT, // Wait for Certificate
  8983. MG_TLS_STATE_CLIENT_WAIT_CV, // Wait for CertificateVerify
  8984. MG_TLS_STATE_CLIENT_WAIT_FINISHED, // Wait for Finished
  8985. MG_TLS_STATE_CLIENT_CONNECTED, // Done
  8986. // Server state machine:
  8987. MG_TLS_STATE_SERVER_START, // Wait for ClientHello
  8988. MG_TLS_STATE_SERVER_NEGOTIATED, // Wait for Finished
  8989. MG_TLS_STATE_SERVER_CONNECTED // Done
  8990. };
  8991. // encryption keys for a TLS connection
  8992. struct tls_enc {
  8993. uint32_t sseq; // server sequence number, used in encryption
  8994. uint32_t cseq; // client sequence number, used in decryption
  8995. // keys for AES encryption or ChaCha20
  8996. uint8_t handshake_secret[32];
  8997. uint8_t server_write_key[32];
  8998. uint8_t server_write_iv[12];
  8999. uint8_t server_finished_key[32];
  9000. uint8_t client_write_key[32];
  9001. uint8_t client_write_iv[12];
  9002. uint8_t client_finished_key[32];
  9003. };
  9004. // per-connection TLS data
  9005. struct tls_data {
  9006. enum mg_tls_hs_state state; // keep track of connection handshake progress
  9007. struct mg_iobuf send; // For the receive path, we're reusing c->rtls
  9008. size_t recv_offset; // While c->rtls contains full records, reuse that
  9009. size_t recv_len; // buffer but point at individual decrypted messages
  9010. uint8_t content_type; // Last received record content type
  9011. mg_sha256_ctx sha256; // incremental SHA-256 hash for TLS handshake
  9012. uint8_t random[32]; // client random from ClientHello
  9013. uint8_t session_id[32]; // client session ID between the handshake states
  9014. uint8_t x25519_cli[32]; // client X25519 key between the handshake states
  9015. uint8_t x25519_sec[32]; // x25519 secret between the handshake states
  9016. int skip_verification; // perform checks on server certificate?
  9017. int cert_requested; // client received a CertificateRequest?
  9018. struct mg_str cert_der; // certificate in DER format
  9019. uint8_t ec_key[32]; // EC private key
  9020. char hostname[254]; // server hostname (client extension)
  9021. uint8_t certhash[32]; // certificate message hash
  9022. uint8_t pubkey[64]; // server EC public key to verify cert
  9023. uint8_t sighash[32]; // server EC public key to verify cert
  9024. struct tls_enc enc;
  9025. };
  9026. #define TLS_RECHDR_SIZE 5 // 1 byte type, 2 bytes version, 2 bytes length
  9027. #define TLS_MSGHDR_SIZE 4 // 1 byte type, 3 bytes length
  9028. #ifdef MG_TLS_SSLKEYLOGFILE
  9029. #include <stdio.h>
  9030. static void mg_ssl_key_log(const char *label, uint8_t client_random[32],
  9031. uint8_t *secret, size_t secretsz) {
  9032. char *keylogfile = getenv("SSLKEYLOGFILE");
  9033. size_t i;
  9034. if (keylogfile != NULL) {
  9035. MG_DEBUG(("Dumping key log into %s", keylogfile));
  9036. FILE *f = fopen(keylogfile, "a");
  9037. if (f != NULL) {
  9038. fprintf(f, "%s ", label);
  9039. for (i = 0; i < 32; i++) {
  9040. fprintf(f, "%02x", client_random[i]);
  9041. }
  9042. fprintf(f, " ");
  9043. for (i = 0; i < secretsz; i++) {
  9044. fprintf(f, "%02x", secret[i]);
  9045. }
  9046. fprintf(f, "\n");
  9047. fclose(f);
  9048. } else {
  9049. MG_ERROR(("Cannot open %s", keylogfile));
  9050. }
  9051. }
  9052. }
  9053. #endif
  9054. // for derived tls keys we need SHA256([0]*32)
  9055. static uint8_t zeros[32] = {0};
  9056. static uint8_t zeros_sha256_digest[32] = {
  9057. 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4,
  9058. 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b,
  9059. 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55};
  9060. // helper to hexdump buffers inline
  9061. static void mg_tls_hexdump(const char *msg, uint8_t *buf, size_t bufsz) {
  9062. MG_VERBOSE(("%s: %M", msg, mg_print_hex, bufsz, buf));
  9063. }
  9064. // helper utilities to parse ASN.1 DER
  9065. struct mg_der_tlv {
  9066. uint8_t type;
  9067. uint32_t len;
  9068. uint8_t *value;
  9069. };
  9070. // parse DER into a TLV record
  9071. static int mg_der_to_tlv(uint8_t *der, size_t dersz, struct mg_der_tlv *tlv) {
  9072. if (dersz < 2) {
  9073. return -1;
  9074. }
  9075. tlv->type = der[0];
  9076. tlv->len = der[1];
  9077. tlv->value = der + 2;
  9078. if (tlv->len > 0x7f) {
  9079. uint32_t i, n = tlv->len - 0x80;
  9080. tlv->len = 0;
  9081. for (i = 0; i < n; i++) {
  9082. tlv->len = (tlv->len << 8) | (der[2 + i]);
  9083. }
  9084. tlv->value = der + 2 + n;
  9085. }
  9086. if (der + dersz < tlv->value + tlv->len) {
  9087. return -1;
  9088. }
  9089. return 0;
  9090. }
  9091. static int mg_der_find(uint8_t *der, size_t dersz, uint8_t *oid, size_t oidsz,
  9092. struct mg_der_tlv *tlv) {
  9093. uint8_t *p, *end;
  9094. struct mg_der_tlv child = {0, 0, NULL};
  9095. if (mg_der_to_tlv(der, dersz, tlv) < 0) {
  9096. return -1; // invalid DER
  9097. } else if (tlv->type == 6) { // found OID, check value
  9098. return (tlv->len == oidsz && memcmp(tlv->value, oid, oidsz) == 0);
  9099. } else if ((tlv->type & 0x20) == 0) {
  9100. return 0; // Primitive, but not OID: not found
  9101. }
  9102. // Constructed object: scan children
  9103. p = tlv->value;
  9104. end = tlv->value + tlv->len;
  9105. while (end > p) {
  9106. int r;
  9107. mg_der_to_tlv(p, (size_t) (end - p), &child);
  9108. r = mg_der_find(p, (size_t) (end - p), oid, oidsz, tlv);
  9109. if (r < 0) return -1; // error
  9110. if (r > 0) return 1; // found OID!
  9111. p = child.value + child.len;
  9112. }
  9113. return 0; // not found
  9114. }
  9115. // Did we receive a full TLS record in the c->rtls buffer?
  9116. static bool mg_tls_got_record(struct mg_connection *c) {
  9117. return c->rtls.len >= (size_t) TLS_RECHDR_SIZE &&
  9118. c->rtls.len >=
  9119. (size_t) (TLS_RECHDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
  9120. }
  9121. // Remove a single TLS record from the recv buffer
  9122. static void mg_tls_drop_record(struct mg_connection *c) {
  9123. struct mg_iobuf *rio = &c->rtls;
  9124. uint16_t n = MG_LOAD_BE16(rio->buf + 3) + TLS_RECHDR_SIZE;
  9125. mg_iobuf_del(rio, 0, n);
  9126. }
  9127. // Remove a single TLS message from decrypted buffer, remove the wrapping
  9128. // record if it was the last message within a record
  9129. static void mg_tls_drop_message(struct mg_connection *c) {
  9130. uint32_t len;
  9131. struct tls_data *tls = (struct tls_data *) c->tls;
  9132. unsigned char *recv_buf = &c->rtls.buf[tls->recv_offset];
  9133. if (tls->recv_len == 0) return;
  9134. len = MG_LOAD_BE24(recv_buf + 1) + TLS_MSGHDR_SIZE;
  9135. if (tls->recv_len < len) {
  9136. mg_error(c, "wrong size");
  9137. return;
  9138. }
  9139. mg_sha256_update(&tls->sha256, recv_buf, len);
  9140. tls->recv_offset += len;
  9141. tls->recv_len -= len;
  9142. if (tls->recv_len == 0) {
  9143. mg_tls_drop_record(c);
  9144. }
  9145. }
  9146. // TLS1.3 secret derivation based on the key label
  9147. static void mg_tls_derive_secret(const char *label, uint8_t *key, size_t keysz,
  9148. uint8_t *data, size_t datasz, uint8_t *hash,
  9149. size_t hashsz) {
  9150. size_t labelsz = strlen(label);
  9151. uint8_t secret[32];
  9152. uint8_t packed[256] = {0, (uint8_t) hashsz, (uint8_t) labelsz};
  9153. // TODO: assert lengths of label, key, data and hash
  9154. if (labelsz > 0) memmove(packed + 3, label, labelsz);
  9155. packed[3 + labelsz] = (uint8_t) datasz;
  9156. if (datasz > 0) memmove(packed + labelsz + 4, data, datasz);
  9157. packed[4 + labelsz + datasz] = 1;
  9158. mg_hmac_sha256(secret, key, keysz, packed, 5 + labelsz + datasz);
  9159. memmove(hash, secret, hashsz);
  9160. }
  9161. // at this point we have x25519 shared secret, we can generate a set of derived
  9162. // handshake encryption keys
  9163. static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
  9164. struct tls_data *tls = (struct tls_data *) c->tls;
  9165. mg_sha256_ctx sha256;
  9166. uint8_t early_secret[32];
  9167. uint8_t pre_extract_secret[32];
  9168. uint8_t hello_hash[32];
  9169. uint8_t server_hs_secret[32];
  9170. uint8_t client_hs_secret[32];
  9171. #if CHACHA20
  9172. const size_t keysz = 32;
  9173. #else
  9174. const size_t keysz = 16;
  9175. #endif
  9176. mg_hmac_sha256(early_secret, NULL, 0, zeros, sizeof(zeros));
  9177. mg_tls_derive_secret("tls13 derived", early_secret, 32, zeros_sha256_digest,
  9178. 32, pre_extract_secret, 32);
  9179. mg_hmac_sha256(tls->enc.handshake_secret, pre_extract_secret,
  9180. sizeof(pre_extract_secret), tls->x25519_sec,
  9181. sizeof(tls->x25519_sec));
  9182. mg_tls_hexdump("hs secret", tls->enc.handshake_secret, 32);
  9183. // mg_sha256_final is not idempotent, need to copy sha256 context to calculate
  9184. // the digest
  9185. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9186. mg_sha256_final(hello_hash, &sha256);
  9187. mg_tls_hexdump("hello hash", hello_hash, 32);
  9188. // derive keys needed for the rest of the handshake
  9189. mg_tls_derive_secret("tls13 s hs traffic", tls->enc.handshake_secret, 32,
  9190. hello_hash, 32, server_hs_secret, 32);
  9191. mg_tls_derive_secret("tls13 c hs traffic", tls->enc.handshake_secret, 32,
  9192. hello_hash, 32, client_hs_secret, 32);
  9193. mg_tls_derive_secret("tls13 key", server_hs_secret, 32, NULL, 0,
  9194. tls->enc.server_write_key, keysz);
  9195. mg_tls_derive_secret("tls13 iv", server_hs_secret, 32, NULL, 0,
  9196. tls->enc.server_write_iv, 12);
  9197. mg_tls_derive_secret("tls13 finished", server_hs_secret, 32, NULL, 0,
  9198. tls->enc.server_finished_key, 32);
  9199. mg_tls_derive_secret("tls13 key", client_hs_secret, 32, NULL, 0,
  9200. tls->enc.client_write_key, keysz);
  9201. mg_tls_derive_secret("tls13 iv", client_hs_secret, 32, NULL, 0,
  9202. tls->enc.client_write_iv, 12);
  9203. mg_tls_derive_secret("tls13 finished", client_hs_secret, 32, NULL, 0,
  9204. tls->enc.client_finished_key, 32);
  9205. mg_tls_hexdump("s hs traffic", server_hs_secret, 32);
  9206. mg_tls_hexdump("s key", tls->enc.server_write_key, keysz);
  9207. mg_tls_hexdump("s iv", tls->enc.server_write_iv, 12);
  9208. mg_tls_hexdump("s finished", tls->enc.server_finished_key, 32);
  9209. mg_tls_hexdump("c hs traffic", client_hs_secret, 32);
  9210. mg_tls_hexdump("c key", tls->enc.client_write_key, keysz);
  9211. mg_tls_hexdump("c iv", tls->enc.client_write_iv, 12);
  9212. mg_tls_hexdump("c finished", tls->enc.client_finished_key, 32);
  9213. #ifdef MG_TLS_SSLKEYLOGFILE
  9214. mg_ssl_key_log("SERVER_HANDSHAKE_TRAFFIC_SECRET", tls->random,
  9215. server_hs_secret, 32);
  9216. mg_ssl_key_log("CLIENT_HANDSHAKE_TRAFFIC_SECRET", tls->random,
  9217. client_hs_secret, 32);
  9218. #endif
  9219. }
  9220. static void mg_tls_generate_application_keys(struct mg_connection *c) {
  9221. struct tls_data *tls = (struct tls_data *) c->tls;
  9222. uint8_t hash[32];
  9223. uint8_t premaster_secret[32];
  9224. uint8_t master_secret[32];
  9225. uint8_t server_secret[32];
  9226. uint8_t client_secret[32];
  9227. #if CHACHA20
  9228. const size_t keysz = 32;
  9229. #else
  9230. const size_t keysz = 16;
  9231. #endif
  9232. mg_sha256_ctx sha256;
  9233. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9234. mg_sha256_final(hash, &sha256);
  9235. mg_tls_derive_secret("tls13 derived", tls->enc.handshake_secret, 32,
  9236. zeros_sha256_digest, 32, premaster_secret, 32);
  9237. mg_hmac_sha256(master_secret, premaster_secret, 32, zeros, 32);
  9238. mg_tls_derive_secret("tls13 s ap traffic", master_secret, 32, hash, 32,
  9239. server_secret, 32);
  9240. mg_tls_derive_secret("tls13 key", server_secret, 32, NULL, 0,
  9241. tls->enc.server_write_key, keysz);
  9242. mg_tls_derive_secret("tls13 iv", server_secret, 32, NULL, 0,
  9243. tls->enc.server_write_iv, 12);
  9244. mg_tls_derive_secret("tls13 c ap traffic", master_secret, 32, hash, 32,
  9245. client_secret, 32);
  9246. mg_tls_derive_secret("tls13 key", client_secret, 32, NULL, 0,
  9247. tls->enc.client_write_key, keysz);
  9248. mg_tls_derive_secret("tls13 iv", client_secret, 32, NULL, 0,
  9249. tls->enc.client_write_iv, 12);
  9250. mg_tls_hexdump("s ap traffic", server_secret, 32);
  9251. mg_tls_hexdump("s key", tls->enc.server_write_key, keysz);
  9252. mg_tls_hexdump("s iv", tls->enc.server_write_iv, 12);
  9253. mg_tls_hexdump("s finished", tls->enc.server_finished_key, 32);
  9254. mg_tls_hexdump("c ap traffic", client_secret, 32);
  9255. mg_tls_hexdump("c key", tls->enc.client_write_key, keysz);
  9256. mg_tls_hexdump("c iv", tls->enc.client_write_iv, 12);
  9257. mg_tls_hexdump("c finished", tls->enc.client_finished_key, 32);
  9258. tls->enc.sseq = tls->enc.cseq = 0;
  9259. #ifdef MG_TLS_SSLKEYLOGFILE
  9260. mg_ssl_key_log("SERVER_TRAFFIC_SECRET_0", tls->random, server_secret, 32);
  9261. mg_ssl_key_log("CLIENT_TRAFFIC_SECRET_0", tls->random, client_secret, 32);
  9262. #endif
  9263. }
  9264. // AES GCM encryption of the message + put encoded data into the write buffer
  9265. static void mg_tls_encrypt(struct mg_connection *c, const uint8_t *msg,
  9266. size_t msgsz, uint8_t msgtype) {
  9267. struct tls_data *tls = (struct tls_data *) c->tls;
  9268. struct mg_iobuf *wio = &tls->send;
  9269. uint8_t *outmsg;
  9270. uint8_t *tag;
  9271. size_t encsz = msgsz + 16 + 1;
  9272. uint8_t hdr[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
  9273. (uint8_t) ((encsz >> 8) & 0xff), (uint8_t) (encsz & 0xff)};
  9274. uint8_t associated_data[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
  9275. (uint8_t) ((encsz >> 8) & 0xff),
  9276. (uint8_t) (encsz & 0xff)};
  9277. uint8_t nonce[12];
  9278. uint32_t seq = c->is_client ? tls->enc.cseq : tls->enc.sseq;
  9279. uint8_t *key =
  9280. c->is_client ? tls->enc.client_write_key : tls->enc.server_write_key;
  9281. uint8_t *iv =
  9282. c->is_client ? tls->enc.client_write_iv : tls->enc.server_write_iv;
  9283. #if !CHACHA20
  9284. mg_gcm_initialize();
  9285. #endif
  9286. memmove(nonce, iv, sizeof(nonce));
  9287. nonce[8] ^= (uint8_t) ((seq >> 24) & 255U);
  9288. nonce[9] ^= (uint8_t) ((seq >> 16) & 255U);
  9289. nonce[10] ^= (uint8_t) ((seq >> 8) & 255U);
  9290. nonce[11] ^= (uint8_t) ((seq) &255U);
  9291. mg_iobuf_add(wio, wio->len, hdr, sizeof(hdr));
  9292. mg_iobuf_resize(wio, wio->len + encsz);
  9293. outmsg = wio->buf + wio->len;
  9294. tag = wio->buf + wio->len + msgsz + 1;
  9295. memmove(outmsg, msg, msgsz);
  9296. outmsg[msgsz] = msgtype;
  9297. #if CHACHA20
  9298. (void) tag; // tag is only used in aes gcm
  9299. {
  9300. size_t maxlen = MG_IO_SIZE > 16384 ? 16384 : MG_IO_SIZE;
  9301. uint8_t *enc = (uint8_t *) calloc(1, maxlen + 256 + 1);
  9302. if (enc == NULL) {
  9303. mg_error(c, "TLS OOM");
  9304. return;
  9305. } else {
  9306. size_t n = mg_chacha20_poly1305_encrypt(enc, key, nonce, associated_data,
  9307. sizeof(associated_data), outmsg,
  9308. msgsz + 1);
  9309. memmove(outmsg, enc, n);
  9310. free(enc);
  9311. }
  9312. }
  9313. #else
  9314. mg_aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, key, 16, nonce, sizeof(nonce),
  9315. associated_data, sizeof(associated_data), tag, 16);
  9316. #endif
  9317. c->is_client ? tls->enc.cseq++ : tls->enc.sseq++;
  9318. wio->len += encsz;
  9319. }
  9320. // read an encrypted record, decrypt it in place
  9321. static int mg_tls_recv_record(struct mg_connection *c) {
  9322. struct tls_data *tls = (struct tls_data *) c->tls;
  9323. struct mg_iobuf *rio = &c->rtls;
  9324. uint16_t msgsz;
  9325. uint8_t *msg;
  9326. uint8_t nonce[12];
  9327. int r;
  9328. uint32_t seq = c->is_client ? tls->enc.sseq : tls->enc.cseq;
  9329. uint8_t *key =
  9330. c->is_client ? tls->enc.server_write_key : tls->enc.client_write_key;
  9331. uint8_t *iv =
  9332. c->is_client ? tls->enc.server_write_iv : tls->enc.client_write_iv;
  9333. if (tls->recv_len > 0) {
  9334. return 0; /* some data from previous record is still present */
  9335. }
  9336. for (;;) {
  9337. if (!mg_tls_got_record(c)) {
  9338. return MG_IO_WAIT;
  9339. }
  9340. if (rio->buf[0] == MG_TLS_APP_DATA) {
  9341. break;
  9342. } else if (rio->buf[0] ==
  9343. MG_TLS_CHANGE_CIPHER) { // Skip ChangeCipher messages
  9344. mg_tls_drop_record(c);
  9345. } else if (rio->buf[0] == MG_TLS_ALERT) { // Skip Alerts
  9346. MG_INFO(("TLS ALERT packet received"));
  9347. mg_tls_drop_record(c);
  9348. } else {
  9349. mg_error(c, "unexpected packet");
  9350. return -1;
  9351. }
  9352. }
  9353. msgsz = MG_LOAD_BE16(rio->buf + 3);
  9354. msg = rio->buf + 5;
  9355. if (msgsz < 16) {
  9356. mg_error(c, "wrong size");
  9357. return -1;
  9358. }
  9359. memmove(nonce, iv, sizeof(nonce));
  9360. nonce[8] ^= (uint8_t) ((seq >> 24) & 255U);
  9361. nonce[9] ^= (uint8_t) ((seq >> 16) & 255U);
  9362. nonce[10] ^= (uint8_t) ((seq >> 8) & 255U);
  9363. nonce[11] ^= (uint8_t) ((seq) &255U);
  9364. #if CHACHA20
  9365. {
  9366. uint8_t *dec = (uint8_t *) calloc(1, msgsz);
  9367. size_t n;
  9368. if (dec == NULL) {
  9369. mg_error(c, "TLS OOM");
  9370. return -1;
  9371. }
  9372. n = mg_chacha20_poly1305_decrypt(dec, key, nonce, msg, msgsz);
  9373. memmove(msg, dec, n);
  9374. free(dec);
  9375. }
  9376. #else
  9377. mg_gcm_initialize();
  9378. mg_aes_gcm_decrypt(msg, msg, msgsz - 16, key, 16, nonce, sizeof(nonce));
  9379. #endif
  9380. r = msgsz - 16 - 1;
  9381. tls->content_type = msg[msgsz - 16 - 1];
  9382. tls->recv_offset = (size_t) msg - (size_t) rio->buf;
  9383. tls->recv_len = msgsz - 16 - 1;
  9384. c->is_client ? tls->enc.sseq++ : tls->enc.cseq++;
  9385. return r;
  9386. }
  9387. static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
  9388. uint8_t hash[32], int is_client) {
  9389. struct tls_data *tls = (struct tls_data *) c->tls;
  9390. uint8_t server_context[34] = "TLS 1.3, server CertificateVerify";
  9391. uint8_t client_context[34] = "TLS 1.3, client CertificateVerify";
  9392. uint8_t sig_content[130];
  9393. mg_sha256_ctx sha256;
  9394. memset(sig_content, 0x20, 64);
  9395. if (is_client) {
  9396. memmove(sig_content + 64, client_context, sizeof(client_context));
  9397. } else {
  9398. memmove(sig_content + 64, server_context, sizeof(server_context));
  9399. }
  9400. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9401. mg_sha256_final(sig_content + 98, &sha256);
  9402. mg_sha256_init(&sha256);
  9403. mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
  9404. mg_sha256_final(hash, &sha256);
  9405. }
  9406. // read and parse ClientHello record
  9407. static int mg_tls_server_recv_hello(struct mg_connection *c) {
  9408. struct tls_data *tls = (struct tls_data *) c->tls;
  9409. struct mg_iobuf *rio = &c->rtls;
  9410. uint8_t session_id_len;
  9411. uint16_t j;
  9412. uint16_t cipher_suites_len;
  9413. uint16_t ext_len;
  9414. uint8_t *ext;
  9415. uint16_t msgsz;
  9416. if (!mg_tls_got_record(c)) {
  9417. return MG_IO_WAIT;
  9418. }
  9419. if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_CLIENT_HELLO) {
  9420. mg_error(c, "not a client hello packet");
  9421. return -1;
  9422. }
  9423. msgsz = MG_LOAD_BE16(rio->buf + 3);
  9424. mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
  9425. // store client random
  9426. memmove(tls->random, rio->buf + 11, sizeof(tls->random));
  9427. // store session_id
  9428. session_id_len = rio->buf[43];
  9429. if (session_id_len == sizeof(tls->session_id)) {
  9430. memmove(tls->session_id, rio->buf + 44, session_id_len);
  9431. } else if (session_id_len != 0) {
  9432. MG_INFO(("bad session id len"));
  9433. }
  9434. cipher_suites_len = MG_LOAD_BE16(rio->buf + 44 + session_id_len);
  9435. if (cipher_suites_len > (rio->len - 46 - session_id_len)) goto fail;
  9436. ext_len = MG_LOAD_BE16(rio->buf + 48 + session_id_len + cipher_suites_len);
  9437. ext = rio->buf + 50 + session_id_len + cipher_suites_len;
  9438. if (ext_len > (rio->len - 50 - session_id_len - cipher_suites_len)) goto fail;
  9439. for (j = 0; j < ext_len;) {
  9440. uint16_t k;
  9441. uint16_t key_exchange_len;
  9442. uint8_t *key_exchange;
  9443. uint16_t n = MG_LOAD_BE16(ext + j + 2);
  9444. if (ext[j] != 0x00 ||
  9445. ext[j + 1] != 0x33) { // not a key share extension, ignore
  9446. j += (uint16_t) (n + 4);
  9447. continue;
  9448. }
  9449. key_exchange_len = MG_LOAD_BE16(ext + j + 4);
  9450. key_exchange = ext + j + 6;
  9451. if (key_exchange_len >
  9452. rio->len - (uint16_t) ((size_t) key_exchange - (size_t) rio->buf) - 2)
  9453. goto fail;
  9454. for (k = 0; k < key_exchange_len;) {
  9455. uint16_t m = MG_LOAD_BE16(key_exchange + k + 2);
  9456. if (m > (key_exchange_len - k - 4)) goto fail;
  9457. if (m == 32 && key_exchange[k] == 0x00 && key_exchange[k + 1] == 0x1d) {
  9458. memmove(tls->x25519_cli, key_exchange + k + 4, m);
  9459. mg_tls_drop_record(c);
  9460. return 0;
  9461. }
  9462. k += (uint16_t) (m + 4);
  9463. }
  9464. j += (uint16_t) (n + 4);
  9465. }
  9466. fail:
  9467. mg_error(c, "bad client hello");
  9468. return -1;
  9469. }
  9470. #define PLACEHOLDER_8B 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'
  9471. #define PLACEHOLDER_16B PLACEHOLDER_8B, PLACEHOLDER_8B
  9472. #define PLACEHOLDER_32B PLACEHOLDER_16B, PLACEHOLDER_16B
  9473. // put ServerHello record into wio buffer
  9474. static void mg_tls_server_send_hello(struct mg_connection *c) {
  9475. struct tls_data *tls = (struct tls_data *) c->tls;
  9476. struct mg_iobuf *wio = &tls->send;
  9477. // clang-format off
  9478. uint8_t msg_server_hello[122] = {
  9479. // server hello, tls 1.2
  9480. 0x02, 0x00, 0x00, 0x76, 0x03, 0x03,
  9481. // random (32 bytes)
  9482. PLACEHOLDER_32B,
  9483. // session ID length + session ID (32 bytes)
  9484. 0x20, PLACEHOLDER_32B,
  9485. #if defined(CHACHA20) && CHACHA20
  9486. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  9487. 0x13, 0x03, 0x00,
  9488. #else
  9489. // TLS_AES_128_GCM_SHA256 + no compression
  9490. 0x13, 0x01, 0x00,
  9491. #endif
  9492. // extensions + keyshare
  9493. 0x00, 0x2e, 0x00, 0x33, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20,
  9494. // x25519 keyshare
  9495. PLACEHOLDER_32B,
  9496. // supported versions (tls1.3 == 0x304)
  9497. 0x00, 0x2b, 0x00, 0x02, 0x03, 0x04};
  9498. // clang-format on
  9499. // calculate keyshare
  9500. uint8_t x25519_pub[X25519_BYTES];
  9501. uint8_t x25519_prv[X25519_BYTES];
  9502. if (!mg_random(x25519_prv, sizeof(x25519_prv))) mg_error(c, "RNG");
  9503. mg_tls_x25519(x25519_pub, x25519_prv, X25519_BASE_POINT, 1);
  9504. mg_tls_x25519(tls->x25519_sec, x25519_prv, tls->x25519_cli, 1);
  9505. mg_tls_hexdump("s x25519 sec", tls->x25519_sec, sizeof(tls->x25519_sec));
  9506. // fill in the gaps: random + session ID + keyshare
  9507. memmove(msg_server_hello + 6, tls->random, sizeof(tls->random));
  9508. memmove(msg_server_hello + 39, tls->session_id, sizeof(tls->session_id));
  9509. memmove(msg_server_hello + 84, x25519_pub, sizeof(x25519_pub));
  9510. // server hello message
  9511. mg_iobuf_add(wio, wio->len, "\x16\x03\x03\x00\x7a", 5);
  9512. mg_iobuf_add(wio, wio->len, msg_server_hello, sizeof(msg_server_hello));
  9513. mg_sha256_update(&tls->sha256, msg_server_hello, sizeof(msg_server_hello));
  9514. // change cipher message
  9515. mg_iobuf_add(wio, wio->len, "\x14\x03\x03\x00\x01\x01", 6);
  9516. }
  9517. static void mg_tls_server_send_ext(struct mg_connection *c) {
  9518. struct tls_data *tls = (struct tls_data *) c->tls;
  9519. // server extensions
  9520. uint8_t ext[6] = {0x08, 0, 0, 2, 0, 0};
  9521. mg_sha256_update(&tls->sha256, ext, sizeof(ext));
  9522. mg_tls_encrypt(c, ext, sizeof(ext), MG_TLS_HANDSHAKE);
  9523. }
  9524. static void mg_tls_server_send_cert(struct mg_connection *c) {
  9525. struct tls_data *tls = (struct tls_data *) c->tls;
  9526. // server DER certificate (empty)
  9527. size_t n = tls->cert_der.len;
  9528. uint8_t *cert = (uint8_t *) calloc(1, 13 + n);
  9529. if (cert == NULL) {
  9530. mg_error(c, "tls cert oom");
  9531. return;
  9532. }
  9533. cert[0] = 0x0b; // handshake header
  9534. cert[1] = (uint8_t) (((n + 9) >> 16) & 255U); // 3 bytes: payload length
  9535. cert[2] = (uint8_t) (((n + 9) >> 8) & 255U);
  9536. cert[3] = (uint8_t) ((n + 9) & 255U);
  9537. cert[4] = 0; // request context
  9538. cert[5] = (uint8_t) (((n + 5) >> 16) & 255U); // 3 bytes: cert (s) length
  9539. cert[6] = (uint8_t) (((n + 5) >> 8) & 255U);
  9540. cert[7] = (uint8_t) ((n + 5) & 255U);
  9541. cert[8] =
  9542. (uint8_t) (((n) >> 16) & 255U); // 3 bytes: first (and only) cert len
  9543. cert[9] = (uint8_t) (((n) >> 8) & 255U);
  9544. cert[10] = (uint8_t) (n & 255U);
  9545. // bytes 11+ are certificate in DER format
  9546. memmove(cert + 11, tls->cert_der.buf, n);
  9547. cert[11 + n] = cert[12 + n] = 0; // certificate extensions (none)
  9548. mg_sha256_update(&tls->sha256, cert, 13 + n);
  9549. mg_tls_encrypt(c, cert, 13 + n, MG_TLS_HANDSHAKE);
  9550. free(cert);
  9551. }
  9552. // type adapter between uECC hash context and our sha256 implementation
  9553. typedef struct SHA256_HashContext {
  9554. MG_UECC_HashContext uECC;
  9555. mg_sha256_ctx ctx;
  9556. } SHA256_HashContext;
  9557. static void init_SHA256(const MG_UECC_HashContext *base) {
  9558. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9559. mg_sha256_init(&c->ctx);
  9560. }
  9561. static void update_SHA256(const MG_UECC_HashContext *base,
  9562. const uint8_t *message, unsigned message_size) {
  9563. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9564. mg_sha256_update(&c->ctx, message, message_size);
  9565. }
  9566. static void finish_SHA256(const MG_UECC_HashContext *base,
  9567. uint8_t *hash_result) {
  9568. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9569. mg_sha256_final(hash_result, &c->ctx);
  9570. }
  9571. static void mg_tls_send_cert_verify(struct mg_connection *c, int is_client) {
  9572. struct tls_data *tls = (struct tls_data *) c->tls;
  9573. // server certificate verify packet
  9574. uint8_t verify[82] = {0x0f, 0x00, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00};
  9575. size_t sigsz, verifysz = 0;
  9576. uint8_t hash[32] = {0}, tmp[2 * 32 + 64] = {0};
  9577. struct SHA256_HashContext ctx = {
  9578. {&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp},
  9579. {{0}, 0, 0, {0}}};
  9580. int neg1, neg2;
  9581. uint8_t sig[64] = {0};
  9582. mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash, is_client);
  9583. mg_uecc_sign_deterministic(tls->ec_key, hash, sizeof(hash), &ctx.uECC, sig,
  9584. mg_uecc_secp256r1());
  9585. neg1 = !!(sig[0] & 0x80);
  9586. neg2 = !!(sig[32] & 0x80);
  9587. verify[8] = 0x30; // ASN.1 SEQUENCE
  9588. verify[9] = (uint8_t) (68 + neg1 + neg2);
  9589. verify[10] = 0x02; // ASN.1 INTEGER
  9590. verify[11] = (uint8_t) (32 + neg1);
  9591. memmove(verify + 12 + neg1, sig, 32);
  9592. verify[12 + 32 + neg1] = 0x02; // ASN.1 INTEGER
  9593. verify[13 + 32 + neg1] = (uint8_t) (32 + neg2);
  9594. memmove(verify + 14 + 32 + neg1 + neg2, sig + 32, 32);
  9595. sigsz = (size_t) (70 + neg1 + neg2);
  9596. verifysz = 8U + sigsz;
  9597. verify[3] = (uint8_t) (sigsz + 4);
  9598. verify[7] = (uint8_t) sigsz;
  9599. mg_sha256_update(&tls->sha256, verify, verifysz);
  9600. mg_tls_encrypt(c, verify, verifysz, MG_TLS_HANDSHAKE);
  9601. }
  9602. static void mg_tls_server_send_finish(struct mg_connection *c) {
  9603. struct tls_data *tls = (struct tls_data *) c->tls;
  9604. struct mg_iobuf *wio = &tls->send;
  9605. mg_sha256_ctx sha256;
  9606. uint8_t hash[32];
  9607. uint8_t finish[36] = {0x14, 0, 0, 32};
  9608. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9609. mg_sha256_final(hash, &sha256);
  9610. mg_hmac_sha256(finish + 4, tls->enc.server_finished_key, 32, hash, 32);
  9611. mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
  9612. mg_io_send(c, wio->buf, wio->len);
  9613. wio->len = 0;
  9614. mg_sha256_update(&tls->sha256, finish, sizeof(finish));
  9615. }
  9616. static int mg_tls_server_recv_finish(struct mg_connection *c) {
  9617. struct tls_data *tls = (struct tls_data *) c->tls;
  9618. unsigned char *recv_buf;
  9619. // we have to backup sha256 value to restore it later, since Finished record
  9620. // is exceptional and is not supposed to be added to the rolling hash
  9621. // calculation.
  9622. mg_sha256_ctx sha256 = tls->sha256;
  9623. if (mg_tls_recv_record(c) < 0) {
  9624. return -1;
  9625. }
  9626. recv_buf = &c->rtls.buf[tls->recv_offset];
  9627. if (recv_buf[0] != MG_TLS_FINISHED) {
  9628. mg_error(c, "expected Finish but got msg 0x%02x", recv_buf[0]);
  9629. return -1;
  9630. }
  9631. mg_tls_drop_message(c);
  9632. // restore hash
  9633. tls->sha256 = sha256;
  9634. return 0;
  9635. }
  9636. static void mg_tls_client_send_hello(struct mg_connection *c) {
  9637. struct tls_data *tls = (struct tls_data *) c->tls;
  9638. struct mg_iobuf *wio = &tls->send;
  9639. uint8_t x25519_pub[X25519_BYTES];
  9640. // the only signature algorithm we actually support
  9641. uint8_t secp256r1_sig_algs[8] = {
  9642. 0x00, 0x0d, 0x00, 0x04, 0x00, 0x02, 0x04, 0x03,
  9643. };
  9644. // all popular signature algorithms (if we don't care about verification)
  9645. uint8_t all_sig_algs[34] = {
  9646. 0x00, 0x0d, 0x00, 0x1e, 0x00, 0x1c, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03,
  9647. 0x08, 0x07, 0x08, 0x08, 0x08, 0x09, 0x08, 0x0a, 0x08, 0x0b, 0x08, 0x04,
  9648. 0x08, 0x05, 0x08, 0x06, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01};
  9649. uint8_t server_name_ext[9] = {0x00, 0x00, 0x00, 0xfe, 0x00,
  9650. 0xfe, 0x00, 0x00, 0xfe};
  9651. // clang-format off
  9652. uint8_t msg_client_hello[145] = {
  9653. // TLS Client Hello header reported as TLS1.2 (5)
  9654. 0x16, 0x03, 0x03, 0x00, 0xfe,
  9655. // client hello, tls 1.2 (6)
  9656. 0x01, 0x00, 0x00, 0x8c, 0x03, 0x03,
  9657. // random (32 bytes)
  9658. PLACEHOLDER_32B,
  9659. // session ID length + session ID (32 bytes)
  9660. 0x20, PLACEHOLDER_32B, 0x00,
  9661. 0x02, // size = 2 bytes
  9662. #if defined(CHACHA20) && CHACHA20
  9663. // TLS_CHACHA20_POLY1305_SHA256
  9664. 0x13, 0x03,
  9665. #else
  9666. // TLS_AES_128_GCM_SHA256
  9667. 0x13, 0x01,
  9668. #endif
  9669. // no compression
  9670. 0x01, 0x00,
  9671. // extensions + keyshare
  9672. 0x00, 0xfe,
  9673. // x25519 keyshare
  9674. 0x00, 0x33, 0x00, 0x26, 0x00, 0x24, 0x00, 0x1d, 0x00, 0x20,
  9675. PLACEHOLDER_32B,
  9676. // supported groups (x25519)
  9677. 0x00, 0x0a, 0x00, 0x04, 0x00, 0x02, 0x00, 0x1d,
  9678. // supported versions (tls1.3 == 0x304)
  9679. 0x00, 0x2b, 0x00, 0x03, 0x02, 0x03, 0x04,
  9680. // session ticket (none)
  9681. 0x00, 0x23, 0x00, 0x00, // 144 bytes till here
  9682. };
  9683. // clang-format on
  9684. const char *hostname = tls->hostname;
  9685. size_t hostnamesz = strlen(tls->hostname);
  9686. size_t hostname_extsz = hostnamesz ? hostnamesz + 9 : 0;
  9687. uint8_t *sig_alg = tls->skip_verification ? all_sig_algs : secp256r1_sig_algs;
  9688. size_t sig_alg_sz = tls->skip_verification ? sizeof(all_sig_algs)
  9689. : sizeof(secp256r1_sig_algs);
  9690. // patch ClientHello with correct hostname ext length (if any)
  9691. MG_STORE_BE16(msg_client_hello + 3,
  9692. hostname_extsz + 183 - 9 - 34 + sig_alg_sz);
  9693. MG_STORE_BE16(msg_client_hello + 7,
  9694. hostname_extsz + 179 - 9 - 34 + sig_alg_sz);
  9695. MG_STORE_BE16(msg_client_hello + 82,
  9696. hostname_extsz + 104 - 9 - 34 + sig_alg_sz);
  9697. if (hostnamesz > 0) {
  9698. MG_STORE_BE16(server_name_ext + 2, hostnamesz + 5);
  9699. MG_STORE_BE16(server_name_ext + 4, hostnamesz + 3);
  9700. MG_STORE_BE16(server_name_ext + 7, hostnamesz);
  9701. }
  9702. // calculate keyshare
  9703. if (!mg_random(tls->x25519_cli, sizeof(tls->x25519_cli))) mg_error(c, "RNG");
  9704. mg_tls_x25519(x25519_pub, tls->x25519_cli, X25519_BASE_POINT, 1);
  9705. // fill in the gaps: random + session ID + keyshare
  9706. if (!mg_random(tls->session_id, sizeof(tls->session_id))) mg_error(c, "RNG");
  9707. if (!mg_random(tls->random, sizeof(tls->random))) mg_error(c, "RNG");
  9708. memmove(msg_client_hello + 11, tls->random, sizeof(tls->random));
  9709. memmove(msg_client_hello + 44, tls->session_id, sizeof(tls->session_id));
  9710. memmove(msg_client_hello + 94, x25519_pub, sizeof(x25519_pub));
  9711. // client hello message
  9712. mg_iobuf_add(wio, wio->len, msg_client_hello, sizeof(msg_client_hello));
  9713. mg_sha256_update(&tls->sha256, msg_client_hello + 5,
  9714. sizeof(msg_client_hello) - 5);
  9715. mg_iobuf_add(wio, wio->len, sig_alg, sig_alg_sz);
  9716. mg_sha256_update(&tls->sha256, sig_alg, sig_alg_sz);
  9717. if (hostnamesz > 0) {
  9718. mg_iobuf_add(wio, wio->len, server_name_ext, sizeof(server_name_ext));
  9719. mg_iobuf_add(wio, wio->len, hostname, hostnamesz);
  9720. mg_sha256_update(&tls->sha256, server_name_ext, sizeof(server_name_ext));
  9721. mg_sha256_update(&tls->sha256, (uint8_t *) hostname, hostnamesz);
  9722. }
  9723. // change cipher message
  9724. mg_iobuf_add(wio, wio->len, (const char *) "\x14\x03\x03\x00\x01\x01", 6);
  9725. mg_io_send(c, wio->buf, wio->len);
  9726. wio->len = 0;
  9727. }
  9728. static int mg_tls_client_recv_hello(struct mg_connection *c) {
  9729. struct tls_data *tls = (struct tls_data *) c->tls;
  9730. struct mg_iobuf *rio = &c->rtls;
  9731. uint16_t msgsz;
  9732. uint8_t *ext;
  9733. uint16_t ext_len;
  9734. int j;
  9735. if (!mg_tls_got_record(c)) {
  9736. return MG_IO_WAIT;
  9737. }
  9738. if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_SERVER_HELLO) {
  9739. if (rio->buf[0] == MG_TLS_ALERT && rio->len >= 7) {
  9740. mg_error(c, "tls alert %d", rio->buf[6]);
  9741. return -1;
  9742. }
  9743. MG_INFO(("got packet type 0x%02x/0x%02x", rio->buf[0], rio->buf[5]));
  9744. mg_error(c, "not a server hello packet");
  9745. return -1;
  9746. }
  9747. msgsz = MG_LOAD_BE16(rio->buf + 3);
  9748. mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
  9749. ext_len = MG_LOAD_BE16(rio->buf + 5 + 39 + 32 + 3);
  9750. ext = rio->buf + 5 + 39 + 32 + 3 + 2;
  9751. if (ext_len > (rio->len - (5 + 39 + 32 + 3 + 2))) goto fail;
  9752. for (j = 0; j < ext_len;) {
  9753. uint16_t ext_type = MG_LOAD_BE16(ext + j);
  9754. uint16_t ext_len2 = MG_LOAD_BE16(ext + j + 2);
  9755. uint16_t group;
  9756. uint8_t *key_exchange;
  9757. uint16_t key_exchange_len;
  9758. if (ext_len2 > (ext_len - j - 4)) goto fail;
  9759. if (ext_type != 0x0033) { // not a key share extension, ignore
  9760. j += (uint16_t) (ext_len2 + 4);
  9761. continue;
  9762. }
  9763. group = MG_LOAD_BE16(ext + j + 4);
  9764. if (group != 0x001d) {
  9765. mg_error(c, "bad key exchange group");
  9766. return -1;
  9767. }
  9768. key_exchange_len = MG_LOAD_BE16(ext + j + 6);
  9769. key_exchange = ext + j + 8;
  9770. if (key_exchange_len != 32) {
  9771. mg_error(c, "bad key exchange length");
  9772. return -1;
  9773. }
  9774. mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1);
  9775. mg_tls_hexdump("c x25519 sec", tls->x25519_sec, 32);
  9776. mg_tls_drop_record(c);
  9777. /* generate handshake keys */
  9778. mg_tls_generate_handshake_keys(c);
  9779. return 0;
  9780. }
  9781. fail:
  9782. mg_error(c, "bad client hello");
  9783. return -1;
  9784. }
  9785. static int mg_tls_client_recv_ext(struct mg_connection *c) {
  9786. struct tls_data *tls = (struct tls_data *) c->tls;
  9787. unsigned char *recv_buf;
  9788. if (mg_tls_recv_record(c) < 0) {
  9789. return -1;
  9790. }
  9791. recv_buf = &c->rtls.buf[tls->recv_offset];
  9792. if (recv_buf[0] != MG_TLS_ENCRYPTED_EXTENSIONS) {
  9793. mg_error(c, "expected server extensions but got msg 0x%02x", recv_buf[0]);
  9794. return -1;
  9795. }
  9796. mg_tls_drop_message(c);
  9797. return 0;
  9798. }
  9799. static int mg_tls_client_recv_cert(struct mg_connection *c) {
  9800. uint8_t *cert;
  9801. uint32_t certsz;
  9802. struct mg_der_tlv oid, pubkey, seq, subj;
  9803. int subj_match = 0;
  9804. struct tls_data *tls = (struct tls_data *) c->tls;
  9805. unsigned char *recv_buf;
  9806. if (mg_tls_recv_record(c) < 0) {
  9807. return -1;
  9808. }
  9809. recv_buf = &c->rtls.buf[tls->recv_offset];
  9810. if (recv_buf[0] == MG_TLS_CERTIFICATE_REQUEST) {
  9811. MG_VERBOSE(("got certificate request"));
  9812. mg_tls_drop_message(c);
  9813. tls->cert_requested = 1;
  9814. return -1;
  9815. }
  9816. if (recv_buf[0] != MG_TLS_CERTIFICATE) {
  9817. mg_error(c, "expected server certificate but got msg 0x%02x", recv_buf[0]);
  9818. return -1;
  9819. }
  9820. if (tls->skip_verification) {
  9821. mg_tls_drop_message(c);
  9822. return 0;
  9823. }
  9824. if (tls->recv_len < 11) {
  9825. mg_error(c, "certificate list too short");
  9826. return -1;
  9827. }
  9828. cert = recv_buf + 11;
  9829. certsz = MG_LOAD_BE24(recv_buf + 8);
  9830. if (certsz > tls->recv_len - 11) {
  9831. mg_error(c, "certificate too long: %d vs %d", certsz, tls->recv_len - 11);
  9832. return -1;
  9833. }
  9834. do {
  9835. // secp256r1 public key
  9836. if (mg_der_find(cert, certsz,
  9837. (uint8_t *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8,
  9838. &oid) < 0) {
  9839. mg_error(c, "certificate secp256r1 public key OID not found");
  9840. return -1;
  9841. }
  9842. if (mg_der_to_tlv(oid.value + oid.len,
  9843. (size_t) (cert + certsz - (oid.value + oid.len)),
  9844. &pubkey) < 0) {
  9845. mg_error(c, "certificate secp256r1 public key not found");
  9846. return -1;
  9847. }
  9848. // expect BIT STRING, unpadded, uncompressed: [0]+[4]+32+32 content bytes
  9849. if (pubkey.type != 3 || pubkey.len != 66 || pubkey.value[0] != 0 ||
  9850. pubkey.value[1] != 4) {
  9851. mg_error(c, "unsupported public key bitstring encoding");
  9852. return -1;
  9853. }
  9854. memmove(tls->pubkey, pubkey.value + 2, pubkey.len - 2);
  9855. } while (0);
  9856. // Subject Alternative Names
  9857. do {
  9858. if (mg_der_find(cert, certsz, (uint8_t *) "\x55\x1d\x11", 3, &oid) < 0) {
  9859. mg_error(c, "certificate does not contain subject alternative names");
  9860. return -1;
  9861. }
  9862. if (mg_der_to_tlv(oid.value + oid.len,
  9863. (size_t) (cert + certsz - (oid.value + oid.len)),
  9864. &seq) < 0) {
  9865. mg_error(c, "certificate subject alternative names not found");
  9866. return -1;
  9867. }
  9868. if (mg_der_to_tlv(seq.value, seq.len, &seq) < 0) {
  9869. mg_error(
  9870. c,
  9871. "certificate subject alternative names is not a constructed object");
  9872. return -1;
  9873. }
  9874. MG_VERBOSE(("verify hostname %s", tls->hostname));
  9875. while (seq.len > 0) {
  9876. if (mg_der_to_tlv(seq.value, seq.len, &subj) < 0) {
  9877. mg_error(c, "bad subject alternative name");
  9878. return -1;
  9879. }
  9880. MG_VERBOSE(("subj=%.*s", subj.len, subj.value));
  9881. if (mg_match(mg_str((const char *) tls->hostname),
  9882. mg_str_n((const char *) subj.value, subj.len), NULL)) {
  9883. subj_match = 1;
  9884. break;
  9885. }
  9886. seq.len = (uint32_t) (seq.value + seq.len - (subj.value + subj.len));
  9887. seq.value = subj.value + subj.len;
  9888. }
  9889. if (!subj_match) {
  9890. mg_error(c, "certificate did not match the hostname");
  9891. return -1;
  9892. }
  9893. } while (0);
  9894. mg_tls_drop_message(c);
  9895. mg_tls_calc_cert_verify_hash(c, tls->sighash, 0);
  9896. return 0;
  9897. }
  9898. static int mg_tls_client_recv_cert_verify(struct mg_connection *c) {
  9899. struct tls_data *tls = (struct tls_data *) c->tls;
  9900. unsigned char *recv_buf;
  9901. if (mg_tls_recv_record(c) < 0) {
  9902. return -1;
  9903. }
  9904. recv_buf = &c->rtls.buf[tls->recv_offset];
  9905. if (recv_buf[0] != MG_TLS_CERTIFICATE_VERIFY) {
  9906. mg_error(c, "expected server certificate verify but got msg 0x%02x", recv_buf[0]);
  9907. return -1;
  9908. }
  9909. // Ignore CertificateVerify is strict checks are not required
  9910. if (tls->skip_verification) {
  9911. mg_tls_drop_message(c);
  9912. return 0;
  9913. }
  9914. // Extract certificate signature and verify it using pubkey and sighash
  9915. do {
  9916. uint8_t sig[64];
  9917. struct mg_der_tlv seq, a, b;
  9918. if (mg_der_to_tlv(recv_buf + 8, tls->recv_len - 8, &seq) < 0) {
  9919. mg_error(c, "verification message is not an ASN.1 DER sequence");
  9920. return -1;
  9921. }
  9922. if (mg_der_to_tlv(seq.value, seq.len, &a) < 0) {
  9923. mg_error(c, "missing first part of the signature");
  9924. return -1;
  9925. }
  9926. if (mg_der_to_tlv(a.value + a.len, seq.len - a.len, &b) < 0) {
  9927. mg_error(c, "missing second part of the signature");
  9928. return -1;
  9929. }
  9930. // Integers may be padded with zeroes
  9931. if (a.len > 32) {
  9932. a.value = a.value + (a.len - 32);
  9933. a.len = 32;
  9934. }
  9935. if (b.len > 32) {
  9936. b.value = b.value + (b.len - 32);
  9937. b.len = 32;
  9938. }
  9939. memmove(sig, a.value, a.len);
  9940. memmove(sig + 32, b.value, b.len);
  9941. if (mg_uecc_verify(tls->pubkey, tls->sighash, sizeof(tls->sighash), sig,
  9942. mg_uecc_secp256r1()) != 1) {
  9943. mg_error(c, "failed to verify certificate");
  9944. return -1;
  9945. }
  9946. } while (0);
  9947. mg_tls_drop_message(c);
  9948. return 0;
  9949. }
  9950. static int mg_tls_client_recv_finish(struct mg_connection *c) {
  9951. struct tls_data *tls = (struct tls_data *) c->tls;
  9952. unsigned char *recv_buf;
  9953. if (mg_tls_recv_record(c) < 0) {
  9954. return -1;
  9955. }
  9956. recv_buf = &c->rtls.buf[tls->recv_offset];
  9957. if (recv_buf[0] != MG_TLS_FINISHED) {
  9958. mg_error(c, "expected server finished but got msg 0x%02x", recv_buf[0]);
  9959. return -1;
  9960. }
  9961. mg_tls_drop_message(c);
  9962. return 0;
  9963. }
  9964. static void mg_tls_client_send_finish(struct mg_connection *c) {
  9965. struct tls_data *tls = (struct tls_data *) c->tls;
  9966. struct mg_iobuf *wio = &tls->send;
  9967. mg_sha256_ctx sha256;
  9968. uint8_t hash[32];
  9969. uint8_t finish[36] = {0x14, 0, 0, 32};
  9970. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9971. mg_sha256_final(hash, &sha256);
  9972. mg_hmac_sha256(finish + 4, tls->enc.client_finished_key, 32, hash, 32);
  9973. mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
  9974. mg_io_send(c, wio->buf, wio->len);
  9975. wio->len = 0;
  9976. }
  9977. static void mg_tls_client_handshake(struct mg_connection *c) {
  9978. struct tls_data *tls = (struct tls_data *) c->tls;
  9979. switch (tls->state) {
  9980. case MG_TLS_STATE_CLIENT_START:
  9981. mg_tls_client_send_hello(c);
  9982. tls->state = MG_TLS_STATE_CLIENT_WAIT_SH;
  9983. // Fallthrough
  9984. case MG_TLS_STATE_CLIENT_WAIT_SH:
  9985. if (mg_tls_client_recv_hello(c) < 0) {
  9986. break;
  9987. }
  9988. tls->state = MG_TLS_STATE_CLIENT_WAIT_EE;
  9989. // Fallthrough
  9990. case MG_TLS_STATE_CLIENT_WAIT_EE:
  9991. if (mg_tls_client_recv_ext(c) < 0) {
  9992. break;
  9993. }
  9994. tls->state = MG_TLS_STATE_CLIENT_WAIT_CERT;
  9995. // Fallthrough
  9996. case MG_TLS_STATE_CLIENT_WAIT_CERT:
  9997. if (mg_tls_client_recv_cert(c) < 0) {
  9998. break;
  9999. }
  10000. tls->state = MG_TLS_STATE_CLIENT_WAIT_CV;
  10001. // Fallthrough
  10002. case MG_TLS_STATE_CLIENT_WAIT_CV:
  10003. if (mg_tls_client_recv_cert_verify(c) < 0) {
  10004. break;
  10005. }
  10006. tls->state = MG_TLS_STATE_CLIENT_WAIT_FINISHED;
  10007. // Fallthrough
  10008. case MG_TLS_STATE_CLIENT_WAIT_FINISHED:
  10009. if (mg_tls_client_recv_finish(c) < 0) {
  10010. break;
  10011. }
  10012. if (tls->cert_requested) {
  10013. /* for mTLS we should generate application keys at this point
  10014. * but then restore handshake keys and continue with
  10015. * the rest of the handshake */
  10016. struct tls_enc app_keys;
  10017. struct tls_enc hs_keys = tls->enc;
  10018. mg_tls_generate_application_keys(c);
  10019. app_keys = tls->enc;
  10020. tls->enc = hs_keys;
  10021. mg_tls_server_send_cert(c);
  10022. mg_tls_send_cert_verify(c, 1);
  10023. mg_tls_client_send_finish(c);
  10024. tls->enc = app_keys;
  10025. } else {
  10026. mg_tls_client_send_finish(c);
  10027. mg_tls_generate_application_keys(c);
  10028. }
  10029. tls->state = MG_TLS_STATE_CLIENT_CONNECTED;
  10030. c->is_tls_hs = 0;
  10031. break;
  10032. default:
  10033. mg_error(c, "unexpected client state: %d", tls->state);
  10034. break;
  10035. }
  10036. }
  10037. static void mg_tls_server_handshake(struct mg_connection *c) {
  10038. struct tls_data *tls = (struct tls_data *) c->tls;
  10039. switch (tls->state) {
  10040. case MG_TLS_STATE_SERVER_START:
  10041. if (mg_tls_server_recv_hello(c) < 0) {
  10042. return;
  10043. }
  10044. mg_tls_server_send_hello(c);
  10045. mg_tls_generate_handshake_keys(c);
  10046. mg_tls_server_send_ext(c);
  10047. mg_tls_server_send_cert(c);
  10048. mg_tls_send_cert_verify(c, 0);
  10049. mg_tls_server_send_finish(c);
  10050. tls->state = MG_TLS_STATE_SERVER_NEGOTIATED;
  10051. // fallthrough
  10052. case MG_TLS_STATE_SERVER_NEGOTIATED:
  10053. if (mg_tls_server_recv_finish(c) < 0) {
  10054. return;
  10055. }
  10056. mg_tls_generate_application_keys(c);
  10057. tls->state = MG_TLS_STATE_SERVER_CONNECTED;
  10058. c->is_tls_hs = 0;
  10059. return;
  10060. default:
  10061. mg_error(c, "unexpected server state: %d", tls->state);
  10062. break;
  10063. }
  10064. }
  10065. void mg_tls_handshake(struct mg_connection *c) {
  10066. if (c->is_client) {
  10067. mg_tls_client_handshake(c);
  10068. } else {
  10069. mg_tls_server_handshake(c);
  10070. }
  10071. }
  10072. static int mg_parse_pem(const struct mg_str pem, const struct mg_str label,
  10073. struct mg_str *der) {
  10074. size_t n = 0, m = 0;
  10075. char *s;
  10076. const char *c;
  10077. struct mg_str caps[6]; // number of wildcards + 1
  10078. if (!mg_match(pem, mg_str("#-----BEGIN #-----#-----END #-----#"), caps)) {
  10079. *der = mg_strdup(pem);
  10080. return 0;
  10081. }
  10082. if (mg_strcmp(caps[1], label) != 0 || mg_strcmp(caps[3], label) != 0) {
  10083. return -1; // bad label
  10084. }
  10085. if ((s = (char *) calloc(1, caps[2].len)) == NULL) {
  10086. return -1;
  10087. }
  10088. for (c = caps[2].buf; c < caps[2].buf + caps[2].len; c++) {
  10089. if (*c == ' ' || *c == '\n' || *c == '\r' || *c == '\t') {
  10090. continue;
  10091. }
  10092. s[n++] = *c;
  10093. }
  10094. m = mg_base64_decode(s, n, s, n);
  10095. if (m == 0) {
  10096. free(s);
  10097. return -1;
  10098. }
  10099. der->buf = s;
  10100. der->len = m;
  10101. return 0;
  10102. }
  10103. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  10104. struct mg_str key;
  10105. struct tls_data *tls = (struct tls_data *) calloc(1, sizeof(struct tls_data));
  10106. if (tls == NULL) {
  10107. mg_error(c, "tls oom");
  10108. return;
  10109. }
  10110. tls->state =
  10111. c->is_client ? MG_TLS_STATE_CLIENT_START : MG_TLS_STATE_SERVER_START;
  10112. tls->skip_verification = opts->skip_verification;
  10113. //tls->send.align = MG_IO_SIZE;
  10114. c->tls = tls;
  10115. c->is_tls = c->is_tls_hs = 1;
  10116. mg_sha256_init(&tls->sha256);
  10117. // save hostname (client extension)
  10118. if (opts->name.len > 0) {
  10119. if (opts->name.len >= sizeof(tls->hostname) - 1) {
  10120. mg_error(c, "hostname too long");
  10121. return;
  10122. }
  10123. strncpy((char *) tls->hostname, opts->name.buf, sizeof(tls->hostname) - 1);
  10124. tls->hostname[opts->name.len] = 0;
  10125. }
  10126. if (opts->cert.buf == NULL) {
  10127. MG_VERBOSE(("no certificate provided"));
  10128. return;
  10129. }
  10130. // parse PEM or DER certificate
  10131. if (mg_parse_pem(opts->cert, mg_str_s("CERTIFICATE"), &tls->cert_der) < 0) {
  10132. MG_ERROR(("Failed to load certificate"));
  10133. return;
  10134. }
  10135. // parse PEM or DER EC key
  10136. if (opts->key.buf == NULL) {
  10137. mg_error(c, "certificate provided without a private key");
  10138. return;
  10139. }
  10140. if (mg_parse_pem(opts->key, mg_str_s("EC PRIVATE KEY"), &key) == 0) {
  10141. if (key.len < 39) {
  10142. MG_ERROR(("EC private key too short"));
  10143. return;
  10144. }
  10145. // expect ASN.1 SEQUENCE=[INTEGER=1, BITSTRING of 32 bytes, ...]
  10146. // 30 nn 02 01 01 04 20 [key] ...
  10147. if (key.buf[0] != 0x30 || (key.buf[1] & 0x80) != 0) {
  10148. MG_ERROR(("EC private key: ASN.1 bad sequence"));
  10149. return;
  10150. }
  10151. if (memcmp(key.buf + 2, "\x02\x01\x01\x04\x20", 5) != 0) {
  10152. MG_ERROR(("EC private key: ASN.1 bad data"));
  10153. }
  10154. memmove(tls->ec_key, key.buf + 7, 32);
  10155. free((void *) key.buf);
  10156. } else if (mg_parse_pem(opts->key, mg_str_s("PRIVATE KEY"), &key) == 0) {
  10157. mg_error(c, "PKCS8 private key format is not supported");
  10158. } else {
  10159. mg_error(c, "expected EC PRIVATE KEY or PRIVATE KEY");
  10160. }
  10161. }
  10162. void mg_tls_free(struct mg_connection *c) {
  10163. struct tls_data *tls = (struct tls_data *) c->tls;
  10164. if (tls != NULL) {
  10165. mg_iobuf_free(&tls->send);
  10166. free((void *) tls->cert_der.buf);
  10167. }
  10168. free(c->tls);
  10169. c->tls = NULL;
  10170. }
  10171. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  10172. struct tls_data *tls = (struct tls_data *) c->tls;
  10173. long n = MG_IO_WAIT;
  10174. if (len > MG_IO_SIZE) len = MG_IO_SIZE;
  10175. if (len > 16384) len = 16384;
  10176. mg_tls_encrypt(c, (const uint8_t *) buf, len, MG_TLS_APP_DATA);
  10177. while (tls->send.len > 0 &&
  10178. (n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {
  10179. mg_iobuf_del(&tls->send, 0, (size_t) n);
  10180. }
  10181. if (n == MG_IO_ERR || n == MG_IO_WAIT) return n;
  10182. return (long) len;
  10183. }
  10184. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  10185. int r = 0;
  10186. struct tls_data *tls = (struct tls_data *) c->tls;
  10187. unsigned char *recv_buf;
  10188. size_t minlen;
  10189. r = mg_tls_recv_record(c);
  10190. if (r < 0) {
  10191. return r;
  10192. }
  10193. recv_buf = &c->rtls.buf[tls->recv_offset];
  10194. if (tls->content_type != MG_TLS_APP_DATA) {
  10195. tls->recv_len = 0;
  10196. mg_tls_drop_record(c);
  10197. return MG_IO_WAIT;
  10198. }
  10199. minlen = len < tls->recv_len ? len : tls->recv_len;
  10200. memmove(buf, recv_buf, minlen);
  10201. tls->recv_offset += minlen;
  10202. tls->recv_len -= minlen;
  10203. if (tls->recv_len == 0) {
  10204. mg_tls_drop_record(c);
  10205. }
  10206. return (long) minlen;
  10207. }
  10208. size_t mg_tls_pending(struct mg_connection *c) {
  10209. struct tls_data *tls = (struct tls_data *) c->tls;
  10210. return tls != NULL ? tls->recv_len : 0;
  10211. }
  10212. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  10213. (void) mgr;
  10214. }
  10215. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  10216. (void) mgr;
  10217. }
  10218. #endif
  10219. #ifdef MG_ENABLE_LINES
  10220. #line 1 "src/tls_chacha20.c"
  10221. #endif
  10222. // portable8439 v1.0.1
  10223. // Source: https://github.com/DavyLandman/portable8439
  10224. // Licensed under CC0-1.0
  10225. // Contains poly1305-donna e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781 (Public
  10226. // Domain)
  10227. #if MG_TLS == MG_TLS_BUILTIN
  10228. // ******* BEGIN: chacha-portable/chacha-portable.h ********
  10229. #if !defined(__cplusplus) && !defined(_MSC_VER) && \
  10230. (!defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L)
  10231. #error "C99 or newer required"
  10232. #endif
  10233. #define CHACHA20_KEY_SIZE (32)
  10234. #define CHACHA20_NONCE_SIZE (12)
  10235. #if defined(_MSC_VER) || defined(__cplusplus)
  10236. // add restrict support
  10237. #if (defined(_MSC_VER) && _MSC_VER >= 1900) || defined(__clang__) || \
  10238. defined(__GNUC__)
  10239. #define restrict __restrict
  10240. #else
  10241. #define restrict
  10242. #endif
  10243. #endif
  10244. // xor data with a ChaCha20 keystream as per RFC8439
  10245. static PORTABLE_8439_DECL void chacha20_xor_stream(
  10246. uint8_t *restrict dest, const uint8_t *restrict source, size_t length,
  10247. const uint8_t key[CHACHA20_KEY_SIZE],
  10248. const uint8_t nonce[CHACHA20_NONCE_SIZE], uint32_t counter);
  10249. static PORTABLE_8439_DECL void rfc8439_keygen(
  10250. uint8_t poly_key[32], const uint8_t key[CHACHA20_KEY_SIZE],
  10251. const uint8_t nonce[CHACHA20_NONCE_SIZE]);
  10252. // ******* END: chacha-portable/chacha-portable.h ********
  10253. // ******* BEGIN: poly1305-donna/poly1305-donna.h ********
  10254. #include <stddef.h>
  10255. typedef struct poly1305_context {
  10256. size_t aligner;
  10257. unsigned char opaque[136];
  10258. } poly1305_context;
  10259. static PORTABLE_8439_DECL void poly1305_init(poly1305_context *ctx,
  10260. const unsigned char key[32]);
  10261. static PORTABLE_8439_DECL void poly1305_update(poly1305_context *ctx,
  10262. const unsigned char *m,
  10263. size_t bytes);
  10264. static PORTABLE_8439_DECL void poly1305_finish(poly1305_context *ctx,
  10265. unsigned char mac[16]);
  10266. // ******* END: poly1305-donna/poly1305-donna.h ********
  10267. // ******* BEGIN: chacha-portable.c ********
  10268. #include <assert.h>
  10269. #include <string.h>
  10270. // this is a fresh implementation of chacha20, based on the description in
  10271. // rfc8349 it's such a nice compact algorithm that it is easy to do. In
  10272. // relationship to other c implementation this implementation:
  10273. // - pure c99
  10274. // - big & little endian support
  10275. // - safe for architectures that don't support unaligned reads
  10276. //
  10277. // Next to this, we try to be fast as possible without resorting inline
  10278. // assembly.
  10279. // based on https://sourceforge.net/p/predef/wiki/Endianness/
  10280. #if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \
  10281. __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  10282. #define __HAVE_LITTLE_ENDIAN 1
  10283. #elif defined(__LITTLE_ENDIAN__) || defined(__ARMEL__) || \
  10284. defined(__THUMBEL__) || defined(__AARCH64EL__) || defined(_MIPSEL) || \
  10285. defined(__MIPSEL) || defined(__MIPSEL__) || defined(__XTENSA_EL__) || \
  10286. defined(__AVR__) || defined(LITTLE_ENDIAN)
  10287. #define __HAVE_LITTLE_ENDIAN 1
  10288. #endif
  10289. #ifndef TEST_SLOW_PATH
  10290. #if defined(__HAVE_LITTLE_ENDIAN)
  10291. #define FAST_PATH
  10292. #endif
  10293. #endif
  10294. #define CHACHA20_STATE_WORDS (16)
  10295. #define CHACHA20_BLOCK_SIZE (CHACHA20_STATE_WORDS * sizeof(uint32_t))
  10296. #ifdef FAST_PATH
  10297. #define store_32_le(target, source) memcpy(&(target), source, sizeof(uint32_t))
  10298. #else
  10299. #define store_32_le(target, source) \
  10300. target = (uint32_t) (source)[0] | ((uint32_t) (source)[1]) << 8 | \
  10301. ((uint32_t) (source)[2]) << 16 | ((uint32_t) (source)[3]) << 24
  10302. #endif
  10303. static void initialize_state(uint32_t state[CHACHA20_STATE_WORDS],
  10304. const uint8_t key[CHACHA20_KEY_SIZE],
  10305. const uint8_t nonce[CHACHA20_NONCE_SIZE],
  10306. uint32_t counter) {
  10307. #ifdef static_assert
  10308. static_assert(sizeof(uint32_t) == 4,
  10309. "We don't support systems that do not conform to standard of "
  10310. "uint32_t being exact 32bit wide");
  10311. #endif
  10312. state[0] = 0x61707865;
  10313. state[1] = 0x3320646e;
  10314. state[2] = 0x79622d32;
  10315. state[3] = 0x6b206574;
  10316. store_32_le(state[4], key);
  10317. store_32_le(state[5], key + 4);
  10318. store_32_le(state[6], key + 8);
  10319. store_32_le(state[7], key + 12);
  10320. store_32_le(state[8], key + 16);
  10321. store_32_le(state[9], key + 20);
  10322. store_32_le(state[10], key + 24);
  10323. store_32_le(state[11], key + 28);
  10324. state[12] = counter;
  10325. store_32_le(state[13], nonce);
  10326. store_32_le(state[14], nonce + 4);
  10327. store_32_le(state[15], nonce + 8);
  10328. }
  10329. #define increment_counter(state) (state)[12]++
  10330. // source: http://blog.regehr.org/archives/1063
  10331. #define rotl32a(x, n) ((x) << (n)) | ((x) >> (32 - (n)))
  10332. #define Qround(a, b, c, d) \
  10333. a += b; \
  10334. d ^= a; \
  10335. d = rotl32a(d, 16); \
  10336. c += d; \
  10337. b ^= c; \
  10338. b = rotl32a(b, 12); \
  10339. a += b; \
  10340. d ^= a; \
  10341. d = rotl32a(d, 8); \
  10342. c += d; \
  10343. b ^= c; \
  10344. b = rotl32a(b, 7);
  10345. #define TIMES16(x) \
  10346. x(0) x(1) x(2) x(3) x(4) x(5) x(6) x(7) x(8) x(9) x(10) x(11) x(12) x(13) \
  10347. x(14) x(15)
  10348. static void core_block(const uint32_t *restrict start,
  10349. uint32_t *restrict output) {
  10350. int i;
  10351. // instead of working on the output array,
  10352. // we let the compiler allocate 16 local variables on the stack
  10353. #define __LV(i) uint32_t __t##i = start[i];
  10354. TIMES16(__LV)
  10355. #define __Q(a, b, c, d) Qround(__t##a, __t##b, __t##c, __t##d)
  10356. for (i = 0; i < 10; i++) {
  10357. __Q(0, 4, 8, 12);
  10358. __Q(1, 5, 9, 13);
  10359. __Q(2, 6, 10, 14);
  10360. __Q(3, 7, 11, 15);
  10361. __Q(0, 5, 10, 15);
  10362. __Q(1, 6, 11, 12);
  10363. __Q(2, 7, 8, 13);
  10364. __Q(3, 4, 9, 14);
  10365. }
  10366. #define __FIN(i) output[i] = start[i] + __t##i;
  10367. TIMES16(__FIN)
  10368. }
  10369. #define U8(x) ((uint8_t) ((x) &0xFF))
  10370. #ifdef FAST_PATH
  10371. #define xor32_le(dst, src, pad) \
  10372. uint32_t __value; \
  10373. memcpy(&__value, src, sizeof(uint32_t)); \
  10374. __value ^= *(pad); \
  10375. memcpy(dst, &__value, sizeof(uint32_t));
  10376. #else
  10377. #define xor32_le(dst, src, pad) \
  10378. (dst)[0] = (src)[0] ^ U8(*(pad)); \
  10379. (dst)[1] = (src)[1] ^ U8(*(pad) >> 8); \
  10380. (dst)[2] = (src)[2] ^ U8(*(pad) >> 16); \
  10381. (dst)[3] = (src)[3] ^ U8(*(pad) >> 24);
  10382. #endif
  10383. #define index8_32(a, ix) ((a) + ((ix) * sizeof(uint32_t)))
  10384. #define xor32_blocks(dest, source, pad, words) \
  10385. for (i = 0; i < words; i++) { \
  10386. xor32_le(index8_32(dest, i), index8_32(source, i), (pad) + i) \
  10387. }
  10388. static void xor_block(uint8_t *restrict dest, const uint8_t *restrict source,
  10389. const uint32_t *restrict pad, unsigned int chunk_size) {
  10390. unsigned int i, full_blocks = chunk_size / (unsigned int) sizeof(uint32_t);
  10391. // have to be carefull, we are going back from uint32 to uint8, so endianness
  10392. // matters again
  10393. xor32_blocks(dest, source, pad, full_blocks)
  10394. dest += full_blocks * sizeof(uint32_t);
  10395. source += full_blocks * sizeof(uint32_t);
  10396. pad += full_blocks;
  10397. switch (chunk_size % sizeof(uint32_t)) {
  10398. case 1:
  10399. dest[0] = source[0] ^ U8(*pad);
  10400. break;
  10401. case 2:
  10402. dest[0] = source[0] ^ U8(*pad);
  10403. dest[1] = source[1] ^ U8(*pad >> 8);
  10404. break;
  10405. case 3:
  10406. dest[0] = source[0] ^ U8(*pad);
  10407. dest[1] = source[1] ^ U8(*pad >> 8);
  10408. dest[2] = source[2] ^ U8(*pad >> 16);
  10409. break;
  10410. }
  10411. }
  10412. static void chacha20_xor_stream(uint8_t *restrict dest,
  10413. const uint8_t *restrict source, size_t length,
  10414. const uint8_t key[CHACHA20_KEY_SIZE],
  10415. const uint8_t nonce[CHACHA20_NONCE_SIZE],
  10416. uint32_t counter) {
  10417. uint32_t state[CHACHA20_STATE_WORDS];
  10418. uint32_t pad[CHACHA20_STATE_WORDS];
  10419. size_t i, b, last_block, full_blocks = length / CHACHA20_BLOCK_SIZE;
  10420. initialize_state(state, key, nonce, counter);
  10421. for (b = 0; b < full_blocks; b++) {
  10422. core_block(state, pad);
  10423. increment_counter(state);
  10424. xor32_blocks(dest, source, pad, CHACHA20_STATE_WORDS) dest +=
  10425. CHACHA20_BLOCK_SIZE;
  10426. source += CHACHA20_BLOCK_SIZE;
  10427. }
  10428. last_block = length % CHACHA20_BLOCK_SIZE;
  10429. if (last_block > 0) {
  10430. core_block(state, pad);
  10431. xor_block(dest, source, pad, (unsigned int) last_block);
  10432. }
  10433. }
  10434. #ifdef FAST_PATH
  10435. #define serialize(poly_key, result) memcpy(poly_key, result, 32)
  10436. #else
  10437. #define store32_le(target, source) \
  10438. (target)[0] = U8(*(source)); \
  10439. (target)[1] = U8(*(source) >> 8); \
  10440. (target)[2] = U8(*(source) >> 16); \
  10441. (target)[3] = U8(*(source) >> 24);
  10442. #define serialize(poly_key, result) \
  10443. for (i = 0; i < 32 / sizeof(uint32_t); i++) { \
  10444. store32_le(index8_32(poly_key, i), result + i); \
  10445. }
  10446. #endif
  10447. static void rfc8439_keygen(uint8_t poly_key[32],
  10448. const uint8_t key[CHACHA20_KEY_SIZE],
  10449. const uint8_t nonce[CHACHA20_NONCE_SIZE]) {
  10450. uint32_t state[CHACHA20_STATE_WORDS];
  10451. uint32_t result[CHACHA20_STATE_WORDS];
  10452. size_t i;
  10453. initialize_state(state, key, nonce, 0);
  10454. core_block(state, result);
  10455. serialize(poly_key, result);
  10456. (void) i;
  10457. }
  10458. // ******* END: chacha-portable.c ********
  10459. // ******* BEGIN: poly1305-donna.c ********
  10460. /* auto detect between 32bit / 64bit */
  10461. #if /* uint128 available on 64bit system*/ \
  10462. (defined(__SIZEOF_INT128__) && \
  10463. defined(__LP64__)) /* MSVC 64bit compiler */ \
  10464. || (defined(_MSC_VER) && defined(_M_X64)) /* gcc >= 4.4 64bit */ \
  10465. || (defined(__GNUC__) && defined(__LP64__) && \
  10466. ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4))))
  10467. #define __GUESS64
  10468. #else
  10469. #define __GUESS32
  10470. #endif
  10471. #if defined(POLY1305_8BIT)
  10472. /*
  10473. poly1305 implementation using 8 bit * 8 bit = 16 bit multiplication and
  10474. 32 bit addition
  10475. based on the public domain reference version in supercop by djb
  10476. static */
  10477. #if defined(_MSC_VER) && _MSC_VER < 1700
  10478. #define POLY1305_NOINLINE
  10479. #elif defined(_MSC_VER)
  10480. #define POLY1305_NOINLINE __declspec(noinline)
  10481. #elif defined(__GNUC__)
  10482. #define POLY1305_NOINLINE __attribute__((noinline))
  10483. #else
  10484. #define POLY1305_NOINLINE
  10485. #endif
  10486. #define poly1305_block_size 16
  10487. /* 17 + sizeof(size_t) + 51*sizeof(unsigned char) */
  10488. typedef struct poly1305_state_internal_t {
  10489. unsigned char buffer[poly1305_block_size];
  10490. size_t leftover;
  10491. unsigned char h[17];
  10492. unsigned char r[17];
  10493. unsigned char pad[17];
  10494. unsigned char final;
  10495. } poly1305_state_internal_t;
  10496. static void poly1305_init(poly1305_context *ctx, const unsigned char key[32]) {
  10497. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  10498. size_t i;
  10499. st->leftover = 0;
  10500. /* h = 0 */
  10501. for (i = 0; i < 17; i++) st->h[i] = 0;
  10502. /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
  10503. st->r[0] = key[0] & 0xff;
  10504. st->r[1] = key[1] & 0xff;
  10505. st->r[2] = key[2] & 0xff;
  10506. st->r[3] = key[3] & 0x0f;
  10507. st->r[4] = key[4] & 0xfc;
  10508. st->r[5] = key[5] & 0xff;
  10509. st->r[6] = key[6] & 0xff;
  10510. st->r[7] = key[7] & 0x0f;
  10511. st->r[8] = key[8] & 0xfc;
  10512. st->r[9] = key[9] & 0xff;
  10513. st->r[10] = key[10] & 0xff;
  10514. st->r[11] = key[11] & 0x0f;
  10515. st->r[12] = key[12] & 0xfc;
  10516. st->r[13] = key[13] & 0xff;
  10517. st->r[14] = key[14] & 0xff;
  10518. st->r[15] = key[15] & 0x0f;
  10519. st->r[16] = 0;
  10520. /* save pad for later */
  10521. for (i = 0; i < 16; i++) st->pad[i] = key[i + 16];
  10522. st->pad[16] = 0;
  10523. st->final = 0;
  10524. }
  10525. static void poly1305_add(unsigned char h[17], const unsigned char c[17]) {
  10526. unsigned short u;
  10527. unsigned int i;
  10528. for (u = 0, i = 0; i < 17; i++) {
  10529. u += (unsigned short) h[i] + (unsigned short) c[i];
  10530. h[i] = (unsigned char) u & 0xff;
  10531. u >>= 8;
  10532. }
  10533. }
  10534. static void poly1305_squeeze(unsigned char h[17], unsigned long hr[17]) {
  10535. unsigned long u;
  10536. unsigned int i;
  10537. u = 0;
  10538. for (i = 0; i < 16; i++) {
  10539. u += hr[i];
  10540. h[i] = (unsigned char) u & 0xff;
  10541. u >>= 8;
  10542. }
  10543. u += hr[16];
  10544. h[16] = (unsigned char) u & 0x03;
  10545. u >>= 2;
  10546. u += (u << 2); /* u *= 5; */
  10547. for (i = 0; i < 16; i++) {
  10548. u += h[i];
  10549. h[i] = (unsigned char) u & 0xff;
  10550. u >>= 8;
  10551. }
  10552. h[16] += (unsigned char) u;
  10553. }
  10554. static void poly1305_freeze(unsigned char h[17]) {
  10555. const unsigned char minusp[17] = {0x05, 0x00, 0x00, 0x00, 0x00, 0x00,
  10556. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  10557. 0x00, 0x00, 0x00, 0x00, 0xfc};
  10558. unsigned char horig[17], negative;
  10559. unsigned int i;
  10560. /* compute h + -p */
  10561. for (i = 0; i < 17; i++) horig[i] = h[i];
  10562. poly1305_add(h, minusp);
  10563. /* select h if h < p, or h + -p if h >= p */
  10564. negative = -(h[16] >> 7);
  10565. for (i = 0; i < 17; i++) h[i] ^= negative & (horig[i] ^ h[i]);
  10566. }
  10567. static void poly1305_blocks(poly1305_state_internal_t *st,
  10568. const unsigned char *m, size_t bytes) {
  10569. const unsigned char hibit = st->final ^ 1; /* 1 << 128 */
  10570. while (bytes >= poly1305_block_size) {
  10571. unsigned long hr[17], u;
  10572. unsigned char c[17];
  10573. unsigned int i, j;
  10574. /* h += m */
  10575. for (i = 0; i < 16; i++) c[i] = m[i];
  10576. c[16] = hibit;
  10577. poly1305_add(st->h, c);
  10578. /* h *= r */
  10579. for (i = 0; i < 17; i++) {
  10580. u = 0;
  10581. for (j = 0; j <= i; j++) {
  10582. u += (unsigned short) st->h[j] * st->r[i - j];
  10583. }
  10584. for (j = i + 1; j < 17; j++) {
  10585. unsigned long v = (unsigned short) st->h[j] * st->r[i + 17 - j];
  10586. v = ((v << 8) + (v << 6)); /* v *= (5 << 6); */
  10587. u += v;
  10588. }
  10589. hr[i] = u;
  10590. }
  10591. /* (partial) h %= p */
  10592. poly1305_squeeze(st->h, hr);
  10593. m += poly1305_block_size;
  10594. bytes -= poly1305_block_size;
  10595. }
  10596. }
  10597. static POLY1305_NOINLINE void poly1305_finish(poly1305_context *ctx,
  10598. unsigned char mac[16]) {
  10599. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  10600. size_t i;
  10601. /* process the remaining block */
  10602. if (st->leftover) {
  10603. size_t i = st->leftover;
  10604. st->buffer[i++] = 1;
  10605. for (; i < poly1305_block_size; i++) st->buffer[i] = 0;
  10606. st->final = 1;
  10607. poly1305_blocks(st, st->buffer, poly1305_block_size);
  10608. }
  10609. /* fully reduce h */
  10610. poly1305_freeze(st->h);
  10611. /* h = (h + pad) % (1 << 128) */
  10612. poly1305_add(st->h, st->pad);
  10613. for (i = 0; i < 16; i++) mac[i] = st->h[i];
  10614. /* zero out the state */
  10615. for (i = 0; i < 17; i++) st->h[i] = 0;
  10616. for (i = 0; i < 17; i++) st->r[i] = 0;
  10617. for (i = 0; i < 17; i++) st->pad[i] = 0;
  10618. }
  10619. #elif defined(POLY1305_16BIT)
  10620. /*
  10621. poly1305 implementation using 16 bit * 16 bit = 32 bit multiplication
  10622. and 32 bit addition static */
  10623. #if defined(_MSC_VER) && _MSC_VER < 1700
  10624. #define POLY1305_NOINLINE
  10625. #elif defined(_MSC_VER)
  10626. #define POLY1305_NOINLINE __declspec(noinline)
  10627. #elif defined(__GNUC__)
  10628. #define POLY1305_NOINLINE __attribute__((noinline))
  10629. #else
  10630. #define POLY1305_NOINLINE
  10631. #endif
  10632. #define poly1305_block_size 16
  10633. /* 17 + sizeof(size_t) + 18*sizeof(unsigned short) */
  10634. typedef struct poly1305_state_internal_t {
  10635. unsigned char buffer[poly1305_block_size];
  10636. size_t leftover;
  10637. unsigned short r[10];
  10638. unsigned short h[10];
  10639. unsigned short pad[8];
  10640. unsigned char final;
  10641. } poly1305_state_internal_t;
  10642. /* interpret two 8 bit unsigned integers as a 16 bit unsigned integer in little
  10643. * endian */
  10644. static unsigned short U8TO16(const unsigned char *p) {
  10645. return (((unsigned short) (p[0] & 0xff)) |
  10646. ((unsigned short) (p[1] & 0xff) << 8));
  10647. }
  10648. /* store a 16 bit unsigned integer as two 8 bit unsigned integers in little
  10649. * endian */
  10650. static void U16TO8(unsigned char *p, unsigned short v) {
  10651. p[0] = (v) &0xff;
  10652. p[1] = (v >> 8) & 0xff;
  10653. }
  10654. static void poly1305_init(poly1305_context *ctx, const unsigned char key[32]) {
  10655. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  10656. unsigned short t0, t1, t2, t3, t4, t5, t6, t7;
  10657. size_t i;
  10658. /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
  10659. t0 = U8TO16(&key[0]);
  10660. st->r[0] = (t0) &0x1fff;
  10661. t1 = U8TO16(&key[2]);
  10662. st->r[1] = ((t0 >> 13) | (t1 << 3)) & 0x1fff;
  10663. t2 = U8TO16(&key[4]);
  10664. st->r[2] = ((t1 >> 10) | (t2 << 6)) & 0x1f03;
  10665. t3 = U8TO16(&key[6]);
  10666. st->r[3] = ((t2 >> 7) | (t3 << 9)) & 0x1fff;
  10667. t4 = U8TO16(&key[8]);
  10668. st->r[4] = ((t3 >> 4) | (t4 << 12)) & 0x00ff;
  10669. st->r[5] = ((t4 >> 1)) & 0x1ffe;
  10670. t5 = U8TO16(&key[10]);
  10671. st->r[6] = ((t4 >> 14) | (t5 << 2)) & 0x1fff;
  10672. t6 = U8TO16(&key[12]);
  10673. st->r[7] = ((t5 >> 11) | (t6 << 5)) & 0x1f81;
  10674. t7 = U8TO16(&key[14]);
  10675. st->r[8] = ((t6 >> 8) | (t7 << 8)) & 0x1fff;
  10676. st->r[9] = ((t7 >> 5)) & 0x007f;
  10677. /* h = 0 */
  10678. for (i = 0; i < 10; i++) st->h[i] = 0;
  10679. /* save pad for later */
  10680. for (i = 0; i < 8; i++) st->pad[i] = U8TO16(&key[16 + (2 * i)]);
  10681. st->leftover = 0;
  10682. st->final = 0;
  10683. }
  10684. static void poly1305_blocks(poly1305_state_internal_t *st,
  10685. const unsigned char *m, size_t bytes) {
  10686. const unsigned short hibit = (st->final) ? 0 : (1 << 11); /* 1 << 128 */
  10687. unsigned short t0, t1, t2, t3, t4, t5, t6, t7;
  10688. unsigned long d[10];
  10689. unsigned long c;
  10690. while (bytes >= poly1305_block_size) {
  10691. size_t i, j;
  10692. /* h += m[i] */
  10693. t0 = U8TO16(&m[0]);
  10694. st->h[0] += (t0) &0x1fff;
  10695. t1 = U8TO16(&m[2]);
  10696. st->h[1] += ((t0 >> 13) | (t1 << 3)) & 0x1fff;
  10697. t2 = U8TO16(&m[4]);
  10698. st->h[2] += ((t1 >> 10) | (t2 << 6)) & 0x1fff;
  10699. t3 = U8TO16(&m[6]);
  10700. st->h[3] += ((t2 >> 7) | (t3 << 9)) & 0x1fff;
  10701. t4 = U8TO16(&m[8]);
  10702. st->h[4] += ((t3 >> 4) | (t4 << 12)) & 0x1fff;
  10703. st->h[5] += ((t4 >> 1)) & 0x1fff;
  10704. t5 = U8TO16(&m[10]);
  10705. st->h[6] += ((t4 >> 14) | (t5 << 2)) & 0x1fff;
  10706. t6 = U8TO16(&m[12]);
  10707. st->h[7] += ((t5 >> 11) | (t6 << 5)) & 0x1fff;
  10708. t7 = U8TO16(&m[14]);
  10709. st->h[8] += ((t6 >> 8) | (t7 << 8)) & 0x1fff;
  10710. st->h[9] += ((t7 >> 5)) | hibit;
  10711. /* h *= r, (partial) h %= p */
  10712. for (i = 0, c = 0; i < 10; i++) {
  10713. d[i] = c;
  10714. for (j = 0; j < 10; j++) {
  10715. d[i] += (unsigned long) st->h[j] *
  10716. ((j <= i) ? st->r[i - j] : (5 * st->r[i + 10 - j]));
  10717. /* Sum(h[i] * r[i] * 5) will overflow slightly above 6 products with an
  10718. * unclamped r, so carry at 5 */
  10719. if (j == 4) {
  10720. c = (d[i] >> 13);
  10721. d[i] &= 0x1fff;
  10722. }
  10723. }
  10724. c += (d[i] >> 13);
  10725. d[i] &= 0x1fff;
  10726. }
  10727. c = ((c << 2) + c); /* c *= 5 */
  10728. c += d[0];
  10729. d[0] = ((unsigned short) c & 0x1fff);
  10730. c = (c >> 13);
  10731. d[1] += c;
  10732. for (i = 0; i < 10; i++) st->h[i] = (unsigned short) d[i];
  10733. m += poly1305_block_size;
  10734. bytes -= poly1305_block_size;
  10735. }
  10736. }
  10737. static POLY1305_NOINLINE void poly1305_finish(poly1305_context *ctx,
  10738. unsigned char mac[16]) {
  10739. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  10740. unsigned short c;
  10741. unsigned short g[10];
  10742. unsigned short mask;
  10743. unsigned long f;
  10744. size_t i;
  10745. /* process the remaining block */
  10746. if (st->leftover) {
  10747. size_t i = st->leftover;
  10748. st->buffer[i++] = 1;
  10749. for (; i < poly1305_block_size; i++) st->buffer[i] = 0;
  10750. st->final = 1;
  10751. poly1305_blocks(st, st->buffer, poly1305_block_size);
  10752. }
  10753. /* fully carry h */
  10754. c = st->h[1] >> 13;
  10755. st->h[1] &= 0x1fff;
  10756. for (i = 2; i < 10; i++) {
  10757. st->h[i] += c;
  10758. c = st->h[i] >> 13;
  10759. st->h[i] &= 0x1fff;
  10760. }
  10761. st->h[0] += (c * 5);
  10762. c = st->h[0] >> 13;
  10763. st->h[0] &= 0x1fff;
  10764. st->h[1] += c;
  10765. c = st->h[1] >> 13;
  10766. st->h[1] &= 0x1fff;
  10767. st->h[2] += c;
  10768. /* compute h + -p */
  10769. g[0] = st->h[0] + 5;
  10770. c = g[0] >> 13;
  10771. g[0] &= 0x1fff;
  10772. for (i = 1; i < 10; i++) {
  10773. g[i] = st->h[i] + c;
  10774. c = g[i] >> 13;
  10775. g[i] &= 0x1fff;
  10776. }
  10777. /* select h if h < p, or h + -p if h >= p */
  10778. mask = (c ^ 1) - 1;
  10779. for (i = 0; i < 10; i++) g[i] &= mask;
  10780. mask = ~mask;
  10781. for (i = 0; i < 10; i++) st->h[i] = (st->h[i] & mask) | g[i];
  10782. /* h = h % (2^128) */
  10783. st->h[0] = ((st->h[0]) | (st->h[1] << 13)) & 0xffff;
  10784. st->h[1] = ((st->h[1] >> 3) | (st->h[2] << 10)) & 0xffff;
  10785. st->h[2] = ((st->h[2] >> 6) | (st->h[3] << 7)) & 0xffff;
  10786. st->h[3] = ((st->h[3] >> 9) | (st->h[4] << 4)) & 0xffff;
  10787. st->h[4] = ((st->h[4] >> 12) | (st->h[5] << 1) | (st->h[6] << 14)) & 0xffff;
  10788. st->h[5] = ((st->h[6] >> 2) | (st->h[7] << 11)) & 0xffff;
  10789. st->h[6] = ((st->h[7] >> 5) | (st->h[8] << 8)) & 0xffff;
  10790. st->h[7] = ((st->h[8] >> 8) | (st->h[9] << 5)) & 0xffff;
  10791. /* mac = (h + pad) % (2^128) */
  10792. f = (unsigned long) st->h[0] + st->pad[0];
  10793. st->h[0] = (unsigned short) f;
  10794. for (i = 1; i < 8; i++) {
  10795. f = (unsigned long) st->h[i] + st->pad[i] + (f >> 16);
  10796. st->h[i] = (unsigned short) f;
  10797. }
  10798. for (i = 0; i < 8; i++) U16TO8(mac + (i * 2), st->h[i]);
  10799. /* zero out the state */
  10800. for (i = 0; i < 10; i++) st->h[i] = 0;
  10801. for (i = 0; i < 10; i++) st->r[i] = 0;
  10802. for (i = 0; i < 8; i++) st->pad[i] = 0;
  10803. }
  10804. #elif defined(POLY1305_32BIT) || \
  10805. (!defined(POLY1305_64BIT) && defined(__GUESS32))
  10806. /*
  10807. poly1305 implementation using 32 bit * 32 bit = 64 bit multiplication
  10808. and 64 bit addition static */
  10809. #if defined(_MSC_VER) && _MSC_VER < 1700
  10810. #define POLY1305_NOINLINE
  10811. #elif defined(_MSC_VER)
  10812. #define POLY1305_NOINLINE __declspec(noinline)
  10813. #elif defined(__GNUC__)
  10814. #define POLY1305_NOINLINE __attribute__((noinline))
  10815. #else
  10816. #define POLY1305_NOINLINE
  10817. #endif
  10818. #define poly1305_block_size 16
  10819. /* 17 + sizeof(size_t) + 14*sizeof(unsigned long) */
  10820. typedef struct poly1305_state_internal_t {
  10821. unsigned long r[5];
  10822. unsigned long h[5];
  10823. unsigned long pad[4];
  10824. size_t leftover;
  10825. unsigned char buffer[poly1305_block_size];
  10826. unsigned char final;
  10827. } poly1305_state_internal_t;
  10828. /* interpret four 8 bit unsigned integers as a 32 bit unsigned integer in little
  10829. * endian */
  10830. static unsigned long U8TO32(const unsigned char *p) {
  10831. return (((unsigned long) (p[0] & 0xff)) |
  10832. ((unsigned long) (p[1] & 0xff) << 8) |
  10833. ((unsigned long) (p[2] & 0xff) << 16) |
  10834. ((unsigned long) (p[3] & 0xff) << 24));
  10835. }
  10836. /* store a 32 bit unsigned integer as four 8 bit unsigned integers in little
  10837. * endian */
  10838. static void U32TO8(unsigned char *p, unsigned long v) {
  10839. p[0] = (unsigned char) ((v) &0xff);
  10840. p[1] = (unsigned char) ((v >> 8) & 0xff);
  10841. p[2] = (unsigned char) ((v >> 16) & 0xff);
  10842. p[3] = (unsigned char) ((v >> 24) & 0xff);
  10843. }
  10844. static void poly1305_init(poly1305_context *ctx, const unsigned char key[32]) {
  10845. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  10846. /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
  10847. st->r[0] = (U8TO32(&key[0])) & 0x3ffffff;
  10848. st->r[1] = (U8TO32(&key[3]) >> 2) & 0x3ffff03;
  10849. st->r[2] = (U8TO32(&key[6]) >> 4) & 0x3ffc0ff;
  10850. st->r[3] = (U8TO32(&key[9]) >> 6) & 0x3f03fff;
  10851. st->r[4] = (U8TO32(&key[12]) >> 8) & 0x00fffff;
  10852. /* h = 0 */
  10853. st->h[0] = 0;
  10854. st->h[1] = 0;
  10855. st->h[2] = 0;
  10856. st->h[3] = 0;
  10857. st->h[4] = 0;
  10858. /* save pad for later */
  10859. st->pad[0] = U8TO32(&key[16]);
  10860. st->pad[1] = U8TO32(&key[20]);
  10861. st->pad[2] = U8TO32(&key[24]);
  10862. st->pad[3] = U8TO32(&key[28]);
  10863. st->leftover = 0;
  10864. st->final = 0;
  10865. }
  10866. static void poly1305_blocks(poly1305_state_internal_t *st,
  10867. const unsigned char *m, size_t bytes) {
  10868. const unsigned long hibit = (st->final) ? 0 : (1UL << 24); /* 1 << 128 */
  10869. unsigned long r0, r1, r2, r3, r4;
  10870. unsigned long s1, s2, s3, s4;
  10871. unsigned long h0, h1, h2, h3, h4;
  10872. uint64_t d0, d1, d2, d3, d4;
  10873. unsigned long c;
  10874. r0 = st->r[0];
  10875. r1 = st->r[1];
  10876. r2 = st->r[2];
  10877. r3 = st->r[3];
  10878. r4 = st->r[4];
  10879. s1 = r1 * 5;
  10880. s2 = r2 * 5;
  10881. s3 = r3 * 5;
  10882. s4 = r4 * 5;
  10883. h0 = st->h[0];
  10884. h1 = st->h[1];
  10885. h2 = st->h[2];
  10886. h3 = st->h[3];
  10887. h4 = st->h[4];
  10888. while (bytes >= poly1305_block_size) {
  10889. /* h += m[i] */
  10890. h0 += (U8TO32(m + 0)) & 0x3ffffff;
  10891. h1 += (U8TO32(m + 3) >> 2) & 0x3ffffff;
  10892. h2 += (U8TO32(m + 6) >> 4) & 0x3ffffff;
  10893. h3 += (U8TO32(m + 9) >> 6) & 0x3ffffff;
  10894. h4 += (U8TO32(m + 12) >> 8) | hibit;
  10895. /* h *= r */
  10896. d0 = ((uint64_t) h0 * r0) + ((uint64_t) h1 * s4) + ((uint64_t) h2 * s3) +
  10897. ((uint64_t) h3 * s2) + ((uint64_t) h4 * s1);
  10898. d1 = ((uint64_t) h0 * r1) + ((uint64_t) h1 * r0) + ((uint64_t) h2 * s4) +
  10899. ((uint64_t) h3 * s3) + ((uint64_t) h4 * s2);
  10900. d2 = ((uint64_t) h0 * r2) + ((uint64_t) h1 * r1) + ((uint64_t) h2 * r0) +
  10901. ((uint64_t) h3 * s4) + ((uint64_t) h4 * s3);
  10902. d3 = ((uint64_t) h0 * r3) + ((uint64_t) h1 * r2) + ((uint64_t) h2 * r1) +
  10903. ((uint64_t) h3 * r0) + ((uint64_t) h4 * s4);
  10904. d4 = ((uint64_t) h0 * r4) + ((uint64_t) h1 * r3) + ((uint64_t) h2 * r2) +
  10905. ((uint64_t) h3 * r1) + ((uint64_t) h4 * r0);
  10906. /* (partial) h %= p */
  10907. c = (unsigned long) (d0 >> 26);
  10908. h0 = (unsigned long) d0 & 0x3ffffff;
  10909. d1 += c;
  10910. c = (unsigned long) (d1 >> 26);
  10911. h1 = (unsigned long) d1 & 0x3ffffff;
  10912. d2 += c;
  10913. c = (unsigned long) (d2 >> 26);
  10914. h2 = (unsigned long) d2 & 0x3ffffff;
  10915. d3 += c;
  10916. c = (unsigned long) (d3 >> 26);
  10917. h3 = (unsigned long) d3 & 0x3ffffff;
  10918. d4 += c;
  10919. c = (unsigned long) (d4 >> 26);
  10920. h4 = (unsigned long) d4 & 0x3ffffff;
  10921. h0 += c * 5;
  10922. c = (h0 >> 26);
  10923. h0 = h0 & 0x3ffffff;
  10924. h1 += c;
  10925. m += poly1305_block_size;
  10926. bytes -= poly1305_block_size;
  10927. }
  10928. st->h[0] = h0;
  10929. st->h[1] = h1;
  10930. st->h[2] = h2;
  10931. st->h[3] = h3;
  10932. st->h[4] = h4;
  10933. }
  10934. static POLY1305_NOINLINE void poly1305_finish(poly1305_context *ctx,
  10935. unsigned char mac[16]) {
  10936. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  10937. unsigned long h0, h1, h2, h3, h4, c;
  10938. unsigned long g0, g1, g2, g3, g4;
  10939. uint64_t f;
  10940. unsigned long mask;
  10941. /* process the remaining block */
  10942. if (st->leftover) {
  10943. size_t i = st->leftover;
  10944. st->buffer[i++] = 1;
  10945. for (; i < poly1305_block_size; i++) st->buffer[i] = 0;
  10946. st->final = 1;
  10947. poly1305_blocks(st, st->buffer, poly1305_block_size);
  10948. }
  10949. /* fully carry h */
  10950. h0 = st->h[0];
  10951. h1 = st->h[1];
  10952. h2 = st->h[2];
  10953. h3 = st->h[3];
  10954. h4 = st->h[4];
  10955. c = h1 >> 26;
  10956. h1 = h1 & 0x3ffffff;
  10957. h2 += c;
  10958. c = h2 >> 26;
  10959. h2 = h2 & 0x3ffffff;
  10960. h3 += c;
  10961. c = h3 >> 26;
  10962. h3 = h3 & 0x3ffffff;
  10963. h4 += c;
  10964. c = h4 >> 26;
  10965. h4 = h4 & 0x3ffffff;
  10966. h0 += c * 5;
  10967. c = h0 >> 26;
  10968. h0 = h0 & 0x3ffffff;
  10969. h1 += c;
  10970. /* compute h + -p */
  10971. g0 = h0 + 5;
  10972. c = g0 >> 26;
  10973. g0 &= 0x3ffffff;
  10974. g1 = h1 + c;
  10975. c = g1 >> 26;
  10976. g1 &= 0x3ffffff;
  10977. g2 = h2 + c;
  10978. c = g2 >> 26;
  10979. g2 &= 0x3ffffff;
  10980. g3 = h3 + c;
  10981. c = g3 >> 26;
  10982. g3 &= 0x3ffffff;
  10983. g4 = h4 + c - (1UL << 26);
  10984. /* select h if h < p, or h + -p if h >= p */
  10985. mask = (g4 >> ((sizeof(unsigned long) * 8) - 1)) - 1;
  10986. g0 &= mask;
  10987. g1 &= mask;
  10988. g2 &= mask;
  10989. g3 &= mask;
  10990. g4 &= mask;
  10991. mask = ~mask;
  10992. h0 = (h0 & mask) | g0;
  10993. h1 = (h1 & mask) | g1;
  10994. h2 = (h2 & mask) | g2;
  10995. h3 = (h3 & mask) | g3;
  10996. h4 = (h4 & mask) | g4;
  10997. /* h = h % (2^128) */
  10998. h0 = ((h0) | (h1 << 26)) & 0xffffffff;
  10999. h1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffff;
  11000. h2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffff;
  11001. h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffff;
  11002. /* mac = (h + pad) % (2^128) */
  11003. f = (uint64_t) h0 + st->pad[0];
  11004. h0 = (unsigned long) f;
  11005. f = (uint64_t) h1 + st->pad[1] + (f >> 32);
  11006. h1 = (unsigned long) f;
  11007. f = (uint64_t) h2 + st->pad[2] + (f >> 32);
  11008. h2 = (unsigned long) f;
  11009. f = (uint64_t) h3 + st->pad[3] + (f >> 32);
  11010. h3 = (unsigned long) f;
  11011. U32TO8(mac + 0, h0);
  11012. U32TO8(mac + 4, h1);
  11013. U32TO8(mac + 8, h2);
  11014. U32TO8(mac + 12, h3);
  11015. /* zero out the state */
  11016. st->h[0] = 0;
  11017. st->h[1] = 0;
  11018. st->h[2] = 0;
  11019. st->h[3] = 0;
  11020. st->h[4] = 0;
  11021. st->r[0] = 0;
  11022. st->r[1] = 0;
  11023. st->r[2] = 0;
  11024. st->r[3] = 0;
  11025. st->r[4] = 0;
  11026. st->pad[0] = 0;
  11027. st->pad[1] = 0;
  11028. st->pad[2] = 0;
  11029. st->pad[3] = 0;
  11030. }
  11031. #else
  11032. /*
  11033. poly1305 implementation using 64 bit * 64 bit = 128 bit multiplication
  11034. and 128 bit addition static */
  11035. #if defined(_MSC_VER)
  11036. typedef struct uint128_t {
  11037. uint64_t lo;
  11038. uint64_t hi;
  11039. } uint128_t;
  11040. #define MUL128(out, x, y) out.lo = _umul128((x), (y), &out.hi)
  11041. #define ADD(out, in) \
  11042. { \
  11043. uint64_t t = out.lo; \
  11044. out.lo += in.lo; \
  11045. out.hi += (out.lo < t) + in.hi; \
  11046. }
  11047. #define ADDLO(out, in) \
  11048. { \
  11049. uint64_t t = out.lo; \
  11050. out.lo += in; \
  11051. out.hi += (out.lo < t); \
  11052. }
  11053. #define SHR(in, shift) (__shiftright128(in.lo, in.hi, (shift)))
  11054. #define LO(in) (in.lo)
  11055. #if defined(_MSC_VER) && _MSC_VER < 1700
  11056. #define POLY1305_NOINLINE
  11057. #else
  11058. #define POLY1305_NOINLINE __declspec(noinline)
  11059. #endif
  11060. #elif defined(__GNUC__)
  11061. #if defined(__SIZEOF_INT128__)
  11062. // Get rid of GCC warning "ISO C does not support '__int128' types"
  11063. #pragma GCC diagnostic push
  11064. #pragma GCC diagnostic ignored "-Wpedantic"
  11065. typedef unsigned __int128 uint128_t;
  11066. #pragma GCC diagnostic pop
  11067. #else
  11068. typedef unsigned uint128_t __attribute__((mode(TI)));
  11069. #endif
  11070. #define MUL128(out, x, y) out = ((uint128_t) x * y)
  11071. #define ADD(out, in) out += in
  11072. #define ADDLO(out, in) out += in
  11073. #define SHR(in, shift) (uint64_t)(in >> (shift))
  11074. #define LO(in) (uint64_t)(in)
  11075. #define POLY1305_NOINLINE __attribute__((noinline))
  11076. #endif
  11077. #define poly1305_block_size 16
  11078. /* 17 + sizeof(size_t) + 8*sizeof(uint64_t) */
  11079. typedef struct poly1305_state_internal_t {
  11080. uint64_t r[3];
  11081. uint64_t h[3];
  11082. uint64_t pad[2];
  11083. size_t leftover;
  11084. unsigned char buffer[poly1305_block_size];
  11085. unsigned char final;
  11086. } poly1305_state_internal_t;
  11087. /* interpret eight 8 bit unsigned integers as a 64 bit unsigned integer in
  11088. * little endian */
  11089. static uint64_t U8TO64(const unsigned char *p) {
  11090. return (((uint64_t) (p[0] & 0xff)) | ((uint64_t) (p[1] & 0xff) << 8) |
  11091. ((uint64_t) (p[2] & 0xff) << 16) | ((uint64_t) (p[3] & 0xff) << 24) |
  11092. ((uint64_t) (p[4] & 0xff) << 32) | ((uint64_t) (p[5] & 0xff) << 40) |
  11093. ((uint64_t) (p[6] & 0xff) << 48) | ((uint64_t) (p[7] & 0xff) << 56));
  11094. }
  11095. /* store a 64 bit unsigned integer as eight 8 bit unsigned integers in little
  11096. * endian */
  11097. static void U64TO8(unsigned char *p, uint64_t v) {
  11098. p[0] = (unsigned char) ((v) &0xff);
  11099. p[1] = (unsigned char) ((v >> 8) & 0xff);
  11100. p[2] = (unsigned char) ((v >> 16) & 0xff);
  11101. p[3] = (unsigned char) ((v >> 24) & 0xff);
  11102. p[4] = (unsigned char) ((v >> 32) & 0xff);
  11103. p[5] = (unsigned char) ((v >> 40) & 0xff);
  11104. p[6] = (unsigned char) ((v >> 48) & 0xff);
  11105. p[7] = (unsigned char) ((v >> 56) & 0xff);
  11106. }
  11107. static void poly1305_init(poly1305_context *ctx, const unsigned char key[32]) {
  11108. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  11109. uint64_t t0, t1;
  11110. /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
  11111. t0 = U8TO64(&key[0]);
  11112. t1 = U8TO64(&key[8]);
  11113. st->r[0] = (t0) &0xffc0fffffff;
  11114. st->r[1] = ((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffff;
  11115. st->r[2] = ((t1 >> 24)) & 0x00ffffffc0f;
  11116. /* h = 0 */
  11117. st->h[0] = 0;
  11118. st->h[1] = 0;
  11119. st->h[2] = 0;
  11120. /* save pad for later */
  11121. st->pad[0] = U8TO64(&key[16]);
  11122. st->pad[1] = U8TO64(&key[24]);
  11123. st->leftover = 0;
  11124. st->final = 0;
  11125. }
  11126. static void poly1305_blocks(poly1305_state_internal_t *st,
  11127. const unsigned char *m, size_t bytes) {
  11128. const uint64_t hibit = (st->final) ? 0 : ((uint64_t) 1 << 40); /* 1 << 128 */
  11129. uint64_t r0, r1, r2;
  11130. uint64_t s1, s2;
  11131. uint64_t h0, h1, h2;
  11132. uint64_t c;
  11133. uint128_t d0, d1, d2, d;
  11134. r0 = st->r[0];
  11135. r1 = st->r[1];
  11136. r2 = st->r[2];
  11137. h0 = st->h[0];
  11138. h1 = st->h[1];
  11139. h2 = st->h[2];
  11140. s1 = r1 * (5 << 2);
  11141. s2 = r2 * (5 << 2);
  11142. while (bytes >= poly1305_block_size) {
  11143. uint64_t t0, t1;
  11144. /* h += m[i] */
  11145. t0 = U8TO64(&m[0]);
  11146. t1 = U8TO64(&m[8]);
  11147. h0 += ((t0) &0xfffffffffff);
  11148. h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff);
  11149. h2 += (((t1 >> 24)) & 0x3ffffffffff) | hibit;
  11150. /* h *= r */
  11151. MUL128(d0, h0, r0);
  11152. MUL128(d, h1, s2);
  11153. ADD(d0, d);
  11154. MUL128(d, h2, s1);
  11155. ADD(d0, d);
  11156. MUL128(d1, h0, r1);
  11157. MUL128(d, h1, r0);
  11158. ADD(d1, d);
  11159. MUL128(d, h2, s2);
  11160. ADD(d1, d);
  11161. MUL128(d2, h0, r2);
  11162. MUL128(d, h1, r1);
  11163. ADD(d2, d);
  11164. MUL128(d, h2, r0);
  11165. ADD(d2, d);
  11166. /* (partial) h %= p */
  11167. c = SHR(d0, 44);
  11168. h0 = LO(d0) & 0xfffffffffff;
  11169. ADDLO(d1, c);
  11170. c = SHR(d1, 44);
  11171. h1 = LO(d1) & 0xfffffffffff;
  11172. ADDLO(d2, c);
  11173. c = SHR(d2, 42);
  11174. h2 = LO(d2) & 0x3ffffffffff;
  11175. h0 += c * 5;
  11176. c = (h0 >> 44);
  11177. h0 = h0 & 0xfffffffffff;
  11178. h1 += c;
  11179. m += poly1305_block_size;
  11180. bytes -= poly1305_block_size;
  11181. }
  11182. st->h[0] = h0;
  11183. st->h[1] = h1;
  11184. st->h[2] = h2;
  11185. }
  11186. static POLY1305_NOINLINE void poly1305_finish(poly1305_context *ctx,
  11187. unsigned char mac[16]) {
  11188. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  11189. uint64_t h0, h1, h2, c;
  11190. uint64_t g0, g1, g2;
  11191. uint64_t t0, t1;
  11192. /* process the remaining block */
  11193. if (st->leftover) {
  11194. size_t i = st->leftover;
  11195. st->buffer[i] = 1;
  11196. for (i = i + 1; i < poly1305_block_size; i++) st->buffer[i] = 0;
  11197. st->final = 1;
  11198. poly1305_blocks(st, st->buffer, poly1305_block_size);
  11199. }
  11200. /* fully carry h */
  11201. h0 = st->h[0];
  11202. h1 = st->h[1];
  11203. h2 = st->h[2];
  11204. c = (h1 >> 44);
  11205. h1 &= 0xfffffffffff;
  11206. h2 += c;
  11207. c = (h2 >> 42);
  11208. h2 &= 0x3ffffffffff;
  11209. h0 += c * 5;
  11210. c = (h0 >> 44);
  11211. h0 &= 0xfffffffffff;
  11212. h1 += c;
  11213. c = (h1 >> 44);
  11214. h1 &= 0xfffffffffff;
  11215. h2 += c;
  11216. c = (h2 >> 42);
  11217. h2 &= 0x3ffffffffff;
  11218. h0 += c * 5;
  11219. c = (h0 >> 44);
  11220. h0 &= 0xfffffffffff;
  11221. h1 += c;
  11222. /* compute h + -p */
  11223. g0 = h0 + 5;
  11224. c = (g0 >> 44);
  11225. g0 &= 0xfffffffffff;
  11226. g1 = h1 + c;
  11227. c = (g1 >> 44);
  11228. g1 &= 0xfffffffffff;
  11229. g2 = h2 + c - ((uint64_t) 1 << 42);
  11230. /* select h if h < p, or h + -p if h >= p */
  11231. c = (g2 >> ((sizeof(uint64_t) * 8) - 1)) - 1;
  11232. g0 &= c;
  11233. g1 &= c;
  11234. g2 &= c;
  11235. c = ~c;
  11236. h0 = (h0 & c) | g0;
  11237. h1 = (h1 & c) | g1;
  11238. h2 = (h2 & c) | g2;
  11239. /* h = (h + pad) */
  11240. t0 = st->pad[0];
  11241. t1 = st->pad[1];
  11242. h0 += ((t0) &0xfffffffffff);
  11243. c = (h0 >> 44);
  11244. h0 &= 0xfffffffffff;
  11245. h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff) + c;
  11246. c = (h1 >> 44);
  11247. h1 &= 0xfffffffffff;
  11248. h2 += (((t1 >> 24)) & 0x3ffffffffff) + c;
  11249. h2 &= 0x3ffffffffff;
  11250. /* mac = h % (2^128) */
  11251. h0 = ((h0) | (h1 << 44));
  11252. h1 = ((h1 >> 20) | (h2 << 24));
  11253. U64TO8(&mac[0], h0);
  11254. U64TO8(&mac[8], h1);
  11255. /* zero out the state */
  11256. st->h[0] = 0;
  11257. st->h[1] = 0;
  11258. st->h[2] = 0;
  11259. st->r[0] = 0;
  11260. st->r[1] = 0;
  11261. st->r[2] = 0;
  11262. st->pad[0] = 0;
  11263. st->pad[1] = 0;
  11264. }
  11265. #endif
  11266. static void poly1305_update(poly1305_context *ctx, const unsigned char *m,
  11267. size_t bytes) {
  11268. poly1305_state_internal_t *st = (poly1305_state_internal_t *) ctx;
  11269. size_t i;
  11270. /* handle leftover */
  11271. if (st->leftover) {
  11272. size_t want = (poly1305_block_size - st->leftover);
  11273. if (want > bytes) want = bytes;
  11274. for (i = 0; i < want; i++) st->buffer[st->leftover + i] = m[i];
  11275. bytes -= want;
  11276. m += want;
  11277. st->leftover += want;
  11278. if (st->leftover < poly1305_block_size) return;
  11279. poly1305_blocks(st, st->buffer, poly1305_block_size);
  11280. st->leftover = 0;
  11281. }
  11282. /* process full blocks */
  11283. if (bytes >= poly1305_block_size) {
  11284. size_t want = (bytes & (size_t) ~(poly1305_block_size - 1));
  11285. poly1305_blocks(st, m, want);
  11286. m += want;
  11287. bytes -= want;
  11288. }
  11289. /* store leftover */
  11290. if (bytes) {
  11291. for (i = 0; i < bytes; i++) st->buffer[st->leftover + i] = m[i];
  11292. st->leftover += bytes;
  11293. }
  11294. }
  11295. // ******* END: poly1305-donna.c ********
  11296. // ******* BEGIN: portable8439.c ********
  11297. #define __CHACHA20_BLOCK_SIZE (64)
  11298. #define __POLY1305_KEY_SIZE (32)
  11299. static PORTABLE_8439_DECL uint8_t __ZEROES[16] = {0};
  11300. static PORTABLE_8439_DECL void pad_if_needed(poly1305_context *ctx,
  11301. size_t size) {
  11302. size_t padding = size % 16;
  11303. if (padding != 0) {
  11304. poly1305_update(ctx, __ZEROES, 16 - padding);
  11305. }
  11306. }
  11307. #define __u8(v) ((uint8_t) ((v) &0xFF))
  11308. // TODO: make this depending on the unaligned/native read size possible
  11309. static PORTABLE_8439_DECL void write_64bit_int(poly1305_context *ctx,
  11310. uint64_t value) {
  11311. uint8_t result[8];
  11312. result[0] = __u8(value);
  11313. result[1] = __u8(value >> 8);
  11314. result[2] = __u8(value >> 16);
  11315. result[3] = __u8(value >> 24);
  11316. result[4] = __u8(value >> 32);
  11317. result[5] = __u8(value >> 40);
  11318. result[6] = __u8(value >> 48);
  11319. result[7] = __u8(value >> 56);
  11320. poly1305_update(ctx, result, 8);
  11321. }
  11322. static PORTABLE_8439_DECL void poly1305_calculate_mac(
  11323. uint8_t *mac, const uint8_t *cipher_text, size_t cipher_text_size,
  11324. const uint8_t key[RFC_8439_KEY_SIZE],
  11325. const uint8_t nonce[RFC_8439_NONCE_SIZE], const uint8_t *ad,
  11326. size_t ad_size) {
  11327. // init poly key (section 2.6)
  11328. uint8_t poly_key[__POLY1305_KEY_SIZE] = {0};
  11329. poly1305_context poly_ctx;
  11330. rfc8439_keygen(poly_key, key, nonce);
  11331. // start poly1305 mac
  11332. poly1305_init(&poly_ctx, poly_key);
  11333. if (ad != NULL && ad_size > 0) {
  11334. // write AD if present
  11335. poly1305_update(&poly_ctx, ad, ad_size);
  11336. pad_if_needed(&poly_ctx, ad_size);
  11337. }
  11338. // now write the cipher text
  11339. poly1305_update(&poly_ctx, cipher_text, cipher_text_size);
  11340. pad_if_needed(&poly_ctx, cipher_text_size);
  11341. // write sizes
  11342. write_64bit_int(&poly_ctx, ad_size);
  11343. write_64bit_int(&poly_ctx, cipher_text_size);
  11344. // calculate MAC
  11345. poly1305_finish(&poly_ctx, mac);
  11346. }
  11347. #define MG_PM(p) ((size_t) (p))
  11348. // pointers overlap if the smaller either ahead of the end,
  11349. // or its end is before the start of the other
  11350. //
  11351. // s_size should be smaller or equal to b_size
  11352. #define MG_OVERLAPPING(s, s_size, b, b_size) \
  11353. (MG_PM(s) < MG_PM((b) + (b_size))) && (MG_PM(b) < MG_PM((s) + (s_size)))
  11354. PORTABLE_8439_DECL size_t mg_chacha20_poly1305_encrypt(
  11355. uint8_t *restrict cipher_text, const uint8_t key[RFC_8439_KEY_SIZE],
  11356. const uint8_t nonce[RFC_8439_NONCE_SIZE], const uint8_t *restrict ad,
  11357. size_t ad_size, const uint8_t *restrict plain_text,
  11358. size_t plain_text_size) {
  11359. size_t new_size = plain_text_size + RFC_8439_TAG_SIZE;
  11360. if (MG_OVERLAPPING(plain_text, plain_text_size, cipher_text, new_size)) {
  11361. return (size_t) -1;
  11362. }
  11363. chacha20_xor_stream(cipher_text, plain_text, plain_text_size, key, nonce, 1);
  11364. poly1305_calculate_mac(cipher_text + plain_text_size, cipher_text,
  11365. plain_text_size, key, nonce, ad, ad_size);
  11366. return new_size;
  11367. }
  11368. PORTABLE_8439_DECL size_t mg_chacha20_poly1305_decrypt(
  11369. uint8_t *restrict plain_text, const uint8_t key[RFC_8439_KEY_SIZE],
  11370. const uint8_t nonce[RFC_8439_NONCE_SIZE],
  11371. const uint8_t *restrict cipher_text, size_t cipher_text_size) {
  11372. // first we calculate the mac and see if it lines up, only then do we decrypt
  11373. size_t actual_size = cipher_text_size - RFC_8439_TAG_SIZE;
  11374. if (MG_OVERLAPPING(plain_text, actual_size, cipher_text, cipher_text_size)) {
  11375. return (size_t) -1;
  11376. }
  11377. chacha20_xor_stream(plain_text, cipher_text, actual_size, key, nonce, 1);
  11378. return actual_size;
  11379. }
  11380. // ******* END: portable8439.c ********
  11381. #endif // MG_TLS == MG_TLS_BUILTIN
  11382. #ifdef MG_ENABLE_LINES
  11383. #line 1 "src/tls_dummy.c"
  11384. #endif
  11385. #if MG_TLS == MG_TLS_NONE
  11386. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  11387. (void) opts;
  11388. mg_error(c, "TLS is not enabled");
  11389. }
  11390. void mg_tls_handshake(struct mg_connection *c) {
  11391. (void) c;
  11392. }
  11393. void mg_tls_free(struct mg_connection *c) {
  11394. (void) c;
  11395. }
  11396. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  11397. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  11398. }
  11399. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  11400. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  11401. }
  11402. size_t mg_tls_pending(struct mg_connection *c) {
  11403. (void) c;
  11404. return 0;
  11405. }
  11406. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  11407. (void) mgr;
  11408. }
  11409. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  11410. (void) mgr;
  11411. }
  11412. #endif
  11413. #ifdef MG_ENABLE_LINES
  11414. #line 1 "src/tls_mbed.c"
  11415. #endif
  11416. #if MG_TLS == MG_TLS_MBED
  11417. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000
  11418. #define MG_MBEDTLS_RNG_GET , mg_mbed_rng, NULL
  11419. #else
  11420. #define MG_MBEDTLS_RNG_GET
  11421. #endif
  11422. static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) {
  11423. mg_random(buf, len);
  11424. (void) ctx;
  11425. return 0;
  11426. }
  11427. static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *p) {
  11428. int rc;
  11429. if (str.buf == NULL || str.buf[0] == '\0' || str.buf[0] == '*') return true;
  11430. if (str.buf[0] == '-') str.len++; // PEM, include trailing NUL
  11431. if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.buf, str.len)) != 0) {
  11432. MG_ERROR(("cert err %#x", -rc));
  11433. return false;
  11434. }
  11435. return true;
  11436. }
  11437. static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) {
  11438. int rc;
  11439. if (str.buf == NULL || str.buf[0] == '\0' || str.buf[0] == '*') return true;
  11440. if (str.buf[0] == '-') str.len++; // PEM, include trailing NUL
  11441. if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.buf, str.len, NULL,
  11442. 0 MG_MBEDTLS_RNG_GET)) != 0) {
  11443. MG_ERROR(("key err %#x", -rc));
  11444. return false;
  11445. }
  11446. return true;
  11447. }
  11448. void mg_tls_free(struct mg_connection *c) {
  11449. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11450. if (tls != NULL) {
  11451. mbedtls_ssl_free(&tls->ssl);
  11452. mbedtls_pk_free(&tls->pk);
  11453. mbedtls_x509_crt_free(&tls->ca);
  11454. mbedtls_x509_crt_free(&tls->cert);
  11455. mbedtls_ssl_config_free(&tls->conf);
  11456. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  11457. mbedtls_ssl_ticket_free(&tls->ticket);
  11458. #endif
  11459. free(tls);
  11460. c->tls = NULL;
  11461. }
  11462. }
  11463. static int mg_net_send(void *ctx, const unsigned char *buf, size_t len) {
  11464. long n = mg_io_send((struct mg_connection *) ctx, buf, len);
  11465. MG_VERBOSE(("%lu n=%ld e=%d", ((struct mg_connection *) ctx)->id, n, errno));
  11466. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  11467. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  11468. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_SEND_FAILED;
  11469. return (int) n;
  11470. }
  11471. static int mg_net_recv(void *ctx, unsigned char *buf, size_t len) {
  11472. long n = mg_io_recv((struct mg_connection *) ctx, buf, len);
  11473. MG_VERBOSE(("%lu n=%ld", ((struct mg_connection *) ctx)->id, n));
  11474. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  11475. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  11476. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_RECV_FAILED;
  11477. return (int) n;
  11478. }
  11479. void mg_tls_handshake(struct mg_connection *c) {
  11480. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11481. int rc = mbedtls_ssl_handshake(&tls->ssl);
  11482. if (rc == 0) { // Success
  11483. MG_DEBUG(("%lu success", c->id));
  11484. c->is_tls_hs = 0;
  11485. mg_call(c, MG_EV_TLS_HS, NULL);
  11486. } else if (rc == MBEDTLS_ERR_SSL_WANT_READ ||
  11487. rc == MBEDTLS_ERR_SSL_WANT_WRITE) { // Still pending
  11488. MG_VERBOSE(("%lu pending, %d%d %d (-%#x)", c->id, c->is_connecting,
  11489. c->is_tls_hs, rc, -rc));
  11490. } else {
  11491. mg_error(c, "TLS handshake: -%#x", -rc); // Error
  11492. }
  11493. }
  11494. static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) {
  11495. n = (int) strlen(s2) - 1;
  11496. MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2));
  11497. (void) s;
  11498. }
  11499. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  11500. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  11501. int rc = 0;
  11502. c->tls = tls;
  11503. if (c->tls == NULL) {
  11504. mg_error(c, "TLS OOM");
  11505. goto fail;
  11506. }
  11507. if (c->is_listening) goto fail;
  11508. MG_DEBUG(("%lu Setting TLS", c->id));
  11509. MG_PROF_ADD(c, "mbedtls_init_start");
  11510. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000 && \
  11511. defined(MBEDTLS_PSA_CRYPTO_C)
  11512. psa_crypto_init(); // https://github.com/Mbed-TLS/mbedtls/issues/9072#issuecomment-2084845711
  11513. #endif
  11514. mbedtls_ssl_init(&tls->ssl);
  11515. mbedtls_ssl_config_init(&tls->conf);
  11516. mbedtls_x509_crt_init(&tls->ca);
  11517. mbedtls_x509_crt_init(&tls->cert);
  11518. mbedtls_pk_init(&tls->pk);
  11519. mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c);
  11520. #if defined(MG_MBEDTLS_DEBUG_LEVEL)
  11521. mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL);
  11522. #endif
  11523. if ((rc = mbedtls_ssl_config_defaults(
  11524. &tls->conf,
  11525. c->is_client ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
  11526. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  11527. mg_error(c, "tls defaults %#x", -rc);
  11528. goto fail;
  11529. }
  11530. mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c);
  11531. if (opts->ca.len == 0 || mg_strcmp(opts->ca, mg_str("*")) == 0) {
  11532. // NOTE: MBEDTLS_SSL_VERIFY_NONE is not supported for TLS1.3 on client side
  11533. // See https://github.com/Mbed-TLS/mbedtls/issues/7075
  11534. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
  11535. } else {
  11536. if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail;
  11537. mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL);
  11538. if (c->is_client && opts->name.buf != NULL && opts->name.buf[0] != '\0') {
  11539. char *host = mg_mprintf("%.*s", opts->name.len, opts->name.buf);
  11540. mbedtls_ssl_set_hostname(&tls->ssl, host);
  11541. MG_DEBUG(("%lu hostname verification: %s", c->id, host));
  11542. free(host);
  11543. }
  11544. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  11545. }
  11546. if (!mg_load_cert(opts->cert, &tls->cert)) goto fail;
  11547. if (!mg_load_key(opts->key, &tls->pk)) goto fail;
  11548. if (tls->cert.version &&
  11549. (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) {
  11550. mg_error(c, "own cert %#x", -rc);
  11551. goto fail;
  11552. }
  11553. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  11554. mbedtls_ssl_conf_session_tickets_cb(
  11555. &tls->conf, mbedtls_ssl_ticket_write, mbedtls_ssl_ticket_parse,
  11556. &((struct mg_tls_ctx *) c->mgr->tls_ctx)->tickets);
  11557. #endif
  11558. if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) {
  11559. mg_error(c, "setup err %#x", -rc);
  11560. goto fail;
  11561. }
  11562. c->is_tls = 1;
  11563. c->is_tls_hs = 1;
  11564. mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0);
  11565. MG_PROF_ADD(c, "mbedtls_init_end");
  11566. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  11567. mg_tls_handshake(c);
  11568. }
  11569. return;
  11570. fail:
  11571. mg_tls_free(c);
  11572. }
  11573. size_t mg_tls_pending(struct mg_connection *c) {
  11574. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11575. return tls == NULL ? 0 : mbedtls_ssl_get_bytes_avail(&tls->ssl);
  11576. }
  11577. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  11578. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11579. long n = mbedtls_ssl_read(&tls->ssl, (unsigned char *) buf, len);
  11580. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  11581. return MG_IO_WAIT;
  11582. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  11583. if (n == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) {
  11584. return MG_IO_WAIT;
  11585. }
  11586. #endif
  11587. if (n <= 0) return MG_IO_ERR;
  11588. return n;
  11589. }
  11590. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  11591. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11592. long n = mbedtls_ssl_write(&tls->ssl, (unsigned char *) buf, len);
  11593. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  11594. return MG_IO_WAIT;
  11595. if (n <= 0) return MG_IO_ERR;
  11596. return n;
  11597. }
  11598. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  11599. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx));
  11600. if (ctx == NULL) {
  11601. MG_ERROR(("TLS context init OOM"));
  11602. } else {
  11603. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  11604. int rc;
  11605. mbedtls_ssl_ticket_init(&ctx->tickets);
  11606. if ((rc = mbedtls_ssl_ticket_setup(&ctx->tickets, mg_mbed_rng, NULL,
  11607. MBEDTLS_CIPHER_AES_128_GCM, 86400)) !=
  11608. 0) {
  11609. MG_ERROR((" mbedtls_ssl_ticket_setup %#x", -rc));
  11610. }
  11611. #endif
  11612. mgr->tls_ctx = ctx;
  11613. }
  11614. }
  11615. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  11616. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx;
  11617. if (ctx != NULL) {
  11618. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  11619. mbedtls_ssl_ticket_free(&ctx->tickets);
  11620. #endif
  11621. free(ctx);
  11622. mgr->tls_ctx = NULL;
  11623. }
  11624. }
  11625. #endif
  11626. #ifdef MG_ENABLE_LINES
  11627. #line 1 "src/tls_openssl.c"
  11628. #endif
  11629. #if MG_TLS == MG_TLS_OPENSSL || MG_TLS == MG_TLS_WOLFSSL
  11630. static int tls_err_cb(const char *s, size_t len, void *c) {
  11631. int n = (int) len - 1;
  11632. MG_ERROR(("%lu %.*s", ((struct mg_connection *) c)->id, n, s));
  11633. return 0; // undocumented
  11634. }
  11635. static int mg_tls_err(struct mg_connection *c, struct mg_tls *tls, int res) {
  11636. int err = SSL_get_error(tls->ssl, res);
  11637. // We've just fetched the last error from the queue.
  11638. // Now we need to clear the error queue. If we do not, then the following
  11639. // can happen (actually reported):
  11640. // - A new connection is accept()-ed with cert error (e.g. self-signed cert)
  11641. // - Since all accept()-ed connections share listener's context,
  11642. // - *ALL* SSL accepted connection report read error on the next poll cycle.
  11643. // Thus a single errored connection can close all the rest, unrelated ones.
  11644. // Clearing the error keeps the shared SSL_CTX in an OK state.
  11645. if (err != 0) ERR_print_errors_cb(tls_err_cb, c);
  11646. ERR_clear_error();
  11647. if (err == SSL_ERROR_WANT_READ) return 0;
  11648. if (err == SSL_ERROR_WANT_WRITE) return 0;
  11649. return err;
  11650. }
  11651. static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) {
  11652. BIO *bio = BIO_new_mem_buf(ca.buf, (int) ca.len);
  11653. STACK_OF(X509_INFO) *certs =
  11654. bio ? PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL) : NULL;
  11655. if (bio) BIO_free(bio);
  11656. return certs;
  11657. }
  11658. static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) {
  11659. int i;
  11660. X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx);
  11661. for (i = 0; i < sk_X509_INFO_num(certs); i++) {
  11662. X509_INFO *cert_info = sk_X509_INFO_value(certs, i);
  11663. if (cert_info->x509 && !X509_STORE_add_cert(cert_store, cert_info->x509))
  11664. return false;
  11665. }
  11666. return true;
  11667. }
  11668. static EVP_PKEY *load_key(struct mg_str s) {
  11669. BIO *bio = BIO_new_mem_buf(s.buf, (int) (long) s.len);
  11670. EVP_PKEY *key = bio ? PEM_read_bio_PrivateKey(bio, NULL, 0, NULL) : NULL;
  11671. if (bio) BIO_free(bio);
  11672. return key;
  11673. }
  11674. static X509 *load_cert(struct mg_str s) {
  11675. BIO *bio = BIO_new_mem_buf(s.buf, (int) (long) s.len);
  11676. X509 *cert = bio == NULL ? NULL
  11677. : s.buf[0] == '-'
  11678. ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM
  11679. : d2i_X509_bio(bio, NULL); // DER
  11680. if (bio) BIO_free(bio);
  11681. return cert;
  11682. }
  11683. static long mg_bio_ctrl(BIO *b, int cmd, long larg, void *pargs) {
  11684. long ret = 0;
  11685. if (cmd == BIO_CTRL_PUSH) ret = 1;
  11686. if (cmd == BIO_CTRL_POP) ret = 1;
  11687. if (cmd == BIO_CTRL_FLUSH) ret = 1;
  11688. #if MG_TLS == MG_TLS_OPENSSL
  11689. if (cmd == BIO_C_SET_NBIO) ret = 1;
  11690. #endif
  11691. // MG_DEBUG(("%d -> %ld", cmd, ret));
  11692. (void) b, (void) cmd, (void) larg, (void) pargs;
  11693. return ret;
  11694. }
  11695. static int mg_bio_read(BIO *bio, char *buf, int len) {
  11696. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  11697. long res = mg_io_recv(c, buf, (size_t) len);
  11698. // MG_DEBUG(("%p %d %ld", buf, len, res));
  11699. len = res > 0 ? (int) res : -1;
  11700. if (res == MG_IO_WAIT) BIO_set_retry_read(bio);
  11701. return len;
  11702. }
  11703. static int mg_bio_write(BIO *bio, const char *buf, int len) {
  11704. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  11705. long res = mg_io_send(c, buf, (size_t) len);
  11706. // MG_DEBUG(("%p %d %ld", buf, len, res));
  11707. len = res > 0 ? (int) res : -1;
  11708. if (res == MG_IO_WAIT) BIO_set_retry_write(bio);
  11709. return len;
  11710. }
  11711. #ifdef MG_TLS_SSLKEYLOGFILE
  11712. static void ssl_keylog_cb(const SSL *ssl, const char *line) {
  11713. char *keylogfile = getenv("SSLKEYLOGFILE");
  11714. if (keylogfile == NULL) {
  11715. return;
  11716. }
  11717. FILE *f = fopen(keylogfile, "a");
  11718. fprintf(f, "%s\n", line);
  11719. fflush(f);
  11720. fclose(f);
  11721. }
  11722. #endif
  11723. void mg_tls_free(struct mg_connection *c) {
  11724. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11725. if (tls == NULL) return;
  11726. SSL_free(tls->ssl);
  11727. SSL_CTX_free(tls->ctx);
  11728. BIO_meth_free(tls->bm);
  11729. free(tls);
  11730. c->tls = NULL;
  11731. }
  11732. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  11733. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  11734. const char *id = "mongoose";
  11735. static unsigned char s_initialised = 0;
  11736. BIO *bio = NULL;
  11737. int rc;
  11738. c->tls = tls;
  11739. if (tls == NULL) {
  11740. mg_error(c, "TLS OOM");
  11741. goto fail;
  11742. }
  11743. if (!s_initialised) {
  11744. SSL_library_init();
  11745. s_initialised++;
  11746. }
  11747. MG_DEBUG(("%lu Setting TLS", c->id));
  11748. tls->ctx = c->is_client ? SSL_CTX_new(TLS_client_method())
  11749. : SSL_CTX_new(TLS_server_method());
  11750. if (tls->ctx == NULL) {
  11751. mg_error(c, "SSL_CTX_new");
  11752. goto fail;
  11753. }
  11754. #ifdef MG_TLS_SSLKEYLOGFILE
  11755. SSL_CTX_set_keylog_callback(tls->ctx, ssl_keylog_cb);
  11756. #endif
  11757. if ((tls->ssl = SSL_new(tls->ctx)) == NULL) {
  11758. mg_error(c, "SSL_new");
  11759. goto fail;
  11760. }
  11761. SSL_set_session_id_context(tls->ssl, (const uint8_t *) id,
  11762. (unsigned) strlen(id));
  11763. // Disable deprecated protocols
  11764. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2);
  11765. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3);
  11766. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1);
  11767. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1);
  11768. #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION
  11769. SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION);
  11770. #endif
  11771. #ifdef MG_ENABLE_OPENSSL_CIPHER_SERVER_PREFERENCE
  11772. SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
  11773. #endif
  11774. #if MG_TLS == MG_TLS_WOLFSSL && !defined(OPENSSL_COMPATIBLE_DEFAULTS)
  11775. if (opts->ca.len == 0 || mg_strcmp(opts->ca, mg_str("*")) == 0) {
  11776. // Older versions require that either the CA is loaded or SSL_VERIFY_NONE
  11777. // explicitly set
  11778. SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, NULL);
  11779. }
  11780. #endif
  11781. if (opts->ca.buf != NULL && opts->ca.buf[0] != '\0') {
  11782. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  11783. NULL);
  11784. STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca);
  11785. rc = add_ca_certs(tls->ctx, certs);
  11786. sk_X509_INFO_pop_free(certs, X509_INFO_free);
  11787. if (!rc) {
  11788. mg_error(c, "CA err");
  11789. goto fail;
  11790. }
  11791. }
  11792. if (opts->cert.buf != NULL && opts->cert.buf[0] != '\0') {
  11793. X509 *cert = load_cert(opts->cert);
  11794. rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert);
  11795. X509_free(cert);
  11796. if (cert == NULL || rc != 1) {
  11797. mg_error(c, "CERT err %d", mg_tls_err(c, tls, rc));
  11798. goto fail;
  11799. }
  11800. }
  11801. if (opts->key.buf != NULL && opts->key.buf[0] != '\0') {
  11802. EVP_PKEY *key = load_key(opts->key);
  11803. rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key);
  11804. EVP_PKEY_free(key);
  11805. if (key == NULL || rc != 1) {
  11806. mg_error(c, "KEY err %d", mg_tls_err(c, tls, rc));
  11807. goto fail;
  11808. }
  11809. }
  11810. SSL_set_mode(tls->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  11811. #if MG_TLS == MG_TLS_OPENSSL && OPENSSL_VERSION_NUMBER > 0x10002000L
  11812. (void) SSL_set_ecdh_auto(tls->ssl, 1);
  11813. #endif
  11814. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  11815. if (opts->name.len > 0) {
  11816. char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.buf);
  11817. #if MG_TLS != MG_TLS_WOLFSSL || LIBWOLFSSL_VERSION_HEX >= 0x05005002
  11818. SSL_set1_host(tls->ssl, s);
  11819. #else
  11820. X509_VERIFY_PARAM_set1_host(SSL_get0_param(tls->ssl), s, 0);
  11821. #endif
  11822. SSL_set_tlsext_host_name(tls->ssl, s);
  11823. free(s);
  11824. }
  11825. #endif
  11826. #if MG_TLS == MG_TLS_WOLFSSL
  11827. tls->bm = BIO_meth_new(0, "bio_mg");
  11828. #else
  11829. tls->bm = BIO_meth_new(BIO_get_new_index() | BIO_TYPE_SOURCE_SINK, "bio_mg");
  11830. #endif
  11831. BIO_meth_set_write(tls->bm, mg_bio_write);
  11832. BIO_meth_set_read(tls->bm, mg_bio_read);
  11833. BIO_meth_set_ctrl(tls->bm, mg_bio_ctrl);
  11834. bio = BIO_new(tls->bm);
  11835. BIO_set_data(bio, c);
  11836. SSL_set_bio(tls->ssl, bio, bio);
  11837. c->is_tls = 1;
  11838. c->is_tls_hs = 1;
  11839. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  11840. mg_tls_handshake(c);
  11841. }
  11842. MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client"));
  11843. return;
  11844. fail:
  11845. mg_tls_free(c);
  11846. }
  11847. void mg_tls_handshake(struct mg_connection *c) {
  11848. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11849. int rc = c->is_client ? SSL_connect(tls->ssl) : SSL_accept(tls->ssl);
  11850. if (rc == 1) {
  11851. MG_DEBUG(("%lu success", c->id));
  11852. c->is_tls_hs = 0;
  11853. mg_call(c, MG_EV_TLS_HS, NULL);
  11854. } else {
  11855. int code = mg_tls_err(c, tls, rc);
  11856. if (code != 0) mg_error(c, "tls hs: rc %d, err %d", rc, code);
  11857. }
  11858. }
  11859. size_t mg_tls_pending(struct mg_connection *c) {
  11860. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11861. return tls == NULL ? 0 : (size_t) SSL_pending(tls->ssl);
  11862. }
  11863. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  11864. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11865. int n = SSL_read(tls->ssl, buf, (int) len);
  11866. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  11867. if (n <= 0) return MG_IO_ERR;
  11868. return n;
  11869. }
  11870. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  11871. struct mg_tls *tls = (struct mg_tls *) c->tls;
  11872. int n = SSL_write(tls->ssl, buf, (int) len);
  11873. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  11874. if (n <= 0) return MG_IO_ERR;
  11875. return n;
  11876. }
  11877. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  11878. (void) mgr;
  11879. }
  11880. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  11881. (void) mgr;
  11882. }
  11883. #endif
  11884. #ifdef MG_ENABLE_LINES
  11885. #line 1 "src/tls_uecc.c"
  11886. #endif
  11887. /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  11888. #if MG_TLS == MG_TLS_BUILTIN
  11889. #ifndef MG_UECC_RNG_MAX_TRIES
  11890. #define MG_UECC_RNG_MAX_TRIES 64
  11891. #endif
  11892. #if MG_UECC_ENABLE_VLI_API
  11893. #define MG_UECC_VLI_API
  11894. #else
  11895. #define MG_UECC_VLI_API static
  11896. #endif
  11897. #if (MG_UECC_PLATFORM == mg_uecc_avr) || (MG_UECC_PLATFORM == mg_uecc_arm) || \
  11898. (MG_UECC_PLATFORM == mg_uecc_arm_thumb) || \
  11899. (MG_UECC_PLATFORM == mg_uecc_arm_thumb2)
  11900. #define MG_UECC_CONCATX(a, ...) a##__VA_ARGS__
  11901. #define MG_UECC_CONCAT(a, ...) MG_UECC_CONCATX(a, __VA_ARGS__)
  11902. #define STRX(a) #a
  11903. #define STR(a) STRX(a)
  11904. #define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__))))
  11905. #define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__))))
  11906. #define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__))))
  11907. #define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__))))
  11908. #define EVAL4(...) __VA_ARGS__
  11909. #define DEC_1 0
  11910. #define DEC_2 1
  11911. #define DEC_3 2
  11912. #define DEC_4 3
  11913. #define DEC_5 4
  11914. #define DEC_6 5
  11915. #define DEC_7 6
  11916. #define DEC_8 7
  11917. #define DEC_9 8
  11918. #define DEC_10 9
  11919. #define DEC_11 10
  11920. #define DEC_12 11
  11921. #define DEC_13 12
  11922. #define DEC_14 13
  11923. #define DEC_15 14
  11924. #define DEC_16 15
  11925. #define DEC_17 16
  11926. #define DEC_18 17
  11927. #define DEC_19 18
  11928. #define DEC_20 19
  11929. #define DEC_21 20
  11930. #define DEC_22 21
  11931. #define DEC_23 22
  11932. #define DEC_24 23
  11933. #define DEC_25 24
  11934. #define DEC_26 25
  11935. #define DEC_27 26
  11936. #define DEC_28 27
  11937. #define DEC_29 28
  11938. #define DEC_30 29
  11939. #define DEC_31 30
  11940. #define DEC_32 31
  11941. #define DEC(N) MG_UECC_CONCAT(DEC_, N)
  11942. #define SECOND_ARG(_, val, ...) val
  11943. #define SOME_CHECK_0 ~, 0
  11944. #define GET_SECOND_ARG(...) SECOND_ARG(__VA_ARGS__, SOME, )
  11945. #define SOME_OR_0(N) GET_SECOND_ARG(MG_UECC_CONCAT(SOME_CHECK_, N))
  11946. #define MG_UECC_EMPTY(...)
  11947. #define DEFER(...) __VA_ARGS__ MG_UECC_EMPTY()
  11948. #define REPEAT_NAME_0() REPEAT_0
  11949. #define REPEAT_NAME_SOME() REPEAT_SOME
  11950. #define REPEAT_0(...)
  11951. #define REPEAT_SOME(N, stuff) \
  11952. DEFER(MG_UECC_CONCAT(REPEAT_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), stuff) stuff
  11953. #define REPEAT(N, stuff) EVAL(REPEAT_SOME(N, stuff))
  11954. #define REPEATM_NAME_0() REPEATM_0
  11955. #define REPEATM_NAME_SOME() REPEATM_SOME
  11956. #define REPEATM_0(...)
  11957. #define REPEATM_SOME(N, macro) \
  11958. macro(N) DEFER(MG_UECC_CONCAT(REPEATM_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), macro)
  11959. #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro))
  11960. #endif
  11961. //
  11962. #if (MG_UECC_WORD_SIZE == 1)
  11963. #if MG_UECC_SUPPORTS_secp160r1
  11964. #define MG_UECC_MAX_WORDS 21 /* Due to the size of curve_n. */
  11965. #endif
  11966. #if MG_UECC_SUPPORTS_secp192r1
  11967. #undef MG_UECC_MAX_WORDS
  11968. #define MG_UECC_MAX_WORDS 24
  11969. #endif
  11970. #if MG_UECC_SUPPORTS_secp224r1
  11971. #undef MG_UECC_MAX_WORDS
  11972. #define MG_UECC_MAX_WORDS 28
  11973. #endif
  11974. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  11975. #undef MG_UECC_MAX_WORDS
  11976. #define MG_UECC_MAX_WORDS 32
  11977. #endif
  11978. #elif (MG_UECC_WORD_SIZE == 4)
  11979. #if MG_UECC_SUPPORTS_secp160r1
  11980. #define MG_UECC_MAX_WORDS 6 /* Due to the size of curve_n. */
  11981. #endif
  11982. #if MG_UECC_SUPPORTS_secp192r1
  11983. #undef MG_UECC_MAX_WORDS
  11984. #define MG_UECC_MAX_WORDS 6
  11985. #endif
  11986. #if MG_UECC_SUPPORTS_secp224r1
  11987. #undef MG_UECC_MAX_WORDS
  11988. #define MG_UECC_MAX_WORDS 7
  11989. #endif
  11990. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  11991. #undef MG_UECC_MAX_WORDS
  11992. #define MG_UECC_MAX_WORDS 8
  11993. #endif
  11994. #elif (MG_UECC_WORD_SIZE == 8)
  11995. #if MG_UECC_SUPPORTS_secp160r1
  11996. #define MG_UECC_MAX_WORDS 3
  11997. #endif
  11998. #if MG_UECC_SUPPORTS_secp192r1
  11999. #undef MG_UECC_MAX_WORDS
  12000. #define MG_UECC_MAX_WORDS 3
  12001. #endif
  12002. #if MG_UECC_SUPPORTS_secp224r1
  12003. #undef MG_UECC_MAX_WORDS
  12004. #define MG_UECC_MAX_WORDS 4
  12005. #endif
  12006. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  12007. #undef MG_UECC_MAX_WORDS
  12008. #define MG_UECC_MAX_WORDS 4
  12009. #endif
  12010. #endif /* MG_UECC_WORD_SIZE */
  12011. #define BITS_TO_WORDS(num_bits) \
  12012. ((wordcount_t) ((num_bits + ((MG_UECC_WORD_SIZE * 8) - 1)) / \
  12013. (MG_UECC_WORD_SIZE * 8)))
  12014. #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
  12015. struct MG_UECC_Curve_t {
  12016. wordcount_t num_words;
  12017. wordcount_t num_bytes;
  12018. bitcount_t num_n_bits;
  12019. mg_uecc_word_t p[MG_UECC_MAX_WORDS];
  12020. mg_uecc_word_t n[MG_UECC_MAX_WORDS];
  12021. mg_uecc_word_t G[MG_UECC_MAX_WORDS * 2];
  12022. mg_uecc_word_t b[MG_UECC_MAX_WORDS];
  12023. void (*double_jacobian)(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12024. mg_uecc_word_t *Z1, MG_UECC_Curve curve);
  12025. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12026. void (*mod_sqrt)(mg_uecc_word_t *a, MG_UECC_Curve curve);
  12027. #endif
  12028. void (*x_side)(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  12029. MG_UECC_Curve curve);
  12030. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12031. void (*mmod_fast)(mg_uecc_word_t *result, mg_uecc_word_t *product);
  12032. #endif
  12033. };
  12034. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12035. static void bcopy(uint8_t *dst, const uint8_t *src, unsigned num_bytes) {
  12036. while (0 != num_bytes) {
  12037. num_bytes--;
  12038. dst[num_bytes] = src[num_bytes];
  12039. }
  12040. }
  12041. #endif
  12042. static cmpresult_t mg_uecc_vli_cmp_unsafe(const mg_uecc_word_t *left,
  12043. const mg_uecc_word_t *right,
  12044. wordcount_t num_words);
  12045. #if (MG_UECC_PLATFORM == mg_uecc_arm || \
  12046. MG_UECC_PLATFORM == mg_uecc_arm_thumb || \
  12047. MG_UECC_PLATFORM == mg_uecc_arm_thumb2)
  12048. #endif
  12049. #if (MG_UECC_PLATFORM == mg_uecc_avr)
  12050. #endif
  12051. #ifndef asm_clear
  12052. #define asm_clear 0
  12053. #endif
  12054. #ifndef asm_set
  12055. #define asm_set 0
  12056. #endif
  12057. #ifndef asm_add
  12058. #define asm_add 0
  12059. #endif
  12060. #ifndef asm_sub
  12061. #define asm_sub 0
  12062. #endif
  12063. #ifndef asm_mult
  12064. #define asm_mult 0
  12065. #endif
  12066. #ifndef asm_rshift1
  12067. #define asm_rshift1 0
  12068. #endif
  12069. #ifndef asm_mmod_fast_secp256r1
  12070. #define asm_mmod_fast_secp256r1 0
  12071. #endif
  12072. #if defined(default_RNG_defined) && default_RNG_defined
  12073. static MG_UECC_RNG_Function g_rng_function = &default_RNG;
  12074. #else
  12075. static MG_UECC_RNG_Function g_rng_function = 0;
  12076. #endif
  12077. void mg_uecc_set_rng(MG_UECC_RNG_Function rng_function) {
  12078. g_rng_function = rng_function;
  12079. }
  12080. MG_UECC_RNG_Function mg_uecc_get_rng(void) {
  12081. return g_rng_function;
  12082. }
  12083. int mg_uecc_curve_private_key_size(MG_UECC_Curve curve) {
  12084. return BITS_TO_BYTES(curve->num_n_bits);
  12085. }
  12086. int mg_uecc_curve_public_key_size(MG_UECC_Curve curve) {
  12087. return 2 * curve->num_bytes;
  12088. }
  12089. #if !asm_clear
  12090. MG_UECC_VLI_API void mg_uecc_vli_clear(mg_uecc_word_t *vli,
  12091. wordcount_t num_words) {
  12092. wordcount_t i;
  12093. for (i = 0; i < num_words; ++i) {
  12094. vli[i] = 0;
  12095. }
  12096. }
  12097. #endif /* !asm_clear */
  12098. /* Constant-time comparison to zero - secure way to compare long integers */
  12099. /* Returns 1 if vli == 0, 0 otherwise. */
  12100. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_isZero(const mg_uecc_word_t *vli,
  12101. wordcount_t num_words) {
  12102. mg_uecc_word_t bits = 0;
  12103. wordcount_t i;
  12104. for (i = 0; i < num_words; ++i) {
  12105. bits |= vli[i];
  12106. }
  12107. return (bits == 0);
  12108. }
  12109. /* Returns nonzero if bit 'bit' of vli is set. */
  12110. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_testBit(const mg_uecc_word_t *vli,
  12111. bitcount_t bit) {
  12112. return (vli[bit >> MG_UECC_WORD_BITS_SHIFT] &
  12113. ((mg_uecc_word_t) 1 << (bit & MG_UECC_WORD_BITS_MASK)));
  12114. }
  12115. /* Counts the number of words in vli. */
  12116. static wordcount_t vli_numDigits(const mg_uecc_word_t *vli,
  12117. const wordcount_t max_words) {
  12118. wordcount_t i;
  12119. /* Search from the end until we find a non-zero digit.
  12120. We do it in reverse because we expect that most digits will be nonzero. */
  12121. for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
  12122. }
  12123. return (i + 1);
  12124. }
  12125. /* Counts the number of bits required to represent vli. */
  12126. MG_UECC_VLI_API bitcount_t mg_uecc_vli_numBits(const mg_uecc_word_t *vli,
  12127. const wordcount_t max_words) {
  12128. mg_uecc_word_t i;
  12129. mg_uecc_word_t digit;
  12130. wordcount_t num_digits = vli_numDigits(vli, max_words);
  12131. if (num_digits == 0) {
  12132. return 0;
  12133. }
  12134. digit = vli[num_digits - 1];
  12135. for (i = 0; digit; ++i) {
  12136. digit >>= 1;
  12137. }
  12138. return (((bitcount_t) ((num_digits - 1) << MG_UECC_WORD_BITS_SHIFT)) +
  12139. (bitcount_t) i);
  12140. }
  12141. /* Sets dest = src. */
  12142. #if !asm_set
  12143. MG_UECC_VLI_API void mg_uecc_vli_set(mg_uecc_word_t *dest,
  12144. const mg_uecc_word_t *src,
  12145. wordcount_t num_words) {
  12146. wordcount_t i;
  12147. for (i = 0; i < num_words; ++i) {
  12148. dest[i] = src[i];
  12149. }
  12150. }
  12151. #endif /* !asm_set */
  12152. /* Returns sign of left - right. */
  12153. static cmpresult_t mg_uecc_vli_cmp_unsafe(const mg_uecc_word_t *left,
  12154. const mg_uecc_word_t *right,
  12155. wordcount_t num_words) {
  12156. wordcount_t i;
  12157. for (i = num_words - 1; i >= 0; --i) {
  12158. if (left[i] > right[i]) {
  12159. return 1;
  12160. } else if (left[i] < right[i]) {
  12161. return -1;
  12162. }
  12163. }
  12164. return 0;
  12165. }
  12166. /* Constant-time comparison function - secure way to compare long integers */
  12167. /* Returns one if left == right, zero otherwise. */
  12168. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_equal(const mg_uecc_word_t *left,
  12169. const mg_uecc_word_t *right,
  12170. wordcount_t num_words) {
  12171. mg_uecc_word_t diff = 0;
  12172. wordcount_t i;
  12173. for (i = num_words - 1; i >= 0; --i) {
  12174. diff |= (left[i] ^ right[i]);
  12175. }
  12176. return (diff == 0);
  12177. }
  12178. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_sub(mg_uecc_word_t *result,
  12179. const mg_uecc_word_t *left,
  12180. const mg_uecc_word_t *right,
  12181. wordcount_t num_words);
  12182. /* Returns sign of left - right, in constant time. */
  12183. MG_UECC_VLI_API cmpresult_t mg_uecc_vli_cmp(const mg_uecc_word_t *left,
  12184. const mg_uecc_word_t *right,
  12185. wordcount_t num_words) {
  12186. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  12187. mg_uecc_word_t neg = !!mg_uecc_vli_sub(tmp, left, right, num_words);
  12188. mg_uecc_word_t equal = mg_uecc_vli_isZero(tmp, num_words);
  12189. return (cmpresult_t) (!equal - 2 * neg);
  12190. }
  12191. /* Computes vli = vli >> 1. */
  12192. #if !asm_rshift1
  12193. MG_UECC_VLI_API void mg_uecc_vli_rshift1(mg_uecc_word_t *vli,
  12194. wordcount_t num_words) {
  12195. mg_uecc_word_t *end = vli;
  12196. mg_uecc_word_t carry = 0;
  12197. vli += num_words;
  12198. while (vli-- > end) {
  12199. mg_uecc_word_t temp = *vli;
  12200. *vli = (temp >> 1) | carry;
  12201. carry = temp << (MG_UECC_WORD_BITS - 1);
  12202. }
  12203. }
  12204. #endif /* !asm_rshift1 */
  12205. /* Computes result = left + right, returning carry. Can modify in place. */
  12206. #if !asm_add
  12207. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_add(mg_uecc_word_t *result,
  12208. const mg_uecc_word_t *left,
  12209. const mg_uecc_word_t *right,
  12210. wordcount_t num_words) {
  12211. mg_uecc_word_t carry = 0;
  12212. wordcount_t i;
  12213. for (i = 0; i < num_words; ++i) {
  12214. mg_uecc_word_t sum = left[i] + right[i] + carry;
  12215. if (sum != left[i]) {
  12216. carry = (sum < left[i]);
  12217. }
  12218. result[i] = sum;
  12219. }
  12220. return carry;
  12221. }
  12222. #endif /* !asm_add */
  12223. /* Computes result = left - right, returning borrow. Can modify in place. */
  12224. #if !asm_sub
  12225. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_sub(mg_uecc_word_t *result,
  12226. const mg_uecc_word_t *left,
  12227. const mg_uecc_word_t *right,
  12228. wordcount_t num_words) {
  12229. mg_uecc_word_t borrow = 0;
  12230. wordcount_t i;
  12231. for (i = 0; i < num_words; ++i) {
  12232. mg_uecc_word_t diff = left[i] - right[i] - borrow;
  12233. if (diff != left[i]) {
  12234. borrow = (diff > left[i]);
  12235. }
  12236. result[i] = diff;
  12237. }
  12238. return borrow;
  12239. }
  12240. #endif /* !asm_sub */
  12241. #if !asm_mult || (MG_UECC_SQUARE_FUNC && !asm_square) || \
  12242. (MG_UECC_SUPPORTS_secp256k1 && (MG_UECC_OPTIMIZATION_LEVEL > 0) && \
  12243. ((MG_UECC_WORD_SIZE == 1) || (MG_UECC_WORD_SIZE == 8)))
  12244. static void muladd(mg_uecc_word_t a, mg_uecc_word_t b, mg_uecc_word_t *r0,
  12245. mg_uecc_word_t *r1, mg_uecc_word_t *r2) {
  12246. #if MG_UECC_WORD_SIZE == 8
  12247. uint64_t a0 = a & 0xffffffff;
  12248. uint64_t a1 = a >> 32;
  12249. uint64_t b0 = b & 0xffffffff;
  12250. uint64_t b1 = b >> 32;
  12251. uint64_t i0 = a0 * b0;
  12252. uint64_t i1 = a0 * b1;
  12253. uint64_t i2 = a1 * b0;
  12254. uint64_t i3 = a1 * b1;
  12255. uint64_t p0, p1;
  12256. i2 += (i0 >> 32);
  12257. i2 += i1;
  12258. if (i2 < i1) { /* overflow */
  12259. i3 += 0x100000000;
  12260. }
  12261. p0 = (i0 & 0xffffffff) | (i2 << 32);
  12262. p1 = i3 + (i2 >> 32);
  12263. *r0 += p0;
  12264. *r1 += (p1 + (*r0 < p0));
  12265. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  12266. #else
  12267. mg_uecc_dword_t p = (mg_uecc_dword_t) a * b;
  12268. mg_uecc_dword_t r01 = ((mg_uecc_dword_t) (*r1) << MG_UECC_WORD_BITS) | *r0;
  12269. r01 += p;
  12270. *r2 += (r01 < p);
  12271. *r1 = (mg_uecc_word_t) (r01 >> MG_UECC_WORD_BITS);
  12272. *r0 = (mg_uecc_word_t) r01;
  12273. #endif
  12274. }
  12275. #endif /* muladd needed */
  12276. #if !asm_mult
  12277. MG_UECC_VLI_API void mg_uecc_vli_mult(mg_uecc_word_t *result,
  12278. const mg_uecc_word_t *left,
  12279. const mg_uecc_word_t *right,
  12280. wordcount_t num_words) {
  12281. mg_uecc_word_t r0 = 0;
  12282. mg_uecc_word_t r1 = 0;
  12283. mg_uecc_word_t r2 = 0;
  12284. wordcount_t i, k;
  12285. /* Compute each digit of result in sequence, maintaining the carries. */
  12286. for (k = 0; k < num_words; ++k) {
  12287. for (i = 0; i <= k; ++i) {
  12288. muladd(left[i], right[k - i], &r0, &r1, &r2);
  12289. }
  12290. result[k] = r0;
  12291. r0 = r1;
  12292. r1 = r2;
  12293. r2 = 0;
  12294. }
  12295. for (k = num_words; k < num_words * 2 - 1; ++k) {
  12296. for (i = (wordcount_t) ((k + 1) - num_words); i < num_words; ++i) {
  12297. muladd(left[i], right[k - i], &r0, &r1, &r2);
  12298. }
  12299. result[k] = r0;
  12300. r0 = r1;
  12301. r1 = r2;
  12302. r2 = 0;
  12303. }
  12304. result[num_words * 2 - 1] = r0;
  12305. }
  12306. #endif /* !asm_mult */
  12307. #if MG_UECC_SQUARE_FUNC
  12308. #if !asm_square
  12309. static void mul2add(mg_uecc_word_t a, mg_uecc_word_t b, mg_uecc_word_t *r0,
  12310. mg_uecc_word_t *r1, mg_uecc_word_t *r2) {
  12311. #if MG_UECC_WORD_SIZE == 8
  12312. uint64_t a0 = a & 0xffffffffull;
  12313. uint64_t a1 = a >> 32;
  12314. uint64_t b0 = b & 0xffffffffull;
  12315. uint64_t b1 = b >> 32;
  12316. uint64_t i0 = a0 * b0;
  12317. uint64_t i1 = a0 * b1;
  12318. uint64_t i2 = a1 * b0;
  12319. uint64_t i3 = a1 * b1;
  12320. uint64_t p0, p1;
  12321. i2 += (i0 >> 32);
  12322. i2 += i1;
  12323. if (i2 < i1) { /* overflow */
  12324. i3 += 0x100000000ull;
  12325. }
  12326. p0 = (i0 & 0xffffffffull) | (i2 << 32);
  12327. p1 = i3 + (i2 >> 32);
  12328. *r2 += (p1 >> 63);
  12329. p1 = (p1 << 1) | (p0 >> 63);
  12330. p0 <<= 1;
  12331. *r0 += p0;
  12332. *r1 += (p1 + (*r0 < p0));
  12333. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  12334. #else
  12335. mg_uecc_dword_t p = (mg_uecc_dword_t) a * b;
  12336. mg_uecc_dword_t r01 = ((mg_uecc_dword_t) (*r1) << MG_UECC_WORD_BITS) | *r0;
  12337. *r2 += (p >> (MG_UECC_WORD_BITS * 2 - 1));
  12338. p *= 2;
  12339. r01 += p;
  12340. *r2 += (r01 < p);
  12341. *r1 = r01 >> MG_UECC_WORD_BITS;
  12342. *r0 = (mg_uecc_word_t) r01;
  12343. #endif
  12344. }
  12345. MG_UECC_VLI_API void mg_uecc_vli_square(mg_uecc_word_t *result,
  12346. const mg_uecc_word_t *left,
  12347. wordcount_t num_words) {
  12348. mg_uecc_word_t r0 = 0;
  12349. mg_uecc_word_t r1 = 0;
  12350. mg_uecc_word_t r2 = 0;
  12351. wordcount_t i, k;
  12352. for (k = 0; k < num_words * 2 - 1; ++k) {
  12353. mg_uecc_word_t min = (k < num_words ? 0 : (k + 1) - num_words);
  12354. for (i = min; i <= k && i <= k - i; ++i) {
  12355. if (i < k - i) {
  12356. mul2add(left[i], left[k - i], &r0, &r1, &r2);
  12357. } else {
  12358. muladd(left[i], left[k - i], &r0, &r1, &r2);
  12359. }
  12360. }
  12361. result[k] = r0;
  12362. r0 = r1;
  12363. r1 = r2;
  12364. r2 = 0;
  12365. }
  12366. result[num_words * 2 - 1] = r0;
  12367. }
  12368. #endif /* !asm_square */
  12369. #else /* MG_UECC_SQUARE_FUNC */
  12370. #if MG_UECC_ENABLE_VLI_API
  12371. MG_UECC_VLI_API void mg_uecc_vli_square(mg_uecc_word_t *result,
  12372. const mg_uecc_word_t *left,
  12373. wordcount_t num_words) {
  12374. mg_uecc_vli_mult(result, left, left, num_words);
  12375. }
  12376. #endif /* MG_UECC_ENABLE_VLI_API */
  12377. #endif /* MG_UECC_SQUARE_FUNC */
  12378. /* Computes result = (left + right) % mod.
  12379. Assumes that left < mod and right < mod, and that result does not overlap
  12380. mod. */
  12381. MG_UECC_VLI_API void mg_uecc_vli_modAdd(mg_uecc_word_t *result,
  12382. const mg_uecc_word_t *left,
  12383. const mg_uecc_word_t *right,
  12384. const mg_uecc_word_t *mod,
  12385. wordcount_t num_words) {
  12386. mg_uecc_word_t carry = mg_uecc_vli_add(result, left, right, num_words);
  12387. if (carry || mg_uecc_vli_cmp_unsafe(mod, result, num_words) != 1) {
  12388. /* result > mod (result = mod + remainder), so subtract mod to get
  12389. * remainder. */
  12390. mg_uecc_vli_sub(result, result, mod, num_words);
  12391. }
  12392. }
  12393. /* Computes result = (left - right) % mod.
  12394. Assumes that left < mod and right < mod, and that result does not overlap
  12395. mod. */
  12396. MG_UECC_VLI_API void mg_uecc_vli_modSub(mg_uecc_word_t *result,
  12397. const mg_uecc_word_t *left,
  12398. const mg_uecc_word_t *right,
  12399. const mg_uecc_word_t *mod,
  12400. wordcount_t num_words) {
  12401. mg_uecc_word_t l_borrow = mg_uecc_vli_sub(result, left, right, num_words);
  12402. if (l_borrow) {
  12403. /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
  12404. we can get the correct result from result + mod (with overflow). */
  12405. mg_uecc_vli_add(result, result, mod, num_words);
  12406. }
  12407. }
  12408. /* Computes result = product % mod, where product is 2N words long. */
  12409. /* Currently only designed to work for curve_p or curve_n. */
  12410. MG_UECC_VLI_API void mg_uecc_vli_mmod(mg_uecc_word_t *result,
  12411. mg_uecc_word_t *product,
  12412. const mg_uecc_word_t *mod,
  12413. wordcount_t num_words) {
  12414. mg_uecc_word_t mod_multiple[2 * MG_UECC_MAX_WORDS];
  12415. mg_uecc_word_t tmp[2 * MG_UECC_MAX_WORDS];
  12416. mg_uecc_word_t *v[2] = {tmp, product};
  12417. mg_uecc_word_t index;
  12418. /* Shift mod so its highest set bit is at the maximum position. */
  12419. bitcount_t shift = (bitcount_t) ((num_words * 2 * MG_UECC_WORD_BITS) -
  12420. mg_uecc_vli_numBits(mod, num_words));
  12421. wordcount_t word_shift = (wordcount_t) (shift / MG_UECC_WORD_BITS);
  12422. wordcount_t bit_shift = (wordcount_t) (shift % MG_UECC_WORD_BITS);
  12423. mg_uecc_word_t carry = 0;
  12424. mg_uecc_vli_clear(mod_multiple, word_shift);
  12425. if (bit_shift > 0) {
  12426. for (index = 0; index < (mg_uecc_word_t) num_words; ++index) {
  12427. mod_multiple[(mg_uecc_word_t) word_shift + index] =
  12428. (mg_uecc_word_t) (mod[index] << bit_shift) | carry;
  12429. carry = mod[index] >> (MG_UECC_WORD_BITS - bit_shift);
  12430. }
  12431. } else {
  12432. mg_uecc_vli_set(mod_multiple + word_shift, mod, num_words);
  12433. }
  12434. for (index = 1; shift >= 0; --shift) {
  12435. mg_uecc_word_t borrow = 0;
  12436. wordcount_t i;
  12437. for (i = 0; i < num_words * 2; ++i) {
  12438. mg_uecc_word_t diff = v[index][i] - mod_multiple[i] - borrow;
  12439. if (diff != v[index][i]) {
  12440. borrow = (diff > v[index][i]);
  12441. }
  12442. v[1 - index][i] = diff;
  12443. }
  12444. index = !(index ^ borrow); /* Swap the index if there was no borrow */
  12445. mg_uecc_vli_rshift1(mod_multiple, num_words);
  12446. mod_multiple[num_words - 1] |= mod_multiple[num_words]
  12447. << (MG_UECC_WORD_BITS - 1);
  12448. mg_uecc_vli_rshift1(mod_multiple + num_words, num_words);
  12449. }
  12450. mg_uecc_vli_set(result, v[index], num_words);
  12451. }
  12452. /* Computes result = (left * right) % mod. */
  12453. MG_UECC_VLI_API void mg_uecc_vli_modMult(mg_uecc_word_t *result,
  12454. const mg_uecc_word_t *left,
  12455. const mg_uecc_word_t *right,
  12456. const mg_uecc_word_t *mod,
  12457. wordcount_t num_words) {
  12458. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  12459. mg_uecc_vli_mult(product, left, right, num_words);
  12460. mg_uecc_vli_mmod(result, product, mod, num_words);
  12461. }
  12462. MG_UECC_VLI_API void mg_uecc_vli_modMult_fast(mg_uecc_word_t *result,
  12463. const mg_uecc_word_t *left,
  12464. const mg_uecc_word_t *right,
  12465. MG_UECC_Curve curve) {
  12466. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  12467. mg_uecc_vli_mult(product, left, right, curve->num_words);
  12468. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12469. curve->mmod_fast(result, product);
  12470. #else
  12471. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  12472. #endif
  12473. }
  12474. #if MG_UECC_SQUARE_FUNC
  12475. #if MG_UECC_ENABLE_VLI_API
  12476. /* Computes result = left^2 % mod. */
  12477. MG_UECC_VLI_API void mg_uecc_vli_modSquare(mg_uecc_word_t *result,
  12478. const mg_uecc_word_t *left,
  12479. const mg_uecc_word_t *mod,
  12480. wordcount_t num_words) {
  12481. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  12482. mg_uecc_vli_square(product, left, num_words);
  12483. mg_uecc_vli_mmod(result, product, mod, num_words);
  12484. }
  12485. #endif /* MG_UECC_ENABLE_VLI_API */
  12486. MG_UECC_VLI_API void mg_uecc_vli_modSquare_fast(mg_uecc_word_t *result,
  12487. const mg_uecc_word_t *left,
  12488. MG_UECC_Curve curve) {
  12489. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  12490. mg_uecc_vli_square(product, left, curve->num_words);
  12491. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12492. curve->mmod_fast(result, product);
  12493. #else
  12494. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  12495. #endif
  12496. }
  12497. #else /* MG_UECC_SQUARE_FUNC */
  12498. #if MG_UECC_ENABLE_VLI_API
  12499. MG_UECC_VLI_API void mg_uecc_vli_modSquare(mg_uecc_word_t *result,
  12500. const mg_uecc_word_t *left,
  12501. const mg_uecc_word_t *mod,
  12502. wordcount_t num_words) {
  12503. mg_uecc_vli_modMult(result, left, left, mod, num_words);
  12504. }
  12505. #endif /* MG_UECC_ENABLE_VLI_API */
  12506. MG_UECC_VLI_API void mg_uecc_vli_modSquare_fast(mg_uecc_word_t *result,
  12507. const mg_uecc_word_t *left,
  12508. MG_UECC_Curve curve) {
  12509. mg_uecc_vli_modMult_fast(result, left, left, curve);
  12510. }
  12511. #endif /* MG_UECC_SQUARE_FUNC */
  12512. #define EVEN(vli) (!(vli[0] & 1))
  12513. static void vli_modInv_update(mg_uecc_word_t *uv, const mg_uecc_word_t *mod,
  12514. wordcount_t num_words) {
  12515. mg_uecc_word_t carry = 0;
  12516. if (!EVEN(uv)) {
  12517. carry = mg_uecc_vli_add(uv, uv, mod, num_words);
  12518. }
  12519. mg_uecc_vli_rshift1(uv, num_words);
  12520. if (carry) {
  12521. uv[num_words - 1] |= HIGH_BIT_SET;
  12522. }
  12523. }
  12524. /* Computes result = (1 / input) % mod. All VLIs are the same size.
  12525. See "From Euclid's GCD to Montgomery Multiplication to the Great Divide" */
  12526. MG_UECC_VLI_API void mg_uecc_vli_modInv(mg_uecc_word_t *result,
  12527. const mg_uecc_word_t *input,
  12528. const mg_uecc_word_t *mod,
  12529. wordcount_t num_words) {
  12530. mg_uecc_word_t a[MG_UECC_MAX_WORDS], b[MG_UECC_MAX_WORDS],
  12531. u[MG_UECC_MAX_WORDS], v[MG_UECC_MAX_WORDS];
  12532. cmpresult_t cmpResult;
  12533. if (mg_uecc_vli_isZero(input, num_words)) {
  12534. mg_uecc_vli_clear(result, num_words);
  12535. return;
  12536. }
  12537. mg_uecc_vli_set(a, input, num_words);
  12538. mg_uecc_vli_set(b, mod, num_words);
  12539. mg_uecc_vli_clear(u, num_words);
  12540. u[0] = 1;
  12541. mg_uecc_vli_clear(v, num_words);
  12542. while ((cmpResult = mg_uecc_vli_cmp_unsafe(a, b, num_words)) != 0) {
  12543. if (EVEN(a)) {
  12544. mg_uecc_vli_rshift1(a, num_words);
  12545. vli_modInv_update(u, mod, num_words);
  12546. } else if (EVEN(b)) {
  12547. mg_uecc_vli_rshift1(b, num_words);
  12548. vli_modInv_update(v, mod, num_words);
  12549. } else if (cmpResult > 0) {
  12550. mg_uecc_vli_sub(a, a, b, num_words);
  12551. mg_uecc_vli_rshift1(a, num_words);
  12552. if (mg_uecc_vli_cmp_unsafe(u, v, num_words) < 0) {
  12553. mg_uecc_vli_add(u, u, mod, num_words);
  12554. }
  12555. mg_uecc_vli_sub(u, u, v, num_words);
  12556. vli_modInv_update(u, mod, num_words);
  12557. } else {
  12558. mg_uecc_vli_sub(b, b, a, num_words);
  12559. mg_uecc_vli_rshift1(b, num_words);
  12560. if (mg_uecc_vli_cmp_unsafe(v, u, num_words) < 0) {
  12561. mg_uecc_vli_add(v, v, mod, num_words);
  12562. }
  12563. mg_uecc_vli_sub(v, v, u, num_words);
  12564. vli_modInv_update(v, mod, num_words);
  12565. }
  12566. }
  12567. mg_uecc_vli_set(result, u, num_words);
  12568. }
  12569. /* ------ Point operations ------ */
  12570. /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  12571. #ifndef _UECC_CURVE_SPECIFIC_H_
  12572. #define _UECC_CURVE_SPECIFIC_H_
  12573. #define num_bytes_secp160r1 20
  12574. #define num_bytes_secp192r1 24
  12575. #define num_bytes_secp224r1 28
  12576. #define num_bytes_secp256r1 32
  12577. #define num_bytes_secp256k1 32
  12578. #if (MG_UECC_WORD_SIZE == 1)
  12579. #define num_words_secp160r1 20
  12580. #define num_words_secp192r1 24
  12581. #define num_words_secp224r1 28
  12582. #define num_words_secp256r1 32
  12583. #define num_words_secp256k1 32
  12584. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) \
  12585. 0x##a, 0x##b, 0x##c, 0x##d, 0x##e, 0x##f, 0x##g, 0x##h
  12586. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##a, 0x##b, 0x##c, 0x##d
  12587. #elif (MG_UECC_WORD_SIZE == 4)
  12588. #define num_words_secp160r1 5
  12589. #define num_words_secp192r1 6
  12590. #define num_words_secp224r1 7
  12591. #define num_words_secp256r1 8
  12592. #define num_words_secp256k1 8
  12593. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
  12594. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
  12595. #elif (MG_UECC_WORD_SIZE == 8)
  12596. #define num_words_secp160r1 3
  12597. #define num_words_secp192r1 3
  12598. #define num_words_secp224r1 4
  12599. #define num_words_secp256r1 4
  12600. #define num_words_secp256k1 4
  12601. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##h##g##f##e##d##c##b##a##U
  12602. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a##U
  12603. #endif /* MG_UECC_WORD_SIZE */
  12604. #if MG_UECC_SUPPORTS_secp160r1 || MG_UECC_SUPPORTS_secp192r1 || \
  12605. MG_UECC_SUPPORTS_secp224r1 || MG_UECC_SUPPORTS_secp256r1
  12606. static void double_jacobian_default(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12607. mg_uecc_word_t *Z1, MG_UECC_Curve curve) {
  12608. /* t1 = X, t2 = Y, t3 = Z */
  12609. mg_uecc_word_t t4[MG_UECC_MAX_WORDS];
  12610. mg_uecc_word_t t5[MG_UECC_MAX_WORDS];
  12611. wordcount_t num_words = curve->num_words;
  12612. if (mg_uecc_vli_isZero(Z1, num_words)) {
  12613. return;
  12614. }
  12615. mg_uecc_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */
  12616. mg_uecc_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
  12617. mg_uecc_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */
  12618. mg_uecc_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
  12619. mg_uecc_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */
  12620. mg_uecc_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
  12621. mg_uecc_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
  12622. mg_uecc_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
  12623. mg_uecc_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */
  12624. mg_uecc_vli_modAdd(Z1, X1, X1, curve->p,
  12625. num_words); /* t3 = 2*(x1^2 - z1^4) */
  12626. mg_uecc_vli_modAdd(X1, X1, Z1, curve->p,
  12627. num_words); /* t1 = 3*(x1^2 - z1^4) */
  12628. if (mg_uecc_vli_testBit(X1, 0)) {
  12629. mg_uecc_word_t l_carry = mg_uecc_vli_add(X1, X1, curve->p, num_words);
  12630. mg_uecc_vli_rshift1(X1, num_words);
  12631. X1[num_words - 1] |= l_carry << (MG_UECC_WORD_BITS - 1);
  12632. } else {
  12633. mg_uecc_vli_rshift1(X1, num_words);
  12634. }
  12635. /* t1 = 3/2*(x1^2 - z1^4) = B */
  12636. mg_uecc_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */
  12637. mg_uecc_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
  12638. mg_uecc_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
  12639. mg_uecc_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
  12640. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */
  12641. mg_uecc_vli_modSub(t4, X1, t4, curve->p,
  12642. num_words); /* t4 = B * (A - x3) - y1^4 = y3 */
  12643. mg_uecc_vli_set(X1, Z1, num_words);
  12644. mg_uecc_vli_set(Z1, Y1, num_words);
  12645. mg_uecc_vli_set(Y1, t4, num_words);
  12646. }
  12647. /* Computes result = x^3 + ax + b. result must not overlap x. */
  12648. static void x_side_default(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  12649. MG_UECC_Curve curve) {
  12650. mg_uecc_word_t _3[MG_UECC_MAX_WORDS] = {3}; /* -a = 3 */
  12651. wordcount_t num_words = curve->num_words;
  12652. mg_uecc_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  12653. mg_uecc_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
  12654. mg_uecc_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */
  12655. mg_uecc_vli_modAdd(result, result, curve->b, curve->p,
  12656. num_words); /* r = x^3 - 3x + b */
  12657. }
  12658. #endif /* MG_UECC_SUPPORTS_secp... */
  12659. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12660. #if MG_UECC_SUPPORTS_secp160r1 || MG_UECC_SUPPORTS_secp192r1 || \
  12661. MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1
  12662. /* Compute a = sqrt(a) (mod curve_p). */
  12663. static void mod_sqrt_default(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  12664. bitcount_t i;
  12665. mg_uecc_word_t p1[MG_UECC_MAX_WORDS] = {1};
  12666. mg_uecc_word_t l_result[MG_UECC_MAX_WORDS] = {1};
  12667. wordcount_t num_words = curve->num_words;
  12668. /* When curve->p == 3 (mod 4), we can compute
  12669. sqrt(a) = a^((curve->p + 1) / 4) (mod curve->p). */
  12670. mg_uecc_vli_add(p1, curve->p, p1, num_words); /* p1 = curve_p + 1 */
  12671. for (i = mg_uecc_vli_numBits(p1, num_words) - 1; i > 1; --i) {
  12672. mg_uecc_vli_modSquare_fast(l_result, l_result, curve);
  12673. if (mg_uecc_vli_testBit(p1, i)) {
  12674. mg_uecc_vli_modMult_fast(l_result, l_result, a, curve);
  12675. }
  12676. }
  12677. mg_uecc_vli_set(a, l_result, num_words);
  12678. }
  12679. #endif /* MG_UECC_SUPPORTS_secp... */
  12680. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  12681. #if MG_UECC_SUPPORTS_secp160r1
  12682. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12683. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  12684. mg_uecc_word_t *product);
  12685. #endif
  12686. static const struct MG_UECC_Curve_t curve_secp160r1 = {
  12687. num_words_secp160r1,
  12688. num_bytes_secp160r1,
  12689. 161, /* num_n_bits */
  12690. {BYTES_TO_WORDS_8(FF, FF, FF, 7F, FF, FF, FF, FF),
  12691. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12692. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  12693. {BYTES_TO_WORDS_8(57, 22, 75, CA, D3, AE, 27, F9),
  12694. BYTES_TO_WORDS_8(C8, F4, 01, 00, 00, 00, 00, 00),
  12695. BYTES_TO_WORDS_8(00, 00, 00, 00, 01, 00, 00, 00)},
  12696. {BYTES_TO_WORDS_8(82, FC, CB, 13, B9, 8B, C3, 68),
  12697. BYTES_TO_WORDS_8(89, 69, 64, 46, 28, 73, F5, 8E),
  12698. BYTES_TO_WORDS_4(68, B5, 96, 4A),
  12699. BYTES_TO_WORDS_8(32, FB, C5, 7A, 37, 51, 23, 04),
  12700. BYTES_TO_WORDS_8(12, C9, DC, 59, 7D, 94, 68, 31),
  12701. BYTES_TO_WORDS_4(55, 28, A6, 23)},
  12702. {BYTES_TO_WORDS_8(45, FA, 65, C5, AD, D4, D4, 81),
  12703. BYTES_TO_WORDS_8(9F, F8, AC, 65, 8B, 7A, BD, 54),
  12704. BYTES_TO_WORDS_4(FC, BE, 97, 1C)},
  12705. &double_jacobian_default,
  12706. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12707. &mod_sqrt_default,
  12708. #endif
  12709. &x_side_default,
  12710. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12711. &vli_mmod_fast_secp160r1
  12712. #endif
  12713. };
  12714. MG_UECC_Curve mg_uecc_secp160r1(void) {
  12715. return &curve_secp160r1;
  12716. }
  12717. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1)
  12718. /* Computes result = product % curve_p
  12719. see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
  12720. Note that this only works if log2(omega) < log2(p) / 2 */
  12721. static void omega_mult_secp160r1(mg_uecc_word_t *result,
  12722. const mg_uecc_word_t *right);
  12723. #if MG_UECC_WORD_SIZE == 8
  12724. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  12725. mg_uecc_word_t *product) {
  12726. mg_uecc_word_t tmp[2 * num_words_secp160r1];
  12727. mg_uecc_word_t copy;
  12728. mg_uecc_vli_clear(tmp, num_words_secp160r1);
  12729. mg_uecc_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  12730. omega_mult_secp160r1(tmp,
  12731. product + num_words_secp160r1 - 1); /* (Rq, q) = q * c */
  12732. product[num_words_secp160r1 - 1] &= 0xffffffff;
  12733. copy = tmp[num_words_secp160r1 - 1];
  12734. tmp[num_words_secp160r1 - 1] &= 0xffffffff;
  12735. mg_uecc_vli_add(result, product, tmp,
  12736. num_words_secp160r1); /* (C, r) = r + q */
  12737. mg_uecc_vli_clear(product, num_words_secp160r1);
  12738. tmp[num_words_secp160r1 - 1] = copy;
  12739. omega_mult_secp160r1(product, tmp + num_words_secp160r1 - 1); /* Rq*c */
  12740. mg_uecc_vli_add(result, result, product,
  12741. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  12742. while (mg_uecc_vli_cmp_unsafe(result, curve_secp160r1.p,
  12743. num_words_secp160r1) > 0) {
  12744. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  12745. }
  12746. }
  12747. static void omega_mult_secp160r1(uint64_t *result, const uint64_t *right) {
  12748. uint32_t carry;
  12749. unsigned i;
  12750. /* Multiply by (2^31 + 1). */
  12751. carry = 0;
  12752. for (i = 0; i < num_words_secp160r1; ++i) {
  12753. uint64_t tmp = (right[i] >> 32) | (right[i + 1] << 32);
  12754. result[i] = (tmp << 31) + tmp + carry;
  12755. carry = (tmp >> 33) + (result[i] < tmp || (carry && result[i] == tmp));
  12756. }
  12757. result[i] = carry;
  12758. }
  12759. #else
  12760. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  12761. mg_uecc_word_t *product) {
  12762. mg_uecc_word_t tmp[2 * num_words_secp160r1];
  12763. mg_uecc_word_t carry;
  12764. mg_uecc_vli_clear(tmp, num_words_secp160r1);
  12765. mg_uecc_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  12766. omega_mult_secp160r1(tmp,
  12767. product + num_words_secp160r1); /* (Rq, q) = q * c */
  12768. carry = mg_uecc_vli_add(result, product, tmp,
  12769. num_words_secp160r1); /* (C, r) = r + q */
  12770. mg_uecc_vli_clear(product, num_words_secp160r1);
  12771. omega_mult_secp160r1(product, tmp + num_words_secp160r1); /* Rq*c */
  12772. carry += mg_uecc_vli_add(result, result, product,
  12773. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  12774. while (carry > 0) {
  12775. --carry;
  12776. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  12777. }
  12778. if (mg_uecc_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) >
  12779. 0) {
  12780. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  12781. }
  12782. }
  12783. #endif
  12784. #if MG_UECC_WORD_SIZE == 1
  12785. static void omega_mult_secp160r1(uint8_t *result, const uint8_t *right) {
  12786. uint8_t carry;
  12787. uint8_t i;
  12788. /* Multiply by (2^31 + 1). */
  12789. mg_uecc_vli_set(result + 4, right, num_words_secp160r1); /* 2^32 */
  12790. mg_uecc_vli_rshift1(result + 4, num_words_secp160r1); /* 2^31 */
  12791. result[3] = right[0] << 7; /* get last bit from shift */
  12792. carry = mg_uecc_vli_add(result, result, right,
  12793. num_words_secp160r1); /* 2^31 + 1 */
  12794. for (i = num_words_secp160r1; carry; ++i) {
  12795. uint16_t sum = (uint16_t) result[i] + carry;
  12796. result[i] = (uint8_t) sum;
  12797. carry = sum >> 8;
  12798. }
  12799. }
  12800. #elif MG_UECC_WORD_SIZE == 4
  12801. static void omega_mult_secp160r1(uint32_t *result, const uint32_t *right) {
  12802. uint32_t carry;
  12803. unsigned i;
  12804. /* Multiply by (2^31 + 1). */
  12805. mg_uecc_vli_set(result + 1, right, num_words_secp160r1); /* 2^32 */
  12806. mg_uecc_vli_rshift1(result + 1, num_words_secp160r1); /* 2^31 */
  12807. result[0] = right[0] << 31; /* get last bit from shift */
  12808. carry = mg_uecc_vli_add(result, result, right,
  12809. num_words_secp160r1); /* 2^31 + 1 */
  12810. for (i = num_words_secp160r1; carry; ++i) {
  12811. uint64_t sum = (uint64_t) result[i] + carry;
  12812. result[i] = (uint32_t) sum;
  12813. carry = sum >> 32;
  12814. }
  12815. }
  12816. #endif /* MG_UECC_WORD_SIZE */
  12817. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) */
  12818. #endif /* MG_UECC_SUPPORTS_secp160r1 */
  12819. #if MG_UECC_SUPPORTS_secp192r1
  12820. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12821. static void vli_mmod_fast_secp192r1(mg_uecc_word_t *result,
  12822. mg_uecc_word_t *product);
  12823. #endif
  12824. static const struct MG_UECC_Curve_t curve_secp192r1 = {
  12825. num_words_secp192r1,
  12826. num_bytes_secp192r1,
  12827. 192, /* num_n_bits */
  12828. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12829. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  12830. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  12831. {BYTES_TO_WORDS_8(31, 28, D2, B4, B1, C9, 6B, 14),
  12832. BYTES_TO_WORDS_8(36, F8, DE, 99, FF, FF, FF, FF),
  12833. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  12834. {BYTES_TO_WORDS_8(12, 10, FF, 82, FD, 0A, FF, F4),
  12835. BYTES_TO_WORDS_8(00, 88, A1, 43, EB, 20, BF, 7C),
  12836. BYTES_TO_WORDS_8(F6, 90, 30, B0, 0E, A8, 8D, 18),
  12837. BYTES_TO_WORDS_8(11, 48, 79, 1E, A1, 77, F9, 73),
  12838. BYTES_TO_WORDS_8(D5, CD, 24, 6B, ED, 11, 10, 63),
  12839. BYTES_TO_WORDS_8(78, DA, C8, FF, 95, 2B, 19, 07)},
  12840. {BYTES_TO_WORDS_8(B1, B9, 46, C1, EC, DE, B8, FE),
  12841. BYTES_TO_WORDS_8(49, 30, 24, 72, AB, E9, A7, 0F),
  12842. BYTES_TO_WORDS_8(E7, 80, 9C, E5, 19, 05, 21, 64)},
  12843. &double_jacobian_default,
  12844. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12845. &mod_sqrt_default,
  12846. #endif
  12847. &x_side_default,
  12848. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12849. &vli_mmod_fast_secp192r1
  12850. #endif
  12851. };
  12852. MG_UECC_Curve mg_uecc_secp192r1(void) {
  12853. return &curve_secp192r1;
  12854. }
  12855. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12856. /* Computes result = product % curve_p.
  12857. See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf
  12858. */
  12859. #if MG_UECC_WORD_SIZE == 1
  12860. static void vli_mmod_fast_secp192r1(uint8_t *result, uint8_t *product) {
  12861. uint8_t tmp[num_words_secp192r1];
  12862. uint8_t carry;
  12863. mg_uecc_vli_set(result, product, num_words_secp192r1);
  12864. mg_uecc_vli_set(tmp, &product[24], num_words_secp192r1);
  12865. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12866. tmp[0] = tmp[1] = tmp[2] = tmp[3] = tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  12867. tmp[8] = product[24];
  12868. tmp[9] = product[25];
  12869. tmp[10] = product[26];
  12870. tmp[11] = product[27];
  12871. tmp[12] = product[28];
  12872. tmp[13] = product[29];
  12873. tmp[14] = product[30];
  12874. tmp[15] = product[31];
  12875. tmp[16] = product[32];
  12876. tmp[17] = product[33];
  12877. tmp[18] = product[34];
  12878. tmp[19] = product[35];
  12879. tmp[20] = product[36];
  12880. tmp[21] = product[37];
  12881. tmp[22] = product[38];
  12882. tmp[23] = product[39];
  12883. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12884. tmp[0] = tmp[8] = product[40];
  12885. tmp[1] = tmp[9] = product[41];
  12886. tmp[2] = tmp[10] = product[42];
  12887. tmp[3] = tmp[11] = product[43];
  12888. tmp[4] = tmp[12] = product[44];
  12889. tmp[5] = tmp[13] = product[45];
  12890. tmp[6] = tmp[14] = product[46];
  12891. tmp[7] = tmp[15] = product[47];
  12892. tmp[16] = tmp[17] = tmp[18] = tmp[19] = tmp[20] = tmp[21] = tmp[22] =
  12893. tmp[23] = 0;
  12894. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12895. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  12896. num_words_secp192r1) != 1) {
  12897. carry -=
  12898. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  12899. }
  12900. }
  12901. #elif MG_UECC_WORD_SIZE == 4
  12902. static void vli_mmod_fast_secp192r1(uint32_t *result, uint32_t *product) {
  12903. uint32_t tmp[num_words_secp192r1];
  12904. int carry;
  12905. mg_uecc_vli_set(result, product, num_words_secp192r1);
  12906. mg_uecc_vli_set(tmp, &product[6], num_words_secp192r1);
  12907. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12908. tmp[0] = tmp[1] = 0;
  12909. tmp[2] = product[6];
  12910. tmp[3] = product[7];
  12911. tmp[4] = product[8];
  12912. tmp[5] = product[9];
  12913. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12914. tmp[0] = tmp[2] = product[10];
  12915. tmp[1] = tmp[3] = product[11];
  12916. tmp[4] = tmp[5] = 0;
  12917. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12918. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  12919. num_words_secp192r1) != 1) {
  12920. carry -=
  12921. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  12922. }
  12923. }
  12924. #else
  12925. static void vli_mmod_fast_secp192r1(uint64_t *result, uint64_t *product) {
  12926. uint64_t tmp[num_words_secp192r1];
  12927. int carry;
  12928. mg_uecc_vli_set(result, product, num_words_secp192r1);
  12929. mg_uecc_vli_set(tmp, &product[3], num_words_secp192r1);
  12930. carry = (int) mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12931. tmp[0] = 0;
  12932. tmp[1] = product[3];
  12933. tmp[2] = product[4];
  12934. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12935. tmp[0] = tmp[1] = product[5];
  12936. tmp[2] = 0;
  12937. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  12938. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  12939. num_words_secp192r1) != 1) {
  12940. carry -=
  12941. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  12942. }
  12943. }
  12944. #endif /* MG_UECC_WORD_SIZE */
  12945. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0) */
  12946. #endif /* MG_UECC_SUPPORTS_secp192r1 */
  12947. #if MG_UECC_SUPPORTS_secp224r1
  12948. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12949. static void mod_sqrt_secp224r1(mg_uecc_word_t *a, MG_UECC_Curve curve);
  12950. #endif
  12951. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12952. static void vli_mmod_fast_secp224r1(mg_uecc_word_t *result,
  12953. mg_uecc_word_t *product);
  12954. #endif
  12955. static const struct MG_UECC_Curve_t curve_secp224r1 = {
  12956. num_words_secp224r1,
  12957. num_bytes_secp224r1,
  12958. 224, /* num_n_bits */
  12959. {BYTES_TO_WORDS_8(01, 00, 00, 00, 00, 00, 00, 00),
  12960. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF),
  12961. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12962. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  12963. {BYTES_TO_WORDS_8(3D, 2A, 5C, 5C, 45, 29, DD, 13),
  12964. BYTES_TO_WORDS_8(3E, F0, B8, E0, A2, 16, FF, FF),
  12965. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12966. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  12967. {BYTES_TO_WORDS_8(21, 1D, 5C, 11, D6, 80, 32, 34),
  12968. BYTES_TO_WORDS_8(22, 11, C2, 56, D3, C1, 03, 4A),
  12969. BYTES_TO_WORDS_8(B9, 90, 13, 32, 7F, BF, B4, 6B),
  12970. BYTES_TO_WORDS_4(BD, 0C, 0E, B7),
  12971. BYTES_TO_WORDS_8(34, 7E, 00, 85, 99, 81, D5, 44),
  12972. BYTES_TO_WORDS_8(64, 47, 07, 5A, A0, 75, 43, CD),
  12973. BYTES_TO_WORDS_8(E6, DF, 22, 4C, FB, 23, F7, B5),
  12974. BYTES_TO_WORDS_4(88, 63, 37, BD)},
  12975. {BYTES_TO_WORDS_8(B4, FF, 55, 23, 43, 39, 0B, 27),
  12976. BYTES_TO_WORDS_8(BA, D8, BF, D7, B7, B0, 44, 50),
  12977. BYTES_TO_WORDS_8(56, 32, 41, F5, AB, B3, 04, 0C),
  12978. BYTES_TO_WORDS_4(85, 0A, 05, B4)},
  12979. &double_jacobian_default,
  12980. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12981. &mod_sqrt_secp224r1,
  12982. #endif
  12983. &x_side_default,
  12984. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12985. &vli_mmod_fast_secp224r1
  12986. #endif
  12987. };
  12988. MG_UECC_Curve mg_uecc_secp224r1(void) {
  12989. return &curve_secp224r1;
  12990. }
  12991. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12992. /* Routine 3.2.4 RS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  12993. static void mod_sqrt_secp224r1_rs(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  12994. mg_uecc_word_t *f1, const mg_uecc_word_t *d0,
  12995. const mg_uecc_word_t *e0,
  12996. const mg_uecc_word_t *f0) {
  12997. mg_uecc_word_t t[num_words_secp224r1];
  12998. mg_uecc_vli_modSquare_fast(t, d0, &curve_secp224r1); /* t <-- d0 ^ 2 */
  12999. mg_uecc_vli_modMult_fast(e1, d0, e0, &curve_secp224r1); /* e1 <-- d0 * e0 */
  13000. mg_uecc_vli_modAdd(d1, t, f0, curve_secp224r1.p,
  13001. num_words_secp224r1); /* d1 <-- t + f0 */
  13002. mg_uecc_vli_modAdd(e1, e1, e1, curve_secp224r1.p,
  13003. num_words_secp224r1); /* e1 <-- e1 + e1 */
  13004. mg_uecc_vli_modMult_fast(f1, t, f0, &curve_secp224r1); /* f1 <-- t * f0 */
  13005. mg_uecc_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  13006. num_words_secp224r1); /* f1 <-- f1 + f1 */
  13007. mg_uecc_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  13008. num_words_secp224r1); /* f1 <-- f1 + f1 */
  13009. }
  13010. /* Routine 3.2.5 RSS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  13011. static void mod_sqrt_secp224r1_rss(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  13012. mg_uecc_word_t *f1, const mg_uecc_word_t *d0,
  13013. const mg_uecc_word_t *e0,
  13014. const mg_uecc_word_t *f0,
  13015. const bitcount_t j) {
  13016. bitcount_t i;
  13017. mg_uecc_vli_set(d1, d0, num_words_secp224r1); /* d1 <-- d0 */
  13018. mg_uecc_vli_set(e1, e0, num_words_secp224r1); /* e1 <-- e0 */
  13019. mg_uecc_vli_set(f1, f0, num_words_secp224r1); /* f1 <-- f0 */
  13020. for (i = 1; i <= j; i++) {
  13021. mod_sqrt_secp224r1_rs(d1, e1, f1, d1, e1, f1); /* RS (d1,e1,f1,d1,e1,f1) */
  13022. }
  13023. }
  13024. /* Routine 3.2.6 RM; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  13025. static void mod_sqrt_secp224r1_rm(mg_uecc_word_t *d2, mg_uecc_word_t *e2,
  13026. mg_uecc_word_t *f2, const mg_uecc_word_t *c,
  13027. const mg_uecc_word_t *d0,
  13028. const mg_uecc_word_t *e0,
  13029. const mg_uecc_word_t *d1,
  13030. const mg_uecc_word_t *e1) {
  13031. mg_uecc_word_t t1[num_words_secp224r1];
  13032. mg_uecc_word_t t2[num_words_secp224r1];
  13033. mg_uecc_vli_modMult_fast(t1, e0, e1, &curve_secp224r1); /* t1 <-- e0 * e1 */
  13034. mg_uecc_vli_modMult_fast(t1, t1, c, &curve_secp224r1); /* t1 <-- t1 * c */
  13035. /* t1 <-- p - t1 */
  13036. mg_uecc_vli_modSub(t1, curve_secp224r1.p, t1, curve_secp224r1.p,
  13037. num_words_secp224r1);
  13038. mg_uecc_vli_modMult_fast(t2, d0, d1, &curve_secp224r1); /* t2 <-- d0 * d1 */
  13039. mg_uecc_vli_modAdd(t2, t2, t1, curve_secp224r1.p,
  13040. num_words_secp224r1); /* t2 <-- t2 + t1 */
  13041. mg_uecc_vli_modMult_fast(t1, d0, e1, &curve_secp224r1); /* t1 <-- d0 * e1 */
  13042. mg_uecc_vli_modMult_fast(e2, d1, e0, &curve_secp224r1); /* e2 <-- d1 * e0 */
  13043. mg_uecc_vli_modAdd(e2, e2, t1, curve_secp224r1.p,
  13044. num_words_secp224r1); /* e2 <-- e2 + t1 */
  13045. mg_uecc_vli_modSquare_fast(f2, e2, &curve_secp224r1); /* f2 <-- e2^2 */
  13046. mg_uecc_vli_modMult_fast(f2, f2, c, &curve_secp224r1); /* f2 <-- f2 * c */
  13047. /* f2 <-- p - f2 */
  13048. mg_uecc_vli_modSub(f2, curve_secp224r1.p, f2, curve_secp224r1.p,
  13049. num_words_secp224r1);
  13050. mg_uecc_vli_set(d2, t2, num_words_secp224r1); /* d2 <-- t2 */
  13051. }
  13052. /* Routine 3.2.7 RP; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  13053. static void mod_sqrt_secp224r1_rp(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  13054. mg_uecc_word_t *f1, const mg_uecc_word_t *c,
  13055. const mg_uecc_word_t *r) {
  13056. wordcount_t i;
  13057. wordcount_t pow2i = 1;
  13058. mg_uecc_word_t d0[num_words_secp224r1];
  13059. mg_uecc_word_t e0[num_words_secp224r1] = {1}; /* e0 <-- 1 */
  13060. mg_uecc_word_t f0[num_words_secp224r1];
  13061. mg_uecc_vli_set(d0, r, num_words_secp224r1); /* d0 <-- r */
  13062. /* f0 <-- p - c */
  13063. mg_uecc_vli_modSub(f0, curve_secp224r1.p, c, curve_secp224r1.p,
  13064. num_words_secp224r1);
  13065. for (i = 0; i <= 6; i++) {
  13066. mod_sqrt_secp224r1_rss(d1, e1, f1, d0, e0, f0,
  13067. pow2i); /* RSS (d1,e1,f1,d0,e0,f0,2^i) */
  13068. mod_sqrt_secp224r1_rm(d1, e1, f1, c, d1, e1, d0,
  13069. e0); /* RM (d1,e1,f1,c,d1,e1,d0,e0) */
  13070. mg_uecc_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  13071. mg_uecc_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  13072. mg_uecc_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  13073. pow2i *= 2;
  13074. }
  13075. }
  13076. /* Compute a = sqrt(a) (mod curve_p). */
  13077. /* Routine 3.2.8 mp_mod_sqrt_224; from
  13078. * http://www.nsa.gov/ia/_files/nist-routines.pdf */
  13079. static void mod_sqrt_secp224r1(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  13080. (void) curve;
  13081. bitcount_t i;
  13082. mg_uecc_word_t e1[num_words_secp224r1];
  13083. mg_uecc_word_t f1[num_words_secp224r1];
  13084. mg_uecc_word_t d0[num_words_secp224r1];
  13085. mg_uecc_word_t e0[num_words_secp224r1];
  13086. mg_uecc_word_t f0[num_words_secp224r1];
  13087. mg_uecc_word_t d1[num_words_secp224r1];
  13088. /* s = a; using constant instead of random value */
  13089. mod_sqrt_secp224r1_rp(d0, e0, f0, a, a); /* RP (d0, e0, f0, c, s) */
  13090. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  13091. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  13092. for (i = 1; i <= 95; i++) {
  13093. mg_uecc_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  13094. mg_uecc_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  13095. mg_uecc_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  13096. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  13097. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  13098. if (mg_uecc_vli_isZero(d1, num_words_secp224r1)) { /* if d1 == 0 */
  13099. break;
  13100. }
  13101. }
  13102. mg_uecc_vli_modInv(f1, e0, curve_secp224r1.p,
  13103. num_words_secp224r1); /* f1 <-- 1 / e0 */
  13104. mg_uecc_vli_modMult_fast(a, d0, f1, &curve_secp224r1); /* a <-- d0 / e0 */
  13105. }
  13106. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  13107. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  13108. /* Computes result = product % curve_p
  13109. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  13110. #if MG_UECC_WORD_SIZE == 1
  13111. static void vli_mmod_fast_secp224r1(uint8_t *result, uint8_t *product) {
  13112. uint8_t tmp[num_words_secp224r1];
  13113. int8_t carry;
  13114. /* t */
  13115. mg_uecc_vli_set(result, product, num_words_secp224r1);
  13116. /* s1 */
  13117. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  13118. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  13119. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  13120. tmp[12] = product[28];
  13121. tmp[13] = product[29];
  13122. tmp[14] = product[30];
  13123. tmp[15] = product[31];
  13124. tmp[16] = product[32];
  13125. tmp[17] = product[33];
  13126. tmp[18] = product[34];
  13127. tmp[19] = product[35];
  13128. tmp[20] = product[36];
  13129. tmp[21] = product[37];
  13130. tmp[22] = product[38];
  13131. tmp[23] = product[39];
  13132. tmp[24] = product[40];
  13133. tmp[25] = product[41];
  13134. tmp[26] = product[42];
  13135. tmp[27] = product[43];
  13136. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  13137. /* s2 */
  13138. tmp[12] = product[44];
  13139. tmp[13] = product[45];
  13140. tmp[14] = product[46];
  13141. tmp[15] = product[47];
  13142. tmp[16] = product[48];
  13143. tmp[17] = product[49];
  13144. tmp[18] = product[50];
  13145. tmp[19] = product[51];
  13146. tmp[20] = product[52];
  13147. tmp[21] = product[53];
  13148. tmp[22] = product[54];
  13149. tmp[23] = product[55];
  13150. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  13151. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  13152. /* d1 */
  13153. tmp[0] = product[28];
  13154. tmp[1] = product[29];
  13155. tmp[2] = product[30];
  13156. tmp[3] = product[31];
  13157. tmp[4] = product[32];
  13158. tmp[5] = product[33];
  13159. tmp[6] = product[34];
  13160. tmp[7] = product[35];
  13161. tmp[8] = product[36];
  13162. tmp[9] = product[37];
  13163. tmp[10] = product[38];
  13164. tmp[11] = product[39];
  13165. tmp[12] = product[40];
  13166. tmp[13] = product[41];
  13167. tmp[14] = product[42];
  13168. tmp[15] = product[43];
  13169. tmp[16] = product[44];
  13170. tmp[17] = product[45];
  13171. tmp[18] = product[46];
  13172. tmp[19] = product[47];
  13173. tmp[20] = product[48];
  13174. tmp[21] = product[49];
  13175. tmp[22] = product[50];
  13176. tmp[23] = product[51];
  13177. tmp[24] = product[52];
  13178. tmp[25] = product[53];
  13179. tmp[26] = product[54];
  13180. tmp[27] = product[55];
  13181. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  13182. /* d2 */
  13183. tmp[0] = product[44];
  13184. tmp[1] = product[45];
  13185. tmp[2] = product[46];
  13186. tmp[3] = product[47];
  13187. tmp[4] = product[48];
  13188. tmp[5] = product[49];
  13189. tmp[6] = product[50];
  13190. tmp[7] = product[51];
  13191. tmp[8] = product[52];
  13192. tmp[9] = product[53];
  13193. tmp[10] = product[54];
  13194. tmp[11] = product[55];
  13195. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  13196. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  13197. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  13198. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  13199. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  13200. if (carry < 0) {
  13201. do {
  13202. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  13203. num_words_secp224r1);
  13204. } while (carry < 0);
  13205. } else {
  13206. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  13207. num_words_secp224r1) != 1) {
  13208. carry -= mg_uecc_vli_sub(result, result, curve_secp224r1.p,
  13209. num_words_secp224r1);
  13210. }
  13211. }
  13212. }
  13213. #elif MG_UECC_WORD_SIZE == 4
  13214. static void vli_mmod_fast_secp224r1(uint32_t *result, uint32_t *product) {
  13215. uint32_t tmp[num_words_secp224r1];
  13216. int carry;
  13217. /* t */
  13218. mg_uecc_vli_set(result, product, num_words_secp224r1);
  13219. /* s1 */
  13220. tmp[0] = tmp[1] = tmp[2] = 0;
  13221. tmp[3] = product[7];
  13222. tmp[4] = product[8];
  13223. tmp[5] = product[9];
  13224. tmp[6] = product[10];
  13225. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  13226. /* s2 */
  13227. tmp[3] = product[11];
  13228. tmp[4] = product[12];
  13229. tmp[5] = product[13];
  13230. tmp[6] = 0;
  13231. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  13232. /* d1 */
  13233. tmp[0] = product[7];
  13234. tmp[1] = product[8];
  13235. tmp[2] = product[9];
  13236. tmp[3] = product[10];
  13237. tmp[4] = product[11];
  13238. tmp[5] = product[12];
  13239. tmp[6] = product[13];
  13240. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  13241. /* d2 */
  13242. tmp[0] = product[11];
  13243. tmp[1] = product[12];
  13244. tmp[2] = product[13];
  13245. tmp[3] = tmp[4] = tmp[5] = tmp[6] = 0;
  13246. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  13247. if (carry < 0) {
  13248. do {
  13249. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  13250. num_words_secp224r1);
  13251. } while (carry < 0);
  13252. } else {
  13253. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  13254. num_words_secp224r1) != 1) {
  13255. carry -= mg_uecc_vli_sub(result, result, curve_secp224r1.p,
  13256. num_words_secp224r1);
  13257. }
  13258. }
  13259. }
  13260. #else
  13261. static void vli_mmod_fast_secp224r1(uint64_t *result, uint64_t *product) {
  13262. uint64_t tmp[num_words_secp224r1];
  13263. int carry = 0;
  13264. /* t */
  13265. mg_uecc_vli_set(result, product, num_words_secp224r1);
  13266. result[num_words_secp224r1 - 1] &= 0xffffffff;
  13267. /* s1 */
  13268. tmp[0] = 0;
  13269. tmp[1] = product[3] & 0xffffffff00000000ull;
  13270. tmp[2] = product[4];
  13271. tmp[3] = product[5] & 0xffffffff;
  13272. mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  13273. /* s2 */
  13274. tmp[1] = product[5] & 0xffffffff00000000ull;
  13275. tmp[2] = product[6];
  13276. tmp[3] = 0;
  13277. mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  13278. /* d1 */
  13279. tmp[0] = (product[3] >> 32) | (product[4] << 32);
  13280. tmp[1] = (product[4] >> 32) | (product[5] << 32);
  13281. tmp[2] = (product[5] >> 32) | (product[6] << 32);
  13282. tmp[3] = product[6] >> 32;
  13283. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  13284. /* d2 */
  13285. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  13286. tmp[1] = product[6] >> 32;
  13287. tmp[2] = tmp[3] = 0;
  13288. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  13289. if (carry < 0) {
  13290. do {
  13291. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  13292. num_words_secp224r1);
  13293. } while (carry < 0);
  13294. } else {
  13295. while (mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  13296. num_words_secp224r1) != 1) {
  13297. mg_uecc_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  13298. }
  13299. }
  13300. }
  13301. #endif /* MG_UECC_WORD_SIZE */
  13302. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0) */
  13303. #endif /* MG_UECC_SUPPORTS_secp224r1 */
  13304. #if MG_UECC_SUPPORTS_secp256r1
  13305. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  13306. static void vli_mmod_fast_secp256r1(mg_uecc_word_t *result,
  13307. mg_uecc_word_t *product);
  13308. #endif
  13309. static const struct MG_UECC_Curve_t curve_secp256r1 = {
  13310. num_words_secp256r1,
  13311. num_bytes_secp256r1,
  13312. 256, /* num_n_bits */
  13313. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  13314. BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00),
  13315. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  13316. BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF)},
  13317. {BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3),
  13318. BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC),
  13319. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  13320. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF)},
  13321. {BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4),
  13322. BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77),
  13323. BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8),
  13324. BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B),
  13325. BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB),
  13326. BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B),
  13327. BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E),
  13328. BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F)},
  13329. {BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B),
  13330. BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65),
  13331. BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3),
  13332. BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A)},
  13333. &double_jacobian_default,
  13334. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  13335. &mod_sqrt_default,
  13336. #endif
  13337. &x_side_default,
  13338. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  13339. &vli_mmod_fast_secp256r1
  13340. #endif
  13341. };
  13342. MG_UECC_Curve mg_uecc_secp256r1(void) {
  13343. return &curve_secp256r1;
  13344. }
  13345. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1)
  13346. /* Computes result = product % curve_p
  13347. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  13348. #if MG_UECC_WORD_SIZE == 1
  13349. static void vli_mmod_fast_secp256r1(uint8_t *result, uint8_t *product) {
  13350. uint8_t tmp[num_words_secp256r1];
  13351. int8_t carry;
  13352. /* t */
  13353. mg_uecc_vli_set(result, product, num_words_secp256r1);
  13354. /* s1 */
  13355. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  13356. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  13357. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  13358. tmp[12] = product[44];
  13359. tmp[13] = product[45];
  13360. tmp[14] = product[46];
  13361. tmp[15] = product[47];
  13362. tmp[16] = product[48];
  13363. tmp[17] = product[49];
  13364. tmp[18] = product[50];
  13365. tmp[19] = product[51];
  13366. tmp[20] = product[52];
  13367. tmp[21] = product[53];
  13368. tmp[22] = product[54];
  13369. tmp[23] = product[55];
  13370. tmp[24] = product[56];
  13371. tmp[25] = product[57];
  13372. tmp[26] = product[58];
  13373. tmp[27] = product[59];
  13374. tmp[28] = product[60];
  13375. tmp[29] = product[61];
  13376. tmp[30] = product[62];
  13377. tmp[31] = product[63];
  13378. carry = mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  13379. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13380. /* s2 */
  13381. tmp[12] = product[48];
  13382. tmp[13] = product[49];
  13383. tmp[14] = product[50];
  13384. tmp[15] = product[51];
  13385. tmp[16] = product[52];
  13386. tmp[17] = product[53];
  13387. tmp[18] = product[54];
  13388. tmp[19] = product[55];
  13389. tmp[20] = product[56];
  13390. tmp[21] = product[57];
  13391. tmp[22] = product[58];
  13392. tmp[23] = product[59];
  13393. tmp[24] = product[60];
  13394. tmp[25] = product[61];
  13395. tmp[26] = product[62];
  13396. tmp[27] = product[63];
  13397. tmp[28] = tmp[29] = tmp[30] = tmp[31] = 0;
  13398. carry += mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  13399. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13400. /* s3 */
  13401. tmp[0] = product[32];
  13402. tmp[1] = product[33];
  13403. tmp[2] = product[34];
  13404. tmp[3] = product[35];
  13405. tmp[4] = product[36];
  13406. tmp[5] = product[37];
  13407. tmp[6] = product[38];
  13408. tmp[7] = product[39];
  13409. tmp[8] = product[40];
  13410. tmp[9] = product[41];
  13411. tmp[10] = product[42];
  13412. tmp[11] = product[43];
  13413. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  13414. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  13415. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  13416. tmp[24] = product[56];
  13417. tmp[25] = product[57];
  13418. tmp[26] = product[58];
  13419. tmp[27] = product[59];
  13420. tmp[28] = product[60];
  13421. tmp[29] = product[61];
  13422. tmp[30] = product[62];
  13423. tmp[31] = product[63];
  13424. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13425. /* s4 */
  13426. tmp[0] = product[36];
  13427. tmp[1] = product[37];
  13428. tmp[2] = product[38];
  13429. tmp[3] = product[39];
  13430. tmp[4] = product[40];
  13431. tmp[5] = product[41];
  13432. tmp[6] = product[42];
  13433. tmp[7] = product[43];
  13434. tmp[8] = product[44];
  13435. tmp[9] = product[45];
  13436. tmp[10] = product[46];
  13437. tmp[11] = product[47];
  13438. tmp[12] = product[52];
  13439. tmp[13] = product[53];
  13440. tmp[14] = product[54];
  13441. tmp[15] = product[55];
  13442. tmp[16] = product[56];
  13443. tmp[17] = product[57];
  13444. tmp[18] = product[58];
  13445. tmp[19] = product[59];
  13446. tmp[20] = product[60];
  13447. tmp[21] = product[61];
  13448. tmp[22] = product[62];
  13449. tmp[23] = product[63];
  13450. tmp[24] = product[52];
  13451. tmp[25] = product[53];
  13452. tmp[26] = product[54];
  13453. tmp[27] = product[55];
  13454. tmp[28] = product[32];
  13455. tmp[29] = product[33];
  13456. tmp[30] = product[34];
  13457. tmp[31] = product[35];
  13458. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13459. /* d1 */
  13460. tmp[0] = product[44];
  13461. tmp[1] = product[45];
  13462. tmp[2] = product[46];
  13463. tmp[3] = product[47];
  13464. tmp[4] = product[48];
  13465. tmp[5] = product[49];
  13466. tmp[6] = product[50];
  13467. tmp[7] = product[51];
  13468. tmp[8] = product[52];
  13469. tmp[9] = product[53];
  13470. tmp[10] = product[54];
  13471. tmp[11] = product[55];
  13472. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  13473. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  13474. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  13475. tmp[24] = product[32];
  13476. tmp[25] = product[33];
  13477. tmp[26] = product[34];
  13478. tmp[27] = product[35];
  13479. tmp[28] = product[40];
  13480. tmp[29] = product[41];
  13481. tmp[30] = product[42];
  13482. tmp[31] = product[43];
  13483. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13484. /* d2 */
  13485. tmp[0] = product[48];
  13486. tmp[1] = product[49];
  13487. tmp[2] = product[50];
  13488. tmp[3] = product[51];
  13489. tmp[4] = product[52];
  13490. tmp[5] = product[53];
  13491. tmp[6] = product[54];
  13492. tmp[7] = product[55];
  13493. tmp[8] = product[56];
  13494. tmp[9] = product[57];
  13495. tmp[10] = product[58];
  13496. tmp[11] = product[59];
  13497. tmp[12] = product[60];
  13498. tmp[13] = product[61];
  13499. tmp[14] = product[62];
  13500. tmp[15] = product[63];
  13501. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  13502. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  13503. tmp[24] = product[36];
  13504. tmp[25] = product[37];
  13505. tmp[26] = product[38];
  13506. tmp[27] = product[39];
  13507. tmp[28] = product[44];
  13508. tmp[29] = product[45];
  13509. tmp[30] = product[46];
  13510. tmp[31] = product[47];
  13511. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13512. /* d3 */
  13513. tmp[0] = product[52];
  13514. tmp[1] = product[53];
  13515. tmp[2] = product[54];
  13516. tmp[3] = product[55];
  13517. tmp[4] = product[56];
  13518. tmp[5] = product[57];
  13519. tmp[6] = product[58];
  13520. tmp[7] = product[59];
  13521. tmp[8] = product[60];
  13522. tmp[9] = product[61];
  13523. tmp[10] = product[62];
  13524. tmp[11] = product[63];
  13525. tmp[12] = product[32];
  13526. tmp[13] = product[33];
  13527. tmp[14] = product[34];
  13528. tmp[15] = product[35];
  13529. tmp[16] = product[36];
  13530. tmp[17] = product[37];
  13531. tmp[18] = product[38];
  13532. tmp[19] = product[39];
  13533. tmp[20] = product[40];
  13534. tmp[21] = product[41];
  13535. tmp[22] = product[42];
  13536. tmp[23] = product[43];
  13537. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  13538. tmp[28] = product[48];
  13539. tmp[29] = product[49];
  13540. tmp[30] = product[50];
  13541. tmp[31] = product[51];
  13542. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13543. /* d4 */
  13544. tmp[0] = product[56];
  13545. tmp[1] = product[57];
  13546. tmp[2] = product[58];
  13547. tmp[3] = product[59];
  13548. tmp[4] = product[60];
  13549. tmp[5] = product[61];
  13550. tmp[6] = product[62];
  13551. tmp[7] = product[63];
  13552. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  13553. tmp[12] = product[36];
  13554. tmp[13] = product[37];
  13555. tmp[14] = product[38];
  13556. tmp[15] = product[39];
  13557. tmp[16] = product[40];
  13558. tmp[17] = product[41];
  13559. tmp[18] = product[42];
  13560. tmp[19] = product[43];
  13561. tmp[20] = product[44];
  13562. tmp[21] = product[45];
  13563. tmp[22] = product[46];
  13564. tmp[23] = product[47];
  13565. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  13566. tmp[28] = product[52];
  13567. tmp[29] = product[53];
  13568. tmp[30] = product[54];
  13569. tmp[31] = product[55];
  13570. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13571. if (carry < 0) {
  13572. do {
  13573. carry += mg_uecc_vli_add(result, result, curve_secp256r1.p,
  13574. num_words_secp256r1);
  13575. } while (carry < 0);
  13576. } else {
  13577. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  13578. num_words_secp256r1) != 1) {
  13579. carry -= mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  13580. num_words_secp256r1);
  13581. }
  13582. }
  13583. }
  13584. #elif MG_UECC_WORD_SIZE == 4
  13585. static void vli_mmod_fast_secp256r1(uint32_t *result, uint32_t *product) {
  13586. uint32_t tmp[num_words_secp256r1];
  13587. int carry;
  13588. /* t */
  13589. mg_uecc_vli_set(result, product, num_words_secp256r1);
  13590. /* s1 */
  13591. tmp[0] = tmp[1] = tmp[2] = 0;
  13592. tmp[3] = product[11];
  13593. tmp[4] = product[12];
  13594. tmp[5] = product[13];
  13595. tmp[6] = product[14];
  13596. tmp[7] = product[15];
  13597. carry = (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  13598. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13599. /* s2 */
  13600. tmp[3] = product[12];
  13601. tmp[4] = product[13];
  13602. tmp[5] = product[14];
  13603. tmp[6] = product[15];
  13604. tmp[7] = 0;
  13605. carry += (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  13606. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13607. /* s3 */
  13608. tmp[0] = product[8];
  13609. tmp[1] = product[9];
  13610. tmp[2] = product[10];
  13611. tmp[3] = tmp[4] = tmp[5] = 0;
  13612. tmp[6] = product[14];
  13613. tmp[7] = product[15];
  13614. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13615. /* s4 */
  13616. tmp[0] = product[9];
  13617. tmp[1] = product[10];
  13618. tmp[2] = product[11];
  13619. tmp[3] = product[13];
  13620. tmp[4] = product[14];
  13621. tmp[5] = product[15];
  13622. tmp[6] = product[13];
  13623. tmp[7] = product[8];
  13624. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13625. /* d1 */
  13626. tmp[0] = product[11];
  13627. tmp[1] = product[12];
  13628. tmp[2] = product[13];
  13629. tmp[3] = tmp[4] = tmp[5] = 0;
  13630. tmp[6] = product[8];
  13631. tmp[7] = product[10];
  13632. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13633. /* d2 */
  13634. tmp[0] = product[12];
  13635. tmp[1] = product[13];
  13636. tmp[2] = product[14];
  13637. tmp[3] = product[15];
  13638. tmp[4] = tmp[5] = 0;
  13639. tmp[6] = product[9];
  13640. tmp[7] = product[11];
  13641. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13642. /* d3 */
  13643. tmp[0] = product[13];
  13644. tmp[1] = product[14];
  13645. tmp[2] = product[15];
  13646. tmp[3] = product[8];
  13647. tmp[4] = product[9];
  13648. tmp[5] = product[10];
  13649. tmp[6] = 0;
  13650. tmp[7] = product[12];
  13651. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13652. /* d4 */
  13653. tmp[0] = product[14];
  13654. tmp[1] = product[15];
  13655. tmp[2] = 0;
  13656. tmp[3] = product[9];
  13657. tmp[4] = product[10];
  13658. tmp[5] = product[11];
  13659. tmp[6] = 0;
  13660. tmp[7] = product[13];
  13661. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13662. if (carry < 0) {
  13663. do {
  13664. carry += (int) mg_uecc_vli_add(result, result, curve_secp256r1.p,
  13665. num_words_secp256r1);
  13666. } while (carry < 0);
  13667. } else {
  13668. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  13669. num_words_secp256r1) != 1) {
  13670. carry -= (int) mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  13671. num_words_secp256r1);
  13672. }
  13673. }
  13674. }
  13675. #else
  13676. static void vli_mmod_fast_secp256r1(uint64_t *result, uint64_t *product) {
  13677. uint64_t tmp[num_words_secp256r1];
  13678. int carry;
  13679. /* t */
  13680. mg_uecc_vli_set(result, product, num_words_secp256r1);
  13681. /* s1 */
  13682. tmp[0] = 0;
  13683. tmp[1] = product[5] & 0xffffffff00000000U;
  13684. tmp[2] = product[6];
  13685. tmp[3] = product[7];
  13686. carry = (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  13687. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13688. /* s2 */
  13689. tmp[1] = product[6] << 32;
  13690. tmp[2] = (product[6] >> 32) | (product[7] << 32);
  13691. tmp[3] = product[7] >> 32;
  13692. carry += (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  13693. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13694. /* s3 */
  13695. tmp[0] = product[4];
  13696. tmp[1] = product[5] & 0xffffffff;
  13697. tmp[2] = 0;
  13698. tmp[3] = product[7];
  13699. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13700. /* s4 */
  13701. tmp[0] = (product[4] >> 32) | (product[5] << 32);
  13702. tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000U);
  13703. tmp[2] = product[7];
  13704. tmp[3] = (product[6] >> 32) | (product[4] << 32);
  13705. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  13706. /* d1 */
  13707. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  13708. tmp[1] = (product[6] >> 32);
  13709. tmp[2] = 0;
  13710. tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32);
  13711. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13712. /* d2 */
  13713. tmp[0] = product[6];
  13714. tmp[1] = product[7];
  13715. tmp[2] = 0;
  13716. tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000);
  13717. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13718. /* d3 */
  13719. tmp[0] = (product[6] >> 32) | (product[7] << 32);
  13720. tmp[1] = (product[7] >> 32) | (product[4] << 32);
  13721. tmp[2] = (product[4] >> 32) | (product[5] << 32);
  13722. tmp[3] = (product[6] << 32);
  13723. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13724. /* d4 */
  13725. tmp[0] = product[7];
  13726. tmp[1] = product[4] & 0xffffffff00000000U;
  13727. tmp[2] = product[5];
  13728. tmp[3] = product[6] & 0xffffffff00000000U;
  13729. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  13730. if (carry < 0) {
  13731. do {
  13732. carry += (int) mg_uecc_vli_add(result, result, curve_secp256r1.p,
  13733. num_words_secp256r1);
  13734. } while (carry < 0);
  13735. } else {
  13736. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  13737. num_words_secp256r1) != 1) {
  13738. carry -= (int) mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  13739. num_words_secp256r1);
  13740. }
  13741. }
  13742. }
  13743. #endif /* MG_UECC_WORD_SIZE */
  13744. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) */
  13745. #endif /* MG_UECC_SUPPORTS_secp256r1 */
  13746. #if MG_UECC_SUPPORTS_secp256k1
  13747. static void double_jacobian_secp256k1(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  13748. mg_uecc_word_t *Z1, MG_UECC_Curve curve);
  13749. static void x_side_secp256k1(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  13750. MG_UECC_Curve curve);
  13751. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  13752. static void vli_mmod_fast_secp256k1(mg_uecc_word_t *result,
  13753. mg_uecc_word_t *product);
  13754. #endif
  13755. static const struct MG_UECC_Curve_t curve_secp256k1 = {
  13756. num_words_secp256k1,
  13757. num_bytes_secp256k1,
  13758. 256, /* num_n_bits */
  13759. {BYTES_TO_WORDS_8(2F, FC, FF, FF, FE, FF, FF, FF),
  13760. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  13761. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  13762. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  13763. {BYTES_TO_WORDS_8(41, 41, 36, D0, 8C, 5E, D2, BF),
  13764. BYTES_TO_WORDS_8(3B, A0, 48, AF, E6, DC, AE, BA),
  13765. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  13766. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  13767. {BYTES_TO_WORDS_8(98, 17, F8, 16, 5B, 81, F2, 59),
  13768. BYTES_TO_WORDS_8(D9, 28, CE, 2D, DB, FC, 9B, 02),
  13769. BYTES_TO_WORDS_8(07, 0B, 87, CE, 95, 62, A0, 55),
  13770. BYTES_TO_WORDS_8(AC, BB, DC, F9, 7E, 66, BE, 79),
  13771. BYTES_TO_WORDS_8(B8, D4, 10, FB, 8F, D0, 47, 9C),
  13772. BYTES_TO_WORDS_8(19, 54, 85, A6, 48, B4, 17, FD),
  13773. BYTES_TO_WORDS_8(A8, 08, 11, 0E, FC, FB, A4, 5D),
  13774. BYTES_TO_WORDS_8(65, C4, A3, 26, 77, DA, 3A, 48)},
  13775. {BYTES_TO_WORDS_8(07, 00, 00, 00, 00, 00, 00, 00),
  13776. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  13777. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  13778. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00)},
  13779. &double_jacobian_secp256k1,
  13780. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  13781. &mod_sqrt_default,
  13782. #endif
  13783. &x_side_secp256k1,
  13784. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  13785. &vli_mmod_fast_secp256k1
  13786. #endif
  13787. };
  13788. MG_UECC_Curve mg_uecc_secp256k1(void) {
  13789. return &curve_secp256k1;
  13790. }
  13791. /* Double in place */
  13792. static void double_jacobian_secp256k1(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  13793. mg_uecc_word_t *Z1, MG_UECC_Curve curve) {
  13794. /* t1 = X, t2 = Y, t3 = Z */
  13795. mg_uecc_word_t t4[num_words_secp256k1];
  13796. mg_uecc_word_t t5[num_words_secp256k1];
  13797. if (mg_uecc_vli_isZero(Z1, num_words_secp256k1)) {
  13798. return;
  13799. }
  13800. mg_uecc_vli_modSquare_fast(t5, Y1, curve); /* t5 = y1^2 */
  13801. mg_uecc_vli_modMult_fast(t4, X1, t5, curve); /* t4 = x1*y1^2 = A */
  13802. mg_uecc_vli_modSquare_fast(X1, X1, curve); /* t1 = x1^2 */
  13803. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = y1^4 */
  13804. mg_uecc_vli_modMult_fast(Z1, Y1, Z1, curve); /* t3 = y1*z1 = z3 */
  13805. mg_uecc_vli_modAdd(Y1, X1, X1, curve->p,
  13806. num_words_secp256k1); /* t2 = 2*x1^2 */
  13807. mg_uecc_vli_modAdd(Y1, Y1, X1, curve->p,
  13808. num_words_secp256k1); /* t2 = 3*x1^2 */
  13809. if (mg_uecc_vli_testBit(Y1, 0)) {
  13810. mg_uecc_word_t carry =
  13811. mg_uecc_vli_add(Y1, Y1, curve->p, num_words_secp256k1);
  13812. mg_uecc_vli_rshift1(Y1, num_words_secp256k1);
  13813. Y1[num_words_secp256k1 - 1] |= carry << (MG_UECC_WORD_BITS - 1);
  13814. } else {
  13815. mg_uecc_vli_rshift1(Y1, num_words_secp256k1);
  13816. }
  13817. /* t2 = 3/2*(x1^2) = B */
  13818. mg_uecc_vli_modSquare_fast(X1, Y1, curve); /* t1 = B^2 */
  13819. mg_uecc_vli_modSub(X1, X1, t4, curve->p,
  13820. num_words_secp256k1); /* t1 = B^2 - A */
  13821. mg_uecc_vli_modSub(X1, X1, t4, curve->p,
  13822. num_words_secp256k1); /* t1 = B^2 - 2A = x3 */
  13823. mg_uecc_vli_modSub(t4, t4, X1, curve->p,
  13824. num_words_secp256k1); /* t4 = A - x3 */
  13825. mg_uecc_vli_modMult_fast(Y1, Y1, t4, curve); /* t2 = B * (A - x3) */
  13826. mg_uecc_vli_modSub(Y1, Y1, t5, curve->p,
  13827. num_words_secp256k1); /* t2 = B * (A - x3) - y1^4 = y3 */
  13828. }
  13829. /* Computes result = x^3 + b. result must not overlap x. */
  13830. static void x_side_secp256k1(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  13831. MG_UECC_Curve curve) {
  13832. mg_uecc_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  13833. mg_uecc_vli_modMult_fast(result, result, x, curve); /* r = x^3 */
  13834. mg_uecc_vli_modAdd(result, result, curve->b, curve->p,
  13835. num_words_secp256k1); /* r = x^3 + b */
  13836. }
  13837. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256k1)
  13838. static void omega_mult_secp256k1(mg_uecc_word_t *result,
  13839. const mg_uecc_word_t *right);
  13840. static void vli_mmod_fast_secp256k1(mg_uecc_word_t *result,
  13841. mg_uecc_word_t *product) {
  13842. mg_uecc_word_t tmp[2 * num_words_secp256k1];
  13843. mg_uecc_word_t carry;
  13844. mg_uecc_vli_clear(tmp, num_words_secp256k1);
  13845. mg_uecc_vli_clear(tmp + num_words_secp256k1, num_words_secp256k1);
  13846. omega_mult_secp256k1(tmp,
  13847. product + num_words_secp256k1); /* (Rq, q) = q * c */
  13848. carry = mg_uecc_vli_add(result, product, tmp,
  13849. num_words_secp256k1); /* (C, r) = r + q */
  13850. mg_uecc_vli_clear(product, num_words_secp256k1);
  13851. omega_mult_secp256k1(product, tmp + num_words_secp256k1); /* Rq*c */
  13852. carry += mg_uecc_vli_add(result, result, product,
  13853. num_words_secp256k1); /* (C1, r) = r + Rq*c */
  13854. while (carry > 0) {
  13855. --carry;
  13856. mg_uecc_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  13857. }
  13858. if (mg_uecc_vli_cmp_unsafe(result, curve_secp256k1.p, num_words_secp256k1) >
  13859. 0) {
  13860. mg_uecc_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  13861. }
  13862. }
  13863. #if MG_UECC_WORD_SIZE == 1
  13864. static void omega_mult_secp256k1(uint8_t *result, const uint8_t *right) {
  13865. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  13866. mg_uecc_word_t r0 = 0;
  13867. mg_uecc_word_t r1 = 0;
  13868. mg_uecc_word_t r2 = 0;
  13869. wordcount_t k;
  13870. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  13871. muladd(0xD1, right[0], &r0, &r1, &r2);
  13872. result[0] = r0;
  13873. r0 = r1;
  13874. r1 = r2;
  13875. /* r2 is still 0 */
  13876. for (k = 1; k < num_words_secp256k1; ++k) {
  13877. muladd(0x03, right[k - 1], &r0, &r1, &r2);
  13878. muladd(0xD1, right[k], &r0, &r1, &r2);
  13879. result[k] = r0;
  13880. r0 = r1;
  13881. r1 = r2;
  13882. r2 = 0;
  13883. }
  13884. muladd(0x03, right[num_words_secp256k1 - 1], &r0, &r1, &r2);
  13885. result[num_words_secp256k1] = r0;
  13886. result[num_words_secp256k1 + 1] = r1;
  13887. /* add the 2^32 multiple */
  13888. result[4 + num_words_secp256k1] =
  13889. mg_uecc_vli_add(result + 4, result + 4, right, num_words_secp256k1);
  13890. }
  13891. #elif MG_UECC_WORD_SIZE == 4
  13892. static void omega_mult_secp256k1(uint32_t *result, const uint32_t *right) {
  13893. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  13894. uint32_t carry = 0;
  13895. wordcount_t k;
  13896. for (k = 0; k < num_words_secp256k1; ++k) {
  13897. uint64_t p = (uint64_t) 0x3D1 * right[k] + carry;
  13898. result[k] = (uint32_t) p;
  13899. carry = p >> 32;
  13900. }
  13901. result[num_words_secp256k1] = carry;
  13902. /* add the 2^32 multiple */
  13903. result[1 + num_words_secp256k1] =
  13904. mg_uecc_vli_add(result + 1, result + 1, right, num_words_secp256k1);
  13905. }
  13906. #else
  13907. static void omega_mult_secp256k1(uint64_t *result, const uint64_t *right) {
  13908. mg_uecc_word_t r0 = 0;
  13909. mg_uecc_word_t r1 = 0;
  13910. mg_uecc_word_t r2 = 0;
  13911. wordcount_t k;
  13912. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  13913. for (k = 0; k < num_words_secp256k1; ++k) {
  13914. muladd(0x1000003D1ull, right[k], &r0, &r1, &r2);
  13915. result[k] = r0;
  13916. r0 = r1;
  13917. r1 = r2;
  13918. r2 = 0;
  13919. }
  13920. result[num_words_secp256k1] = r0;
  13921. }
  13922. #endif /* MG_UECC_WORD_SIZE */
  13923. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && && !asm_mmod_fast_secp256k1) */
  13924. #endif /* MG_UECC_SUPPORTS_secp256k1 */
  13925. #endif /* _UECC_CURVE_SPECIFIC_H_ */
  13926. /* Returns 1 if 'point' is the point at infinity, 0 otherwise. */
  13927. #define EccPoint_isZero(point, curve) \
  13928. mg_uecc_vli_isZero((point), (wordcount_t) ((curve)->num_words * 2))
  13929. /* Point multiplication algorithm using Montgomery's ladder with co-Z
  13930. coordinates. From http://eprint.iacr.org/2011/338.pdf
  13931. */
  13932. /* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
  13933. static void apply_z(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  13934. const mg_uecc_word_t *const Z, MG_UECC_Curve curve) {
  13935. mg_uecc_word_t t1[MG_UECC_MAX_WORDS];
  13936. mg_uecc_vli_modSquare_fast(t1, Z, curve); /* z^2 */
  13937. mg_uecc_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
  13938. mg_uecc_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */
  13939. mg_uecc_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
  13940. }
  13941. /* P = (x1, y1) => 2P, (x2, y2) => P' */
  13942. static void XYcZ_initial_double(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  13943. mg_uecc_word_t *X2, mg_uecc_word_t *Y2,
  13944. const mg_uecc_word_t *const initial_Z,
  13945. MG_UECC_Curve curve) {
  13946. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  13947. wordcount_t num_words = curve->num_words;
  13948. if (initial_Z) {
  13949. mg_uecc_vli_set(z, initial_Z, num_words);
  13950. } else {
  13951. mg_uecc_vli_clear(z, num_words);
  13952. z[0] = 1;
  13953. }
  13954. mg_uecc_vli_set(X2, X1, num_words);
  13955. mg_uecc_vli_set(Y2, Y1, num_words);
  13956. apply_z(X1, Y1, z, curve);
  13957. curve->double_jacobian(X1, Y1, z, curve);
  13958. apply_z(X2, Y2, z, curve);
  13959. }
  13960. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  13961. Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
  13962. or P => P', Q => P + Q
  13963. */
  13964. static void XYcZ_add(mg_uecc_word_t *X1, mg_uecc_word_t *Y1, mg_uecc_word_t *X2,
  13965. mg_uecc_word_t *Y2, MG_UECC_Curve curve) {
  13966. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  13967. mg_uecc_word_t t5[MG_UECC_MAX_WORDS] = {0};
  13968. wordcount_t num_words = curve->num_words;
  13969. mg_uecc_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  13970. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  13971. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  13972. mg_uecc_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  13973. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  13974. mg_uecc_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */
  13975. mg_uecc_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
  13976. mg_uecc_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
  13977. mg_uecc_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
  13978. mg_uecc_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */
  13979. mg_uecc_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
  13980. mg_uecc_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */
  13981. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
  13982. mg_uecc_vli_set(X2, t5, num_words);
  13983. }
  13984. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  13985. Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
  13986. or P => P - Q, Q => P + Q
  13987. */
  13988. static void XYcZ_addC(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  13989. mg_uecc_word_t *X2, mg_uecc_word_t *Y2,
  13990. MG_UECC_Curve curve) {
  13991. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  13992. mg_uecc_word_t t5[MG_UECC_MAX_WORDS] = {0};
  13993. mg_uecc_word_t t6[MG_UECC_MAX_WORDS];
  13994. mg_uecc_word_t t7[MG_UECC_MAX_WORDS];
  13995. wordcount_t num_words = curve->num_words;
  13996. mg_uecc_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  13997. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  13998. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  13999. mg_uecc_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  14000. mg_uecc_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
  14001. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  14002. mg_uecc_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
  14003. mg_uecc_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */
  14004. mg_uecc_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
  14005. mg_uecc_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */
  14006. mg_uecc_vli_modSub(X2, X2, t6, curve->p,
  14007. num_words); /* t3 = D - (B + C) = x3 */
  14008. mg_uecc_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
  14009. mg_uecc_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */
  14010. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p,
  14011. num_words); /* t4 = (y2 - y1)*(B - x3) - E = y3 */
  14012. mg_uecc_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */
  14013. mg_uecc_vli_modSub(t7, t7, t6, curve->p,
  14014. num_words); /* t7 = F - (B + C) = x3' */
  14015. mg_uecc_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
  14016. mg_uecc_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */
  14017. mg_uecc_vli_modSub(Y1, t6, Y1, curve->p,
  14018. num_words); /* t2 = (y2+y1)*(x3' - B) - E = y3' */
  14019. mg_uecc_vli_set(X1, t7, num_words);
  14020. }
  14021. /* result may overlap point. */
  14022. static void EccPoint_mult(mg_uecc_word_t *result, const mg_uecc_word_t *point,
  14023. const mg_uecc_word_t *scalar,
  14024. const mg_uecc_word_t *initial_Z, bitcount_t num_bits,
  14025. MG_UECC_Curve curve) {
  14026. /* R0 and R1 */
  14027. mg_uecc_word_t Rx[2][MG_UECC_MAX_WORDS];
  14028. mg_uecc_word_t Ry[2][MG_UECC_MAX_WORDS];
  14029. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  14030. bitcount_t i;
  14031. mg_uecc_word_t nb;
  14032. wordcount_t num_words = curve->num_words;
  14033. mg_uecc_vli_set(Rx[1], point, num_words);
  14034. mg_uecc_vli_set(Ry[1], point + num_words, num_words);
  14035. XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
  14036. for (i = num_bits - 2; i > 0; --i) {
  14037. nb = !mg_uecc_vli_testBit(scalar, i);
  14038. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  14039. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  14040. }
  14041. nb = !mg_uecc_vli_testBit(scalar, 0);
  14042. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  14043. /* Find final 1/Z value. */
  14044. mg_uecc_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
  14045. mg_uecc_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */
  14046. mg_uecc_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */
  14047. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0)) */
  14048. /* yP / (xP * Yb * (X1 - X0)) */
  14049. mg_uecc_vli_modMult_fast(z, z, point + num_words, curve);
  14050. mg_uecc_vli_modMult_fast(z, z, Rx[1 - nb],
  14051. curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */
  14052. /* End 1/Z calculation */
  14053. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  14054. apply_z(Rx[0], Ry[0], z, curve);
  14055. mg_uecc_vli_set(result, Rx[0], num_words);
  14056. mg_uecc_vli_set(result + num_words, Ry[0], num_words);
  14057. }
  14058. static mg_uecc_word_t regularize_k(const mg_uecc_word_t *const k,
  14059. mg_uecc_word_t *k0, mg_uecc_word_t *k1,
  14060. MG_UECC_Curve curve) {
  14061. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  14062. bitcount_t num_n_bits = curve->num_n_bits;
  14063. mg_uecc_word_t carry =
  14064. mg_uecc_vli_add(k0, k, curve->n, num_n_words) ||
  14065. (num_n_bits < ((bitcount_t) num_n_words * MG_UECC_WORD_SIZE * 8) &&
  14066. mg_uecc_vli_testBit(k0, num_n_bits));
  14067. mg_uecc_vli_add(k1, k0, curve->n, num_n_words);
  14068. return carry;
  14069. }
  14070. /* Generates a random integer in the range 0 < random < top.
  14071. Both random and top have num_words words. */
  14072. MG_UECC_VLI_API int mg_uecc_generate_random_int(mg_uecc_word_t *random,
  14073. const mg_uecc_word_t *top,
  14074. wordcount_t num_words) {
  14075. mg_uecc_word_t mask = (mg_uecc_word_t) -1;
  14076. mg_uecc_word_t tries;
  14077. bitcount_t num_bits = mg_uecc_vli_numBits(top, num_words);
  14078. if (!g_rng_function) {
  14079. return 0;
  14080. }
  14081. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  14082. if (!g_rng_function((uint8_t *) random,
  14083. (unsigned int) (num_words * MG_UECC_WORD_SIZE))) {
  14084. return 0;
  14085. }
  14086. random[num_words - 1] &=
  14087. mask >> ((bitcount_t) (num_words * MG_UECC_WORD_SIZE * 8 - num_bits));
  14088. if (!mg_uecc_vli_isZero(random, num_words) &&
  14089. mg_uecc_vli_cmp(top, random, num_words) == 1) {
  14090. return 1;
  14091. }
  14092. }
  14093. return 0;
  14094. }
  14095. static mg_uecc_word_t EccPoint_compute_public_key(mg_uecc_word_t *result,
  14096. mg_uecc_word_t *private_key,
  14097. MG_UECC_Curve curve) {
  14098. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  14099. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  14100. mg_uecc_word_t *p2[2] = {tmp1, tmp2};
  14101. mg_uecc_word_t *initial_Z = 0;
  14102. mg_uecc_word_t carry;
  14103. /* Regularize the bitcount for the private key so that attackers cannot use a
  14104. side channel attack to learn the number of leading zeros. */
  14105. carry = regularize_k(private_key, tmp1, tmp2, curve);
  14106. /* If an RNG function was specified, try to get a random initial Z value to
  14107. improve protection against side-channel attacks. */
  14108. if (g_rng_function) {
  14109. if (!mg_uecc_generate_random_int(p2[carry], curve->p, curve->num_words)) {
  14110. return 0;
  14111. }
  14112. initial_Z = p2[carry];
  14113. }
  14114. EccPoint_mult(result, curve->G, p2[!carry], initial_Z,
  14115. (bitcount_t) (curve->num_n_bits + 1), curve);
  14116. if (EccPoint_isZero(result, curve)) {
  14117. return 0;
  14118. }
  14119. return 1;
  14120. }
  14121. #if MG_UECC_WORD_SIZE == 1
  14122. MG_UECC_VLI_API void mg_uecc_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  14123. const uint8_t *native) {
  14124. wordcount_t i;
  14125. for (i = 0; i < num_bytes; ++i) {
  14126. bytes[i] = native[(num_bytes - 1) - i];
  14127. }
  14128. }
  14129. MG_UECC_VLI_API void mg_uecc_vli_bytesToNative(uint8_t *native,
  14130. const uint8_t *bytes,
  14131. int num_bytes) {
  14132. mg_uecc_vli_nativeToBytes(native, num_bytes, bytes);
  14133. }
  14134. #else
  14135. MG_UECC_VLI_API void mg_uecc_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  14136. const mg_uecc_word_t *native) {
  14137. int i;
  14138. for (i = 0; i < num_bytes; ++i) {
  14139. unsigned b = (unsigned) (num_bytes - 1 - i);
  14140. bytes[i] = (uint8_t) (native[b / MG_UECC_WORD_SIZE] >>
  14141. (8 * (b % MG_UECC_WORD_SIZE)));
  14142. }
  14143. }
  14144. MG_UECC_VLI_API void mg_uecc_vli_bytesToNative(mg_uecc_word_t *native,
  14145. const uint8_t *bytes,
  14146. int num_bytes) {
  14147. int i;
  14148. mg_uecc_vli_clear(native,
  14149. (wordcount_t) ((num_bytes + (MG_UECC_WORD_SIZE - 1)) /
  14150. MG_UECC_WORD_SIZE));
  14151. for (i = 0; i < num_bytes; ++i) {
  14152. unsigned b = (unsigned) (num_bytes - 1 - i);
  14153. native[b / MG_UECC_WORD_SIZE] |= (mg_uecc_word_t) bytes[i]
  14154. << (8 * (b % MG_UECC_WORD_SIZE));
  14155. }
  14156. }
  14157. #endif /* MG_UECC_WORD_SIZE */
  14158. int mg_uecc_make_key(uint8_t *public_key, uint8_t *private_key,
  14159. MG_UECC_Curve curve) {
  14160. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14161. mg_uecc_word_t *_private = (mg_uecc_word_t *) private_key;
  14162. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  14163. #else
  14164. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  14165. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  14166. #endif
  14167. mg_uecc_word_t tries;
  14168. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  14169. if (!mg_uecc_generate_random_int(_private, curve->n,
  14170. BITS_TO_WORDS(curve->num_n_bits))) {
  14171. return 0;
  14172. }
  14173. if (EccPoint_compute_public_key(_public, _private, curve)) {
  14174. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  14175. mg_uecc_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits),
  14176. _private);
  14177. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  14178. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  14179. _public + curve->num_words);
  14180. #endif
  14181. return 1;
  14182. }
  14183. }
  14184. return 0;
  14185. }
  14186. int mg_uecc_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
  14187. uint8_t *secret, MG_UECC_Curve curve) {
  14188. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  14189. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  14190. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  14191. mg_uecc_word_t *p2[2] = {_private, tmp};
  14192. mg_uecc_word_t *initial_Z = 0;
  14193. mg_uecc_word_t carry;
  14194. wordcount_t num_words = curve->num_words;
  14195. wordcount_t num_bytes = curve->num_bytes;
  14196. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14197. bcopy((uint8_t *) _private, private_key, num_bytes);
  14198. bcopy((uint8_t *) _public, public_key, num_bytes * 2);
  14199. #else
  14200. mg_uecc_vli_bytesToNative(_private, private_key,
  14201. BITS_TO_BYTES(curve->num_n_bits));
  14202. mg_uecc_vli_bytesToNative(_public, public_key, num_bytes);
  14203. mg_uecc_vli_bytesToNative(_public + num_words, public_key + num_bytes,
  14204. num_bytes);
  14205. #endif
  14206. /* Regularize the bitcount for the private key so that attackers cannot use a
  14207. side channel attack to learn the number of leading zeros. */
  14208. carry = regularize_k(_private, _private, tmp, curve);
  14209. /* If an RNG function was specified, try to get a random initial Z value to
  14210. improve protection against side-channel attacks. */
  14211. if (g_rng_function) {
  14212. if (!mg_uecc_generate_random_int(p2[carry], curve->p, num_words)) {
  14213. return 0;
  14214. }
  14215. initial_Z = p2[carry];
  14216. }
  14217. EccPoint_mult(_public, _public, p2[!carry], initial_Z,
  14218. (bitcount_t) (curve->num_n_bits + 1), curve);
  14219. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14220. bcopy((uint8_t *) secret, (uint8_t *) _public, num_bytes);
  14221. #else
  14222. mg_uecc_vli_nativeToBytes(secret, num_bytes, _public);
  14223. #endif
  14224. return !EccPoint_isZero(_public, curve);
  14225. }
  14226. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  14227. void mg_uecc_compress(const uint8_t *public_key, uint8_t *compressed,
  14228. MG_UECC_Curve curve) {
  14229. wordcount_t i;
  14230. for (i = 0; i < curve->num_bytes; ++i) {
  14231. compressed[i + 1] = public_key[i];
  14232. }
  14233. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14234. compressed[0] = 2 + (public_key[curve->num_bytes] & 0x01);
  14235. #else
  14236. compressed[0] = 2 + (public_key[curve->num_bytes * 2 - 1] & 0x01);
  14237. #endif
  14238. }
  14239. void mg_uecc_decompress(const uint8_t *compressed, uint8_t *public_key,
  14240. MG_UECC_Curve curve) {
  14241. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14242. mg_uecc_word_t *point = (mg_uecc_word_t *) public_key;
  14243. #else
  14244. mg_uecc_word_t point[MG_UECC_MAX_WORDS * 2];
  14245. #endif
  14246. mg_uecc_word_t *y = point + curve->num_words;
  14247. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14248. bcopy(public_key, compressed + 1, curve->num_bytes);
  14249. #else
  14250. mg_uecc_vli_bytesToNative(point, compressed + 1, curve->num_bytes);
  14251. #endif
  14252. curve->x_side(y, point, curve);
  14253. curve->mod_sqrt(y, curve);
  14254. if ((uint8_t) (y[0] & 0x01) != (compressed[0] & 0x01)) {
  14255. mg_uecc_vli_sub(y, curve->p, y, curve->num_words);
  14256. }
  14257. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  14258. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, point);
  14259. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, y);
  14260. #endif
  14261. }
  14262. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  14263. MG_UECC_VLI_API int mg_uecc_valid_point(const mg_uecc_word_t *point,
  14264. MG_UECC_Curve curve) {
  14265. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  14266. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  14267. wordcount_t num_words = curve->num_words;
  14268. /* The point at infinity is invalid. */
  14269. if (EccPoint_isZero(point, curve)) {
  14270. return 0;
  14271. }
  14272. /* x and y must be smaller than p. */
  14273. if (mg_uecc_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
  14274. mg_uecc_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
  14275. return 0;
  14276. }
  14277. mg_uecc_vli_modSquare_fast(tmp1, point + num_words, curve);
  14278. curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
  14279. /* Make sure that y^2 == x^3 + ax + b */
  14280. return (int) (mg_uecc_vli_equal(tmp1, tmp2, num_words));
  14281. }
  14282. int mg_uecc_valid_public_key(const uint8_t *public_key, MG_UECC_Curve curve) {
  14283. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14284. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  14285. #else
  14286. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  14287. #endif
  14288. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  14289. mg_uecc_vli_bytesToNative(_public, public_key, curve->num_bytes);
  14290. mg_uecc_vli_bytesToNative(_public + curve->num_words,
  14291. public_key + curve->num_bytes, curve->num_bytes);
  14292. #endif
  14293. return mg_uecc_valid_point(_public, curve);
  14294. }
  14295. int mg_uecc_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
  14296. MG_UECC_Curve curve) {
  14297. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14298. mg_uecc_word_t *_private = (mg_uecc_word_t *) private_key;
  14299. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  14300. #else
  14301. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  14302. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  14303. #endif
  14304. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  14305. mg_uecc_vli_bytesToNative(_private, private_key,
  14306. BITS_TO_BYTES(curve->num_n_bits));
  14307. #endif
  14308. /* Make sure the private key is in the range [1, n-1]. */
  14309. if (mg_uecc_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
  14310. return 0;
  14311. }
  14312. if (mg_uecc_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) !=
  14313. 1) {
  14314. return 0;
  14315. }
  14316. /* Compute public key. */
  14317. if (!EccPoint_compute_public_key(_public, _private, curve)) {
  14318. return 0;
  14319. }
  14320. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  14321. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  14322. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  14323. _public + curve->num_words);
  14324. #endif
  14325. return 1;
  14326. }
  14327. /* -------- ECDSA code -------- */
  14328. static void bits2int(mg_uecc_word_t *native, const uint8_t *bits,
  14329. unsigned bits_size, MG_UECC_Curve curve) {
  14330. unsigned num_n_bytes = (unsigned) BITS_TO_BYTES(curve->num_n_bits);
  14331. unsigned num_n_words = (unsigned) BITS_TO_WORDS(curve->num_n_bits);
  14332. int shift;
  14333. mg_uecc_word_t carry;
  14334. mg_uecc_word_t *ptr;
  14335. if (bits_size > num_n_bytes) {
  14336. bits_size = num_n_bytes;
  14337. }
  14338. mg_uecc_vli_clear(native, (wordcount_t) num_n_words);
  14339. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14340. bcopy((uint8_t *) native, bits, bits_size);
  14341. #else
  14342. mg_uecc_vli_bytesToNative(native, bits, (int) bits_size);
  14343. #endif
  14344. if (bits_size * 8 <= (unsigned) curve->num_n_bits) {
  14345. return;
  14346. }
  14347. shift = (int) bits_size * 8 - curve->num_n_bits;
  14348. carry = 0;
  14349. ptr = native + num_n_words;
  14350. while (ptr-- > native) {
  14351. mg_uecc_word_t temp = *ptr;
  14352. *ptr = (temp >> shift) | carry;
  14353. carry = temp << (MG_UECC_WORD_BITS - shift);
  14354. }
  14355. /* Reduce mod curve_n */
  14356. if (mg_uecc_vli_cmp_unsafe(curve->n, native, (wordcount_t) num_n_words) !=
  14357. 1) {
  14358. mg_uecc_vli_sub(native, native, curve->n, (wordcount_t) num_n_words);
  14359. }
  14360. }
  14361. static int mg_uecc_sign_with_k_internal(const uint8_t *private_key,
  14362. const uint8_t *message_hash,
  14363. unsigned hash_size, mg_uecc_word_t *k,
  14364. uint8_t *signature,
  14365. MG_UECC_Curve curve) {
  14366. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  14367. mg_uecc_word_t s[MG_UECC_MAX_WORDS];
  14368. mg_uecc_word_t *k2[2] = {tmp, s};
  14369. mg_uecc_word_t *initial_Z = 0;
  14370. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14371. mg_uecc_word_t *p = (mg_uecc_word_t *) signature;
  14372. #else
  14373. mg_uecc_word_t p[MG_UECC_MAX_WORDS * 2];
  14374. #endif
  14375. mg_uecc_word_t carry;
  14376. wordcount_t num_words = curve->num_words;
  14377. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  14378. bitcount_t num_n_bits = curve->num_n_bits;
  14379. /* Make sure 0 < k < curve_n */
  14380. if (mg_uecc_vli_isZero(k, num_words) ||
  14381. mg_uecc_vli_cmp(curve->n, k, num_n_words) != 1) {
  14382. return 0;
  14383. }
  14384. carry = regularize_k(k, tmp, s, curve);
  14385. /* If an RNG function was specified, try to get a random initial Z value to
  14386. improve protection against side-channel attacks. */
  14387. if (g_rng_function) {
  14388. if (!mg_uecc_generate_random_int(k2[carry], curve->p, num_words)) {
  14389. return 0;
  14390. }
  14391. initial_Z = k2[carry];
  14392. }
  14393. EccPoint_mult(p, curve->G, k2[!carry], initial_Z,
  14394. (bitcount_t) (num_n_bits + 1), curve);
  14395. if (mg_uecc_vli_isZero(p, num_words)) {
  14396. return 0;
  14397. }
  14398. /* If an RNG function was specified, get a random number
  14399. to prevent side channel analysis of k. */
  14400. if (!g_rng_function) {
  14401. mg_uecc_vli_clear(tmp, num_n_words);
  14402. tmp[0] = 1;
  14403. } else if (!mg_uecc_generate_random_int(tmp, curve->n, num_n_words)) {
  14404. return 0;
  14405. }
  14406. /* Prevent side channel analysis of mg_uecc_vli_modInv() to determine
  14407. bits of k / the private key by premultiplying by a random number */
  14408. mg_uecc_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
  14409. mg_uecc_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */
  14410. mg_uecc_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
  14411. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  14412. mg_uecc_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
  14413. #endif
  14414. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14415. bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
  14416. #else
  14417. mg_uecc_vli_bytesToNative(tmp, private_key,
  14418. BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */
  14419. #endif
  14420. s[num_n_words - 1] = 0;
  14421. mg_uecc_vli_set(s, p, num_words);
  14422. mg_uecc_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
  14423. bits2int(tmp, message_hash, hash_size, curve);
  14424. mg_uecc_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
  14425. mg_uecc_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */
  14426. if (mg_uecc_vli_numBits(s, num_n_words) > (bitcount_t) curve->num_bytes * 8) {
  14427. return 0;
  14428. }
  14429. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14430. bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s,
  14431. curve->num_bytes);
  14432. #else
  14433. mg_uecc_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
  14434. #endif
  14435. return 1;
  14436. }
  14437. #if 0
  14438. /* For testing - sign with an explicitly specified k value */
  14439. int mg_uecc_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
  14440. unsigned hash_size, const uint8_t *k, uint8_t *signature,
  14441. MG_UECC_Curve curve) {
  14442. mg_uecc_word_t k2[MG_UECC_MAX_WORDS];
  14443. bits2int(k2, k, (unsigned) BITS_TO_BYTES(curve->num_n_bits), curve);
  14444. return mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, k2,
  14445. signature, curve);
  14446. }
  14447. #endif
  14448. int mg_uecc_sign(const uint8_t *private_key, const uint8_t *message_hash,
  14449. unsigned hash_size, uint8_t *signature, MG_UECC_Curve curve) {
  14450. mg_uecc_word_t k[MG_UECC_MAX_WORDS];
  14451. mg_uecc_word_t tries;
  14452. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  14453. if (!mg_uecc_generate_random_int(k, curve->n,
  14454. BITS_TO_WORDS(curve->num_n_bits))) {
  14455. return 0;
  14456. }
  14457. if (mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, k,
  14458. signature, curve)) {
  14459. return 1;
  14460. }
  14461. }
  14462. return 0;
  14463. }
  14464. /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always
  14465. the same size as the hash result size. */
  14466. static void HMAC_init(const MG_UECC_HashContext *hash_context,
  14467. const uint8_t *K) {
  14468. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  14469. unsigned i;
  14470. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x36;
  14471. for (; i < hash_context->block_size; ++i) pad[i] = 0x36;
  14472. hash_context->init_hash(hash_context);
  14473. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  14474. }
  14475. static void HMAC_update(const MG_UECC_HashContext *hash_context,
  14476. const uint8_t *message, unsigned message_size) {
  14477. hash_context->update_hash(hash_context, message, message_size);
  14478. }
  14479. static void HMAC_finish(const MG_UECC_HashContext *hash_context,
  14480. const uint8_t *K, uint8_t *result) {
  14481. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  14482. unsigned i;
  14483. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x5c;
  14484. for (; i < hash_context->block_size; ++i) pad[i] = 0x5c;
  14485. hash_context->finish_hash(hash_context, result);
  14486. hash_context->init_hash(hash_context);
  14487. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  14488. hash_context->update_hash(hash_context, result, hash_context->result_size);
  14489. hash_context->finish_hash(hash_context, result);
  14490. }
  14491. /* V = HMAC_K(V) */
  14492. static void update_V(const MG_UECC_HashContext *hash_context, uint8_t *K,
  14493. uint8_t *V) {
  14494. HMAC_init(hash_context, K);
  14495. HMAC_update(hash_context, V, hash_context->result_size);
  14496. HMAC_finish(hash_context, K, V);
  14497. }
  14498. /* Deterministic signing, similar to RFC 6979. Differences are:
  14499. * We just use H(m) directly rather than bits2octets(H(m))
  14500. (it is not reduced modulo curve_n).
  14501. * We generate a value for k (aka T) directly rather than converting
  14502. endianness.
  14503. Layout of hash_context->tmp: <K> | <V> | (1 byte overlapped 0x00 or 0x01) /
  14504. <HMAC pad> */
  14505. int mg_uecc_sign_deterministic(const uint8_t *private_key,
  14506. const uint8_t *message_hash, unsigned hash_size,
  14507. const MG_UECC_HashContext *hash_context,
  14508. uint8_t *signature, MG_UECC_Curve curve) {
  14509. uint8_t *K = hash_context->tmp;
  14510. uint8_t *V = K + hash_context->result_size;
  14511. wordcount_t num_bytes = curve->num_bytes;
  14512. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  14513. bitcount_t num_n_bits = curve->num_n_bits;
  14514. mg_uecc_word_t tries;
  14515. unsigned i;
  14516. for (i = 0; i < hash_context->result_size; ++i) {
  14517. V[i] = 0x01;
  14518. K[i] = 0;
  14519. }
  14520. /* K = HMAC_K(V || 0x00 || int2octets(x) || h(m)) */
  14521. HMAC_init(hash_context, K);
  14522. V[hash_context->result_size] = 0x00;
  14523. HMAC_update(hash_context, V, hash_context->result_size + 1);
  14524. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  14525. HMAC_update(hash_context, message_hash, hash_size);
  14526. HMAC_finish(hash_context, K, K);
  14527. update_V(hash_context, K, V);
  14528. /* K = HMAC_K(V || 0x01 || int2octets(x) || h(m)) */
  14529. HMAC_init(hash_context, K);
  14530. V[hash_context->result_size] = 0x01;
  14531. HMAC_update(hash_context, V, hash_context->result_size + 1);
  14532. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  14533. HMAC_update(hash_context, message_hash, hash_size);
  14534. HMAC_finish(hash_context, K, K);
  14535. update_V(hash_context, K, V);
  14536. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  14537. mg_uecc_word_t T[MG_UECC_MAX_WORDS];
  14538. uint8_t *T_ptr = (uint8_t *) T;
  14539. wordcount_t T_bytes = 0;
  14540. for (;;) {
  14541. update_V(hash_context, K, V);
  14542. for (i = 0; i < hash_context->result_size; ++i) {
  14543. T_ptr[T_bytes++] = V[i];
  14544. if (T_bytes >= num_n_words * MG_UECC_WORD_SIZE) {
  14545. goto filled;
  14546. }
  14547. }
  14548. }
  14549. filled:
  14550. if ((bitcount_t) num_n_words * MG_UECC_WORD_SIZE * 8 > num_n_bits) {
  14551. mg_uecc_word_t mask = (mg_uecc_word_t) -1;
  14552. T[num_n_words - 1] &=
  14553. mask >>
  14554. ((bitcount_t) (num_n_words * MG_UECC_WORD_SIZE * 8 - num_n_bits));
  14555. }
  14556. if (mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, T,
  14557. signature, curve)) {
  14558. return 1;
  14559. }
  14560. /* K = HMAC_K(V || 0x00) */
  14561. HMAC_init(hash_context, K);
  14562. V[hash_context->result_size] = 0x00;
  14563. HMAC_update(hash_context, V, hash_context->result_size + 1);
  14564. HMAC_finish(hash_context, K, K);
  14565. update_V(hash_context, K, V);
  14566. }
  14567. return 0;
  14568. }
  14569. static bitcount_t smax(bitcount_t a, bitcount_t b) {
  14570. return (a > b ? a : b);
  14571. }
  14572. int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash,
  14573. unsigned hash_size, const uint8_t *signature,
  14574. MG_UECC_Curve curve) {
  14575. mg_uecc_word_t u1[MG_UECC_MAX_WORDS], u2[MG_UECC_MAX_WORDS];
  14576. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  14577. mg_uecc_word_t sum[MG_UECC_MAX_WORDS * 2];
  14578. mg_uecc_word_t rx[MG_UECC_MAX_WORDS];
  14579. mg_uecc_word_t ry[MG_UECC_MAX_WORDS];
  14580. mg_uecc_word_t tx[MG_UECC_MAX_WORDS];
  14581. mg_uecc_word_t ty[MG_UECC_MAX_WORDS];
  14582. mg_uecc_word_t tz[MG_UECC_MAX_WORDS];
  14583. const mg_uecc_word_t *points[4];
  14584. const mg_uecc_word_t *point;
  14585. bitcount_t num_bits;
  14586. bitcount_t i;
  14587. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14588. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  14589. #else
  14590. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  14591. #endif
  14592. mg_uecc_word_t r[MG_UECC_MAX_WORDS], s[MG_UECC_MAX_WORDS];
  14593. wordcount_t num_words = curve->num_words;
  14594. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  14595. rx[num_n_words - 1] = 0;
  14596. r[num_n_words - 1] = 0;
  14597. s[num_n_words - 1] = 0;
  14598. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  14599. bcopy((uint8_t *) r, signature, curve->num_bytes);
  14600. bcopy((uint8_t *) s, signature + curve->num_bytes, curve->num_bytes);
  14601. #else
  14602. mg_uecc_vli_bytesToNative(_public, public_key, curve->num_bytes);
  14603. mg_uecc_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
  14604. curve->num_bytes);
  14605. mg_uecc_vli_bytesToNative(r, signature, curve->num_bytes);
  14606. mg_uecc_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
  14607. #endif
  14608. /* r, s must not be 0. */
  14609. if (mg_uecc_vli_isZero(r, num_words) || mg_uecc_vli_isZero(s, num_words)) {
  14610. return 0;
  14611. }
  14612. /* r, s must be < n. */
  14613. if (mg_uecc_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
  14614. mg_uecc_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
  14615. return 0;
  14616. }
  14617. /* Calculate u1 and u2. */
  14618. mg_uecc_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
  14619. u1[num_n_words - 1] = 0;
  14620. bits2int(u1, message_hash, hash_size, curve);
  14621. mg_uecc_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
  14622. mg_uecc_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */
  14623. /* Calculate sum = G + Q. */
  14624. mg_uecc_vli_set(sum, _public, num_words);
  14625. mg_uecc_vli_set(sum + num_words, _public + num_words, num_words);
  14626. mg_uecc_vli_set(tx, curve->G, num_words);
  14627. mg_uecc_vli_set(ty, curve->G + num_words, num_words);
  14628. mg_uecc_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
  14629. XYcZ_add(tx, ty, sum, sum + num_words, curve);
  14630. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
  14631. apply_z(sum, sum + num_words, z, curve);
  14632. /* Use Shamir's trick to calculate u1*G + u2*Q */
  14633. points[0] = 0;
  14634. points[1] = curve->G;
  14635. points[2] = _public;
  14636. points[3] = sum;
  14637. num_bits = smax(mg_uecc_vli_numBits(u1, num_n_words),
  14638. mg_uecc_vli_numBits(u2, num_n_words));
  14639. point =
  14640. points[(!!mg_uecc_vli_testBit(u1, (bitcount_t) (num_bits - 1))) |
  14641. ((!!mg_uecc_vli_testBit(u2, (bitcount_t) (num_bits - 1))) << 1)];
  14642. mg_uecc_vli_set(rx, point, num_words);
  14643. mg_uecc_vli_set(ry, point + num_words, num_words);
  14644. mg_uecc_vli_clear(z, num_words);
  14645. z[0] = 1;
  14646. for (i = num_bits - 2; i >= 0; --i) {
  14647. mg_uecc_word_t index;
  14648. curve->double_jacobian(rx, ry, z, curve);
  14649. index = (!!mg_uecc_vli_testBit(u1, i)) |
  14650. (mg_uecc_word_t) ((!!mg_uecc_vli_testBit(u2, i)) << 1);
  14651. point = points[index];
  14652. if (point) {
  14653. mg_uecc_vli_set(tx, point, num_words);
  14654. mg_uecc_vli_set(ty, point + num_words, num_words);
  14655. apply_z(tx, ty, z, curve);
  14656. mg_uecc_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
  14657. XYcZ_add(tx, ty, rx, ry, curve);
  14658. mg_uecc_vli_modMult_fast(z, z, tz, curve);
  14659. }
  14660. }
  14661. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
  14662. apply_z(rx, ry, z, curve);
  14663. /* v = x1 (mod n) */
  14664. if (mg_uecc_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
  14665. mg_uecc_vli_sub(rx, rx, curve->n, num_n_words);
  14666. }
  14667. /* Accept only if v == r. */
  14668. return (int) (mg_uecc_vli_equal(rx, r, num_words));
  14669. }
  14670. #if MG_UECC_ENABLE_VLI_API
  14671. unsigned mg_uecc_curve_num_words(MG_UECC_Curve curve) {
  14672. return curve->num_words;
  14673. }
  14674. unsigned mg_uecc_curve_num_bytes(MG_UECC_Curve curve) {
  14675. return curve->num_bytes;
  14676. }
  14677. unsigned mg_uecc_curve_num_bits(MG_UECC_Curve curve) {
  14678. return curve->num_bytes * 8;
  14679. }
  14680. unsigned mg_uecc_curve_num_n_words(MG_UECC_Curve curve) {
  14681. return BITS_TO_WORDS(curve->num_n_bits);
  14682. }
  14683. unsigned mg_uecc_curve_num_n_bytes(MG_UECC_Curve curve) {
  14684. return BITS_TO_BYTES(curve->num_n_bits);
  14685. }
  14686. unsigned mg_uecc_curve_num_n_bits(MG_UECC_Curve curve) {
  14687. return curve->num_n_bits;
  14688. }
  14689. const mg_uecc_word_t *mg_uecc_curve_p(MG_UECC_Curve curve) {
  14690. return curve->p;
  14691. }
  14692. const mg_uecc_word_t *mg_uecc_curve_n(MG_UECC_Curve curve) {
  14693. return curve->n;
  14694. }
  14695. const mg_uecc_word_t *mg_uecc_curve_G(MG_UECC_Curve curve) {
  14696. return curve->G;
  14697. }
  14698. const mg_uecc_word_t *mg_uecc_curve_b(MG_UECC_Curve curve) {
  14699. return curve->b;
  14700. }
  14701. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  14702. void mg_uecc_vli_mod_sqrt(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  14703. curve->mod_sqrt(a, curve);
  14704. }
  14705. #endif
  14706. void mg_uecc_vli_mmod_fast(mg_uecc_word_t *result, mg_uecc_word_t *product,
  14707. MG_UECC_Curve curve) {
  14708. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  14709. curve->mmod_fast(result, product);
  14710. #else
  14711. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  14712. #endif
  14713. }
  14714. void mg_uecc_point_mult(mg_uecc_word_t *result, const mg_uecc_word_t *point,
  14715. const mg_uecc_word_t *scalar, MG_UECC_Curve curve) {
  14716. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  14717. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  14718. mg_uecc_word_t *p2[2] = {tmp1, tmp2};
  14719. mg_uecc_word_t carry = regularize_k(scalar, tmp1, tmp2, curve);
  14720. EccPoint_mult(result, point, p2[!carry], 0, curve->num_n_bits + 1, curve);
  14721. }
  14722. #endif /* MG_UECC_ENABLE_VLI_API */
  14723. #endif // MG_TLS_BUILTIN
  14724. // End of uecc BSD-2
  14725. #ifdef MG_ENABLE_LINES
  14726. #line 1 "src/tls_x25519.c"
  14727. #endif
  14728. /**
  14729. * Adapted from STROBE: https://strobe.sourceforge.io/
  14730. * Copyright (c) 2015-2016 Cryptography Research, Inc.
  14731. * Author: Mike Hamburg
  14732. * License: MIT License
  14733. */
  14734. const uint8_t X25519_BASE_POINT[X25519_BYTES] = {9};
  14735. #define X25519_WBITS 32
  14736. typedef uint32_t limb_t;
  14737. typedef uint64_t dlimb_t;
  14738. typedef int64_t sdlimb_t;
  14739. #define NLIMBS (256 / X25519_WBITS)
  14740. typedef limb_t mg_fe[NLIMBS];
  14741. static limb_t umaal(limb_t *carry, limb_t acc, limb_t mand, limb_t mier) {
  14742. dlimb_t tmp = (dlimb_t) mand * mier + acc + *carry;
  14743. *carry = (limb_t) (tmp >> X25519_WBITS);
  14744. return (limb_t) tmp;
  14745. }
  14746. // These functions are implemented in terms of umaal on ARM
  14747. static limb_t adc(limb_t *carry, limb_t acc, limb_t mand) {
  14748. dlimb_t total = (dlimb_t) *carry + acc + mand;
  14749. *carry = (limb_t) (total >> X25519_WBITS);
  14750. return (limb_t) total;
  14751. }
  14752. static limb_t adc0(limb_t *carry, limb_t acc) {
  14753. dlimb_t total = (dlimb_t) *carry + acc;
  14754. *carry = (limb_t) (total >> X25519_WBITS);
  14755. return (limb_t) total;
  14756. }
  14757. // - Precondition: carry is small.
  14758. // - Invariant: result of propagate is < 2^255 + 1 word
  14759. // - In particular, always less than 2p.
  14760. // - Also, output x >= min(x,19)
  14761. static void propagate(mg_fe x, limb_t over) {
  14762. unsigned i;
  14763. limb_t carry;
  14764. over = x[NLIMBS - 1] >> (X25519_WBITS - 1) | over << 1;
  14765. x[NLIMBS - 1] &= ~((limb_t) 1 << (X25519_WBITS - 1));
  14766. carry = over * 19;
  14767. for (i = 0; i < NLIMBS; i++) {
  14768. x[i] = adc0(&carry, x[i]);
  14769. }
  14770. }
  14771. static void add(mg_fe out, const mg_fe a, const mg_fe b) {
  14772. unsigned i;
  14773. limb_t carry = 0;
  14774. for (i = 0; i < NLIMBS; i++) {
  14775. out[i] = adc(&carry, a[i], b[i]);
  14776. }
  14777. propagate(out, carry);
  14778. }
  14779. static void sub(mg_fe out, const mg_fe a, const mg_fe b) {
  14780. unsigned i;
  14781. sdlimb_t carry = -38;
  14782. for (i = 0; i < NLIMBS; i++) {
  14783. carry = carry + a[i] - b[i];
  14784. out[i] = (limb_t) carry;
  14785. carry >>= X25519_WBITS;
  14786. }
  14787. propagate(out, (limb_t) (1 + carry));
  14788. }
  14789. // `b` can contain less than 8 limbs, thus we use `limb_t *` instead of `mg_fe`
  14790. // to avoid build warnings
  14791. static void mul(mg_fe out, const mg_fe a, const limb_t *b, unsigned nb) {
  14792. limb_t accum[2 * NLIMBS] = {0};
  14793. unsigned i, j;
  14794. limb_t carry2;
  14795. for (i = 0; i < nb; i++) {
  14796. limb_t mand = b[i];
  14797. carry2 = 0;
  14798. for (j = 0; j < NLIMBS; j++) {
  14799. limb_t tmp; // "a" may be misaligned
  14800. memcpy(&tmp, &a[j], sizeof(tmp)); // So make an aligned copy
  14801. accum[i + j] = umaal(&carry2, accum[i + j], mand, tmp);
  14802. }
  14803. accum[i + j] = carry2;
  14804. }
  14805. carry2 = 0;
  14806. for (j = 0; j < NLIMBS; j++) {
  14807. out[j] = umaal(&carry2, accum[j], 38, accum[j + NLIMBS]);
  14808. }
  14809. propagate(out, carry2);
  14810. }
  14811. static void sqr(mg_fe out, const mg_fe a) {
  14812. mul(out, a, a, NLIMBS);
  14813. }
  14814. static void mul1(mg_fe out, const mg_fe a) {
  14815. mul(out, a, out, NLIMBS);
  14816. }
  14817. static void sqr1(mg_fe a) {
  14818. mul1(a, a);
  14819. }
  14820. static void condswap(limb_t a[2 * NLIMBS], limb_t b[2 * NLIMBS],
  14821. limb_t doswap) {
  14822. unsigned i;
  14823. for (i = 0; i < 2 * NLIMBS; i++) {
  14824. limb_t xor_ab = (a[i] ^ b[i]) & doswap;
  14825. a[i] ^= xor_ab;
  14826. b[i] ^= xor_ab;
  14827. }
  14828. }
  14829. // Canonicalize a field element x, reducing it to the least residue which is
  14830. // congruent to it mod 2^255-19
  14831. // - Precondition: x < 2^255 + 1 word
  14832. static limb_t canon(mg_fe x) {
  14833. // First, add 19.
  14834. unsigned i;
  14835. limb_t carry0 = 19;
  14836. limb_t res;
  14837. sdlimb_t carry;
  14838. for (i = 0; i < NLIMBS; i++) {
  14839. x[i] = adc0(&carry0, x[i]);
  14840. }
  14841. propagate(x, carry0);
  14842. // Here, 19 <= x2 < 2^255
  14843. // - This is because we added 19, so before propagate it can't be less
  14844. // than 19. After propagate, it still can't be less than 19, because if
  14845. // propagate does anything it adds 19.
  14846. // - We know that the high bit must be clear, because either the input was ~
  14847. // 2^255 + one word + 19 (in which case it propagates to at most 2 words) or
  14848. // it was < 2^255. So now, if we subtract 19, we will get back to something in
  14849. // [0,2^255-19).
  14850. carry = -19;
  14851. res = 0;
  14852. for (i = 0; i < NLIMBS; i++) {
  14853. carry += x[i];
  14854. res |= x[i] = (limb_t) carry;
  14855. carry >>= X25519_WBITS;
  14856. }
  14857. return (limb_t) (((dlimb_t) res - 1) >> X25519_WBITS);
  14858. }
  14859. static const limb_t a24[1] = {121665};
  14860. static void ladder_part1(mg_fe xs[5]) {
  14861. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  14862. add(t1, x2, z2); // t1 = A
  14863. sub(z2, x2, z2); // z2 = B
  14864. add(x2, x3, z3); // x2 = C
  14865. sub(z3, x3, z3); // z3 = D
  14866. mul1(z3, t1); // z3 = DA
  14867. mul1(x2, z2); // x3 = BC
  14868. add(x3, z3, x2); // x3 = DA+CB
  14869. sub(z3, z3, x2); // z3 = DA-CB
  14870. sqr1(t1); // t1 = AA
  14871. sqr1(z2); // z2 = BB
  14872. sub(x2, t1, z2); // x2 = E = AA-BB
  14873. mul(z2, x2, a24, sizeof(a24) / sizeof(a24[0])); // z2 = E*a24
  14874. add(z2, z2, t1); // z2 = E*a24 + AA
  14875. }
  14876. static void ladder_part2(mg_fe xs[5], const mg_fe x1) {
  14877. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  14878. sqr1(z3); // z3 = (DA-CB)^2
  14879. mul1(z3, x1); // z3 = x1 * (DA-CB)^2
  14880. sqr1(x3); // x3 = (DA+CB)^2
  14881. mul1(z2, x2); // z2 = AA*(E*a24+AA)
  14882. sub(x2, t1, x2); // x2 = BB again
  14883. mul1(x2, t1); // x2 = AA*BB
  14884. }
  14885. static void x25519_core(mg_fe xs[5], const uint8_t scalar[X25519_BYTES],
  14886. const uint8_t *x1, int clamp) {
  14887. int i;
  14888. mg_fe x1_limbs;
  14889. limb_t swap = 0;
  14890. limb_t *x2 = xs[0], *x3 = xs[2], *z3 = xs[3];
  14891. memset(xs, 0, 4 * sizeof(mg_fe));
  14892. x2[0] = z3[0] = 1;
  14893. for (i = 0; i < NLIMBS; i++) {
  14894. x3[i] = x1_limbs[i] =
  14895. MG_U32(x1[i * 4 + 3], x1[i * 4 + 2], x1[i * 4 + 1], x1[i * 4]);
  14896. }
  14897. for (i = 255; i >= 0; i--) {
  14898. uint8_t bytei = scalar[i / 8];
  14899. limb_t doswap;
  14900. if (clamp) {
  14901. if (i / 8 == 0) {
  14902. bytei &= (uint8_t) ~7U;
  14903. } else if (i / 8 == X25519_BYTES - 1) {
  14904. bytei &= 0x7F;
  14905. bytei |= 0x40;
  14906. }
  14907. }
  14908. doswap = 0 - (limb_t) ((bytei >> (i % 8)) & 1);
  14909. condswap(x2, x3, swap ^ doswap);
  14910. swap = doswap;
  14911. ladder_part1(xs);
  14912. ladder_part2(xs, (const limb_t *) x1_limbs);
  14913. }
  14914. condswap(x2, x3, swap);
  14915. }
  14916. int mg_tls_x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES],
  14917. const uint8_t x1[X25519_BYTES], int clamp) {
  14918. int i, ret;
  14919. mg_fe xs[5], out_limbs;
  14920. limb_t *x2, *z2, *z3, *prev;
  14921. static const struct {
  14922. uint8_t a, c, n;
  14923. } steps[13] = {{2, 1, 1}, {2, 1, 1}, {4, 2, 3}, {2, 4, 6}, {3, 1, 1},
  14924. {3, 2, 12}, {4, 3, 25}, {2, 3, 25}, {2, 4, 50}, {3, 2, 125},
  14925. {3, 1, 2}, {3, 1, 2}, {3, 1, 1}};
  14926. x25519_core(xs, scalar, x1, clamp);
  14927. // Precomputed inversion chain
  14928. x2 = xs[0];
  14929. z2 = xs[1];
  14930. z3 = xs[3];
  14931. prev = z2;
  14932. for (i = 0; i < 13; i++) {
  14933. int j;
  14934. limb_t *a = xs[steps[i].a];
  14935. for (j = steps[i].n; j > 0; j--) {
  14936. sqr(a, prev);
  14937. prev = a;
  14938. }
  14939. mul1(a, xs[steps[i].c]);
  14940. }
  14941. // Here prev = z3
  14942. // x2 /= z2
  14943. mul(out_limbs, x2, z3, NLIMBS);
  14944. ret = (int) canon(out_limbs);
  14945. if (!clamp) ret = 0;
  14946. for (i = 0; i < NLIMBS; i++) {
  14947. uint32_t n = out_limbs[i];
  14948. out[i * 4] = (uint8_t) (n & 0xff);
  14949. out[i * 4 + 1] = (uint8_t) ((n >> 8) & 0xff);
  14950. out[i * 4 + 2] = (uint8_t) ((n >> 16) & 0xff);
  14951. out[i * 4 + 3] = (uint8_t) ((n >> 24) & 0xff);
  14952. }
  14953. return ret;
  14954. }
  14955. #ifdef MG_ENABLE_LINES
  14956. #line 1 "src/url.c"
  14957. #endif
  14958. struct url {
  14959. size_t key, user, pass, host, port, uri, end;
  14960. };
  14961. int mg_url_is_ssl(const char *url) {
  14962. return strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0 ||
  14963. strncmp(url, "mqtts:", 6) == 0 || strncmp(url, "ssl:", 4) == 0 ||
  14964. strncmp(url, "tls:", 4) == 0 || strncmp(url, "tcps:", 5) == 0;
  14965. }
  14966. static struct url urlparse(const char *url) {
  14967. size_t i;
  14968. struct url u;
  14969. memset(&u, 0, sizeof(u));
  14970. for (i = 0; url[i] != '\0'; i++) {
  14971. if (url[i] == '/' && i > 0 && u.host == 0 && url[i - 1] == '/') {
  14972. u.host = i + 1;
  14973. u.port = 0;
  14974. } else if (url[i] == ']') {
  14975. u.port = 0; // IPv6 URLs, like http://[::1]/bar
  14976. } else if (url[i] == ':' && u.port == 0 && u.uri == 0) {
  14977. u.port = i + 1;
  14978. } else if (url[i] == '@' && u.user == 0 && u.pass == 0 && u.uri == 0) {
  14979. u.user = u.host;
  14980. u.pass = u.port;
  14981. u.host = i + 1;
  14982. u.port = 0;
  14983. } else if (url[i] == '/' && u.host && u.uri == 0) {
  14984. u.uri = i;
  14985. }
  14986. }
  14987. u.end = i;
  14988. #if 0
  14989. printf("[%s] %d %d %d %d %d\n", url, u.user, u.pass, u.host, u.port, u.uri);
  14990. #endif
  14991. return u;
  14992. }
  14993. struct mg_str mg_url_host(const char *url) {
  14994. struct url u = urlparse(url);
  14995. size_t n = u.port ? u.port - u.host - 1
  14996. : u.uri ? u.uri - u.host
  14997. : u.end - u.host;
  14998. struct mg_str s = mg_str_n(url + u.host, n);
  14999. return s;
  15000. }
  15001. const char *mg_url_uri(const char *url) {
  15002. struct url u = urlparse(url);
  15003. return u.uri ? url + u.uri : "/";
  15004. }
  15005. unsigned short mg_url_port(const char *url) {
  15006. struct url u = urlparse(url);
  15007. unsigned short port = 0;
  15008. if (strncmp(url, "http:", 5) == 0 || strncmp(url, "ws:", 3) == 0) port = 80;
  15009. if (strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0)
  15010. port = 443;
  15011. if (strncmp(url, "mqtt:", 5) == 0) port = 1883;
  15012. if (strncmp(url, "mqtts:", 6) == 0) port = 8883;
  15013. if (u.port) port = (unsigned short) atoi(url + u.port);
  15014. return port;
  15015. }
  15016. struct mg_str mg_url_user(const char *url) {
  15017. struct url u = urlparse(url);
  15018. struct mg_str s = mg_str("");
  15019. if (u.user && (u.pass || u.host)) {
  15020. size_t n = u.pass ? u.pass - u.user - 1 : u.host - u.user - 1;
  15021. s = mg_str_n(url + u.user, n);
  15022. }
  15023. return s;
  15024. }
  15025. struct mg_str mg_url_pass(const char *url) {
  15026. struct url u = urlparse(url);
  15027. struct mg_str s = mg_str_n("", 0UL);
  15028. if (u.pass && u.host) {
  15029. size_t n = u.host - u.pass - 1;
  15030. s = mg_str_n(url + u.pass, n);
  15031. }
  15032. return s;
  15033. }
  15034. #ifdef MG_ENABLE_LINES
  15035. #line 1 "src/util.c"
  15036. #endif
  15037. // Not using memset for zeroing memory, cause it can be dropped by compiler
  15038. // See https://github.com/cesanta/mongoose/pull/1265
  15039. void mg_bzero(volatile unsigned char *buf, size_t len) {
  15040. if (buf != NULL) {
  15041. while (len--) *buf++ = 0;
  15042. }
  15043. }
  15044. #if MG_ENABLE_CUSTOM_RANDOM
  15045. #else
  15046. bool mg_random(void *buf, size_t len) {
  15047. bool success = false;
  15048. unsigned char *p = (unsigned char *) buf;
  15049. #if MG_ARCH == MG_ARCH_ESP32
  15050. while (len--) *p++ = (unsigned char) (esp_random() & 255);
  15051. success = true;
  15052. #elif MG_ARCH == MG_ARCH_PICOSDK
  15053. while (len--) *p++ = (unsigned char) (get_rand_32() & 255);
  15054. success = true;
  15055. #elif MG_ARCH == MG_ARCH_WIN32
  15056. #if defined(_MSC_VER) && _MSC_VER < 1700
  15057. static bool initialised = false;
  15058. static HCRYPTPROV hProv;
  15059. // CryptGenRandom() implementation earlier than 2008 is weak, see
  15060. // https://en.wikipedia.org/wiki/CryptGenRandom
  15061. if (!initialised) {
  15062. initialised = CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL,
  15063. CRYPT_VERIFYCONTEXT);
  15064. }
  15065. if (initialised) success = CryptGenRandom(hProv, len, p);
  15066. #else
  15067. size_t i;
  15068. for (i = 0; i < len; i++) {
  15069. unsigned int rand_v;
  15070. if (rand_s(&rand_v) == 0) {
  15071. p[i] = (unsigned char) (rand_v & 255);
  15072. } else {
  15073. break;
  15074. }
  15075. }
  15076. success = (i == len);
  15077. #endif
  15078. #elif MG_ARCH == MG_ARCH_UNIX
  15079. FILE *fp = fopen("/dev/urandom", "rb");
  15080. if (fp != NULL) {
  15081. if (fread(buf, 1, len, fp) == len) success = true;
  15082. fclose(fp);
  15083. }
  15084. #endif
  15085. // If everything above did not work, fallback to a pseudo random generator
  15086. if (success == false) {
  15087. MG_ERROR(("Weak RNG: using rand()"));
  15088. while (len--) *p++ = (unsigned char) (rand() & 255);
  15089. }
  15090. return success;
  15091. }
  15092. #endif
  15093. char *mg_random_str(char *buf, size_t len) {
  15094. size_t i;
  15095. mg_random(buf, len);
  15096. for (i = 0; i < len; i++) {
  15097. uint8_t c = ((uint8_t *) buf)[i] % 62U;
  15098. buf[i] = i == len - 1 ? (char) '\0' // 0-terminate last byte
  15099. : c < 26 ? (char) ('a' + c) // lowercase
  15100. : c < 52 ? (char) ('A' + c - 26) // uppercase
  15101. : (char) ('0' + c - 52); // numeric
  15102. }
  15103. return buf;
  15104. }
  15105. uint32_t mg_ntohl(uint32_t net) {
  15106. uint8_t data[4] = {0, 0, 0, 0};
  15107. memcpy(&data, &net, sizeof(data));
  15108. return (((uint32_t) data[3]) << 0) | (((uint32_t) data[2]) << 8) |
  15109. (((uint32_t) data[1]) << 16) | (((uint32_t) data[0]) << 24);
  15110. }
  15111. uint16_t mg_ntohs(uint16_t net) {
  15112. uint8_t data[2] = {0, 0};
  15113. memcpy(&data, &net, sizeof(data));
  15114. return (uint16_t) ((uint16_t) data[1] | (((uint16_t) data[0]) << 8));
  15115. }
  15116. uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len) {
  15117. static const uint32_t crclut[16] = {
  15118. // table for polynomial 0xEDB88320 (reflected)
  15119. 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
  15120. 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
  15121. 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
  15122. crc = ~crc;
  15123. while (len--) {
  15124. uint8_t b = *(uint8_t *) buf++;
  15125. crc = crclut[(crc ^ b) & 0x0F] ^ (crc >> 4);
  15126. crc = crclut[(crc ^ (b >> 4)) & 0x0F] ^ (crc >> 4);
  15127. }
  15128. return ~crc;
  15129. }
  15130. static int isbyte(int n) {
  15131. return n >= 0 && n <= 255;
  15132. }
  15133. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  15134. int n, a, b, c, d, slash = 32, len = 0;
  15135. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  15136. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  15137. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  15138. slash < 33) {
  15139. len = n;
  15140. *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) |
  15141. (uint32_t) d;
  15142. *mask = slash ? (uint32_t) (0xffffffffU << (32 - slash)) : (uint32_t) 0;
  15143. }
  15144. return len;
  15145. }
  15146. int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) {
  15147. struct mg_str entry;
  15148. int allowed = acl.len == 0 ? '+' : '-'; // If any ACL is set, deny by default
  15149. uint32_t remote_ip4;
  15150. if (remote_ip->is_ip6) {
  15151. return -1; // TODO(): handle IPv6 ACL and addresses
  15152. } else { // IPv4
  15153. memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4));
  15154. while (mg_span(acl, &entry, &acl, ',')) {
  15155. uint32_t net, mask;
  15156. if (entry.buf[0] != '+' && entry.buf[0] != '-') return -1;
  15157. if (parse_net(&entry.buf[1], &net, &mask) == 0) return -2;
  15158. if ((mg_ntohl(remote_ip4) & mask) == net) allowed = entry.buf[0];
  15159. }
  15160. }
  15161. return allowed == '+';
  15162. }
  15163. bool mg_path_is_sane(const struct mg_str path) {
  15164. const char *s = path.buf;
  15165. size_t n = path.len;
  15166. if (path.buf[0] == '.' && path.buf[1] == '.') return false; // Starts with ..
  15167. for (; s[0] != '\0' && n > 0; s++, n--) {
  15168. if ((s[0] == '/' || s[0] == '\\') && n >= 2) { // Subdir?
  15169. if (s[1] == '.' && s[2] == '.') return false; // Starts with ..
  15170. }
  15171. }
  15172. return true;
  15173. }
  15174. #if MG_ENABLE_CUSTOM_MILLIS
  15175. #else
  15176. uint64_t mg_millis(void) {
  15177. #if MG_ARCH == MG_ARCH_WIN32
  15178. return GetTickCount();
  15179. #elif MG_ARCH == MG_ARCH_PICOSDK
  15180. return time_us_64() / 1000;
  15181. #elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \
  15182. MG_ARCH == MG_ARCH_FREERTOS
  15183. return xTaskGetTickCount() * portTICK_PERIOD_MS;
  15184. #elif MG_ARCH == MG_ARCH_AZURERTOS
  15185. return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND);
  15186. #elif MG_ARCH == MG_ARCH_TIRTOS
  15187. return (uint64_t) Clock_getTicks();
  15188. #elif MG_ARCH == MG_ARCH_ZEPHYR
  15189. return (uint64_t) k_uptime_get();
  15190. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
  15191. return (uint64_t) rt_time_get();
  15192. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
  15193. return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq());
  15194. #elif MG_ARCH == MG_ARCH_RTTHREAD
  15195. return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND);
  15196. #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
  15197. // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
  15198. // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
  15199. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000;
  15200. #elif MG_ARCH == MG_ARCH_UNIX
  15201. struct timespec ts = {0, 0};
  15202. // See #1615 - prefer monotonic clock
  15203. #if defined(CLOCK_MONOTONIC_RAW)
  15204. // Raw hardware-based time that is not subject to NTP adjustment
  15205. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  15206. #elif defined(CLOCK_MONOTONIC)
  15207. // Affected by the incremental adjustments performed by adjtime and NTP
  15208. clock_gettime(CLOCK_MONOTONIC, &ts);
  15209. #else
  15210. // Affected by discontinuous jumps in the system time and by the incremental
  15211. // adjustments performed by adjtime and NTP
  15212. clock_gettime(CLOCK_REALTIME, &ts);
  15213. #endif
  15214. return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000);
  15215. #elif defined(ARDUINO)
  15216. return (uint64_t) millis();
  15217. #else
  15218. return (uint64_t) (time(NULL) * 1000);
  15219. #endif
  15220. }
  15221. #endif
  15222. #ifdef MG_ENABLE_LINES
  15223. #line 1 "src/ws.c"
  15224. #endif
  15225. struct ws_msg {
  15226. uint8_t flags;
  15227. size_t header_len;
  15228. size_t data_len;
  15229. };
  15230. size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
  15231. va_list *ap) {
  15232. size_t len = c->send.len;
  15233. size_t n = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  15234. mg_ws_wrap(c, c->send.len - len, op);
  15235. return n;
  15236. }
  15237. size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...) {
  15238. size_t len = 0;
  15239. va_list ap;
  15240. va_start(ap, fmt);
  15241. len = mg_ws_vprintf(c, op, fmt, &ap);
  15242. va_end(ap);
  15243. return len;
  15244. }
  15245. static void ws_handshake(struct mg_connection *c, const struct mg_str *wskey,
  15246. const struct mg_str *wsproto, const char *fmt,
  15247. va_list *ap) {
  15248. const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  15249. unsigned char sha[20], b64_sha[30];
  15250. mg_sha1_ctx sha_ctx;
  15251. mg_sha1_init(&sha_ctx);
  15252. mg_sha1_update(&sha_ctx, (unsigned char *) wskey->buf, wskey->len);
  15253. mg_sha1_update(&sha_ctx, (unsigned char *) magic, 36);
  15254. mg_sha1_final(sha, &sha_ctx);
  15255. mg_base64_encode(sha, sizeof(sha), (char *) b64_sha, sizeof(b64_sha));
  15256. mg_xprintf(mg_pfn_iobuf, &c->send,
  15257. "HTTP/1.1 101 Switching Protocols\r\n"
  15258. "Upgrade: websocket\r\n"
  15259. "Connection: Upgrade\r\n"
  15260. "Sec-WebSocket-Accept: %s\r\n",
  15261. b64_sha);
  15262. if (fmt != NULL) mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  15263. if (wsproto != NULL) {
  15264. mg_printf(c, "Sec-WebSocket-Protocol: %.*s\r\n", (int) wsproto->len,
  15265. wsproto->buf);
  15266. }
  15267. mg_send(c, "\r\n", 2);
  15268. }
  15269. static uint32_t be32(const uint8_t *p) {
  15270. return (((uint32_t) p[3]) << 0) | (((uint32_t) p[2]) << 8) |
  15271. (((uint32_t) p[1]) << 16) | (((uint32_t) p[0]) << 24);
  15272. }
  15273. static size_t ws_process(uint8_t *buf, size_t len, struct ws_msg *msg) {
  15274. size_t i, n = 0, mask_len = 0;
  15275. memset(msg, 0, sizeof(*msg));
  15276. if (len >= 2) {
  15277. n = buf[1] & 0x7f; // Frame length
  15278. mask_len = buf[1] & 128 ? 4 : 0; // last bit is a mask bit
  15279. msg->flags = buf[0];
  15280. if (n < 126 && len >= mask_len) {
  15281. msg->data_len = n;
  15282. msg->header_len = 2 + mask_len;
  15283. } else if (n == 126 && len >= 4 + mask_len) {
  15284. msg->header_len = 4 + mask_len;
  15285. msg->data_len = (((size_t) buf[2]) << 8) | buf[3];
  15286. } else if (len >= 10 + mask_len) {
  15287. msg->header_len = 10 + mask_len;
  15288. msg->data_len =
  15289. (size_t) (((uint64_t) be32(buf + 2) << 32) + be32(buf + 6));
  15290. }
  15291. }
  15292. // Sanity check, and integer overflow protection for the boundary check below
  15293. // data_len should not be larger than 1 Gb
  15294. if (msg->data_len > 1024 * 1024 * 1024) return 0;
  15295. if (msg->header_len + msg->data_len > len) return 0;
  15296. if (mask_len > 0) {
  15297. uint8_t *p = buf + msg->header_len, *m = p - mask_len;
  15298. for (i = 0; i < msg->data_len; i++) p[i] ^= m[i & 3];
  15299. }
  15300. return msg->header_len + msg->data_len;
  15301. }
  15302. static size_t mkhdr(size_t len, int op, bool is_client, uint8_t *buf) {
  15303. size_t n = 0;
  15304. buf[0] = (uint8_t) (op | 128);
  15305. if (len < 126) {
  15306. buf[1] = (unsigned char) len;
  15307. n = 2;
  15308. } else if (len < 65536) {
  15309. uint16_t tmp = mg_htons((uint16_t) len);
  15310. buf[1] = 126;
  15311. memcpy(&buf[2], &tmp, sizeof(tmp));
  15312. n = 4;
  15313. } else {
  15314. uint32_t tmp;
  15315. buf[1] = 127;
  15316. tmp = mg_htonl((uint32_t) (((uint64_t) len) >> 32));
  15317. memcpy(&buf[2], &tmp, sizeof(tmp));
  15318. tmp = mg_htonl((uint32_t) (len & 0xffffffffU));
  15319. memcpy(&buf[6], &tmp, sizeof(tmp));
  15320. n = 10;
  15321. }
  15322. if (is_client) {
  15323. buf[1] |= 1 << 7; // Set masking flag
  15324. mg_random(&buf[n], 4);
  15325. n += 4;
  15326. }
  15327. return n;
  15328. }
  15329. static void mg_ws_mask(struct mg_connection *c, size_t len) {
  15330. if (c->is_client && c->send.buf != NULL) {
  15331. size_t i;
  15332. uint8_t *p = c->send.buf + c->send.len - len, *mask = p - 4;
  15333. for (i = 0; i < len; i++) p[i] ^= mask[i & 3];
  15334. }
  15335. }
  15336. size_t mg_ws_send(struct mg_connection *c, const void *buf, size_t len,
  15337. int op) {
  15338. uint8_t header[14];
  15339. size_t header_len = mkhdr(len, op, c->is_client, header);
  15340. if (!mg_send(c, header, header_len)) return 0;
  15341. if (!mg_send(c, buf, len)) return header_len;
  15342. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  15343. mg_ws_mask(c, len);
  15344. return header_len + len;
  15345. }
  15346. static bool mg_ws_client_handshake(struct mg_connection *c) {
  15347. int n = mg_http_get_request_len(c->recv.buf, c->recv.len);
  15348. if (n < 0) {
  15349. mg_error(c, "not http"); // Some just, not an HTTP request
  15350. } else if (n > 0) {
  15351. if (n < 15 || memcmp(c->recv.buf + 9, "101", 3) != 0) {
  15352. mg_error(c, "ws handshake error");
  15353. } else {
  15354. struct mg_http_message hm;
  15355. if (mg_http_parse((char *) c->recv.buf, c->recv.len, &hm)) {
  15356. c->is_websocket = 1;
  15357. mg_call(c, MG_EV_WS_OPEN, &hm);
  15358. } else {
  15359. mg_error(c, "ws handshake error");
  15360. }
  15361. }
  15362. mg_iobuf_del(&c->recv, 0, (size_t) n);
  15363. } else {
  15364. return true; // Request is not yet received, quit event handler
  15365. }
  15366. return false; // Continue event handler
  15367. }
  15368. static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
  15369. struct ws_msg msg;
  15370. size_t ofs = (size_t) c->pfn_data;
  15371. // assert(ofs < c->recv.len);
  15372. if (ev == MG_EV_READ) {
  15373. if (c->is_client && !c->is_websocket && mg_ws_client_handshake(c)) return;
  15374. while (ws_process(c->recv.buf + ofs, c->recv.len - ofs, &msg) > 0) {
  15375. char *s = (char *) c->recv.buf + ofs + msg.header_len;
  15376. struct mg_ws_message m = {{s, msg.data_len}, msg.flags};
  15377. size_t len = msg.header_len + msg.data_len;
  15378. uint8_t final = msg.flags & 128, op = msg.flags & 15;
  15379. // MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
  15380. // (int) m.data.len, (int) m.data.len, m.data.buf));
  15381. switch (op) {
  15382. case WEBSOCKET_OP_CONTINUE:
  15383. mg_call(c, MG_EV_WS_CTL, &m);
  15384. break;
  15385. case WEBSOCKET_OP_PING:
  15386. MG_DEBUG(("%s", "WS PONG"));
  15387. mg_ws_send(c, s, msg.data_len, WEBSOCKET_OP_PONG);
  15388. mg_call(c, MG_EV_WS_CTL, &m);
  15389. break;
  15390. case WEBSOCKET_OP_PONG:
  15391. mg_call(c, MG_EV_WS_CTL, &m);
  15392. break;
  15393. case WEBSOCKET_OP_TEXT:
  15394. case WEBSOCKET_OP_BINARY:
  15395. if (final) mg_call(c, MG_EV_WS_MSG, &m);
  15396. break;
  15397. case WEBSOCKET_OP_CLOSE:
  15398. MG_DEBUG(("%lu WS CLOSE", c->id));
  15399. mg_call(c, MG_EV_WS_CTL, &m);
  15400. // Echo the payload of the received CLOSE message back to the sender
  15401. mg_ws_send(c, m.data.buf, m.data.len, WEBSOCKET_OP_CLOSE);
  15402. c->is_draining = 1;
  15403. break;
  15404. default:
  15405. // Per RFC6455, close conn when an unknown op is recvd
  15406. mg_error(c, "unknown WS op %d", op);
  15407. break;
  15408. }
  15409. // Handle fragmented frames: strip header, keep in c->recv
  15410. if (final == 0 || op == 0) {
  15411. if (op) ofs++, len--, msg.header_len--; // First frame
  15412. mg_iobuf_del(&c->recv, ofs, msg.header_len); // Strip header
  15413. len -= msg.header_len;
  15414. ofs += len;
  15415. c->pfn_data = (void *) ofs;
  15416. // MG_INFO(("FRAG %d [%.*s]", (int) ofs, (int) ofs, c->recv.buf));
  15417. }
  15418. // Remove non-fragmented frame
  15419. if (final && op) mg_iobuf_del(&c->recv, ofs, len);
  15420. // Last chunk of the fragmented frame
  15421. if (final && !op) {
  15422. m.flags = c->recv.buf[0];
  15423. m.data = mg_str_n((char *) &c->recv.buf[1], (size_t) (ofs - 1));
  15424. mg_call(c, MG_EV_WS_MSG, &m);
  15425. mg_iobuf_del(&c->recv, 0, ofs);
  15426. ofs = 0;
  15427. c->pfn_data = NULL;
  15428. }
  15429. }
  15430. }
  15431. (void) ev_data;
  15432. }
  15433. struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
  15434. mg_event_handler_t fn, void *fn_data,
  15435. const char *fmt, ...) {
  15436. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  15437. if (c != NULL) {
  15438. char nonce[16], key[30];
  15439. struct mg_str host = mg_url_host(url);
  15440. mg_random(nonce, sizeof(nonce));
  15441. mg_base64_encode((unsigned char *) nonce, sizeof(nonce), key, sizeof(key));
  15442. mg_xprintf(mg_pfn_iobuf, &c->send,
  15443. "GET %s HTTP/1.1\r\n"
  15444. "Upgrade: websocket\r\n"
  15445. "Host: %.*s\r\n"
  15446. "Connection: Upgrade\r\n"
  15447. "Sec-WebSocket-Version: 13\r\n"
  15448. "Sec-WebSocket-Key: %s\r\n",
  15449. mg_url_uri(url), (int) host.len, host.buf, key);
  15450. if (fmt != NULL) {
  15451. va_list ap;
  15452. va_start(ap, fmt);
  15453. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  15454. va_end(ap);
  15455. }
  15456. mg_xprintf(mg_pfn_iobuf, &c->send, "\r\n");
  15457. c->pfn = mg_ws_cb;
  15458. c->pfn_data = NULL;
  15459. }
  15460. return c;
  15461. }
  15462. void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
  15463. const char *fmt, ...) {
  15464. struct mg_str *wskey = mg_http_get_header(hm, "Sec-WebSocket-Key");
  15465. c->pfn = mg_ws_cb;
  15466. c->pfn_data = NULL;
  15467. if (wskey == NULL) {
  15468. mg_http_reply(c, 426, "", "WS upgrade expected\n");
  15469. c->is_draining = 1;
  15470. } else {
  15471. struct mg_str *wsproto = mg_http_get_header(hm, "Sec-WebSocket-Protocol");
  15472. va_list ap;
  15473. va_start(ap, fmt);
  15474. ws_handshake(c, wskey, wsproto, fmt, &ap);
  15475. va_end(ap);
  15476. c->is_websocket = 1;
  15477. c->is_resp = 0;
  15478. mg_call(c, MG_EV_WS_OPEN, hm);
  15479. }
  15480. }
  15481. size_t mg_ws_wrap(struct mg_connection *c, size_t len, int op) {
  15482. uint8_t header[14], *p;
  15483. size_t header_len = mkhdr(len, op, c->is_client, header);
  15484. // NOTE: order of operations is important!
  15485. if (mg_iobuf_add(&c->send, c->send.len, NULL, header_len) != 0) {
  15486. p = &c->send.buf[c->send.len - len]; // p points to data
  15487. memmove(p, p - header_len, len); // Shift data
  15488. memcpy(p - header_len, header, header_len); // Prepend header
  15489. mg_ws_mask(c, len); // Mask data
  15490. }
  15491. return c->send.len;
  15492. }
  15493. #ifdef MG_ENABLE_LINES
  15494. #line 1 "src/drivers/cmsis.c"
  15495. #endif
  15496. // https://arm-software.github.io/CMSIS_5/Driver/html/index.html
  15497. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
  15498. extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0;
  15499. extern ARM_DRIVER_ETH_PHY Driver_ETH_PHY0;
  15500. static struct mg_tcpip_if *s_ifp;
  15501. static void mac_cb(uint32_t);
  15502. static bool cmsis_init(struct mg_tcpip_if *);
  15503. static bool cmsis_up(struct mg_tcpip_if *);
  15504. static size_t cmsis_tx(const void *, size_t, struct mg_tcpip_if *);
  15505. static size_t cmsis_rx(void *, size_t, struct mg_tcpip_if *);
  15506. struct mg_tcpip_driver mg_tcpip_driver_cmsis = {cmsis_init, cmsis_tx, NULL,
  15507. cmsis_up};
  15508. static bool cmsis_init(struct mg_tcpip_if *ifp) {
  15509. ARM_ETH_MAC_ADDR addr;
  15510. s_ifp = ifp;
  15511. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  15512. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  15513. ARM_ETH_MAC_CAPABILITIES cap = mac->GetCapabilities();
  15514. if (mac->Initialize(mac_cb) != ARM_DRIVER_OK) return false;
  15515. if (phy->Initialize(mac->PHY_Read, mac->PHY_Write) != ARM_DRIVER_OK)
  15516. return false;
  15517. if (cap.event_rx_frame == 0) // polled mode driver
  15518. mg_tcpip_driver_cmsis.rx = cmsis_rx;
  15519. mac->PowerControl(ARM_POWER_FULL);
  15520. if (cap.mac_address) { // driver provides MAC address
  15521. mac->GetMacAddress(&addr);
  15522. memcpy(ifp->mac, &addr, sizeof(ifp->mac));
  15523. } else { // we provide MAC address
  15524. memcpy(&addr, ifp->mac, sizeof(addr));
  15525. mac->SetMacAddress(&addr);
  15526. }
  15527. phy->PowerControl(ARM_POWER_FULL);
  15528. phy->SetInterface(cap.media_interface);
  15529. phy->SetMode(ARM_ETH_PHY_AUTO_NEGOTIATE);
  15530. return true;
  15531. }
  15532. static size_t cmsis_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
  15533. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  15534. if (mac->SendFrame(buf, (uint32_t) len, 0) != ARM_DRIVER_OK) {
  15535. ifp->nerr++;
  15536. return 0;
  15537. }
  15538. ifp->nsent++;
  15539. return len;
  15540. }
  15541. static bool cmsis_up(struct mg_tcpip_if *ifp) {
  15542. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  15543. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  15544. bool up = (phy->GetLinkState() == ARM_ETH_LINK_UP) ? 1 : 0; // link state
  15545. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // just went up
  15546. ARM_ETH_LINK_INFO st = phy->GetLinkInfo();
  15547. mac->Control(ARM_ETH_MAC_CONFIGURE,
  15548. (st.speed << ARM_ETH_MAC_SPEED_Pos) |
  15549. (st.duplex << ARM_ETH_MAC_DUPLEX_Pos) |
  15550. ARM_ETH_MAC_ADDRESS_BROADCAST);
  15551. MG_DEBUG(("Link is %uM %s-duplex",
  15552. (st.speed == 2) ? 1000
  15553. : st.speed ? 100
  15554. : 10,
  15555. st.duplex ? "full" : "half"));
  15556. mac->Control(ARM_ETH_MAC_CONTROL_TX, 1);
  15557. mac->Control(ARM_ETH_MAC_CONTROL_RX, 1);
  15558. } else if ((ifp->state != MG_TCPIP_STATE_DOWN) && !up) { // just went down
  15559. mac->Control(ARM_ETH_MAC_FLUSH,
  15560. ARM_ETH_MAC_FLUSH_TX | ARM_ETH_MAC_FLUSH_RX);
  15561. mac->Control(ARM_ETH_MAC_CONTROL_TX, 0);
  15562. mac->Control(ARM_ETH_MAC_CONTROL_RX, 0);
  15563. }
  15564. return up;
  15565. }
  15566. static void mac_cb(uint32_t ev) {
  15567. if ((ev & ARM_ETH_MAC_EVENT_RX_FRAME) == 0) return;
  15568. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  15569. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  15570. if (len >= 60 && len <= 1518) { // proper frame
  15571. char *p;
  15572. if (mg_queue_book(&s_ifp->recv_queue, &p, len) >= len) { // have room
  15573. if ((len = mac->ReadFrame((uint8_t *) p, len)) > 0) { // copy succeeds
  15574. mg_queue_add(&s_ifp->recv_queue, len);
  15575. s_ifp->nrecv++;
  15576. }
  15577. return;
  15578. }
  15579. s_ifp->ndrop++;
  15580. }
  15581. mac->ReadFrame(NULL, 0); // otherwise, discard
  15582. }
  15583. static size_t cmsis_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  15584. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  15585. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  15586. if (len >= 60 && len <= 1518 &&
  15587. ((len = mac->ReadFrame(buf, (uint32_t) buflen)) > 0))
  15588. return len;
  15589. if (len > 0) mac->ReadFrame(NULL, 0); // discard bad frames
  15590. (void) ifp;
  15591. return 0;
  15592. }
  15593. #endif
  15594. #ifdef MG_ENABLE_LINES
  15595. #line 1 "src/drivers/imxrt.c"
  15596. #endif
  15597. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_IMXRT) && MG_ENABLE_DRIVER_IMXRT
  15598. struct imxrt_enet {
  15599. volatile uint32_t RESERVED0, EIR, EIMR, RESERVED1, RDAR, TDAR, RESERVED2[3],
  15600. ECR, RESERVED3[6], MMFR, MSCR, RESERVED4[7], MIBC, RESERVED5[7], RCR,
  15601. RESERVED6[15], TCR, RESERVED7[7], PALR, PAUR, OPD, TXIC0, TXIC1, TXIC2,
  15602. RESERVED8, RXIC0, RXIC1, RXIC2, RESERVED9[3], IAUR, IALR, GAUR, GALR,
  15603. RESERVED10[7], TFWR, RESERVED11[14], RDSR, TDSR, MRBR[2], RSFL, RSEM,
  15604. RAEM, RAFL, TSEM, TAEM, TAFL, TIPG, FTRL, RESERVED12[3], TACC, RACC,
  15605. RESERVED13[15], RMON_T_PACKETS, RMON_T_BC_PKT, RMON_T_MC_PKT,
  15606. RMON_T_CRC_ALIGN, RMON_T_UNDERSIZE, RMON_T_OVERSIZE, RMON_T_FRAG,
  15607. RMON_T_JAB, RMON_T_COL, RMON_T_P64, RMON_T_P65TO127, RMON_T_P128TO255,
  15608. RMON_T_P256TO511, RMON_T_P512TO1023, RMON_T_P1024TO2048, RMON_T_GTE2048,
  15609. RMON_T_OCTETS, IEEE_T_DROP, IEEE_T_FRAME_OK, IEEE_T_1COL, IEEE_T_MCOL,
  15610. IEEE_T_DEF, IEEE_T_LCOL, IEEE_T_EXCOL, IEEE_T_MACERR, IEEE_T_CSERR,
  15611. IEEE_T_SQE, IEEE_T_FDXFC, IEEE_T_OCTETS_OK, RESERVED14[3], RMON_R_PACKETS,
  15612. RMON_R_BC_PKT, RMON_R_MC_PKT, RMON_R_CRC_ALIGN, RMON_R_UNDERSIZE,
  15613. RMON_R_OVERSIZE, RMON_R_FRAG, RMON_R_JAB, RESERVED15, RMON_R_P64,
  15614. RMON_R_P65TO127, RMON_R_P128TO255, RMON_R_P256TO511, RMON_R_P512TO1023,
  15615. RMON_R_P1024TO2047, RMON_R_GTE2048, RMON_R_OCTETS, IEEE_R_DROP,
  15616. IEEE_R_FRAME_OK, IEEE_R_CRC, IEEE_R_ALIGN, IEEE_R_MACERR, IEEE_R_FDXFC,
  15617. IEEE_R_OCTETS_OK, RESERVED16[71], ATCR, ATVR, ATOFF, ATPER, ATCOR, ATINC,
  15618. ATSTMP, RESERVED17[122], TGSR, TCSR0, TCCR0, TCSR1, TCCR1, TCSR2, TCCR2,
  15619. TCSR3;
  15620. };
  15621. #undef ENET
  15622. #if defined(MG_DRIVER_IMXRT_RT11) && MG_DRIVER_IMXRT_RT11
  15623. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x40424000U)
  15624. #define ETH_DESC_CNT 5 // Descriptors count
  15625. #else
  15626. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x402D8000U)
  15627. #define ETH_DESC_CNT 4 // Descriptors count
  15628. #endif
  15629. #define ETH_PKT_SIZE 1536 // Max frame size, 64-bit aligned
  15630. struct enet_desc {
  15631. uint16_t length; // Data length
  15632. uint16_t control; // Control and status
  15633. uint32_t *buffer; // Data ptr
  15634. };
  15635. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  15636. #define MG_64BYTE_ALIGNED __attribute__((aligned((64U))))
  15637. // Descriptors: in non-cached area (TODO(scaprile)), (37.5.1.22.2 37.5.1.23.2)
  15638. // Buffers: 64-byte aligned (37.3.14)
  15639. static volatile struct enet_desc s_rxdesc[ETH_DESC_CNT] MG_64BYTE_ALIGNED;
  15640. static volatile struct enet_desc s_txdesc[ETH_DESC_CNT] MG_64BYTE_ALIGNED;
  15641. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BYTE_ALIGNED;
  15642. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BYTE_ALIGNED;
  15643. static struct mg_tcpip_if *s_ifp; // MIP interface
  15644. static uint16_t enet_read_phy(uint8_t addr, uint8_t reg) {
  15645. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  15646. ENET->MMFR = (1 << 30) | (2 << 28) | (addr << 23) | (reg << 18) | (2 << 16);
  15647. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  15648. return ENET->MMFR & 0xffff;
  15649. }
  15650. static void enet_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15651. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  15652. ENET->MMFR =
  15653. (1 << 30) | (1 << 28) | (addr << 23) | (reg << 18) | (2 << 16) | val;
  15654. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  15655. }
  15656. // MDC clock is generated from IPS Bus clock (ipg_clk); as per 802.3,
  15657. // it must not exceed 2.5MHz
  15658. // The PHY receives the PLL6-generated 50MHz clock
  15659. static bool mg_tcpip_driver_imxrt_init(struct mg_tcpip_if *ifp) {
  15660. struct mg_tcpip_driver_imxrt_data *d =
  15661. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  15662. s_ifp = ifp;
  15663. // Init RX descriptors
  15664. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15665. s_rxdesc[i].control = MG_BIT(15); // Own (E)
  15666. s_rxdesc[i].buffer = (uint32_t *) s_rxbuf[i]; // Point to data buffer
  15667. }
  15668. s_rxdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  15669. // Init TX descriptors
  15670. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15671. // s_txdesc[i].control = MG_BIT(10); // Own (TC)
  15672. s_txdesc[i].buffer = (uint32_t *) s_txbuf[i];
  15673. }
  15674. s_txdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  15675. ENET->ECR = MG_BIT(0); // Software reset, disable
  15676. while ((ENET->ECR & MG_BIT(0))) (void) 0; // Wait until done
  15677. // Set MDC clock divider. If user told us the value, use it.
  15678. // TODO(): Otherwise, guess (currently assuming max freq)
  15679. int cr = (d == NULL || d->mdc_cr < 0) ? 24 : d->mdc_cr;
  15680. ENET->MSCR = (1 << 8) | ((cr & 0x3f) << 1); // HOLDTIME 2 clks
  15681. struct mg_phy phy = {enet_read_phy, enet_write_phy};
  15682. mg_phy_init(&phy, d->phy_addr, MG_PHY_LEDS_ACTIVE_HIGH); // MAC clocks PHY
  15683. // Select RMII mode, 100M, keep CRC, set max rx length, disable loop
  15684. ENET->RCR = (1518 << 16) | MG_BIT(8) | MG_BIT(2);
  15685. // ENET->RCR |= MG_BIT(3); // Receive all
  15686. ENET->TCR = MG_BIT(2); // Full-duplex
  15687. ENET->RDSR = (uint32_t) (uintptr_t) s_rxdesc;
  15688. ENET->TDSR = (uint32_t) (uintptr_t) s_txdesc;
  15689. ENET->MRBR[0] = ETH_PKT_SIZE; // Same size for RX/TX buffers
  15690. // MAC address filtering (bytes in reversed order)
  15691. ENET->PAUR = ((uint32_t) ifp->mac[4] << 24U) | (uint32_t) ifp->mac[5] << 16U;
  15692. ENET->PALR = (uint32_t) (ifp->mac[0] << 24U) |
  15693. ((uint32_t) ifp->mac[1] << 16U) |
  15694. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  15695. ENET->ECR = MG_BIT(8) | MG_BIT(1); // Little-endian CPU, Enable
  15696. ENET->EIMR = MG_BIT(25); // Set interrupt mask
  15697. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  15698. ENET->TDAR = MG_BIT(24); // Transmit Descriptors have changed
  15699. // ENET->OPD = 0x10014;
  15700. return true;
  15701. }
  15702. // Transmit frame
  15703. static size_t mg_tcpip_driver_imxrt_tx(const void *buf, size_t len,
  15704. struct mg_tcpip_if *ifp) {
  15705. static int s_txno; // Current descriptor index
  15706. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  15707. MG_ERROR(("Frame too big, %ld", (long) len));
  15708. len = (size_t) -1; // fail
  15709. } else if ((s_txdesc[s_txno].control & MG_BIT(15))) {
  15710. ifp->nerr++;
  15711. MG_ERROR(("No descriptors available"));
  15712. len = 0; // retry later
  15713. } else {
  15714. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  15715. s_txdesc[s_txno].length = (uint16_t) len; // Set data len
  15716. // Table 37-34, R, L, TC (Ready, last, transmit CRC after frame
  15717. s_txdesc[s_txno].control |=
  15718. (uint16_t) (MG_BIT(15) | MG_BIT(11) | MG_BIT(10));
  15719. ENET->TDAR = MG_BIT(24); // Descriptor ring updated
  15720. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15721. }
  15722. (void) ifp;
  15723. return len;
  15724. }
  15725. static bool mg_tcpip_driver_imxrt_up(struct mg_tcpip_if *ifp) {
  15726. struct mg_tcpip_driver_imxrt_data *d =
  15727. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  15728. uint8_t speed = MG_PHY_SPEED_10M;
  15729. bool up = false, full_duplex = false;
  15730. struct mg_phy phy = {enet_read_phy, enet_write_phy};
  15731. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  15732. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15733. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  15734. // if(link is slow or half) set flags otherwise
  15735. // reg = tmp
  15736. uint32_t tcr = ENET->TCR | MG_BIT(2); // Full-duplex
  15737. uint32_t rcr = ENET->RCR & ~MG_BIT(9); // 100M
  15738. if (speed == MG_PHY_SPEED_10M) rcr |= MG_BIT(9); // 10M
  15739. if (full_duplex == false) tcr &= ~MG_BIT(2); // Half-duplex
  15740. ENET->TCR = tcr; // IRQ handler does not fiddle with these registers
  15741. ENET->RCR = rcr;
  15742. MG_DEBUG(("Link is %uM %s-duplex", rcr & MG_BIT(9) ? 10 : 100,
  15743. tcr & MG_BIT(2) ? "full" : "half"));
  15744. }
  15745. return up;
  15746. }
  15747. void ENET_IRQHandler(void);
  15748. static uint32_t s_rxno;
  15749. void ENET_IRQHandler(void) {
  15750. ENET->EIR = MG_BIT(25); // Ack IRQ
  15751. // Frame received, loop
  15752. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  15753. uint32_t r = s_rxdesc[s_rxno].control;
  15754. if (r & MG_BIT(15)) break; // exit when done
  15755. // skip partial/errored frames (Table 37-32)
  15756. if ((r & MG_BIT(11)) &&
  15757. !(r & (MG_BIT(5) | MG_BIT(4) | MG_BIT(2) | MG_BIT(1) | MG_BIT(0)))) {
  15758. size_t len = s_rxdesc[s_rxno].length;
  15759. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  15760. }
  15761. s_rxdesc[s_rxno].control |= MG_BIT(15);
  15762. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15763. }
  15764. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  15765. // If b24 == 0, descriptors were exhausted and probably frames were dropped
  15766. }
  15767. struct mg_tcpip_driver mg_tcpip_driver_imxrt = {mg_tcpip_driver_imxrt_init,
  15768. mg_tcpip_driver_imxrt_tx, NULL,
  15769. mg_tcpip_driver_imxrt_up};
  15770. #endif
  15771. #ifdef MG_ENABLE_LINES
  15772. #line 1 "src/drivers/phy.c"
  15773. #endif
  15774. enum { // ID1 ID2
  15775. MG_PHY_KSZ8x = 0x22, // 0022 1561 - KSZ8081RNB
  15776. MG_PHY_DP83x = 0x2000,
  15777. MG_PHY_DP83867 = 0xa231, // 2000 a231 - TI DP83867I
  15778. MG_PHY_DP83825 = 0xa140, // 2000 a140 - TI DP83825I
  15779. MG_PHY_DP83848 = 0x5ca2, // 2000 5ca2 - TI DP83848I
  15780. MG_PHY_LAN87x = 0x7, // 0007 c0fx - LAN8720
  15781. MG_PHY_RTL8201 = 0x1C // 001c c816 - RTL8201
  15782. };
  15783. enum {
  15784. MG_PHY_REG_BCR = 0,
  15785. MG_PHY_REG_BSR = 1,
  15786. MG_PHY_REG_ID1 = 2,
  15787. MG_PHY_REG_ID2 = 3,
  15788. MG_PHY_DP83x_REG_PHYSTS = 16,
  15789. MG_PHY_DP83867_REG_PHYSTS = 17,
  15790. MG_PHY_DP83x_REG_RCSR = 23,
  15791. MG_PHY_DP83x_REG_LEDCR = 24,
  15792. MG_PHY_KSZ8x_REG_PC1R = 30,
  15793. MG_PHY_KSZ8x_REG_PC2R = 31,
  15794. MG_PHY_LAN87x_REG_SCSR = 31,
  15795. MG_PHY_RTL8201_REG_RMSR = 16, // in page 7
  15796. MG_PHY_RTL8201_REG_PAGESEL = 31
  15797. };
  15798. static const char *mg_phy_id_to_str(uint16_t id1, uint16_t id2) {
  15799. switch (id1) {
  15800. case MG_PHY_DP83x:
  15801. switch (id2) {
  15802. case MG_PHY_DP83867:
  15803. return "DP83867";
  15804. case MG_PHY_DP83848:
  15805. return "DP83848";
  15806. case MG_PHY_DP83825:
  15807. return "DP83825";
  15808. default:
  15809. return "DP83x";
  15810. }
  15811. case MG_PHY_KSZ8x:
  15812. return "KSZ8x";
  15813. case MG_PHY_LAN87x:
  15814. return "LAN87x";
  15815. case MG_PHY_RTL8201:
  15816. return "RTL8201";
  15817. default:
  15818. return "unknown";
  15819. }
  15820. (void) id2;
  15821. }
  15822. void mg_phy_init(struct mg_phy *phy, uint8_t phy_addr, uint8_t config) {
  15823. uint16_t id1, id2;
  15824. phy->write_reg(phy_addr, MG_PHY_REG_BCR, MG_BIT(15)); // Reset PHY
  15825. while (phy->read_reg(phy_addr, MG_PHY_REG_BCR) & MG_BIT(15)) (void) 0;
  15826. // MG_PHY_REG_BCR[12]: Autonegotiation is default unless hw says otherwise
  15827. id1 = phy->read_reg(phy_addr, MG_PHY_REG_ID1);
  15828. id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
  15829. MG_INFO(("PHY ID: %#04x %#04x (%s)", id1, id2, mg_phy_id_to_str(id1, id2)));
  15830. if (id1 == MG_PHY_DP83x && id2 == MG_PHY_DP83867) {
  15831. phy->write_reg(phy_addr, 0x0d, 0x1f); // write 0x10d to IO_MUX_CFG (0x0170)
  15832. phy->write_reg(phy_addr, 0x0e, 0x170);
  15833. phy->write_reg(phy_addr, 0x0d, 0x401f);
  15834. phy->write_reg(phy_addr, 0x0e, 0x10d);
  15835. }
  15836. if (config & MG_PHY_CLOCKS_MAC) {
  15837. // Use PHY crystal oscillator (preserve defaults)
  15838. // nothing to do
  15839. } else { // MAC clocks PHY, PHY has no xtal
  15840. // Enable 50 MHz external ref clock at XI (preserve defaults)
  15841. if (id1 == MG_PHY_DP83x && id2 != MG_PHY_DP83867 && id2 != MG_PHY_DP83848) {
  15842. phy->write_reg(phy_addr, MG_PHY_DP83x_REG_RCSR, MG_BIT(7) | MG_BIT(0));
  15843. } else if (id1 == MG_PHY_KSZ8x) {
  15844. // Disable isolation (override hw, it doesn't make sense at this point)
  15845. phy->write_reg( // #2848, some NXP boards set ISO, even though
  15846. phy_addr, MG_PHY_REG_BCR, // docs say they don't
  15847. phy->read_reg(phy_addr, MG_PHY_REG_BCR) & (uint16_t) ~MG_BIT(10));
  15848. phy->write_reg(phy_addr, MG_PHY_KSZ8x_REG_PC2R, // now do clock stuff
  15849. MG_BIT(15) | MG_BIT(8) | MG_BIT(7));
  15850. } else if (id1 == MG_PHY_LAN87x) {
  15851. // nothing to do
  15852. } else if (id1 == MG_PHY_RTL8201) {
  15853. // assume PHY has been hardware strapped properly
  15854. #if 0
  15855. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_PAGESEL, 7); // Select page 7
  15856. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_RMSR, 0x1ffa);
  15857. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_PAGESEL, 0); // Select page 0
  15858. #endif
  15859. }
  15860. }
  15861. if (config & MG_PHY_LEDS_ACTIVE_HIGH && id1 == MG_PHY_DP83x) {
  15862. phy->write_reg(phy_addr, MG_PHY_DP83x_REG_LEDCR,
  15863. MG_BIT(9) | MG_BIT(7)); // LED status, active high
  15864. } // Other PHYs do not support this feature
  15865. }
  15866. bool mg_phy_up(struct mg_phy *phy, uint8_t phy_addr, bool *full_duplex,
  15867. uint8_t *speed) {
  15868. bool up = false;
  15869. uint16_t bsr = phy->read_reg(phy_addr, MG_PHY_REG_BSR);
  15870. if ((bsr & MG_BIT(5)) && !(bsr & MG_BIT(2))) // some PHYs latch down events
  15871. bsr = phy->read_reg(phy_addr, MG_PHY_REG_BSR); // read again
  15872. up = bsr & MG_BIT(2);
  15873. if (up && full_duplex != NULL && speed != NULL) {
  15874. uint16_t id1 = phy->read_reg(phy_addr, MG_PHY_REG_ID1);
  15875. if (id1 == MG_PHY_DP83x) {
  15876. uint16_t id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
  15877. if (id2 == MG_PHY_DP83867) {
  15878. uint16_t physts = phy->read_reg(phy_addr, MG_PHY_DP83867_REG_PHYSTS);
  15879. *full_duplex = physts & MG_BIT(13);
  15880. *speed = (physts & MG_BIT(15)) ? MG_PHY_SPEED_1000M
  15881. : (physts & MG_BIT(14)) ? MG_PHY_SPEED_100M
  15882. : MG_PHY_SPEED_10M;
  15883. } else {
  15884. uint16_t physts = phy->read_reg(phy_addr, MG_PHY_DP83x_REG_PHYSTS);
  15885. *full_duplex = physts & MG_BIT(2);
  15886. *speed = (physts & MG_BIT(1)) ? MG_PHY_SPEED_10M : MG_PHY_SPEED_100M;
  15887. }
  15888. } else if (id1 == MG_PHY_KSZ8x) {
  15889. uint16_t pc1r = phy->read_reg(phy_addr, MG_PHY_KSZ8x_REG_PC1R);
  15890. *full_duplex = pc1r & MG_BIT(2);
  15891. *speed = (pc1r & 3) == 1 ? MG_PHY_SPEED_10M : MG_PHY_SPEED_100M;
  15892. } else if (id1 == MG_PHY_LAN87x) {
  15893. uint16_t scsr = phy->read_reg(phy_addr, MG_PHY_LAN87x_REG_SCSR);
  15894. *full_duplex = scsr & MG_BIT(4);
  15895. *speed = (scsr & MG_BIT(3)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
  15896. } else if (id1 == MG_PHY_RTL8201) {
  15897. uint16_t bcr = phy->read_reg(phy_addr, MG_PHY_REG_BCR);
  15898. *full_duplex = bcr & MG_BIT(8);
  15899. *speed = (bcr & MG_BIT(13)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
  15900. }
  15901. }
  15902. return up;
  15903. }
  15904. #ifdef MG_ENABLE_LINES
  15905. #line 1 "src/drivers/pico-w.c"
  15906. #endif
  15907. #if MG_ENABLE_TCPIP && MG_ARCH == MG_ARCH_PICOSDK && \
  15908. defined(MG_ENABLE_DRIVER_PICO_W) && MG_ENABLE_DRIVER_PICO_W
  15909. static struct mg_tcpip_if *s_ifp;
  15910. static bool mg_tcpip_driver_pico_w_init(struct mg_tcpip_if *ifp) {
  15911. struct mg_tcpip_driver_pico_w_data *d =
  15912. (struct mg_tcpip_driver_pico_w_data *) ifp->driver_data;
  15913. s_ifp = ifp;
  15914. if (cyw43_arch_init() != 0)
  15915. return false; // initialize async_context and WiFi chip
  15916. cyw43_arch_enable_sta_mode();
  15917. // start connecting to network
  15918. if (cyw43_arch_wifi_connect_bssid_async(d->ssid, NULL, d->pass,
  15919. CYW43_AUTH_WPA2_AES_PSK) != 0)
  15920. return false;
  15921. cyw43_wifi_get_mac(&cyw43_state, CYW43_ITF_STA, ifp->mac);
  15922. return true;
  15923. }
  15924. static size_t mg_tcpip_driver_pico_w_tx(const void *buf, size_t len,
  15925. struct mg_tcpip_if *ifp) {
  15926. (void) ifp;
  15927. return cyw43_send_ethernet(&cyw43_state, CYW43_ITF_STA, len, buf, false)
  15928. ? 0
  15929. : len;
  15930. }
  15931. static bool mg_tcpip_driver_pico_w_up(struct mg_tcpip_if *ifp) {
  15932. (void) ifp;
  15933. return (cyw43_wifi_link_status(&cyw43_state, CYW43_ITF_STA) ==
  15934. CYW43_LINK_JOIN);
  15935. }
  15936. struct mg_tcpip_driver mg_tcpip_driver_pico_w = {
  15937. mg_tcpip_driver_pico_w_init,
  15938. mg_tcpip_driver_pico_w_tx,
  15939. NULL,
  15940. mg_tcpip_driver_pico_w_up,
  15941. };
  15942. // Called once per outstanding frame by async_context
  15943. void cyw43_cb_process_ethernet(void *cb_data, int itf, size_t len,
  15944. const uint8_t *buf) {
  15945. if (itf != CYW43_ITF_STA) return;
  15946. mg_tcpip_qwrite((void *) buf, len, s_ifp);
  15947. (void) cb_data;
  15948. }
  15949. // Called by async_context
  15950. void cyw43_cb_tcpip_set_link_up(cyw43_t *self, int itf) {}
  15951. void cyw43_cb_tcpip_set_link_down(cyw43_t *self, int itf) {}
  15952. // there's life beyond lwIP
  15953. void pbuf_copy_partial(void) {(void) 0;}
  15954. #endif
  15955. #ifdef MG_ENABLE_LINES
  15956. #line 1 "src/drivers/ppp.c"
  15957. #endif
  15958. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_PPP) && MG_ENABLE_DRIVER_PPP
  15959. #define MG_PPP_FLAG 0x7e // PPP frame delimiter
  15960. #define MG_PPP_ESC 0x7d // PPP escape byte for special characters
  15961. #define MG_PPP_ADDR 0xff
  15962. #define MG_PPP_CTRL 0x03
  15963. #define MG_PPP_PROTO_IP 0x0021
  15964. #define MG_PPP_PROTO_LCP 0xc021
  15965. #define MG_PPP_PROTO_IPCP 0x8021
  15966. #define MG_PPP_IPCP_REQ 1
  15967. #define MG_PPP_IPCP_ACK 2
  15968. #define MG_PPP_IPCP_NACK 3
  15969. #define MG_PPP_IPCP_IPADDR 3
  15970. #define MG_PPP_LCP_CFG_REQ 1
  15971. #define MG_PPP_LCP_CFG_ACK 2
  15972. #define MG_PPP_LCP_CFG_NACK 3
  15973. #define MG_PPP_LCP_CFG_REJECT 4
  15974. #define MG_PPP_LCP_CFG_TERM_REQ 5
  15975. #define MG_PPP_LCP_CFG_TERM_ACK 6
  15976. #define MG_PPP_AT_TIMEOUT 2000
  15977. static size_t print_atcmd(void (*out)(char, void *), void *arg, va_list *ap) {
  15978. struct mg_str s = va_arg(*ap, struct mg_str);
  15979. for (size_t i = 0; i < s.len; i++) out(s.buf[i] < 0x20 ? '.' : s.buf[i], arg);
  15980. return s.len;
  15981. }
  15982. static void mg_ppp_reset(struct mg_tcpip_driver_ppp_data *dd) {
  15983. dd->script_index = 0;
  15984. dd->deadline = 0;
  15985. if (dd->reset) dd->reset(dd->uart);
  15986. }
  15987. static bool mg_ppp_atcmd_handle(struct mg_tcpip_if *ifp) {
  15988. struct mg_tcpip_driver_ppp_data *dd =
  15989. (struct mg_tcpip_driver_ppp_data *) ifp->driver_data;
  15990. if (dd->script == NULL || dd->script_index < 0) return true;
  15991. if (dd->deadline == 0) dd->deadline = mg_millis() + MG_PPP_AT_TIMEOUT;
  15992. for (;;) {
  15993. if (dd->script_index % 2 == 0) { // send AT command
  15994. const char *cmd = dd->script[dd->script_index];
  15995. MG_DEBUG(("send AT[%d]: %M", dd->script_index, print_atcmd, mg_str(cmd)));
  15996. while (*cmd) dd->tx(dd->uart, *cmd++);
  15997. dd->script_index++;
  15998. ifp->recv_queue.head = 0;
  15999. } else { // check AT command response
  16000. const char *expect = dd->script[dd->script_index];
  16001. struct mg_queue *q = &ifp->recv_queue;
  16002. for (;;) {
  16003. int c;
  16004. int is_timeout = dd->deadline > 0 && mg_millis() > dd->deadline;
  16005. int is_overflow = q->head >= q->size - 1;
  16006. if (is_timeout || is_overflow) {
  16007. MG_ERROR(("AT error: %s, retrying...",
  16008. is_timeout ? "timeout" : "overflow"));
  16009. mg_ppp_reset(dd);
  16010. return false; // FAIL: timeout
  16011. }
  16012. if ((c = dd->rx(dd->uart)) < 0) return false; // no data
  16013. q->buf[q->head++] = c;
  16014. if (mg_match(mg_str_n(q->buf, q->head), mg_str(expect), NULL)) {
  16015. MG_DEBUG(("recv AT[%d]: %M", dd->script_index, print_atcmd,
  16016. mg_str_n(q->buf, q->head)));
  16017. dd->script_index++;
  16018. q->head = 0;
  16019. break;
  16020. }
  16021. }
  16022. }
  16023. if (dd->script[dd->script_index] == NULL) {
  16024. MG_DEBUG(("finished AT script"));
  16025. dd->script_index = -1;
  16026. return true;
  16027. }
  16028. }
  16029. }
  16030. static bool mg_ppp_init(struct mg_tcpip_if *ifp) {
  16031. ifp->recv_queue.size = 3000; // MTU=1500, worst case escaping = 2x
  16032. return true;
  16033. }
  16034. // Calculate FCS/CRC for PPP frames. Could be implemented faster using lookup
  16035. // tables.
  16036. static uint32_t fcs_do(uint32_t fcs, uint8_t x) {
  16037. for (int i = 0; i < 8; i++) {
  16038. fcs = ((fcs ^ x) & 1) ? (fcs >> 1) ^ 0x8408 : fcs >> 1;
  16039. x >>= 1;
  16040. }
  16041. return fcs;
  16042. }
  16043. static bool mg_ppp_up(struct mg_tcpip_if *ifp) {
  16044. return ifp->driver_data != NULL;
  16045. }
  16046. // Transmit a single byte as part of the PPP frame (escaped, if needed)
  16047. static void mg_ppp_tx_byte(struct mg_tcpip_driver_ppp_data *dd, uint8_t b) {
  16048. if ((b < 0x20) || (b == MG_PPP_ESC) || (b == MG_PPP_FLAG)) {
  16049. dd->tx(dd->uart, MG_PPP_ESC);
  16050. dd->tx(dd->uart, b ^ 0x20);
  16051. } else {
  16052. dd->tx(dd->uart, b);
  16053. }
  16054. }
  16055. // Transmit a single PPP frame for the given protocol
  16056. static void mg_ppp_tx_frame(struct mg_tcpip_driver_ppp_data *dd, uint16_t proto,
  16057. uint8_t *data, size_t datasz) {
  16058. uint16_t crc;
  16059. uint32_t fcs = 0xffff;
  16060. dd->tx(dd->uart, MG_PPP_FLAG);
  16061. mg_ppp_tx_byte(dd, MG_PPP_ADDR);
  16062. mg_ppp_tx_byte(dd, MG_PPP_CTRL);
  16063. mg_ppp_tx_byte(dd, proto >> 8);
  16064. mg_ppp_tx_byte(dd, proto & 0xff);
  16065. fcs = fcs_do(fcs, MG_PPP_ADDR);
  16066. fcs = fcs_do(fcs, MG_PPP_CTRL);
  16067. fcs = fcs_do(fcs, proto >> 8);
  16068. fcs = fcs_do(fcs, proto & 0xff);
  16069. for (unsigned int i = 0; i < datasz; i++) {
  16070. mg_ppp_tx_byte(dd, data[i]);
  16071. fcs = fcs_do(fcs, data[i]);
  16072. }
  16073. crc = fcs & 0xffff;
  16074. mg_ppp_tx_byte(dd, ~crc); // send CRC, note the byte order
  16075. mg_ppp_tx_byte(dd, ~crc >> 8);
  16076. dd->tx(dd->uart, MG_PPP_FLAG); // end of frame
  16077. }
  16078. // Send Ethernet frame as PPP frame
  16079. static size_t mg_ppp_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
  16080. struct mg_tcpip_driver_ppp_data *dd =
  16081. (struct mg_tcpip_driver_ppp_data *) ifp->driver_data;
  16082. if (ifp->state != MG_TCPIP_STATE_READY) return 0;
  16083. // XXX: what if not an IP protocol?
  16084. mg_ppp_tx_frame(dd, MG_PPP_PROTO_IP, (uint8_t *) buf + 14, len - 14);
  16085. return len;
  16086. }
  16087. // Given a full PPP frame, unescape it in place and verify FCS, returns actual
  16088. // data size on success or 0 on error.
  16089. static size_t mg_ppp_verify_frame(uint8_t *buf, size_t bufsz) {
  16090. int unpack = 0;
  16091. uint16_t crc;
  16092. size_t pktsz = 0;
  16093. uint32_t fcs = 0xffff;
  16094. for (unsigned int i = 0; i < bufsz; i++) {
  16095. if (unpack == 0) {
  16096. if (buf[i] == 0x7d) {
  16097. unpack = 1;
  16098. } else {
  16099. buf[pktsz] = buf[i];
  16100. fcs = fcs_do(fcs, buf[pktsz]);
  16101. pktsz++;
  16102. }
  16103. } else {
  16104. unpack = 0;
  16105. buf[pktsz] = buf[i] ^ 0x20;
  16106. fcs = fcs_do(fcs, buf[pktsz]);
  16107. pktsz++;
  16108. }
  16109. }
  16110. crc = fcs & 0xffff;
  16111. if (crc != 0xf0b8) {
  16112. MG_DEBUG(("bad crc: %04x", crc));
  16113. return 0;
  16114. }
  16115. if (pktsz < 6 || buf[0] != MG_PPP_ADDR || buf[1] != MG_PPP_CTRL) {
  16116. return 0;
  16117. }
  16118. return pktsz - 2; // strip FCS
  16119. }
  16120. // fetch as much data as we can, until a single PPP frame is received
  16121. static size_t mg_ppp_rx_frame(struct mg_tcpip_driver_ppp_data *dd,
  16122. struct mg_queue *q) {
  16123. while (q->head < q->size) {
  16124. int c;
  16125. if ((c = dd->rx(dd->uart)) < 0) {
  16126. return 0;
  16127. }
  16128. if (c == MG_PPP_FLAG) {
  16129. if (q->head > 0) {
  16130. break;
  16131. } else {
  16132. continue;
  16133. }
  16134. }
  16135. q->buf[q->head++] = c;
  16136. }
  16137. size_t n = mg_ppp_verify_frame((uint8_t *) q->buf, q->head);
  16138. if (n == 0) {
  16139. MG_DEBUG(("invalid PPP frame of %d bytes", q->head));
  16140. q->head = 0;
  16141. return 0;
  16142. }
  16143. q->head = n;
  16144. return q->head;
  16145. }
  16146. static void mg_ppp_handle_lcp(struct mg_tcpip_if *ifp, uint8_t *lcp,
  16147. size_t lcpsz) {
  16148. uint8_t id;
  16149. uint16_t len;
  16150. struct mg_tcpip_driver_ppp_data *dd =
  16151. (struct mg_tcpip_driver_ppp_data *) ifp->driver_data;
  16152. if (lcpsz < 4) return;
  16153. id = lcp[1];
  16154. len = (((uint16_t) lcp[2]) << 8) | (lcp[3]);
  16155. switch (lcp[0]) {
  16156. case MG_PPP_LCP_CFG_REQ: {
  16157. if (len == 4) {
  16158. MG_DEBUG(("LCP config request of %d bytes, acknowledging...", len));
  16159. lcp[0] = MG_PPP_LCP_CFG_ACK;
  16160. mg_ppp_tx_frame(dd, MG_PPP_PROTO_LCP, lcp, len);
  16161. lcp[0] = MG_PPP_LCP_CFG_REQ;
  16162. mg_ppp_tx_frame(dd, MG_PPP_PROTO_LCP, lcp, len);
  16163. } else {
  16164. MG_DEBUG(("LCP config request of %d bytes, rejecting...", len));
  16165. lcp[0] = MG_PPP_LCP_CFG_REJECT;
  16166. mg_ppp_tx_frame(dd, MG_PPP_PROTO_LCP, lcp, len);
  16167. }
  16168. } break;
  16169. case MG_PPP_LCP_CFG_TERM_REQ: {
  16170. uint8_t ack[4] = {MG_PPP_LCP_CFG_TERM_ACK, id, 0, 4};
  16171. MG_DEBUG(("LCP termination request, acknowledging..."));
  16172. mg_ppp_tx_frame(dd, MG_PPP_PROTO_LCP, ack, sizeof(ack));
  16173. mg_ppp_reset(dd);
  16174. ifp->state = MG_TCPIP_STATE_UP;
  16175. if (dd->reset) dd->reset(dd->uart);
  16176. } break;
  16177. }
  16178. }
  16179. static void mg_ppp_handle_ipcp(struct mg_tcpip_if *ifp, uint8_t *ipcp,
  16180. size_t ipcpsz) {
  16181. struct mg_tcpip_driver_ppp_data *dd =
  16182. (struct mg_tcpip_driver_ppp_data *) ifp->driver_data;
  16183. uint16_t len;
  16184. uint8_t id;
  16185. uint8_t req[] = {
  16186. MG_PPP_IPCP_REQ, 0, 0, 10, MG_PPP_IPCP_IPADDR, 6, 0, 0, 0, 0};
  16187. if (ipcpsz < 4) return;
  16188. id = ipcp[1];
  16189. len = (((uint16_t) ipcp[2]) << 8) | (ipcp[3]);
  16190. switch (ipcp[0]) {
  16191. case MG_PPP_IPCP_REQ:
  16192. MG_DEBUG(("got IPCP config request, acknowledging..."));
  16193. if (len >= 10 && ipcp[4] == MG_PPP_IPCP_IPADDR) {
  16194. uint8_t *ip = ipcp + 6;
  16195. MG_DEBUG(("host ip: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]));
  16196. }
  16197. ipcp[0] = MG_PPP_IPCP_ACK;
  16198. mg_ppp_tx_frame(dd, MG_PPP_PROTO_IPCP, ipcp, len);
  16199. req[1] = id;
  16200. // Request IP address 0.0.0.0
  16201. mg_ppp_tx_frame(dd, MG_PPP_PROTO_IPCP, req, sizeof(req));
  16202. break;
  16203. case MG_PPP_IPCP_ACK:
  16204. // This usually does not happen, as our "preferred" IP address is invalid
  16205. MG_DEBUG(("got IPCP config ack, link is online now"));
  16206. ifp->state = MG_TCPIP_STATE_READY;
  16207. break;
  16208. case MG_PPP_IPCP_NACK:
  16209. MG_DEBUG(("got IPCP config nack"));
  16210. // NACK contains our "suggested" IP address, use it
  16211. if (len >= 10 && ipcp[4] == MG_PPP_IPCP_IPADDR) {
  16212. uint8_t *ip = ipcp + 6;
  16213. MG_DEBUG(("ipcp ack, ip: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]));
  16214. ipcp[0] = MG_PPP_IPCP_REQ;
  16215. mg_ppp_tx_frame(dd, MG_PPP_PROTO_IPCP, ipcp, len);
  16216. ifp->ip = ifp->mask = MG_IPV4(ip[0], ip[1], ip[2], ip[3]);
  16217. ifp->state = MG_TCPIP_STATE_READY;
  16218. }
  16219. break;
  16220. }
  16221. }
  16222. static size_t mg_ppp_rx(void *ethbuf, size_t ethlen, struct mg_tcpip_if *ifp) {
  16223. uint8_t *eth = ethbuf;
  16224. size_t ethsz = 0;
  16225. struct mg_tcpip_driver_ppp_data *dd =
  16226. (struct mg_tcpip_driver_ppp_data *) ifp->driver_data;
  16227. uint8_t *buf = (uint8_t *) ifp->recv_queue.buf;
  16228. if (!mg_ppp_atcmd_handle(ifp)) return 0;
  16229. size_t bufsz = mg_ppp_rx_frame(dd, &ifp->recv_queue);
  16230. if (!bufsz) return 0;
  16231. uint16_t proto = (((uint16_t) buf[2]) << 8) | (uint16_t) buf[3];
  16232. switch (proto) {
  16233. case MG_PPP_PROTO_LCP: mg_ppp_handle_lcp(ifp, buf + 4, bufsz - 4); break;
  16234. case MG_PPP_PROTO_IPCP: mg_ppp_handle_ipcp(ifp, buf + 4, bufsz - 4); break;
  16235. case MG_PPP_PROTO_IP:
  16236. MG_VERBOSE(("got IP packet of %d bytes", bufsz - 4));
  16237. memmove(eth + 14, buf + 4, bufsz - 4);
  16238. memmove(eth, ifp->mac, 6);
  16239. memmove(eth + 6, "\xff\xff\xff\xff\xff\xff", 6);
  16240. eth[12] = 0x08;
  16241. eth[13] = 0x00;
  16242. ethsz = bufsz - 4 + 14;
  16243. ifp->recv_queue.head = 0;
  16244. return ethsz;
  16245. #if 0
  16246. default:
  16247. MG_DEBUG(("unknown PPP frame:"));
  16248. mg_hexdump(ppp->buf, ppp->bufsz);
  16249. #endif
  16250. }
  16251. ifp->recv_queue.head = 0;
  16252. return 0;
  16253. (void) ethlen;
  16254. }
  16255. struct mg_tcpip_driver mg_tcpip_driver_ppp = {mg_ppp_init, mg_ppp_tx, mg_ppp_rx,
  16256. mg_ppp_up};
  16257. #endif
  16258. #ifdef MG_ENABLE_LINES
  16259. #line 1 "src/drivers/ra.c"
  16260. #endif
  16261. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RA) && MG_ENABLE_DRIVER_RA
  16262. struct ra_etherc {
  16263. volatile uint32_t ECMR, RESERVED, RFLR, RESERVED1, ECSR, RESERVED2, ECSIPR,
  16264. RESERVED3, PIR, RESERVED4, PSR, RESERVED5[5], RDMLR, RESERVED6[3], IPGR,
  16265. APR, MPR, RESERVED7, RFCF, TPAUSER, TPAUSECR, BCFRR, RESERVED8[20], MAHR,
  16266. RESERVED9, MALR, RESERVED10, TROCR, CDCR, LCCR, CNDCR, RESERVED11, CEFCR,
  16267. FRECR, TSFRCR, TLFRCR, RFCR, MAFCR;
  16268. };
  16269. struct ra_edmac {
  16270. volatile uint32_t EDMR, RESERVED, EDTRR, RESERVED1, EDRRR, RESERVED2, TDLAR,
  16271. RESERVED3, RDLAR, RESERVED4, EESR, RESERVED5, EESIPR, RESERVED6, TRSCER,
  16272. RESERVED7, RMFCR, RESERVED8, TFTR, RESERVED9, FDR, RESERVED10, RMCR,
  16273. RESERVED11[2], TFUCR, RFOCR, IOSR, FCFTR, RESERVED12, RPADIR, TRIMD,
  16274. RESERVED13[18], RBWAR, RDFAR, RESERVED14, TBRAR, TDFAR;
  16275. };
  16276. #undef ETHERC
  16277. #define ETHERC ((struct ra_etherc *) (uintptr_t) 0x40114100U)
  16278. #undef EDMAC
  16279. #define EDMAC ((struct ra_edmac *) (uintptr_t) 0x40114000U)
  16280. #undef RASYSC
  16281. #define RASYSC ((uint32_t *) (uintptr_t) 0x4001E000U)
  16282. #undef ICU_IELSR
  16283. #define ICU_IELSR ((uint32_t *) (uintptr_t) 0x40006300U)
  16284. #define ETH_PKT_SIZE 1536 // Max frame size, multiple of 32
  16285. #define ETH_DESC_CNT 4 // Descriptors count
  16286. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  16287. #define MG_16BYTE_ALIGNED __attribute__((aligned((16U))))
  16288. #define MG_32BYTE_ALIGNED __attribute__((aligned((32U))))
  16289. // Descriptors: 16-byte aligned
  16290. // Buffers: 32-byte aligned (27.3.1)
  16291. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][4] MG_16BYTE_ALIGNED;
  16292. static volatile uint32_t s_txdesc[ETH_DESC_CNT][4] MG_16BYTE_ALIGNED;
  16293. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_32BYTE_ALIGNED;
  16294. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_32BYTE_ALIGNED;
  16295. static struct mg_tcpip_if *s_ifp; // MIP interface
  16296. // fastest is 3 cycles (SUB + BNE) on a 3-stage pipeline or equivalent
  16297. static inline void raspin(volatile uint32_t count) {
  16298. while (count--) (void) 0;
  16299. }
  16300. // count to get the 200ns SMC semi-cycle period (2.5MHz) calling raspin():
  16301. // SYS_FREQUENCY * 200ns / 3 = SYS_FREQUENCY / 15000000
  16302. static uint32_t s_smispin;
  16303. // Bit-banged SMI
  16304. static void smi_preamble(void) {
  16305. unsigned int i = 32;
  16306. uint32_t pir = MG_BIT(1) | MG_BIT(2); // write, mdio = 1, mdc = 0
  16307. ETHERC->PIR = pir;
  16308. while (i--) {
  16309. pir &= ~MG_BIT(0); // mdc = 0
  16310. ETHERC->PIR = pir;
  16311. raspin(s_smispin);
  16312. pir |= MG_BIT(0); // mdc = 1
  16313. ETHERC->PIR = pir;
  16314. raspin(s_smispin);
  16315. }
  16316. }
  16317. static void smi_wr(uint16_t header, uint16_t data) {
  16318. uint32_t word = (header << 16) | data;
  16319. smi_preamble();
  16320. unsigned int i = 32;
  16321. while (i--) {
  16322. uint32_t pir = MG_BIT(1) |
  16323. (word & 0x80000000 ? MG_BIT(2) : 0); // write, mdc = 0, data
  16324. ETHERC->PIR = pir;
  16325. raspin(s_smispin);
  16326. pir |= MG_BIT(0); // mdc = 1
  16327. ETHERC->PIR = pir;
  16328. raspin(s_smispin);
  16329. word <<= 1;
  16330. }
  16331. }
  16332. static uint16_t smi_rd(uint16_t header) {
  16333. smi_preamble();
  16334. unsigned int i = 16; // 2 LSb as turnaround
  16335. uint32_t pir;
  16336. while (i--) {
  16337. pir = (i > 1 ? MG_BIT(1) : 0) |
  16338. (header & 0x8000
  16339. ? MG_BIT(2)
  16340. : 0); // mdc = 0, header, set read direction at turnaround
  16341. ETHERC->PIR = pir;
  16342. raspin(s_smispin);
  16343. pir |= MG_BIT(0); // mdc = 1
  16344. ETHERC->PIR = pir;
  16345. raspin(s_smispin);
  16346. header <<= 1;
  16347. }
  16348. i = 16;
  16349. uint16_t data = 0;
  16350. while (i--) {
  16351. data <<= 1;
  16352. pir = 0; // read, mdc = 0
  16353. ETHERC->PIR = pir;
  16354. raspin(s_smispin / 2); // 1/4 clock period, 300ns max access time
  16355. data |= (uint16_t)(ETHERC->PIR & MG_BIT(3) ? 1 : 0); // read mdio
  16356. raspin(s_smispin / 2); // 1/4 clock period
  16357. pir |= MG_BIT(0); // mdc = 1
  16358. ETHERC->PIR = pir;
  16359. raspin(s_smispin);
  16360. }
  16361. return data;
  16362. }
  16363. static uint16_t raeth_read_phy(uint8_t addr, uint8_t reg) {
  16364. return smi_rd((uint16_t)((1 << 14) | (2 << 12) | (addr << 7) | (reg << 2) | (2 << 0)));
  16365. }
  16366. static void raeth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  16367. smi_wr((uint16_t)((1 << 14) | (1 << 12) | (addr << 7) | (reg << 2) | (2 << 0)), val);
  16368. }
  16369. // MDC clock is generated manually; as per 802.3, it must not exceed 2.5MHz
  16370. static bool mg_tcpip_driver_ra_init(struct mg_tcpip_if *ifp) {
  16371. struct mg_tcpip_driver_ra_data *d =
  16372. (struct mg_tcpip_driver_ra_data *) ifp->driver_data;
  16373. s_ifp = ifp;
  16374. // Init SMI clock timing. If user told us the clock value, use it.
  16375. // TODO(): Otherwise, guess
  16376. s_smispin = d->clock / 15000000;
  16377. // Init RX descriptors
  16378. for (int i = 0; i < ETH_DESC_CNT; i++) {
  16379. s_rxdesc[i][0] = MG_BIT(31); // RACT
  16380. s_rxdesc[i][1] = ETH_PKT_SIZE << 16; // RBL
  16381. s_rxdesc[i][2] = (uint32_t) s_rxbuf[i]; // Point to data buffer
  16382. }
  16383. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(30); // Wrap last descriptor
  16384. // Init TX descriptors
  16385. for (int i = 0; i < ETH_DESC_CNT; i++) {
  16386. // TACT = 0
  16387. s_txdesc[i][2] = (uint32_t) s_txbuf[i];
  16388. }
  16389. s_txdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(30); // Wrap last descriptor
  16390. EDMAC->EDMR = MG_BIT(0); // Software reset, wait 64 PCLKA clocks (27.2.1)
  16391. uint32_t sckdivcr = RASYSC[8]; // get divisors from SCKDIVCR (8.2.2)
  16392. uint32_t ick = 1 << ((sckdivcr >> 24) & 7); // sys_clock div
  16393. uint32_t pcka = 1 << ((sckdivcr >> 12) & 7); // pclka div
  16394. raspin((64U * pcka) / (3U * ick));
  16395. EDMAC->EDMR = MG_BIT(6); // Initialize, little-endian (27.2.1)
  16396. MG_DEBUG(("PHY addr: %d, smispin: %d", d->phy_addr, s_smispin));
  16397. struct mg_phy phy = {raeth_read_phy, raeth_write_phy};
  16398. mg_phy_init(&phy, d->phy_addr, 0); // MAC clocks PHY
  16399. // Select RMII mode,
  16400. ETHERC->ECMR = MG_BIT(2) | MG_BIT(1); // 100M, Full-duplex, CRC
  16401. // ETHERC->ECMR |= MG_BIT(0); // Receive all
  16402. ETHERC->RFLR = 1518; // Set max rx length
  16403. EDMAC->RDLAR = (uint32_t) (uintptr_t) s_rxdesc;
  16404. EDMAC->TDLAR = (uint32_t) (uintptr_t) s_txdesc;
  16405. // MAC address filtering (bytes in reversed order)
  16406. ETHERC->MAHR = (uint32_t) (ifp->mac[0] << 24U) |
  16407. ((uint32_t) ifp->mac[1] << 16U) |
  16408. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  16409. ETHERC->MALR = ((uint32_t) ifp->mac[4] << 8U) | ifp->mac[5];
  16410. EDMAC->TFTR = 0; // Store and forward (27.2.10)
  16411. EDMAC->FDR = 0x070f; // (27.2.11)
  16412. EDMAC->RMCR = MG_BIT(0); // (27.2.12)
  16413. ETHERC->ECMR |= MG_BIT(6) | MG_BIT(5); // TE RE
  16414. EDMAC->EESIPR = MG_BIT(18); // Enable Rx IRQ
  16415. EDMAC->EDRRR = MG_BIT(0); // Receive Descriptors have changed
  16416. EDMAC->EDTRR = MG_BIT(0); // Transmit Descriptors have changed
  16417. return true;
  16418. }
  16419. // Transmit frame
  16420. static size_t mg_tcpip_driver_ra_tx(const void *buf, size_t len,
  16421. struct mg_tcpip_if *ifp) {
  16422. static int s_txno; // Current descriptor index
  16423. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  16424. MG_ERROR(("Frame too big, %ld", (long) len));
  16425. len = (size_t) -1; // fail
  16426. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  16427. ifp->nerr++;
  16428. MG_ERROR(("No descriptors available"));
  16429. len = 0; // retry later
  16430. } else {
  16431. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  16432. s_txdesc[s_txno][1] = len << 16; // Set data len
  16433. s_txdesc[s_txno][0] |= MG_BIT(31) | 3 << 28; // (27.3.1.1) mark valid
  16434. EDMAC->EDTRR = MG_BIT(0); // Transmit request
  16435. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  16436. }
  16437. return len;
  16438. }
  16439. static bool mg_tcpip_driver_ra_up(struct mg_tcpip_if *ifp) {
  16440. struct mg_tcpip_driver_ra_data *d =
  16441. (struct mg_tcpip_driver_ra_data *) ifp->driver_data;
  16442. uint8_t speed = MG_PHY_SPEED_10M;
  16443. bool up = false, full_duplex = false;
  16444. struct mg_phy phy = {raeth_read_phy, raeth_write_phy};
  16445. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  16446. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  16447. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  16448. // if(link is slow or half) set flags otherwise
  16449. // reg = tmp
  16450. uint32_t ecmr = ETHERC->ECMR | MG_BIT(2) | MG_BIT(1); // 100M Full-duplex
  16451. if (speed == MG_PHY_SPEED_10M) ecmr &= ~MG_BIT(2); // 10M
  16452. if (full_duplex == false) ecmr &= ~MG_BIT(1); // Half-duplex
  16453. ETHERC->ECMR = ecmr; // IRQ handler does not fiddle with these registers
  16454. MG_DEBUG(("Link is %uM %s-duplex", ecmr & MG_BIT(2) ? 100 : 10,
  16455. ecmr & MG_BIT(1) ? "full" : "half"));
  16456. }
  16457. return up;
  16458. }
  16459. void EDMAC_IRQHandler(void);
  16460. static uint32_t s_rxno;
  16461. void EDMAC_IRQHandler(void) {
  16462. struct mg_tcpip_driver_ra_data *d =
  16463. (struct mg_tcpip_driver_ra_data *) s_ifp->driver_data;
  16464. EDMAC->EESR = MG_BIT(18); // Ack IRQ in EDMAC 1st
  16465. ICU_IELSR[d->irqno] &= ~MG_BIT(16); // Ack IRQ in ICU last
  16466. // Frame received, loop
  16467. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  16468. uint32_t r = s_rxdesc[s_rxno][0];
  16469. if (r & MG_BIT(31)) break; // exit when done
  16470. // skip partial/errored frames (27.3.1.2)
  16471. if ((r & (MG_BIT(29) | MG_BIT(28)) && !(r & MG_BIT(27)))) {
  16472. size_t len = s_rxdesc[s_rxno][1] & 0xffff;
  16473. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp); // CRC already stripped
  16474. }
  16475. s_rxdesc[s_rxno][0] |= MG_BIT(31);
  16476. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  16477. }
  16478. EDMAC->EDRRR = MG_BIT(0); // Receive Descriptors have changed
  16479. // If b0 == 0, descriptors were exhausted and probably frames were dropped,
  16480. // (27.2.9 RMFCR counts them)
  16481. }
  16482. struct mg_tcpip_driver mg_tcpip_driver_ra = {mg_tcpip_driver_ra_init,
  16483. mg_tcpip_driver_ra_tx, NULL,
  16484. mg_tcpip_driver_ra_up};
  16485. #endif
  16486. #ifdef MG_ENABLE_LINES
  16487. #line 1 "src/drivers/same54.c"
  16488. #endif
  16489. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && MG_ENABLE_DRIVER_SAME54
  16490. #include <sam.h>
  16491. #define ETH_PKT_SIZE 1536 // Max frame size
  16492. #define ETH_DESC_CNT 4 // Descriptors count
  16493. #define ETH_DS 2 // Descriptor size (words)
  16494. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  16495. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  16496. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  16497. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  16498. static uint8_t s_txno; // Current TX descriptor
  16499. static uint8_t s_rxno; // Current RX descriptor
  16500. static struct mg_tcpip_if *s_ifp; // MIP interface
  16501. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  16502. #define MG_PHYREGBIT_BCR_DUPLEX_MODE MG_BIT(8)
  16503. #define MG_PHYREGBIT_BCR_SPEED MG_BIT(13)
  16504. #define MG_PHYREGBIT_BSR_LINK_STATUS MG_BIT(2)
  16505. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  16506. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk |
  16507. GMAC_MAN_OP(2) | // Setting the read operation
  16508. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  16509. GMAC_MAN_REGA(reg); // Setting the register
  16510. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)) (void) 0;
  16511. return GMAC_REGS->GMAC_MAN & GMAC_MAN_DATA_Msk; // Getting the read value
  16512. }
  16513. #if 0
  16514. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  16515. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk | GMAC_MAN_OP(1) | // Setting the write operation
  16516. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  16517. GMAC_MAN_REGA(reg) | GMAC_MAN_DATA(val); // Setting the register
  16518. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)); // Waiting until the write op is complete
  16519. }
  16520. #endif
  16521. int get_clock_rate(struct mg_tcpip_driver_same54_data *d) {
  16522. if (d && d->mdc_cr >= 0 && d->mdc_cr <= 5) {
  16523. return d->mdc_cr;
  16524. } else {
  16525. // get MCLK from GCLK_GENERATOR 0
  16526. uint32_t div = 512;
  16527. uint32_t mclk;
  16528. if (!(GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_DIVSEL_Msk)) {
  16529. div = ((GCLK_REGS->GCLK_GENCTRL[0] & 0x00FF0000) >> 16);
  16530. if (div == 0) div = 1;
  16531. }
  16532. switch (GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_SRC_Msk) {
  16533. case GCLK_GENCTRL_SRC_XOSC0_Val:
  16534. mclk = 32000000UL; /* 32MHz */
  16535. break;
  16536. case GCLK_GENCTRL_SRC_XOSC1_Val:
  16537. mclk = 32000000UL; /* 32MHz */
  16538. break;
  16539. case GCLK_GENCTRL_SRC_OSCULP32K_Val:
  16540. mclk = 32000UL;
  16541. break;
  16542. case GCLK_GENCTRL_SRC_XOSC32K_Val:
  16543. mclk = 32000UL;
  16544. break;
  16545. case GCLK_GENCTRL_SRC_DFLL_Val:
  16546. mclk = 48000000UL; /* 48MHz */
  16547. break;
  16548. case GCLK_GENCTRL_SRC_DPLL0_Val:
  16549. mclk = 200000000UL; /* 200MHz */
  16550. break;
  16551. case GCLK_GENCTRL_SRC_DPLL1_Val:
  16552. mclk = 200000000UL; /* 200MHz */
  16553. break;
  16554. default:
  16555. mclk = 200000000UL; /* 200MHz */
  16556. }
  16557. mclk /= div;
  16558. uint8_t crs[] = {0, 1, 2, 3, 4, 5}; // GMAC->NCFGR::CLK values
  16559. uint8_t dividers[] = {8, 16, 32, 48, 64, 96}; // Respective CLK dividers
  16560. for (int i = 0; i < 6; i++) {
  16561. if (mclk / dividers[i] <= 2375000UL /* 2.5MHz - 5% */) {
  16562. return crs[i];
  16563. }
  16564. }
  16565. return 5;
  16566. }
  16567. }
  16568. static bool mg_tcpip_driver_same54_init(struct mg_tcpip_if *ifp) {
  16569. struct mg_tcpip_driver_same54_data *d =
  16570. (struct mg_tcpip_driver_same54_data *) ifp->driver_data;
  16571. s_ifp = ifp;
  16572. MCLK_REGS->MCLK_APBCMASK |= MCLK_APBCMASK_GMAC_Msk;
  16573. MCLK_REGS->MCLK_AHBMASK |= MCLK_AHBMASK_GMAC_Msk;
  16574. GMAC_REGS->GMAC_NCFGR = GMAC_NCFGR_CLK(get_clock_rate(d)); // Set MDC divider
  16575. GMAC_REGS->GMAC_NCR = 0; // Disable RX & TX
  16576. GMAC_REGS->GMAC_NCR |= GMAC_NCR_MPE_Msk; // Enable MDC & MDIO
  16577. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init TX descriptors
  16578. s_txdesc[i][0] = (uint32_t) s_txbuf[i]; // Point to data buffer
  16579. s_txdesc[i][1] = MG_BIT(31); // OWN bit
  16580. }
  16581. s_txdesc[ETH_DESC_CNT - 1][1] |= MG_BIT(30); // Last tx descriptor - wrap
  16582. GMAC_REGS->GMAC_DCFGR = GMAC_DCFGR_DRBS(0x18) // DMA recv buf 1536
  16583. | GMAC_DCFGR_RXBMS(GMAC_DCFGR_RXBMS_FULL_Val) |
  16584. GMAC_DCFGR_TXPBMS(1); // See #2487
  16585. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init RX descriptors
  16586. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i]; // Address of the data buffer
  16587. s_rxdesc[i][1] = 0; // Clear status
  16588. }
  16589. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(1); // Last rx descriptor - wrap
  16590. GMAC_REGS->GMAC_TBQB = (uint32_t) s_txdesc; // about the descriptor addresses
  16591. GMAC_REGS->GMAC_RBQB = (uint32_t) s_rxdesc; // Let the controller know
  16592. GMAC_REGS->SA[0].GMAC_SAB =
  16593. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  16594. GMAC_REGS->SA[0].GMAC_SAT = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  16595. GMAC_REGS->GMAC_UR &= ~GMAC_UR_MII_Msk; // Disable MII, use RMII
  16596. GMAC_REGS->GMAC_NCFGR |= GMAC_NCFGR_MAXFS_Msk | GMAC_NCFGR_MTIHEN_Msk |
  16597. GMAC_NCFGR_EFRHD_Msk | GMAC_NCFGR_CAF_Msk;
  16598. GMAC_REGS->GMAC_TSR = GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk |
  16599. GMAC_TSR_TXCOMP_Msk | GMAC_TSR_TFC_Msk |
  16600. GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  16601. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk;
  16602. GMAC_REGS->GMAC_RSR = GMAC_RSR_HNO_Msk | GMAC_RSR_RXOVR_Msk |
  16603. GMAC_RSR_REC_Msk | GMAC_RSR_BNA_Msk;
  16604. GMAC_REGS->GMAC_IDR = ~0U; // Disable interrupts, then enable required
  16605. GMAC_REGS->GMAC_IER = GMAC_IER_HRESP_Msk | GMAC_IER_ROVR_Msk |
  16606. GMAC_IER_TCOMP_Msk | GMAC_IER_TFC_Msk |
  16607. GMAC_IER_RLEX_Msk | GMAC_IER_TUR_Msk |
  16608. GMAC_IER_RXUBR_Msk | GMAC_IER_RCOMP_Msk;
  16609. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TXEN_Msk | GMAC_NCR_RXEN_Msk;
  16610. NVIC_EnableIRQ(GMAC_IRQn);
  16611. return true;
  16612. }
  16613. static size_t mg_tcpip_driver_same54_tx(const void *buf, size_t len,
  16614. struct mg_tcpip_if *ifp) {
  16615. if (len > sizeof(s_txbuf[s_txno])) {
  16616. MG_ERROR(("Frame too big, %ld", (long) len));
  16617. len = 0; // Frame is too big
  16618. } else if ((s_txdesc[s_txno][1] & MG_BIT(31)) == 0) {
  16619. ifp->nerr++;
  16620. MG_ERROR(("No free descriptors"));
  16621. len = 0; // All descriptors are busy, fail
  16622. } else {
  16623. uint32_t status = len | MG_BIT(15); // Frame length, last chunk
  16624. if (s_txno == ETH_DESC_CNT - 1) status |= MG_BIT(30); // wrap
  16625. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  16626. s_txdesc[s_txno][1] = status;
  16627. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  16628. }
  16629. __DSB(); // Ensure descriptors have been written
  16630. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TSTART_Msk; // Enable transmission
  16631. return len;
  16632. }
  16633. static bool mg_tcpip_driver_same54_up(struct mg_tcpip_if *ifp) {
  16634. uint16_t bsr = eth_read_phy(MG_PHY_ADDR, MG_PHYREG_BSR);
  16635. bool up = bsr & MG_PHYREGBIT_BSR_LINK_STATUS ? 1 : 0;
  16636. // If PHY is ready, update NCFGR accordingly
  16637. if (ifp->state == MG_TCPIP_STATE_DOWN && up) {
  16638. uint16_t bcr = eth_read_phy(MG_PHY_ADDR, MG_PHYREG_BCR);
  16639. bool fd = bcr & MG_PHYREGBIT_BCR_DUPLEX_MODE ? 1 : 0;
  16640. bool spd = bcr & MG_PHYREGBIT_BCR_SPEED ? 1 : 0;
  16641. GMAC_REGS->GMAC_NCFGR = (GMAC_REGS->GMAC_NCFGR &
  16642. ~(GMAC_NCFGR_SPD_Msk | MG_PHYREGBIT_BCR_SPEED)) |
  16643. GMAC_NCFGR_SPD(spd) | GMAC_NCFGR_FD(fd);
  16644. }
  16645. return up;
  16646. }
  16647. void GMAC_Handler(void);
  16648. void GMAC_Handler(void) {
  16649. uint32_t isr = GMAC_REGS->GMAC_ISR;
  16650. uint32_t rsr = GMAC_REGS->GMAC_RSR;
  16651. uint32_t tsr = GMAC_REGS->GMAC_TSR;
  16652. if (isr & GMAC_ISR_RCOMP_Msk) {
  16653. if (rsr & GMAC_ISR_RCOMP_Msk) {
  16654. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  16655. if ((s_rxdesc[s_rxno][0] & MG_BIT(0)) == 0) break;
  16656. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  16657. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  16658. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // Disown
  16659. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  16660. }
  16661. }
  16662. }
  16663. if ((tsr & (GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk | GMAC_TSR_TXCOMP_Msk |
  16664. GMAC_TSR_TFC_Msk | GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  16665. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk)) != 0) {
  16666. // MG_INFO((" --> %#x %#x", s_txdesc[s_txno][1], tsr));
  16667. if (!(s_txdesc[s_txno][1] & MG_BIT(31))) s_txdesc[s_txno][1] |= MG_BIT(31);
  16668. }
  16669. GMAC_REGS->GMAC_RSR = rsr;
  16670. GMAC_REGS->GMAC_TSR = tsr;
  16671. }
  16672. struct mg_tcpip_driver mg_tcpip_driver_same54 = {
  16673. mg_tcpip_driver_same54_init, mg_tcpip_driver_same54_tx, NULL,
  16674. mg_tcpip_driver_same54_up};
  16675. #endif
  16676. #ifdef MG_ENABLE_LINES
  16677. #line 1 "src/drivers/stm32f.c"
  16678. #endif
  16679. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
  16680. MG_ENABLE_DRIVER_STM32F
  16681. struct stm32f_eth {
  16682. volatile uint32_t MACCR, MACFFR, MACHTHR, MACHTLR, MACMIIAR, MACMIIDR, MACFCR,
  16683. MACVLANTR, RESERVED0[2], MACRWUFFR, MACPMTCSR, RESERVED1, MACDBGR, MACSR,
  16684. MACIMR, MACA0HR, MACA0LR, MACA1HR, MACA1LR, MACA2HR, MACA2LR, MACA3HR,
  16685. MACA3LR, RESERVED2[40], MMCCR, MMCRIR, MMCTIR, MMCRIMR, MMCTIMR,
  16686. RESERVED3[14], MMCTGFSCCR, MMCTGFMSCCR, RESERVED4[5], MMCTGFCR,
  16687. RESERVED5[10], MMCRFCECR, MMCRFAECR, RESERVED6[10], MMCRGUFCR,
  16688. RESERVED7[334], PTPTSCR, PTPSSIR, PTPTSHR, PTPTSLR, PTPTSHUR, PTPTSLUR,
  16689. PTPTSAR, PTPTTHR, PTPTTLR, RESERVED8, PTPTSSR, PTPPPSCR, RESERVED9[564],
  16690. DMABMR, DMATPDR, DMARPDR, DMARDLAR, DMATDLAR, DMASR, DMAOMR, DMAIER,
  16691. DMAMFBOCR, DMARSWTR, RESERVED10[8], DMACHTDR, DMACHRDR, DMACHTBAR,
  16692. DMACHRBAR;
  16693. };
  16694. #undef ETH
  16695. #define ETH ((struct stm32f_eth *) (uintptr_t) 0x40028000)
  16696. #define ETH_PKT_SIZE 1540 // Max frame size
  16697. #define ETH_DESC_CNT 4 // Descriptors count
  16698. #define ETH_DS 4 // Descriptor size (words)
  16699. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  16700. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  16701. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  16702. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  16703. static uint8_t s_txno; // Current TX descriptor
  16704. static uint8_t s_rxno; // Current RX descriptor
  16705. static struct mg_tcpip_if *s_ifp; // MIP interface
  16706. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  16707. ETH->MACMIIAR &= (7 << 2);
  16708. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  16709. ETH->MACMIIAR |= MG_BIT(0);
  16710. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  16711. return ETH->MACMIIDR & 0xffff;
  16712. }
  16713. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  16714. ETH->MACMIIDR = val;
  16715. ETH->MACMIIAR &= (7 << 2);
  16716. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  16717. ETH->MACMIIAR |= MG_BIT(0);
  16718. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  16719. }
  16720. static uint32_t get_hclk(void) {
  16721. struct rcc {
  16722. volatile uint32_t CR, PLLCFGR, CFGR;
  16723. } *rcc = (struct rcc *) 0x40023800;
  16724. uint32_t clk = 0, hsi = 16000000 /* 16 MHz */, hse = 8000000 /* 8MHz */;
  16725. if (rcc->CFGR & (1 << 2)) {
  16726. clk = hse;
  16727. } else if (rcc->CFGR & (1 << 3)) {
  16728. uint32_t vco, m, n, p;
  16729. m = (rcc->PLLCFGR & (0x3f << 0)) >> 0;
  16730. n = (rcc->PLLCFGR & (0x1ff << 6)) >> 6;
  16731. p = (((rcc->PLLCFGR & (3 << 16)) >> 16) + 1) * 2;
  16732. clk = (rcc->PLLCFGR & (1 << 22)) ? hse : hsi;
  16733. vco = (uint32_t) ((uint64_t) clk * n / m);
  16734. clk = vco / p;
  16735. } else {
  16736. clk = hsi;
  16737. }
  16738. uint32_t hpre = (rcc->CFGR & (15 << 4)) >> 4;
  16739. if (hpre < 8) return clk;
  16740. uint8_t ahbptab[8] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  16741. return ((uint32_t) clk) >> ahbptab[hpre - 8];
  16742. }
  16743. // Guess CR from HCLK. MDC clock is generated from HCLK (AHB); as per 802.3,
  16744. // it must not exceed 2.5MHz As the AHB clock can be (and usually is) derived
  16745. // from the HSI (internal RC), and it can go above specs, the datasheets
  16746. // specify a range of frequencies and activate one of a series of dividers to
  16747. // keep the MDC clock safely below 2.5MHz. We guess a divider setting based on
  16748. // HCLK with a +5% drift. If the user uses a different clock from our
  16749. // defaults, needs to set the macros on top Valid for STM32F74xxx/75xxx
  16750. // (38.8.1) and STM32F42xxx/43xxx (33.8.1) (both 4.5% worst case drift)
  16751. static int guess_mdc_cr(void) {
  16752. uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMIIAR::CR values
  16753. uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  16754. uint32_t hclk = get_hclk(); // Guess system HCLK
  16755. int result = -1; // Invalid CR value
  16756. if (hclk < 25000000) {
  16757. MG_ERROR(("HCLK too low"));
  16758. } else {
  16759. for (int i = 0; i < 6; i++) {
  16760. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  16761. result = crs[i];
  16762. break;
  16763. }
  16764. }
  16765. if (result < 0) MG_ERROR(("HCLK too high"));
  16766. }
  16767. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  16768. return result;
  16769. }
  16770. static bool mg_tcpip_driver_stm32f_init(struct mg_tcpip_if *ifp) {
  16771. struct mg_tcpip_driver_stm32f_data *d =
  16772. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  16773. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  16774. s_ifp = ifp;
  16775. // Init RX descriptors
  16776. for (int i = 0; i < ETH_DESC_CNT; i++) {
  16777. s_rxdesc[i][0] = MG_BIT(31); // Own
  16778. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  16779. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  16780. s_rxdesc[i][3] =
  16781. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  16782. }
  16783. // Init TX descriptors
  16784. for (int i = 0; i < ETH_DESC_CNT; i++) {
  16785. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  16786. s_txdesc[i][3] =
  16787. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  16788. }
  16789. ETH->DMABMR |= MG_BIT(0); // Software reset
  16790. while ((ETH->DMABMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  16791. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  16792. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  16793. ETH->MACMIIAR = ((uint32_t) cr & 7) << 2;
  16794. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  16795. // hardware checksum. Therefore, descriptor size is 4, not 8
  16796. // ETH->DMABMR = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) |
  16797. // MG_BIT(25);
  16798. ETH->MACIMR = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  16799. ETH->MACFCR = MG_BIT(7); // Disable zero quarta pause
  16800. // ETH->MACFFR = MG_BIT(31); // Receive all
  16801. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  16802. mg_phy_init(&phy, phy_addr, MG_PHY_CLOCKS_MAC);
  16803. ETH->DMARDLAR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  16804. ETH->DMATDLAR = (uint32_t) (uintptr_t) s_txdesc; // RX descriptors
  16805. ETH->DMAIER = MG_BIT(6) | MG_BIT(16); // RIE, NISE
  16806. ETH->MACCR =
  16807. MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  16808. ETH->DMAOMR =
  16809. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  16810. // MAC address filtering
  16811. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  16812. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  16813. ((uint32_t) ifp->mac[2] << 16) |
  16814. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  16815. return true;
  16816. }
  16817. static size_t mg_tcpip_driver_stm32f_tx(const void *buf, size_t len,
  16818. struct mg_tcpip_if *ifp) {
  16819. if (len > sizeof(s_txbuf[s_txno])) {
  16820. MG_ERROR(("Frame too big, %ld", (long) len));
  16821. len = 0; // Frame is too big
  16822. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  16823. ifp->nerr++;
  16824. MG_ERROR(("No free descriptors"));
  16825. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long) ETH->DMASR);
  16826. len = 0; // All descriptors are busy, fail
  16827. } else {
  16828. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  16829. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  16830. s_txdesc[s_txno][0] = MG_BIT(20) | MG_BIT(28) | MG_BIT(29); // Chain,FS,LS
  16831. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  16832. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  16833. }
  16834. MG_DSB(); // ensure descriptors have been written
  16835. ETH->DMASR = MG_BIT(2) | MG_BIT(5); // Clear any prior TBUS/TUS
  16836. ETH->DMATPDR = 0; // and resume
  16837. return len;
  16838. }
  16839. static bool mg_tcpip_driver_stm32f_up(struct mg_tcpip_if *ifp) {
  16840. struct mg_tcpip_driver_stm32f_data *d =
  16841. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  16842. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  16843. uint8_t speed = MG_PHY_SPEED_10M;
  16844. bool up = false, full_duplex = false;
  16845. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  16846. up = mg_phy_up(&phy, phy_addr, &full_duplex, &speed);
  16847. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  16848. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  16849. // if(link is slow or half) set flags otherwise
  16850. // reg = tmp
  16851. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  16852. if (speed == MG_PHY_SPEED_10M) maccr &= ~MG_BIT(14); // 10M
  16853. if (full_duplex == false) maccr &= ~MG_BIT(11); // Half-duplex
  16854. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  16855. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  16856. maccr & MG_BIT(11) ? "full" : "half"));
  16857. }
  16858. return up;
  16859. }
  16860. #ifdef __riscv
  16861. __attribute__((interrupt())) // For RISCV CH32V307, which share the same MAC
  16862. #endif
  16863. void ETH_IRQHandler(void);
  16864. void ETH_IRQHandler(void) {
  16865. if (ETH->DMASR & MG_BIT(6)) { // Frame received, loop
  16866. ETH->DMASR = MG_BIT(16) | MG_BIT(6); // Clear flag
  16867. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  16868. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  16869. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) ==
  16870. (MG_BIT(8) | MG_BIT(9))) &&
  16871. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  16872. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  16873. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  16874. // ETH->DMASR);
  16875. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  16876. }
  16877. s_rxdesc[s_rxno][0] = MG_BIT(31);
  16878. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  16879. }
  16880. }
  16881. // Cleanup flags
  16882. ETH->DMASR = MG_BIT(16) // NIS, normal interrupt summary
  16883. | MG_BIT(7); // Clear possible RBUS while processing
  16884. ETH->DMARPDR = 0; // and resume RX
  16885. }
  16886. struct mg_tcpip_driver mg_tcpip_driver_stm32f = {
  16887. mg_tcpip_driver_stm32f_init, mg_tcpip_driver_stm32f_tx, NULL,
  16888. mg_tcpip_driver_stm32f_up};
  16889. #endif
  16890. #ifdef MG_ENABLE_LINES
  16891. #line 1 "src/drivers/stm32h.c"
  16892. #endif
  16893. #if MG_ENABLE_TCPIP && (MG_ENABLE_DRIVER_STM32H || MG_ENABLE_DRIVER_MCXN)
  16894. // STM32H: vendor modded single-queue Synopsys v4.2
  16895. // MCXNx4x: dual-queue Synopsys v5.2
  16896. // RT1170 ENET_QOS: quad-queue Synopsys v5.1
  16897. struct synopsys_enet_qos {
  16898. volatile uint32_t MACCR, MACECR, MACPFR, MACWTR, MACHT0R, MACHT1R,
  16899. RESERVED1[14], MACVTR, RESERVED2, MACVHTR, RESERVED3, MACVIR, MACIVIR,
  16900. RESERVED4[2], MACTFCR, RESERVED5[7], MACRFCR, RESERVED6[7], MACISR,
  16901. MACIER, MACRXTXSR, RESERVED7, MACPCSR, MACRWKPFR, RESERVED8[2], MACLCSR,
  16902. MACLTCR, MACLETR, MAC1USTCR, RESERVED9[12], MACVR, MACDR, RESERVED10,
  16903. MACHWF0R, MACHWF1R, MACHWF2R, RESERVED11[54], MACMDIOAR, MACMDIODR,
  16904. RESERVED12[2], MACARPAR, RESERVED13[59], MACA0HR, MACA0LR, MACA1HR,
  16905. MACA1LR, MACA2HR, MACA2LR, MACA3HR, MACA3LR, RESERVED14[248], MMCCR,
  16906. MMCRIR, MMCTIR, MMCRIMR, MMCTIMR, RESERVED15[14], MMCTSCGPR, MMCTMCGPR,
  16907. RESERVED16[5], MMCTPCGR, RESERVED17[10], MMCRCRCEPR, MMCRAEPR,
  16908. RESERVED18[10], MMCRUPGR, RESERVED19[9], MMCTLPIMSTR, MMCTLPITCR,
  16909. MMCRLPIMSTR, MMCRLPITCR, RESERVED20[65], MACL3L4C0R, MACL4A0R,
  16910. RESERVED21[2], MACL3A0R0R, MACL3A1R0R, MACL3A2R0R, MACL3A3R0R,
  16911. RESERVED22[4], MACL3L4C1R, MACL4A1R, RESERVED23[2], MACL3A0R1R,
  16912. MACL3A1R1R, MACL3A2R1R, MACL3A3R1R, RESERVED24[108], MACTSCR, MACSSIR,
  16913. MACSTSR, MACSTNR, MACSTSUR, MACSTNUR, MACTSAR, RESERVED25, MACTSSR,
  16914. RESERVED26[3], MACTTSSNR, MACTTSSSR, RESERVED27[2], MACACR, RESERVED28,
  16915. MACATSNR, MACATSSR, MACTSIACR, MACTSEACR, MACTSICNR, MACTSECNR,
  16916. RESERVED29[4], MACPPSCR, RESERVED30[3], MACPPSTTSR, MACPPSTTNR, MACPPSIR,
  16917. MACPPSWR, RESERVED31[12], MACPOCR, MACSPI0R, MACSPI1R, MACSPI2R, MACLMIR,
  16918. RESERVED32[11], MTLOMR, RESERVED33[7], MTLISR, RESERVED34[55], MTLTQOMR,
  16919. MTLTQUR, MTLTQDR, RESERVED35[8], MTLQICSR, MTLRQOMR, MTLRQMPOCR, MTLRQDR,
  16920. RESERVED36[177], DMAMR, DMASBMR, DMAISR, DMADSR, RESERVED37[60], DMACCR,
  16921. DMACTCR, DMACRCR, RESERVED38[2], DMACTDLAR, RESERVED39, DMACRDLAR,
  16922. DMACTDTPR, RESERVED40, DMACRDTPR, DMACTDRLR, DMACRDRLR, DMACIER,
  16923. DMACRIWTR, DMACSFCSR, RESERVED41, DMACCATDR, RESERVED42, DMACCARDR,
  16924. RESERVED43, DMACCATBR, RESERVED44, DMACCARBR, DMACSR, RESERVED45[2],
  16925. DMACMFCR;
  16926. };
  16927. #undef ETH
  16928. #if MG_ENABLE_DRIVER_STM32H
  16929. #define ETH \
  16930. ((struct synopsys_enet_qos *) (uintptr_t) (0x40000000UL + 0x00020000UL + \
  16931. 0x8000UL))
  16932. #elif MG_ENABLE_DRIVER_MCXN
  16933. #define ETH ((struct synopsys_enet_qos *) (uintptr_t) 0x40100000UL)
  16934. #endif
  16935. #define ETH_PKT_SIZE 1540 // Max frame size
  16936. #define ETH_DESC_CNT 4 // Descriptors count
  16937. #define ETH_DS 4 // Descriptor size (words)
  16938. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  16939. static volatile uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  16940. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  16941. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  16942. static struct mg_tcpip_if *s_ifp; // MIP interface
  16943. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  16944. ETH->MACMDIOAR &= (0xF << 8);
  16945. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 3 << 2;
  16946. ETH->MACMDIOAR |= MG_BIT(0);
  16947. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  16948. return (uint16_t) ETH->MACMDIODR;
  16949. }
  16950. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  16951. ETH->MACMDIODR = val;
  16952. ETH->MACMDIOAR &= (0xF << 8);
  16953. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 1 << 2;
  16954. ETH->MACMDIOAR |= MG_BIT(0);
  16955. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  16956. }
  16957. static bool mg_tcpip_driver_stm32h_init(struct mg_tcpip_if *ifp) {
  16958. struct mg_tcpip_driver_stm32h_data *d =
  16959. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  16960. s_ifp = ifp;
  16961. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  16962. uint8_t phy_conf = d == NULL ? MG_PHY_CLOCKS_MAC : d->phy_conf;
  16963. // Init RX descriptors
  16964. for (int i = 0; i < ETH_DESC_CNT; i++) {
  16965. s_rxdesc[i][0] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  16966. s_rxdesc[i][3] = MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  16967. }
  16968. // Init TX descriptors
  16969. for (int i = 0; i < ETH_DESC_CNT; i++) {
  16970. s_txdesc[i][0] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  16971. }
  16972. ETH->DMAMR |= MG_BIT(0); // Software reset
  16973. for (int i = 0; i < 4; i++)
  16974. (void) 0; // wait at least 4 clocks before reading
  16975. while ((ETH->DMAMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  16976. // Set MDC clock divider. Get user value, else, assume max freq
  16977. int cr = (d == NULL || d->mdc_cr < 0) ? 7 : d->mdc_cr;
  16978. ETH->MACMDIOAR = ((uint32_t) cr & 0xF) << 8;
  16979. // NOTE(scaprile): We do not use timing facilities so the DMA engine does not
  16980. // re-write buffer address
  16981. ETH->DMAMR = 0 << 16; // use interrupt mode 0 (58.8.1) (reset value)
  16982. ETH->DMASBMR |= MG_BIT(12); // AAL NOTE(scaprile): is this actually needed
  16983. ETH->MACIER = 0; // Do not enable additional irq sources (reset value)
  16984. ETH->MACTFCR = MG_BIT(7); // Disable zero-quanta pause
  16985. // ETH->MACPFR = MG_BIT(31); // Receive all
  16986. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  16987. mg_phy_init(&phy, phy_addr, phy_conf);
  16988. ETH->DMACRDLAR =
  16989. (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors start address
  16990. ETH->DMACRDRLR = ETH_DESC_CNT - 1; // ring length
  16991. ETH->DMACRDTPR =
  16992. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT -
  16993. 1]; // last valid descriptor address
  16994. ETH->DMACTDLAR =
  16995. (uint32_t) (uintptr_t) s_txdesc; // TX descriptors start address
  16996. ETH->DMACTDRLR = ETH_DESC_CNT - 1; // ring length
  16997. ETH->DMACTDTPR =
  16998. (uint32_t) (uintptr_t) s_txdesc; // first available descriptor address
  16999. ETH->DMACCR = 0; // DSL = 0 (contiguous descriptor table) (reset value)
  17000. #if !MG_ENABLE_DRIVER_STM32H
  17001. MG_SET_BITS(ETH->DMACTCR, 0x3F << 16, MG_BIT(16));
  17002. MG_SET_BITS(ETH->DMACRCR, 0x3F << 16, MG_BIT(16));
  17003. #endif
  17004. ETH->DMACIER = MG_BIT(6) | MG_BIT(15); // RIE, NIE
  17005. ETH->MACCR = MG_BIT(0) | MG_BIT(1) | MG_BIT(13) | MG_BIT(14) |
  17006. MG_BIT(15); // RE, TE, Duplex, Fast, Reserved
  17007. #if MG_ENABLE_DRIVER_STM32H
  17008. ETH->MTLTQOMR |= MG_BIT(1); // TSF
  17009. ETH->MTLRQOMR |= MG_BIT(5); // RSF
  17010. #else
  17011. ETH->MTLTQOMR |= (7 << 16) | MG_BIT(3) | MG_BIT(1); // 2KB Q0, TSF
  17012. ETH->MTLRQOMR |= (7 << 20) | MG_BIT(5); // 2KB Q, RSF
  17013. MG_SET_BITS(ETH->RESERVED6[3], 3, 2); // Enable RxQ0 (MAC_RXQ_CTRL0)
  17014. #endif
  17015. ETH->DMACTCR |= MG_BIT(0); // ST
  17016. ETH->DMACRCR |= MG_BIT(0); // SR
  17017. // MAC address filtering
  17018. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  17019. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  17020. ((uint32_t) ifp->mac[2] << 16) |
  17021. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  17022. return true;
  17023. }
  17024. static uint32_t s_txno;
  17025. static size_t mg_tcpip_driver_stm32h_tx(const void *buf, size_t len,
  17026. struct mg_tcpip_if *ifp) {
  17027. if (len > sizeof(s_txbuf[s_txno])) {
  17028. MG_ERROR(("Frame too big, %ld", (long) len));
  17029. len = 0; // Frame is too big
  17030. } else if ((s_txdesc[s_txno][3] & MG_BIT(31))) {
  17031. ifp->nerr++;
  17032. MG_ERROR(("No free descriptors: %u %08X %08X %08X", s_txno,
  17033. s_txdesc[s_txno][3], ETH->DMACSR, ETH->DMACTCR));
  17034. for (int i = 0; i < ETH_DESC_CNT; i++) MG_ERROR(("%08X", s_txdesc[i][3]));
  17035. len = 0; // All descriptors are busy, fail
  17036. } else {
  17037. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  17038. s_txdesc[s_txno][2] = (uint32_t) len; // Set data len
  17039. s_txdesc[s_txno][3] = MG_BIT(28) | MG_BIT(29); // FD, LD
  17040. s_txdesc[s_txno][3] |= MG_BIT(31); // Set OWN bit - let DMA take over
  17041. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  17042. }
  17043. ETH->DMACSR |= MG_BIT(2) | MG_BIT(1); // Clear any prior TBU, TPS
  17044. ETH->DMACTDTPR = (uint32_t) (uintptr_t) &s_txdesc[s_txno]; // and resume
  17045. return len;
  17046. (void) ifp;
  17047. }
  17048. static bool mg_tcpip_driver_stm32h_up(struct mg_tcpip_if *ifp) {
  17049. struct mg_tcpip_driver_stm32h_data *d =
  17050. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  17051. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  17052. uint8_t speed = MG_PHY_SPEED_10M;
  17053. bool up = false, full_duplex = false;
  17054. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  17055. up = mg_phy_up(&phy, phy_addr, &full_duplex, &speed);
  17056. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  17057. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  17058. // if(link is slow or half) set flags otherwise
  17059. // reg = tmp
  17060. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(13); // 100M, Full-duplex
  17061. if (speed == MG_PHY_SPEED_10M) maccr &= ~MG_BIT(14); // 10M
  17062. if (full_duplex == false) maccr &= ~MG_BIT(13); // Half-duplex
  17063. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  17064. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  17065. maccr & MG_BIT(13) ? "full" : "half"));
  17066. }
  17067. return up;
  17068. }
  17069. static uint32_t s_rxno;
  17070. #if MG_ENABLE_DRIVER_MCXN
  17071. void ETHERNET_IRQHandler(void);
  17072. void ETHERNET_IRQHandler(void) {
  17073. #else
  17074. void ETH_IRQHandler(void);
  17075. void ETH_IRQHandler(void) {
  17076. #endif
  17077. if (ETH->DMACSR & MG_BIT(6)) { // Frame received, loop
  17078. ETH->DMACSR = MG_BIT(15) | MG_BIT(6); // Clear flag
  17079. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  17080. if (s_rxdesc[s_rxno][3] & MG_BIT(31)) break; // exit when done
  17081. if (((s_rxdesc[s_rxno][3] & (MG_BIT(28) | MG_BIT(29))) ==
  17082. (MG_BIT(28) | MG_BIT(29))) &&
  17083. !(s_rxdesc[s_rxno][3] & MG_BIT(15))) { // skip partial/errored frames
  17084. uint32_t len = s_rxdesc[s_rxno][3] & (MG_BIT(15) - 1);
  17085. // MG_DEBUG(("%lx %lu %lx %08lx", s_rxno, len, s_rxdesc[s_rxno][3],
  17086. // ETH->DMACSR));
  17087. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  17088. }
  17089. s_rxdesc[s_rxno][3] =
  17090. MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  17091. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  17092. }
  17093. }
  17094. ETH->DMACSR =
  17095. MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing
  17096. ETH->DMACRDTPR =
  17097. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT - 1]; // and resume RX
  17098. }
  17099. struct mg_tcpip_driver mg_tcpip_driver_stm32h = {
  17100. mg_tcpip_driver_stm32h_init, mg_tcpip_driver_stm32h_tx, NULL,
  17101. mg_tcpip_driver_stm32h_up};
  17102. #endif
  17103. #ifdef MG_ENABLE_LINES
  17104. #line 1 "src/drivers/tm4c.c"
  17105. #endif
  17106. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
  17107. struct tm4c_emac {
  17108. volatile uint32_t EMACCFG, EMACFRAMEFLTR, EMACHASHTBLH, EMACHASHTBLL,
  17109. EMACMIIADDR, EMACMIIDATA, EMACFLOWCTL, EMACVLANTG, RESERVED0, EMACSTATUS,
  17110. EMACRWUFF, EMACPMTCTLSTAT, RESERVED1[2], EMACRIS, EMACIM, EMACADDR0H,
  17111. EMACADDR0L, EMACADDR1H, EMACADDR1L, EMACADDR2H, EMACADDR2L, EMACADDR3H,
  17112. EMACADDR3L, RESERVED2[31], EMACWDOGTO, RESERVED3[8], EMACMMCCTRL,
  17113. EMACMMCRXRIS, EMACMMCTXRIS, EMACMMCRXIM, EMACMMCTXIM, RESERVED4,
  17114. EMACTXCNTGB, RESERVED5[12], EMACTXCNTSCOL, EMACTXCNTMCOL, RESERVED6[4],
  17115. EMACTXOCTCNTG, RESERVED7[6], EMACRXCNTGB, RESERVED8[4], EMACRXCNTCRCERR,
  17116. EMACRXCNTALGNERR, RESERVED9[10], EMACRXCNTGUNI, RESERVED10[239],
  17117. EMACVLNINCREP, EMACVLANHASH, RESERVED11[93], EMACTIMSTCTRL, EMACSUBSECINC,
  17118. EMACTIMSEC, EMACTIMNANO, EMACTIMSECU, EMACTIMNANOU, EMACTIMADD,
  17119. EMACTARGSEC, EMACTARGNANO, EMACHWORDSEC, EMACTIMSTAT, EMACPPSCTRL,
  17120. RESERVED12[12], EMACPPS0INTVL, EMACPPS0WIDTH, RESERVED13[294],
  17121. EMACDMABUSMOD, EMACTXPOLLD, EMACRXPOLLD, EMACRXDLADDR, EMACTXDLADDR,
  17122. EMACDMARIS, EMACDMAOPMODE, EMACDMAIM, EMACMFBOC, EMACRXINTWDT,
  17123. RESERVED14[8], EMACHOSTXDESC, EMACHOSRXDESC, EMACHOSTXBA, EMACHOSRXBA,
  17124. RESERVED15[218], EMACPP, EMACPC, EMACCC, RESERVED16, EMACEPHYRIS,
  17125. EMACEPHYIM, EMACEPHYIMSC;
  17126. };
  17127. #undef EMAC
  17128. #define EMAC ((struct tm4c_emac *) (uintptr_t) 0x400EC000)
  17129. #define ETH_PKT_SIZE 1540 // Max frame size
  17130. #define ETH_DESC_CNT 4 // Descriptors count
  17131. #define ETH_DS 4 // Descriptor size (words)
  17132. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  17133. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  17134. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  17135. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  17136. static struct mg_tcpip_if *s_ifp; // MIP interface
  17137. enum {
  17138. EPHY_ADDR = 0,
  17139. EPHYBMCR = 0,
  17140. EPHYBMSR = 1,
  17141. EPHYSTS = 16
  17142. }; // PHY constants
  17143. static inline void tm4cspin(volatile uint32_t count) {
  17144. while (count--) (void) 0;
  17145. }
  17146. static uint32_t emac_read_phy(uint8_t addr, uint8_t reg) {
  17147. EMAC->EMACMIIADDR &= (0xf << 2);
  17148. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  17149. EMAC->EMACMIIADDR |= MG_BIT(0);
  17150. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  17151. return EMAC->EMACMIIDATA;
  17152. }
  17153. static void emac_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  17154. EMAC->EMACMIIDATA = val;
  17155. EMAC->EMACMIIADDR &= (0xf << 2);
  17156. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  17157. EMAC->EMACMIIADDR |= MG_BIT(0);
  17158. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  17159. }
  17160. static uint32_t get_sysclk(void) {
  17161. struct sysctl {
  17162. volatile uint32_t DONTCARE0[44], RSCLKCFG, DONTCARE1[43], PLLFREQ0,
  17163. PLLFREQ1;
  17164. } *sysctl = (struct sysctl *) 0x400FE000;
  17165. uint32_t clk = 0, piosc = 16000000 /* 16 MHz */, mosc = 25000000 /* 25MHz */;
  17166. if (sysctl->RSCLKCFG & (1 << 28)) { // USEPLL
  17167. uint32_t fin, vco, mdiv, n, q, psysdiv;
  17168. uint32_t pllsrc = (sysctl->RSCLKCFG & (0xf << 24)) >> 24;
  17169. if (pllsrc == 0) {
  17170. clk = piosc;
  17171. } else if (pllsrc == 3) {
  17172. clk = mosc;
  17173. } else {
  17174. MG_ERROR(("Unsupported clock source"));
  17175. }
  17176. q = (sysctl->PLLFREQ1 & (0x1f << 8)) >> 8;
  17177. n = (sysctl->PLLFREQ1 & (0x1f << 0)) >> 0;
  17178. fin = clk / ((q + 1) * (n + 1));
  17179. mdiv = (sysctl->PLLFREQ0 & (0x3ff << 0)) >>
  17180. 0; // mint + (mfrac / 1024); MFRAC not supported
  17181. psysdiv = (sysctl->RSCLKCFG & (0x3f << 0)) >> 0;
  17182. vco = (uint32_t) ((uint64_t) fin * mdiv);
  17183. return vco / (psysdiv + 1);
  17184. }
  17185. uint32_t oscsrc = (sysctl->RSCLKCFG & (0xf << 20)) >> 20;
  17186. if (oscsrc == 0) {
  17187. clk = piosc;
  17188. } else if (oscsrc == 3) {
  17189. clk = mosc;
  17190. } else {
  17191. MG_ERROR(("Unsupported clock source"));
  17192. }
  17193. uint32_t osysdiv = (sysctl->RSCLKCFG & (0xf << 16)) >> 16;
  17194. return clk / (osysdiv + 1);
  17195. }
  17196. // Guess CR from SYSCLK. MDC clock is generated from SYSCLK (AHB); as per
  17197. // 802.3, it must not exceed 2.5MHz (also 20.4.2.6) As the AHB clock can be
  17198. // derived from the PIOSC (internal RC), and it can go above specs, the
  17199. // datasheets specify a range of frequencies and activate one of a series of
  17200. // dividers to keep the MDC clock safely below 2.5MHz. We guess a divider
  17201. // setting based on SYSCLK with a +5% drift. If the user uses a different clock
  17202. // from our defaults, needs to set the macros on top Valid for TM4C129x (20.7)
  17203. // (4.5% worst case drift)
  17204. // The PHY receives the main oscillator (MOSC) (20.3.1)
  17205. static int guess_mdc_cr(void) {
  17206. uint8_t crs[] = {2, 3, 0, 1}; // EMAC->MACMIIAR::CR values
  17207. uint8_t div[] = {16, 26, 42, 62}; // Respective HCLK dividers
  17208. uint32_t sysclk = get_sysclk(); // Guess system SYSCLK
  17209. int result = -1; // Invalid CR value
  17210. if (sysclk < 25000000) {
  17211. MG_ERROR(("SYSCLK too low"));
  17212. } else {
  17213. for (int i = 0; i < 4; i++) {
  17214. if (sysclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  17215. result = crs[i];
  17216. break;
  17217. }
  17218. }
  17219. if (result < 0) MG_ERROR(("SYSCLK too high"));
  17220. }
  17221. MG_DEBUG(("SYSCLK: %u, CR: %d", sysclk, result));
  17222. return result;
  17223. }
  17224. static bool mg_tcpip_driver_tm4c_init(struct mg_tcpip_if *ifp) {
  17225. struct mg_tcpip_driver_tm4c_data *d =
  17226. (struct mg_tcpip_driver_tm4c_data *) ifp->driver_data;
  17227. s_ifp = ifp;
  17228. // Init RX descriptors
  17229. for (int i = 0; i < ETH_DESC_CNT; i++) {
  17230. s_rxdesc[i][0] = MG_BIT(31); // Own
  17231. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  17232. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  17233. s_rxdesc[i][3] =
  17234. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  17235. // MG_DEBUG(("%d %p", i, s_rxdesc[i]));
  17236. }
  17237. // Init TX descriptors
  17238. for (int i = 0; i < ETH_DESC_CNT; i++) {
  17239. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  17240. s_txdesc[i][3] =
  17241. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  17242. }
  17243. EMAC->EMACDMABUSMOD |= MG_BIT(0); // Software reset
  17244. while ((EMAC->EMACDMABUSMOD & MG_BIT(0)) != 0) tm4cspin(1); // Wait until done
  17245. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  17246. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  17247. EMAC->EMACMIIADDR = ((uint32_t) cr & 0xf) << 2;
  17248. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  17249. // hardware checksum. Therefore, descriptor size is 4, not 8
  17250. // EMAC->EMACDMABUSMOD = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) | MG_BIT(25);
  17251. EMAC->EMACIM = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  17252. EMAC->EMACFLOWCTL = MG_BIT(7); // Disable zero-quanta pause
  17253. // EMAC->EMACFRAMEFLTR = MG_BIT(31); // Receive all
  17254. // EMAC->EMACPC defaults to internal PHY (EPHY) in MMI mode
  17255. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(15)); // Reset internal PHY (EPHY)
  17256. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(12)); // Set autonegotiation
  17257. EMAC->EMACRXDLADDR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  17258. EMAC->EMACTXDLADDR = (uint32_t) (uintptr_t) s_txdesc; // TX descriptors
  17259. EMAC->EMACDMAIM = MG_BIT(6) | MG_BIT(16); // RIE, NIE
  17260. EMAC->EMACCFG = MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  17261. EMAC->EMACDMAOPMODE =
  17262. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  17263. EMAC->EMACADDR0H = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  17264. EMAC->EMACADDR0L = (uint32_t) (ifp->mac[3] << 24) |
  17265. ((uint32_t) ifp->mac[2] << 16) |
  17266. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  17267. // NOTE(scaprile) There are 3 additional slots for filtering, disabled by
  17268. // default. This also applies to the STM32 driver (at least for F7)
  17269. return true;
  17270. }
  17271. static uint32_t s_txno;
  17272. static size_t mg_tcpip_driver_tm4c_tx(const void *buf, size_t len,
  17273. struct mg_tcpip_if *ifp) {
  17274. if (len > sizeof(s_txbuf[s_txno])) {
  17275. MG_ERROR(("Frame too big, %ld", (long) len));
  17276. len = 0; // fail
  17277. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  17278. ifp->nerr++;
  17279. MG_ERROR(("No descriptors available"));
  17280. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long)
  17281. // EMAC->EMACDMARIS);
  17282. len = 0; // fail
  17283. } else {
  17284. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  17285. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  17286. s_txdesc[s_txno][0] =
  17287. MG_BIT(20) | MG_BIT(28) | MG_BIT(29) | MG_BIT(30); // Chain,FS,LS,IC
  17288. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  17289. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  17290. }
  17291. EMAC->EMACDMARIS = MG_BIT(2) | MG_BIT(5); // Clear any prior TU/UNF
  17292. EMAC->EMACTXPOLLD = 0; // and resume
  17293. return len;
  17294. (void) ifp;
  17295. }
  17296. static bool mg_tcpip_driver_tm4c_up(struct mg_tcpip_if *ifp) {
  17297. uint32_t bmsr = emac_read_phy(EPHY_ADDR, EPHYBMSR);
  17298. bool up = (bmsr & MG_BIT(2)) ? 1 : 0;
  17299. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  17300. uint32_t sts = emac_read_phy(EPHY_ADDR, EPHYSTS);
  17301. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  17302. // if(link is slow or half) set flags otherwise
  17303. // reg = tmp
  17304. uint32_t emaccfg = EMAC->EMACCFG | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  17305. if (sts & MG_BIT(1)) emaccfg &= ~MG_BIT(14); // 10M
  17306. if ((sts & MG_BIT(2)) == 0) emaccfg &= ~MG_BIT(11); // Half-duplex
  17307. EMAC->EMACCFG = emaccfg; // IRQ handler does not fiddle with this register
  17308. MG_DEBUG(("Link is %uM %s-duplex", emaccfg & MG_BIT(14) ? 100 : 10,
  17309. emaccfg & MG_BIT(11) ? "full" : "half"));
  17310. }
  17311. return up;
  17312. }
  17313. void EMAC0_IRQHandler(void);
  17314. static uint32_t s_rxno;
  17315. void EMAC0_IRQHandler(void) {
  17316. if (EMAC->EMACDMARIS & MG_BIT(6)) { // Frame received, loop
  17317. EMAC->EMACDMARIS = MG_BIT(16) | MG_BIT(6); // Clear flag
  17318. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  17319. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  17320. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) == (MG_BIT(8) | MG_BIT(9))) &&
  17321. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  17322. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  17323. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  17324. // EMAC->EMACDMARIS);
  17325. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  17326. }
  17327. s_rxdesc[s_rxno][0] = MG_BIT(31);
  17328. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  17329. }
  17330. }
  17331. EMAC->EMACDMARIS = MG_BIT(7); // Clear possible RU while processing
  17332. EMAC->EMACRXPOLLD = 0; // and resume RX
  17333. }
  17334. struct mg_tcpip_driver mg_tcpip_driver_tm4c = {mg_tcpip_driver_tm4c_init,
  17335. mg_tcpip_driver_tm4c_tx, NULL,
  17336. mg_tcpip_driver_tm4c_up};
  17337. #endif
  17338. #ifdef MG_ENABLE_LINES
  17339. #line 1 "src/drivers/tms570.c"
  17340. #endif
  17341. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TMS570) && MG_ENABLE_DRIVER_TMS570
  17342. struct tms570_emac_ctrl {
  17343. volatile uint32_t REVID, SOFTRESET, RESERVED1[1], INTCONTROL, C0RXTHRESHEN,
  17344. C0RXEN, C0TXEN, C0MISCEN, RESERVED2[8],
  17345. C0RXTHRESHSTAT, C0RXSTAT, C0TXSTAT, C0MISCSTAT,
  17346. RESERVED3[8],
  17347. C0RXIMAX, C0TXIMAX;
  17348. };
  17349. struct tms570_emac {
  17350. volatile uint32_t TXREVID, TXCONTROL, TXTEARDOWN, RESERVED1[1], RXREVID,
  17351. RXCONTROL, RXTEARDOWN, RESERVED2[25], TXINTSTATRAW,TXINTSTATMASKED,
  17352. TXINTMASKSET, TXINTMASKCLEAR, MACINVECTOR, MACEOIVECTOR, RESERVED8[2], RXINTSTATRAW,
  17353. RXINTSTATMASKED, RXINTMASKSET, RXINTMASKCLEAR, MACINTSTATRAW, MACINTSTATMASKED,
  17354. MACINTMASKSET, MACINTMASKCLEAR, RESERVED3[16], RXMBPENABLE, RXUNICASTSET,
  17355. RXUNICASTCLEAR, RXMAXLEN, RXBUFFEROFFSET, RXFILTERLOWTHRESH, RESERVED9[2], RXFLOWTHRESH[8],
  17356. RXFREEBUFFER[8], MACCONTROL, MACSTATUS, EMCONTROL, FIFOCONTROL, MACCONFIG,
  17357. SOFTRESET, RESERVED4[22], MACSRCADDRLO, MACSRCADDRHI, MACHASH1, MACHASH2,
  17358. BOFFTEST, TPACETEST, RXPAUSE, TXPAUSE, RESERVED5[4], RXGOODFRAMES, RXBCASTFRAMES,
  17359. RXMCASTFRAMES, RXPAUSEFRAMES, RXCRCERRORS, RXALIGNCODEERRORS, RXOVERSIZED,
  17360. RXJABBER, RXUNDERSIZED, RXFRAGMENTS, RXFILTERED, RXQOSFILTERED, RXOCTETS,
  17361. TXGOODFRAMES, TXBCASTFRAMES, TXMCASTFRAMES, TXPAUSEFRAMES, TXDEFERRED,
  17362. TXCOLLISION, TXSINGLECOLL, TXMULTICOLL, TXEXCESSIVECOLL, TXLATECOLL,
  17363. TXUNDERRUN, TXCARRIERSENSE, TXOCTETS, FRAME64, FRAME65T127, FRAME128T255,
  17364. FRAME256T511, FRAME512T1023, FRAME1024TUP, NETOCTETS, RXSOFOVERRUNS,
  17365. RXMOFOVERRUNS, RXDMAOVERRUNS, RESERVED6[156], MACADDRLO, MACADDRHI,
  17366. MACINDEX, RESERVED7[61], TXHDP[8], RXHDP[8], TXCP[8], RXCP[8];
  17367. };
  17368. struct tms570_mdio {
  17369. volatile uint32_t REVID, CONTROL, ALIVE, LINK, LINKINTRAW, LINKINTMASKED,
  17370. RESERVED1[2], USERINTRAW, USERINTMASKED, USERINTMASKSET, USERINTMASKCLEAR,
  17371. RESERVED2[20], USERACCESS0, USERPHYSEL0, USERACCESS1, USERPHYSEL1;
  17372. };
  17373. #define SWAP32(x) ( (((x) & 0x000000FF) << 24) | \
  17374. (((x) & 0x0000FF00) << 8) | \
  17375. (((x) & 0x00FF0000) >> 8) | \
  17376. (((x) & 0xFF000000) >> 24) )
  17377. #undef EMAC
  17378. #undef EMAC_CTRL
  17379. #undef MDIO
  17380. #define EMAC ((struct tms570_emac *) (uintptr_t) 0xFCF78000)
  17381. #define EMAC_CTRL ((struct tms570_emac_ctrl *) (uintptr_t) 0xFCF78800)
  17382. #define MDIO ((struct tms570_mdio *) (uintptr_t) 0xFCF78900)
  17383. #define ETH_PKT_SIZE 1540 // Max frame size
  17384. #define ETH_DESC_CNT 4 // Descriptors count
  17385. #define ETH_DS 4 // Descriptor size (words)
  17386. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]
  17387. __attribute__((section(".ETH_CPPI"), aligned(4))); // TX descriptors
  17388. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]
  17389. __attribute__((section(".ETH_CPPI"), aligned(4))); // RX descriptors
  17390. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]
  17391. __attribute__((aligned(4))); // RX ethernet buffers
  17392. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]
  17393. __attribute__((aligned(4))); // TX ethernet buffers
  17394. static struct mg_tcpip_if *s_ifp; // MIP interface
  17395. static uint16_t emac_read_phy(uint8_t addr, uint8_t reg) {
  17396. while(MDIO->USERACCESS0 & MG_BIT(31)) (void) 0;
  17397. MDIO->USERACCESS0 = MG_BIT(31) | ((reg & 0x1f) << 21) |
  17398. ((addr & 0x1f) << 16);
  17399. while(MDIO->USERACCESS0 & MG_BIT(31)) (void) 0;
  17400. return MDIO->USERACCESS0 & 0xffff;
  17401. }
  17402. static void emac_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  17403. while(MDIO->USERACCESS0 & MG_BIT(31)) (void) 0;
  17404. MDIO->USERACCESS0 = MG_BIT(31) | MG_BIT(30) | ((reg & 0x1f) << 21) |
  17405. ((addr & 0x1f) << 16) | (val & 0xffff);
  17406. while(MDIO->USERACCESS0 & MG_BIT(31)) (void) 0;
  17407. }
  17408. static bool mg_tcpip_driver_tms570_init(struct mg_tcpip_if *ifp) {
  17409. struct mg_tcpip_driver_tms570_data *d =
  17410. (struct mg_tcpip_driver_tms570_data *) ifp->driver_data;
  17411. s_ifp = ifp;
  17412. EMAC_CTRL->SOFTRESET = MG_BIT(0); // Reset the EMAC Control Module
  17413. while(EMAC_CTRL->SOFTRESET & MG_BIT(0)) (void) 0; // wait
  17414. EMAC->SOFTRESET = MG_BIT(0); // Reset the EMAC Module
  17415. while(EMAC->SOFTRESET & MG_BIT(0)) (void) 0;
  17416. EMAC->MACCONTROL = 0;
  17417. EMAC->RXCONTROL = 0;
  17418. EMAC->TXCONTROL = 0;
  17419. // Initialize all the header descriptor pointer registers
  17420. uint32_t i;
  17421. for(i = 0; i < ETH_DESC_CNT; i++) {
  17422. EMAC->RXHDP[i] = 0;
  17423. EMAC->TXHDP[i] = 0;
  17424. EMAC->RXCP[i] = 0;
  17425. EMAC->TXCP[i] = 0;
  17426. ///EMAC->RXFREEBUFFER[i] = 0xff;
  17427. }
  17428. // Clear the interrupt enable for all the channels
  17429. EMAC->TXINTMASKCLEAR = 0xff;
  17430. EMAC->RXINTMASKCLEAR = 0xff;
  17431. EMAC->MACHASH1 = 0;
  17432. EMAC->MACHASH2 = 0;
  17433. EMAC->RXBUFFEROFFSET = 0;
  17434. EMAC->RXUNICASTCLEAR = 0xff;
  17435. EMAC->RXUNICASTSET = 0;
  17436. EMAC->RXMBPENABLE = 0;
  17437. // init MDIO
  17438. // MDIO_CLK frequency = VCLK3/(CLKDIV + 1). (MDIO must be between 1.0 - 2.5Mhz)
  17439. uint32_t clkdiv = 75; // VCLK is configured to 75Mhz
  17440. // CLKDIV, ENABLE, PREAMBLE, FAULTENB
  17441. MDIO->CONTROL = (clkdiv - 1) | MG_BIT(30) | MG_BIT(20) | MG_BIT(18);
  17442. volatile int delay = 0xfff;
  17443. while (delay-- != 0) (void) 0;
  17444. struct mg_phy phy = {emac_read_phy, emac_write_phy};
  17445. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  17446. // set the mac address
  17447. EMAC->MACSRCADDRHI = ifp->mac[0] | (ifp->mac[1] << 8) | (ifp->mac[2] << 16) |
  17448. (ifp->mac[3] << 24);
  17449. EMAC->MACSRCADDRLO = ifp->mac[4] | (ifp->mac[5] << 8);
  17450. uint32_t channel;
  17451. for (channel = 0; channel < 8; channel++) {
  17452. EMAC->MACINDEX = channel;
  17453. EMAC->MACADDRHI = ifp->mac[0] | (ifp->mac[1] << 8) | (ifp->mac[2] << 16) |
  17454. (ifp->mac[3] << 24);
  17455. EMAC->MACADDRLO = ifp->mac[4] | (ifp->mac[5] << 8) | MG_BIT(20) |
  17456. MG_BIT(19) | (channel << 16);
  17457. }
  17458. EMAC->RXUNICASTSET = 1; // accept unicast frames;
  17459. EMAC->RXMBPENABLE = MG_BIT(30) | MG_BIT(13); // CRC, broadcast;
  17460. // Initialize the descriptors
  17461. for (i = 0; i < ETH_DESC_CNT; i++) {
  17462. if (i < ETH_DESC_CNT - 1) {
  17463. s_txdesc[i][0] = 0;
  17464. s_rxdesc[i][0] = SWAP32(((uint32_t) &s_rxdesc[i + 1][0]));
  17465. }
  17466. s_txdesc[i][1] = SWAP32(((uint32_t) s_txbuf[i]));
  17467. s_rxdesc[i][1] = SWAP32(((uint32_t) s_rxbuf[i]));
  17468. s_txdesc[i][2] = 0;
  17469. s_rxdesc[i][2] = SWAP32(ETH_PKT_SIZE);
  17470. s_txdesc[i][3] = 0;
  17471. s_rxdesc[i][3] = SWAP32(MG_BIT(29)); // OWN
  17472. }
  17473. s_txdesc[ETH_DESC_CNT - 1][0] = 0;
  17474. s_rxdesc[ETH_DESC_CNT - 1][0] = 0;
  17475. EMAC->MACCONTROL = MG_BIT(5) | MG_BIT(0); // Enable MII, Full-duplex
  17476. //EMAC->TXINTMASKSET = 1; // Enable TX interrupt
  17477. EMAC->RXINTMASKSET = 1; // Enable RX interrupt
  17478. //EMAC_CTRL->C0TXEN = 1; // TX completion interrupt
  17479. EMAC_CTRL->C0RXEN = 1; // RX completion interrupt
  17480. EMAC->TXCONTROL = 1; // TXEN
  17481. EMAC->RXCONTROL = 1; // RXEN
  17482. EMAC->RXHDP[0] = (uint32_t) &s_rxdesc[0][0];
  17483. return true;
  17484. }
  17485. static uint32_t s_txno;
  17486. static size_t mg_tcpip_driver_tms570_tx(const void *buf, size_t len,
  17487. struct mg_tcpip_if *ifp) {
  17488. if (len > sizeof(s_txbuf[s_txno])) {
  17489. MG_ERROR(("Frame too big, %ld", (long) len));
  17490. len = 0; // fail
  17491. } else if ((s_txdesc[s_txno][3] & SWAP32(MG_BIT(29)))) {
  17492. ifp->nerr++;
  17493. MG_ERROR(("No descriptors available"));
  17494. len = 0; // fail
  17495. } else {
  17496. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  17497. if (len < 128) len = 128;
  17498. s_txdesc[s_txno][2] = SWAP32((uint32_t) len); // Set data len
  17499. s_txdesc[s_txno][3] =
  17500. SWAP32(MG_BIT(31) | MG_BIT(30) | MG_BIT(29) | len); // SOP, EOP, OWN, length
  17501. while(EMAC->TXHDP[0] != 0) (void) 0;
  17502. EMAC->TXHDP[0] = (uint32_t) &s_txdesc[s_txno][0];
  17503. if(++s_txno == ETH_DESC_CNT) {
  17504. s_txno = 0;
  17505. }
  17506. }
  17507. return len;
  17508. (void) ifp;
  17509. }
  17510. static bool mg_tcpip_driver_tms570_up(struct mg_tcpip_if *ifp) {
  17511. struct mg_tcpip_driver_tms570_data *d =
  17512. (struct mg_tcpip_driver_tms570_data *) ifp->driver_data;
  17513. uint8_t speed = MG_PHY_SPEED_10M;
  17514. bool up = false, full_duplex = false;
  17515. struct mg_phy phy = {emac_read_phy, emac_write_phy};
  17516. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  17517. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) {
  17518. // link state just went up
  17519. MG_DEBUG(("Link is %uM %s-duplex", speed == MG_PHY_SPEED_10M ? 10 : 100,
  17520. full_duplex ? "full" : "half"));
  17521. }
  17522. return up;
  17523. }
  17524. #pragma CODE_STATE(EMAC_TX_IRQHandler, 32)
  17525. #pragma INTERRUPT(EMAC_TX_IRQHandler, IRQ)
  17526. void EMAC_TX_IRQHandler(void) {
  17527. uint32_t status = EMAC_CTRL->C0TXSTAT;
  17528. if (status & 1) { // interrupt caused on channel 0
  17529. while(s_txdesc[s_txno][3] & SWAP32(MG_BIT(29))) (void) 0;
  17530. EMAC->TXCP[0] = (uint32_t) &s_txdesc[s_txno][0];
  17531. }
  17532. //Write the DMA end of interrupt vector
  17533. EMAC->MACEOIVECTOR = 2;
  17534. }
  17535. static uint32_t s_rxno;
  17536. #pragma CODE_STATE(EMAC_RX_IRQHandler, 32)
  17537. #pragma INTERRUPT(EMAC_RX_IRQHandler, IRQ)
  17538. void EMAC_RX_IRQHandler(void) {
  17539. uint32_t status = EMAC_CTRL->C0RXSTAT;
  17540. if (status & 1) { // Frame received, loop
  17541. uint32_t i;
  17542. //MG_INFO(("RX interrupt"));
  17543. for (i = 0; i < 10; i++) { // read as they arrive but not forever
  17544. if ((s_rxdesc[s_rxno][3] & SWAP32(MG_BIT(29))) == 0) {
  17545. uint32_t len = SWAP32(s_rxdesc[s_rxno][3]) & 0xffff;
  17546. //MG_INFO(("recv len: %d", len));
  17547. //mg_hexdump(s_rxbuf[s_rxno], len);
  17548. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  17549. uint32_t flags = s_rxdesc[s_rxno][3];
  17550. s_rxdesc[s_rxno][3] = SWAP32(MG_BIT(29));
  17551. s_rxdesc[s_rxno][2] = SWAP32(ETH_PKT_SIZE);
  17552. EMAC->RXCP[0] = (uint32_t) &s_rxdesc[s_rxno][0];
  17553. if (flags & SWAP32(MG_BIT(28))) {
  17554. //MG_INFO(("EOQ detected"));
  17555. EMAC->RXHDP[0] = (uint32_t) &s_rxdesc[0][0];
  17556. }
  17557. }
  17558. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  17559. }
  17560. }
  17561. //Write the DMA end of interrupt vector
  17562. EMAC->MACEOIVECTOR = 1;
  17563. }
  17564. struct mg_tcpip_driver mg_tcpip_driver_tms570 = {mg_tcpip_driver_tms570_init,
  17565. mg_tcpip_driver_tms570_tx, NULL,
  17566. mg_tcpip_driver_tms570_up};
  17567. #endif
  17568. #ifdef MG_ENABLE_LINES
  17569. #line 1 "src/drivers/w5100.c"
  17570. #endif
  17571. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5100) && MG_ENABLE_DRIVER_W5100
  17572. static void w5100_txn(struct mg_tcpip_spi *s, uint16_t addr,
  17573. bool wr, void *buf, size_t len) {
  17574. size_t i;
  17575. uint8_t *p = (uint8_t *) buf;
  17576. uint8_t control = wr ? 0xF0 : 0x0F;
  17577. uint8_t cmd[] = {control, (uint8_t) (addr >> 8), (uint8_t) (addr & 255)};
  17578. s->begin(s->spi);
  17579. for (i = 0; i < sizeof(cmd); i++) s->txn(s->spi, cmd[i]);
  17580. for (i = 0; i < len; i++) {
  17581. uint8_t r = s->txn(s->spi, p[i]);
  17582. if (!wr) p[i] = r;
  17583. }
  17584. s->end(s->spi);
  17585. }
  17586. // clang-format off
  17587. static void w5100_wn(struct mg_tcpip_spi *s, uint16_t addr, void *buf, size_t len) { w5100_txn(s, addr, true, buf, len); }
  17588. static void w5100_w1(struct mg_tcpip_spi *s, uint16_t addr, uint8_t val) { w5100_wn(s, addr, &val, 1); }
  17589. static void w5100_w2(struct mg_tcpip_spi *s, uint16_t addr, uint16_t val) { uint8_t buf[2] = {(uint8_t) (val >> 8), (uint8_t) (val & 255)}; w5100_wn(s, addr, buf, sizeof(buf)); }
  17590. static void w5100_rn(struct mg_tcpip_spi *s, uint16_t addr, void *buf, size_t len) { w5100_txn(s, addr, false, buf, len); }
  17591. static uint8_t w5100_r1(struct mg_tcpip_spi *s, uint16_t addr) { uint8_t r = 0; w5100_rn(s, addr, &r, 1); return r; }
  17592. static uint16_t w5100_r2(struct mg_tcpip_spi *s, uint16_t addr) { uint8_t buf[2] = {0, 0}; w5100_rn(s, addr, buf, sizeof(buf)); return (uint16_t) ((buf[0] << 8) | buf[1]); }
  17593. // clang-format on
  17594. static size_t w5100_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  17595. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  17596. uint16_t r = 0, n = 0, len = (uint16_t) buflen, n2; // Read recv len
  17597. while ((n2 = w5100_r2(s, 0x426)) > n) n = n2; // Until it is stable
  17598. if (n > 0) {
  17599. uint16_t ptr = w5100_r2(s, 0x428); // Get read pointer
  17600. if (n <= len + 2 && n > 1) {
  17601. r = (uint16_t) (n - 2);
  17602. }
  17603. uint16_t rxbuf_size = (1 << (w5100_r1(s, 0x1a) & 3)) * 1024;
  17604. uint16_t rxbuf_addr = 0x6000;
  17605. uint16_t ptr_ofs = (ptr + 2) & (rxbuf_size - 1);
  17606. if (ptr_ofs + r < rxbuf_size) {
  17607. w5100_rn(s, rxbuf_addr + ptr_ofs, buf, r);
  17608. } else {
  17609. uint16_t remaining_len = rxbuf_size - ptr_ofs;
  17610. w5100_rn(s, rxbuf_addr + ptr_ofs, buf, remaining_len);
  17611. w5100_rn(s, rxbuf_addr, buf + remaining_len, n - remaining_len);
  17612. }
  17613. w5100_w2(s, 0x428, (uint16_t) (ptr + n));
  17614. w5100_w1(s, 0x401, 0x40); // Sock0 CR -> RECV
  17615. }
  17616. return r;
  17617. }
  17618. static size_t w5100_tx(const void *buf, size_t buflen,
  17619. struct mg_tcpip_if *ifp) {
  17620. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  17621. uint16_t i, n = 0, ptr = 0, len = (uint16_t) buflen;
  17622. while (n < len) n = w5100_r2(s, 0x420); // Wait for space
  17623. ptr = w5100_r2(s, 0x424); // Get write pointer
  17624. uint16_t txbuf_size = (1 << (w5100_r1(s, 0x1b) & 3)) * 1024;
  17625. uint16_t ptr_ofs = ptr & (txbuf_size - 1);
  17626. uint16_t txbuf_addr = 0x4000;
  17627. if (ptr_ofs + len > txbuf_size) {
  17628. uint16_t size = txbuf_size - ptr_ofs;
  17629. w5100_wn(s, txbuf_addr + ptr_ofs, (char*) buf, size);
  17630. w5100_wn(s, txbuf_addr, (char*) buf + size, len - size);
  17631. } else {
  17632. w5100_wn(s, txbuf_addr + ptr_ofs, (char*) buf, len);
  17633. }
  17634. w5100_w2(s, 0x424, (uint16_t) (ptr + len)); // Advance write pointer
  17635. w5100_w1(s, 0x401, 0x20); // Sock0 CR -> SEND
  17636. for (i = 0; i < 40; i++) {
  17637. uint8_t ir = w5100_r1(s, 0x402); // Read S0 IR
  17638. if (ir == 0) continue;
  17639. // printf("IR %d, len=%d, free=%d, ptr %d\n", ir, (int) len, (int) n, ptr);
  17640. w5100_w1(s, 0x402, ir); // Write S0 IR: clear it!
  17641. if (ir & 8) len = 0; // Timeout. Report error
  17642. if (ir & (16 | 8)) break; // Stop on SEND_OK or timeout
  17643. }
  17644. return len;
  17645. }
  17646. static bool w5100_init(struct mg_tcpip_if *ifp) {
  17647. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  17648. s->end(s->spi);
  17649. w5100_w1(s, 0, 0x80); // Reset chip: CR -> 0x80
  17650. w5100_w1(s, 0x72, 0x53); // CR PHYLCKR -> unlock PHY
  17651. w5100_w1(s, 0x46, 0); // CR PHYCR0 -> autonegotiation
  17652. w5100_w1(s, 0x47, 0); // CR PHYCR1 -> reset
  17653. w5100_w1(s, 0x72, 0x00); // CR PHYLCKR -> lock PHY
  17654. w5100_w1(s, 0x1a, 6); // Sock0 RX buf size - 4KB
  17655. w5100_w1(s, 0x1b, 6); // Sock0 TX buf size - 4KB
  17656. w5100_w1(s, 0x400, 4); // Sock0 MR -> MACRAW
  17657. w5100_w1(s, 0x401, 1); // Sock0 CR -> OPEN
  17658. return w5100_r1(s, 0x403) == 0x42; // Sock0 SR == MACRAW
  17659. }
  17660. static bool w5100_up(struct mg_tcpip_if *ifp) {
  17661. struct mg_tcpip_spi *spi = (struct mg_tcpip_spi *) ifp->driver_data;
  17662. uint8_t physr0 = w5100_r1(spi, 0x3c);
  17663. return physr0 & 1; // Bit 0 of PHYSR is LNK (0 - down, 1 - up)
  17664. }
  17665. struct mg_tcpip_driver mg_tcpip_driver_w5100 = {w5100_init, w5100_tx, w5100_rx,
  17666. w5100_up};
  17667. #endif
  17668. #ifdef MG_ENABLE_LINES
  17669. #line 1 "src/drivers/w5500.c"
  17670. #endif
  17671. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5500) && MG_ENABLE_DRIVER_W5500
  17672. enum { W5500_CR = 0, W5500_S0 = 1, W5500_TX0 = 2, W5500_RX0 = 3 };
  17673. static void w5500_txn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr,
  17674. bool wr, void *buf, size_t len) {
  17675. size_t i;
  17676. uint8_t *p = (uint8_t *) buf;
  17677. uint8_t cmd[] = {(uint8_t) (addr >> 8), (uint8_t) (addr & 255),
  17678. (uint8_t) ((block << 3) | (wr ? 4 : 0))};
  17679. s->begin(s->spi);
  17680. for (i = 0; i < sizeof(cmd); i++) s->txn(s->spi, cmd[i]);
  17681. for (i = 0; i < len; i++) {
  17682. uint8_t r = s->txn(s->spi, p[i]);
  17683. if (!wr) p[i] = r;
  17684. }
  17685. s->end(s->spi);
  17686. }
  17687. // clang-format off
  17688. 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); }
  17689. 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); }
  17690. 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)); }
  17691. 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); }
  17692. 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; }
  17693. 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]); }
  17694. // clang-format on
  17695. static size_t w5500_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  17696. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  17697. uint16_t r = 0, n = 0, len = (uint16_t) buflen, n2; // Read recv len
  17698. while ((n2 = w5500_r2(s, W5500_S0, 0x26)) > n) n = n2; // Until it is stable
  17699. // printf("RSR: %d\n", (int) n);
  17700. if (n > 0) {
  17701. uint16_t ptr = w5500_r2(s, W5500_S0, 0x28); // Get read pointer
  17702. n = w5500_r2(s, W5500_RX0, ptr); // Read frame length
  17703. if (n <= len + 2 && n > 1) {
  17704. r = (uint16_t) (n - 2);
  17705. w5500_rn(s, W5500_RX0, (uint16_t) (ptr + 2), buf, r);
  17706. }
  17707. w5500_w2(s, W5500_S0, 0x28, (uint16_t) (ptr + n)); // Advance read pointer
  17708. w5500_w1(s, W5500_S0, 1, 0x40); // Sock0 CR -> RECV
  17709. // printf(" RX_RD: tot=%u n=%u r=%u\n", n2, n, r);
  17710. }
  17711. return r;
  17712. }
  17713. static size_t w5500_tx(const void *buf, size_t buflen,
  17714. struct mg_tcpip_if *ifp) {
  17715. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  17716. uint16_t i, ptr, n = 0, len = (uint16_t) buflen;
  17717. while (n < len) n = w5500_r2(s, W5500_S0, 0x20); // Wait for space
  17718. ptr = w5500_r2(s, W5500_S0, 0x24); // Get write pointer
  17719. w5500_wn(s, W5500_TX0, ptr, (void *) buf, len); // Write data
  17720. w5500_w2(s, W5500_S0, 0x24, (uint16_t) (ptr + len)); // Advance write pointer
  17721. w5500_w1(s, W5500_S0, 1, 0x20); // Sock0 CR -> SEND
  17722. for (i = 0; i < 40; i++) {
  17723. uint8_t ir = w5500_r1(s, W5500_S0, 2); // Read S0 IR
  17724. if (ir == 0) continue;
  17725. // printf("IR %d, len=%d, free=%d, ptr %d\n", ir, (int) len, (int) n, ptr);
  17726. w5500_w1(s, W5500_S0, 2, ir); // Write S0 IR: clear it!
  17727. if (ir & 8) len = 0; // Timeout. Report error
  17728. if (ir & (16 | 8)) break; // Stop on SEND_OK or timeout
  17729. }
  17730. return len;
  17731. }
  17732. static bool w5500_init(struct mg_tcpip_if *ifp) {
  17733. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  17734. s->end(s->spi);
  17735. w5500_w1(s, W5500_CR, 0, 0x80); // Reset chip: CR -> 0x80
  17736. w5500_w1(s, W5500_CR, 0x2e, 0); // CR PHYCFGR -> reset
  17737. w5500_w1(s, W5500_CR, 0x2e, 0xf8); // CR PHYCFGR -> set
  17738. // w5500_wn(s, W5500_CR, 9, s->mac, 6); // Set source MAC
  17739. w5500_w1(s, W5500_S0, 0x1e, 16); // Sock0 RX buf size
  17740. w5500_w1(s, W5500_S0, 0x1f, 16); // Sock0 TX buf size
  17741. w5500_w1(s, W5500_S0, 0, 4); // Sock0 MR -> MACRAW
  17742. w5500_w1(s, W5500_S0, 1, 1); // Sock0 CR -> OPEN
  17743. return w5500_r1(s, W5500_S0, 3) == 0x42; // Sock0 SR == MACRAW
  17744. }
  17745. static bool w5500_up(struct mg_tcpip_if *ifp) {
  17746. struct mg_tcpip_spi *spi = (struct mg_tcpip_spi *) ifp->driver_data;
  17747. uint8_t phycfgr = w5500_r1(spi, W5500_CR, 0x2e);
  17748. return phycfgr & 1; // Bit 0 of PHYCFGR is LNK (0 - down, 1 - up)
  17749. }
  17750. struct mg_tcpip_driver mg_tcpip_driver_w5500 = {w5500_init, w5500_tx, w5500_rx,
  17751. w5500_up};
  17752. #endif
  17753. #ifdef MG_ENABLE_LINES
  17754. #line 1 "src/drivers/xmc.c"
  17755. #endif
  17756. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC
  17757. struct ETH_GLOBAL_TypeDef {
  17758. volatile uint32_t MAC_CONFIGURATION, MAC_FRAME_FILTER, HASH_TABLE_HIGH,
  17759. HASH_TABLE_LOW, GMII_ADDRESS, GMII_DATA, FLOW_CONTROL, VLAN_TAG, VERSION,
  17760. DEBUG, REMOTE_WAKE_UP_FRAME_FILTER, PMT_CONTROL_STATUS, RESERVED[2],
  17761. INTERRUPT_STATUS, INTERRUPT_MASK, MAC_ADDRESS0_HIGH, MAC_ADDRESS0_LOW,
  17762. MAC_ADDRESS1_HIGH, MAC_ADDRESS1_LOW, MAC_ADDRESS2_HIGH, MAC_ADDRESS2_LOW,
  17763. MAC_ADDRESS3_HIGH, MAC_ADDRESS3_LOW, RESERVED1[40], MMC_CONTROL,
  17764. MMC_RECEIVE_INTERRUPT, MMC_TRANSMIT_INTERRUPT, MMC_RECEIVE_INTERRUPT_MASK,
  17765. MMC_TRANSMIT_INTERRUPT_MASK, TX_STATISTICS[26], RESERVED2,
  17766. RX_STATISTICS_1[26], RESERVED3[6], MMC_IPC_RECEIVE_INTERRUPT_MASK,
  17767. RESERVED4, MMC_IPC_RECEIVE_INTERRUPT, RESERVED5, RX_STATISTICS_2[30],
  17768. RESERVED7[286], TIMESTAMP_CONTROL, SUB_SECOND_INCREMENT,
  17769. SYSTEM_TIME_SECONDS, SYSTEM_TIME_NANOSECONDS,
  17770. SYSTEM_TIME_SECONDS_UPDATE, SYSTEM_TIME_NANOSECONDS_UPDATE,
  17771. TIMESTAMP_ADDEND, TARGET_TIME_SECONDS, TARGET_TIME_NANOSECONDS,
  17772. SYSTEM_TIME_HIGHER_WORD_SECONDS, TIMESTAMP_STATUS,
  17773. PPS_CONTROL, RESERVED8[564], BUS_MODE, TRANSMIT_POLL_DEMAND,
  17774. RECEIVE_POLL_DEMAND, RECEIVE_DESCRIPTOR_LIST_ADDRESS,
  17775. TRANSMIT_DESCRIPTOR_LIST_ADDRESS, STATUS, OPERATION_MODE,
  17776. INTERRUPT_ENABLE, MISSED_FRAME_AND_BUFFER_OVERFLOW_COUNTER,
  17777. RECEIVE_INTERRUPT_WATCHDOG_TIMER, RESERVED9, AHB_STATUS,
  17778. RESERVED10[6], CURRENT_HOST_TRANSMIT_DESCRIPTOR,
  17779. CURRENT_HOST_RECEIVE_DESCRIPTOR, CURRENT_HOST_TRANSMIT_BUFFER_ADDRESS,
  17780. CURRENT_HOST_RECEIVE_BUFFER_ADDRESS, HW_FEATURE;
  17781. };
  17782. #undef ETH0
  17783. #define ETH0 ((struct ETH_GLOBAL_TypeDef*) 0x5000C000UL)
  17784. #define ETH_PKT_SIZE 1536 // Max frame size
  17785. #define ETH_DESC_CNT 4 // Descriptors count
  17786. #define ETH_DS 4 // Descriptor size (words)
  17787. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  17788. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  17789. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  17790. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  17791. static uint8_t s_txno; // Current TX descriptor
  17792. static uint8_t s_rxno; // Current RX descriptor
  17793. static struct mg_tcpip_if *s_ifp; // MIP interface
  17794. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  17795. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  17796. ETH0->GMII_ADDRESS = (ETH0->GMII_ADDRESS & 0x3c) |
  17797. ((uint32_t)addr << 11) |
  17798. ((uint32_t)reg << 6) | 1;
  17799. while ((ETH0->GMII_ADDRESS & 1) != 0) (void) 0;
  17800. return (uint16_t)(ETH0->GMII_DATA & 0xffff);
  17801. }
  17802. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  17803. ETH0->GMII_DATA = val;
  17804. ETH0->GMII_ADDRESS = (ETH0->GMII_ADDRESS & 0x3c) |
  17805. ((uint32_t)addr << 11) |
  17806. ((uint32_t)reg << 6) | 3;
  17807. while ((ETH0->GMII_ADDRESS & 1) != 0) (void) 0;
  17808. }
  17809. static uint32_t get_clock_rate(struct mg_tcpip_driver_xmc_data *d) {
  17810. if (d->mdc_cr == -1) {
  17811. // assume ETH clock is 60MHz by default
  17812. // then according to 13.2.8.1, we need to set value 3
  17813. return 3;
  17814. }
  17815. return d->mdc_cr;
  17816. }
  17817. static bool mg_tcpip_driver_xmc_init(struct mg_tcpip_if *ifp) {
  17818. struct mg_tcpip_driver_xmc_data *d =
  17819. (struct mg_tcpip_driver_xmc_data *) ifp->driver_data;
  17820. s_ifp = ifp;
  17821. // reset MAC
  17822. ETH0->BUS_MODE |= 1;
  17823. while (ETH0->BUS_MODE & 1) (void) 0;
  17824. // set clock rate
  17825. ETH0->GMII_ADDRESS = get_clock_rate(d) << 2;
  17826. // init phy
  17827. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  17828. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  17829. // configure MAC: DO, DM, FES, TC
  17830. ETH0->MAC_CONFIGURATION = MG_BIT(13) | MG_BIT(11) | MG_BIT(14) | MG_BIT(24);
  17831. // set the MAC address
  17832. ETH0->MAC_ADDRESS0_HIGH = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  17833. ETH0->MAC_ADDRESS0_LOW =
  17834. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  17835. // Configure the receive filter
  17836. ETH0->MAC_FRAME_FILTER = MG_BIT(10) | MG_BIT(2); // HFP, HMC
  17837. // Disable flow control
  17838. ETH0->FLOW_CONTROL = 0;
  17839. // Enable store and forward mode
  17840. ETH0->OPERATION_MODE = MG_BIT(25) | MG_BIT(21); // RSF, TSF
  17841. // Configure DMA bus mode (AAL, USP, RPBL, PBL)
  17842. ETH0->BUS_MODE = MG_BIT(25) | MG_BIT(23) | (32 << 17) | (32 << 8);
  17843. // init RX descriptors
  17844. for (int i = 0; i < ETH_DESC_CNT; i++) {
  17845. s_rxdesc[i][0] = MG_BIT(31); // OWN descriptor
  17846. s_rxdesc[i][1] = MG_BIT(14) | ETH_PKT_SIZE;
  17847. s_rxdesc[i][2] = (uint32_t) s_rxbuf[i];
  17848. if (i == ETH_DESC_CNT - 1) {
  17849. s_rxdesc[i][3] = (uint32_t) &s_rxdesc[0][0];
  17850. } else {
  17851. s_rxdesc[i][3] = (uint32_t) &s_rxdesc[i + 1][0];
  17852. }
  17853. }
  17854. ETH0->RECEIVE_DESCRIPTOR_LIST_ADDRESS = (uint32_t) &s_rxdesc[0][0];
  17855. // init TX descriptors
  17856. for (int i = 0; i < ETH_DESC_CNT; i++) {
  17857. s_txdesc[i][0] = MG_BIT(30) | MG_BIT(20);
  17858. s_txdesc[i][2] = (uint32_t) s_txbuf[i];
  17859. if (i == ETH_DESC_CNT - 1) {
  17860. s_txdesc[i][3] = (uint32_t) &s_txdesc[0][0];
  17861. } else {
  17862. s_txdesc[i][3] = (uint32_t) &s_txdesc[i + 1][0];
  17863. }
  17864. }
  17865. ETH0->TRANSMIT_DESCRIPTOR_LIST_ADDRESS = (uint32_t) &s_txdesc[0][0];
  17866. // Clear interrupts
  17867. ETH0->STATUS = 0xFFFFFFFF;
  17868. // Disable MAC interrupts
  17869. ETH0->MMC_TRANSMIT_INTERRUPT_MASK = 0xFFFFFFFF;
  17870. ETH0->MMC_RECEIVE_INTERRUPT_MASK = 0xFFFFFFFF;
  17871. ETH0->MMC_IPC_RECEIVE_INTERRUPT_MASK = 0xFFFFFFFF;
  17872. ETH0->INTERRUPT_MASK = MG_BIT(9) | MG_BIT(3); // TSIM, PMTIM
  17873. //Enable interrupts (NIE, RIE, TIE)
  17874. ETH0->INTERRUPT_ENABLE = MG_BIT(16) | MG_BIT(6) | MG_BIT(0);
  17875. // Enable MAC transmission and reception (TE, RE)
  17876. ETH0->MAC_CONFIGURATION |= MG_BIT(3) | MG_BIT(2);
  17877. // Enable DMA transmission and reception (ST, SR)
  17878. ETH0->OPERATION_MODE |= MG_BIT(13) | MG_BIT(1);
  17879. return true;
  17880. }
  17881. static size_t mg_tcpip_driver_xmc_tx(const void *buf, size_t len,
  17882. struct mg_tcpip_if *ifp) {
  17883. if (len > sizeof(s_txbuf[s_txno])) {
  17884. MG_ERROR(("Frame too big, %ld", (long) len));
  17885. len = 0; // Frame is too big
  17886. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  17887. ifp->nerr++;
  17888. MG_ERROR(("No free descriptors"));
  17889. len = 0; // All descriptors are busy, fail
  17890. } else {
  17891. memcpy(s_txbuf[s_txno], buf, len);
  17892. s_txdesc[s_txno][1] = len;
  17893. // Table 13-19 Transmit Descriptor Word 0 (IC, LS, FS, TCH)
  17894. s_txdesc[s_txno][0] = MG_BIT(30) | MG_BIT(29) | MG_BIT(28) | MG_BIT(20);
  17895. s_txdesc[s_txno][0] |= MG_BIT(31); // OWN bit: handle control to DMA
  17896. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  17897. }
  17898. // Resume processing
  17899. ETH0->STATUS = MG_BIT(2); // clear Transmit unavailable
  17900. ETH0->TRANSMIT_POLL_DEMAND = 0;
  17901. return len;
  17902. }
  17903. static bool mg_tcpip_driver_xmc_up(struct mg_tcpip_if *ifp) {
  17904. struct mg_tcpip_driver_xmc_data *d =
  17905. (struct mg_tcpip_driver_xmc_data *) ifp->driver_data;
  17906. uint8_t speed = MG_PHY_SPEED_10M;
  17907. bool up = false, full_duplex = false;
  17908. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  17909. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  17910. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  17911. MG_DEBUG(("Link is %uM %s-duplex", speed == MG_PHY_SPEED_10M ? 10 : 100,
  17912. full_duplex ? "full" : "half"));
  17913. }
  17914. return up;
  17915. }
  17916. void ETH0_IRQHandler(void);
  17917. void ETH0_IRQHandler(void) {
  17918. uint32_t irq_status = ETH0->STATUS;
  17919. // check if a frame was received
  17920. if (irq_status & MG_BIT(6)) {
  17921. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  17922. if ((s_rxdesc[s_rxno][0] & MG_BIT(31)) == 0) {
  17923. size_t len = (s_rxdesc[s_rxno][0] & 0x3fff0000) >> 16;
  17924. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  17925. s_rxdesc[s_rxno][0] = MG_BIT(31); // OWN bit: handle control to DMA
  17926. // Resume processing
  17927. ETH0->STATUS = MG_BIT(7) | MG_BIT(6); // clear RU and RI
  17928. ETH0->RECEIVE_POLL_DEMAND = 0;
  17929. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  17930. }
  17931. }
  17932. ETH0->STATUS = MG_BIT(6);
  17933. }
  17934. // clear Successful transmission interrupt
  17935. if (irq_status & 1) {
  17936. ETH0->STATUS = 1;
  17937. }
  17938. // clear normal interrupt
  17939. if (irq_status & MG_BIT(16)) {
  17940. ETH0->STATUS = MG_BIT(16);
  17941. }
  17942. }
  17943. struct mg_tcpip_driver mg_tcpip_driver_xmc = {
  17944. mg_tcpip_driver_xmc_init, mg_tcpip_driver_xmc_tx, NULL,
  17945. mg_tcpip_driver_xmc_up};
  17946. #endif
  17947. #ifdef MG_ENABLE_LINES
  17948. #line 1 "src/drivers/xmc7.c"
  17949. #endif
  17950. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7
  17951. struct ETH_Type {
  17952. volatile uint32_t CTL, STATUS, RESERVED[1022], NETWORK_CONTROL,
  17953. NETWORK_CONFIG, NETWORK_STATUS, USER_IO_REGISTER, DMA_CONFIG,
  17954. TRANSMIT_STATUS, RECEIVE_Q_PTR, TRANSMIT_Q_PTR, RECEIVE_STATUS,
  17955. INT_STATUS, INT_ENABLE, INT_DISABLE, INT_MASK, PHY_MANAGEMENT, PAUSE_TIME,
  17956. TX_PAUSE_QUANTUM, PBUF_TXCUTTHRU, PBUF_RXCUTTHRU, JUMBO_MAX_LENGTH,
  17957. EXTERNAL_FIFO_INTERFACE, RESERVED1, AXI_MAX_PIPELINE, RSC_CONTROL,
  17958. INT_MODERATION, SYS_WAKE_TIME, RESERVED2[7], HASH_BOTTOM, HASH_TOP,
  17959. SPEC_ADD1_BOTTOM, SPEC_ADD1_TOP, SPEC_ADD2_BOTTOM, SPEC_ADD2_TOP,
  17960. SPEC_ADD3_BOTTOM, SPEC_ADD3_TOP, SPEC_ADD4_BOTTOM, SPEC_ADD4_TOP,
  17961. SPEC_TYPE1, SPEC_TYPE2, SPEC_TYPE3, SPEC_TYPE4, WOL_REGISTER,
  17962. STRETCH_RATIO, STACKED_VLAN, TX_PFC_PAUSE, MASK_ADD1_BOTTOM,
  17963. MASK_ADD1_TOP, DMA_ADDR_OR_MASK, RX_PTP_UNICAST, TX_PTP_UNICAST,
  17964. TSU_NSEC_CMP, TSU_SEC_CMP, TSU_MSB_SEC_CMP, TSU_PTP_TX_MSB_SEC,
  17965. TSU_PTP_RX_MSB_SEC, TSU_PEER_TX_MSB_SEC, TSU_PEER_RX_MSB_SEC,
  17966. DPRAM_FILL_DBG, REVISION_REG, OCTETS_TXED_BOTTOM, OCTETS_TXED_TOP,
  17967. FRAMES_TXED_OK, BROADCAST_TXED, MULTICAST_TXED, PAUSE_FRAMES_TXED,
  17968. FRAMES_TXED_64, FRAMES_TXED_65, FRAMES_TXED_128, FRAMES_TXED_256,
  17969. FRAMES_TXED_512, FRAMES_TXED_1024, FRAMES_TXED_1519, TX_UNDERRUNS,
  17970. SINGLE_COLLISIONS, MULTIPLE_COLLISIONS, EXCESSIVE_COLLISIONS,
  17971. LATE_COLLISIONS, DEFERRED_FRAMES, CRS_ERRORS, OCTETS_RXED_BOTTOM,
  17972. OCTETS_RXED_TOP, FRAMES_RXED_OK, BROADCAST_RXED, MULTICAST_RXED,
  17973. PAUSE_FRAMES_RXED, FRAMES_RXED_64, FRAMES_RXED_65, FRAMES_RXED_128,
  17974. FRAMES_RXED_256, FRAMES_RXED_512, FRAMES_RXED_1024, FRAMES_RXED_1519,
  17975. UNDERSIZE_FRAMES, EXCESSIVE_RX_LENGTH, RX_JABBERS, FCS_ERRORS,
  17976. RX_LENGTH_ERRORS, RX_SYMBOL_ERRORS, ALIGNMENT_ERRORS, RX_RESOURCE_ERRORS,
  17977. RX_OVERRUNS, RX_IP_CK_ERRORS, RX_TCP_CK_ERRORS, RX_UDP_CK_ERRORS,
  17978. AUTO_FLUSHED_PKTS, RESERVED3, TSU_TIMER_INCR_SUB_NSEC, TSU_TIMER_MSB_SEC,
  17979. TSU_STROBE_MSB_SEC, TSU_STROBE_SEC, TSU_STROBE_NSEC, TSU_TIMER_SEC,
  17980. TSU_TIMER_NSEC, TSU_TIMER_ADJUST, TSU_TIMER_INCR, TSU_PTP_TX_SEC,
  17981. TSU_PTP_TX_NSEC, TSU_PTP_RX_SEC, TSU_PTP_RX_NSEC, TSU_PEER_TX_SEC,
  17982. TSU_PEER_TX_NSEC, TSU_PEER_RX_SEC, TSU_PEER_RX_NSEC, PCS_CONTROL,
  17983. PCS_STATUS, RESERVED4[2], PCS_AN_ADV, PCS_AN_LP_BASE, PCS_AN_EXP,
  17984. PCS_AN_NP_TX, PCS_AN_LP_NP, RESERVED5[6], PCS_AN_EXT_STATUS, RESERVED6[8],
  17985. TX_PAUSE_QUANTUM1, TX_PAUSE_QUANTUM2, TX_PAUSE_QUANTUM3, RESERVED7,
  17986. RX_LPI, RX_LPI_TIME, TX_LPI, TX_LPI_TIME, DESIGNCFG_DEBUG1,
  17987. DESIGNCFG_DEBUG2, DESIGNCFG_DEBUG3, DESIGNCFG_DEBUG4, DESIGNCFG_DEBUG5,
  17988. DESIGNCFG_DEBUG6, DESIGNCFG_DEBUG7, DESIGNCFG_DEBUG8, DESIGNCFG_DEBUG9,
  17989. DESIGNCFG_DEBUG10, RESERVED8[22], SPEC_ADD5_BOTTOM, SPEC_ADD5_TOP,
  17990. RESERVED9[60], SPEC_ADD36_BOTTOM, SPEC_ADD36_TOP, INT_Q1_STATUS,
  17991. INT_Q2_STATUS, INT_Q3_STATUS, RESERVED10[11], INT_Q15_STATUS, RESERVED11,
  17992. TRANSMIT_Q1_PTR, TRANSMIT_Q2_PTR, TRANSMIT_Q3_PTR, RESERVED12[11],
  17993. TRANSMIT_Q15_PTR, RESERVED13, RECEIVE_Q1_PTR, RECEIVE_Q2_PTR,
  17994. RECEIVE_Q3_PTR, RESERVED14[3], RECEIVE_Q7_PTR, RESERVED15,
  17995. DMA_RXBUF_SIZE_Q1, DMA_RXBUF_SIZE_Q2, DMA_RXBUF_SIZE_Q3, RESERVED16[3],
  17996. DMA_RXBUF_SIZE_Q7, CBS_CONTROL, CBS_IDLESLOPE_Q_A, CBS_IDLESLOPE_Q_B,
  17997. UPPER_TX_Q_BASE_ADDR, TX_BD_CONTROL, RX_BD_CONTROL, UPPER_RX_Q_BASE_ADDR,
  17998. RESERVED17[2], HIDDEN_REG0, HIDDEN_REG1, HIDDEN_REG2, HIDDEN_REG3,
  17999. RESERVED18[2], HIDDEN_REG4, HIDDEN_REG5;
  18000. };
  18001. #define ETH0 ((struct ETH_Type *) 0x40490000)
  18002. #define ETH_PKT_SIZE 1536 // Max frame size
  18003. #define ETH_DESC_CNT 4 // Descriptors count
  18004. #define ETH_DS 2 // Descriptor size (words)
  18005. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  18006. #define MG_8BYTE_ALIGNED __attribute__((aligned((8U))))
  18007. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  18008. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  18009. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS] MG_8BYTE_ALIGNED;
  18010. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS] MG_8BYTE_ALIGNED;
  18011. static uint8_t s_txno MG_8BYTE_ALIGNED; // Current TX descriptor
  18012. static uint8_t s_rxno MG_8BYTE_ALIGNED; // Current RX descriptor
  18013. static struct mg_tcpip_if *s_ifp; // MIP interface
  18014. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  18015. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  18016. // WRITE1, READ OPERATION, PHY, REG, WRITE10
  18017. ETH0->PHY_MANAGEMENT = MG_BIT(30) | MG_BIT(29) | ((addr & 0xf) << 24) |
  18018. ((reg & 0x1f) << 18) | MG_BIT(17);
  18019. while ((ETH0->NETWORK_STATUS & MG_BIT(2)) == 0) (void) 0;
  18020. return ETH0->PHY_MANAGEMENT & 0xffff;
  18021. }
  18022. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  18023. ETH0->PHY_MANAGEMENT = MG_BIT(30) | MG_BIT(28) | ((addr & 0xf) << 24) |
  18024. ((reg & 0x1f) << 18) | MG_BIT(17) | val;
  18025. while ((ETH0->NETWORK_STATUS & MG_BIT(2)) == 0) (void) 0;
  18026. }
  18027. static uint32_t get_clock_rate(struct mg_tcpip_driver_xmc7_data *d) {
  18028. // see ETH0 -> NETWORK_CONFIG register
  18029. (void) d;
  18030. return 3;
  18031. }
  18032. static bool mg_tcpip_driver_xmc7_init(struct mg_tcpip_if *ifp) {
  18033. struct mg_tcpip_driver_xmc7_data *d =
  18034. (struct mg_tcpip_driver_xmc7_data *) ifp->driver_data;
  18035. s_ifp = ifp;
  18036. // enable controller, set RGMII mode
  18037. ETH0->CTL = MG_BIT(31) | (4 << 8) | 2;
  18038. uint32_t cr = get_clock_rate(d);
  18039. // set NSP change, ignore RX FCS, data bus width, clock rate
  18040. // frame length 1536, full duplex, speed
  18041. ETH0->NETWORK_CONFIG = MG_BIT(29) | MG_BIT(26) | MG_BIT(21) |
  18042. ((cr & 7) << 18) | MG_BIT(8) | MG_BIT(4) | MG_BIT(1) |
  18043. MG_BIT(0);
  18044. // config DMA settings: Force TX burst, Discard on Error, set RX buffer size
  18045. // to 1536, TX_PBUF_SIZE, RX_PBUF_SIZE, AMBA_BURST_LENGTH
  18046. ETH0->DMA_CONFIG =
  18047. MG_BIT(26) | MG_BIT(24) | (0x18 << 16) | MG_BIT(10) | (3 << 8) | 4;
  18048. // initialize descriptors
  18049. for (int i = 0; i < ETH_DESC_CNT; i++) {
  18050. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i];
  18051. if (i == ETH_DESC_CNT - 1) {
  18052. s_rxdesc[i][0] |= MG_BIT(1); // mark last descriptor
  18053. }
  18054. s_txdesc[i][0] = (uint32_t) s_txbuf[i];
  18055. s_txdesc[i][1] = MG_BIT(31); // OWN descriptor
  18056. if (i == ETH_DESC_CNT - 1) {
  18057. s_txdesc[i][1] |= MG_BIT(30); // mark last descriptor
  18058. }
  18059. }
  18060. ETH0->RECEIVE_Q_PTR = (uint32_t) s_rxdesc;
  18061. ETH0->TRANSMIT_Q_PTR = (uint32_t) s_txdesc;
  18062. // disable other queues
  18063. ETH0->TRANSMIT_Q2_PTR = 1;
  18064. ETH0->TRANSMIT_Q1_PTR = 1;
  18065. ETH0->RECEIVE_Q2_PTR = 1;
  18066. ETH0->RECEIVE_Q1_PTR = 1;
  18067. // enable interrupts (RX complete)
  18068. ETH0->INT_ENABLE = MG_BIT(1);
  18069. // set MAC address
  18070. ETH0->SPEC_ADD1_BOTTOM =
  18071. ifp->mac[3] << 24 | ifp->mac[2] << 16 | ifp->mac[1] << 8 | ifp->mac[0];
  18072. ETH0->SPEC_ADD1_TOP = ifp->mac[5] << 8 | ifp->mac[4];
  18073. // enable MDIO, TX, RX
  18074. ETH0->NETWORK_CONTROL = MG_BIT(4) | MG_BIT(3) | MG_BIT(2);
  18075. // start transmission
  18076. ETH0->NETWORK_CONTROL |= MG_BIT(9);
  18077. // init phy
  18078. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  18079. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  18080. (void) d;
  18081. return true;
  18082. }
  18083. static size_t mg_tcpip_driver_xmc7_tx(const void *buf, size_t len,
  18084. struct mg_tcpip_if *ifp) {
  18085. if (len > sizeof(s_txbuf[s_txno])) {
  18086. MG_ERROR(("Frame too big, %ld", (long) len));
  18087. len = 0; // Frame is too big
  18088. } else if (((s_txdesc[s_txno][1] & MG_BIT(31)) == 0)) {
  18089. ifp->nerr++;
  18090. MG_ERROR(("No free descriptors"));
  18091. len = 0; // All descriptors are busy, fail
  18092. } else {
  18093. memcpy(s_txbuf[s_txno], buf, len);
  18094. s_txdesc[s_txno][1] = (s_txno == ETH_DESC_CNT - 1 ? MG_BIT(30) : 0) |
  18095. MG_BIT(15) | len; // Last buffer and length
  18096. ETH0->NETWORK_CONTROL |= MG_BIT(9); // enable transmission
  18097. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  18098. }
  18099. MG_DSB();
  18100. ETH0->TRANSMIT_STATUS = ETH0->TRANSMIT_STATUS;
  18101. ETH0->NETWORK_CONTROL |= MG_BIT(9); // enable transmission
  18102. return len;
  18103. }
  18104. static bool mg_tcpip_driver_xmc7_up(struct mg_tcpip_if *ifp) {
  18105. struct mg_tcpip_driver_xmc7_data *d =
  18106. (struct mg_tcpip_driver_xmc7_data *) ifp->driver_data;
  18107. uint8_t speed = MG_PHY_SPEED_10M;
  18108. bool up = false, full_duplex = false;
  18109. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  18110. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  18111. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  18112. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  18113. // if(link is slow or half) set flags otherwise
  18114. // reg = tmp
  18115. uint32_t netconf = ETH0->NETWORK_CONFIG;
  18116. MG_SET_BITS(netconf, MG_BIT(10),
  18117. MG_BIT(1) | MG_BIT(0)); // 100M, Full-duplex
  18118. uint32_t ctl = ETH0->CTL;
  18119. MG_SET_BITS(ctl, 0xFF00, 4 << 8); // /5 for 25M clock
  18120. if (speed == MG_PHY_SPEED_1000M) {
  18121. netconf |= MG_BIT(10); // 1000M
  18122. MG_SET_BITS(ctl, 0xFF00, 0); // /1 for 125M clock TODO() IS THIS NEEDED ?
  18123. } else if (speed == MG_PHY_SPEED_10M) {
  18124. netconf &= ~MG_BIT(0); // 10M
  18125. MG_SET_BITS(ctl, 0xFF00, 49); // /50 for 2.5M clock
  18126. }
  18127. if (full_duplex == false) netconf &= ~MG_BIT(1); // Half-duplex
  18128. ETH0->NETWORK_CONFIG = netconf; // IRQ handler does not fiddle with these
  18129. ETH0->CTL = ctl;
  18130. MG_DEBUG(("Link is %uM %s-duplex",
  18131. speed == MG_PHY_SPEED_10M
  18132. ? 10
  18133. : (speed == MG_PHY_SPEED_100M ? 100 : 1000),
  18134. full_duplex ? "full" : "half"));
  18135. }
  18136. return up;
  18137. }
  18138. void ETH_IRQHandler(void) {
  18139. uint32_t irq_status = ETH0->INT_STATUS;
  18140. if (irq_status & MG_BIT(1)) {
  18141. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  18142. if (s_rxdesc[s_rxno][0] & MG_BIT(0)) {
  18143. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  18144. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  18145. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // OWN bit: handle control to DMA
  18146. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  18147. }
  18148. }
  18149. }
  18150. ETH0->INT_STATUS = irq_status;
  18151. }
  18152. struct mg_tcpip_driver mg_tcpip_driver_xmc7 = {mg_tcpip_driver_xmc7_init,
  18153. mg_tcpip_driver_xmc7_tx, NULL,
  18154. mg_tcpip_driver_xmc7_up};
  18155. #endif