mongoose.c 605 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773
  1. // Copyright (c) 2004-2013 Sergey Lyubka
  2. // Copyright (c) 2013-2024 Cesanta Software Limited
  3. // All rights reserved
  4. //
  5. // This software is dual-licensed: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License version 2 as
  7. // published by the Free Software Foundation. For the terms of this
  8. // license, see http://www.gnu.org/licenses/
  9. //
  10. // You are free to use this software under the terms of the GNU General
  11. // Public License, but WITHOUT ANY WARRANTY; without even the implied
  12. // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. // See the GNU General Public License for more details.
  14. //
  15. // Alternatively, you can license this software under a commercial
  16. // license, as set out in https://www.mongoose.ws/licensing/
  17. //
  18. // SPDX-License-Identifier: GPL-2.0-only or commercial
  19. #include "mongoose.h"
  20. #ifdef MG_ENABLE_LINES
  21. #line 1 "src/base64.c"
  22. #endif
  23. static int mg_base64_encode_single(int c) {
  24. if (c < 26) {
  25. return c + 'A';
  26. } else if (c < 52) {
  27. return c - 26 + 'a';
  28. } else if (c < 62) {
  29. return c - 52 + '0';
  30. } else {
  31. return c == 62 ? '+' : '/';
  32. }
  33. }
  34. static int mg_base64_decode_single(int c) {
  35. if (c >= 'A' && c <= 'Z') {
  36. return c - 'A';
  37. } else if (c >= 'a' && c <= 'z') {
  38. return c + 26 - 'a';
  39. } else if (c >= '0' && c <= '9') {
  40. return c + 52 - '0';
  41. } else if (c == '+') {
  42. return 62;
  43. } else if (c == '/') {
  44. return 63;
  45. } else if (c == '=') {
  46. return 64;
  47. } else {
  48. return -1;
  49. }
  50. }
  51. size_t mg_base64_update(unsigned char ch, char *to, size_t n) {
  52. unsigned long rem = (n & 3) % 3;
  53. if (rem == 0) {
  54. to[n] = (char) mg_base64_encode_single(ch >> 2);
  55. to[++n] = (char) ((ch & 3) << 4);
  56. } else if (rem == 1) {
  57. to[n] = (char) mg_base64_encode_single(to[n] | (ch >> 4));
  58. to[++n] = (char) ((ch & 15) << 2);
  59. } else {
  60. to[n] = (char) mg_base64_encode_single(to[n] | (ch >> 6));
  61. to[++n] = (char) mg_base64_encode_single(ch & 63);
  62. n++;
  63. }
  64. return n;
  65. }
  66. size_t mg_base64_final(char *to, size_t n) {
  67. size_t saved = n;
  68. // printf("---[%.*s]\n", n, to);
  69. if (n & 3) n = mg_base64_update(0, to, n);
  70. if ((saved & 3) == 2) n--;
  71. // printf(" %d[%.*s]\n", n, n, to);
  72. while (n & 3) to[n++] = '=';
  73. to[n] = '\0';
  74. return n;
  75. }
  76. size_t mg_base64_encode(const unsigned char *p, size_t n, char *to, size_t dl) {
  77. size_t i, len = 0;
  78. if (dl > 0) to[0] = '\0';
  79. if (dl < ((n / 3) + (n % 3 ? 1 : 0)) * 4 + 1) return 0;
  80. for (i = 0; i < n; i++) len = mg_base64_update(p[i], to, len);
  81. len = mg_base64_final(to, len);
  82. return len;
  83. }
  84. size_t mg_base64_decode(const char *src, size_t n, char *dst, size_t dl) {
  85. const char *end = src == NULL ? NULL : src + n; // Cannot add to NULL
  86. size_t len = 0;
  87. if (dl < n / 4 * 3 + 1) goto fail;
  88. while (src != NULL && src + 3 < end) {
  89. int a = mg_base64_decode_single(src[0]),
  90. b = mg_base64_decode_single(src[1]),
  91. c = mg_base64_decode_single(src[2]),
  92. d = mg_base64_decode_single(src[3]);
  93. if (a == 64 || a < 0 || b == 64 || b < 0 || c < 0 || d < 0) {
  94. goto fail;
  95. }
  96. dst[len++] = (char) ((a << 2) | (b >> 4));
  97. if (src[2] != '=') {
  98. dst[len++] = (char) ((b << 4) | (c >> 2));
  99. if (src[3] != '=') dst[len++] = (char) ((c << 6) | d);
  100. }
  101. src += 4;
  102. }
  103. dst[len] = '\0';
  104. return len;
  105. fail:
  106. if (dl > 0) dst[0] = '\0';
  107. return 0;
  108. }
  109. #ifdef MG_ENABLE_LINES
  110. #line 1 "src/device_ch32v307.c"
  111. #endif
  112. #if MG_DEVICE == MG_DEVICE_CH32V307
  113. // RM: https://www.wch-ic.com/downloads/CH32FV2x_V3xRM_PDF.html
  114. #define FLASH_BASE 0x40022000
  115. #define FLASH_ACTLR (FLASH_BASE + 0)
  116. #define FLASH_KEYR (FLASH_BASE + 4)
  117. #define FLASH_OBKEYR (FLASH_BASE + 8)
  118. #define FLASH_STATR (FLASH_BASE + 12)
  119. #define FLASH_CTLR (FLASH_BASE + 16)
  120. #define FLASH_ADDR (FLASH_BASE + 20)
  121. #define FLASH_OBR (FLASH_BASE + 28)
  122. #define FLASH_WPR (FLASH_BASE + 32)
  123. void *mg_flash_start(void) {
  124. return (void *) 0x08000000;
  125. }
  126. size_t mg_flash_size(void) {
  127. return 480 * 1024; // First 320k is 0-wait
  128. }
  129. size_t mg_flash_sector_size(void) {
  130. return 4096;
  131. }
  132. size_t mg_flash_write_align(void) {
  133. return 4;
  134. }
  135. int mg_flash_bank(void) {
  136. return 0;
  137. }
  138. void mg_device_reset(void) {
  139. *((volatile uint32_t *) 0xbeef0000) |= 1U << 7; // NVIC_SystemReset()
  140. }
  141. static void flash_unlock(void) {
  142. static bool unlocked;
  143. if (unlocked == false) {
  144. MG_REG(FLASH_KEYR) = 0x45670123;
  145. MG_REG(FLASH_KEYR) = 0xcdef89ab;
  146. unlocked = true;
  147. }
  148. }
  149. static void flash_wait(void) {
  150. while (MG_REG(FLASH_STATR) & MG_BIT(0)) (void) 0;
  151. }
  152. bool mg_flash_erase(void *addr) {
  153. //MG_INFO(("%p", addr));
  154. flash_unlock();
  155. flash_wait();
  156. MG_REG(FLASH_ADDR) = (uint32_t) addr;
  157. MG_REG(FLASH_CTLR) |= MG_BIT(1) | MG_BIT(6); // PER | STRT;
  158. flash_wait();
  159. return true;
  160. }
  161. static bool is_page_boundary(const void *addr) {
  162. uint32_t val = (uint32_t) addr;
  163. return (val & (mg_flash_sector_size() - 1)) == 0;
  164. }
  165. bool mg_flash_write(void *addr, const void *buf, size_t len) {
  166. //MG_INFO(("%p %p %lu", addr, buf, len));
  167. //mg_hexdump(buf, len);
  168. flash_unlock();
  169. const uint16_t *src = (uint16_t *) buf, *end = &src[len / 2];
  170. uint16_t *dst = (uint16_t *) addr;
  171. MG_REG(FLASH_CTLR) |= MG_BIT(0); // Set PG
  172. //MG_INFO(("CTLR: %#lx", MG_REG(FLASH_CTLR)));
  173. while (src < end) {
  174. if (is_page_boundary(dst)) mg_flash_erase(dst);
  175. *dst++ = *src++;
  176. flash_wait();
  177. }
  178. MG_REG(FLASH_CTLR) &= ~MG_BIT(0); // Clear PG
  179. return true;
  180. }
  181. #endif
  182. #ifdef MG_ENABLE_LINES
  183. #line 1 "src/device_dummy.c"
  184. #endif
  185. #if MG_DEVICE == MG_DEVICE_NONE
  186. void *mg_flash_start(void) {
  187. return NULL;
  188. }
  189. size_t mg_flash_size(void) {
  190. return 0;
  191. }
  192. size_t mg_flash_sector_size(void) {
  193. return 0;
  194. }
  195. size_t mg_flash_write_align(void) {
  196. return 0;
  197. }
  198. int mg_flash_bank(void) {
  199. return 0;
  200. }
  201. bool mg_flash_erase(void *location) {
  202. (void) location;
  203. return false;
  204. }
  205. bool mg_flash_swap_bank(void) {
  206. return true;
  207. }
  208. bool mg_flash_write(void *addr, const void *buf, size_t len) {
  209. (void) addr, (void) buf, (void) len;
  210. return false;
  211. }
  212. void mg_device_reset(void) {
  213. }
  214. #endif
  215. #ifdef MG_ENABLE_LINES
  216. #line 1 "src/device_flash.c"
  217. #endif
  218. #if MG_DEVICE == MG_DEVICE_STM32H7 || MG_DEVICE == MG_DEVICE_STM32H5 || \
  219. MG_DEVICE == MG_DEVICE_RT1020 || MG_DEVICE == MG_DEVICE_RT1060
  220. // Flash can be written only if it is erased. Erased flash is 0xff (all bits 1)
  221. // Writes must be mg_flash_write_align() - aligned. Thus if we want to save an
  222. // object, we pad it at the end for alignment.
  223. //
  224. // Objects in the flash sector are stored sequentially:
  225. // | 32-bit size | 32-bit KEY | ..data.. | ..pad.. | 32-bit size | ......
  226. //
  227. // In order to get to the next object, read its size, then align up.
  228. // Traverse the list of saved objects
  229. size_t mg_flash_next(char *p, char *end, uint32_t *key, size_t *size) {
  230. size_t aligned_size = 0, align = mg_flash_write_align(), left = end - p;
  231. uint32_t *p32 = (uint32_t *) p, min_size = sizeof(uint32_t) * 2;
  232. if (p32[0] != 0xffffffff && left > MG_ROUND_UP(min_size, align)) {
  233. if (size) *size = (size_t) p32[0];
  234. if (key) *key = p32[1];
  235. aligned_size = MG_ROUND_UP(p32[0] + sizeof(uint32_t) * 2, align);
  236. if (left < aligned_size) aligned_size = 0; // Out of bounds, fail
  237. }
  238. return aligned_size;
  239. }
  240. // Return the last sector of Bank 2
  241. static char *flash_last_sector(void) {
  242. size_t ss = mg_flash_sector_size(), size = mg_flash_size();
  243. char *base = (char *) mg_flash_start(), *last = base + size - ss;
  244. if (mg_flash_bank() == 2) last -= size / 2;
  245. return last;
  246. }
  247. // Find a saved object with a given key
  248. bool mg_flash_load(void *sector, uint32_t key, void *buf, size_t len) {
  249. char *base = (char *) mg_flash_start(), *s = (char *) sector, *res = NULL;
  250. size_t ss = mg_flash_sector_size(), ofs = 0, n, sz;
  251. bool ok = false;
  252. if (s == NULL) s = flash_last_sector();
  253. if (s < base || s >= base + mg_flash_size()) {
  254. MG_ERROR(("%p is outsize of flash", sector));
  255. } else if (((s - base) % ss) != 0) {
  256. MG_ERROR(("%p is not a sector boundary", sector));
  257. } else {
  258. uint32_t k, scanned = 0;
  259. while ((n = mg_flash_next(s + ofs, s + ss, &k, &sz)) > 0) {
  260. // MG_DEBUG((" > obj %lu, ofs %lu, key %x/%x", scanned, ofs, k, key));
  261. // mg_hexdump(s + ofs, n);
  262. if (k == key && sz == len) {
  263. res = s + ofs + sizeof(uint32_t) * 2;
  264. memcpy(buf, res, len); // Copy object
  265. ok = true; // Keep scanning for the newer versions of it
  266. }
  267. ofs += n, scanned++;
  268. }
  269. MG_DEBUG(("Scanned %u objects, key %x is @ %p", scanned, key, res));
  270. }
  271. return ok;
  272. }
  273. // For all saved objects in the sector, delete old versions of objects
  274. static void mg_flash_sector_cleanup(char *sector) {
  275. // Buffer all saved objects into an IO buffer (backed by RAM)
  276. // erase sector, and re-save them.
  277. struct mg_iobuf io = {0, 0, 0, 2048};
  278. size_t ss = mg_flash_sector_size();
  279. size_t n, size, size2, ofs = 0, hs = sizeof(uint32_t) * 2;
  280. uint32_t key;
  281. // Traverse all objects
  282. MG_DEBUG(("Cleaning up sector %p", sector));
  283. while ((n = mg_flash_next(sector + ofs, sector + ss, &key, &size)) > 0) {
  284. // Delete an old copy of this object in the cache
  285. for (size_t o = 0; o < io.len; o += size2 + hs) {
  286. uint32_t k = *(uint32_t *) (io.buf + o + sizeof(uint32_t));
  287. size2 = *(uint32_t *) (io.buf + o);
  288. if (k == key) {
  289. mg_iobuf_del(&io, o, size2 + hs);
  290. break;
  291. }
  292. }
  293. // And add the new copy
  294. mg_iobuf_add(&io, io.len, sector + ofs, size + hs);
  295. ofs += n;
  296. }
  297. // All objects are cached in RAM now
  298. if (mg_flash_erase(sector)) { // Erase sector. If successful,
  299. for (ofs = 0; ofs < io.len; ofs += size + hs) { // Traverse cached objects
  300. size = *(uint32_t *) (io.buf + ofs);
  301. key = *(uint32_t *) (io.buf + ofs + sizeof(uint32_t));
  302. mg_flash_save(sector, key, io.buf + ofs + hs, size); // Save to flash
  303. }
  304. }
  305. mg_iobuf_free(&io);
  306. }
  307. // Save an object with a given key - append to the end of an object list
  308. bool mg_flash_save(void *sector, uint32_t key, const void *buf, size_t len) {
  309. char *base = (char *) mg_flash_start(), *s = (char *) sector;
  310. size_t ss = mg_flash_sector_size(), ofs = 0, n;
  311. bool ok = false;
  312. if (s == NULL) s = flash_last_sector();
  313. if (s < base || s >= base + mg_flash_size()) {
  314. MG_ERROR(("%p is outsize of flash", sector));
  315. } else if (((s - base) % ss) != 0) {
  316. MG_ERROR(("%p is not a sector boundary", sector));
  317. } else {
  318. char ab[mg_flash_write_align()]; // Aligned write block
  319. uint32_t hdr[2] = {(uint32_t) len, key};
  320. size_t needed = sizeof(hdr) + len;
  321. size_t needed_aligned = MG_ROUND_UP(needed, sizeof(ab));
  322. while ((n = mg_flash_next(s + ofs, s + ss, NULL, NULL)) > 0) ofs += n;
  323. // If there is not enough space left, cleanup sector and re-eval ofs
  324. if (ofs + needed_aligned >= ss) {
  325. mg_flash_sector_cleanup(s);
  326. ofs = 0;
  327. while ((n = mg_flash_next(s + ofs, s + ss, NULL, NULL)) > 0) ofs += n;
  328. }
  329. if (ofs + needed_aligned <= ss) {
  330. // Enough space to save this object
  331. if (sizeof(ab) < sizeof(hdr)) {
  332. // Flash write granularity is 32 bit or less, write with no buffering
  333. ok = mg_flash_write(s + ofs, hdr, sizeof(hdr));
  334. if (ok) mg_flash_write(s + ofs + sizeof(hdr), buf, len);
  335. } else {
  336. // Flash granularity is sizeof(hdr) or more. We need to save in
  337. // 3 chunks: initial block, bulk, rest. This is because we have
  338. // two memory chunks to write: hdr and buf, on aligned boundaries.
  339. n = sizeof(ab) - sizeof(hdr); // Initial chunk that we write
  340. if (n > len) n = len; // is
  341. memset(ab, 0xff, sizeof(ab)); // initialized to all-one
  342. memcpy(ab, hdr, sizeof(hdr)); // contains the header (key + size)
  343. memcpy(ab + sizeof(hdr), buf, n); // and an initial part of buf
  344. MG_INFO(("saving initial block of %lu", sizeof(ab)));
  345. ok = mg_flash_write(s + ofs, ab, sizeof(ab));
  346. if (ok && len > n) {
  347. size_t n2 = MG_ROUND_DOWN(len - n, sizeof(ab));
  348. if (n2 > 0) {
  349. MG_INFO(("saving bulk, %lu", n2));
  350. ok = mg_flash_write(s + ofs + sizeof(ab), (char *) buf + n, n2);
  351. }
  352. if (ok && len > n) {
  353. size_t n3 = len - n - n2;
  354. if (n3 > sizeof(ab)) n3 = sizeof(ab);
  355. memset(ab, 0xff, sizeof(ab));
  356. memcpy(ab, (char *) buf + n + n2, n3);
  357. MG_INFO(("saving rest, %lu", n3));
  358. ok = mg_flash_write(s + ofs + sizeof(ab) + n2, ab, sizeof(ab));
  359. }
  360. }
  361. }
  362. MG_DEBUG(("Saved %lu/%lu bytes @ %p, key %x: %d", len, needed_aligned,
  363. s + ofs, key, ok));
  364. MG_DEBUG(("Sector space left: %lu bytes", ss - ofs - needed_aligned));
  365. } else {
  366. MG_ERROR(("Sector is full"));
  367. }
  368. }
  369. return ok;
  370. }
  371. #else
  372. bool mg_flash_save(void *sector, uint32_t key, const void *buf, size_t len) {
  373. (void) sector, (void) key, (void) buf, (void) len;
  374. return false;
  375. }
  376. bool mg_flash_load(void *sector, uint32_t key, void *buf, size_t len) {
  377. (void) sector, (void) key, (void) buf, (void) len;
  378. return false;
  379. }
  380. #endif
  381. #ifdef MG_ENABLE_LINES
  382. #line 1 "src/device_imxrt.c"
  383. #endif
  384. #if MG_DEVICE == MG_DEVICE_RT1020 || MG_DEVICE == MG_DEVICE_RT1060
  385. struct mg_flexspi_lut_seq {
  386. uint8_t seqNum;
  387. uint8_t seqId;
  388. uint16_t reserved;
  389. };
  390. struct mg_flexspi_mem_config {
  391. uint32_t tag;
  392. uint32_t version;
  393. uint32_t reserved0;
  394. uint8_t readSampleClkSrc;
  395. uint8_t csHoldTime;
  396. uint8_t csSetupTime;
  397. uint8_t columnAddressWidth;
  398. uint8_t deviceModeCfgEnable;
  399. uint8_t deviceModeType;
  400. uint16_t waitTimeCfgCommands;
  401. struct mg_flexspi_lut_seq deviceModeSeq;
  402. uint32_t deviceModeArg;
  403. uint8_t configCmdEnable;
  404. uint8_t configModeType[3];
  405. struct mg_flexspi_lut_seq configCmdSeqs[3];
  406. uint32_t reserved1;
  407. uint32_t configCmdArgs[3];
  408. uint32_t reserved2;
  409. uint32_t controllerMiscOption;
  410. uint8_t deviceType;
  411. uint8_t sflashPadType;
  412. uint8_t serialClkFreq;
  413. uint8_t lutCustomSeqEnable;
  414. uint32_t reserved3[2];
  415. uint32_t sflashA1Size;
  416. uint32_t sflashA2Size;
  417. uint32_t sflashB1Size;
  418. uint32_t sflashB2Size;
  419. uint32_t csPadSettingOverride;
  420. uint32_t sclkPadSettingOverride;
  421. uint32_t dataPadSettingOverride;
  422. uint32_t dqsPadSettingOverride;
  423. uint32_t timeoutInMs;
  424. uint32_t commandInterval;
  425. uint16_t dataValidTime[2];
  426. uint16_t busyOffset;
  427. uint16_t busyBitPolarity;
  428. uint32_t lookupTable[64];
  429. struct mg_flexspi_lut_seq lutCustomSeq[12];
  430. uint32_t reserved4[4];
  431. };
  432. struct mg_flexspi_nor_config {
  433. struct mg_flexspi_mem_config memConfig;
  434. uint32_t pageSize;
  435. uint32_t sectorSize;
  436. uint8_t ipcmdSerialClkFreq;
  437. uint8_t isUniformBlockSize;
  438. uint8_t reserved0[2];
  439. uint8_t serialNorType;
  440. uint8_t needExitNoCmdMode;
  441. uint8_t halfClkForNonReadCmd;
  442. uint8_t needRestoreNoCmdMode;
  443. uint32_t blockSize;
  444. uint32_t reserve2[11];
  445. };
  446. /* FLEXSPI memory config block related defintions */
  447. #define MG_FLEXSPI_CFG_BLK_TAG (0x42464346UL) // ascii "FCFB" Big Endian
  448. #define MG_FLEXSPI_CFG_BLK_VERSION (0x56010400UL) // V1.4.0
  449. #define MG_FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) \
  450. (MG_FLEXSPI_LUT_OPERAND0(op0) | MG_FLEXSPI_LUT_NUM_PADS0(pad0) | MG_FLEXSPI_LUT_OPCODE0(cmd0) | \
  451. MG_FLEXSPI_LUT_OPERAND1(op1) | MG_FLEXSPI_LUT_NUM_PADS1(pad1) | MG_FLEXSPI_LUT_OPCODE1(cmd1))
  452. #define MG_CMD_SDR 0x01
  453. #define MG_CMD_DDR 0x21
  454. #define MG_DUMMY_SDR 0x0C
  455. #define MG_DUMMY_DDR 0x2C
  456. #define MG_RADDR_SDR 0x02
  457. #define MG_RADDR_DDR 0x22
  458. #define MG_READ_SDR 0x09
  459. #define MG_READ_DDR 0x29
  460. #define MG_WRITE_SDR 0x08
  461. #define MG_WRITE_DDR 0x28
  462. #define MG_STOP 0
  463. #define MG_FLEXSPI_1PAD 0
  464. #define MG_FLEXSPI_2PAD 1
  465. #define MG_FLEXSPI_4PAD 2
  466. #define MG_FLEXSPI_8PAD 3
  467. #define MG_FLEXSPI_QSPI_LUT \
  468. { \
  469. [0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0xEB, MG_RADDR_SDR, MG_FLEXSPI_4PAD, \
  470. 0x18), \
  471. [1] = MG_FLEXSPI_LUT_SEQ(MG_DUMMY_SDR, MG_FLEXSPI_4PAD, 0x06, MG_READ_SDR, MG_FLEXSPI_4PAD, \
  472. 0x04), \
  473. [4 * 1 + 0] = \
  474. MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x05, MG_READ_SDR, MG_FLEXSPI_1PAD, 0x04), \
  475. [4 * 3 + 0] = \
  476. MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x06, MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  477. [4 * 5 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x20, MG_RADDR_SDR, \
  478. MG_FLEXSPI_1PAD, 0x18), \
  479. [4 * 8 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0xD8, MG_RADDR_SDR, \
  480. MG_FLEXSPI_1PAD, 0x18), \
  481. [4 * 9 + 0] = MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x02, MG_RADDR_SDR, \
  482. MG_FLEXSPI_1PAD, 0x18), \
  483. [4 * 9 + 1] = \
  484. MG_FLEXSPI_LUT_SEQ(MG_WRITE_SDR, MG_FLEXSPI_1PAD, 0x04, MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  485. [4 * 11 + 0] = \
  486. MG_FLEXSPI_LUT_SEQ(MG_CMD_SDR, MG_FLEXSPI_1PAD, 0x60, MG_STOP, MG_FLEXSPI_1PAD, 0x0), \
  487. }
  488. #define MG_FLEXSPI_LUT_OPERAND0(x) (((uint32_t) (((uint32_t) (x)))) & 0xFFU)
  489. #define MG_FLEXSPI_LUT_NUM_PADS0(x) (((uint32_t) (((uint32_t) (x)) << 8U)) & 0x300U)
  490. #define MG_FLEXSPI_LUT_OPCODE0(x) (((uint32_t) (((uint32_t) (x)) << 10U)) & 0xFC00U)
  491. #define MG_FLEXSPI_LUT_OPERAND1(x) (((uint32_t) (((uint32_t) (x)) << 16U)) & 0xFF0000U)
  492. #define MG_FLEXSPI_LUT_NUM_PADS1(x) (((uint32_t) (((uint32_t) (x)) << 24U)) & 0x3000000U)
  493. #define MG_FLEXSPI_LUT_OPCODE1(x) (((uint32_t) (((uint32_t) (x)) << 26U)) & 0xFC000000U)
  494. #define FLEXSPI_NOR_INSTANCE 0
  495. #if MG_DEVICE == MG_DEVICE_RT1020
  496. struct mg_flexspi_nor_driver_interface {
  497. uint32_t version;
  498. int (*init)(uint32_t instance, struct mg_flexspi_nor_config *config);
  499. int (*program)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t dst_addr,
  500. const uint32_t *src);
  501. uint32_t reserved;
  502. int (*erase)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t start,
  503. uint32_t lengthInBytes);
  504. uint32_t reserved2;
  505. int (*update_lut)(uint32_t instance, uint32_t seqIndex, const uint32_t *lutBase,
  506. uint32_t seqNumber);
  507. int (*xfer)(uint32_t instance, char *xfer);
  508. void (*clear_cache)(uint32_t instance);
  509. };
  510. #elif MG_DEVICE == MG_DEVICE_RT1060
  511. struct mg_flexspi_nor_driver_interface {
  512. uint32_t version;
  513. int (*init)(uint32_t instance, struct mg_flexspi_nor_config *config);
  514. int (*program)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t dst_addr,
  515. const uint32_t *src);
  516. int (*erase_all)(uint32_t instance, struct mg_flexspi_nor_config *config);
  517. int (*erase)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t start,
  518. uint32_t lengthInBytes);
  519. int (*read)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t *dst, uint32_t addr,
  520. uint32_t lengthInBytes);
  521. void (*clear_cache)(uint32_t instance);
  522. int (*xfer)(uint32_t instance, char *xfer);
  523. int (*update_lut)(uint32_t instance, uint32_t seqIndex, const uint32_t *lutBase,
  524. uint32_t seqNumber);
  525. int (*get_config)(uint32_t instance, struct mg_flexspi_nor_config *config, uint32_t *option);
  526. };
  527. #endif
  528. #define flexspi_nor (*((struct mg_flexspi_nor_driver_interface**) \
  529. (*(uint32_t*)0x0020001c + 16)))
  530. static bool s_flash_irq_disabled;
  531. MG_IRAM void *mg_flash_start(void) {
  532. return (void *) 0x60000000;
  533. }
  534. MG_IRAM size_t mg_flash_size(void) {
  535. return 8 * 1024 * 1024;
  536. }
  537. MG_IRAM size_t mg_flash_sector_size(void) {
  538. return 4 * 1024; // 4k
  539. }
  540. MG_IRAM size_t mg_flash_write_align(void) {
  541. return 256;
  542. }
  543. MG_IRAM int mg_flash_bank(void) {
  544. return 0;
  545. }
  546. MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
  547. char *base = (char *) mg_flash_start(), *end = base + mg_flash_size();
  548. volatile char *p = (char *) dst;
  549. return p >= base && p < end && ((p - base) % mg_flash_sector_size()) == 0;
  550. }
  551. // Note: the get_config function below works both for RT1020 and 1060
  552. #if MG_DEVICE == MG_DEVICE_RT1020
  553. MG_IRAM static int flexspi_nor_get_config(struct mg_flexspi_nor_config *config) {
  554. struct mg_flexspi_nor_config default_config = {
  555. .memConfig = {.tag = MG_FLEXSPI_CFG_BLK_TAG,
  556. .version = MG_FLEXSPI_CFG_BLK_VERSION,
  557. .readSampleClkSrc = 1, // ReadSampleClk_LoopbackFromDqsPad
  558. .csHoldTime = 3,
  559. .csSetupTime = 3,
  560. .controllerMiscOption = MG_BIT(4),
  561. .deviceType = 1, // serial NOR
  562. .sflashPadType = 4,
  563. .serialClkFreq = 7, // 133MHz
  564. .sflashA1Size = 8 * 1024 * 1024,
  565. .lookupTable = MG_FLEXSPI_QSPI_LUT},
  566. .pageSize = 256,
  567. .sectorSize = 4 * 1024,
  568. .ipcmdSerialClkFreq = 1,
  569. .blockSize = 64 * 1024,
  570. .isUniformBlockSize = false};
  571. *config = default_config;
  572. return 0;
  573. }
  574. #else
  575. MG_IRAM static int flexspi_nor_get_config(struct mg_flexspi_nor_config *config) {
  576. uint32_t options[] = {0xc0000000, 0x00};
  577. MG_ARM_DISABLE_IRQ();
  578. uint32_t status =
  579. flexspi_nor->get_config(FLEXSPI_NOR_INSTANCE, config, options);
  580. if (!s_flash_irq_disabled) {
  581. MG_ARM_ENABLE_IRQ();
  582. }
  583. if (status) {
  584. MG_ERROR(("Failed to extract flash configuration: status %u", status));
  585. }
  586. return status;
  587. }
  588. #endif
  589. MG_IRAM bool mg_flash_erase(void *addr) {
  590. struct mg_flexspi_nor_config config;
  591. if (flexspi_nor_get_config(&config) != 0) {
  592. return false;
  593. }
  594. if (flash_page_start(addr) == false) {
  595. MG_ERROR(("%p is not on a sector boundary", addr));
  596. return false;
  597. }
  598. void *dst = (void *)((char *) addr - (char *) mg_flash_start());
  599. // Note: Interrupts must be disabled before any call to the ROM API on RT1020
  600. // and 1060
  601. MG_ARM_DISABLE_IRQ();
  602. bool ok = (flexspi_nor->erase(FLEXSPI_NOR_INSTANCE, &config, (uint32_t) dst,
  603. mg_flash_sector_size()) == 0);
  604. if (!s_flash_irq_disabled) {
  605. MG_ARM_ENABLE_IRQ(); // Reenable them after the call
  606. }
  607. MG_DEBUG(("Sector starting at %p erasure: %s", addr, ok ? "ok" : "fail"));
  608. return ok;
  609. }
  610. MG_IRAM bool mg_flash_swap_bank(void) {
  611. return true;
  612. }
  613. static inline void spin(volatile uint32_t count) {
  614. while (count--) (void) 0;
  615. }
  616. static inline void flash_wait(void) {
  617. while ((*((volatile uint32_t *)(0x402A8000 + 0xE0)) & MG_BIT(1)) == 0)
  618. spin(1);
  619. }
  620. MG_IRAM static void *flash_code_location(void) {
  621. return (void *) ((char *) mg_flash_start() + 0x2000);
  622. }
  623. MG_IRAM bool mg_flash_write(void *addr, const void *buf, size_t len) {
  624. struct mg_flexspi_nor_config config;
  625. if (flexspi_nor_get_config(&config) != 0) {
  626. return false;
  627. }
  628. if ((len % mg_flash_write_align()) != 0) {
  629. MG_ERROR(("%lu is not aligned to %lu", len, mg_flash_write_align()));
  630. return false;
  631. }
  632. if ((char *) addr < (char *) mg_flash_start()) {
  633. MG_ERROR(("Invalid flash write address: %p", addr));
  634. return false;
  635. }
  636. uint32_t *dst = (uint32_t *) addr;
  637. uint32_t *src = (uint32_t *) buf;
  638. uint32_t *end = (uint32_t *) ((char *) buf + len);
  639. bool ok = true;
  640. // Note: If we overwrite the flash irq section of the image, we must also
  641. // make sure interrupts are disabled and are not reenabled until we write
  642. // this sector with another irq table.
  643. if ((char *) addr == (char *) flash_code_location()) {
  644. s_flash_irq_disabled = true;
  645. MG_ARM_DISABLE_IRQ();
  646. }
  647. while (ok && src < end) {
  648. if (flash_page_start(dst) && mg_flash_erase(dst) == false) {
  649. break;
  650. }
  651. uint32_t status;
  652. uint32_t dst_ofs = (uint32_t) dst - (uint32_t) mg_flash_start();
  653. if ((char *) buf >= (char *) mg_flash_start()) {
  654. // If we copy from FLASH to FLASH, then we first need to copy the source
  655. // to RAM
  656. size_t tmp_buf_size = mg_flash_write_align() / sizeof(uint32_t);
  657. uint32_t tmp[tmp_buf_size];
  658. for (size_t i = 0; i < tmp_buf_size; i++) {
  659. flash_wait();
  660. tmp[i] = src[i];
  661. }
  662. MG_ARM_DISABLE_IRQ();
  663. status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, &config,
  664. (uint32_t) dst_ofs, tmp);
  665. } else {
  666. MG_ARM_DISABLE_IRQ();
  667. status = flexspi_nor->program(FLEXSPI_NOR_INSTANCE, &config,
  668. (uint32_t) dst_ofs, src);
  669. }
  670. if (!s_flash_irq_disabled) {
  671. MG_ARM_ENABLE_IRQ();
  672. }
  673. src = (uint32_t *) ((char *) src + mg_flash_write_align());
  674. dst = (uint32_t *) ((char *) dst + mg_flash_write_align());
  675. if (status != 0) {
  676. ok = false;
  677. }
  678. }
  679. MG_DEBUG(("Flash write %lu bytes @ %p: %s.", len, dst, ok ? "ok" : "fail"));
  680. return ok;
  681. }
  682. MG_IRAM void mg_device_reset(void) {
  683. MG_DEBUG(("Resetting device..."));
  684. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  685. }
  686. #endif
  687. #ifdef MG_ENABLE_LINES
  688. #line 1 "src/device_stm32h5.c"
  689. #endif
  690. #if MG_DEVICE == MG_DEVICE_STM32H5
  691. #define FLASH_BASE 0x40022000 // Base address of the flash controller
  692. #define FLASH_KEYR (FLASH_BASE + 0x4) // See RM0481 7.11
  693. #define FLASH_OPTKEYR (FLASH_BASE + 0xc)
  694. #define FLASH_OPTCR (FLASH_BASE + 0x1c)
  695. #define FLASH_NSSR (FLASH_BASE + 0x20)
  696. #define FLASH_NSCR (FLASH_BASE + 0x28)
  697. #define FLASH_NSCCR (FLASH_BASE + 0x30)
  698. #define FLASH_OPTSR_CUR (FLASH_BASE + 0x50)
  699. #define FLASH_OPTSR_PRG (FLASH_BASE + 0x54)
  700. void *mg_flash_start(void) {
  701. return (void *) 0x08000000;
  702. }
  703. size_t mg_flash_size(void) {
  704. return 2 * 1024 * 1024; // 2Mb
  705. }
  706. size_t mg_flash_sector_size(void) {
  707. return 8 * 1024; // 8k
  708. }
  709. size_t mg_flash_write_align(void) {
  710. return 16; // 128 bit
  711. }
  712. int mg_flash_bank(void) {
  713. return MG_REG(FLASH_OPTCR) & MG_BIT(31) ? 2 : 1;
  714. }
  715. static void flash_unlock(void) {
  716. static bool unlocked = false;
  717. if (unlocked == false) {
  718. MG_REG(FLASH_KEYR) = 0x45670123;
  719. MG_REG(FLASH_KEYR) = 0Xcdef89ab;
  720. MG_REG(FLASH_OPTKEYR) = 0x08192a3b;
  721. MG_REG(FLASH_OPTKEYR) = 0x4c5d6e7f;
  722. unlocked = true;
  723. }
  724. }
  725. static int flash_page_start(volatile uint32_t *dst) {
  726. char *base = (char *) mg_flash_start(), *end = base + mg_flash_size();
  727. volatile char *p = (char *) dst;
  728. return p >= base && p < end && ((p - base) % mg_flash_sector_size()) == 0;
  729. }
  730. static bool flash_is_err(void) {
  731. return MG_REG(FLASH_NSSR) & ((MG_BIT(8) - 1) << 17); // RM0481 7.11.9
  732. }
  733. static void flash_wait(void) {
  734. while ((MG_REG(FLASH_NSSR) & MG_BIT(0)) &&
  735. (MG_REG(FLASH_NSSR) & MG_BIT(16)) == 0) {
  736. (void) 0;
  737. }
  738. }
  739. static void flash_clear_err(void) {
  740. flash_wait(); // Wait until ready
  741. MG_REG(FLASH_NSCCR) = ((MG_BIT(9) - 1) << 16U); // Clear all errors
  742. }
  743. static bool flash_bank_is_swapped(void) {
  744. return MG_REG(FLASH_OPTCR) & MG_BIT(31); // RM0481 7.11.8
  745. }
  746. bool mg_flash_erase(void *location) {
  747. bool ok = false;
  748. if (flash_page_start(location) == false) {
  749. MG_ERROR(("%p is not on a sector boundary"));
  750. } else {
  751. uintptr_t diff = (char *) location - (char *) mg_flash_start();
  752. uint32_t sector = diff / mg_flash_sector_size();
  753. uint32_t saved_cr = MG_REG(FLASH_NSCR); // Save CR value
  754. flash_unlock();
  755. flash_clear_err();
  756. MG_REG(FLASH_NSCR) = 0;
  757. if ((sector < 128 && flash_bank_is_swapped()) ||
  758. (sector > 127 && !flash_bank_is_swapped())) {
  759. MG_REG(FLASH_NSCR) |= MG_BIT(31); // Set FLASH_CR_BKSEL
  760. }
  761. if (sector > 127) sector -= 128;
  762. MG_REG(FLASH_NSCR) |= MG_BIT(2) | (sector << 6); // Erase | sector_num
  763. MG_REG(FLASH_NSCR) |= MG_BIT(5); // Start erasing
  764. flash_wait();
  765. ok = !flash_is_err();
  766. MG_DEBUG(("Erase sector %lu @ %p: %s. CR %#lx SR %#lx", sector, location,
  767. ok ? "ok" : "fail", MG_REG(FLASH_NSCR), MG_REG(FLASH_NSSR)));
  768. // mg_hexdump(location, 32);
  769. MG_REG(FLASH_NSCR) = saved_cr; // Restore saved CR
  770. }
  771. return ok;
  772. }
  773. bool mg_flash_swap_bank(void) {
  774. uint32_t desired = flash_bank_is_swapped() ? 0 : MG_BIT(31);
  775. flash_unlock();
  776. flash_clear_err();
  777. // printf("OPTSR_PRG 1 %#lx\n", FLASH->OPTSR_PRG);
  778. MG_SET_BITS(MG_REG(FLASH_OPTSR_PRG), MG_BIT(31), desired);
  779. // printf("OPTSR_PRG 2 %#lx\n", FLASH->OPTSR_PRG);
  780. MG_REG(FLASH_OPTCR) |= MG_BIT(1); // OPTSTART
  781. while ((MG_REG(FLASH_OPTSR_CUR) & MG_BIT(31)) != desired) (void) 0;
  782. return true;
  783. }
  784. bool mg_flash_write(void *addr, const void *buf, size_t len) {
  785. if ((len % mg_flash_write_align()) != 0) {
  786. MG_ERROR(("%lu is not aligned to %lu", len, mg_flash_write_align()));
  787. return false;
  788. }
  789. uint32_t *dst = (uint32_t *) addr;
  790. uint32_t *src = (uint32_t *) buf;
  791. uint32_t *end = (uint32_t *) ((char *) buf + len);
  792. bool ok = true;
  793. flash_unlock();
  794. flash_clear_err();
  795. MG_ARM_DISABLE_IRQ();
  796. // MG_DEBUG(("Starting flash write %lu bytes @ %p", len, addr));
  797. MG_REG(FLASH_NSCR) = MG_BIT(1); // Set programming flag
  798. while (ok && src < end) {
  799. if (flash_page_start(dst) && mg_flash_erase(dst) == false) break;
  800. *(volatile uint32_t *) dst++ = *src++;
  801. flash_wait();
  802. if (flash_is_err()) ok = false;
  803. }
  804. MG_ARM_ENABLE_IRQ();
  805. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  806. flash_is_err() ? "fail" : "ok", MG_REG(FLASH_NSCR),
  807. MG_REG(FLASH_NSSR)));
  808. MG_REG(FLASH_NSCR) = 0; // Clear flags
  809. return ok;
  810. }
  811. void mg_device_reset(void) {
  812. // SCB->AIRCR = ((0x5fa << SCB_AIRCR_VECTKEY_Pos)|SCB_AIRCR_SYSRESETREQ_Msk);
  813. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  814. }
  815. #endif
  816. #ifdef MG_ENABLE_LINES
  817. #line 1 "src/device_stm32h7.c"
  818. #endif
  819. #if MG_DEVICE == MG_DEVICE_STM32H7
  820. #define FLASH_BASE1 0x52002000 // Base address for bank1
  821. #define FLASH_BASE2 0x52002100 // Base address for bank2
  822. #define FLASH_KEYR 0x04 // See RM0433 4.9.2
  823. #define FLASH_OPTKEYR 0x08
  824. #define FLASH_OPTCR 0x18
  825. #define FLASH_SR 0x10
  826. #define FLASH_CR 0x0c
  827. #define FLASH_CCR 0x14
  828. #define FLASH_OPTSR_CUR 0x1c
  829. #define FLASH_OPTSR_PRG 0x20
  830. #define FLASH_SIZE_REG 0x1ff1e880
  831. MG_IRAM void *mg_flash_start(void) {
  832. return (void *) 0x08000000;
  833. }
  834. MG_IRAM size_t mg_flash_size(void) {
  835. return MG_REG(FLASH_SIZE_REG) * 1024;
  836. }
  837. MG_IRAM size_t mg_flash_sector_size(void) {
  838. return 128 * 1024; // 128k
  839. }
  840. MG_IRAM size_t mg_flash_write_align(void) {
  841. return 32; // 256 bit
  842. }
  843. MG_IRAM int mg_flash_bank(void) {
  844. if (mg_flash_size() < 2 * 1024 * 1024) return 0; // No dual bank support
  845. return MG_REG(FLASH_BASE1 + FLASH_OPTCR) & MG_BIT(31) ? 2 : 1;
  846. }
  847. MG_IRAM static void flash_unlock(void) {
  848. static bool unlocked = false;
  849. if (unlocked == false) {
  850. MG_REG(FLASH_BASE1 + FLASH_KEYR) = 0x45670123;
  851. MG_REG(FLASH_BASE1 + FLASH_KEYR) = 0xcdef89ab;
  852. if (mg_flash_bank() > 0) {
  853. MG_REG(FLASH_BASE2 + FLASH_KEYR) = 0x45670123;
  854. MG_REG(FLASH_BASE2 + FLASH_KEYR) = 0xcdef89ab;
  855. }
  856. MG_REG(FLASH_BASE1 + FLASH_OPTKEYR) = 0x08192a3b; // opt reg is "shared"
  857. MG_REG(FLASH_BASE1 + FLASH_OPTKEYR) = 0x4c5d6e7f; // thus unlock once
  858. unlocked = true;
  859. }
  860. }
  861. MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
  862. char *base = (char *) mg_flash_start(), *end = base + mg_flash_size();
  863. volatile char *p = (char *) dst;
  864. return p >= base && p < end && ((p - base) % mg_flash_sector_size()) == 0;
  865. }
  866. MG_IRAM static bool flash_is_err(uint32_t bank) {
  867. return MG_REG(bank + FLASH_SR) & ((MG_BIT(11) - 1) << 17); // RM0433 4.9.5
  868. }
  869. MG_IRAM static void flash_wait(uint32_t bank) {
  870. while (MG_REG(bank + FLASH_SR) & (MG_BIT(0) | MG_BIT(2))) (void) 0;
  871. }
  872. MG_IRAM static void flash_clear_err(uint32_t bank) {
  873. flash_wait(bank); // Wait until ready
  874. MG_REG(bank + FLASH_CCR) = ((MG_BIT(11) - 1) << 16U); // Clear all errors
  875. }
  876. MG_IRAM static bool flash_bank_is_swapped(uint32_t bank) {
  877. return MG_REG(bank + FLASH_OPTCR) & MG_BIT(31); // RM0433 4.9.7
  878. }
  879. // Figure out flash bank based on the address
  880. MG_IRAM static uint32_t flash_bank(void *addr) {
  881. size_t ofs = (char *) addr - (char *) mg_flash_start();
  882. if (mg_flash_bank() == 0) return FLASH_BASE1;
  883. return ofs < mg_flash_size() / 2 ? FLASH_BASE1 : FLASH_BASE2;
  884. }
  885. MG_IRAM bool mg_flash_erase(void *addr) {
  886. bool ok = false;
  887. if (flash_page_start(addr) == false) {
  888. MG_ERROR(("%p is not on a sector boundary", addr));
  889. } else {
  890. uintptr_t diff = (char *) addr - (char *) mg_flash_start();
  891. uint32_t sector = diff / mg_flash_sector_size();
  892. uint32_t bank = flash_bank(addr);
  893. uint32_t saved_cr = MG_REG(bank + FLASH_CR); // Save CR value
  894. flash_unlock();
  895. if (sector > 7) sector -= 8;
  896. flash_clear_err(bank);
  897. MG_REG(bank + FLASH_CR) = MG_BIT(5); // 32-bit write parallelism
  898. MG_REG(bank + FLASH_CR) |= (sector & 7U) << 8U; // Sector to erase
  899. MG_REG(bank + FLASH_CR) |= MG_BIT(2); // Sector erase bit
  900. MG_REG(bank + FLASH_CR) |= MG_BIT(7); // Start erasing
  901. ok = !flash_is_err(bank);
  902. MG_DEBUG(("Erase sector %lu @ %p %s. CR %#lx SR %#lx", sector, addr,
  903. ok ? "ok" : "fail", MG_REG(bank + FLASH_CR),
  904. MG_REG(bank + FLASH_SR)));
  905. MG_REG(bank + FLASH_CR) = saved_cr; // Restore CR
  906. }
  907. return ok;
  908. }
  909. MG_IRAM bool mg_flash_swap_bank(void) {
  910. if (mg_flash_bank() == 0) return true;
  911. uint32_t bank = FLASH_BASE1;
  912. uint32_t desired = flash_bank_is_swapped(bank) ? 0 : MG_BIT(31);
  913. flash_unlock();
  914. flash_clear_err(bank);
  915. // printf("OPTSR_PRG 1 %#lx\n", FLASH->OPTSR_PRG);
  916. MG_SET_BITS(MG_REG(bank + FLASH_OPTSR_PRG), MG_BIT(31), desired);
  917. // printf("OPTSR_PRG 2 %#lx\n", FLASH->OPTSR_PRG);
  918. MG_REG(bank + FLASH_OPTCR) |= MG_BIT(1); // OPTSTART
  919. while ((MG_REG(bank + FLASH_OPTSR_CUR) & MG_BIT(31)) != desired) (void) 0;
  920. return true;
  921. }
  922. MG_IRAM bool mg_flash_write(void *addr, const void *buf, size_t len) {
  923. if ((len % mg_flash_write_align()) != 0) {
  924. MG_ERROR(("%lu is not aligned to %lu", len, mg_flash_write_align()));
  925. return false;
  926. }
  927. uint32_t bank = flash_bank(addr);
  928. uint32_t *dst = (uint32_t *) addr;
  929. uint32_t *src = (uint32_t *) buf;
  930. uint32_t *end = (uint32_t *) ((char *) buf + len);
  931. bool ok = true;
  932. flash_unlock();
  933. flash_clear_err(bank);
  934. MG_REG(bank + FLASH_CR) = MG_BIT(1); // Set programming flag
  935. MG_REG(bank + FLASH_CR) |= MG_BIT(5); // 32-bit write parallelism
  936. MG_DEBUG(("Writing flash @ %p, %lu bytes", addr, len));
  937. MG_ARM_DISABLE_IRQ();
  938. while (ok && src < end) {
  939. if (flash_page_start(dst) && mg_flash_erase(dst) == false) break;
  940. *(volatile uint32_t *) dst++ = *src++;
  941. flash_wait(bank);
  942. if (flash_is_err(bank)) ok = false;
  943. }
  944. MG_ARM_ENABLE_IRQ();
  945. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  946. ok ? "ok" : "fail", MG_REG(bank + FLASH_CR),
  947. MG_REG(bank + FLASH_SR)));
  948. MG_REG(bank + FLASH_CR) &= ~MG_BIT(1); // Clear programming flag
  949. return ok;
  950. }
  951. MG_IRAM void mg_device_reset(void) {
  952. // SCB->AIRCR = ((0x5fa << SCB_AIRCR_VECTKEY_Pos)|SCB_AIRCR_SYSRESETREQ_Msk);
  953. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  954. }
  955. #endif
  956. #ifdef MG_ENABLE_LINES
  957. #line 1 "src/dns.c"
  958. #endif
  959. struct dns_data {
  960. struct dns_data *next;
  961. struct mg_connection *c;
  962. uint64_t expire;
  963. uint16_t txnid;
  964. };
  965. static void mg_sendnsreq(struct mg_connection *, struct mg_str *, int,
  966. struct mg_dns *, bool);
  967. static void mg_dns_free(struct dns_data **head, struct dns_data *d) {
  968. LIST_DELETE(struct dns_data, head, d);
  969. free(d);
  970. }
  971. void mg_resolve_cancel(struct mg_connection *c) {
  972. struct dns_data *tmp, *d;
  973. struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests;
  974. for (d = *head; d != NULL; d = tmp) {
  975. tmp = d->next;
  976. if (d->c == c) mg_dns_free(head, d);
  977. }
  978. }
  979. static size_t mg_dns_parse_name_depth(const uint8_t *s, size_t len, size_t ofs,
  980. char *to, size_t tolen, size_t j,
  981. int depth) {
  982. size_t i = 0;
  983. if (tolen > 0 && depth == 0) to[0] = '\0';
  984. if (depth > 5) return 0;
  985. // MG_INFO(("ofs %lx %x %x", (unsigned long) ofs, s[ofs], s[ofs + 1]));
  986. while (ofs + i + 1 < len) {
  987. size_t n = s[ofs + i];
  988. if (n == 0) {
  989. i++;
  990. break;
  991. }
  992. if (n & 0xc0) {
  993. size_t ptr = (((n & 0x3f) << 8) | s[ofs + i + 1]); // 12 is hdr len
  994. // MG_INFO(("PTR %lx", (unsigned long) ptr));
  995. if (ptr + 1 < len && (s[ptr] & 0xc0) == 0 &&
  996. mg_dns_parse_name_depth(s, len, ptr, to, tolen, j, depth + 1) == 0)
  997. return 0;
  998. i += 2;
  999. break;
  1000. }
  1001. if (ofs + i + n + 1 >= len) return 0;
  1002. if (j > 0) {
  1003. if (j < tolen) to[j] = '.';
  1004. j++;
  1005. }
  1006. if (j + n < tolen) memcpy(&to[j], &s[ofs + i + 1], n);
  1007. j += n;
  1008. i += n + 1;
  1009. if (j < tolen) to[j] = '\0'; // Zero-terminate this chunk
  1010. // MG_INFO(("--> [%s]", to));
  1011. }
  1012. if (tolen > 0) to[tolen - 1] = '\0'; // Make sure make sure it is nul-term
  1013. return i;
  1014. }
  1015. static size_t mg_dns_parse_name(const uint8_t *s, size_t n, size_t ofs,
  1016. char *dst, size_t dstlen) {
  1017. return mg_dns_parse_name_depth(s, n, ofs, dst, dstlen, 0, 0);
  1018. }
  1019. size_t mg_dns_parse_rr(const uint8_t *buf, size_t len, size_t ofs,
  1020. bool is_question, struct mg_dns_rr *rr) {
  1021. const uint8_t *s = buf + ofs, *e = &buf[len];
  1022. memset(rr, 0, sizeof(*rr));
  1023. if (len < sizeof(struct mg_dns_header)) return 0; // Too small
  1024. if (len > 512) return 0; // Too large, we don't expect that
  1025. if (s >= e) return 0; // Overflow
  1026. if ((rr->nlen = (uint16_t) mg_dns_parse_name(buf, len, ofs, NULL, 0)) == 0)
  1027. return 0;
  1028. s += rr->nlen + 4;
  1029. if (s > e) return 0;
  1030. rr->atype = (uint16_t) (((uint16_t) s[-4] << 8) | s[-3]);
  1031. rr->aclass = (uint16_t) (((uint16_t) s[-2] << 8) | s[-1]);
  1032. if (is_question) return (size_t) (rr->nlen + 4);
  1033. s += 6;
  1034. if (s > e) return 0;
  1035. rr->alen = (uint16_t) (((uint16_t) s[-2] << 8) | s[-1]);
  1036. if (s + rr->alen > e) return 0;
  1037. return (size_t) (rr->nlen + rr->alen + 10);
  1038. }
  1039. bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) {
  1040. const struct mg_dns_header *h = (struct mg_dns_header *) buf;
  1041. struct mg_dns_rr rr;
  1042. size_t i, n, num_answers, ofs = sizeof(*h);
  1043. memset(dm, 0, sizeof(*dm));
  1044. if (len < sizeof(*h)) return 0; // Too small, headers dont fit
  1045. if (mg_ntohs(h->num_questions) > 1) return 0; // Sanity
  1046. num_answers = mg_ntohs(h->num_answers);
  1047. if (num_answers > 10) {
  1048. MG_DEBUG(("Got %u answers, ignoring beyond 10th one", num_answers));
  1049. num_answers = 10; // Sanity cap
  1050. }
  1051. dm->txnid = mg_ntohs(h->txnid);
  1052. for (i = 0; i < mg_ntohs(h->num_questions); i++) {
  1053. if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false;
  1054. // MG_INFO(("Q %lu %lu %hu/%hu", ofs, n, rr.atype, rr.aclass));
  1055. ofs += n;
  1056. }
  1057. for (i = 0; i < num_answers; i++) {
  1058. if ((n = mg_dns_parse_rr(buf, len, ofs, false, &rr)) == 0) return false;
  1059. // MG_INFO(("A -- %lu %lu %hu/%hu %s", ofs, n, rr.atype, rr.aclass,
  1060. // dm->name));
  1061. mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name));
  1062. ofs += n;
  1063. if (rr.alen == 4 && rr.atype == 1 && rr.aclass == 1) {
  1064. dm->addr.is_ip6 = false;
  1065. memcpy(&dm->addr.ip, &buf[ofs - 4], 4);
  1066. dm->resolved = true;
  1067. break; // Return success
  1068. } else if (rr.alen == 16 && rr.atype == 28 && rr.aclass == 1) {
  1069. dm->addr.is_ip6 = true;
  1070. memcpy(&dm->addr.ip, &buf[ofs - 16], 16);
  1071. dm->resolved = true;
  1072. break; // Return success
  1073. }
  1074. }
  1075. return true;
  1076. }
  1077. static void dns_cb(struct mg_connection *c, int ev, void *ev_data) {
  1078. struct dns_data *d, *tmp;
  1079. struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests;
  1080. if (ev == MG_EV_POLL) {
  1081. uint64_t now = *(uint64_t *) ev_data;
  1082. for (d = *head; d != NULL; d = tmp) {
  1083. tmp = d->next;
  1084. // MG_DEBUG ("%lu %lu dns poll", d->expire, now));
  1085. if (now > d->expire) mg_error(d->c, "DNS timeout");
  1086. }
  1087. } else if (ev == MG_EV_READ) {
  1088. struct mg_dns_message dm;
  1089. int resolved = 0;
  1090. if (mg_dns_parse(c->recv.buf, c->recv.len, &dm) == false) {
  1091. MG_ERROR(("Unexpected DNS response:"));
  1092. mg_hexdump(c->recv.buf, c->recv.len);
  1093. } else {
  1094. // MG_VERBOSE(("%s %d", dm.name, dm.resolved));
  1095. for (d = *head; d != NULL; d = tmp) {
  1096. tmp = d->next;
  1097. // MG_INFO(("d %p %hu %hu", d, d->txnid, dm.txnid));
  1098. if (dm.txnid != d->txnid) continue;
  1099. if (d->c->is_resolving) {
  1100. if (dm.resolved) {
  1101. dm.addr.port = d->c->rem.port; // Save port
  1102. d->c->rem = dm.addr; // Copy resolved address
  1103. MG_DEBUG(
  1104. ("%lu %s is %M", d->c->id, dm.name, mg_print_ip, &d->c->rem));
  1105. mg_connect_resolved(d->c);
  1106. #if MG_ENABLE_IPV6
  1107. } else if (dm.addr.is_ip6 == false && dm.name[0] != '\0' &&
  1108. c->mgr->use_dns6 == false) {
  1109. struct mg_str x = mg_str(dm.name);
  1110. mg_sendnsreq(d->c, &x, c->mgr->dnstimeout, &c->mgr->dns6, true);
  1111. #endif
  1112. } else {
  1113. mg_error(d->c, "%s DNS lookup failed", dm.name);
  1114. }
  1115. } else {
  1116. MG_ERROR(("%lu already resolved", d->c->id));
  1117. }
  1118. mg_dns_free(head, d);
  1119. resolved = 1;
  1120. }
  1121. }
  1122. if (!resolved) MG_ERROR(("stray DNS reply"));
  1123. c->recv.len = 0;
  1124. } else if (ev == MG_EV_CLOSE) {
  1125. for (d = *head; d != NULL; d = tmp) {
  1126. tmp = d->next;
  1127. mg_error(d->c, "DNS error");
  1128. mg_dns_free(head, d);
  1129. }
  1130. }
  1131. }
  1132. static bool mg_dns_send(struct mg_connection *c, const struct mg_str *name,
  1133. uint16_t txnid, bool ipv6) {
  1134. struct {
  1135. struct mg_dns_header header;
  1136. uint8_t data[256];
  1137. } pkt;
  1138. size_t i, n;
  1139. memset(&pkt, 0, sizeof(pkt));
  1140. pkt.header.txnid = mg_htons(txnid);
  1141. pkt.header.flags = mg_htons(0x100);
  1142. pkt.header.num_questions = mg_htons(1);
  1143. for (i = n = 0; i < sizeof(pkt.data) - 5; i++) {
  1144. if (name->buf[i] == '.' || i >= name->len) {
  1145. pkt.data[n] = (uint8_t) (i - n);
  1146. memcpy(&pkt.data[n + 1], name->buf + n, i - n);
  1147. n = i + 1;
  1148. }
  1149. if (i >= name->len) break;
  1150. }
  1151. memcpy(&pkt.data[n], "\x00\x00\x01\x00\x01", 5); // A query
  1152. n += 5;
  1153. if (ipv6) pkt.data[n - 3] = 0x1c; // AAAA query
  1154. // memcpy(&pkt.data[n], "\xc0\x0c\x00\x1c\x00\x01", 6); // AAAA query
  1155. // n += 6;
  1156. return mg_send(c, &pkt, sizeof(pkt.header) + n);
  1157. }
  1158. static void mg_sendnsreq(struct mg_connection *c, struct mg_str *name, int ms,
  1159. struct mg_dns *dnsc, bool ipv6) {
  1160. struct dns_data *d = NULL;
  1161. if (dnsc->url == NULL) {
  1162. mg_error(c, "DNS server URL is NULL. Call mg_mgr_init()");
  1163. } else if (dnsc->c == NULL) {
  1164. dnsc->c = mg_connect(c->mgr, dnsc->url, NULL, NULL);
  1165. if (dnsc->c != NULL) {
  1166. dnsc->c->pfn = dns_cb;
  1167. // dnsc->c->is_hexdumping = 1;
  1168. }
  1169. }
  1170. if (dnsc->c == NULL) {
  1171. mg_error(c, "resolver");
  1172. } else if ((d = (struct dns_data *) calloc(1, sizeof(*d))) == NULL) {
  1173. mg_error(c, "resolve OOM");
  1174. } else {
  1175. struct dns_data *reqs = (struct dns_data *) c->mgr->active_dns_requests;
  1176. d->txnid = reqs ? (uint16_t) (reqs->txnid + 1) : 1;
  1177. d->next = (struct dns_data *) c->mgr->active_dns_requests;
  1178. c->mgr->active_dns_requests = d;
  1179. d->expire = mg_millis() + (uint64_t) ms;
  1180. d->c = c;
  1181. c->is_resolving = 1;
  1182. MG_VERBOSE(("%lu resolving %.*s @ %s, txnid %hu", c->id, (int) name->len,
  1183. name->buf, dnsc->url, d->txnid));
  1184. if (!mg_dns_send(dnsc->c, name, d->txnid, ipv6)) {
  1185. mg_error(dnsc->c, "DNS send");
  1186. }
  1187. }
  1188. }
  1189. void mg_resolve(struct mg_connection *c, const char *url) {
  1190. struct mg_str host = mg_url_host(url);
  1191. c->rem.port = mg_htons(mg_url_port(url));
  1192. if (mg_aton(host, &c->rem)) {
  1193. // host is an IP address, do not fire name resolution
  1194. mg_connect_resolved(c);
  1195. } else {
  1196. // host is not an IP, send DNS resolution request
  1197. struct mg_dns *dns = c->mgr->use_dns6 ? &c->mgr->dns6 : &c->mgr->dns4;
  1198. mg_sendnsreq(c, &host, c->mgr->dnstimeout, dns, c->mgr->use_dns6);
  1199. }
  1200. }
  1201. #ifdef MG_ENABLE_LINES
  1202. #line 1 "src/event.c"
  1203. #endif
  1204. void mg_call(struct mg_connection *c, int ev, void *ev_data) {
  1205. #if MG_ENABLE_PROFILE
  1206. const char *names[] = {
  1207. "EV_ERROR", "EV_OPEN", "EV_POLL", "EV_RESOLVE",
  1208. "EV_CONNECT", "EV_ACCEPT", "EV_TLS_HS", "EV_READ",
  1209. "EV_WRITE", "EV_CLOSE", "EV_HTTP_MSG", "EV_HTTP_CHUNK",
  1210. "EV_WS_OPEN", "EV_WS_MSG", "EV_WS_CTL", "EV_MQTT_CMD",
  1211. "EV_MQTT_MSG", "EV_MQTT_OPEN", "EV_SNTP_TIME", "EV_USER"};
  1212. if (ev != MG_EV_POLL && ev < (int) (sizeof(names) / sizeof(names[0]))) {
  1213. MG_PROF_ADD(c, names[ev]);
  1214. }
  1215. #endif
  1216. // Fire protocol handler first, user handler second. See #2559
  1217. if (c->pfn != NULL) c->pfn(c, ev, ev_data);
  1218. if (c->fn != NULL) c->fn(c, ev, ev_data);
  1219. }
  1220. void mg_error(struct mg_connection *c, const char *fmt, ...) {
  1221. char buf[64];
  1222. va_list ap;
  1223. va_start(ap, fmt);
  1224. mg_vsnprintf(buf, sizeof(buf), fmt, &ap);
  1225. va_end(ap);
  1226. MG_ERROR(("%lu %ld %s", c->id, c->fd, buf));
  1227. c->is_closing = 1; // Set is_closing before sending MG_EV_CALL
  1228. mg_call(c, MG_EV_ERROR, buf); // Let user handler override it
  1229. }
  1230. #ifdef MG_ENABLE_LINES
  1231. #line 1 "src/fmt.c"
  1232. #endif
  1233. static bool is_digit(int c) {
  1234. return c >= '0' && c <= '9';
  1235. }
  1236. static int addexp(char *buf, int e, int sign) {
  1237. int n = 0;
  1238. buf[n++] = 'e';
  1239. buf[n++] = (char) sign;
  1240. if (e > 400) return 0;
  1241. if (e < 10) buf[n++] = '0';
  1242. if (e >= 100) buf[n++] = (char) (e / 100 + '0'), e -= 100 * (e / 100);
  1243. if (e >= 10) buf[n++] = (char) (e / 10 + '0'), e -= 10 * (e / 10);
  1244. buf[n++] = (char) (e + '0');
  1245. return n;
  1246. }
  1247. static int xisinf(double x) {
  1248. union {
  1249. double f;
  1250. uint64_t u;
  1251. } ieee754 = {x};
  1252. return ((unsigned) (ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
  1253. ((unsigned) ieee754.u == 0);
  1254. }
  1255. static int xisnan(double x) {
  1256. union {
  1257. double f;
  1258. uint64_t u;
  1259. } ieee754 = {x};
  1260. return ((unsigned) (ieee754.u >> 32) & 0x7fffffff) +
  1261. ((unsigned) ieee754.u != 0) >
  1262. 0x7ff00000;
  1263. }
  1264. static size_t mg_dtoa(char *dst, size_t dstlen, double d, int width, bool tz) {
  1265. char buf[40];
  1266. int i, s = 0, n = 0, e = 0;
  1267. double t, mul, saved;
  1268. if (d == 0.0) return mg_snprintf(dst, dstlen, "%s", "0");
  1269. if (xisinf(d)) return mg_snprintf(dst, dstlen, "%s", d > 0 ? "inf" : "-inf");
  1270. if (xisnan(d)) return mg_snprintf(dst, dstlen, "%s", "nan");
  1271. if (d < 0.0) d = -d, buf[s++] = '-';
  1272. // Round
  1273. saved = d;
  1274. mul = 1.0;
  1275. while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0;
  1276. while (d <= 1.0 && d / mul <= 1.0) mul /= 10.0;
  1277. for (i = 0, t = mul * 5; i < width; i++) t /= 10.0;
  1278. d += t;
  1279. // Calculate exponent, and 'mul' for scientific representation
  1280. mul = 1.0;
  1281. while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0, e++;
  1282. while (d < 1.0 && d / mul < 1.0) mul /= 10.0, e--;
  1283. // printf(" --> %g %d %g %g\n", saved, e, t, mul);
  1284. if (e >= width && width > 1) {
  1285. n = (int) mg_dtoa(buf, sizeof(buf), saved / mul, width, tz);
  1286. // printf(" --> %.*g %d [%.*s]\n", 10, d / t, e, n, buf);
  1287. n += addexp(buf + s + n, e, '+');
  1288. return mg_snprintf(dst, dstlen, "%.*s", n, buf);
  1289. } else if (e <= -width && width > 1) {
  1290. n = (int) mg_dtoa(buf, sizeof(buf), saved / mul, width, tz);
  1291. // printf(" --> %.*g %d [%.*s]\n", 10, d / mul, e, n, buf);
  1292. n += addexp(buf + s + n, -e, '-');
  1293. return mg_snprintf(dst, dstlen, "%.*s", n, buf);
  1294. } else {
  1295. for (i = 0, t = mul; t >= 1.0 && s + n < (int) sizeof(buf); i++) {
  1296. int ch = (int) (d / t);
  1297. if (n > 0 || ch > 0) buf[s + n++] = (char) (ch + '0');
  1298. d -= ch * t;
  1299. t /= 10.0;
  1300. }
  1301. // printf(" --> [%g] -> %g %g (%d) [%.*s]\n", saved, d, t, n, s + n, buf);
  1302. if (n == 0) buf[s++] = '0';
  1303. while (t >= 1.0 && n + s < (int) sizeof(buf)) buf[n++] = '0', t /= 10.0;
  1304. if (s + n < (int) sizeof(buf)) buf[n + s++] = '.';
  1305. // printf(" 1--> [%g] -> [%.*s]\n", saved, s + n, buf);
  1306. for (i = 0, t = 0.1; s + n < (int) sizeof(buf) && n < width; i++) {
  1307. int ch = (int) (d / t);
  1308. buf[s + n++] = (char) (ch + '0');
  1309. d -= ch * t;
  1310. t /= 10.0;
  1311. }
  1312. }
  1313. while (tz && n > 0 && buf[s + n - 1] == '0') n--; // Trim trailing zeroes
  1314. if (n > 0 && buf[s + n - 1] == '.') n--; // Trim trailing dot
  1315. n += s;
  1316. if (n >= (int) sizeof(buf)) n = (int) sizeof(buf) - 1;
  1317. buf[n] = '\0';
  1318. return mg_snprintf(dst, dstlen, "%s", buf);
  1319. }
  1320. static size_t mg_lld(char *buf, int64_t val, bool is_signed, bool is_hex) {
  1321. const char *letters = "0123456789abcdef";
  1322. uint64_t v = (uint64_t) val;
  1323. size_t s = 0, n, i;
  1324. if (is_signed && val < 0) buf[s++] = '-', v = (uint64_t) (-val);
  1325. // This loop prints a number in reverse order. I guess this is because we
  1326. // write numbers from right to left: least significant digit comes last.
  1327. // Maybe because we use Arabic numbers, and Arabs write RTL?
  1328. if (is_hex) {
  1329. for (n = 0; v; v >>= 4) buf[s + n++] = letters[v & 15];
  1330. } else {
  1331. for (n = 0; v; v /= 10) buf[s + n++] = letters[v % 10];
  1332. }
  1333. // Reverse a string
  1334. for (i = 0; i < n / 2; i++) {
  1335. char t = buf[s + i];
  1336. buf[s + i] = buf[s + n - i - 1], buf[s + n - i - 1] = t;
  1337. }
  1338. if (val == 0) buf[n++] = '0'; // Handle special case
  1339. return n + s;
  1340. }
  1341. static size_t scpy(void (*out)(char, void *), void *ptr, char *buf,
  1342. size_t len) {
  1343. size_t i = 0;
  1344. while (i < len && buf[i] != '\0') out(buf[i++], ptr);
  1345. return i;
  1346. }
  1347. size_t mg_xprintf(void (*out)(char, void *), void *ptr, const char *fmt, ...) {
  1348. size_t len = 0;
  1349. va_list ap;
  1350. va_start(ap, fmt);
  1351. len = mg_vxprintf(out, ptr, fmt, &ap);
  1352. va_end(ap);
  1353. return len;
  1354. }
  1355. size_t mg_vxprintf(void (*out)(char, void *), void *param, const char *fmt,
  1356. va_list *ap) {
  1357. size_t i = 0, n = 0;
  1358. while (fmt[i] != '\0') {
  1359. if (fmt[i] == '%') {
  1360. size_t j, k, x = 0, is_long = 0, w = 0 /* width */, pr = ~0U /* prec */;
  1361. char pad = ' ', minus = 0, c = fmt[++i];
  1362. if (c == '#') x++, c = fmt[++i];
  1363. if (c == '-') minus++, c = fmt[++i];
  1364. if (c == '0') pad = '0', c = fmt[++i];
  1365. while (is_digit(c)) w *= 10, w += (size_t) (c - '0'), c = fmt[++i];
  1366. if (c == '.') {
  1367. c = fmt[++i];
  1368. if (c == '*') {
  1369. pr = (size_t) va_arg(*ap, int);
  1370. c = fmt[++i];
  1371. } else {
  1372. pr = 0;
  1373. while (is_digit(c)) pr *= 10, pr += (size_t) (c - '0'), c = fmt[++i];
  1374. }
  1375. }
  1376. while (c == 'h') c = fmt[++i]; // Treat h and hh as int
  1377. if (c == 'l') {
  1378. is_long++, c = fmt[++i];
  1379. if (c == 'l') is_long++, c = fmt[++i];
  1380. }
  1381. if (c == 'p') x = 1, is_long = 1;
  1382. if (c == 'd' || c == 'u' || c == 'x' || c == 'X' || c == 'p' ||
  1383. c == 'g' || c == 'f') {
  1384. bool s = (c == 'd'), h = (c == 'x' || c == 'X' || c == 'p');
  1385. char tmp[40];
  1386. size_t xl = x ? 2 : 0;
  1387. if (c == 'g' || c == 'f') {
  1388. double v = va_arg(*ap, double);
  1389. if (pr == ~0U) pr = 6;
  1390. k = mg_dtoa(tmp, sizeof(tmp), v, (int) pr, c == 'g');
  1391. } else if (is_long == 2) {
  1392. int64_t v = va_arg(*ap, int64_t);
  1393. k = mg_lld(tmp, v, s, h);
  1394. } else if (is_long == 1) {
  1395. long v = va_arg(*ap, long);
  1396. k = mg_lld(tmp, s ? (int64_t) v : (int64_t) (unsigned long) v, s, h);
  1397. } else {
  1398. int v = va_arg(*ap, int);
  1399. k = mg_lld(tmp, s ? (int64_t) v : (int64_t) (unsigned) v, s, h);
  1400. }
  1401. for (j = 0; j < xl && w > 0; j++) w--;
  1402. for (j = 0; pad == ' ' && !minus && k < w && j + k < w; j++)
  1403. n += scpy(out, param, &pad, 1);
  1404. n += scpy(out, param, (char *) "0x", xl);
  1405. for (j = 0; pad == '0' && k < w && j + k < w; j++)
  1406. n += scpy(out, param, &pad, 1);
  1407. n += scpy(out, param, tmp, k);
  1408. for (j = 0; pad == ' ' && minus && k < w && j + k < w; j++)
  1409. n += scpy(out, param, &pad, 1);
  1410. } else if (c == 'm' || c == 'M') {
  1411. mg_pm_t f = va_arg(*ap, mg_pm_t);
  1412. if (c == 'm') out('"', param);
  1413. n += f(out, param, ap);
  1414. if (c == 'm') n += 2, out('"', param);
  1415. } else if (c == 'c') {
  1416. int ch = va_arg(*ap, int);
  1417. out((char) ch, param);
  1418. n++;
  1419. } else if (c == 's') {
  1420. char *p = va_arg(*ap, char *);
  1421. if (pr == ~0U) pr = p == NULL ? 0 : strlen(p);
  1422. for (j = 0; !minus && pr < w && j + pr < w; j++)
  1423. n += scpy(out, param, &pad, 1);
  1424. n += scpy(out, param, p, pr);
  1425. for (j = 0; minus && pr < w && j + pr < w; j++)
  1426. n += scpy(out, param, &pad, 1);
  1427. } else if (c == '%') {
  1428. out('%', param);
  1429. n++;
  1430. } else {
  1431. out('%', param);
  1432. out(c, param);
  1433. n += 2;
  1434. }
  1435. i++;
  1436. } else {
  1437. out(fmt[i], param), n++, i++;
  1438. }
  1439. }
  1440. return n;
  1441. }
  1442. #ifdef MG_ENABLE_LINES
  1443. #line 1 "src/fs.c"
  1444. #endif
  1445. struct mg_fd *mg_fs_open(struct mg_fs *fs, const char *path, int flags) {
  1446. struct mg_fd *fd = (struct mg_fd *) calloc(1, sizeof(*fd));
  1447. if (fd != NULL) {
  1448. fd->fd = fs->op(path, flags);
  1449. fd->fs = fs;
  1450. if (fd->fd == NULL) {
  1451. free(fd);
  1452. fd = NULL;
  1453. }
  1454. }
  1455. return fd;
  1456. }
  1457. void mg_fs_close(struct mg_fd *fd) {
  1458. if (fd != NULL) {
  1459. fd->fs->cl(fd->fd);
  1460. free(fd);
  1461. }
  1462. }
  1463. struct mg_str mg_file_read(struct mg_fs *fs, const char *path) {
  1464. struct mg_str result = {NULL, 0};
  1465. void *fp;
  1466. fs->st(path, &result.len, NULL);
  1467. if ((fp = fs->op(path, MG_FS_READ)) != NULL) {
  1468. result.buf = (char *) calloc(1, result.len + 1);
  1469. if (result.buf != NULL &&
  1470. fs->rd(fp, (void *) result.buf, result.len) != result.len) {
  1471. free((void *) result.buf);
  1472. result.buf = NULL;
  1473. }
  1474. fs->cl(fp);
  1475. }
  1476. if (result.buf == NULL) result.len = 0;
  1477. return result;
  1478. }
  1479. bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
  1480. size_t len) {
  1481. bool result = false;
  1482. struct mg_fd *fd;
  1483. char tmp[MG_PATH_MAX];
  1484. mg_snprintf(tmp, sizeof(tmp), "%s..%d", path, rand());
  1485. if ((fd = mg_fs_open(fs, tmp, MG_FS_WRITE)) != NULL) {
  1486. result = fs->wr(fd->fd, buf, len) == len;
  1487. mg_fs_close(fd);
  1488. if (result) {
  1489. fs->rm(path);
  1490. fs->mv(tmp, path);
  1491. } else {
  1492. fs->rm(tmp);
  1493. }
  1494. }
  1495. return result;
  1496. }
  1497. bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...) {
  1498. va_list ap;
  1499. char *data;
  1500. bool result = false;
  1501. va_start(ap, fmt);
  1502. data = mg_vmprintf(fmt, &ap);
  1503. va_end(ap);
  1504. result = mg_file_write(fs, path, data, strlen(data));
  1505. free(data);
  1506. return result;
  1507. }
  1508. // This helper function allows to scan a filesystem in a sequential way,
  1509. // without using callback function:
  1510. // char buf[100] = "";
  1511. // while (mg_fs_ls(&mg_fs_posix, "./", buf, sizeof(buf))) {
  1512. // ...
  1513. static void mg_fs_ls_fn(const char *filename, void *param) {
  1514. struct mg_str *s = (struct mg_str *) param;
  1515. if (s->buf[0] == '\0') {
  1516. mg_snprintf((char *) s->buf, s->len, "%s", filename);
  1517. } else if (strcmp(s->buf, filename) == 0) {
  1518. ((char *) s->buf)[0] = '\0'; // Fetch next file
  1519. }
  1520. }
  1521. bool mg_fs_ls(struct mg_fs *fs, const char *path, char *buf, size_t len) {
  1522. struct mg_str s = {buf, len};
  1523. fs->ls(path, mg_fs_ls_fn, &s);
  1524. return buf[0] != '\0';
  1525. }
  1526. #ifdef MG_ENABLE_LINES
  1527. #line 1 "src/fs_fat.c"
  1528. #endif
  1529. #if MG_ENABLE_FATFS
  1530. #include <ff.h>
  1531. static int mg_days_from_epoch(int y, int m, int d) {
  1532. y -= m <= 2;
  1533. int era = y / 400;
  1534. int yoe = y - era * 400;
  1535. int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
  1536. int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  1537. return era * 146097 + doe - 719468;
  1538. }
  1539. static time_t mg_timegm(const struct tm *t) {
  1540. int year = t->tm_year + 1900;
  1541. int month = t->tm_mon; // 0-11
  1542. if (month > 11) {
  1543. year += month / 12;
  1544. month %= 12;
  1545. } else if (month < 0) {
  1546. int years_diff = (11 - month) / 12;
  1547. year -= years_diff;
  1548. month += 12 * years_diff;
  1549. }
  1550. int x = mg_days_from_epoch(year, month + 1, t->tm_mday);
  1551. return 60 * (60 * (24L * x + t->tm_hour) + t->tm_min) + t->tm_sec;
  1552. }
  1553. static time_t ff_time_to_epoch(uint16_t fdate, uint16_t ftime) {
  1554. struct tm tm;
  1555. memset(&tm, 0, sizeof(struct tm));
  1556. tm.tm_sec = (ftime << 1) & 0x3e;
  1557. tm.tm_min = ((ftime >> 5) & 0x3f);
  1558. tm.tm_hour = ((ftime >> 11) & 0x1f);
  1559. tm.tm_mday = (fdate & 0x1f);
  1560. tm.tm_mon = ((fdate >> 5) & 0x0f) - 1;
  1561. tm.tm_year = ((fdate >> 9) & 0x7f) + 80;
  1562. return mg_timegm(&tm);
  1563. }
  1564. static int ff_stat(const char *path, size_t *size, time_t *mtime) {
  1565. FILINFO fi;
  1566. if (path[0] == '\0') {
  1567. if (size) *size = 0;
  1568. if (mtime) *mtime = 0;
  1569. return MG_FS_DIR;
  1570. } else if (f_stat(path, &fi) == 0) {
  1571. if (size) *size = (size_t) fi.fsize;
  1572. if (mtime) *mtime = ff_time_to_epoch(fi.fdate, fi.ftime);
  1573. return MG_FS_READ | MG_FS_WRITE | ((fi.fattrib & AM_DIR) ? MG_FS_DIR : 0);
  1574. } else {
  1575. return 0;
  1576. }
  1577. }
  1578. static void ff_list(const char *dir, void (*fn)(const char *, void *),
  1579. void *userdata) {
  1580. DIR d;
  1581. FILINFO fi;
  1582. if (f_opendir(&d, dir) == FR_OK) {
  1583. while (f_readdir(&d, &fi) == FR_OK && fi.fname[0] != '\0') {
  1584. if (!strcmp(fi.fname, ".") || !strcmp(fi.fname, "..")) continue;
  1585. fn(fi.fname, userdata);
  1586. }
  1587. f_closedir(&d);
  1588. }
  1589. }
  1590. static void *ff_open(const char *path, int flags) {
  1591. FIL f;
  1592. unsigned char mode = FA_READ;
  1593. if (flags & MG_FS_WRITE) mode |= FA_WRITE | FA_OPEN_ALWAYS | FA_OPEN_APPEND;
  1594. if (f_open(&f, path, mode) == 0) {
  1595. FIL *fp;
  1596. if ((fp = calloc(1, sizeof(*fp))) != NULL) {
  1597. memcpy(fp, &f, sizeof(*fp));
  1598. return fp;
  1599. }
  1600. }
  1601. return NULL;
  1602. }
  1603. static void ff_close(void *fp) {
  1604. if (fp != NULL) {
  1605. f_close((FIL *) fp);
  1606. free(fp);
  1607. }
  1608. }
  1609. static size_t ff_read(void *fp, void *buf, size_t len) {
  1610. UINT n = 0, misalign = ((size_t) buf) & 3;
  1611. if (misalign) {
  1612. char aligned[4];
  1613. f_read((FIL *) fp, aligned, len > misalign ? misalign : len, &n);
  1614. memcpy(buf, aligned, n);
  1615. } else {
  1616. f_read((FIL *) fp, buf, len, &n);
  1617. }
  1618. return n;
  1619. }
  1620. static size_t ff_write(void *fp, const void *buf, size_t len) {
  1621. UINT n = 0;
  1622. return f_write((FIL *) fp, (char *) buf, len, &n) == FR_OK ? n : 0;
  1623. }
  1624. static size_t ff_seek(void *fp, size_t offset) {
  1625. f_lseek((FIL *) fp, offset);
  1626. return offset;
  1627. }
  1628. static bool ff_rename(const char *from, const char *to) {
  1629. return f_rename(from, to) == FR_OK;
  1630. }
  1631. static bool ff_remove(const char *path) {
  1632. return f_unlink(path) == FR_OK;
  1633. }
  1634. static bool ff_mkdir(const char *path) {
  1635. return f_mkdir(path) == FR_OK;
  1636. }
  1637. struct mg_fs mg_fs_fat = {ff_stat, ff_list, ff_open, ff_close, ff_read,
  1638. ff_write, ff_seek, ff_rename, ff_remove, ff_mkdir};
  1639. #endif
  1640. #ifdef MG_ENABLE_LINES
  1641. #line 1 "src/fs_packed.c"
  1642. #endif
  1643. struct packed_file {
  1644. const char *data;
  1645. size_t size;
  1646. size_t pos;
  1647. };
  1648. #if MG_ENABLE_PACKED_FS
  1649. static const struct packed_file2 {
  1650. const char *name;
  1651. const unsigned char *data;
  1652. size_t size;
  1653. time_t mtime;
  1654. } packed_files[] = {
  1655. {NULL, NULL, 0, 0}
  1656. };
  1657. static int scmp(const char *a, const char *b) {
  1658. while (*a && (*a == *b)) a++, b++;
  1659. return *(const unsigned char *) a - *(const unsigned char *) b;
  1660. }
  1661. const char *mg_unlist(size_t no) {
  1662. return packed_files[no].name;
  1663. }
  1664. const char *mg_unpack(const char *name, size_t *size, time_t *mtime) {
  1665. const struct packed_file2 *p;
  1666. for (p = packed_files; p->name != NULL; p++) {
  1667. if (scmp(p->name, name) != 0) continue;
  1668. if (size != NULL) *size = p->size - 1;
  1669. if (mtime != NULL) *mtime = p->mtime;
  1670. return (const char *) p->data;
  1671. }
  1672. return NULL;
  1673. }
  1674. #else
  1675. const char *mg_unpack(const char *path, size_t *size, time_t *mtime) {
  1676. *size = 0, *mtime = 0;
  1677. (void) path;
  1678. return NULL;
  1679. }
  1680. const char *mg_unlist(size_t no) {
  1681. (void) no;
  1682. return NULL;
  1683. }
  1684. #endif
  1685. struct mg_str mg_unpacked(const char *path) {
  1686. size_t len = 0;
  1687. const char *buf = mg_unpack(path, &len, NULL);
  1688. return mg_str_n(buf, len);
  1689. }
  1690. static int is_dir_prefix(const char *prefix, size_t n, const char *path) {
  1691. // MG_INFO(("[%.*s] [%s] %c", (int) n, prefix, path, path[n]));
  1692. return n < strlen(path) && strncmp(prefix, path, n) == 0 &&
  1693. (n == 0 || path[n] == '/' || path[n - 1] == '/');
  1694. }
  1695. static int packed_stat(const char *path, size_t *size, time_t *mtime) {
  1696. const char *p;
  1697. size_t i, n = strlen(path);
  1698. if (mg_unpack(path, size, mtime)) return MG_FS_READ; // Regular file
  1699. // Scan all files. If `path` is a dir prefix for any of them, it's a dir
  1700. for (i = 0; (p = mg_unlist(i)) != NULL; i++) {
  1701. if (is_dir_prefix(path, n, p)) return MG_FS_DIR;
  1702. }
  1703. return 0;
  1704. }
  1705. static void packed_list(const char *dir, void (*fn)(const char *, void *),
  1706. void *userdata) {
  1707. char buf[MG_PATH_MAX], tmp[sizeof(buf)];
  1708. const char *path, *begin, *end;
  1709. size_t i, n = strlen(dir);
  1710. tmp[0] = '\0'; // Previously listed entry
  1711. for (i = 0; (path = mg_unlist(i)) != NULL; i++) {
  1712. if (!is_dir_prefix(dir, n, path)) continue;
  1713. begin = &path[n + 1];
  1714. end = strchr(begin, '/');
  1715. if (end == NULL) end = begin + strlen(begin);
  1716. mg_snprintf(buf, sizeof(buf), "%.*s", (int) (end - begin), begin);
  1717. buf[sizeof(buf) - 1] = '\0';
  1718. // If this entry has been already listed, skip
  1719. // NOTE: we're assuming that file list is sorted alphabetically
  1720. if (strcmp(buf, tmp) == 0) continue;
  1721. fn(buf, userdata); // Not yet listed, call user function
  1722. strcpy(tmp, buf); // And save this entry as listed
  1723. }
  1724. }
  1725. static void *packed_open(const char *path, int flags) {
  1726. size_t size = 0;
  1727. const char *data = mg_unpack(path, &size, NULL);
  1728. struct packed_file *fp = NULL;
  1729. if (data == NULL) return NULL;
  1730. if (flags & MG_FS_WRITE) return NULL;
  1731. if ((fp = (struct packed_file *) calloc(1, sizeof(*fp))) != NULL) {
  1732. fp->size = size;
  1733. fp->data = data;
  1734. }
  1735. return (void *) fp;
  1736. }
  1737. static void packed_close(void *fp) {
  1738. if (fp != NULL) free(fp);
  1739. }
  1740. static size_t packed_read(void *fd, void *buf, size_t len) {
  1741. struct packed_file *fp = (struct packed_file *) fd;
  1742. if (fp->pos + len > fp->size) len = fp->size - fp->pos;
  1743. memcpy(buf, &fp->data[fp->pos], len);
  1744. fp->pos += len;
  1745. return len;
  1746. }
  1747. static size_t packed_write(void *fd, const void *buf, size_t len) {
  1748. (void) fd, (void) buf, (void) len;
  1749. return 0;
  1750. }
  1751. static size_t packed_seek(void *fd, size_t offset) {
  1752. struct packed_file *fp = (struct packed_file *) fd;
  1753. fp->pos = offset;
  1754. if (fp->pos > fp->size) fp->pos = fp->size;
  1755. return fp->pos;
  1756. }
  1757. static bool packed_rename(const char *from, const char *to) {
  1758. (void) from, (void) to;
  1759. return false;
  1760. }
  1761. static bool packed_remove(const char *path) {
  1762. (void) path;
  1763. return false;
  1764. }
  1765. static bool packed_mkdir(const char *path) {
  1766. (void) path;
  1767. return false;
  1768. }
  1769. struct mg_fs mg_fs_packed = {
  1770. packed_stat, packed_list, packed_open, packed_close, packed_read,
  1771. packed_write, packed_seek, packed_rename, packed_remove, packed_mkdir};
  1772. #ifdef MG_ENABLE_LINES
  1773. #line 1 "src/fs_posix.c"
  1774. #endif
  1775. #if MG_ENABLE_POSIX_FS
  1776. #ifndef MG_STAT_STRUCT
  1777. #define MG_STAT_STRUCT stat
  1778. #endif
  1779. #ifndef MG_STAT_FUNC
  1780. #define MG_STAT_FUNC stat
  1781. #endif
  1782. static int p_stat(const char *path, size_t *size, time_t *mtime) {
  1783. #if !defined(S_ISDIR)
  1784. MG_ERROR(("stat() API is not supported. %p %p %p", path, size, mtime));
  1785. return 0;
  1786. #else
  1787. #if MG_ARCH == MG_ARCH_WIN32
  1788. struct _stati64 st;
  1789. wchar_t tmp[MG_PATH_MAX];
  1790. MultiByteToWideChar(CP_UTF8, 0, path, -1, tmp, sizeof(tmp) / sizeof(tmp[0]));
  1791. if (_wstati64(tmp, &st) != 0) return 0;
  1792. // If path is a symlink, windows reports 0 in st.st_size.
  1793. // Get a real file size by opening it and jumping to the end
  1794. if (st.st_size == 0 && (st.st_mode & _S_IFREG)) {
  1795. FILE *fp = _wfopen(tmp, L"rb");
  1796. if (fp != NULL) {
  1797. fseek(fp, 0, SEEK_END);
  1798. if (ftell(fp) > 0) st.st_size = ftell(fp); // Use _ftelli64 on win10+
  1799. fclose(fp);
  1800. }
  1801. }
  1802. #else
  1803. struct MG_STAT_STRUCT st;
  1804. if (MG_STAT_FUNC(path, &st) != 0) return 0;
  1805. #endif
  1806. if (size) *size = (size_t) st.st_size;
  1807. if (mtime) *mtime = st.st_mtime;
  1808. return MG_FS_READ | MG_FS_WRITE | (S_ISDIR(st.st_mode) ? MG_FS_DIR : 0);
  1809. #endif
  1810. }
  1811. #if MG_ARCH == MG_ARCH_WIN32
  1812. struct dirent {
  1813. char d_name[MAX_PATH];
  1814. };
  1815. typedef struct win32_dir {
  1816. HANDLE handle;
  1817. WIN32_FIND_DATAW info;
  1818. struct dirent result;
  1819. } DIR;
  1820. #if 0
  1821. int gettimeofday(struct timeval *tv, void *tz) {
  1822. FILETIME ft;
  1823. unsigned __int64 tmpres = 0;
  1824. if (tv != NULL) {
  1825. GetSystemTimeAsFileTime(&ft);
  1826. tmpres |= ft.dwHighDateTime;
  1827. tmpres <<= 32;
  1828. tmpres |= ft.dwLowDateTime;
  1829. tmpres /= 10; // convert into microseconds
  1830. tmpres -= (int64_t) 11644473600000000;
  1831. tv->tv_sec = (long) (tmpres / 1000000UL);
  1832. tv->tv_usec = (long) (tmpres % 1000000UL);
  1833. }
  1834. (void) tz;
  1835. return 0;
  1836. }
  1837. #endif
  1838. static int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1839. int ret;
  1840. char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
  1841. strncpy(buf, path, sizeof(buf));
  1842. buf[sizeof(buf) - 1] = '\0';
  1843. // Trim trailing slashes. Leave backslash for paths like "X:\"
  1844. p = buf + strlen(buf) - 1;
  1845. while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
  1846. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1847. ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1848. // Convert back to Unicode. If doubly-converted string does not match the
  1849. // original, something is fishy, reject.
  1850. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1851. NULL, NULL);
  1852. if (strcmp(buf, buf2) != 0) {
  1853. wbuf[0] = L'\0';
  1854. ret = 0;
  1855. }
  1856. return ret;
  1857. }
  1858. DIR *opendir(const char *name) {
  1859. DIR *d = NULL;
  1860. wchar_t wpath[MAX_PATH];
  1861. DWORD attrs;
  1862. if (name == NULL) {
  1863. SetLastError(ERROR_BAD_ARGUMENTS);
  1864. } else if ((d = (DIR *) calloc(1, sizeof(*d))) == NULL) {
  1865. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1866. } else {
  1867. to_wchar(name, wpath, sizeof(wpath) / sizeof(wpath[0]));
  1868. attrs = GetFileAttributesW(wpath);
  1869. if (attrs != 0Xffffffff && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1870. (void) wcscat(wpath, L"\\*");
  1871. d->handle = FindFirstFileW(wpath, &d->info);
  1872. d->result.d_name[0] = '\0';
  1873. } else {
  1874. free(d);
  1875. d = NULL;
  1876. }
  1877. }
  1878. return d;
  1879. }
  1880. int closedir(DIR *d) {
  1881. int result = 0;
  1882. if (d != NULL) {
  1883. if (d->handle != INVALID_HANDLE_VALUE)
  1884. result = FindClose(d->handle) ? 0 : -1;
  1885. free(d);
  1886. } else {
  1887. result = -1;
  1888. SetLastError(ERROR_BAD_ARGUMENTS);
  1889. }
  1890. return result;
  1891. }
  1892. struct dirent *readdir(DIR *d) {
  1893. struct dirent *result = NULL;
  1894. if (d != NULL) {
  1895. memset(&d->result, 0, sizeof(d->result));
  1896. if (d->handle != INVALID_HANDLE_VALUE) {
  1897. result = &d->result;
  1898. WideCharToMultiByte(CP_UTF8, 0, d->info.cFileName, -1, result->d_name,
  1899. sizeof(result->d_name), NULL, NULL);
  1900. if (!FindNextFileW(d->handle, &d->info)) {
  1901. FindClose(d->handle);
  1902. d->handle = INVALID_HANDLE_VALUE;
  1903. }
  1904. } else {
  1905. SetLastError(ERROR_FILE_NOT_FOUND);
  1906. }
  1907. } else {
  1908. SetLastError(ERROR_BAD_ARGUMENTS);
  1909. }
  1910. return result;
  1911. }
  1912. #endif
  1913. static void p_list(const char *dir, void (*fn)(const char *, void *),
  1914. void *userdata) {
  1915. #if MG_ENABLE_DIRLIST
  1916. struct dirent *dp;
  1917. DIR *dirp;
  1918. if ((dirp = (opendir(dir))) == NULL) return;
  1919. while ((dp = readdir(dirp)) != NULL) {
  1920. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
  1921. fn(dp->d_name, userdata);
  1922. }
  1923. closedir(dirp);
  1924. #else
  1925. (void) dir, (void) fn, (void) userdata;
  1926. #endif
  1927. }
  1928. static void *p_open(const char *path, int flags) {
  1929. #if MG_ARCH == MG_ARCH_WIN32
  1930. const char *mode = flags == MG_FS_READ ? "rb" : "a+b";
  1931. wchar_t b1[MG_PATH_MAX], b2[10];
  1932. MultiByteToWideChar(CP_UTF8, 0, path, -1, b1, sizeof(b1) / sizeof(b1[0]));
  1933. MultiByteToWideChar(CP_UTF8, 0, mode, -1, b2, sizeof(b2) / sizeof(b2[0]));
  1934. return (void *) _wfopen(b1, b2);
  1935. #else
  1936. const char *mode = flags == MG_FS_READ ? "rbe" : "a+be"; // e for CLOEXEC
  1937. return (void *) fopen(path, mode);
  1938. #endif
  1939. }
  1940. static void p_close(void *fp) {
  1941. fclose((FILE *) fp);
  1942. }
  1943. static size_t p_read(void *fp, void *buf, size_t len) {
  1944. return fread(buf, 1, len, (FILE *) fp);
  1945. }
  1946. static size_t p_write(void *fp, const void *buf, size_t len) {
  1947. return fwrite(buf, 1, len, (FILE *) fp);
  1948. }
  1949. static size_t p_seek(void *fp, size_t offset) {
  1950. #if (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64) || \
  1951. (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) || \
  1952. (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
  1953. if (fseeko((FILE *) fp, (off_t) offset, SEEK_SET) != 0) (void) 0;
  1954. #else
  1955. if (fseek((FILE *) fp, (long) offset, SEEK_SET) != 0) (void) 0;
  1956. #endif
  1957. return (size_t) ftell((FILE *) fp);
  1958. }
  1959. static bool p_rename(const char *from, const char *to) {
  1960. return rename(from, to) == 0;
  1961. }
  1962. static bool p_remove(const char *path) {
  1963. return remove(path) == 0;
  1964. }
  1965. static bool p_mkdir(const char *path) {
  1966. return mkdir(path, 0775) == 0;
  1967. }
  1968. #else
  1969. static int p_stat(const char *path, size_t *size, time_t *mtime) {
  1970. (void) path, (void) size, (void) mtime;
  1971. return 0;
  1972. }
  1973. static void p_list(const char *path, void (*fn)(const char *, void *),
  1974. void *userdata) {
  1975. (void) path, (void) fn, (void) userdata;
  1976. }
  1977. static void *p_open(const char *path, int flags) {
  1978. (void) path, (void) flags;
  1979. return NULL;
  1980. }
  1981. static void p_close(void *fp) {
  1982. (void) fp;
  1983. }
  1984. static size_t p_read(void *fd, void *buf, size_t len) {
  1985. (void) fd, (void) buf, (void) len;
  1986. return 0;
  1987. }
  1988. static size_t p_write(void *fd, const void *buf, size_t len) {
  1989. (void) fd, (void) buf, (void) len;
  1990. return 0;
  1991. }
  1992. static size_t p_seek(void *fd, size_t offset) {
  1993. (void) fd, (void) offset;
  1994. return (size_t) ~0;
  1995. }
  1996. static bool p_rename(const char *from, const char *to) {
  1997. (void) from, (void) to;
  1998. return false;
  1999. }
  2000. static bool p_remove(const char *path) {
  2001. (void) path;
  2002. return false;
  2003. }
  2004. static bool p_mkdir(const char *path) {
  2005. (void) path;
  2006. return false;
  2007. }
  2008. #endif
  2009. struct mg_fs mg_fs_posix = {p_stat, p_list, p_open, p_close, p_read,
  2010. p_write, p_seek, p_rename, p_remove, p_mkdir};
  2011. #ifdef MG_ENABLE_LINES
  2012. #line 1 "src/http.c"
  2013. #endif
  2014. static int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  2015. int diff = 0;
  2016. if (len > 0) do {
  2017. int c = *s1++, d = *s2++;
  2018. if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
  2019. if (d >= 'A' && d <= 'Z') d += 'a' - 'A';
  2020. diff = c - d;
  2021. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2022. return diff;
  2023. }
  2024. bool mg_to_size_t(struct mg_str str, size_t *val);
  2025. bool mg_to_size_t(struct mg_str str, size_t *val) {
  2026. size_t i = 0, max = (size_t) -1, max2 = max / 10, result = 0, ndigits = 0;
  2027. while (i < str.len && (str.buf[i] == ' ' || str.buf[i] == '\t')) i++;
  2028. if (i < str.len && str.buf[i] == '-') return false;
  2029. while (i < str.len && str.buf[i] >= '0' && str.buf[i] <= '9') {
  2030. size_t digit = (size_t) (str.buf[i] - '0');
  2031. if (result > max2) return false; // Overflow
  2032. result *= 10;
  2033. if (result > max - digit) return false; // Overflow
  2034. result += digit;
  2035. i++, ndigits++;
  2036. }
  2037. while (i < str.len && (str.buf[i] == ' ' || str.buf[i] == '\t')) i++;
  2038. if (ndigits == 0) return false; // #2322: Content-Length = 1 * DIGIT
  2039. if (i != str.len) return false; // Ditto
  2040. *val = (size_t) result;
  2041. return true;
  2042. }
  2043. // Chunk deletion marker is the MSB in the "processed" counter
  2044. #define MG_DMARK ((size_t) 1 << (sizeof(size_t) * 8 - 1))
  2045. // Multipart POST example:
  2046. // --xyz
  2047. // Content-Disposition: form-data; name="val"
  2048. //
  2049. // abcdef
  2050. // --xyz
  2051. // Content-Disposition: form-data; name="foo"; filename="a.txt"
  2052. // Content-Type: text/plain
  2053. //
  2054. // hello world
  2055. //
  2056. // --xyz--
  2057. size_t mg_http_next_multipart(struct mg_str body, size_t ofs,
  2058. struct mg_http_part *part) {
  2059. struct mg_str cd = mg_str_n("Content-Disposition", 19);
  2060. const char *s = body.buf;
  2061. size_t b = ofs, h1, h2, b1, b2, max = body.len;
  2062. // Init part params
  2063. if (part != NULL) part->name = part->filename = part->body = mg_str_n(0, 0);
  2064. // Skip boundary
  2065. while (b + 2 < max && s[b] != '\r' && s[b + 1] != '\n') b++;
  2066. if (b <= ofs || b + 2 >= max) return 0;
  2067. // MG_INFO(("B: %zu %zu [%.*s]", ofs, b - ofs, (int) (b - ofs), s));
  2068. // Skip headers
  2069. h1 = h2 = b + 2;
  2070. for (;;) {
  2071. while (h2 + 2 < max && s[h2] != '\r' && s[h2 + 1] != '\n') h2++;
  2072. if (h2 == h1) break;
  2073. if (h2 + 2 >= max) return 0;
  2074. // MG_INFO(("Header: [%.*s]", (int) (h2 - h1), &s[h1]));
  2075. if (part != NULL && h1 + cd.len + 2 < h2 && s[h1 + cd.len] == ':' &&
  2076. mg_ncasecmp(&s[h1], cd.buf, cd.len) == 0) {
  2077. struct mg_str v = mg_str_n(&s[h1 + cd.len + 2], h2 - (h1 + cd.len + 2));
  2078. part->name = mg_http_get_header_var(v, mg_str_n("name", 4));
  2079. part->filename = mg_http_get_header_var(v, mg_str_n("filename", 8));
  2080. }
  2081. h1 = h2 = h2 + 2;
  2082. }
  2083. b1 = b2 = h2 + 2;
  2084. while (b2 + 2 + (b - ofs) + 2 < max && !(s[b2] == '\r' && s[b2 + 1] == '\n' &&
  2085. memcmp(&s[b2 + 2], s, b - ofs) == 0))
  2086. b2++;
  2087. if (b2 + 2 >= max) return 0;
  2088. if (part != NULL) part->body = mg_str_n(&s[b1], b2 - b1);
  2089. // MG_INFO(("Body: [%.*s]", (int) (b2 - b1), &s[b1]));
  2090. return b2 + 2;
  2091. }
  2092. void mg_http_bauth(struct mg_connection *c, const char *user,
  2093. const char *pass) {
  2094. struct mg_str u = mg_str(user), p = mg_str(pass);
  2095. size_t need = c->send.len + 36 + (u.len + p.len) * 2;
  2096. if (c->send.size < need) mg_iobuf_resize(&c->send, need);
  2097. if (c->send.size >= need) {
  2098. size_t i, n = 0;
  2099. char *buf = (char *) &c->send.buf[c->send.len];
  2100. memcpy(buf, "Authorization: Basic ", 21); // DON'T use mg_send!
  2101. for (i = 0; i < u.len; i++) {
  2102. n = mg_base64_update(((unsigned char *) u.buf)[i], buf + 21, n);
  2103. }
  2104. if (p.len > 0) {
  2105. n = mg_base64_update(':', buf + 21, n);
  2106. for (i = 0; i < p.len; i++) {
  2107. n = mg_base64_update(((unsigned char *) p.buf)[i], buf + 21, n);
  2108. }
  2109. }
  2110. n = mg_base64_final(buf + 21, n);
  2111. c->send.len += 21 + (size_t) n + 2;
  2112. memcpy(&c->send.buf[c->send.len - 2], "\r\n", 2);
  2113. } else {
  2114. MG_ERROR(("%lu oom %d->%d ", c->id, (int) c->send.size, (int) need));
  2115. }
  2116. }
  2117. struct mg_str mg_http_var(struct mg_str buf, struct mg_str name) {
  2118. struct mg_str entry, k, v, result = mg_str_n(NULL, 0);
  2119. while (mg_span(buf, &entry, &buf, '&')) {
  2120. if (mg_span(entry, &k, &v, '=') && name.len == k.len &&
  2121. mg_ncasecmp(name.buf, k.buf, k.len) == 0) {
  2122. result = v;
  2123. break;
  2124. }
  2125. }
  2126. return result;
  2127. }
  2128. int mg_http_get_var(const struct mg_str *buf, const char *name, char *dst,
  2129. size_t dst_len) {
  2130. int len;
  2131. if (dst != NULL && dst_len > 0) {
  2132. dst[0] = '\0'; // If destination buffer is valid, always nul-terminate it
  2133. }
  2134. if (dst == NULL || dst_len == 0) {
  2135. len = -2; // Bad destination
  2136. } else if (buf->buf == NULL || name == NULL || buf->len == 0) {
  2137. len = -1; // Bad source
  2138. } else {
  2139. struct mg_str v = mg_http_var(*buf, mg_str(name));
  2140. if (v.buf == NULL) {
  2141. len = -4; // Name does not exist
  2142. } else {
  2143. len = mg_url_decode(v.buf, v.len, dst, dst_len, 1);
  2144. if (len < 0) len = -3; // Failed to decode
  2145. }
  2146. }
  2147. return len;
  2148. }
  2149. static bool isx(int c) {
  2150. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  2151. (c >= 'A' && c <= 'F');
  2152. }
  2153. int mg_url_decode(const char *src, size_t src_len, char *dst, size_t dst_len,
  2154. int is_form_url_encoded) {
  2155. size_t i, j;
  2156. for (i = j = 0; i < src_len && j + 1 < dst_len; i++, j++) {
  2157. if (src[i] == '%') {
  2158. // Use `i + 2 < src_len`, not `i < src_len - 2`, note small src_len
  2159. if (i + 2 < src_len && isx(src[i + 1]) && isx(src[i + 2])) {
  2160. mg_str_to_num(mg_str_n(src + i + 1, 2), 16, &dst[j], sizeof(uint8_t));
  2161. i += 2;
  2162. } else {
  2163. return -1;
  2164. }
  2165. } else if (is_form_url_encoded && src[i] == '+') {
  2166. dst[j] = ' ';
  2167. } else {
  2168. dst[j] = src[i];
  2169. }
  2170. }
  2171. if (j < dst_len) dst[j] = '\0'; // Null-terminate the destination
  2172. return i >= src_len && j < dst_len ? (int) j : -1;
  2173. }
  2174. static bool isok(uint8_t c) {
  2175. return c == '\n' || c == '\r' || c >= ' ';
  2176. }
  2177. int mg_http_get_request_len(const unsigned char *buf, size_t buf_len) {
  2178. size_t i;
  2179. for (i = 0; i < buf_len; i++) {
  2180. if (!isok(buf[i])) return -1;
  2181. if ((i > 0 && buf[i] == '\n' && buf[i - 1] == '\n') ||
  2182. (i > 3 && buf[i] == '\n' && buf[i - 1] == '\r' && buf[i - 2] == '\n'))
  2183. return (int) i + 1;
  2184. }
  2185. return 0;
  2186. }
  2187. struct mg_str *mg_http_get_header(struct mg_http_message *h, const char *name) {
  2188. size_t i, n = strlen(name), max = sizeof(h->headers) / sizeof(h->headers[0]);
  2189. for (i = 0; i < max && h->headers[i].name.len > 0; i++) {
  2190. struct mg_str *k = &h->headers[i].name, *v = &h->headers[i].value;
  2191. if (n == k->len && mg_ncasecmp(k->buf, name, n) == 0) return v;
  2192. }
  2193. return NULL;
  2194. }
  2195. // Is it a valid utf-8 continuation byte
  2196. static bool vcb(uint8_t c) {
  2197. return (c & 0xc0) == 0x80;
  2198. }
  2199. // Get character length (valid utf-8). Used to parse method, URI, headers
  2200. static size_t clen(const char *s, const char *end) {
  2201. const unsigned char *u = (unsigned char *) s, c = *u;
  2202. long n = (long) (end - s);
  2203. if (c > ' ' && c < '~') return 1; // Usual ascii printed char
  2204. if ((c & 0xe0) == 0xc0 && n > 1 && vcb(u[1])) return 2; // 2-byte UTF8
  2205. if ((c & 0xf0) == 0xe0 && n > 2 && vcb(u[1]) && vcb(u[2])) return 3;
  2206. if ((c & 0xf8) == 0xf0 && n > 3 && vcb(u[1]) && vcb(u[2]) && vcb(u[3]))
  2207. return 4;
  2208. return 0;
  2209. }
  2210. // Skip until the newline. Return advanced `s`, or NULL on error
  2211. static const char *skiptorn(const char *s, const char *end, struct mg_str *v) {
  2212. v->buf = (char *) s;
  2213. while (s < end && s[0] != '\n' && s[0] != '\r') s++, v->len++; // To newline
  2214. if (s >= end || (s[0] == '\r' && s[1] != '\n')) return NULL; // Stray \r
  2215. if (s < end && s[0] == '\r') s++; // Skip \r
  2216. if (s >= end || *s++ != '\n') return NULL; // Skip \n
  2217. return s;
  2218. }
  2219. static bool mg_http_parse_headers(const char *s, const char *end,
  2220. struct mg_http_header *h, size_t max_hdrs) {
  2221. size_t i, n;
  2222. for (i = 0; i < max_hdrs; i++) {
  2223. struct mg_str k = {NULL, 0}, v = {NULL, 0};
  2224. if (s >= end) return false;
  2225. if (s[0] == '\n' || (s[0] == '\r' && s[1] == '\n')) break;
  2226. k.buf = (char *) s;
  2227. while (s < end && s[0] != ':' && (n = clen(s, end)) > 0) s += n, k.len += n;
  2228. if (k.len == 0) return false; // Empty name
  2229. if (s >= end || clen(s, end) == 0) return false; // Invalid UTF-8
  2230. if (*s++ != ':') return false; // Invalid, not followed by :
  2231. // if (clen(s, end) == 0) return false; // Invalid UTF-8
  2232. while (s < end && s[0] == ' ') s++; // Skip spaces
  2233. if ((s = skiptorn(s, end, &v)) == NULL) return false;
  2234. while (v.len > 0 && v.buf[v.len - 1] == ' ') v.len--; // Trim spaces
  2235. // MG_INFO(("--HH [%.*s] [%.*s]", (int) k.len, k.buf, (int) v.len, v.buf));
  2236. h[i].name = k, h[i].value = v; // Success. Assign values
  2237. }
  2238. return true;
  2239. }
  2240. int mg_http_parse(const char *s, size_t len, struct mg_http_message *hm) {
  2241. int is_response, req_len = mg_http_get_request_len((unsigned char *) s, len);
  2242. const char *end = s == NULL ? NULL : s + req_len, *qs; // Cannot add to NULL
  2243. const struct mg_str *cl;
  2244. size_t n;
  2245. memset(hm, 0, sizeof(*hm));
  2246. if (req_len <= 0) return req_len;
  2247. hm->message.buf = hm->head.buf = (char *) s;
  2248. hm->body.buf = (char *) end;
  2249. hm->head.len = (size_t) req_len;
  2250. hm->message.len = hm->body.len = (size_t) -1; // Set body length to infinite
  2251. // Parse request line
  2252. hm->method.buf = (char *) s;
  2253. while (s < end && (n = clen(s, end)) > 0) s += n, hm->method.len += n;
  2254. while (s < end && s[0] == ' ') s++; // Skip spaces
  2255. hm->uri.buf = (char *) s;
  2256. while (s < end && (n = clen(s, end)) > 0) s += n, hm->uri.len += n;
  2257. while (s < end && s[0] == ' ') s++; // Skip spaces
  2258. if ((s = skiptorn(s, end, &hm->proto)) == NULL) return false;
  2259. // If URI contains '?' character, setup query string
  2260. if ((qs = (const char *) memchr(hm->uri.buf, '?', hm->uri.len)) != NULL) {
  2261. hm->query.buf = (char *) qs + 1;
  2262. hm->query.len = (size_t) (&hm->uri.buf[hm->uri.len] - (qs + 1));
  2263. hm->uri.len = (size_t) (qs - hm->uri.buf);
  2264. }
  2265. // Sanity check. Allow protocol/reason to be empty
  2266. // Do this check after hm->method.len and hm->uri.len are finalised
  2267. if (hm->method.len == 0 || hm->uri.len == 0) return -1;
  2268. if (!mg_http_parse_headers(s, end, hm->headers,
  2269. sizeof(hm->headers) / sizeof(hm->headers[0])))
  2270. return -1; // error when parsing
  2271. if ((cl = mg_http_get_header(hm, "Content-Length")) != NULL) {
  2272. if (mg_to_size_t(*cl, &hm->body.len) == false) return -1;
  2273. hm->message.len = (size_t) req_len + hm->body.len;
  2274. }
  2275. // mg_http_parse() is used to parse both HTTP requests and HTTP
  2276. // responses. If HTTP response does not have Content-Length set, then
  2277. // body is read until socket is closed, i.e. body.len is infinite (~0).
  2278. //
  2279. // For HTTP requests though, according to
  2280. // http://tools.ietf.org/html/rfc7231#section-8.1.3,
  2281. // only POST and PUT methods have defined body semantics.
  2282. // Therefore, if Content-Length is not specified and methods are
  2283. // not one of PUT or POST, set body length to 0.
  2284. //
  2285. // So, if it is HTTP request, and Content-Length is not set,
  2286. // and method is not (PUT or POST) then reset body length to zero.
  2287. is_response = mg_ncasecmp(hm->method.buf, "HTTP/", 5) == 0;
  2288. if (hm->body.len == (size_t) ~0 && !is_response &&
  2289. mg_strcasecmp(hm->method, mg_str("PUT")) != 0 &&
  2290. mg_strcasecmp(hm->method, mg_str("POST")) != 0) {
  2291. hm->body.len = 0;
  2292. hm->message.len = (size_t) req_len;
  2293. }
  2294. // The 204 (No content) responses also have 0 body length
  2295. if (hm->body.len == (size_t) ~0 && is_response &&
  2296. mg_strcasecmp(hm->uri, mg_str("204")) == 0) {
  2297. hm->body.len = 0;
  2298. hm->message.len = (size_t) req_len;
  2299. }
  2300. if (hm->message.len < (size_t) req_len) return -1; // Overflow protection
  2301. return req_len;
  2302. }
  2303. static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt,
  2304. va_list *ap) {
  2305. size_t len = c->send.len;
  2306. mg_send(c, " \r\n", 10);
  2307. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  2308. if (c->send.len >= len + 10) {
  2309. mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10);
  2310. c->send.buf[len + 8] = '\r';
  2311. if (c->send.len == len + 10) c->is_resp = 0; // Last chunk, reset marker
  2312. }
  2313. mg_send(c, "\r\n", 2);
  2314. }
  2315. void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) {
  2316. va_list ap;
  2317. va_start(ap, fmt);
  2318. mg_http_vprintf_chunk(c, fmt, &ap);
  2319. va_end(ap);
  2320. }
  2321. void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) {
  2322. mg_printf(c, "%lx\r\n", (unsigned long) len);
  2323. mg_send(c, buf, len);
  2324. mg_send(c, "\r\n", 2);
  2325. if (len == 0) c->is_resp = 0;
  2326. }
  2327. // clang-format off
  2328. static const char *mg_http_status_code_str(int status_code) {
  2329. switch (status_code) {
  2330. case 100: return "Continue";
  2331. case 101: return "Switching Protocols";
  2332. case 102: return "Processing";
  2333. case 200: return "OK";
  2334. case 201: return "Created";
  2335. case 202: return "Accepted";
  2336. case 203: return "Non-authoritative Information";
  2337. case 204: return "No Content";
  2338. case 205: return "Reset Content";
  2339. case 206: return "Partial Content";
  2340. case 207: return "Multi-Status";
  2341. case 208: return "Already Reported";
  2342. case 226: return "IM Used";
  2343. case 300: return "Multiple Choices";
  2344. case 301: return "Moved Permanently";
  2345. case 302: return "Found";
  2346. case 303: return "See Other";
  2347. case 304: return "Not Modified";
  2348. case 305: return "Use Proxy";
  2349. case 307: return "Temporary Redirect";
  2350. case 308: return "Permanent Redirect";
  2351. case 400: return "Bad Request";
  2352. case 401: return "Unauthorized";
  2353. case 402: return "Payment Required";
  2354. case 403: return "Forbidden";
  2355. case 404: return "Not Found";
  2356. case 405: return "Method Not Allowed";
  2357. case 406: return "Not Acceptable";
  2358. case 407: return "Proxy Authentication Required";
  2359. case 408: return "Request Timeout";
  2360. case 409: return "Conflict";
  2361. case 410: return "Gone";
  2362. case 411: return "Length Required";
  2363. case 412: return "Precondition Failed";
  2364. case 413: return "Payload Too Large";
  2365. case 414: return "Request-URI Too Long";
  2366. case 415: return "Unsupported Media Type";
  2367. case 416: return "Requested Range Not Satisfiable";
  2368. case 417: return "Expectation Failed";
  2369. case 418: return "I'm a teapot";
  2370. case 421: return "Misdirected Request";
  2371. case 422: return "Unprocessable Entity";
  2372. case 423: return "Locked";
  2373. case 424: return "Failed Dependency";
  2374. case 426: return "Upgrade Required";
  2375. case 428: return "Precondition Required";
  2376. case 429: return "Too Many Requests";
  2377. case 431: return "Request Header Fields Too Large";
  2378. case 444: return "Connection Closed Without Response";
  2379. case 451: return "Unavailable For Legal Reasons";
  2380. case 499: return "Client Closed Request";
  2381. case 500: return "Internal Server Error";
  2382. case 501: return "Not Implemented";
  2383. case 502: return "Bad Gateway";
  2384. case 503: return "Service Unavailable";
  2385. case 504: return "Gateway Timeout";
  2386. case 505: return "HTTP Version Not Supported";
  2387. case 506: return "Variant Also Negotiates";
  2388. case 507: return "Insufficient Storage";
  2389. case 508: return "Loop Detected";
  2390. case 510: return "Not Extended";
  2391. case 511: return "Network Authentication Required";
  2392. case 599: return "Network Connect Timeout Error";
  2393. default: return "";
  2394. }
  2395. }
  2396. // clang-format on
  2397. void mg_http_reply(struct mg_connection *c, int code, const char *headers,
  2398. const char *fmt, ...) {
  2399. va_list ap;
  2400. size_t len;
  2401. mg_printf(c, "HTTP/1.1 %d %s\r\n%sContent-Length: \r\n\r\n", code,
  2402. mg_http_status_code_str(code), headers == NULL ? "" : headers);
  2403. len = c->send.len;
  2404. va_start(ap, fmt);
  2405. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  2406. va_end(ap);
  2407. if (c->send.len > 16) {
  2408. size_t n = mg_snprintf((char *) &c->send.buf[len - 15], 11, "%-10lu",
  2409. (unsigned long) (c->send.len - len));
  2410. c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space
  2411. }
  2412. c->is_resp = 0;
  2413. }
  2414. int mg_http_reply2(struct mg_connection *c, int code, const char *headers,
  2415. const char *fmt, ...) {
  2416. va_list ap;
  2417. size_t len;
  2418. int r;
  2419. if (c==NULL) return -1;
  2420. mg_printf(c, "HTTP/1.1 %d %s\r\n"
  2421. "Content-Type: text/html\n"
  2422. "Content-Length: %d\n"
  2423. "Connection: Keep-Alive\n"
  2424. "Keep-Alive: timeout=30, max=396\n"
  2425. "X-Content-Type-0ptions: nosniff\n"
  2426. "X-Frame-0ptions:: SAMEORIGIN\n"
  2427. "X-Xss-Protection: 1: mode=block\n"
  2428. "Accept-Ranges: bytes\n"
  2429. "Vary: Accept-Encoding\n\n"
  2430. "%s\n", code, mg_http_status_code_str(code),strlen(fmt == NULL ? "" : fmt), fmt == NULL ? "" : fmt);
  2431. len = c->send.len;
  2432. va_start(ap, fmt);
  2433. r = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt?fmt:"", &ap);
  2434. va_end(ap);
  2435. c->is_resp = 0;
  2436. return r;
  2437. }
  2438. static void http_cb(struct mg_connection *, int, void *);
  2439. static void restore_http_cb(struct mg_connection *c) {
  2440. mg_fs_close((struct mg_fd *) c->pfn_data);
  2441. c->pfn_data = NULL;
  2442. c->pfn = http_cb;
  2443. c->is_resp = 0;
  2444. }
  2445. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
  2446. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime) {
  2447. mg_snprintf(buf, len, "\"%lld.%lld\"", (int64_t) mtime, (int64_t) size);
  2448. return buf;
  2449. }
  2450. static void static_cb(struct mg_connection *c, int ev, void *ev_data) {
  2451. if (ev == MG_EV_WRITE || ev == MG_EV_POLL) {
  2452. struct mg_fd *fd = (struct mg_fd *) c->pfn_data;
  2453. // Read to send IO buffer directly, avoid extra on-stack buffer
  2454. size_t n, max = MG_IO_SIZE, space;
  2455. size_t *cl = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2456. sizeof(size_t) * sizeof(size_t)];
  2457. if (c->send.size < max) mg_iobuf_resize(&c->send, max);
  2458. if (c->send.len >= c->send.size) return; // Rate limit
  2459. if ((space = c->send.size - c->send.len) > *cl) space = *cl;
  2460. n = fd->fs->rd(fd->fd, c->send.buf + c->send.len, space);
  2461. c->send.len += n;
  2462. *cl -= n;
  2463. if (n == 0) restore_http_cb(c);
  2464. } else if (ev == MG_EV_CLOSE) {
  2465. restore_http_cb(c);
  2466. }
  2467. (void) ev_data;
  2468. }
  2469. // Known mime types. Keep it outside guess_content_type() function, since
  2470. // some environments don't like it defined there.
  2471. // clang-format off
  2472. #define MG_C_STR(a) { (char *) (a), sizeof(a) - 1 }
  2473. static struct mg_str s_known_types[] = {
  2474. MG_C_STR("html"), MG_C_STR("text/html; charset=utf-8"),
  2475. MG_C_STR("htm"), MG_C_STR("text/html; charset=utf-8"),
  2476. MG_C_STR("css"), MG_C_STR("text/css; charset=utf-8"),
  2477. MG_C_STR("js"), MG_C_STR("text/javascript; charset=utf-8"),
  2478. MG_C_STR("gif"), MG_C_STR("image/gif"),
  2479. MG_C_STR("png"), MG_C_STR("image/png"),
  2480. MG_C_STR("jpg"), MG_C_STR("image/jpeg"),
  2481. MG_C_STR("jpeg"), MG_C_STR("image/jpeg"),
  2482. MG_C_STR("woff"), MG_C_STR("font/woff"),
  2483. MG_C_STR("ttf"), MG_C_STR("font/ttf"),
  2484. MG_C_STR("svg"), MG_C_STR("image/svg+xml"),
  2485. MG_C_STR("txt"), MG_C_STR("text/plain; charset=utf-8"),
  2486. MG_C_STR("avi"), MG_C_STR("video/x-msvideo"),
  2487. MG_C_STR("csv"), MG_C_STR("text/csv"),
  2488. MG_C_STR("doc"), MG_C_STR("application/msword"),
  2489. MG_C_STR("exe"), MG_C_STR("application/octet-stream"),
  2490. MG_C_STR("gz"), MG_C_STR("application/gzip"),
  2491. MG_C_STR("ico"), MG_C_STR("image/x-icon"),
  2492. MG_C_STR("json"), MG_C_STR("application/json"),
  2493. MG_C_STR("mov"), MG_C_STR("video/quicktime"),
  2494. MG_C_STR("mp3"), MG_C_STR("audio/mpeg"),
  2495. MG_C_STR("mp4"), MG_C_STR("video/mp4"),
  2496. MG_C_STR("mpeg"), MG_C_STR("video/mpeg"),
  2497. MG_C_STR("pdf"), MG_C_STR("application/pdf"),
  2498. MG_C_STR("shtml"), MG_C_STR("text/html; charset=utf-8"),
  2499. MG_C_STR("tgz"), MG_C_STR("application/tar-gz"),
  2500. MG_C_STR("wav"), MG_C_STR("audio/wav"),
  2501. MG_C_STR("webp"), MG_C_STR("image/webp"),
  2502. MG_C_STR("zip"), MG_C_STR("application/zip"),
  2503. MG_C_STR("3gp"), MG_C_STR("video/3gpp"),
  2504. {0, 0},
  2505. };
  2506. // clang-format on
  2507. static struct mg_str guess_content_type(struct mg_str path, const char *extra) {
  2508. struct mg_str entry, k, v, s = mg_str(extra);
  2509. size_t i = 0;
  2510. // Shrink path to its extension only
  2511. while (i < path.len && path.buf[path.len - i - 1] != '.') i++;
  2512. path.buf += path.len - i;
  2513. path.len = i;
  2514. // Process user-provided mime type overrides, if any
  2515. while (mg_span(s, &entry, &s, ',')) {
  2516. if (mg_span(entry, &k, &v, '=') && mg_strcmp(path, k) == 0) return v;
  2517. }
  2518. // Process built-in mime types
  2519. for (i = 0; s_known_types[i].buf != NULL; i += 2) {
  2520. if (mg_strcmp(path, s_known_types[i]) == 0) return s_known_types[i + 1];
  2521. }
  2522. return mg_str("text/plain; charset=utf-8");
  2523. }
  2524. static int getrange(struct mg_str *s, size_t *a, size_t *b) {
  2525. size_t i, numparsed = 0;
  2526. for (i = 0; i + 6 < s->len; i++) {
  2527. struct mg_str k, v = mg_str_n(s->buf + i + 6, s->len - i - 6);
  2528. if (memcmp(&s->buf[i], "bytes=", 6) != 0) continue;
  2529. if (mg_span(v, &k, &v, '-')) {
  2530. if (mg_to_size_t(k, a)) numparsed++;
  2531. if (v.len > 0 && mg_to_size_t(v, b)) numparsed++;
  2532. } else {
  2533. if (mg_to_size_t(v, a)) numparsed++;
  2534. }
  2535. break;
  2536. }
  2537. return (int) numparsed;
  2538. }
  2539. void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
  2540. const char *path,
  2541. const struct mg_http_serve_opts *opts) {
  2542. char etag[64], tmp[MG_PATH_MAX];
  2543. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2544. struct mg_fd *fd = NULL;
  2545. size_t size = 0;
  2546. time_t mtime = 0;
  2547. struct mg_str *inm = NULL;
  2548. struct mg_str mime = guess_content_type(mg_str(path), opts->mime_types);
  2549. bool gzip = false;
  2550. if (path != NULL) {
  2551. // If a browser sends us "Accept-Encoding: gzip", try to open .gz first
  2552. struct mg_str *ae = mg_http_get_header(hm, "Accept-Encoding");
  2553. if (ae != NULL) {
  2554. char *ae_ = mg_mprintf("%.*s", ae->len, ae->buf);
  2555. if (ae_ != NULL && strstr(ae_, "gzip") != NULL) {
  2556. mg_snprintf(tmp, sizeof(tmp), "%s.gz", path);
  2557. fd = mg_fs_open(fs, tmp, MG_FS_READ);
  2558. if (fd != NULL) gzip = true, path = tmp;
  2559. }
  2560. free(ae_);
  2561. }
  2562. // No luck opening .gz? Open what we've told to open
  2563. if (fd == NULL) fd = mg_fs_open(fs, path, MG_FS_READ);
  2564. }
  2565. // Failed to open, and page404 is configured? Open it, then
  2566. if (fd == NULL && opts->page404 != NULL) {
  2567. fd = mg_fs_open(fs, opts->page404, MG_FS_READ);
  2568. path = opts->page404;
  2569. mime = guess_content_type(mg_str(path), opts->mime_types);
  2570. }
  2571. if (fd == NULL || fs->st(path, &size, &mtime) == 0) {
  2572. mg_http_reply(c, 404, opts->extra_headers, "Not found\n");
  2573. mg_fs_close(fd);
  2574. // NOTE: mg_http_etag() call should go first!
  2575. } else if (mg_http_etag(etag, sizeof(etag), size, mtime) != NULL &&
  2576. (inm = mg_http_get_header(hm, "If-None-Match")) != NULL &&
  2577. mg_strcasecmp(*inm, mg_str(etag)) == 0) {
  2578. mg_fs_close(fd);
  2579. mg_http_reply(c, 304, opts->extra_headers, "");
  2580. } else {
  2581. int n, status = 200;
  2582. char range[100];
  2583. size_t r1 = 0, r2 = 0, cl = size;
  2584. // Handle Range header
  2585. struct mg_str *rh = mg_http_get_header(hm, "Range");
  2586. range[0] = '\0';
  2587. if (rh != NULL && (n = getrange(rh, &r1, &r2)) > 0) {
  2588. // If range is specified like "400-", set second limit to content len
  2589. if (n == 1) r2 = cl - 1;
  2590. if (r1 > r2 || r2 >= cl) {
  2591. status = 416;
  2592. cl = 0;
  2593. mg_snprintf(range, sizeof(range), "Content-Range: bytes */%lld\r\n",
  2594. (int64_t) size);
  2595. } else {
  2596. status = 206;
  2597. cl = r2 - r1 + 1;
  2598. mg_snprintf(range, sizeof(range),
  2599. "Content-Range: bytes %llu-%llu/%llu\r\n", (uint64_t) r1,
  2600. (uint64_t) (r1 + cl - 1), (uint64_t) size);
  2601. fs->sk(fd->fd, r1);
  2602. }
  2603. }
  2604. mg_printf(c,
  2605. "HTTP/1.1 %d %s\r\n"
  2606. "Content-Type: %.*s\r\n"
  2607. "Etag: %s\r\n"
  2608. "Content-Length: %llu\r\n"
  2609. "%s%s%s\r\n",
  2610. status, mg_http_status_code_str(status), (int) mime.len, mime.buf,
  2611. etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
  2612. range, opts->extra_headers ? opts->extra_headers : "");
  2613. if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0) {
  2614. c->is_draining = 1;
  2615. c->is_resp = 0;
  2616. mg_fs_close(fd);
  2617. } else {
  2618. // Track to-be-sent content length at the end of c->data, aligned
  2619. size_t *clp = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2620. sizeof(size_t) * sizeof(size_t)];
  2621. c->pfn = static_cb;
  2622. c->pfn_data = fd;
  2623. *clp = cl;
  2624. }
  2625. }
  2626. }
  2627. static char *get_fname(const char *path)
  2628. {
  2629. char *p=strrchr(path, '/');
  2630. if(p) {
  2631. return p+1;
  2632. }
  2633. return (char*)path;
  2634. }
  2635. void mg_http_serve_file2(struct mg_connection *c, struct mg_http_message *hm,
  2636. const char *path,
  2637. const struct mg_http_serve_opts *opts) {
  2638. char etag[64], tmp[MG_PATH_MAX];
  2639. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2640. struct mg_fd *fd = NULL;
  2641. size_t size = 0;
  2642. time_t mtime = 0;
  2643. struct mg_str *inm = NULL;
  2644. struct mg_str mime = guess_content_type(mg_str(path), opts->mime_types);
  2645. bool gzip = false;
  2646. if (path != NULL) {
  2647. // If a browser sends us "Accept-Encoding: gzip", try to open .gz first
  2648. struct mg_str *ae = mg_http_get_header(hm, "Accept-Encoding");
  2649. if (ae != NULL) {
  2650. char *ae_ = mg_mprintf("%.*s", ae->len, ae->buf);
  2651. if (ae_ != NULL && strstr(ae_, "gzip") != NULL) {
  2652. mg_snprintf(tmp, sizeof(tmp), "%s.gz", path);
  2653. fd = mg_fs_open(fs, tmp, MG_FS_READ);
  2654. if (fd != NULL) gzip = true, path = tmp;
  2655. }
  2656. free(ae_);
  2657. }
  2658. // No luck opening .gz? Open what we've told to open
  2659. if (fd == NULL) fd = mg_fs_open(fs, path, MG_FS_READ);
  2660. }
  2661. // Failed to open, and page404 is configured? Open it, then
  2662. if (fd == NULL && opts->page404 != NULL) {
  2663. fd = mg_fs_open(fs, opts->page404, MG_FS_READ);
  2664. path = opts->page404;
  2665. mime = guess_content_type(mg_str(path), opts->mime_types);
  2666. }
  2667. if (fd == NULL || fs->st(path, &size, &mtime) == 0) {
  2668. mg_http_reply(c, 404, opts->extra_headers, "Not found\n");
  2669. mg_fs_close(fd);
  2670. // NOTE: mg_http_etag() call should go first!
  2671. } else if (mg_http_etag(etag, sizeof(etag), size, mtime) != NULL &&
  2672. (inm = mg_http_get_header(hm, "If-None-Match")) != NULL &&
  2673. mg_strcasecmp(*inm, mg_str(etag)) == 0) {
  2674. mg_fs_close(fd);
  2675. mg_http_reply(c, 304, opts->extra_headers, "");
  2676. } else {
  2677. int n, status = 200;
  2678. char range[100];
  2679. size_t r1 = 0, r2 = 0, cl = size;
  2680. // Handle Range header
  2681. struct mg_str *rh = mg_http_get_header(hm, "Range");
  2682. range[0] = '\0';
  2683. if (rh != NULL && (n = getrange(rh, &r1, &r2)) > 0) {
  2684. // If range is specified like "400-", set second limit to content len
  2685. if (n == 1) r2 = cl - 1;
  2686. if (r1 > r2 || r2 >= cl) {
  2687. status = 416;
  2688. cl = 0;
  2689. mg_snprintf(range, sizeof(range), "Content-Range: bytes */%lld\r\n",
  2690. (int64_t) size);
  2691. } else {
  2692. status = 206;
  2693. cl = r2 - r1 + 1;
  2694. mg_snprintf(range, sizeof(range),
  2695. "Content-Range: bytes %llu-%llu/%llu\r\n", (uint64_t) r1,
  2696. (uint64_t) (r1 + cl - 1), (uint64_t) size);
  2697. fs->sk(fd->fd, r1);
  2698. }
  2699. }
  2700. mg_printf(c,
  2701. "HTTP/1.1 %d %s\r\n"
  2702. "Content-Type: %.*s\r\n"
  2703. "Content-Disposition: attachment;filename=%s\r\n"
  2704. "Etag: %s\r\n"
  2705. "Content-Length: %llu\r\n"
  2706. "%s%s%s\r\n",
  2707. status, mg_http_status_code_str(status), (int) mime.len, mime.buf,
  2708. get_fname(path),
  2709. etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
  2710. range, opts->extra_headers ? opts->extra_headers : "");
  2711. if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0) {
  2712. c->is_draining = 1;
  2713. c->is_resp = 0;
  2714. mg_fs_close(fd);
  2715. } else {
  2716. // Track to-be-sent content length at the end of c->data, aligned
  2717. size_t *clp = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2718. sizeof(size_t) * sizeof(size_t)];
  2719. c->pfn = static_cb;
  2720. c->pfn_data = fd;
  2721. *clp = cl;
  2722. }
  2723. }
  2724. }
  2725. struct printdirentrydata {
  2726. struct mg_connection *c;
  2727. struct mg_http_message *hm;
  2728. const struct mg_http_serve_opts *opts;
  2729. const char *dir;
  2730. };
  2731. #if MG_ENABLE_DIRLIST
  2732. static void printdirentry(const char *name, void *userdata) {
  2733. struct printdirentrydata *d = (struct printdirentrydata *) userdata;
  2734. struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs;
  2735. size_t size = 0;
  2736. time_t t = 0;
  2737. char path[MG_PATH_MAX], sz[40], mod[40];
  2738. int flags, n = 0;
  2739. // MG_DEBUG(("[%s] [%s]", d->dir, name));
  2740. if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >
  2741. sizeof(path)) {
  2742. MG_ERROR(("%s truncated", name));
  2743. } else if ((flags = fs->st(path, &size, &t)) == 0) {
  2744. MG_ERROR(("%lu stat(%s): %d", d->c->id, path, errno));
  2745. } else {
  2746. const char *slash = flags & MG_FS_DIR ? "/" : "";
  2747. if (flags & MG_FS_DIR) {
  2748. mg_snprintf(sz, sizeof(sz), "%s", "[DIR]");
  2749. } else {
  2750. mg_snprintf(sz, sizeof(sz), "%lld", (uint64_t) size);
  2751. }
  2752. #if defined(MG_HTTP_DIRLIST_TIME_FMT)
  2753. {
  2754. char time_str[40];
  2755. struct tm *time_info = localtime(&t);
  2756. strftime(time_str, sizeof time_str, "%Y/%m/%d %H:%M:%S", time_info);
  2757. mg_snprintf(mod, sizeof(mod), "%s", time_str);
  2758. }
  2759. #else
  2760. mg_snprintf(mod, sizeof(mod), "%lu", (unsigned long) t);
  2761. #endif
  2762. n = (int) mg_url_encode(name, strlen(name), path, sizeof(path));
  2763. mg_printf(d->c,
  2764. " <tr><td><a href=\"%.*s%s\">%s%s</a></td>"
  2765. "<td name=%lu>%s</td><td name=%lld>%s</td></tr>\n",
  2766. n, path, slash, name, slash, (unsigned long) t, mod,
  2767. flags & MG_FS_DIR ? (int64_t) -1 : (int64_t) size, sz);
  2768. }
  2769. }
  2770. static void listdir(struct mg_connection *c, struct mg_http_message *hm,
  2771. const struct mg_http_serve_opts *opts, char *dir) {
  2772. const char *sort_js_code =
  2773. "<script>function srt(tb, sc, so, d) {"
  2774. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  2775. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  2776. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  2777. "t1 = a.cells[2].getAttribute('name'), "
  2778. "t2 = b.cells[2].getAttribute('name'); "
  2779. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  2780. "n1 ? parseInt(n2) - parseInt(n1) : "
  2781. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  2782. const char *sort_js_code2 =
  2783. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  2784. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  2785. "};"
  2786. "window.onload = function() {"
  2787. "var tb = document.getElementById('tb');"
  2788. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  2789. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  2790. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  2791. "sc = c; ev.preventDefault();}};"
  2792. "srt(tb, sc, so, true);"
  2793. "}"
  2794. "</script>";
  2795. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2796. struct printdirentrydata d = {c, hm, opts, dir};
  2797. char tmp[10], buf[MG_PATH_MAX];
  2798. size_t off, n;
  2799. int len = mg_url_decode(hm->uri.buf, hm->uri.len, buf, sizeof(buf), 0);
  2800. struct mg_str uri = len > 0 ? mg_str_n(buf, (size_t) len) : hm->uri;
  2801. mg_printf(c,
  2802. "HTTP/1.1 200 OK\r\n"
  2803. "Content-Type: text/html; charset=utf-8\r\n"
  2804. "%s"
  2805. "Content-Length: \r\n\r\n",
  2806. opts->extra_headers == NULL ? "" : opts->extra_headers);
  2807. off = c->send.len; // Start of body
  2808. mg_printf(c,
  2809. "<!DOCTYPE html><html><head><title>Index of %.*s</title>%s%s"
  2810. "<style>th,td {text-align: left; padding-right: 1em; "
  2811. "font-family: monospace; }</style></head>"
  2812. "<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>"
  2813. "<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
  2814. "<a href=\"#\" rel=\"1\">Modified</a></th>"
  2815. "<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
  2816. "<tr><td colspan=\"3\"><hr></td></tr>"
  2817. "</thead>"
  2818. "<tbody id=\"tb\">\n",
  2819. (int) uri.len, uri.buf, sort_js_code, sort_js_code2, (int) uri.len,
  2820. uri.buf);
  2821. mg_printf(c, "%s",
  2822. " <tr><td><a href=\"..\">..</a></td>"
  2823. "<td name=-1></td><td name=-1>[DIR]</td></tr>\n");
  2824. fs->ls(dir, printdirentry, &d);
  2825. mg_printf(c,
  2826. "</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
  2827. "</table><address>Mongoose v.%s</address></body></html>\n",
  2828. MG_VERSION);
  2829. n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
  2830. if (n > sizeof(tmp)) n = 0;
  2831. memcpy(c->send.buf + off - 12, tmp, n); // Set content length
  2832. c->is_resp = 0; // Mark response end
  2833. }
  2834. #endif
  2835. // Resolve requested file into `path` and return its fs->st() result
  2836. static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
  2837. struct mg_fs *fs, struct mg_str url, struct mg_str dir,
  2838. char *path, size_t path_size) {
  2839. int flags, tmp;
  2840. // Append URI to the root_dir, and sanitize it
  2841. size_t n = mg_snprintf(path, path_size, "%.*s", (int) dir.len, dir.buf);
  2842. if (n + 2 >= path_size) {
  2843. mg_http_reply(c, 400, "", "Exceeded path size");
  2844. return -1;
  2845. }
  2846. path[path_size - 1] = '\0';
  2847. // Terminate root dir with slash
  2848. if (n > 0 && path[n - 1] != '/') path[n++] = '/', path[n] = '\0';
  2849. if (url.len < hm->uri.len) {
  2850. mg_url_decode(hm->uri.buf + url.len, hm->uri.len - url.len, path + n,
  2851. path_size - n, 0);
  2852. }
  2853. path[path_size - 1] = '\0'; // Double-check
  2854. if (!mg_path_is_sane(mg_str_n(path, path_size))) {
  2855. mg_http_reply(c, 400, "", "Invalid path");
  2856. return -1;
  2857. }
  2858. n = strlen(path);
  2859. while (n > 1 && path[n - 1] == '/') path[--n] = 0; // Trim trailing slashes
  2860. flags = mg_strcmp(hm->uri, mg_str("/")) == 0 ? MG_FS_DIR
  2861. : fs->st(path, NULL, NULL);
  2862. MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.buf, path,
  2863. flags));
  2864. if (flags == 0) {
  2865. // Do nothing - let's caller decide
  2866. } else if ((flags & MG_FS_DIR) && hm->uri.len > 0 &&
  2867. hm->uri.buf[hm->uri.len - 1] != '/') {
  2868. mg_printf(c,
  2869. "HTTP/1.1 301 Moved\r\n"
  2870. "Location: %.*s/\r\n"
  2871. "Content-Length: 0\r\n"
  2872. "\r\n",
  2873. (int) hm->uri.len, hm->uri.buf);
  2874. c->is_resp = 0;
  2875. flags = -1;
  2876. } else if (flags & MG_FS_DIR) {
  2877. if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
  2878. (tmp = fs->st(path, NULL, NULL)) != 0) ||
  2879. (mg_snprintf(path + n, path_size - n, "/index.shtml") > 0 &&
  2880. (tmp = fs->st(path, NULL, NULL)) != 0))) {
  2881. flags = tmp;
  2882. } else if ((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX ".gz") >
  2883. 0 &&
  2884. (tmp = fs->st(path, NULL, NULL)) !=
  2885. 0)) { // check for gzipped index
  2886. flags = tmp;
  2887. path[n + 1 + strlen(MG_HTTP_INDEX)] =
  2888. '\0'; // Remove appended .gz in index file name
  2889. } else {
  2890. path[n] = '\0'; // Remove appended index file name
  2891. }
  2892. }
  2893. return flags;
  2894. }
  2895. static int uri_to_path(struct mg_connection *c, struct mg_http_message *hm,
  2896. const struct mg_http_serve_opts *opts, char *path,
  2897. size_t path_size) {
  2898. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2899. struct mg_str k, v, part, s = mg_str(opts->root_dir), u = {NULL, 0}, p = u;
  2900. while (mg_span(s, &part, &s, ',')) {
  2901. if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
  2902. if (v.len == 0) v = k, k = mg_str("/"), u = k, p = v;
  2903. if (hm->uri.len < k.len) continue;
  2904. if (mg_strcmp(k, mg_str_n(hm->uri.buf, k.len)) != 0) continue;
  2905. u = k, p = v;
  2906. }
  2907. return uri_to_path2(c, hm, fs, u, p, path, path_size);
  2908. }
  2909. void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
  2910. const struct mg_http_serve_opts *opts) {
  2911. char path[MG_PATH_MAX];
  2912. const char *sp = opts->ssi_pattern;
  2913. int flags = uri_to_path(c, hm, opts, path, sizeof(path));
  2914. if (flags < 0) {
  2915. // Do nothing: the response has already been sent by uri_to_path()
  2916. } else if (flags & MG_FS_DIR) {
  2917. #if MG_ENABLE_DIRLIST
  2918. listdir(c, hm, opts, path);
  2919. #else
  2920. mg_http_reply(c, 403, "", "Forbidden\n");
  2921. #endif
  2922. } else if (flags && sp != NULL && mg_match(mg_str(path), mg_str(sp), NULL)) {
  2923. mg_http_serve_ssi(c, opts->root_dir, path);
  2924. } else {
  2925. mg_http_serve_file(c, hm, path, opts);
  2926. }
  2927. }
  2928. static bool mg_is_url_safe(int c) {
  2929. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
  2930. (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~';
  2931. }
  2932. size_t mg_url_encode(const char *s, size_t sl, char *buf, size_t len) {
  2933. size_t i, n = 0;
  2934. for (i = 0; i < sl; i++) {
  2935. int c = *(unsigned char *) &s[i];
  2936. if (n + 4 >= len) return 0;
  2937. if (mg_is_url_safe(c)) {
  2938. buf[n++] = s[i];
  2939. } else {
  2940. mg_snprintf(&buf[n], 4, "%%%M", mg_print_hex, 1, &s[i]);
  2941. n += 3;
  2942. }
  2943. }
  2944. if (len > 0 && n < len - 1) buf[n] = '\0'; // Null-terminate the destination
  2945. if (len > 0) buf[len - 1] = '\0'; // Always.
  2946. return n;
  2947. }
  2948. void mg_http_creds(struct mg_http_message *hm, char *user, size_t userlen,
  2949. char *pass, size_t passlen) {
  2950. struct mg_str *v = mg_http_get_header(hm, "Authorization");
  2951. user[0] = pass[0] = '\0';
  2952. if (v != NULL && v->len > 6 && memcmp(v->buf, "Basic ", 6) == 0) {
  2953. char buf[256];
  2954. size_t n = mg_base64_decode(v->buf + 6, v->len - 6, buf, sizeof(buf));
  2955. const char *p = (const char *) memchr(buf, ':', n > 0 ? n : 0);
  2956. if (p != NULL) {
  2957. mg_snprintf(user, userlen, "%.*s", p - buf, buf);
  2958. mg_snprintf(pass, passlen, "%.*s", n - (size_t) (p - buf) - 1, p + 1);
  2959. }
  2960. } else if (v != NULL && v->len > 7 && memcmp(v->buf, "Bearer ", 7) == 0) {
  2961. mg_snprintf(pass, passlen, "%.*s", (int) v->len - 7, v->buf + 7);
  2962. } else if ((v = mg_http_get_header(hm, "Cookie")) != NULL) {
  2963. struct mg_str t = mg_http_get_header_var(*v, mg_str_n("access_token", 12));
  2964. if (t.len > 0) mg_snprintf(pass, passlen, "%.*s", (int) t.len, t.buf);
  2965. } else {
  2966. mg_http_get_var(&hm->query, "access_token", pass, passlen);
  2967. }
  2968. }
  2969. static struct mg_str stripquotes(struct mg_str s) {
  2970. return s.len > 1 && s.buf[0] == '"' && s.buf[s.len - 1] == '"'
  2971. ? mg_str_n(s.buf + 1, s.len - 2)
  2972. : s;
  2973. }
  2974. struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v) {
  2975. size_t i;
  2976. for (i = 0; v.len > 0 && i + v.len + 2 < s.len; i++) {
  2977. if (s.buf[i + v.len] == '=' && memcmp(&s.buf[i], v.buf, v.len) == 0) {
  2978. const char *p = &s.buf[i + v.len + 1], *b = p, *x = &s.buf[s.len];
  2979. int q = p < x && *p == '"' ? 1 : 0;
  2980. while (p < x &&
  2981. (q ? p == b || *p != '"' : *p != ';' && *p != ' ' && *p != ','))
  2982. p++;
  2983. // MG_INFO(("[%.*s] [%.*s] [%.*s]", (int) s.len, s.buf, (int) v.len,
  2984. // v.buf, (int) (p - b), b));
  2985. return stripquotes(mg_str_n(b, (size_t) (p - b + q)));
  2986. }
  2987. }
  2988. return mg_str_n(NULL, 0);
  2989. }
  2990. long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
  2991. struct mg_fs *fs, const char *dir, size_t max_size) {
  2992. char buf[20] = "0", file[MG_PATH_MAX], path[MG_PATH_MAX];
  2993. long res = 0, offset;
  2994. mg_http_get_var(&hm->query, "offset", buf, sizeof(buf));
  2995. mg_http_get_var(&hm->query, "file", file, sizeof(file));
  2996. offset = strtol(buf, NULL, 0);
  2997. mg_snprintf(path, sizeof(path), "%s%c%s", dir, MG_DIRSEP, file);
  2998. if (hm->body.len == 0) {
  2999. mg_http_reply(c, 200, "", "%ld", res); // Nothing to write
  3000. } else if (file[0] == '\0') {
  3001. mg_http_reply(c, 400, "", "file required");
  3002. res = -1;
  3003. } else if (mg_path_is_sane(mg_str(file)) == false) {
  3004. mg_http_reply(c, 400, "", "%s: invalid file", file);
  3005. res = -2;
  3006. } else if (offset < 0) {
  3007. mg_http_reply(c, 400, "", "offset required");
  3008. res = -3;
  3009. } else if ((size_t) offset + hm->body.len > max_size) {
  3010. mg_http_reply(c, 400, "", "%s: over max size of %lu", path,
  3011. (unsigned long) max_size);
  3012. res = -4;
  3013. } else {
  3014. struct mg_fd *fd;
  3015. size_t current_size = 0;
  3016. MG_DEBUG(("%s -> %lu bytes @ %ld", path, hm->body.len, offset));
  3017. if (offset == 0) fs->rm(path); // If offset if 0, truncate file
  3018. fs->st(path, &current_size, NULL);
  3019. if (offset > 0 && current_size != (size_t) offset) {
  3020. mg_http_reply(c, 400, "", "%s: offset mismatch", path);
  3021. res = -5;
  3022. } else if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
  3023. mg_http_reply(c, 400, "", "open(%s): %d", path, errno);
  3024. res = -6;
  3025. } else {
  3026. res = offset + (long) fs->wr(fd->fd, hm->body.buf, hm->body.len);
  3027. mg_fs_close(fd);
  3028. mg_http_reply(c, 200, "", "%ld", res);
  3029. }
  3030. }
  3031. return res;
  3032. }
  3033. int mg_http_status(const struct mg_http_message *hm) {
  3034. return atoi(hm->uri.buf);
  3035. }
  3036. static bool is_hex_digit(int c) {
  3037. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  3038. (c >= 'A' && c <= 'F');
  3039. }
  3040. static int skip_chunk(const char *buf, int len, int *pl, int *dl) {
  3041. int i = 0, n = 0;
  3042. if (len < 3) return 0;
  3043. while (i < len && is_hex_digit(buf[i])) i++;
  3044. if (i == 0) return -1; // Error, no length specified
  3045. if (i > (int) sizeof(int) * 2) return -1; // Chunk length is too big
  3046. if (len < i + 1 || buf[i] != '\r' || buf[i + 1] != '\n') return -1; // Error
  3047. if (mg_str_to_num(mg_str_n(buf, (size_t) i), 16, &n, sizeof(int)) == false)
  3048. return -1; // Decode chunk length, overflow
  3049. if (n < 0) return -1; // Error. TODO(): some checks now redundant
  3050. if (n > len - i - 4) return 0; // Chunk not yet fully buffered
  3051. if (buf[i + n + 2] != '\r' || buf[i + n + 3] != '\n') return -1; // Error
  3052. *pl = i + 2, *dl = n;
  3053. return i + 2 + n + 2;
  3054. }
  3055. static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
  3056. if (ev == MG_EV_READ || ev == MG_EV_CLOSE) {
  3057. struct mg_http_message hm;
  3058. size_t ofs = 0; // Parsing offset
  3059. while (c->is_resp == 0 && ofs < c->recv.len) {
  3060. const char *buf = (char *) c->recv.buf + ofs;
  3061. int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
  3062. struct mg_str *te; // Transfer - encoding header
  3063. bool is_chunked = false;
  3064. if (n < 0) {
  3065. // We don't use mg_error() here, to avoid closing pipelined requests
  3066. // prematurely, see #2592
  3067. MG_ERROR(("HTTP parse, %lu bytes", c->recv.len));
  3068. c->is_draining = 1;
  3069. mg_hexdump(buf, c->recv.len - ofs > 16 ? 16 : c->recv.len - ofs);
  3070. c->recv.len = 0;
  3071. return;
  3072. }
  3073. if (n == 0) break; // Request is not buffered yet
  3074. mg_call(c, MG_EV_HTTP_HDRS, &hm); // Got all HTTP headers
  3075. if (ev == MG_EV_CLOSE) { // If client did not set Content-Length
  3076. hm.message.len = c->recv.len - ofs; // and closes now, deliver MSG
  3077. hm.body.len = hm.message.len - (size_t) (hm.body.buf - hm.message.buf);
  3078. }
  3079. if ((te = mg_http_get_header(&hm, "Transfer-Encoding")) != NULL) {
  3080. if (mg_strcasecmp(*te, mg_str("chunked")) == 0) {
  3081. is_chunked = true;
  3082. } else {
  3083. mg_error(c, "Invalid Transfer-Encoding"); // See #2460
  3084. return;
  3085. }
  3086. } else if (mg_http_get_header(&hm, "Content-length") == NULL) {
  3087. // #2593: HTTP packets must contain either Transfer-Encoding or
  3088. // Content-length
  3089. bool is_response = mg_ncasecmp(hm.method.buf, "HTTP/", 5) == 0;
  3090. bool require_content_len = false;
  3091. if (!is_response && (mg_strcasecmp(hm.method, mg_str("POST")) == 0 ||
  3092. mg_strcasecmp(hm.method, mg_str("PUT")) == 0)) {
  3093. // POST and PUT should include an entity body. Therefore, they should
  3094. // contain a Content-length header. Other requests can also contain a
  3095. // body, but their content has no defined semantics (RFC 7231)
  3096. require_content_len = true;
  3097. } else if (is_response) {
  3098. // HTTP spec 7.2 Entity body: All other responses must include a body
  3099. // or Content-Length header field defined with a value of 0.
  3100. int status = mg_http_status(&hm);
  3101. require_content_len = status >= 200 && status != 204 && status != 304;
  3102. }
  3103. if (require_content_len) {
  3104. mg_http_reply(c, 411, "", "");
  3105. MG_ERROR(("%s", "Content length missing from request"));
  3106. }
  3107. }
  3108. if (is_chunked) {
  3109. // For chunked data, strip off prefixes and suffixes from chunks
  3110. // and relocate them right after the headers, then report a message
  3111. char *s = (char *) c->recv.buf + ofs + n;
  3112. int o = 0, pl, dl, cl, len = (int) (c->recv.len - ofs - (size_t) n);
  3113. // Find zero-length chunk (the end of the body)
  3114. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0 && dl) o += cl;
  3115. if (cl == 0) break; // No zero-len chunk, buffer more data
  3116. if (cl < 0) {
  3117. mg_error(c, "Invalid chunk");
  3118. break;
  3119. }
  3120. // Zero chunk found. Second pass: strip + relocate
  3121. o = 0, hm.body.len = 0, hm.message.len = (size_t) n;
  3122. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0) {
  3123. memmove(s + hm.body.len, s + o + pl, (size_t) dl);
  3124. o += cl, hm.body.len += (size_t) dl, hm.message.len += (size_t) dl;
  3125. if (dl == 0) break;
  3126. }
  3127. ofs += (size_t) (n + o);
  3128. } else { // Normal, non-chunked data
  3129. size_t len = c->recv.len - ofs - (size_t) n;
  3130. if (hm.body.len > len) break; // Buffer more data
  3131. ofs += (size_t) n + hm.body.len;
  3132. }
  3133. if (c->is_accepted) c->is_resp = 1; // Start generating response
  3134. mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp
  3135. }
  3136. if (ofs > 0) mg_iobuf_del(&c->recv, 0, ofs); // Delete processed data
  3137. }
  3138. (void) ev_data;
  3139. }
  3140. static void mg_hfn(struct mg_connection *c, int ev, void *ev_data) {
  3141. if (ev == MG_EV_HTTP_MSG) {
  3142. struct mg_http_message *hm = (struct mg_http_message *) ev_data;
  3143. if (mg_match(hm->uri, mg_str("/quit"), NULL)) {
  3144. mg_http_reply(c, 200, "", "ok\n");
  3145. c->is_draining = 1;
  3146. c->data[0] = 'X';
  3147. } else if (mg_match(hm->uri, mg_str("/debug"), NULL)) {
  3148. int level = (int) mg_json_get_long(hm->body, "$.level", MG_LL_DEBUG);
  3149. mg_log_set(level);
  3150. mg_http_reply(c, 200, "", "Debug level set to %d\n", level);
  3151. } else {
  3152. mg_http_reply(c, 200, "", "hi\n");
  3153. }
  3154. } else if (ev == MG_EV_CLOSE) {
  3155. if (c->data[0] == 'X') *(bool *) c->fn_data = true;
  3156. }
  3157. }
  3158. void mg_hello(const char *url) {
  3159. struct mg_mgr mgr;
  3160. bool done = false;
  3161. mg_mgr_init(&mgr);
  3162. if (mg_http_listen(&mgr, url, mg_hfn, &done) == NULL) done = true;
  3163. while (done == false) mg_mgr_poll(&mgr, 100);
  3164. mg_mgr_free(&mgr);
  3165. }
  3166. struct mg_connection *mg_http_connect(struct mg_mgr *mgr, const char *url,
  3167. mg_event_handler_t fn, void *fn_data) {
  3168. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  3169. if (c != NULL) c->pfn = http_cb;
  3170. return c;
  3171. }
  3172. struct mg_connection *mg_http_listen(struct mg_mgr *mgr, const char *url,
  3173. mg_event_handler_t fn, void *fn_data) {
  3174. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  3175. if (c != NULL) c->pfn = http_cb;
  3176. return c;
  3177. }
  3178. #ifdef MG_ENABLE_LINES
  3179. #line 1 "src/iobuf.c"
  3180. #endif
  3181. static size_t roundup(size_t size, size_t align) {
  3182. return align == 0 ? size : (size + align - 1) / align * align;
  3183. }
  3184. int mg_iobuf_resize(struct mg_iobuf *io, size_t new_size) {
  3185. int ok = 1;
  3186. new_size = roundup(new_size, io->align);
  3187. if (new_size == 0) {
  3188. mg_bzero(io->buf, io->size);
  3189. free(io->buf);
  3190. io->buf = NULL;
  3191. io->len = io->size = 0;
  3192. } else if (new_size != io->size) {
  3193. // NOTE(lsm): do not use realloc here. Use calloc/free only, to ease the
  3194. // porting to some obscure platforms like FreeRTOS
  3195. void *p = calloc(1, new_size);
  3196. if (p != NULL) {
  3197. size_t len = new_size < io->len ? new_size : io->len;
  3198. if (len > 0 && io->buf != NULL) memmove(p, io->buf, len);
  3199. mg_bzero(io->buf, io->size);
  3200. free(io->buf);
  3201. io->buf = (unsigned char *) p;
  3202. io->size = new_size;
  3203. } else {
  3204. ok = 0;
  3205. MG_ERROR(("%lld->%lld", (uint64_t) io->size, (uint64_t) new_size));
  3206. }
  3207. }
  3208. return ok;
  3209. }
  3210. int mg_iobuf_init(struct mg_iobuf *io, size_t size, size_t align) {
  3211. io->buf = NULL;
  3212. io->align = align;
  3213. io->size = io->len = 0;
  3214. return mg_iobuf_resize(io, size);
  3215. }
  3216. size_t mg_iobuf_add(struct mg_iobuf *io, size_t ofs, const void *buf,
  3217. size_t len) {
  3218. size_t new_size = roundup(io->len + len, io->align);
  3219. mg_iobuf_resize(io, new_size); // Attempt to resize
  3220. if (new_size != io->size) len = 0; // Resize failure, append nothing
  3221. if (ofs < io->len) memmove(io->buf + ofs + len, io->buf + ofs, io->len - ofs);
  3222. if (buf != NULL) memmove(io->buf + ofs, buf, len);
  3223. if (ofs > io->len) io->len += ofs - io->len;
  3224. io->len += len;
  3225. return len;
  3226. }
  3227. size_t mg_iobuf_del(struct mg_iobuf *io, size_t ofs, size_t len) {
  3228. if (ofs > io->len) ofs = io->len;
  3229. if (ofs + len > io->len) len = io->len - ofs;
  3230. if (io->buf) memmove(io->buf + ofs, io->buf + ofs + len, io->len - ofs - len);
  3231. if (io->buf) mg_bzero(io->buf + io->len - len, len);
  3232. io->len -= len;
  3233. return len;
  3234. }
  3235. void mg_iobuf_free(struct mg_iobuf *io) {
  3236. mg_iobuf_resize(io, 0);
  3237. }
  3238. #ifdef MG_ENABLE_LINES
  3239. #line 1 "src/json.c"
  3240. #endif
  3241. static const char *escapeseq(int esc) {
  3242. return esc ? "\b\f\n\r\t\\\"" : "bfnrt\\\"";
  3243. }
  3244. static char json_esc(int c, int esc) {
  3245. const char *p, *esc1 = escapeseq(esc), *esc2 = escapeseq(!esc);
  3246. for (p = esc1; *p != '\0'; p++) {
  3247. if (*p == c) return esc2[p - esc1];
  3248. }
  3249. return 0;
  3250. }
  3251. static int mg_pass_string(const char *s, int len) {
  3252. int i;
  3253. for (i = 0; i < len; i++) {
  3254. if (s[i] == '\\' && i + 1 < len && json_esc(s[i + 1], 1)) {
  3255. i++;
  3256. } else if (s[i] == '\0') {
  3257. return MG_JSON_INVALID;
  3258. } else if (s[i] == '"') {
  3259. return i;
  3260. }
  3261. }
  3262. return MG_JSON_INVALID;
  3263. }
  3264. static double mg_atod(const char *p, int len, int *numlen) {
  3265. double d = 0.0;
  3266. int i = 0, sign = 1;
  3267. // Sign
  3268. if (i < len && *p == '-') {
  3269. sign = -1, i++;
  3270. } else if (i < len && *p == '+') {
  3271. i++;
  3272. }
  3273. // Decimal
  3274. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  3275. d *= 10.0;
  3276. d += p[i] - '0';
  3277. }
  3278. d *= sign;
  3279. // Fractional
  3280. if (i < len && p[i] == '.') {
  3281. double frac = 0.0, base = 0.1;
  3282. i++;
  3283. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  3284. frac += base * (p[i] - '0');
  3285. base /= 10.0;
  3286. }
  3287. d += frac * sign;
  3288. }
  3289. // Exponential
  3290. if (i < len && (p[i] == 'e' || p[i] == 'E')) {
  3291. int j, exp = 0, minus = 0;
  3292. i++;
  3293. if (i < len && p[i] == '-') minus = 1, i++;
  3294. if (i < len && p[i] == '+') i++;
  3295. while (i < len && p[i] >= '0' && p[i] <= '9' && exp < 308)
  3296. exp = exp * 10 + (p[i++] - '0');
  3297. if (minus) exp = -exp;
  3298. for (j = 0; j < exp; j++) d *= 10.0;
  3299. for (j = 0; j < -exp; j++) d /= 10.0;
  3300. }
  3301. if (numlen != NULL) *numlen = i;
  3302. return d;
  3303. }
  3304. // Iterate over object or array elements
  3305. size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key,
  3306. struct mg_str *val) {
  3307. if (ofs >= obj.len) {
  3308. ofs = 0; // Out of boundaries, stop scanning
  3309. } else if (obj.len < 2 || (*obj.buf != '{' && *obj.buf != '[')) {
  3310. ofs = 0; // Not an array or object, stop
  3311. } else {
  3312. struct mg_str sub = mg_str_n(obj.buf + ofs, obj.len - ofs);
  3313. if (ofs == 0) ofs++, sub.buf++, sub.len--;
  3314. if (*obj.buf == '[') { // Iterate over an array
  3315. int n = 0, o = mg_json_get(sub, "$", &n);
  3316. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3317. ofs = 0; // Error parsing key, stop scanning
  3318. } else {
  3319. if (key) *key = mg_str_n(NULL, 0);
  3320. if (val) *val = mg_str_n(sub.buf + o, (size_t) n);
  3321. ofs = (size_t) (&sub.buf[o + n] - obj.buf);
  3322. }
  3323. } else { // Iterate over an object
  3324. int n = 0, o = mg_json_get(sub, "$", &n);
  3325. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3326. ofs = 0; // Error parsing key, stop scanning
  3327. } else {
  3328. if (key) *key = mg_str_n(sub.buf + o, (size_t) n);
  3329. sub.buf += o + n, sub.len -= (size_t) (o + n);
  3330. while (sub.len > 0 && *sub.buf != ':') sub.len--, sub.buf++;
  3331. if (sub.len > 0 && *sub.buf == ':') sub.len--, sub.buf++;
  3332. n = 0, o = mg_json_get(sub, "$", &n);
  3333. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3334. ofs = 0; // Error parsing value, stop scanning
  3335. } else {
  3336. if (val) *val = mg_str_n(sub.buf + o, (size_t) n);
  3337. ofs = (size_t) (&sub.buf[o + n] - obj.buf);
  3338. }
  3339. }
  3340. }
  3341. // MG_INFO(("SUB ofs %u %.*s", ofs, sub.len, sub.buf));
  3342. while (ofs && ofs < obj.len &&
  3343. (obj.buf[ofs] == ' ' || obj.buf[ofs] == '\t' ||
  3344. obj.buf[ofs] == '\n' || obj.buf[ofs] == '\r')) {
  3345. ofs++;
  3346. }
  3347. if (ofs && ofs < obj.len && obj.buf[ofs] == ',') ofs++;
  3348. if (ofs > obj.len) ofs = 0;
  3349. }
  3350. return ofs;
  3351. }
  3352. int mg_json_get(struct mg_str json, const char *path, int *toklen) {
  3353. const char *s = json.buf;
  3354. int len = (int) json.len;
  3355. enum { S_VALUE, S_KEY, S_COLON, S_COMMA_OR_EOO } expecting = S_VALUE;
  3356. unsigned char nesting[MG_JSON_MAX_DEPTH];
  3357. int i = 0; // Current offset in `s`
  3358. int j = 0; // Offset in `s` we're looking for (return value)
  3359. int depth = 0; // Current depth (nesting level)
  3360. int ed = 0; // Expected depth
  3361. int pos = 1; // Current position in `path`
  3362. int ci = -1, ei = -1; // Current and expected index in array
  3363. if (toklen) *toklen = 0;
  3364. if (path[0] != '$') return MG_JSON_INVALID;
  3365. #define MG_CHECKRET(x) \
  3366. do { \
  3367. if (depth == ed && path[pos] == '\0' && ci == ei) { \
  3368. if (toklen) *toklen = i - j + 1; \
  3369. return j; \
  3370. } \
  3371. } while (0)
  3372. // In the ascii table, the distance between `[` and `]` is 2.
  3373. // Ditto for `{` and `}`. Hence +2 in the code below.
  3374. #define MG_EOO(x) \
  3375. do { \
  3376. if (depth == ed && ci != ei) return MG_JSON_NOT_FOUND; \
  3377. if (c != nesting[depth - 1] + 2) return MG_JSON_INVALID; \
  3378. depth--; \
  3379. MG_CHECKRET(x); \
  3380. } while (0)
  3381. for (i = 0; i < len; i++) {
  3382. unsigned char c = ((unsigned char *) s)[i];
  3383. if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
  3384. switch (expecting) {
  3385. case S_VALUE:
  3386. // p("V %s [%.*s] %d %d %d %d\n", path, pos, path, depth, ed, ci, ei);
  3387. if (depth == ed) j = i;
  3388. if (c == '{') {
  3389. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  3390. if (depth == ed && path[pos] == '.' && ci == ei) {
  3391. // If we start the object, reset array indices
  3392. ed++, pos++, ci = ei = -1;
  3393. }
  3394. nesting[depth++] = c;
  3395. expecting = S_KEY;
  3396. break;
  3397. } else if (c == '[') {
  3398. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  3399. if (depth == ed && path[pos] == '[' && ei == ci) {
  3400. ed++, pos++, ci = 0;
  3401. for (ei = 0; path[pos] != ']' && path[pos] != '\0'; pos++) {
  3402. ei *= 10;
  3403. ei += path[pos] - '0';
  3404. }
  3405. if (path[pos] != 0) pos++;
  3406. }
  3407. nesting[depth++] = c;
  3408. break;
  3409. } else if (c == ']' && depth > 0) { // Empty array
  3410. MG_EOO(']');
  3411. } else if (c == 't' && i + 3 < len && memcmp(&s[i], "true", 4) == 0) {
  3412. i += 3;
  3413. } else if (c == 'n' && i + 3 < len && memcmp(&s[i], "null", 4) == 0) {
  3414. i += 3;
  3415. } else if (c == 'f' && i + 4 < len && memcmp(&s[i], "false", 5) == 0) {
  3416. i += 4;
  3417. } else if (c == '-' || ((c >= '0' && c <= '9'))) {
  3418. int numlen = 0;
  3419. mg_atod(&s[i], len - i, &numlen);
  3420. i += numlen - 1;
  3421. } else if (c == '"') {
  3422. int n = mg_pass_string(&s[i + 1], len - i - 1);
  3423. if (n < 0) return n;
  3424. i += n + 1;
  3425. } else {
  3426. return MG_JSON_INVALID;
  3427. }
  3428. MG_CHECKRET('V');
  3429. if (depth == ed && ei >= 0) ci++;
  3430. expecting = S_COMMA_OR_EOO;
  3431. break;
  3432. case S_KEY:
  3433. if (c == '"') {
  3434. int n = mg_pass_string(&s[i + 1], len - i - 1);
  3435. if (n < 0) return n;
  3436. if (i + 1 + n >= len) return MG_JSON_NOT_FOUND;
  3437. if (depth < ed) return MG_JSON_NOT_FOUND;
  3438. if (depth == ed && path[pos - 1] != '.') return MG_JSON_NOT_FOUND;
  3439. // printf("K %s [%.*s] [%.*s] %d %d %d %d %d\n", path, pos, path, n,
  3440. // &s[i + 1], n, depth, ed, ci, ei);
  3441. // NOTE(cpq): in the check sequence below is important.
  3442. // strncmp() must go first: it fails fast if the remaining length
  3443. // of the path is smaller than `n`.
  3444. if (depth == ed && path[pos - 1] == '.' &&
  3445. strncmp(&s[i + 1], &path[pos], (size_t) n) == 0 &&
  3446. (path[pos + n] == '\0' || path[pos + n] == '.' ||
  3447. path[pos + n] == '[')) {
  3448. pos += n;
  3449. }
  3450. i += n + 1;
  3451. expecting = S_COLON;
  3452. } else if (c == '}') { // Empty object
  3453. MG_EOO('}');
  3454. expecting = S_COMMA_OR_EOO;
  3455. if (depth == ed && ei >= 0) ci++;
  3456. } else {
  3457. return MG_JSON_INVALID;
  3458. }
  3459. break;
  3460. case S_COLON:
  3461. if (c == ':') {
  3462. expecting = S_VALUE;
  3463. } else {
  3464. return MG_JSON_INVALID;
  3465. }
  3466. break;
  3467. case S_COMMA_OR_EOO:
  3468. if (depth <= 0) {
  3469. return MG_JSON_INVALID;
  3470. } else if (c == ',') {
  3471. expecting = (nesting[depth - 1] == '{') ? S_KEY : S_VALUE;
  3472. } else if (c == ']' || c == '}') {
  3473. if (depth == ed && c == '}' && path[pos - 1] == '.')
  3474. return MG_JSON_NOT_FOUND;
  3475. if (depth == ed && c == ']' && path[pos - 1] == ',')
  3476. return MG_JSON_NOT_FOUND;
  3477. MG_EOO('O');
  3478. if (depth == ed && ei >= 0) ci++;
  3479. } else {
  3480. return MG_JSON_INVALID;
  3481. }
  3482. break;
  3483. }
  3484. }
  3485. return MG_JSON_NOT_FOUND;
  3486. }
  3487. struct mg_str mg_json_get_tok(struct mg_str json, const char *path) {
  3488. int len = 0, ofs = mg_json_get(json, path, &len);
  3489. return mg_str_n(ofs < 0 ? NULL : json.buf + ofs,
  3490. (size_t) (len < 0 ? 0 : len));
  3491. }
  3492. bool mg_json_get_num(struct mg_str json, const char *path, double *v) {
  3493. int n, toklen, found = 0;
  3494. if ((n = mg_json_get(json, path, &toklen)) >= 0 &&
  3495. (json.buf[n] == '-' || (json.buf[n] >= '0' && json.buf[n] <= '9'))) {
  3496. if (v != NULL) *v = mg_atod(json.buf + n, toklen, NULL);
  3497. found = 1;
  3498. }
  3499. return found;
  3500. }
  3501. bool mg_json_get_bool(struct mg_str json, const char *path, bool *v) {
  3502. int found = 0, off = mg_json_get(json, path, NULL);
  3503. if (off >= 0 && (json.buf[off] == 't' || json.buf[off] == 'f')) {
  3504. if (v != NULL) *v = json.buf[off] == 't';
  3505. found = 1;
  3506. }
  3507. return found;
  3508. }
  3509. bool mg_json_unescape(struct mg_str s, char *to, size_t n) {
  3510. size_t i, j;
  3511. for (i = 0, j = 0; i < s.len && j < n; i++, j++) {
  3512. if (s.buf[i] == '\\' && i + 5 < s.len && s.buf[i + 1] == 'u') {
  3513. // \uXXXX escape. We process simple one-byte chars \u00xx within ASCII
  3514. // range. More complex chars would require dragging in a UTF8 library,
  3515. // which is too much for us
  3516. if (mg_str_to_num(mg_str_n(s.buf + i + 2, 4), 16, &to[j],
  3517. sizeof(uint8_t)) == false)
  3518. return false;
  3519. i += 5;
  3520. } else if (s.buf[i] == '\\' && i + 1 < s.len) {
  3521. char c = json_esc(s.buf[i + 1], 0);
  3522. if (c == 0) return false;
  3523. to[j] = c;
  3524. i++;
  3525. } else {
  3526. to[j] = s.buf[i];
  3527. }
  3528. }
  3529. if (j >= n) return false;
  3530. if (n > 0) to[j] = '\0';
  3531. return true;
  3532. }
  3533. char *mg_json_get_str(struct mg_str json, const char *path) {
  3534. char *result = NULL;
  3535. int len = 0, off = mg_json_get(json, path, &len);
  3536. if (off >= 0 && len > 1 && json.buf[off] == '"') {
  3537. if ((result = (char *) calloc(1, (size_t) len)) != NULL &&
  3538. !mg_json_unescape(mg_str_n(json.buf + off + 1, (size_t) (len - 2)),
  3539. result, (size_t) len)) {
  3540. free(result);
  3541. result = NULL;
  3542. }
  3543. }
  3544. return result;
  3545. }
  3546. char *mg_json_get_b64(struct mg_str json, const char *path, int *slen) {
  3547. char *result = NULL;
  3548. int len = 0, off = mg_json_get(json, path, &len);
  3549. if (off >= 0 && json.buf[off] == '"' && len > 1 &&
  3550. (result = (char *) calloc(1, (size_t) len)) != NULL) {
  3551. size_t k = mg_base64_decode(json.buf + off + 1, (size_t) (len - 2), result,
  3552. (size_t) len);
  3553. if (slen != NULL) *slen = (int) k;
  3554. }
  3555. return result;
  3556. }
  3557. char *mg_json_get_hex(struct mg_str json, const char *path, int *slen) {
  3558. char *result = NULL;
  3559. int len = 0, off = mg_json_get(json, path, &len);
  3560. if (off >= 0 && json.buf[off] == '"' && len > 1 &&
  3561. (result = (char *) calloc(1, (size_t) len / 2)) != NULL) {
  3562. int i;
  3563. for (i = 0; i < len - 2; i += 2) {
  3564. mg_str_to_num(mg_str_n(json.buf + off + 1 + i, 2), 16, &result[i >> 1],
  3565. sizeof(uint8_t));
  3566. }
  3567. result[len / 2 - 1] = '\0';
  3568. if (slen != NULL) *slen = len / 2 - 1;
  3569. }
  3570. return result;
  3571. }
  3572. long mg_json_get_long(struct mg_str json, const char *path, long dflt) {
  3573. double dv;
  3574. long result = dflt;
  3575. if (mg_json_get_num(json, path, &dv)) result = (long) dv;
  3576. return result;
  3577. }
  3578. #ifdef MG_ENABLE_LINES
  3579. #line 1 "src/log.c"
  3580. #endif
  3581. int mg_log_level = MG_LL_INFO;
  3582. static mg_pfn_t s_log_func = mg_pfn_stdout;
  3583. static void *s_log_func_param = NULL;
  3584. void mg_log_set_fn(mg_pfn_t fn, void *param) {
  3585. s_log_func = fn;
  3586. s_log_func_param = param;
  3587. }
  3588. static void logc(unsigned char c) {
  3589. s_log_func((char) c, s_log_func_param);
  3590. }
  3591. static void logs(const char *buf, size_t len) {
  3592. size_t i;
  3593. for (i = 0; i < len; i++) logc(((unsigned char *) buf)[i]);
  3594. }
  3595. #if MG_ENABLE_CUSTOM_LOG
  3596. // Let user define their own mg_log_prefix() and mg_log()
  3597. #else
  3598. void mg_log_prefix(int level, const char *file, int line, const char *fname) {
  3599. const char *p = strrchr(file, '/');
  3600. char buf[41];
  3601. size_t n;
  3602. if (p == NULL) p = strrchr(file, '\\');
  3603. n = mg_snprintf(buf, sizeof(buf), "%-6llx %d %s:%d:%s", mg_millis(), level,
  3604. p == NULL ? file : p + 1, line, fname);
  3605. if (n > sizeof(buf) - 2) n = sizeof(buf) - 2;
  3606. while (n < sizeof(buf)) buf[n++] = ' ';
  3607. logs(buf, n - 1);
  3608. }
  3609. void mg_log(const char *fmt, ...) {
  3610. va_list ap;
  3611. va_start(ap, fmt);
  3612. mg_vxprintf(s_log_func, s_log_func_param, fmt, &ap);
  3613. va_end(ap);
  3614. logs("\r\n", 2);
  3615. }
  3616. #endif
  3617. static unsigned char nibble(unsigned c) {
  3618. return (unsigned char) (c < 10 ? c + '0' : c + 'W');
  3619. }
  3620. #define ISPRINT(x) ((x) >= ' ' && (x) <= '~')
  3621. void mg_hexdump(const void *buf, size_t len) {
  3622. const unsigned char *p = (const unsigned char *) buf;
  3623. unsigned char ascii[16], alen = 0;
  3624. size_t i;
  3625. for (i = 0; i < len; i++) {
  3626. if ((i % 16) == 0) {
  3627. // Print buffered ascii chars
  3628. if (i > 0) logs(" ", 2), logs((char *) ascii, 16), logc('\n'), alen = 0;
  3629. // Print hex address, then \t
  3630. logc(nibble((i >> 12) & 15)), logc(nibble((i >> 8) & 15)),
  3631. logc(nibble((i >> 4) & 15)), logc('0'), logs(" ", 3);
  3632. }
  3633. logc(nibble(p[i] >> 4)), logc(nibble(p[i] & 15)); // Two nibbles, e.g. c5
  3634. logc(' '); // Space after hex number
  3635. ascii[alen++] = ISPRINT(p[i]) ? p[i] : '.'; // Add to the ascii buf
  3636. }
  3637. while (alen < 16) logs(" ", 3), ascii[alen++] = ' ';
  3638. logs(" ", 2), logs((char *) ascii, 16), logc('\n');
  3639. }
  3640. #ifdef MG_ENABLE_LINES
  3641. #line 1 "src/md5.c"
  3642. #endif
  3643. // This code implements the MD5 message-digest algorithm.
  3644. // The algorithm is due to Ron Rivest. This code was
  3645. // written by Colin Plumb in 1993, no copyright is claimed.
  3646. // This code is in the public domain; do with it what you wish.
  3647. //
  3648. // Equivalent code is available from RSA Data Security, Inc.
  3649. // This code has been tested against that, and is equivalent,
  3650. // except that you don't need to include two pages of legalese
  3651. // with every copy.
  3652. //
  3653. // To compute the message digest of a chunk of bytes, declare an
  3654. // MD5Context structure, pass it to MD5Init, call MD5Update as
  3655. // needed on buffers full of bytes, and then call MD5Final, which
  3656. // will fill a supplied 16-byte array with the digest.
  3657. #if defined(MG_ENABLE_MD5) && MG_ENABLE_MD5
  3658. static void mg_byte_reverse(unsigned char *buf, unsigned longs) {
  3659. if (MG_BIG_ENDIAN) {
  3660. do {
  3661. uint32_t t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  3662. ((unsigned) buf[1] << 8 | buf[0]);
  3663. *(uint32_t *) buf = t;
  3664. buf += 4;
  3665. } while (--longs);
  3666. } else {
  3667. (void) buf, (void) longs; // Little endian. Do nothing
  3668. }
  3669. }
  3670. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  3671. #define F2(x, y, z) F1(z, x, y)
  3672. #define F3(x, y, z) (x ^ y ^ z)
  3673. #define F4(x, y, z) (y ^ (x | ~z))
  3674. #define MD5STEP(f, w, x, y, z, data, s) \
  3675. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  3676. /*
  3677. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  3678. * initialization constants.
  3679. */
  3680. void mg_md5_init(mg_md5_ctx *ctx) {
  3681. ctx->buf[0] = 0x67452301;
  3682. ctx->buf[1] = 0xefcdab89;
  3683. ctx->buf[2] = 0x98badcfe;
  3684. ctx->buf[3] = 0x10325476;
  3685. ctx->bits[0] = 0;
  3686. ctx->bits[1] = 0;
  3687. }
  3688. static void mg_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
  3689. uint32_t a, b, c, d;
  3690. a = buf[0];
  3691. b = buf[1];
  3692. c = buf[2];
  3693. d = buf[3];
  3694. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  3695. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  3696. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  3697. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  3698. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  3699. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  3700. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  3701. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  3702. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  3703. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  3704. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  3705. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  3706. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  3707. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  3708. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  3709. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  3710. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  3711. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  3712. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  3713. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  3714. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  3715. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  3716. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  3717. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  3718. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  3719. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  3720. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  3721. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  3722. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  3723. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  3724. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  3725. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  3726. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  3727. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  3728. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  3729. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  3730. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  3731. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  3732. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  3733. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  3734. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  3735. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  3736. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  3737. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  3738. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  3739. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  3740. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  3741. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  3742. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  3743. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  3744. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  3745. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  3746. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  3747. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  3748. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  3749. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  3750. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  3751. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  3752. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  3753. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  3754. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  3755. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  3756. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  3757. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  3758. buf[0] += a;
  3759. buf[1] += b;
  3760. buf[2] += c;
  3761. buf[3] += d;
  3762. }
  3763. void mg_md5_update(mg_md5_ctx *ctx, const unsigned char *buf, size_t len) {
  3764. uint32_t t;
  3765. t = ctx->bits[0];
  3766. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  3767. ctx->bits[1] += (uint32_t) len >> 29;
  3768. t = (t >> 3) & 0x3f;
  3769. if (t) {
  3770. unsigned char *p = (unsigned char *) ctx->in + t;
  3771. t = 64 - t;
  3772. if (len < t) {
  3773. memcpy(p, buf, len);
  3774. return;
  3775. }
  3776. memcpy(p, buf, t);
  3777. mg_byte_reverse(ctx->in, 16);
  3778. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3779. buf += t;
  3780. len -= t;
  3781. }
  3782. while (len >= 64) {
  3783. memcpy(ctx->in, buf, 64);
  3784. mg_byte_reverse(ctx->in, 16);
  3785. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3786. buf += 64;
  3787. len -= 64;
  3788. }
  3789. memcpy(ctx->in, buf, len);
  3790. }
  3791. void mg_md5_final(mg_md5_ctx *ctx, unsigned char digest[16]) {
  3792. unsigned count;
  3793. unsigned char *p;
  3794. uint32_t *a;
  3795. count = (ctx->bits[0] >> 3) & 0x3F;
  3796. p = ctx->in + count;
  3797. *p++ = 0x80;
  3798. count = 64 - 1 - count;
  3799. if (count < 8) {
  3800. memset(p, 0, count);
  3801. mg_byte_reverse(ctx->in, 16);
  3802. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3803. memset(ctx->in, 0, 56);
  3804. } else {
  3805. memset(p, 0, count - 8);
  3806. }
  3807. mg_byte_reverse(ctx->in, 14);
  3808. a = (uint32_t *) ctx->in;
  3809. a[14] = ctx->bits[0];
  3810. a[15] = ctx->bits[1];
  3811. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3812. mg_byte_reverse((unsigned char *) ctx->buf, 4);
  3813. memcpy(digest, ctx->buf, 16);
  3814. memset((char *) ctx, 0, sizeof(*ctx));
  3815. }
  3816. #endif
  3817. #ifdef MG_ENABLE_LINES
  3818. #line 1 "src/mqtt.c"
  3819. #endif
  3820. #define MQTT_CLEAN_SESSION 0x02
  3821. #define MQTT_HAS_WILL 0x04
  3822. #define MQTT_WILL_RETAIN 0x20
  3823. #define MQTT_HAS_PASSWORD 0x40
  3824. #define MQTT_HAS_USER_NAME 0x80
  3825. struct mg_mqtt_pmap {
  3826. uint8_t id;
  3827. uint8_t type;
  3828. };
  3829. static const struct mg_mqtt_pmap s_prop_map[] = {
  3830. {MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, MQTT_PROP_TYPE_BYTE},
  3831. {MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3832. {MQTT_PROP_CONTENT_TYPE, MQTT_PROP_TYPE_STRING},
  3833. {MQTT_PROP_RESPONSE_TOPIC, MQTT_PROP_TYPE_STRING},
  3834. {MQTT_PROP_CORRELATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3835. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER, MQTT_PROP_TYPE_VARIABLE_INT},
  3836. {MQTT_PROP_SESSION_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3837. {MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, MQTT_PROP_TYPE_STRING},
  3838. {MQTT_PROP_SERVER_KEEP_ALIVE, MQTT_PROP_TYPE_SHORT},
  3839. {MQTT_PROP_AUTHENTICATION_METHOD, MQTT_PROP_TYPE_STRING},
  3840. {MQTT_PROP_AUTHENTICATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3841. {MQTT_PROP_REQUEST_PROBLEM_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3842. {MQTT_PROP_WILL_DELAY_INTERVAL, MQTT_PROP_TYPE_INT},
  3843. {MQTT_PROP_REQUEST_RESPONSE_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3844. {MQTT_PROP_RESPONSE_INFORMATION, MQTT_PROP_TYPE_STRING},
  3845. {MQTT_PROP_SERVER_REFERENCE, MQTT_PROP_TYPE_STRING},
  3846. {MQTT_PROP_REASON_STRING, MQTT_PROP_TYPE_STRING},
  3847. {MQTT_PROP_RECEIVE_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3848. {MQTT_PROP_TOPIC_ALIAS_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3849. {MQTT_PROP_TOPIC_ALIAS, MQTT_PROP_TYPE_SHORT},
  3850. {MQTT_PROP_MAXIMUM_QOS, MQTT_PROP_TYPE_BYTE},
  3851. {MQTT_PROP_RETAIN_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3852. {MQTT_PROP_USER_PROPERTY, MQTT_PROP_TYPE_STRING_PAIR},
  3853. {MQTT_PROP_MAXIMUM_PACKET_SIZE, MQTT_PROP_TYPE_INT},
  3854. {MQTT_PROP_WILDCARD_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3855. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3856. {MQTT_PROP_SHARED_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE}};
  3857. void mg_mqtt_send_header(struct mg_connection *c, uint8_t cmd, uint8_t flags,
  3858. uint32_t len) {
  3859. uint8_t buf[1 + sizeof(len)], *vlen = &buf[1];
  3860. buf[0] = (uint8_t) ((cmd << 4) | flags);
  3861. do {
  3862. *vlen = len % 0x80;
  3863. len /= 0x80;
  3864. if (len > 0) *vlen |= 0x80;
  3865. vlen++;
  3866. } while (len > 0 && vlen < &buf[sizeof(buf)]);
  3867. mg_send(c, buf, (size_t) (vlen - buf));
  3868. }
  3869. static void mg_send_u16(struct mg_connection *c, uint16_t value) {
  3870. mg_send(c, &value, sizeof(value));
  3871. }
  3872. static void mg_send_u32(struct mg_connection *c, uint32_t value) {
  3873. mg_send(c, &value, sizeof(value));
  3874. }
  3875. static uint8_t varint_size(size_t length) {
  3876. uint8_t bytes_needed = 0;
  3877. do {
  3878. bytes_needed++;
  3879. length /= 0x80;
  3880. } while (length > 0);
  3881. return bytes_needed;
  3882. }
  3883. static size_t encode_varint(uint8_t *buf, size_t value) {
  3884. size_t len = 0;
  3885. do {
  3886. uint8_t b = (uint8_t) (value % 128);
  3887. value /= 128;
  3888. if (value > 0) b |= 0x80;
  3889. buf[len++] = b;
  3890. } while (value > 0);
  3891. return len;
  3892. }
  3893. static size_t decode_varint(const uint8_t *buf, size_t len, size_t *value) {
  3894. size_t multiplier = 1, offset;
  3895. *value = 0;
  3896. for (offset = 0; offset < 4 && offset < len; offset++) {
  3897. uint8_t encoded_byte = buf[offset];
  3898. *value += (encoded_byte & 0x7f) * multiplier;
  3899. multiplier *= 128;
  3900. if ((encoded_byte & 0x80) == 0) return offset + 1;
  3901. }
  3902. return 0;
  3903. }
  3904. static int mqtt_prop_type_by_id(uint8_t prop_id) {
  3905. size_t i, num_properties = sizeof(s_prop_map) / sizeof(s_prop_map[0]);
  3906. for (i = 0; i < num_properties; ++i) {
  3907. if (s_prop_map[i].id == prop_id) return s_prop_map[i].type;
  3908. }
  3909. return -1; // Property ID not found
  3910. }
  3911. // Returns the size of the properties section, without the
  3912. // size of the content's length
  3913. static size_t get_properties_length(struct mg_mqtt_prop *props, size_t count) {
  3914. size_t i, size = 0;
  3915. for (i = 0; i < count; i++) {
  3916. size++; // identifier
  3917. switch (mqtt_prop_type_by_id(props[i].id)) {
  3918. case MQTT_PROP_TYPE_STRING_PAIR:
  3919. size += (uint32_t) (props[i].val.len + props[i].key.len +
  3920. 2 * sizeof(uint16_t));
  3921. break;
  3922. case MQTT_PROP_TYPE_STRING:
  3923. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3924. break;
  3925. case MQTT_PROP_TYPE_BINARY_DATA:
  3926. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3927. break;
  3928. case MQTT_PROP_TYPE_VARIABLE_INT:
  3929. size += varint_size((uint32_t) props[i].iv);
  3930. break;
  3931. case MQTT_PROP_TYPE_INT:
  3932. size += (uint32_t) sizeof(uint32_t);
  3933. break;
  3934. case MQTT_PROP_TYPE_SHORT:
  3935. size += (uint32_t) sizeof(uint16_t);
  3936. break;
  3937. case MQTT_PROP_TYPE_BYTE:
  3938. size += (uint32_t) sizeof(uint8_t);
  3939. break;
  3940. default:
  3941. return size; // cannot parse further down
  3942. }
  3943. }
  3944. return size;
  3945. }
  3946. // returns the entire size of the properties section, including the
  3947. // size of the variable length of the content
  3948. static size_t get_props_size(struct mg_mqtt_prop *props, size_t count) {
  3949. size_t size = get_properties_length(props, count);
  3950. size += varint_size(size);
  3951. return size;
  3952. }
  3953. static void mg_send_mqtt_properties(struct mg_connection *c,
  3954. struct mg_mqtt_prop *props, size_t nprops) {
  3955. size_t total_size = get_properties_length(props, nprops);
  3956. uint8_t buf_v[4] = {0, 0, 0, 0};
  3957. uint8_t buf[4] = {0, 0, 0, 0};
  3958. size_t i, len = encode_varint(buf, total_size);
  3959. mg_send(c, buf, (size_t) len);
  3960. for (i = 0; i < nprops; i++) {
  3961. mg_send(c, &props[i].id, sizeof(props[i].id));
  3962. switch (mqtt_prop_type_by_id(props[i].id)) {
  3963. case MQTT_PROP_TYPE_STRING_PAIR:
  3964. mg_send_u16(c, mg_htons((uint16_t) props[i].key.len));
  3965. mg_send(c, props[i].key.buf, props[i].key.len);
  3966. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3967. mg_send(c, props[i].val.buf, props[i].val.len);
  3968. break;
  3969. case MQTT_PROP_TYPE_BYTE:
  3970. mg_send(c, &props[i].iv, sizeof(uint8_t));
  3971. break;
  3972. case MQTT_PROP_TYPE_SHORT:
  3973. mg_send_u16(c, mg_htons((uint16_t) props[i].iv));
  3974. break;
  3975. case MQTT_PROP_TYPE_INT:
  3976. mg_send_u32(c, mg_htonl((uint32_t) props[i].iv));
  3977. break;
  3978. case MQTT_PROP_TYPE_STRING:
  3979. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3980. mg_send(c, props[i].val.buf, props[i].val.len);
  3981. break;
  3982. case MQTT_PROP_TYPE_BINARY_DATA:
  3983. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3984. mg_send(c, props[i].val.buf, props[i].val.len);
  3985. break;
  3986. case MQTT_PROP_TYPE_VARIABLE_INT:
  3987. len = encode_varint(buf_v, props[i].iv);
  3988. mg_send(c, buf_v, (size_t) len);
  3989. break;
  3990. }
  3991. }
  3992. }
  3993. size_t mg_mqtt_next_prop(struct mg_mqtt_message *msg, struct mg_mqtt_prop *prop,
  3994. size_t ofs) {
  3995. uint8_t *i = (uint8_t *) msg->dgram.buf + msg->props_start + ofs;
  3996. uint8_t *end = (uint8_t *) msg->dgram.buf + msg->dgram.len;
  3997. size_t new_pos = ofs, len;
  3998. prop->id = i[0];
  3999. if (ofs >= msg->dgram.len || ofs >= msg->props_start + msg->props_size)
  4000. return 0;
  4001. i++, new_pos++;
  4002. switch (mqtt_prop_type_by_id(prop->id)) {
  4003. case MQTT_PROP_TYPE_STRING_PAIR:
  4004. prop->key.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4005. prop->key.buf = (char *) i + 2;
  4006. i += 2 + prop->key.len;
  4007. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4008. prop->val.buf = (char *) i + 2;
  4009. new_pos += 2 * sizeof(uint16_t) + prop->val.len + prop->key.len;
  4010. break;
  4011. case MQTT_PROP_TYPE_BYTE:
  4012. prop->iv = (uint8_t) i[0];
  4013. new_pos++;
  4014. break;
  4015. case MQTT_PROP_TYPE_SHORT:
  4016. prop->iv = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4017. new_pos += sizeof(uint16_t);
  4018. break;
  4019. case MQTT_PROP_TYPE_INT:
  4020. prop->iv = ((uint32_t) i[0] << 24) | ((uint32_t) i[1] << 16) |
  4021. ((uint32_t) i[2] << 8) | i[3];
  4022. new_pos += sizeof(uint32_t);
  4023. break;
  4024. case MQTT_PROP_TYPE_STRING:
  4025. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4026. prop->val.buf = (char *) i + 2;
  4027. new_pos += 2 + prop->val.len;
  4028. break;
  4029. case MQTT_PROP_TYPE_BINARY_DATA:
  4030. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4031. prop->val.buf = (char *) i + 2;
  4032. new_pos += 2 + prop->val.len;
  4033. break;
  4034. case MQTT_PROP_TYPE_VARIABLE_INT:
  4035. len = decode_varint(i, (size_t) (end - i), (size_t *) &prop->iv);
  4036. new_pos = (!len) ? 0 : new_pos + len;
  4037. break;
  4038. default:
  4039. new_pos = 0;
  4040. }
  4041. return new_pos;
  4042. }
  4043. void mg_mqtt_login(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  4044. char client_id[21];
  4045. struct mg_str cid = opts->client_id;
  4046. size_t total_len = 7 + 1 + 2 + 2;
  4047. uint8_t hdr[8] = {0, 4, 'M', 'Q', 'T', 'T', opts->version, 0};
  4048. if (cid.len == 0) {
  4049. mg_random_str(client_id, sizeof(client_id) - 1);
  4050. client_id[sizeof(client_id) - 1] = '\0';
  4051. cid = mg_str(client_id);
  4052. }
  4053. if (hdr[6] == 0) hdr[6] = 4; // If version is not set, use 4 (3.1.1)
  4054. c->is_mqtt5 = hdr[6] == 5; // Set version 5 flag
  4055. hdr[7] = (uint8_t) ((opts->qos & 3) << 3); // Connection flags
  4056. if (opts->user.len > 0) {
  4057. total_len += 2 + (uint32_t) opts->user.len;
  4058. hdr[7] |= MQTT_HAS_USER_NAME;
  4059. }
  4060. if (opts->pass.len > 0) {
  4061. total_len += 2 + (uint32_t) opts->pass.len;
  4062. hdr[7] |= MQTT_HAS_PASSWORD;
  4063. }
  4064. if (opts->topic.len > 0) { // allow zero-length msgs, message.len is size_t
  4065. total_len += 4 + (uint32_t) opts->topic.len + (uint32_t) opts->message.len;
  4066. hdr[7] |= MQTT_HAS_WILL;
  4067. }
  4068. if (opts->clean || cid.len == 0) hdr[7] |= MQTT_CLEAN_SESSION;
  4069. if (opts->retain) hdr[7] |= MQTT_WILL_RETAIN;
  4070. total_len += (uint32_t) cid.len;
  4071. if (c->is_mqtt5) {
  4072. total_len += get_props_size(opts->props, opts->num_props);
  4073. if (hdr[7] & MQTT_HAS_WILL)
  4074. total_len += get_props_size(opts->will_props, opts->num_will_props);
  4075. }
  4076. mg_mqtt_send_header(c, MQTT_CMD_CONNECT, 0, (uint32_t) total_len);
  4077. mg_send(c, hdr, sizeof(hdr));
  4078. // keepalive == 0 means "do not disconnect us!"
  4079. mg_send_u16(c, mg_htons((uint16_t) opts->keepalive));
  4080. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4081. mg_send_u16(c, mg_htons((uint16_t) cid.len));
  4082. mg_send(c, cid.buf, cid.len);
  4083. if (hdr[7] & MQTT_HAS_WILL) {
  4084. if (c->is_mqtt5)
  4085. mg_send_mqtt_properties(c, opts->will_props, opts->num_will_props);
  4086. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  4087. mg_send(c, opts->topic.buf, opts->topic.len);
  4088. mg_send_u16(c, mg_htons((uint16_t) opts->message.len));
  4089. mg_send(c, opts->message.buf, opts->message.len);
  4090. }
  4091. if (opts->user.len > 0) {
  4092. mg_send_u16(c, mg_htons((uint16_t) opts->user.len));
  4093. mg_send(c, opts->user.buf, opts->user.len);
  4094. }
  4095. if (opts->pass.len > 0) {
  4096. mg_send_u16(c, mg_htons((uint16_t) opts->pass.len));
  4097. mg_send(c, opts->pass.buf, opts->pass.len);
  4098. }
  4099. }
  4100. uint16_t mg_mqtt_pub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  4101. uint16_t id = opts->retransmit_id;
  4102. uint8_t flags = (uint8_t) (((opts->qos & 3) << 1) | (opts->retain ? 1 : 0));
  4103. size_t len = 2 + opts->topic.len + opts->message.len;
  4104. MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) opts->topic.len,
  4105. (char *) opts->topic.buf, (int) opts->message.len,
  4106. (char *) opts->message.buf));
  4107. if (opts->qos > 0) len += 2;
  4108. if (c->is_mqtt5) len += get_props_size(opts->props, opts->num_props);
  4109. if (opts->qos > 0 && id != 0) flags |= 1 << 3;
  4110. mg_mqtt_send_header(c, MQTT_CMD_PUBLISH, flags, (uint32_t) len);
  4111. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  4112. mg_send(c, opts->topic.buf, opts->topic.len);
  4113. if (opts->qos > 0) { // need to send 'id' field
  4114. if (id == 0) { // generate new one if not resending
  4115. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  4116. id = c->mgr->mqtt_id;
  4117. }
  4118. mg_send_u16(c, mg_htons(id));
  4119. }
  4120. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4121. if (opts->message.len > 0) mg_send(c, opts->message.buf, opts->message.len);
  4122. return id;
  4123. }
  4124. void mg_mqtt_sub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  4125. uint8_t qos_ = opts->qos & 3;
  4126. size_t plen = c->is_mqtt5 ? get_props_size(opts->props, opts->num_props) : 0;
  4127. size_t len = 2 + opts->topic.len + 2 + 1 + plen;
  4128. mg_mqtt_send_header(c, MQTT_CMD_SUBSCRIBE, 2, (uint32_t) len);
  4129. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  4130. mg_send_u16(c, mg_htons(c->mgr->mqtt_id));
  4131. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4132. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  4133. mg_send(c, opts->topic.buf, opts->topic.len);
  4134. mg_send(c, &qos_, sizeof(qos_));
  4135. }
  4136. int mg_mqtt_parse(const uint8_t *buf, size_t len, uint8_t version,
  4137. struct mg_mqtt_message *m) {
  4138. uint8_t lc = 0, *p, *end;
  4139. uint32_t n = 0, len_len = 0;
  4140. memset(m, 0, sizeof(*m));
  4141. m->dgram.buf = (char *) buf;
  4142. if (len < 2) return MQTT_INCOMPLETE;
  4143. m->cmd = (uint8_t) (buf[0] >> 4);
  4144. m->qos = (buf[0] >> 1) & 3;
  4145. n = len_len = 0;
  4146. p = (uint8_t *) buf + 1;
  4147. while ((size_t) (p - buf) < len) {
  4148. lc = *((uint8_t *) p++);
  4149. n += (uint32_t) ((lc & 0x7f) << 7 * len_len);
  4150. len_len++;
  4151. if (!(lc & 0x80)) break;
  4152. if (len_len >= 4) return MQTT_MALFORMED;
  4153. }
  4154. end = p + n;
  4155. if ((lc & 0x80) || (end > buf + len)) return MQTT_INCOMPLETE;
  4156. m->dgram.len = (size_t) (end - buf);
  4157. switch (m->cmd) {
  4158. case MQTT_CMD_CONNACK:
  4159. if (end - p < 2) return MQTT_MALFORMED;
  4160. m->ack = p[1];
  4161. break;
  4162. case MQTT_CMD_PUBACK:
  4163. case MQTT_CMD_PUBREC:
  4164. case MQTT_CMD_PUBREL:
  4165. case MQTT_CMD_PUBCOMP:
  4166. case MQTT_CMD_SUBSCRIBE:
  4167. case MQTT_CMD_SUBACK:
  4168. case MQTT_CMD_UNSUBSCRIBE:
  4169. case MQTT_CMD_UNSUBACK:
  4170. if (p + 2 > end) return MQTT_MALFORMED;
  4171. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4172. p += 2;
  4173. break;
  4174. case MQTT_CMD_PUBLISH: {
  4175. if (p + 2 > end) return MQTT_MALFORMED;
  4176. m->topic.len = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4177. m->topic.buf = (char *) p + 2;
  4178. p += 2 + m->topic.len;
  4179. if (p > end) return MQTT_MALFORMED;
  4180. if (m->qos > 0) {
  4181. if (p + 2 > end) return MQTT_MALFORMED;
  4182. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4183. p += 2;
  4184. }
  4185. if (p > end) return MQTT_MALFORMED;
  4186. if (version == 5 && p + 2 < end) {
  4187. len_len =
  4188. (uint32_t) decode_varint(p, (size_t) (end - p), &m->props_size);
  4189. if (!len_len) return MQTT_MALFORMED;
  4190. m->props_start = (size_t) (p + len_len - buf);
  4191. p += len_len + m->props_size;
  4192. }
  4193. if (p > end) return MQTT_MALFORMED;
  4194. m->data.buf = (char *) p;
  4195. m->data.len = (size_t) (end - p);
  4196. break;
  4197. }
  4198. default:
  4199. break;
  4200. }
  4201. return MQTT_OK;
  4202. }
  4203. static void mqtt_cb(struct mg_connection *c, int ev, void *ev_data) {
  4204. if (ev == MG_EV_READ) {
  4205. for (;;) {
  4206. uint8_t version = c->is_mqtt5 ? 5 : 4;
  4207. struct mg_mqtt_message mm;
  4208. int rc = mg_mqtt_parse(c->recv.buf, c->recv.len, version, &mm);
  4209. if (rc == MQTT_MALFORMED) {
  4210. MG_ERROR(("%lu MQTT malformed message", c->id));
  4211. c->is_closing = 1;
  4212. break;
  4213. } else if (rc == MQTT_OK) {
  4214. MG_VERBOSE(("%lu MQTT CMD %d len %d [%.*s]", c->id, mm.cmd,
  4215. (int) mm.dgram.len, (int) mm.data.len, mm.data.buf));
  4216. switch (mm.cmd) {
  4217. case MQTT_CMD_CONNACK:
  4218. mg_call(c, MG_EV_MQTT_OPEN, &mm.ack);
  4219. if (mm.ack == 0) {
  4220. MG_DEBUG(("%lu Connected", c->id));
  4221. } else {
  4222. MG_ERROR(("%lu MQTT auth failed, code %d", c->id, mm.ack));
  4223. c->is_closing = 1;
  4224. }
  4225. break;
  4226. case MQTT_CMD_PUBLISH: {
  4227. /*MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) mm.topic.len,
  4228. mm.topic.buf, (int) mm.data.len, mm.data.buf));*/
  4229. if (mm.qos > 0) {
  4230. uint16_t id = mg_ntohs(mm.id);
  4231. uint32_t remaining_len = sizeof(id);
  4232. if (c->is_mqtt5) remaining_len += 2; // 3.4.2
  4233. mg_mqtt_send_header(
  4234. c,
  4235. (uint8_t) (mm.qos == 2 ? MQTT_CMD_PUBREC : MQTT_CMD_PUBACK),
  4236. 0, remaining_len);
  4237. mg_send(c, &id, sizeof(id));
  4238. if (c->is_mqtt5) {
  4239. uint16_t zero = 0;
  4240. mg_send(c, &zero, sizeof(zero));
  4241. }
  4242. }
  4243. mg_call(c, MG_EV_MQTT_MSG, &mm); // let the app handle qos stuff
  4244. break;
  4245. }
  4246. case MQTT_CMD_PUBREC: { // MQTT5: 3.5.2-1 TODO(): variable header rc
  4247. uint16_t id = mg_ntohs(mm.id);
  4248. uint32_t remaining_len = sizeof(id); // MQTT5 3.6.2-1
  4249. mg_mqtt_send_header(c, MQTT_CMD_PUBREL, 2, remaining_len);
  4250. mg_send(c, &id, sizeof(id)); // MQTT5 3.6.1-1, flags = 2
  4251. break;
  4252. }
  4253. case MQTT_CMD_PUBREL: { // MQTT5: 3.6.2-1 TODO(): variable header rc
  4254. uint16_t id = mg_ntohs(mm.id);
  4255. uint32_t remaining_len = sizeof(id); // MQTT5 3.7.2-1
  4256. mg_mqtt_send_header(c, MQTT_CMD_PUBCOMP, 0, remaining_len);
  4257. mg_send(c, &id, sizeof(id));
  4258. break;
  4259. }
  4260. }
  4261. mg_call(c, MG_EV_MQTT_CMD, &mm);
  4262. mg_iobuf_del(&c->recv, 0, mm.dgram.len);
  4263. } else {
  4264. break;
  4265. }
  4266. }
  4267. }
  4268. (void) ev_data;
  4269. }
  4270. void mg_mqtt_ping(struct mg_connection *nc) {
  4271. mg_mqtt_send_header(nc, MQTT_CMD_PINGREQ, 0, 0);
  4272. }
  4273. void mg_mqtt_pong(struct mg_connection *nc) {
  4274. mg_mqtt_send_header(nc, MQTT_CMD_PINGRESP, 0, 0);
  4275. }
  4276. void mg_mqtt_disconnect(struct mg_connection *c,
  4277. const struct mg_mqtt_opts *opts) {
  4278. size_t len = 0;
  4279. if (c->is_mqtt5) len = 1 + get_props_size(opts->props, opts->num_props);
  4280. mg_mqtt_send_header(c, MQTT_CMD_DISCONNECT, 0, (uint32_t) len);
  4281. if (c->is_mqtt5) {
  4282. uint8_t zero = 0;
  4283. mg_send(c, &zero, sizeof(zero)); // reason code
  4284. mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4285. }
  4286. }
  4287. struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url,
  4288. const struct mg_mqtt_opts *opts,
  4289. mg_event_handler_t fn, void *fn_data) {
  4290. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  4291. if (c != NULL) {
  4292. struct mg_mqtt_opts empty;
  4293. memset(&empty, 0, sizeof(empty));
  4294. mg_mqtt_login(c, opts == NULL ? &empty : opts);
  4295. c->pfn = mqtt_cb;
  4296. }
  4297. return c;
  4298. }
  4299. struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url,
  4300. mg_event_handler_t fn, void *fn_data) {
  4301. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  4302. if (c != NULL) c->pfn = mqtt_cb, c->pfn_data = mgr;
  4303. return c;
  4304. }
  4305. #ifdef MG_ENABLE_LINES
  4306. #line 1 "src/net.c"
  4307. #endif
  4308. size_t mg_vprintf(struct mg_connection *c, const char *fmt, va_list *ap) {
  4309. size_t old = c->send.len;
  4310. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  4311. return c->send.len - old;
  4312. }
  4313. size_t mg_printf(struct mg_connection *c, const char *fmt, ...) {
  4314. size_t len = 0;
  4315. va_list ap;
  4316. va_start(ap, fmt);
  4317. len = mg_vprintf(c, fmt, &ap);
  4318. va_end(ap);
  4319. return len;
  4320. }
  4321. static bool mg_atonl(struct mg_str str, struct mg_addr *addr) {
  4322. uint32_t localhost = mg_htonl(0x7f000001);
  4323. if (mg_strcasecmp(str, mg_str("localhost")) != 0) return false;
  4324. memcpy(addr->ip, &localhost, sizeof(uint32_t));
  4325. addr->is_ip6 = false;
  4326. return true;
  4327. }
  4328. static bool mg_atone(struct mg_str str, struct mg_addr *addr) {
  4329. if (str.len > 0) return false;
  4330. memset(addr->ip, 0, sizeof(addr->ip));
  4331. addr->is_ip6 = false;
  4332. return true;
  4333. }
  4334. static bool mg_aton4(struct mg_str str, struct mg_addr *addr) {
  4335. uint8_t data[4] = {0, 0, 0, 0};
  4336. size_t i, num_dots = 0;
  4337. for (i = 0; i < str.len; i++) {
  4338. if (str.buf[i] >= '0' && str.buf[i] <= '9') {
  4339. int octet = data[num_dots] * 10 + (str.buf[i] - '0');
  4340. if (octet > 255) return false;
  4341. data[num_dots] = (uint8_t) octet;
  4342. } else if (str.buf[i] == '.') {
  4343. if (num_dots >= 3 || i == 0 || str.buf[i - 1] == '.') return false;
  4344. num_dots++;
  4345. } else {
  4346. return false;
  4347. }
  4348. }
  4349. if (num_dots != 3 || str.buf[i - 1] == '.') return false;
  4350. memcpy(&addr->ip, data, sizeof(data));
  4351. addr->is_ip6 = false;
  4352. return true;
  4353. }
  4354. static bool mg_v4mapped(struct mg_str str, struct mg_addr *addr) {
  4355. int i;
  4356. uint32_t ipv4;
  4357. if (str.len < 14) return false;
  4358. if (str.buf[0] != ':' || str.buf[1] != ':' || str.buf[6] != ':') return false;
  4359. for (i = 2; i < 6; i++) {
  4360. if (str.buf[i] != 'f' && str.buf[i] != 'F') return false;
  4361. }
  4362. // struct mg_str s = mg_str_n(&str.buf[7], str.len - 7);
  4363. if (!mg_aton4(mg_str_n(&str.buf[7], str.len - 7), addr)) return false;
  4364. memcpy(&ipv4, addr->ip, sizeof(ipv4));
  4365. memset(addr->ip, 0, sizeof(addr->ip));
  4366. addr->ip[10] = addr->ip[11] = 255;
  4367. memcpy(&addr->ip[12], &ipv4, 4);
  4368. addr->is_ip6 = true;
  4369. return true;
  4370. }
  4371. static bool mg_aton6(struct mg_str str, struct mg_addr *addr) {
  4372. size_t i, j = 0, n = 0, dc = 42;
  4373. addr->scope_id = 0;
  4374. if (str.len > 2 && str.buf[0] == '[') str.buf++, str.len -= 2;
  4375. if (mg_v4mapped(str, addr)) return true;
  4376. for (i = 0; i < str.len; i++) {
  4377. if ((str.buf[i] >= '0' && str.buf[i] <= '9') ||
  4378. (str.buf[i] >= 'a' && str.buf[i] <= 'f') ||
  4379. (str.buf[i] >= 'A' && str.buf[i] <= 'F')) {
  4380. unsigned long val; // TODO(): This loops on chars, refactor
  4381. if (i > j + 3) return false;
  4382. // MG_DEBUG(("%lu %lu [%.*s]", i, j, (int) (i - j + 1), &str.buf[j]));
  4383. mg_str_to_num(mg_str_n(&str.buf[j], i - j + 1), 16, &val, sizeof(val));
  4384. addr->ip[n] = (uint8_t) ((val >> 8) & 255);
  4385. addr->ip[n + 1] = (uint8_t) (val & 255);
  4386. } else if (str.buf[i] == ':') {
  4387. j = i + 1;
  4388. if (i > 0 && str.buf[i - 1] == ':') {
  4389. dc = n; // Double colon
  4390. if (i > 1 && str.buf[i - 2] == ':') return false;
  4391. } else if (i > 0) {
  4392. n += 2;
  4393. }
  4394. if (n > 14) return false;
  4395. addr->ip[n] = addr->ip[n + 1] = 0; // For trailing ::
  4396. } else if (str.buf[i] == '%') { // Scope ID, last in string
  4397. return mg_str_to_num(mg_str_n(&str.buf[i + 1], str.len - i - 1), 10,
  4398. &addr->scope_id, sizeof(uint8_t));
  4399. } else {
  4400. return false;
  4401. }
  4402. }
  4403. if (n < 14 && dc == 42) return false;
  4404. if (n < 14) {
  4405. memmove(&addr->ip[dc + (14 - n)], &addr->ip[dc], n - dc + 2);
  4406. memset(&addr->ip[dc], 0, 14 - n);
  4407. }
  4408. addr->is_ip6 = true;
  4409. return true;
  4410. }
  4411. bool mg_aton(struct mg_str str, struct mg_addr *addr) {
  4412. // MG_INFO(("[%.*s]", (int) str.len, str.buf));
  4413. return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) ||
  4414. mg_aton6(str, addr);
  4415. }
  4416. struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) {
  4417. struct mg_connection *c =
  4418. (struct mg_connection *) calloc(1, sizeof(*c) + mgr->extraconnsize);
  4419. if (c != NULL) {
  4420. c->mgr = mgr;
  4421. c->send.align = c->recv.align = c->rtls.align = MG_IO_SIZE;
  4422. c->id = ++mgr->nextid;
  4423. MG_PROF_INIT(c);
  4424. }
  4425. return c;
  4426. }
  4427. void mg_close_conn(struct mg_connection *c) {
  4428. mg_resolve_cancel(c); // Close any pending DNS query
  4429. LIST_DELETE(struct mg_connection, &c->mgr->conns, c);
  4430. if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL;
  4431. if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL;
  4432. // Order of operations is important. `MG_EV_CLOSE` event must be fired
  4433. // before we deallocate received data, see #1331
  4434. mg_call(c, MG_EV_CLOSE, NULL);
  4435. MG_DEBUG(("%lu %ld closed", c->id, c->fd));
  4436. MG_PROF_DUMP(c);
  4437. MG_PROF_FREE(c);
  4438. mg_tls_free(c);
  4439. mg_iobuf_free(&c->recv);
  4440. mg_iobuf_free(&c->send);
  4441. mg_iobuf_free(&c->rtls);
  4442. mg_bzero((unsigned char *) c, sizeof(*c));
  4443. free(c);
  4444. }
  4445. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url,
  4446. mg_event_handler_t fn, void *fn_data) {
  4447. struct mg_connection *c = NULL;
  4448. if (url == NULL || url[0] == '\0') {
  4449. MG_ERROR(("null url"));
  4450. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  4451. MG_ERROR(("OOM"));
  4452. } else {
  4453. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4454. c->is_udp = (strncmp(url, "udp:", 4) == 0);
  4455. c->fd = (void *) (size_t) MG_INVALID_SOCKET;
  4456. c->fn = fn;
  4457. c->is_client = true;
  4458. c->fn_data = fn_data;
  4459. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  4460. mg_call(c, MG_EV_OPEN, (void *) url);
  4461. mg_resolve(c, url);
  4462. }
  4463. return c;
  4464. }
  4465. struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url,
  4466. mg_event_handler_t fn, void *fn_data) {
  4467. struct mg_connection *c = NULL;
  4468. if ((c = mg_alloc_conn(mgr)) == NULL) {
  4469. MG_ERROR(("OOM %s", url));
  4470. } else if (!mg_open_listener(c, url)) {
  4471. MG_ERROR(("Failed: %s, errno %d", url, errno));
  4472. MG_PROF_FREE(c);
  4473. free(c);
  4474. c = NULL;
  4475. } else {
  4476. c->is_listening = 1;
  4477. c->is_udp = strncmp(url, "udp:", 4) == 0;
  4478. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4479. c->fn = fn;
  4480. c->fn_data = fn_data;
  4481. mg_call(c, MG_EV_OPEN, NULL);
  4482. if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must
  4483. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  4484. }
  4485. return c;
  4486. }
  4487. struct mg_connection *mg_wrapfd(struct mg_mgr *mgr, int fd,
  4488. mg_event_handler_t fn, void *fn_data) {
  4489. struct mg_connection *c = mg_alloc_conn(mgr);
  4490. if (c != NULL) {
  4491. c->fd = (void *) (size_t) fd;
  4492. c->fn = fn;
  4493. c->fn_data = fn_data;
  4494. MG_EPOLL_ADD(c);
  4495. mg_call(c, MG_EV_OPEN, NULL);
  4496. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4497. }
  4498. return c;
  4499. }
  4500. struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds,
  4501. unsigned flags, void (*fn)(void *), void *arg) {
  4502. struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t));
  4503. if (t != NULL) {
  4504. mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg);
  4505. t->id = mgr->timerid++;
  4506. }
  4507. return t;
  4508. }
  4509. long mg_io_recv(struct mg_connection *c, void *buf, size_t len) {
  4510. if (c->rtls.len == 0) return MG_IO_WAIT;
  4511. if (len > c->rtls.len) len = c->rtls.len;
  4512. memcpy(buf, c->rtls.buf, len);
  4513. mg_iobuf_del(&c->rtls, 0, len);
  4514. return (long) len;
  4515. }
  4516. void mg_mgr_free(struct mg_mgr *mgr) {
  4517. struct mg_connection *c;
  4518. struct mg_timer *tmp, *t = mgr->timers;
  4519. while (t != NULL) tmp = t->next, free(t), t = tmp;
  4520. mgr->timers = NULL; // Important. Next call to poll won't touch timers
  4521. for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1;
  4522. mg_mgr_poll(mgr, 0);
  4523. #if MG_ENABLE_FREERTOS_TCP
  4524. FreeRTOS_DeleteSocketSet(mgr->ss);
  4525. #endif
  4526. MG_DEBUG(("All connections closed"));
  4527. #if MG_ENABLE_EPOLL
  4528. if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1;
  4529. #endif
  4530. mg_tls_ctx_free(mgr);
  4531. }
  4532. void mg_mgr_init(struct mg_mgr *mgr) {
  4533. memset(mgr, 0, sizeof(*mgr));
  4534. #if MG_ENABLE_EPOLL
  4535. if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
  4536. MG_ERROR(("epoll_create1 errno %d", errno));
  4537. #else
  4538. mgr->epoll_fd = -1;
  4539. #endif
  4540. #if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  4541. // clang-format off
  4542. { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
  4543. // clang-format on
  4544. #elif MG_ENABLE_FREERTOS_TCP
  4545. mgr->ss = FreeRTOS_CreateSocketSet();
  4546. #elif defined(__unix) || defined(__unix__) || defined(__APPLE__)
  4547. // Ignore SIGPIPE signal, so if client cancels the request, it
  4548. // won't kill the whole process.
  4549. signal(SIGPIPE, SIG_IGN);
  4550. #elif MG_ENABLE_TCPIP_DRIVER_INIT && defined(MG_TCPIP_DRIVER_INIT)
  4551. MG_TCPIP_DRIVER_INIT(mgr);
  4552. #endif
  4553. mgr->pipe = MG_INVALID_SOCKET;
  4554. mgr->dnstimeout = 3000;
  4555. mgr->dns4.url = "udp://8.8.8.8:53";
  4556. mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
  4557. mg_tls_ctx_init(mgr);
  4558. }
  4559. #ifdef MG_ENABLE_LINES
  4560. #line 1 "src/net_builtin.c"
  4561. #endif
  4562. #if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP
  4563. #define MG_EPHEMERAL_PORT_BASE 32768
  4564. #define PDIFF(a, b) ((size_t) (((char *) (b)) - ((char *) (a))))
  4565. #ifndef MIP_TCP_KEEPALIVE_MS
  4566. #define MIP_TCP_KEEPALIVE_MS 45000 // TCP keep-alive period, ms
  4567. #endif
  4568. #define MIP_TCP_ACK_MS 150 // Timeout for ACKing
  4569. #define MIP_TCP_ARP_MS 100 // Timeout for ARP response
  4570. #define MIP_TCP_SYN_MS 15000 // Timeout for connection establishment
  4571. #define MIP_TCP_FIN_MS 1000 // Timeout for closing connection
  4572. #define MIP_TCP_WIN 6000 // TCP window size
  4573. struct connstate {
  4574. uint32_t seq, ack; // TCP seq/ack counters
  4575. uint64_t timer; // TCP keep-alive / ACK timer
  4576. uint32_t acked; // Last ACK-ed number
  4577. size_t unacked; // Not acked bytes
  4578. uint8_t mac[6]; // Peer MAC address
  4579. uint8_t ttype; // Timer type. 0: ack, 1: keep-alive
  4580. #define MIP_TTYPE_KEEPALIVE 0 // Connection is idle for long, send keepalive
  4581. #define MIP_TTYPE_ACK 1 // Peer sent us data, we have to ack it soon
  4582. #define MIP_TTYPE_ARP 2 // ARP resolve sent, waiting for response
  4583. #define MIP_TTYPE_SYN 3 // SYN sent, waiting for response
  4584. #define MIP_TTYPE_FIN 4 // FIN sent, waiting until terminating the connection
  4585. uint8_t tmiss; // Number of keep-alive misses
  4586. struct mg_iobuf raw; // For TLS only. Incoming raw data
  4587. };
  4588. #pragma pack(push, 1)
  4589. struct lcp {
  4590. uint8_t addr, ctrl, proto[2], code, id, len[2];
  4591. };
  4592. struct eth {
  4593. uint8_t dst[6]; // Destination MAC address
  4594. uint8_t src[6]; // Source MAC address
  4595. uint16_t type; // Ethernet type
  4596. };
  4597. struct ip {
  4598. uint8_t ver; // Version
  4599. uint8_t tos; // Unused
  4600. uint16_t len; // Length
  4601. uint16_t id; // Unused
  4602. uint16_t frag; // Fragmentation
  4603. #define IP_FRAG_OFFSET_MSK 0xFF1F
  4604. #define IP_MORE_FRAGS_MSK 0x20
  4605. uint8_t ttl; // Time to live
  4606. uint8_t proto; // Upper level protocol
  4607. uint16_t csum; // Checksum
  4608. uint32_t src; // Source IP
  4609. uint32_t dst; // Destination IP
  4610. };
  4611. struct ip6 {
  4612. uint8_t ver; // Version
  4613. uint8_t opts[3]; // Options
  4614. uint16_t len; // Length
  4615. uint8_t proto; // Upper level protocol
  4616. uint8_t ttl; // Time to live
  4617. uint8_t src[16]; // Source IP
  4618. uint8_t dst[16]; // Destination IP
  4619. };
  4620. struct icmp {
  4621. uint8_t type;
  4622. uint8_t code;
  4623. uint16_t csum;
  4624. };
  4625. struct arp {
  4626. uint16_t fmt; // Format of hardware address
  4627. uint16_t pro; // Format of protocol address
  4628. uint8_t hlen; // Length of hardware address
  4629. uint8_t plen; // Length of protocol address
  4630. uint16_t op; // Operation
  4631. uint8_t sha[6]; // Sender hardware address
  4632. uint32_t spa; // Sender protocol address
  4633. uint8_t tha[6]; // Target hardware address
  4634. uint32_t tpa; // Target protocol address
  4635. };
  4636. struct tcp {
  4637. uint16_t sport; // Source port
  4638. uint16_t dport; // Destination port
  4639. uint32_t seq; // Sequence number
  4640. uint32_t ack; // Acknowledgement number
  4641. uint8_t off; // Data offset
  4642. uint8_t flags; // TCP flags
  4643. #define TH_FIN 0x01
  4644. #define TH_SYN 0x02
  4645. #define TH_RST 0x04
  4646. #define TH_PUSH 0x08
  4647. #define TH_ACK 0x10
  4648. #define TH_URG 0x20
  4649. #define TH_ECE 0x40
  4650. #define TH_CWR 0x80
  4651. uint16_t win; // Window
  4652. uint16_t csum; // Checksum
  4653. uint16_t urp; // Urgent pointer
  4654. };
  4655. struct udp {
  4656. uint16_t sport; // Source port
  4657. uint16_t dport; // Destination port
  4658. uint16_t len; // UDP length
  4659. uint16_t csum; // UDP checksum
  4660. };
  4661. struct dhcp {
  4662. uint8_t op, htype, hlen, hops;
  4663. uint32_t xid;
  4664. uint16_t secs, flags;
  4665. uint32_t ciaddr, yiaddr, siaddr, giaddr;
  4666. uint8_t hwaddr[208];
  4667. uint32_t magic;
  4668. uint8_t options[32];
  4669. };
  4670. #pragma pack(pop)
  4671. struct pkt {
  4672. struct mg_str raw; // Raw packet data
  4673. struct mg_str pay; // Payload data
  4674. struct eth *eth;
  4675. struct llc *llc;
  4676. struct arp *arp;
  4677. struct ip *ip;
  4678. struct ip6 *ip6;
  4679. struct icmp *icmp;
  4680. struct tcp *tcp;
  4681. struct udp *udp;
  4682. struct dhcp *dhcp;
  4683. };
  4684. static void send_syn(struct mg_connection *c);
  4685. static void mkpay(struct pkt *pkt, void *p) {
  4686. pkt->pay =
  4687. mg_str_n((char *) p, (size_t) (&pkt->raw.buf[pkt->raw.len] - (char *) p));
  4688. }
  4689. static uint32_t csumup(uint32_t sum, const void *buf, size_t len) {
  4690. size_t i;
  4691. const uint8_t *p = (const uint8_t *) buf;
  4692. for (i = 0; i < len; i++) sum += i & 1 ? p[i] : (uint32_t) (p[i] << 8);
  4693. return sum;
  4694. }
  4695. static uint16_t csumfin(uint32_t sum) {
  4696. while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
  4697. return mg_htons(~sum & 0xffff);
  4698. }
  4699. static uint16_t ipcsum(const void *buf, size_t len) {
  4700. uint32_t sum = csumup(0, buf, len);
  4701. return csumfin(sum);
  4702. }
  4703. static void settmout(struct mg_connection *c, uint8_t type) {
  4704. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4705. struct connstate *s = (struct connstate *) (c + 1);
  4706. unsigned n = type == MIP_TTYPE_ACK ? MIP_TCP_ACK_MS
  4707. : type == MIP_TTYPE_ARP ? MIP_TCP_ARP_MS
  4708. : type == MIP_TTYPE_SYN ? MIP_TCP_SYN_MS
  4709. : type == MIP_TTYPE_FIN ? MIP_TCP_FIN_MS
  4710. : MIP_TCP_KEEPALIVE_MS;
  4711. s->timer = ifp->now + n;
  4712. s->ttype = type;
  4713. MG_VERBOSE(("%lu %d -> %llx", c->id, type, s->timer));
  4714. }
  4715. static size_t ether_output(struct mg_tcpip_if *ifp, size_t len) {
  4716. size_t n = ifp->driver->tx(ifp->tx.buf, len, ifp);
  4717. if (n == len) ifp->nsent++;
  4718. return n;
  4719. }
  4720. static void arp_ask(struct mg_tcpip_if *ifp, uint32_t ip) {
  4721. struct eth *eth = (struct eth *) ifp->tx.buf;
  4722. struct arp *arp = (struct arp *) (eth + 1);
  4723. memset(eth->dst, 255, sizeof(eth->dst));
  4724. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4725. eth->type = mg_htons(0x806);
  4726. memset(arp, 0, sizeof(*arp));
  4727. arp->fmt = mg_htons(1), arp->pro = mg_htons(0x800), arp->hlen = 6,
  4728. arp->plen = 4;
  4729. arp->op = mg_htons(1), arp->tpa = ip, arp->spa = ifp->ip;
  4730. memcpy(arp->sha, ifp->mac, sizeof(arp->sha));
  4731. ether_output(ifp, PDIFF(eth, arp + 1));
  4732. }
  4733. static void onstatechange(struct mg_tcpip_if *ifp) {
  4734. if (ifp->state == MG_TCPIP_STATE_READY) {
  4735. MG_INFO(("READY, IP: %M", mg_print_ip4, &ifp->ip));
  4736. MG_INFO((" GW: %M", mg_print_ip4, &ifp->gw));
  4737. MG_INFO((" MAC: %M", mg_print_mac, &ifp->mac));
  4738. arp_ask(ifp, ifp->gw);
  4739. } else if (ifp->state == MG_TCPIP_STATE_UP) {
  4740. MG_ERROR(("Link up"));
  4741. srand((unsigned int) mg_millis());
  4742. } else if (ifp->state == MG_TCPIP_STATE_DOWN) {
  4743. MG_ERROR(("Link down"));
  4744. }
  4745. }
  4746. static struct ip *tx_ip(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4747. uint8_t proto, uint32_t ip_src, uint32_t ip_dst,
  4748. size_t plen) {
  4749. struct eth *eth = (struct eth *) ifp->tx.buf;
  4750. struct ip *ip = (struct ip *) (eth + 1);
  4751. memcpy(eth->dst, mac_dst, sizeof(eth->dst));
  4752. memcpy(eth->src, ifp->mac, sizeof(eth->src)); // Use our MAC
  4753. eth->type = mg_htons(0x800);
  4754. memset(ip, 0, sizeof(*ip));
  4755. ip->ver = 0x45; // Version 4, header length 5 words
  4756. ip->frag = 0x40; // Don't fragment
  4757. ip->len = mg_htons((uint16_t) (sizeof(*ip) + plen));
  4758. ip->ttl = 64;
  4759. ip->proto = proto;
  4760. ip->src = ip_src;
  4761. ip->dst = ip_dst;
  4762. ip->csum = ipcsum(ip, sizeof(*ip));
  4763. return ip;
  4764. }
  4765. static void tx_udp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4766. uint16_t sport, uint32_t ip_dst, uint16_t dport,
  4767. const void *buf, size_t len) {
  4768. struct ip *ip =
  4769. tx_ip(ifp, mac_dst, 17, ip_src, ip_dst, len + sizeof(struct udp));
  4770. struct udp *udp = (struct udp *) (ip + 1);
  4771. // MG_DEBUG(("UDP XX LEN %d %d", (int) len, (int) ifp->tx.len));
  4772. udp->sport = sport;
  4773. udp->dport = dport;
  4774. udp->len = mg_htons((uint16_t) (sizeof(*udp) + len));
  4775. udp->csum = 0;
  4776. uint32_t cs = csumup(0, udp, sizeof(*udp));
  4777. cs = csumup(cs, buf, len);
  4778. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4779. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4780. cs += (uint32_t) (ip->proto + sizeof(*udp) + len);
  4781. udp->csum = csumfin(cs);
  4782. memmove(udp + 1, buf, len);
  4783. // MG_DEBUG(("UDP LEN %d %d", (int) len, (int) ifp->frame_len));
  4784. ether_output(ifp, sizeof(struct eth) + sizeof(*ip) + sizeof(*udp) + len);
  4785. }
  4786. static void tx_dhcp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4787. uint32_t ip_dst, uint8_t *opts, size_t optslen,
  4788. bool ciaddr) {
  4789. // https://datatracker.ietf.org/doc/html/rfc2132#section-9.6
  4790. struct dhcp dhcp = {1, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4791. dhcp.magic = mg_htonl(0x63825363);
  4792. memcpy(&dhcp.hwaddr, ifp->mac, sizeof(ifp->mac));
  4793. memcpy(&dhcp.xid, ifp->mac + 2, sizeof(dhcp.xid));
  4794. memcpy(&dhcp.options, opts, optslen);
  4795. if (ciaddr) dhcp.ciaddr = ip_src;
  4796. tx_udp(ifp, mac_dst, ip_src, mg_htons(68), ip_dst, mg_htons(67), &dhcp,
  4797. sizeof(dhcp));
  4798. }
  4799. static const uint8_t broadcast[] = {255, 255, 255, 255, 255, 255};
  4800. // RFC-2131 #4.3.6, #4.4.1
  4801. static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
  4802. uint32_t ip_srv) {
  4803. uint8_t opts[] = {
  4804. 53, 1, 3, // Type: DHCP request
  4805. 55, 2, 1, 3, // GW and mask
  4806. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4807. 54, 4, 0, 0, 0, 0, // DHCP server ID
  4808. 50, 4, 0, 0, 0, 0, // Requested IP
  4809. 255 // End of options
  4810. };
  4811. memcpy(opts + 14, &ip_srv, sizeof(ip_srv));
  4812. memcpy(opts + 20, &ip_req, sizeof(ip_req));
  4813. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4814. MG_DEBUG(("DHCP req sent"));
  4815. }
  4816. // RFC-2131 #4.3.6, #4.4.5 (renewing: unicast, rebinding: bcast)
  4817. static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4818. uint32_t ip_src, uint32_t ip_dst) {
  4819. uint8_t opts[] = {
  4820. 53, 1, 3, // Type: DHCP request
  4821. 255 // End of options
  4822. };
  4823. tx_dhcp(ifp, mac_dst, ip_src, ip_dst, opts, sizeof(opts), true);
  4824. MG_DEBUG(("DHCP req sent"));
  4825. }
  4826. static void tx_dhcp_discover(struct mg_tcpip_if *ifp) {
  4827. uint8_t opts[] = {
  4828. 53, 1, 1, // Type: DHCP discover
  4829. 55, 2, 1, 3, // Parameters: ip, mask
  4830. 255 // End of options
  4831. };
  4832. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4833. MG_DEBUG(("DHCP discover sent. Our MAC: %M", mg_print_mac, ifp->mac));
  4834. }
  4835. static struct mg_connection *getpeer(struct mg_mgr *mgr, struct pkt *pkt,
  4836. bool lsn) {
  4837. struct mg_connection *c = NULL;
  4838. for (c = mgr->conns; c != NULL; c = c->next) {
  4839. if (c->is_arplooking && pkt->arp &&
  4840. memcmp(&pkt->arp->spa, c->rem.ip, sizeof(pkt->arp->spa)) == 0)
  4841. break;
  4842. if (c->is_udp && pkt->udp && c->loc.port == pkt->udp->dport) break;
  4843. if (!c->is_udp && pkt->tcp && c->loc.port == pkt->tcp->dport &&
  4844. lsn == c->is_listening && (lsn || c->rem.port == pkt->tcp->sport))
  4845. break;
  4846. }
  4847. return c;
  4848. }
  4849. static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4850. if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) {
  4851. // ARP request. Make a response, then send
  4852. // MG_DEBUG(("ARP op %d %M: %M", mg_ntohs(pkt->arp->op), mg_print_ip4,
  4853. // &pkt->arp->spa, mg_print_ip4, &pkt->arp->tpa));
  4854. struct eth *eth = (struct eth *) ifp->tx.buf;
  4855. struct arp *arp = (struct arp *) (eth + 1);
  4856. memcpy(eth->dst, pkt->eth->src, sizeof(eth->dst));
  4857. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4858. eth->type = mg_htons(0x806);
  4859. *arp = *pkt->arp;
  4860. arp->op = mg_htons(2);
  4861. memcpy(arp->tha, pkt->arp->sha, sizeof(pkt->arp->tha));
  4862. memcpy(arp->sha, ifp->mac, sizeof(pkt->arp->sha));
  4863. arp->tpa = pkt->arp->spa;
  4864. arp->spa = ifp->ip;
  4865. MG_DEBUG(("ARP: tell %M we're %M", mg_print_ip4, &arp->tpa, mg_print_mac,
  4866. &ifp->mac));
  4867. ether_output(ifp, PDIFF(eth, arp + 1));
  4868. } else if (pkt->arp->op == mg_htons(2)) {
  4869. if (memcmp(pkt->arp->tha, ifp->mac, sizeof(pkt->arp->tha)) != 0) return;
  4870. if (pkt->arp->spa == ifp->gw) {
  4871. // Got response for the GW ARP request. Set ifp->gwmac
  4872. memcpy(ifp->gwmac, pkt->arp->sha, sizeof(ifp->gwmac));
  4873. } else {
  4874. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4875. if (c != NULL && c->is_arplooking) {
  4876. struct connstate *s = (struct connstate *) (c + 1);
  4877. memcpy(s->mac, pkt->arp->sha, sizeof(s->mac));
  4878. MG_DEBUG(("%lu ARP resolved %M -> %M", c->id, mg_print_ip4, c->rem.ip,
  4879. mg_print_mac, s->mac));
  4880. c->is_arplooking = 0;
  4881. send_syn(c);
  4882. settmout(c, MIP_TTYPE_SYN);
  4883. }
  4884. }
  4885. }
  4886. }
  4887. static void rx_icmp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4888. // MG_DEBUG(("ICMP %d", (int) len));
  4889. if (pkt->icmp->type == 8 && pkt->ip != NULL && pkt->ip->dst == ifp->ip) {
  4890. size_t hlen = sizeof(struct eth) + sizeof(struct ip) + sizeof(struct icmp);
  4891. size_t space = ifp->tx.len - hlen, plen = pkt->pay.len;
  4892. if (plen > space) plen = space;
  4893. struct ip *ip = tx_ip(ifp, pkt->eth->src, 1, ifp->ip, pkt->ip->src,
  4894. sizeof(struct icmp) + plen);
  4895. struct icmp *icmp = (struct icmp *) (ip + 1);
  4896. memset(icmp, 0, sizeof(*icmp)); // Set csum to 0
  4897. memcpy(icmp + 1, pkt->pay.buf, plen); // Copy RX payload to TX
  4898. icmp->csum = ipcsum(icmp, sizeof(*icmp) + plen);
  4899. ether_output(ifp, hlen + plen);
  4900. }
  4901. }
  4902. static void rx_dhcp_client(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4903. uint32_t ip = 0, gw = 0, mask = 0, lease = 0;
  4904. uint8_t msgtype = 0, state = ifp->state;
  4905. // perform size check first, then access fields
  4906. uint8_t *p = pkt->dhcp->options,
  4907. *end = (uint8_t *) &pkt->raw.buf[pkt->raw.len];
  4908. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4909. if (memcmp(&pkt->dhcp->xid, ifp->mac + 2, sizeof(pkt->dhcp->xid))) return;
  4910. while (p + 1 < end && p[0] != 255) { // Parse options RFC-1533 #9
  4911. if (p[0] == 1 && p[1] == sizeof(ifp->mask) && p + 6 < end) { // Mask
  4912. memcpy(&mask, p + 2, sizeof(mask));
  4913. } else if (p[0] == 3 && p[1] == sizeof(ifp->gw) && p + 6 < end) { // GW
  4914. memcpy(&gw, p + 2, sizeof(gw));
  4915. ip = pkt->dhcp->yiaddr;
  4916. } else if (p[0] == 51 && p[1] == 4 && p + 6 < end) { // Lease
  4917. memcpy(&lease, p + 2, sizeof(lease));
  4918. lease = mg_ntohl(lease);
  4919. } else if (p[0] == 53 && p[1] == 1 && p + 6 < end) { // Msg Type
  4920. msgtype = p[2];
  4921. }
  4922. p += p[1] + 2;
  4923. }
  4924. // Process message type, RFC-1533 (9.4); RFC-2131 (3.1, 4)
  4925. if (msgtype == 6 && ifp->ip == ip) { // DHCPNACK, release IP
  4926. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0;
  4927. } else if (msgtype == 2 && ifp->state == MG_TCPIP_STATE_UP && ip && gw &&
  4928. lease) { // DHCPOFFER
  4929. // select IP, (4.4.1) (fallback to IP source addr on foul play)
  4930. tx_dhcp_request_sel(ifp, ip,
  4931. pkt->dhcp->siaddr ? pkt->dhcp->siaddr : pkt->ip->src);
  4932. ifp->state = MG_TCPIP_STATE_REQ; // REQUESTING state
  4933. } else if (msgtype == 5) { // DHCPACK
  4934. if (ifp->state == MG_TCPIP_STATE_REQ && ip && gw && lease) { // got an IP
  4935. ifp->lease_expire = ifp->now + lease * 1000;
  4936. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4937. // assume DHCP server = router until ARP resolves
  4938. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4939. ifp->ip = ip, ifp->gw = gw, ifp->mask = mask;
  4940. ifp->state = MG_TCPIP_STATE_READY; // BOUND state
  4941. uint64_t rand;
  4942. mg_random(&rand, sizeof(rand));
  4943. srand((unsigned int) (rand + mg_millis()));
  4944. } else if (ifp->state == MG_TCPIP_STATE_READY && ifp->ip == ip) { // renew
  4945. ifp->lease_expire = ifp->now + lease * 1000;
  4946. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4947. } // TODO(): accept provided T1/T2 and store server IP for renewal (4.4)
  4948. }
  4949. if (ifp->state != state) onstatechange(ifp);
  4950. }
  4951. // Simple DHCP server that assigns a next IP address: ifp->ip + 1
  4952. static void rx_dhcp_server(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4953. uint8_t op = 0, *p = pkt->dhcp->options,
  4954. *end = (uint8_t *) &pkt->raw.buf[pkt->raw.len];
  4955. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4956. // struct dhcp *req = pkt->dhcp;
  4957. struct dhcp res = {2, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4958. res.yiaddr = ifp->ip;
  4959. ((uint8_t *) (&res.yiaddr))[3]++; // Offer our IP + 1
  4960. while (p + 1 < end && p[0] != 255) { // Parse options
  4961. if (p[0] == 53 && p[1] == 1 && p + 2 < end) { // Message type
  4962. op = p[2];
  4963. }
  4964. p += p[1] + 2;
  4965. }
  4966. if (op == 1 || op == 3) { // DHCP Discover or DHCP Request
  4967. uint8_t msg = op == 1 ? 2 : 5; // Message type: DHCP OFFER or DHCP ACK
  4968. uint8_t opts[] = {
  4969. 53, 1, msg, // Message type
  4970. 1, 4, 0, 0, 0, 0, // Subnet mask
  4971. 54, 4, 0, 0, 0, 0, // Server ID
  4972. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4973. 51, 4, 255, 255, 255, 255, // Lease time
  4974. 255 // End of options
  4975. };
  4976. memcpy(&res.hwaddr, pkt->dhcp->hwaddr, 6);
  4977. memcpy(opts + 5, &ifp->mask, sizeof(ifp->mask));
  4978. memcpy(opts + 11, &ifp->ip, sizeof(ifp->ip));
  4979. memcpy(&res.options, opts, sizeof(opts));
  4980. res.magic = pkt->dhcp->magic;
  4981. res.xid = pkt->dhcp->xid;
  4982. if (ifp->enable_get_gateway) {
  4983. ifp->gw = res.yiaddr;
  4984. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4985. }
  4986. tx_udp(ifp, pkt->eth->src, ifp->ip, mg_htons(67),
  4987. op == 1 ? ~0U : res.yiaddr, mg_htons(68), &res, sizeof(res));
  4988. }
  4989. }
  4990. static void rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4991. struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
  4992. if (c == NULL) {
  4993. // No UDP listener on this port. Should send ICMP, but keep silent.
  4994. } else {
  4995. c->rem.port = pkt->udp->sport;
  4996. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4997. struct connstate *s = (struct connstate *) (c + 1);
  4998. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4999. if (c->recv.len >= MG_MAX_RECV_SIZE) {
  5000. mg_error(c, "max_recv_buf_size reached");
  5001. } else if (c->recv.size - c->recv.len < pkt->pay.len &&
  5002. !mg_iobuf_resize(&c->recv, c->recv.len + pkt->pay.len)) {
  5003. mg_error(c, "oom");
  5004. } else {
  5005. memcpy(&c->recv.buf[c->recv.len], pkt->pay.buf, pkt->pay.len);
  5006. c->recv.len += pkt->pay.len;
  5007. mg_call(c, MG_EV_READ, &pkt->pay.len);
  5008. }
  5009. }
  5010. }
  5011. static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *dst_mac, uint32_t dst_ip,
  5012. uint8_t flags, uint16_t sport, uint16_t dport,
  5013. uint32_t seq, uint32_t ack, const void *buf, size_t len) {
  5014. #if 0
  5015. uint8_t opts[] = {2, 4, 5, 0xb4, 4, 2, 0, 0}; // MSS = 1460, SACK permitted
  5016. if (flags & TH_SYN) {
  5017. // Handshake? Set MSS
  5018. buf = opts;
  5019. len = sizeof(opts);
  5020. }
  5021. #endif
  5022. struct ip *ip =
  5023. tx_ip(ifp, dst_mac, 6, ifp->ip, dst_ip, sizeof(struct tcp) + len);
  5024. struct tcp *tcp = (struct tcp *) (ip + 1);
  5025. memset(tcp, 0, sizeof(*tcp));
  5026. if (buf != NULL && len) memmove(tcp + 1, buf, len);
  5027. tcp->sport = sport;
  5028. tcp->dport = dport;
  5029. tcp->seq = seq;
  5030. tcp->ack = ack;
  5031. tcp->flags = flags;
  5032. tcp->win = mg_htons(MIP_TCP_WIN);
  5033. tcp->off = (uint8_t) (sizeof(*tcp) / 4 << 4);
  5034. // if (flags & TH_SYN) tcp->off = 0x70; // Handshake? header size 28 bytes
  5035. uint32_t cs = 0;
  5036. uint16_t n = (uint16_t) (sizeof(*tcp) + len);
  5037. uint8_t pseudo[] = {0, ip->proto, (uint8_t) (n >> 8), (uint8_t) (n & 255)};
  5038. cs = csumup(cs, tcp, n);
  5039. cs = csumup(cs, &ip->src, sizeof(ip->src));
  5040. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  5041. cs = csumup(cs, pseudo, sizeof(pseudo));
  5042. tcp->csum = csumfin(cs);
  5043. MG_VERBOSE(("TCP %M:%hu -> %M:%hu fl %x len %u", mg_print_ip4, &ip->src,
  5044. mg_ntohs(tcp->sport), mg_print_ip4, &ip->dst,
  5045. mg_ntohs(tcp->dport), tcp->flags, len));
  5046. // mg_hexdump(ifp->tx.buf, PDIFF(ifp->tx.buf, tcp + 1) + len);
  5047. return ether_output(ifp, PDIFF(ifp->tx.buf, tcp + 1) + len);
  5048. }
  5049. static size_t tx_tcp_pkt(struct mg_tcpip_if *ifp, struct pkt *pkt,
  5050. uint8_t flags, uint32_t seq, const void *buf,
  5051. size_t len) {
  5052. uint32_t delta = (pkt->tcp->flags & (TH_SYN | TH_FIN)) ? 1 : 0;
  5053. return tx_tcp(ifp, pkt->eth->src, pkt->ip->src, flags, pkt->tcp->dport,
  5054. pkt->tcp->sport, seq, mg_htonl(mg_ntohl(pkt->tcp->seq) + delta),
  5055. buf, len);
  5056. }
  5057. static struct mg_connection *accept_conn(struct mg_connection *lsn,
  5058. struct pkt *pkt) {
  5059. struct mg_connection *c = mg_alloc_conn(lsn->mgr);
  5060. if (c == NULL) {
  5061. MG_ERROR(("OOM"));
  5062. return NULL;
  5063. }
  5064. struct connstate *s = (struct connstate *) (c + 1);
  5065. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq);
  5066. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  5067. settmout(c, MIP_TTYPE_KEEPALIVE);
  5068. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  5069. c->rem.port = pkt->tcp->sport;
  5070. MG_DEBUG(("%lu accepted %M", c->id, mg_print_ip_port, &c->rem));
  5071. LIST_ADD_HEAD(struct mg_connection, &lsn->mgr->conns, c);
  5072. c->is_accepted = 1;
  5073. c->is_hexdumping = lsn->is_hexdumping;
  5074. c->pfn = lsn->pfn;
  5075. c->loc = lsn->loc;
  5076. c->pfn_data = lsn->pfn_data;
  5077. c->fn = lsn->fn;
  5078. c->fn_data = lsn->fn_data;
  5079. mg_call(c, MG_EV_OPEN, NULL);
  5080. mg_call(c, MG_EV_ACCEPT, NULL);
  5081. return c;
  5082. }
  5083. static size_t trim_len(struct mg_connection *c, size_t len) {
  5084. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5085. size_t eth_h_len = 14, ip_max_h_len = 24, tcp_max_h_len = 60, udp_h_len = 8;
  5086. size_t max_headers_len =
  5087. eth_h_len + ip_max_h_len + (c->is_udp ? udp_h_len : tcp_max_h_len);
  5088. size_t min_mtu = c->is_udp ? 68 /* RFC-791 */ : max_headers_len - eth_h_len;
  5089. // If the frame exceeds the available buffer, trim the length
  5090. if (len + max_headers_len > ifp->tx.len) {
  5091. len = ifp->tx.len - max_headers_len;
  5092. }
  5093. // Ensure the MTU isn't lower than the minimum allowed value
  5094. if (ifp->mtu < min_mtu) {
  5095. MG_ERROR(("MTU is lower than minimum, capping to %lu", min_mtu));
  5096. ifp->mtu = (uint16_t) min_mtu;
  5097. }
  5098. // If the total packet size exceeds the MTU, trim the length
  5099. if (len + max_headers_len - eth_h_len > ifp->mtu) {
  5100. len = ifp->mtu - max_headers_len + eth_h_len;
  5101. if (c->is_udp) {
  5102. MG_ERROR(("UDP datagram exceeds MTU. Truncating it."));
  5103. }
  5104. }
  5105. return len;
  5106. }
  5107. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  5108. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5109. struct connstate *s = (struct connstate *) (c + 1);
  5110. uint32_t dst_ip = *(uint32_t *) c->rem.ip;
  5111. len = trim_len(c, len);
  5112. if (c->is_udp) {
  5113. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, dst_ip, c->rem.port, buf, len);
  5114. } else {
  5115. size_t sent =
  5116. tx_tcp(ifp, s->mac, dst_ip, TH_PUSH | TH_ACK, c->loc.port, c->rem.port,
  5117. mg_htonl(s->seq), mg_htonl(s->ack), buf, len);
  5118. if (sent == 0) {
  5119. return MG_IO_WAIT;
  5120. } else if (sent == (size_t) -1) {
  5121. return MG_IO_ERR;
  5122. } else {
  5123. s->seq += (uint32_t) len;
  5124. if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
  5125. }
  5126. }
  5127. return (long) len;
  5128. }
  5129. static void handle_tls_recv(struct mg_connection *c, struct mg_iobuf *io) {
  5130. long n = mg_tls_recv(c, &io->buf[io->len], io->size - io->len);
  5131. if (n == MG_IO_ERR) {
  5132. mg_error(c, "TLS recv error");
  5133. } else if (n > 0) {
  5134. // Decrypted successfully - trigger MG_EV_READ
  5135. io->len += (size_t) n;
  5136. mg_call(c, MG_EV_READ, &n);
  5137. }
  5138. }
  5139. static void read_conn(struct mg_connection *c, struct pkt *pkt) {
  5140. struct connstate *s = (struct connstate *) (c + 1);
  5141. struct mg_iobuf *io = c->is_tls ? &c->rtls : &c->recv;
  5142. uint32_t seq = mg_ntohl(pkt->tcp->seq);
  5143. uint32_t rem_ip;
  5144. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5145. if (pkt->tcp->flags & TH_FIN) {
  5146. // If we initiated the closure, we reply with ACK upon receiving FIN
  5147. // If we didn't initiate it, we reply with FIN as part of the normal TCP
  5148. // closure process
  5149. uint8_t flags = TH_ACK;
  5150. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len + 1);
  5151. if (c->is_draining && s->ttype == MIP_TTYPE_FIN) {
  5152. if (s->seq == mg_htonl(pkt->tcp->ack)) { // Simultaneous closure ?
  5153. s->seq++; // Yes. Increment our SEQ
  5154. } else { // Otherwise,
  5155. s->seq = mg_htonl(pkt->tcp->ack); // Set to peer's ACK
  5156. }
  5157. } else {
  5158. flags |= TH_FIN;
  5159. c->is_draining = 1;
  5160. settmout(c, MIP_TTYPE_FIN);
  5161. }
  5162. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, flags,
  5163. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  5164. } else if (pkt->pay.len == 0) {
  5165. // TODO(cpq): handle this peer's ACK
  5166. } else if (seq != s->ack) {
  5167. uint32_t ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  5168. if (s->ack == ack) {
  5169. MG_VERBOSE(("ignoring duplicate pkt"));
  5170. } else {
  5171. MG_VERBOSE(("SEQ != ACK: %x %x %x", seq, s->ack, ack));
  5172. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  5173. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "",
  5174. 0);
  5175. }
  5176. } else if (io->size - io->len < pkt->pay.len &&
  5177. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  5178. mg_error(c, "oom");
  5179. } else {
  5180. // Copy TCP payload into the IO buffer. If the connection is plain text,
  5181. // we copy to c->recv. If the connection is TLS, this data is encrypted,
  5182. // therefore we copy that encrypted data to the c->rtls iobuffer instead,
  5183. // and then call mg_tls_recv() to decrypt it. NOTE: mg_tls_recv() will
  5184. // call back mg_io_recv() which grabs raw data from c->rtls
  5185. memcpy(&io->buf[io->len], pkt->pay.buf, pkt->pay.len);
  5186. io->len += pkt->pay.len;
  5187. MG_VERBOSE(("%lu SEQ %x -> %x", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  5188. // Advance ACK counter
  5189. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  5190. s->unacked += pkt->pay.len;
  5191. // size_t diff = s->acked <= s->ack ? s->ack - s->acked : s->ack;
  5192. if (s->unacked > MIP_TCP_WIN / 2 && s->acked != s->ack) {
  5193. // Send ACK immediately
  5194. MG_VERBOSE(("%lu imm ACK %lu", c->id, s->acked));
  5195. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  5196. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), NULL,
  5197. 0);
  5198. s->unacked = 0;
  5199. s->acked = s->ack;
  5200. if (s->ttype != MIP_TTYPE_KEEPALIVE) settmout(c, MIP_TTYPE_KEEPALIVE);
  5201. } else {
  5202. // if not already running, setup a timer to send an ACK later
  5203. if (s->ttype != MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_ACK);
  5204. }
  5205. if (c->is_tls && c->is_tls_hs) {
  5206. mg_tls_handshake(c);
  5207. } else if (c->is_tls) {
  5208. // TLS connection. Make room for decrypted data in c->recv
  5209. io = &c->recv;
  5210. if (io->size - io->len < pkt->pay.len &&
  5211. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  5212. mg_error(c, "oom");
  5213. } else {
  5214. // Decrypt data directly into c->recv
  5215. handle_tls_recv(c, io);
  5216. }
  5217. } else {
  5218. // Plain text connection, data is already in c->recv, trigger
  5219. // MG_EV_READ
  5220. mg_call(c, MG_EV_READ, &pkt->pay.len);
  5221. }
  5222. }
  5223. }
  5224. static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5225. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  5226. struct connstate *s = c == NULL ? NULL : (struct connstate *) (c + 1);
  5227. #if 0
  5228. MG_INFO(("%lu %hhu %d", c ? c->id : 0, pkt->tcp->flags, (int) pkt->pay.len));
  5229. #endif
  5230. if (c != NULL && c->is_connecting && pkt->tcp->flags == (TH_SYN | TH_ACK)) {
  5231. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq) + 1;
  5232. tx_tcp_pkt(ifp, pkt, TH_ACK, pkt->tcp->ack, NULL, 0);
  5233. c->is_connecting = 0; // Client connected
  5234. settmout(c, MIP_TTYPE_KEEPALIVE);
  5235. mg_call(c, MG_EV_CONNECT, NULL); // Let user know
  5236. } else if (c != NULL && c->is_connecting && pkt->tcp->flags != TH_ACK) {
  5237. // mg_hexdump(pkt->raw.buf, pkt->raw.len);
  5238. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5239. } else if (c != NULL && pkt->tcp->flags & TH_RST) {
  5240. mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  5241. } else if (c != NULL) {
  5242. #if 0
  5243. MG_DEBUG(("%lu %d %M:%hu -> %M:%hu", c->id, (int) pkt->raw.len,
  5244. mg_print_ip4, &pkt->ip->src, mg_ntohs(pkt->tcp->sport),
  5245. mg_print_ip4, &pkt->ip->dst, mg_ntohs(pkt->tcp->dport)));
  5246. mg_hexdump(pkt->pay.buf, pkt->pay.len);
  5247. #endif
  5248. s->tmiss = 0; // Reset missed keep-alive counter
  5249. if (s->ttype == MIP_TTYPE_KEEPALIVE) // Advance keep-alive timer
  5250. settmout(c,
  5251. MIP_TTYPE_KEEPALIVE); // unless a former ACK timeout is pending
  5252. read_conn(c, pkt); // Override timer with ACK timeout if needed
  5253. } else if ((c = getpeer(ifp->mgr, pkt, true)) == NULL) {
  5254. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5255. } else if (pkt->tcp->flags & TH_RST) {
  5256. if (c->is_accepted) mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  5257. // ignore RST if not connected
  5258. } else if (pkt->tcp->flags & TH_SYN) {
  5259. // Use peer's source port as ISN, in order to recognise the handshake
  5260. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(pkt->tcp->sport));
  5261. tx_tcp_pkt(ifp, pkt, TH_SYN | TH_ACK, isn, NULL, 0);
  5262. } else if (pkt->tcp->flags & TH_FIN) {
  5263. tx_tcp_pkt(ifp, pkt, TH_FIN | TH_ACK, pkt->tcp->ack, NULL, 0);
  5264. } else if (mg_htonl(pkt->tcp->ack) == mg_htons(pkt->tcp->sport) + 1U) {
  5265. accept_conn(c, pkt);
  5266. } else if (!c->is_accepted) { // no peer
  5267. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5268. } else {
  5269. // MG_VERBOSE(("dropped silently.."));
  5270. }
  5271. }
  5272. static void rx_ip(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5273. if (pkt->ip->frag & IP_MORE_FRAGS_MSK || pkt->ip->frag & IP_FRAG_OFFSET_MSK) {
  5274. if (pkt->ip->proto == 17) pkt->udp = (struct udp *) (pkt->ip + 1);
  5275. if (pkt->ip->proto == 6) pkt->tcp = (struct tcp *) (pkt->ip + 1);
  5276. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  5277. if (c) mg_error(c, "Received fragmented packet");
  5278. } else if (pkt->ip->proto == 1) {
  5279. pkt->icmp = (struct icmp *) (pkt->ip + 1);
  5280. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  5281. mkpay(pkt, pkt->icmp + 1);
  5282. rx_icmp(ifp, pkt);
  5283. } else if (pkt->ip->proto == 17) {
  5284. pkt->udp = (struct udp *) (pkt->ip + 1);
  5285. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  5286. mkpay(pkt, pkt->udp + 1);
  5287. MG_VERBOSE(("UDP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  5288. mg_ntohs(pkt->udp->sport), mg_print_ip4, &pkt->ip->dst,
  5289. mg_ntohs(pkt->udp->dport), (int) pkt->pay.len));
  5290. if (ifp->enable_dhcp_client && pkt->udp->dport == mg_htons(68)) {
  5291. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  5292. mkpay(pkt, pkt->dhcp + 1);
  5293. rx_dhcp_client(ifp, pkt);
  5294. } else if (ifp->enable_dhcp_server && pkt->udp->dport == mg_htons(67)) {
  5295. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  5296. mkpay(pkt, pkt->dhcp + 1);
  5297. rx_dhcp_server(ifp, pkt);
  5298. } else {
  5299. rx_udp(ifp, pkt);
  5300. }
  5301. } else if (pkt->ip->proto == 6) {
  5302. pkt->tcp = (struct tcp *) (pkt->ip + 1);
  5303. if (pkt->pay.len < sizeof(*pkt->tcp)) return;
  5304. mkpay(pkt, pkt->tcp + 1);
  5305. uint16_t iplen = mg_ntohs(pkt->ip->len);
  5306. uint16_t off = (uint16_t) (sizeof(*pkt->ip) + ((pkt->tcp->off >> 4) * 4U));
  5307. if (iplen >= off) pkt->pay.len = (size_t) (iplen - off);
  5308. MG_VERBOSE(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  5309. mg_ntohs(pkt->tcp->sport), mg_print_ip4, &pkt->ip->dst,
  5310. mg_ntohs(pkt->tcp->dport), (int) pkt->pay.len));
  5311. rx_tcp(ifp, pkt);
  5312. }
  5313. }
  5314. static void rx_ip6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5315. // MG_DEBUG(("IP %d", (int) len));
  5316. if (pkt->ip6->proto == 1 || pkt->ip6->proto == 58) {
  5317. pkt->icmp = (struct icmp *) (pkt->ip6 + 1);
  5318. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  5319. mkpay(pkt, pkt->icmp + 1);
  5320. rx_icmp(ifp, pkt);
  5321. } else if (pkt->ip6->proto == 17) {
  5322. pkt->udp = (struct udp *) (pkt->ip6 + 1);
  5323. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  5324. // MG_DEBUG((" UDP %u %u -> %u", len, mg_htons(udp->sport),
  5325. // mg_htons(udp->dport)));
  5326. mkpay(pkt, pkt->udp + 1);
  5327. }
  5328. }
  5329. static void mg_tcpip_rx(struct mg_tcpip_if *ifp, void *buf, size_t len) {
  5330. struct pkt pkt;
  5331. memset(&pkt, 0, sizeof(pkt));
  5332. pkt.raw.buf = (char *) buf;
  5333. pkt.raw.len = len;
  5334. pkt.eth = (struct eth *) buf;
  5335. // mg_hexdump(buf, len > 16 ? 16: len);
  5336. if (pkt.raw.len < sizeof(*pkt.eth)) return; // Truncated - runt?
  5337. if (ifp->enable_mac_check &&
  5338. memcmp(pkt.eth->dst, ifp->mac, sizeof(pkt.eth->dst)) != 0 &&
  5339. memcmp(pkt.eth->dst, broadcast, sizeof(pkt.eth->dst)) != 0)
  5340. return;
  5341. if (ifp->enable_crc32_check && len > 4) {
  5342. len -= 4; // TODO(scaprile): check on bigendian
  5343. uint32_t crc = mg_crc32(0, (const char *) buf, len);
  5344. if (memcmp((void *) ((size_t) buf + len), &crc, sizeof(crc))) return;
  5345. }
  5346. if (pkt.eth->type == mg_htons(0x806)) {
  5347. pkt.arp = (struct arp *) (pkt.eth + 1);
  5348. if (sizeof(*pkt.eth) + sizeof(*pkt.arp) > pkt.raw.len) return; // Truncated
  5349. rx_arp(ifp, &pkt);
  5350. } else if (pkt.eth->type == mg_htons(0x86dd)) {
  5351. pkt.ip6 = (struct ip6 *) (pkt.eth + 1);
  5352. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip6)) return; // Truncated
  5353. if ((pkt.ip6->ver >> 4) != 0x6) return; // Not IP
  5354. mkpay(&pkt, pkt.ip6 + 1);
  5355. rx_ip6(ifp, &pkt);
  5356. } else if (pkt.eth->type == mg_htons(0x800)) {
  5357. pkt.ip = (struct ip *) (pkt.eth + 1);
  5358. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  5359. // Truncate frame to what IP header tells us
  5360. if ((size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth) < pkt.raw.len) {
  5361. pkt.raw.len = (size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth);
  5362. }
  5363. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  5364. if ((pkt.ip->ver >> 4) != 4) return; // Not IP
  5365. mkpay(&pkt, pkt.ip + 1);
  5366. rx_ip(ifp, &pkt);
  5367. } else {
  5368. MG_DEBUG(("Unknown eth type %x", mg_htons(pkt.eth->type)));
  5369. if (mg_log_level >= MG_LL_VERBOSE) mg_hexdump(buf, len >= 32 ? 32 : len);
  5370. }
  5371. }
  5372. static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t now) {
  5373. struct mg_connection *c;
  5374. bool expired_1000ms = mg_timer_expired(&ifp->timer_1000ms, 1000, now);
  5375. ifp->now = now;
  5376. #if MG_ENABLE_TCPIP_PRINT_DEBUG_STATS
  5377. if (expired_1000ms) {
  5378. const char *names[] = {"down", "up", "req", "ready"};
  5379. MG_INFO(("Status: %s, IP: %M, rx:%u, tx:%u, dr:%u, er:%u",
  5380. names[ifp->state], mg_print_ip4, &ifp->ip, ifp->nrecv, ifp->nsent,
  5381. ifp->ndrop, ifp->nerr));
  5382. }
  5383. #endif
  5384. // Handle physical interface up/down status
  5385. if (expired_1000ms && ifp->driver->up) {
  5386. bool up = ifp->driver->up(ifp);
  5387. bool current = ifp->state != MG_TCPIP_STATE_DOWN;
  5388. if (up != current) {
  5389. ifp->state = up == false ? MG_TCPIP_STATE_DOWN
  5390. : ifp->enable_dhcp_client ? MG_TCPIP_STATE_UP
  5391. : MG_TCPIP_STATE_READY;
  5392. if (!up && ifp->enable_dhcp_client) ifp->ip = 0;
  5393. onstatechange(ifp);
  5394. }
  5395. if (ifp->state == MG_TCPIP_STATE_DOWN) MG_ERROR(("Network is down"));
  5396. }
  5397. if (ifp->state == MG_TCPIP_STATE_DOWN) return;
  5398. // DHCP RFC-2131 (4.4)
  5399. if (ifp->state == MG_TCPIP_STATE_UP && expired_1000ms) {
  5400. tx_dhcp_discover(ifp); // INIT (4.4.1)
  5401. } else if (expired_1000ms && ifp->state == MG_TCPIP_STATE_READY &&
  5402. ifp->lease_expire > 0) { // BOUND / RENEWING / REBINDING
  5403. if (ifp->now >= ifp->lease_expire) {
  5404. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0; // expired, release IP
  5405. onstatechange(ifp);
  5406. } else if (ifp->now + 30UL * 60UL * 1000UL > ifp->lease_expire &&
  5407. ((ifp->now / 1000) % 60) == 0) {
  5408. // hack: 30 min before deadline, try to rebind (4.3.6) every min
  5409. tx_dhcp_request_re(ifp, (uint8_t *) broadcast, ifp->ip, 0xffffffff);
  5410. } // TODO(): Handle T1 (RENEWING) and T2 (REBINDING) (4.4.5)
  5411. }
  5412. // Read data from the network
  5413. if (ifp->driver->rx != NULL) { // Polling driver. We must call it
  5414. size_t len =
  5415. ifp->driver->rx(ifp->recv_queue.buf, ifp->recv_queue.size, ifp);
  5416. if (len > 0) {
  5417. ifp->nrecv++;
  5418. mg_tcpip_rx(ifp, ifp->recv_queue.buf, len);
  5419. }
  5420. } else { // Interrupt-based driver. Fills recv queue itself
  5421. char *buf;
  5422. size_t len = mg_queue_next(&ifp->recv_queue, &buf);
  5423. if (len > 0) {
  5424. mg_tcpip_rx(ifp, buf, len);
  5425. mg_queue_del(&ifp->recv_queue, len);
  5426. }
  5427. }
  5428. // Process timeouts
  5429. for (c = ifp->mgr->conns; c != NULL; c = c->next) {
  5430. if (c->is_udp || c->is_listening || c->is_resolving) continue;
  5431. struct connstate *s = (struct connstate *) (c + 1);
  5432. uint32_t rem_ip;
  5433. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5434. if (now > s->timer) {
  5435. if (s->ttype == MIP_TTYPE_ACK && s->acked != s->ack) {
  5436. MG_VERBOSE(("%lu ack %x %x", c->id, s->seq, s->ack));
  5437. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  5438. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5439. s->acked = s->ack;
  5440. } else if (s->ttype == MIP_TTYPE_ARP) {
  5441. mg_error(c, "ARP timeout");
  5442. } else if (s->ttype == MIP_TTYPE_SYN) {
  5443. mg_error(c, "Connection timeout");
  5444. } else if (s->ttype == MIP_TTYPE_FIN) {
  5445. c->is_closing = 1;
  5446. continue;
  5447. } else {
  5448. if (s->tmiss++ > 2) {
  5449. mg_error(c, "keepalive");
  5450. } else {
  5451. MG_VERBOSE(("%lu keepalive", c->id));
  5452. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  5453. mg_htonl(s->seq - 1), mg_htonl(s->ack), NULL, 0);
  5454. }
  5455. }
  5456. settmout(c, MIP_TTYPE_KEEPALIVE);
  5457. }
  5458. }
  5459. }
  5460. // This function executes in interrupt context, thus it should copy data
  5461. // somewhere fast. Note that newlib's malloc is not thread safe, thus use
  5462. // our lock-free queue with preallocated buffer to copy data and return asap
  5463. void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) {
  5464. char *p;
  5465. if (mg_queue_book(&ifp->recv_queue, &p, len) >= len) {
  5466. memcpy(p, buf, len);
  5467. mg_queue_add(&ifp->recv_queue, len);
  5468. ifp->nrecv++;
  5469. } else {
  5470. ifp->ndrop++;
  5471. }
  5472. }
  5473. void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
  5474. // If MAC address is not set, make a random one
  5475. if (ifp->mac[0] == 0 && ifp->mac[1] == 0 && ifp->mac[2] == 0 &&
  5476. ifp->mac[3] == 0 && ifp->mac[4] == 0 && ifp->mac[5] == 0) {
  5477. ifp->mac[0] = 0x02; // Locally administered, unicast
  5478. mg_random(&ifp->mac[1], sizeof(ifp->mac) - 1);
  5479. MG_INFO(("MAC not set. Generated random: %M", mg_print_mac, ifp->mac));
  5480. }
  5481. if (ifp->driver->init && !ifp->driver->init(ifp)) {
  5482. MG_ERROR(("driver init failed"));
  5483. } else {
  5484. size_t framesize = 1540;
  5485. ifp->tx.buf = (char *) calloc(1, framesize), ifp->tx.len = framesize;
  5486. if (ifp->recv_queue.size == 0)
  5487. ifp->recv_queue.size = ifp->driver->rx ? framesize : 8192;
  5488. ifp->recv_queue.buf = (char *) calloc(1, ifp->recv_queue.size);
  5489. ifp->timer_1000ms = mg_millis();
  5490. mgr->priv = ifp;
  5491. ifp->mgr = mgr;
  5492. ifp->mtu = MG_TCPIP_MTU_DEFAULT;
  5493. mgr->extraconnsize = sizeof(struct connstate);
  5494. if (ifp->ip == 0) ifp->enable_dhcp_client = true;
  5495. memset(ifp->gwmac, 255, sizeof(ifp->gwmac)); // Set to broadcast
  5496. mg_random(&ifp->eport, sizeof(ifp->eport)); // Random from 0 to 65535
  5497. ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
  5498. // MG_EPHEMERAL_PORT_BASE to 65535
  5499. if (ifp->tx.buf == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
  5500. }
  5501. }
  5502. void mg_tcpip_free(struct mg_tcpip_if *ifp) {
  5503. free(ifp->recv_queue.buf);
  5504. free(ifp->tx.buf);
  5505. }
  5506. static void send_syn(struct mg_connection *c) {
  5507. struct connstate *s = (struct connstate *) (c + 1);
  5508. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(c->loc.port));
  5509. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5510. uint32_t rem_ip;
  5511. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5512. tx_tcp(ifp, s->mac, rem_ip, TH_SYN, c->loc.port, c->rem.port, isn, 0, NULL,
  5513. 0);
  5514. }
  5515. void mg_connect_resolved(struct mg_connection *c) {
  5516. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5517. uint32_t rem_ip;
  5518. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5519. c->is_resolving = 0;
  5520. if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
  5521. memcpy(c->loc.ip, &ifp->ip, sizeof(uint32_t));
  5522. c->loc.port = mg_htons(ifp->eport++);
  5523. MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
  5524. &c->rem));
  5525. mg_call(c, MG_EV_RESOLVE, NULL);
  5526. if (c->is_udp && (rem_ip == 0xffffffff || rem_ip == (ifp->ip | ~ifp->mask))) {
  5527. struct connstate *s = (struct connstate *) (c + 1);
  5528. memset(s->mac, 0xFF, sizeof(s->mac)); // global or local broadcast
  5529. } else if (ifp->ip && ((rem_ip & ifp->mask) == (ifp->ip & ifp->mask))) {
  5530. // If we're in the same LAN, fire an ARP lookup.
  5531. MG_DEBUG(("%lu ARP lookup...", c->id));
  5532. arp_ask(ifp, rem_ip);
  5533. settmout(c, MIP_TTYPE_ARP);
  5534. c->is_arplooking = 1;
  5535. c->is_connecting = 1;
  5536. } else if ((*((uint8_t *) &rem_ip) & 0xE0) == 0xE0) {
  5537. struct connstate *s = (struct connstate *) (c + 1); // 224 to 239, E0 to EF
  5538. uint8_t mcastp[3] = {0x01, 0x00, 0x5E}; // multicast group
  5539. memcpy(s->mac, mcastp, 3);
  5540. memcpy(s->mac + 3, ((uint8_t *) &rem_ip) + 1, 3); // 23 LSb
  5541. s->mac[3] &= 0x7F;
  5542. } else {
  5543. struct connstate *s = (struct connstate *) (c + 1);
  5544. memcpy(s->mac, ifp->gwmac, sizeof(ifp->gwmac));
  5545. if (c->is_udp) {
  5546. mg_call(c, MG_EV_CONNECT, NULL);
  5547. } else {
  5548. send_syn(c);
  5549. settmout(c, MIP_TTYPE_SYN);
  5550. c->is_connecting = 1;
  5551. }
  5552. }
  5553. }
  5554. bool mg_open_listener(struct mg_connection *c, const char *url) {
  5555. c->loc.port = mg_htons(mg_url_port(url));
  5556. return true;
  5557. }
  5558. static void write_conn(struct mg_connection *c) {
  5559. long len = c->is_tls ? mg_tls_send(c, c->send.buf, c->send.len)
  5560. : mg_io_send(c, c->send.buf, c->send.len);
  5561. if (len == MG_IO_ERR) {
  5562. mg_error(c, "tx err");
  5563. } else if (len > 0) {
  5564. mg_iobuf_del(&c->send, 0, (size_t) len);
  5565. mg_call(c, MG_EV_WRITE, &len);
  5566. }
  5567. }
  5568. static void init_closure(struct mg_connection *c) {
  5569. struct connstate *s = (struct connstate *) (c + 1);
  5570. if (c->is_udp == false && c->is_listening == false &&
  5571. c->is_connecting == false) { // For TCP conns,
  5572. struct mg_tcpip_if *ifp =
  5573. (struct mg_tcpip_if *) c->mgr->priv; // send TCP FIN
  5574. uint32_t rem_ip;
  5575. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5576. tx_tcp(ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port, c->rem.port,
  5577. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5578. settmout(c, MIP_TTYPE_FIN);
  5579. }
  5580. }
  5581. static void close_conn(struct mg_connection *c) {
  5582. struct connstate *s = (struct connstate *) (c + 1);
  5583. mg_iobuf_free(&s->raw); // For TLS connections, release raw data
  5584. mg_close_conn(c);
  5585. }
  5586. static bool can_write(struct mg_connection *c) {
  5587. return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 &&
  5588. c->is_tls_hs == 0 && c->is_arplooking == 0;
  5589. }
  5590. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  5591. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) mgr->priv;
  5592. struct mg_connection *c, *tmp;
  5593. uint64_t now = mg_millis();
  5594. mg_timer_poll(&mgr->timers, now);
  5595. if (ifp == NULL || ifp->driver == NULL) return;
  5596. mg_tcpip_poll(ifp, now);
  5597. for (c = mgr->conns; c != NULL; c = tmp) {
  5598. tmp = c->next;
  5599. struct connstate *s = (struct connstate *) (c + 1);
  5600. mg_call(c, MG_EV_POLL, &now);
  5601. MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't',
  5602. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  5603. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  5604. if (c->is_tls && mg_tls_pending(c) > 0)
  5605. handle_tls_recv(c, (struct mg_iobuf *) &c->rtls);
  5606. if (can_write(c)) write_conn(c);
  5607. if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN)
  5608. init_closure(c);
  5609. if (c->is_closing) close_conn(c);
  5610. }
  5611. (void) ms;
  5612. }
  5613. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  5614. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5615. bool res = false;
  5616. uint32_t rem_ip;
  5617. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5618. if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) {
  5619. mg_error(c, "net down");
  5620. } else if (c->is_udp) {
  5621. struct connstate *s = (struct connstate *) (c + 1);
  5622. len = trim_len(c, len); // Trimming length if necessary
  5623. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len);
  5624. res = true;
  5625. } else {
  5626. res = mg_iobuf_add(&c->send, c->send.len, buf, len);
  5627. }
  5628. return res;
  5629. }
  5630. #endif // MG_ENABLE_TCPIP
  5631. #ifdef MG_ENABLE_LINES
  5632. #line 1 "src/ota_dummy.c"
  5633. #endif
  5634. #if MG_OTA == MG_OTA_NONE
  5635. bool mg_ota_begin(size_t new_firmware_size) {
  5636. (void) new_firmware_size;
  5637. return true;
  5638. }
  5639. bool mg_ota_write(const void *buf, size_t len) {
  5640. (void) buf, (void) len;
  5641. return true;
  5642. }
  5643. bool mg_ota_end(void) {
  5644. return true;
  5645. }
  5646. bool mg_ota_commit(void) {
  5647. return true;
  5648. }
  5649. bool mg_ota_rollback(void) {
  5650. return true;
  5651. }
  5652. int mg_ota_status(int fw) {
  5653. (void) fw;
  5654. return 0;
  5655. }
  5656. uint32_t mg_ota_crc32(int fw) {
  5657. (void) fw;
  5658. return 0;
  5659. }
  5660. uint32_t mg_ota_timestamp(int fw) {
  5661. (void) fw;
  5662. return 0;
  5663. }
  5664. size_t mg_ota_size(int fw) {
  5665. (void) fw;
  5666. return 0;
  5667. }
  5668. MG_IRAM void mg_ota_boot(void) {
  5669. }
  5670. #endif
  5671. #ifdef MG_ENABLE_LINES
  5672. #line 1 "src/ota_esp32.c"
  5673. #endif
  5674. #if MG_ARCH == MG_ARCH_ESP32 && MG_OTA == MG_OTA_ESP32
  5675. static const esp_partition_t *s_ota_update_partition;
  5676. static esp_ota_handle_t s_ota_update_handle;
  5677. static bool s_ota_success;
  5678. // Those empty macros do nothing, but mark places in the code which could
  5679. // potentially trigger a watchdog reboot due to the log flash erase operation
  5680. #define disable_wdt()
  5681. #define enable_wdt()
  5682. bool mg_ota_begin(size_t new_firmware_size) {
  5683. if (s_ota_update_partition != NULL) {
  5684. MG_ERROR(("Update in progress. Call mg_ota_end() ?"));
  5685. return false;
  5686. } else {
  5687. s_ota_success = false;
  5688. disable_wdt();
  5689. s_ota_update_partition = esp_ota_get_next_update_partition(NULL);
  5690. esp_err_t err = esp_ota_begin(s_ota_update_partition, new_firmware_size,
  5691. &s_ota_update_handle);
  5692. enable_wdt();
  5693. MG_DEBUG(("esp_ota_begin(): %d", err));
  5694. s_ota_success = (err == ESP_OK);
  5695. }
  5696. return s_ota_success;
  5697. }
  5698. bool mg_ota_write(const void *buf, size_t len) {
  5699. disable_wdt();
  5700. esp_err_t err = esp_ota_write(s_ota_update_handle, buf, len);
  5701. enable_wdt();
  5702. MG_INFO(("esp_ota_write(): %d", err));
  5703. s_ota_success = err == ESP_OK;
  5704. return s_ota_success;
  5705. }
  5706. bool mg_ota_end(void) {
  5707. esp_err_t err = esp_ota_end(s_ota_update_handle);
  5708. MG_DEBUG(("esp_ota_end(%p): %d", s_ota_update_handle, err));
  5709. if (s_ota_success && err == ESP_OK) {
  5710. err = esp_ota_set_boot_partition(s_ota_update_partition);
  5711. s_ota_success = (err == ESP_OK);
  5712. }
  5713. MG_DEBUG(("Finished ESP32 OTA, success: %d", s_ota_success));
  5714. s_ota_update_partition = NULL;
  5715. return s_ota_success;
  5716. }
  5717. #endif
  5718. #ifdef MG_ENABLE_LINES
  5719. #line 1 "src/ota_flash.c"
  5720. #endif
  5721. // This OTA implementation uses the internal flash API outlined in device.h
  5722. // It splits flash into 2 equal partitions, and stores OTA status in the
  5723. // last sector of the partition.
  5724. #if MG_OTA == MG_OTA_FLASH
  5725. #define MG_OTADATA_KEY 0xb07afed0
  5726. static char *s_addr; // Current address to write to
  5727. static size_t s_size; // Firmware size to flash. In-progress indicator
  5728. static uint32_t s_crc32; // Firmware checksum
  5729. struct mg_otadata {
  5730. uint32_t crc32, size, timestamp, status;
  5731. };
  5732. bool mg_ota_begin(size_t new_firmware_size) {
  5733. bool ok = false;
  5734. if (s_size) {
  5735. MG_ERROR(("OTA already in progress. Call mg_ota_end()"));
  5736. } else {
  5737. size_t half = mg_flash_size() / 2, max = half - mg_flash_sector_size();
  5738. s_crc32 = 0;
  5739. s_addr = (char *) mg_flash_start() + half;
  5740. MG_DEBUG(("Firmware %lu bytes, max %lu", new_firmware_size, max));
  5741. if (new_firmware_size < max) {
  5742. ok = true;
  5743. s_size = new_firmware_size;
  5744. MG_INFO(("Starting OTA, firmware size %lu", s_size));
  5745. } else {
  5746. MG_ERROR(("Firmware %lu is too big to fit %lu", new_firmware_size, max));
  5747. }
  5748. }
  5749. return ok;
  5750. }
  5751. bool mg_ota_write(const void *buf, size_t len) {
  5752. bool ok = false;
  5753. if (s_size == 0) {
  5754. MG_ERROR(("OTA is not started, call mg_ota_begin()"));
  5755. } else {
  5756. size_t align = mg_flash_write_align();
  5757. size_t len_aligned_down = MG_ROUND_DOWN(len, align);
  5758. if (len_aligned_down) ok = mg_flash_write(s_addr, buf, len_aligned_down);
  5759. if (len_aligned_down < len) {
  5760. size_t left = len - len_aligned_down;
  5761. char tmp[align];
  5762. memset(tmp, 0xff, sizeof(tmp));
  5763. memcpy(tmp, (char *) buf + len_aligned_down, left);
  5764. ok = mg_flash_write(s_addr + len_aligned_down, tmp, sizeof(tmp));
  5765. }
  5766. s_crc32 = mg_crc32(s_crc32, (char *) buf, len); // Update CRC
  5767. MG_DEBUG(("%#x %p %lu -> %d", s_addr - len, buf, len, ok));
  5768. s_addr += len;
  5769. }
  5770. return ok;
  5771. }
  5772. MG_IRAM static uint32_t mg_fwkey(int fw) {
  5773. uint32_t key = MG_OTADATA_KEY + fw;
  5774. int bank = mg_flash_bank();
  5775. if (bank == 2 && fw == MG_FIRMWARE_PREVIOUS) key--;
  5776. if (bank == 2 && fw == MG_FIRMWARE_CURRENT) key++;
  5777. return key;
  5778. }
  5779. bool mg_ota_end(void) {
  5780. char *base = (char *) mg_flash_start() + mg_flash_size() / 2;
  5781. bool ok = false;
  5782. if (s_size) {
  5783. size_t size = s_addr - base;
  5784. uint32_t crc32 = mg_crc32(0, base, s_size);
  5785. if (size == s_size && crc32 == s_crc32) {
  5786. uint32_t now = (uint32_t) (mg_now() / 1000);
  5787. struct mg_otadata od = {crc32, size, now, MG_OTA_FIRST_BOOT};
  5788. uint32_t key = mg_fwkey(MG_FIRMWARE_PREVIOUS);
  5789. ok = mg_flash_save(NULL, key, &od, sizeof(od));
  5790. }
  5791. MG_DEBUG(("CRC: %x/%x, size: %lu/%lu, status: %s", s_crc32, crc32, s_size,
  5792. size, ok ? "ok" : "fail"));
  5793. s_size = 0;
  5794. if (ok) ok = mg_flash_swap_bank();
  5795. }
  5796. MG_INFO(("Finishing OTA: %s", ok ? "ok" : "fail"));
  5797. return ok;
  5798. }
  5799. MG_IRAM static struct mg_otadata mg_otadata(int fw) {
  5800. uint32_t key = mg_fwkey(fw);
  5801. struct mg_otadata od = {};
  5802. MG_INFO(("Loading %s OTA data", fw == MG_FIRMWARE_CURRENT ? "curr" : "prev"));
  5803. mg_flash_load(NULL, key, &od, sizeof(od));
  5804. // MG_DEBUG(("Loaded OTA data. fw %d, bank %d, key %p", fw, bank, key));
  5805. // mg_hexdump(&od, sizeof(od));
  5806. return od;
  5807. }
  5808. int mg_ota_status(int fw) {
  5809. struct mg_otadata od = mg_otadata(fw);
  5810. return od.status;
  5811. }
  5812. uint32_t mg_ota_crc32(int fw) {
  5813. struct mg_otadata od = mg_otadata(fw);
  5814. return od.crc32;
  5815. }
  5816. uint32_t mg_ota_timestamp(int fw) {
  5817. struct mg_otadata od = mg_otadata(fw);
  5818. return od.timestamp;
  5819. }
  5820. size_t mg_ota_size(int fw) {
  5821. struct mg_otadata od = mg_otadata(fw);
  5822. return od.size;
  5823. }
  5824. MG_IRAM bool mg_ota_commit(void) {
  5825. bool ok = true;
  5826. struct mg_otadata od = mg_otadata(MG_FIRMWARE_CURRENT);
  5827. if (od.status != MG_OTA_COMMITTED) {
  5828. od.status = MG_OTA_COMMITTED;
  5829. MG_INFO(("Committing current firmware, OD size %lu", sizeof(od)));
  5830. ok = mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &od, sizeof(od));
  5831. }
  5832. return ok;
  5833. }
  5834. bool mg_ota_rollback(void) {
  5835. MG_DEBUG(("Rolling firmware back"));
  5836. if (mg_flash_bank() == 0) {
  5837. // No dual bank support. Mark previous firmware as FIRST_BOOT
  5838. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5839. prev.status = MG_OTA_FIRST_BOOT;
  5840. return mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &prev,
  5841. sizeof(prev));
  5842. } else {
  5843. return mg_flash_swap_bank();
  5844. }
  5845. }
  5846. MG_IRAM void mg_ota_boot(void) {
  5847. MG_INFO(("Booting. Flash bank: %d", mg_flash_bank()));
  5848. struct mg_otadata curr = mg_otadata(MG_FIRMWARE_CURRENT);
  5849. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5850. if (curr.status == MG_OTA_FIRST_BOOT) {
  5851. if (prev.status == MG_OTA_UNAVAILABLE) {
  5852. MG_INFO(("Setting previous firmware state to committed"));
  5853. prev.status = MG_OTA_COMMITTED;
  5854. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_PREVIOUS), &prev, sizeof(prev));
  5855. }
  5856. curr.status = MG_OTA_UNCOMMITTED;
  5857. MG_INFO(("First boot, setting status to UNCOMMITTED"));
  5858. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &curr, sizeof(curr));
  5859. } else if (prev.status == MG_OTA_FIRST_BOOT && mg_flash_bank() == 0) {
  5860. // Swap paritions. Pray power does not disappear
  5861. size_t fs = mg_flash_size(), ss = mg_flash_sector_size();
  5862. char *partition1 = mg_flash_start();
  5863. char *partition2 = mg_flash_start() + fs / 2;
  5864. size_t ofs, max = fs / 2 - ss; // Set swap size to the whole partition
  5865. if (curr.status != MG_OTA_UNAVAILABLE &&
  5866. prev.status != MG_OTA_UNAVAILABLE) {
  5867. // We know exact sizes of both firmwares.
  5868. // Shrink swap size to the MAX(firmware1, firmware2)
  5869. size_t sz = curr.size > prev.size ? curr.size : prev.size;
  5870. if (sz > 0 && sz < max) max = sz;
  5871. }
  5872. // MG_OTA_FIRST_BOOT -> MG_OTA_UNCOMMITTED
  5873. prev.status = MG_OTA_UNCOMMITTED;
  5874. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_CURRENT, &prev,
  5875. sizeof(prev));
  5876. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &curr,
  5877. sizeof(curr));
  5878. MG_INFO(("Swapping partitions, size %u (%u sectors)", max, max / ss));
  5879. MG_INFO(("Do NOT power off..."));
  5880. mg_log_level = MG_LL_NONE;
  5881. // We use the last sector of partition2 for OTA data/config storage
  5882. // Therefore we can use last sector of partition1 for swapping
  5883. char *tmpsector = partition1 + fs / 2 - ss; // Last sector of partition1
  5884. (void) tmpsector;
  5885. for (ofs = 0; ofs < max; ofs += ss) {
  5886. // mg_flash_erase(tmpsector);
  5887. mg_flash_write(tmpsector, partition1 + ofs, ss);
  5888. // mg_flash_erase(partition1 + ofs);
  5889. mg_flash_write(partition1 + ofs, partition2 + ofs, ss);
  5890. // mg_flash_erase(partition2 + ofs);
  5891. mg_flash_write(partition2 + ofs, tmpsector, ss);
  5892. }
  5893. mg_device_reset();
  5894. }
  5895. }
  5896. #endif
  5897. #ifdef MG_ENABLE_LINES
  5898. #line 1 "src/printf.c"
  5899. #endif
  5900. size_t mg_queue_vprintf(struct mg_queue *q, const char *fmt, va_list *ap) {
  5901. size_t len = mg_snprintf(NULL, 0, fmt, ap);
  5902. char *buf;
  5903. if (len == 0 || mg_queue_book(q, &buf, len + 1) < len + 1) {
  5904. len = 0; // Nah. Not enough space
  5905. } else {
  5906. len = mg_vsnprintf((char *) buf, len + 1, fmt, ap);
  5907. mg_queue_add(q, len);
  5908. }
  5909. return len;
  5910. }
  5911. size_t mg_queue_printf(struct mg_queue *q, const char *fmt, ...) {
  5912. va_list ap;
  5913. size_t len;
  5914. va_start(ap, fmt);
  5915. len = mg_queue_vprintf(q, fmt, &ap);
  5916. va_end(ap);
  5917. return len;
  5918. }
  5919. static void mg_pfn_iobuf_private(char ch, void *param, bool expand) {
  5920. struct mg_iobuf *io = (struct mg_iobuf *) param;
  5921. if (expand && io->len + 2 > io->size) mg_iobuf_resize(io, io->len + 2);
  5922. if (io->len + 2 <= io->size) {
  5923. io->buf[io->len++] = (uint8_t) ch;
  5924. io->buf[io->len] = 0;
  5925. } else if (io->len < io->size) {
  5926. io->buf[io->len++] = 0; // Guarantee to 0-terminate
  5927. }
  5928. }
  5929. static void mg_putchar_iobuf_static(char ch, void *param) {
  5930. mg_pfn_iobuf_private(ch, param, false);
  5931. }
  5932. void mg_pfn_iobuf(char ch, void *param) {
  5933. mg_pfn_iobuf_private(ch, param, true);
  5934. }
  5935. size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap) {
  5936. struct mg_iobuf io = {(uint8_t *) buf, len, 0, 0};
  5937. size_t n = mg_vxprintf(mg_putchar_iobuf_static, &io, fmt, ap);
  5938. if (n < len) buf[n] = '\0';
  5939. return n;
  5940. }
  5941. size_t mg_snprintf(char *buf, size_t len, const char *fmt, ...) {
  5942. va_list ap;
  5943. size_t n;
  5944. va_start(ap, fmt);
  5945. n = mg_vsnprintf(buf, len, fmt, &ap);
  5946. va_end(ap);
  5947. return n;
  5948. }
  5949. char *mg_vmprintf(const char *fmt, va_list *ap) {
  5950. struct mg_iobuf io = {0, 0, 0, 256};
  5951. mg_vxprintf(mg_pfn_iobuf, &io, fmt, ap);
  5952. return (char *) io.buf;
  5953. }
  5954. char *mg_mprintf(const char *fmt, ...) {
  5955. char *s;
  5956. va_list ap;
  5957. va_start(ap, fmt);
  5958. s = mg_vmprintf(fmt, &ap);
  5959. va_end(ap);
  5960. return s;
  5961. }
  5962. void mg_pfn_stdout(char c, void *param) {
  5963. putchar(c);
  5964. (void) param;
  5965. }
  5966. static size_t print_ip4(void (*out)(char, void *), void *arg, uint8_t *p) {
  5967. return mg_xprintf(out, arg, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  5968. }
  5969. static size_t print_ip6(void (*out)(char, void *), void *arg, uint16_t *p) {
  5970. return mg_xprintf(out, arg, "[%x:%x:%x:%x:%x:%x:%x:%x]", mg_ntohs(p[0]),
  5971. mg_ntohs(p[1]), mg_ntohs(p[2]), mg_ntohs(p[3]),
  5972. mg_ntohs(p[4]), mg_ntohs(p[5]), mg_ntohs(p[6]),
  5973. mg_ntohs(p[7]));
  5974. }
  5975. size_t mg_print_ip4(void (*out)(char, void *), void *arg, va_list *ap) {
  5976. uint8_t *p = va_arg(*ap, uint8_t *);
  5977. return print_ip4(out, arg, p);
  5978. }
  5979. size_t mg_print_ip6(void (*out)(char, void *), void *arg, va_list *ap) {
  5980. uint16_t *p = va_arg(*ap, uint16_t *);
  5981. return print_ip6(out, arg, p);
  5982. }
  5983. size_t mg_print_ip(void (*out)(char, void *), void *arg, va_list *ap) {
  5984. struct mg_addr *addr = va_arg(*ap, struct mg_addr *);
  5985. if (addr->is_ip6) return print_ip6(out, arg, (uint16_t *) addr->ip);
  5986. return print_ip4(out, arg, (uint8_t *) &addr->ip);
  5987. }
  5988. size_t mg_print_ip_port(void (*out)(char, void *), void *arg, va_list *ap) {
  5989. struct mg_addr *a = va_arg(*ap, struct mg_addr *);
  5990. return mg_xprintf(out, arg, "%M:%hu", mg_print_ip, a, mg_ntohs(a->port));
  5991. }
  5992. size_t mg_print_mac(void (*out)(char, void *), void *arg, va_list *ap) {
  5993. uint8_t *p = va_arg(*ap, uint8_t *);
  5994. return mg_xprintf(out, arg, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2],
  5995. p[3], p[4], p[5]);
  5996. }
  5997. static char mg_esc(int c, bool esc) {
  5998. const char *p, *esc1 = "\b\f\n\r\t\\\"", *esc2 = "bfnrt\\\"";
  5999. for (p = esc ? esc1 : esc2; *p != '\0'; p++) {
  6000. if (*p == c) return esc ? esc2[p - esc1] : esc1[p - esc2];
  6001. }
  6002. return 0;
  6003. }
  6004. static char mg_escape(int c) {
  6005. return mg_esc(c, true);
  6006. }
  6007. static size_t qcpy(void (*out)(char, void *), void *ptr, char *buf,
  6008. size_t len) {
  6009. size_t i = 0, extra = 0;
  6010. for (i = 0; i < len && buf[i] != '\0'; i++) {
  6011. char c = mg_escape(buf[i]);
  6012. if (c) {
  6013. out('\\', ptr), out(c, ptr), extra++;
  6014. } else {
  6015. out(buf[i], ptr);
  6016. }
  6017. }
  6018. return i + extra;
  6019. }
  6020. static size_t bcpy(void (*out)(char, void *), void *arg, uint8_t *buf,
  6021. size_t len) {
  6022. size_t i, j, n = 0;
  6023. const char *t =
  6024. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6025. for (i = 0; i < len; i += 3) {
  6026. uint8_t c1 = buf[i], c2 = i + 1 < len ? buf[i + 1] : 0,
  6027. c3 = i + 2 < len ? buf[i + 2] : 0;
  6028. char tmp[4] = {t[c1 >> 2], t[(c1 & 3) << 4 | (c2 >> 4)], '=', '='};
  6029. if (i + 1 < len) tmp[2] = t[(c2 & 15) << 2 | (c3 >> 6)];
  6030. if (i + 2 < len) tmp[3] = t[c3 & 63];
  6031. for (j = 0; j < sizeof(tmp) && tmp[j] != '\0'; j++) out(tmp[j], arg);
  6032. n += j;
  6033. }
  6034. return n;
  6035. }
  6036. size_t mg_print_hex(void (*out)(char, void *), void *arg, va_list *ap) {
  6037. size_t bl = (size_t) va_arg(*ap, int);
  6038. uint8_t *p = va_arg(*ap, uint8_t *);
  6039. const char *hex = "0123456789abcdef";
  6040. size_t j;
  6041. for (j = 0; j < bl; j++) {
  6042. out(hex[(p[j] >> 4) & 0x0F], arg);
  6043. out(hex[p[j] & 0x0F], arg);
  6044. }
  6045. return 2 * bl;
  6046. }
  6047. size_t mg_print_base64(void (*out)(char, void *), void *arg, va_list *ap) {
  6048. size_t len = (size_t) va_arg(*ap, int);
  6049. uint8_t *buf = va_arg(*ap, uint8_t *);
  6050. return bcpy(out, arg, buf, len);
  6051. }
  6052. size_t mg_print_esc(void (*out)(char, void *), void *arg, va_list *ap) {
  6053. size_t len = (size_t) va_arg(*ap, int);
  6054. char *p = va_arg(*ap, char *);
  6055. if (len == 0) len = p == NULL ? 0 : strlen(p);
  6056. return qcpy(out, arg, p, len);
  6057. }
  6058. #ifdef MG_ENABLE_LINES
  6059. #line 1 "src/queue.c"
  6060. #endif
  6061. #if (defined(__GNUC__) && (__GNUC__ > 4) || \
  6062. (defined(__GNUC_MINOR__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
  6063. defined(__clang__)
  6064. #define MG_MEMORY_BARRIER() __sync_synchronize()
  6065. #elif defined(_MSC_VER) && _MSC_VER >= 1700
  6066. #define MG_MEMORY_BARRIER() MemoryBarrier()
  6067. #elif !defined(MG_MEMORY_BARRIER)
  6068. #define MG_MEMORY_BARRIER()
  6069. #endif
  6070. // Every message in a queue is prepended by a 32-bit message length (ML).
  6071. // If ML is 0, then it is the end, and reader must wrap to the beginning.
  6072. //
  6073. // Queue when q->tail <= q->head:
  6074. // |----- free -----| ML | message1 | ML | message2 | ----- free ------|
  6075. // ^ ^ ^ ^
  6076. // buf tail head len
  6077. //
  6078. // Queue when q->tail > q->head:
  6079. // | ML | message2 |----- free ------| ML | message1 | 0 |---- free ----|
  6080. // ^ ^ ^ ^
  6081. // buf head tail len
  6082. void mg_queue_init(struct mg_queue *q, char *buf, size_t size) {
  6083. q->size = size;
  6084. q->buf = buf;
  6085. q->head = q->tail = 0;
  6086. }
  6087. static size_t mg_queue_read_len(struct mg_queue *q) {
  6088. uint32_t n = 0;
  6089. MG_MEMORY_BARRIER();
  6090. memcpy(&n, q->buf + q->tail, sizeof(n));
  6091. assert(q->tail + n + sizeof(n) <= q->size);
  6092. return n;
  6093. }
  6094. static void mg_queue_write_len(struct mg_queue *q, size_t len) {
  6095. uint32_t n = (uint32_t) len;
  6096. memcpy(q->buf + q->head, &n, sizeof(n));
  6097. MG_MEMORY_BARRIER();
  6098. }
  6099. size_t mg_queue_book(struct mg_queue *q, char **buf, size_t len) {
  6100. size_t space = 0, hs = sizeof(uint32_t) * 2; // *2 is for the 0 marker
  6101. if (q->head >= q->tail && q->head + len + hs <= q->size) {
  6102. space = q->size - q->head - hs; // There is enough space
  6103. } else if (q->head >= q->tail && q->tail > hs) {
  6104. mg_queue_write_len(q, 0); // Not enough space ahead
  6105. q->head = 0; // Wrap head to the beginning
  6106. }
  6107. if (q->head + hs + len < q->tail) space = q->tail - q->head - hs;
  6108. if (buf != NULL) *buf = q->buf + q->head + sizeof(uint32_t);
  6109. return space;
  6110. }
  6111. size_t mg_queue_next(struct mg_queue *q, char **buf) {
  6112. size_t len = 0;
  6113. if (q->tail != q->head) {
  6114. len = mg_queue_read_len(q);
  6115. if (len == 0) { // Zero (head wrapped) ?
  6116. q->tail = 0; // Reset tail to the start
  6117. if (q->head > q->tail) len = mg_queue_read_len(q); // Read again
  6118. }
  6119. }
  6120. if (buf != NULL) *buf = q->buf + q->tail + sizeof(uint32_t);
  6121. assert(q->tail + len <= q->size);
  6122. return len;
  6123. }
  6124. void mg_queue_add(struct mg_queue *q, size_t len) {
  6125. assert(len > 0);
  6126. mg_queue_write_len(q, len);
  6127. assert(q->head + sizeof(uint32_t) * 2 + len <= q->size);
  6128. q->head += len + sizeof(uint32_t);
  6129. }
  6130. void mg_queue_del(struct mg_queue *q, size_t len) {
  6131. q->tail += len + sizeof(uint32_t);
  6132. assert(q->tail + sizeof(uint32_t) <= q->size);
  6133. }
  6134. #ifdef MG_ENABLE_LINES
  6135. #line 1 "src/rpc.c"
  6136. #endif
  6137. void mg_rpc_add(struct mg_rpc **head, struct mg_str method,
  6138. void (*fn)(struct mg_rpc_req *), void *fn_data) {
  6139. struct mg_rpc *rpc = (struct mg_rpc *) calloc(1, sizeof(*rpc));
  6140. if (rpc != NULL) {
  6141. rpc->method.buf = mg_mprintf("%.*s", method.len, method.buf);
  6142. rpc->method.len = method.len;
  6143. rpc->fn = fn;
  6144. rpc->fn_data = fn_data;
  6145. rpc->next = *head, *head = rpc;
  6146. }
  6147. }
  6148. void mg_rpc_del(struct mg_rpc **head, void (*fn)(struct mg_rpc_req *)) {
  6149. struct mg_rpc *r;
  6150. while ((r = *head) != NULL) {
  6151. if (r->fn == fn || fn == NULL) {
  6152. *head = r->next;
  6153. free((void *) r->method.buf);
  6154. free(r);
  6155. } else {
  6156. head = &(*head)->next;
  6157. }
  6158. }
  6159. }
  6160. static void mg_rpc_call(struct mg_rpc_req *r, struct mg_str method) {
  6161. struct mg_rpc *h = r->head == NULL ? NULL : *r->head;
  6162. while (h != NULL && !mg_match(method, h->method, NULL)) h = h->next;
  6163. if (h != NULL) {
  6164. r->rpc = h;
  6165. h->fn(r);
  6166. } else {
  6167. mg_rpc_err(r, -32601, "\"%.*s not found\"", (int) method.len, method.buf);
  6168. }
  6169. }
  6170. void mg_rpc_process(struct mg_rpc_req *r) {
  6171. int len, off = mg_json_get(r->frame, "$.method", &len);
  6172. if (off > 0 && r->frame.buf[off] == '"') {
  6173. struct mg_str method = mg_str_n(&r->frame.buf[off + 1], (size_t) len - 2);
  6174. mg_rpc_call(r, method);
  6175. } else if ((off = mg_json_get(r->frame, "$.result", &len)) > 0 ||
  6176. (off = mg_json_get(r->frame, "$.error", &len)) > 0) {
  6177. mg_rpc_call(r, mg_str("")); // JSON response! call "" method handler
  6178. } else {
  6179. mg_rpc_err(r, -32700, "%m", mg_print_esc, (int) r->frame.len,
  6180. r->frame.buf); // Invalid
  6181. }
  6182. }
  6183. void mg_rpc_vok(struct mg_rpc_req *r, const char *fmt, va_list *ap) {
  6184. int len, off = mg_json_get(r->frame, "$.id", &len);
  6185. if (off > 0) {
  6186. mg_xprintf(r->pfn, r->pfn_data, "{%m:%.*s,%m:", mg_print_esc, 0, "id", len,
  6187. &r->frame.buf[off], mg_print_esc, 0, "result");
  6188. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  6189. mg_xprintf(r->pfn, r->pfn_data, "}");
  6190. }
  6191. }
  6192. void mg_rpc_ok(struct mg_rpc_req *r, const char *fmt, ...) {
  6193. va_list ap;
  6194. va_start(ap, fmt);
  6195. mg_rpc_vok(r, fmt, &ap);
  6196. va_end(ap);
  6197. }
  6198. void mg_rpc_verr(struct mg_rpc_req *r, int code, const char *fmt, va_list *ap) {
  6199. int len, off = mg_json_get(r->frame, "$.id", &len);
  6200. mg_xprintf(r->pfn, r->pfn_data, "{");
  6201. if (off > 0) {
  6202. mg_xprintf(r->pfn, r->pfn_data, "%m:%.*s,", mg_print_esc, 0, "id", len,
  6203. &r->frame.buf[off]);
  6204. }
  6205. mg_xprintf(r->pfn, r->pfn_data, "%m:{%m:%d,%m:", mg_print_esc, 0, "error",
  6206. mg_print_esc, 0, "code", code, mg_print_esc, 0, "message");
  6207. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  6208. mg_xprintf(r->pfn, r->pfn_data, "}}");
  6209. }
  6210. void mg_rpc_err(struct mg_rpc_req *r, int code, const char *fmt, ...) {
  6211. va_list ap;
  6212. va_start(ap, fmt);
  6213. mg_rpc_verr(r, code, fmt, &ap);
  6214. va_end(ap);
  6215. }
  6216. static size_t print_methods(mg_pfn_t pfn, void *pfn_data, va_list *ap) {
  6217. struct mg_rpc *h, **head = (struct mg_rpc **) va_arg(*ap, void **);
  6218. size_t len = 0;
  6219. for (h = *head; h != NULL; h = h->next) {
  6220. if (h->method.len == 0) continue; // Ignore response handler
  6221. len += mg_xprintf(pfn, pfn_data, "%s%m", h == *head ? "" : ",",
  6222. mg_print_esc, (int) h->method.len, h->method.buf);
  6223. }
  6224. return len;
  6225. }
  6226. void mg_rpc_list(struct mg_rpc_req *r) {
  6227. mg_rpc_ok(r, "[%M]", print_methods, r->head);
  6228. }
  6229. #ifdef MG_ENABLE_LINES
  6230. #line 1 "src/sha1.c"
  6231. #endif
  6232. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  6233. /* 100% Public Domain */
  6234. union char64long16 {
  6235. unsigned char c[64];
  6236. uint32_t l[16];
  6237. };
  6238. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6239. static uint32_t blk0(union char64long16 *block, int i) {
  6240. if (MG_BIG_ENDIAN) {
  6241. } else {
  6242. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  6243. (rol(block->l[i], 8) & 0x00FF00FF);
  6244. }
  6245. return block->l[i];
  6246. }
  6247. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  6248. #undef blk
  6249. #undef R0
  6250. #undef R1
  6251. #undef R2
  6252. #undef R3
  6253. #undef R4
  6254. #define blk(i) \
  6255. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  6256. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6257. 1))
  6258. #define R0(v, w, x, y, z, i) \
  6259. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6260. w = rol(w, 30);
  6261. #define R1(v, w, x, y, z, i) \
  6262. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6263. w = rol(w, 30);
  6264. #define R2(v, w, x, y, z, i) \
  6265. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6266. w = rol(w, 30);
  6267. #define R3(v, w, x, y, z, i) \
  6268. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6269. w = rol(w, 30);
  6270. #define R4(v, w, x, y, z, i) \
  6271. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6272. w = rol(w, 30);
  6273. static void mg_sha1_transform(uint32_t state[5],
  6274. const unsigned char *buffer) {
  6275. uint32_t a, b, c, d, e;
  6276. union char64long16 block[1];
  6277. memcpy(block, buffer, 64);
  6278. a = state[0];
  6279. b = state[1];
  6280. c = state[2];
  6281. d = state[3];
  6282. e = state[4];
  6283. R0(a, b, c, d, e, 0);
  6284. R0(e, a, b, c, d, 1);
  6285. R0(d, e, a, b, c, 2);
  6286. R0(c, d, e, a, b, 3);
  6287. R0(b, c, d, e, a, 4);
  6288. R0(a, b, c, d, e, 5);
  6289. R0(e, a, b, c, d, 6);
  6290. R0(d, e, a, b, c, 7);
  6291. R0(c, d, e, a, b, 8);
  6292. R0(b, c, d, e, a, 9);
  6293. R0(a, b, c, d, e, 10);
  6294. R0(e, a, b, c, d, 11);
  6295. R0(d, e, a, b, c, 12);
  6296. R0(c, d, e, a, b, 13);
  6297. R0(b, c, d, e, a, 14);
  6298. R0(a, b, c, d, e, 15);
  6299. R1(e, a, b, c, d, 16);
  6300. R1(d, e, a, b, c, 17);
  6301. R1(c, d, e, a, b, 18);
  6302. R1(b, c, d, e, a, 19);
  6303. R2(a, b, c, d, e, 20);
  6304. R2(e, a, b, c, d, 21);
  6305. R2(d, e, a, b, c, 22);
  6306. R2(c, d, e, a, b, 23);
  6307. R2(b, c, d, e, a, 24);
  6308. R2(a, b, c, d, e, 25);
  6309. R2(e, a, b, c, d, 26);
  6310. R2(d, e, a, b, c, 27);
  6311. R2(c, d, e, a, b, 28);
  6312. R2(b, c, d, e, a, 29);
  6313. R2(a, b, c, d, e, 30);
  6314. R2(e, a, b, c, d, 31);
  6315. R2(d, e, a, b, c, 32);
  6316. R2(c, d, e, a, b, 33);
  6317. R2(b, c, d, e, a, 34);
  6318. R2(a, b, c, d, e, 35);
  6319. R2(e, a, b, c, d, 36);
  6320. R2(d, e, a, b, c, 37);
  6321. R2(c, d, e, a, b, 38);
  6322. R2(b, c, d, e, a, 39);
  6323. R3(a, b, c, d, e, 40);
  6324. R3(e, a, b, c, d, 41);
  6325. R3(d, e, a, b, c, 42);
  6326. R3(c, d, e, a, b, 43);
  6327. R3(b, c, d, e, a, 44);
  6328. R3(a, b, c, d, e, 45);
  6329. R3(e, a, b, c, d, 46);
  6330. R3(d, e, a, b, c, 47);
  6331. R3(c, d, e, a, b, 48);
  6332. R3(b, c, d, e, a, 49);
  6333. R3(a, b, c, d, e, 50);
  6334. R3(e, a, b, c, d, 51);
  6335. R3(d, e, a, b, c, 52);
  6336. R3(c, d, e, a, b, 53);
  6337. R3(b, c, d, e, a, 54);
  6338. R3(a, b, c, d, e, 55);
  6339. R3(e, a, b, c, d, 56);
  6340. R3(d, e, a, b, c, 57);
  6341. R3(c, d, e, a, b, 58);
  6342. R3(b, c, d, e, a, 59);
  6343. R4(a, b, c, d, e, 60);
  6344. R4(e, a, b, c, d, 61);
  6345. R4(d, e, a, b, c, 62);
  6346. R4(c, d, e, a, b, 63);
  6347. R4(b, c, d, e, a, 64);
  6348. R4(a, b, c, d, e, 65);
  6349. R4(e, a, b, c, d, 66);
  6350. R4(d, e, a, b, c, 67);
  6351. R4(c, d, e, a, b, 68);
  6352. R4(b, c, d, e, a, 69);
  6353. R4(a, b, c, d, e, 70);
  6354. R4(e, a, b, c, d, 71);
  6355. R4(d, e, a, b, c, 72);
  6356. R4(c, d, e, a, b, 73);
  6357. R4(b, c, d, e, a, 74);
  6358. R4(a, b, c, d, e, 75);
  6359. R4(e, a, b, c, d, 76);
  6360. R4(d, e, a, b, c, 77);
  6361. R4(c, d, e, a, b, 78);
  6362. R4(b, c, d, e, a, 79);
  6363. state[0] += a;
  6364. state[1] += b;
  6365. state[2] += c;
  6366. state[3] += d;
  6367. state[4] += e;
  6368. /* Erase working structures. The order of operations is important,
  6369. * used to ensure that compiler doesn't optimize those out. */
  6370. memset(block, 0, sizeof(block));
  6371. a = b = c = d = e = 0;
  6372. (void) a;
  6373. (void) b;
  6374. (void) c;
  6375. (void) d;
  6376. (void) e;
  6377. }
  6378. void mg_sha1_init(mg_sha1_ctx *context) {
  6379. context->state[0] = 0x67452301;
  6380. context->state[1] = 0xEFCDAB89;
  6381. context->state[2] = 0x98BADCFE;
  6382. context->state[3] = 0x10325476;
  6383. context->state[4] = 0xC3D2E1F0;
  6384. context->count[0] = context->count[1] = 0;
  6385. }
  6386. void mg_sha1_update(mg_sha1_ctx *context, const unsigned char *data,
  6387. size_t len) {
  6388. size_t i, j;
  6389. j = context->count[0];
  6390. if ((context->count[0] += (uint32_t) len << 3) < j) context->count[1]++;
  6391. context->count[1] += (uint32_t) (len >> 29);
  6392. j = (j >> 3) & 63;
  6393. if ((j + len) > 63) {
  6394. memcpy(&context->buffer[j], data, (i = 64 - j));
  6395. mg_sha1_transform(context->state, context->buffer);
  6396. for (; i + 63 < len; i += 64) {
  6397. mg_sha1_transform(context->state, &data[i]);
  6398. }
  6399. j = 0;
  6400. } else
  6401. i = 0;
  6402. memcpy(&context->buffer[j], &data[i], len - i);
  6403. }
  6404. void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *context) {
  6405. unsigned i;
  6406. unsigned char finalcount[8], c;
  6407. for (i = 0; i < 8; i++) {
  6408. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  6409. ((3 - (i & 3)) * 8)) &
  6410. 255);
  6411. }
  6412. c = 0200;
  6413. mg_sha1_update(context, &c, 1);
  6414. while ((context->count[0] & 504) != 448) {
  6415. c = 0000;
  6416. mg_sha1_update(context, &c, 1);
  6417. }
  6418. mg_sha1_update(context, finalcount, 8);
  6419. for (i = 0; i < 20; i++) {
  6420. digest[i] =
  6421. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  6422. }
  6423. memset(context, '\0', sizeof(*context));
  6424. memset(&finalcount, '\0', sizeof(finalcount));
  6425. }
  6426. #ifdef MG_ENABLE_LINES
  6427. #line 1 "src/sha256.c"
  6428. #endif
  6429. // https://github.com/B-Con/crypto-algorithms
  6430. // Author: Brad Conte (brad AT bradconte.com)
  6431. // Disclaimer: This code is presented "as is" without any guarantees.
  6432. // Details: Defines the API for the corresponding SHA1 implementation.
  6433. // Copyright: public domain
  6434. #define ror(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
  6435. #define ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
  6436. #define maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
  6437. #define ep0(x) (ror(x, 2) ^ ror(x, 13) ^ ror(x, 22))
  6438. #define ep1(x) (ror(x, 6) ^ ror(x, 11) ^ ror(x, 25))
  6439. #define sig0(x) (ror(x, 7) ^ ror(x, 18) ^ ((x) >> 3))
  6440. #define sig1(x) (ror(x, 17) ^ ror(x, 19) ^ ((x) >> 10))
  6441. static const uint32_t mg_sha256_k[64] = {
  6442. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
  6443. 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  6444. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
  6445. 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  6446. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
  6447. 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  6448. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
  6449. 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  6450. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
  6451. 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  6452. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
  6453. void mg_sha256_init(mg_sha256_ctx *ctx) {
  6454. ctx->len = 0;
  6455. ctx->bits = 0;
  6456. ctx->state[0] = 0x6a09e667;
  6457. ctx->state[1] = 0xbb67ae85;
  6458. ctx->state[2] = 0x3c6ef372;
  6459. ctx->state[3] = 0xa54ff53a;
  6460. ctx->state[4] = 0x510e527f;
  6461. ctx->state[5] = 0x9b05688c;
  6462. ctx->state[6] = 0x1f83d9ab;
  6463. ctx->state[7] = 0x5be0cd19;
  6464. }
  6465. static void mg_sha256_chunk(mg_sha256_ctx *ctx) {
  6466. int i, j;
  6467. uint32_t a, b, c, d, e, f, g, h;
  6468. uint32_t m[64];
  6469. for (i = 0, j = 0; i < 16; ++i, j += 4)
  6470. m[i] = (uint32_t) (((uint32_t) ctx->buffer[j] << 24) |
  6471. ((uint32_t) ctx->buffer[j + 1] << 16) |
  6472. ((uint32_t) ctx->buffer[j + 2] << 8) |
  6473. ((uint32_t) ctx->buffer[j + 3]));
  6474. for (; i < 64; ++i)
  6475. m[i] = sig1(m[i - 2]) + m[i - 7] + sig0(m[i - 15]) + m[i - 16];
  6476. a = ctx->state[0];
  6477. b = ctx->state[1];
  6478. c = ctx->state[2];
  6479. d = ctx->state[3];
  6480. e = ctx->state[4];
  6481. f = ctx->state[5];
  6482. g = ctx->state[6];
  6483. h = ctx->state[7];
  6484. for (i = 0; i < 64; ++i) {
  6485. uint32_t t1 = h + ep1(e) + ch(e, f, g) + mg_sha256_k[i] + m[i];
  6486. uint32_t t2 = ep0(a) + maj(a, b, c);
  6487. h = g;
  6488. g = f;
  6489. f = e;
  6490. e = d + t1;
  6491. d = c;
  6492. c = b;
  6493. b = a;
  6494. a = t1 + t2;
  6495. }
  6496. ctx->state[0] += a;
  6497. ctx->state[1] += b;
  6498. ctx->state[2] += c;
  6499. ctx->state[3] += d;
  6500. ctx->state[4] += e;
  6501. ctx->state[5] += f;
  6502. ctx->state[6] += g;
  6503. ctx->state[7] += h;
  6504. }
  6505. void mg_sha256_update(mg_sha256_ctx *ctx, const unsigned char *data,
  6506. size_t len) {
  6507. size_t i;
  6508. for (i = 0; i < len; i++) {
  6509. ctx->buffer[ctx->len] = data[i];
  6510. if ((++ctx->len) == 64) {
  6511. mg_sha256_chunk(ctx);
  6512. ctx->bits += 512;
  6513. ctx->len = 0;
  6514. }
  6515. }
  6516. }
  6517. // TODO: make final reusable (remove side effects)
  6518. void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *ctx) {
  6519. uint32_t i = ctx->len;
  6520. if (i < 56) {
  6521. ctx->buffer[i++] = 0x80;
  6522. while (i < 56) {
  6523. ctx->buffer[i++] = 0x00;
  6524. }
  6525. } else {
  6526. ctx->buffer[i++] = 0x80;
  6527. while (i < 64) {
  6528. ctx->buffer[i++] = 0x00;
  6529. }
  6530. mg_sha256_chunk(ctx);
  6531. memset(ctx->buffer, 0, 56);
  6532. }
  6533. ctx->bits += ctx->len * 8;
  6534. ctx->buffer[63] = (uint8_t) ((ctx->bits) & 0xff);
  6535. ctx->buffer[62] = (uint8_t) ((ctx->bits >> 8) & 0xff);
  6536. ctx->buffer[61] = (uint8_t) ((ctx->bits >> 16) & 0xff);
  6537. ctx->buffer[60] = (uint8_t) ((ctx->bits >> 24) & 0xff);
  6538. ctx->buffer[59] = (uint8_t) ((ctx->bits >> 32) & 0xff);
  6539. ctx->buffer[58] = (uint8_t) ((ctx->bits >> 40) & 0xff);
  6540. ctx->buffer[57] = (uint8_t) ((ctx->bits >> 48) & 0xff);
  6541. ctx->buffer[56] = (uint8_t) ((ctx->bits >> 56) & 0xff);
  6542. mg_sha256_chunk(ctx);
  6543. for (i = 0; i < 4; ++i) {
  6544. digest[i] = (uint8_t) ((ctx->state[0] >> (24 - i * 8)) & 0xff);
  6545. digest[i + 4] = (uint8_t) ((ctx->state[1] >> (24 - i * 8)) & 0xff);
  6546. digest[i + 8] = (uint8_t) ((ctx->state[2] >> (24 - i * 8)) & 0xff);
  6547. digest[i + 12] = (uint8_t) ((ctx->state[3] >> (24 - i * 8)) & 0xff);
  6548. digest[i + 16] = (uint8_t) ((ctx->state[4] >> (24 - i * 8)) & 0xff);
  6549. digest[i + 20] = (uint8_t) ((ctx->state[5] >> (24 - i * 8)) & 0xff);
  6550. digest[i + 24] = (uint8_t) ((ctx->state[6] >> (24 - i * 8)) & 0xff);
  6551. digest[i + 28] = (uint8_t) ((ctx->state[7] >> (24 - i * 8)) & 0xff);
  6552. }
  6553. }
  6554. void mg_hmac_sha256(uint8_t dst[32], uint8_t *key, size_t keysz, uint8_t *data,
  6555. size_t datasz) {
  6556. mg_sha256_ctx ctx;
  6557. uint8_t k[64] = {0};
  6558. uint8_t o_pad[64], i_pad[64];
  6559. unsigned int i;
  6560. memset(i_pad, 0x36, sizeof(i_pad));
  6561. memset(o_pad, 0x5c, sizeof(o_pad));
  6562. if (keysz < 64) {
  6563. if (keysz > 0) memmove(k, key, keysz);
  6564. } else {
  6565. mg_sha256_init(&ctx);
  6566. mg_sha256_update(&ctx, key, keysz);
  6567. mg_sha256_final(k, &ctx);
  6568. }
  6569. for (i = 0; i < sizeof(k); i++) {
  6570. i_pad[i] ^= k[i];
  6571. o_pad[i] ^= k[i];
  6572. }
  6573. mg_sha256_init(&ctx);
  6574. mg_sha256_update(&ctx, i_pad, sizeof(i_pad));
  6575. mg_sha256_update(&ctx, data, datasz);
  6576. mg_sha256_final(dst, &ctx);
  6577. mg_sha256_init(&ctx);
  6578. mg_sha256_update(&ctx, o_pad, sizeof(o_pad));
  6579. mg_sha256_update(&ctx, dst, 32);
  6580. mg_sha256_final(dst, &ctx);
  6581. }
  6582. #ifdef MG_ENABLE_LINES
  6583. #line 1 "src/sntp.c"
  6584. #endif
  6585. #define SNTP_TIME_OFFSET 2208988800U // (1970 - 1900) in seconds
  6586. #define SNTP_MAX_FRAC 4294967295.0 // 2 ** 32 - 1
  6587. static int64_t gettimestamp(const uint32_t *data) {
  6588. uint32_t sec = mg_ntohl(data[0]), frac = mg_ntohl(data[1]);
  6589. if (sec) sec -= SNTP_TIME_OFFSET;
  6590. return ((int64_t) sec) * 1000 + (int64_t) (frac / SNTP_MAX_FRAC * 1000.0);
  6591. }
  6592. int64_t mg_sntp_parse(const unsigned char *buf, size_t len) {
  6593. int64_t res = -1;
  6594. int mode = len > 0 ? buf[0] & 7 : 0;
  6595. int version = len > 0 ? (buf[0] >> 3) & 7 : 0;
  6596. if (len < 48) {
  6597. MG_ERROR(("%s", "corrupt packet"));
  6598. } else if (mode != 4 && mode != 5) {
  6599. MG_ERROR(("%s", "not a server reply"));
  6600. } else if (buf[1] == 0) {
  6601. MG_ERROR(("%s", "server sent a kiss of death"));
  6602. } else if (version == 4 || version == 3) {
  6603. // int64_t ref = gettimestamp((uint32_t *) &buf[16]);
  6604. int64_t t0 = gettimestamp((uint32_t *) &buf[24]);
  6605. int64_t t1 = gettimestamp((uint32_t *) &buf[32]);
  6606. int64_t t2 = gettimestamp((uint32_t *) &buf[40]);
  6607. int64_t t3 = (int64_t) mg_millis();
  6608. int64_t delta = (t3 - t0) - (t2 - t1);
  6609. MG_VERBOSE(("%lld %lld %lld %lld delta:%lld", t0, t1, t2, t3, delta));
  6610. res = t2 + delta / 2;
  6611. } else {
  6612. MG_ERROR(("unexpected version: %d", version));
  6613. }
  6614. return res;
  6615. }
  6616. static void sntp_cb(struct mg_connection *c, int ev, void *ev_data) {
  6617. if (ev == MG_EV_READ) {
  6618. int64_t milliseconds = mg_sntp_parse(c->recv.buf, c->recv.len);
  6619. if (milliseconds > 0) {
  6620. MG_DEBUG(("%lu got time: %lld ms from epoch", c->id, milliseconds));
  6621. mg_call(c, MG_EV_SNTP_TIME, (uint64_t *) &milliseconds);
  6622. MG_VERBOSE(("%u.%u", (unsigned) (milliseconds / 1000),
  6623. (unsigned) (milliseconds % 1000)));
  6624. }
  6625. mg_iobuf_del(&c->recv, 0, c->recv.len); // Free receive buffer
  6626. } else if (ev == MG_EV_CONNECT) {
  6627. mg_sntp_request(c);
  6628. } else if (ev == MG_EV_CLOSE) {
  6629. }
  6630. (void) ev_data;
  6631. }
  6632. void mg_sntp_request(struct mg_connection *c) {
  6633. if (c->is_resolving) {
  6634. MG_ERROR(("%lu wait until resolved", c->id));
  6635. } else {
  6636. int64_t now = (int64_t) mg_millis(); // Use int64_t, for vc98
  6637. uint8_t buf[48] = {0};
  6638. uint32_t *t = (uint32_t *) &buf[40];
  6639. double frac = ((double) (now % 1000)) / 1000.0 * SNTP_MAX_FRAC;
  6640. buf[0] = (0 << 6) | (4 << 3) | 3;
  6641. t[0] = mg_htonl((uint32_t) (now / 1000) + SNTP_TIME_OFFSET);
  6642. t[1] = mg_htonl((uint32_t) frac);
  6643. mg_send(c, buf, sizeof(buf));
  6644. }
  6645. }
  6646. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url,
  6647. mg_event_handler_t fn, void *fnd) {
  6648. struct mg_connection *c = NULL;
  6649. if (url == NULL) url = "udp://time.google.com:123";
  6650. if ((c = mg_connect(mgr, url, fn, fnd)) != NULL) c->pfn = sntp_cb;
  6651. return c;
  6652. }
  6653. #ifdef MG_ENABLE_LINES
  6654. #line 1 "src/sock.c"
  6655. #endif
  6656. #if MG_ENABLE_SOCKET
  6657. #ifndef closesocket
  6658. #define closesocket(x) close(x)
  6659. #endif
  6660. #define FD(c_) ((MG_SOCKET_TYPE) (size_t) (c_)->fd)
  6661. #define S2PTR(s_) ((void *) (size_t) (s_))
  6662. #ifndef MSG_NONBLOCKING
  6663. #define MSG_NONBLOCKING 0
  6664. #endif
  6665. #ifndef AF_INET6
  6666. #define AF_INET6 10
  6667. #endif
  6668. #ifndef MG_SOCK_ERR
  6669. #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? errno : 0)
  6670. #endif
  6671. #ifndef MG_SOCK_INTR
  6672. #define MG_SOCK_INTR(fd) (fd == MG_INVALID_SOCKET && MG_SOCK_ERR(-1) == EINTR)
  6673. #endif
  6674. #ifndef MG_SOCK_PENDING
  6675. #define MG_SOCK_PENDING(errcode) \
  6676. (((errcode) < 0) && (errno == EINPROGRESS || errno == EWOULDBLOCK))
  6677. #endif
  6678. #ifndef MG_SOCK_RESET
  6679. #define MG_SOCK_RESET(errcode) \
  6680. (((errcode) < 0) && (errno == EPIPE || errno == ECONNRESET))
  6681. #endif
  6682. union usa {
  6683. struct sockaddr sa;
  6684. struct sockaddr_in sin;
  6685. #if MG_ENABLE_IPV6
  6686. struct sockaddr_in6 sin6;
  6687. #endif
  6688. };
  6689. static socklen_t tousa(struct mg_addr *a, union usa *usa) {
  6690. socklen_t len = sizeof(usa->sin);
  6691. memset(usa, 0, sizeof(*usa));
  6692. usa->sin.sin_family = AF_INET;
  6693. usa->sin.sin_port = a->port;
  6694. memcpy(&usa->sin.sin_addr, a->ip, sizeof(uint32_t));
  6695. #if MG_ENABLE_IPV6
  6696. if (a->is_ip6) {
  6697. usa->sin.sin_family = AF_INET6;
  6698. usa->sin6.sin6_port = a->port;
  6699. usa->sin6.sin6_scope_id = a->scope_id;
  6700. memcpy(&usa->sin6.sin6_addr, a->ip, sizeof(a->ip));
  6701. len = sizeof(usa->sin6);
  6702. }
  6703. #endif
  6704. return len;
  6705. }
  6706. static void tomgaddr(union usa *usa, struct mg_addr *a, bool is_ip6) {
  6707. a->is_ip6 = is_ip6;
  6708. a->port = usa->sin.sin_port;
  6709. memcpy(&a->ip, &usa->sin.sin_addr, sizeof(uint32_t));
  6710. #if MG_ENABLE_IPV6
  6711. if (is_ip6) {
  6712. memcpy(a->ip, &usa->sin6.sin6_addr, sizeof(a->ip));
  6713. a->port = usa->sin6.sin6_port;
  6714. a->scope_id = (uint8_t) usa->sin6.sin6_scope_id;
  6715. }
  6716. #endif
  6717. }
  6718. static void setlocaddr(MG_SOCKET_TYPE fd, struct mg_addr *addr) {
  6719. union usa usa;
  6720. socklen_t n = sizeof(usa);
  6721. if (getsockname(fd, &usa.sa, &n) == 0) {
  6722. tomgaddr(&usa, addr, n != sizeof(usa.sin));
  6723. }
  6724. }
  6725. static void iolog(struct mg_connection *c, char *buf, long n, bool r) {
  6726. if (n == MG_IO_WAIT) {
  6727. // Do nothing
  6728. } else if (n <= 0) {
  6729. c->is_closing = 1; // Termination. Don't call mg_error(): #1529
  6730. } else if (n > 0) {
  6731. if (c->is_hexdumping) {
  6732. MG_INFO(("\n-- %lu %M %s %M %ld", c->id, mg_print_ip_port, &c->loc,
  6733. r ? "<-" : "->", mg_print_ip_port, &c->rem, n));
  6734. mg_hexdump(buf, (size_t) n);
  6735. }
  6736. if (r) {
  6737. c->recv.len += (size_t) n;
  6738. mg_call(c, MG_EV_READ, &n);
  6739. } else {
  6740. mg_iobuf_del(&c->send, 0, (size_t) n);
  6741. // if (c->send.len == 0) mg_iobuf_resize(&c->send, 0);
  6742. if (c->send.len == 0) {
  6743. MG_EPOLL_MOD(c, 0);
  6744. }
  6745. mg_call(c, MG_EV_WRITE, &n);
  6746. }
  6747. }
  6748. }
  6749. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  6750. long n;
  6751. if (c->is_udp) {
  6752. union usa usa;
  6753. socklen_t slen = tousa(&c->rem, &usa);
  6754. n = sendto(FD(c), (char *) buf, len, 0, &usa.sa, slen);
  6755. if (n > 0) setlocaddr(FD(c), &c->loc);
  6756. } else {
  6757. n = send(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6758. }
  6759. MG_VERBOSE(("%lu %ld %d", c->id, n, MG_SOCK_ERR(n)));
  6760. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6761. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6762. if (n <= 0) return MG_IO_ERR;
  6763. return n;
  6764. }
  6765. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  6766. if (c->is_udp) {
  6767. long n = mg_io_send(c, buf, len);
  6768. MG_DEBUG(("%lu %ld %lu:%lu:%lu %ld err %d", c->id, c->fd, c->send.len,
  6769. c->recv.len, c->rtls.len, n, MG_SOCK_ERR(n)));
  6770. iolog(c, (char *) buf, n, false);
  6771. return n > 0;
  6772. } else {
  6773. return mg_iobuf_add(&c->send, c->send.len, buf, len);
  6774. }
  6775. }
  6776. static void mg_set_non_blocking_mode(MG_SOCKET_TYPE fd) {
  6777. #if defined(MG_CUSTOM_NONBLOCK)
  6778. MG_CUSTOM_NONBLOCK(fd);
  6779. #elif MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  6780. unsigned long on = 1;
  6781. ioctlsocket(fd, FIONBIO, &on);
  6782. #elif MG_ENABLE_RL
  6783. unsigned long on = 1;
  6784. ioctlsocket(fd, FIONBIO, &on);
  6785. #elif MG_ENABLE_FREERTOS_TCP
  6786. const BaseType_t off = 0;
  6787. if (setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6788. if (setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6789. #elif MG_ENABLE_LWIP
  6790. lwip_fcntl(fd, F_SETFL, O_NONBLOCK);
  6791. #elif MG_ARCH == MG_ARCH_AZURERTOS
  6792. fcntl(fd, F_SETFL, O_NONBLOCK);
  6793. #elif MG_ARCH == MG_ARCH_TIRTOS
  6794. int val = 0;
  6795. setsockopt(fd, SOL_SOCKET, SO_BLOCKING, &val, sizeof(val));
  6796. // SPRU524J section 3.3.3 page 63, SO_SNDLOWAT
  6797. int sz = sizeof(val);
  6798. getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &val, &sz);
  6799. val /= 2; // set send low-water mark at half send buffer size
  6800. setsockopt(fd, SOL_SOCKET, SO_SNDLOWAT, &val, sizeof(val));
  6801. #else
  6802. fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); // Non-blocking mode
  6803. fcntl(fd, F_SETFD, FD_CLOEXEC); // Set close-on-exec
  6804. #endif
  6805. }
  6806. bool mg_open_listener(struct mg_connection *c, const char *url) {
  6807. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6808. bool success = false;
  6809. c->loc.port = mg_htons(mg_url_port(url));
  6810. if (!mg_aton(mg_url_host(url), &c->loc)) {
  6811. MG_ERROR(("invalid listening URL: %s", url));
  6812. } else {
  6813. union usa usa;
  6814. socklen_t slen = tousa(&c->loc, &usa);
  6815. int rc, on = 1, af = c->loc.is_ip6 ? AF_INET6 : AF_INET;
  6816. int type = strncmp(url, "udp:", 4) == 0 ? SOCK_DGRAM : SOCK_STREAM;
  6817. int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP;
  6818. (void) on;
  6819. if ((fd = socket(af, type, proto)) == MG_INVALID_SOCKET) {
  6820. MG_ERROR(("socket: %d", MG_SOCK_ERR(-1)));
  6821. #if defined(SO_EXCLUSIVEADDRUSE)
  6822. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  6823. (char *) &on, sizeof(on))) != 0) {
  6824. // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE"
  6825. MG_ERROR(("setsockopt(SO_EXCLUSIVEADDRUSE): %d %d", on, MG_SOCK_ERR(rc)));
  6826. #elif defined(SO_REUSEADDR) && (!defined(LWIP_SOCKET) || SO_REUSE)
  6827. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on,
  6828. sizeof(on))) != 0) {
  6829. // 1. SO_REUSEADDR semantics on UNIX and Windows is different. On
  6830. // Windows, SO_REUSEADDR allows to bind a socket to a port without error
  6831. // even if the port is already open by another program. This is not the
  6832. // behavior SO_REUSEADDR was designed for, and leads to hard-to-track
  6833. // failure scenarios.
  6834. //
  6835. // 2. For LWIP, SO_REUSEADDR should be explicitly enabled by defining
  6836. // SO_REUSE = 1 in lwipopts.h, otherwise the code below will compile but
  6837. // won't work! (setsockopt will return EINVAL)
  6838. MG_ERROR(("setsockopt(SO_REUSEADDR): %d", MG_SOCK_ERR(rc)));
  6839. #endif
  6840. #if MG_IPV6_V6ONLY
  6841. // Bind only to the V6 address, not V4 address on this port
  6842. } else if (c->loc.is_ip6 &&
  6843. (rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &on,
  6844. sizeof(on))) != 0) {
  6845. // See #2089. Allow to bind v4 and v6 sockets on the same port
  6846. MG_ERROR(("setsockopt(IPV6_V6ONLY): %d", MG_SOCK_ERR(rc)));
  6847. #endif
  6848. } else if ((rc = bind(fd, &usa.sa, slen)) != 0) {
  6849. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6850. } else if ((type == SOCK_STREAM &&
  6851. (rc = listen(fd, MG_SOCK_LISTEN_BACKLOG_SIZE)) != 0)) {
  6852. // NOTE(lsm): FreeRTOS uses backlog value as a connection limit
  6853. // In case port was set to 0, get the real port number
  6854. MG_ERROR(("listen: %d", MG_SOCK_ERR(rc)));
  6855. } else {
  6856. setlocaddr(fd, &c->loc);
  6857. mg_set_non_blocking_mode(fd);
  6858. c->fd = S2PTR(fd);
  6859. MG_EPOLL_ADD(c);
  6860. success = true;
  6861. }
  6862. }
  6863. if (success == false && fd != MG_INVALID_SOCKET) closesocket(fd);
  6864. return success;
  6865. }
  6866. static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
  6867. long n = 0;
  6868. if (c->is_udp) {
  6869. union usa usa;
  6870. socklen_t slen = tousa(&c->rem, &usa);
  6871. n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
  6872. if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
  6873. } else {
  6874. n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6875. }
  6876. MG_VERBOSE(("%lu %ld %d", c->id, n, MG_SOCK_ERR(n)));
  6877. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6878. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6879. if (n <= 0) return MG_IO_ERR;
  6880. return n;
  6881. }
  6882. static bool ioalloc(struct mg_connection *c, struct mg_iobuf *io) {
  6883. bool res = false;
  6884. if (io->len >= MG_MAX_RECV_SIZE) {
  6885. mg_error(c, "MG_MAX_RECV_SIZE");
  6886. } else if (io->size <= io->len &&
  6887. !mg_iobuf_resize(io, io->size + MG_IO_SIZE)) {
  6888. mg_error(c, "OOM");
  6889. } else {
  6890. res = true;
  6891. }
  6892. return res;
  6893. }
  6894. // NOTE(lsm): do only one iteration of reads, cause some systems
  6895. // (e.g. FreeRTOS stack) return 0 instead of -1/EWOULDBLOCK when no data
  6896. static void read_conn(struct mg_connection *c) {
  6897. if (ioalloc(c, &c->recv)) {
  6898. char *buf = (char *) &c->recv.buf[c->recv.len];
  6899. size_t len = c->recv.size - c->recv.len;
  6900. long n = -1;
  6901. if (c->is_tls) {
  6902. if (!ioalloc(c, &c->rtls)) return;
  6903. n = recv_raw(c, (char *) &c->rtls.buf[c->rtls.len],
  6904. c->rtls.size - c->rtls.len);
  6905. if (n == MG_IO_ERR && c->rtls.len == 0) {
  6906. // Close only if we have fully drained both raw (rtls) and TLS buffers
  6907. c->is_closing = 1;
  6908. } else {
  6909. if (n > 0) c->rtls.len += (size_t) n;
  6910. if (c->is_tls_hs) mg_tls_handshake(c);
  6911. n = c->is_tls_hs ? (long) MG_IO_WAIT : mg_tls_recv(c, buf, len);
  6912. }
  6913. } else {
  6914. n = recv_raw(c, buf, len);
  6915. }
  6916. MG_DEBUG(("%lu %ld %lu:%lu:%lu %ld err %d", c->id, c->fd, c->send.len,
  6917. c->recv.len, c->rtls.len, n, MG_SOCK_ERR(n)));
  6918. iolog(c, buf, n, true);
  6919. }
  6920. }
  6921. static void write_conn(struct mg_connection *c) {
  6922. char *buf = (char *) c->send.buf;
  6923. size_t len = c->send.len;
  6924. long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len);
  6925. MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6926. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6927. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6928. iolog(c, buf, n, false);
  6929. }
  6930. static void close_conn(struct mg_connection *c) {
  6931. if (FD(c) != MG_INVALID_SOCKET) {
  6932. #if MG_ENABLE_EPOLL
  6933. epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_DEL, FD(c), NULL);
  6934. #endif
  6935. closesocket(FD(c));
  6936. #if MG_ENABLE_FREERTOS_TCP
  6937. FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL);
  6938. #endif
  6939. }
  6940. mg_close_conn(c);
  6941. }
  6942. static void connect_conn(struct mg_connection *c) {
  6943. union usa usa;
  6944. socklen_t n = sizeof(usa);
  6945. // Use getpeername() to test whether we have connected
  6946. if (getpeername(FD(c), &usa.sa, &n) == 0) {
  6947. c->is_connecting = 0;
  6948. setlocaddr(FD(c), &c->loc);
  6949. mg_call(c, MG_EV_CONNECT, NULL);
  6950. MG_EPOLL_MOD(c, 0);
  6951. if (c->is_tls_hs) mg_tls_handshake(c);
  6952. } else {
  6953. mg_error(c, "socket error");
  6954. }
  6955. }
  6956. static void setsockopts(struct mg_connection *c) {
  6957. #if MG_ENABLE_FREERTOS_TCP || MG_ARCH == MG_ARCH_AZURERTOS || \
  6958. MG_ARCH == MG_ARCH_TIRTOS
  6959. (void) c;
  6960. #else
  6961. int on = 1;
  6962. #if !defined(SOL_TCP)
  6963. #define SOL_TCP IPPROTO_TCP
  6964. #endif
  6965. if (setsockopt(FD(c), SOL_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) != 0)
  6966. (void) 0;
  6967. if (setsockopt(FD(c), SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) !=
  6968. 0)
  6969. (void) 0;
  6970. #endif
  6971. }
  6972. void mg_connect_resolved(struct mg_connection *c) {
  6973. int type = c->is_udp ? SOCK_DGRAM : SOCK_STREAM;
  6974. int rc, af = c->rem.is_ip6 ? AF_INET6 : AF_INET; // c->rem has resolved IP
  6975. c->fd = S2PTR(socket(af, type, 0)); // Create outbound socket
  6976. c->is_resolving = 0; // Clear resolving flag
  6977. if (FD(c) == MG_INVALID_SOCKET) {
  6978. mg_error(c, "socket(): %d", MG_SOCK_ERR(-1));
  6979. } else if (c->is_udp) {
  6980. MG_EPOLL_ADD(c);
  6981. #if MG_ARCH == MG_ARCH_TIRTOS
  6982. union usa usa; // TI-RTOS NDK requires binding to receive on UDP sockets
  6983. socklen_t slen = tousa(&c->loc, &usa);
  6984. if ((rc = bind(c->fd, &usa.sa, slen)) != 0)
  6985. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6986. #endif
  6987. setlocaddr(FD(c), &c->loc);
  6988. mg_call(c, MG_EV_RESOLVE, NULL);
  6989. mg_call(c, MG_EV_CONNECT, NULL);
  6990. } else {
  6991. union usa usa;
  6992. socklen_t slen = tousa(&c->rem, &usa);
  6993. mg_set_non_blocking_mode(FD(c));
  6994. setsockopts(c);
  6995. MG_EPOLL_ADD(c);
  6996. mg_call(c, MG_EV_RESOLVE, NULL);
  6997. rc = connect(FD(c), &usa.sa, slen); // Attempt to connect
  6998. if (rc == 0) { // Success
  6999. setlocaddr(FD(c), &c->loc);
  7000. mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user
  7001. } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake
  7002. MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem));
  7003. c->is_connecting = 1;
  7004. } else {
  7005. mg_error(c, "connect: %d", MG_SOCK_ERR(rc));
  7006. }
  7007. }
  7008. }
  7009. static MG_SOCKET_TYPE raccept(MG_SOCKET_TYPE sock, union usa *usa,
  7010. socklen_t *len) {
  7011. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  7012. do {
  7013. memset(usa, 0, sizeof(*usa));
  7014. fd = accept(sock, &usa->sa, len);
  7015. } while (MG_SOCK_INTR(fd));
  7016. return fd;
  7017. }
  7018. static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) {
  7019. struct mg_connection *c = NULL;
  7020. union usa usa;
  7021. socklen_t sa_len = sizeof(usa);
  7022. MG_SOCKET_TYPE fd = raccept(FD(lsn), &usa, &sa_len);
  7023. if (fd == MG_INVALID_SOCKET) {
  7024. #if MG_ARCH == MG_ARCH_AZURERTOS || defined(__ECOS)
  7025. // AzureRTOS, in non-block socket mode can mark listening socket readable
  7026. // even it is not. See comment for 'select' func implementation in
  7027. // nx_bsd.c That's not an error, just should try later
  7028. if (errno != EAGAIN)
  7029. #endif
  7030. MG_ERROR(("%lu accept failed, errno %d", lsn->id, MG_SOCK_ERR(-1)));
  7031. #if (MG_ARCH != MG_ARCH_WIN32) && !MG_ENABLE_FREERTOS_TCP && \
  7032. (MG_ARCH != MG_ARCH_TIRTOS) && !MG_ENABLE_POLL && !MG_ENABLE_EPOLL
  7033. } else if ((long) fd >= FD_SETSIZE) {
  7034. MG_ERROR(("%ld > %ld", (long) fd, (long) FD_SETSIZE));
  7035. closesocket(fd);
  7036. #endif
  7037. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  7038. MG_ERROR(("%lu OOM", lsn->id));
  7039. closesocket(fd);
  7040. } else {
  7041. tomgaddr(&usa, &c->rem, sa_len != sizeof(usa.sin));
  7042. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  7043. c->fd = S2PTR(fd);
  7044. MG_EPOLL_ADD(c);
  7045. mg_set_non_blocking_mode(FD(c));
  7046. setsockopts(c);
  7047. c->is_accepted = 1;
  7048. c->is_hexdumping = lsn->is_hexdumping;
  7049. c->loc = lsn->loc;
  7050. c->pfn = lsn->pfn;
  7051. c->pfn_data = lsn->pfn_data;
  7052. c->fn = lsn->fn;
  7053. c->fn_data = lsn->fn_data;
  7054. MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port,
  7055. &c->rem, mg_print_ip_port, &c->loc));
  7056. mg_call(c, MG_EV_OPEN, NULL);
  7057. mg_call(c, MG_EV_ACCEPT, NULL);
  7058. }
  7059. }
  7060. static bool can_read(const struct mg_connection *c) {
  7061. return c->is_full == false;
  7062. }
  7063. static bool can_write(const struct mg_connection *c) {
  7064. return c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0);
  7065. }
  7066. static bool skip_iotest(const struct mg_connection *c) {
  7067. return (c->is_closing || c->is_resolving || FD(c) == MG_INVALID_SOCKET) ||
  7068. (can_read(c) == false && can_write(c) == false);
  7069. }
  7070. static void mg_iotest(struct mg_mgr *mgr, int ms) {
  7071. #if MG_ENABLE_FREERTOS_TCP
  7072. struct mg_connection *c;
  7073. for (c = mgr->conns; c != NULL; c = c->next) {
  7074. c->is_readable = c->is_writable = 0;
  7075. if (skip_iotest(c)) continue;
  7076. if (can_read(c))
  7077. FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_READ | eSELECT_EXCEPT);
  7078. if (can_write(c)) FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_WRITE);
  7079. if (c->is_closing) ms = 1;
  7080. }
  7081. FreeRTOS_select(mgr->ss, pdMS_TO_TICKS(ms));
  7082. for (c = mgr->conns; c != NULL; c = c->next) {
  7083. EventBits_t bits = FreeRTOS_FD_ISSET(c->fd, mgr->ss);
  7084. c->is_readable = bits & (eSELECT_READ | eSELECT_EXCEPT) ? 1U : 0;
  7085. c->is_writable = bits & eSELECT_WRITE ? 1U : 0;
  7086. if (c->fd != MG_INVALID_SOCKET)
  7087. FreeRTOS_FD_CLR(c->fd, mgr->ss,
  7088. eSELECT_READ | eSELECT_EXCEPT | eSELECT_WRITE);
  7089. }
  7090. #elif MG_ENABLE_EPOLL
  7091. size_t max = 1;
  7092. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7093. c->is_readable = c->is_writable = 0;
  7094. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) ms = 1, c->is_readable = 1;
  7095. if (can_write(c)) MG_EPOLL_MOD(c, 1);
  7096. if (c->is_closing) ms = 1;
  7097. max++;
  7098. }
  7099. struct epoll_event *evs = (struct epoll_event *) alloca(max * sizeof(evs[0]));
  7100. int n = epoll_wait(mgr->epoll_fd, evs, (int) max, ms);
  7101. for (int i = 0; i < n; i++) {
  7102. struct mg_connection *c = (struct mg_connection *) evs[i].data.ptr;
  7103. if (evs[i].events & EPOLLERR) {
  7104. mg_error(c, "socket error");
  7105. } else if (c->is_readable == 0) {
  7106. bool rd = evs[i].events & (EPOLLIN | EPOLLHUP);
  7107. bool wr = evs[i].events & EPOLLOUT;
  7108. c->is_readable = can_read(c) && rd ? 1U : 0;
  7109. c->is_writable = can_write(c) && wr ? 1U : 0;
  7110. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7111. }
  7112. }
  7113. (void) skip_iotest;
  7114. #elif MG_ENABLE_POLL
  7115. nfds_t n = 0;
  7116. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) n++;
  7117. struct pollfd *fds = (struct pollfd *) alloca(n * sizeof(fds[0]));
  7118. memset(fds, 0, n * sizeof(fds[0]));
  7119. n = 0;
  7120. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7121. c->is_readable = c->is_writable = 0;
  7122. if (skip_iotest(c)) {
  7123. // Socket not valid, ignore
  7124. } else if (c->rtls.len > 0 || mg_tls_pending(c) > 0) {
  7125. ms = 1; // Don't wait if TLS is ready
  7126. } else {
  7127. fds[n].fd = FD(c);
  7128. if (can_read(c)) fds[n].events |= POLLIN;
  7129. if (can_write(c)) fds[n].events |= POLLOUT;
  7130. if (c->is_closing) ms = 1;
  7131. n++;
  7132. }
  7133. }
  7134. // MG_INFO(("poll n=%d ms=%d", (int) n, ms));
  7135. if (poll(fds, n, ms) < 0) {
  7136. #if MG_ARCH == MG_ARCH_WIN32
  7137. if (n == 0) Sleep(ms); // On Windows, poll fails if no sockets
  7138. #endif
  7139. memset(fds, 0, n * sizeof(fds[0]));
  7140. }
  7141. n = 0;
  7142. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7143. if (skip_iotest(c)) {
  7144. // Socket not valid, ignore
  7145. } else if (c->rtls.len > 0 || mg_tls_pending(c) > 0) {
  7146. c->is_readable = 1;
  7147. } else {
  7148. if (fds[n].revents & POLLERR) {
  7149. mg_error(c, "socket error");
  7150. } else {
  7151. c->is_readable =
  7152. (unsigned) (fds[n].revents & (POLLIN | POLLHUP) ? 1 : 0);
  7153. c->is_writable = (unsigned) (fds[n].revents & POLLOUT ? 1 : 0);
  7154. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7155. }
  7156. n++;
  7157. }
  7158. }
  7159. #else
  7160. struct timeval tv = {ms / 1000, (ms % 1000) * 1000}, tv_zero = {0, 0}, *tvp;
  7161. struct mg_connection *c;
  7162. fd_set rset, wset, eset;
  7163. MG_SOCKET_TYPE maxfd = 0;
  7164. int rc;
  7165. FD_ZERO(&rset);
  7166. FD_ZERO(&wset);
  7167. FD_ZERO(&eset);
  7168. tvp = ms < 0 ? NULL : &tv;
  7169. for (c = mgr->conns; c != NULL; c = c->next) {
  7170. c->is_readable = c->is_writable = 0;
  7171. if (skip_iotest(c)) continue;
  7172. FD_SET(FD(c), &eset);
  7173. if (can_read(c)) FD_SET(FD(c), &rset);
  7174. if (can_write(c)) FD_SET(FD(c), &wset);
  7175. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) tvp = &tv_zero;
  7176. if (FD(c) > maxfd) maxfd = FD(c);
  7177. if (c->is_closing) ms = 1;
  7178. }
  7179. if ((rc = select((int) maxfd + 1, &rset, &wset, &eset, tvp)) < 0) {
  7180. #if MG_ARCH == MG_ARCH_WIN32
  7181. if (maxfd == 0) Sleep(ms); // On Windows, select fails if no sockets
  7182. #else
  7183. MG_ERROR(("select: %d %d", rc, MG_SOCK_ERR(rc)));
  7184. #endif
  7185. FD_ZERO(&rset);
  7186. FD_ZERO(&wset);
  7187. FD_ZERO(&eset);
  7188. }
  7189. for (c = mgr->conns; c != NULL; c = c->next) {
  7190. if (FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &eset)) {
  7191. mg_error(c, "socket error");
  7192. } else {
  7193. c->is_readable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &rset);
  7194. c->is_writable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &wset);
  7195. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7196. }
  7197. }
  7198. #endif
  7199. }
  7200. static bool mg_socketpair(MG_SOCKET_TYPE sp[2], union usa usa[2]) {
  7201. socklen_t n = sizeof(usa[0].sin);
  7202. bool success = false;
  7203. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7204. (void) memset(&usa[0], 0, sizeof(usa[0]));
  7205. usa[0].sin.sin_family = AF_INET;
  7206. *(uint32_t *) &usa->sin.sin_addr = mg_htonl(0x7f000001U); // 127.0.0.1
  7207. usa[1] = usa[0];
  7208. if ((sp[0] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  7209. (sp[1] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  7210. bind(sp[0], &usa[0].sa, n) == 0 && //
  7211. bind(sp[1], &usa[1].sa, n) == 0 && //
  7212. getsockname(sp[0], &usa[0].sa, &n) == 0 && //
  7213. getsockname(sp[1], &usa[1].sa, &n) == 0 && //
  7214. connect(sp[0], &usa[1].sa, n) == 0 && //
  7215. connect(sp[1], &usa[0].sa, n) == 0) { //
  7216. success = true;
  7217. }
  7218. if (!success) {
  7219. if (sp[0] != MG_INVALID_SOCKET) closesocket(sp[0]);
  7220. if (sp[1] != MG_INVALID_SOCKET) closesocket(sp[1]);
  7221. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7222. }
  7223. return success;
  7224. }
  7225. // mg_wakeup() event handler
  7226. static void wufn(struct mg_connection *c, int ev, void *ev_data) {
  7227. if (ev == MG_EV_READ) {
  7228. unsigned long *id = (unsigned long *) c->recv.buf;
  7229. // MG_INFO(("Got data"));
  7230. // mg_hexdump(c->recv.buf, c->recv.len);
  7231. if (c->recv.len >= sizeof(*id)) {
  7232. struct mg_connection *t;
  7233. for (t = c->mgr->conns; t != NULL; t = t->next) {
  7234. if (t->id == *id) {
  7235. struct mg_str data = mg_str_n((char *) c->recv.buf + sizeof(*id),
  7236. c->recv.len - sizeof(*id));
  7237. mg_call(t, MG_EV_WAKEUP, &data);
  7238. }
  7239. }
  7240. }
  7241. c->recv.len = 0; // Consume received data
  7242. } else if (ev == MG_EV_CLOSE) {
  7243. closesocket(c->mgr->pipe); // When we're closing, close the other
  7244. c->mgr->pipe = MG_INVALID_SOCKET; // side of the socketpair, too
  7245. }
  7246. (void) ev_data;
  7247. }
  7248. bool mg_wakeup_init(struct mg_mgr *mgr) {
  7249. bool ok = false;
  7250. if (mgr->pipe == MG_INVALID_SOCKET) {
  7251. union usa usa[2];
  7252. MG_SOCKET_TYPE sp[2] = {MG_INVALID_SOCKET, MG_INVALID_SOCKET};
  7253. struct mg_connection *c = NULL;
  7254. if (!mg_socketpair(sp, usa)) {
  7255. MG_ERROR(("Cannot create socket pair"));
  7256. } else if ((c = mg_wrapfd(mgr, (int) sp[1], wufn, NULL)) == NULL) {
  7257. closesocket(sp[0]);
  7258. closesocket(sp[1]);
  7259. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7260. } else {
  7261. tomgaddr(&usa[0], &c->rem, false);
  7262. MG_DEBUG(("%lu %p pipe %lu", c->id, c->fd, (unsigned long) sp[0]));
  7263. mgr->pipe = sp[0];
  7264. ok = true;
  7265. }
  7266. }
  7267. return ok;
  7268. }
  7269. bool mg_wakeup(struct mg_mgr *mgr, unsigned long conn_id, const void *buf,
  7270. size_t len) {
  7271. if (mgr->pipe != MG_INVALID_SOCKET && conn_id > 0) {
  7272. char *extended_buf = (char *) alloca(len + sizeof(conn_id));
  7273. memcpy(extended_buf, &conn_id, sizeof(conn_id));
  7274. memcpy(extended_buf + sizeof(conn_id), buf, len);
  7275. send(mgr->pipe, extended_buf, len + sizeof(conn_id), MSG_NONBLOCKING);
  7276. return true;
  7277. }
  7278. return false;
  7279. }
  7280. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  7281. struct mg_connection *c, *tmp;
  7282. uint64_t now;
  7283. mg_iotest(mgr, ms);
  7284. now = mg_millis();
  7285. mg_timer_poll(&mgr->timers, now);
  7286. for (c = mgr->conns; c != NULL; c = tmp) {
  7287. bool is_resp = c->is_resp;
  7288. tmp = c->next;
  7289. mg_call(c, MG_EV_POLL, &now);
  7290. if (is_resp && !c->is_resp) {
  7291. long n = 0;
  7292. mg_call(c, MG_EV_READ, &n);
  7293. }
  7294. MG_VERBOSE(("%lu %c%c %c%c%c%c%c %lu %lu", c->id,
  7295. c->is_readable ? 'r' : '-', c->is_writable ? 'w' : '-',
  7296. c->is_tls ? 'T' : 't', c->is_connecting ? 'C' : 'c',
  7297. c->is_tls_hs ? 'H' : 'h', c->is_resolving ? 'R' : 'r',
  7298. c->is_closing ? 'C' : 'c', mg_tls_pending(c), c->rtls.len));
  7299. if (c->is_resolving || c->is_closing) {
  7300. // Do nothing
  7301. } else if (c->is_listening && c->is_udp == 0) {
  7302. if (c->is_readable) accept_conn(mgr, c);
  7303. } else if (c->is_connecting) {
  7304. if (c->is_readable || c->is_writable) connect_conn(c);
  7305. //} else if (c->is_tls_hs) {
  7306. // if ((c->is_readable || c->is_writable)) mg_tls_handshake(c);
  7307. } else {
  7308. if (c->is_readable) read_conn(c);
  7309. if (c->is_writable) write_conn(c);
  7310. }
  7311. if (c->is_draining && c->send.len == 0) c->is_closing = 1;
  7312. if (c->is_closing) close_conn(c);
  7313. }
  7314. }
  7315. #endif
  7316. #ifdef MG_ENABLE_LINES
  7317. #line 1 "src/ssi.c"
  7318. #endif
  7319. #ifndef MG_MAX_SSI_DEPTH
  7320. #define MG_MAX_SSI_DEPTH 5
  7321. #endif
  7322. #ifndef MG_SSI_BUFSIZ
  7323. #define MG_SSI_BUFSIZ 1024
  7324. #endif
  7325. #if MG_ENABLE_SSI
  7326. static char *mg_ssi(const char *path, const char *root, int depth) {
  7327. struct mg_iobuf b = {NULL, 0, 0, MG_IO_SIZE};
  7328. FILE *fp = fopen(path, "rb");
  7329. if (fp != NULL) {
  7330. char buf[MG_SSI_BUFSIZ], arg[sizeof(buf)];
  7331. int ch, intag = 0;
  7332. size_t len = 0;
  7333. buf[0] = arg[0] = '\0';
  7334. while ((ch = fgetc(fp)) != EOF) {
  7335. if (intag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  7336. buf[len++] = (char) (ch & 0xff);
  7337. buf[len] = '\0';
  7338. if (sscanf(buf, "<!--#include file=\"%[^\"]", arg)) {
  7339. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10],
  7340. *p = (char *) path + strlen(path), *data;
  7341. while (p > path && p[-1] != MG_DIRSEP && p[-1] != '/') p--;
  7342. mg_snprintf(tmp, sizeof(tmp), "%.*s%s", (int) (p - path), path, arg);
  7343. if (depth < MG_MAX_SSI_DEPTH &&
  7344. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  7345. mg_iobuf_add(&b, b.len, data, strlen(data));
  7346. free(data);
  7347. } else {
  7348. MG_ERROR(("%s: file=%s error or too deep", path, arg));
  7349. }
  7350. } else if (sscanf(buf, "<!--#include virtual=\"%[^\"]", arg)) {
  7351. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10], *data;
  7352. mg_snprintf(tmp, sizeof(tmp), "%s%s", root, arg);
  7353. if (depth < MG_MAX_SSI_DEPTH &&
  7354. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  7355. mg_iobuf_add(&b, b.len, data, strlen(data));
  7356. free(data);
  7357. } else {
  7358. MG_ERROR(("%s: virtual=%s error or too deep", path, arg));
  7359. }
  7360. } else {
  7361. // Unknown SSI tag
  7362. MG_ERROR(("Unknown SSI tag: %.*s", (int) len, buf));
  7363. mg_iobuf_add(&b, b.len, buf, len);
  7364. }
  7365. intag = 0;
  7366. len = 0;
  7367. } else if (ch == '<') {
  7368. intag = 1;
  7369. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  7370. len = 0;
  7371. buf[len++] = (char) (ch & 0xff);
  7372. } else if (intag) {
  7373. if (len == 5 && strncmp(buf, "<!--#", 5) != 0) {
  7374. intag = 0;
  7375. } else if (len >= sizeof(buf) - 2) {
  7376. MG_ERROR(("%s: SSI tag is too large", path));
  7377. len = 0;
  7378. }
  7379. buf[len++] = (char) (ch & 0xff);
  7380. } else {
  7381. buf[len++] = (char) (ch & 0xff);
  7382. if (len >= sizeof(buf)) {
  7383. mg_iobuf_add(&b, b.len, buf, len);
  7384. len = 0;
  7385. }
  7386. }
  7387. }
  7388. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  7389. if (b.len > 0) mg_iobuf_add(&b, b.len, "", 1); // nul-terminate
  7390. fclose(fp);
  7391. }
  7392. (void) depth;
  7393. (void) root;
  7394. return (char *) b.buf;
  7395. }
  7396. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  7397. const char *fullpath) {
  7398. const char *headers = "Content-Type: text/html; charset=utf-8\r\n";
  7399. char *data = mg_ssi(fullpath, root, 0);
  7400. mg_http_reply(c, 200, headers, "%s", data == NULL ? "" : data);
  7401. free(data);
  7402. }
  7403. #else
  7404. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  7405. const char *fullpath) {
  7406. mg_http_reply(c, 501, NULL, "SSI not enabled");
  7407. (void) root, (void) fullpath;
  7408. }
  7409. #endif
  7410. #ifdef MG_ENABLE_LINES
  7411. #line 1 "src/str.c"
  7412. #endif
  7413. struct mg_str mg_str_s(const char *s) {
  7414. struct mg_str str = {(char *) s, s == NULL ? 0 : strlen(s)};
  7415. return str;
  7416. }
  7417. struct mg_str mg_str_n(const char *s, size_t n) {
  7418. struct mg_str str = {(char *) s, n};
  7419. return str;
  7420. }
  7421. static int mg_tolc(char c) {
  7422. return (c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c;
  7423. }
  7424. int mg_casecmp(const char *s1, const char *s2) {
  7425. int diff = 0;
  7426. do {
  7427. int c = mg_tolc(*s1++), d = mg_tolc(*s2++);
  7428. diff = c - d;
  7429. } while (diff == 0 && s1[-1] != '\0');
  7430. return diff;
  7431. }
  7432. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  7433. size_t i = 0;
  7434. while (i < str1.len && i < str2.len) {
  7435. int c1 = str1.buf[i];
  7436. int c2 = str2.buf[i];
  7437. if (c1 < c2) return -1;
  7438. if (c1 > c2) return 1;
  7439. i++;
  7440. }
  7441. if (i < str1.len) return 1;
  7442. if (i < str2.len) return -1;
  7443. return 0;
  7444. }
  7445. int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2) {
  7446. size_t i = 0;
  7447. while (i < str1.len && i < str2.len) {
  7448. int c1 = mg_tolc(str1.buf[i]);
  7449. int c2 = mg_tolc(str2.buf[i]);
  7450. if (c1 < c2) return -1;
  7451. if (c1 > c2) return 1;
  7452. i++;
  7453. }
  7454. if (i < str1.len) return 1;
  7455. if (i < str2.len) return -1;
  7456. return 0;
  7457. }
  7458. bool mg_match(struct mg_str s, struct mg_str p, struct mg_str *caps) {
  7459. size_t i = 0, j = 0, ni = 0, nj = 0;
  7460. if (caps) caps->buf = NULL, caps->len = 0;
  7461. while (i < p.len || j < s.len) {
  7462. if (i < p.len && j < s.len && (p.buf[i] == '?' || s.buf[j] == p.buf[i])) {
  7463. if (caps == NULL) {
  7464. } else if (p.buf[i] == '?') {
  7465. caps->buf = &s.buf[j], caps->len = 1; // Finalize `?` cap
  7466. caps++, caps->buf = NULL, caps->len = 0; // Init next cap
  7467. } else if (caps->buf != NULL && caps->len == 0) {
  7468. caps->len = (size_t) (&s.buf[j] - caps->buf); // Finalize current cap
  7469. caps++, caps->len = 0, caps->buf = NULL; // Init next cap
  7470. }
  7471. i++, j++;
  7472. } else if (i < p.len && (p.buf[i] == '*' || p.buf[i] == '#')) {
  7473. if (caps && !caps->buf) caps->len = 0, caps->buf = &s.buf[j]; // Init cap
  7474. ni = i++, nj = j + 1;
  7475. } else if (nj > 0 && nj <= s.len && (p.buf[ni] == '#' || s.buf[j] != '/')) {
  7476. i = ni, j = nj;
  7477. if (caps && caps->buf == NULL && caps->len == 0) {
  7478. caps--, caps->len = 0; // Restart previous cap
  7479. }
  7480. } else {
  7481. return false;
  7482. }
  7483. }
  7484. if (caps && caps->buf && caps->len == 0) {
  7485. caps->len = (size_t) (&s.buf[j] - caps->buf);
  7486. }
  7487. return true;
  7488. }
  7489. bool mg_span(struct mg_str s, struct mg_str *a, struct mg_str *b, char sep) {
  7490. if (s.len == 0 || s.buf == NULL) {
  7491. return false; // Empty string, nothing to span - fail
  7492. } else {
  7493. size_t len = 0;
  7494. while (len < s.len && s.buf[len] != sep) len++; // Find separator
  7495. if (a) *a = mg_str_n(s.buf, len); // Init a
  7496. if (b) *b = mg_str_n(s.buf + len, s.len - len); // Init b
  7497. if (b && len < s.len) b->buf++, b->len--; // Skip separator
  7498. return true;
  7499. }
  7500. }
  7501. bool mg_str_to_num(struct mg_str str, int base, void *val, size_t val_len) {
  7502. size_t i = 0, ndigits = 0;
  7503. uint64_t max = val_len == sizeof(uint8_t) ? 0xFF
  7504. : val_len == sizeof(uint16_t) ? 0xFFFF
  7505. : val_len == sizeof(uint32_t) ? 0xFFFFFFFF
  7506. : (uint64_t) ~0;
  7507. uint64_t result = 0;
  7508. if (max == (uint64_t) ~0 && val_len != sizeof(uint64_t)) return false;
  7509. if (base == 0 && str.len >= 2) {
  7510. if (str.buf[i] == '0') {
  7511. i++;
  7512. base = str.buf[i] == 'b' ? 2 : str.buf[i] == 'x' ? 16 : 10;
  7513. if (base != 10) ++i;
  7514. } else {
  7515. base = 10;
  7516. }
  7517. }
  7518. switch (base) {
  7519. case 2:
  7520. while (i < str.len && (str.buf[i] == '0' || str.buf[i] == '1')) {
  7521. uint64_t digit = (uint64_t) (str.buf[i] - '0');
  7522. if (result > max/2) return false; // Overflow
  7523. result *= 2;
  7524. if (result > max - digit) return false; // Overflow
  7525. result += digit;
  7526. i++, ndigits++;
  7527. }
  7528. break;
  7529. case 10:
  7530. while (i < str.len && str.buf[i] >= '0' && str.buf[i] <= '9') {
  7531. uint64_t digit = (uint64_t) (str.buf[i] - '0');
  7532. if (result > max/10) return false; // Overflow
  7533. result *= 10;
  7534. if (result > max - digit) return false; // Overflow
  7535. result += digit;
  7536. i++, ndigits++;
  7537. }
  7538. break;
  7539. case 16:
  7540. while (i < str.len) {
  7541. char c = str.buf[i];
  7542. uint64_t digit = (c >= '0' && c <= '9') ? (uint64_t) (c - '0')
  7543. : (c >= 'A' && c <= 'F') ? (uint64_t) (c - '7')
  7544. : (c >= 'a' && c <= 'f') ? (uint64_t) (c - 'W')
  7545. : (uint64_t) ~0;
  7546. if (digit == (uint64_t) ~0) break;
  7547. if (result > max/16) return false; // Overflow
  7548. result *= 16;
  7549. if (result > max - digit) return false; // Overflow
  7550. result += digit;
  7551. i++, ndigits++;
  7552. }
  7553. break;
  7554. default:
  7555. return false;
  7556. }
  7557. if (ndigits == 0) return false;
  7558. if (i != str.len) return false;
  7559. if (val_len == 1) {
  7560. *((uint8_t *) val) = (uint8_t) result;
  7561. } else if (val_len == 2) {
  7562. *((uint16_t *) val) = (uint16_t) result;
  7563. } else if (val_len == 4) {
  7564. *((uint32_t *) val) = (uint32_t) result;
  7565. } else {
  7566. *((uint64_t *) val) = (uint64_t) result;
  7567. }
  7568. return true;
  7569. }
  7570. #ifdef MG_ENABLE_LINES
  7571. #line 1 "src/timer.c"
  7572. #endif
  7573. #define MG_TIMER_CALLED 4
  7574. void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
  7575. unsigned flags, void (*fn)(void *), void *arg) {
  7576. t->id = 0, t->period_ms = ms, t->expire = 0;
  7577. t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
  7578. *head = t;
  7579. }
  7580. void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
  7581. while (*head && *head != t) head = &(*head)->next;
  7582. if (*head) *head = t->next;
  7583. }
  7584. // t: expiration time, prd: period, now: current time. Return true if expired
  7585. bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
  7586. if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
  7587. if (*t == 0) *t = now + prd; // Firt poll? Set expiration
  7588. if (*t > now) return false; // Not expired yet, return
  7589. *t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
  7590. return true; // Expired, return true
  7591. }
  7592. void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
  7593. struct mg_timer *t, *tmp;
  7594. for (t = *head; t != NULL; t = tmp) {
  7595. bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
  7596. !(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
  7597. bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
  7598. tmp = t->next;
  7599. if (!once && !expired) continue;
  7600. if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
  7601. t->fn(t->arg);
  7602. }
  7603. t->flags |= MG_TIMER_CALLED;
  7604. }
  7605. }
  7606. #ifdef MG_ENABLE_LINES
  7607. #line 1 "src/tls_aes128.c"
  7608. #endif
  7609. /******************************************************************************
  7610. *
  7611. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7612. *
  7613. * This is a simple and straightforward implementation of the AES Rijndael
  7614. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7615. * of this work was correctness & accuracy. It is written in 'C' without any
  7616. * particular focus upon optimization or speed. It should be endian (memory
  7617. * byte order) neutral since the few places that care are handled explicitly.
  7618. *
  7619. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7620. *
  7621. * It is intended for general purpose use, but was written in support of GRC's
  7622. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7623. *
  7624. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7625. *
  7626. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7627. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7628. *
  7629. *******************************************************************************/
  7630. /******************************************************************************/
  7631. #define AES_DECRYPTION 1 // whether AES decryption is supported
  7632. /******************************************************************************/
  7633. #define MG_ENCRYPT 1 // specify whether we're encrypting
  7634. #define MG_DECRYPT 0 // or decrypting
  7635. #if MG_TLS == MG_TLS_BUILTIN
  7636. /******************************************************************************
  7637. * AES_INIT_KEYGEN_TABLES : MUST be called once before any AES use
  7638. ******************************************************************************/
  7639. static void aes_init_keygen_tables(void);
  7640. /******************************************************************************
  7641. * AES_SETKEY : called to expand the key for encryption or decryption
  7642. ******************************************************************************/
  7643. static int aes_setkey(aes_context *ctx, // pointer to context
  7644. int mode, // 1 or 0 for Encrypt/Decrypt
  7645. const uchar *key, // AES input key
  7646. uint keysize); // size in bytes (must be 16, 24, 32 for
  7647. // 128, 192 or 256-bit keys respectively)
  7648. // returns 0 for success
  7649. /******************************************************************************
  7650. * AES_CIPHER : called to encrypt or decrypt ONE 128-bit block of data
  7651. ******************************************************************************/
  7652. static int aes_cipher(aes_context *ctx, // pointer to context
  7653. const uchar input[16], // 128-bit block to en/decipher
  7654. uchar output[16]); // 128-bit output result block
  7655. // returns 0 for success
  7656. /******************************************************************************
  7657. * GCM_CONTEXT : GCM context / holds keytables, instance data, and AES ctx
  7658. ******************************************************************************/
  7659. typedef struct {
  7660. int mode; // cipher direction: encrypt/decrypt
  7661. uint64_t len; // cipher data length processed so far
  7662. uint64_t add_len; // total add data length
  7663. uint64_t HL[16]; // precalculated lo-half HTable
  7664. uint64_t HH[16]; // precalculated hi-half HTable
  7665. uchar base_ectr[16]; // first counter-mode cipher output for tag
  7666. uchar y[16]; // the current cipher-input IV|Counter value
  7667. uchar buf[16]; // buf working value
  7668. aes_context aes_ctx; // cipher context used
  7669. } gcm_context;
  7670. /******************************************************************************
  7671. * GCM_SETKEY : sets the GCM (and AES) keying material for use
  7672. ******************************************************************************/
  7673. static int gcm_setkey(
  7674. gcm_context *ctx, // caller-provided context ptr
  7675. const uchar *key, // pointer to cipher key
  7676. const uint keysize // size in bytes (must be 16, 24, 32 for
  7677. // 128, 192 or 256-bit keys respectively)
  7678. ); // returns 0 for success
  7679. /******************************************************************************
  7680. *
  7681. * GCM_CRYPT_AND_TAG
  7682. *
  7683. * This either encrypts or decrypts the user-provided data and, either
  7684. * way, generates an authentication tag of the requested length. It must be
  7685. * called with a GCM context whose key has already been set with GCM_SETKEY.
  7686. *
  7687. * The user would typically call this explicitly to ENCRYPT a buffer of data
  7688. * and optional associated data, and produce its an authentication tag.
  7689. *
  7690. * To reverse the process the user would typically call the companion
  7691. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  7692. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  7693. * to perform its decryption and tag generation, which it then compares.
  7694. *
  7695. ******************************************************************************/
  7696. static int gcm_crypt_and_tag(
  7697. gcm_context *ctx, // gcm context with key already setup
  7698. int mode, // cipher direction: MG_ENCRYPT (1) or MG_DECRYPT (0)
  7699. const uchar *iv, // pointer to the 12-byte initialization vector
  7700. size_t iv_len, // byte length if the IV. should always be 12
  7701. const uchar *add, // pointer to the non-ciphered additional data
  7702. size_t add_len, // byte length of the additional AEAD data
  7703. const uchar *input, // pointer to the cipher data source
  7704. uchar *output, // pointer to the cipher data destination
  7705. size_t length, // byte length of the cipher data
  7706. uchar *tag, // pointer to the tag to be generated
  7707. size_t tag_len); // byte length of the tag to be generated
  7708. /******************************************************************************
  7709. *
  7710. * GCM_START
  7711. *
  7712. * Given a user-provided GCM context, this initializes it, sets the encryption
  7713. * mode, and preprocesses the initialization vector and additional AEAD data.
  7714. *
  7715. ******************************************************************************/
  7716. static int gcm_start(
  7717. gcm_context *ctx, // pointer to user-provided GCM context
  7718. int mode, // MG_ENCRYPT (1) or MG_DECRYPT (0)
  7719. const uchar *iv, // pointer to initialization vector
  7720. size_t iv_len, // IV length in bytes (should == 12)
  7721. const uchar *add, // pointer to additional AEAD data (NULL if none)
  7722. size_t add_len); // length of additional AEAD data (bytes)
  7723. /******************************************************************************
  7724. *
  7725. * GCM_UPDATE
  7726. *
  7727. * This is called once or more to process bulk plaintext or ciphertext data.
  7728. * We give this some number of bytes of input and it returns the same number
  7729. * of output bytes. If called multiple times (which is fine) all but the final
  7730. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  7731. * have a partial block length of < 128 bits.)
  7732. *
  7733. ******************************************************************************/
  7734. static int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  7735. size_t length, // length, in bytes, of data to process
  7736. const uchar *input, // pointer to source data
  7737. uchar *output); // pointer to destination data
  7738. /******************************************************************************
  7739. *
  7740. * GCM_FINISH
  7741. *
  7742. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  7743. * It performs the final GHASH to produce the resulting authentication TAG.
  7744. *
  7745. ******************************************************************************/
  7746. static int gcm_finish(
  7747. gcm_context *ctx, // pointer to user-provided GCM context
  7748. uchar *tag, // ptr to tag buffer - NULL if tag_len = 0
  7749. size_t tag_len); // length, in bytes, of the tag-receiving buf
  7750. /******************************************************************************
  7751. *
  7752. * GCM_ZERO_CTX
  7753. *
  7754. * The GCM context contains both the GCM context and the AES context.
  7755. * This includes keying and key-related material which is security-
  7756. * sensitive, so it MUST be zeroed after use. This function does that.
  7757. *
  7758. ******************************************************************************/
  7759. static void gcm_zero_ctx(gcm_context *ctx);
  7760. /******************************************************************************
  7761. *
  7762. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7763. *
  7764. * This is a simple and straightforward implementation of the AES Rijndael
  7765. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7766. * of this work was correctness & accuracy. It is written in 'C' without any
  7767. * particular focus upon optimization or speed. It should be endian (memory
  7768. * byte order) neutral since the few places that care are handled explicitly.
  7769. *
  7770. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7771. *
  7772. * It is intended for general purpose use, but was written in support of GRC's
  7773. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7774. *
  7775. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7776. *
  7777. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7778. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7779. *
  7780. *******************************************************************************/
  7781. static int aes_tables_inited = 0; // run-once flag for performing key
  7782. // expasion table generation (see below)
  7783. /*
  7784. * The following static local tables must be filled-in before the first use of
  7785. * the GCM or AES ciphers. They are used for the AES key expansion/scheduling
  7786. * and once built are read-only and thread safe. The "gcm_initialize" function
  7787. * must be called once during system initialization to populate these arrays
  7788. * for subsequent use by the AES key scheduler. If they have not been built
  7789. * before attempted use, an error will be returned to the caller.
  7790. *
  7791. * NOTE: GCM Encryption/Decryption does NOT REQUIRE AES decryption. Since
  7792. * GCM uses AES in counter-mode, where the AES cipher output is XORed with
  7793. * the GCM input, we ONLY NEED AES encryption. Thus, to save space AES
  7794. * decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.
  7795. */
  7796. // We always need our forward tables
  7797. static uchar FSb[256]; // Forward substitution box (FSb)
  7798. static uint32_t FT0[256]; // Forward key schedule assembly tables
  7799. static uint32_t FT1[256];
  7800. static uint32_t FT2[256];
  7801. static uint32_t FT3[256];
  7802. #if AES_DECRYPTION // We ONLY need reverse for decryption
  7803. static uchar RSb[256]; // Reverse substitution box (RSb)
  7804. static uint32_t RT0[256]; // Reverse key schedule assembly tables
  7805. static uint32_t RT1[256];
  7806. static uint32_t RT2[256];
  7807. static uint32_t RT3[256];
  7808. #endif /* AES_DECRYPTION */
  7809. static uint32_t RCON[10]; // AES round constants
  7810. /*
  7811. * Platform Endianness Neutralizing Load and Store Macro definitions
  7812. * AES wants platform-neutral Little Endian (LE) byte ordering
  7813. */
  7814. #define GET_UINT32_LE(n, b, i) \
  7815. { \
  7816. (n) = ((uint32_t) (b)[(i)]) | ((uint32_t) (b)[(i) + 1] << 8) | \
  7817. ((uint32_t) (b)[(i) + 2] << 16) | ((uint32_t) (b)[(i) + 3] << 24); \
  7818. }
  7819. #define PUT_UINT32_LE(n, b, i) \
  7820. { \
  7821. (b)[(i)] = (uchar) ((n)); \
  7822. (b)[(i) + 1] = (uchar) ((n) >> 8); \
  7823. (b)[(i) + 2] = (uchar) ((n) >> 16); \
  7824. (b)[(i) + 3] = (uchar) ((n) >> 24); \
  7825. }
  7826. /*
  7827. * AES forward and reverse encryption round processing macros
  7828. */
  7829. #define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7830. { \
  7831. X0 = *RK++ ^ FT0[(Y0) & 0xFF] ^ FT1[(Y1 >> 8) & 0xFF] ^ \
  7832. FT2[(Y2 >> 16) & 0xFF] ^ FT3[(Y3 >> 24) & 0xFF]; \
  7833. \
  7834. X1 = *RK++ ^ FT0[(Y1) & 0xFF] ^ FT1[(Y2 >> 8) & 0xFF] ^ \
  7835. FT2[(Y3 >> 16) & 0xFF] ^ FT3[(Y0 >> 24) & 0xFF]; \
  7836. \
  7837. X2 = *RK++ ^ FT0[(Y2) & 0xFF] ^ FT1[(Y3 >> 8) & 0xFF] ^ \
  7838. FT2[(Y0 >> 16) & 0xFF] ^ FT3[(Y1 >> 24) & 0xFF]; \
  7839. \
  7840. X3 = *RK++ ^ FT0[(Y3) & 0xFF] ^ FT1[(Y0 >> 8) & 0xFF] ^ \
  7841. FT2[(Y1 >> 16) & 0xFF] ^ FT3[(Y2 >> 24) & 0xFF]; \
  7842. }
  7843. #define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7844. { \
  7845. X0 = *RK++ ^ RT0[(Y0) & 0xFF] ^ RT1[(Y3 >> 8) & 0xFF] ^ \
  7846. RT2[(Y2 >> 16) & 0xFF] ^ RT3[(Y1 >> 24) & 0xFF]; \
  7847. \
  7848. X1 = *RK++ ^ RT0[(Y1) & 0xFF] ^ RT1[(Y0 >> 8) & 0xFF] ^ \
  7849. RT2[(Y3 >> 16) & 0xFF] ^ RT3[(Y2 >> 24) & 0xFF]; \
  7850. \
  7851. X2 = *RK++ ^ RT0[(Y2) & 0xFF] ^ RT1[(Y1 >> 8) & 0xFF] ^ \
  7852. RT2[(Y0 >> 16) & 0xFF] ^ RT3[(Y3 >> 24) & 0xFF]; \
  7853. \
  7854. X3 = *RK++ ^ RT0[(Y3) & 0xFF] ^ RT1[(Y2 >> 8) & 0xFF] ^ \
  7855. RT2[(Y1 >> 16) & 0xFF] ^ RT3[(Y0 >> 24) & 0xFF]; \
  7856. }
  7857. /*
  7858. * These macros improve the readability of the key
  7859. * generation initialization code by collapsing
  7860. * repetitive common operations into logical pieces.
  7861. */
  7862. #define ROTL8(x) ((x << 8) & 0xFFFFFFFF) | (x >> 24)
  7863. #define XTIME(x) ((x << 1) ^ ((x & 0x80) ? 0x1B : 0x00))
  7864. #define MUL(x, y) ((x && y) ? pow[(log[x] + log[y]) % 255] : 0)
  7865. #define MIX(x, y) \
  7866. { \
  7867. y = ((y << 1) | (y >> 7)) & 0xFF; \
  7868. x ^= y; \
  7869. }
  7870. #define CPY128 \
  7871. { \
  7872. *RK++ = *SK++; \
  7873. *RK++ = *SK++; \
  7874. *RK++ = *SK++; \
  7875. *RK++ = *SK++; \
  7876. }
  7877. /******************************************************************************
  7878. *
  7879. * AES_INIT_KEYGEN_TABLES
  7880. *
  7881. * Fills the AES key expansion tables allocated above with their static
  7882. * data. This is not "per key" data, but static system-wide read-only
  7883. * table data. THIS FUNCTION IS NOT THREAD SAFE. It must be called once
  7884. * at system initialization to setup the tables for all subsequent use.
  7885. *
  7886. ******************************************************************************/
  7887. void aes_init_keygen_tables(void) {
  7888. int i, x, y, z; // general purpose iteration and computation locals
  7889. int pow[256];
  7890. int log[256];
  7891. if (aes_tables_inited) return;
  7892. // fill the 'pow' and 'log' tables over GF(2^8)
  7893. for (i = 0, x = 1; i < 256; i++) {
  7894. pow[i] = x;
  7895. log[x] = i;
  7896. x = (x ^ XTIME(x)) & 0xFF;
  7897. }
  7898. // compute the round constants
  7899. for (i = 0, x = 1; i < 10; i++) {
  7900. RCON[i] = (uint32_t) x;
  7901. x = XTIME(x) & 0xFF;
  7902. }
  7903. // fill the forward and reverse substitution boxes
  7904. FSb[0x00] = 0x63;
  7905. #if AES_DECRYPTION // whether AES decryption is supported
  7906. RSb[0x63] = 0x00;
  7907. #endif /* AES_DECRYPTION */
  7908. for (i = 1; i < 256; i++) {
  7909. x = y = pow[255 - log[i]];
  7910. MIX(x, y);
  7911. MIX(x, y);
  7912. MIX(x, y);
  7913. MIX(x, y);
  7914. FSb[i] = (uchar) (x ^= 0x63);
  7915. #if AES_DECRYPTION // whether AES decryption is supported
  7916. RSb[x] = (uchar) i;
  7917. #endif /* AES_DECRYPTION */
  7918. }
  7919. // generate the forward and reverse key expansion tables
  7920. for (i = 0; i < 256; i++) {
  7921. x = FSb[i];
  7922. y = XTIME(x) & 0xFF;
  7923. z = (y ^ x) & 0xFF;
  7924. FT0[i] = ((uint32_t) y) ^ ((uint32_t) x << 8) ^ ((uint32_t) x << 16) ^
  7925. ((uint32_t) z << 24);
  7926. FT1[i] = ROTL8(FT0[i]);
  7927. FT2[i] = ROTL8(FT1[i]);
  7928. FT3[i] = ROTL8(FT2[i]);
  7929. #if AES_DECRYPTION // whether AES decryption is supported
  7930. x = RSb[i];
  7931. RT0[i] = ((uint32_t) MUL(0x0E, x)) ^ ((uint32_t) MUL(0x09, x) << 8) ^
  7932. ((uint32_t) MUL(0x0D, x) << 16) ^ ((uint32_t) MUL(0x0B, x) << 24);
  7933. RT1[i] = ROTL8(RT0[i]);
  7934. RT2[i] = ROTL8(RT1[i]);
  7935. RT3[i] = ROTL8(RT2[i]);
  7936. #endif /* AES_DECRYPTION */
  7937. }
  7938. aes_tables_inited = 1; // flag that the tables have been generated
  7939. } // to permit subsequent use of the AES cipher
  7940. /******************************************************************************
  7941. *
  7942. * AES_SET_ENCRYPTION_KEY
  7943. *
  7944. * This is called by 'aes_setkey' when we're establishing a key for
  7945. * subsequent encryption. We give it a pointer to the encryption
  7946. * context, a pointer to the key, and the key's length in bytes.
  7947. * Valid lengths are: 16, 24 or 32 bytes (128, 192, 256 bits).
  7948. *
  7949. ******************************************************************************/
  7950. static int aes_set_encryption_key(aes_context *ctx, const uchar *key,
  7951. uint keysize) {
  7952. uint i; // general purpose iteration local
  7953. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7954. for (i = 0; i < (keysize >> 2); i++) {
  7955. GET_UINT32_LE(RK[i], key, i << 2);
  7956. }
  7957. switch (ctx->rounds) {
  7958. case 10:
  7959. for (i = 0; i < 10; i++, RK += 4) {
  7960. RK[4] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[3] >> 8) & 0xFF]) ^
  7961. ((uint32_t) FSb[(RK[3] >> 16) & 0xFF] << 8) ^
  7962. ((uint32_t) FSb[(RK[3] >> 24) & 0xFF] << 16) ^
  7963. ((uint32_t) FSb[(RK[3]) & 0xFF] << 24);
  7964. RK[5] = RK[1] ^ RK[4];
  7965. RK[6] = RK[2] ^ RK[5];
  7966. RK[7] = RK[3] ^ RK[6];
  7967. }
  7968. break;
  7969. case 12:
  7970. for (i = 0; i < 8; i++, RK += 6) {
  7971. RK[6] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[5] >> 8) & 0xFF]) ^
  7972. ((uint32_t) FSb[(RK[5] >> 16) & 0xFF] << 8) ^
  7973. ((uint32_t) FSb[(RK[5] >> 24) & 0xFF] << 16) ^
  7974. ((uint32_t) FSb[(RK[5]) & 0xFF] << 24);
  7975. RK[7] = RK[1] ^ RK[6];
  7976. RK[8] = RK[2] ^ RK[7];
  7977. RK[9] = RK[3] ^ RK[8];
  7978. RK[10] = RK[4] ^ RK[9];
  7979. RK[11] = RK[5] ^ RK[10];
  7980. }
  7981. break;
  7982. case 14:
  7983. for (i = 0; i < 7; i++, RK += 8) {
  7984. RK[8] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[7] >> 8) & 0xFF]) ^
  7985. ((uint32_t) FSb[(RK[7] >> 16) & 0xFF] << 8) ^
  7986. ((uint32_t) FSb[(RK[7] >> 24) & 0xFF] << 16) ^
  7987. ((uint32_t) FSb[(RK[7]) & 0xFF] << 24);
  7988. RK[9] = RK[1] ^ RK[8];
  7989. RK[10] = RK[2] ^ RK[9];
  7990. RK[11] = RK[3] ^ RK[10];
  7991. RK[12] = RK[4] ^ ((uint32_t) FSb[(RK[11]) & 0xFF]) ^
  7992. ((uint32_t) FSb[(RK[11] >> 8) & 0xFF] << 8) ^
  7993. ((uint32_t) FSb[(RK[11] >> 16) & 0xFF] << 16) ^
  7994. ((uint32_t) FSb[(RK[11] >> 24) & 0xFF] << 24);
  7995. RK[13] = RK[5] ^ RK[12];
  7996. RK[14] = RK[6] ^ RK[13];
  7997. RK[15] = RK[7] ^ RK[14];
  7998. }
  7999. break;
  8000. default:
  8001. return -1;
  8002. }
  8003. return (0);
  8004. }
  8005. #if AES_DECRYPTION // whether AES decryption is supported
  8006. /******************************************************************************
  8007. *
  8008. * AES_SET_DECRYPTION_KEY
  8009. *
  8010. * This is called by 'aes_setkey' when we're establishing a
  8011. * key for subsequent decryption. We give it a pointer to
  8012. * the encryption context, a pointer to the key, and the key's
  8013. * length in bits. Valid lengths are: 128, 192, or 256 bits.
  8014. *
  8015. ******************************************************************************/
  8016. static int aes_set_decryption_key(aes_context *ctx, const uchar *key,
  8017. uint keysize) {
  8018. int i, j;
  8019. aes_context cty; // a calling aes context for set_encryption_key
  8020. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  8021. uint32_t *SK;
  8022. int ret;
  8023. cty.rounds = ctx->rounds; // initialize our local aes context
  8024. cty.rk = cty.buf; // round count and key buf pointer
  8025. if ((ret = aes_set_encryption_key(&cty, key, keysize)) != 0) return (ret);
  8026. SK = cty.rk + cty.rounds * 4;
  8027. CPY128 // copy a 128-bit block from *SK to *RK
  8028. for (i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8) {
  8029. for (j = 0; j < 4; j++, SK++) {
  8030. *RK++ = RT0[FSb[(*SK) & 0xFF]] ^ RT1[FSb[(*SK >> 8) & 0xFF]] ^
  8031. RT2[FSb[(*SK >> 16) & 0xFF]] ^ RT3[FSb[(*SK >> 24) & 0xFF]];
  8032. }
  8033. }
  8034. CPY128 // copy a 128-bit block from *SK to *RK
  8035. memset(&cty, 0, sizeof(aes_context)); // clear local aes context
  8036. return (0);
  8037. }
  8038. #endif /* AES_DECRYPTION */
  8039. /******************************************************************************
  8040. *
  8041. * AES_SETKEY
  8042. *
  8043. * Invoked to establish the key schedule for subsequent encryption/decryption
  8044. *
  8045. ******************************************************************************/
  8046. static int aes_setkey(aes_context *ctx, // AES context provided by our caller
  8047. int mode, // ENCRYPT or DECRYPT flag
  8048. const uchar *key, // pointer to the key
  8049. uint keysize) // key length in bytes
  8050. {
  8051. // since table initialization is not thread safe, we could either add
  8052. // system-specific mutexes and init the AES key generation tables on
  8053. // demand, or ask the developer to simply call "gcm_initialize" once during
  8054. // application startup before threading begins. That's what we choose.
  8055. if (!aes_tables_inited) return (-1); // fail the call when not inited.
  8056. ctx->mode = mode; // capture the key type we're creating
  8057. ctx->rk = ctx->buf; // initialize our round key pointer
  8058. switch (keysize) // set the rounds count based upon the keysize
  8059. {
  8060. case 16:
  8061. ctx->rounds = 10;
  8062. break; // 16-byte, 128-bit key
  8063. case 24:
  8064. ctx->rounds = 12;
  8065. break; // 24-byte, 192-bit key
  8066. case 32:
  8067. ctx->rounds = 14;
  8068. break; // 32-byte, 256-bit key
  8069. default:
  8070. return (-1);
  8071. }
  8072. #if AES_DECRYPTION
  8073. if (mode == MG_DECRYPT) // expand our key for encryption or decryption
  8074. return (aes_set_decryption_key(ctx, key, keysize));
  8075. else /* MG_ENCRYPT */
  8076. #endif /* AES_DECRYPTION */
  8077. return (aes_set_encryption_key(ctx, key, keysize));
  8078. }
  8079. /******************************************************************************
  8080. *
  8081. * AES_CIPHER
  8082. *
  8083. * Perform AES encryption and decryption.
  8084. * The AES context will have been setup with the encryption mode
  8085. * and all keying information appropriate for the task.
  8086. *
  8087. ******************************************************************************/
  8088. static int aes_cipher(aes_context *ctx, const uchar input[16],
  8089. uchar output[16]) {
  8090. int i;
  8091. uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; // general purpose locals
  8092. RK = ctx->rk;
  8093. GET_UINT32_LE(X0, input, 0);
  8094. X0 ^= *RK++; // load our 128-bit
  8095. GET_UINT32_LE(X1, input, 4);
  8096. X1 ^= *RK++; // input buffer in a storage
  8097. GET_UINT32_LE(X2, input, 8);
  8098. X2 ^= *RK++; // memory endian-neutral way
  8099. GET_UINT32_LE(X3, input, 12);
  8100. X3 ^= *RK++;
  8101. #if AES_DECRYPTION // whether AES decryption is supported
  8102. if (ctx->mode == MG_DECRYPT) {
  8103. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  8104. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8105. AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  8106. }
  8107. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8108. X0 = *RK++ ^ ((uint32_t) RSb[(Y0) & 0xFF]) ^
  8109. ((uint32_t) RSb[(Y3 >> 8) & 0xFF] << 8) ^
  8110. ((uint32_t) RSb[(Y2 >> 16) & 0xFF] << 16) ^
  8111. ((uint32_t) RSb[(Y1 >> 24) & 0xFF] << 24);
  8112. X1 = *RK++ ^ ((uint32_t) RSb[(Y1) & 0xFF]) ^
  8113. ((uint32_t) RSb[(Y0 >> 8) & 0xFF] << 8) ^
  8114. ((uint32_t) RSb[(Y3 >> 16) & 0xFF] << 16) ^
  8115. ((uint32_t) RSb[(Y2 >> 24) & 0xFF] << 24);
  8116. X2 = *RK++ ^ ((uint32_t) RSb[(Y2) & 0xFF]) ^
  8117. ((uint32_t) RSb[(Y1 >> 8) & 0xFF] << 8) ^
  8118. ((uint32_t) RSb[(Y0 >> 16) & 0xFF] << 16) ^
  8119. ((uint32_t) RSb[(Y3 >> 24) & 0xFF] << 24);
  8120. X3 = *RK++ ^ ((uint32_t) RSb[(Y3) & 0xFF]) ^
  8121. ((uint32_t) RSb[(Y2 >> 8) & 0xFF] << 8) ^
  8122. ((uint32_t) RSb[(Y1 >> 16) & 0xFF] << 16) ^
  8123. ((uint32_t) RSb[(Y0 >> 24) & 0xFF] << 24);
  8124. } else /* MG_ENCRYPT */
  8125. {
  8126. #endif /* AES_DECRYPTION */
  8127. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  8128. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8129. AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  8130. }
  8131. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8132. X0 = *RK++ ^ ((uint32_t) FSb[(Y0) & 0xFF]) ^
  8133. ((uint32_t) FSb[(Y1 >> 8) & 0xFF] << 8) ^
  8134. ((uint32_t) FSb[(Y2 >> 16) & 0xFF] << 16) ^
  8135. ((uint32_t) FSb[(Y3 >> 24) & 0xFF] << 24);
  8136. X1 = *RK++ ^ ((uint32_t) FSb[(Y1) & 0xFF]) ^
  8137. ((uint32_t) FSb[(Y2 >> 8) & 0xFF] << 8) ^
  8138. ((uint32_t) FSb[(Y3 >> 16) & 0xFF] << 16) ^
  8139. ((uint32_t) FSb[(Y0 >> 24) & 0xFF] << 24);
  8140. X2 = *RK++ ^ ((uint32_t) FSb[(Y2) & 0xFF]) ^
  8141. ((uint32_t) FSb[(Y3 >> 8) & 0xFF] << 8) ^
  8142. ((uint32_t) FSb[(Y0 >> 16) & 0xFF] << 16) ^
  8143. ((uint32_t) FSb[(Y1 >> 24) & 0xFF] << 24);
  8144. X3 = *RK++ ^ ((uint32_t) FSb[(Y3) & 0xFF]) ^
  8145. ((uint32_t) FSb[(Y0 >> 8) & 0xFF] << 8) ^
  8146. ((uint32_t) FSb[(Y1 >> 16) & 0xFF] << 16) ^
  8147. ((uint32_t) FSb[(Y2 >> 24) & 0xFF] << 24);
  8148. #if AES_DECRYPTION // whether AES decryption is supported
  8149. }
  8150. #endif /* AES_DECRYPTION */
  8151. PUT_UINT32_LE(X0, output, 0);
  8152. PUT_UINT32_LE(X1, output, 4);
  8153. PUT_UINT32_LE(X2, output, 8);
  8154. PUT_UINT32_LE(X3, output, 12);
  8155. return (0);
  8156. }
  8157. /* end of aes.c */
  8158. /******************************************************************************
  8159. *
  8160. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  8161. *
  8162. * This is a simple and straightforward implementation of AES-GCM authenticated
  8163. * encryption. The focus of this work was correctness & accuracy. It is written
  8164. * in straight 'C' without any particular focus upon optimization or speed. It
  8165. * should be endian (memory byte order) neutral since the few places that care
  8166. * are handled explicitly.
  8167. *
  8168. * This implementation of AES-GCM was created by Steven M. Gibson of GRC.com.
  8169. *
  8170. * It is intended for general purpose use, but was written in support of GRC's
  8171. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  8172. *
  8173. * See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  8174. * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/
  8175. * gcm/gcm-revised-spec.pdf
  8176. *
  8177. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  8178. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  8179. *
  8180. *******************************************************************************/
  8181. /******************************************************************************
  8182. * ==== IMPLEMENTATION WARNING ====
  8183. *
  8184. * This code was developed for use within SQRL's fixed environmnent. Thus, it
  8185. * is somewhat less "general purpose" than it would be if it were designed as
  8186. * a general purpose AES-GCM library. Specifically, it bothers with almost NO
  8187. * error checking on parameter limits, buffer bounds, etc. It assumes that it
  8188. * is being invoked by its author or by someone who understands the values it
  8189. * expects to receive. Its behavior will be undefined otherwise.
  8190. *
  8191. * All functions that might fail are defined to return 'ints' to indicate a
  8192. * problem. Most do not do so now. But this allows for error propagation out
  8193. * of internal functions if robust error checking should ever be desired.
  8194. *
  8195. ******************************************************************************/
  8196. /* Calculating the "GHASH"
  8197. *
  8198. * There are many ways of calculating the so-called GHASH in software, each with
  8199. * a traditional size vs performance tradeoff. The GHASH (Galois field hash) is
  8200. * an intriguing construction which takes two 128-bit strings (also the cipher's
  8201. * block size and the fundamental operation size for the system) and hashes them
  8202. * into a third 128-bit result.
  8203. *
  8204. * Many implementation solutions have been worked out that use large precomputed
  8205. * table lookups in place of more time consuming bit fiddling, and this approach
  8206. * can be scaled easily upward or downward as needed to change the time/space
  8207. * tradeoff. It's been studied extensively and there's a solid body of theory
  8208. * and practice. For example, without using any lookup tables an implementation
  8209. * might obtain 119 cycles per byte throughput, whereas using a simple, though
  8210. * large, key-specific 64 kbyte 8-bit lookup table the performance jumps to 13
  8211. * cycles per byte.
  8212. *
  8213. * And Intel's processors have, since 2010, included an instruction which does
  8214. * the entire 128x128->128 bit job in just several 64x64->128 bit pieces.
  8215. *
  8216. * Since SQRL is interactive, and only processing a few 128-bit blocks, I've
  8217. * settled upon a relatively slower but appealing small-table compromise which
  8218. * folds a bunch of not only time consuming but also bit twiddling into a simple
  8219. * 16-entry table which is attributed to Victor Shoup's 1996 work while at
  8220. * Bellcore: "On Fast and Provably Secure MessageAuthentication Based on
  8221. * Universal Hashing." See: http://www.shoup.net/papers/macs.pdf
  8222. * See, also section 4.1 of the "gcm-revised-spec" cited above.
  8223. */
  8224. /*
  8225. * This 16-entry table of pre-computed constants is used by the
  8226. * GHASH multiplier to improve over a strictly table-free but
  8227. * significantly slower 128x128 bit multiple within GF(2^128).
  8228. */
  8229. static const uint64_t last4[16] = {
  8230. 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
  8231. 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0};
  8232. /*
  8233. * Platform Endianness Neutralizing Load and Store Macro definitions
  8234. * GCM wants platform-neutral Big Endian (BE) byte ordering
  8235. */
  8236. #define GET_UINT32_BE(n, b, i) \
  8237. { \
  8238. (n) = ((uint32_t) (b)[(i)] << 24) | ((uint32_t) (b)[(i) + 1] << 16) | \
  8239. ((uint32_t) (b)[(i) + 2] << 8) | ((uint32_t) (b)[(i) + 3]); \
  8240. }
  8241. #define PUT_UINT32_BE(n, b, i) \
  8242. { \
  8243. (b)[(i)] = (uchar) ((n) >> 24); \
  8244. (b)[(i) + 1] = (uchar) ((n) >> 16); \
  8245. (b)[(i) + 2] = (uchar) ((n) >> 8); \
  8246. (b)[(i) + 3] = (uchar) ((n)); \
  8247. }
  8248. /******************************************************************************
  8249. *
  8250. * GCM_INITIALIZE
  8251. *
  8252. * Must be called once to initialize the GCM library.
  8253. *
  8254. * At present, this only calls the AES keygen table generator, which expands
  8255. * the AES keying tables for use. This is NOT A THREAD-SAFE function, so it
  8256. * MUST be called during system initialization before a multi-threading
  8257. * environment is running.
  8258. *
  8259. ******************************************************************************/
  8260. int mg_gcm_initialize(void) {
  8261. aes_init_keygen_tables();
  8262. return (0);
  8263. }
  8264. /******************************************************************************
  8265. *
  8266. * GCM_MULT
  8267. *
  8268. * Performs a GHASH operation on the 128-bit input vector 'x', setting
  8269. * the 128-bit output vector to 'x' times H using our precomputed tables.
  8270. * 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  8271. *
  8272. ******************************************************************************/
  8273. static void gcm_mult(gcm_context *ctx, // pointer to established context
  8274. const uchar x[16], // pointer to 128-bit input vector
  8275. uchar output[16]) // pointer to 128-bit output vector
  8276. {
  8277. int i;
  8278. uchar lo, hi, rem;
  8279. uint64_t zh, zl;
  8280. lo = (uchar) (x[15] & 0x0f);
  8281. hi = (uchar) (x[15] >> 4);
  8282. zh = ctx->HH[lo];
  8283. zl = ctx->HL[lo];
  8284. for (i = 15; i >= 0; i--) {
  8285. lo = (uchar) (x[i] & 0x0f);
  8286. hi = (uchar) (x[i] >> 4);
  8287. if (i != 15) {
  8288. rem = (uchar) (zl & 0x0f);
  8289. zl = (zh << 60) | (zl >> 4);
  8290. zh = (zh >> 4);
  8291. zh ^= (uint64_t) last4[rem] << 48;
  8292. zh ^= ctx->HH[lo];
  8293. zl ^= ctx->HL[lo];
  8294. }
  8295. rem = (uchar) (zl & 0x0f);
  8296. zl = (zh << 60) | (zl >> 4);
  8297. zh = (zh >> 4);
  8298. zh ^= (uint64_t) last4[rem] << 48;
  8299. zh ^= ctx->HH[hi];
  8300. zl ^= ctx->HL[hi];
  8301. }
  8302. PUT_UINT32_BE(zh >> 32, output, 0);
  8303. PUT_UINT32_BE(zh, output, 4);
  8304. PUT_UINT32_BE(zl >> 32, output, 8);
  8305. PUT_UINT32_BE(zl, output, 12);
  8306. }
  8307. /******************************************************************************
  8308. *
  8309. * GCM_SETKEY
  8310. *
  8311. * This is called to set the AES-GCM key. It initializes the AES key
  8312. * and populates the gcm context's pre-calculated HTables.
  8313. *
  8314. ******************************************************************************/
  8315. static int gcm_setkey(
  8316. gcm_context *ctx, // pointer to caller-provided gcm context
  8317. const uchar *key, // pointer to the AES encryption key
  8318. const uint keysize) // size in bytes (must be 16, 24, 32 for
  8319. // 128, 192 or 256-bit keys respectively)
  8320. {
  8321. int ret, i, j;
  8322. uint64_t hi, lo;
  8323. uint64_t vl, vh;
  8324. unsigned char h[16];
  8325. memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
  8326. memset(h, 0, 16); // initialize the block to encrypt
  8327. // encrypt the null 128-bit block to generate a key-based value
  8328. // which is then used to initialize our GHASH lookup tables
  8329. if ((ret = aes_setkey(&ctx->aes_ctx, MG_ENCRYPT, key, keysize)) != 0)
  8330. return (ret);
  8331. if ((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
  8332. GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
  8333. GET_UINT32_BE(lo, h, 4);
  8334. vh = (uint64_t) hi << 32 | lo;
  8335. GET_UINT32_BE(hi, h, 8);
  8336. GET_UINT32_BE(lo, h, 12);
  8337. vl = (uint64_t) hi << 32 | lo;
  8338. ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
  8339. ctx->HH[8] = vh;
  8340. ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
  8341. ctx->HL[0] = 0;
  8342. for (i = 4; i > 0; i >>= 1) {
  8343. uint32_t T = (uint32_t) (vl & 1) * 0xe1000000U;
  8344. vl = (vh << 63) | (vl >> 1);
  8345. vh = (vh >> 1) ^ ((uint64_t) T << 32);
  8346. ctx->HL[i] = vl;
  8347. ctx->HH[i] = vh;
  8348. }
  8349. for (i = 2; i < 16; i <<= 1) {
  8350. uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
  8351. vh = *HiH;
  8352. vl = *HiL;
  8353. for (j = 1; j < i; j++) {
  8354. HiH[j] = vh ^ ctx->HH[j];
  8355. HiL[j] = vl ^ ctx->HL[j];
  8356. }
  8357. }
  8358. return (0);
  8359. }
  8360. /******************************************************************************
  8361. *
  8362. * GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
  8363. *
  8364. * SETKEY:
  8365. *
  8366. * START: Sets the Encryption/Decryption mode.
  8367. * Accepts the initialization vector and additional data.
  8368. *
  8369. * UPDATE: Encrypts or decrypts the plaintext or ciphertext.
  8370. *
  8371. * FINISH: Performs a final GHASH to generate the authentication tag.
  8372. *
  8373. ******************************************************************************
  8374. *
  8375. * GCM_START
  8376. *
  8377. * Given a user-provided GCM context, this initializes it, sets the encryption
  8378. * mode, and preprocesses the initialization vector and additional AEAD data.
  8379. *
  8380. ******************************************************************************/
  8381. int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context
  8382. int mode, // GCM_ENCRYPT or GCM_DECRYPT
  8383. const uchar *iv, // pointer to initialization vector
  8384. size_t iv_len, // IV length in bytes (should == 12)
  8385. const uchar *add, // ptr to additional AEAD data (NULL if none)
  8386. size_t add_len) // length of additional AEAD data (bytes)
  8387. {
  8388. int ret; // our error return if the AES encrypt fails
  8389. uchar work_buf[16]; // XOR source built from provided IV if len != 16
  8390. const uchar *p; // general purpose array pointer
  8391. size_t use_len; // byte count to process, up to 16 bytes
  8392. size_t i; // local loop iterator
  8393. // since the context might be reused under the same key
  8394. // we zero the working buffers for this next new process
  8395. memset(ctx->y, 0x00, sizeof(ctx->y));
  8396. memset(ctx->buf, 0x00, sizeof(ctx->buf));
  8397. ctx->len = 0;
  8398. ctx->add_len = 0;
  8399. ctx->mode = mode; // set the GCM encryption/decryption mode
  8400. ctx->aes_ctx.mode = MG_ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
  8401. if (iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
  8402. memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
  8403. ctx->y[15] = 1; // start "counting" from 1 (not 0)
  8404. } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
  8405. {
  8406. memset(work_buf, 0x00, 16); // clear the working buffer
  8407. PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
  8408. p = iv;
  8409. while (iv_len > 0) {
  8410. use_len = (iv_len < 16) ? iv_len : 16;
  8411. for (i = 0; i < use_len; i++) ctx->y[i] ^= p[i];
  8412. gcm_mult(ctx, ctx->y, ctx->y);
  8413. iv_len -= use_len;
  8414. p += use_len;
  8415. }
  8416. for (i = 0; i < 16; i++) ctx->y[i] ^= work_buf[i];
  8417. gcm_mult(ctx, ctx->y, ctx->y);
  8418. }
  8419. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0)
  8420. return (ret);
  8421. ctx->add_len = add_len;
  8422. p = add;
  8423. while (add_len > 0) {
  8424. use_len = (add_len < 16) ? add_len : 16;
  8425. for (i = 0; i < use_len; i++) ctx->buf[i] ^= p[i];
  8426. gcm_mult(ctx, ctx->buf, ctx->buf);
  8427. add_len -= use_len;
  8428. p += use_len;
  8429. }
  8430. return (0);
  8431. }
  8432. /******************************************************************************
  8433. *
  8434. * GCM_UPDATE
  8435. *
  8436. * This is called once or more to process bulk plaintext or ciphertext data.
  8437. * We give this some number of bytes of input and it returns the same number
  8438. * of output bytes. If called multiple times (which is fine) all but the final
  8439. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  8440. * have a partial block length of < 128 bits.)
  8441. *
  8442. ******************************************************************************/
  8443. int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  8444. size_t length, // length, in bytes, of data to process
  8445. const uchar *input, // pointer to source data
  8446. uchar *output) // pointer to destination data
  8447. {
  8448. int ret; // our error return if the AES encrypt fails
  8449. uchar ectr[16]; // counter-mode cipher output for XORing
  8450. size_t use_len; // byte count to process, up to 16 bytes
  8451. size_t i; // local loop iterator
  8452. ctx->len += length; // bump the GCM context's running length count
  8453. while (length > 0) {
  8454. // clamp the length to process at 16 bytes
  8455. use_len = (length < 16) ? length : 16;
  8456. // increment the context's 128-bit IV||Counter 'y' vector
  8457. for (i = 16; i > 12; i--)
  8458. if (++ctx->y[i - 1] != 0) break;
  8459. // encrypt the context's 'y' vector under the established key
  8460. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
  8461. // encrypt or decrypt the input to the output
  8462. if (ctx->mode == MG_ENCRYPT) {
  8463. for (i = 0; i < use_len; i++) {
  8464. // XOR the cipher's ouptut vector (ectr) with our input
  8465. output[i] = (uchar) (ectr[i] ^ input[i]);
  8466. // now we mix in our data into the authentication hash.
  8467. // if we're ENcrypting we XOR in the post-XOR (output)
  8468. // results, but if we're DEcrypting we XOR in the input
  8469. // data
  8470. ctx->buf[i] ^= output[i];
  8471. }
  8472. } else {
  8473. for (i = 0; i < use_len; i++) {
  8474. // but if we're DEcrypting we XOR in the input data first,
  8475. // i.e. before saving to ouput data, otherwise if the input
  8476. // and output buffer are the same (inplace decryption) we
  8477. // would not get the correct auth tag
  8478. ctx->buf[i] ^= input[i];
  8479. // XOR the cipher's ouptut vector (ectr) with our input
  8480. output[i] = (uchar) (ectr[i] ^ input[i]);
  8481. }
  8482. }
  8483. gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
  8484. length -= use_len; // drop the remaining byte count to process
  8485. input += use_len; // bump our input pointer forward
  8486. output += use_len; // bump our output pointer forward
  8487. }
  8488. return (0);
  8489. }
  8490. /******************************************************************************
  8491. *
  8492. * GCM_FINISH
  8493. *
  8494. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  8495. * It performs the final GHASH to produce the resulting authentication TAG.
  8496. *
  8497. ******************************************************************************/
  8498. int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context
  8499. uchar *tag, // pointer to buffer which receives the tag
  8500. size_t tag_len) // length, in bytes, of the tag-receiving buf
  8501. {
  8502. uchar work_buf[16];
  8503. uint64_t orig_len = ctx->len * 8;
  8504. uint64_t orig_add_len = ctx->add_len * 8;
  8505. size_t i;
  8506. if (tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
  8507. if (orig_len || orig_add_len) {
  8508. memset(work_buf, 0x00, 16);
  8509. PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
  8510. PUT_UINT32_BE((orig_add_len), work_buf, 4);
  8511. PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
  8512. PUT_UINT32_BE((orig_len), work_buf, 12);
  8513. for (i = 0; i < 16; i++) ctx->buf[i] ^= work_buf[i];
  8514. gcm_mult(ctx, ctx->buf, ctx->buf);
  8515. for (i = 0; i < tag_len; i++) tag[i] ^= ctx->buf[i];
  8516. }
  8517. return (0);
  8518. }
  8519. /******************************************************************************
  8520. *
  8521. * GCM_CRYPT_AND_TAG
  8522. *
  8523. * This either encrypts or decrypts the user-provided data and, either
  8524. * way, generates an authentication tag of the requested length. It must be
  8525. * called with a GCM context whose key has already been set with GCM_SETKEY.
  8526. *
  8527. * The user would typically call this explicitly to ENCRYPT a buffer of data
  8528. * and optional associated data, and produce its an authentication tag.
  8529. *
  8530. * To reverse the process the user would typically call the companion
  8531. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  8532. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  8533. * to perform its decryption and tag generation, which it then compares.
  8534. *
  8535. ******************************************************************************/
  8536. int gcm_crypt_and_tag(
  8537. gcm_context *ctx, // gcm context with key already setup
  8538. int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
  8539. const uchar *iv, // pointer to the 12-byte initialization vector
  8540. size_t iv_len, // byte length if the IV. should always be 12
  8541. const uchar *add, // pointer to the non-ciphered additional data
  8542. size_t add_len, // byte length of the additional AEAD data
  8543. const uchar *input, // pointer to the cipher data source
  8544. uchar *output, // pointer to the cipher data destination
  8545. size_t length, // byte length of the cipher data
  8546. uchar *tag, // pointer to the tag to be generated
  8547. size_t tag_len) // byte length of the tag to be generated
  8548. { /*
  8549. assuming that the caller has already invoked gcm_setkey to
  8550. prepare the gcm context with the keying material, we simply
  8551. invoke each of the three GCM sub-functions in turn...
  8552. */
  8553. gcm_start(ctx, mode, iv, iv_len, add, add_len);
  8554. gcm_update(ctx, length, input, output);
  8555. gcm_finish(ctx, tag, tag_len);
  8556. return (0);
  8557. }
  8558. /******************************************************************************
  8559. *
  8560. * GCM_ZERO_CTX
  8561. *
  8562. * The GCM context contains both the GCM context and the AES context.
  8563. * This includes keying and key-related material which is security-
  8564. * sensitive, so it MUST be zeroed after use. This function does that.
  8565. *
  8566. ******************************************************************************/
  8567. void gcm_zero_ctx(gcm_context *ctx) {
  8568. // zero the context originally provided to us
  8569. memset(ctx, 0, sizeof(gcm_context));
  8570. }
  8571. //
  8572. // aes-gcm.c
  8573. // Pods
  8574. //
  8575. // Created by Markus Kosmal on 20/11/14.
  8576. //
  8577. //
  8578. int mg_aes_gcm_encrypt(unsigned char *output, //
  8579. const unsigned char *input, size_t input_length,
  8580. const unsigned char *key, const size_t key_len,
  8581. const unsigned char *iv, const size_t iv_len,
  8582. unsigned char *aead, size_t aead_len, unsigned char *tag,
  8583. const size_t tag_len) {
  8584. int ret = 0; // our return value
  8585. gcm_context ctx; // includes the AES context structure
  8586. gcm_setkey(&ctx, key, (uint) key_len);
  8587. ret = gcm_crypt_and_tag(&ctx, MG_ENCRYPT, iv, iv_len, aead, aead_len, input,
  8588. output, input_length, tag, tag_len);
  8589. gcm_zero_ctx(&ctx);
  8590. return (ret);
  8591. }
  8592. int mg_aes_gcm_decrypt(unsigned char *output, const unsigned char *input,
  8593. size_t input_length, const unsigned char *key,
  8594. const size_t key_len, const unsigned char *iv,
  8595. const size_t iv_len) {
  8596. int ret = 0; // our return value
  8597. gcm_context ctx; // includes the AES context structure
  8598. size_t tag_len = 0;
  8599. unsigned char *tag_buf = NULL;
  8600. gcm_setkey(&ctx, key, (uint) key_len);
  8601. ret = gcm_crypt_and_tag(&ctx, MG_DECRYPT, iv, iv_len, NULL, 0, input, output,
  8602. input_length, tag_buf, tag_len);
  8603. gcm_zero_ctx(&ctx);
  8604. return (ret);
  8605. }
  8606. #endif
  8607. // End of aes128 PD
  8608. #ifdef MG_ENABLE_LINES
  8609. #line 1 "src/tls_builtin.c"
  8610. #endif
  8611. #if MG_TLS == MG_TLS_BUILTIN
  8612. /* TLS 1.3 Record Content Type (RFC8446 B.1) */
  8613. #define MG_TLS_CHANGE_CIPHER 20
  8614. #define MG_TLS_ALERT 21
  8615. #define MG_TLS_HANDSHAKE 22
  8616. #define MG_TLS_APP_DATA 23
  8617. #define MG_TLS_HEARTBEAT 24
  8618. /* TLS 1.3 Handshake Message Type (RFC8446 B.3) */
  8619. #define MG_TLS_CLIENT_HELLO 1
  8620. #define MG_TLS_SERVER_HELLO 2
  8621. #define MG_TLS_ENCRYPTED_EXTENSIONS 8
  8622. #define MG_TLS_CERTIFICATE 11
  8623. #define MG_TLS_CERTIFICATE_VERIFY 15
  8624. #define MG_TLS_FINISHED 20
  8625. // handshake is re-entrant, so we need to keep track of its state state names
  8626. // refer to RFC8446#A.1
  8627. enum mg_tls_hs_state {
  8628. // Client state machine:
  8629. MG_TLS_STATE_CLIENT_START, // Send ClientHello
  8630. MG_TLS_STATE_CLIENT_WAIT_SH, // Wait for ServerHello
  8631. MG_TLS_STATE_CLIENT_WAIT_EE, // Wait for EncryptedExtensions
  8632. MG_TLS_STATE_CLIENT_WAIT_CERT, // Wait for Certificate
  8633. MG_TLS_STATE_CLIENT_WAIT_CV, // Wait for CertificateVerify
  8634. MG_TLS_STATE_CLIENT_WAIT_FINISHED, // Wait for Finished
  8635. MG_TLS_STATE_CLIENT_CONNECTED, // Done
  8636. // Server state machine:
  8637. MG_TLS_STATE_SERVER_START, // Wait for ClientHello
  8638. MG_TLS_STATE_SERVER_NEGOTIATED, // Wait for Finished
  8639. MG_TLS_STATE_SERVER_CONNECTED // Done
  8640. };
  8641. // per-connection TLS data
  8642. struct tls_data {
  8643. enum mg_tls_hs_state state; // keep track of connection handshake progress
  8644. struct mg_iobuf send; // For the receive path, we're reusing c->rtls
  8645. struct mg_iobuf recv; // While c->rtls contains full records, recv reuses
  8646. // the same underlying buffer but points at individual
  8647. // decrypted messages
  8648. uint8_t content_type; // Last received record content type
  8649. mg_sha256_ctx sha256; // incremental SHA-256 hash for TLS handshake
  8650. uint32_t sseq; // server sequence number, used in encryption
  8651. uint32_t cseq; // client sequence number, used in decryption
  8652. uint8_t random[32]; // client random from ClientHello
  8653. uint8_t session_id[32]; // client session ID between the handshake states
  8654. uint8_t x25519_cli[32]; // client X25519 key between the handshake states
  8655. uint8_t x25519_sec[32]; // x25519 secret between the handshake states
  8656. int skip_verification; // perform checks on server certificate?
  8657. struct mg_str server_cert_der; // server certificate in DER format
  8658. uint8_t server_key[32]; // server EC private key
  8659. char hostname[254]; // server hostname (client extension)
  8660. uint8_t certhash[32]; // certificate message hash
  8661. uint8_t pubkey[64]; // server EC public key to verify cert
  8662. uint8_t sighash[32]; // server EC public key to verify cert
  8663. // keys for AES encryption
  8664. uint8_t handshake_secret[32];
  8665. uint8_t server_write_key[16];
  8666. uint8_t server_write_iv[12];
  8667. uint8_t server_finished_key[32];
  8668. uint8_t client_write_key[16];
  8669. uint8_t client_write_iv[12];
  8670. uint8_t client_finished_key[32];
  8671. };
  8672. #define MG_LOAD_BE16(p) ((uint16_t) ((MG_U8P(p)[0] << 8U) | MG_U8P(p)[1]))
  8673. #define MG_LOAD_BE24(p) \
  8674. ((uint32_t) ((MG_U8P(p)[0] << 16U) | (MG_U8P(p)[1] << 8U) | MG_U8P(p)[2]))
  8675. #define MG_STORE_BE16(p, n) \
  8676. do { \
  8677. MG_U8P(p)[0] = ((n) >> 8U) & 255; \
  8678. MG_U8P(p)[1] = (n) & 255; \
  8679. } while (0)
  8680. #define TLS_RECHDR_SIZE 5 // 1 byte type, 2 bytes version, 2 bytes length
  8681. #define TLS_MSGHDR_SIZE 4 // 1 byte type, 3 bytes length
  8682. #if 1
  8683. static void mg_ssl_key_log(const char *label, uint8_t client_random[32],
  8684. uint8_t *secret, size_t secretsz) {
  8685. (void) label;
  8686. (void) client_random;
  8687. (void) secret;
  8688. (void) secretsz;
  8689. }
  8690. #else
  8691. #include <stdio.h>
  8692. static void mg_ssl_key_log(const char *label, uint8_t client_random[32],
  8693. uint8_t *secret, size_t secretsz) {
  8694. char *keylogfile = getenv("SSLKEYLOGFILE");
  8695. if (keylogfile == NULL) {
  8696. return;
  8697. }
  8698. FILE *f = fopen(keylogfile, "a");
  8699. fprintf(f, "%s ", label);
  8700. for (int i = 0; i < 32; i++) {
  8701. fprintf(f, "%02x", client_random[i]);
  8702. }
  8703. fprintf(f, " ");
  8704. for (unsigned int i = 0; i < secretsz; i++) {
  8705. fprintf(f, "%02x", secret[i]);
  8706. }
  8707. fprintf(f, "\n");
  8708. fclose(f);
  8709. }
  8710. #endif
  8711. // for derived tls keys we need SHA256([0]*32)
  8712. static uint8_t zeros[32] = {0};
  8713. static uint8_t zeros_sha256_digest[32] = {
  8714. 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4,
  8715. 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b,
  8716. 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55};
  8717. // helper to hexdump buffers inline
  8718. static void mg_tls_hexdump(const char *msg, uint8_t *buf, size_t bufsz) {
  8719. MG_VERBOSE(("%s: %M", msg, mg_print_hex, bufsz, buf));
  8720. }
  8721. // helper utilities to parse ASN.1 DER
  8722. struct mg_der_tlv {
  8723. uint8_t type;
  8724. uint32_t len;
  8725. uint8_t *value;
  8726. };
  8727. // parse DER into a TLV record
  8728. static int mg_der_to_tlv(uint8_t *der, size_t dersz, struct mg_der_tlv *tlv) {
  8729. if (dersz < 2) {
  8730. return -1;
  8731. }
  8732. tlv->type = der[0];
  8733. tlv->len = der[1];
  8734. tlv->value = der + 2;
  8735. if (tlv->len > 0x7f) {
  8736. uint32_t i, n = tlv->len - 0x80;
  8737. tlv->len = 0;
  8738. for (i = 0; i < n; i++) {
  8739. tlv->len = (tlv->len << 8) | (der[2 + i]);
  8740. }
  8741. tlv->value = der + 2 + n;
  8742. }
  8743. if (der + dersz < tlv->value + tlv->len) {
  8744. return -1;
  8745. }
  8746. return 0;
  8747. }
  8748. static int mg_der_find(uint8_t *der, size_t dersz, uint8_t *oid, size_t oidsz,
  8749. struct mg_der_tlv *tlv) {
  8750. uint8_t *p, *end;
  8751. struct mg_der_tlv child = {0, 0, NULL};
  8752. if (mg_der_to_tlv(der, dersz, tlv) < 0) {
  8753. return -1; // invalid DER
  8754. } else if (tlv->type == 6) { // found OID, check value
  8755. return (tlv->len == oidsz && memcmp(tlv->value, oid, oidsz) == 0);
  8756. } else if ((tlv->type & 0x20) == 0) {
  8757. return 0; // Primitive, but not OID: not found
  8758. }
  8759. // Constructed object: scan children
  8760. p = tlv->value;
  8761. end = tlv->value + tlv->len;
  8762. while (end > p) {
  8763. int r;
  8764. mg_der_to_tlv(p, (size_t) (end - p), &child);
  8765. r = mg_der_find(p, (size_t) (end - p), oid, oidsz, tlv);
  8766. if (r < 0) return -1; // error
  8767. if (r > 0) return 1; // found OID!
  8768. p = child.value + child.len;
  8769. }
  8770. return 0; // not found
  8771. }
  8772. // Did we receive a full TLS record in the c->rtls buffer?
  8773. static bool mg_tls_got_record(struct mg_connection *c) {
  8774. return c->rtls.len >= (size_t) TLS_RECHDR_SIZE &&
  8775. c->rtls.len >=
  8776. (size_t) (TLS_RECHDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
  8777. }
  8778. // Remove a single TLS record from the recv buffer
  8779. static void mg_tls_drop_record(struct mg_connection *c) {
  8780. struct mg_iobuf *rio = &c->rtls;
  8781. uint16_t n = MG_LOAD_BE16(rio->buf + 3) + TLS_RECHDR_SIZE;
  8782. mg_iobuf_del(rio, 0, n);
  8783. }
  8784. // Remove a single TLS message from decrypted buffer, remove the wrapping
  8785. // record if it was the last message within a record
  8786. static void mg_tls_drop_message(struct mg_connection *c) {
  8787. uint32_t len;
  8788. struct tls_data *tls = (struct tls_data *) c->tls;
  8789. if (tls->recv.len == 0) {
  8790. return;
  8791. }
  8792. len = MG_LOAD_BE24(tls->recv.buf + 1);
  8793. mg_sha256_update(&tls->sha256, tls->recv.buf, len + TLS_MSGHDR_SIZE);
  8794. tls->recv.buf += len + TLS_MSGHDR_SIZE;
  8795. tls->recv.len -= len + TLS_MSGHDR_SIZE;
  8796. if (tls->recv.len == 0) {
  8797. mg_tls_drop_record(c);
  8798. }
  8799. }
  8800. // TLS1.3 secret derivation based on the key label
  8801. static void mg_tls_derive_secret(const char *label, uint8_t *key, size_t keysz,
  8802. uint8_t *data, size_t datasz, uint8_t *hash,
  8803. size_t hashsz) {
  8804. size_t labelsz = strlen(label);
  8805. uint8_t secret[32];
  8806. uint8_t packed[256] = {0, (uint8_t) hashsz, (uint8_t) labelsz};
  8807. // TODO: assert lengths of label, key, data and hash
  8808. if (labelsz > 0) memmove(packed + 3, label, labelsz);
  8809. packed[3 + labelsz] = (uint8_t) datasz;
  8810. if (datasz > 0) memmove(packed + labelsz + 4, data, datasz);
  8811. packed[4 + labelsz + datasz] = 1;
  8812. mg_hmac_sha256(secret, key, keysz, packed, 5 + labelsz + datasz);
  8813. memmove(hash, secret, hashsz);
  8814. }
  8815. // at this point we have x25519 shared secret, we can generate a set of derived
  8816. // handshake encryption keys
  8817. static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
  8818. struct tls_data *tls = (struct tls_data *) c->tls;
  8819. mg_sha256_ctx sha256;
  8820. uint8_t early_secret[32];
  8821. uint8_t pre_extract_secret[32];
  8822. uint8_t hello_hash[32];
  8823. uint8_t server_hs_secret[32];
  8824. uint8_t client_hs_secret[32];
  8825. mg_hmac_sha256(early_secret, NULL, 0, zeros, sizeof(zeros));
  8826. mg_tls_derive_secret("tls13 derived", early_secret, 32, zeros_sha256_digest,
  8827. 32, pre_extract_secret, 32);
  8828. mg_hmac_sha256(tls->handshake_secret, pre_extract_secret,
  8829. sizeof(pre_extract_secret), tls->x25519_sec,
  8830. sizeof(tls->x25519_sec));
  8831. mg_tls_hexdump("hs secret", tls->handshake_secret, 32);
  8832. // mg_sha256_final is not idempotent, need to copy sha256 context to calculate
  8833. // the digest
  8834. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8835. mg_sha256_final(hello_hash, &sha256);
  8836. mg_tls_hexdump("hello hash", hello_hash, 32);
  8837. // derive keys needed for the rest of the handshake
  8838. mg_tls_derive_secret("tls13 s hs traffic", tls->handshake_secret, 32,
  8839. hello_hash, 32, server_hs_secret, 32);
  8840. mg_tls_derive_secret("tls13 key", server_hs_secret, 32, NULL, 0,
  8841. tls->server_write_key, 16);
  8842. mg_tls_derive_secret("tls13 iv", server_hs_secret, 32, NULL, 0,
  8843. tls->server_write_iv, 12);
  8844. mg_tls_derive_secret("tls13 finished", server_hs_secret, 32, NULL, 0,
  8845. tls->server_finished_key, 32);
  8846. mg_tls_derive_secret("tls13 c hs traffic", tls->handshake_secret, 32,
  8847. hello_hash, 32, client_hs_secret, 32);
  8848. mg_tls_derive_secret("tls13 key", client_hs_secret, 32, NULL, 0,
  8849. tls->client_write_key, 16);
  8850. mg_tls_derive_secret("tls13 iv", client_hs_secret, 32, NULL, 0,
  8851. tls->client_write_iv, 12);
  8852. mg_tls_derive_secret("tls13 finished", client_hs_secret, 32, NULL, 0,
  8853. tls->client_finished_key, 32);
  8854. mg_tls_hexdump("s hs traffic", server_hs_secret, 32);
  8855. mg_tls_hexdump("s key", tls->server_write_key, 16);
  8856. mg_tls_hexdump("s iv", tls->server_write_iv, 12);
  8857. mg_tls_hexdump("s finished", tls->server_finished_key, 32);
  8858. mg_tls_hexdump("c hs traffic", client_hs_secret, 32);
  8859. mg_tls_hexdump("c key", tls->client_write_key, 16);
  8860. mg_tls_hexdump("c iv", tls->client_write_iv, 16);
  8861. mg_tls_hexdump("c finished", tls->client_finished_key, 32);
  8862. mg_ssl_key_log("SERVER_HANDSHAKE_TRAFFIC_SECRET", tls->random,
  8863. server_hs_secret, 32);
  8864. mg_ssl_key_log("CLIENT_HANDSHAKE_TRAFFIC_SECRET", tls->random,
  8865. client_hs_secret, 32);
  8866. }
  8867. static void mg_tls_generate_application_keys(struct mg_connection *c) {
  8868. struct tls_data *tls = (struct tls_data *) c->tls;
  8869. uint8_t hash[32];
  8870. uint8_t premaster_secret[32];
  8871. uint8_t master_secret[32];
  8872. uint8_t server_secret[32];
  8873. uint8_t client_secret[32];
  8874. mg_sha256_ctx sha256;
  8875. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8876. mg_sha256_final(hash, &sha256);
  8877. mg_tls_derive_secret("tls13 derived", tls->handshake_secret, 32,
  8878. zeros_sha256_digest, 32, premaster_secret, 32);
  8879. mg_hmac_sha256(master_secret, premaster_secret, 32, zeros, 32);
  8880. mg_tls_derive_secret("tls13 s ap traffic", master_secret, 32, hash, 32,
  8881. server_secret, 32);
  8882. mg_tls_derive_secret("tls13 key", server_secret, 32, NULL, 0,
  8883. tls->server_write_key, 16);
  8884. mg_tls_derive_secret("tls13 iv", server_secret, 32, NULL, 0,
  8885. tls->server_write_iv, 12);
  8886. mg_tls_derive_secret("tls13 c ap traffic", master_secret, 32, hash, 32,
  8887. client_secret, 32);
  8888. mg_tls_derive_secret("tls13 key", client_secret, 32, NULL, 0,
  8889. tls->client_write_key, 16);
  8890. mg_tls_derive_secret("tls13 iv", client_secret, 32, NULL, 0,
  8891. tls->client_write_iv, 12);
  8892. mg_tls_hexdump("s ap traffic", server_secret, 32);
  8893. mg_tls_hexdump("s key", tls->server_write_key, 16);
  8894. mg_tls_hexdump("s iv", tls->server_write_iv, 12);
  8895. mg_tls_hexdump("s finished", tls->server_finished_key, 32);
  8896. mg_tls_hexdump("c ap traffic", client_secret, 32);
  8897. mg_tls_hexdump("c key", tls->client_write_key, 16);
  8898. mg_tls_hexdump("c iv", tls->client_write_iv, 16);
  8899. mg_tls_hexdump("c finished", tls->client_finished_key, 32);
  8900. tls->sseq = tls->cseq = 0;
  8901. mg_ssl_key_log("SERVER_TRAFFIC_SECRET_0", tls->random, server_secret, 32);
  8902. mg_ssl_key_log("CLIENT_TRAFFIC_SECRET_0", tls->random, client_secret, 32);
  8903. }
  8904. // AES GCM encryption of the message + put encoded data into the write buffer
  8905. static void mg_tls_encrypt(struct mg_connection *c, const uint8_t *msg,
  8906. size_t msgsz, uint8_t msgtype) {
  8907. struct tls_data *tls = (struct tls_data *) c->tls;
  8908. struct mg_iobuf *wio = &tls->send;
  8909. uint8_t *outmsg;
  8910. uint8_t *tag;
  8911. size_t encsz = msgsz + 16 + 1;
  8912. uint8_t hdr[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
  8913. (uint8_t) ((encsz >> 8) & 0xff), (uint8_t) (encsz & 0xff)};
  8914. uint8_t associated_data[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
  8915. (uint8_t) ((encsz >> 8) & 0xff),
  8916. (uint8_t) (encsz & 0xff)};
  8917. uint8_t nonce[12];
  8918. mg_gcm_initialize();
  8919. if (c->is_client) {
  8920. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  8921. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  8922. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  8923. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  8924. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  8925. } else {
  8926. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8927. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8928. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8929. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8930. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8931. }
  8932. mg_iobuf_add(wio, wio->len, hdr, sizeof(hdr));
  8933. mg_iobuf_resize(wio, wio->len + encsz);
  8934. outmsg = wio->buf + wio->len;
  8935. tag = wio->buf + wio->len + msgsz + 1;
  8936. memmove(outmsg, msg, msgsz);
  8937. outmsg[msgsz] = msgtype;
  8938. if (c->is_client) {
  8939. mg_aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->client_write_key,
  8940. sizeof(tls->client_write_key), nonce, sizeof(nonce),
  8941. associated_data, sizeof(associated_data), tag, 16);
  8942. tls->cseq++;
  8943. } else {
  8944. mg_aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->server_write_key,
  8945. sizeof(tls->server_write_key), nonce, sizeof(nonce),
  8946. associated_data, sizeof(associated_data), tag, 16);
  8947. tls->sseq++;
  8948. }
  8949. wio->len += encsz;
  8950. }
  8951. // read an encrypted record, decrypt it in place
  8952. static int mg_tls_recv_record(struct mg_connection *c) {
  8953. struct tls_data *tls = (struct tls_data *) c->tls;
  8954. struct mg_iobuf *rio = &c->rtls;
  8955. uint16_t msgsz;
  8956. uint8_t *msg;
  8957. uint8_t nonce[12];
  8958. int r;
  8959. if (tls->recv.len > 0) {
  8960. return 0; /* some data from previous record is still present */
  8961. }
  8962. for (;;) {
  8963. if (!mg_tls_got_record(c)) {
  8964. return MG_IO_WAIT;
  8965. }
  8966. if (rio->buf[0] == MG_TLS_APP_DATA) {
  8967. break;
  8968. } else if (rio->buf[0] ==
  8969. MG_TLS_CHANGE_CIPHER) { // Skip ChangeCipher messages
  8970. mg_tls_drop_record(c);
  8971. } else if (rio->buf[0] == MG_TLS_ALERT) { // Skip Alerts
  8972. MG_INFO(("TLS ALERT packet received"));
  8973. mg_tls_drop_record(c);
  8974. } else {
  8975. mg_error(c, "unexpected packet");
  8976. return -1;
  8977. }
  8978. }
  8979. mg_gcm_initialize();
  8980. msgsz = MG_LOAD_BE16(rio->buf + 3);
  8981. msg = rio->buf + 5;
  8982. if (c->is_client) {
  8983. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8984. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8985. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8986. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8987. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8988. mg_aes_gcm_decrypt(msg, msg, msgsz - 16, tls->server_write_key,
  8989. sizeof(tls->server_write_key), nonce, sizeof(nonce));
  8990. tls->sseq++;
  8991. } else {
  8992. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  8993. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  8994. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  8995. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  8996. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  8997. mg_aes_gcm_decrypt(msg, msg, msgsz - 16, tls->client_write_key,
  8998. sizeof(tls->client_write_key), nonce, sizeof(nonce));
  8999. tls->cseq++;
  9000. }
  9001. r = msgsz - 16 - 1;
  9002. tls->content_type = msg[msgsz - 16 - 1];
  9003. tls->recv.buf = msg;
  9004. tls->recv.size = tls->recv.len = msgsz - 16 - 1;
  9005. return r;
  9006. }
  9007. static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
  9008. uint8_t hash[32]) {
  9009. struct tls_data *tls = (struct tls_data *) c->tls;
  9010. uint8_t sig_content[130] = {
  9011. " "
  9012. " "
  9013. "TLS 1.3, server CertificateVerify\0"};
  9014. mg_sha256_ctx sha256;
  9015. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9016. mg_sha256_final(sig_content + 98, &sha256);
  9017. mg_sha256_init(&sha256);
  9018. mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
  9019. mg_sha256_final(hash, &sha256);
  9020. }
  9021. // read and parse ClientHello record
  9022. static int mg_tls_server_recv_hello(struct mg_connection *c) {
  9023. struct tls_data *tls = (struct tls_data *) c->tls;
  9024. struct mg_iobuf *rio = &c->rtls;
  9025. uint8_t session_id_len;
  9026. uint16_t j;
  9027. uint16_t cipher_suites_len;
  9028. uint16_t ext_len;
  9029. uint8_t *ext;
  9030. uint16_t msgsz;
  9031. if (!mg_tls_got_record(c)) {
  9032. return MG_IO_WAIT;
  9033. }
  9034. if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_CLIENT_HELLO) {
  9035. mg_error(c, "not a client hello packet");
  9036. return -1;
  9037. }
  9038. msgsz = MG_LOAD_BE16(rio->buf + 3);
  9039. mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
  9040. // store client random
  9041. memmove(tls->random, rio->buf + 11, sizeof(tls->random));
  9042. // store session_id
  9043. session_id_len = rio->buf[43];
  9044. if (session_id_len == sizeof(tls->session_id)) {
  9045. memmove(tls->session_id, rio->buf + 44, session_id_len);
  9046. } else if (session_id_len != 0) {
  9047. MG_INFO(("bad session id len"));
  9048. }
  9049. cipher_suites_len = MG_LOAD_BE16(rio->buf + 44 + session_id_len);
  9050. ext_len = MG_LOAD_BE16(rio->buf + 48 + session_id_len + cipher_suites_len);
  9051. ext = rio->buf + 50 + session_id_len + cipher_suites_len;
  9052. for (j = 0; j < ext_len;) {
  9053. uint16_t k;
  9054. uint16_t key_exchange_len;
  9055. uint8_t *key_exchange;
  9056. uint16_t n = MG_LOAD_BE16(ext + j + 2);
  9057. if (ext[j] != 0x00 ||
  9058. ext[j + 1] != 0x33) { // not a key share extension, ignore
  9059. j += (uint16_t) (n + 4);
  9060. continue;
  9061. }
  9062. key_exchange_len = MG_LOAD_BE16(ext + j + 5);
  9063. key_exchange = ext + j + 6;
  9064. for (k = 0; k < key_exchange_len;) {
  9065. uint16_t m = MG_LOAD_BE16(key_exchange + k + 2);
  9066. if (m == 32 && key_exchange[k] == 0x00 && key_exchange[k + 1] == 0x1d) {
  9067. memmove(tls->x25519_cli, key_exchange + k + 4, m);
  9068. mg_tls_drop_record(c);
  9069. return 0;
  9070. }
  9071. k += (uint16_t) (m + 4);
  9072. }
  9073. j += (uint16_t) (n + 4);
  9074. }
  9075. mg_error(c, "bad client hello");
  9076. return -1;
  9077. }
  9078. #define PLACEHOLDER_8B 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'
  9079. #define PLACEHOLDER_16B PLACEHOLDER_8B, PLACEHOLDER_8B
  9080. #define PLACEHOLDER_32B PLACEHOLDER_16B, PLACEHOLDER_16B
  9081. // put ServerHello record into wio buffer
  9082. static void mg_tls_server_send_hello(struct mg_connection *c) {
  9083. struct tls_data *tls = (struct tls_data *) c->tls;
  9084. struct mg_iobuf *wio = &tls->send;
  9085. uint8_t msg_server_hello[122] = {
  9086. // server hello, tls 1.2
  9087. 0x02,
  9088. 0x00,
  9089. 0x00,
  9090. 0x76,
  9091. 0x03,
  9092. 0x03,
  9093. // random (32 bytes)
  9094. PLACEHOLDER_32B,
  9095. // session ID length + session ID (32 bytes)
  9096. 0x20,
  9097. PLACEHOLDER_32B,
  9098. #if defined(CHACHA20) && CHACHA20
  9099. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  9100. 0x13,
  9101. 0x03,
  9102. 0x00,
  9103. #else
  9104. // TLS_AES_128_GCM_SHA256 + no compression
  9105. 0x13,
  9106. 0x01,
  9107. 0x00,
  9108. #endif
  9109. // extensions + keyshare
  9110. 0x00,
  9111. 0x2e,
  9112. 0x00,
  9113. 0x33,
  9114. 0x00,
  9115. 0x24,
  9116. 0x00,
  9117. 0x1d,
  9118. 0x00,
  9119. 0x20,
  9120. // x25519 keyshare
  9121. PLACEHOLDER_32B,
  9122. // supported versions (tls1.3 == 0x304)
  9123. 0x00,
  9124. 0x2b,
  9125. 0x00,
  9126. 0x02,
  9127. 0x03,
  9128. 0x04
  9129. };
  9130. // calculate keyshare
  9131. uint8_t x25519_pub[X25519_BYTES];
  9132. uint8_t x25519_prv[X25519_BYTES];
  9133. mg_random(x25519_prv, sizeof(x25519_prv));
  9134. mg_tls_x25519(x25519_pub, x25519_prv, X25519_BASE_POINT, 1);
  9135. mg_tls_x25519(tls->x25519_sec, x25519_prv, tls->x25519_cli, 1);
  9136. mg_tls_hexdump("s x25519 sec", tls->x25519_sec, sizeof(tls->x25519_sec));
  9137. // fill in the gaps: random + session ID + keyshare
  9138. memmove(msg_server_hello + 6, tls->random, sizeof(tls->random));
  9139. memmove(msg_server_hello + 39, tls->session_id, sizeof(tls->session_id));
  9140. memmove(msg_server_hello + 84, x25519_pub, sizeof(x25519_pub));
  9141. // server hello message
  9142. mg_iobuf_add(wio, wio->len, "\x16\x03\x03\x00\x7a", 5);
  9143. mg_iobuf_add(wio, wio->len, msg_server_hello, sizeof(msg_server_hello));
  9144. mg_sha256_update(&tls->sha256, msg_server_hello, sizeof(msg_server_hello));
  9145. // change cipher message
  9146. mg_iobuf_add(wio, wio->len, "\x14\x03\x03\x00\x01\x01", 6);
  9147. }
  9148. static void mg_tls_server_send_ext(struct mg_connection *c) {
  9149. struct tls_data *tls = (struct tls_data *) c->tls;
  9150. // server extensions
  9151. uint8_t ext[6] = {0x08, 0, 0, 2, 0, 0};
  9152. mg_sha256_update(&tls->sha256, ext, sizeof(ext));
  9153. mg_tls_encrypt(c, ext, sizeof(ext), MG_TLS_HANDSHAKE);
  9154. }
  9155. static void mg_tls_server_send_cert(struct mg_connection *c) {
  9156. struct tls_data *tls = (struct tls_data *) c->tls;
  9157. // server DER certificate (empty)
  9158. size_t n = tls->server_cert_der.len;
  9159. uint8_t *cert = (uint8_t *) calloc(1, 13 + n);
  9160. if (cert == NULL) {
  9161. mg_error(c, "tls cert oom");
  9162. return;
  9163. }
  9164. cert[0] = 0x0b; // handshake header
  9165. cert[1] = (uint8_t) (((n + 9) >> 16) & 255U); // 3 bytes: payload length
  9166. cert[2] = (uint8_t) (((n + 9) >> 8) & 255U);
  9167. cert[3] = (uint8_t) ((n + 9) & 255U);
  9168. cert[4] = 0; // request context
  9169. cert[5] = (uint8_t) (((n + 5) >> 16) & 255U); // 3 bytes: cert (s) length
  9170. cert[6] = (uint8_t) (((n + 5) >> 8) & 255U);
  9171. cert[7] = (uint8_t) ((n + 5) & 255U);
  9172. cert[8] =
  9173. (uint8_t) (((n) >> 16) & 255U); // 3 bytes: first (and only) cert len
  9174. cert[9] = (uint8_t) (((n) >> 8) & 255U);
  9175. cert[10] = (uint8_t) (n & 255U);
  9176. // bytes 11+ are certificate in DER format
  9177. memmove(cert + 11, tls->server_cert_der.buf, n);
  9178. cert[11 + n] = cert[12 + n] = 0; // certificate extensions (none)
  9179. mg_sha256_update(&tls->sha256, cert, 13 + n);
  9180. mg_tls_encrypt(c, cert, 13 + n, MG_TLS_HANDSHAKE);
  9181. free(cert);
  9182. }
  9183. // type adapter between uECC hash context and our sha256 implementation
  9184. typedef struct SHA256_HashContext {
  9185. MG_UECC_HashContext uECC;
  9186. mg_sha256_ctx ctx;
  9187. } SHA256_HashContext;
  9188. static void init_SHA256(const MG_UECC_HashContext *base) {
  9189. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9190. mg_sha256_init(&c->ctx);
  9191. }
  9192. static void update_SHA256(const MG_UECC_HashContext *base,
  9193. const uint8_t *message, unsigned message_size) {
  9194. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9195. mg_sha256_update(&c->ctx, message, message_size);
  9196. }
  9197. static void finish_SHA256(const MG_UECC_HashContext *base,
  9198. uint8_t *hash_result) {
  9199. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9200. mg_sha256_final(hash_result, &c->ctx);
  9201. }
  9202. static void mg_tls_server_send_cert_verify(struct mg_connection *c) {
  9203. struct tls_data *tls = (struct tls_data *) c->tls;
  9204. // server certificate verify packet
  9205. uint8_t verify[82] = {0x0f, 0x00, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00};
  9206. size_t sigsz, verifysz = 0;
  9207. uint8_t hash[32] = {0}, tmp[2 * 32 + 64] = {0};
  9208. struct SHA256_HashContext ctx = {
  9209. {&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp},
  9210. {{0}, 0, 0, {0}}};
  9211. int neg1, neg2;
  9212. uint8_t sig[64] = {0};
  9213. mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash);
  9214. mg_uecc_sign_deterministic(tls->server_key, hash, sizeof(hash), &ctx.uECC,
  9215. sig, mg_uecc_secp256r1());
  9216. neg1 = !!(sig[0] & 0x80);
  9217. neg2 = !!(sig[32] & 0x80);
  9218. verify[8] = 0x30; // ASN.1 SEQUENCE
  9219. verify[9] = (uint8_t) (68 + neg1 + neg2);
  9220. verify[10] = 0x02; // ASN.1 INTEGER
  9221. verify[11] = (uint8_t) (32 + neg1);
  9222. memmove(verify + 12 + neg1, sig, 32);
  9223. verify[12 + 32 + neg1] = 0x02; // ASN.1 INTEGER
  9224. verify[13 + 32 + neg1] = (uint8_t) (32 + neg2);
  9225. memmove(verify + 14 + 32 + neg1 + neg2, sig + 32, 32);
  9226. sigsz = (size_t) (70 + neg1 + neg2);
  9227. verifysz = 8U + sigsz;
  9228. verify[3] = (uint8_t) (sigsz + 4);
  9229. verify[7] = (uint8_t) sigsz;
  9230. mg_sha256_update(&tls->sha256, verify, verifysz);
  9231. mg_tls_encrypt(c, verify, verifysz, MG_TLS_HANDSHAKE);
  9232. }
  9233. static void mg_tls_server_send_finish(struct mg_connection *c) {
  9234. struct tls_data *tls = (struct tls_data *) c->tls;
  9235. struct mg_iobuf *wio = &tls->send;
  9236. mg_sha256_ctx sha256;
  9237. uint8_t hash[32];
  9238. uint8_t finish[36] = {0x14, 0, 0, 32};
  9239. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9240. mg_sha256_final(hash, &sha256);
  9241. mg_hmac_sha256(finish + 4, tls->server_finished_key, 32, hash, 32);
  9242. mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
  9243. mg_io_send(c, wio->buf, wio->len);
  9244. wio->len = 0;
  9245. mg_sha256_update(&tls->sha256, finish, sizeof(finish));
  9246. }
  9247. static int mg_tls_server_recv_finish(struct mg_connection *c) {
  9248. struct tls_data *tls = (struct tls_data *) c->tls;
  9249. // we have to backup sha256 value to restore it later, since Finished record
  9250. // is exceptional and is not supposed to be added to the rolling hash
  9251. // calculation.
  9252. mg_sha256_ctx sha256 = tls->sha256;
  9253. if (mg_tls_recv_record(c) < 0) {
  9254. return -1;
  9255. }
  9256. if (tls->recv.buf[0] != MG_TLS_FINISHED) {
  9257. mg_error(c, "expected Finish but got msg 0x%02x", tls->recv.buf[0]);
  9258. return -1;
  9259. }
  9260. mg_tls_drop_message(c);
  9261. // restore hash
  9262. tls->sha256 = sha256;
  9263. return 0;
  9264. }
  9265. static void mg_tls_client_send_hello(struct mg_connection *c) {
  9266. struct tls_data *tls = (struct tls_data *) c->tls;
  9267. struct mg_iobuf *wio = &tls->send;
  9268. const char *hostname = tls->hostname;
  9269. size_t hostnamesz = strlen(tls->hostname);
  9270. uint8_t x25519_pub[X25519_BYTES];
  9271. uint8_t msg_client_hello[162 + 32] = {
  9272. // TLS Client Hello header reported as TLS1.2 (5)
  9273. 0x16,
  9274. 0x03,
  9275. 0x01,
  9276. 0x00,
  9277. 0xfe,
  9278. // server hello, tls 1.2 (6)
  9279. 0x01,
  9280. 0x00,
  9281. 0x00,
  9282. 0x8c,
  9283. 0x03,
  9284. 0x03,
  9285. // random (32 bytes)
  9286. PLACEHOLDER_32B,
  9287. // session ID length + session ID (32 bytes)
  9288. 0x20,
  9289. PLACEHOLDER_32B,
  9290. #if defined(CHACHA20) && CHACHA20
  9291. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  9292. 0x13,
  9293. 0x03,
  9294. 0x00,
  9295. #else
  9296. 0x00,
  9297. 0x02, // size = 2 bytes
  9298. 0x13,
  9299. 0x01, // TLS_AES_128_GCM_SHA256
  9300. 0x01,
  9301. 0x00, // no compression
  9302. #endif
  9303. // extensions + keyshare
  9304. 0x00,
  9305. 0xfe,
  9306. // x25519 keyshare
  9307. 0x00,
  9308. 0x33,
  9309. 0x00,
  9310. 0x26,
  9311. 0x00,
  9312. 0x24,
  9313. 0x00,
  9314. 0x1d,
  9315. 0x00,
  9316. 0x20,
  9317. PLACEHOLDER_32B,
  9318. // supported groups (x25519)
  9319. 0x00,
  9320. 0x0a,
  9321. 0x00,
  9322. 0x04,
  9323. 0x00,
  9324. 0x02,
  9325. 0x00,
  9326. 0x1d,
  9327. // supported versions (tls1.3 == 0x304)
  9328. 0x00,
  9329. 0x2b,
  9330. 0x00,
  9331. 0x03,
  9332. 0x02,
  9333. 0x03,
  9334. 0x04,
  9335. // session ticket (none)
  9336. 0x00,
  9337. 0x23,
  9338. 0x00,
  9339. 0x00,
  9340. // signature algorithms (we don't care, so list all the common ones)
  9341. 0x00,
  9342. 0x0d,
  9343. 0x00,
  9344. 0x24,
  9345. 0x00,
  9346. 0x22,
  9347. 0x04,
  9348. 0x03,
  9349. 0x05,
  9350. 0x03,
  9351. 0x06,
  9352. 0x03,
  9353. 0x08,
  9354. 0x07,
  9355. 0x08,
  9356. 0x08,
  9357. 0x08,
  9358. 0x1a,
  9359. 0x08,
  9360. 0x1b,
  9361. 0x08,
  9362. 0x1c,
  9363. 0x08,
  9364. 0x09,
  9365. 0x08,
  9366. 0x0a,
  9367. 0x08,
  9368. 0x0b,
  9369. 0x08,
  9370. 0x04,
  9371. 0x08,
  9372. 0x05,
  9373. 0x08,
  9374. 0x06,
  9375. 0x04,
  9376. 0x01,
  9377. 0x05,
  9378. 0x01,
  9379. 0x06,
  9380. 0x01,
  9381. // server name
  9382. 0x00,
  9383. 0x00,
  9384. 0x00,
  9385. 0xfe,
  9386. 0x00,
  9387. 0xfe,
  9388. 0x00,
  9389. 0x00,
  9390. 0xfe
  9391. };
  9392. // patch ClientHello with correct hostname length + offset:
  9393. MG_STORE_BE16(msg_client_hello + 3, hostnamesz + 189);
  9394. MG_STORE_BE16(msg_client_hello + 7, hostnamesz + 185);
  9395. MG_STORE_BE16(msg_client_hello + 82, hostnamesz + 110);
  9396. MG_STORE_BE16(msg_client_hello + 187, hostnamesz + 5);
  9397. MG_STORE_BE16(msg_client_hello + 189, hostnamesz + 3);
  9398. MG_STORE_BE16(msg_client_hello + 192, hostnamesz);
  9399. // calculate keyshare
  9400. mg_random(tls->x25519_cli, sizeof(tls->x25519_cli));
  9401. mg_tls_x25519(x25519_pub, tls->x25519_cli, X25519_BASE_POINT, 1);
  9402. // fill in the gaps: random + session ID + keyshare
  9403. mg_random(tls->session_id, sizeof(tls->session_id));
  9404. mg_random(tls->random, sizeof(tls->random));
  9405. memmove(msg_client_hello + 11, tls->random, sizeof(tls->random));
  9406. memmove(msg_client_hello + 44, tls->session_id, sizeof(tls->session_id));
  9407. memmove(msg_client_hello + 94, x25519_pub, sizeof(x25519_pub));
  9408. // server hello message
  9409. mg_iobuf_add(wio, wio->len, msg_client_hello, sizeof(msg_client_hello));
  9410. mg_iobuf_add(wio, wio->len, hostname, strlen(hostname));
  9411. mg_sha256_update(&tls->sha256, msg_client_hello + 5,
  9412. sizeof(msg_client_hello) - 5);
  9413. mg_sha256_update(&tls->sha256, (uint8_t *) hostname, strlen(hostname));
  9414. // change cipher message
  9415. mg_iobuf_add(wio, wio->len, (const char *) "\x14\x03\x03\x00\x01\x01", 6);
  9416. mg_io_send(c, wio->buf, wio->len);
  9417. wio->len = 0;
  9418. }
  9419. static int mg_tls_client_recv_hello(struct mg_connection *c) {
  9420. struct tls_data *tls = (struct tls_data *) c->tls;
  9421. struct mg_iobuf *rio = &c->rtls;
  9422. uint16_t msgsz;
  9423. uint8_t *ext;
  9424. uint16_t ext_len;
  9425. int j;
  9426. if (!mg_tls_got_record(c)) {
  9427. return MG_IO_WAIT;
  9428. }
  9429. if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_SERVER_HELLO) {
  9430. if (rio->buf[0] == MG_TLS_ALERT && rio->len >= 7) {
  9431. mg_error(c, "tls alert %d", rio->buf[6]);
  9432. return -1;
  9433. }
  9434. MG_INFO(("got packet type 0x%02x/0x%02x", rio->buf[0], rio->buf[5]));
  9435. mg_error(c, "not a server hello packet");
  9436. return -1;
  9437. }
  9438. msgsz = MG_LOAD_BE16(rio->buf + 3);
  9439. mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
  9440. ext_len = MG_LOAD_BE16(rio->buf + 5 + 39 + 32 + 3);
  9441. ext = rio->buf + 5 + 39 + 32 + 3 + 2;
  9442. for (j = 0; j < ext_len;) {
  9443. uint16_t ext_type = MG_LOAD_BE16(ext + j);
  9444. uint16_t ext_len2 = MG_LOAD_BE16(ext + j + 2);
  9445. uint16_t group;
  9446. uint8_t *key_exchange;
  9447. uint16_t key_exchange_len;
  9448. if (ext_type != 0x0033) { // not a key share extension, ignore
  9449. j += (uint16_t) (ext_len2 + 4);
  9450. continue;
  9451. }
  9452. group = MG_LOAD_BE16(ext + j + 4);
  9453. if (group != 0x001d) {
  9454. mg_error(c, "bad key exchange group");
  9455. return -1;
  9456. }
  9457. key_exchange_len = MG_LOAD_BE16(ext + j + 6);
  9458. key_exchange = ext + j + 8;
  9459. if (key_exchange_len != 32) {
  9460. mg_error(c, "bad key exchange length");
  9461. return -1;
  9462. }
  9463. mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1);
  9464. mg_tls_hexdump("c x25519 sec", tls->x25519_sec, 32);
  9465. mg_tls_drop_record(c);
  9466. /* generate handshake keys */
  9467. mg_tls_generate_handshake_keys(c);
  9468. return 0;
  9469. }
  9470. mg_error(c, "bad client hello");
  9471. return -1;
  9472. }
  9473. static int mg_tls_client_recv_ext(struct mg_connection *c) {
  9474. struct tls_data *tls = (struct tls_data *) c->tls;
  9475. if (mg_tls_recv_record(c) < 0) {
  9476. return -1;
  9477. }
  9478. if (tls->recv.buf[0] != MG_TLS_ENCRYPTED_EXTENSIONS) {
  9479. mg_error(c, "expected server extensions but got msg 0x%02x",
  9480. tls->recv.buf[0]);
  9481. return -1;
  9482. }
  9483. mg_tls_drop_message(c);
  9484. return 0;
  9485. }
  9486. static int mg_tls_client_recv_cert(struct mg_connection *c) {
  9487. uint8_t *cert;
  9488. uint32_t certsz;
  9489. struct mg_der_tlv oid, pubkey, seq, subj;
  9490. int subj_match = 0;
  9491. struct tls_data *tls = (struct tls_data *) c->tls;
  9492. if (mg_tls_recv_record(c) < 0) {
  9493. return -1;
  9494. }
  9495. if (tls->recv.buf[0] != MG_TLS_CERTIFICATE) {
  9496. mg_error(c, "expected server certificate but got msg 0x%02x",
  9497. tls->recv.buf[0]);
  9498. return -1;
  9499. }
  9500. if (tls->skip_verification) {
  9501. mg_tls_drop_message(c);
  9502. return 0;
  9503. }
  9504. if (tls->recv.len < 11) {
  9505. mg_error(c, "certificate list too short");
  9506. return -1;
  9507. }
  9508. cert = tls->recv.buf + 11;
  9509. certsz = MG_LOAD_BE24(tls->recv.buf + 8);
  9510. if (certsz > tls->recv.len - 11) {
  9511. mg_error(c, "certificate too long: %d vs %d", certsz, tls->recv.len - 11);
  9512. return -1;
  9513. }
  9514. do {
  9515. // secp256r1 public key
  9516. if (mg_der_find(cert, certsz,
  9517. (uint8_t *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8,
  9518. &oid) < 0) {
  9519. mg_error(c, "certificate secp256r1 public key OID not found");
  9520. return -1;
  9521. }
  9522. if (mg_der_to_tlv(oid.value + oid.len,
  9523. (size_t) (cert + certsz - (oid.value + oid.len)),
  9524. &pubkey) < 0) {
  9525. mg_error(c, "certificate secp256r1 public key not found");
  9526. return -1;
  9527. }
  9528. // expect BIT STRING, unpadded, uncompressed: [0]+[4]+32+32 content bytes
  9529. if (pubkey.type != 3 || pubkey.len != 66 || pubkey.value[0] != 0 ||
  9530. pubkey.value[1] != 4) {
  9531. mg_error(c, "unsupported public key bitstring encoding");
  9532. return -1;
  9533. }
  9534. memmove(tls->pubkey, pubkey.value + 2, pubkey.len - 2);
  9535. } while (0);
  9536. // Subject Alternative Names
  9537. do {
  9538. if (mg_der_find(cert, certsz, (uint8_t *) "\x55\x1d\x11", 3, &oid) < 0) {
  9539. mg_error(c, "certificate does not contain subject alternative names");
  9540. return -1;
  9541. }
  9542. if (mg_der_to_tlv(oid.value + oid.len,
  9543. (size_t) (cert + certsz - (oid.value + oid.len)),
  9544. &seq) < 0) {
  9545. mg_error(c, "certificate subject alternative names not found");
  9546. return -1;
  9547. }
  9548. if (mg_der_to_tlv(seq.value, seq.len, &seq) < 0) {
  9549. mg_error(
  9550. c,
  9551. "certificate subject alternative names is not a constructed object");
  9552. return -1;
  9553. }
  9554. MG_VERBOSE(("verify hostname %s", tls->hostname));
  9555. while (seq.len > 0) {
  9556. if (mg_der_to_tlv(seq.value, seq.len, &subj) < 0) {
  9557. mg_error(c, "bad subject alternative name");
  9558. return -1;
  9559. }
  9560. MG_VERBOSE(("subj=%.*s", subj.len, subj.value));
  9561. if (mg_match(mg_str((const char *) tls->hostname),
  9562. mg_str_n((const char *) subj.value, subj.len), NULL)) {
  9563. subj_match = 1;
  9564. break;
  9565. }
  9566. seq.len = (uint32_t) (seq.value + seq.len - (subj.value + subj.len));
  9567. seq.value = subj.value + subj.len;
  9568. }
  9569. if (!subj_match) {
  9570. mg_error(c, "certificate did not match the hostname");
  9571. return -1;
  9572. }
  9573. } while (0);
  9574. mg_tls_drop_message(c);
  9575. mg_tls_calc_cert_verify_hash(c, tls->sighash);
  9576. return 0;
  9577. }
  9578. static int mg_tls_client_recv_cert_verify(struct mg_connection *c) {
  9579. struct tls_data *tls = (struct tls_data *) c->tls;
  9580. if (mg_tls_recv_record(c) < 0) {
  9581. return -1;
  9582. }
  9583. if (tls->recv.buf[0] != MG_TLS_CERTIFICATE_VERIFY) {
  9584. mg_error(c, "expected server certificate verify but got msg 0x%02x",
  9585. tls->recv.buf[0]);
  9586. return -1;
  9587. }
  9588. // Ignore CertificateVerify is strict checks are not required
  9589. if (tls->skip_verification) {
  9590. mg_tls_drop_message(c);
  9591. return 0;
  9592. }
  9593. // Extract certificate signature and verify it using pubkey and sighash
  9594. do {
  9595. uint8_t sig[64];
  9596. struct mg_der_tlv seq, a, b;
  9597. if (mg_der_to_tlv(tls->recv.buf + 8, tls->recv.len - 8, &seq) < 0) {
  9598. mg_error(c, "verification message is not an ASN.1 DER sequence");
  9599. return -1;
  9600. }
  9601. if (mg_der_to_tlv(seq.value, seq.len, &a) < 0) {
  9602. mg_error(c, "missing first part of the signature");
  9603. return -1;
  9604. }
  9605. if (mg_der_to_tlv(a.value + a.len, seq.len - a.len, &b) < 0) {
  9606. mg_error(c, "missing second part of the signature");
  9607. return -1;
  9608. }
  9609. // Integers may be padded with zeroes
  9610. if (a.len > 32) {
  9611. a.value = a.value + (a.len - 32);
  9612. a.len = 32;
  9613. }
  9614. if (b.len > 32) {
  9615. b.value = b.value + (b.len - 32);
  9616. b.len = 32;
  9617. }
  9618. memmove(sig, a.value, a.len);
  9619. memmove(sig + 32, b.value, b.len);
  9620. if (mg_uecc_verify(tls->pubkey, tls->sighash, sizeof(tls->sighash), sig,
  9621. mg_uecc_secp256r1()) != 1) {
  9622. mg_error(c, "failed to verify certificate");
  9623. return -1;
  9624. }
  9625. } while (0);
  9626. mg_tls_drop_message(c);
  9627. return 0;
  9628. }
  9629. static int mg_tls_client_recv_finish(struct mg_connection *c) {
  9630. struct tls_data *tls = (struct tls_data *) c->tls;
  9631. if (mg_tls_recv_record(c) < 0) {
  9632. return -1;
  9633. }
  9634. if (tls->recv.buf[0] != MG_TLS_FINISHED) {
  9635. mg_error(c, "expected server finished but got msg 0x%02x",
  9636. tls->recv.buf[0]);
  9637. return -1;
  9638. }
  9639. mg_tls_drop_message(c);
  9640. return 0;
  9641. }
  9642. static void mg_tls_client_send_finish(struct mg_connection *c) {
  9643. struct tls_data *tls = (struct tls_data *) c->tls;
  9644. struct mg_iobuf *wio = &tls->send;
  9645. mg_sha256_ctx sha256;
  9646. uint8_t hash[32];
  9647. uint8_t finish[36] = {0x14, 0, 0, 32};
  9648. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9649. mg_sha256_final(hash, &sha256);
  9650. mg_hmac_sha256(finish + 4, tls->client_finished_key, 32, hash, 32);
  9651. mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
  9652. mg_io_send(c, wio->buf, wio->len);
  9653. wio->len = 0;
  9654. }
  9655. static void mg_tls_client_handshake(struct mg_connection *c) {
  9656. struct tls_data *tls = (struct tls_data *) c->tls;
  9657. switch (tls->state) {
  9658. case MG_TLS_STATE_CLIENT_START:
  9659. mg_tls_client_send_hello(c);
  9660. tls->state = MG_TLS_STATE_CLIENT_WAIT_SH;
  9661. // Fallthrough
  9662. case MG_TLS_STATE_CLIENT_WAIT_SH:
  9663. if (mg_tls_client_recv_hello(c) < 0) {
  9664. break;
  9665. }
  9666. tls->state = MG_TLS_STATE_CLIENT_WAIT_EE;
  9667. // Fallthrough
  9668. case MG_TLS_STATE_CLIENT_WAIT_EE:
  9669. if (mg_tls_client_recv_ext(c) < 0) {
  9670. break;
  9671. }
  9672. tls->state = MG_TLS_STATE_CLIENT_WAIT_CERT;
  9673. // Fallthrough
  9674. case MG_TLS_STATE_CLIENT_WAIT_CERT:
  9675. if (mg_tls_client_recv_cert(c) < 0) {
  9676. break;
  9677. }
  9678. tls->state = MG_TLS_STATE_CLIENT_WAIT_CV;
  9679. // Fallthrough
  9680. case MG_TLS_STATE_CLIENT_WAIT_CV:
  9681. if (mg_tls_client_recv_cert_verify(c) < 0) {
  9682. break;
  9683. }
  9684. tls->state = MG_TLS_STATE_CLIENT_WAIT_FINISHED;
  9685. // Fallthrough
  9686. case MG_TLS_STATE_CLIENT_WAIT_FINISHED:
  9687. if (mg_tls_client_recv_finish(c) < 0) {
  9688. break;
  9689. }
  9690. mg_tls_client_send_finish(c);
  9691. mg_tls_generate_application_keys(c);
  9692. tls->state = MG_TLS_STATE_CLIENT_CONNECTED;
  9693. c->is_tls_hs = 0;
  9694. break;
  9695. default: mg_error(c, "unexpected client state: %d", tls->state); break;
  9696. }
  9697. }
  9698. static void mg_tls_server_handshake(struct mg_connection *c) {
  9699. struct tls_data *tls = (struct tls_data *) c->tls;
  9700. switch (tls->state) {
  9701. case MG_TLS_STATE_SERVER_START:
  9702. if (mg_tls_server_recv_hello(c) < 0) {
  9703. return;
  9704. }
  9705. mg_tls_server_send_hello(c);
  9706. mg_tls_generate_handshake_keys(c);
  9707. mg_tls_server_send_ext(c);
  9708. mg_tls_server_send_cert(c);
  9709. mg_tls_server_send_cert_verify(c);
  9710. mg_tls_server_send_finish(c);
  9711. tls->state = MG_TLS_STATE_SERVER_NEGOTIATED;
  9712. // fallthrough
  9713. case MG_TLS_STATE_SERVER_NEGOTIATED:
  9714. if (mg_tls_server_recv_finish(c) < 0) {
  9715. return;
  9716. }
  9717. mg_tls_generate_application_keys(c);
  9718. tls->state = MG_TLS_STATE_SERVER_CONNECTED;
  9719. c->is_tls_hs = 0;
  9720. return;
  9721. default: mg_error(c, "unexpected server state: %d", tls->state); break;
  9722. }
  9723. }
  9724. void mg_tls_handshake(struct mg_connection *c) {
  9725. if (c->is_client) {
  9726. mg_tls_client_handshake(c);
  9727. } else {
  9728. mg_tls_server_handshake(c);
  9729. }
  9730. }
  9731. static int mg_parse_pem(const struct mg_str pem, const struct mg_str label,
  9732. struct mg_str *der) {
  9733. size_t n = 0, m = 0;
  9734. char *s;
  9735. const char *c;
  9736. struct mg_str caps[5];
  9737. if (!mg_match(pem, mg_str("#-----BEGIN #-----#-----END #-----#"), caps)) {
  9738. der->buf = mg_mprintf("%.*s", pem.len, pem.buf);
  9739. der->len = pem.len;
  9740. return 0;
  9741. }
  9742. if (mg_strcmp(caps[1], label) != 0 || mg_strcmp(caps[3], label) != 0) {
  9743. return -1; // bad label
  9744. }
  9745. if ((s = (char *) calloc(1, caps[2].len)) == NULL) {
  9746. return -1;
  9747. }
  9748. for (c = caps[2].buf; c < caps[2].buf + caps[2].len; c++) {
  9749. if (*c == ' ' || *c == '\n' || *c == '\r' || *c == '\t') {
  9750. continue;
  9751. }
  9752. s[n++] = *c;
  9753. }
  9754. m = mg_base64_decode(s, n, s, n);
  9755. if (m == 0) {
  9756. free(s);
  9757. return -1;
  9758. }
  9759. der->buf = s;
  9760. der->len = m;
  9761. return 0;
  9762. }
  9763. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9764. struct mg_str key;
  9765. struct tls_data *tls = (struct tls_data *) calloc(1, sizeof(struct tls_data));
  9766. if (tls == NULL) {
  9767. mg_error(c, "tls oom");
  9768. return;
  9769. }
  9770. tls->state =
  9771. c->is_client ? MG_TLS_STATE_CLIENT_START : MG_TLS_STATE_SERVER_START;
  9772. tls->skip_verification = opts->skip_verification;
  9773. tls->send.align = MG_IO_SIZE;
  9774. c->tls = tls;
  9775. c->is_tls = c->is_tls_hs = 1;
  9776. mg_sha256_init(&tls->sha256);
  9777. // save hostname (client extension)
  9778. if (opts->name.len > 0) {
  9779. if (opts->name.len >= sizeof(tls->hostname) - 1) {
  9780. mg_error(c, "hostname too long");
  9781. }
  9782. strncpy((char *) tls->hostname, opts->name.buf, sizeof(tls->hostname) - 1);
  9783. tls->hostname[opts->name.len] = 0;
  9784. }
  9785. if (c->is_client) {
  9786. tls->server_cert_der.buf = NULL;
  9787. return;
  9788. }
  9789. // parse PEM or DER certificate
  9790. if (mg_parse_pem(opts->cert, mg_str_s("CERTIFICATE"), &tls->server_cert_der) <
  9791. 0) {
  9792. MG_ERROR(("Failed to load certificate"));
  9793. return;
  9794. }
  9795. // parse PEM or DER EC key
  9796. if (opts->key.buf == NULL) {
  9797. mg_error(c, "certificate provided without a private key");
  9798. return;
  9799. }
  9800. if (mg_parse_pem(opts->key, mg_str_s("EC PRIVATE KEY"), &key) == 0) {
  9801. if (key.len < 39) {
  9802. MG_ERROR(("EC private key too short"));
  9803. return;
  9804. }
  9805. // expect ASN.1 SEQUENCE=[INTEGER=1, BITSTRING of 32 bytes, ...]
  9806. // 30 nn 02 01 01 04 20 [key] ...
  9807. if (key.buf[0] != 0x30 || (key.buf[1] & 0x80) != 0) {
  9808. MG_ERROR(("EC private key: ASN.1 bad sequence"));
  9809. return;
  9810. }
  9811. if (memcmp(key.buf + 2, "\x02\x01\x01\x04\x20", 5) != 0) {
  9812. MG_ERROR(("EC private key: ASN.1 bad data"));
  9813. }
  9814. memmove(tls->server_key, key.buf + 7, 32);
  9815. free((void *) key.buf);
  9816. } else if (mg_parse_pem(opts->key, mg_str_s("PRIVATE KEY"), &key) == 0) {
  9817. mg_error(c, "PKCS8 private key format is not supported");
  9818. } else {
  9819. mg_error(c, "expected EC PRIVATE KEY or PRIVATE KEY");
  9820. }
  9821. }
  9822. void mg_tls_free(struct mg_connection *c) {
  9823. struct tls_data *tls = (struct tls_data *) c->tls;
  9824. if (tls != NULL) {
  9825. mg_iobuf_free(&tls->send);
  9826. free((void *) tls->server_cert_der.buf);
  9827. }
  9828. free(c->tls);
  9829. c->tls = NULL;
  9830. }
  9831. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9832. struct tls_data *tls = (struct tls_data *) c->tls;
  9833. long n = MG_IO_WAIT;
  9834. if (len > MG_IO_SIZE) len = MG_IO_SIZE;
  9835. mg_tls_encrypt(c, (const uint8_t *) buf, len, MG_TLS_APP_DATA);
  9836. while (tls->send.len > 0 &&
  9837. (n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {
  9838. mg_iobuf_del(&tls->send, 0, (size_t) n);
  9839. }
  9840. if (n == MG_IO_ERR || n == MG_IO_WAIT) return n;
  9841. return (long) len;
  9842. }
  9843. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9844. int r = 0;
  9845. struct tls_data *tls = (struct tls_data *) c->tls;
  9846. size_t minlen;
  9847. r = mg_tls_recv_record(c);
  9848. if (r < 0) {
  9849. return r;
  9850. }
  9851. if (tls->content_type != MG_TLS_APP_DATA) {
  9852. tls->recv.len = 0;
  9853. mg_tls_drop_record(c);
  9854. return MG_IO_WAIT;
  9855. }
  9856. minlen = len < tls->recv.len ? len : tls->recv.len;
  9857. memmove(buf, tls->recv.buf, minlen);
  9858. tls->recv.buf += minlen;
  9859. tls->recv.len -= minlen;
  9860. if (tls->recv.len == 0) {
  9861. mg_tls_drop_record(c);
  9862. }
  9863. return (long) minlen;
  9864. }
  9865. size_t mg_tls_pending(struct mg_connection *c) {
  9866. return mg_tls_got_record(c) ? 1 : 0;
  9867. }
  9868. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9869. (void) mgr;
  9870. }
  9871. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9872. (void) mgr;
  9873. }
  9874. #endif
  9875. #ifdef MG_ENABLE_LINES
  9876. #line 1 "src/tls_dummy.c"
  9877. #endif
  9878. #if MG_TLS == MG_TLS_NONE
  9879. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9880. (void) opts;
  9881. mg_error(c, "TLS is not enabled");
  9882. }
  9883. void mg_tls_handshake(struct mg_connection *c) {
  9884. (void) c;
  9885. }
  9886. void mg_tls_free(struct mg_connection *c) {
  9887. (void) c;
  9888. }
  9889. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9890. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  9891. }
  9892. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9893. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  9894. }
  9895. size_t mg_tls_pending(struct mg_connection *c) {
  9896. (void) c;
  9897. return 0;
  9898. }
  9899. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9900. (void) mgr;
  9901. }
  9902. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9903. (void) mgr;
  9904. }
  9905. #endif
  9906. #ifdef MG_ENABLE_LINES
  9907. #line 1 "src/tls_mbed.c"
  9908. #endif
  9909. #if MG_TLS == MG_TLS_MBED
  9910. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000
  9911. #define MG_MBEDTLS_RNG_GET , mg_mbed_rng, NULL
  9912. #else
  9913. #define MG_MBEDTLS_RNG_GET
  9914. #endif
  9915. static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) {
  9916. mg_random(buf, len);
  9917. (void) ctx;
  9918. return 0;
  9919. }
  9920. static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *p) {
  9921. int rc;
  9922. if (str.buf == NULL || str.buf[0] == '\0' || str.buf[0] == '*') return true;
  9923. if (str.buf[0] == '-') str.len++; // PEM, include trailing NUL
  9924. if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.buf, str.len)) != 0) {
  9925. MG_ERROR(("cert err %#x", -rc));
  9926. return false;
  9927. }
  9928. return true;
  9929. }
  9930. static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) {
  9931. int rc;
  9932. if (str.buf == NULL || str.buf[0] == '\0' || str.buf[0] == '*') return true;
  9933. if (str.buf[0] == '-') str.len++; // PEM, include trailing NUL
  9934. if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.buf, str.len, NULL,
  9935. 0 MG_MBEDTLS_RNG_GET)) != 0) {
  9936. MG_ERROR(("key err %#x", -rc));
  9937. return false;
  9938. }
  9939. return true;
  9940. }
  9941. void mg_tls_free(struct mg_connection *c) {
  9942. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9943. if (tls != NULL) {
  9944. mbedtls_ssl_free(&tls->ssl);
  9945. mbedtls_pk_free(&tls->pk);
  9946. mbedtls_x509_crt_free(&tls->ca);
  9947. mbedtls_x509_crt_free(&tls->cert);
  9948. mbedtls_ssl_config_free(&tls->conf);
  9949. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  9950. mbedtls_ssl_ticket_free(&tls->ticket);
  9951. #endif
  9952. free(tls);
  9953. c->tls = NULL;
  9954. }
  9955. }
  9956. static int mg_net_send(void *ctx, const unsigned char *buf, size_t len) {
  9957. long n = mg_io_send((struct mg_connection *) ctx, buf, len);
  9958. MG_VERBOSE(("%lu n=%ld e=%d", ((struct mg_connection *) ctx)->id, n, errno));
  9959. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  9960. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  9961. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_SEND_FAILED;
  9962. return (int) n;
  9963. }
  9964. static int mg_net_recv(void *ctx, unsigned char *buf, size_t len) {
  9965. long n = mg_io_recv((struct mg_connection *) ctx, buf, len);
  9966. MG_VERBOSE(("%lu n=%ld", ((struct mg_connection *) ctx)->id, n));
  9967. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  9968. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  9969. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_RECV_FAILED;
  9970. return (int) n;
  9971. }
  9972. void mg_tls_handshake(struct mg_connection *c) {
  9973. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9974. int rc = mbedtls_ssl_handshake(&tls->ssl);
  9975. if (rc == 0) { // Success
  9976. MG_DEBUG(("%lu success", c->id));
  9977. c->is_tls_hs = 0;
  9978. mg_call(c, MG_EV_TLS_HS, NULL);
  9979. } else if (rc == MBEDTLS_ERR_SSL_WANT_READ ||
  9980. rc == MBEDTLS_ERR_SSL_WANT_WRITE) { // Still pending
  9981. MG_VERBOSE(("%lu pending, %d%d %d (-%#x)", c->id, c->is_connecting,
  9982. c->is_tls_hs, rc, -rc));
  9983. } else {
  9984. mg_error(c, "TLS handshake: -%#x", -rc); // Error
  9985. }
  9986. }
  9987. static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) {
  9988. n = (int) strlen(s2) - 1;
  9989. MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2));
  9990. (void) s;
  9991. }
  9992. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9993. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  9994. int rc = 0;
  9995. c->tls = tls;
  9996. if (c->tls == NULL) {
  9997. mg_error(c, "TLS OOM");
  9998. goto fail;
  9999. }
  10000. if (c->is_listening) goto fail;
  10001. MG_DEBUG(("%lu Setting TLS", c->id));
  10002. MG_PROF_ADD(c, "mbedtls_init_start");
  10003. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000 && \
  10004. defined(MBEDTLS_PSA_CRYPTO_C)
  10005. psa_crypto_init(); // https://github.com/Mbed-TLS/mbedtls/issues/9072#issuecomment-2084845711
  10006. #endif
  10007. mbedtls_ssl_init(&tls->ssl);
  10008. mbedtls_ssl_config_init(&tls->conf);
  10009. mbedtls_x509_crt_init(&tls->ca);
  10010. mbedtls_x509_crt_init(&tls->cert);
  10011. mbedtls_pk_init(&tls->pk);
  10012. mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c);
  10013. #if defined(MG_MBEDTLS_DEBUG_LEVEL)
  10014. mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL);
  10015. #endif
  10016. if ((rc = mbedtls_ssl_config_defaults(
  10017. &tls->conf,
  10018. c->is_client ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
  10019. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  10020. mg_error(c, "tls defaults %#x", -rc);
  10021. goto fail;
  10022. }
  10023. mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c);
  10024. if (opts->ca.len == 0 || mg_strcmp(opts->ca, mg_str("*")) == 0) {
  10025. // NOTE: MBEDTLS_SSL_VERIFY_NONE is not supported for TLS1.3 on client side
  10026. // See https://github.com/Mbed-TLS/mbedtls/issues/7075
  10027. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
  10028. } else {
  10029. if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail;
  10030. mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL);
  10031. if (c->is_client && opts->name.buf != NULL && opts->name.buf[0] != '\0') {
  10032. char *host = mg_mprintf("%.*s", opts->name.len, opts->name.buf);
  10033. mbedtls_ssl_set_hostname(&tls->ssl, host);
  10034. MG_DEBUG(("%lu hostname verification: %s", c->id, host));
  10035. free(host);
  10036. }
  10037. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  10038. }
  10039. if (!mg_load_cert(opts->cert, &tls->cert)) goto fail;
  10040. if (!mg_load_key(opts->key, &tls->pk)) goto fail;
  10041. if (tls->cert.version &&
  10042. (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) {
  10043. mg_error(c, "own cert %#x", -rc);
  10044. goto fail;
  10045. }
  10046. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  10047. mbedtls_ssl_conf_session_tickets_cb(
  10048. &tls->conf, mbedtls_ssl_ticket_write, mbedtls_ssl_ticket_parse,
  10049. &((struct mg_tls_ctx *) c->mgr->tls_ctx)->tickets);
  10050. #endif
  10051. if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) {
  10052. mg_error(c, "setup err %#x", -rc);
  10053. goto fail;
  10054. }
  10055. c->is_tls = 1;
  10056. c->is_tls_hs = 1;
  10057. mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0);
  10058. MG_PROF_ADD(c, "mbedtls_init_end");
  10059. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  10060. mg_tls_handshake(c);
  10061. }
  10062. return;
  10063. fail:
  10064. mg_tls_free(c);
  10065. }
  10066. size_t mg_tls_pending(struct mg_connection *c) {
  10067. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10068. return tls == NULL ? 0 : mbedtls_ssl_get_bytes_avail(&tls->ssl);
  10069. }
  10070. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  10071. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10072. long n = mbedtls_ssl_read(&tls->ssl, (unsigned char *) buf, len);
  10073. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  10074. return MG_IO_WAIT;
  10075. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  10076. if (n == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) {
  10077. return MG_IO_WAIT;
  10078. }
  10079. #endif
  10080. if (n <= 0) return MG_IO_ERR;
  10081. return n;
  10082. }
  10083. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  10084. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10085. long n = mbedtls_ssl_write(&tls->ssl, (unsigned char *) buf, len);
  10086. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  10087. return MG_IO_WAIT;
  10088. if (n <= 0) return MG_IO_ERR;
  10089. return n;
  10090. }
  10091. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  10092. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx));
  10093. if (ctx == NULL) {
  10094. MG_ERROR(("TLS context init OOM"));
  10095. } else {
  10096. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  10097. int rc;
  10098. mbedtls_ssl_ticket_init(&ctx->tickets);
  10099. if ((rc = mbedtls_ssl_ticket_setup(&ctx->tickets, mg_mbed_rng, NULL,
  10100. MBEDTLS_CIPHER_AES_128_GCM, 86400)) !=
  10101. 0) {
  10102. MG_ERROR((" mbedtls_ssl_ticket_setup %#x", -rc));
  10103. }
  10104. #endif
  10105. mgr->tls_ctx = ctx;
  10106. }
  10107. }
  10108. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  10109. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx;
  10110. if (ctx != NULL) {
  10111. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  10112. mbedtls_ssl_ticket_free(&ctx->tickets);
  10113. #endif
  10114. free(ctx);
  10115. mgr->tls_ctx = NULL;
  10116. }
  10117. }
  10118. #endif
  10119. #ifdef MG_ENABLE_LINES
  10120. #line 1 "src/tls_openssl.c"
  10121. #endif
  10122. #if MG_TLS == MG_TLS_OPENSSL || MG_TLS == MG_TLS_WOLFSSL
  10123. static int tls_err_cb(const char *s, size_t len, void *c) {
  10124. int n = (int) len - 1;
  10125. MG_ERROR(("%lu %.*s", ((struct mg_connection *) c)->id, n, s));
  10126. return 0; // undocumented
  10127. }
  10128. static int mg_tls_err(struct mg_connection *c, struct mg_tls *tls, int res) {
  10129. int err = SSL_get_error(tls->ssl, res);
  10130. // We've just fetched the last error from the queue.
  10131. // Now we need to clear the error queue. If we do not, then the following
  10132. // can happen (actually reported):
  10133. // - A new connection is accept()-ed with cert error (e.g. self-signed cert)
  10134. // - Since all accept()-ed connections share listener's context,
  10135. // - *ALL* SSL accepted connection report read error on the next poll cycle.
  10136. // Thus a single errored connection can close all the rest, unrelated ones.
  10137. // Clearing the error keeps the shared SSL_CTX in an OK state.
  10138. if (err != 0) ERR_print_errors_cb(tls_err_cb, c);
  10139. ERR_clear_error();
  10140. if (err == SSL_ERROR_WANT_READ) return 0;
  10141. if (err == SSL_ERROR_WANT_WRITE) return 0;
  10142. return err;
  10143. }
  10144. static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) {
  10145. BIO *bio = BIO_new_mem_buf(ca.buf, (int) ca.len);
  10146. STACK_OF(X509_INFO) *certs =
  10147. bio ? PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL) : NULL;
  10148. if (bio) BIO_free(bio);
  10149. return certs;
  10150. }
  10151. static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) {
  10152. X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx);
  10153. for (int i = 0; i < sk_X509_INFO_num(certs); i++) {
  10154. X509_INFO *cert_info = sk_X509_INFO_value(certs, i);
  10155. if (cert_info->x509 && !X509_STORE_add_cert(cert_store, cert_info->x509))
  10156. return false;
  10157. }
  10158. return true;
  10159. }
  10160. static EVP_PKEY *load_key(struct mg_str s) {
  10161. BIO *bio = BIO_new_mem_buf(s.buf, (int) (long) s.len);
  10162. EVP_PKEY *key = bio ? PEM_read_bio_PrivateKey(bio, NULL, 0, NULL) : NULL;
  10163. if (bio) BIO_free(bio);
  10164. return key;
  10165. }
  10166. static X509 *load_cert(struct mg_str s) {
  10167. BIO *bio = BIO_new_mem_buf(s.buf, (int) (long) s.len);
  10168. X509 *cert = bio == NULL ? NULL
  10169. : s.buf[0] == '-'
  10170. ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM
  10171. : d2i_X509_bio(bio, NULL); // DER
  10172. if (bio) BIO_free(bio);
  10173. return cert;
  10174. }
  10175. static long mg_bio_ctrl(BIO *b, int cmd, long larg, void *pargs) {
  10176. long ret = 0;
  10177. if (cmd == BIO_CTRL_PUSH) ret = 1;
  10178. if (cmd == BIO_CTRL_POP) ret = 1;
  10179. if (cmd == BIO_CTRL_FLUSH) ret = 1;
  10180. #if MG_TLS == MG_TLS_OPENSSL
  10181. if (cmd == BIO_C_SET_NBIO) ret = 1;
  10182. #endif
  10183. // MG_DEBUG(("%d -> %ld", cmd, ret));
  10184. (void) b, (void) cmd, (void) larg, (void) pargs;
  10185. return ret;
  10186. }
  10187. static int mg_bio_read(BIO *bio, char *buf, int len) {
  10188. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  10189. long res = mg_io_recv(c, buf, (size_t) len);
  10190. // MG_DEBUG(("%p %d %ld", buf, len, res));
  10191. len = res > 0 ? (int) res : -1;
  10192. if (res == MG_IO_WAIT) BIO_set_retry_read(bio);
  10193. return len;
  10194. }
  10195. static int mg_bio_write(BIO *bio, const char *buf, int len) {
  10196. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  10197. long res = mg_io_send(c, buf, (size_t) len);
  10198. // MG_DEBUG(("%p %d %ld", buf, len, res));
  10199. len = res > 0 ? (int) res : -1;
  10200. if (res == MG_IO_WAIT) BIO_set_retry_write(bio);
  10201. return len;
  10202. }
  10203. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  10204. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  10205. const char *id = "mongoose";
  10206. static unsigned char s_initialised = 0;
  10207. BIO *bio = NULL;
  10208. int rc;
  10209. if (tls == NULL) {
  10210. mg_error(c, "TLS OOM");
  10211. goto fail;
  10212. }
  10213. if (!s_initialised) {
  10214. #if (CHIP_TYPE != CHIP_T113s)
  10215. SSL_library_init();
  10216. #else
  10217. //OPENSSL_init_ssl(0, NULL);
  10218. #endif
  10219. s_initialised++;
  10220. }
  10221. MG_DEBUG(("%lu Setting TLS", c->id));
  10222. tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method())
  10223. : SSL_CTX_new(SSLv23_server_method());
  10224. if ((tls->ssl = SSL_new(tls->ctx)) == NULL) {
  10225. mg_error(c, "SSL_new");
  10226. goto fail;
  10227. }
  10228. SSL_set_session_id_context(tls->ssl, (const uint8_t *) id,
  10229. (unsigned) strlen(id));
  10230. // Disable deprecated protocols
  10231. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2);
  10232. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3);
  10233. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1);
  10234. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1);
  10235. #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION
  10236. SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION);
  10237. #endif
  10238. #ifdef MG_ENABLE_OPENSSL_CIPHER_SERVER_PREFERENCE
  10239. SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10240. #endif
  10241. #if MG_TLS == MG_TLS_WOLFSSL && !defined(OPENSSL_COMPATIBLE_DEFAULTS)
  10242. if (opts->ca.len == 0 || mg_strcmp(opts->ca, mg_str("*")) == 0) {
  10243. // Older versions require that either the CA is loaded or SSL_VERIFY_NONE
  10244. // explicitly set
  10245. SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, NULL);
  10246. }
  10247. #endif
  10248. if (opts->ca.buf != NULL && opts->ca.buf[0] != '\0') {
  10249. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10250. NULL);
  10251. STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca);
  10252. rc = add_ca_certs(tls->ctx, certs);
  10253. sk_X509_INFO_pop_free(certs, X509_INFO_free);
  10254. if (!rc) {
  10255. mg_error(c, "CA err");
  10256. goto fail;
  10257. }
  10258. }
  10259. if (opts->cert.buf != NULL && opts->cert.buf[0] != '\0') {
  10260. X509 *cert = load_cert(opts->cert);
  10261. rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert);
  10262. X509_free(cert);
  10263. if (cert == NULL || rc != 1) {
  10264. mg_error(c, "CERT err %d", mg_tls_err(c, tls, rc));
  10265. goto fail;
  10266. }
  10267. }
  10268. if (opts->key.buf != NULL && opts->key.buf[0] != '\0') {
  10269. EVP_PKEY *key = load_key(opts->key);
  10270. rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key);
  10271. EVP_PKEY_free(key);
  10272. if (key == NULL || rc != 1) {
  10273. mg_error(c, "KEY err %d", mg_tls_err(c, tls, rc));
  10274. goto fail;
  10275. }
  10276. }
  10277. SSL_set_mode(tls->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  10278. #if MG_TLS == MG_TLS_OPENSSL && OPENSSL_VERSION_NUMBER > 0x10002000L
  10279. #if (CHIP_TYPE != CHIP_T113s)
  10280. (void) SSL_set_ecdh_auto(tls->ssl, 1);
  10281. #endif
  10282. #endif
  10283. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  10284. if (opts->name.len > 0) {
  10285. char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.buf);
  10286. #if MG_TLS != MG_TLS_WOLFSSL || LIBWOLFSSL_VERSION_HEX >= 0x05005002
  10287. SSL_set1_host(tls->ssl, s);
  10288. #else
  10289. X509_VERIFY_PARAM_set1_host(SSL_get0_param(tls->ssl), s, 0);
  10290. #endif
  10291. SSL_set_tlsext_host_name(tls->ssl, s);
  10292. free(s);
  10293. }
  10294. #endif
  10295. #if MG_TLS == MG_TLS_WOLFSSL
  10296. tls->bm = BIO_meth_new(0, "bio_mg");
  10297. #else
  10298. tls->bm = BIO_meth_new(BIO_get_new_index() | BIO_TYPE_SOURCE_SINK, "bio_mg");
  10299. #endif
  10300. BIO_meth_set_write(tls->bm, mg_bio_write);
  10301. BIO_meth_set_read(tls->bm, mg_bio_read);
  10302. BIO_meth_set_ctrl(tls->bm, mg_bio_ctrl);
  10303. bio = BIO_new(tls->bm);
  10304. BIO_set_data(bio, c);
  10305. SSL_set_bio(tls->ssl, bio, bio);
  10306. c->tls = tls;
  10307. c->is_tls = 1;
  10308. c->is_tls_hs = 1;
  10309. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  10310. mg_tls_handshake(c);
  10311. }
  10312. MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client"));
  10313. return;
  10314. fail:
  10315. free(tls);
  10316. }
  10317. void mg_tls_handshake(struct mg_connection *c) {
  10318. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10319. int rc = c->is_client ? SSL_connect(tls->ssl) : SSL_accept(tls->ssl);
  10320. if (rc == 1) {
  10321. MG_DEBUG(("%lu success", c->id));
  10322. c->is_tls_hs = 0;
  10323. mg_call(c, MG_EV_TLS_HS, NULL);
  10324. } else {
  10325. int code = mg_tls_err(c, tls, rc);
  10326. if (code != 0) mg_error(c, "tls hs: rc %d, err %d", rc, code);
  10327. }
  10328. }
  10329. void mg_tls_free(struct mg_connection *c) {
  10330. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10331. if (tls == NULL) return;
  10332. SSL_free(tls->ssl);
  10333. SSL_CTX_free(tls->ctx);
  10334. BIO_meth_free(tls->bm);
  10335. free(tls);
  10336. c->tls = NULL;
  10337. }
  10338. size_t mg_tls_pending(struct mg_connection *c) {
  10339. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10340. return tls == NULL ? 0 : (size_t) SSL_pending(tls->ssl);
  10341. }
  10342. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  10343. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10344. int n = SSL_read(tls->ssl, buf, (int) len);
  10345. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  10346. if (n <= 0) return MG_IO_ERR;
  10347. return n;
  10348. }
  10349. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  10350. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10351. int n = SSL_write(tls->ssl, buf, (int) len);
  10352. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  10353. if (n <= 0) return MG_IO_ERR;
  10354. return n;
  10355. }
  10356. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  10357. (void) mgr;
  10358. }
  10359. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  10360. (void) mgr;
  10361. }
  10362. #endif
  10363. #ifdef MG_ENABLE_LINES
  10364. #line 1 "src/tls_uecc.c"
  10365. #endif
  10366. /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  10367. #if MG_TLS == MG_TLS_BUILTIN
  10368. #ifndef MG_UECC_RNG_MAX_TRIES
  10369. #define MG_UECC_RNG_MAX_TRIES 64
  10370. #endif
  10371. #if MG_UECC_ENABLE_VLI_API
  10372. #define MG_UECC_VLI_API
  10373. #else
  10374. #define MG_UECC_VLI_API static
  10375. #endif
  10376. #if (MG_UECC_PLATFORM == mg_uecc_avr) || (MG_UECC_PLATFORM == mg_uecc_arm) || \
  10377. (MG_UECC_PLATFORM == mg_uecc_arm_thumb) || \
  10378. (MG_UECC_PLATFORM == mg_uecc_arm_thumb2)
  10379. #define CONCATX(a, ...) a##__VA_ARGS__
  10380. #define CONCAT(a, ...) CONCATX(a, __VA_ARGS__)
  10381. #define STRX(a) #a
  10382. #define STR(a) STRX(a)
  10383. #define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__))))
  10384. #define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__))))
  10385. #define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__))))
  10386. #define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__))))
  10387. #define EVAL4(...) __VA_ARGS__
  10388. #define DEC_1 0
  10389. #define DEC_2 1
  10390. #define DEC_3 2
  10391. #define DEC_4 3
  10392. #define DEC_5 4
  10393. #define DEC_6 5
  10394. #define DEC_7 6
  10395. #define DEC_8 7
  10396. #define DEC_9 8
  10397. #define DEC_10 9
  10398. #define DEC_11 10
  10399. #define DEC_12 11
  10400. #define DEC_13 12
  10401. #define DEC_14 13
  10402. #define DEC_15 14
  10403. #define DEC_16 15
  10404. #define DEC_17 16
  10405. #define DEC_18 17
  10406. #define DEC_19 18
  10407. #define DEC_20 19
  10408. #define DEC_21 20
  10409. #define DEC_22 21
  10410. #define DEC_23 22
  10411. #define DEC_24 23
  10412. #define DEC_25 24
  10413. #define DEC_26 25
  10414. #define DEC_27 26
  10415. #define DEC_28 27
  10416. #define DEC_29 28
  10417. #define DEC_30 29
  10418. #define DEC_31 30
  10419. #define DEC_32 31
  10420. #define DEC(N) CONCAT(DEC_, N)
  10421. #define SECOND_ARG(_, val, ...) val
  10422. #define SOME_CHECK_0 ~, 0
  10423. #define GET_SECOND_ARG(...) SECOND_ARG(__VA_ARGS__, SOME, )
  10424. #define SOME_OR_0(N) GET_SECOND_ARG(CONCAT(SOME_CHECK_, N))
  10425. #define EMPTY(...)
  10426. #define DEFER(...) __VA_ARGS__ EMPTY()
  10427. #define REPEAT_NAME_0() REPEAT_0
  10428. #define REPEAT_NAME_SOME() REPEAT_SOME
  10429. #define REPEAT_0(...)
  10430. #define REPEAT_SOME(N, stuff) \
  10431. DEFER(CONCAT(REPEAT_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), stuff) stuff
  10432. #define REPEAT(N, stuff) EVAL(REPEAT_SOME(N, stuff))
  10433. #define REPEATM_NAME_0() REPEATM_0
  10434. #define REPEATM_NAME_SOME() REPEATM_SOME
  10435. #define REPEATM_0(...)
  10436. #define REPEATM_SOME(N, macro) \
  10437. macro(N) DEFER(CONCAT(REPEATM_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), macro)
  10438. #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro))
  10439. #endif
  10440. //
  10441. #if (MG_UECC_WORD_SIZE == 1)
  10442. #if MG_UECC_SUPPORTS_secp160r1
  10443. #define MG_UECC_MAX_WORDS 21 /* Due to the size of curve_n. */
  10444. #endif
  10445. #if MG_UECC_SUPPORTS_secp192r1
  10446. #undef MG_UECC_MAX_WORDS
  10447. #define MG_UECC_MAX_WORDS 24
  10448. #endif
  10449. #if MG_UECC_SUPPORTS_secp224r1
  10450. #undef MG_UECC_MAX_WORDS
  10451. #define MG_UECC_MAX_WORDS 28
  10452. #endif
  10453. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10454. #undef MG_UECC_MAX_WORDS
  10455. #define MG_UECC_MAX_WORDS 32
  10456. #endif
  10457. #elif (MG_UECC_WORD_SIZE == 4)
  10458. #if MG_UECC_SUPPORTS_secp160r1
  10459. #define MG_UECC_MAX_WORDS 6 /* Due to the size of curve_n. */
  10460. #endif
  10461. #if MG_UECC_SUPPORTS_secp192r1
  10462. #undef MG_UECC_MAX_WORDS
  10463. #define MG_UECC_MAX_WORDS 6
  10464. #endif
  10465. #if MG_UECC_SUPPORTS_secp224r1
  10466. #undef MG_UECC_MAX_WORDS
  10467. #define MG_UECC_MAX_WORDS 7
  10468. #endif
  10469. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10470. #undef MG_UECC_MAX_WORDS
  10471. #define MG_UECC_MAX_WORDS 8
  10472. #endif
  10473. #elif (MG_UECC_WORD_SIZE == 8)
  10474. #if MG_UECC_SUPPORTS_secp160r1
  10475. #define MG_UECC_MAX_WORDS 3
  10476. #endif
  10477. #if MG_UECC_SUPPORTS_secp192r1
  10478. #undef MG_UECC_MAX_WORDS
  10479. #define MG_UECC_MAX_WORDS 3
  10480. #endif
  10481. #if MG_UECC_SUPPORTS_secp224r1
  10482. #undef MG_UECC_MAX_WORDS
  10483. #define MG_UECC_MAX_WORDS 4
  10484. #endif
  10485. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10486. #undef MG_UECC_MAX_WORDS
  10487. #define MG_UECC_MAX_WORDS 4
  10488. #endif
  10489. #endif /* MG_UECC_WORD_SIZE */
  10490. #define BITS_TO_WORDS(num_bits) \
  10491. ((wordcount_t) ((num_bits + ((MG_UECC_WORD_SIZE * 8) - 1)) / \
  10492. (MG_UECC_WORD_SIZE * 8)))
  10493. #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
  10494. struct MG_UECC_Curve_t {
  10495. wordcount_t num_words;
  10496. wordcount_t num_bytes;
  10497. bitcount_t num_n_bits;
  10498. mg_uecc_word_t p[MG_UECC_MAX_WORDS];
  10499. mg_uecc_word_t n[MG_UECC_MAX_WORDS];
  10500. mg_uecc_word_t G[MG_UECC_MAX_WORDS * 2];
  10501. mg_uecc_word_t b[MG_UECC_MAX_WORDS];
  10502. void (*double_jacobian)(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  10503. mg_uecc_word_t *Z1, MG_UECC_Curve curve);
  10504. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  10505. void (*mod_sqrt)(mg_uecc_word_t *a, MG_UECC_Curve curve);
  10506. #endif
  10507. void (*x_side)(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  10508. MG_UECC_Curve curve);
  10509. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10510. void (*mmod_fast)(mg_uecc_word_t *result, mg_uecc_word_t *product);
  10511. #endif
  10512. };
  10513. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  10514. static void bcopy(uint8_t *dst, const uint8_t *src, unsigned num_bytes) {
  10515. while (0 != num_bytes) {
  10516. num_bytes--;
  10517. dst[num_bytes] = src[num_bytes];
  10518. }
  10519. }
  10520. #endif
  10521. static cmpresult_t mg_uecc_vli_cmp_unsafe(const mg_uecc_word_t *left,
  10522. const mg_uecc_word_t *right,
  10523. wordcount_t num_words);
  10524. #if (MG_UECC_PLATFORM == mg_uecc_arm || \
  10525. MG_UECC_PLATFORM == mg_uecc_arm_thumb || \
  10526. MG_UECC_PLATFORM == mg_uecc_arm_thumb2)
  10527. #endif
  10528. #if (MG_UECC_PLATFORM == mg_uecc_avr)
  10529. #endif
  10530. #ifndef asm_clear
  10531. #define asm_clear 0
  10532. #endif
  10533. #ifndef asm_set
  10534. #define asm_set 0
  10535. #endif
  10536. #ifndef asm_add
  10537. #define asm_add 0
  10538. #endif
  10539. #ifndef asm_sub
  10540. #define asm_sub 0
  10541. #endif
  10542. #ifndef asm_mult
  10543. #define asm_mult 0
  10544. #endif
  10545. #ifndef asm_rshift1
  10546. #define asm_rshift1 0
  10547. #endif
  10548. #ifndef asm_mmod_fast_secp256r1
  10549. #define asm_mmod_fast_secp256r1 0
  10550. #endif
  10551. #if defined(default_RNG_defined) && default_RNG_defined
  10552. static MG_UECC_RNG_Function g_rng_function = &default_RNG;
  10553. #else
  10554. static MG_UECC_RNG_Function g_rng_function = 0;
  10555. #endif
  10556. void mg_uecc_set_rng(MG_UECC_RNG_Function rng_function) {
  10557. g_rng_function = rng_function;
  10558. }
  10559. MG_UECC_RNG_Function mg_uecc_get_rng(void) {
  10560. return g_rng_function;
  10561. }
  10562. int mg_uecc_curve_private_key_size(MG_UECC_Curve curve) {
  10563. return BITS_TO_BYTES(curve->num_n_bits);
  10564. }
  10565. int mg_uecc_curve_public_key_size(MG_UECC_Curve curve) {
  10566. return 2 * curve->num_bytes;
  10567. }
  10568. #if !asm_clear
  10569. MG_UECC_VLI_API void mg_uecc_vli_clear(mg_uecc_word_t *vli,
  10570. wordcount_t num_words) {
  10571. wordcount_t i;
  10572. for (i = 0; i < num_words; ++i) {
  10573. vli[i] = 0;
  10574. }
  10575. }
  10576. #endif /* !asm_clear */
  10577. /* Constant-time comparison to zero - secure way to compare long integers */
  10578. /* Returns 1 if vli == 0, 0 otherwise. */
  10579. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_isZero(const mg_uecc_word_t *vli,
  10580. wordcount_t num_words) {
  10581. mg_uecc_word_t bits = 0;
  10582. wordcount_t i;
  10583. for (i = 0; i < num_words; ++i) {
  10584. bits |= vli[i];
  10585. }
  10586. return (bits == 0);
  10587. }
  10588. /* Returns nonzero if bit 'bit' of vli is set. */
  10589. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_testBit(const mg_uecc_word_t *vli,
  10590. bitcount_t bit) {
  10591. return (vli[bit >> MG_UECC_WORD_BITS_SHIFT] &
  10592. ((mg_uecc_word_t) 1 << (bit & MG_UECC_WORD_BITS_MASK)));
  10593. }
  10594. /* Counts the number of words in vli. */
  10595. static wordcount_t vli_numDigits(const mg_uecc_word_t *vli,
  10596. const wordcount_t max_words) {
  10597. wordcount_t i;
  10598. /* Search from the end until we find a non-zero digit.
  10599. We do it in reverse because we expect that most digits will be nonzero. */
  10600. for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
  10601. }
  10602. return (i + 1);
  10603. }
  10604. /* Counts the number of bits required to represent vli. */
  10605. MG_UECC_VLI_API bitcount_t mg_uecc_vli_numBits(const mg_uecc_word_t *vli,
  10606. const wordcount_t max_words) {
  10607. mg_uecc_word_t i;
  10608. mg_uecc_word_t digit;
  10609. wordcount_t num_digits = vli_numDigits(vli, max_words);
  10610. if (num_digits == 0) {
  10611. return 0;
  10612. }
  10613. digit = vli[num_digits - 1];
  10614. for (i = 0; digit; ++i) {
  10615. digit >>= 1;
  10616. }
  10617. return (((bitcount_t) ((num_digits - 1) << MG_UECC_WORD_BITS_SHIFT)) +
  10618. (bitcount_t) i);
  10619. }
  10620. /* Sets dest = src. */
  10621. #if !asm_set
  10622. MG_UECC_VLI_API void mg_uecc_vli_set(mg_uecc_word_t *dest,
  10623. const mg_uecc_word_t *src,
  10624. wordcount_t num_words) {
  10625. wordcount_t i;
  10626. for (i = 0; i < num_words; ++i) {
  10627. dest[i] = src[i];
  10628. }
  10629. }
  10630. #endif /* !asm_set */
  10631. /* Returns sign of left - right. */
  10632. static cmpresult_t mg_uecc_vli_cmp_unsafe(const mg_uecc_word_t *left,
  10633. const mg_uecc_word_t *right,
  10634. wordcount_t num_words) {
  10635. wordcount_t i;
  10636. for (i = num_words - 1; i >= 0; --i) {
  10637. if (left[i] > right[i]) {
  10638. return 1;
  10639. } else if (left[i] < right[i]) {
  10640. return -1;
  10641. }
  10642. }
  10643. return 0;
  10644. }
  10645. /* Constant-time comparison function - secure way to compare long integers */
  10646. /* Returns one if left == right, zero otherwise. */
  10647. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_equal(const mg_uecc_word_t *left,
  10648. const mg_uecc_word_t *right,
  10649. wordcount_t num_words) {
  10650. mg_uecc_word_t diff = 0;
  10651. wordcount_t i;
  10652. for (i = num_words - 1; i >= 0; --i) {
  10653. diff |= (left[i] ^ right[i]);
  10654. }
  10655. return (diff == 0);
  10656. }
  10657. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_sub(mg_uecc_word_t *result,
  10658. const mg_uecc_word_t *left,
  10659. const mg_uecc_word_t *right,
  10660. wordcount_t num_words);
  10661. /* Returns sign of left - right, in constant time. */
  10662. MG_UECC_VLI_API cmpresult_t mg_uecc_vli_cmp(const mg_uecc_word_t *left,
  10663. const mg_uecc_word_t *right,
  10664. wordcount_t num_words) {
  10665. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  10666. mg_uecc_word_t neg = !!mg_uecc_vli_sub(tmp, left, right, num_words);
  10667. mg_uecc_word_t equal = mg_uecc_vli_isZero(tmp, num_words);
  10668. return (cmpresult_t) (!equal - 2 * neg);
  10669. }
  10670. /* Computes vli = vli >> 1. */
  10671. #if !asm_rshift1
  10672. MG_UECC_VLI_API void mg_uecc_vli_rshift1(mg_uecc_word_t *vli,
  10673. wordcount_t num_words) {
  10674. mg_uecc_word_t *end = vli;
  10675. mg_uecc_word_t carry = 0;
  10676. vli += num_words;
  10677. while (vli-- > end) {
  10678. mg_uecc_word_t temp = *vli;
  10679. *vli = (temp >> 1) | carry;
  10680. carry = temp << (MG_UECC_WORD_BITS - 1);
  10681. }
  10682. }
  10683. #endif /* !asm_rshift1 */
  10684. /* Computes result = left + right, returning carry. Can modify in place. */
  10685. #if !asm_add
  10686. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_add(mg_uecc_word_t *result,
  10687. const mg_uecc_word_t *left,
  10688. const mg_uecc_word_t *right,
  10689. wordcount_t num_words) {
  10690. mg_uecc_word_t carry = 0;
  10691. wordcount_t i;
  10692. for (i = 0; i < num_words; ++i) {
  10693. mg_uecc_word_t sum = left[i] + right[i] + carry;
  10694. if (sum != left[i]) {
  10695. carry = (sum < left[i]);
  10696. }
  10697. result[i] = sum;
  10698. }
  10699. return carry;
  10700. }
  10701. #endif /* !asm_add */
  10702. /* Computes result = left - right, returning borrow. Can modify in place. */
  10703. #if !asm_sub
  10704. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_sub(mg_uecc_word_t *result,
  10705. const mg_uecc_word_t *left,
  10706. const mg_uecc_word_t *right,
  10707. wordcount_t num_words) {
  10708. mg_uecc_word_t borrow = 0;
  10709. wordcount_t i;
  10710. for (i = 0; i < num_words; ++i) {
  10711. mg_uecc_word_t diff = left[i] - right[i] - borrow;
  10712. if (diff != left[i]) {
  10713. borrow = (diff > left[i]);
  10714. }
  10715. result[i] = diff;
  10716. }
  10717. return borrow;
  10718. }
  10719. #endif /* !asm_sub */
  10720. #if !asm_mult || (MG_UECC_SQUARE_FUNC && !asm_square) || \
  10721. (MG_UECC_SUPPORTS_secp256k1 && (MG_UECC_OPTIMIZATION_LEVEL > 0) && \
  10722. ((MG_UECC_WORD_SIZE == 1) || (MG_UECC_WORD_SIZE == 8)))
  10723. static void muladd(mg_uecc_word_t a, mg_uecc_word_t b, mg_uecc_word_t *r0,
  10724. mg_uecc_word_t *r1, mg_uecc_word_t *r2) {
  10725. #if MG_UECC_WORD_SIZE == 8
  10726. uint64_t a0 = a & 0xffffffff;
  10727. uint64_t a1 = a >> 32;
  10728. uint64_t b0 = b & 0xffffffff;
  10729. uint64_t b1 = b >> 32;
  10730. uint64_t i0 = a0 * b0;
  10731. uint64_t i1 = a0 * b1;
  10732. uint64_t i2 = a1 * b0;
  10733. uint64_t i3 = a1 * b1;
  10734. uint64_t p0, p1;
  10735. i2 += (i0 >> 32);
  10736. i2 += i1;
  10737. if (i2 < i1) { /* overflow */
  10738. i3 += 0x100000000;
  10739. }
  10740. p0 = (i0 & 0xffffffff) | (i2 << 32);
  10741. p1 = i3 + (i2 >> 32);
  10742. *r0 += p0;
  10743. *r1 += (p1 + (*r0 < p0));
  10744. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  10745. #else
  10746. mg_uecc_dword_t p = (mg_uecc_dword_t) a * b;
  10747. mg_uecc_dword_t r01 = ((mg_uecc_dword_t) (*r1) << MG_UECC_WORD_BITS) | *r0;
  10748. r01 += p;
  10749. *r2 += (r01 < p);
  10750. *r1 = (mg_uecc_word_t) (r01 >> MG_UECC_WORD_BITS);
  10751. *r0 = (mg_uecc_word_t) r01;
  10752. #endif
  10753. }
  10754. #endif /* muladd needed */
  10755. #if !asm_mult
  10756. MG_UECC_VLI_API void mg_uecc_vli_mult(mg_uecc_word_t *result,
  10757. const mg_uecc_word_t *left,
  10758. const mg_uecc_word_t *right,
  10759. wordcount_t num_words) {
  10760. mg_uecc_word_t r0 = 0;
  10761. mg_uecc_word_t r1 = 0;
  10762. mg_uecc_word_t r2 = 0;
  10763. wordcount_t i, k;
  10764. /* Compute each digit of result in sequence, maintaining the carries. */
  10765. for (k = 0; k < num_words; ++k) {
  10766. for (i = 0; i <= k; ++i) {
  10767. muladd(left[i], right[k - i], &r0, &r1, &r2);
  10768. }
  10769. result[k] = r0;
  10770. r0 = r1;
  10771. r1 = r2;
  10772. r2 = 0;
  10773. }
  10774. for (k = num_words; k < num_words * 2 - 1; ++k) {
  10775. for (i = (wordcount_t) ((k + 1) - num_words); i < num_words; ++i) {
  10776. muladd(left[i], right[k - i], &r0, &r1, &r2);
  10777. }
  10778. result[k] = r0;
  10779. r0 = r1;
  10780. r1 = r2;
  10781. r2 = 0;
  10782. }
  10783. result[num_words * 2 - 1] = r0;
  10784. }
  10785. #endif /* !asm_mult */
  10786. #if MG_UECC_SQUARE_FUNC
  10787. #if !asm_square
  10788. static void mul2add(mg_uecc_word_t a, mg_uecc_word_t b, mg_uecc_word_t *r0,
  10789. mg_uecc_word_t *r1, mg_uecc_word_t *r2) {
  10790. #if MG_UECC_WORD_SIZE == 8
  10791. uint64_t a0 = a & 0xffffffffull;
  10792. uint64_t a1 = a >> 32;
  10793. uint64_t b0 = b & 0xffffffffull;
  10794. uint64_t b1 = b >> 32;
  10795. uint64_t i0 = a0 * b0;
  10796. uint64_t i1 = a0 * b1;
  10797. uint64_t i2 = a1 * b0;
  10798. uint64_t i3 = a1 * b1;
  10799. uint64_t p0, p1;
  10800. i2 += (i0 >> 32);
  10801. i2 += i1;
  10802. if (i2 < i1) { /* overflow */
  10803. i3 += 0x100000000ull;
  10804. }
  10805. p0 = (i0 & 0xffffffffull) | (i2 << 32);
  10806. p1 = i3 + (i2 >> 32);
  10807. *r2 += (p1 >> 63);
  10808. p1 = (p1 << 1) | (p0 >> 63);
  10809. p0 <<= 1;
  10810. *r0 += p0;
  10811. *r1 += (p1 + (*r0 < p0));
  10812. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  10813. #else
  10814. mg_uecc_dword_t p = (mg_uecc_dword_t) a * b;
  10815. mg_uecc_dword_t r01 = ((mg_uecc_dword_t) (*r1) << MG_UECC_WORD_BITS) | *r0;
  10816. *r2 += (p >> (MG_UECC_WORD_BITS * 2 - 1));
  10817. p *= 2;
  10818. r01 += p;
  10819. *r2 += (r01 < p);
  10820. *r1 = r01 >> MG_UECC_WORD_BITS;
  10821. *r0 = (mg_uecc_word_t) r01;
  10822. #endif
  10823. }
  10824. MG_UECC_VLI_API void mg_uecc_vli_square(mg_uecc_word_t *result,
  10825. const mg_uecc_word_t *left,
  10826. wordcount_t num_words) {
  10827. mg_uecc_word_t r0 = 0;
  10828. mg_uecc_word_t r1 = 0;
  10829. mg_uecc_word_t r2 = 0;
  10830. wordcount_t i, k;
  10831. for (k = 0; k < num_words * 2 - 1; ++k) {
  10832. mg_uecc_word_t min = (k < num_words ? 0 : (k + 1) - num_words);
  10833. for (i = min; i <= k && i <= k - i; ++i) {
  10834. if (i < k - i) {
  10835. mul2add(left[i], left[k - i], &r0, &r1, &r2);
  10836. } else {
  10837. muladd(left[i], left[k - i], &r0, &r1, &r2);
  10838. }
  10839. }
  10840. result[k] = r0;
  10841. r0 = r1;
  10842. r1 = r2;
  10843. r2 = 0;
  10844. }
  10845. result[num_words * 2 - 1] = r0;
  10846. }
  10847. #endif /* !asm_square */
  10848. #else /* MG_UECC_SQUARE_FUNC */
  10849. #if MG_UECC_ENABLE_VLI_API
  10850. MG_UECC_VLI_API void mg_uecc_vli_square(mg_uecc_word_t *result,
  10851. const mg_uecc_word_t *left,
  10852. wordcount_t num_words) {
  10853. mg_uecc_vli_mult(result, left, left, num_words);
  10854. }
  10855. #endif /* MG_UECC_ENABLE_VLI_API */
  10856. #endif /* MG_UECC_SQUARE_FUNC */
  10857. /* Computes result = (left + right) % mod.
  10858. Assumes that left < mod and right < mod, and that result does not overlap
  10859. mod. */
  10860. MG_UECC_VLI_API void mg_uecc_vli_modAdd(mg_uecc_word_t *result,
  10861. const mg_uecc_word_t *left,
  10862. const mg_uecc_word_t *right,
  10863. const mg_uecc_word_t *mod,
  10864. wordcount_t num_words) {
  10865. mg_uecc_word_t carry = mg_uecc_vli_add(result, left, right, num_words);
  10866. if (carry || mg_uecc_vli_cmp_unsafe(mod, result, num_words) != 1) {
  10867. /* result > mod (result = mod + remainder), so subtract mod to get
  10868. * remainder. */
  10869. mg_uecc_vli_sub(result, result, mod, num_words);
  10870. }
  10871. }
  10872. /* Computes result = (left - right) % mod.
  10873. Assumes that left < mod and right < mod, and that result does not overlap
  10874. mod. */
  10875. MG_UECC_VLI_API void mg_uecc_vli_modSub(mg_uecc_word_t *result,
  10876. const mg_uecc_word_t *left,
  10877. const mg_uecc_word_t *right,
  10878. const mg_uecc_word_t *mod,
  10879. wordcount_t num_words) {
  10880. mg_uecc_word_t l_borrow = mg_uecc_vli_sub(result, left, right, num_words);
  10881. if (l_borrow) {
  10882. /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
  10883. we can get the correct result from result + mod (with overflow). */
  10884. mg_uecc_vli_add(result, result, mod, num_words);
  10885. }
  10886. }
  10887. /* Computes result = product % mod, where product is 2N words long. */
  10888. /* Currently only designed to work for curve_p or curve_n. */
  10889. MG_UECC_VLI_API void mg_uecc_vli_mmod(mg_uecc_word_t *result,
  10890. mg_uecc_word_t *product,
  10891. const mg_uecc_word_t *mod,
  10892. wordcount_t num_words) {
  10893. mg_uecc_word_t mod_multiple[2 * MG_UECC_MAX_WORDS];
  10894. mg_uecc_word_t tmp[2 * MG_UECC_MAX_WORDS];
  10895. mg_uecc_word_t *v[2] = {tmp, product};
  10896. mg_uecc_word_t index;
  10897. /* Shift mod so its highest set bit is at the maximum position. */
  10898. bitcount_t shift = (bitcount_t) ((num_words * 2 * MG_UECC_WORD_BITS) -
  10899. mg_uecc_vli_numBits(mod, num_words));
  10900. wordcount_t word_shift = (wordcount_t) (shift / MG_UECC_WORD_BITS);
  10901. wordcount_t bit_shift = (wordcount_t) (shift % MG_UECC_WORD_BITS);
  10902. mg_uecc_word_t carry = 0;
  10903. mg_uecc_vli_clear(mod_multiple, word_shift);
  10904. if (bit_shift > 0) {
  10905. for (index = 0; index < (mg_uecc_word_t) num_words; ++index) {
  10906. mod_multiple[(mg_uecc_word_t) word_shift + index] =
  10907. (mg_uecc_word_t) (mod[index] << bit_shift) | carry;
  10908. carry = mod[index] >> (MG_UECC_WORD_BITS - bit_shift);
  10909. }
  10910. } else {
  10911. mg_uecc_vli_set(mod_multiple + word_shift, mod, num_words);
  10912. }
  10913. for (index = 1; shift >= 0; --shift) {
  10914. mg_uecc_word_t borrow = 0;
  10915. wordcount_t i;
  10916. for (i = 0; i < num_words * 2; ++i) {
  10917. mg_uecc_word_t diff = v[index][i] - mod_multiple[i] - borrow;
  10918. if (diff != v[index][i]) {
  10919. borrow = (diff > v[index][i]);
  10920. }
  10921. v[1 - index][i] = diff;
  10922. }
  10923. index = !(index ^ borrow); /* Swap the index if there was no borrow */
  10924. mg_uecc_vli_rshift1(mod_multiple, num_words);
  10925. mod_multiple[num_words - 1] |= mod_multiple[num_words]
  10926. << (MG_UECC_WORD_BITS - 1);
  10927. mg_uecc_vli_rshift1(mod_multiple + num_words, num_words);
  10928. }
  10929. mg_uecc_vli_set(result, v[index], num_words);
  10930. }
  10931. /* Computes result = (left * right) % mod. */
  10932. MG_UECC_VLI_API void mg_uecc_vli_modMult(mg_uecc_word_t *result,
  10933. const mg_uecc_word_t *left,
  10934. const mg_uecc_word_t *right,
  10935. const mg_uecc_word_t *mod,
  10936. wordcount_t num_words) {
  10937. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10938. mg_uecc_vli_mult(product, left, right, num_words);
  10939. mg_uecc_vli_mmod(result, product, mod, num_words);
  10940. }
  10941. MG_UECC_VLI_API void mg_uecc_vli_modMult_fast(mg_uecc_word_t *result,
  10942. const mg_uecc_word_t *left,
  10943. const mg_uecc_word_t *right,
  10944. MG_UECC_Curve curve) {
  10945. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10946. mg_uecc_vli_mult(product, left, right, curve->num_words);
  10947. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10948. curve->mmod_fast(result, product);
  10949. #else
  10950. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  10951. #endif
  10952. }
  10953. #if MG_UECC_SQUARE_FUNC
  10954. #if MG_UECC_ENABLE_VLI_API
  10955. /* Computes result = left^2 % mod. */
  10956. MG_UECC_VLI_API void mg_uecc_vli_modSquare(mg_uecc_word_t *result,
  10957. const mg_uecc_word_t *left,
  10958. const mg_uecc_word_t *mod,
  10959. wordcount_t num_words) {
  10960. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10961. mg_uecc_vli_square(product, left, num_words);
  10962. mg_uecc_vli_mmod(result, product, mod, num_words);
  10963. }
  10964. #endif /* MG_UECC_ENABLE_VLI_API */
  10965. MG_UECC_VLI_API void mg_uecc_vli_modSquare_fast(mg_uecc_word_t *result,
  10966. const mg_uecc_word_t *left,
  10967. MG_UECC_Curve curve) {
  10968. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10969. mg_uecc_vli_square(product, left, curve->num_words);
  10970. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10971. curve->mmod_fast(result, product);
  10972. #else
  10973. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  10974. #endif
  10975. }
  10976. #else /* MG_UECC_SQUARE_FUNC */
  10977. #if MG_UECC_ENABLE_VLI_API
  10978. MG_UECC_VLI_API void mg_uecc_vli_modSquare(mg_uecc_word_t *result,
  10979. const mg_uecc_word_t *left,
  10980. const mg_uecc_word_t *mod,
  10981. wordcount_t num_words) {
  10982. mg_uecc_vli_modMult(result, left, left, mod, num_words);
  10983. }
  10984. #endif /* MG_UECC_ENABLE_VLI_API */
  10985. MG_UECC_VLI_API void mg_uecc_vli_modSquare_fast(mg_uecc_word_t *result,
  10986. const mg_uecc_word_t *left,
  10987. MG_UECC_Curve curve) {
  10988. mg_uecc_vli_modMult_fast(result, left, left, curve);
  10989. }
  10990. #endif /* MG_UECC_SQUARE_FUNC */
  10991. #define EVEN(vli) (!(vli[0] & 1))
  10992. static void vli_modInv_update(mg_uecc_word_t *uv, const mg_uecc_word_t *mod,
  10993. wordcount_t num_words) {
  10994. mg_uecc_word_t carry = 0;
  10995. if (!EVEN(uv)) {
  10996. carry = mg_uecc_vli_add(uv, uv, mod, num_words);
  10997. }
  10998. mg_uecc_vli_rshift1(uv, num_words);
  10999. if (carry) {
  11000. uv[num_words - 1] |= HIGH_BIT_SET;
  11001. }
  11002. }
  11003. /* Computes result = (1 / input) % mod. All VLIs are the same size.
  11004. See "From Euclid's GCD to Montgomery Multiplication to the Great Divide" */
  11005. MG_UECC_VLI_API void mg_uecc_vli_modInv(mg_uecc_word_t *result,
  11006. const mg_uecc_word_t *input,
  11007. const mg_uecc_word_t *mod,
  11008. wordcount_t num_words) {
  11009. mg_uecc_word_t a[MG_UECC_MAX_WORDS], b[MG_UECC_MAX_WORDS],
  11010. u[MG_UECC_MAX_WORDS], v[MG_UECC_MAX_WORDS];
  11011. cmpresult_t cmpResult;
  11012. if (mg_uecc_vli_isZero(input, num_words)) {
  11013. mg_uecc_vli_clear(result, num_words);
  11014. return;
  11015. }
  11016. mg_uecc_vli_set(a, input, num_words);
  11017. mg_uecc_vli_set(b, mod, num_words);
  11018. mg_uecc_vli_clear(u, num_words);
  11019. u[0] = 1;
  11020. mg_uecc_vli_clear(v, num_words);
  11021. while ((cmpResult = mg_uecc_vli_cmp_unsafe(a, b, num_words)) != 0) {
  11022. if (EVEN(a)) {
  11023. mg_uecc_vli_rshift1(a, num_words);
  11024. vli_modInv_update(u, mod, num_words);
  11025. } else if (EVEN(b)) {
  11026. mg_uecc_vli_rshift1(b, num_words);
  11027. vli_modInv_update(v, mod, num_words);
  11028. } else if (cmpResult > 0) {
  11029. mg_uecc_vli_sub(a, a, b, num_words);
  11030. mg_uecc_vli_rshift1(a, num_words);
  11031. if (mg_uecc_vli_cmp_unsafe(u, v, num_words) < 0) {
  11032. mg_uecc_vli_add(u, u, mod, num_words);
  11033. }
  11034. mg_uecc_vli_sub(u, u, v, num_words);
  11035. vli_modInv_update(u, mod, num_words);
  11036. } else {
  11037. mg_uecc_vli_sub(b, b, a, num_words);
  11038. mg_uecc_vli_rshift1(b, num_words);
  11039. if (mg_uecc_vli_cmp_unsafe(v, u, num_words) < 0) {
  11040. mg_uecc_vli_add(v, v, mod, num_words);
  11041. }
  11042. mg_uecc_vli_sub(v, v, u, num_words);
  11043. vli_modInv_update(v, mod, num_words);
  11044. }
  11045. }
  11046. mg_uecc_vli_set(result, u, num_words);
  11047. }
  11048. /* ------ Point operations ------ */
  11049. /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  11050. #ifndef _UECC_CURVE_SPECIFIC_H_
  11051. #define _UECC_CURVE_SPECIFIC_H_
  11052. #define num_bytes_secp160r1 20
  11053. #define num_bytes_secp192r1 24
  11054. #define num_bytes_secp224r1 28
  11055. #define num_bytes_secp256r1 32
  11056. #define num_bytes_secp256k1 32
  11057. #if (MG_UECC_WORD_SIZE == 1)
  11058. #define num_words_secp160r1 20
  11059. #define num_words_secp192r1 24
  11060. #define num_words_secp224r1 28
  11061. #define num_words_secp256r1 32
  11062. #define num_words_secp256k1 32
  11063. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) \
  11064. 0x##a, 0x##b, 0x##c, 0x##d, 0x##e, 0x##f, 0x##g, 0x##h
  11065. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##a, 0x##b, 0x##c, 0x##d
  11066. #elif (MG_UECC_WORD_SIZE == 4)
  11067. #define num_words_secp160r1 5
  11068. #define num_words_secp192r1 6
  11069. #define num_words_secp224r1 7
  11070. #define num_words_secp256r1 8
  11071. #define num_words_secp256k1 8
  11072. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
  11073. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
  11074. #elif (MG_UECC_WORD_SIZE == 8)
  11075. #define num_words_secp160r1 3
  11076. #define num_words_secp192r1 3
  11077. #define num_words_secp224r1 4
  11078. #define num_words_secp256r1 4
  11079. #define num_words_secp256k1 4
  11080. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##h##g##f##e##d##c##b##a##U
  11081. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a##U
  11082. #endif /* MG_UECC_WORD_SIZE */
  11083. #if MG_UECC_SUPPORTS_secp160r1 || MG_UECC_SUPPORTS_secp192r1 || \
  11084. MG_UECC_SUPPORTS_secp224r1 || MG_UECC_SUPPORTS_secp256r1
  11085. static void double_jacobian_default(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  11086. mg_uecc_word_t *Z1, MG_UECC_Curve curve) {
  11087. /* t1 = X, t2 = Y, t3 = Z */
  11088. mg_uecc_word_t t4[MG_UECC_MAX_WORDS];
  11089. mg_uecc_word_t t5[MG_UECC_MAX_WORDS];
  11090. wordcount_t num_words = curve->num_words;
  11091. if (mg_uecc_vli_isZero(Z1, num_words)) {
  11092. return;
  11093. }
  11094. mg_uecc_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */
  11095. mg_uecc_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
  11096. mg_uecc_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */
  11097. mg_uecc_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
  11098. mg_uecc_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */
  11099. mg_uecc_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
  11100. mg_uecc_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
  11101. mg_uecc_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
  11102. mg_uecc_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */
  11103. mg_uecc_vli_modAdd(Z1, X1, X1, curve->p,
  11104. num_words); /* t3 = 2*(x1^2 - z1^4) */
  11105. mg_uecc_vli_modAdd(X1, X1, Z1, curve->p,
  11106. num_words); /* t1 = 3*(x1^2 - z1^4) */
  11107. if (mg_uecc_vli_testBit(X1, 0)) {
  11108. mg_uecc_word_t l_carry = mg_uecc_vli_add(X1, X1, curve->p, num_words);
  11109. mg_uecc_vli_rshift1(X1, num_words);
  11110. X1[num_words - 1] |= l_carry << (MG_UECC_WORD_BITS - 1);
  11111. } else {
  11112. mg_uecc_vli_rshift1(X1, num_words);
  11113. }
  11114. /* t1 = 3/2*(x1^2 - z1^4) = B */
  11115. mg_uecc_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */
  11116. mg_uecc_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
  11117. mg_uecc_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
  11118. mg_uecc_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
  11119. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */
  11120. mg_uecc_vli_modSub(t4, X1, t4, curve->p,
  11121. num_words); /* t4 = B * (A - x3) - y1^4 = y3 */
  11122. mg_uecc_vli_set(X1, Z1, num_words);
  11123. mg_uecc_vli_set(Z1, Y1, num_words);
  11124. mg_uecc_vli_set(Y1, t4, num_words);
  11125. }
  11126. /* Computes result = x^3 + ax + b. result must not overlap x. */
  11127. static void x_side_default(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  11128. MG_UECC_Curve curve) {
  11129. mg_uecc_word_t _3[MG_UECC_MAX_WORDS] = {3}; /* -a = 3 */
  11130. wordcount_t num_words = curve->num_words;
  11131. mg_uecc_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  11132. mg_uecc_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
  11133. mg_uecc_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */
  11134. mg_uecc_vli_modAdd(result, result, curve->b, curve->p,
  11135. num_words); /* r = x^3 - 3x + b */
  11136. }
  11137. #endif /* MG_UECC_SUPPORTS_secp... */
  11138. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11139. #if MG_UECC_SUPPORTS_secp160r1 || MG_UECC_SUPPORTS_secp192r1 || \
  11140. MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1
  11141. /* Compute a = sqrt(a) (mod curve_p). */
  11142. static void mod_sqrt_default(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  11143. bitcount_t i;
  11144. mg_uecc_word_t p1[MG_UECC_MAX_WORDS] = {1};
  11145. mg_uecc_word_t l_result[MG_UECC_MAX_WORDS] = {1};
  11146. wordcount_t num_words = curve->num_words;
  11147. /* When curve->p == 3 (mod 4), we can compute
  11148. sqrt(a) = a^((curve->p + 1) / 4) (mod curve->p). */
  11149. mg_uecc_vli_add(p1, curve->p, p1, num_words); /* p1 = curve_p + 1 */
  11150. for (i = mg_uecc_vli_numBits(p1, num_words) - 1; i > 1; --i) {
  11151. mg_uecc_vli_modSquare_fast(l_result, l_result, curve);
  11152. if (mg_uecc_vli_testBit(p1, i)) {
  11153. mg_uecc_vli_modMult_fast(l_result, l_result, a, curve);
  11154. }
  11155. }
  11156. mg_uecc_vli_set(a, l_result, num_words);
  11157. }
  11158. #endif /* MG_UECC_SUPPORTS_secp... */
  11159. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  11160. #if MG_UECC_SUPPORTS_secp160r1
  11161. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11162. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11163. mg_uecc_word_t *product);
  11164. #endif
  11165. static const struct MG_UECC_Curve_t curve_secp160r1 = {
  11166. num_words_secp160r1,
  11167. num_bytes_secp160r1,
  11168. 161, /* num_n_bits */
  11169. {BYTES_TO_WORDS_8(FF, FF, FF, 7F, FF, FF, FF, FF),
  11170. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11171. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11172. {BYTES_TO_WORDS_8(57, 22, 75, CA, D3, AE, 27, F9),
  11173. BYTES_TO_WORDS_8(C8, F4, 01, 00, 00, 00, 00, 00),
  11174. BYTES_TO_WORDS_8(00, 00, 00, 00, 01, 00, 00, 00)},
  11175. {BYTES_TO_WORDS_8(82, FC, CB, 13, B9, 8B, C3, 68),
  11176. BYTES_TO_WORDS_8(89, 69, 64, 46, 28, 73, F5, 8E),
  11177. BYTES_TO_WORDS_4(68, B5, 96, 4A),
  11178. BYTES_TO_WORDS_8(32, FB, C5, 7A, 37, 51, 23, 04),
  11179. BYTES_TO_WORDS_8(12, C9, DC, 59, 7D, 94, 68, 31),
  11180. BYTES_TO_WORDS_4(55, 28, A6, 23)},
  11181. {BYTES_TO_WORDS_8(45, FA, 65, C5, AD, D4, D4, 81),
  11182. BYTES_TO_WORDS_8(9F, F8, AC, 65, 8B, 7A, BD, 54),
  11183. BYTES_TO_WORDS_4(FC, BE, 97, 1C)},
  11184. &double_jacobian_default,
  11185. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11186. &mod_sqrt_default,
  11187. #endif
  11188. &x_side_default,
  11189. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11190. &vli_mmod_fast_secp160r1
  11191. #endif
  11192. };
  11193. MG_UECC_Curve mg_uecc_secp160r1(void) {
  11194. return &curve_secp160r1;
  11195. }
  11196. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1)
  11197. /* Computes result = product % curve_p
  11198. see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
  11199. Note that this only works if log2(omega) < log2(p) / 2 */
  11200. static void omega_mult_secp160r1(mg_uecc_word_t *result,
  11201. const mg_uecc_word_t *right);
  11202. #if MG_UECC_WORD_SIZE == 8
  11203. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11204. mg_uecc_word_t *product) {
  11205. mg_uecc_word_t tmp[2 * num_words_secp160r1];
  11206. mg_uecc_word_t copy;
  11207. mg_uecc_vli_clear(tmp, num_words_secp160r1);
  11208. mg_uecc_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  11209. omega_mult_secp160r1(tmp,
  11210. product + num_words_secp160r1 - 1); /* (Rq, q) = q * c */
  11211. product[num_words_secp160r1 - 1] &= 0xffffffff;
  11212. copy = tmp[num_words_secp160r1 - 1];
  11213. tmp[num_words_secp160r1 - 1] &= 0xffffffff;
  11214. mg_uecc_vli_add(result, product, tmp,
  11215. num_words_secp160r1); /* (C, r) = r + q */
  11216. mg_uecc_vli_clear(product, num_words_secp160r1);
  11217. tmp[num_words_secp160r1 - 1] = copy;
  11218. omega_mult_secp160r1(product, tmp + num_words_secp160r1 - 1); /* Rq*c */
  11219. mg_uecc_vli_add(result, result, product,
  11220. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  11221. while (mg_uecc_vli_cmp_unsafe(result, curve_secp160r1.p,
  11222. num_words_secp160r1) > 0) {
  11223. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11224. }
  11225. }
  11226. static void omega_mult_secp160r1(uint64_t *result, const uint64_t *right) {
  11227. uint32_t carry;
  11228. unsigned i;
  11229. /* Multiply by (2^31 + 1). */
  11230. carry = 0;
  11231. for (i = 0; i < num_words_secp160r1; ++i) {
  11232. uint64_t tmp = (right[i] >> 32) | (right[i + 1] << 32);
  11233. result[i] = (tmp << 31) + tmp + carry;
  11234. carry = (tmp >> 33) + (result[i] < tmp || (carry && result[i] == tmp));
  11235. }
  11236. result[i] = carry;
  11237. }
  11238. #else
  11239. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11240. mg_uecc_word_t *product) {
  11241. mg_uecc_word_t tmp[2 * num_words_secp160r1];
  11242. mg_uecc_word_t carry;
  11243. mg_uecc_vli_clear(tmp, num_words_secp160r1);
  11244. mg_uecc_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  11245. omega_mult_secp160r1(tmp,
  11246. product + num_words_secp160r1); /* (Rq, q) = q * c */
  11247. carry = mg_uecc_vli_add(result, product, tmp,
  11248. num_words_secp160r1); /* (C, r) = r + q */
  11249. mg_uecc_vli_clear(product, num_words_secp160r1);
  11250. omega_mult_secp160r1(product, tmp + num_words_secp160r1); /* Rq*c */
  11251. carry += mg_uecc_vli_add(result, result, product,
  11252. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  11253. while (carry > 0) {
  11254. --carry;
  11255. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11256. }
  11257. if (mg_uecc_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) >
  11258. 0) {
  11259. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11260. }
  11261. }
  11262. #endif
  11263. #if MG_UECC_WORD_SIZE == 1
  11264. static void omega_mult_secp160r1(uint8_t *result, const uint8_t *right) {
  11265. uint8_t carry;
  11266. uint8_t i;
  11267. /* Multiply by (2^31 + 1). */
  11268. mg_uecc_vli_set(result + 4, right, num_words_secp160r1); /* 2^32 */
  11269. mg_uecc_vli_rshift1(result + 4, num_words_secp160r1); /* 2^31 */
  11270. result[3] = right[0] << 7; /* get last bit from shift */
  11271. carry = mg_uecc_vli_add(result, result, right,
  11272. num_words_secp160r1); /* 2^31 + 1 */
  11273. for (i = num_words_secp160r1; carry; ++i) {
  11274. uint16_t sum = (uint16_t) result[i] + carry;
  11275. result[i] = (uint8_t) sum;
  11276. carry = sum >> 8;
  11277. }
  11278. }
  11279. #elif MG_UECC_WORD_SIZE == 4
  11280. static void omega_mult_secp160r1(uint32_t *result, const uint32_t *right) {
  11281. uint32_t carry;
  11282. unsigned i;
  11283. /* Multiply by (2^31 + 1). */
  11284. mg_uecc_vli_set(result + 1, right, num_words_secp160r1); /* 2^32 */
  11285. mg_uecc_vli_rshift1(result + 1, num_words_secp160r1); /* 2^31 */
  11286. result[0] = right[0] << 31; /* get last bit from shift */
  11287. carry = mg_uecc_vli_add(result, result, right,
  11288. num_words_secp160r1); /* 2^31 + 1 */
  11289. for (i = num_words_secp160r1; carry; ++i) {
  11290. uint64_t sum = (uint64_t) result[i] + carry;
  11291. result[i] = (uint32_t) sum;
  11292. carry = sum >> 32;
  11293. }
  11294. }
  11295. #endif /* MG_UECC_WORD_SIZE */
  11296. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) */
  11297. #endif /* MG_UECC_SUPPORTS_secp160r1 */
  11298. #if MG_UECC_SUPPORTS_secp192r1
  11299. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11300. static void vli_mmod_fast_secp192r1(mg_uecc_word_t *result,
  11301. mg_uecc_word_t *product);
  11302. #endif
  11303. static const struct MG_UECC_Curve_t curve_secp192r1 = {
  11304. num_words_secp192r1,
  11305. num_bytes_secp192r1,
  11306. 192, /* num_n_bits */
  11307. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11308. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  11309. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11310. {BYTES_TO_WORDS_8(31, 28, D2, B4, B1, C9, 6B, 14),
  11311. BYTES_TO_WORDS_8(36, F8, DE, 99, FF, FF, FF, FF),
  11312. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11313. {BYTES_TO_WORDS_8(12, 10, FF, 82, FD, 0A, FF, F4),
  11314. BYTES_TO_WORDS_8(00, 88, A1, 43, EB, 20, BF, 7C),
  11315. BYTES_TO_WORDS_8(F6, 90, 30, B0, 0E, A8, 8D, 18),
  11316. BYTES_TO_WORDS_8(11, 48, 79, 1E, A1, 77, F9, 73),
  11317. BYTES_TO_WORDS_8(D5, CD, 24, 6B, ED, 11, 10, 63),
  11318. BYTES_TO_WORDS_8(78, DA, C8, FF, 95, 2B, 19, 07)},
  11319. {BYTES_TO_WORDS_8(B1, B9, 46, C1, EC, DE, B8, FE),
  11320. BYTES_TO_WORDS_8(49, 30, 24, 72, AB, E9, A7, 0F),
  11321. BYTES_TO_WORDS_8(E7, 80, 9C, E5, 19, 05, 21, 64)},
  11322. &double_jacobian_default,
  11323. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11324. &mod_sqrt_default,
  11325. #endif
  11326. &x_side_default,
  11327. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11328. &vli_mmod_fast_secp192r1
  11329. #endif
  11330. };
  11331. MG_UECC_Curve mg_uecc_secp192r1(void) {
  11332. return &curve_secp192r1;
  11333. }
  11334. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11335. /* Computes result = product % curve_p.
  11336. See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf
  11337. */
  11338. #if MG_UECC_WORD_SIZE == 1
  11339. static void vli_mmod_fast_secp192r1(uint8_t *result, uint8_t *product) {
  11340. uint8_t tmp[num_words_secp192r1];
  11341. uint8_t carry;
  11342. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11343. mg_uecc_vli_set(tmp, &product[24], num_words_secp192r1);
  11344. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11345. tmp[0] = tmp[1] = tmp[2] = tmp[3] = tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11346. tmp[8] = product[24];
  11347. tmp[9] = product[25];
  11348. tmp[10] = product[26];
  11349. tmp[11] = product[27];
  11350. tmp[12] = product[28];
  11351. tmp[13] = product[29];
  11352. tmp[14] = product[30];
  11353. tmp[15] = product[31];
  11354. tmp[16] = product[32];
  11355. tmp[17] = product[33];
  11356. tmp[18] = product[34];
  11357. tmp[19] = product[35];
  11358. tmp[20] = product[36];
  11359. tmp[21] = product[37];
  11360. tmp[22] = product[38];
  11361. tmp[23] = product[39];
  11362. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11363. tmp[0] = tmp[8] = product[40];
  11364. tmp[1] = tmp[9] = product[41];
  11365. tmp[2] = tmp[10] = product[42];
  11366. tmp[3] = tmp[11] = product[43];
  11367. tmp[4] = tmp[12] = product[44];
  11368. tmp[5] = tmp[13] = product[45];
  11369. tmp[6] = tmp[14] = product[46];
  11370. tmp[7] = tmp[15] = product[47];
  11371. tmp[16] = tmp[17] = tmp[18] = tmp[19] = tmp[20] = tmp[21] = tmp[22] =
  11372. tmp[23] = 0;
  11373. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11374. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11375. num_words_secp192r1) != 1) {
  11376. carry -=
  11377. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11378. }
  11379. }
  11380. #elif MG_UECC_WORD_SIZE == 4
  11381. static void vli_mmod_fast_secp192r1(uint32_t *result, uint32_t *product) {
  11382. uint32_t tmp[num_words_secp192r1];
  11383. int carry;
  11384. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11385. mg_uecc_vli_set(tmp, &product[6], num_words_secp192r1);
  11386. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11387. tmp[0] = tmp[1] = 0;
  11388. tmp[2] = product[6];
  11389. tmp[3] = product[7];
  11390. tmp[4] = product[8];
  11391. tmp[5] = product[9];
  11392. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11393. tmp[0] = tmp[2] = product[10];
  11394. tmp[1] = tmp[3] = product[11];
  11395. tmp[4] = tmp[5] = 0;
  11396. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11397. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11398. num_words_secp192r1) != 1) {
  11399. carry -=
  11400. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11401. }
  11402. }
  11403. #else
  11404. static void vli_mmod_fast_secp192r1(uint64_t *result, uint64_t *product) {
  11405. uint64_t tmp[num_words_secp192r1];
  11406. int carry;
  11407. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11408. mg_uecc_vli_set(tmp, &product[3], num_words_secp192r1);
  11409. carry = (int) mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11410. tmp[0] = 0;
  11411. tmp[1] = product[3];
  11412. tmp[2] = product[4];
  11413. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11414. tmp[0] = tmp[1] = product[5];
  11415. tmp[2] = 0;
  11416. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11417. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11418. num_words_secp192r1) != 1) {
  11419. carry -=
  11420. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11421. }
  11422. }
  11423. #endif /* MG_UECC_WORD_SIZE */
  11424. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0) */
  11425. #endif /* MG_UECC_SUPPORTS_secp192r1 */
  11426. #if MG_UECC_SUPPORTS_secp224r1
  11427. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11428. static void mod_sqrt_secp224r1(mg_uecc_word_t *a, MG_UECC_Curve curve);
  11429. #endif
  11430. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11431. static void vli_mmod_fast_secp224r1(mg_uecc_word_t *result,
  11432. mg_uecc_word_t *product);
  11433. #endif
  11434. static const struct MG_UECC_Curve_t curve_secp224r1 = {
  11435. num_words_secp224r1,
  11436. num_bytes_secp224r1,
  11437. 224, /* num_n_bits */
  11438. {BYTES_TO_WORDS_8(01, 00, 00, 00, 00, 00, 00, 00),
  11439. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF),
  11440. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11441. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11442. {BYTES_TO_WORDS_8(3D, 2A, 5C, 5C, 45, 29, DD, 13),
  11443. BYTES_TO_WORDS_8(3E, F0, B8, E0, A2, 16, FF, FF),
  11444. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11445. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11446. {BYTES_TO_WORDS_8(21, 1D, 5C, 11, D6, 80, 32, 34),
  11447. BYTES_TO_WORDS_8(22, 11, C2, 56, D3, C1, 03, 4A),
  11448. BYTES_TO_WORDS_8(B9, 90, 13, 32, 7F, BF, B4, 6B),
  11449. BYTES_TO_WORDS_4(BD, 0C, 0E, B7),
  11450. BYTES_TO_WORDS_8(34, 7E, 00, 85, 99, 81, D5, 44),
  11451. BYTES_TO_WORDS_8(64, 47, 07, 5A, A0, 75, 43, CD),
  11452. BYTES_TO_WORDS_8(E6, DF, 22, 4C, FB, 23, F7, B5),
  11453. BYTES_TO_WORDS_4(88, 63, 37, BD)},
  11454. {BYTES_TO_WORDS_8(B4, FF, 55, 23, 43, 39, 0B, 27),
  11455. BYTES_TO_WORDS_8(BA, D8, BF, D7, B7, B0, 44, 50),
  11456. BYTES_TO_WORDS_8(56, 32, 41, F5, AB, B3, 04, 0C),
  11457. BYTES_TO_WORDS_4(85, 0A, 05, B4)},
  11458. &double_jacobian_default,
  11459. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11460. &mod_sqrt_secp224r1,
  11461. #endif
  11462. &x_side_default,
  11463. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11464. &vli_mmod_fast_secp224r1
  11465. #endif
  11466. };
  11467. MG_UECC_Curve mg_uecc_secp224r1(void) {
  11468. return &curve_secp224r1;
  11469. }
  11470. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11471. /* Routine 3.2.4 RS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11472. static void mod_sqrt_secp224r1_rs(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11473. mg_uecc_word_t *f1, const mg_uecc_word_t *d0,
  11474. const mg_uecc_word_t *e0,
  11475. const mg_uecc_word_t *f0) {
  11476. mg_uecc_word_t t[num_words_secp224r1];
  11477. mg_uecc_vli_modSquare_fast(t, d0, &curve_secp224r1); /* t <-- d0 ^ 2 */
  11478. mg_uecc_vli_modMult_fast(e1, d0, e0, &curve_secp224r1); /* e1 <-- d0 * e0 */
  11479. mg_uecc_vli_modAdd(d1, t, f0, curve_secp224r1.p,
  11480. num_words_secp224r1); /* d1 <-- t + f0 */
  11481. mg_uecc_vli_modAdd(e1, e1, e1, curve_secp224r1.p,
  11482. num_words_secp224r1); /* e1 <-- e1 + e1 */
  11483. mg_uecc_vli_modMult_fast(f1, t, f0, &curve_secp224r1); /* f1 <-- t * f0 */
  11484. mg_uecc_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  11485. num_words_secp224r1); /* f1 <-- f1 + f1 */
  11486. mg_uecc_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  11487. num_words_secp224r1); /* f1 <-- f1 + f1 */
  11488. }
  11489. /* Routine 3.2.5 RSS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11490. static void mod_sqrt_secp224r1_rss(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11491. mg_uecc_word_t *f1, const mg_uecc_word_t *d0,
  11492. const mg_uecc_word_t *e0,
  11493. const mg_uecc_word_t *f0,
  11494. const bitcount_t j) {
  11495. bitcount_t i;
  11496. mg_uecc_vli_set(d1, d0, num_words_secp224r1); /* d1 <-- d0 */
  11497. mg_uecc_vli_set(e1, e0, num_words_secp224r1); /* e1 <-- e0 */
  11498. mg_uecc_vli_set(f1, f0, num_words_secp224r1); /* f1 <-- f0 */
  11499. for (i = 1; i <= j; i++) {
  11500. mod_sqrt_secp224r1_rs(d1, e1, f1, d1, e1, f1); /* RS (d1,e1,f1,d1,e1,f1) */
  11501. }
  11502. }
  11503. /* Routine 3.2.6 RM; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11504. static void mod_sqrt_secp224r1_rm(mg_uecc_word_t *d2, mg_uecc_word_t *e2,
  11505. mg_uecc_word_t *f2, const mg_uecc_word_t *c,
  11506. const mg_uecc_word_t *d0,
  11507. const mg_uecc_word_t *e0,
  11508. const mg_uecc_word_t *d1,
  11509. const mg_uecc_word_t *e1) {
  11510. mg_uecc_word_t t1[num_words_secp224r1];
  11511. mg_uecc_word_t t2[num_words_secp224r1];
  11512. mg_uecc_vli_modMult_fast(t1, e0, e1, &curve_secp224r1); /* t1 <-- e0 * e1 */
  11513. mg_uecc_vli_modMult_fast(t1, t1, c, &curve_secp224r1); /* t1 <-- t1 * c */
  11514. /* t1 <-- p - t1 */
  11515. mg_uecc_vli_modSub(t1, curve_secp224r1.p, t1, curve_secp224r1.p,
  11516. num_words_secp224r1);
  11517. mg_uecc_vli_modMult_fast(t2, d0, d1, &curve_secp224r1); /* t2 <-- d0 * d1 */
  11518. mg_uecc_vli_modAdd(t2, t2, t1, curve_secp224r1.p,
  11519. num_words_secp224r1); /* t2 <-- t2 + t1 */
  11520. mg_uecc_vli_modMult_fast(t1, d0, e1, &curve_secp224r1); /* t1 <-- d0 * e1 */
  11521. mg_uecc_vli_modMult_fast(e2, d1, e0, &curve_secp224r1); /* e2 <-- d1 * e0 */
  11522. mg_uecc_vli_modAdd(e2, e2, t1, curve_secp224r1.p,
  11523. num_words_secp224r1); /* e2 <-- e2 + t1 */
  11524. mg_uecc_vli_modSquare_fast(f2, e2, &curve_secp224r1); /* f2 <-- e2^2 */
  11525. mg_uecc_vli_modMult_fast(f2, f2, c, &curve_secp224r1); /* f2 <-- f2 * c */
  11526. /* f2 <-- p - f2 */
  11527. mg_uecc_vli_modSub(f2, curve_secp224r1.p, f2, curve_secp224r1.p,
  11528. num_words_secp224r1);
  11529. mg_uecc_vli_set(d2, t2, num_words_secp224r1); /* d2 <-- t2 */
  11530. }
  11531. /* Routine 3.2.7 RP; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11532. static void mod_sqrt_secp224r1_rp(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11533. mg_uecc_word_t *f1, const mg_uecc_word_t *c,
  11534. const mg_uecc_word_t *r) {
  11535. wordcount_t i;
  11536. wordcount_t pow2i = 1;
  11537. mg_uecc_word_t d0[num_words_secp224r1];
  11538. mg_uecc_word_t e0[num_words_secp224r1] = {1}; /* e0 <-- 1 */
  11539. mg_uecc_word_t f0[num_words_secp224r1];
  11540. mg_uecc_vli_set(d0, r, num_words_secp224r1); /* d0 <-- r */
  11541. /* f0 <-- p - c */
  11542. mg_uecc_vli_modSub(f0, curve_secp224r1.p, c, curve_secp224r1.p,
  11543. num_words_secp224r1);
  11544. for (i = 0; i <= 6; i++) {
  11545. mod_sqrt_secp224r1_rss(d1, e1, f1, d0, e0, f0,
  11546. pow2i); /* RSS (d1,e1,f1,d0,e0,f0,2^i) */
  11547. mod_sqrt_secp224r1_rm(d1, e1, f1, c, d1, e1, d0,
  11548. e0); /* RM (d1,e1,f1,c,d1,e1,d0,e0) */
  11549. mg_uecc_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  11550. mg_uecc_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  11551. mg_uecc_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  11552. pow2i *= 2;
  11553. }
  11554. }
  11555. /* Compute a = sqrt(a) (mod curve_p). */
  11556. /* Routine 3.2.8 mp_mod_sqrt_224; from
  11557. * http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11558. static void mod_sqrt_secp224r1(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  11559. (void) curve;
  11560. bitcount_t i;
  11561. mg_uecc_word_t e1[num_words_secp224r1];
  11562. mg_uecc_word_t f1[num_words_secp224r1];
  11563. mg_uecc_word_t d0[num_words_secp224r1];
  11564. mg_uecc_word_t e0[num_words_secp224r1];
  11565. mg_uecc_word_t f0[num_words_secp224r1];
  11566. mg_uecc_word_t d1[num_words_secp224r1];
  11567. /* s = a; using constant instead of random value */
  11568. mod_sqrt_secp224r1_rp(d0, e0, f0, a, a); /* RP (d0, e0, f0, c, s) */
  11569. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  11570. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  11571. for (i = 1; i <= 95; i++) {
  11572. mg_uecc_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  11573. mg_uecc_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  11574. mg_uecc_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  11575. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  11576. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  11577. if (mg_uecc_vli_isZero(d1, num_words_secp224r1)) { /* if d1 == 0 */
  11578. break;
  11579. }
  11580. }
  11581. mg_uecc_vli_modInv(f1, e0, curve_secp224r1.p,
  11582. num_words_secp224r1); /* f1 <-- 1 / e0 */
  11583. mg_uecc_vli_modMult_fast(a, d0, f1, &curve_secp224r1); /* a <-- d0 / e0 */
  11584. }
  11585. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  11586. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11587. /* Computes result = product % curve_p
  11588. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11589. #if MG_UECC_WORD_SIZE == 1
  11590. static void vli_mmod_fast_secp224r1(uint8_t *result, uint8_t *product) {
  11591. uint8_t tmp[num_words_secp224r1];
  11592. int8_t carry;
  11593. /* t */
  11594. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11595. /* s1 */
  11596. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  11597. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11598. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  11599. tmp[12] = product[28];
  11600. tmp[13] = product[29];
  11601. tmp[14] = product[30];
  11602. tmp[15] = product[31];
  11603. tmp[16] = product[32];
  11604. tmp[17] = product[33];
  11605. tmp[18] = product[34];
  11606. tmp[19] = product[35];
  11607. tmp[20] = product[36];
  11608. tmp[21] = product[37];
  11609. tmp[22] = product[38];
  11610. tmp[23] = product[39];
  11611. tmp[24] = product[40];
  11612. tmp[25] = product[41];
  11613. tmp[26] = product[42];
  11614. tmp[27] = product[43];
  11615. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11616. /* s2 */
  11617. tmp[12] = product[44];
  11618. tmp[13] = product[45];
  11619. tmp[14] = product[46];
  11620. tmp[15] = product[47];
  11621. tmp[16] = product[48];
  11622. tmp[17] = product[49];
  11623. tmp[18] = product[50];
  11624. tmp[19] = product[51];
  11625. tmp[20] = product[52];
  11626. tmp[21] = product[53];
  11627. tmp[22] = product[54];
  11628. tmp[23] = product[55];
  11629. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  11630. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11631. /* d1 */
  11632. tmp[0] = product[28];
  11633. tmp[1] = product[29];
  11634. tmp[2] = product[30];
  11635. tmp[3] = product[31];
  11636. tmp[4] = product[32];
  11637. tmp[5] = product[33];
  11638. tmp[6] = product[34];
  11639. tmp[7] = product[35];
  11640. tmp[8] = product[36];
  11641. tmp[9] = product[37];
  11642. tmp[10] = product[38];
  11643. tmp[11] = product[39];
  11644. tmp[12] = product[40];
  11645. tmp[13] = product[41];
  11646. tmp[14] = product[42];
  11647. tmp[15] = product[43];
  11648. tmp[16] = product[44];
  11649. tmp[17] = product[45];
  11650. tmp[18] = product[46];
  11651. tmp[19] = product[47];
  11652. tmp[20] = product[48];
  11653. tmp[21] = product[49];
  11654. tmp[22] = product[50];
  11655. tmp[23] = product[51];
  11656. tmp[24] = product[52];
  11657. tmp[25] = product[53];
  11658. tmp[26] = product[54];
  11659. tmp[27] = product[55];
  11660. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11661. /* d2 */
  11662. tmp[0] = product[44];
  11663. tmp[1] = product[45];
  11664. tmp[2] = product[46];
  11665. tmp[3] = product[47];
  11666. tmp[4] = product[48];
  11667. tmp[5] = product[49];
  11668. tmp[6] = product[50];
  11669. tmp[7] = product[51];
  11670. tmp[8] = product[52];
  11671. tmp[9] = product[53];
  11672. tmp[10] = product[54];
  11673. tmp[11] = product[55];
  11674. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11675. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11676. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11677. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  11678. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11679. if (carry < 0) {
  11680. do {
  11681. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11682. num_words_secp224r1);
  11683. } while (carry < 0);
  11684. } else {
  11685. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11686. num_words_secp224r1) != 1) {
  11687. carry -= mg_uecc_vli_sub(result, result, curve_secp224r1.p,
  11688. num_words_secp224r1);
  11689. }
  11690. }
  11691. }
  11692. #elif MG_UECC_WORD_SIZE == 4
  11693. static void vli_mmod_fast_secp224r1(uint32_t *result, uint32_t *product) {
  11694. uint32_t tmp[num_words_secp224r1];
  11695. int carry;
  11696. /* t */
  11697. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11698. /* s1 */
  11699. tmp[0] = tmp[1] = tmp[2] = 0;
  11700. tmp[3] = product[7];
  11701. tmp[4] = product[8];
  11702. tmp[5] = product[9];
  11703. tmp[6] = product[10];
  11704. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11705. /* s2 */
  11706. tmp[3] = product[11];
  11707. tmp[4] = product[12];
  11708. tmp[5] = product[13];
  11709. tmp[6] = 0;
  11710. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11711. /* d1 */
  11712. tmp[0] = product[7];
  11713. tmp[1] = product[8];
  11714. tmp[2] = product[9];
  11715. tmp[3] = product[10];
  11716. tmp[4] = product[11];
  11717. tmp[5] = product[12];
  11718. tmp[6] = product[13];
  11719. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11720. /* d2 */
  11721. tmp[0] = product[11];
  11722. tmp[1] = product[12];
  11723. tmp[2] = product[13];
  11724. tmp[3] = tmp[4] = tmp[5] = tmp[6] = 0;
  11725. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11726. if (carry < 0) {
  11727. do {
  11728. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11729. num_words_secp224r1);
  11730. } while (carry < 0);
  11731. } else {
  11732. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11733. num_words_secp224r1) != 1) {
  11734. carry -= mg_uecc_vli_sub(result, result, curve_secp224r1.p,
  11735. num_words_secp224r1);
  11736. }
  11737. }
  11738. }
  11739. #else
  11740. static void vli_mmod_fast_secp224r1(uint64_t *result, uint64_t *product) {
  11741. uint64_t tmp[num_words_secp224r1];
  11742. int carry = 0;
  11743. /* t */
  11744. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11745. result[num_words_secp224r1 - 1] &= 0xffffffff;
  11746. /* s1 */
  11747. tmp[0] = 0;
  11748. tmp[1] = product[3] & 0xffffffff00000000ull;
  11749. tmp[2] = product[4];
  11750. tmp[3] = product[5] & 0xffffffff;
  11751. mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11752. /* s2 */
  11753. tmp[1] = product[5] & 0xffffffff00000000ull;
  11754. tmp[2] = product[6];
  11755. tmp[3] = 0;
  11756. mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11757. /* d1 */
  11758. tmp[0] = (product[3] >> 32) | (product[4] << 32);
  11759. tmp[1] = (product[4] >> 32) | (product[5] << 32);
  11760. tmp[2] = (product[5] >> 32) | (product[6] << 32);
  11761. tmp[3] = product[6] >> 32;
  11762. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11763. /* d2 */
  11764. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  11765. tmp[1] = product[6] >> 32;
  11766. tmp[2] = tmp[3] = 0;
  11767. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11768. if (carry < 0) {
  11769. do {
  11770. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11771. num_words_secp224r1);
  11772. } while (carry < 0);
  11773. } else {
  11774. while (mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11775. num_words_secp224r1) != 1) {
  11776. mg_uecc_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  11777. }
  11778. }
  11779. }
  11780. #endif /* MG_UECC_WORD_SIZE */
  11781. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0) */
  11782. #endif /* MG_UECC_SUPPORTS_secp224r1 */
  11783. #if MG_UECC_SUPPORTS_secp256r1
  11784. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11785. static void vli_mmod_fast_secp256r1(mg_uecc_word_t *result,
  11786. mg_uecc_word_t *product);
  11787. #endif
  11788. static const struct MG_UECC_Curve_t curve_secp256r1 = {
  11789. num_words_secp256r1,
  11790. num_bytes_secp256r1,
  11791. 256, /* num_n_bits */
  11792. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11793. BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00),
  11794. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  11795. BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF)},
  11796. {BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3),
  11797. BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC),
  11798. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11799. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF)},
  11800. {BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4),
  11801. BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77),
  11802. BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8),
  11803. BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B),
  11804. BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB),
  11805. BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B),
  11806. BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E),
  11807. BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F)},
  11808. {BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B),
  11809. BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65),
  11810. BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3),
  11811. BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A)},
  11812. &double_jacobian_default,
  11813. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11814. &mod_sqrt_default,
  11815. #endif
  11816. &x_side_default,
  11817. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11818. &vli_mmod_fast_secp256r1
  11819. #endif
  11820. };
  11821. MG_UECC_Curve mg_uecc_secp256r1(void) {
  11822. return &curve_secp256r1;
  11823. }
  11824. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1)
  11825. /* Computes result = product % curve_p
  11826. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11827. #if MG_UECC_WORD_SIZE == 1
  11828. static void vli_mmod_fast_secp256r1(uint8_t *result, uint8_t *product) {
  11829. uint8_t tmp[num_words_secp256r1];
  11830. int8_t carry;
  11831. /* t */
  11832. mg_uecc_vli_set(result, product, num_words_secp256r1);
  11833. /* s1 */
  11834. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  11835. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11836. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  11837. tmp[12] = product[44];
  11838. tmp[13] = product[45];
  11839. tmp[14] = product[46];
  11840. tmp[15] = product[47];
  11841. tmp[16] = product[48];
  11842. tmp[17] = product[49];
  11843. tmp[18] = product[50];
  11844. tmp[19] = product[51];
  11845. tmp[20] = product[52];
  11846. tmp[21] = product[53];
  11847. tmp[22] = product[54];
  11848. tmp[23] = product[55];
  11849. tmp[24] = product[56];
  11850. tmp[25] = product[57];
  11851. tmp[26] = product[58];
  11852. tmp[27] = product[59];
  11853. tmp[28] = product[60];
  11854. tmp[29] = product[61];
  11855. tmp[30] = product[62];
  11856. tmp[31] = product[63];
  11857. carry = mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  11858. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11859. /* s2 */
  11860. tmp[12] = product[48];
  11861. tmp[13] = product[49];
  11862. tmp[14] = product[50];
  11863. tmp[15] = product[51];
  11864. tmp[16] = product[52];
  11865. tmp[17] = product[53];
  11866. tmp[18] = product[54];
  11867. tmp[19] = product[55];
  11868. tmp[20] = product[56];
  11869. tmp[21] = product[57];
  11870. tmp[22] = product[58];
  11871. tmp[23] = product[59];
  11872. tmp[24] = product[60];
  11873. tmp[25] = product[61];
  11874. tmp[26] = product[62];
  11875. tmp[27] = product[63];
  11876. tmp[28] = tmp[29] = tmp[30] = tmp[31] = 0;
  11877. carry += mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  11878. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11879. /* s3 */
  11880. tmp[0] = product[32];
  11881. tmp[1] = product[33];
  11882. tmp[2] = product[34];
  11883. tmp[3] = product[35];
  11884. tmp[4] = product[36];
  11885. tmp[5] = product[37];
  11886. tmp[6] = product[38];
  11887. tmp[7] = product[39];
  11888. tmp[8] = product[40];
  11889. tmp[9] = product[41];
  11890. tmp[10] = product[42];
  11891. tmp[11] = product[43];
  11892. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11893. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11894. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11895. tmp[24] = product[56];
  11896. tmp[25] = product[57];
  11897. tmp[26] = product[58];
  11898. tmp[27] = product[59];
  11899. tmp[28] = product[60];
  11900. tmp[29] = product[61];
  11901. tmp[30] = product[62];
  11902. tmp[31] = product[63];
  11903. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11904. /* s4 */
  11905. tmp[0] = product[36];
  11906. tmp[1] = product[37];
  11907. tmp[2] = product[38];
  11908. tmp[3] = product[39];
  11909. tmp[4] = product[40];
  11910. tmp[5] = product[41];
  11911. tmp[6] = product[42];
  11912. tmp[7] = product[43];
  11913. tmp[8] = product[44];
  11914. tmp[9] = product[45];
  11915. tmp[10] = product[46];
  11916. tmp[11] = product[47];
  11917. tmp[12] = product[52];
  11918. tmp[13] = product[53];
  11919. tmp[14] = product[54];
  11920. tmp[15] = product[55];
  11921. tmp[16] = product[56];
  11922. tmp[17] = product[57];
  11923. tmp[18] = product[58];
  11924. tmp[19] = product[59];
  11925. tmp[20] = product[60];
  11926. tmp[21] = product[61];
  11927. tmp[22] = product[62];
  11928. tmp[23] = product[63];
  11929. tmp[24] = product[52];
  11930. tmp[25] = product[53];
  11931. tmp[26] = product[54];
  11932. tmp[27] = product[55];
  11933. tmp[28] = product[32];
  11934. tmp[29] = product[33];
  11935. tmp[30] = product[34];
  11936. tmp[31] = product[35];
  11937. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11938. /* d1 */
  11939. tmp[0] = product[44];
  11940. tmp[1] = product[45];
  11941. tmp[2] = product[46];
  11942. tmp[3] = product[47];
  11943. tmp[4] = product[48];
  11944. tmp[5] = product[49];
  11945. tmp[6] = product[50];
  11946. tmp[7] = product[51];
  11947. tmp[8] = product[52];
  11948. tmp[9] = product[53];
  11949. tmp[10] = product[54];
  11950. tmp[11] = product[55];
  11951. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11952. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11953. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11954. tmp[24] = product[32];
  11955. tmp[25] = product[33];
  11956. tmp[26] = product[34];
  11957. tmp[27] = product[35];
  11958. tmp[28] = product[40];
  11959. tmp[29] = product[41];
  11960. tmp[30] = product[42];
  11961. tmp[31] = product[43];
  11962. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11963. /* d2 */
  11964. tmp[0] = product[48];
  11965. tmp[1] = product[49];
  11966. tmp[2] = product[50];
  11967. tmp[3] = product[51];
  11968. tmp[4] = product[52];
  11969. tmp[5] = product[53];
  11970. tmp[6] = product[54];
  11971. tmp[7] = product[55];
  11972. tmp[8] = product[56];
  11973. tmp[9] = product[57];
  11974. tmp[10] = product[58];
  11975. tmp[11] = product[59];
  11976. tmp[12] = product[60];
  11977. tmp[13] = product[61];
  11978. tmp[14] = product[62];
  11979. tmp[15] = product[63];
  11980. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11981. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11982. tmp[24] = product[36];
  11983. tmp[25] = product[37];
  11984. tmp[26] = product[38];
  11985. tmp[27] = product[39];
  11986. tmp[28] = product[44];
  11987. tmp[29] = product[45];
  11988. tmp[30] = product[46];
  11989. tmp[31] = product[47];
  11990. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11991. /* d3 */
  11992. tmp[0] = product[52];
  11993. tmp[1] = product[53];
  11994. tmp[2] = product[54];
  11995. tmp[3] = product[55];
  11996. tmp[4] = product[56];
  11997. tmp[5] = product[57];
  11998. tmp[6] = product[58];
  11999. tmp[7] = product[59];
  12000. tmp[8] = product[60];
  12001. tmp[9] = product[61];
  12002. tmp[10] = product[62];
  12003. tmp[11] = product[63];
  12004. tmp[12] = product[32];
  12005. tmp[13] = product[33];
  12006. tmp[14] = product[34];
  12007. tmp[15] = product[35];
  12008. tmp[16] = product[36];
  12009. tmp[17] = product[37];
  12010. tmp[18] = product[38];
  12011. tmp[19] = product[39];
  12012. tmp[20] = product[40];
  12013. tmp[21] = product[41];
  12014. tmp[22] = product[42];
  12015. tmp[23] = product[43];
  12016. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  12017. tmp[28] = product[48];
  12018. tmp[29] = product[49];
  12019. tmp[30] = product[50];
  12020. tmp[31] = product[51];
  12021. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12022. /* d4 */
  12023. tmp[0] = product[56];
  12024. tmp[1] = product[57];
  12025. tmp[2] = product[58];
  12026. tmp[3] = product[59];
  12027. tmp[4] = product[60];
  12028. tmp[5] = product[61];
  12029. tmp[6] = product[62];
  12030. tmp[7] = product[63];
  12031. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  12032. tmp[12] = product[36];
  12033. tmp[13] = product[37];
  12034. tmp[14] = product[38];
  12035. tmp[15] = product[39];
  12036. tmp[16] = product[40];
  12037. tmp[17] = product[41];
  12038. tmp[18] = product[42];
  12039. tmp[19] = product[43];
  12040. tmp[20] = product[44];
  12041. tmp[21] = product[45];
  12042. tmp[22] = product[46];
  12043. tmp[23] = product[47];
  12044. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  12045. tmp[28] = product[52];
  12046. tmp[29] = product[53];
  12047. tmp[30] = product[54];
  12048. tmp[31] = product[55];
  12049. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12050. if (carry < 0) {
  12051. do {
  12052. carry += mg_uecc_vli_add(result, result, curve_secp256r1.p,
  12053. num_words_secp256r1);
  12054. } while (carry < 0);
  12055. } else {
  12056. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  12057. num_words_secp256r1) != 1) {
  12058. carry -= mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  12059. num_words_secp256r1);
  12060. }
  12061. }
  12062. }
  12063. #elif MG_UECC_WORD_SIZE == 4
  12064. static void vli_mmod_fast_secp256r1(uint32_t *result, uint32_t *product) {
  12065. uint32_t tmp[num_words_secp256r1];
  12066. int carry;
  12067. /* t */
  12068. mg_uecc_vli_set(result, product, num_words_secp256r1);
  12069. /* s1 */
  12070. tmp[0] = tmp[1] = tmp[2] = 0;
  12071. tmp[3] = product[11];
  12072. tmp[4] = product[12];
  12073. tmp[5] = product[13];
  12074. tmp[6] = product[14];
  12075. tmp[7] = product[15];
  12076. carry = (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12077. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12078. /* s2 */
  12079. tmp[3] = product[12];
  12080. tmp[4] = product[13];
  12081. tmp[5] = product[14];
  12082. tmp[6] = product[15];
  12083. tmp[7] = 0;
  12084. carry += (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12085. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12086. /* s3 */
  12087. tmp[0] = product[8];
  12088. tmp[1] = product[9];
  12089. tmp[2] = product[10];
  12090. tmp[3] = tmp[4] = tmp[5] = 0;
  12091. tmp[6] = product[14];
  12092. tmp[7] = product[15];
  12093. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12094. /* s4 */
  12095. tmp[0] = product[9];
  12096. tmp[1] = product[10];
  12097. tmp[2] = product[11];
  12098. tmp[3] = product[13];
  12099. tmp[4] = product[14];
  12100. tmp[5] = product[15];
  12101. tmp[6] = product[13];
  12102. tmp[7] = product[8];
  12103. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12104. /* d1 */
  12105. tmp[0] = product[11];
  12106. tmp[1] = product[12];
  12107. tmp[2] = product[13];
  12108. tmp[3] = tmp[4] = tmp[5] = 0;
  12109. tmp[6] = product[8];
  12110. tmp[7] = product[10];
  12111. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12112. /* d2 */
  12113. tmp[0] = product[12];
  12114. tmp[1] = product[13];
  12115. tmp[2] = product[14];
  12116. tmp[3] = product[15];
  12117. tmp[4] = tmp[5] = 0;
  12118. tmp[6] = product[9];
  12119. tmp[7] = product[11];
  12120. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12121. /* d3 */
  12122. tmp[0] = product[13];
  12123. tmp[1] = product[14];
  12124. tmp[2] = product[15];
  12125. tmp[3] = product[8];
  12126. tmp[4] = product[9];
  12127. tmp[5] = product[10];
  12128. tmp[6] = 0;
  12129. tmp[7] = product[12];
  12130. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12131. /* d4 */
  12132. tmp[0] = product[14];
  12133. tmp[1] = product[15];
  12134. tmp[2] = 0;
  12135. tmp[3] = product[9];
  12136. tmp[4] = product[10];
  12137. tmp[5] = product[11];
  12138. tmp[6] = 0;
  12139. tmp[7] = product[13];
  12140. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12141. if (carry < 0) {
  12142. do {
  12143. carry += (int) mg_uecc_vli_add(result, result, curve_secp256r1.p,
  12144. num_words_secp256r1);
  12145. } while (carry < 0);
  12146. } else {
  12147. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  12148. num_words_secp256r1) != 1) {
  12149. carry -= (int) mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  12150. num_words_secp256r1);
  12151. }
  12152. }
  12153. }
  12154. #else
  12155. static void vli_mmod_fast_secp256r1(uint64_t *result, uint64_t *product) {
  12156. uint64_t tmp[num_words_secp256r1];
  12157. int carry;
  12158. /* t */
  12159. mg_uecc_vli_set(result, product, num_words_secp256r1);
  12160. /* s1 */
  12161. tmp[0] = 0;
  12162. tmp[1] = product[5] & 0xffffffff00000000U;
  12163. tmp[2] = product[6];
  12164. tmp[3] = product[7];
  12165. carry = (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12166. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12167. /* s2 */
  12168. tmp[1] = product[6] << 32;
  12169. tmp[2] = (product[6] >> 32) | (product[7] << 32);
  12170. tmp[3] = product[7] >> 32;
  12171. carry += (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12172. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12173. /* s3 */
  12174. tmp[0] = product[4];
  12175. tmp[1] = product[5] & 0xffffffff;
  12176. tmp[2] = 0;
  12177. tmp[3] = product[7];
  12178. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12179. /* s4 */
  12180. tmp[0] = (product[4] >> 32) | (product[5] << 32);
  12181. tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000U);
  12182. tmp[2] = product[7];
  12183. tmp[3] = (product[6] >> 32) | (product[4] << 32);
  12184. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12185. /* d1 */
  12186. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  12187. tmp[1] = (product[6] >> 32);
  12188. tmp[2] = 0;
  12189. tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32);
  12190. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12191. /* d2 */
  12192. tmp[0] = product[6];
  12193. tmp[1] = product[7];
  12194. tmp[2] = 0;
  12195. tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000);
  12196. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12197. /* d3 */
  12198. tmp[0] = (product[6] >> 32) | (product[7] << 32);
  12199. tmp[1] = (product[7] >> 32) | (product[4] << 32);
  12200. tmp[2] = (product[4] >> 32) | (product[5] << 32);
  12201. tmp[3] = (product[6] << 32);
  12202. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12203. /* d4 */
  12204. tmp[0] = product[7];
  12205. tmp[1] = product[4] & 0xffffffff00000000U;
  12206. tmp[2] = product[5];
  12207. tmp[3] = product[6] & 0xffffffff00000000U;
  12208. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12209. if (carry < 0) {
  12210. do {
  12211. carry += (int) mg_uecc_vli_add(result, result, curve_secp256r1.p,
  12212. num_words_secp256r1);
  12213. } while (carry < 0);
  12214. } else {
  12215. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  12216. num_words_secp256r1) != 1) {
  12217. carry -= (int) mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  12218. num_words_secp256r1);
  12219. }
  12220. }
  12221. }
  12222. #endif /* MG_UECC_WORD_SIZE */
  12223. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) */
  12224. #endif /* MG_UECC_SUPPORTS_secp256r1 */
  12225. #if MG_UECC_SUPPORTS_secp256k1
  12226. static void double_jacobian_secp256k1(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12227. mg_uecc_word_t *Z1, MG_UECC_Curve curve);
  12228. static void x_side_secp256k1(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  12229. MG_UECC_Curve curve);
  12230. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12231. static void vli_mmod_fast_secp256k1(mg_uecc_word_t *result,
  12232. mg_uecc_word_t *product);
  12233. #endif
  12234. static const struct MG_UECC_Curve_t curve_secp256k1 = {
  12235. num_words_secp256k1,
  12236. num_bytes_secp256k1,
  12237. 256, /* num_n_bits */
  12238. {BYTES_TO_WORDS_8(2F, FC, FF, FF, FE, FF, FF, FF),
  12239. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12240. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12241. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  12242. {BYTES_TO_WORDS_8(41, 41, 36, D0, 8C, 5E, D2, BF),
  12243. BYTES_TO_WORDS_8(3B, A0, 48, AF, E6, DC, AE, BA),
  12244. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  12245. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  12246. {BYTES_TO_WORDS_8(98, 17, F8, 16, 5B, 81, F2, 59),
  12247. BYTES_TO_WORDS_8(D9, 28, CE, 2D, DB, FC, 9B, 02),
  12248. BYTES_TO_WORDS_8(07, 0B, 87, CE, 95, 62, A0, 55),
  12249. BYTES_TO_WORDS_8(AC, BB, DC, F9, 7E, 66, BE, 79),
  12250. BYTES_TO_WORDS_8(B8, D4, 10, FB, 8F, D0, 47, 9C),
  12251. BYTES_TO_WORDS_8(19, 54, 85, A6, 48, B4, 17, FD),
  12252. BYTES_TO_WORDS_8(A8, 08, 11, 0E, FC, FB, A4, 5D),
  12253. BYTES_TO_WORDS_8(65, C4, A3, 26, 77, DA, 3A, 48)},
  12254. {BYTES_TO_WORDS_8(07, 00, 00, 00, 00, 00, 00, 00),
  12255. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  12256. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  12257. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00)},
  12258. &double_jacobian_secp256k1,
  12259. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12260. &mod_sqrt_default,
  12261. #endif
  12262. &x_side_secp256k1,
  12263. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12264. &vli_mmod_fast_secp256k1
  12265. #endif
  12266. };
  12267. MG_UECC_Curve mg_uecc_secp256k1(void) {
  12268. return &curve_secp256k1;
  12269. }
  12270. /* Double in place */
  12271. static void double_jacobian_secp256k1(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12272. mg_uecc_word_t *Z1, MG_UECC_Curve curve) {
  12273. /* t1 = X, t2 = Y, t3 = Z */
  12274. mg_uecc_word_t t4[num_words_secp256k1];
  12275. mg_uecc_word_t t5[num_words_secp256k1];
  12276. if (mg_uecc_vli_isZero(Z1, num_words_secp256k1)) {
  12277. return;
  12278. }
  12279. mg_uecc_vli_modSquare_fast(t5, Y1, curve); /* t5 = y1^2 */
  12280. mg_uecc_vli_modMult_fast(t4, X1, t5, curve); /* t4 = x1*y1^2 = A */
  12281. mg_uecc_vli_modSquare_fast(X1, X1, curve); /* t1 = x1^2 */
  12282. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = y1^4 */
  12283. mg_uecc_vli_modMult_fast(Z1, Y1, Z1, curve); /* t3 = y1*z1 = z3 */
  12284. mg_uecc_vli_modAdd(Y1, X1, X1, curve->p,
  12285. num_words_secp256k1); /* t2 = 2*x1^2 */
  12286. mg_uecc_vli_modAdd(Y1, Y1, X1, curve->p,
  12287. num_words_secp256k1); /* t2 = 3*x1^2 */
  12288. if (mg_uecc_vli_testBit(Y1, 0)) {
  12289. mg_uecc_word_t carry =
  12290. mg_uecc_vli_add(Y1, Y1, curve->p, num_words_secp256k1);
  12291. mg_uecc_vli_rshift1(Y1, num_words_secp256k1);
  12292. Y1[num_words_secp256k1 - 1] |= carry << (MG_UECC_WORD_BITS - 1);
  12293. } else {
  12294. mg_uecc_vli_rshift1(Y1, num_words_secp256k1);
  12295. }
  12296. /* t2 = 3/2*(x1^2) = B */
  12297. mg_uecc_vli_modSquare_fast(X1, Y1, curve); /* t1 = B^2 */
  12298. mg_uecc_vli_modSub(X1, X1, t4, curve->p,
  12299. num_words_secp256k1); /* t1 = B^2 - A */
  12300. mg_uecc_vli_modSub(X1, X1, t4, curve->p,
  12301. num_words_secp256k1); /* t1 = B^2 - 2A = x3 */
  12302. mg_uecc_vli_modSub(t4, t4, X1, curve->p,
  12303. num_words_secp256k1); /* t4 = A - x3 */
  12304. mg_uecc_vli_modMult_fast(Y1, Y1, t4, curve); /* t2 = B * (A - x3) */
  12305. mg_uecc_vli_modSub(Y1, Y1, t5, curve->p,
  12306. num_words_secp256k1); /* t2 = B * (A - x3) - y1^4 = y3 */
  12307. }
  12308. /* Computes result = x^3 + b. result must not overlap x. */
  12309. static void x_side_secp256k1(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  12310. MG_UECC_Curve curve) {
  12311. mg_uecc_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  12312. mg_uecc_vli_modMult_fast(result, result, x, curve); /* r = x^3 */
  12313. mg_uecc_vli_modAdd(result, result, curve->b, curve->p,
  12314. num_words_secp256k1); /* r = x^3 + b */
  12315. }
  12316. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256k1)
  12317. static void omega_mult_secp256k1(mg_uecc_word_t *result,
  12318. const mg_uecc_word_t *right);
  12319. static void vli_mmod_fast_secp256k1(mg_uecc_word_t *result,
  12320. mg_uecc_word_t *product) {
  12321. mg_uecc_word_t tmp[2 * num_words_secp256k1];
  12322. mg_uecc_word_t carry;
  12323. mg_uecc_vli_clear(tmp, num_words_secp256k1);
  12324. mg_uecc_vli_clear(tmp + num_words_secp256k1, num_words_secp256k1);
  12325. omega_mult_secp256k1(tmp,
  12326. product + num_words_secp256k1); /* (Rq, q) = q * c */
  12327. carry = mg_uecc_vli_add(result, product, tmp,
  12328. num_words_secp256k1); /* (C, r) = r + q */
  12329. mg_uecc_vli_clear(product, num_words_secp256k1);
  12330. omega_mult_secp256k1(product, tmp + num_words_secp256k1); /* Rq*c */
  12331. carry += mg_uecc_vli_add(result, result, product,
  12332. num_words_secp256k1); /* (C1, r) = r + Rq*c */
  12333. while (carry > 0) {
  12334. --carry;
  12335. mg_uecc_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  12336. }
  12337. if (mg_uecc_vli_cmp_unsafe(result, curve_secp256k1.p, num_words_secp256k1) >
  12338. 0) {
  12339. mg_uecc_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  12340. }
  12341. }
  12342. #if MG_UECC_WORD_SIZE == 1
  12343. static void omega_mult_secp256k1(uint8_t *result, const uint8_t *right) {
  12344. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12345. mg_uecc_word_t r0 = 0;
  12346. mg_uecc_word_t r1 = 0;
  12347. mg_uecc_word_t r2 = 0;
  12348. wordcount_t k;
  12349. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12350. muladd(0xD1, right[0], &r0, &r1, &r2);
  12351. result[0] = r0;
  12352. r0 = r1;
  12353. r1 = r2;
  12354. /* r2 is still 0 */
  12355. for (k = 1; k < num_words_secp256k1; ++k) {
  12356. muladd(0x03, right[k - 1], &r0, &r1, &r2);
  12357. muladd(0xD1, right[k], &r0, &r1, &r2);
  12358. result[k] = r0;
  12359. r0 = r1;
  12360. r1 = r2;
  12361. r2 = 0;
  12362. }
  12363. muladd(0x03, right[num_words_secp256k1 - 1], &r0, &r1, &r2);
  12364. result[num_words_secp256k1] = r0;
  12365. result[num_words_secp256k1 + 1] = r1;
  12366. /* add the 2^32 multiple */
  12367. result[4 + num_words_secp256k1] =
  12368. mg_uecc_vli_add(result + 4, result + 4, right, num_words_secp256k1);
  12369. }
  12370. #elif MG_UECC_WORD_SIZE == 4
  12371. static void omega_mult_secp256k1(uint32_t *result, const uint32_t *right) {
  12372. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12373. uint32_t carry = 0;
  12374. wordcount_t k;
  12375. for (k = 0; k < num_words_secp256k1; ++k) {
  12376. uint64_t p = (uint64_t) 0x3D1 * right[k] + carry;
  12377. result[k] = (uint32_t) p;
  12378. carry = p >> 32;
  12379. }
  12380. result[num_words_secp256k1] = carry;
  12381. /* add the 2^32 multiple */
  12382. result[1 + num_words_secp256k1] =
  12383. mg_uecc_vli_add(result + 1, result + 1, right, num_words_secp256k1);
  12384. }
  12385. #else
  12386. static void omega_mult_secp256k1(uint64_t *result, const uint64_t *right) {
  12387. mg_uecc_word_t r0 = 0;
  12388. mg_uecc_word_t r1 = 0;
  12389. mg_uecc_word_t r2 = 0;
  12390. wordcount_t k;
  12391. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12392. for (k = 0; k < num_words_secp256k1; ++k) {
  12393. muladd(0x1000003D1ull, right[k], &r0, &r1, &r2);
  12394. result[k] = r0;
  12395. r0 = r1;
  12396. r1 = r2;
  12397. r2 = 0;
  12398. }
  12399. result[num_words_secp256k1] = r0;
  12400. }
  12401. #endif /* MG_UECC_WORD_SIZE */
  12402. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && && !asm_mmod_fast_secp256k1) */
  12403. #endif /* MG_UECC_SUPPORTS_secp256k1 */
  12404. #endif /* _UECC_CURVE_SPECIFIC_H_ */
  12405. /* Returns 1 if 'point' is the point at infinity, 0 otherwise. */
  12406. #define EccPoint_isZero(point, curve) \
  12407. mg_uecc_vli_isZero((point), (wordcount_t) ((curve)->num_words * 2))
  12408. /* Point multiplication algorithm using Montgomery's ladder with co-Z
  12409. coordinates. From http://eprint.iacr.org/2011/338.pdf
  12410. */
  12411. /* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
  12412. static void apply_z(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12413. const mg_uecc_word_t *const Z, MG_UECC_Curve curve) {
  12414. mg_uecc_word_t t1[MG_UECC_MAX_WORDS];
  12415. mg_uecc_vli_modSquare_fast(t1, Z, curve); /* z^2 */
  12416. mg_uecc_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
  12417. mg_uecc_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */
  12418. mg_uecc_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
  12419. }
  12420. /* P = (x1, y1) => 2P, (x2, y2) => P' */
  12421. static void XYcZ_initial_double(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12422. mg_uecc_word_t *X2, mg_uecc_word_t *Y2,
  12423. const mg_uecc_word_t *const initial_Z,
  12424. MG_UECC_Curve curve) {
  12425. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  12426. wordcount_t num_words = curve->num_words;
  12427. if (initial_Z) {
  12428. mg_uecc_vli_set(z, initial_Z, num_words);
  12429. } else {
  12430. mg_uecc_vli_clear(z, num_words);
  12431. z[0] = 1;
  12432. }
  12433. mg_uecc_vli_set(X2, X1, num_words);
  12434. mg_uecc_vli_set(Y2, Y1, num_words);
  12435. apply_z(X1, Y1, z, curve);
  12436. curve->double_jacobian(X1, Y1, z, curve);
  12437. apply_z(X2, Y2, z, curve);
  12438. }
  12439. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  12440. Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
  12441. or P => P', Q => P + Q
  12442. */
  12443. static void XYcZ_add(mg_uecc_word_t *X1, mg_uecc_word_t *Y1, mg_uecc_word_t *X2,
  12444. mg_uecc_word_t *Y2, MG_UECC_Curve curve) {
  12445. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  12446. mg_uecc_word_t t5[MG_UECC_MAX_WORDS] = {0};
  12447. wordcount_t num_words = curve->num_words;
  12448. mg_uecc_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  12449. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  12450. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  12451. mg_uecc_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  12452. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  12453. mg_uecc_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */
  12454. mg_uecc_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
  12455. mg_uecc_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
  12456. mg_uecc_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
  12457. mg_uecc_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */
  12458. mg_uecc_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
  12459. mg_uecc_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */
  12460. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
  12461. mg_uecc_vli_set(X2, t5, num_words);
  12462. }
  12463. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  12464. Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
  12465. or P => P - Q, Q => P + Q
  12466. */
  12467. static void XYcZ_addC(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12468. mg_uecc_word_t *X2, mg_uecc_word_t *Y2,
  12469. MG_UECC_Curve curve) {
  12470. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  12471. mg_uecc_word_t t5[MG_UECC_MAX_WORDS] = {0};
  12472. mg_uecc_word_t t6[MG_UECC_MAX_WORDS];
  12473. mg_uecc_word_t t7[MG_UECC_MAX_WORDS];
  12474. wordcount_t num_words = curve->num_words;
  12475. mg_uecc_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  12476. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  12477. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  12478. mg_uecc_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  12479. mg_uecc_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
  12480. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  12481. mg_uecc_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
  12482. mg_uecc_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */
  12483. mg_uecc_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
  12484. mg_uecc_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */
  12485. mg_uecc_vli_modSub(X2, X2, t6, curve->p,
  12486. num_words); /* t3 = D - (B + C) = x3 */
  12487. mg_uecc_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
  12488. mg_uecc_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */
  12489. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p,
  12490. num_words); /* t4 = (y2 - y1)*(B - x3) - E = y3 */
  12491. mg_uecc_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */
  12492. mg_uecc_vli_modSub(t7, t7, t6, curve->p,
  12493. num_words); /* t7 = F - (B + C) = x3' */
  12494. mg_uecc_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
  12495. mg_uecc_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */
  12496. mg_uecc_vli_modSub(Y1, t6, Y1, curve->p,
  12497. num_words); /* t2 = (y2+y1)*(x3' - B) - E = y3' */
  12498. mg_uecc_vli_set(X1, t7, num_words);
  12499. }
  12500. /* result may overlap point. */
  12501. static void EccPoint_mult(mg_uecc_word_t *result, const mg_uecc_word_t *point,
  12502. const mg_uecc_word_t *scalar,
  12503. const mg_uecc_word_t *initial_Z, bitcount_t num_bits,
  12504. MG_UECC_Curve curve) {
  12505. /* R0 and R1 */
  12506. mg_uecc_word_t Rx[2][MG_UECC_MAX_WORDS];
  12507. mg_uecc_word_t Ry[2][MG_UECC_MAX_WORDS];
  12508. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  12509. bitcount_t i;
  12510. mg_uecc_word_t nb;
  12511. wordcount_t num_words = curve->num_words;
  12512. mg_uecc_vli_set(Rx[1], point, num_words);
  12513. mg_uecc_vli_set(Ry[1], point + num_words, num_words);
  12514. XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
  12515. for (i = num_bits - 2; i > 0; --i) {
  12516. nb = !mg_uecc_vli_testBit(scalar, i);
  12517. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  12518. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  12519. }
  12520. nb = !mg_uecc_vli_testBit(scalar, 0);
  12521. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  12522. /* Find final 1/Z value. */
  12523. mg_uecc_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
  12524. mg_uecc_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */
  12525. mg_uecc_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */
  12526. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0)) */
  12527. /* yP / (xP * Yb * (X1 - X0)) */
  12528. mg_uecc_vli_modMult_fast(z, z, point + num_words, curve);
  12529. mg_uecc_vli_modMult_fast(z, z, Rx[1 - nb],
  12530. curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */
  12531. /* End 1/Z calculation */
  12532. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  12533. apply_z(Rx[0], Ry[0], z, curve);
  12534. mg_uecc_vli_set(result, Rx[0], num_words);
  12535. mg_uecc_vli_set(result + num_words, Ry[0], num_words);
  12536. }
  12537. static mg_uecc_word_t regularize_k(const mg_uecc_word_t *const k,
  12538. mg_uecc_word_t *k0, mg_uecc_word_t *k1,
  12539. MG_UECC_Curve curve) {
  12540. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12541. bitcount_t num_n_bits = curve->num_n_bits;
  12542. mg_uecc_word_t carry =
  12543. mg_uecc_vli_add(k0, k, curve->n, num_n_words) ||
  12544. (num_n_bits < ((bitcount_t) num_n_words * MG_UECC_WORD_SIZE * 8) &&
  12545. mg_uecc_vli_testBit(k0, num_n_bits));
  12546. mg_uecc_vli_add(k1, k0, curve->n, num_n_words);
  12547. return carry;
  12548. }
  12549. /* Generates a random integer in the range 0 < random < top.
  12550. Both random and top have num_words words. */
  12551. MG_UECC_VLI_API int mg_uecc_generate_random_int(mg_uecc_word_t *random,
  12552. const mg_uecc_word_t *top,
  12553. wordcount_t num_words) {
  12554. mg_uecc_word_t mask = (mg_uecc_word_t) -1;
  12555. mg_uecc_word_t tries;
  12556. bitcount_t num_bits = mg_uecc_vli_numBits(top, num_words);
  12557. if (!g_rng_function) {
  12558. return 0;
  12559. }
  12560. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12561. if (!g_rng_function((uint8_t *) random,
  12562. (unsigned int) (num_words * MG_UECC_WORD_SIZE))) {
  12563. return 0;
  12564. }
  12565. random[num_words - 1] &=
  12566. mask >> ((bitcount_t) (num_words * MG_UECC_WORD_SIZE * 8 - num_bits));
  12567. if (!mg_uecc_vli_isZero(random, num_words) &&
  12568. mg_uecc_vli_cmp(top, random, num_words) == 1) {
  12569. return 1;
  12570. }
  12571. }
  12572. return 0;
  12573. }
  12574. static mg_uecc_word_t EccPoint_compute_public_key(mg_uecc_word_t *result,
  12575. mg_uecc_word_t *private_key,
  12576. MG_UECC_Curve curve) {
  12577. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  12578. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  12579. mg_uecc_word_t *p2[2] = {tmp1, tmp2};
  12580. mg_uecc_word_t *initial_Z = 0;
  12581. mg_uecc_word_t carry;
  12582. /* Regularize the bitcount for the private key so that attackers cannot use a
  12583. side channel attack to learn the number of leading zeros. */
  12584. carry = regularize_k(private_key, tmp1, tmp2, curve);
  12585. /* If an RNG function was specified, try to get a random initial Z value to
  12586. improve protection against side-channel attacks. */
  12587. if (g_rng_function) {
  12588. if (!mg_uecc_generate_random_int(p2[carry], curve->p, curve->num_words)) {
  12589. return 0;
  12590. }
  12591. initial_Z = p2[carry];
  12592. }
  12593. EccPoint_mult(result, curve->G, p2[!carry], initial_Z,
  12594. (bitcount_t) (curve->num_n_bits + 1), curve);
  12595. if (EccPoint_isZero(result, curve)) {
  12596. return 0;
  12597. }
  12598. return 1;
  12599. }
  12600. #if MG_UECC_WORD_SIZE == 1
  12601. MG_UECC_VLI_API void mg_uecc_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  12602. const uint8_t *native) {
  12603. wordcount_t i;
  12604. for (i = 0; i < num_bytes; ++i) {
  12605. bytes[i] = native[(num_bytes - 1) - i];
  12606. }
  12607. }
  12608. MG_UECC_VLI_API void mg_uecc_vli_bytesToNative(uint8_t *native,
  12609. const uint8_t *bytes,
  12610. int num_bytes) {
  12611. mg_uecc_vli_nativeToBytes(native, num_bytes, bytes);
  12612. }
  12613. #else
  12614. MG_UECC_VLI_API void mg_uecc_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  12615. const mg_uecc_word_t *native) {
  12616. int i;
  12617. for (i = 0; i < num_bytes; ++i) {
  12618. unsigned b = (unsigned) (num_bytes - 1 - i);
  12619. bytes[i] = (uint8_t) (native[b / MG_UECC_WORD_SIZE] >>
  12620. (8 * (b % MG_UECC_WORD_SIZE)));
  12621. }
  12622. }
  12623. MG_UECC_VLI_API void mg_uecc_vli_bytesToNative(mg_uecc_word_t *native,
  12624. const uint8_t *bytes,
  12625. int num_bytes) {
  12626. int i;
  12627. mg_uecc_vli_clear(native,
  12628. (wordcount_t) ((num_bytes + (MG_UECC_WORD_SIZE - 1)) /
  12629. MG_UECC_WORD_SIZE));
  12630. for (i = 0; i < num_bytes; ++i) {
  12631. unsigned b = (unsigned) (num_bytes - 1 - i);
  12632. native[b / MG_UECC_WORD_SIZE] |= (mg_uecc_word_t) bytes[i]
  12633. << (8 * (b % MG_UECC_WORD_SIZE));
  12634. }
  12635. }
  12636. #endif /* MG_UECC_WORD_SIZE */
  12637. int mg_uecc_make_key(uint8_t *public_key, uint8_t *private_key,
  12638. MG_UECC_Curve curve) {
  12639. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12640. mg_uecc_word_t *_private = (mg_uecc_word_t *) private_key;
  12641. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12642. #else
  12643. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12644. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12645. #endif
  12646. mg_uecc_word_t tries;
  12647. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12648. if (!mg_uecc_generate_random_int(_private, curve->n,
  12649. BITS_TO_WORDS(curve->num_n_bits))) {
  12650. return 0;
  12651. }
  12652. if (EccPoint_compute_public_key(_public, _private, curve)) {
  12653. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12654. mg_uecc_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits),
  12655. _private);
  12656. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  12657. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  12658. _public + curve->num_words);
  12659. #endif
  12660. return 1;
  12661. }
  12662. }
  12663. return 0;
  12664. }
  12665. int mg_uecc_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
  12666. uint8_t *secret, MG_UECC_Curve curve) {
  12667. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12668. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12669. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  12670. mg_uecc_word_t *p2[2] = {_private, tmp};
  12671. mg_uecc_word_t *initial_Z = 0;
  12672. mg_uecc_word_t carry;
  12673. wordcount_t num_words = curve->num_words;
  12674. wordcount_t num_bytes = curve->num_bytes;
  12675. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12676. bcopy((uint8_t *) _private, private_key, num_bytes);
  12677. bcopy((uint8_t *) _public, public_key, num_bytes * 2);
  12678. #else
  12679. mg_uecc_vli_bytesToNative(_private, private_key,
  12680. BITS_TO_BYTES(curve->num_n_bits));
  12681. mg_uecc_vli_bytesToNative(_public, public_key, num_bytes);
  12682. mg_uecc_vli_bytesToNative(_public + num_words, public_key + num_bytes,
  12683. num_bytes);
  12684. #endif
  12685. /* Regularize the bitcount for the private key so that attackers cannot use a
  12686. side channel attack to learn the number of leading zeros. */
  12687. carry = regularize_k(_private, _private, tmp, curve);
  12688. /* If an RNG function was specified, try to get a random initial Z value to
  12689. improve protection against side-channel attacks. */
  12690. if (g_rng_function) {
  12691. if (!mg_uecc_generate_random_int(p2[carry], curve->p, num_words)) {
  12692. return 0;
  12693. }
  12694. initial_Z = p2[carry];
  12695. }
  12696. EccPoint_mult(_public, _public, p2[!carry], initial_Z,
  12697. (bitcount_t) (curve->num_n_bits + 1), curve);
  12698. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12699. bcopy((uint8_t *) secret, (uint8_t *) _public, num_bytes);
  12700. #else
  12701. mg_uecc_vli_nativeToBytes(secret, num_bytes, _public);
  12702. #endif
  12703. return !EccPoint_isZero(_public, curve);
  12704. }
  12705. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12706. void mg_uecc_compress(const uint8_t *public_key, uint8_t *compressed,
  12707. MG_UECC_Curve curve) {
  12708. wordcount_t i;
  12709. for (i = 0; i < curve->num_bytes; ++i) {
  12710. compressed[i + 1] = public_key[i];
  12711. }
  12712. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12713. compressed[0] = 2 + (public_key[curve->num_bytes] & 0x01);
  12714. #else
  12715. compressed[0] = 2 + (public_key[curve->num_bytes * 2 - 1] & 0x01);
  12716. #endif
  12717. }
  12718. void mg_uecc_decompress(const uint8_t *compressed, uint8_t *public_key,
  12719. MG_UECC_Curve curve) {
  12720. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12721. mg_uecc_word_t *point = (mg_uecc_word_t *) public_key;
  12722. #else
  12723. mg_uecc_word_t point[MG_UECC_MAX_WORDS * 2];
  12724. #endif
  12725. mg_uecc_word_t *y = point + curve->num_words;
  12726. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12727. bcopy(public_key, compressed + 1, curve->num_bytes);
  12728. #else
  12729. mg_uecc_vli_bytesToNative(point, compressed + 1, curve->num_bytes);
  12730. #endif
  12731. curve->x_side(y, point, curve);
  12732. curve->mod_sqrt(y, curve);
  12733. if ((uint8_t) (y[0] & 0x01) != (compressed[0] & 0x01)) {
  12734. mg_uecc_vli_sub(y, curve->p, y, curve->num_words);
  12735. }
  12736. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12737. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, point);
  12738. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, y);
  12739. #endif
  12740. }
  12741. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  12742. MG_UECC_VLI_API int mg_uecc_valid_point(const mg_uecc_word_t *point,
  12743. MG_UECC_Curve curve) {
  12744. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  12745. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  12746. wordcount_t num_words = curve->num_words;
  12747. /* The point at infinity is invalid. */
  12748. if (EccPoint_isZero(point, curve)) {
  12749. return 0;
  12750. }
  12751. /* x and y must be smaller than p. */
  12752. if (mg_uecc_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
  12753. mg_uecc_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
  12754. return 0;
  12755. }
  12756. mg_uecc_vli_modSquare_fast(tmp1, point + num_words, curve);
  12757. curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
  12758. /* Make sure that y^2 == x^3 + ax + b */
  12759. return (int) (mg_uecc_vli_equal(tmp1, tmp2, num_words));
  12760. }
  12761. int mg_uecc_valid_public_key(const uint8_t *public_key, MG_UECC_Curve curve) {
  12762. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12763. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12764. #else
  12765. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12766. #endif
  12767. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12768. mg_uecc_vli_bytesToNative(_public, public_key, curve->num_bytes);
  12769. mg_uecc_vli_bytesToNative(_public + curve->num_words,
  12770. public_key + curve->num_bytes, curve->num_bytes);
  12771. #endif
  12772. return mg_uecc_valid_point(_public, curve);
  12773. }
  12774. int mg_uecc_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
  12775. MG_UECC_Curve curve) {
  12776. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12777. mg_uecc_word_t *_private = (mg_uecc_word_t *) private_key;
  12778. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12779. #else
  12780. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12781. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12782. #endif
  12783. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12784. mg_uecc_vli_bytesToNative(_private, private_key,
  12785. BITS_TO_BYTES(curve->num_n_bits));
  12786. #endif
  12787. /* Make sure the private key is in the range [1, n-1]. */
  12788. if (mg_uecc_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
  12789. return 0;
  12790. }
  12791. if (mg_uecc_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) !=
  12792. 1) {
  12793. return 0;
  12794. }
  12795. /* Compute public key. */
  12796. if (!EccPoint_compute_public_key(_public, _private, curve)) {
  12797. return 0;
  12798. }
  12799. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12800. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  12801. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  12802. _public + curve->num_words);
  12803. #endif
  12804. return 1;
  12805. }
  12806. /* -------- ECDSA code -------- */
  12807. static void bits2int(mg_uecc_word_t *native, const uint8_t *bits,
  12808. unsigned bits_size, MG_UECC_Curve curve) {
  12809. unsigned num_n_bytes = (unsigned) BITS_TO_BYTES(curve->num_n_bits);
  12810. unsigned num_n_words = (unsigned) BITS_TO_WORDS(curve->num_n_bits);
  12811. int shift;
  12812. mg_uecc_word_t carry;
  12813. mg_uecc_word_t *ptr;
  12814. if (bits_size > num_n_bytes) {
  12815. bits_size = num_n_bytes;
  12816. }
  12817. mg_uecc_vli_clear(native, (wordcount_t) num_n_words);
  12818. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12819. bcopy((uint8_t *) native, bits, bits_size);
  12820. #else
  12821. mg_uecc_vli_bytesToNative(native, bits, (int) bits_size);
  12822. #endif
  12823. if (bits_size * 8 <= (unsigned) curve->num_n_bits) {
  12824. return;
  12825. }
  12826. shift = (int) bits_size * 8 - curve->num_n_bits;
  12827. carry = 0;
  12828. ptr = native + num_n_words;
  12829. while (ptr-- > native) {
  12830. mg_uecc_word_t temp = *ptr;
  12831. *ptr = (temp >> shift) | carry;
  12832. carry = temp << (MG_UECC_WORD_BITS - shift);
  12833. }
  12834. /* Reduce mod curve_n */
  12835. if (mg_uecc_vli_cmp_unsafe(curve->n, native, (wordcount_t) num_n_words) !=
  12836. 1) {
  12837. mg_uecc_vli_sub(native, native, curve->n, (wordcount_t) num_n_words);
  12838. }
  12839. }
  12840. static int mg_uecc_sign_with_k_internal(const uint8_t *private_key,
  12841. const uint8_t *message_hash,
  12842. unsigned hash_size, mg_uecc_word_t *k,
  12843. uint8_t *signature,
  12844. MG_UECC_Curve curve) {
  12845. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  12846. mg_uecc_word_t s[MG_UECC_MAX_WORDS];
  12847. mg_uecc_word_t *k2[2] = {tmp, s};
  12848. mg_uecc_word_t *initial_Z = 0;
  12849. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12850. mg_uecc_word_t *p = (mg_uecc_word_t *) signature;
  12851. #else
  12852. mg_uecc_word_t p[MG_UECC_MAX_WORDS * 2];
  12853. #endif
  12854. mg_uecc_word_t carry;
  12855. wordcount_t num_words = curve->num_words;
  12856. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12857. bitcount_t num_n_bits = curve->num_n_bits;
  12858. /* Make sure 0 < k < curve_n */
  12859. if (mg_uecc_vli_isZero(k, num_words) ||
  12860. mg_uecc_vli_cmp(curve->n, k, num_n_words) != 1) {
  12861. return 0;
  12862. }
  12863. carry = regularize_k(k, tmp, s, curve);
  12864. /* If an RNG function was specified, try to get a random initial Z value to
  12865. improve protection against side-channel attacks. */
  12866. if (g_rng_function) {
  12867. if (!mg_uecc_generate_random_int(k2[carry], curve->p, num_words)) {
  12868. return 0;
  12869. }
  12870. initial_Z = k2[carry];
  12871. }
  12872. EccPoint_mult(p, curve->G, k2[!carry], initial_Z,
  12873. (bitcount_t) (num_n_bits + 1), curve);
  12874. if (mg_uecc_vli_isZero(p, num_words)) {
  12875. return 0;
  12876. }
  12877. /* If an RNG function was specified, get a random number
  12878. to prevent side channel analysis of k. */
  12879. if (!g_rng_function) {
  12880. mg_uecc_vli_clear(tmp, num_n_words);
  12881. tmp[0] = 1;
  12882. } else if (!mg_uecc_generate_random_int(tmp, curve->n, num_n_words)) {
  12883. return 0;
  12884. }
  12885. /* Prevent side channel analysis of mg_uecc_vli_modInv() to determine
  12886. bits of k / the private key by premultiplying by a random number */
  12887. mg_uecc_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
  12888. mg_uecc_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */
  12889. mg_uecc_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
  12890. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12891. mg_uecc_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
  12892. #endif
  12893. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12894. bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
  12895. #else
  12896. mg_uecc_vli_bytesToNative(tmp, private_key,
  12897. BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */
  12898. #endif
  12899. s[num_n_words - 1] = 0;
  12900. mg_uecc_vli_set(s, p, num_words);
  12901. mg_uecc_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
  12902. bits2int(tmp, message_hash, hash_size, curve);
  12903. mg_uecc_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
  12904. mg_uecc_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */
  12905. if (mg_uecc_vli_numBits(s, num_n_words) > (bitcount_t) curve->num_bytes * 8) {
  12906. return 0;
  12907. }
  12908. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12909. bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s,
  12910. curve->num_bytes);
  12911. #else
  12912. mg_uecc_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
  12913. #endif
  12914. return 1;
  12915. }
  12916. #if 0
  12917. /* For testing - sign with an explicitly specified k value */
  12918. int mg_uecc_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
  12919. unsigned hash_size, const uint8_t *k, uint8_t *signature,
  12920. MG_UECC_Curve curve) {
  12921. mg_uecc_word_t k2[MG_UECC_MAX_WORDS];
  12922. bits2int(k2, k, (unsigned) BITS_TO_BYTES(curve->num_n_bits), curve);
  12923. return mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, k2,
  12924. signature, curve);
  12925. }
  12926. #endif
  12927. int mg_uecc_sign(const uint8_t *private_key, const uint8_t *message_hash,
  12928. unsigned hash_size, uint8_t *signature, MG_UECC_Curve curve) {
  12929. mg_uecc_word_t k[MG_UECC_MAX_WORDS];
  12930. mg_uecc_word_t tries;
  12931. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12932. if (!mg_uecc_generate_random_int(k, curve->n,
  12933. BITS_TO_WORDS(curve->num_n_bits))) {
  12934. return 0;
  12935. }
  12936. if (mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, k,
  12937. signature, curve)) {
  12938. return 1;
  12939. }
  12940. }
  12941. return 0;
  12942. }
  12943. /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always
  12944. the same size as the hash result size. */
  12945. static void HMAC_init(const MG_UECC_HashContext *hash_context,
  12946. const uint8_t *K) {
  12947. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  12948. unsigned i;
  12949. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x36;
  12950. for (; i < hash_context->block_size; ++i) pad[i] = 0x36;
  12951. hash_context->init_hash(hash_context);
  12952. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  12953. }
  12954. static void HMAC_update(const MG_UECC_HashContext *hash_context,
  12955. const uint8_t *message, unsigned message_size) {
  12956. hash_context->update_hash(hash_context, message, message_size);
  12957. }
  12958. static void HMAC_finish(const MG_UECC_HashContext *hash_context,
  12959. const uint8_t *K, uint8_t *result) {
  12960. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  12961. unsigned i;
  12962. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x5c;
  12963. for (; i < hash_context->block_size; ++i) pad[i] = 0x5c;
  12964. hash_context->finish_hash(hash_context, result);
  12965. hash_context->init_hash(hash_context);
  12966. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  12967. hash_context->update_hash(hash_context, result, hash_context->result_size);
  12968. hash_context->finish_hash(hash_context, result);
  12969. }
  12970. /* V = HMAC_K(V) */
  12971. static void update_V(const MG_UECC_HashContext *hash_context, uint8_t *K,
  12972. uint8_t *V) {
  12973. HMAC_init(hash_context, K);
  12974. HMAC_update(hash_context, V, hash_context->result_size);
  12975. HMAC_finish(hash_context, K, V);
  12976. }
  12977. /* Deterministic signing, similar to RFC 6979. Differences are:
  12978. * We just use H(m) directly rather than bits2octets(H(m))
  12979. (it is not reduced modulo curve_n).
  12980. * We generate a value for k (aka T) directly rather than converting
  12981. endianness.
  12982. Layout of hash_context->tmp: <K> | <V> | (1 byte overlapped 0x00 or 0x01) /
  12983. <HMAC pad> */
  12984. int mg_uecc_sign_deterministic(const uint8_t *private_key,
  12985. const uint8_t *message_hash, unsigned hash_size,
  12986. const MG_UECC_HashContext *hash_context,
  12987. uint8_t *signature, MG_UECC_Curve curve) {
  12988. uint8_t *K = hash_context->tmp;
  12989. uint8_t *V = K + hash_context->result_size;
  12990. wordcount_t num_bytes = curve->num_bytes;
  12991. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12992. bitcount_t num_n_bits = curve->num_n_bits;
  12993. mg_uecc_word_t tries;
  12994. unsigned i;
  12995. for (i = 0; i < hash_context->result_size; ++i) {
  12996. V[i] = 0x01;
  12997. K[i] = 0;
  12998. }
  12999. /* K = HMAC_K(V || 0x00 || int2octets(x) || h(m)) */
  13000. HMAC_init(hash_context, K);
  13001. V[hash_context->result_size] = 0x00;
  13002. HMAC_update(hash_context, V, hash_context->result_size + 1);
  13003. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  13004. HMAC_update(hash_context, message_hash, hash_size);
  13005. HMAC_finish(hash_context, K, K);
  13006. update_V(hash_context, K, V);
  13007. /* K = HMAC_K(V || 0x01 || int2octets(x) || h(m)) */
  13008. HMAC_init(hash_context, K);
  13009. V[hash_context->result_size] = 0x01;
  13010. HMAC_update(hash_context, V, hash_context->result_size + 1);
  13011. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  13012. HMAC_update(hash_context, message_hash, hash_size);
  13013. HMAC_finish(hash_context, K, K);
  13014. update_V(hash_context, K, V);
  13015. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  13016. mg_uecc_word_t T[MG_UECC_MAX_WORDS];
  13017. uint8_t *T_ptr = (uint8_t *) T;
  13018. wordcount_t T_bytes = 0;
  13019. for (;;) {
  13020. update_V(hash_context, K, V);
  13021. for (i = 0; i < hash_context->result_size; ++i) {
  13022. T_ptr[T_bytes++] = V[i];
  13023. if (T_bytes >= num_n_words * MG_UECC_WORD_SIZE) {
  13024. goto filled;
  13025. }
  13026. }
  13027. }
  13028. filled:
  13029. if ((bitcount_t) num_n_words * MG_UECC_WORD_SIZE * 8 > num_n_bits) {
  13030. mg_uecc_word_t mask = (mg_uecc_word_t) -1;
  13031. T[num_n_words - 1] &=
  13032. mask >>
  13033. ((bitcount_t) (num_n_words * MG_UECC_WORD_SIZE * 8 - num_n_bits));
  13034. }
  13035. if (mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, T,
  13036. signature, curve)) {
  13037. return 1;
  13038. }
  13039. /* K = HMAC_K(V || 0x00) */
  13040. HMAC_init(hash_context, K);
  13041. V[hash_context->result_size] = 0x00;
  13042. HMAC_update(hash_context, V, hash_context->result_size + 1);
  13043. HMAC_finish(hash_context, K, K);
  13044. update_V(hash_context, K, V);
  13045. }
  13046. return 0;
  13047. }
  13048. static bitcount_t smax(bitcount_t a, bitcount_t b) {
  13049. return (a > b ? a : b);
  13050. }
  13051. int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash,
  13052. unsigned hash_size, const uint8_t *signature,
  13053. MG_UECC_Curve curve) {
  13054. mg_uecc_word_t u1[MG_UECC_MAX_WORDS], u2[MG_UECC_MAX_WORDS];
  13055. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  13056. mg_uecc_word_t sum[MG_UECC_MAX_WORDS * 2];
  13057. mg_uecc_word_t rx[MG_UECC_MAX_WORDS];
  13058. mg_uecc_word_t ry[MG_UECC_MAX_WORDS];
  13059. mg_uecc_word_t tx[MG_UECC_MAX_WORDS];
  13060. mg_uecc_word_t ty[MG_UECC_MAX_WORDS];
  13061. mg_uecc_word_t tz[MG_UECC_MAX_WORDS];
  13062. const mg_uecc_word_t *points[4];
  13063. const mg_uecc_word_t *point;
  13064. bitcount_t num_bits;
  13065. bitcount_t i;
  13066. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  13067. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  13068. #else
  13069. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  13070. #endif
  13071. mg_uecc_word_t r[MG_UECC_MAX_WORDS], s[MG_UECC_MAX_WORDS];
  13072. wordcount_t num_words = curve->num_words;
  13073. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  13074. rx[num_n_words - 1] = 0;
  13075. r[num_n_words - 1] = 0;
  13076. s[num_n_words - 1] = 0;
  13077. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  13078. bcopy((uint8_t *) r, signature, curve->num_bytes);
  13079. bcopy((uint8_t *) s, signature + curve->num_bytes, curve->num_bytes);
  13080. #else
  13081. mg_uecc_vli_bytesToNative(_public, public_key, curve->num_bytes);
  13082. mg_uecc_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
  13083. curve->num_bytes);
  13084. mg_uecc_vli_bytesToNative(r, signature, curve->num_bytes);
  13085. mg_uecc_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
  13086. #endif
  13087. /* r, s must not be 0. */
  13088. if (mg_uecc_vli_isZero(r, num_words) || mg_uecc_vli_isZero(s, num_words)) {
  13089. return 0;
  13090. }
  13091. /* r, s must be < n. */
  13092. if (mg_uecc_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
  13093. mg_uecc_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
  13094. return 0;
  13095. }
  13096. /* Calculate u1 and u2. */
  13097. mg_uecc_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
  13098. u1[num_n_words - 1] = 0;
  13099. bits2int(u1, message_hash, hash_size, curve);
  13100. mg_uecc_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
  13101. mg_uecc_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */
  13102. /* Calculate sum = G + Q. */
  13103. mg_uecc_vli_set(sum, _public, num_words);
  13104. mg_uecc_vli_set(sum + num_words, _public + num_words, num_words);
  13105. mg_uecc_vli_set(tx, curve->G, num_words);
  13106. mg_uecc_vli_set(ty, curve->G + num_words, num_words);
  13107. mg_uecc_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
  13108. XYcZ_add(tx, ty, sum, sum + num_words, curve);
  13109. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
  13110. apply_z(sum, sum + num_words, z, curve);
  13111. /* Use Shamir's trick to calculate u1*G + u2*Q */
  13112. points[0] = 0;
  13113. points[1] = curve->G;
  13114. points[2] = _public;
  13115. points[3] = sum;
  13116. num_bits = smax(mg_uecc_vli_numBits(u1, num_n_words),
  13117. mg_uecc_vli_numBits(u2, num_n_words));
  13118. point =
  13119. points[(!!mg_uecc_vli_testBit(u1, (bitcount_t) (num_bits - 1))) |
  13120. ((!!mg_uecc_vli_testBit(u2, (bitcount_t) (num_bits - 1))) << 1)];
  13121. mg_uecc_vli_set(rx, point, num_words);
  13122. mg_uecc_vli_set(ry, point + num_words, num_words);
  13123. mg_uecc_vli_clear(z, num_words);
  13124. z[0] = 1;
  13125. for (i = num_bits - 2; i >= 0; --i) {
  13126. mg_uecc_word_t index;
  13127. curve->double_jacobian(rx, ry, z, curve);
  13128. index = (!!mg_uecc_vli_testBit(u1, i)) |
  13129. (mg_uecc_word_t) ((!!mg_uecc_vli_testBit(u2, i)) << 1);
  13130. point = points[index];
  13131. if (point) {
  13132. mg_uecc_vli_set(tx, point, num_words);
  13133. mg_uecc_vli_set(ty, point + num_words, num_words);
  13134. apply_z(tx, ty, z, curve);
  13135. mg_uecc_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
  13136. XYcZ_add(tx, ty, rx, ry, curve);
  13137. mg_uecc_vli_modMult_fast(z, z, tz, curve);
  13138. }
  13139. }
  13140. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
  13141. apply_z(rx, ry, z, curve);
  13142. /* v = x1 (mod n) */
  13143. if (mg_uecc_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
  13144. mg_uecc_vli_sub(rx, rx, curve->n, num_n_words);
  13145. }
  13146. /* Accept only if v == r. */
  13147. return (int) (mg_uecc_vli_equal(rx, r, num_words));
  13148. }
  13149. #if MG_UECC_ENABLE_VLI_API
  13150. unsigned mg_uecc_curve_num_words(MG_UECC_Curve curve) {
  13151. return curve->num_words;
  13152. }
  13153. unsigned mg_uecc_curve_num_bytes(MG_UECC_Curve curve) {
  13154. return curve->num_bytes;
  13155. }
  13156. unsigned mg_uecc_curve_num_bits(MG_UECC_Curve curve) {
  13157. return curve->num_bytes * 8;
  13158. }
  13159. unsigned mg_uecc_curve_num_n_words(MG_UECC_Curve curve) {
  13160. return BITS_TO_WORDS(curve->num_n_bits);
  13161. }
  13162. unsigned mg_uecc_curve_num_n_bytes(MG_UECC_Curve curve) {
  13163. return BITS_TO_BYTES(curve->num_n_bits);
  13164. }
  13165. unsigned mg_uecc_curve_num_n_bits(MG_UECC_Curve curve) {
  13166. return curve->num_n_bits;
  13167. }
  13168. const mg_uecc_word_t *mg_uecc_curve_p(MG_UECC_Curve curve) {
  13169. return curve->p;
  13170. }
  13171. const mg_uecc_word_t *mg_uecc_curve_n(MG_UECC_Curve curve) {
  13172. return curve->n;
  13173. }
  13174. const mg_uecc_word_t *mg_uecc_curve_G(MG_UECC_Curve curve) {
  13175. return curve->G;
  13176. }
  13177. const mg_uecc_word_t *mg_uecc_curve_b(MG_UECC_Curve curve) {
  13178. return curve->b;
  13179. }
  13180. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  13181. void mg_uecc_vli_mod_sqrt(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  13182. curve->mod_sqrt(a, curve);
  13183. }
  13184. #endif
  13185. void mg_uecc_vli_mmod_fast(mg_uecc_word_t *result, mg_uecc_word_t *product,
  13186. MG_UECC_Curve curve) {
  13187. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  13188. curve->mmod_fast(result, product);
  13189. #else
  13190. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  13191. #endif
  13192. }
  13193. void mg_uecc_point_mult(mg_uecc_word_t *result, const mg_uecc_word_t *point,
  13194. const mg_uecc_word_t *scalar, MG_UECC_Curve curve) {
  13195. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  13196. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  13197. mg_uecc_word_t *p2[2] = {tmp1, tmp2};
  13198. mg_uecc_word_t carry = regularize_k(scalar, tmp1, tmp2, curve);
  13199. EccPoint_mult(result, point, p2[!carry], 0, curve->num_n_bits + 1, curve);
  13200. }
  13201. #endif /* MG_UECC_ENABLE_VLI_API */
  13202. #endif // MG_TLS_BUILTIN
  13203. // End of uecc BSD-2
  13204. #ifdef MG_ENABLE_LINES
  13205. #line 1 "src/tls_x25519.c"
  13206. #endif
  13207. /**
  13208. * Adapted from STROBE: https://strobe.sourceforge.io/
  13209. * Copyright (c) 2015-2016 Cryptography Research, Inc.
  13210. * Author: Mike Hamburg
  13211. * License: MIT License
  13212. */
  13213. const uint8_t X25519_BASE_POINT[X25519_BYTES] = {9};
  13214. #define X25519_WBITS 32
  13215. typedef uint32_t limb_t;
  13216. typedef uint64_t dlimb_t;
  13217. typedef int64_t sdlimb_t;
  13218. #define NLIMBS (256 / X25519_WBITS)
  13219. typedef limb_t mg_fe[NLIMBS];
  13220. static limb_t umaal(limb_t *carry, limb_t acc, limb_t mand, limb_t mier) {
  13221. dlimb_t tmp = (dlimb_t) mand * mier + acc + *carry;
  13222. *carry = (limb_t) (tmp >> X25519_WBITS);
  13223. return (limb_t) tmp;
  13224. }
  13225. // These functions are implemented in terms of umaal on ARM
  13226. static limb_t adc(limb_t *carry, limb_t acc, limb_t mand) {
  13227. dlimb_t total = (dlimb_t) *carry + acc + mand;
  13228. *carry = (limb_t) (total >> X25519_WBITS);
  13229. return (limb_t) total;
  13230. }
  13231. static limb_t adc0(limb_t *carry, limb_t acc) {
  13232. dlimb_t total = (dlimb_t) *carry + acc;
  13233. *carry = (limb_t) (total >> X25519_WBITS);
  13234. return (limb_t) total;
  13235. }
  13236. // - Precondition: carry is small.
  13237. // - Invariant: result of propagate is < 2^255 + 1 word
  13238. // - In particular, always less than 2p.
  13239. // - Also, output x >= min(x,19)
  13240. static void propagate(mg_fe x, limb_t over) {
  13241. unsigned i;
  13242. limb_t carry;
  13243. over = x[NLIMBS - 1] >> (X25519_WBITS - 1) | over << 1;
  13244. x[NLIMBS - 1] &= ~((limb_t) 1 << (X25519_WBITS - 1));
  13245. carry = over * 19;
  13246. for (i = 0; i < NLIMBS; i++) {
  13247. x[i] = adc0(&carry, x[i]);
  13248. }
  13249. }
  13250. static void add(mg_fe out, const mg_fe a, const mg_fe b) {
  13251. unsigned i;
  13252. limb_t carry = 0;
  13253. for (i = 0; i < NLIMBS; i++) {
  13254. out[i] = adc(&carry, a[i], b[i]);
  13255. }
  13256. propagate(out, carry);
  13257. }
  13258. static void sub(mg_fe out, const mg_fe a, const mg_fe b) {
  13259. unsigned i;
  13260. sdlimb_t carry = -38;
  13261. for (i = 0; i < NLIMBS; i++) {
  13262. carry = carry + a[i] - b[i];
  13263. out[i] = (limb_t) carry;
  13264. carry >>= X25519_WBITS;
  13265. }
  13266. propagate(out, (limb_t) (1 + carry));
  13267. }
  13268. // `b` can contain less than 8 limbs, thus we use `limb_t *` instead of `mg_fe`
  13269. // to avoid build warnings
  13270. static void mul(mg_fe out, const mg_fe a, const limb_t *b, unsigned nb) {
  13271. limb_t accum[2 * NLIMBS] = {0};
  13272. unsigned i, j;
  13273. limb_t carry2;
  13274. for (i = 0; i < nb; i++) {
  13275. limb_t mand = b[i];
  13276. carry2 = 0;
  13277. for (j = 0; j < NLIMBS; j++) {
  13278. limb_t tmp; // "a" may be misaligned
  13279. memcpy(&tmp, &a[j], sizeof(tmp)); // So make an aligned copy
  13280. accum[i + j] = umaal(&carry2, accum[i + j], mand, tmp);
  13281. }
  13282. accum[i + j] = carry2;
  13283. }
  13284. carry2 = 0;
  13285. for (j = 0; j < NLIMBS; j++) {
  13286. out[j] = umaal(&carry2, accum[j], 38, accum[j + NLIMBS]);
  13287. }
  13288. propagate(out, carry2);
  13289. }
  13290. static void sqr(mg_fe out, const mg_fe a) {
  13291. mul(out, a, a, NLIMBS);
  13292. }
  13293. static void mul1(mg_fe out, const mg_fe a) {
  13294. mul(out, a, out, NLIMBS);
  13295. }
  13296. static void sqr1(mg_fe a) {
  13297. mul1(a, a);
  13298. }
  13299. static void condswap(limb_t a[2 * NLIMBS], limb_t b[2 * NLIMBS],
  13300. limb_t doswap) {
  13301. unsigned i;
  13302. for (i = 0; i < 2 * NLIMBS; i++) {
  13303. limb_t xor_ab = (a[i] ^ b[i]) & doswap;
  13304. a[i] ^= xor_ab;
  13305. b[i] ^= xor_ab;
  13306. }
  13307. }
  13308. // Canonicalize a field element x, reducing it to the least residue which is
  13309. // congruent to it mod 2^255-19
  13310. // - Precondition: x < 2^255 + 1 word
  13311. static limb_t canon(mg_fe x) {
  13312. // First, add 19.
  13313. unsigned i;
  13314. limb_t carry0 = 19;
  13315. limb_t res;
  13316. sdlimb_t carry;
  13317. for (i = 0; i < NLIMBS; i++) {
  13318. x[i] = adc0(&carry0, x[i]);
  13319. }
  13320. propagate(x, carry0);
  13321. // Here, 19 <= x2 < 2^255
  13322. // - This is because we added 19, so before propagate it can't be less
  13323. // than 19. After propagate, it still can't be less than 19, because if
  13324. // propagate does anything it adds 19.
  13325. // - We know that the high bit must be clear, because either the input was ~
  13326. // 2^255 + one word + 19 (in which case it propagates to at most 2 words) or
  13327. // it was < 2^255. So now, if we subtract 19, we will get back to something in
  13328. // [0,2^255-19).
  13329. carry = -19;
  13330. res = 0;
  13331. for (i = 0; i < NLIMBS; i++) {
  13332. carry += x[i];
  13333. res |= x[i] = (limb_t) carry;
  13334. carry >>= X25519_WBITS;
  13335. }
  13336. return (limb_t) (((dlimb_t) res - 1) >> X25519_WBITS);
  13337. }
  13338. static const limb_t a24[1] = {121665};
  13339. static void ladder_part1(mg_fe xs[5]) {
  13340. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  13341. add(t1, x2, z2); // t1 = A
  13342. sub(z2, x2, z2); // z2 = B
  13343. add(x2, x3, z3); // x2 = C
  13344. sub(z3, x3, z3); // z3 = D
  13345. mul1(z3, t1); // z3 = DA
  13346. mul1(x2, z2); // x3 = BC
  13347. add(x3, z3, x2); // x3 = DA+CB
  13348. sub(z3, z3, x2); // z3 = DA-CB
  13349. sqr1(t1); // t1 = AA
  13350. sqr1(z2); // z2 = BB
  13351. sub(x2, t1, z2); // x2 = E = AA-BB
  13352. mul(z2, x2, a24, sizeof(a24) / sizeof(a24[0])); // z2 = E*a24
  13353. add(z2, z2, t1); // z2 = E*a24 + AA
  13354. }
  13355. static void ladder_part2(mg_fe xs[5], const mg_fe x1) {
  13356. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  13357. sqr1(z3); // z3 = (DA-CB)^2
  13358. mul1(z3, x1); // z3 = x1 * (DA-CB)^2
  13359. sqr1(x3); // x3 = (DA+CB)^2
  13360. mul1(z2, x2); // z2 = AA*(E*a24+AA)
  13361. sub(x2, t1, x2); // x2 = BB again
  13362. mul1(x2, t1); // x2 = AA*BB
  13363. }
  13364. static void x25519_core(mg_fe xs[5], const uint8_t scalar[X25519_BYTES],
  13365. const uint8_t *x1, int clamp) {
  13366. int i;
  13367. mg_fe x1_limbs;
  13368. limb_t swap = 0;
  13369. limb_t *x2 = xs[0], *x3 = xs[2], *z3 = xs[3];
  13370. memset(xs, 0, 4 * sizeof(mg_fe));
  13371. x2[0] = z3[0] = 1;
  13372. for (i = 0; i < NLIMBS; i++) {
  13373. x3[i] = x1_limbs[i] =
  13374. MG_U32(x1[i * 4 + 3], x1[i * 4 + 2], x1[i * 4 + 1], x1[i * 4]);
  13375. }
  13376. for (i = 255; i >= 0; i--) {
  13377. uint8_t bytei = scalar[i / 8];
  13378. limb_t doswap;
  13379. if (clamp) {
  13380. if (i / 8 == 0) {
  13381. bytei &= (uint8_t) ~7U;
  13382. } else if (i / 8 == X25519_BYTES - 1) {
  13383. bytei &= 0x7F;
  13384. bytei |= 0x40;
  13385. }
  13386. }
  13387. doswap = 0 - (limb_t) ((bytei >> (i % 8)) & 1);
  13388. condswap(x2, x3, swap ^ doswap);
  13389. swap = doswap;
  13390. ladder_part1(xs);
  13391. ladder_part2(xs, (const limb_t *) x1_limbs);
  13392. }
  13393. condswap(x2, x3, swap);
  13394. }
  13395. int mg_tls_x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES],
  13396. const uint8_t x1[X25519_BYTES], int clamp) {
  13397. int i, ret;
  13398. mg_fe xs[5], out_limbs;
  13399. limb_t *x2, *z2, *z3, *prev;
  13400. static const struct {
  13401. uint8_t a, c, n;
  13402. } steps[13] = {{2, 1, 1}, {2, 1, 1}, {4, 2, 3}, {2, 4, 6}, {3, 1, 1},
  13403. {3, 2, 12}, {4, 3, 25}, {2, 3, 25}, {2, 4, 50}, {3, 2, 125},
  13404. {3, 1, 2}, {3, 1, 2}, {3, 1, 1}};
  13405. x25519_core(xs, scalar, x1, clamp);
  13406. // Precomputed inversion chain
  13407. x2 = xs[0];
  13408. z2 = xs[1];
  13409. z3 = xs[3];
  13410. prev = z2;
  13411. for (i = 0; i < 13; i++) {
  13412. int j;
  13413. limb_t *a = xs[steps[i].a];
  13414. for (j = steps[i].n; j > 0; j--) {
  13415. sqr(a, prev);
  13416. prev = a;
  13417. }
  13418. mul1(a, xs[steps[i].c]);
  13419. }
  13420. // Here prev = z3
  13421. // x2 /= z2
  13422. mul(out_limbs, x2, z3, NLIMBS);
  13423. ret = (int) canon(out_limbs);
  13424. if (!clamp) ret = 0;
  13425. for (i = 0; i < NLIMBS; i++) {
  13426. uint32_t n = out_limbs[i];
  13427. out[i * 4] = (uint8_t) (n & 0xff);
  13428. out[i * 4 + 1] = (uint8_t) ((n >> 8) & 0xff);
  13429. out[i * 4 + 2] = (uint8_t) ((n >> 16) & 0xff);
  13430. out[i * 4 + 3] = (uint8_t) ((n >> 24) & 0xff);
  13431. }
  13432. return ret;
  13433. }
  13434. #ifdef MG_ENABLE_LINES
  13435. #line 1 "src/url.c"
  13436. #endif
  13437. struct url {
  13438. size_t key, user, pass, host, port, uri, end;
  13439. };
  13440. int mg_url_is_ssl(const char *url) {
  13441. return strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0 ||
  13442. strncmp(url, "mqtts:", 6) == 0 || strncmp(url, "ssl:", 4) == 0 ||
  13443. strncmp(url, "tls:", 4) == 0 || strncmp(url, "tcps:", 5) == 0;
  13444. }
  13445. static struct url urlparse(const char *url) {
  13446. size_t i;
  13447. struct url u;
  13448. memset(&u, 0, sizeof(u));
  13449. for (i = 0; url[i] != '\0'; i++) {
  13450. if (url[i] == '/' && i > 0 && u.host == 0 && url[i - 1] == '/') {
  13451. u.host = i + 1;
  13452. u.port = 0;
  13453. } else if (url[i] == ']') {
  13454. u.port = 0; // IPv6 URLs, like http://[::1]/bar
  13455. } else if (url[i] == ':' && u.port == 0 && u.uri == 0) {
  13456. u.port = i + 1;
  13457. } else if (url[i] == '@' && u.user == 0 && u.pass == 0 && u.uri == 0) {
  13458. u.user = u.host;
  13459. u.pass = u.port;
  13460. u.host = i + 1;
  13461. u.port = 0;
  13462. } else if (url[i] == '/' && u.host && u.uri == 0) {
  13463. u.uri = i;
  13464. }
  13465. }
  13466. u.end = i;
  13467. #if 0
  13468. printf("[%s] %d %d %d %d %d\n", url, u.user, u.pass, u.host, u.port, u.uri);
  13469. #endif
  13470. return u;
  13471. }
  13472. struct mg_str mg_url_host(const char *url) {
  13473. struct url u = urlparse(url);
  13474. size_t n = u.port ? u.port - u.host - 1
  13475. : u.uri ? u.uri - u.host
  13476. : u.end - u.host;
  13477. struct mg_str s = mg_str_n(url + u.host, n);
  13478. return s;
  13479. }
  13480. const char *mg_url_uri(const char *url) {
  13481. struct url u = urlparse(url);
  13482. return u.uri ? url + u.uri : "/";
  13483. }
  13484. unsigned short mg_url_port(const char *url) {
  13485. struct url u = urlparse(url);
  13486. unsigned short port = 0;
  13487. if (strncmp(url, "http:", 5) == 0 || strncmp(url, "ws:", 3) == 0) port = 80;
  13488. if (strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0)
  13489. port = 443;
  13490. if (strncmp(url, "mqtt:", 5) == 0) port = 1883;
  13491. if (strncmp(url, "mqtts:", 6) == 0) port = 8883;
  13492. if (u.port) port = (unsigned short) atoi(url + u.port);
  13493. return port;
  13494. }
  13495. struct mg_str mg_url_user(const char *url) {
  13496. struct url u = urlparse(url);
  13497. struct mg_str s = mg_str("");
  13498. if (u.user && (u.pass || u.host)) {
  13499. size_t n = u.pass ? u.pass - u.user - 1 : u.host - u.user - 1;
  13500. s = mg_str_n(url + u.user, n);
  13501. }
  13502. return s;
  13503. }
  13504. struct mg_str mg_url_pass(const char *url) {
  13505. struct url u = urlparse(url);
  13506. struct mg_str s = mg_str_n("", 0UL);
  13507. if (u.pass && u.host) {
  13508. size_t n = u.host - u.pass - 1;
  13509. s = mg_str_n(url + u.pass, n);
  13510. }
  13511. return s;
  13512. }
  13513. #ifdef MG_ENABLE_LINES
  13514. #line 1 "src/util.c"
  13515. #endif
  13516. // Not using memset for zeroing memory, cause it can be dropped by compiler
  13517. // See https://github.com/cesanta/mongoose/pull/1265
  13518. void mg_bzero(volatile unsigned char *buf, size_t len) {
  13519. if (buf != NULL) {
  13520. while (len--) *buf++ = 0;
  13521. }
  13522. }
  13523. #if MG_ENABLE_CUSTOM_RANDOM
  13524. #else
  13525. void mg_random(void *buf, size_t len) {
  13526. bool done = false;
  13527. unsigned char *p = (unsigned char *) buf;
  13528. #if MG_ARCH == MG_ARCH_ESP32
  13529. while (len--) *p++ = (unsigned char) (esp_random() & 255);
  13530. done = true;
  13531. #elif MG_ARCH == MG_ARCH_WIN32
  13532. #elif MG_ARCH == MG_ARCH_UNIX
  13533. FILE *fp = fopen("/dev/urandom", "rb");
  13534. if (fp != NULL) {
  13535. if (fread(buf, 1, len, fp) == len) done = true;
  13536. fclose(fp);
  13537. }
  13538. #endif
  13539. // If everything above did not work, fallback to a pseudo random generator
  13540. while (!done && len--) *p++ = (unsigned char) (rand() & 255);
  13541. }
  13542. #endif
  13543. char *mg_random_str(char *buf, size_t len) {
  13544. size_t i;
  13545. mg_random(buf, len);
  13546. for (i = 0; i < len; i++) {
  13547. uint8_t c = ((uint8_t *) buf)[i] % 62U;
  13548. buf[i] = i == len - 1 ? (char) '\0' // 0-terminate last byte
  13549. : c < 26 ? (char) ('a' + c) // lowercase
  13550. : c < 52 ? (char) ('A' + c - 26) // uppercase
  13551. : (char) ('0' + c - 52); // numeric
  13552. }
  13553. return buf;
  13554. }
  13555. uint32_t mg_ntohl(uint32_t net) {
  13556. uint8_t data[4] = {0, 0, 0, 0};
  13557. memcpy(&data, &net, sizeof(data));
  13558. return (((uint32_t) data[3]) << 0) | (((uint32_t) data[2]) << 8) |
  13559. (((uint32_t) data[1]) << 16) | (((uint32_t) data[0]) << 24);
  13560. }
  13561. uint16_t mg_ntohs(uint16_t net) {
  13562. uint8_t data[2] = {0, 0};
  13563. memcpy(&data, &net, sizeof(data));
  13564. return (uint16_t) ((uint16_t) data[1] | (((uint16_t) data[0]) << 8));
  13565. }
  13566. uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len) {
  13567. static const uint32_t crclut[16] = {
  13568. // table for polynomial 0xEDB88320 (reflected)
  13569. 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
  13570. 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
  13571. 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
  13572. crc = ~crc;
  13573. while (len--) {
  13574. uint8_t b = *(uint8_t *) buf++;
  13575. crc = crclut[(crc ^ b) & 0x0F] ^ (crc >> 4);
  13576. crc = crclut[(crc ^ (b >> 4)) & 0x0F] ^ (crc >> 4);
  13577. }
  13578. return ~crc;
  13579. }
  13580. static int isbyte(int n) {
  13581. return n >= 0 && n <= 255;
  13582. }
  13583. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  13584. int n, a, b, c, d, slash = 32, len = 0;
  13585. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  13586. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  13587. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  13588. slash < 33) {
  13589. len = n;
  13590. *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) |
  13591. (uint32_t) d;
  13592. *mask = slash ? (uint32_t) (0xffffffffU << (32 - slash)) : (uint32_t) 0;
  13593. }
  13594. return len;
  13595. }
  13596. int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) {
  13597. struct mg_str entry;
  13598. int allowed = acl.len == 0 ? '+' : '-'; // If any ACL is set, deny by default
  13599. uint32_t remote_ip4;
  13600. if (remote_ip->is_ip6) {
  13601. return -1; // TODO(): handle IPv6 ACL and addresses
  13602. } else { // IPv4
  13603. memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4));
  13604. while (mg_span(acl, &entry, &acl, ',')) {
  13605. uint32_t net, mask;
  13606. if (entry.buf[0] != '+' && entry.buf[0] != '-') return -1;
  13607. if (parse_net(&entry.buf[1], &net, &mask) == 0) return -2;
  13608. if ((mg_ntohl(remote_ip4) & mask) == net) allowed = entry.buf[0];
  13609. }
  13610. }
  13611. return allowed == '+';
  13612. }
  13613. bool mg_path_is_sane(const struct mg_str path) {
  13614. const char *s = path.buf;
  13615. size_t n = path.len;
  13616. if (path.buf[0] == '.' && path.buf[1] == '.') return false; // Starts with ..
  13617. for (; s[0] != '\0' && n > 0; s++, n--) {
  13618. if ((s[0] == '/' || s[0] == '\\') && n >= 2) { // Subdir?
  13619. if (s[1] == '.' && s[2] == '.') return false; // Starts with ..
  13620. }
  13621. }
  13622. return true;
  13623. }
  13624. #if MG_ENABLE_CUSTOM_MILLIS
  13625. #else
  13626. uint64_t mg_millis(void) {
  13627. #if MG_ARCH == MG_ARCH_WIN32
  13628. return GetTickCount();
  13629. #elif MG_ARCH == MG_ARCH_RP2040
  13630. return time_us_64() / 1000;
  13631. #elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \
  13632. MG_ARCH == MG_ARCH_FREERTOS
  13633. return xTaskGetTickCount() * portTICK_PERIOD_MS;
  13634. #elif MG_ARCH == MG_ARCH_AZURERTOS
  13635. return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND);
  13636. #elif MG_ARCH == MG_ARCH_TIRTOS
  13637. return (uint64_t) Clock_getTicks();
  13638. #elif MG_ARCH == MG_ARCH_ZEPHYR
  13639. return (uint64_t) k_uptime_get();
  13640. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
  13641. return (uint64_t) rt_time_get();
  13642. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
  13643. return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq());
  13644. #elif MG_ARCH == MG_ARCH_RTTHREAD
  13645. return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND);
  13646. #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
  13647. // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
  13648. // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
  13649. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000;
  13650. #elif MG_ARCH == MG_ARCH_UNIX
  13651. struct timespec ts = {0, 0};
  13652. // See #1615 - prefer monotonic clock
  13653. #if defined(CLOCK_MONOTONIC_RAW)
  13654. // Raw hardware-based time that is not subject to NTP adjustment
  13655. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  13656. #elif defined(CLOCK_MONOTONIC)
  13657. // Affected by the incremental adjustments performed by adjtime and NTP
  13658. clock_gettime(CLOCK_MONOTONIC, &ts);
  13659. #else
  13660. // Affected by discontinuous jumps in the system time and by the incremental
  13661. // adjustments performed by adjtime and NTP
  13662. clock_gettime(CLOCK_REALTIME, &ts);
  13663. #endif
  13664. return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000);
  13665. #elif defined(ARDUINO)
  13666. return (uint64_t) millis();
  13667. #else
  13668. return (uint64_t) (time(NULL) * 1000);
  13669. #endif
  13670. }
  13671. #endif
  13672. #ifdef MG_ENABLE_LINES
  13673. #line 1 "src/ws.c"
  13674. #endif
  13675. struct ws_msg {
  13676. uint8_t flags;
  13677. size_t header_len;
  13678. size_t data_len;
  13679. };
  13680. size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
  13681. va_list *ap) {
  13682. size_t len = c->send.len;
  13683. size_t n = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  13684. mg_ws_wrap(c, c->send.len - len, op);
  13685. return n;
  13686. }
  13687. size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...) {
  13688. size_t len = 0;
  13689. va_list ap;
  13690. va_start(ap, fmt);
  13691. len = mg_ws_vprintf(c, op, fmt, &ap);
  13692. va_end(ap);
  13693. return len;
  13694. }
  13695. static void ws_handshake(struct mg_connection *c, const struct mg_str *wskey,
  13696. const struct mg_str *wsproto, const char *fmt,
  13697. va_list *ap) {
  13698. const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  13699. unsigned char sha[20], b64_sha[30];
  13700. mg_sha1_ctx sha_ctx;
  13701. mg_sha1_init(&sha_ctx);
  13702. mg_sha1_update(&sha_ctx, (unsigned char *) wskey->buf, wskey->len);
  13703. mg_sha1_update(&sha_ctx, (unsigned char *) magic, 36);
  13704. mg_sha1_final(sha, &sha_ctx);
  13705. mg_base64_encode(sha, sizeof(sha), (char *) b64_sha, sizeof(b64_sha));
  13706. mg_xprintf(mg_pfn_iobuf, &c->send,
  13707. "HTTP/1.1 101 Switching Protocols\r\n"
  13708. "Upgrade: websocket\r\n"
  13709. "Connection: Upgrade\r\n"
  13710. "Sec-WebSocket-Accept: %s\r\n",
  13711. b64_sha);
  13712. if (fmt != NULL) mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  13713. if (wsproto != NULL) {
  13714. mg_printf(c, "Sec-WebSocket-Protocol: %.*s\r\n", (int) wsproto->len,
  13715. wsproto->buf);
  13716. }
  13717. mg_send(c, "\r\n", 2);
  13718. }
  13719. static uint32_t be32(const uint8_t *p) {
  13720. return (((uint32_t) p[3]) << 0) | (((uint32_t) p[2]) << 8) |
  13721. (((uint32_t) p[1]) << 16) | (((uint32_t) p[0]) << 24);
  13722. }
  13723. static size_t ws_process(uint8_t *buf, size_t len, struct ws_msg *msg) {
  13724. size_t i, n = 0, mask_len = 0;
  13725. memset(msg, 0, sizeof(*msg));
  13726. if (len >= 2) {
  13727. n = buf[1] & 0x7f; // Frame length
  13728. mask_len = buf[1] & 128 ? 4 : 0; // last bit is a mask bit
  13729. msg->flags = buf[0];
  13730. if (n < 126 && len >= mask_len) {
  13731. msg->data_len = n;
  13732. msg->header_len = 2 + mask_len;
  13733. } else if (n == 126 && len >= 4 + mask_len) {
  13734. msg->header_len = 4 + mask_len;
  13735. msg->data_len = (((size_t) buf[2]) << 8) | buf[3];
  13736. } else if (len >= 10 + mask_len) {
  13737. msg->header_len = 10 + mask_len;
  13738. msg->data_len =
  13739. (size_t) (((uint64_t) be32(buf + 2) << 32) + be32(buf + 6));
  13740. }
  13741. }
  13742. // Sanity check, and integer overflow protection for the boundary check below
  13743. // data_len should not be larger than 1 Gb
  13744. if (msg->data_len > 1024 * 1024 * 1024) return 0;
  13745. if (msg->header_len + msg->data_len > len) return 0;
  13746. if (mask_len > 0) {
  13747. uint8_t *p = buf + msg->header_len, *m = p - mask_len;
  13748. for (i = 0; i < msg->data_len; i++) p[i] ^= m[i & 3];
  13749. }
  13750. return msg->header_len + msg->data_len;
  13751. }
  13752. static size_t mkhdr(size_t len, int op, bool is_client, uint8_t *buf) {
  13753. size_t n = 0;
  13754. buf[0] = (uint8_t) (op | 128);
  13755. if (len < 126) {
  13756. buf[1] = (unsigned char) len;
  13757. n = 2;
  13758. } else if (len < 65536) {
  13759. uint16_t tmp = mg_htons((uint16_t) len);
  13760. buf[1] = 126;
  13761. memcpy(&buf[2], &tmp, sizeof(tmp));
  13762. n = 4;
  13763. } else {
  13764. uint32_t tmp;
  13765. buf[1] = 127;
  13766. tmp = mg_htonl((uint32_t) (((uint64_t) len) >> 32));
  13767. memcpy(&buf[2], &tmp, sizeof(tmp));
  13768. tmp = mg_htonl((uint32_t) (len & 0xffffffffU));
  13769. memcpy(&buf[6], &tmp, sizeof(tmp));
  13770. n = 10;
  13771. }
  13772. if (is_client) {
  13773. buf[1] |= 1 << 7; // Set masking flag
  13774. mg_random(&buf[n], 4);
  13775. n += 4;
  13776. }
  13777. return n;
  13778. }
  13779. static void mg_ws_mask(struct mg_connection *c, size_t len) {
  13780. if (c->is_client && c->send.buf != NULL) {
  13781. size_t i;
  13782. uint8_t *p = c->send.buf + c->send.len - len, *mask = p - 4;
  13783. for (i = 0; i < len; i++) p[i] ^= mask[i & 3];
  13784. }
  13785. }
  13786. size_t mg_ws_send(struct mg_connection *c, const void *buf, size_t len,
  13787. int op) {
  13788. uint8_t header[14];
  13789. size_t header_len = mkhdr(len, op, c->is_client, header);
  13790. mg_send(c, header, header_len);
  13791. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  13792. mg_send(c, buf, len);
  13793. mg_ws_mask(c, len);
  13794. return header_len + len;
  13795. }
  13796. size_t mg_ws_send2(struct mg_connection *c, const void *buf, size_t len, int op, int max_tlen) {
  13797. uint8_t header[14];
  13798. if(!c) return -1;
  13799. if(max_tlen>0 && c->send.len>max_tlen) {
  13800. mg_iobuf_resize(&c->send, 0);
  13801. }
  13802. size_t header_len = mkhdr(len, op, c->is_client, header);
  13803. mg_send(c, header, header_len);
  13804. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  13805. mg_send(c, buf, len);
  13806. mg_ws_mask(c, len);
  13807. return header_len + len;
  13808. }
  13809. static bool mg_ws_client_handshake(struct mg_connection *c) {
  13810. int n = mg_http_get_request_len(c->recv.buf, c->recv.len);
  13811. if (n < 0) {
  13812. mg_error(c, "not http"); // Some just, not an HTTP request
  13813. } else if (n > 0) {
  13814. if (n < 15 || memcmp(c->recv.buf + 9, "101", 3) != 0) {
  13815. mg_error(c, "ws handshake error");
  13816. } else {
  13817. struct mg_http_message hm;
  13818. if (mg_http_parse((char *) c->recv.buf, c->recv.len, &hm)) {
  13819. c->is_websocket = 1;
  13820. mg_call(c, MG_EV_WS_OPEN, &hm);
  13821. } else {
  13822. mg_error(c, "ws handshake error");
  13823. }
  13824. }
  13825. mg_iobuf_del(&c->recv, 0, (size_t) n);
  13826. } else {
  13827. return true; // Request is not yet received, quit event handler
  13828. }
  13829. return false; // Continue event handler
  13830. }
  13831. static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
  13832. struct ws_msg msg;
  13833. size_t ofs = (size_t) c->pfn_data;
  13834. // assert(ofs < c->recv.len);
  13835. if (ev == MG_EV_READ) {
  13836. if (c->is_client && !c->is_websocket && mg_ws_client_handshake(c)) return;
  13837. while (ws_process(c->recv.buf + ofs, c->recv.len - ofs, &msg) > 0) {
  13838. char *s = (char *) c->recv.buf + ofs + msg.header_len;
  13839. struct mg_ws_message m = {{s, msg.data_len}, msg.flags};
  13840. size_t len = msg.header_len + msg.data_len;
  13841. uint8_t final = msg.flags & 128, op = msg.flags & 15;
  13842. // MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
  13843. // (int) m.data.len, (int) m.data.len, m.data.buf));
  13844. switch (op) {
  13845. case WEBSOCKET_OP_CONTINUE:
  13846. mg_call(c, MG_EV_WS_CTL, &m);
  13847. break;
  13848. case WEBSOCKET_OP_PING:
  13849. MG_DEBUG(("%s", "WS PONG"));
  13850. mg_ws_send(c, s, msg.data_len, WEBSOCKET_OP_PONG);
  13851. mg_call(c, MG_EV_WS_CTL, &m);
  13852. break;
  13853. case WEBSOCKET_OP_PONG:
  13854. mg_call(c, MG_EV_WS_CTL, &m);
  13855. break;
  13856. case WEBSOCKET_OP_TEXT:
  13857. case WEBSOCKET_OP_BINARY:
  13858. if (final) mg_call(c, MG_EV_WS_MSG, &m);
  13859. break;
  13860. case WEBSOCKET_OP_CLOSE:
  13861. MG_DEBUG(("%lu WS CLOSE", c->id));
  13862. mg_call(c, MG_EV_WS_CTL, &m);
  13863. // Echo the payload of the received CLOSE message back to the sender
  13864. mg_ws_send(c, m.data.buf, m.data.len, WEBSOCKET_OP_CLOSE);
  13865. c->is_draining = 1;
  13866. break;
  13867. default:
  13868. // Per RFC6455, close conn when an unknown op is recvd
  13869. mg_error(c, "unknown WS op %d", op);
  13870. break;
  13871. }
  13872. // Handle fragmented frames: strip header, keep in c->recv
  13873. if (final == 0 || op == 0) {
  13874. if (op) ofs++, len--, msg.header_len--; // First frame
  13875. mg_iobuf_del(&c->recv, ofs, msg.header_len); // Strip header
  13876. len -= msg.header_len;
  13877. ofs += len;
  13878. c->pfn_data = (void *) ofs;
  13879. // MG_INFO(("FRAG %d [%.*s]", (int) ofs, (int) ofs, c->recv.buf));
  13880. }
  13881. // Remove non-fragmented frame
  13882. if (final && op) mg_iobuf_del(&c->recv, ofs, len);
  13883. // Last chunk of the fragmented frame
  13884. if (final && !op) {
  13885. m.flags = c->recv.buf[0];
  13886. m.data = mg_str_n((char *) &c->recv.buf[1], (size_t) (ofs - 1));
  13887. mg_call(c, MG_EV_WS_MSG, &m);
  13888. mg_iobuf_del(&c->recv, 0, ofs);
  13889. ofs = 0;
  13890. c->pfn_data = NULL;
  13891. }
  13892. }
  13893. }
  13894. (void) ev_data;
  13895. }
  13896. struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
  13897. mg_event_handler_t fn, void *fn_data,
  13898. const char *fmt, ...) {
  13899. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  13900. if (c != NULL) {
  13901. char nonce[16], key[30];
  13902. struct mg_str host = mg_url_host(url);
  13903. mg_random(nonce, sizeof(nonce));
  13904. mg_base64_encode((unsigned char *) nonce, sizeof(nonce), key, sizeof(key));
  13905. mg_xprintf(mg_pfn_iobuf, &c->send,
  13906. "GET %s HTTP/1.1\r\n"
  13907. "Upgrade: websocket\r\n"
  13908. "Host: %.*s\r\n"
  13909. "Connection: Upgrade\r\n"
  13910. "Sec-WebSocket-Version: 13\r\n"
  13911. "Sec-WebSocket-Key: %s\r\n",
  13912. mg_url_uri(url), (int) host.len, host.buf, key);
  13913. if (fmt != NULL) {
  13914. va_list ap;
  13915. va_start(ap, fmt);
  13916. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  13917. va_end(ap);
  13918. }
  13919. mg_xprintf(mg_pfn_iobuf, &c->send, "\r\n");
  13920. c->pfn = mg_ws_cb;
  13921. c->pfn_data = NULL;
  13922. }
  13923. return c;
  13924. }
  13925. void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
  13926. const char *fmt, ...) {
  13927. struct mg_str *wskey = mg_http_get_header(hm, "Sec-WebSocket-Key");
  13928. c->pfn = mg_ws_cb;
  13929. c->pfn_data = NULL;
  13930. if (wskey == NULL) {
  13931. mg_http_reply(c, 426, "", "WS upgrade expected\n");
  13932. c->is_draining = 1;
  13933. } else {
  13934. struct mg_str *wsproto = mg_http_get_header(hm, "Sec-WebSocket-Protocol");
  13935. va_list ap;
  13936. va_start(ap, fmt);
  13937. ws_handshake(c, wskey, wsproto, fmt, &ap);
  13938. va_end(ap);
  13939. c->is_websocket = 1;
  13940. c->is_resp = 0;
  13941. mg_call(c, MG_EV_WS_OPEN, hm);
  13942. }
  13943. }
  13944. size_t mg_ws_wrap(struct mg_connection *c, size_t len, int op) {
  13945. uint8_t header[14], *p;
  13946. size_t header_len = mkhdr(len, op, c->is_client, header);
  13947. // NOTE: order of operations is important!
  13948. mg_iobuf_add(&c->send, c->send.len, NULL, header_len);
  13949. p = &c->send.buf[c->send.len - len]; // p points to data
  13950. memmove(p, p - header_len, len); // Shift data
  13951. memcpy(p - header_len, header, header_len); // Prepend header
  13952. mg_ws_mask(c, len); // Mask data
  13953. return c->send.len;
  13954. }
  13955. #ifdef MG_ENABLE_LINES
  13956. #line 1 "src/drivers/cmsis.c"
  13957. #endif
  13958. // https://arm-software.github.io/CMSIS_5/Driver/html/index.html
  13959. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
  13960. extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0;
  13961. extern ARM_DRIVER_ETH_PHY Driver_ETH_PHY0;
  13962. static struct mg_tcpip_if *s_ifp;
  13963. static void mac_cb(uint32_t);
  13964. static bool cmsis_init(struct mg_tcpip_if *);
  13965. static bool cmsis_up(struct mg_tcpip_if *);
  13966. static size_t cmsis_tx(const void *, size_t, struct mg_tcpip_if *);
  13967. static size_t cmsis_rx(void *, size_t, struct mg_tcpip_if *);
  13968. struct mg_tcpip_driver mg_tcpip_driver_cmsis = {cmsis_init, cmsis_tx, NULL,
  13969. cmsis_up};
  13970. static bool cmsis_init(struct mg_tcpip_if *ifp) {
  13971. ARM_ETH_MAC_ADDR addr;
  13972. s_ifp = ifp;
  13973. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  13974. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  13975. ARM_ETH_MAC_CAPABILITIES cap = mac->GetCapabilities();
  13976. if (mac->Initialize(mac_cb) != ARM_DRIVER_OK) return false;
  13977. if (phy->Initialize(mac->PHY_Read, mac->PHY_Write) != ARM_DRIVER_OK)
  13978. return false;
  13979. if (cap.event_rx_frame == 0) // polled mode driver
  13980. mg_tcpip_driver_cmsis.rx = cmsis_rx;
  13981. mac->PowerControl(ARM_POWER_FULL);
  13982. if (cap.mac_address) { // driver provides MAC address
  13983. mac->GetMacAddress(&addr);
  13984. memcpy(ifp->mac, &addr, sizeof(ifp->mac));
  13985. } else { // we provide MAC address
  13986. memcpy(&addr, ifp->mac, sizeof(addr));
  13987. mac->SetMacAddress(&addr);
  13988. }
  13989. phy->PowerControl(ARM_POWER_FULL);
  13990. phy->SetInterface(cap.media_interface);
  13991. phy->SetMode(ARM_ETH_PHY_AUTO_NEGOTIATE);
  13992. return true;
  13993. }
  13994. static size_t cmsis_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
  13995. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  13996. if (mac->SendFrame(buf, (uint32_t) len, 0) != ARM_DRIVER_OK) {
  13997. ifp->nerr++;
  13998. return 0;
  13999. }
  14000. ifp->nsent++;
  14001. return len;
  14002. }
  14003. static bool cmsis_up(struct mg_tcpip_if *ifp) {
  14004. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  14005. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  14006. bool up = (phy->GetLinkState() == ARM_ETH_LINK_UP) ? 1 : 0; // link state
  14007. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // just went up
  14008. ARM_ETH_LINK_INFO st = phy->GetLinkInfo();
  14009. mac->Control(ARM_ETH_MAC_CONFIGURE,
  14010. (st.speed << ARM_ETH_MAC_SPEED_Pos) |
  14011. (st.duplex << ARM_ETH_MAC_DUPLEX_Pos) |
  14012. ARM_ETH_MAC_ADDRESS_BROADCAST);
  14013. MG_DEBUG(("Link is %uM %s-duplex",
  14014. (st.speed == 2) ? 1000
  14015. : st.speed ? 100
  14016. : 10,
  14017. st.duplex ? "full" : "half"));
  14018. mac->Control(ARM_ETH_MAC_CONTROL_TX, 1);
  14019. mac->Control(ARM_ETH_MAC_CONTROL_RX, 1);
  14020. } else if ((ifp->state != MG_TCPIP_STATE_DOWN) && !up) { // just went down
  14021. mac->Control(ARM_ETH_MAC_FLUSH,
  14022. ARM_ETH_MAC_FLUSH_TX | ARM_ETH_MAC_FLUSH_RX);
  14023. mac->Control(ARM_ETH_MAC_CONTROL_TX, 0);
  14024. mac->Control(ARM_ETH_MAC_CONTROL_RX, 0);
  14025. }
  14026. return up;
  14027. }
  14028. static void mac_cb(uint32_t ev) {
  14029. if ((ev & ARM_ETH_MAC_EVENT_RX_FRAME) == 0) return;
  14030. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  14031. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  14032. if (len >= 60 && len <= 1518) { // proper frame
  14033. char *p;
  14034. if (mg_queue_book(&s_ifp->recv_queue, &p, len) >= len) { // have room
  14035. if ((len = mac->ReadFrame((uint8_t *) p, len)) > 0) { // copy succeeds
  14036. mg_queue_add(&s_ifp->recv_queue, len);
  14037. s_ifp->nrecv++;
  14038. }
  14039. return;
  14040. }
  14041. s_ifp->ndrop++;
  14042. }
  14043. mac->ReadFrame(NULL, 0); // otherwise, discard
  14044. }
  14045. static size_t cmsis_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  14046. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  14047. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  14048. if (len >= 60 && len <= 1518 &&
  14049. ((len = mac->ReadFrame(buf, (uint32_t) buflen)) > 0))
  14050. return len;
  14051. if (len > 0) mac->ReadFrame(NULL, 0); // discard bad frames
  14052. (void) ifp;
  14053. return 0;
  14054. }
  14055. #endif
  14056. #ifdef MG_ENABLE_LINES
  14057. #line 1 "src/drivers/imxrt.c"
  14058. #endif
  14059. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_IMXRT) && MG_ENABLE_DRIVER_IMXRT
  14060. struct imxrt_enet {
  14061. volatile uint32_t RESERVED0, EIR, EIMR, RESERVED1, RDAR, TDAR, RESERVED2[3],
  14062. ECR, RESERVED3[6], MMFR, MSCR, RESERVED4[7], MIBC, RESERVED5[7], RCR,
  14063. RESERVED6[15], TCR, RESERVED7[7], PALR, PAUR, OPD, TXIC0, TXIC1, TXIC2,
  14064. RESERVED8, RXIC0, RXIC1, RXIC2, RESERVED9[3], IAUR, IALR, GAUR, GALR,
  14065. RESERVED10[7], TFWR, RESERVED11[14], RDSR, TDSR, MRBR[2], RSFL, RSEM,
  14066. RAEM, RAFL, TSEM, TAEM, TAFL, TIPG, FTRL, RESERVED12[3], TACC, RACC,
  14067. RESERVED13[15], RMON_T_PACKETS, RMON_T_BC_PKT, RMON_T_MC_PKT,
  14068. RMON_T_CRC_ALIGN, RMON_T_UNDERSIZE, RMON_T_OVERSIZE, RMON_T_FRAG,
  14069. RMON_T_JAB, RMON_T_COL, RMON_T_P64, RMON_T_P65TO127, RMON_T_P128TO255,
  14070. RMON_T_P256TO511, RMON_T_P512TO1023, RMON_T_P1024TO2048, RMON_T_GTE2048,
  14071. RMON_T_OCTETS, IEEE_T_DROP, IEEE_T_FRAME_OK, IEEE_T_1COL, IEEE_T_MCOL,
  14072. IEEE_T_DEF, IEEE_T_LCOL, IEEE_T_EXCOL, IEEE_T_MACERR, IEEE_T_CSERR,
  14073. IEEE_T_SQE, IEEE_T_FDXFC, IEEE_T_OCTETS_OK, RESERVED14[3], RMON_R_PACKETS,
  14074. RMON_R_BC_PKT, RMON_R_MC_PKT, RMON_R_CRC_ALIGN, RMON_R_UNDERSIZE,
  14075. RMON_R_OVERSIZE, RMON_R_FRAG, RMON_R_JAB, RESERVED15, RMON_R_P64,
  14076. RMON_R_P65TO127, RMON_R_P128TO255, RMON_R_P256TO511, RMON_R_P512TO1023,
  14077. RMON_R_P1024TO2047, RMON_R_GTE2048, RMON_R_OCTETS, IEEE_R_DROP,
  14078. IEEE_R_FRAME_OK, IEEE_R_CRC, IEEE_R_ALIGN, IEEE_R_MACERR, IEEE_R_FDXFC,
  14079. IEEE_R_OCTETS_OK, RESERVED16[71], ATCR, ATVR, ATOFF, ATPER, ATCOR, ATINC,
  14080. ATSTMP, RESERVED17[122], TGSR, TCSR0, TCCR0, TCSR1, TCCR1, TCSR2, TCCR2,
  14081. TCSR3;
  14082. };
  14083. #undef ENET
  14084. #if defined(MG_DRIVER_IMXRT_RT11) && MG_DRIVER_IMXRT_RT11
  14085. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x40424000U)
  14086. #define ETH_DESC_CNT 5 // Descriptors count
  14087. #else
  14088. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x402D8000U)
  14089. #define ETH_DESC_CNT 4 // Descriptors count
  14090. #endif
  14091. #define ETH_PKT_SIZE 1536 // Max frame size, 64-bit aligned
  14092. struct enet_desc {
  14093. uint16_t length; // Data length
  14094. uint16_t control; // Control and status
  14095. uint32_t *buffer; // Data ptr
  14096. };
  14097. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  14098. #define MG_64BYTE_ALIGNED __attribute__((aligned((64U))))
  14099. // Descriptors: in non-cached area (TODO(scaprile)), (37.5.1.22.2 37.5.1.23.2)
  14100. // Buffers: 64-byte aligned (37.3.14)
  14101. static volatile struct enet_desc s_rxdesc[ETH_DESC_CNT] MG_64BYTE_ALIGNED;
  14102. static volatile struct enet_desc s_txdesc[ETH_DESC_CNT] MG_64BYTE_ALIGNED;
  14103. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BYTE_ALIGNED;
  14104. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BYTE_ALIGNED;
  14105. static struct mg_tcpip_if *s_ifp; // MIP interface
  14106. static uint16_t enet_read_phy(uint8_t addr, uint8_t reg) {
  14107. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  14108. ENET->MMFR = (1 << 30) | (2 << 28) | (addr << 23) | (reg << 18) | (2 << 16);
  14109. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  14110. return ENET->MMFR & 0xffff;
  14111. }
  14112. static void enet_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14113. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  14114. ENET->MMFR =
  14115. (1 << 30) | (1 << 28) | (addr << 23) | (reg << 18) | (2 << 16) | val;
  14116. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  14117. }
  14118. // MDC clock is generated from IPS Bus clock (ipg_clk); as per 802.3,
  14119. // it must not exceed 2.5MHz
  14120. // The PHY receives the PLL6-generated 50MHz clock
  14121. static bool mg_tcpip_driver_imxrt_init(struct mg_tcpip_if *ifp) {
  14122. struct mg_tcpip_driver_imxrt_data *d =
  14123. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  14124. s_ifp = ifp;
  14125. // Init RX descriptors
  14126. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14127. s_rxdesc[i].control = MG_BIT(15); // Own (E)
  14128. s_rxdesc[i].buffer = (uint32_t *) s_rxbuf[i]; // Point to data buffer
  14129. }
  14130. s_rxdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  14131. // Init TX descriptors
  14132. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14133. // s_txdesc[i].control = MG_BIT(10); // Own (TC)
  14134. s_txdesc[i].buffer = (uint32_t *) s_txbuf[i];
  14135. }
  14136. s_txdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  14137. ENET->ECR = MG_BIT(0); // Software reset, disable
  14138. while ((ENET->ECR & MG_BIT(0))) (void) 0; // Wait until done
  14139. // Set MDC clock divider. If user told us the value, use it.
  14140. // TODO(): Otherwise, guess (currently assuming max freq)
  14141. int cr = (d == NULL || d->mdc_cr < 0) ? 24 : d->mdc_cr;
  14142. ENET->MSCR = (1 << 8) | ((cr & 0x3f) << 1); // HOLDTIME 2 clks
  14143. struct mg_phy phy = {enet_read_phy, enet_write_phy};
  14144. mg_phy_init(&phy, d->phy_addr, MG_PHY_LEDS_ACTIVE_HIGH); // MAC clocks PHY
  14145. // Select RMII mode, 100M, keep CRC, set max rx length, disable loop
  14146. ENET->RCR = (1518 << 16) | MG_BIT(8) | MG_BIT(2);
  14147. // ENET->RCR |= MG_BIT(3); // Receive all
  14148. ENET->TCR = MG_BIT(2); // Full-duplex
  14149. ENET->RDSR = (uint32_t) (uintptr_t) s_rxdesc;
  14150. ENET->TDSR = (uint32_t) (uintptr_t) s_txdesc;
  14151. ENET->MRBR[0] = ETH_PKT_SIZE; // Same size for RX/TX buffers
  14152. // MAC address filtering (bytes in reversed order)
  14153. ENET->PAUR = ((uint32_t) ifp->mac[4] << 24U) | (uint32_t) ifp->mac[5] << 16U;
  14154. ENET->PALR = (uint32_t) (ifp->mac[0] << 24U) |
  14155. ((uint32_t) ifp->mac[1] << 16U) |
  14156. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  14157. ENET->ECR = MG_BIT(8) | MG_BIT(1); // Little-endian CPU, Enable
  14158. ENET->EIMR = MG_BIT(25); // Set interrupt mask
  14159. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  14160. ENET->TDAR = MG_BIT(24); // Transmit Descriptors have changed
  14161. // ENET->OPD = 0x10014;
  14162. return true;
  14163. }
  14164. // Transmit frame
  14165. static size_t mg_tcpip_driver_imxrt_tx(const void *buf, size_t len,
  14166. struct mg_tcpip_if *ifp) {
  14167. static int s_txno; // Current descriptor index
  14168. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  14169. MG_ERROR(("Frame too big, %ld", (long) len));
  14170. len = (size_t) -1; // fail
  14171. } else if ((s_txdesc[s_txno].control & MG_BIT(15))) {
  14172. ifp->nerr++;
  14173. MG_ERROR(("No descriptors available"));
  14174. len = 0; // retry later
  14175. } else {
  14176. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14177. s_txdesc[s_txno].length = (uint16_t) len; // Set data len
  14178. // Table 37-34, R, L, TC (Ready, last, transmit CRC after frame
  14179. s_txdesc[s_txno].control |=
  14180. (uint16_t) (MG_BIT(15) | MG_BIT(11) | MG_BIT(10));
  14181. ENET->TDAR = MG_BIT(24); // Descriptor ring updated
  14182. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14183. }
  14184. (void) ifp;
  14185. return len;
  14186. }
  14187. static bool mg_tcpip_driver_imxrt_up(struct mg_tcpip_if *ifp) {
  14188. struct mg_tcpip_driver_imxrt_data *d =
  14189. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  14190. uint8_t speed = MG_PHY_SPEED_10M;
  14191. bool up = false, full_duplex = false;
  14192. struct mg_phy phy = {enet_read_phy, enet_write_phy};
  14193. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  14194. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14195. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14196. // if(link is slow or half) set flags otherwise
  14197. // reg = tmp
  14198. uint32_t tcr = ENET->TCR | MG_BIT(2); // Full-duplex
  14199. uint32_t rcr = ENET->RCR & ~MG_BIT(9); // 100M
  14200. if (speed == MG_PHY_SPEED_10M) rcr |= MG_BIT(9); // 10M
  14201. if (full_duplex == false) tcr &= ~MG_BIT(2); // Half-duplex
  14202. ENET->TCR = tcr; // IRQ handler does not fiddle with these registers
  14203. ENET->RCR = rcr;
  14204. MG_DEBUG(("Link is %uM %s-duplex", rcr & MG_BIT(9) ? 10 : 100,
  14205. tcr & MG_BIT(2) ? "full" : "half"));
  14206. }
  14207. return up;
  14208. }
  14209. void ENET_IRQHandler(void);
  14210. static uint32_t s_rxno;
  14211. void ENET_IRQHandler(void) {
  14212. ENET->EIR = MG_BIT(25); // Ack IRQ
  14213. // Frame received, loop
  14214. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14215. uint32_t r = s_rxdesc[s_rxno].control;
  14216. if (r & MG_BIT(15)) break; // exit when done
  14217. // skip partial/errored frames (Table 37-32)
  14218. if ((r & MG_BIT(11)) &&
  14219. !(r & (MG_BIT(5) | MG_BIT(4) | MG_BIT(2) | MG_BIT(1) | MG_BIT(0)))) {
  14220. size_t len = s_rxdesc[s_rxno].length;
  14221. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  14222. }
  14223. s_rxdesc[s_rxno].control |= MG_BIT(15);
  14224. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14225. }
  14226. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  14227. // If b24 == 0, descriptors were exhausted and probably frames were dropped
  14228. }
  14229. struct mg_tcpip_driver mg_tcpip_driver_imxrt = {mg_tcpip_driver_imxrt_init,
  14230. mg_tcpip_driver_imxrt_tx, NULL,
  14231. mg_tcpip_driver_imxrt_up};
  14232. #endif
  14233. #ifdef MG_ENABLE_LINES
  14234. #line 1 "src/drivers/phy.c"
  14235. #endif
  14236. enum { // ID1 ID2
  14237. MG_PHY_KSZ8x = 0x22, // 0022 1561 - KSZ8081RNB
  14238. MG_PHY_DP83x = 0x2000, // 2000 a140 - TI DP83825I
  14239. MG_PHY_DP83867 = 0xa231, // 2000 a231 - TI DP83867I
  14240. MG_PHY_LAN87x = 0x7, // 0007 c0fx - LAN8720
  14241. MG_PHY_RTL8201 = 0x1C // 001c c816 - RTL8201
  14242. };
  14243. enum {
  14244. MG_PHY_REG_BCR = 0,
  14245. MG_PHY_REG_BSR = 1,
  14246. MG_PHY_REG_ID1 = 2,
  14247. MG_PHY_REG_ID2 = 3,
  14248. MG_PHY_DP83x_REG_PHYSTS = 16,
  14249. MG_PHY_DP83867_REG_PHYSTS = 17,
  14250. MG_PHY_DP83x_REG_RCSR = 23,
  14251. MG_PHY_DP83x_REG_LEDCR = 24,
  14252. MG_PHY_KSZ8x_REG_PC1R = 30,
  14253. MG_PHY_KSZ8x_REG_PC2R = 31,
  14254. MG_PHY_LAN87x_REG_SCSR = 31,
  14255. MG_PHY_RTL8201_REG_RMSR = 16, // in page 7
  14256. MG_PHY_RTL8201_REG_PAGESEL = 31
  14257. };
  14258. static const char *mg_phy_id_to_str(uint16_t id1, uint16_t id2) {
  14259. switch (id1) {
  14260. case MG_PHY_DP83x:
  14261. switch (id2) {
  14262. case MG_PHY_DP83867:
  14263. return "DP83867";
  14264. default:
  14265. return "DP83x";
  14266. }
  14267. case MG_PHY_KSZ8x:
  14268. return "KSZ8x";
  14269. case MG_PHY_LAN87x:
  14270. return "LAN87x";
  14271. case MG_PHY_RTL8201:
  14272. return "RTL8201";
  14273. default:
  14274. return "unknown";
  14275. }
  14276. (void) id2;
  14277. }
  14278. void mg_phy_init(struct mg_phy *phy, uint8_t phy_addr, uint8_t config) {
  14279. uint16_t id1, id2;
  14280. phy->write_reg(phy_addr, MG_PHY_REG_BCR, MG_BIT(15)); // Reset PHY
  14281. while (phy->read_reg(phy_addr, MG_PHY_REG_BCR) & MG_BIT(15)) (void) 0;
  14282. // MG_PHY_REG_BCR[12]: Autonegotiation is default unless hw says otherwise
  14283. id1 = phy->read_reg(phy_addr, MG_PHY_REG_ID1);
  14284. id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
  14285. MG_INFO(("PHY ID: %#04x %#04x (%s)", id1, id2, mg_phy_id_to_str(id1, id2)));
  14286. if (id1 == MG_PHY_DP83x && id2 == MG_PHY_DP83867) {
  14287. phy->write_reg(phy_addr, 0x0d, 0x1f); // write 0x10d to IO_MUX_CFG (0x0170)
  14288. phy->write_reg(phy_addr, 0x0e, 0x170);
  14289. phy->write_reg(phy_addr, 0x0d, 0x401f);
  14290. phy->write_reg(phy_addr, 0x0e, 0x10d);
  14291. }
  14292. if (config & MG_PHY_CLOCKS_MAC) {
  14293. // Use PHY crystal oscillator (preserve defaults)
  14294. // nothing to do
  14295. } else { // MAC clocks PHY, PHY has no xtal
  14296. // Enable 50 MHz external ref clock at XI (preserve defaults)
  14297. if (id1 == MG_PHY_DP83x && id2 != MG_PHY_DP83867) {
  14298. phy->write_reg(phy_addr, MG_PHY_DP83x_REG_RCSR, MG_BIT(7) | MG_BIT(0));
  14299. } else if (id1 == MG_PHY_KSZ8x) {
  14300. phy->write_reg(phy_addr, MG_PHY_KSZ8x_REG_PC2R,
  14301. MG_BIT(15) | MG_BIT(8) | MG_BIT(7));
  14302. } else if (id1 == MG_PHY_LAN87x) {
  14303. // nothing to do
  14304. } else if (id1 == MG_PHY_RTL8201) {
  14305. // assume PHY has been hardware strapped properly
  14306. #if 0
  14307. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_PAGESEL, 7); // Select page 7
  14308. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_RMSR, 0x1ffa);
  14309. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_PAGESEL, 0); // Select page 0
  14310. #endif
  14311. }
  14312. }
  14313. if (config & MG_PHY_LEDS_ACTIVE_HIGH && id1 == MG_PHY_DP83x) {
  14314. phy->write_reg(phy_addr, MG_PHY_DP83x_REG_LEDCR,
  14315. MG_BIT(9) | MG_BIT(7)); // LED status, active high
  14316. } // Other PHYs do not support this feature
  14317. }
  14318. bool mg_phy_up(struct mg_phy *phy, uint8_t phy_addr, bool *full_duplex,
  14319. uint8_t *speed) {
  14320. bool up = false;
  14321. uint16_t bsr = phy->read_reg(phy_addr, MG_PHY_REG_BSR);
  14322. if ((bsr & MG_BIT(5)) && !(bsr & MG_BIT(2))) // some PHYs latch down events
  14323. bsr = phy->read_reg(phy_addr, MG_PHY_REG_BSR); // read again
  14324. up = bsr & MG_BIT(2);
  14325. if (up && full_duplex != NULL && speed != NULL) {
  14326. uint16_t id1 = phy->read_reg(phy_addr, MG_PHY_REG_ID1);
  14327. if (id1 == MG_PHY_DP83x) {
  14328. uint16_t id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
  14329. if (id2 == MG_PHY_DP83867) {
  14330. uint16_t physts = phy->read_reg(phy_addr, MG_PHY_DP83867_REG_PHYSTS);
  14331. *full_duplex = physts & MG_BIT(13);
  14332. *speed = (physts & MG_BIT(15)) ? MG_PHY_SPEED_1000M
  14333. : (physts & MG_BIT(14)) ? MG_PHY_SPEED_100M
  14334. : MG_PHY_SPEED_10M;
  14335. } else {
  14336. uint16_t physts = phy->read_reg(phy_addr, MG_PHY_DP83x_REG_PHYSTS);
  14337. *full_duplex = physts & MG_BIT(2);
  14338. *speed = (physts & MG_BIT(1)) ? MG_PHY_SPEED_10M : MG_PHY_SPEED_100M;
  14339. }
  14340. } else if (id1 == MG_PHY_KSZ8x) {
  14341. uint16_t pc1r = phy->read_reg(phy_addr, MG_PHY_KSZ8x_REG_PC1R);
  14342. *full_duplex = pc1r & MG_BIT(2);
  14343. *speed = (pc1r & 3) == 1 ? MG_PHY_SPEED_10M : MG_PHY_SPEED_100M;
  14344. } else if (id1 == MG_PHY_LAN87x) {
  14345. uint16_t scsr = phy->read_reg(phy_addr, MG_PHY_LAN87x_REG_SCSR);
  14346. *full_duplex = scsr & MG_BIT(4);
  14347. *speed = (scsr & MG_BIT(3)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
  14348. } else if (id1 == MG_PHY_RTL8201) {
  14349. uint16_t bcr = phy->read_reg(phy_addr, MG_PHY_REG_BCR);
  14350. *full_duplex = bcr & MG_BIT(8);
  14351. *speed = (bcr & MG_BIT(13)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
  14352. }
  14353. }
  14354. return up;
  14355. }
  14356. #ifdef MG_ENABLE_LINES
  14357. #line 1 "src/drivers/ra.c"
  14358. #endif
  14359. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RA) && MG_ENABLE_DRIVER_RA
  14360. struct ra_etherc {
  14361. volatile uint32_t ECMR, RESERVED, RFLR, RESERVED1, ECSR, RESERVED2, ECSIPR,
  14362. RESERVED3, PIR, RESERVED4, PSR, RESERVED5[5], RDMLR, RESERVED6[3], IPGR,
  14363. APR, MPR, RESERVED7, RFCF, TPAUSER, TPAUSECR, BCFRR, RESERVED8[20], MAHR,
  14364. RESERVED9, MALR, RESERVED10, TROCR, CDCR, LCCR, CNDCR, RESERVED11, CEFCR,
  14365. FRECR, TSFRCR, TLFRCR, RFCR, MAFCR;
  14366. };
  14367. struct ra_edmac {
  14368. volatile uint32_t EDMR, RESERVED, EDTRR, RESERVED1, EDRRR, RESERVED2, TDLAR,
  14369. RESERVED3, RDLAR, RESERVED4, EESR, RESERVED5, EESIPR, RESERVED6, TRSCER,
  14370. RESERVED7, RMFCR, RESERVED8, TFTR, RESERVED9, FDR, RESERVED10, RMCR,
  14371. RESERVED11[2], TFUCR, RFOCR, IOSR, FCFTR, RESERVED12, RPADIR, TRIMD,
  14372. RESERVED13[18], RBWAR, RDFAR, RESERVED14, TBRAR, TDFAR;
  14373. };
  14374. #undef ETHERC
  14375. #define ETHERC ((struct ra_etherc *) (uintptr_t) 0x40114100U)
  14376. #undef EDMAC
  14377. #define EDMAC ((struct ra_edmac *) (uintptr_t) 0x40114000U)
  14378. #undef RASYSC
  14379. #define RASYSC ((uint32_t *) (uintptr_t) 0x4001E000U)
  14380. #undef ICU_IELSR
  14381. #define ICU_IELSR ((uint32_t *) (uintptr_t) 0x40006300U)
  14382. #define ETH_PKT_SIZE 1536 // Max frame size, multiple of 32
  14383. #define ETH_DESC_CNT 4 // Descriptors count
  14384. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  14385. #define MG_16BYTE_ALIGNED __attribute__((aligned((16U))))
  14386. #define MG_32BYTE_ALIGNED __attribute__((aligned((32U))))
  14387. // Descriptors: 16-byte aligned
  14388. // Buffers: 32-byte aligned (27.3.1)
  14389. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][4] MG_16BYTE_ALIGNED;
  14390. static volatile uint32_t s_txdesc[ETH_DESC_CNT][4] MG_16BYTE_ALIGNED;
  14391. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_32BYTE_ALIGNED;
  14392. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_32BYTE_ALIGNED;
  14393. static struct mg_tcpip_if *s_ifp; // MIP interface
  14394. // fastest is 3 cycles (SUB + BNE) on a 3-stage pipeline or equivalent
  14395. static inline void raspin(volatile uint32_t count) {
  14396. while (count--) (void) 0;
  14397. }
  14398. // count to get the 200ns SMC semi-cycle period (2.5MHz) calling raspin():
  14399. // SYS_FREQUENCY * 200ns / 3 = SYS_FREQUENCY / 15000000
  14400. static uint32_t s_smispin;
  14401. // Bit-banged SMI
  14402. static void smi_preamble(void) {
  14403. unsigned int i = 32;
  14404. uint32_t pir = MG_BIT(1) | MG_BIT(2); // write, mdio = 1, mdc = 0
  14405. ETHERC->PIR = pir;
  14406. while (i--) {
  14407. pir &= ~MG_BIT(0); // mdc = 0
  14408. ETHERC->PIR = pir;
  14409. raspin(s_smispin);
  14410. pir |= MG_BIT(0); // mdc = 1
  14411. ETHERC->PIR = pir;
  14412. raspin(s_smispin);
  14413. }
  14414. }
  14415. static void smi_wr(uint16_t header, uint16_t data) {
  14416. uint32_t word = (header << 16) | data;
  14417. smi_preamble();
  14418. unsigned int i = 32;
  14419. while (i--) {
  14420. uint32_t pir = MG_BIT(1) |
  14421. (word & 0x80000000 ? MG_BIT(2) : 0); // write, mdc = 0, data
  14422. ETHERC->PIR = pir;
  14423. raspin(s_smispin);
  14424. pir |= MG_BIT(0); // mdc = 1
  14425. ETHERC->PIR = pir;
  14426. raspin(s_smispin);
  14427. word <<= 1;
  14428. }
  14429. }
  14430. static uint16_t smi_rd(uint16_t header) {
  14431. smi_preamble();
  14432. unsigned int i = 16; // 2 LSb as turnaround
  14433. uint32_t pir;
  14434. while (i--) {
  14435. pir = (i > 1 ? MG_BIT(1) : 0) |
  14436. (header & 0x8000
  14437. ? MG_BIT(2)
  14438. : 0); // mdc = 0, header, set read direction at turnaround
  14439. ETHERC->PIR = pir;
  14440. raspin(s_smispin);
  14441. pir |= MG_BIT(0); // mdc = 1
  14442. ETHERC->PIR = pir;
  14443. raspin(s_smispin);
  14444. header <<= 1;
  14445. }
  14446. i = 16;
  14447. uint16_t data = 0;
  14448. while (i--) {
  14449. data <<= 1;
  14450. pir = 0; // read, mdc = 0
  14451. ETHERC->PIR = pir;
  14452. raspin(s_smispin / 2); // 1/4 clock period, 300ns max access time
  14453. data |= (uint16_t)(ETHERC->PIR & MG_BIT(3) ? 1 : 0); // read mdio
  14454. raspin(s_smispin / 2); // 1/4 clock period
  14455. pir |= MG_BIT(0); // mdc = 1
  14456. ETHERC->PIR = pir;
  14457. raspin(s_smispin);
  14458. }
  14459. return data;
  14460. }
  14461. static uint16_t raeth_read_phy(uint8_t addr, uint8_t reg) {
  14462. return smi_rd((uint16_t)((1 << 14) | (2 << 12) | (addr << 7) | (reg << 2) | (2 << 0)));
  14463. }
  14464. static void raeth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14465. smi_wr((uint16_t)((1 << 14) | (1 << 12) | (addr << 7) | (reg << 2) | (2 << 0)), val);
  14466. }
  14467. // MDC clock is generated manually; as per 802.3, it must not exceed 2.5MHz
  14468. static bool mg_tcpip_driver_ra_init(struct mg_tcpip_if *ifp) {
  14469. struct mg_tcpip_driver_ra_data *d =
  14470. (struct mg_tcpip_driver_ra_data *) ifp->driver_data;
  14471. s_ifp = ifp;
  14472. // Init SMI clock timing. If user told us the clock value, use it.
  14473. // TODO(): Otherwise, guess
  14474. s_smispin = d->clock / 15000000;
  14475. // Init RX descriptors
  14476. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14477. s_rxdesc[i][0] = MG_BIT(31); // RACT
  14478. s_rxdesc[i][1] = ETH_PKT_SIZE << 16; // RBL
  14479. s_rxdesc[i][2] = (uint32_t) s_rxbuf[i]; // Point to data buffer
  14480. }
  14481. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(30); // Wrap last descriptor
  14482. // Init TX descriptors
  14483. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14484. // TACT = 0
  14485. s_txdesc[i][2] = (uint32_t) s_txbuf[i];
  14486. }
  14487. s_txdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(30); // Wrap last descriptor
  14488. EDMAC->EDMR = MG_BIT(0); // Software reset, wait 64 PCLKA clocks (27.2.1)
  14489. uint32_t sckdivcr = RASYSC[8]; // get divisors from SCKDIVCR (8.2.2)
  14490. uint32_t ick = 1 << ((sckdivcr >> 24) & 7); // sys_clock div
  14491. uint32_t pcka = 1 << ((sckdivcr >> 12) & 7); // pclka div
  14492. raspin((64U * pcka) / (3U * ick));
  14493. EDMAC->EDMR = MG_BIT(6); // Initialize, little-endian (27.2.1)
  14494. MG_DEBUG(("PHY addr: %d, smispin: %d", d->phy_addr, s_smispin));
  14495. struct mg_phy phy = {raeth_read_phy, raeth_write_phy};
  14496. mg_phy_init(&phy, d->phy_addr, 0); // MAC clocks PHY
  14497. // Select RMII mode,
  14498. ETHERC->ECMR = MG_BIT(2) | MG_BIT(1); // 100M, Full-duplex, CRC
  14499. // ETHERC->ECMR |= MG_BIT(0); // Receive all
  14500. ETHERC->RFLR = 1518; // Set max rx length
  14501. EDMAC->RDLAR = (uint32_t) (uintptr_t) s_rxdesc;
  14502. EDMAC->TDLAR = (uint32_t) (uintptr_t) s_txdesc;
  14503. // MAC address filtering (bytes in reversed order)
  14504. ETHERC->MAHR = (uint32_t) (ifp->mac[0] << 24U) |
  14505. ((uint32_t) ifp->mac[1] << 16U) |
  14506. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  14507. ETHERC->MALR = ((uint32_t) ifp->mac[4] << 8U) | ifp->mac[5];
  14508. EDMAC->TFTR = 0; // Store and forward (27.2.10)
  14509. EDMAC->FDR = 0x070f; // (27.2.11)
  14510. EDMAC->RMCR = MG_BIT(0); // (27.2.12)
  14511. ETHERC->ECMR |= MG_BIT(6) | MG_BIT(5); // TE RE
  14512. EDMAC->EESIPR = MG_BIT(18); // Enable Rx IRQ
  14513. EDMAC->EDRRR = MG_BIT(0); // Receive Descriptors have changed
  14514. EDMAC->EDTRR = MG_BIT(0); // Transmit Descriptors have changed
  14515. return true;
  14516. }
  14517. // Transmit frame
  14518. static size_t mg_tcpip_driver_ra_tx(const void *buf, size_t len,
  14519. struct mg_tcpip_if *ifp) {
  14520. static int s_txno; // Current descriptor index
  14521. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  14522. MG_ERROR(("Frame too big, %ld", (long) len));
  14523. len = (size_t) -1; // fail
  14524. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  14525. ifp->nerr++;
  14526. MG_ERROR(("No descriptors available"));
  14527. len = 0; // retry later
  14528. } else {
  14529. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14530. s_txdesc[s_txno][1] = len << 16; // Set data len
  14531. s_txdesc[s_txno][0] |= MG_BIT(31) | 3 << 28; // (27.3.1.1) mark valid
  14532. EDMAC->EDTRR = MG_BIT(0); // Transmit request
  14533. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14534. }
  14535. return len;
  14536. }
  14537. static bool mg_tcpip_driver_ra_up(struct mg_tcpip_if *ifp) {
  14538. struct mg_tcpip_driver_ra_data *d =
  14539. (struct mg_tcpip_driver_ra_data *) ifp->driver_data;
  14540. uint8_t speed = MG_PHY_SPEED_10M;
  14541. bool up = false, full_duplex = false;
  14542. struct mg_phy phy = {raeth_read_phy, raeth_write_phy};
  14543. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  14544. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14545. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14546. // if(link is slow or half) set flags otherwise
  14547. // reg = tmp
  14548. uint32_t ecmr = ETHERC->ECMR | MG_BIT(2) | MG_BIT(1); // 100M Full-duplex
  14549. if (speed == MG_PHY_SPEED_10M) ecmr &= ~MG_BIT(2); // 10M
  14550. if (full_duplex == false) ecmr &= ~MG_BIT(1); // Half-duplex
  14551. ETHERC->ECMR = ecmr; // IRQ handler does not fiddle with these registers
  14552. MG_DEBUG(("Link is %uM %s-duplex", ecmr & MG_BIT(2) ? 100 : 10,
  14553. ecmr & MG_BIT(1) ? "full" : "half"));
  14554. }
  14555. return up;
  14556. }
  14557. void EDMAC_IRQHandler(void);
  14558. static uint32_t s_rxno;
  14559. void EDMAC_IRQHandler(void) {
  14560. struct mg_tcpip_driver_ra_data *d =
  14561. (struct mg_tcpip_driver_ra_data *) s_ifp->driver_data;
  14562. EDMAC->EESR = MG_BIT(18); // Ack IRQ in EDMAC 1st
  14563. ICU_IELSR[d->irqno] &= ~MG_BIT(16); // Ack IRQ in ICU last
  14564. // Frame received, loop
  14565. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14566. uint32_t r = s_rxdesc[s_rxno][0];
  14567. if (r & MG_BIT(31)) break; // exit when done
  14568. // skip partial/errored frames (27.3.1.2)
  14569. if ((r & (MG_BIT(29) | MG_BIT(28)) && !(r & MG_BIT(27)))) {
  14570. size_t len = s_rxdesc[s_rxno][1] & 0xffff;
  14571. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp); // CRC already stripped
  14572. }
  14573. s_rxdesc[s_rxno][0] |= MG_BIT(31);
  14574. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14575. }
  14576. EDMAC->EDRRR = MG_BIT(0); // Receive Descriptors have changed
  14577. // If b0 == 0, descriptors were exhausted and probably frames were dropped,
  14578. // (27.2.9 RMFCR counts them)
  14579. }
  14580. struct mg_tcpip_driver mg_tcpip_driver_ra = {mg_tcpip_driver_ra_init,
  14581. mg_tcpip_driver_ra_tx, NULL,
  14582. mg_tcpip_driver_ra_up};
  14583. #endif
  14584. #ifdef MG_ENABLE_LINES
  14585. #line 1 "src/drivers/same54.c"
  14586. #endif
  14587. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && MG_ENABLE_DRIVER_SAME54
  14588. #include <sam.h>
  14589. #define ETH_PKT_SIZE 1536 // Max frame size
  14590. #define ETH_DESC_CNT 4 // Descriptors count
  14591. #define ETH_DS 2 // Descriptor size (words)
  14592. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  14593. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  14594. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  14595. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  14596. static uint8_t s_txno; // Current TX descriptor
  14597. static uint8_t s_rxno; // Current RX descriptor
  14598. static struct mg_tcpip_if *s_ifp; // MIP interface
  14599. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  14600. #define MG_PHYREGBIT_BCR_DUPLEX_MODE MG_BIT(8)
  14601. #define MG_PHYREGBIT_BCR_SPEED MG_BIT(13)
  14602. #define MG_PHYREGBIT_BSR_LINK_STATUS MG_BIT(2)
  14603. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  14604. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk |
  14605. GMAC_MAN_OP(2) | // Setting the read operation
  14606. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  14607. GMAC_MAN_REGA(reg); // Setting the register
  14608. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)) (void) 0;
  14609. return GMAC_REGS->GMAC_MAN & GMAC_MAN_DATA_Msk; // Getting the read value
  14610. }
  14611. #if 0
  14612. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14613. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk | GMAC_MAN_OP(1) | // Setting the write operation
  14614. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  14615. GMAC_MAN_REGA(reg) | GMAC_MAN_DATA(val); // Setting the register
  14616. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)); // Waiting until the write op is complete
  14617. }
  14618. #endif
  14619. int get_clock_rate(struct mg_tcpip_driver_same54_data *d) {
  14620. if (d && d->mdc_cr >= 0 && d->mdc_cr <= 5) {
  14621. return d->mdc_cr;
  14622. } else {
  14623. // get MCLK from GCLK_GENERATOR 0
  14624. uint32_t div = 512;
  14625. uint32_t mclk;
  14626. if (!(GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_DIVSEL_Msk)) {
  14627. div = ((GCLK_REGS->GCLK_GENCTRL[0] & 0x00FF0000) >> 16);
  14628. if (div == 0) div = 1;
  14629. }
  14630. switch (GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_SRC_Msk) {
  14631. case GCLK_GENCTRL_SRC_XOSC0_Val:
  14632. mclk = 32000000UL; /* 32MHz */
  14633. break;
  14634. case GCLK_GENCTRL_SRC_XOSC1_Val:
  14635. mclk = 32000000UL; /* 32MHz */
  14636. break;
  14637. case GCLK_GENCTRL_SRC_OSCULP32K_Val:
  14638. mclk = 32000UL;
  14639. break;
  14640. case GCLK_GENCTRL_SRC_XOSC32K_Val:
  14641. mclk = 32000UL;
  14642. break;
  14643. case GCLK_GENCTRL_SRC_DFLL_Val:
  14644. mclk = 48000000UL; /* 48MHz */
  14645. break;
  14646. case GCLK_GENCTRL_SRC_DPLL0_Val:
  14647. mclk = 200000000UL; /* 200MHz */
  14648. break;
  14649. case GCLK_GENCTRL_SRC_DPLL1_Val:
  14650. mclk = 200000000UL; /* 200MHz */
  14651. break;
  14652. default:
  14653. mclk = 200000000UL; /* 200MHz */
  14654. }
  14655. mclk /= div;
  14656. uint8_t crs[] = {0, 1, 2, 3, 4, 5}; // GMAC->NCFGR::CLK values
  14657. uint8_t dividers[] = {8, 16, 32, 48, 64, 96}; // Respective CLK dividers
  14658. for (int i = 0; i < 6; i++) {
  14659. if (mclk / dividers[i] <= 2375000UL /* 2.5MHz - 5% */) {
  14660. return crs[i];
  14661. }
  14662. }
  14663. return 5;
  14664. }
  14665. }
  14666. static bool mg_tcpip_driver_same54_init(struct mg_tcpip_if *ifp) {
  14667. struct mg_tcpip_driver_same54_data *d =
  14668. (struct mg_tcpip_driver_same54_data *) ifp->driver_data;
  14669. s_ifp = ifp;
  14670. MCLK_REGS->MCLK_APBCMASK |= MCLK_APBCMASK_GMAC_Msk;
  14671. MCLK_REGS->MCLK_AHBMASK |= MCLK_AHBMASK_GMAC_Msk;
  14672. GMAC_REGS->GMAC_NCFGR = GMAC_NCFGR_CLK(get_clock_rate(d)); // Set MDC divider
  14673. GMAC_REGS->GMAC_NCR = 0; // Disable RX & TX
  14674. GMAC_REGS->GMAC_NCR |= GMAC_NCR_MPE_Msk; // Enable MDC & MDIO
  14675. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init TX descriptors
  14676. s_txdesc[i][0] = (uint32_t) s_txbuf[i]; // Point to data buffer
  14677. s_txdesc[i][1] = MG_BIT(31); // OWN bit
  14678. }
  14679. s_txdesc[ETH_DESC_CNT - 1][1] |= MG_BIT(30); // Last tx descriptor - wrap
  14680. GMAC_REGS->GMAC_DCFGR = GMAC_DCFGR_DRBS(0x18) // DMA recv buf 1536
  14681. | GMAC_DCFGR_RXBMS(GMAC_DCFGR_RXBMS_FULL_Val) |
  14682. GMAC_DCFGR_TXPBMS(1); // See #2487
  14683. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init RX descriptors
  14684. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i]; // Address of the data buffer
  14685. s_rxdesc[i][1] = 0; // Clear status
  14686. }
  14687. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(1); // Last rx descriptor - wrap
  14688. GMAC_REGS->GMAC_TBQB = (uint32_t) s_txdesc; // about the descriptor addresses
  14689. GMAC_REGS->GMAC_RBQB = (uint32_t) s_rxdesc; // Let the controller know
  14690. GMAC_REGS->SA[0].GMAC_SAB =
  14691. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  14692. GMAC_REGS->SA[0].GMAC_SAT = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  14693. GMAC_REGS->GMAC_UR &= ~GMAC_UR_MII_Msk; // Disable MII, use RMII
  14694. GMAC_REGS->GMAC_NCFGR |= GMAC_NCFGR_MAXFS_Msk | GMAC_NCFGR_MTIHEN_Msk |
  14695. GMAC_NCFGR_EFRHD_Msk | GMAC_NCFGR_CAF_Msk;
  14696. GMAC_REGS->GMAC_TSR = GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk |
  14697. GMAC_TSR_TXCOMP_Msk | GMAC_TSR_TFC_Msk |
  14698. GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  14699. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk;
  14700. GMAC_REGS->GMAC_RSR = GMAC_RSR_HNO_Msk | GMAC_RSR_RXOVR_Msk |
  14701. GMAC_RSR_REC_Msk | GMAC_RSR_BNA_Msk;
  14702. GMAC_REGS->GMAC_IDR = ~0U; // Disable interrupts, then enable required
  14703. GMAC_REGS->GMAC_IER = GMAC_IER_HRESP_Msk | GMAC_IER_ROVR_Msk |
  14704. GMAC_IER_TCOMP_Msk | GMAC_IER_TFC_Msk |
  14705. GMAC_IER_RLEX_Msk | GMAC_IER_TUR_Msk |
  14706. GMAC_IER_RXUBR_Msk | GMAC_IER_RCOMP_Msk;
  14707. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TXEN_Msk | GMAC_NCR_RXEN_Msk;
  14708. NVIC_EnableIRQ(GMAC_IRQn);
  14709. return true;
  14710. }
  14711. static size_t mg_tcpip_driver_same54_tx(const void *buf, size_t len,
  14712. struct mg_tcpip_if *ifp) {
  14713. if (len > sizeof(s_txbuf[s_txno])) {
  14714. MG_ERROR(("Frame too big, %ld", (long) len));
  14715. len = 0; // Frame is too big
  14716. } else if ((s_txdesc[s_txno][1] & MG_BIT(31)) == 0) {
  14717. ifp->nerr++;
  14718. MG_ERROR(("No free descriptors"));
  14719. len = 0; // All descriptors are busy, fail
  14720. } else {
  14721. uint32_t status = len | MG_BIT(15); // Frame length, last chunk
  14722. if (s_txno == ETH_DESC_CNT - 1) status |= MG_BIT(30); // wrap
  14723. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14724. s_txdesc[s_txno][1] = status;
  14725. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14726. }
  14727. __DSB(); // Ensure descriptors have been written
  14728. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TSTART_Msk; // Enable transmission
  14729. return len;
  14730. }
  14731. static bool mg_tcpip_driver_same54_up(struct mg_tcpip_if *ifp) {
  14732. uint16_t bsr = eth_read_phy(MG_PHY_ADDR, MG_PHYREG_BSR);
  14733. bool up = bsr & MG_PHYREGBIT_BSR_LINK_STATUS ? 1 : 0;
  14734. // If PHY is ready, update NCFGR accordingly
  14735. if (ifp->state == MG_TCPIP_STATE_DOWN && up) {
  14736. uint16_t bcr = eth_read_phy(MG_PHY_ADDR, MG_PHYREG_BCR);
  14737. bool fd = bcr & MG_PHYREGBIT_BCR_DUPLEX_MODE ? 1 : 0;
  14738. bool spd = bcr & MG_PHYREGBIT_BCR_SPEED ? 1 : 0;
  14739. GMAC_REGS->GMAC_NCFGR = (GMAC_REGS->GMAC_NCFGR &
  14740. ~(GMAC_NCFGR_SPD_Msk | MG_PHYREGBIT_BCR_SPEED)) |
  14741. GMAC_NCFGR_SPD(spd) | GMAC_NCFGR_FD(fd);
  14742. }
  14743. return up;
  14744. }
  14745. void GMAC_Handler(void);
  14746. void GMAC_Handler(void) {
  14747. uint32_t isr = GMAC_REGS->GMAC_ISR;
  14748. uint32_t rsr = GMAC_REGS->GMAC_RSR;
  14749. uint32_t tsr = GMAC_REGS->GMAC_TSR;
  14750. if (isr & GMAC_ISR_RCOMP_Msk) {
  14751. if (rsr & GMAC_ISR_RCOMP_Msk) {
  14752. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  14753. if ((s_rxdesc[s_rxno][0] & MG_BIT(0)) == 0) break;
  14754. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  14755. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  14756. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // Disown
  14757. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14758. }
  14759. }
  14760. }
  14761. if ((tsr & (GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk | GMAC_TSR_TXCOMP_Msk |
  14762. GMAC_TSR_TFC_Msk | GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  14763. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk)) != 0) {
  14764. // MG_INFO((" --> %#x %#x", s_txdesc[s_txno][1], tsr));
  14765. if (!(s_txdesc[s_txno][1] & MG_BIT(31))) s_txdesc[s_txno][1] |= MG_BIT(31);
  14766. }
  14767. GMAC_REGS->GMAC_RSR = rsr;
  14768. GMAC_REGS->GMAC_TSR = tsr;
  14769. }
  14770. struct mg_tcpip_driver mg_tcpip_driver_same54 = {
  14771. mg_tcpip_driver_same54_init, mg_tcpip_driver_same54_tx, NULL,
  14772. mg_tcpip_driver_same54_up};
  14773. #endif
  14774. #ifdef MG_ENABLE_LINES
  14775. #line 1 "src/drivers/stm32f.c"
  14776. #endif
  14777. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
  14778. MG_ENABLE_DRIVER_STM32F
  14779. struct stm32f_eth {
  14780. volatile uint32_t MACCR, MACFFR, MACHTHR, MACHTLR, MACMIIAR, MACMIIDR, MACFCR,
  14781. MACVLANTR, RESERVED0[2], MACRWUFFR, MACPMTCSR, RESERVED1, MACDBGR, MACSR,
  14782. MACIMR, MACA0HR, MACA0LR, MACA1HR, MACA1LR, MACA2HR, MACA2LR, MACA3HR,
  14783. MACA3LR, RESERVED2[40], MMCCR, MMCRIR, MMCTIR, MMCRIMR, MMCTIMR,
  14784. RESERVED3[14], MMCTGFSCCR, MMCTGFMSCCR, RESERVED4[5], MMCTGFCR,
  14785. RESERVED5[10], MMCRFCECR, MMCRFAECR, RESERVED6[10], MMCRGUFCR,
  14786. RESERVED7[334], PTPTSCR, PTPSSIR, PTPTSHR, PTPTSLR, PTPTSHUR, PTPTSLUR,
  14787. PTPTSAR, PTPTTHR, PTPTTLR, RESERVED8, PTPTSSR, PTPPPSCR, RESERVED9[564],
  14788. DMABMR, DMATPDR, DMARPDR, DMARDLAR, DMATDLAR, DMASR, DMAOMR, DMAIER,
  14789. DMAMFBOCR, DMARSWTR, RESERVED10[8], DMACHTDR, DMACHRDR, DMACHTBAR,
  14790. DMACHRBAR;
  14791. };
  14792. #undef ETH
  14793. #define ETH ((struct stm32f_eth *) (uintptr_t) 0x40028000)
  14794. #define ETH_PKT_SIZE 1540 // Max frame size
  14795. #define ETH_DESC_CNT 4 // Descriptors count
  14796. #define ETH_DS 4 // Descriptor size (words)
  14797. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  14798. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  14799. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  14800. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  14801. static uint8_t s_txno; // Current TX descriptor
  14802. static uint8_t s_rxno; // Current RX descriptor
  14803. static struct mg_tcpip_if *s_ifp; // MIP interface
  14804. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  14805. ETH->MACMIIAR &= (7 << 2);
  14806. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  14807. ETH->MACMIIAR |= MG_BIT(0);
  14808. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  14809. return ETH->MACMIIDR & 0xffff;
  14810. }
  14811. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14812. ETH->MACMIIDR = val;
  14813. ETH->MACMIIAR &= (7 << 2);
  14814. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  14815. ETH->MACMIIAR |= MG_BIT(0);
  14816. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  14817. }
  14818. static uint32_t get_hclk(void) {
  14819. struct rcc {
  14820. volatile uint32_t CR, PLLCFGR, CFGR;
  14821. } *rcc = (struct rcc *) 0x40023800;
  14822. uint32_t clk = 0, hsi = 16000000 /* 16 MHz */, hse = 8000000 /* 8MHz */;
  14823. if (rcc->CFGR & (1 << 2)) {
  14824. clk = hse;
  14825. } else if (rcc->CFGR & (1 << 3)) {
  14826. uint32_t vco, m, n, p;
  14827. m = (rcc->PLLCFGR & (0x3f << 0)) >> 0;
  14828. n = (rcc->PLLCFGR & (0x1ff << 6)) >> 6;
  14829. p = (((rcc->PLLCFGR & (3 << 16)) >> 16) + 1) * 2;
  14830. clk = (rcc->PLLCFGR & (1 << 22)) ? hse : hsi;
  14831. vco = (uint32_t) ((uint64_t) clk * n / m);
  14832. clk = vco / p;
  14833. } else {
  14834. clk = hsi;
  14835. }
  14836. uint32_t hpre = (rcc->CFGR & (15 << 4)) >> 4;
  14837. if (hpre < 8) return clk;
  14838. uint8_t ahbptab[8] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  14839. return ((uint32_t) clk) >> ahbptab[hpre - 8];
  14840. }
  14841. // Guess CR from HCLK. MDC clock is generated from HCLK (AHB); as per 802.3,
  14842. // it must not exceed 2.5MHz As the AHB clock can be (and usually is) derived
  14843. // from the HSI (internal RC), and it can go above specs, the datasheets
  14844. // specify a range of frequencies and activate one of a series of dividers to
  14845. // keep the MDC clock safely below 2.5MHz. We guess a divider setting based on
  14846. // HCLK with a +5% drift. If the user uses a different clock from our
  14847. // defaults, needs to set the macros on top Valid for STM32F74xxx/75xxx
  14848. // (38.8.1) and STM32F42xxx/43xxx (33.8.1) (both 4.5% worst case drift)
  14849. static int guess_mdc_cr(void) {
  14850. uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMIIAR::CR values
  14851. uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  14852. uint32_t hclk = get_hclk(); // Guess system HCLK
  14853. int result = -1; // Invalid CR value
  14854. if (hclk < 25000000) {
  14855. MG_ERROR(("HCLK too low"));
  14856. } else {
  14857. for (int i = 0; i < 6; i++) {
  14858. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  14859. result = crs[i];
  14860. break;
  14861. }
  14862. }
  14863. if (result < 0) MG_ERROR(("HCLK too high"));
  14864. }
  14865. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  14866. return result;
  14867. }
  14868. static bool mg_tcpip_driver_stm32f_init(struct mg_tcpip_if *ifp) {
  14869. struct mg_tcpip_driver_stm32f_data *d =
  14870. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  14871. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  14872. s_ifp = ifp;
  14873. // Init RX descriptors
  14874. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14875. s_rxdesc[i][0] = MG_BIT(31); // Own
  14876. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  14877. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  14878. s_rxdesc[i][3] =
  14879. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  14880. }
  14881. // Init TX descriptors
  14882. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14883. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  14884. s_txdesc[i][3] =
  14885. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  14886. }
  14887. ETH->DMABMR |= MG_BIT(0); // Software reset
  14888. while ((ETH->DMABMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  14889. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  14890. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  14891. ETH->MACMIIAR = ((uint32_t) cr & 7) << 2;
  14892. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  14893. // hardware checksum. Therefore, descriptor size is 4, not 8
  14894. // ETH->DMABMR = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) |
  14895. // MG_BIT(25);
  14896. ETH->MACIMR = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  14897. ETH->MACFCR = MG_BIT(7); // Disable zero quarta pause
  14898. // ETH->MACFFR = MG_BIT(31); // Receive all
  14899. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  14900. mg_phy_init(&phy, phy_addr, MG_PHY_CLOCKS_MAC);
  14901. ETH->DMARDLAR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  14902. ETH->DMATDLAR = (uint32_t) (uintptr_t) s_txdesc; // RX descriptors
  14903. ETH->DMAIER = MG_BIT(6) | MG_BIT(16); // RIE, NISE
  14904. ETH->MACCR =
  14905. MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  14906. ETH->DMAOMR =
  14907. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  14908. // MAC address filtering
  14909. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  14910. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  14911. ((uint32_t) ifp->mac[2] << 16) |
  14912. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  14913. return true;
  14914. }
  14915. static size_t mg_tcpip_driver_stm32f_tx(const void *buf, size_t len,
  14916. struct mg_tcpip_if *ifp) {
  14917. if (len > sizeof(s_txbuf[s_txno])) {
  14918. MG_ERROR(("Frame too big, %ld", (long) len));
  14919. len = 0; // Frame is too big
  14920. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  14921. ifp->nerr++;
  14922. MG_ERROR(("No free descriptors"));
  14923. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long) ETH->DMASR);
  14924. len = 0; // All descriptors are busy, fail
  14925. } else {
  14926. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14927. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  14928. s_txdesc[s_txno][0] = MG_BIT(20) | MG_BIT(28) | MG_BIT(29); // Chain,FS,LS
  14929. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  14930. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14931. }
  14932. MG_DSB(); // ensure descriptors have been written
  14933. ETH->DMASR = MG_BIT(2) | MG_BIT(5); // Clear any prior TBUS/TUS
  14934. ETH->DMATPDR = 0; // and resume
  14935. return len;
  14936. }
  14937. static bool mg_tcpip_driver_stm32f_up(struct mg_tcpip_if *ifp) {
  14938. struct mg_tcpip_driver_stm32f_data *d =
  14939. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  14940. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  14941. uint8_t speed = MG_PHY_SPEED_10M;
  14942. bool up = false, full_duplex = false;
  14943. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  14944. up = mg_phy_up(&phy, phy_addr, &full_duplex, &speed);
  14945. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14946. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14947. // if(link is slow or half) set flags otherwise
  14948. // reg = tmp
  14949. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  14950. if (speed == MG_PHY_SPEED_10M) maccr &= ~MG_BIT(14); // 10M
  14951. if (full_duplex == false) maccr &= ~MG_BIT(11); // Half-duplex
  14952. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  14953. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  14954. maccr & MG_BIT(11) ? "full" : "half"));
  14955. }
  14956. return up;
  14957. }
  14958. #ifdef __riscv
  14959. __attribute__((interrupt())) // For RISCV CH32V307, which share the same MAC
  14960. #endif
  14961. void ETH_IRQHandler(void);
  14962. void ETH_IRQHandler(void) {
  14963. if (ETH->DMASR & MG_BIT(6)) { // Frame received, loop
  14964. ETH->DMASR = MG_BIT(16) | MG_BIT(6); // Clear flag
  14965. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14966. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  14967. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) ==
  14968. (MG_BIT(8) | MG_BIT(9))) &&
  14969. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  14970. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  14971. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  14972. // ETH->DMASR);
  14973. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  14974. }
  14975. s_rxdesc[s_rxno][0] = MG_BIT(31);
  14976. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14977. }
  14978. }
  14979. // Cleanup flags
  14980. ETH->DMASR = MG_BIT(16) // NIS, normal interrupt summary
  14981. | MG_BIT(7); // Clear possible RBUS while processing
  14982. ETH->DMARPDR = 0; // and resume RX
  14983. }
  14984. struct mg_tcpip_driver mg_tcpip_driver_stm32f = {
  14985. mg_tcpip_driver_stm32f_init, mg_tcpip_driver_stm32f_tx, NULL,
  14986. mg_tcpip_driver_stm32f_up};
  14987. #endif
  14988. #ifdef MG_ENABLE_LINES
  14989. #line 1 "src/drivers/stm32h.c"
  14990. #endif
  14991. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32H) && \
  14992. MG_ENABLE_DRIVER_STM32H
  14993. struct stm32h_eth {
  14994. volatile uint32_t MACCR, MACECR, MACPFR, MACWTR, MACHT0R, MACHT1R,
  14995. RESERVED1[14], MACVTR, RESERVED2, MACVHTR, RESERVED3, MACVIR, MACIVIR,
  14996. RESERVED4[2], MACTFCR, RESERVED5[7], MACRFCR, RESERVED6[7], MACISR,
  14997. MACIER, MACRXTXSR, RESERVED7, MACPCSR, MACRWKPFR, RESERVED8[2], MACLCSR,
  14998. MACLTCR, MACLETR, MAC1USTCR, RESERVED9[12], MACVR, MACDR, RESERVED10,
  14999. MACHWF0R, MACHWF1R, MACHWF2R, RESERVED11[54], MACMDIOAR, MACMDIODR,
  15000. RESERVED12[2], MACARPAR, RESERVED13[59], MACA0HR, MACA0LR, MACA1HR,
  15001. MACA1LR, MACA2HR, MACA2LR, MACA3HR, MACA3LR, RESERVED14[248], MMCCR,
  15002. MMCRIR, MMCTIR, MMCRIMR, MMCTIMR, RESERVED15[14], MMCTSCGPR, MMCTMCGPR,
  15003. RESERVED16[5], MMCTPCGR, RESERVED17[10], MMCRCRCEPR, MMCRAEPR,
  15004. RESERVED18[10], MMCRUPGR, RESERVED19[9], MMCTLPIMSTR, MMCTLPITCR,
  15005. MMCRLPIMSTR, MMCRLPITCR, RESERVED20[65], MACL3L4C0R, MACL4A0R,
  15006. RESERVED21[2], MACL3A0R0R, MACL3A1R0R, MACL3A2R0R, MACL3A3R0R,
  15007. RESERVED22[4], MACL3L4C1R, MACL4A1R, RESERVED23[2], MACL3A0R1R,
  15008. MACL3A1R1R, MACL3A2R1R, MACL3A3R1R, RESERVED24[108], MACTSCR, MACSSIR,
  15009. MACSTSR, MACSTNR, MACSTSUR, MACSTNUR, MACTSAR, RESERVED25, MACTSSR,
  15010. RESERVED26[3], MACTTSSNR, MACTTSSSR, RESERVED27[2], MACACR, RESERVED28,
  15011. MACATSNR, MACATSSR, MACTSIACR, MACTSEACR, MACTSICNR, MACTSECNR,
  15012. RESERVED29[4], MACPPSCR, RESERVED30[3], MACPPSTTSR, MACPPSTTNR, MACPPSIR,
  15013. MACPPSWR, RESERVED31[12], MACPOCR, MACSPI0R, MACSPI1R, MACSPI2R, MACLMIR,
  15014. RESERVED32[11], MTLOMR, RESERVED33[7], MTLISR, RESERVED34[55], MTLTQOMR,
  15015. MTLTQUR, MTLTQDR, RESERVED35[8], MTLQICSR, MTLRQOMR, MTLRQMPOCR, MTLRQDR,
  15016. RESERVED36[177], DMAMR, DMASBMR, DMAISR, DMADSR, RESERVED37[60], DMACCR,
  15017. DMACTCR, DMACRCR, RESERVED38[2], DMACTDLAR, RESERVED39, DMACRDLAR,
  15018. DMACTDTPR, RESERVED40, DMACRDTPR, DMACTDRLR, DMACRDRLR, DMACIER,
  15019. DMACRIWTR, DMACSFCSR, RESERVED41, DMACCATDR, RESERVED42, DMACCARDR,
  15020. RESERVED43, DMACCATBR, RESERVED44, DMACCARBR, DMACSR, RESERVED45[2],
  15021. DMACMFCR;
  15022. };
  15023. #undef ETH
  15024. #define ETH \
  15025. ((struct stm32h_eth *) (uintptr_t) (0x40000000UL + 0x00020000UL + 0x8000UL))
  15026. #define ETH_PKT_SIZE 1540 // Max frame size
  15027. #define ETH_DESC_CNT 4 // Descriptors count
  15028. #define ETH_DS 4 // Descriptor size (words)
  15029. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15030. static volatile uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15031. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  15032. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  15033. static struct mg_tcpip_if *s_ifp; // MIP interface
  15034. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  15035. ETH->MACMDIOAR &= (0xF << 8);
  15036. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 3 << 2;
  15037. ETH->MACMDIOAR |= MG_BIT(0);
  15038. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  15039. return (uint16_t) ETH->MACMDIODR;
  15040. }
  15041. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15042. ETH->MACMDIODR = val;
  15043. ETH->MACMDIOAR &= (0xF << 8);
  15044. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 1 << 2;
  15045. ETH->MACMDIOAR |= MG_BIT(0);
  15046. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  15047. }
  15048. static uint32_t get_hclk(void) {
  15049. struct rcc {
  15050. volatile uint32_t CR, HSICFGR, CRRCR, CSICFGR, CFGR, RESERVED1, D1CFGR,
  15051. D2CFGR, D3CFGR, RESERVED2, PLLCKSELR, PLLCFGR, PLL1DIVR, PLL1FRACR,
  15052. PLL2DIVR, PLL2FRACR, PLL3DIVR, PLL3FRACR, RESERVED3, D1CCIPR, D2CCIP1R,
  15053. D2CCIP2R, D3CCIPR, RESERVED4, CIER, CIFR, CICR, RESERVED5, BDCR, CSR,
  15054. RESERVED6, AHB3RSTR, AHB1RSTR, AHB2RSTR, AHB4RSTR, APB3RSTR, APB1LRSTR,
  15055. APB1HRSTR, APB2RSTR, APB4RSTR, GCR, RESERVED8, D3AMR, RESERVED11[9],
  15056. RSR, AHB3ENR, AHB1ENR, AHB2ENR, AHB4ENR, APB3ENR, APB1LENR, APB1HENR,
  15057. APB2ENR, APB4ENR, RESERVED12, AHB3LPENR, AHB1LPENR, AHB2LPENR,
  15058. AHB4LPENR, APB3LPENR, APB1LLPENR, APB1HLPENR, APB2LPENR, APB4LPENR,
  15059. RESERVED13[4];
  15060. } *rcc = ((struct rcc *) (0x40000000 + 0x18020000 + 0x4400));
  15061. uint32_t clk = 0, hsi = 64000000 /* 64 MHz */, hse = 8000000 /* 8MHz */,
  15062. csi = 4000000 /* 4MHz */;
  15063. unsigned int sel = (rcc->CFGR & (7 << 3)) >> 3;
  15064. if (sel == 1) {
  15065. clk = csi;
  15066. } else if (sel == 2) {
  15067. clk = hse;
  15068. } else if (sel == 3) {
  15069. uint32_t vco, m, n, p;
  15070. unsigned int src = (rcc->PLLCKSELR & (3 << 0)) >> 0;
  15071. m = ((rcc->PLLCKSELR & (0x3F << 4)) >> 4);
  15072. n = ((rcc->PLL1DIVR & (0x1FF << 0)) >> 0) + 1 +
  15073. ((rcc->PLLCFGR & MG_BIT(0)) ? 1 : 0); // round-up in fractional mode
  15074. p = ((rcc->PLL1DIVR & (0x7F << 9)) >> 9) + 1;
  15075. if (src == 1) {
  15076. clk = csi;
  15077. } else if (src == 2) {
  15078. clk = hse;
  15079. } else {
  15080. clk = hsi;
  15081. clk >>= ((rcc->CR & 3) >> 3);
  15082. }
  15083. vco = (uint32_t) ((uint64_t) clk * n / m);
  15084. clk = vco / p;
  15085. } else {
  15086. clk = hsi;
  15087. clk >>= ((rcc->CR & 3) >> 3);
  15088. }
  15089. const uint8_t cptab[12] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  15090. uint32_t d1cpre = (rcc->D1CFGR & (0x0F << 8)) >> 8;
  15091. if (d1cpre >= 8) clk >>= cptab[d1cpre - 8];
  15092. MG_DEBUG(("D1 CLK: %u", clk));
  15093. uint32_t hpre = (rcc->D1CFGR & (0x0F << 0)) >> 0;
  15094. if (hpre < 8) return clk;
  15095. return ((uint32_t) clk) >> cptab[hpre - 8];
  15096. }
  15097. // Guess CR from AHB1 clock. MDC clock is generated from the ETH peripheral
  15098. // clock (AHB1); as per 802.3, it must not exceed 2. As the AHB clock can
  15099. // be derived from HSI or CSI (internal RC) clocks, and those can go above
  15100. // specs, the datasheets specify a range of frequencies and activate one of a
  15101. // series of dividers to keep the MDC clock safely below 2.5MHz. We guess a
  15102. // divider setting based on HCLK with some drift. If the user uses a different
  15103. // clock from our defaults, needs to set the macros on top. Valid for
  15104. // STM32H74xxx/75xxx (58.11.4)(4.5% worst case drift)(CSI clock has a 7.5 %
  15105. // worst case drift @ max temp)
  15106. static int guess_mdc_cr(void) {
  15107. const uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMDIOAR::CR values
  15108. const uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  15109. uint32_t hclk = get_hclk(); // Guess system HCLK
  15110. int result = -1; // Invalid CR value
  15111. for (int i = 0; i < 6; i++) {
  15112. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  15113. result = crs[i];
  15114. break;
  15115. }
  15116. }
  15117. if (result < 0) MG_ERROR(("HCLK too high"));
  15118. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  15119. return result;
  15120. }
  15121. static bool mg_tcpip_driver_stm32h_init(struct mg_tcpip_if *ifp) {
  15122. struct mg_tcpip_driver_stm32h_data *d =
  15123. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  15124. s_ifp = ifp;
  15125. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  15126. uint8_t phy_conf = d == NULL ? MG_PHY_CLOCKS_MAC : d->phy_conf;
  15127. // Init RX descriptors
  15128. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15129. s_rxdesc[i][0] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  15130. s_rxdesc[i][3] = MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  15131. }
  15132. // Init TX descriptors
  15133. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15134. s_txdesc[i][0] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  15135. }
  15136. ETH->DMAMR |= MG_BIT(0); // Software reset
  15137. while ((ETH->DMAMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  15138. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  15139. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  15140. ETH->MACMDIOAR = ((uint32_t) cr & 0xF) << 8;
  15141. // NOTE(scaprile): We do not use timing facilities so the DMA engine does not
  15142. // re-write buffer address
  15143. ETH->DMAMR = 0 << 16; // use interrupt mode 0 (58.8.1) (reset value)
  15144. ETH->DMASBMR |= MG_BIT(12); // AAL NOTE(scaprile): is this actually needed
  15145. ETH->MACIER = 0; // Do not enable additional irq sources (reset value)
  15146. ETH->MACTFCR = MG_BIT(7); // Disable zero-quanta pause
  15147. // ETH->MACPFR = MG_BIT(31); // Receive all
  15148. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15149. mg_phy_init(&phy, phy_addr, phy_conf);
  15150. ETH->DMACRDLAR =
  15151. (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors start address
  15152. ETH->DMACRDRLR = ETH_DESC_CNT - 1; // ring length
  15153. ETH->DMACRDTPR =
  15154. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT -
  15155. 1]; // last valid descriptor address
  15156. ETH->DMACTDLAR =
  15157. (uint32_t) (uintptr_t) s_txdesc; // TX descriptors start address
  15158. ETH->DMACTDRLR = ETH_DESC_CNT - 1; // ring length
  15159. ETH->DMACTDTPR =
  15160. (uint32_t) (uintptr_t) s_txdesc; // first available descriptor address
  15161. ETH->DMACCR = 0; // DSL = 0 (contiguous descriptor table) (reset value)
  15162. ETH->DMACIER = MG_BIT(6) | MG_BIT(15); // RIE, NIE
  15163. ETH->MACCR = MG_BIT(0) | MG_BIT(1) | MG_BIT(13) | MG_BIT(14) |
  15164. MG_BIT(15); // RE, TE, Duplex, Fast, Reserved
  15165. ETH->MTLTQOMR |= MG_BIT(1); // TSF
  15166. ETH->MTLRQOMR |= MG_BIT(5); // RSF
  15167. ETH->DMACTCR |= MG_BIT(0); // ST
  15168. ETH->DMACRCR |= MG_BIT(0); // SR
  15169. // MAC address filtering
  15170. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  15171. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  15172. ((uint32_t) ifp->mac[2] << 16) |
  15173. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  15174. return true;
  15175. }
  15176. static uint32_t s_txno;
  15177. static size_t mg_tcpip_driver_stm32h_tx(const void *buf, size_t len,
  15178. struct mg_tcpip_if *ifp) {
  15179. if (len > sizeof(s_txbuf[s_txno])) {
  15180. MG_ERROR(("Frame too big, %ld", (long) len));
  15181. len = 0; // Frame is too big
  15182. } else if ((s_txdesc[s_txno][3] & MG_BIT(31))) {
  15183. ifp->nerr++;
  15184. MG_ERROR(("No free descriptors: %u %08X %08X %08X", s_txno,
  15185. s_txdesc[s_txno][3], ETH->DMACSR, ETH->DMACTCR));
  15186. for (int i = 0; i < ETH_DESC_CNT; i++) MG_ERROR(("%08X", s_txdesc[i][3]));
  15187. len = 0; // All descriptors are busy, fail
  15188. } else {
  15189. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  15190. s_txdesc[s_txno][2] = (uint32_t) len; // Set data len
  15191. s_txdesc[s_txno][3] = MG_BIT(28) | MG_BIT(29); // FD, LD
  15192. s_txdesc[s_txno][3] |= MG_BIT(31); // Set OWN bit - let DMA take over
  15193. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15194. }
  15195. ETH->DMACSR |= MG_BIT(2) | MG_BIT(1); // Clear any prior TBU, TPS
  15196. ETH->DMACTDTPR = (uint32_t) (uintptr_t) &s_txdesc[s_txno]; // and resume
  15197. return len;
  15198. (void) ifp;
  15199. }
  15200. static bool mg_tcpip_driver_stm32h_up(struct mg_tcpip_if *ifp) {
  15201. struct mg_tcpip_driver_stm32h_data *d =
  15202. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  15203. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  15204. uint8_t speed = MG_PHY_SPEED_10M;
  15205. bool up = false, full_duplex = false;
  15206. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15207. up = mg_phy_up(&phy, phy_addr, &full_duplex, &speed);
  15208. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15209. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  15210. // if(link is slow or half) set flags otherwise
  15211. // reg = tmp
  15212. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(13); // 100M, Full-duplex
  15213. if (speed == MG_PHY_SPEED_10M) maccr &= ~MG_BIT(14); // 10M
  15214. if (full_duplex == false) maccr &= ~MG_BIT(13); // Half-duplex
  15215. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  15216. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  15217. maccr & MG_BIT(13) ? "full" : "half"));
  15218. }
  15219. return up;
  15220. }
  15221. void ETH_IRQHandler(void);
  15222. static uint32_t s_rxno;
  15223. void ETH_IRQHandler(void) {
  15224. if (ETH->DMACSR & MG_BIT(6)) { // Frame received, loop
  15225. ETH->DMACSR = MG_BIT(15) | MG_BIT(6); // Clear flag
  15226. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  15227. if (s_rxdesc[s_rxno][3] & MG_BIT(31)) break; // exit when done
  15228. if (((s_rxdesc[s_rxno][3] & (MG_BIT(28) | MG_BIT(29))) ==
  15229. (MG_BIT(28) | MG_BIT(29))) &&
  15230. !(s_rxdesc[s_rxno][3] & MG_BIT(15))) { // skip partial/errored frames
  15231. uint32_t len = s_rxdesc[s_rxno][3] & (MG_BIT(15) - 1);
  15232. // MG_DEBUG(("%lx %lu %lx %08lx", s_rxno, len, s_rxdesc[s_rxno][3],
  15233. // ETH->DMACSR));
  15234. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  15235. }
  15236. s_rxdesc[s_rxno][3] =
  15237. MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  15238. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15239. }
  15240. }
  15241. ETH->DMACSR =
  15242. MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing
  15243. ETH->DMACRDTPR =
  15244. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT - 1]; // and resume RX
  15245. }
  15246. struct mg_tcpip_driver mg_tcpip_driver_stm32h = {
  15247. mg_tcpip_driver_stm32h_init, mg_tcpip_driver_stm32h_tx, NULL,
  15248. mg_tcpip_driver_stm32h_up};
  15249. #endif
  15250. #ifdef MG_ENABLE_LINES
  15251. #line 1 "src/drivers/tm4c.c"
  15252. #endif
  15253. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
  15254. struct tm4c_emac {
  15255. volatile uint32_t EMACCFG, EMACFRAMEFLTR, EMACHASHTBLH, EMACHASHTBLL,
  15256. EMACMIIADDR, EMACMIIDATA, EMACFLOWCTL, EMACVLANTG, RESERVED0, EMACSTATUS,
  15257. EMACRWUFF, EMACPMTCTLSTAT, RESERVED1[2], EMACRIS, EMACIM, EMACADDR0H,
  15258. EMACADDR0L, EMACADDR1H, EMACADDR1L, EMACADDR2H, EMACADDR2L, EMACADDR3H,
  15259. EMACADDR3L, RESERVED2[31], EMACWDOGTO, RESERVED3[8], EMACMMCCTRL,
  15260. EMACMMCRXRIS, EMACMMCTXRIS, EMACMMCRXIM, EMACMMCTXIM, RESERVED4,
  15261. EMACTXCNTGB, RESERVED5[12], EMACTXCNTSCOL, EMACTXCNTMCOL, RESERVED6[4],
  15262. EMACTXOCTCNTG, RESERVED7[6], EMACRXCNTGB, RESERVED8[4], EMACRXCNTCRCERR,
  15263. EMACRXCNTALGNERR, RESERVED9[10], EMACRXCNTGUNI, RESERVED10[239],
  15264. EMACVLNINCREP, EMACVLANHASH, RESERVED11[93], EMACTIMSTCTRL, EMACSUBSECINC,
  15265. EMACTIMSEC, EMACTIMNANO, EMACTIMSECU, EMACTIMNANOU, EMACTIMADD,
  15266. EMACTARGSEC, EMACTARGNANO, EMACHWORDSEC, EMACTIMSTAT, EMACPPSCTRL,
  15267. RESERVED12[12], EMACPPS0INTVL, EMACPPS0WIDTH, RESERVED13[294],
  15268. EMACDMABUSMOD, EMACTXPOLLD, EMACRXPOLLD, EMACRXDLADDR, EMACTXDLADDR,
  15269. EMACDMARIS, EMACDMAOPMODE, EMACDMAIM, EMACMFBOC, EMACRXINTWDT,
  15270. RESERVED14[8], EMACHOSTXDESC, EMACHOSRXDESC, EMACHOSTXBA, EMACHOSRXBA,
  15271. RESERVED15[218], EMACPP, EMACPC, EMACCC, RESERVED16, EMACEPHYRIS,
  15272. EMACEPHYIM, EMACEPHYIMSC;
  15273. };
  15274. #undef EMAC
  15275. #define EMAC ((struct tm4c_emac *) (uintptr_t) 0x400EC000)
  15276. #define ETH_PKT_SIZE 1540 // Max frame size
  15277. #define ETH_DESC_CNT 4 // Descriptors count
  15278. #define ETH_DS 4 // Descriptor size (words)
  15279. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15280. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15281. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  15282. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  15283. static struct mg_tcpip_if *s_ifp; // MIP interface
  15284. enum {
  15285. EPHY_ADDR = 0,
  15286. EPHYBMCR = 0,
  15287. EPHYBMSR = 1,
  15288. EPHYSTS = 16
  15289. }; // PHY constants
  15290. static inline void tm4cspin(volatile uint32_t count) {
  15291. while (count--) (void) 0;
  15292. }
  15293. static uint32_t emac_read_phy(uint8_t addr, uint8_t reg) {
  15294. EMAC->EMACMIIADDR &= (0xf << 2);
  15295. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  15296. EMAC->EMACMIIADDR |= MG_BIT(0);
  15297. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  15298. return EMAC->EMACMIIDATA;
  15299. }
  15300. static void emac_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  15301. EMAC->EMACMIIDATA = val;
  15302. EMAC->EMACMIIADDR &= (0xf << 2);
  15303. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  15304. EMAC->EMACMIIADDR |= MG_BIT(0);
  15305. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  15306. }
  15307. static uint32_t get_sysclk(void) {
  15308. struct sysctl {
  15309. volatile uint32_t DONTCARE0[44], RSCLKCFG, DONTCARE1[43], PLLFREQ0,
  15310. PLLFREQ1;
  15311. } *sysctl = (struct sysctl *) 0x400FE000;
  15312. uint32_t clk = 0, piosc = 16000000 /* 16 MHz */, mosc = 25000000 /* 25MHz */;
  15313. if (sysctl->RSCLKCFG & (1 << 28)) { // USEPLL
  15314. uint32_t fin, vco, mdiv, n, q, psysdiv;
  15315. uint32_t pllsrc = (sysctl->RSCLKCFG & (0xf << 24)) >> 24;
  15316. if (pllsrc == 0) {
  15317. clk = piosc;
  15318. } else if (pllsrc == 3) {
  15319. clk = mosc;
  15320. } else {
  15321. MG_ERROR(("Unsupported clock source"));
  15322. }
  15323. q = (sysctl->PLLFREQ1 & (0x1f << 8)) >> 8;
  15324. n = (sysctl->PLLFREQ1 & (0x1f << 0)) >> 0;
  15325. fin = clk / ((q + 1) * (n + 1));
  15326. mdiv = (sysctl->PLLFREQ0 & (0x3ff << 0)) >>
  15327. 0; // mint + (mfrac / 1024); MFRAC not supported
  15328. psysdiv = (sysctl->RSCLKCFG & (0x3f << 0)) >> 0;
  15329. vco = (uint32_t) ((uint64_t) fin * mdiv);
  15330. return vco / (psysdiv + 1);
  15331. }
  15332. uint32_t oscsrc = (sysctl->RSCLKCFG & (0xf << 20)) >> 20;
  15333. if (oscsrc == 0) {
  15334. clk = piosc;
  15335. } else if (oscsrc == 3) {
  15336. clk = mosc;
  15337. } else {
  15338. MG_ERROR(("Unsupported clock source"));
  15339. }
  15340. uint32_t osysdiv = (sysctl->RSCLKCFG & (0xf << 16)) >> 16;
  15341. return clk / (osysdiv + 1);
  15342. }
  15343. // Guess CR from SYSCLK. MDC clock is generated from SYSCLK (AHB); as per
  15344. // 802.3, it must not exceed 2.5MHz (also 20.4.2.6) As the AHB clock can be
  15345. // derived from the PIOSC (internal RC), and it can go above specs, the
  15346. // datasheets specify a range of frequencies and activate one of a series of
  15347. // dividers to keep the MDC clock safely below 2.5MHz. We guess a divider
  15348. // setting based on SYSCLK with a +5% drift. If the user uses a different clock
  15349. // from our defaults, needs to set the macros on top Valid for TM4C129x (20.7)
  15350. // (4.5% worst case drift)
  15351. // The PHY receives the main oscillator (MOSC) (20.3.1)
  15352. static int guess_mdc_cr(void) {
  15353. uint8_t crs[] = {2, 3, 0, 1}; // EMAC->MACMIIAR::CR values
  15354. uint8_t div[] = {16, 26, 42, 62}; // Respective HCLK dividers
  15355. uint32_t sysclk = get_sysclk(); // Guess system SYSCLK
  15356. int result = -1; // Invalid CR value
  15357. if (sysclk < 25000000) {
  15358. MG_ERROR(("SYSCLK too low"));
  15359. } else {
  15360. for (int i = 0; i < 4; i++) {
  15361. if (sysclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  15362. result = crs[i];
  15363. break;
  15364. }
  15365. }
  15366. if (result < 0) MG_ERROR(("SYSCLK too high"));
  15367. }
  15368. MG_DEBUG(("SYSCLK: %u, CR: %d", sysclk, result));
  15369. return result;
  15370. }
  15371. static bool mg_tcpip_driver_tm4c_init(struct mg_tcpip_if *ifp) {
  15372. struct mg_tcpip_driver_tm4c_data *d =
  15373. (struct mg_tcpip_driver_tm4c_data *) ifp->driver_data;
  15374. s_ifp = ifp;
  15375. // Init RX descriptors
  15376. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15377. s_rxdesc[i][0] = MG_BIT(31); // Own
  15378. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  15379. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  15380. s_rxdesc[i][3] =
  15381. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  15382. // MG_DEBUG(("%d %p", i, s_rxdesc[i]));
  15383. }
  15384. // Init TX descriptors
  15385. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15386. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  15387. s_txdesc[i][3] =
  15388. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  15389. }
  15390. EMAC->EMACDMABUSMOD |= MG_BIT(0); // Software reset
  15391. while ((EMAC->EMACDMABUSMOD & MG_BIT(0)) != 0) tm4cspin(1); // Wait until done
  15392. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  15393. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  15394. EMAC->EMACMIIADDR = ((uint32_t) cr & 0xf) << 2;
  15395. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  15396. // hardware checksum. Therefore, descriptor size is 4, not 8
  15397. // EMAC->EMACDMABUSMOD = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) | MG_BIT(25);
  15398. EMAC->EMACIM = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  15399. EMAC->EMACFLOWCTL = MG_BIT(7); // Disable zero-quanta pause
  15400. // EMAC->EMACFRAMEFLTR = MG_BIT(31); // Receive all
  15401. // EMAC->EMACPC defaults to internal PHY (EPHY) in MMI mode
  15402. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(15)); // Reset internal PHY (EPHY)
  15403. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(12)); // Set autonegotiation
  15404. EMAC->EMACRXDLADDR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  15405. EMAC->EMACTXDLADDR = (uint32_t) (uintptr_t) s_txdesc; // TX descriptors
  15406. EMAC->EMACDMAIM = MG_BIT(6) | MG_BIT(16); // RIE, NIE
  15407. EMAC->EMACCFG = MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  15408. EMAC->EMACDMAOPMODE =
  15409. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  15410. EMAC->EMACADDR0H = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  15411. EMAC->EMACADDR0L = (uint32_t) (ifp->mac[3] << 24) |
  15412. ((uint32_t) ifp->mac[2] << 16) |
  15413. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  15414. // NOTE(scaprile) There are 3 additional slots for filtering, disabled by
  15415. // default. This also applies to the STM32 driver (at least for F7)
  15416. return true;
  15417. }
  15418. static uint32_t s_txno;
  15419. static size_t mg_tcpip_driver_tm4c_tx(const void *buf, size_t len,
  15420. struct mg_tcpip_if *ifp) {
  15421. if (len > sizeof(s_txbuf[s_txno])) {
  15422. MG_ERROR(("Frame too big, %ld", (long) len));
  15423. len = 0; // fail
  15424. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  15425. ifp->nerr++;
  15426. MG_ERROR(("No descriptors available"));
  15427. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long)
  15428. // EMAC->EMACDMARIS);
  15429. len = 0; // fail
  15430. } else {
  15431. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  15432. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  15433. s_txdesc[s_txno][0] =
  15434. MG_BIT(20) | MG_BIT(28) | MG_BIT(29) | MG_BIT(30); // Chain,FS,LS,IC
  15435. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  15436. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15437. }
  15438. EMAC->EMACDMARIS = MG_BIT(2) | MG_BIT(5); // Clear any prior TU/UNF
  15439. EMAC->EMACTXPOLLD = 0; // and resume
  15440. return len;
  15441. (void) ifp;
  15442. }
  15443. static bool mg_tcpip_driver_tm4c_up(struct mg_tcpip_if *ifp) {
  15444. uint32_t bmsr = emac_read_phy(EPHY_ADDR, EPHYBMSR);
  15445. bool up = (bmsr & MG_BIT(2)) ? 1 : 0;
  15446. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15447. uint32_t sts = emac_read_phy(EPHY_ADDR, EPHYSTS);
  15448. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  15449. // if(link is slow or half) set flags otherwise
  15450. // reg = tmp
  15451. uint32_t emaccfg = EMAC->EMACCFG | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  15452. if (sts & MG_BIT(1)) emaccfg &= ~MG_BIT(14); // 10M
  15453. if ((sts & MG_BIT(2)) == 0) emaccfg &= ~MG_BIT(11); // Half-duplex
  15454. EMAC->EMACCFG = emaccfg; // IRQ handler does not fiddle with this register
  15455. MG_DEBUG(("Link is %uM %s-duplex", emaccfg & MG_BIT(14) ? 100 : 10,
  15456. emaccfg & MG_BIT(11) ? "full" : "half"));
  15457. }
  15458. return up;
  15459. }
  15460. void EMAC0_IRQHandler(void);
  15461. static uint32_t s_rxno;
  15462. void EMAC0_IRQHandler(void) {
  15463. if (EMAC->EMACDMARIS & MG_BIT(6)) { // Frame received, loop
  15464. EMAC->EMACDMARIS = MG_BIT(16) | MG_BIT(6); // Clear flag
  15465. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  15466. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  15467. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) == (MG_BIT(8) | MG_BIT(9))) &&
  15468. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  15469. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  15470. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  15471. // EMAC->EMACDMARIS);
  15472. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  15473. }
  15474. s_rxdesc[s_rxno][0] = MG_BIT(31);
  15475. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15476. }
  15477. }
  15478. EMAC->EMACDMARIS = MG_BIT(7); // Clear possible RU while processing
  15479. EMAC->EMACRXPOLLD = 0; // and resume RX
  15480. }
  15481. struct mg_tcpip_driver mg_tcpip_driver_tm4c = {mg_tcpip_driver_tm4c_init,
  15482. mg_tcpip_driver_tm4c_tx, NULL,
  15483. mg_tcpip_driver_tm4c_up};
  15484. #endif
  15485. #ifdef MG_ENABLE_LINES
  15486. #line 1 "src/drivers/w5500.c"
  15487. #endif
  15488. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5500) && MG_ENABLE_DRIVER_W5500
  15489. enum { W5500_CR = 0, W5500_S0 = 1, W5500_TX0 = 2, W5500_RX0 = 3 };
  15490. static void w5500_txn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr,
  15491. bool wr, void *buf, size_t len) {
  15492. size_t i;
  15493. uint8_t *p = (uint8_t *) buf;
  15494. uint8_t cmd[] = {(uint8_t) (addr >> 8), (uint8_t) (addr & 255),
  15495. (uint8_t) ((block << 3) | (wr ? 4 : 0))};
  15496. s->begin(s->spi);
  15497. for (i = 0; i < sizeof(cmd); i++) s->txn(s->spi, cmd[i]);
  15498. for (i = 0; i < len; i++) {
  15499. uint8_t r = s->txn(s->spi, p[i]);
  15500. if (!wr) p[i] = r;
  15501. }
  15502. s->end(s->spi);
  15503. }
  15504. // clang-format off
  15505. 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); }
  15506. 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); }
  15507. 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)); }
  15508. 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); }
  15509. 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; }
  15510. 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]); }
  15511. // clang-format on
  15512. static size_t w5500_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  15513. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15514. uint16_t r = 0, n = 0, len = (uint16_t) buflen, n2; // Read recv len
  15515. while ((n2 = w5500_r2(s, W5500_S0, 0x26)) > n) n = n2; // Until it is stable
  15516. // printf("RSR: %d\n", (int) n);
  15517. if (n > 0) {
  15518. uint16_t ptr = w5500_r2(s, W5500_S0, 0x28); // Get read pointer
  15519. n = w5500_r2(s, W5500_RX0, ptr); // Read frame length
  15520. if (n <= len + 2 && n > 1) {
  15521. r = (uint16_t) (n - 2);
  15522. w5500_rn(s, W5500_RX0, (uint16_t) (ptr + 2), buf, r);
  15523. }
  15524. w5500_w2(s, W5500_S0, 0x28, (uint16_t) (ptr + n)); // Advance read pointer
  15525. w5500_w1(s, W5500_S0, 1, 0x40); // Sock0 CR -> RECV
  15526. // printf(" RX_RD: tot=%u n=%u r=%u\n", n2, n, r);
  15527. }
  15528. return r;
  15529. }
  15530. static size_t w5500_tx(const void *buf, size_t buflen,
  15531. struct mg_tcpip_if *ifp) {
  15532. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15533. uint16_t i, ptr, n = 0, len = (uint16_t) buflen;
  15534. while (n < len) n = w5500_r2(s, W5500_S0, 0x20); // Wait for space
  15535. ptr = w5500_r2(s, W5500_S0, 0x24); // Get write pointer
  15536. w5500_wn(s, W5500_TX0, ptr, (void *) buf, len); // Write data
  15537. w5500_w2(s, W5500_S0, 0x24, (uint16_t) (ptr + len)); // Advance write pointer
  15538. w5500_w1(s, W5500_S0, 1, 0x20); // Sock0 CR -> SEND
  15539. for (i = 0; i < 40; i++) {
  15540. uint8_t ir = w5500_r1(s, W5500_S0, 2); // Read S0 IR
  15541. if (ir == 0) continue;
  15542. // printf("IR %d, len=%d, free=%d, ptr %d\n", ir, (int) len, (int) n, ptr);
  15543. w5500_w1(s, W5500_S0, 2, ir); // Write S0 IR: clear it!
  15544. if (ir & 8) len = 0; // Timeout. Report error
  15545. if (ir & (16 | 8)) break; // Stop on SEND_OK or timeout
  15546. }
  15547. return len;
  15548. }
  15549. static bool w5500_init(struct mg_tcpip_if *ifp) {
  15550. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15551. s->end(s->spi);
  15552. w5500_w1(s, W5500_CR, 0, 0x80); // Reset chip: CR -> 0x80
  15553. w5500_w1(s, W5500_CR, 0x2e, 0); // CR PHYCFGR -> reset
  15554. w5500_w1(s, W5500_CR, 0x2e, 0xf8); // CR PHYCFGR -> set
  15555. // w5500_wn(s, W5500_CR, 9, s->mac, 6); // Set source MAC
  15556. w5500_w1(s, W5500_S0, 0x1e, 16); // Sock0 RX buf size
  15557. w5500_w1(s, W5500_S0, 0x1f, 16); // Sock0 TX buf size
  15558. w5500_w1(s, W5500_S0, 0, 4); // Sock0 MR -> MACRAW
  15559. w5500_w1(s, W5500_S0, 1, 1); // Sock0 CR -> OPEN
  15560. return w5500_r1(s, W5500_S0, 3) == 0x42; // Sock0 SR == MACRAW
  15561. }
  15562. static bool w5500_up(struct mg_tcpip_if *ifp) {
  15563. struct mg_tcpip_spi *spi = (struct mg_tcpip_spi *) ifp->driver_data;
  15564. uint8_t phycfgr = w5500_r1(spi, W5500_CR, 0x2e);
  15565. return phycfgr & 1; // Bit 0 of PHYCFGR is LNK (0 - down, 1 - up)
  15566. }
  15567. struct mg_tcpip_driver mg_tcpip_driver_w5500 = {w5500_init, w5500_tx, w5500_rx,
  15568. w5500_up};
  15569. #endif
  15570. #ifdef MG_ENABLE_LINES
  15571. #line 1 "src/drivers/xmc.c"
  15572. #endif
  15573. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC
  15574. struct ETH_GLOBAL_TypeDef {
  15575. volatile uint32_t MAC_CONFIGURATION, MAC_FRAME_FILTER, HASH_TABLE_HIGH,
  15576. HASH_TABLE_LOW, GMII_ADDRESS, GMII_DATA, FLOW_CONTROL, VLAN_TAG, VERSION,
  15577. DEBUG, REMOTE_WAKE_UP_FRAME_FILTER, PMT_CONTROL_STATUS, RESERVED[2],
  15578. INTERRUPT_STATUS, INTERRUPT_MASK, MAC_ADDRESS0_HIGH, MAC_ADDRESS0_LOW,
  15579. MAC_ADDRESS1_HIGH, MAC_ADDRESS1_LOW, MAC_ADDRESS2_HIGH, MAC_ADDRESS2_LOW,
  15580. MAC_ADDRESS3_HIGH, MAC_ADDRESS3_LOW, RESERVED1[40], MMC_CONTROL,
  15581. MMC_RECEIVE_INTERRUPT, MMC_TRANSMIT_INTERRUPT, MMC_RECEIVE_INTERRUPT_MASK,
  15582. MMC_TRANSMIT_INTERRUPT_MASK, TX_STATISTICS[26], RESERVED2,
  15583. RX_STATISTICS_1[26], RESERVED3[6], MMC_IPC_RECEIVE_INTERRUPT_MASK,
  15584. RESERVED4, MMC_IPC_RECEIVE_INTERRUPT, RESERVED5, RX_STATISTICS_2[30],
  15585. RESERVED7[286], TIMESTAMP_CONTROL, SUB_SECOND_INCREMENT,
  15586. SYSTEM_TIME_SECONDS, SYSTEM_TIME_NANOSECONDS,
  15587. SYSTEM_TIME_SECONDS_UPDATE, SYSTEM_TIME_NANOSECONDS_UPDATE,
  15588. TIMESTAMP_ADDEND, TARGET_TIME_SECONDS, TARGET_TIME_NANOSECONDS,
  15589. SYSTEM_TIME_HIGHER_WORD_SECONDS, TIMESTAMP_STATUS,
  15590. PPS_CONTROL, RESERVED8[564], BUS_MODE, TRANSMIT_POLL_DEMAND,
  15591. RECEIVE_POLL_DEMAND, RECEIVE_DESCRIPTOR_LIST_ADDRESS,
  15592. TRANSMIT_DESCRIPTOR_LIST_ADDRESS, STATUS, OPERATION_MODE,
  15593. INTERRUPT_ENABLE, MISSED_FRAME_AND_BUFFER_OVERFLOW_COUNTER,
  15594. RECEIVE_INTERRUPT_WATCHDOG_TIMER, RESERVED9, AHB_STATUS,
  15595. RESERVED10[6], CURRENT_HOST_TRANSMIT_DESCRIPTOR,
  15596. CURRENT_HOST_RECEIVE_DESCRIPTOR, CURRENT_HOST_TRANSMIT_BUFFER_ADDRESS,
  15597. CURRENT_HOST_RECEIVE_BUFFER_ADDRESS, HW_FEATURE;
  15598. };
  15599. #undef ETH0
  15600. #define ETH0 ((struct ETH_GLOBAL_TypeDef*) 0x5000C000UL)
  15601. #define ETH_PKT_SIZE 1536 // Max frame size
  15602. #define ETH_DESC_CNT 4 // Descriptors count
  15603. #define ETH_DS 4 // Descriptor size (words)
  15604. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15605. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15606. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15607. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15608. static uint8_t s_txno; // Current TX descriptor
  15609. static uint8_t s_rxno; // Current RX descriptor
  15610. static struct mg_tcpip_if *s_ifp; // MIP interface
  15611. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  15612. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  15613. ETH0->GMII_ADDRESS = (ETH0->GMII_ADDRESS & 0x3c) |
  15614. ((uint32_t)addr << 11) |
  15615. ((uint32_t)reg << 6) | 1;
  15616. while ((ETH0->GMII_ADDRESS & 1) != 0) (void) 0;
  15617. return (uint16_t)(ETH0->GMII_DATA & 0xffff);
  15618. }
  15619. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15620. ETH0->GMII_DATA = val;
  15621. ETH0->GMII_ADDRESS = (ETH0->GMII_ADDRESS & 0x3c) |
  15622. ((uint32_t)addr << 11) |
  15623. ((uint32_t)reg << 6) | 3;
  15624. while ((ETH0->GMII_ADDRESS & 1) != 0) (void) 0;
  15625. }
  15626. static uint32_t get_clock_rate(struct mg_tcpip_driver_xmc_data *d) {
  15627. if (d->mdc_cr == -1) {
  15628. // assume ETH clock is 60MHz by default
  15629. // then according to 13.2.8.1, we need to set value 3
  15630. return 3;
  15631. }
  15632. return d->mdc_cr;
  15633. }
  15634. static bool mg_tcpip_driver_xmc_init(struct mg_tcpip_if *ifp) {
  15635. struct mg_tcpip_driver_xmc_data *d =
  15636. (struct mg_tcpip_driver_xmc_data *) ifp->driver_data;
  15637. s_ifp = ifp;
  15638. // reset MAC
  15639. ETH0->BUS_MODE |= 1;
  15640. while (ETH0->BUS_MODE & 1) (void) 0;
  15641. // set clock rate
  15642. ETH0->GMII_ADDRESS = get_clock_rate(d) << 2;
  15643. // init phy
  15644. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15645. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  15646. // configure MAC: DO, DM, FES, TC
  15647. ETH0->MAC_CONFIGURATION = MG_BIT(13) | MG_BIT(11) | MG_BIT(14) | MG_BIT(24);
  15648. // set the MAC address
  15649. ETH0->MAC_ADDRESS0_HIGH = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  15650. ETH0->MAC_ADDRESS0_LOW =
  15651. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  15652. // Configure the receive filter
  15653. ETH0->MAC_FRAME_FILTER = MG_BIT(10) | MG_BIT(2); // HFP, HMC
  15654. // Disable flow control
  15655. ETH0->FLOW_CONTROL = 0;
  15656. // Enable store and forward mode
  15657. ETH0->OPERATION_MODE = MG_BIT(25) | MG_BIT(21); // RSF, TSF
  15658. // Configure DMA bus mode (AAL, USP, RPBL, PBL)
  15659. ETH0->BUS_MODE = MG_BIT(25) | MG_BIT(23) | (32 << 17) | (32 << 8);
  15660. // init RX descriptors
  15661. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15662. s_rxdesc[i][0] = MG_BIT(31); // OWN descriptor
  15663. s_rxdesc[i][1] = MG_BIT(14) | ETH_PKT_SIZE;
  15664. s_rxdesc[i][2] = (uint32_t) s_rxbuf[i];
  15665. if (i == ETH_DESC_CNT - 1) {
  15666. s_rxdesc[i][3] = (uint32_t) &s_rxdesc[0][0];
  15667. } else {
  15668. s_rxdesc[i][3] = (uint32_t) &s_rxdesc[i + 1][0];
  15669. }
  15670. }
  15671. ETH0->RECEIVE_DESCRIPTOR_LIST_ADDRESS = (uint32_t) &s_rxdesc[0][0];
  15672. // init TX descriptors
  15673. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15674. s_txdesc[i][0] = MG_BIT(30) | MG_BIT(20);
  15675. s_txdesc[i][2] = (uint32_t) s_txbuf[i];
  15676. if (i == ETH_DESC_CNT - 1) {
  15677. s_txdesc[i][3] = (uint32_t) &s_txdesc[0][0];
  15678. } else {
  15679. s_txdesc[i][3] = (uint32_t) &s_txdesc[i + 1][0];
  15680. }
  15681. }
  15682. ETH0->TRANSMIT_DESCRIPTOR_LIST_ADDRESS = (uint32_t) &s_txdesc[0][0];
  15683. // Clear interrupts
  15684. ETH0->STATUS = 0xFFFFFFFF;
  15685. // Disable MAC interrupts
  15686. ETH0->MMC_TRANSMIT_INTERRUPT_MASK = 0xFFFFFFFF;
  15687. ETH0->MMC_RECEIVE_INTERRUPT_MASK = 0xFFFFFFFF;
  15688. ETH0->MMC_IPC_RECEIVE_INTERRUPT_MASK = 0xFFFFFFFF;
  15689. ETH0->INTERRUPT_MASK = MG_BIT(9) | MG_BIT(3); // TSIM, PMTIM
  15690. //Enable interrupts (NIE, RIE, TIE)
  15691. ETH0->INTERRUPT_ENABLE = MG_BIT(16) | MG_BIT(6) | MG_BIT(0);
  15692. // Enable MAC transmission and reception (TE, RE)
  15693. ETH0->MAC_CONFIGURATION |= MG_BIT(3) | MG_BIT(2);
  15694. // Enable DMA transmission and reception (ST, SR)
  15695. ETH0->OPERATION_MODE |= MG_BIT(13) | MG_BIT(1);
  15696. return true;
  15697. }
  15698. static size_t mg_tcpip_driver_xmc_tx(const void *buf, size_t len,
  15699. struct mg_tcpip_if *ifp) {
  15700. if (len > sizeof(s_txbuf[s_txno])) {
  15701. MG_ERROR(("Frame too big, %ld", (long) len));
  15702. len = 0; // Frame is too big
  15703. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  15704. ifp->nerr++;
  15705. MG_ERROR(("No free descriptors"));
  15706. len = 0; // All descriptors are busy, fail
  15707. } else {
  15708. memcpy(s_txbuf[s_txno], buf, len);
  15709. s_txdesc[s_txno][1] = len;
  15710. // Table 13-19 Transmit Descriptor Word 0 (IC, LS, FS, TCH)
  15711. s_txdesc[s_txno][0] = MG_BIT(30) | MG_BIT(29) | MG_BIT(28) | MG_BIT(20);
  15712. s_txdesc[s_txno][0] |= MG_BIT(31); // OWN bit: handle control to DMA
  15713. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15714. }
  15715. // Resume processing
  15716. ETH0->STATUS = MG_BIT(2); // clear Transmit unavailable
  15717. ETH0->TRANSMIT_POLL_DEMAND = 0;
  15718. return len;
  15719. }
  15720. static bool mg_tcpip_driver_xmc_up(struct mg_tcpip_if *ifp) {
  15721. struct mg_tcpip_driver_xmc_data *d =
  15722. (struct mg_tcpip_driver_xmc_data *) ifp->driver_data;
  15723. uint8_t speed = MG_PHY_SPEED_10M;
  15724. bool up = false, full_duplex = false;
  15725. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15726. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  15727. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15728. MG_DEBUG(("Link is %uM %s-duplex", speed == MG_PHY_SPEED_10M ? 10 : 100,
  15729. full_duplex ? "full" : "half"));
  15730. }
  15731. return up;
  15732. }
  15733. void ETH0_IRQHandler(void);
  15734. void ETH0_IRQHandler(void) {
  15735. uint32_t irq_status = ETH0->STATUS;
  15736. // check if a frame was received
  15737. if (irq_status & MG_BIT(6)) {
  15738. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  15739. if ((s_rxdesc[s_rxno][0] & MG_BIT(31)) == 0) {
  15740. size_t len = (s_rxdesc[s_rxno][0] & 0x3fff0000) >> 16;
  15741. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  15742. s_rxdesc[s_rxno][0] = MG_BIT(31); // OWN bit: handle control to DMA
  15743. // Resume processing
  15744. ETH0->STATUS = MG_BIT(7) | MG_BIT(6); // clear RU and RI
  15745. ETH0->RECEIVE_POLL_DEMAND = 0;
  15746. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15747. }
  15748. }
  15749. ETH0->STATUS = MG_BIT(6);
  15750. }
  15751. // clear Successful transmission interrupt
  15752. if (irq_status & 1) {
  15753. ETH0->STATUS = 1;
  15754. }
  15755. // clear normal interrupt
  15756. if (irq_status & MG_BIT(16)) {
  15757. ETH0->STATUS = MG_BIT(16);
  15758. }
  15759. }
  15760. struct mg_tcpip_driver mg_tcpip_driver_xmc = {
  15761. mg_tcpip_driver_xmc_init, mg_tcpip_driver_xmc_tx, NULL,
  15762. mg_tcpip_driver_xmc_up};
  15763. #endif
  15764. #ifdef MG_ENABLE_LINES
  15765. #line 1 "src/drivers/xmc7.c"
  15766. #endif
  15767. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7
  15768. struct ETH_Type {
  15769. volatile uint32_t CTL, STATUS, RESERVED[1022], NETWORK_CONTROL,
  15770. NETWORK_CONFIG, NETWORK_STATUS, USER_IO_REGISTER, DMA_CONFIG,
  15771. TRANSMIT_STATUS, RECEIVE_Q_PTR, TRANSMIT_Q_PTR, RECEIVE_STATUS,
  15772. INT_STATUS, INT_ENABLE, INT_DISABLE, INT_MASK, PHY_MANAGEMENT, PAUSE_TIME,
  15773. TX_PAUSE_QUANTUM, PBUF_TXCUTTHRU, PBUF_RXCUTTHRU, JUMBO_MAX_LENGTH,
  15774. EXTERNAL_FIFO_INTERFACE, RESERVED1, AXI_MAX_PIPELINE, RSC_CONTROL,
  15775. INT_MODERATION, SYS_WAKE_TIME, RESERVED2[7], HASH_BOTTOM, HASH_TOP,
  15776. SPEC_ADD1_BOTTOM, SPEC_ADD1_TOP, SPEC_ADD2_BOTTOM, SPEC_ADD2_TOP,
  15777. SPEC_ADD3_BOTTOM, SPEC_ADD3_TOP, SPEC_ADD4_BOTTOM, SPEC_ADD4_TOP,
  15778. SPEC_TYPE1, SPEC_TYPE2, SPEC_TYPE3, SPEC_TYPE4, WOL_REGISTER,
  15779. STRETCH_RATIO, STACKED_VLAN, TX_PFC_PAUSE, MASK_ADD1_BOTTOM,
  15780. MASK_ADD1_TOP, DMA_ADDR_OR_MASK, RX_PTP_UNICAST, TX_PTP_UNICAST,
  15781. TSU_NSEC_CMP, TSU_SEC_CMP, TSU_MSB_SEC_CMP, TSU_PTP_TX_MSB_SEC,
  15782. TSU_PTP_RX_MSB_SEC, TSU_PEER_TX_MSB_SEC, TSU_PEER_RX_MSB_SEC,
  15783. DPRAM_FILL_DBG, REVISION_REG, OCTETS_TXED_BOTTOM, OCTETS_TXED_TOP,
  15784. FRAMES_TXED_OK, BROADCAST_TXED, MULTICAST_TXED, PAUSE_FRAMES_TXED,
  15785. FRAMES_TXED_64, FRAMES_TXED_65, FRAMES_TXED_128, FRAMES_TXED_256,
  15786. FRAMES_TXED_512, FRAMES_TXED_1024, FRAMES_TXED_1519, TX_UNDERRUNS,
  15787. SINGLE_COLLISIONS, MULTIPLE_COLLISIONS, EXCESSIVE_COLLISIONS,
  15788. LATE_COLLISIONS, DEFERRED_FRAMES, CRS_ERRORS, OCTETS_RXED_BOTTOM,
  15789. OCTETS_RXED_TOP, FRAMES_RXED_OK, BROADCAST_RXED, MULTICAST_RXED,
  15790. PAUSE_FRAMES_RXED, FRAMES_RXED_64, FRAMES_RXED_65, FRAMES_RXED_128,
  15791. FRAMES_RXED_256, FRAMES_RXED_512, FRAMES_RXED_1024, FRAMES_RXED_1519,
  15792. UNDERSIZE_FRAMES, EXCESSIVE_RX_LENGTH, RX_JABBERS, FCS_ERRORS,
  15793. RX_LENGTH_ERRORS, RX_SYMBOL_ERRORS, ALIGNMENT_ERRORS, RX_RESOURCE_ERRORS,
  15794. RX_OVERRUNS, RX_IP_CK_ERRORS, RX_TCP_CK_ERRORS, RX_UDP_CK_ERRORS,
  15795. AUTO_FLUSHED_PKTS, RESERVED3, TSU_TIMER_INCR_SUB_NSEC, TSU_TIMER_MSB_SEC,
  15796. TSU_STROBE_MSB_SEC, TSU_STROBE_SEC, TSU_STROBE_NSEC, TSU_TIMER_SEC,
  15797. TSU_TIMER_NSEC, TSU_TIMER_ADJUST, TSU_TIMER_INCR, TSU_PTP_TX_SEC,
  15798. TSU_PTP_TX_NSEC, TSU_PTP_RX_SEC, TSU_PTP_RX_NSEC, TSU_PEER_TX_SEC,
  15799. TSU_PEER_TX_NSEC, TSU_PEER_RX_SEC, TSU_PEER_RX_NSEC, PCS_CONTROL,
  15800. PCS_STATUS, RESERVED4[2], PCS_AN_ADV, PCS_AN_LP_BASE, PCS_AN_EXP,
  15801. PCS_AN_NP_TX, PCS_AN_LP_NP, RESERVED5[6], PCS_AN_EXT_STATUS, RESERVED6[8],
  15802. TX_PAUSE_QUANTUM1, TX_PAUSE_QUANTUM2, TX_PAUSE_QUANTUM3, RESERVED7,
  15803. RX_LPI, RX_LPI_TIME, TX_LPI, TX_LPI_TIME, DESIGNCFG_DEBUG1,
  15804. DESIGNCFG_DEBUG2, DESIGNCFG_DEBUG3, DESIGNCFG_DEBUG4, DESIGNCFG_DEBUG5,
  15805. DESIGNCFG_DEBUG6, DESIGNCFG_DEBUG7, DESIGNCFG_DEBUG8, DESIGNCFG_DEBUG9,
  15806. DESIGNCFG_DEBUG10, RESERVED8[22], SPEC_ADD5_BOTTOM, SPEC_ADD5_TOP,
  15807. RESERVED9[60], SPEC_ADD36_BOTTOM, SPEC_ADD36_TOP, INT_Q1_STATUS,
  15808. INT_Q2_STATUS, INT_Q3_STATUS, RESERVED10[11], INT_Q15_STATUS, RESERVED11,
  15809. TRANSMIT_Q1_PTR, TRANSMIT_Q2_PTR, TRANSMIT_Q3_PTR, RESERVED12[11],
  15810. TRANSMIT_Q15_PTR, RESERVED13, RECEIVE_Q1_PTR, RECEIVE_Q2_PTR,
  15811. RECEIVE_Q3_PTR, RESERVED14[3], RECEIVE_Q7_PTR, RESERVED15,
  15812. DMA_RXBUF_SIZE_Q1, DMA_RXBUF_SIZE_Q2, DMA_RXBUF_SIZE_Q3, RESERVED16[3],
  15813. DMA_RXBUF_SIZE_Q7, CBS_CONTROL, CBS_IDLESLOPE_Q_A, CBS_IDLESLOPE_Q_B,
  15814. UPPER_TX_Q_BASE_ADDR, TX_BD_CONTROL, RX_BD_CONTROL, UPPER_RX_Q_BASE_ADDR,
  15815. RESERVED17[2], HIDDEN_REG0, HIDDEN_REG1, HIDDEN_REG2, HIDDEN_REG3,
  15816. RESERVED18[2], HIDDEN_REG4, HIDDEN_REG5;
  15817. };
  15818. #define ETH0 ((struct ETH_Type *) 0x40490000)
  15819. #define ETH_PKT_SIZE 1536 // Max frame size
  15820. #define ETH_DESC_CNT 4 // Descriptors count
  15821. #define ETH_DS 2 // Descriptor size (words)
  15822. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15823. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15824. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15825. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15826. static uint8_t s_txno; // Current TX descriptor
  15827. static uint8_t s_rxno; // Current RX descriptor
  15828. static struct mg_tcpip_if *s_ifp; // MIP interface
  15829. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  15830. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  15831. // WRITE1, READ OPERATION, PHY, REG, WRITE10
  15832. ETH0->PHY_MANAGEMENT = MG_BIT(30) | MG_BIT(29) | ((addr & 0xf) << 24) |
  15833. ((reg & 0x1f) << 18) | MG_BIT(17);
  15834. while ((ETH0->NETWORK_STATUS & MG_BIT(2)) == 0) (void) 0;
  15835. return ETH0->PHY_MANAGEMENT & 0xffff;
  15836. }
  15837. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15838. ETH0->PHY_MANAGEMENT = MG_BIT(30) | MG_BIT(28) | ((addr & 0xf) << 24) |
  15839. ((reg & 0x1f) << 18) | MG_BIT(17) | val;
  15840. while ((ETH0->NETWORK_STATUS & MG_BIT(2)) == 0) (void) 0;
  15841. }
  15842. static uint32_t get_clock_rate(struct mg_tcpip_driver_xmc7_data *d) {
  15843. // see ETH0 -> NETWORK_CONFIG register
  15844. (void) d;
  15845. return 3;
  15846. }
  15847. static bool mg_tcpip_driver_xmc7_init(struct mg_tcpip_if *ifp) {
  15848. struct mg_tcpip_driver_xmc7_data *d =
  15849. (struct mg_tcpip_driver_xmc7_data *) ifp->driver_data;
  15850. s_ifp = ifp;
  15851. // enable controller, set RGMII mode
  15852. ETH0->CTL = MG_BIT(31) | 2;
  15853. uint32_t cr = get_clock_rate(d);
  15854. // set NSP change, ignore RX FCS, data bus width, clock rate
  15855. // frame length 1536, full duplex, speed
  15856. ETH0->NETWORK_CONFIG = MG_BIT(29) | MG_BIT(26) | MG_BIT(21) |
  15857. ((cr & 7) << 18) | MG_BIT(8) | MG_BIT(4) |
  15858. MG_BIT(1) | MG_BIT(0);
  15859. // config DMA settings: Force TX burst, Discard on Error, set RX buffer size
  15860. // to 1536, TX_PBUF_SIZE, RX_PBUF_SIZE, AMBA_BURST_LENGTH
  15861. ETH0->DMA_CONFIG =
  15862. MG_BIT(26) | MG_BIT(24) | (0x18 << 16) | MG_BIT(10) | (3 << 8) | 4;
  15863. // initialize descriptors
  15864. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15865. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i];
  15866. if (i == ETH_DESC_CNT - 1) {
  15867. s_rxdesc[i][0] |= MG_BIT(1); // mark last descriptor
  15868. }
  15869. s_txdesc[i][0] = (uint32_t) s_txbuf[i];
  15870. s_txdesc[i][1] = MG_BIT(31); // OWN descriptor
  15871. if (i == ETH_DESC_CNT - 1) {
  15872. s_txdesc[i][1] |= MG_BIT(30); // mark last descriptor
  15873. }
  15874. }
  15875. ETH0->RECEIVE_Q_PTR = (uint32_t) s_rxdesc;
  15876. ETH0->TRANSMIT_Q_PTR = (uint32_t) s_txdesc;
  15877. // disable other queues
  15878. ETH0->TRANSMIT_Q2_PTR = 1;
  15879. ETH0->TRANSMIT_Q1_PTR = 1;
  15880. ETH0->RECEIVE_Q2_PTR = 1;
  15881. ETH0->RECEIVE_Q1_PTR = 1;
  15882. // enable interrupts (TX and RX complete)
  15883. ETH0->INT_ENABLE = MG_BIT(7) | MG_BIT(1);
  15884. // set MAC address
  15885. ETH0->SPEC_ADD1_BOTTOM =
  15886. ifp->mac[3] << 24 | ifp->mac[2] << 16 | ifp->mac[1] << 8 | ifp->mac[0];
  15887. ETH0->SPEC_ADD1_TOP = ifp->mac[5] << 8 | ifp->mac[4];
  15888. // enable MDIO, TX, RX
  15889. ETH0->NETWORK_CONTROL = MG_BIT(4) | MG_BIT(3) | MG_BIT(2);
  15890. // start transmission
  15891. ETH0->NETWORK_CONTROL |= MG_BIT(9);
  15892. // init phy
  15893. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15894. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  15895. (void) d;
  15896. return true;
  15897. }
  15898. static size_t mg_tcpip_driver_xmc7_tx(const void *buf, size_t len,
  15899. struct mg_tcpip_if *ifp) {
  15900. if (len > sizeof(s_txbuf[s_txno])) {
  15901. MG_ERROR(("Frame too big, %ld", (long) len));
  15902. len = 0; // Frame is too big
  15903. } else if (((s_txdesc[s_txno][1] & MG_BIT(31)) == 0)) {
  15904. ifp->nerr++;
  15905. MG_ERROR(("No free descriptors"));
  15906. len = 0; // All descriptors are busy, fail
  15907. } else {
  15908. memcpy(s_txbuf[s_txno], buf, len);
  15909. s_txdesc[s_txno][1] = (s_txno == ETH_DESC_CNT - 1 ? MG_BIT(30) : 0) |
  15910. MG_BIT(15) | len; // Last buffer and length
  15911. ETH0->NETWORK_CONTROL |= MG_BIT(9); // enable transmission
  15912. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15913. }
  15914. MG_DSB();
  15915. ETH0->TRANSMIT_STATUS = ETH0->TRANSMIT_STATUS;
  15916. ETH0->NETWORK_CONTROL |= MG_BIT(9); // enable transmission
  15917. return len;
  15918. }
  15919. static bool mg_tcpip_driver_xmc7_up(struct mg_tcpip_if *ifp) {
  15920. struct mg_tcpip_driver_xmc7_data *d =
  15921. (struct mg_tcpip_driver_xmc7_data *) ifp->driver_data;
  15922. uint8_t speed = MG_PHY_SPEED_10M;
  15923. bool up = false, full_duplex = false;
  15924. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15925. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  15926. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15927. if (speed == MG_PHY_SPEED_1000M) {
  15928. ETH0->NETWORK_CONFIG |= MG_BIT(10);
  15929. }
  15930. MG_DEBUG(("Link is %uM %s-duplex",
  15931. speed == MG_PHY_SPEED_10M ? 10 :
  15932. (speed == MG_PHY_SPEED_100M ? 100 : 1000),
  15933. full_duplex ? "full" : "half"));
  15934. }
  15935. (void) d;
  15936. return up;
  15937. }
  15938. void ETH_IRQHandler(void) {
  15939. uint32_t irq_status = ETH0->INT_STATUS;
  15940. if (irq_status & MG_BIT(1)) {
  15941. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  15942. if (s_rxdesc[s_rxno][0] & MG_BIT(0)) {
  15943. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  15944. //MG_INFO(("Receive complete: %ld bytes", len));
  15945. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  15946. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // OWN bit: handle control to DMA
  15947. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15948. }
  15949. }
  15950. }
  15951. ETH0->INT_STATUS = irq_status;
  15952. }
  15953. struct mg_tcpip_driver mg_tcpip_driver_xmc7 = {mg_tcpip_driver_xmc7_init,
  15954. mg_tcpip_driver_xmc7_tx, NULL,
  15955. mg_tcpip_driver_xmc7_up};
  15956. #endif