mongoose.c 605 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784
  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. mg_printf(c, "HTTP/1.1 %d %s\r\n"
  2432. "Content-Type: text/html\n"
  2433. "Content-Length: %d\n"
  2434. "Connection: Keep-Alive\n"
  2435. "Keep-Alive: timeout=30, max=396\n"
  2436. "X-Content-Type-0ptions: nosniff\n"
  2437. "X-Frame-0ptions:: SAMEORIGIN\n"
  2438. "X-Xss-Protection: 1: mode=block\n"
  2439. "Accept-Ranges: bytes\n"
  2440. "Vary: Accept-Encoding\n\n", code, mg_http_status_code_str(code),strlen(fmt == NULL ? "" : fmt));
  2441. len = c->send.len;
  2442. va_start(ap, fmt);
  2443. r = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt?fmt:"", &ap);
  2444. va_end(ap);
  2445. c->is_resp = 0;
  2446. return r;
  2447. }
  2448. static void http_cb(struct mg_connection *, int, void *);
  2449. static void restore_http_cb(struct mg_connection *c) {
  2450. mg_fs_close((struct mg_fd *) c->pfn_data);
  2451. c->pfn_data = NULL;
  2452. c->pfn = http_cb;
  2453. c->is_resp = 0;
  2454. }
  2455. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
  2456. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime) {
  2457. mg_snprintf(buf, len, "\"%lld.%lld\"", (int64_t) mtime, (int64_t) size);
  2458. return buf;
  2459. }
  2460. static void static_cb(struct mg_connection *c, int ev, void *ev_data) {
  2461. if (ev == MG_EV_WRITE || ev == MG_EV_POLL) {
  2462. struct mg_fd *fd = (struct mg_fd *) c->pfn_data;
  2463. // Read to send IO buffer directly, avoid extra on-stack buffer
  2464. size_t n, max = MG_IO_SIZE, space;
  2465. size_t *cl = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2466. sizeof(size_t) * sizeof(size_t)];
  2467. if (c->send.size < max) mg_iobuf_resize(&c->send, max);
  2468. if (c->send.len >= c->send.size) return; // Rate limit
  2469. if ((space = c->send.size - c->send.len) > *cl) space = *cl;
  2470. n = fd->fs->rd(fd->fd, c->send.buf + c->send.len, space);
  2471. c->send.len += n;
  2472. *cl -= n;
  2473. if (n == 0) restore_http_cb(c);
  2474. } else if (ev == MG_EV_CLOSE) {
  2475. restore_http_cb(c);
  2476. }
  2477. (void) ev_data;
  2478. }
  2479. // Known mime types. Keep it outside guess_content_type() function, since
  2480. // some environments don't like it defined there.
  2481. // clang-format off
  2482. #define MG_C_STR(a) { (char *) (a), sizeof(a) - 1 }
  2483. static struct mg_str s_known_types[] = {
  2484. MG_C_STR("html"), MG_C_STR("text/html; charset=utf-8"),
  2485. MG_C_STR("htm"), MG_C_STR("text/html; charset=utf-8"),
  2486. MG_C_STR("css"), MG_C_STR("text/css; charset=utf-8"),
  2487. MG_C_STR("js"), MG_C_STR("text/javascript; charset=utf-8"),
  2488. MG_C_STR("gif"), MG_C_STR("image/gif"),
  2489. MG_C_STR("png"), MG_C_STR("image/png"),
  2490. MG_C_STR("jpg"), MG_C_STR("image/jpeg"),
  2491. MG_C_STR("jpeg"), MG_C_STR("image/jpeg"),
  2492. MG_C_STR("woff"), MG_C_STR("font/woff"),
  2493. MG_C_STR("ttf"), MG_C_STR("font/ttf"),
  2494. MG_C_STR("svg"), MG_C_STR("image/svg+xml"),
  2495. MG_C_STR("txt"), MG_C_STR("text/plain; charset=utf-8"),
  2496. MG_C_STR("avi"), MG_C_STR("video/x-msvideo"),
  2497. MG_C_STR("csv"), MG_C_STR("text/csv"),
  2498. MG_C_STR("doc"), MG_C_STR("application/msword"),
  2499. MG_C_STR("exe"), MG_C_STR("application/octet-stream"),
  2500. MG_C_STR("gz"), MG_C_STR("application/gzip"),
  2501. MG_C_STR("ico"), MG_C_STR("image/x-icon"),
  2502. MG_C_STR("json"), MG_C_STR("application/json"),
  2503. MG_C_STR("mov"), MG_C_STR("video/quicktime"),
  2504. MG_C_STR("mp3"), MG_C_STR("audio/mpeg"),
  2505. MG_C_STR("mp4"), MG_C_STR("video/mp4"),
  2506. MG_C_STR("mpeg"), MG_C_STR("video/mpeg"),
  2507. MG_C_STR("pdf"), MG_C_STR("application/pdf"),
  2508. MG_C_STR("shtml"), MG_C_STR("text/html; charset=utf-8"),
  2509. MG_C_STR("tgz"), MG_C_STR("application/tar-gz"),
  2510. MG_C_STR("wav"), MG_C_STR("audio/wav"),
  2511. MG_C_STR("webp"), MG_C_STR("image/webp"),
  2512. MG_C_STR("zip"), MG_C_STR("application/zip"),
  2513. MG_C_STR("3gp"), MG_C_STR("video/3gpp"),
  2514. {0, 0},
  2515. };
  2516. // clang-format on
  2517. static struct mg_str guess_content_type(struct mg_str path, const char *extra) {
  2518. struct mg_str entry, k, v, s = mg_str(extra);
  2519. size_t i = 0;
  2520. // Shrink path to its extension only
  2521. while (i < path.len && path.buf[path.len - i - 1] != '.') i++;
  2522. path.buf += path.len - i;
  2523. path.len = i;
  2524. // Process user-provided mime type overrides, if any
  2525. while (mg_span(s, &entry, &s, ',')) {
  2526. if (mg_span(entry, &k, &v, '=') && mg_strcmp(path, k) == 0) return v;
  2527. }
  2528. // Process built-in mime types
  2529. for (i = 0; s_known_types[i].buf != NULL; i += 2) {
  2530. if (mg_strcmp(path, s_known_types[i]) == 0) return s_known_types[i + 1];
  2531. }
  2532. return mg_str("text/plain; charset=utf-8");
  2533. }
  2534. static int getrange(struct mg_str *s, size_t *a, size_t *b) {
  2535. size_t i, numparsed = 0;
  2536. for (i = 0; i + 6 < s->len; i++) {
  2537. struct mg_str k, v = mg_str_n(s->buf + i + 6, s->len - i - 6);
  2538. if (memcmp(&s->buf[i], "bytes=", 6) != 0) continue;
  2539. if (mg_span(v, &k, &v, '-')) {
  2540. if (mg_to_size_t(k, a)) numparsed++;
  2541. if (v.len > 0 && mg_to_size_t(v, b)) numparsed++;
  2542. } else {
  2543. if (mg_to_size_t(v, a)) numparsed++;
  2544. }
  2545. break;
  2546. }
  2547. return (int) numparsed;
  2548. }
  2549. void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
  2550. const char *path,
  2551. const struct mg_http_serve_opts *opts) {
  2552. char etag[64], tmp[MG_PATH_MAX];
  2553. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2554. struct mg_fd *fd = NULL;
  2555. size_t size = 0;
  2556. time_t mtime = 0;
  2557. struct mg_str *inm = NULL;
  2558. struct mg_str mime = guess_content_type(mg_str(path), opts->mime_types);
  2559. bool gzip = false;
  2560. if (path != NULL) {
  2561. // If a browser sends us "Accept-Encoding: gzip", try to open .gz first
  2562. struct mg_str *ae = mg_http_get_header(hm, "Accept-Encoding");
  2563. if (ae != NULL) {
  2564. char *ae_ = mg_mprintf("%.*s", ae->len, ae->buf);
  2565. if (ae_ != NULL && strstr(ae_, "gzip") != NULL) {
  2566. mg_snprintf(tmp, sizeof(tmp), "%s.gz", path);
  2567. fd = mg_fs_open(fs, tmp, MG_FS_READ);
  2568. if (fd != NULL) gzip = true, path = tmp;
  2569. }
  2570. free(ae_);
  2571. }
  2572. // No luck opening .gz? Open what we've told to open
  2573. if (fd == NULL) fd = mg_fs_open(fs, path, MG_FS_READ);
  2574. }
  2575. // Failed to open, and page404 is configured? Open it, then
  2576. if (fd == NULL && opts->page404 != NULL) {
  2577. fd = mg_fs_open(fs, opts->page404, MG_FS_READ);
  2578. path = opts->page404;
  2579. mime = guess_content_type(mg_str(path), opts->mime_types);
  2580. }
  2581. if (fd == NULL || fs->st(path, &size, &mtime) == 0) {
  2582. mg_http_reply(c, 404, opts->extra_headers, "Not found\n");
  2583. mg_fs_close(fd);
  2584. // NOTE: mg_http_etag() call should go first!
  2585. } else if (mg_http_etag(etag, sizeof(etag), size, mtime) != NULL &&
  2586. (inm = mg_http_get_header(hm, "If-None-Match")) != NULL &&
  2587. mg_strcasecmp(*inm, mg_str(etag)) == 0) {
  2588. mg_fs_close(fd);
  2589. mg_http_reply(c, 304, opts->extra_headers, "");
  2590. } else {
  2591. int n, status = 200;
  2592. char range[100];
  2593. size_t r1 = 0, r2 = 0, cl = size;
  2594. // Handle Range header
  2595. struct mg_str *rh = mg_http_get_header(hm, "Range");
  2596. range[0] = '\0';
  2597. if (rh != NULL && (n = getrange(rh, &r1, &r2)) > 0) {
  2598. // If range is specified like "400-", set second limit to content len
  2599. if (n == 1) r2 = cl - 1;
  2600. if (r1 > r2 || r2 >= cl) {
  2601. status = 416;
  2602. cl = 0;
  2603. mg_snprintf(range, sizeof(range), "Content-Range: bytes */%lld\r\n",
  2604. (int64_t) size);
  2605. } else {
  2606. status = 206;
  2607. cl = r2 - r1 + 1;
  2608. mg_snprintf(range, sizeof(range),
  2609. "Content-Range: bytes %llu-%llu/%llu\r\n", (uint64_t) r1,
  2610. (uint64_t) (r1 + cl - 1), (uint64_t) size);
  2611. fs->sk(fd->fd, r1);
  2612. }
  2613. }
  2614. mg_printf(c,
  2615. "HTTP/1.1 %d %s\r\n"
  2616. "Content-Type: %.*s\r\n"
  2617. "Etag: %s\r\n"
  2618. "Content-Length: %llu\r\n"
  2619. "%s%s%s\r\n",
  2620. status, mg_http_status_code_str(status), (int) mime.len, mime.buf,
  2621. etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
  2622. range, opts->extra_headers ? opts->extra_headers : "");
  2623. if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0) {
  2624. c->is_draining = 1;
  2625. c->is_resp = 0;
  2626. mg_fs_close(fd);
  2627. } else {
  2628. // Track to-be-sent content length at the end of c->data, aligned
  2629. size_t *clp = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2630. sizeof(size_t) * sizeof(size_t)];
  2631. c->pfn = static_cb;
  2632. c->pfn_data = fd;
  2633. *clp = cl;
  2634. }
  2635. }
  2636. }
  2637. static char *get_fname(const char *path)
  2638. {
  2639. char *p=strrchr(path, '/');
  2640. if(p) {
  2641. return p+1;
  2642. }
  2643. return (char*)path;
  2644. }
  2645. void mg_http_serve_file2(struct mg_connection *c, struct mg_http_message *hm,
  2646. const char *path,
  2647. const struct mg_http_serve_opts *opts) {
  2648. char etag[64], tmp[MG_PATH_MAX];
  2649. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2650. struct mg_fd *fd = NULL;
  2651. size_t size = 0;
  2652. time_t mtime = 0;
  2653. struct mg_str *inm = NULL;
  2654. struct mg_str mime = guess_content_type(mg_str(path), opts->mime_types);
  2655. bool gzip = false;
  2656. if (path != NULL) {
  2657. // If a browser sends us "Accept-Encoding: gzip", try to open .gz first
  2658. struct mg_str *ae = mg_http_get_header(hm, "Accept-Encoding");
  2659. if (ae != NULL) {
  2660. char *ae_ = mg_mprintf("%.*s", ae->len, ae->buf);
  2661. if (ae_ != NULL && strstr(ae_, "gzip") != NULL) {
  2662. mg_snprintf(tmp, sizeof(tmp), "%s.gz", path);
  2663. fd = mg_fs_open(fs, tmp, MG_FS_READ);
  2664. if (fd != NULL) gzip = true, path = tmp;
  2665. }
  2666. free(ae_);
  2667. }
  2668. // No luck opening .gz? Open what we've told to open
  2669. if (fd == NULL) fd = mg_fs_open(fs, path, MG_FS_READ);
  2670. }
  2671. // Failed to open, and page404 is configured? Open it, then
  2672. if (fd == NULL && opts->page404 != NULL) {
  2673. fd = mg_fs_open(fs, opts->page404, MG_FS_READ);
  2674. path = opts->page404;
  2675. mime = guess_content_type(mg_str(path), opts->mime_types);
  2676. }
  2677. if (fd == NULL || fs->st(path, &size, &mtime) == 0) {
  2678. mg_http_reply(c, 404, opts->extra_headers, "Not found\n");
  2679. mg_fs_close(fd);
  2680. // NOTE: mg_http_etag() call should go first!
  2681. } else if (mg_http_etag(etag, sizeof(etag), size, mtime) != NULL &&
  2682. (inm = mg_http_get_header(hm, "If-None-Match")) != NULL &&
  2683. mg_strcasecmp(*inm, mg_str(etag)) == 0) {
  2684. mg_fs_close(fd);
  2685. mg_http_reply(c, 304, opts->extra_headers, "");
  2686. } else {
  2687. int n, status = 200;
  2688. char range[100];
  2689. size_t r1 = 0, r2 = 0, cl = size;
  2690. // Handle Range header
  2691. struct mg_str *rh = mg_http_get_header(hm, "Range");
  2692. range[0] = '\0';
  2693. if (rh != NULL && (n = getrange(rh, &r1, &r2)) > 0) {
  2694. // If range is specified like "400-", set second limit to content len
  2695. if (n == 1) r2 = cl - 1;
  2696. if (r1 > r2 || r2 >= cl) {
  2697. status = 416;
  2698. cl = 0;
  2699. mg_snprintf(range, sizeof(range), "Content-Range: bytes */%lld\r\n",
  2700. (int64_t) size);
  2701. } else {
  2702. status = 206;
  2703. cl = r2 - r1 + 1;
  2704. mg_snprintf(range, sizeof(range),
  2705. "Content-Range: bytes %llu-%llu/%llu\r\n", (uint64_t) r1,
  2706. (uint64_t) (r1 + cl - 1), (uint64_t) size);
  2707. fs->sk(fd->fd, r1);
  2708. }
  2709. }
  2710. mg_printf(c,
  2711. "HTTP/1.1 %d %s\r\n"
  2712. "Content-Type: %.*s\r\n"
  2713. "Content-Disposition: attachment;filename=%s\r\n"
  2714. "Etag: %s\r\n"
  2715. "Content-Length: %llu\r\n"
  2716. "%s%s%s\r\n",
  2717. status, mg_http_status_code_str(status), (int) mime.len, mime.buf,
  2718. get_fname(path),
  2719. etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
  2720. range, opts->extra_headers ? opts->extra_headers : "");
  2721. if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0) {
  2722. c->is_draining = 1;
  2723. c->is_resp = 0;
  2724. mg_fs_close(fd);
  2725. } else {
  2726. // Track to-be-sent content length at the end of c->data, aligned
  2727. size_t *clp = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2728. sizeof(size_t) * sizeof(size_t)];
  2729. c->pfn = static_cb;
  2730. c->pfn_data = fd;
  2731. *clp = cl;
  2732. }
  2733. }
  2734. }
  2735. struct printdirentrydata {
  2736. struct mg_connection *c;
  2737. struct mg_http_message *hm;
  2738. const struct mg_http_serve_opts *opts;
  2739. const char *dir;
  2740. };
  2741. #if MG_ENABLE_DIRLIST
  2742. static void printdirentry(const char *name, void *userdata) {
  2743. struct printdirentrydata *d = (struct printdirentrydata *) userdata;
  2744. struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs;
  2745. size_t size = 0;
  2746. time_t t = 0;
  2747. char path[MG_PATH_MAX], sz[40], mod[40];
  2748. int flags, n = 0;
  2749. // MG_DEBUG(("[%s] [%s]", d->dir, name));
  2750. if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >
  2751. sizeof(path)) {
  2752. MG_ERROR(("%s truncated", name));
  2753. } else if ((flags = fs->st(path, &size, &t)) == 0) {
  2754. MG_ERROR(("%lu stat(%s): %d", d->c->id, path, errno));
  2755. } else {
  2756. const char *slash = flags & MG_FS_DIR ? "/" : "";
  2757. if (flags & MG_FS_DIR) {
  2758. mg_snprintf(sz, sizeof(sz), "%s", "[DIR]");
  2759. } else {
  2760. mg_snprintf(sz, sizeof(sz), "%lld", (uint64_t) size);
  2761. }
  2762. #if defined(MG_HTTP_DIRLIST_TIME_FMT)
  2763. {
  2764. char time_str[40];
  2765. struct tm *time_info = localtime(&t);
  2766. strftime(time_str, sizeof time_str, "%Y/%m/%d %H:%M:%S", time_info);
  2767. mg_snprintf(mod, sizeof(mod), "%s", time_str);
  2768. }
  2769. #else
  2770. mg_snprintf(mod, sizeof(mod), "%lu", (unsigned long) t);
  2771. #endif
  2772. n = (int) mg_url_encode(name, strlen(name), path, sizeof(path));
  2773. mg_printf(d->c,
  2774. " <tr><td><a href=\"%.*s%s\">%s%s</a></td>"
  2775. "<td name=%lu>%s</td><td name=%lld>%s</td></tr>\n",
  2776. n, path, slash, name, slash, (unsigned long) t, mod,
  2777. flags & MG_FS_DIR ? (int64_t) -1 : (int64_t) size, sz);
  2778. }
  2779. }
  2780. static void listdir(struct mg_connection *c, struct mg_http_message *hm,
  2781. const struct mg_http_serve_opts *opts, char *dir) {
  2782. const char *sort_js_code =
  2783. "<script>function srt(tb, sc, so, d) {"
  2784. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  2785. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  2786. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  2787. "t1 = a.cells[2].getAttribute('name'), "
  2788. "t2 = b.cells[2].getAttribute('name'); "
  2789. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  2790. "n1 ? parseInt(n2) - parseInt(n1) : "
  2791. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  2792. const char *sort_js_code2 =
  2793. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  2794. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  2795. "};"
  2796. "window.onload = function() {"
  2797. "var tb = document.getElementById('tb');"
  2798. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  2799. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  2800. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  2801. "sc = c; ev.preventDefault();}};"
  2802. "srt(tb, sc, so, true);"
  2803. "}"
  2804. "</script>";
  2805. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2806. struct printdirentrydata d = {c, hm, opts, dir};
  2807. char tmp[10], buf[MG_PATH_MAX];
  2808. size_t off, n;
  2809. int len = mg_url_decode(hm->uri.buf, hm->uri.len, buf, sizeof(buf), 0);
  2810. struct mg_str uri = len > 0 ? mg_str_n(buf, (size_t) len) : hm->uri;
  2811. mg_printf(c,
  2812. "HTTP/1.1 200 OK\r\n"
  2813. "Content-Type: text/html; charset=utf-8\r\n"
  2814. "%s"
  2815. "Content-Length: \r\n\r\n",
  2816. opts->extra_headers == NULL ? "" : opts->extra_headers);
  2817. off = c->send.len; // Start of body
  2818. mg_printf(c,
  2819. "<!DOCTYPE html><html><head><title>Index of %.*s</title>%s%s"
  2820. "<style>th,td {text-align: left; padding-right: 1em; "
  2821. "font-family: monospace; }</style></head>"
  2822. "<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>"
  2823. "<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
  2824. "<a href=\"#\" rel=\"1\">Modified</a></th>"
  2825. "<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
  2826. "<tr><td colspan=\"3\"><hr></td></tr>"
  2827. "</thead>"
  2828. "<tbody id=\"tb\">\n",
  2829. (int) uri.len, uri.buf, sort_js_code, sort_js_code2, (int) uri.len,
  2830. uri.buf);
  2831. mg_printf(c, "%s",
  2832. " <tr><td><a href=\"..\">..</a></td>"
  2833. "<td name=-1></td><td name=-1>[DIR]</td></tr>\n");
  2834. fs->ls(dir, printdirentry, &d);
  2835. mg_printf(c,
  2836. "</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
  2837. "</table><address>Mongoose v.%s</address></body></html>\n",
  2838. MG_VERSION);
  2839. n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
  2840. if (n > sizeof(tmp)) n = 0;
  2841. memcpy(c->send.buf + off - 12, tmp, n); // Set content length
  2842. c->is_resp = 0; // Mark response end
  2843. }
  2844. #endif
  2845. // Resolve requested file into `path` and return its fs->st() result
  2846. static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
  2847. struct mg_fs *fs, struct mg_str url, struct mg_str dir,
  2848. char *path, size_t path_size) {
  2849. int flags, tmp;
  2850. // Append URI to the root_dir, and sanitize it
  2851. size_t n = mg_snprintf(path, path_size, "%.*s", (int) dir.len, dir.buf);
  2852. if (n + 2 >= path_size) {
  2853. mg_http_reply(c, 400, "", "Exceeded path size");
  2854. return -1;
  2855. }
  2856. path[path_size - 1] = '\0';
  2857. // Terminate root dir with slash
  2858. if (n > 0 && path[n - 1] != '/') path[n++] = '/', path[n] = '\0';
  2859. if (url.len < hm->uri.len) {
  2860. mg_url_decode(hm->uri.buf + url.len, hm->uri.len - url.len, path + n,
  2861. path_size - n, 0);
  2862. }
  2863. path[path_size - 1] = '\0'; // Double-check
  2864. if (!mg_path_is_sane(mg_str_n(path, path_size))) {
  2865. mg_http_reply(c, 400, "", "Invalid path");
  2866. return -1;
  2867. }
  2868. n = strlen(path);
  2869. while (n > 1 && path[n - 1] == '/') path[--n] = 0; // Trim trailing slashes
  2870. flags = mg_strcmp(hm->uri, mg_str("/")) == 0 ? MG_FS_DIR
  2871. : fs->st(path, NULL, NULL);
  2872. MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.buf, path,
  2873. flags));
  2874. if (flags == 0) {
  2875. // Do nothing - let's caller decide
  2876. } else if ((flags & MG_FS_DIR) && hm->uri.len > 0 &&
  2877. hm->uri.buf[hm->uri.len - 1] != '/') {
  2878. mg_printf(c,
  2879. "HTTP/1.1 301 Moved\r\n"
  2880. "Location: %.*s/\r\n"
  2881. "Content-Length: 0\r\n"
  2882. "\r\n",
  2883. (int) hm->uri.len, hm->uri.buf);
  2884. c->is_resp = 0;
  2885. flags = -1;
  2886. } else if (flags & MG_FS_DIR) {
  2887. if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
  2888. (tmp = fs->st(path, NULL, NULL)) != 0) ||
  2889. (mg_snprintf(path + n, path_size - n, "/index.shtml") > 0 &&
  2890. (tmp = fs->st(path, NULL, NULL)) != 0))) {
  2891. flags = tmp;
  2892. } else if ((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX ".gz") >
  2893. 0 &&
  2894. (tmp = fs->st(path, NULL, NULL)) !=
  2895. 0)) { // check for gzipped index
  2896. flags = tmp;
  2897. path[n + 1 + strlen(MG_HTTP_INDEX)] =
  2898. '\0'; // Remove appended .gz in index file name
  2899. } else {
  2900. path[n] = '\0'; // Remove appended index file name
  2901. }
  2902. }
  2903. return flags;
  2904. }
  2905. static int uri_to_path(struct mg_connection *c, struct mg_http_message *hm,
  2906. const struct mg_http_serve_opts *opts, char *path,
  2907. size_t path_size) {
  2908. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2909. struct mg_str k, v, part, s = mg_str(opts->root_dir), u = {NULL, 0}, p = u;
  2910. while (mg_span(s, &part, &s, ',')) {
  2911. if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
  2912. if (v.len == 0) v = k, k = mg_str("/"), u = k, p = v;
  2913. if (hm->uri.len < k.len) continue;
  2914. if (mg_strcmp(k, mg_str_n(hm->uri.buf, k.len)) != 0) continue;
  2915. u = k, p = v;
  2916. }
  2917. return uri_to_path2(c, hm, fs, u, p, path, path_size);
  2918. }
  2919. void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
  2920. const struct mg_http_serve_opts *opts) {
  2921. char path[MG_PATH_MAX];
  2922. const char *sp = opts->ssi_pattern;
  2923. int flags = uri_to_path(c, hm, opts, path, sizeof(path));
  2924. if (flags < 0) {
  2925. // Do nothing: the response has already been sent by uri_to_path()
  2926. } else if (flags & MG_FS_DIR) {
  2927. #if MG_ENABLE_DIRLIST
  2928. listdir(c, hm, opts, path);
  2929. #else
  2930. mg_http_reply(c, 403, "", "Forbidden\n");
  2931. #endif
  2932. } else if (flags && sp != NULL && mg_match(mg_str(path), mg_str(sp), NULL)) {
  2933. mg_http_serve_ssi(c, opts->root_dir, path);
  2934. } else {
  2935. mg_http_serve_file(c, hm, path, opts);
  2936. }
  2937. }
  2938. static bool mg_is_url_safe(int c) {
  2939. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
  2940. (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~';
  2941. }
  2942. size_t mg_url_encode(const char *s, size_t sl, char *buf, size_t len) {
  2943. size_t i, n = 0;
  2944. for (i = 0; i < sl; i++) {
  2945. int c = *(unsigned char *) &s[i];
  2946. if (n + 4 >= len) return 0;
  2947. if (mg_is_url_safe(c)) {
  2948. buf[n++] = s[i];
  2949. } else {
  2950. mg_snprintf(&buf[n], 4, "%%%M", mg_print_hex, 1, &s[i]);
  2951. n += 3;
  2952. }
  2953. }
  2954. if (len > 0 && n < len - 1) buf[n] = '\0'; // Null-terminate the destination
  2955. if (len > 0) buf[len - 1] = '\0'; // Always.
  2956. return n;
  2957. }
  2958. void mg_http_creds(struct mg_http_message *hm, char *user, size_t userlen,
  2959. char *pass, size_t passlen) {
  2960. struct mg_str *v = mg_http_get_header(hm, "Authorization");
  2961. user[0] = pass[0] = '\0';
  2962. if (v != NULL && v->len > 6 && memcmp(v->buf, "Basic ", 6) == 0) {
  2963. char buf[256];
  2964. size_t n = mg_base64_decode(v->buf + 6, v->len - 6, buf, sizeof(buf));
  2965. const char *p = (const char *) memchr(buf, ':', n > 0 ? n : 0);
  2966. if (p != NULL) {
  2967. mg_snprintf(user, userlen, "%.*s", p - buf, buf);
  2968. mg_snprintf(pass, passlen, "%.*s", n - (size_t) (p - buf) - 1, p + 1);
  2969. }
  2970. } else if (v != NULL && v->len > 7 && memcmp(v->buf, "Bearer ", 7) == 0) {
  2971. mg_snprintf(pass, passlen, "%.*s", (int) v->len - 7, v->buf + 7);
  2972. } else if ((v = mg_http_get_header(hm, "Cookie")) != NULL) {
  2973. struct mg_str t = mg_http_get_header_var(*v, mg_str_n("access_token", 12));
  2974. if (t.len > 0) mg_snprintf(pass, passlen, "%.*s", (int) t.len, t.buf);
  2975. } else {
  2976. mg_http_get_var(&hm->query, "access_token", pass, passlen);
  2977. }
  2978. }
  2979. static struct mg_str stripquotes(struct mg_str s) {
  2980. return s.len > 1 && s.buf[0] == '"' && s.buf[s.len - 1] == '"'
  2981. ? mg_str_n(s.buf + 1, s.len - 2)
  2982. : s;
  2983. }
  2984. struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v) {
  2985. size_t i;
  2986. for (i = 0; v.len > 0 && i + v.len + 2 < s.len; i++) {
  2987. if (s.buf[i + v.len] == '=' && memcmp(&s.buf[i], v.buf, v.len) == 0) {
  2988. const char *p = &s.buf[i + v.len + 1], *b = p, *x = &s.buf[s.len];
  2989. int q = p < x && *p == '"' ? 1 : 0;
  2990. while (p < x &&
  2991. (q ? p == b || *p != '"' : *p != ';' && *p != ' ' && *p != ','))
  2992. p++;
  2993. // MG_INFO(("[%.*s] [%.*s] [%.*s]", (int) s.len, s.buf, (int) v.len,
  2994. // v.buf, (int) (p - b), b));
  2995. return stripquotes(mg_str_n(b, (size_t) (p - b + q)));
  2996. }
  2997. }
  2998. return mg_str_n(NULL, 0);
  2999. }
  3000. long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
  3001. struct mg_fs *fs, const char *dir, size_t max_size) {
  3002. char buf[20] = "0", file[MG_PATH_MAX], path[MG_PATH_MAX];
  3003. long res = 0, offset;
  3004. mg_http_get_var(&hm->query, "offset", buf, sizeof(buf));
  3005. mg_http_get_var(&hm->query, "file", file, sizeof(file));
  3006. offset = strtol(buf, NULL, 0);
  3007. mg_snprintf(path, sizeof(path), "%s%c%s", dir, MG_DIRSEP, file);
  3008. if (hm->body.len == 0) {
  3009. mg_http_reply(c, 200, "", "%ld", res); // Nothing to write
  3010. } else if (file[0] == '\0') {
  3011. mg_http_reply(c, 400, "", "file required");
  3012. res = -1;
  3013. } else if (mg_path_is_sane(mg_str(file)) == false) {
  3014. mg_http_reply(c, 400, "", "%s: invalid file", file);
  3015. res = -2;
  3016. } else if (offset < 0) {
  3017. mg_http_reply(c, 400, "", "offset required");
  3018. res = -3;
  3019. } else if ((size_t) offset + hm->body.len > max_size) {
  3020. mg_http_reply(c, 400, "", "%s: over max size of %lu", path,
  3021. (unsigned long) max_size);
  3022. res = -4;
  3023. } else {
  3024. struct mg_fd *fd;
  3025. size_t current_size = 0;
  3026. MG_DEBUG(("%s -> %lu bytes @ %ld", path, hm->body.len, offset));
  3027. if (offset == 0) fs->rm(path); // If offset if 0, truncate file
  3028. fs->st(path, &current_size, NULL);
  3029. if (offset > 0 && current_size != (size_t) offset) {
  3030. mg_http_reply(c, 400, "", "%s: offset mismatch", path);
  3031. res = -5;
  3032. } else if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
  3033. mg_http_reply(c, 400, "", "open(%s): %d", path, errno);
  3034. res = -6;
  3035. } else {
  3036. res = offset + (long) fs->wr(fd->fd, hm->body.buf, hm->body.len);
  3037. mg_fs_close(fd);
  3038. mg_http_reply(c, 200, "", "%ld", res);
  3039. }
  3040. }
  3041. return res;
  3042. }
  3043. int mg_http_status(const struct mg_http_message *hm) {
  3044. return atoi(hm->uri.buf);
  3045. }
  3046. static bool is_hex_digit(int c) {
  3047. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  3048. (c >= 'A' && c <= 'F');
  3049. }
  3050. static int skip_chunk(const char *buf, int len, int *pl, int *dl) {
  3051. int i = 0, n = 0;
  3052. if (len < 3) return 0;
  3053. while (i < len && is_hex_digit(buf[i])) i++;
  3054. if (i == 0) return -1; // Error, no length specified
  3055. if (i > (int) sizeof(int) * 2) return -1; // Chunk length is too big
  3056. if (len < i + 1 || buf[i] != '\r' || buf[i + 1] != '\n') return -1; // Error
  3057. if (mg_str_to_num(mg_str_n(buf, (size_t) i), 16, &n, sizeof(int)) == false)
  3058. return -1; // Decode chunk length, overflow
  3059. if (n < 0) return -1; // Error. TODO(): some checks now redundant
  3060. if (n > len - i - 4) return 0; // Chunk not yet fully buffered
  3061. if (buf[i + n + 2] != '\r' || buf[i + n + 3] != '\n') return -1; // Error
  3062. *pl = i + 2, *dl = n;
  3063. return i + 2 + n + 2;
  3064. }
  3065. static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
  3066. if (ev == MG_EV_READ || ev == MG_EV_CLOSE) {
  3067. struct mg_http_message hm;
  3068. size_t ofs = 0; // Parsing offset
  3069. while (c->is_resp == 0 && ofs < c->recv.len) {
  3070. const char *buf = (char *) c->recv.buf + ofs;
  3071. int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
  3072. struct mg_str *te; // Transfer - encoding header
  3073. bool is_chunked = false;
  3074. if (n < 0) {
  3075. // We don't use mg_error() here, to avoid closing pipelined requests
  3076. // prematurely, see #2592
  3077. MG_ERROR(("HTTP parse, %lu bytes", c->recv.len));
  3078. c->is_draining = 1;
  3079. mg_hexdump(buf, c->recv.len - ofs > 16 ? 16 : c->recv.len - ofs);
  3080. c->recv.len = 0;
  3081. return;
  3082. }
  3083. if (n == 0) break; // Request is not buffered yet
  3084. mg_call(c, MG_EV_HTTP_HDRS, &hm); // Got all HTTP headers
  3085. if (ev == MG_EV_CLOSE) { // If client did not set Content-Length
  3086. hm.message.len = c->recv.len - ofs; // and closes now, deliver MSG
  3087. hm.body.len = hm.message.len - (size_t) (hm.body.buf - hm.message.buf);
  3088. }
  3089. if ((te = mg_http_get_header(&hm, "Transfer-Encoding")) != NULL) {
  3090. if (mg_strcasecmp(*te, mg_str("chunked")) == 0) {
  3091. is_chunked = true;
  3092. } else {
  3093. mg_error(c, "Invalid Transfer-Encoding"); // See #2460
  3094. return;
  3095. }
  3096. } else if (mg_http_get_header(&hm, "Content-length") == NULL) {
  3097. // #2593: HTTP packets must contain either Transfer-Encoding or
  3098. // Content-length
  3099. bool is_response = mg_ncasecmp(hm.method.buf, "HTTP/", 5) == 0;
  3100. bool require_content_len = false;
  3101. if (!is_response && (mg_strcasecmp(hm.method, mg_str("POST")) == 0 ||
  3102. mg_strcasecmp(hm.method, mg_str("PUT")) == 0)) {
  3103. // POST and PUT should include an entity body. Therefore, they should
  3104. // contain a Content-length header. Other requests can also contain a
  3105. // body, but their content has no defined semantics (RFC 7231)
  3106. require_content_len = true;
  3107. } else if (is_response) {
  3108. // HTTP spec 7.2 Entity body: All other responses must include a body
  3109. // or Content-Length header field defined with a value of 0.
  3110. int status = mg_http_status(&hm);
  3111. require_content_len = status >= 200 && status != 204 && status != 304;
  3112. }
  3113. if (require_content_len) {
  3114. mg_http_reply(c, 411, "", "");
  3115. MG_ERROR(("%s", "Content length missing from request"));
  3116. }
  3117. }
  3118. if (is_chunked) {
  3119. // For chunked data, strip off prefixes and suffixes from chunks
  3120. // and relocate them right after the headers, then report a message
  3121. char *s = (char *) c->recv.buf + ofs + n;
  3122. int o = 0, pl, dl, cl, len = (int) (c->recv.len - ofs - (size_t) n);
  3123. // Find zero-length chunk (the end of the body)
  3124. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0 && dl) o += cl;
  3125. if (cl == 0) break; // No zero-len chunk, buffer more data
  3126. if (cl < 0) {
  3127. mg_error(c, "Invalid chunk");
  3128. break;
  3129. }
  3130. // Zero chunk found. Second pass: strip + relocate
  3131. o = 0, hm.body.len = 0, hm.message.len = (size_t) n;
  3132. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0) {
  3133. memmove(s + hm.body.len, s + o + pl, (size_t) dl);
  3134. o += cl, hm.body.len += (size_t) dl, hm.message.len += (size_t) dl;
  3135. if (dl == 0) break;
  3136. }
  3137. ofs += (size_t) (n + o);
  3138. } else { // Normal, non-chunked data
  3139. size_t len = c->recv.len - ofs - (size_t) n;
  3140. if (hm.body.len > len) break; // Buffer more data
  3141. ofs += (size_t) n + hm.body.len;
  3142. }
  3143. if (c->is_accepted) c->is_resp = 1; // Start generating response
  3144. mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp
  3145. }
  3146. if (ofs > 0) mg_iobuf_del(&c->recv, 0, ofs); // Delete processed data
  3147. }
  3148. (void) ev_data;
  3149. }
  3150. static void mg_hfn(struct mg_connection *c, int ev, void *ev_data) {
  3151. if (ev == MG_EV_HTTP_MSG) {
  3152. struct mg_http_message *hm = (struct mg_http_message *) ev_data;
  3153. if (mg_match(hm->uri, mg_str("/quit"), NULL)) {
  3154. mg_http_reply(c, 200, "", "ok\n");
  3155. c->is_draining = 1;
  3156. c->data[0] = 'X';
  3157. } else if (mg_match(hm->uri, mg_str("/debug"), NULL)) {
  3158. int level = (int) mg_json_get_long(hm->body, "$.level", MG_LL_DEBUG);
  3159. mg_log_set(level);
  3160. mg_http_reply(c, 200, "", "Debug level set to %d\n", level);
  3161. } else {
  3162. mg_http_reply(c, 200, "", "hi\n");
  3163. }
  3164. } else if (ev == MG_EV_CLOSE) {
  3165. if (c->data[0] == 'X') *(bool *) c->fn_data = true;
  3166. }
  3167. }
  3168. void mg_hello(const char *url) {
  3169. struct mg_mgr mgr;
  3170. bool done = false;
  3171. mg_mgr_init(&mgr);
  3172. if (mg_http_listen(&mgr, url, mg_hfn, &done) == NULL) done = true;
  3173. while (done == false) mg_mgr_poll(&mgr, 100);
  3174. mg_mgr_free(&mgr);
  3175. }
  3176. struct mg_connection *mg_http_connect(struct mg_mgr *mgr, const char *url,
  3177. mg_event_handler_t fn, void *fn_data) {
  3178. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  3179. if (c != NULL) c->pfn = http_cb;
  3180. return c;
  3181. }
  3182. struct mg_connection *mg_http_listen(struct mg_mgr *mgr, const char *url,
  3183. mg_event_handler_t fn, void *fn_data) {
  3184. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  3185. if (c != NULL) c->pfn = http_cb;
  3186. return c;
  3187. }
  3188. #ifdef MG_ENABLE_LINES
  3189. #line 1 "src/iobuf.c"
  3190. #endif
  3191. static size_t roundup(size_t size, size_t align) {
  3192. return align == 0 ? size : (size + align - 1) / align * align;
  3193. }
  3194. int mg_iobuf_resize(struct mg_iobuf *io, size_t new_size) {
  3195. int ok = 1;
  3196. new_size = roundup(new_size, io->align);
  3197. if (new_size == 0) {
  3198. mg_bzero(io->buf, io->size);
  3199. free(io->buf);
  3200. io->buf = NULL;
  3201. io->len = io->size = 0;
  3202. } else if (new_size != io->size) {
  3203. // NOTE(lsm): do not use realloc here. Use calloc/free only, to ease the
  3204. // porting to some obscure platforms like FreeRTOS
  3205. void *p = calloc(1, new_size);
  3206. if (p != NULL) {
  3207. size_t len = new_size < io->len ? new_size : io->len;
  3208. if (len > 0 && io->buf != NULL) memmove(p, io->buf, len);
  3209. mg_bzero(io->buf, io->size);
  3210. free(io->buf);
  3211. io->buf = (unsigned char *) p;
  3212. io->size = new_size;
  3213. } else {
  3214. ok = 0;
  3215. MG_ERROR(("%lld->%lld", (uint64_t) io->size, (uint64_t) new_size));
  3216. }
  3217. }
  3218. return ok;
  3219. }
  3220. int mg_iobuf_init(struct mg_iobuf *io, size_t size, size_t align) {
  3221. io->buf = NULL;
  3222. io->align = align;
  3223. io->size = io->len = 0;
  3224. return mg_iobuf_resize(io, size);
  3225. }
  3226. size_t mg_iobuf_add(struct mg_iobuf *io, size_t ofs, const void *buf,
  3227. size_t len) {
  3228. size_t new_size = roundup(io->len + len, io->align);
  3229. mg_iobuf_resize(io, new_size); // Attempt to resize
  3230. if (new_size != io->size) len = 0; // Resize failure, append nothing
  3231. if (ofs < io->len) memmove(io->buf + ofs + len, io->buf + ofs, io->len - ofs);
  3232. if (buf != NULL) memmove(io->buf + ofs, buf, len);
  3233. if (ofs > io->len) io->len += ofs - io->len;
  3234. io->len += len;
  3235. return len;
  3236. }
  3237. size_t mg_iobuf_del(struct mg_iobuf *io, size_t ofs, size_t len) {
  3238. if (ofs > io->len) ofs = io->len;
  3239. if (ofs + len > io->len) len = io->len - ofs;
  3240. if (io->buf) memmove(io->buf + ofs, io->buf + ofs + len, io->len - ofs - len);
  3241. if (io->buf) mg_bzero(io->buf + io->len - len, len);
  3242. io->len -= len;
  3243. return len;
  3244. }
  3245. void mg_iobuf_free(struct mg_iobuf *io) {
  3246. mg_iobuf_resize(io, 0);
  3247. }
  3248. #ifdef MG_ENABLE_LINES
  3249. #line 1 "src/json.c"
  3250. #endif
  3251. static const char *escapeseq(int esc) {
  3252. return esc ? "\b\f\n\r\t\\\"" : "bfnrt\\\"";
  3253. }
  3254. static char json_esc(int c, int esc) {
  3255. const char *p, *esc1 = escapeseq(esc), *esc2 = escapeseq(!esc);
  3256. for (p = esc1; *p != '\0'; p++) {
  3257. if (*p == c) return esc2[p - esc1];
  3258. }
  3259. return 0;
  3260. }
  3261. static int mg_pass_string(const char *s, int len) {
  3262. int i;
  3263. for (i = 0; i < len; i++) {
  3264. if (s[i] == '\\' && i + 1 < len && json_esc(s[i + 1], 1)) {
  3265. i++;
  3266. } else if (s[i] == '\0') {
  3267. return MG_JSON_INVALID;
  3268. } else if (s[i] == '"') {
  3269. return i;
  3270. }
  3271. }
  3272. return MG_JSON_INVALID;
  3273. }
  3274. static double mg_atod(const char *p, int len, int *numlen) {
  3275. double d = 0.0;
  3276. int i = 0, sign = 1;
  3277. // Sign
  3278. if (i < len && *p == '-') {
  3279. sign = -1, i++;
  3280. } else if (i < len && *p == '+') {
  3281. i++;
  3282. }
  3283. // Decimal
  3284. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  3285. d *= 10.0;
  3286. d += p[i] - '0';
  3287. }
  3288. d *= sign;
  3289. // Fractional
  3290. if (i < len && p[i] == '.') {
  3291. double frac = 0.0, base = 0.1;
  3292. i++;
  3293. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  3294. frac += base * (p[i] - '0');
  3295. base /= 10.0;
  3296. }
  3297. d += frac * sign;
  3298. }
  3299. // Exponential
  3300. if (i < len && (p[i] == 'e' || p[i] == 'E')) {
  3301. int j, exp = 0, minus = 0;
  3302. i++;
  3303. if (i < len && p[i] == '-') minus = 1, i++;
  3304. if (i < len && p[i] == '+') i++;
  3305. while (i < len && p[i] >= '0' && p[i] <= '9' && exp < 308)
  3306. exp = exp * 10 + (p[i++] - '0');
  3307. if (minus) exp = -exp;
  3308. for (j = 0; j < exp; j++) d *= 10.0;
  3309. for (j = 0; j < -exp; j++) d /= 10.0;
  3310. }
  3311. if (numlen != NULL) *numlen = i;
  3312. return d;
  3313. }
  3314. // Iterate over object or array elements
  3315. size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key,
  3316. struct mg_str *val) {
  3317. if (ofs >= obj.len) {
  3318. ofs = 0; // Out of boundaries, stop scanning
  3319. } else if (obj.len < 2 || (*obj.buf != '{' && *obj.buf != '[')) {
  3320. ofs = 0; // Not an array or object, stop
  3321. } else {
  3322. struct mg_str sub = mg_str_n(obj.buf + ofs, obj.len - ofs);
  3323. if (ofs == 0) ofs++, sub.buf++, sub.len--;
  3324. if (*obj.buf == '[') { // Iterate over an array
  3325. int n = 0, o = mg_json_get(sub, "$", &n);
  3326. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3327. ofs = 0; // Error parsing key, stop scanning
  3328. } else {
  3329. if (key) *key = mg_str_n(NULL, 0);
  3330. if (val) *val = mg_str_n(sub.buf + o, (size_t) n);
  3331. ofs = (size_t) (&sub.buf[o + n] - obj.buf);
  3332. }
  3333. } else { // Iterate over an object
  3334. int n = 0, o = mg_json_get(sub, "$", &n);
  3335. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3336. ofs = 0; // Error parsing key, stop scanning
  3337. } else {
  3338. if (key) *key = mg_str_n(sub.buf + o, (size_t) n);
  3339. sub.buf += o + n, sub.len -= (size_t) (o + n);
  3340. while (sub.len > 0 && *sub.buf != ':') sub.len--, sub.buf++;
  3341. if (sub.len > 0 && *sub.buf == ':') sub.len--, sub.buf++;
  3342. n = 0, o = mg_json_get(sub, "$", &n);
  3343. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  3344. ofs = 0; // Error parsing value, stop scanning
  3345. } else {
  3346. if (val) *val = mg_str_n(sub.buf + o, (size_t) n);
  3347. ofs = (size_t) (&sub.buf[o + n] - obj.buf);
  3348. }
  3349. }
  3350. }
  3351. // MG_INFO(("SUB ofs %u %.*s", ofs, sub.len, sub.buf));
  3352. while (ofs && ofs < obj.len &&
  3353. (obj.buf[ofs] == ' ' || obj.buf[ofs] == '\t' ||
  3354. obj.buf[ofs] == '\n' || obj.buf[ofs] == '\r')) {
  3355. ofs++;
  3356. }
  3357. if (ofs && ofs < obj.len && obj.buf[ofs] == ',') ofs++;
  3358. if (ofs > obj.len) ofs = 0;
  3359. }
  3360. return ofs;
  3361. }
  3362. int mg_json_get(struct mg_str json, const char *path, int *toklen) {
  3363. const char *s = json.buf;
  3364. int len = (int) json.len;
  3365. enum { S_VALUE, S_KEY, S_COLON, S_COMMA_OR_EOO } expecting = S_VALUE;
  3366. unsigned char nesting[MG_JSON_MAX_DEPTH];
  3367. int i = 0; // Current offset in `s`
  3368. int j = 0; // Offset in `s` we're looking for (return value)
  3369. int depth = 0; // Current depth (nesting level)
  3370. int ed = 0; // Expected depth
  3371. int pos = 1; // Current position in `path`
  3372. int ci = -1, ei = -1; // Current and expected index in array
  3373. if (toklen) *toklen = 0;
  3374. if (path[0] != '$') return MG_JSON_INVALID;
  3375. #define MG_CHECKRET(x) \
  3376. do { \
  3377. if (depth == ed && path[pos] == '\0' && ci == ei) { \
  3378. if (toklen) *toklen = i - j + 1; \
  3379. return j; \
  3380. } \
  3381. } while (0)
  3382. // In the ascii table, the distance between `[` and `]` is 2.
  3383. // Ditto for `{` and `}`. Hence +2 in the code below.
  3384. #define MG_EOO(x) \
  3385. do { \
  3386. if (depth == ed && ci != ei) return MG_JSON_NOT_FOUND; \
  3387. if (c != nesting[depth - 1] + 2) return MG_JSON_INVALID; \
  3388. depth--; \
  3389. MG_CHECKRET(x); \
  3390. } while (0)
  3391. for (i = 0; i < len; i++) {
  3392. unsigned char c = ((unsigned char *) s)[i];
  3393. if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
  3394. switch (expecting) {
  3395. case S_VALUE:
  3396. // p("V %s [%.*s] %d %d %d %d\n", path, pos, path, depth, ed, ci, ei);
  3397. if (depth == ed) j = i;
  3398. if (c == '{') {
  3399. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  3400. if (depth == ed && path[pos] == '.' && ci == ei) {
  3401. // If we start the object, reset array indices
  3402. ed++, pos++, ci = ei = -1;
  3403. }
  3404. nesting[depth++] = c;
  3405. expecting = S_KEY;
  3406. break;
  3407. } else if (c == '[') {
  3408. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  3409. if (depth == ed && path[pos] == '[' && ei == ci) {
  3410. ed++, pos++, ci = 0;
  3411. for (ei = 0; path[pos] != ']' && path[pos] != '\0'; pos++) {
  3412. ei *= 10;
  3413. ei += path[pos] - '0';
  3414. }
  3415. if (path[pos] != 0) pos++;
  3416. }
  3417. nesting[depth++] = c;
  3418. break;
  3419. } else if (c == ']' && depth > 0) { // Empty array
  3420. MG_EOO(']');
  3421. } else if (c == 't' && i + 3 < len && memcmp(&s[i], "true", 4) == 0) {
  3422. i += 3;
  3423. } else if (c == 'n' && i + 3 < len && memcmp(&s[i], "null", 4) == 0) {
  3424. i += 3;
  3425. } else if (c == 'f' && i + 4 < len && memcmp(&s[i], "false", 5) == 0) {
  3426. i += 4;
  3427. } else if (c == '-' || ((c >= '0' && c <= '9'))) {
  3428. int numlen = 0;
  3429. mg_atod(&s[i], len - i, &numlen);
  3430. i += numlen - 1;
  3431. } else if (c == '"') {
  3432. int n = mg_pass_string(&s[i + 1], len - i - 1);
  3433. if (n < 0) return n;
  3434. i += n + 1;
  3435. } else {
  3436. return MG_JSON_INVALID;
  3437. }
  3438. MG_CHECKRET('V');
  3439. if (depth == ed && ei >= 0) ci++;
  3440. expecting = S_COMMA_OR_EOO;
  3441. break;
  3442. case S_KEY:
  3443. if (c == '"') {
  3444. int n = mg_pass_string(&s[i + 1], len - i - 1);
  3445. if (n < 0) return n;
  3446. if (i + 1 + n >= len) return MG_JSON_NOT_FOUND;
  3447. if (depth < ed) return MG_JSON_NOT_FOUND;
  3448. if (depth == ed && path[pos - 1] != '.') return MG_JSON_NOT_FOUND;
  3449. // printf("K %s [%.*s] [%.*s] %d %d %d %d %d\n", path, pos, path, n,
  3450. // &s[i + 1], n, depth, ed, ci, ei);
  3451. // NOTE(cpq): in the check sequence below is important.
  3452. // strncmp() must go first: it fails fast if the remaining length
  3453. // of the path is smaller than `n`.
  3454. if (depth == ed && path[pos - 1] == '.' &&
  3455. strncmp(&s[i + 1], &path[pos], (size_t) n) == 0 &&
  3456. (path[pos + n] == '\0' || path[pos + n] == '.' ||
  3457. path[pos + n] == '[')) {
  3458. pos += n;
  3459. }
  3460. i += n + 1;
  3461. expecting = S_COLON;
  3462. } else if (c == '}') { // Empty object
  3463. MG_EOO('}');
  3464. expecting = S_COMMA_OR_EOO;
  3465. if (depth == ed && ei >= 0) ci++;
  3466. } else {
  3467. return MG_JSON_INVALID;
  3468. }
  3469. break;
  3470. case S_COLON:
  3471. if (c == ':') {
  3472. expecting = S_VALUE;
  3473. } else {
  3474. return MG_JSON_INVALID;
  3475. }
  3476. break;
  3477. case S_COMMA_OR_EOO:
  3478. if (depth <= 0) {
  3479. return MG_JSON_INVALID;
  3480. } else if (c == ',') {
  3481. expecting = (nesting[depth - 1] == '{') ? S_KEY : S_VALUE;
  3482. } else if (c == ']' || c == '}') {
  3483. if (depth == ed && c == '}' && path[pos - 1] == '.')
  3484. return MG_JSON_NOT_FOUND;
  3485. if (depth == ed && c == ']' && path[pos - 1] == ',')
  3486. return MG_JSON_NOT_FOUND;
  3487. MG_EOO('O');
  3488. if (depth == ed && ei >= 0) ci++;
  3489. } else {
  3490. return MG_JSON_INVALID;
  3491. }
  3492. break;
  3493. }
  3494. }
  3495. return MG_JSON_NOT_FOUND;
  3496. }
  3497. struct mg_str mg_json_get_tok(struct mg_str json, const char *path) {
  3498. int len = 0, ofs = mg_json_get(json, path, &len);
  3499. return mg_str_n(ofs < 0 ? NULL : json.buf + ofs,
  3500. (size_t) (len < 0 ? 0 : len));
  3501. }
  3502. bool mg_json_get_num(struct mg_str json, const char *path, double *v) {
  3503. int n, toklen, found = 0;
  3504. if ((n = mg_json_get(json, path, &toklen)) >= 0 &&
  3505. (json.buf[n] == '-' || (json.buf[n] >= '0' && json.buf[n] <= '9'))) {
  3506. if (v != NULL) *v = mg_atod(json.buf + n, toklen, NULL);
  3507. found = 1;
  3508. }
  3509. return found;
  3510. }
  3511. bool mg_json_get_bool(struct mg_str json, const char *path, bool *v) {
  3512. int found = 0, off = mg_json_get(json, path, NULL);
  3513. if (off >= 0 && (json.buf[off] == 't' || json.buf[off] == 'f')) {
  3514. if (v != NULL) *v = json.buf[off] == 't';
  3515. found = 1;
  3516. }
  3517. return found;
  3518. }
  3519. bool mg_json_unescape(struct mg_str s, char *to, size_t n) {
  3520. size_t i, j;
  3521. for (i = 0, j = 0; i < s.len && j < n; i++, j++) {
  3522. if (s.buf[i] == '\\' && i + 5 < s.len && s.buf[i + 1] == 'u') {
  3523. // \uXXXX escape. We process simple one-byte chars \u00xx within ASCII
  3524. // range. More complex chars would require dragging in a UTF8 library,
  3525. // which is too much for us
  3526. if (mg_str_to_num(mg_str_n(s.buf + i + 2, 4), 16, &to[j],
  3527. sizeof(uint8_t)) == false)
  3528. return false;
  3529. i += 5;
  3530. } else if (s.buf[i] == '\\' && i + 1 < s.len) {
  3531. char c = json_esc(s.buf[i + 1], 0);
  3532. if (c == 0) return false;
  3533. to[j] = c;
  3534. i++;
  3535. } else {
  3536. to[j] = s.buf[i];
  3537. }
  3538. }
  3539. if (j >= n) return false;
  3540. if (n > 0) to[j] = '\0';
  3541. return true;
  3542. }
  3543. char *mg_json_get_str(struct mg_str json, const char *path) {
  3544. char *result = NULL;
  3545. int len = 0, off = mg_json_get(json, path, &len);
  3546. if (off >= 0 && len > 1 && json.buf[off] == '"') {
  3547. if ((result = (char *) calloc(1, (size_t) len)) != NULL &&
  3548. !mg_json_unescape(mg_str_n(json.buf + off + 1, (size_t) (len - 2)),
  3549. result, (size_t) len)) {
  3550. free(result);
  3551. result = NULL;
  3552. }
  3553. }
  3554. return result;
  3555. }
  3556. char *mg_json_get_b64(struct mg_str json, const char *path, int *slen) {
  3557. char *result = NULL;
  3558. int len = 0, off = mg_json_get(json, path, &len);
  3559. if (off >= 0 && json.buf[off] == '"' && len > 1 &&
  3560. (result = (char *) calloc(1, (size_t) len)) != NULL) {
  3561. size_t k = mg_base64_decode(json.buf + off + 1, (size_t) (len - 2), result,
  3562. (size_t) len);
  3563. if (slen != NULL) *slen = (int) k;
  3564. }
  3565. return result;
  3566. }
  3567. char *mg_json_get_hex(struct mg_str json, const char *path, int *slen) {
  3568. char *result = NULL;
  3569. int len = 0, off = mg_json_get(json, path, &len);
  3570. if (off >= 0 && json.buf[off] == '"' && len > 1 &&
  3571. (result = (char *) calloc(1, (size_t) len / 2)) != NULL) {
  3572. int i;
  3573. for (i = 0; i < len - 2; i += 2) {
  3574. mg_str_to_num(mg_str_n(json.buf + off + 1 + i, 2), 16, &result[i >> 1],
  3575. sizeof(uint8_t));
  3576. }
  3577. result[len / 2 - 1] = '\0';
  3578. if (slen != NULL) *slen = len / 2 - 1;
  3579. }
  3580. return result;
  3581. }
  3582. long mg_json_get_long(struct mg_str json, const char *path, long dflt) {
  3583. double dv;
  3584. long result = dflt;
  3585. if (mg_json_get_num(json, path, &dv)) result = (long) dv;
  3586. return result;
  3587. }
  3588. #ifdef MG_ENABLE_LINES
  3589. #line 1 "src/log.c"
  3590. #endif
  3591. int mg_log_level = MG_LL_INFO;
  3592. static mg_pfn_t s_log_func = mg_pfn_stdout;
  3593. static void *s_log_func_param = NULL;
  3594. void mg_log_set_fn(mg_pfn_t fn, void *param) {
  3595. s_log_func = fn;
  3596. s_log_func_param = param;
  3597. }
  3598. static void logc(unsigned char c) {
  3599. s_log_func((char) c, s_log_func_param);
  3600. }
  3601. static void logs(const char *buf, size_t len) {
  3602. size_t i;
  3603. for (i = 0; i < len; i++) logc(((unsigned char *) buf)[i]);
  3604. }
  3605. #if MG_ENABLE_CUSTOM_LOG
  3606. // Let user define their own mg_log_prefix() and mg_log()
  3607. #else
  3608. void mg_log_prefix(int level, const char *file, int line, const char *fname) {
  3609. const char *p = strrchr(file, '/');
  3610. char buf[41];
  3611. size_t n;
  3612. if (p == NULL) p = strrchr(file, '\\');
  3613. n = mg_snprintf(buf, sizeof(buf), "%-6llx %d %s:%d:%s", mg_millis(), level,
  3614. p == NULL ? file : p + 1, line, fname);
  3615. if (n > sizeof(buf) - 2) n = sizeof(buf) - 2;
  3616. while (n < sizeof(buf)) buf[n++] = ' ';
  3617. logs(buf, n - 1);
  3618. }
  3619. void mg_log(const char *fmt, ...) {
  3620. va_list ap;
  3621. va_start(ap, fmt);
  3622. mg_vxprintf(s_log_func, s_log_func_param, fmt, &ap);
  3623. va_end(ap);
  3624. logs("\r\n", 2);
  3625. }
  3626. #endif
  3627. static unsigned char nibble(unsigned c) {
  3628. return (unsigned char) (c < 10 ? c + '0' : c + 'W');
  3629. }
  3630. #define ISPRINT(x) ((x) >= ' ' && (x) <= '~')
  3631. void mg_hexdump(const void *buf, size_t len) {
  3632. const unsigned char *p = (const unsigned char *) buf;
  3633. unsigned char ascii[16], alen = 0;
  3634. size_t i;
  3635. for (i = 0; i < len; i++) {
  3636. if ((i % 16) == 0) {
  3637. // Print buffered ascii chars
  3638. if (i > 0) logs(" ", 2), logs((char *) ascii, 16), logc('\n'), alen = 0;
  3639. // Print hex address, then \t
  3640. logc(nibble((i >> 12) & 15)), logc(nibble((i >> 8) & 15)),
  3641. logc(nibble((i >> 4) & 15)), logc('0'), logs(" ", 3);
  3642. }
  3643. logc(nibble(p[i] >> 4)), logc(nibble(p[i] & 15)); // Two nibbles, e.g. c5
  3644. logc(' '); // Space after hex number
  3645. ascii[alen++] = ISPRINT(p[i]) ? p[i] : '.'; // Add to the ascii buf
  3646. }
  3647. while (alen < 16) logs(" ", 3), ascii[alen++] = ' ';
  3648. logs(" ", 2), logs((char *) ascii, 16), logc('\n');
  3649. }
  3650. #ifdef MG_ENABLE_LINES
  3651. #line 1 "src/md5.c"
  3652. #endif
  3653. // This code implements the MD5 message-digest algorithm.
  3654. // The algorithm is due to Ron Rivest. This code was
  3655. // written by Colin Plumb in 1993, no copyright is claimed.
  3656. // This code is in the public domain; do with it what you wish.
  3657. //
  3658. // Equivalent code is available from RSA Data Security, Inc.
  3659. // This code has been tested against that, and is equivalent,
  3660. // except that you don't need to include two pages of legalese
  3661. // with every copy.
  3662. //
  3663. // To compute the message digest of a chunk of bytes, declare an
  3664. // MD5Context structure, pass it to MD5Init, call MD5Update as
  3665. // needed on buffers full of bytes, and then call MD5Final, which
  3666. // will fill a supplied 16-byte array with the digest.
  3667. #if defined(MG_ENABLE_MD5) && MG_ENABLE_MD5
  3668. static void mg_byte_reverse(unsigned char *buf, unsigned longs) {
  3669. if (MG_BIG_ENDIAN) {
  3670. do {
  3671. uint32_t t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  3672. ((unsigned) buf[1] << 8 | buf[0]);
  3673. *(uint32_t *) buf = t;
  3674. buf += 4;
  3675. } while (--longs);
  3676. } else {
  3677. (void) buf, (void) longs; // Little endian. Do nothing
  3678. }
  3679. }
  3680. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  3681. #define F2(x, y, z) F1(z, x, y)
  3682. #define F3(x, y, z) (x ^ y ^ z)
  3683. #define F4(x, y, z) (y ^ (x | ~z))
  3684. #define MD5STEP(f, w, x, y, z, data, s) \
  3685. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  3686. /*
  3687. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  3688. * initialization constants.
  3689. */
  3690. void mg_md5_init(mg_md5_ctx *ctx) {
  3691. ctx->buf[0] = 0x67452301;
  3692. ctx->buf[1] = 0xefcdab89;
  3693. ctx->buf[2] = 0x98badcfe;
  3694. ctx->buf[3] = 0x10325476;
  3695. ctx->bits[0] = 0;
  3696. ctx->bits[1] = 0;
  3697. }
  3698. static void mg_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
  3699. uint32_t a, b, c, d;
  3700. a = buf[0];
  3701. b = buf[1];
  3702. c = buf[2];
  3703. d = buf[3];
  3704. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  3705. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  3706. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  3707. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  3708. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  3709. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  3710. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  3711. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  3712. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  3713. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  3714. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  3715. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  3716. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  3717. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  3718. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  3719. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  3720. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  3721. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  3722. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  3723. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  3724. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  3725. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  3726. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  3727. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  3728. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  3729. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  3730. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  3731. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  3732. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  3733. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  3734. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  3735. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  3736. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  3737. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  3738. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  3739. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  3740. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  3741. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  3742. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  3743. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  3744. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  3745. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  3746. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  3747. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  3748. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  3749. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  3750. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  3751. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  3752. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  3753. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  3754. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  3755. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  3756. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  3757. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  3758. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  3759. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  3760. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  3761. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  3762. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  3763. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  3764. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  3765. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  3766. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  3767. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  3768. buf[0] += a;
  3769. buf[1] += b;
  3770. buf[2] += c;
  3771. buf[3] += d;
  3772. }
  3773. void mg_md5_update(mg_md5_ctx *ctx, const unsigned char *buf, size_t len) {
  3774. uint32_t t;
  3775. t = ctx->bits[0];
  3776. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  3777. ctx->bits[1] += (uint32_t) len >> 29;
  3778. t = (t >> 3) & 0x3f;
  3779. if (t) {
  3780. unsigned char *p = (unsigned char *) ctx->in + t;
  3781. t = 64 - t;
  3782. if (len < t) {
  3783. memcpy(p, buf, len);
  3784. return;
  3785. }
  3786. memcpy(p, buf, t);
  3787. mg_byte_reverse(ctx->in, 16);
  3788. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3789. buf += t;
  3790. len -= t;
  3791. }
  3792. while (len >= 64) {
  3793. memcpy(ctx->in, buf, 64);
  3794. mg_byte_reverse(ctx->in, 16);
  3795. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3796. buf += 64;
  3797. len -= 64;
  3798. }
  3799. memcpy(ctx->in, buf, len);
  3800. }
  3801. void mg_md5_final(mg_md5_ctx *ctx, unsigned char digest[16]) {
  3802. unsigned count;
  3803. unsigned char *p;
  3804. uint32_t *a;
  3805. count = (ctx->bits[0] >> 3) & 0x3F;
  3806. p = ctx->in + count;
  3807. *p++ = 0x80;
  3808. count = 64 - 1 - count;
  3809. if (count < 8) {
  3810. memset(p, 0, count);
  3811. mg_byte_reverse(ctx->in, 16);
  3812. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3813. memset(ctx->in, 0, 56);
  3814. } else {
  3815. memset(p, 0, count - 8);
  3816. }
  3817. mg_byte_reverse(ctx->in, 14);
  3818. a = (uint32_t *) ctx->in;
  3819. a[14] = ctx->bits[0];
  3820. a[15] = ctx->bits[1];
  3821. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3822. mg_byte_reverse((unsigned char *) ctx->buf, 4);
  3823. memcpy(digest, ctx->buf, 16);
  3824. memset((char *) ctx, 0, sizeof(*ctx));
  3825. }
  3826. #endif
  3827. #ifdef MG_ENABLE_LINES
  3828. #line 1 "src/mqtt.c"
  3829. #endif
  3830. #define MQTT_CLEAN_SESSION 0x02
  3831. #define MQTT_HAS_WILL 0x04
  3832. #define MQTT_WILL_RETAIN 0x20
  3833. #define MQTT_HAS_PASSWORD 0x40
  3834. #define MQTT_HAS_USER_NAME 0x80
  3835. struct mg_mqtt_pmap {
  3836. uint8_t id;
  3837. uint8_t type;
  3838. };
  3839. static const struct mg_mqtt_pmap s_prop_map[] = {
  3840. {MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, MQTT_PROP_TYPE_BYTE},
  3841. {MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3842. {MQTT_PROP_CONTENT_TYPE, MQTT_PROP_TYPE_STRING},
  3843. {MQTT_PROP_RESPONSE_TOPIC, MQTT_PROP_TYPE_STRING},
  3844. {MQTT_PROP_CORRELATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3845. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER, MQTT_PROP_TYPE_VARIABLE_INT},
  3846. {MQTT_PROP_SESSION_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3847. {MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, MQTT_PROP_TYPE_STRING},
  3848. {MQTT_PROP_SERVER_KEEP_ALIVE, MQTT_PROP_TYPE_SHORT},
  3849. {MQTT_PROP_AUTHENTICATION_METHOD, MQTT_PROP_TYPE_STRING},
  3850. {MQTT_PROP_AUTHENTICATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3851. {MQTT_PROP_REQUEST_PROBLEM_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3852. {MQTT_PROP_WILL_DELAY_INTERVAL, MQTT_PROP_TYPE_INT},
  3853. {MQTT_PROP_REQUEST_RESPONSE_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3854. {MQTT_PROP_RESPONSE_INFORMATION, MQTT_PROP_TYPE_STRING},
  3855. {MQTT_PROP_SERVER_REFERENCE, MQTT_PROP_TYPE_STRING},
  3856. {MQTT_PROP_REASON_STRING, MQTT_PROP_TYPE_STRING},
  3857. {MQTT_PROP_RECEIVE_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3858. {MQTT_PROP_TOPIC_ALIAS_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3859. {MQTT_PROP_TOPIC_ALIAS, MQTT_PROP_TYPE_SHORT},
  3860. {MQTT_PROP_MAXIMUM_QOS, MQTT_PROP_TYPE_BYTE},
  3861. {MQTT_PROP_RETAIN_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3862. {MQTT_PROP_USER_PROPERTY, MQTT_PROP_TYPE_STRING_PAIR},
  3863. {MQTT_PROP_MAXIMUM_PACKET_SIZE, MQTT_PROP_TYPE_INT},
  3864. {MQTT_PROP_WILDCARD_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3865. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3866. {MQTT_PROP_SHARED_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE}};
  3867. void mg_mqtt_send_header(struct mg_connection *c, uint8_t cmd, uint8_t flags,
  3868. uint32_t len) {
  3869. uint8_t buf[1 + sizeof(len)], *vlen = &buf[1];
  3870. buf[0] = (uint8_t) ((cmd << 4) | flags);
  3871. do {
  3872. *vlen = len % 0x80;
  3873. len /= 0x80;
  3874. if (len > 0) *vlen |= 0x80;
  3875. vlen++;
  3876. } while (len > 0 && vlen < &buf[sizeof(buf)]);
  3877. mg_send(c, buf, (size_t) (vlen - buf));
  3878. }
  3879. static void mg_send_u16(struct mg_connection *c, uint16_t value) {
  3880. mg_send(c, &value, sizeof(value));
  3881. }
  3882. static void mg_send_u32(struct mg_connection *c, uint32_t value) {
  3883. mg_send(c, &value, sizeof(value));
  3884. }
  3885. static uint8_t varint_size(size_t length) {
  3886. uint8_t bytes_needed = 0;
  3887. do {
  3888. bytes_needed++;
  3889. length /= 0x80;
  3890. } while (length > 0);
  3891. return bytes_needed;
  3892. }
  3893. static size_t encode_varint(uint8_t *buf, size_t value) {
  3894. size_t len = 0;
  3895. do {
  3896. uint8_t b = (uint8_t) (value % 128);
  3897. value /= 128;
  3898. if (value > 0) b |= 0x80;
  3899. buf[len++] = b;
  3900. } while (value > 0);
  3901. return len;
  3902. }
  3903. static size_t decode_varint(const uint8_t *buf, size_t len, size_t *value) {
  3904. size_t multiplier = 1, offset;
  3905. *value = 0;
  3906. for (offset = 0; offset < 4 && offset < len; offset++) {
  3907. uint8_t encoded_byte = buf[offset];
  3908. *value += (encoded_byte & 0x7f) * multiplier;
  3909. multiplier *= 128;
  3910. if ((encoded_byte & 0x80) == 0) return offset + 1;
  3911. }
  3912. return 0;
  3913. }
  3914. static int mqtt_prop_type_by_id(uint8_t prop_id) {
  3915. size_t i, num_properties = sizeof(s_prop_map) / sizeof(s_prop_map[0]);
  3916. for (i = 0; i < num_properties; ++i) {
  3917. if (s_prop_map[i].id == prop_id) return s_prop_map[i].type;
  3918. }
  3919. return -1; // Property ID not found
  3920. }
  3921. // Returns the size of the properties section, without the
  3922. // size of the content's length
  3923. static size_t get_properties_length(struct mg_mqtt_prop *props, size_t count) {
  3924. size_t i, size = 0;
  3925. for (i = 0; i < count; i++) {
  3926. size++; // identifier
  3927. switch (mqtt_prop_type_by_id(props[i].id)) {
  3928. case MQTT_PROP_TYPE_STRING_PAIR:
  3929. size += (uint32_t) (props[i].val.len + props[i].key.len +
  3930. 2 * sizeof(uint16_t));
  3931. break;
  3932. case MQTT_PROP_TYPE_STRING:
  3933. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3934. break;
  3935. case MQTT_PROP_TYPE_BINARY_DATA:
  3936. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3937. break;
  3938. case MQTT_PROP_TYPE_VARIABLE_INT:
  3939. size += varint_size((uint32_t) props[i].iv);
  3940. break;
  3941. case MQTT_PROP_TYPE_INT:
  3942. size += (uint32_t) sizeof(uint32_t);
  3943. break;
  3944. case MQTT_PROP_TYPE_SHORT:
  3945. size += (uint32_t) sizeof(uint16_t);
  3946. break;
  3947. case MQTT_PROP_TYPE_BYTE:
  3948. size += (uint32_t) sizeof(uint8_t);
  3949. break;
  3950. default:
  3951. return size; // cannot parse further down
  3952. }
  3953. }
  3954. return size;
  3955. }
  3956. // returns the entire size of the properties section, including the
  3957. // size of the variable length of the content
  3958. static size_t get_props_size(struct mg_mqtt_prop *props, size_t count) {
  3959. size_t size = get_properties_length(props, count);
  3960. size += varint_size(size);
  3961. return size;
  3962. }
  3963. static void mg_send_mqtt_properties(struct mg_connection *c,
  3964. struct mg_mqtt_prop *props, size_t nprops) {
  3965. size_t total_size = get_properties_length(props, nprops);
  3966. uint8_t buf_v[4] = {0, 0, 0, 0};
  3967. uint8_t buf[4] = {0, 0, 0, 0};
  3968. size_t i, len = encode_varint(buf, total_size);
  3969. mg_send(c, buf, (size_t) len);
  3970. for (i = 0; i < nprops; i++) {
  3971. mg_send(c, &props[i].id, sizeof(props[i].id));
  3972. switch (mqtt_prop_type_by_id(props[i].id)) {
  3973. case MQTT_PROP_TYPE_STRING_PAIR:
  3974. mg_send_u16(c, mg_htons((uint16_t) props[i].key.len));
  3975. mg_send(c, props[i].key.buf, props[i].key.len);
  3976. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3977. mg_send(c, props[i].val.buf, props[i].val.len);
  3978. break;
  3979. case MQTT_PROP_TYPE_BYTE:
  3980. mg_send(c, &props[i].iv, sizeof(uint8_t));
  3981. break;
  3982. case MQTT_PROP_TYPE_SHORT:
  3983. mg_send_u16(c, mg_htons((uint16_t) props[i].iv));
  3984. break;
  3985. case MQTT_PROP_TYPE_INT:
  3986. mg_send_u32(c, mg_htonl((uint32_t) props[i].iv));
  3987. break;
  3988. case MQTT_PROP_TYPE_STRING:
  3989. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3990. mg_send(c, props[i].val.buf, props[i].val.len);
  3991. break;
  3992. case MQTT_PROP_TYPE_BINARY_DATA:
  3993. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3994. mg_send(c, props[i].val.buf, props[i].val.len);
  3995. break;
  3996. case MQTT_PROP_TYPE_VARIABLE_INT:
  3997. len = encode_varint(buf_v, props[i].iv);
  3998. mg_send(c, buf_v, (size_t) len);
  3999. break;
  4000. }
  4001. }
  4002. }
  4003. size_t mg_mqtt_next_prop(struct mg_mqtt_message *msg, struct mg_mqtt_prop *prop,
  4004. size_t ofs) {
  4005. uint8_t *i = (uint8_t *) msg->dgram.buf + msg->props_start + ofs;
  4006. uint8_t *end = (uint8_t *) msg->dgram.buf + msg->dgram.len;
  4007. size_t new_pos = ofs, len;
  4008. prop->id = i[0];
  4009. if (ofs >= msg->dgram.len || ofs >= msg->props_start + msg->props_size)
  4010. return 0;
  4011. i++, new_pos++;
  4012. switch (mqtt_prop_type_by_id(prop->id)) {
  4013. case MQTT_PROP_TYPE_STRING_PAIR:
  4014. prop->key.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4015. prop->key.buf = (char *) i + 2;
  4016. i += 2 + prop->key.len;
  4017. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4018. prop->val.buf = (char *) i + 2;
  4019. new_pos += 2 * sizeof(uint16_t) + prop->val.len + prop->key.len;
  4020. break;
  4021. case MQTT_PROP_TYPE_BYTE:
  4022. prop->iv = (uint8_t) i[0];
  4023. new_pos++;
  4024. break;
  4025. case MQTT_PROP_TYPE_SHORT:
  4026. prop->iv = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4027. new_pos += sizeof(uint16_t);
  4028. break;
  4029. case MQTT_PROP_TYPE_INT:
  4030. prop->iv = ((uint32_t) i[0] << 24) | ((uint32_t) i[1] << 16) |
  4031. ((uint32_t) i[2] << 8) | i[3];
  4032. new_pos += sizeof(uint32_t);
  4033. break;
  4034. case MQTT_PROP_TYPE_STRING:
  4035. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4036. prop->val.buf = (char *) i + 2;
  4037. new_pos += 2 + prop->val.len;
  4038. break;
  4039. case MQTT_PROP_TYPE_BINARY_DATA:
  4040. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  4041. prop->val.buf = (char *) i + 2;
  4042. new_pos += 2 + prop->val.len;
  4043. break;
  4044. case MQTT_PROP_TYPE_VARIABLE_INT:
  4045. len = decode_varint(i, (size_t) (end - i), (size_t *) &prop->iv);
  4046. new_pos = (!len) ? 0 : new_pos + len;
  4047. break;
  4048. default:
  4049. new_pos = 0;
  4050. }
  4051. return new_pos;
  4052. }
  4053. void mg_mqtt_login(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  4054. char client_id[21];
  4055. struct mg_str cid = opts->client_id;
  4056. size_t total_len = 7 + 1 + 2 + 2;
  4057. uint8_t hdr[8] = {0, 4, 'M', 'Q', 'T', 'T', opts->version, 0};
  4058. if (cid.len == 0) {
  4059. mg_random_str(client_id, sizeof(client_id) - 1);
  4060. client_id[sizeof(client_id) - 1] = '\0';
  4061. cid = mg_str(client_id);
  4062. }
  4063. if (hdr[6] == 0) hdr[6] = 4; // If version is not set, use 4 (3.1.1)
  4064. c->is_mqtt5 = hdr[6] == 5; // Set version 5 flag
  4065. hdr[7] = (uint8_t) ((opts->qos & 3) << 3); // Connection flags
  4066. if (opts->user.len > 0) {
  4067. total_len += 2 + (uint32_t) opts->user.len;
  4068. hdr[7] |= MQTT_HAS_USER_NAME;
  4069. }
  4070. if (opts->pass.len > 0) {
  4071. total_len += 2 + (uint32_t) opts->pass.len;
  4072. hdr[7] |= MQTT_HAS_PASSWORD;
  4073. }
  4074. if (opts->topic.len > 0) { // allow zero-length msgs, message.len is size_t
  4075. total_len += 4 + (uint32_t) opts->topic.len + (uint32_t) opts->message.len;
  4076. hdr[7] |= MQTT_HAS_WILL;
  4077. }
  4078. if (opts->clean || cid.len == 0) hdr[7] |= MQTT_CLEAN_SESSION;
  4079. if (opts->retain) hdr[7] |= MQTT_WILL_RETAIN;
  4080. total_len += (uint32_t) cid.len;
  4081. if (c->is_mqtt5) {
  4082. total_len += get_props_size(opts->props, opts->num_props);
  4083. if (hdr[7] & MQTT_HAS_WILL)
  4084. total_len += get_props_size(opts->will_props, opts->num_will_props);
  4085. }
  4086. mg_mqtt_send_header(c, MQTT_CMD_CONNECT, 0, (uint32_t) total_len);
  4087. mg_send(c, hdr, sizeof(hdr));
  4088. // keepalive == 0 means "do not disconnect us!"
  4089. mg_send_u16(c, mg_htons((uint16_t) opts->keepalive));
  4090. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4091. mg_send_u16(c, mg_htons((uint16_t) cid.len));
  4092. mg_send(c, cid.buf, cid.len);
  4093. if (hdr[7] & MQTT_HAS_WILL) {
  4094. if (c->is_mqtt5)
  4095. mg_send_mqtt_properties(c, opts->will_props, opts->num_will_props);
  4096. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  4097. mg_send(c, opts->topic.buf, opts->topic.len);
  4098. mg_send_u16(c, mg_htons((uint16_t) opts->message.len));
  4099. mg_send(c, opts->message.buf, opts->message.len);
  4100. }
  4101. if (opts->user.len > 0) {
  4102. mg_send_u16(c, mg_htons((uint16_t) opts->user.len));
  4103. mg_send(c, opts->user.buf, opts->user.len);
  4104. }
  4105. if (opts->pass.len > 0) {
  4106. mg_send_u16(c, mg_htons((uint16_t) opts->pass.len));
  4107. mg_send(c, opts->pass.buf, opts->pass.len);
  4108. }
  4109. }
  4110. uint16_t mg_mqtt_pub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  4111. uint16_t id = opts->retransmit_id;
  4112. uint8_t flags = (uint8_t) (((opts->qos & 3) << 1) | (opts->retain ? 1 : 0));
  4113. size_t len = 2 + opts->topic.len + opts->message.len;
  4114. MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) opts->topic.len,
  4115. (char *) opts->topic.buf, (int) opts->message.len,
  4116. (char *) opts->message.buf));
  4117. if (opts->qos > 0) len += 2;
  4118. if (c->is_mqtt5) len += get_props_size(opts->props, opts->num_props);
  4119. if (opts->qos > 0 && id != 0) flags |= 1 << 3;
  4120. mg_mqtt_send_header(c, MQTT_CMD_PUBLISH, flags, (uint32_t) len);
  4121. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  4122. mg_send(c, opts->topic.buf, opts->topic.len);
  4123. if (opts->qos > 0) { // need to send 'id' field
  4124. if (id == 0) { // generate new one if not resending
  4125. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  4126. id = c->mgr->mqtt_id;
  4127. }
  4128. mg_send_u16(c, mg_htons(id));
  4129. }
  4130. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4131. if (opts->message.len > 0) mg_send(c, opts->message.buf, opts->message.len);
  4132. return id;
  4133. }
  4134. void mg_mqtt_sub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  4135. uint8_t qos_ = opts->qos & 3;
  4136. size_t plen = c->is_mqtt5 ? get_props_size(opts->props, opts->num_props) : 0;
  4137. size_t len = 2 + opts->topic.len + 2 + 1 + plen;
  4138. mg_mqtt_send_header(c, MQTT_CMD_SUBSCRIBE, 2, (uint32_t) len);
  4139. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  4140. mg_send_u16(c, mg_htons(c->mgr->mqtt_id));
  4141. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4142. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  4143. mg_send(c, opts->topic.buf, opts->topic.len);
  4144. mg_send(c, &qos_, sizeof(qos_));
  4145. }
  4146. int mg_mqtt_parse(const uint8_t *buf, size_t len, uint8_t version,
  4147. struct mg_mqtt_message *m) {
  4148. uint8_t lc = 0, *p, *end;
  4149. uint32_t n = 0, len_len = 0;
  4150. memset(m, 0, sizeof(*m));
  4151. m->dgram.buf = (char *) buf;
  4152. if (len < 2) return MQTT_INCOMPLETE;
  4153. m->cmd = (uint8_t) (buf[0] >> 4);
  4154. m->qos = (buf[0] >> 1) & 3;
  4155. n = len_len = 0;
  4156. p = (uint8_t *) buf + 1;
  4157. while ((size_t) (p - buf) < len) {
  4158. lc = *((uint8_t *) p++);
  4159. n += (uint32_t) ((lc & 0x7f) << 7 * len_len);
  4160. len_len++;
  4161. if (!(lc & 0x80)) break;
  4162. if (len_len >= 4) return MQTT_MALFORMED;
  4163. }
  4164. end = p + n;
  4165. if ((lc & 0x80) || (end > buf + len)) return MQTT_INCOMPLETE;
  4166. m->dgram.len = (size_t) (end - buf);
  4167. switch (m->cmd) {
  4168. case MQTT_CMD_CONNACK:
  4169. if (end - p < 2) return MQTT_MALFORMED;
  4170. m->ack = p[1];
  4171. break;
  4172. case MQTT_CMD_PUBACK:
  4173. case MQTT_CMD_PUBREC:
  4174. case MQTT_CMD_PUBREL:
  4175. case MQTT_CMD_PUBCOMP:
  4176. case MQTT_CMD_SUBSCRIBE:
  4177. case MQTT_CMD_SUBACK:
  4178. case MQTT_CMD_UNSUBSCRIBE:
  4179. case MQTT_CMD_UNSUBACK:
  4180. if (p + 2 > end) return MQTT_MALFORMED;
  4181. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4182. p += 2;
  4183. break;
  4184. case MQTT_CMD_PUBLISH: {
  4185. if (p + 2 > end) return MQTT_MALFORMED;
  4186. m->topic.len = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4187. m->topic.buf = (char *) p + 2;
  4188. p += 2 + m->topic.len;
  4189. if (p > end) return MQTT_MALFORMED;
  4190. if (m->qos > 0) {
  4191. if (p + 2 > end) return MQTT_MALFORMED;
  4192. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  4193. p += 2;
  4194. }
  4195. if (p > end) return MQTT_MALFORMED;
  4196. if (version == 5 && p + 2 < end) {
  4197. len_len =
  4198. (uint32_t) decode_varint(p, (size_t) (end - p), &m->props_size);
  4199. if (!len_len) return MQTT_MALFORMED;
  4200. m->props_start = (size_t) (p + len_len - buf);
  4201. p += len_len + m->props_size;
  4202. }
  4203. if (p > end) return MQTT_MALFORMED;
  4204. m->data.buf = (char *) p;
  4205. m->data.len = (size_t) (end - p);
  4206. break;
  4207. }
  4208. default:
  4209. break;
  4210. }
  4211. return MQTT_OK;
  4212. }
  4213. static void mqtt_cb(struct mg_connection *c, int ev, void *ev_data) {
  4214. if (ev == MG_EV_READ) {
  4215. for (;;) {
  4216. uint8_t version = c->is_mqtt5 ? 5 : 4;
  4217. struct mg_mqtt_message mm;
  4218. int rc = mg_mqtt_parse(c->recv.buf, c->recv.len, version, &mm);
  4219. if (rc == MQTT_MALFORMED) {
  4220. MG_ERROR(("%lu MQTT malformed message", c->id));
  4221. c->is_closing = 1;
  4222. break;
  4223. } else if (rc == MQTT_OK) {
  4224. MG_VERBOSE(("%lu MQTT CMD %d len %d [%.*s]", c->id, mm.cmd,
  4225. (int) mm.dgram.len, (int) mm.data.len, mm.data.buf));
  4226. switch (mm.cmd) {
  4227. case MQTT_CMD_CONNACK:
  4228. mg_call(c, MG_EV_MQTT_OPEN, &mm.ack);
  4229. if (mm.ack == 0) {
  4230. MG_DEBUG(("%lu Connected", c->id));
  4231. } else {
  4232. MG_ERROR(("%lu MQTT auth failed, code %d", c->id, mm.ack));
  4233. c->is_closing = 1;
  4234. }
  4235. break;
  4236. case MQTT_CMD_PUBLISH: {
  4237. /*MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) mm.topic.len,
  4238. mm.topic.buf, (int) mm.data.len, mm.data.buf));*/
  4239. if (mm.qos > 0) {
  4240. uint16_t id = mg_ntohs(mm.id);
  4241. uint32_t remaining_len = sizeof(id);
  4242. if (c->is_mqtt5) remaining_len += 2; // 3.4.2
  4243. mg_mqtt_send_header(
  4244. c,
  4245. (uint8_t) (mm.qos == 2 ? MQTT_CMD_PUBREC : MQTT_CMD_PUBACK),
  4246. 0, remaining_len);
  4247. mg_send(c, &id, sizeof(id));
  4248. if (c->is_mqtt5) {
  4249. uint16_t zero = 0;
  4250. mg_send(c, &zero, sizeof(zero));
  4251. }
  4252. }
  4253. mg_call(c, MG_EV_MQTT_MSG, &mm); // let the app handle qos stuff
  4254. break;
  4255. }
  4256. case MQTT_CMD_PUBREC: { // MQTT5: 3.5.2-1 TODO(): variable header rc
  4257. uint16_t id = mg_ntohs(mm.id);
  4258. uint32_t remaining_len = sizeof(id); // MQTT5 3.6.2-1
  4259. mg_mqtt_send_header(c, MQTT_CMD_PUBREL, 2, remaining_len);
  4260. mg_send(c, &id, sizeof(id)); // MQTT5 3.6.1-1, flags = 2
  4261. break;
  4262. }
  4263. case MQTT_CMD_PUBREL: { // MQTT5: 3.6.2-1 TODO(): variable header rc
  4264. uint16_t id = mg_ntohs(mm.id);
  4265. uint32_t remaining_len = sizeof(id); // MQTT5 3.7.2-1
  4266. mg_mqtt_send_header(c, MQTT_CMD_PUBCOMP, 0, remaining_len);
  4267. mg_send(c, &id, sizeof(id));
  4268. break;
  4269. }
  4270. }
  4271. mg_call(c, MG_EV_MQTT_CMD, &mm);
  4272. mg_iobuf_del(&c->recv, 0, mm.dgram.len);
  4273. } else {
  4274. break;
  4275. }
  4276. }
  4277. }
  4278. (void) ev_data;
  4279. }
  4280. void mg_mqtt_ping(struct mg_connection *nc) {
  4281. mg_mqtt_send_header(nc, MQTT_CMD_PINGREQ, 0, 0);
  4282. }
  4283. void mg_mqtt_pong(struct mg_connection *nc) {
  4284. mg_mqtt_send_header(nc, MQTT_CMD_PINGRESP, 0, 0);
  4285. }
  4286. void mg_mqtt_disconnect(struct mg_connection *c,
  4287. const struct mg_mqtt_opts *opts) {
  4288. size_t len = 0;
  4289. if (c->is_mqtt5) len = 1 + get_props_size(opts->props, opts->num_props);
  4290. mg_mqtt_send_header(c, MQTT_CMD_DISCONNECT, 0, (uint32_t) len);
  4291. if (c->is_mqtt5) {
  4292. uint8_t zero = 0;
  4293. mg_send(c, &zero, sizeof(zero)); // reason code
  4294. mg_send_mqtt_properties(c, opts->props, opts->num_props);
  4295. }
  4296. }
  4297. struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url,
  4298. const struct mg_mqtt_opts *opts,
  4299. mg_event_handler_t fn, void *fn_data) {
  4300. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  4301. if (c != NULL) {
  4302. struct mg_mqtt_opts empty;
  4303. memset(&empty, 0, sizeof(empty));
  4304. mg_mqtt_login(c, opts == NULL ? &empty : opts);
  4305. c->pfn = mqtt_cb;
  4306. }
  4307. return c;
  4308. }
  4309. struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url,
  4310. mg_event_handler_t fn, void *fn_data) {
  4311. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  4312. if (c != NULL) c->pfn = mqtt_cb, c->pfn_data = mgr;
  4313. return c;
  4314. }
  4315. #ifdef MG_ENABLE_LINES
  4316. #line 1 "src/net.c"
  4317. #endif
  4318. size_t mg_vprintf(struct mg_connection *c, const char *fmt, va_list *ap) {
  4319. size_t old = c->send.len;
  4320. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  4321. return c->send.len - old;
  4322. }
  4323. size_t mg_printf(struct mg_connection *c, const char *fmt, ...) {
  4324. size_t len = 0;
  4325. va_list ap;
  4326. va_start(ap, fmt);
  4327. len = mg_vprintf(c, fmt, &ap);
  4328. va_end(ap);
  4329. return len;
  4330. }
  4331. static bool mg_atonl(struct mg_str str, struct mg_addr *addr) {
  4332. uint32_t localhost = mg_htonl(0x7f000001);
  4333. if (mg_strcasecmp(str, mg_str("localhost")) != 0) return false;
  4334. memcpy(addr->ip, &localhost, sizeof(uint32_t));
  4335. addr->is_ip6 = false;
  4336. return true;
  4337. }
  4338. static bool mg_atone(struct mg_str str, struct mg_addr *addr) {
  4339. if (str.len > 0) return false;
  4340. memset(addr->ip, 0, sizeof(addr->ip));
  4341. addr->is_ip6 = false;
  4342. return true;
  4343. }
  4344. static bool mg_aton4(struct mg_str str, struct mg_addr *addr) {
  4345. uint8_t data[4] = {0, 0, 0, 0};
  4346. size_t i, num_dots = 0;
  4347. for (i = 0; i < str.len; i++) {
  4348. if (str.buf[i] >= '0' && str.buf[i] <= '9') {
  4349. int octet = data[num_dots] * 10 + (str.buf[i] - '0');
  4350. if (octet > 255) return false;
  4351. data[num_dots] = (uint8_t) octet;
  4352. } else if (str.buf[i] == '.') {
  4353. if (num_dots >= 3 || i == 0 || str.buf[i - 1] == '.') return false;
  4354. num_dots++;
  4355. } else {
  4356. return false;
  4357. }
  4358. }
  4359. if (num_dots != 3 || str.buf[i - 1] == '.') return false;
  4360. memcpy(&addr->ip, data, sizeof(data));
  4361. addr->is_ip6 = false;
  4362. return true;
  4363. }
  4364. static bool mg_v4mapped(struct mg_str str, struct mg_addr *addr) {
  4365. int i;
  4366. uint32_t ipv4;
  4367. if (str.len < 14) return false;
  4368. if (str.buf[0] != ':' || str.buf[1] != ':' || str.buf[6] != ':') return false;
  4369. for (i = 2; i < 6; i++) {
  4370. if (str.buf[i] != 'f' && str.buf[i] != 'F') return false;
  4371. }
  4372. // struct mg_str s = mg_str_n(&str.buf[7], str.len - 7);
  4373. if (!mg_aton4(mg_str_n(&str.buf[7], str.len - 7), addr)) return false;
  4374. memcpy(&ipv4, addr->ip, sizeof(ipv4));
  4375. memset(addr->ip, 0, sizeof(addr->ip));
  4376. addr->ip[10] = addr->ip[11] = 255;
  4377. memcpy(&addr->ip[12], &ipv4, 4);
  4378. addr->is_ip6 = true;
  4379. return true;
  4380. }
  4381. static bool mg_aton6(struct mg_str str, struct mg_addr *addr) {
  4382. size_t i, j = 0, n = 0, dc = 42;
  4383. addr->scope_id = 0;
  4384. if (str.len > 2 && str.buf[0] == '[') str.buf++, str.len -= 2;
  4385. if (mg_v4mapped(str, addr)) return true;
  4386. for (i = 0; i < str.len; i++) {
  4387. if ((str.buf[i] >= '0' && str.buf[i] <= '9') ||
  4388. (str.buf[i] >= 'a' && str.buf[i] <= 'f') ||
  4389. (str.buf[i] >= 'A' && str.buf[i] <= 'F')) {
  4390. unsigned long val; // TODO(): This loops on chars, refactor
  4391. if (i > j + 3) return false;
  4392. // MG_DEBUG(("%lu %lu [%.*s]", i, j, (int) (i - j + 1), &str.buf[j]));
  4393. mg_str_to_num(mg_str_n(&str.buf[j], i - j + 1), 16, &val, sizeof(val));
  4394. addr->ip[n] = (uint8_t) ((val >> 8) & 255);
  4395. addr->ip[n + 1] = (uint8_t) (val & 255);
  4396. } else if (str.buf[i] == ':') {
  4397. j = i + 1;
  4398. if (i > 0 && str.buf[i - 1] == ':') {
  4399. dc = n; // Double colon
  4400. if (i > 1 && str.buf[i - 2] == ':') return false;
  4401. } else if (i > 0) {
  4402. n += 2;
  4403. }
  4404. if (n > 14) return false;
  4405. addr->ip[n] = addr->ip[n + 1] = 0; // For trailing ::
  4406. } else if (str.buf[i] == '%') { // Scope ID, last in string
  4407. return mg_str_to_num(mg_str_n(&str.buf[i + 1], str.len - i - 1), 10,
  4408. &addr->scope_id, sizeof(uint8_t));
  4409. } else {
  4410. return false;
  4411. }
  4412. }
  4413. if (n < 14 && dc == 42) return false;
  4414. if (n < 14) {
  4415. memmove(&addr->ip[dc + (14 - n)], &addr->ip[dc], n - dc + 2);
  4416. memset(&addr->ip[dc], 0, 14 - n);
  4417. }
  4418. addr->is_ip6 = true;
  4419. return true;
  4420. }
  4421. bool mg_aton(struct mg_str str, struct mg_addr *addr) {
  4422. // MG_INFO(("[%.*s]", (int) str.len, str.buf));
  4423. return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) ||
  4424. mg_aton6(str, addr);
  4425. }
  4426. struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) {
  4427. struct mg_connection *c =
  4428. (struct mg_connection *) calloc(1, sizeof(*c) + mgr->extraconnsize);
  4429. if (c != NULL) {
  4430. c->mgr = mgr;
  4431. c->send.align = c->recv.align = c->rtls.align = MG_IO_SIZE;
  4432. c->id = ++mgr->nextid;
  4433. MG_PROF_INIT(c);
  4434. }
  4435. return c;
  4436. }
  4437. void mg_close_conn(struct mg_connection *c) {
  4438. mg_resolve_cancel(c); // Close any pending DNS query
  4439. LIST_DELETE(struct mg_connection, &c->mgr->conns, c);
  4440. if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL;
  4441. if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL;
  4442. // Order of operations is important. `MG_EV_CLOSE` event must be fired
  4443. // before we deallocate received data, see #1331
  4444. mg_call(c, MG_EV_CLOSE, NULL);
  4445. MG_DEBUG(("%lu %ld closed", c->id, c->fd));
  4446. MG_PROF_DUMP(c);
  4447. MG_PROF_FREE(c);
  4448. mg_tls_free(c);
  4449. mg_iobuf_free(&c->recv);
  4450. mg_iobuf_free(&c->send);
  4451. mg_iobuf_free(&c->rtls);
  4452. mg_bzero((unsigned char *) c, sizeof(*c));
  4453. free(c);
  4454. }
  4455. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url,
  4456. mg_event_handler_t fn, void *fn_data) {
  4457. struct mg_connection *c = NULL;
  4458. if (url == NULL || url[0] == '\0') {
  4459. MG_ERROR(("null url"));
  4460. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  4461. MG_ERROR(("OOM"));
  4462. } else {
  4463. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4464. c->is_udp = (strncmp(url, "udp:", 4) == 0);
  4465. c->fd = (void *) (size_t) MG_INVALID_SOCKET;
  4466. c->fn = fn;
  4467. c->is_client = true;
  4468. c->fn_data = fn_data;
  4469. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  4470. mg_call(c, MG_EV_OPEN, (void *) url);
  4471. mg_resolve(c, url);
  4472. }
  4473. return c;
  4474. }
  4475. struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url,
  4476. mg_event_handler_t fn, void *fn_data) {
  4477. struct mg_connection *c = NULL;
  4478. if ((c = mg_alloc_conn(mgr)) == NULL) {
  4479. MG_ERROR(("OOM %s", url));
  4480. } else if (!mg_open_listener(c, url)) {
  4481. MG_ERROR(("Failed: %s, errno %d", url, errno));
  4482. MG_PROF_FREE(c);
  4483. free(c);
  4484. c = NULL;
  4485. } else {
  4486. c->is_listening = 1;
  4487. c->is_udp = strncmp(url, "udp:", 4) == 0;
  4488. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4489. c->fn = fn;
  4490. c->fn_data = fn_data;
  4491. mg_call(c, MG_EV_OPEN, NULL);
  4492. if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must
  4493. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  4494. }
  4495. return c;
  4496. }
  4497. struct mg_connection *mg_wrapfd(struct mg_mgr *mgr, int fd,
  4498. mg_event_handler_t fn, void *fn_data) {
  4499. struct mg_connection *c = mg_alloc_conn(mgr);
  4500. if (c != NULL) {
  4501. c->fd = (void *) (size_t) fd;
  4502. c->fn = fn;
  4503. c->fn_data = fn_data;
  4504. MG_EPOLL_ADD(c);
  4505. mg_call(c, MG_EV_OPEN, NULL);
  4506. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  4507. }
  4508. return c;
  4509. }
  4510. struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds,
  4511. unsigned flags, void (*fn)(void *), void *arg) {
  4512. struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t));
  4513. if (t != NULL) {
  4514. mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg);
  4515. t->id = mgr->timerid++;
  4516. }
  4517. return t;
  4518. }
  4519. long mg_io_recv(struct mg_connection *c, void *buf, size_t len) {
  4520. if (c->rtls.len == 0) return MG_IO_WAIT;
  4521. if (len > c->rtls.len) len = c->rtls.len;
  4522. memcpy(buf, c->rtls.buf, len);
  4523. mg_iobuf_del(&c->rtls, 0, len);
  4524. return (long) len;
  4525. }
  4526. void mg_mgr_free(struct mg_mgr *mgr) {
  4527. struct mg_connection *c;
  4528. struct mg_timer *tmp, *t = mgr->timers;
  4529. while (t != NULL) tmp = t->next, free(t), t = tmp;
  4530. mgr->timers = NULL; // Important. Next call to poll won't touch timers
  4531. for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1;
  4532. mg_mgr_poll(mgr, 0);
  4533. #if MG_ENABLE_FREERTOS_TCP
  4534. FreeRTOS_DeleteSocketSet(mgr->ss);
  4535. #endif
  4536. MG_DEBUG(("All connections closed"));
  4537. #if MG_ENABLE_EPOLL
  4538. if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1;
  4539. #endif
  4540. mg_tls_ctx_free(mgr);
  4541. }
  4542. void mg_mgr_init(struct mg_mgr *mgr) {
  4543. memset(mgr, 0, sizeof(*mgr));
  4544. #if MG_ENABLE_EPOLL
  4545. if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
  4546. MG_ERROR(("epoll_create1 errno %d", errno));
  4547. #else
  4548. mgr->epoll_fd = -1;
  4549. #endif
  4550. #if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  4551. // clang-format off
  4552. { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
  4553. // clang-format on
  4554. #elif MG_ENABLE_FREERTOS_TCP
  4555. mgr->ss = FreeRTOS_CreateSocketSet();
  4556. #elif defined(__unix) || defined(__unix__) || defined(__APPLE__)
  4557. // Ignore SIGPIPE signal, so if client cancels the request, it
  4558. // won't kill the whole process.
  4559. signal(SIGPIPE, SIG_IGN);
  4560. #elif MG_ENABLE_TCPIP_DRIVER_INIT && defined(MG_TCPIP_DRIVER_INIT)
  4561. MG_TCPIP_DRIVER_INIT(mgr);
  4562. #endif
  4563. mgr->pipe = MG_INVALID_SOCKET;
  4564. mgr->dnstimeout = 3000;
  4565. mgr->dns4.url = "udp://8.8.8.8:53";
  4566. mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
  4567. mg_tls_ctx_init(mgr);
  4568. }
  4569. #ifdef MG_ENABLE_LINES
  4570. #line 1 "src/net_builtin.c"
  4571. #endif
  4572. #if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP
  4573. #define MG_EPHEMERAL_PORT_BASE 32768
  4574. #define PDIFF(a, b) ((size_t) (((char *) (b)) - ((char *) (a))))
  4575. #ifndef MIP_TCP_KEEPALIVE_MS
  4576. #define MIP_TCP_KEEPALIVE_MS 45000 // TCP keep-alive period, ms
  4577. #endif
  4578. #define MIP_TCP_ACK_MS 150 // Timeout for ACKing
  4579. #define MIP_TCP_ARP_MS 100 // Timeout for ARP response
  4580. #define MIP_TCP_SYN_MS 15000 // Timeout for connection establishment
  4581. #define MIP_TCP_FIN_MS 1000 // Timeout for closing connection
  4582. #define MIP_TCP_WIN 6000 // TCP window size
  4583. struct connstate {
  4584. uint32_t seq, ack; // TCP seq/ack counters
  4585. uint64_t timer; // TCP keep-alive / ACK timer
  4586. uint32_t acked; // Last ACK-ed number
  4587. size_t unacked; // Not acked bytes
  4588. uint8_t mac[6]; // Peer MAC address
  4589. uint8_t ttype; // Timer type. 0: ack, 1: keep-alive
  4590. #define MIP_TTYPE_KEEPALIVE 0 // Connection is idle for long, send keepalive
  4591. #define MIP_TTYPE_ACK 1 // Peer sent us data, we have to ack it soon
  4592. #define MIP_TTYPE_ARP 2 // ARP resolve sent, waiting for response
  4593. #define MIP_TTYPE_SYN 3 // SYN sent, waiting for response
  4594. #define MIP_TTYPE_FIN 4 // FIN sent, waiting until terminating the connection
  4595. uint8_t tmiss; // Number of keep-alive misses
  4596. struct mg_iobuf raw; // For TLS only. Incoming raw data
  4597. };
  4598. #pragma pack(push, 1)
  4599. struct lcp {
  4600. uint8_t addr, ctrl, proto[2], code, id, len[2];
  4601. };
  4602. struct eth {
  4603. uint8_t dst[6]; // Destination MAC address
  4604. uint8_t src[6]; // Source MAC address
  4605. uint16_t type; // Ethernet type
  4606. };
  4607. struct ip {
  4608. uint8_t ver; // Version
  4609. uint8_t tos; // Unused
  4610. uint16_t len; // Length
  4611. uint16_t id; // Unused
  4612. uint16_t frag; // Fragmentation
  4613. #define IP_FRAG_OFFSET_MSK 0xFF1F
  4614. #define IP_MORE_FRAGS_MSK 0x20
  4615. uint8_t ttl; // Time to live
  4616. uint8_t proto; // Upper level protocol
  4617. uint16_t csum; // Checksum
  4618. uint32_t src; // Source IP
  4619. uint32_t dst; // Destination IP
  4620. };
  4621. struct ip6 {
  4622. uint8_t ver; // Version
  4623. uint8_t opts[3]; // Options
  4624. uint16_t len; // Length
  4625. uint8_t proto; // Upper level protocol
  4626. uint8_t ttl; // Time to live
  4627. uint8_t src[16]; // Source IP
  4628. uint8_t dst[16]; // Destination IP
  4629. };
  4630. struct icmp {
  4631. uint8_t type;
  4632. uint8_t code;
  4633. uint16_t csum;
  4634. };
  4635. struct arp {
  4636. uint16_t fmt; // Format of hardware address
  4637. uint16_t pro; // Format of protocol address
  4638. uint8_t hlen; // Length of hardware address
  4639. uint8_t plen; // Length of protocol address
  4640. uint16_t op; // Operation
  4641. uint8_t sha[6]; // Sender hardware address
  4642. uint32_t spa; // Sender protocol address
  4643. uint8_t tha[6]; // Target hardware address
  4644. uint32_t tpa; // Target protocol address
  4645. };
  4646. struct tcp {
  4647. uint16_t sport; // Source port
  4648. uint16_t dport; // Destination port
  4649. uint32_t seq; // Sequence number
  4650. uint32_t ack; // Acknowledgement number
  4651. uint8_t off; // Data offset
  4652. uint8_t flags; // TCP flags
  4653. #define TH_FIN 0x01
  4654. #define TH_SYN 0x02
  4655. #define TH_RST 0x04
  4656. #define TH_PUSH 0x08
  4657. #define TH_ACK 0x10
  4658. #define TH_URG 0x20
  4659. #define TH_ECE 0x40
  4660. #define TH_CWR 0x80
  4661. uint16_t win; // Window
  4662. uint16_t csum; // Checksum
  4663. uint16_t urp; // Urgent pointer
  4664. };
  4665. struct udp {
  4666. uint16_t sport; // Source port
  4667. uint16_t dport; // Destination port
  4668. uint16_t len; // UDP length
  4669. uint16_t csum; // UDP checksum
  4670. };
  4671. struct dhcp {
  4672. uint8_t op, htype, hlen, hops;
  4673. uint32_t xid;
  4674. uint16_t secs, flags;
  4675. uint32_t ciaddr, yiaddr, siaddr, giaddr;
  4676. uint8_t hwaddr[208];
  4677. uint32_t magic;
  4678. uint8_t options[32];
  4679. };
  4680. #pragma pack(pop)
  4681. struct pkt {
  4682. struct mg_str raw; // Raw packet data
  4683. struct mg_str pay; // Payload data
  4684. struct eth *eth;
  4685. struct llc *llc;
  4686. struct arp *arp;
  4687. struct ip *ip;
  4688. struct ip6 *ip6;
  4689. struct icmp *icmp;
  4690. struct tcp *tcp;
  4691. struct udp *udp;
  4692. struct dhcp *dhcp;
  4693. };
  4694. static void send_syn(struct mg_connection *c);
  4695. static void mkpay(struct pkt *pkt, void *p) {
  4696. pkt->pay =
  4697. mg_str_n((char *) p, (size_t) (&pkt->raw.buf[pkt->raw.len] - (char *) p));
  4698. }
  4699. static uint32_t csumup(uint32_t sum, const void *buf, size_t len) {
  4700. size_t i;
  4701. const uint8_t *p = (const uint8_t *) buf;
  4702. for (i = 0; i < len; i++) sum += i & 1 ? p[i] : (uint32_t) (p[i] << 8);
  4703. return sum;
  4704. }
  4705. static uint16_t csumfin(uint32_t sum) {
  4706. while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
  4707. return mg_htons(~sum & 0xffff);
  4708. }
  4709. static uint16_t ipcsum(const void *buf, size_t len) {
  4710. uint32_t sum = csumup(0, buf, len);
  4711. return csumfin(sum);
  4712. }
  4713. static void settmout(struct mg_connection *c, uint8_t type) {
  4714. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4715. struct connstate *s = (struct connstate *) (c + 1);
  4716. unsigned n = type == MIP_TTYPE_ACK ? MIP_TCP_ACK_MS
  4717. : type == MIP_TTYPE_ARP ? MIP_TCP_ARP_MS
  4718. : type == MIP_TTYPE_SYN ? MIP_TCP_SYN_MS
  4719. : type == MIP_TTYPE_FIN ? MIP_TCP_FIN_MS
  4720. : MIP_TCP_KEEPALIVE_MS;
  4721. s->timer = ifp->now + n;
  4722. s->ttype = type;
  4723. MG_VERBOSE(("%lu %d -> %llx", c->id, type, s->timer));
  4724. }
  4725. static size_t ether_output(struct mg_tcpip_if *ifp, size_t len) {
  4726. size_t n = ifp->driver->tx(ifp->tx.buf, len, ifp);
  4727. if (n == len) ifp->nsent++;
  4728. return n;
  4729. }
  4730. static void arp_ask(struct mg_tcpip_if *ifp, uint32_t ip) {
  4731. struct eth *eth = (struct eth *) ifp->tx.buf;
  4732. struct arp *arp = (struct arp *) (eth + 1);
  4733. memset(eth->dst, 255, sizeof(eth->dst));
  4734. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4735. eth->type = mg_htons(0x806);
  4736. memset(arp, 0, sizeof(*arp));
  4737. arp->fmt = mg_htons(1), arp->pro = mg_htons(0x800), arp->hlen = 6,
  4738. arp->plen = 4;
  4739. arp->op = mg_htons(1), arp->tpa = ip, arp->spa = ifp->ip;
  4740. memcpy(arp->sha, ifp->mac, sizeof(arp->sha));
  4741. ether_output(ifp, PDIFF(eth, arp + 1));
  4742. }
  4743. static void onstatechange(struct mg_tcpip_if *ifp) {
  4744. if (ifp->state == MG_TCPIP_STATE_READY) {
  4745. MG_INFO(("READY, IP: %M", mg_print_ip4, &ifp->ip));
  4746. MG_INFO((" GW: %M", mg_print_ip4, &ifp->gw));
  4747. MG_INFO((" MAC: %M", mg_print_mac, &ifp->mac));
  4748. arp_ask(ifp, ifp->gw);
  4749. } else if (ifp->state == MG_TCPIP_STATE_UP) {
  4750. MG_ERROR(("Link up"));
  4751. srand((unsigned int) mg_millis());
  4752. } else if (ifp->state == MG_TCPIP_STATE_DOWN) {
  4753. MG_ERROR(("Link down"));
  4754. }
  4755. }
  4756. static struct ip *tx_ip(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4757. uint8_t proto, uint32_t ip_src, uint32_t ip_dst,
  4758. size_t plen) {
  4759. struct eth *eth = (struct eth *) ifp->tx.buf;
  4760. struct ip *ip = (struct ip *) (eth + 1);
  4761. memcpy(eth->dst, mac_dst, sizeof(eth->dst));
  4762. memcpy(eth->src, ifp->mac, sizeof(eth->src)); // Use our MAC
  4763. eth->type = mg_htons(0x800);
  4764. memset(ip, 0, sizeof(*ip));
  4765. ip->ver = 0x45; // Version 4, header length 5 words
  4766. ip->frag = 0x40; // Don't fragment
  4767. ip->len = mg_htons((uint16_t) (sizeof(*ip) + plen));
  4768. ip->ttl = 64;
  4769. ip->proto = proto;
  4770. ip->src = ip_src;
  4771. ip->dst = ip_dst;
  4772. ip->csum = ipcsum(ip, sizeof(*ip));
  4773. return ip;
  4774. }
  4775. static void tx_udp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4776. uint16_t sport, uint32_t ip_dst, uint16_t dport,
  4777. const void *buf, size_t len) {
  4778. struct ip *ip =
  4779. tx_ip(ifp, mac_dst, 17, ip_src, ip_dst, len + sizeof(struct udp));
  4780. struct udp *udp = (struct udp *) (ip + 1);
  4781. // MG_DEBUG(("UDP XX LEN %d %d", (int) len, (int) ifp->tx.len));
  4782. udp->sport = sport;
  4783. udp->dport = dport;
  4784. udp->len = mg_htons((uint16_t) (sizeof(*udp) + len));
  4785. udp->csum = 0;
  4786. uint32_t cs = csumup(0, udp, sizeof(*udp));
  4787. cs = csumup(cs, buf, len);
  4788. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4789. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4790. cs += (uint32_t) (ip->proto + sizeof(*udp) + len);
  4791. udp->csum = csumfin(cs);
  4792. memmove(udp + 1, buf, len);
  4793. // MG_DEBUG(("UDP LEN %d %d", (int) len, (int) ifp->frame_len));
  4794. ether_output(ifp, sizeof(struct eth) + sizeof(*ip) + sizeof(*udp) + len);
  4795. }
  4796. static void tx_dhcp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4797. uint32_t ip_dst, uint8_t *opts, size_t optslen,
  4798. bool ciaddr) {
  4799. // https://datatracker.ietf.org/doc/html/rfc2132#section-9.6
  4800. struct dhcp dhcp = {1, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4801. dhcp.magic = mg_htonl(0x63825363);
  4802. memcpy(&dhcp.hwaddr, ifp->mac, sizeof(ifp->mac));
  4803. memcpy(&dhcp.xid, ifp->mac + 2, sizeof(dhcp.xid));
  4804. memcpy(&dhcp.options, opts, optslen);
  4805. if (ciaddr) dhcp.ciaddr = ip_src;
  4806. tx_udp(ifp, mac_dst, ip_src, mg_htons(68), ip_dst, mg_htons(67), &dhcp,
  4807. sizeof(dhcp));
  4808. }
  4809. static const uint8_t broadcast[] = {255, 255, 255, 255, 255, 255};
  4810. // RFC-2131 #4.3.6, #4.4.1
  4811. static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
  4812. uint32_t ip_srv) {
  4813. uint8_t opts[] = {
  4814. 53, 1, 3, // Type: DHCP request
  4815. 55, 2, 1, 3, // GW and mask
  4816. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4817. 54, 4, 0, 0, 0, 0, // DHCP server ID
  4818. 50, 4, 0, 0, 0, 0, // Requested IP
  4819. 255 // End of options
  4820. };
  4821. memcpy(opts + 14, &ip_srv, sizeof(ip_srv));
  4822. memcpy(opts + 20, &ip_req, sizeof(ip_req));
  4823. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4824. MG_DEBUG(("DHCP req sent"));
  4825. }
  4826. // RFC-2131 #4.3.6, #4.4.5 (renewing: unicast, rebinding: bcast)
  4827. static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4828. uint32_t ip_src, uint32_t ip_dst) {
  4829. uint8_t opts[] = {
  4830. 53, 1, 3, // Type: DHCP request
  4831. 255 // End of options
  4832. };
  4833. tx_dhcp(ifp, mac_dst, ip_src, ip_dst, opts, sizeof(opts), true);
  4834. MG_DEBUG(("DHCP req sent"));
  4835. }
  4836. static void tx_dhcp_discover(struct mg_tcpip_if *ifp) {
  4837. uint8_t opts[] = {
  4838. 53, 1, 1, // Type: DHCP discover
  4839. 55, 2, 1, 3, // Parameters: ip, mask
  4840. 255 // End of options
  4841. };
  4842. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4843. MG_DEBUG(("DHCP discover sent. Our MAC: %M", mg_print_mac, ifp->mac));
  4844. }
  4845. static struct mg_connection *getpeer(struct mg_mgr *mgr, struct pkt *pkt,
  4846. bool lsn) {
  4847. struct mg_connection *c = NULL;
  4848. for (c = mgr->conns; c != NULL; c = c->next) {
  4849. if (c->is_arplooking && pkt->arp &&
  4850. memcmp(&pkt->arp->spa, c->rem.ip, sizeof(pkt->arp->spa)) == 0)
  4851. break;
  4852. if (c->is_udp && pkt->udp && c->loc.port == pkt->udp->dport) break;
  4853. if (!c->is_udp && pkt->tcp && c->loc.port == pkt->tcp->dport &&
  4854. lsn == c->is_listening && (lsn || c->rem.port == pkt->tcp->sport))
  4855. break;
  4856. }
  4857. return c;
  4858. }
  4859. static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4860. if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) {
  4861. // ARP request. Make a response, then send
  4862. // MG_DEBUG(("ARP op %d %M: %M", mg_ntohs(pkt->arp->op), mg_print_ip4,
  4863. // &pkt->arp->spa, mg_print_ip4, &pkt->arp->tpa));
  4864. struct eth *eth = (struct eth *) ifp->tx.buf;
  4865. struct arp *arp = (struct arp *) (eth + 1);
  4866. memcpy(eth->dst, pkt->eth->src, sizeof(eth->dst));
  4867. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4868. eth->type = mg_htons(0x806);
  4869. *arp = *pkt->arp;
  4870. arp->op = mg_htons(2);
  4871. memcpy(arp->tha, pkt->arp->sha, sizeof(pkt->arp->tha));
  4872. memcpy(arp->sha, ifp->mac, sizeof(pkt->arp->sha));
  4873. arp->tpa = pkt->arp->spa;
  4874. arp->spa = ifp->ip;
  4875. MG_DEBUG(("ARP: tell %M we're %M", mg_print_ip4, &arp->tpa, mg_print_mac,
  4876. &ifp->mac));
  4877. ether_output(ifp, PDIFF(eth, arp + 1));
  4878. } else if (pkt->arp->op == mg_htons(2)) {
  4879. if (memcmp(pkt->arp->tha, ifp->mac, sizeof(pkt->arp->tha)) != 0) return;
  4880. if (pkt->arp->spa == ifp->gw) {
  4881. // Got response for the GW ARP request. Set ifp->gwmac
  4882. memcpy(ifp->gwmac, pkt->arp->sha, sizeof(ifp->gwmac));
  4883. } else {
  4884. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4885. if (c != NULL && c->is_arplooking) {
  4886. struct connstate *s = (struct connstate *) (c + 1);
  4887. memcpy(s->mac, pkt->arp->sha, sizeof(s->mac));
  4888. MG_DEBUG(("%lu ARP resolved %M -> %M", c->id, mg_print_ip4, c->rem.ip,
  4889. mg_print_mac, s->mac));
  4890. c->is_arplooking = 0;
  4891. send_syn(c);
  4892. settmout(c, MIP_TTYPE_SYN);
  4893. }
  4894. }
  4895. }
  4896. }
  4897. static void rx_icmp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4898. // MG_DEBUG(("ICMP %d", (int) len));
  4899. if (pkt->icmp->type == 8 && pkt->ip != NULL && pkt->ip->dst == ifp->ip) {
  4900. size_t hlen = sizeof(struct eth) + sizeof(struct ip) + sizeof(struct icmp);
  4901. size_t space = ifp->tx.len - hlen, plen = pkt->pay.len;
  4902. if (plen > space) plen = space;
  4903. struct ip *ip = tx_ip(ifp, pkt->eth->src, 1, ifp->ip, pkt->ip->src,
  4904. sizeof(struct icmp) + plen);
  4905. struct icmp *icmp = (struct icmp *) (ip + 1);
  4906. memset(icmp, 0, sizeof(*icmp)); // Set csum to 0
  4907. memcpy(icmp + 1, pkt->pay.buf, plen); // Copy RX payload to TX
  4908. icmp->csum = ipcsum(icmp, sizeof(*icmp) + plen);
  4909. ether_output(ifp, hlen + plen);
  4910. }
  4911. }
  4912. static void rx_dhcp_client(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4913. uint32_t ip = 0, gw = 0, mask = 0, lease = 0;
  4914. uint8_t msgtype = 0, state = ifp->state;
  4915. // perform size check first, then access fields
  4916. uint8_t *p = pkt->dhcp->options,
  4917. *end = (uint8_t *) &pkt->raw.buf[pkt->raw.len];
  4918. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4919. if (memcmp(&pkt->dhcp->xid, ifp->mac + 2, sizeof(pkt->dhcp->xid))) return;
  4920. while (p + 1 < end && p[0] != 255) { // Parse options RFC-1533 #9
  4921. if (p[0] == 1 && p[1] == sizeof(ifp->mask) && p + 6 < end) { // Mask
  4922. memcpy(&mask, p + 2, sizeof(mask));
  4923. } else if (p[0] == 3 && p[1] == sizeof(ifp->gw) && p + 6 < end) { // GW
  4924. memcpy(&gw, p + 2, sizeof(gw));
  4925. ip = pkt->dhcp->yiaddr;
  4926. } else if (p[0] == 51 && p[1] == 4 && p + 6 < end) { // Lease
  4927. memcpy(&lease, p + 2, sizeof(lease));
  4928. lease = mg_ntohl(lease);
  4929. } else if (p[0] == 53 && p[1] == 1 && p + 6 < end) { // Msg Type
  4930. msgtype = p[2];
  4931. }
  4932. p += p[1] + 2;
  4933. }
  4934. // Process message type, RFC-1533 (9.4); RFC-2131 (3.1, 4)
  4935. if (msgtype == 6 && ifp->ip == ip) { // DHCPNACK, release IP
  4936. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0;
  4937. } else if (msgtype == 2 && ifp->state == MG_TCPIP_STATE_UP && ip && gw &&
  4938. lease) { // DHCPOFFER
  4939. // select IP, (4.4.1) (fallback to IP source addr on foul play)
  4940. tx_dhcp_request_sel(ifp, ip,
  4941. pkt->dhcp->siaddr ? pkt->dhcp->siaddr : pkt->ip->src);
  4942. ifp->state = MG_TCPIP_STATE_REQ; // REQUESTING state
  4943. } else if (msgtype == 5) { // DHCPACK
  4944. if (ifp->state == MG_TCPIP_STATE_REQ && ip && gw && lease) { // got an IP
  4945. ifp->lease_expire = ifp->now + lease * 1000;
  4946. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4947. // assume DHCP server = router until ARP resolves
  4948. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4949. ifp->ip = ip, ifp->gw = gw, ifp->mask = mask;
  4950. ifp->state = MG_TCPIP_STATE_READY; // BOUND state
  4951. uint64_t rand;
  4952. mg_random(&rand, sizeof(rand));
  4953. srand((unsigned int) (rand + mg_millis()));
  4954. } else if (ifp->state == MG_TCPIP_STATE_READY && ifp->ip == ip) { // renew
  4955. ifp->lease_expire = ifp->now + lease * 1000;
  4956. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4957. } // TODO(): accept provided T1/T2 and store server IP for renewal (4.4)
  4958. }
  4959. if (ifp->state != state) onstatechange(ifp);
  4960. }
  4961. // Simple DHCP server that assigns a next IP address: ifp->ip + 1
  4962. static void rx_dhcp_server(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4963. uint8_t op = 0, *p = pkt->dhcp->options,
  4964. *end = (uint8_t *) &pkt->raw.buf[pkt->raw.len];
  4965. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4966. // struct dhcp *req = pkt->dhcp;
  4967. struct dhcp res = {2, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4968. res.yiaddr = ifp->ip;
  4969. ((uint8_t *) (&res.yiaddr))[3]++; // Offer our IP + 1
  4970. while (p + 1 < end && p[0] != 255) { // Parse options
  4971. if (p[0] == 53 && p[1] == 1 && p + 2 < end) { // Message type
  4972. op = p[2];
  4973. }
  4974. p += p[1] + 2;
  4975. }
  4976. if (op == 1 || op == 3) { // DHCP Discover or DHCP Request
  4977. uint8_t msg = op == 1 ? 2 : 5; // Message type: DHCP OFFER or DHCP ACK
  4978. uint8_t opts[] = {
  4979. 53, 1, msg, // Message type
  4980. 1, 4, 0, 0, 0, 0, // Subnet mask
  4981. 54, 4, 0, 0, 0, 0, // Server ID
  4982. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4983. 51, 4, 255, 255, 255, 255, // Lease time
  4984. 255 // End of options
  4985. };
  4986. memcpy(&res.hwaddr, pkt->dhcp->hwaddr, 6);
  4987. memcpy(opts + 5, &ifp->mask, sizeof(ifp->mask));
  4988. memcpy(opts + 11, &ifp->ip, sizeof(ifp->ip));
  4989. memcpy(&res.options, opts, sizeof(opts));
  4990. res.magic = pkt->dhcp->magic;
  4991. res.xid = pkt->dhcp->xid;
  4992. if (ifp->enable_get_gateway) {
  4993. ifp->gw = res.yiaddr;
  4994. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4995. }
  4996. tx_udp(ifp, pkt->eth->src, ifp->ip, mg_htons(67),
  4997. op == 1 ? ~0U : res.yiaddr, mg_htons(68), &res, sizeof(res));
  4998. }
  4999. }
  5000. static void rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5001. struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
  5002. if (c == NULL) {
  5003. // No UDP listener on this port. Should send ICMP, but keep silent.
  5004. } else {
  5005. c->rem.port = pkt->udp->sport;
  5006. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  5007. struct connstate *s = (struct connstate *) (c + 1);
  5008. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  5009. if (c->recv.len >= MG_MAX_RECV_SIZE) {
  5010. mg_error(c, "max_recv_buf_size reached");
  5011. } else if (c->recv.size - c->recv.len < pkt->pay.len &&
  5012. !mg_iobuf_resize(&c->recv, c->recv.len + pkt->pay.len)) {
  5013. mg_error(c, "oom");
  5014. } else {
  5015. memcpy(&c->recv.buf[c->recv.len], pkt->pay.buf, pkt->pay.len);
  5016. c->recv.len += pkt->pay.len;
  5017. mg_call(c, MG_EV_READ, &pkt->pay.len);
  5018. }
  5019. }
  5020. }
  5021. static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *dst_mac, uint32_t dst_ip,
  5022. uint8_t flags, uint16_t sport, uint16_t dport,
  5023. uint32_t seq, uint32_t ack, const void *buf, size_t len) {
  5024. #if 0
  5025. uint8_t opts[] = {2, 4, 5, 0xb4, 4, 2, 0, 0}; // MSS = 1460, SACK permitted
  5026. if (flags & TH_SYN) {
  5027. // Handshake? Set MSS
  5028. buf = opts;
  5029. len = sizeof(opts);
  5030. }
  5031. #endif
  5032. struct ip *ip =
  5033. tx_ip(ifp, dst_mac, 6, ifp->ip, dst_ip, sizeof(struct tcp) + len);
  5034. struct tcp *tcp = (struct tcp *) (ip + 1);
  5035. memset(tcp, 0, sizeof(*tcp));
  5036. if (buf != NULL && len) memmove(tcp + 1, buf, len);
  5037. tcp->sport = sport;
  5038. tcp->dport = dport;
  5039. tcp->seq = seq;
  5040. tcp->ack = ack;
  5041. tcp->flags = flags;
  5042. tcp->win = mg_htons(MIP_TCP_WIN);
  5043. tcp->off = (uint8_t) (sizeof(*tcp) / 4 << 4);
  5044. // if (flags & TH_SYN) tcp->off = 0x70; // Handshake? header size 28 bytes
  5045. uint32_t cs = 0;
  5046. uint16_t n = (uint16_t) (sizeof(*tcp) + len);
  5047. uint8_t pseudo[] = {0, ip->proto, (uint8_t) (n >> 8), (uint8_t) (n & 255)};
  5048. cs = csumup(cs, tcp, n);
  5049. cs = csumup(cs, &ip->src, sizeof(ip->src));
  5050. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  5051. cs = csumup(cs, pseudo, sizeof(pseudo));
  5052. tcp->csum = csumfin(cs);
  5053. MG_VERBOSE(("TCP %M:%hu -> %M:%hu fl %x len %u", mg_print_ip4, &ip->src,
  5054. mg_ntohs(tcp->sport), mg_print_ip4, &ip->dst,
  5055. mg_ntohs(tcp->dport), tcp->flags, len));
  5056. // mg_hexdump(ifp->tx.buf, PDIFF(ifp->tx.buf, tcp + 1) + len);
  5057. return ether_output(ifp, PDIFF(ifp->tx.buf, tcp + 1) + len);
  5058. }
  5059. static size_t tx_tcp_pkt(struct mg_tcpip_if *ifp, struct pkt *pkt,
  5060. uint8_t flags, uint32_t seq, const void *buf,
  5061. size_t len) {
  5062. uint32_t delta = (pkt->tcp->flags & (TH_SYN | TH_FIN)) ? 1 : 0;
  5063. return tx_tcp(ifp, pkt->eth->src, pkt->ip->src, flags, pkt->tcp->dport,
  5064. pkt->tcp->sport, seq, mg_htonl(mg_ntohl(pkt->tcp->seq) + delta),
  5065. buf, len);
  5066. }
  5067. static struct mg_connection *accept_conn(struct mg_connection *lsn,
  5068. struct pkt *pkt) {
  5069. struct mg_connection *c = mg_alloc_conn(lsn->mgr);
  5070. if (c == NULL) {
  5071. MG_ERROR(("OOM"));
  5072. return NULL;
  5073. }
  5074. struct connstate *s = (struct connstate *) (c + 1);
  5075. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq);
  5076. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  5077. settmout(c, MIP_TTYPE_KEEPALIVE);
  5078. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  5079. c->rem.port = pkt->tcp->sport;
  5080. MG_DEBUG(("%lu accepted %M", c->id, mg_print_ip_port, &c->rem));
  5081. LIST_ADD_HEAD(struct mg_connection, &lsn->mgr->conns, c);
  5082. c->is_accepted = 1;
  5083. c->is_hexdumping = lsn->is_hexdumping;
  5084. c->pfn = lsn->pfn;
  5085. c->loc = lsn->loc;
  5086. c->pfn_data = lsn->pfn_data;
  5087. c->fn = lsn->fn;
  5088. c->fn_data = lsn->fn_data;
  5089. mg_call(c, MG_EV_OPEN, NULL);
  5090. mg_call(c, MG_EV_ACCEPT, NULL);
  5091. return c;
  5092. }
  5093. static size_t trim_len(struct mg_connection *c, size_t len) {
  5094. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5095. size_t eth_h_len = 14, ip_max_h_len = 24, tcp_max_h_len = 60, udp_h_len = 8;
  5096. size_t max_headers_len =
  5097. eth_h_len + ip_max_h_len + (c->is_udp ? udp_h_len : tcp_max_h_len);
  5098. size_t min_mtu = c->is_udp ? 68 /* RFC-791 */ : max_headers_len - eth_h_len;
  5099. // If the frame exceeds the available buffer, trim the length
  5100. if (len + max_headers_len > ifp->tx.len) {
  5101. len = ifp->tx.len - max_headers_len;
  5102. }
  5103. // Ensure the MTU isn't lower than the minimum allowed value
  5104. if (ifp->mtu < min_mtu) {
  5105. MG_ERROR(("MTU is lower than minimum, capping to %lu", min_mtu));
  5106. ifp->mtu = (uint16_t) min_mtu;
  5107. }
  5108. // If the total packet size exceeds the MTU, trim the length
  5109. if (len + max_headers_len - eth_h_len > ifp->mtu) {
  5110. len = ifp->mtu - max_headers_len + eth_h_len;
  5111. if (c->is_udp) {
  5112. MG_ERROR(("UDP datagram exceeds MTU. Truncating it."));
  5113. }
  5114. }
  5115. return len;
  5116. }
  5117. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  5118. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5119. struct connstate *s = (struct connstate *) (c + 1);
  5120. uint32_t dst_ip = *(uint32_t *) c->rem.ip;
  5121. len = trim_len(c, len);
  5122. if (c->is_udp) {
  5123. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, dst_ip, c->rem.port, buf, len);
  5124. } else {
  5125. size_t sent =
  5126. tx_tcp(ifp, s->mac, dst_ip, TH_PUSH | TH_ACK, c->loc.port, c->rem.port,
  5127. mg_htonl(s->seq), mg_htonl(s->ack), buf, len);
  5128. if (sent == 0) {
  5129. return MG_IO_WAIT;
  5130. } else if (sent == (size_t) -1) {
  5131. return MG_IO_ERR;
  5132. } else {
  5133. s->seq += (uint32_t) len;
  5134. if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
  5135. }
  5136. }
  5137. return (long) len;
  5138. }
  5139. static void handle_tls_recv(struct mg_connection *c, struct mg_iobuf *io) {
  5140. long n = mg_tls_recv(c, &io->buf[io->len], io->size - io->len);
  5141. if (n == MG_IO_ERR) {
  5142. mg_error(c, "TLS recv error");
  5143. } else if (n > 0) {
  5144. // Decrypted successfully - trigger MG_EV_READ
  5145. io->len += (size_t) n;
  5146. mg_call(c, MG_EV_READ, &n);
  5147. }
  5148. }
  5149. static void read_conn(struct mg_connection *c, struct pkt *pkt) {
  5150. struct connstate *s = (struct connstate *) (c + 1);
  5151. struct mg_iobuf *io = c->is_tls ? &c->rtls : &c->recv;
  5152. uint32_t seq = mg_ntohl(pkt->tcp->seq);
  5153. uint32_t rem_ip;
  5154. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5155. if (pkt->tcp->flags & TH_FIN) {
  5156. // If we initiated the closure, we reply with ACK upon receiving FIN
  5157. // If we didn't initiate it, we reply with FIN as part of the normal TCP
  5158. // closure process
  5159. uint8_t flags = TH_ACK;
  5160. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len + 1);
  5161. if (c->is_draining && s->ttype == MIP_TTYPE_FIN) {
  5162. if (s->seq == mg_htonl(pkt->tcp->ack)) { // Simultaneous closure ?
  5163. s->seq++; // Yes. Increment our SEQ
  5164. } else { // Otherwise,
  5165. s->seq = mg_htonl(pkt->tcp->ack); // Set to peer's ACK
  5166. }
  5167. } else {
  5168. flags |= TH_FIN;
  5169. c->is_draining = 1;
  5170. settmout(c, MIP_TTYPE_FIN);
  5171. }
  5172. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, flags,
  5173. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  5174. } else if (pkt->pay.len == 0) {
  5175. // TODO(cpq): handle this peer's ACK
  5176. } else if (seq != s->ack) {
  5177. uint32_t ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  5178. if (s->ack == ack) {
  5179. MG_VERBOSE(("ignoring duplicate pkt"));
  5180. } else {
  5181. MG_VERBOSE(("SEQ != ACK: %x %x %x", seq, s->ack, ack));
  5182. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  5183. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "",
  5184. 0);
  5185. }
  5186. } else if (io->size - io->len < pkt->pay.len &&
  5187. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  5188. mg_error(c, "oom");
  5189. } else {
  5190. // Copy TCP payload into the IO buffer. If the connection is plain text,
  5191. // we copy to c->recv. If the connection is TLS, this data is encrypted,
  5192. // therefore we copy that encrypted data to the c->rtls iobuffer instead,
  5193. // and then call mg_tls_recv() to decrypt it. NOTE: mg_tls_recv() will
  5194. // call back mg_io_recv() which grabs raw data from c->rtls
  5195. memcpy(&io->buf[io->len], pkt->pay.buf, pkt->pay.len);
  5196. io->len += pkt->pay.len;
  5197. MG_VERBOSE(("%lu SEQ %x -> %x", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  5198. // Advance ACK counter
  5199. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  5200. s->unacked += pkt->pay.len;
  5201. // size_t diff = s->acked <= s->ack ? s->ack - s->acked : s->ack;
  5202. if (s->unacked > MIP_TCP_WIN / 2 && s->acked != s->ack) {
  5203. // Send ACK immediately
  5204. MG_VERBOSE(("%lu imm ACK %lu", c->id, s->acked));
  5205. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  5206. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), NULL,
  5207. 0);
  5208. s->unacked = 0;
  5209. s->acked = s->ack;
  5210. if (s->ttype != MIP_TTYPE_KEEPALIVE) settmout(c, MIP_TTYPE_KEEPALIVE);
  5211. } else {
  5212. // if not already running, setup a timer to send an ACK later
  5213. if (s->ttype != MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_ACK);
  5214. }
  5215. if (c->is_tls && c->is_tls_hs) {
  5216. mg_tls_handshake(c);
  5217. } else if (c->is_tls) {
  5218. // TLS connection. Make room for decrypted data in c->recv
  5219. io = &c->recv;
  5220. if (io->size - io->len < pkt->pay.len &&
  5221. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  5222. mg_error(c, "oom");
  5223. } else {
  5224. // Decrypt data directly into c->recv
  5225. handle_tls_recv(c, io);
  5226. }
  5227. } else {
  5228. // Plain text connection, data is already in c->recv, trigger
  5229. // MG_EV_READ
  5230. mg_call(c, MG_EV_READ, &pkt->pay.len);
  5231. }
  5232. }
  5233. }
  5234. static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5235. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  5236. struct connstate *s = c == NULL ? NULL : (struct connstate *) (c + 1);
  5237. #if 0
  5238. MG_INFO(("%lu %hhu %d", c ? c->id : 0, pkt->tcp->flags, (int) pkt->pay.len));
  5239. #endif
  5240. if (c != NULL && c->is_connecting && pkt->tcp->flags == (TH_SYN | TH_ACK)) {
  5241. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq) + 1;
  5242. tx_tcp_pkt(ifp, pkt, TH_ACK, pkt->tcp->ack, NULL, 0);
  5243. c->is_connecting = 0; // Client connected
  5244. settmout(c, MIP_TTYPE_KEEPALIVE);
  5245. mg_call(c, MG_EV_CONNECT, NULL); // Let user know
  5246. } else if (c != NULL && c->is_connecting && pkt->tcp->flags != TH_ACK) {
  5247. // mg_hexdump(pkt->raw.buf, pkt->raw.len);
  5248. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5249. } else if (c != NULL && pkt->tcp->flags & TH_RST) {
  5250. mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  5251. } else if (c != NULL) {
  5252. #if 0
  5253. MG_DEBUG(("%lu %d %M:%hu -> %M:%hu", c->id, (int) pkt->raw.len,
  5254. mg_print_ip4, &pkt->ip->src, mg_ntohs(pkt->tcp->sport),
  5255. mg_print_ip4, &pkt->ip->dst, mg_ntohs(pkt->tcp->dport)));
  5256. mg_hexdump(pkt->pay.buf, pkt->pay.len);
  5257. #endif
  5258. s->tmiss = 0; // Reset missed keep-alive counter
  5259. if (s->ttype == MIP_TTYPE_KEEPALIVE) // Advance keep-alive timer
  5260. settmout(c,
  5261. MIP_TTYPE_KEEPALIVE); // unless a former ACK timeout is pending
  5262. read_conn(c, pkt); // Override timer with ACK timeout if needed
  5263. } else if ((c = getpeer(ifp->mgr, pkt, true)) == NULL) {
  5264. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5265. } else if (pkt->tcp->flags & TH_RST) {
  5266. if (c->is_accepted) mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  5267. // ignore RST if not connected
  5268. } else if (pkt->tcp->flags & TH_SYN) {
  5269. // Use peer's source port as ISN, in order to recognise the handshake
  5270. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(pkt->tcp->sport));
  5271. tx_tcp_pkt(ifp, pkt, TH_SYN | TH_ACK, isn, NULL, 0);
  5272. } else if (pkt->tcp->flags & TH_FIN) {
  5273. tx_tcp_pkt(ifp, pkt, TH_FIN | TH_ACK, pkt->tcp->ack, NULL, 0);
  5274. } else if (mg_htonl(pkt->tcp->ack) == mg_htons(pkt->tcp->sport) + 1U) {
  5275. accept_conn(c, pkt);
  5276. } else if (!c->is_accepted) { // no peer
  5277. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  5278. } else {
  5279. // MG_VERBOSE(("dropped silently.."));
  5280. }
  5281. }
  5282. static void rx_ip(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5283. if (pkt->ip->frag & IP_MORE_FRAGS_MSK || pkt->ip->frag & IP_FRAG_OFFSET_MSK) {
  5284. if (pkt->ip->proto == 17) pkt->udp = (struct udp *) (pkt->ip + 1);
  5285. if (pkt->ip->proto == 6) pkt->tcp = (struct tcp *) (pkt->ip + 1);
  5286. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  5287. if (c) mg_error(c, "Received fragmented packet");
  5288. } else if (pkt->ip->proto == 1) {
  5289. pkt->icmp = (struct icmp *) (pkt->ip + 1);
  5290. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  5291. mkpay(pkt, pkt->icmp + 1);
  5292. rx_icmp(ifp, pkt);
  5293. } else if (pkt->ip->proto == 17) {
  5294. pkt->udp = (struct udp *) (pkt->ip + 1);
  5295. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  5296. mkpay(pkt, pkt->udp + 1);
  5297. MG_VERBOSE(("UDP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  5298. mg_ntohs(pkt->udp->sport), mg_print_ip4, &pkt->ip->dst,
  5299. mg_ntohs(pkt->udp->dport), (int) pkt->pay.len));
  5300. if (ifp->enable_dhcp_client && pkt->udp->dport == mg_htons(68)) {
  5301. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  5302. mkpay(pkt, pkt->dhcp + 1);
  5303. rx_dhcp_client(ifp, pkt);
  5304. } else if (ifp->enable_dhcp_server && pkt->udp->dport == mg_htons(67)) {
  5305. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  5306. mkpay(pkt, pkt->dhcp + 1);
  5307. rx_dhcp_server(ifp, pkt);
  5308. } else {
  5309. rx_udp(ifp, pkt);
  5310. }
  5311. } else if (pkt->ip->proto == 6) {
  5312. pkt->tcp = (struct tcp *) (pkt->ip + 1);
  5313. if (pkt->pay.len < sizeof(*pkt->tcp)) return;
  5314. mkpay(pkt, pkt->tcp + 1);
  5315. uint16_t iplen = mg_ntohs(pkt->ip->len);
  5316. uint16_t off = (uint16_t) (sizeof(*pkt->ip) + ((pkt->tcp->off >> 4) * 4U));
  5317. if (iplen >= off) pkt->pay.len = (size_t) (iplen - off);
  5318. MG_VERBOSE(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  5319. mg_ntohs(pkt->tcp->sport), mg_print_ip4, &pkt->ip->dst,
  5320. mg_ntohs(pkt->tcp->dport), (int) pkt->pay.len));
  5321. rx_tcp(ifp, pkt);
  5322. }
  5323. }
  5324. static void rx_ip6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  5325. // MG_DEBUG(("IP %d", (int) len));
  5326. if (pkt->ip6->proto == 1 || pkt->ip6->proto == 58) {
  5327. pkt->icmp = (struct icmp *) (pkt->ip6 + 1);
  5328. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  5329. mkpay(pkt, pkt->icmp + 1);
  5330. rx_icmp(ifp, pkt);
  5331. } else if (pkt->ip6->proto == 17) {
  5332. pkt->udp = (struct udp *) (pkt->ip6 + 1);
  5333. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  5334. // MG_DEBUG((" UDP %u %u -> %u", len, mg_htons(udp->sport),
  5335. // mg_htons(udp->dport)));
  5336. mkpay(pkt, pkt->udp + 1);
  5337. }
  5338. }
  5339. static void mg_tcpip_rx(struct mg_tcpip_if *ifp, void *buf, size_t len) {
  5340. struct pkt pkt;
  5341. memset(&pkt, 0, sizeof(pkt));
  5342. pkt.raw.buf = (char *) buf;
  5343. pkt.raw.len = len;
  5344. pkt.eth = (struct eth *) buf;
  5345. // mg_hexdump(buf, len > 16 ? 16: len);
  5346. if (pkt.raw.len < sizeof(*pkt.eth)) return; // Truncated - runt?
  5347. if (ifp->enable_mac_check &&
  5348. memcmp(pkt.eth->dst, ifp->mac, sizeof(pkt.eth->dst)) != 0 &&
  5349. memcmp(pkt.eth->dst, broadcast, sizeof(pkt.eth->dst)) != 0)
  5350. return;
  5351. if (ifp->enable_crc32_check && len > 4) {
  5352. len -= 4; // TODO(scaprile): check on bigendian
  5353. uint32_t crc = mg_crc32(0, (const char *) buf, len);
  5354. if (memcmp((void *) ((size_t) buf + len), &crc, sizeof(crc))) return;
  5355. }
  5356. if (pkt.eth->type == mg_htons(0x806)) {
  5357. pkt.arp = (struct arp *) (pkt.eth + 1);
  5358. if (sizeof(*pkt.eth) + sizeof(*pkt.arp) > pkt.raw.len) return; // Truncated
  5359. rx_arp(ifp, &pkt);
  5360. } else if (pkt.eth->type == mg_htons(0x86dd)) {
  5361. pkt.ip6 = (struct ip6 *) (pkt.eth + 1);
  5362. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip6)) return; // Truncated
  5363. if ((pkt.ip6->ver >> 4) != 0x6) return; // Not IP
  5364. mkpay(&pkt, pkt.ip6 + 1);
  5365. rx_ip6(ifp, &pkt);
  5366. } else if (pkt.eth->type == mg_htons(0x800)) {
  5367. pkt.ip = (struct ip *) (pkt.eth + 1);
  5368. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  5369. // Truncate frame to what IP header tells us
  5370. if ((size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth) < pkt.raw.len) {
  5371. pkt.raw.len = (size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth);
  5372. }
  5373. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  5374. if ((pkt.ip->ver >> 4) != 4) return; // Not IP
  5375. mkpay(&pkt, pkt.ip + 1);
  5376. rx_ip(ifp, &pkt);
  5377. } else {
  5378. MG_DEBUG(("Unknown eth type %x", mg_htons(pkt.eth->type)));
  5379. if (mg_log_level >= MG_LL_VERBOSE) mg_hexdump(buf, len >= 32 ? 32 : len);
  5380. }
  5381. }
  5382. static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t now) {
  5383. struct mg_connection *c;
  5384. bool expired_1000ms = mg_timer_expired(&ifp->timer_1000ms, 1000, now);
  5385. ifp->now = now;
  5386. #if MG_ENABLE_TCPIP_PRINT_DEBUG_STATS
  5387. if (expired_1000ms) {
  5388. const char *names[] = {"down", "up", "req", "ready"};
  5389. MG_INFO(("Status: %s, IP: %M, rx:%u, tx:%u, dr:%u, er:%u",
  5390. names[ifp->state], mg_print_ip4, &ifp->ip, ifp->nrecv, ifp->nsent,
  5391. ifp->ndrop, ifp->nerr));
  5392. }
  5393. #endif
  5394. // Handle physical interface up/down status
  5395. if (expired_1000ms && ifp->driver->up) {
  5396. bool up = ifp->driver->up(ifp);
  5397. bool current = ifp->state != MG_TCPIP_STATE_DOWN;
  5398. if (up != current) {
  5399. ifp->state = up == false ? MG_TCPIP_STATE_DOWN
  5400. : ifp->enable_dhcp_client ? MG_TCPIP_STATE_UP
  5401. : MG_TCPIP_STATE_READY;
  5402. if (!up && ifp->enable_dhcp_client) ifp->ip = 0;
  5403. onstatechange(ifp);
  5404. }
  5405. if (ifp->state == MG_TCPIP_STATE_DOWN) MG_ERROR(("Network is down"));
  5406. }
  5407. if (ifp->state == MG_TCPIP_STATE_DOWN) return;
  5408. // DHCP RFC-2131 (4.4)
  5409. if (ifp->state == MG_TCPIP_STATE_UP && expired_1000ms) {
  5410. tx_dhcp_discover(ifp); // INIT (4.4.1)
  5411. } else if (expired_1000ms && ifp->state == MG_TCPIP_STATE_READY &&
  5412. ifp->lease_expire > 0) { // BOUND / RENEWING / REBINDING
  5413. if (ifp->now >= ifp->lease_expire) {
  5414. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0; // expired, release IP
  5415. onstatechange(ifp);
  5416. } else if (ifp->now + 30UL * 60UL * 1000UL > ifp->lease_expire &&
  5417. ((ifp->now / 1000) % 60) == 0) {
  5418. // hack: 30 min before deadline, try to rebind (4.3.6) every min
  5419. tx_dhcp_request_re(ifp, (uint8_t *) broadcast, ifp->ip, 0xffffffff);
  5420. } // TODO(): Handle T1 (RENEWING) and T2 (REBINDING) (4.4.5)
  5421. }
  5422. // Read data from the network
  5423. if (ifp->driver->rx != NULL) { // Polling driver. We must call it
  5424. size_t len =
  5425. ifp->driver->rx(ifp->recv_queue.buf, ifp->recv_queue.size, ifp);
  5426. if (len > 0) {
  5427. ifp->nrecv++;
  5428. mg_tcpip_rx(ifp, ifp->recv_queue.buf, len);
  5429. }
  5430. } else { // Interrupt-based driver. Fills recv queue itself
  5431. char *buf;
  5432. size_t len = mg_queue_next(&ifp->recv_queue, &buf);
  5433. if (len > 0) {
  5434. mg_tcpip_rx(ifp, buf, len);
  5435. mg_queue_del(&ifp->recv_queue, len);
  5436. }
  5437. }
  5438. // Process timeouts
  5439. for (c = ifp->mgr->conns; c != NULL; c = c->next) {
  5440. if (c->is_udp || c->is_listening || c->is_resolving) continue;
  5441. struct connstate *s = (struct connstate *) (c + 1);
  5442. uint32_t rem_ip;
  5443. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5444. if (now > s->timer) {
  5445. if (s->ttype == MIP_TTYPE_ACK && s->acked != s->ack) {
  5446. MG_VERBOSE(("%lu ack %x %x", c->id, s->seq, s->ack));
  5447. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  5448. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5449. s->acked = s->ack;
  5450. } else if (s->ttype == MIP_TTYPE_ARP) {
  5451. mg_error(c, "ARP timeout");
  5452. } else if (s->ttype == MIP_TTYPE_SYN) {
  5453. mg_error(c, "Connection timeout");
  5454. } else if (s->ttype == MIP_TTYPE_FIN) {
  5455. c->is_closing = 1;
  5456. continue;
  5457. } else {
  5458. if (s->tmiss++ > 2) {
  5459. mg_error(c, "keepalive");
  5460. } else {
  5461. MG_VERBOSE(("%lu keepalive", c->id));
  5462. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  5463. mg_htonl(s->seq - 1), mg_htonl(s->ack), NULL, 0);
  5464. }
  5465. }
  5466. settmout(c, MIP_TTYPE_KEEPALIVE);
  5467. }
  5468. }
  5469. }
  5470. // This function executes in interrupt context, thus it should copy data
  5471. // somewhere fast. Note that newlib's malloc is not thread safe, thus use
  5472. // our lock-free queue with preallocated buffer to copy data and return asap
  5473. void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) {
  5474. char *p;
  5475. if (mg_queue_book(&ifp->recv_queue, &p, len) >= len) {
  5476. memcpy(p, buf, len);
  5477. mg_queue_add(&ifp->recv_queue, len);
  5478. ifp->nrecv++;
  5479. } else {
  5480. ifp->ndrop++;
  5481. }
  5482. }
  5483. void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
  5484. // If MAC address is not set, make a random one
  5485. if (ifp->mac[0] == 0 && ifp->mac[1] == 0 && ifp->mac[2] == 0 &&
  5486. ifp->mac[3] == 0 && ifp->mac[4] == 0 && ifp->mac[5] == 0) {
  5487. ifp->mac[0] = 0x02; // Locally administered, unicast
  5488. mg_random(&ifp->mac[1], sizeof(ifp->mac) - 1);
  5489. MG_INFO(("MAC not set. Generated random: %M", mg_print_mac, ifp->mac));
  5490. }
  5491. if (ifp->driver->init && !ifp->driver->init(ifp)) {
  5492. MG_ERROR(("driver init failed"));
  5493. } else {
  5494. size_t framesize = 1540;
  5495. ifp->tx.buf = (char *) calloc(1, framesize), ifp->tx.len = framesize;
  5496. if (ifp->recv_queue.size == 0)
  5497. ifp->recv_queue.size = ifp->driver->rx ? framesize : 8192;
  5498. ifp->recv_queue.buf = (char *) calloc(1, ifp->recv_queue.size);
  5499. ifp->timer_1000ms = mg_millis();
  5500. mgr->priv = ifp;
  5501. ifp->mgr = mgr;
  5502. ifp->mtu = MG_TCPIP_MTU_DEFAULT;
  5503. mgr->extraconnsize = sizeof(struct connstate);
  5504. if (ifp->ip == 0) ifp->enable_dhcp_client = true;
  5505. memset(ifp->gwmac, 255, sizeof(ifp->gwmac)); // Set to broadcast
  5506. mg_random(&ifp->eport, sizeof(ifp->eport)); // Random from 0 to 65535
  5507. ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
  5508. // MG_EPHEMERAL_PORT_BASE to 65535
  5509. if (ifp->tx.buf == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
  5510. }
  5511. }
  5512. void mg_tcpip_free(struct mg_tcpip_if *ifp) {
  5513. free(ifp->recv_queue.buf);
  5514. free(ifp->tx.buf);
  5515. }
  5516. static void send_syn(struct mg_connection *c) {
  5517. struct connstate *s = (struct connstate *) (c + 1);
  5518. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(c->loc.port));
  5519. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5520. uint32_t rem_ip;
  5521. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5522. tx_tcp(ifp, s->mac, rem_ip, TH_SYN, c->loc.port, c->rem.port, isn, 0, NULL,
  5523. 0);
  5524. }
  5525. void mg_connect_resolved(struct mg_connection *c) {
  5526. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5527. uint32_t rem_ip;
  5528. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5529. c->is_resolving = 0;
  5530. if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
  5531. memcpy(c->loc.ip, &ifp->ip, sizeof(uint32_t));
  5532. c->loc.port = mg_htons(ifp->eport++);
  5533. MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
  5534. &c->rem));
  5535. mg_call(c, MG_EV_RESOLVE, NULL);
  5536. if (c->is_udp && (rem_ip == 0xffffffff || rem_ip == (ifp->ip | ~ifp->mask))) {
  5537. struct connstate *s = (struct connstate *) (c + 1);
  5538. memset(s->mac, 0xFF, sizeof(s->mac)); // global or local broadcast
  5539. } else if (ifp->ip && ((rem_ip & ifp->mask) == (ifp->ip & ifp->mask))) {
  5540. // If we're in the same LAN, fire an ARP lookup.
  5541. MG_DEBUG(("%lu ARP lookup...", c->id));
  5542. arp_ask(ifp, rem_ip);
  5543. settmout(c, MIP_TTYPE_ARP);
  5544. c->is_arplooking = 1;
  5545. c->is_connecting = 1;
  5546. } else if ((*((uint8_t *) &rem_ip) & 0xE0) == 0xE0) {
  5547. struct connstate *s = (struct connstate *) (c + 1); // 224 to 239, E0 to EF
  5548. uint8_t mcastp[3] = {0x01, 0x00, 0x5E}; // multicast group
  5549. memcpy(s->mac, mcastp, 3);
  5550. memcpy(s->mac + 3, ((uint8_t *) &rem_ip) + 1, 3); // 23 LSb
  5551. s->mac[3] &= 0x7F;
  5552. } else {
  5553. struct connstate *s = (struct connstate *) (c + 1);
  5554. memcpy(s->mac, ifp->gwmac, sizeof(ifp->gwmac));
  5555. if (c->is_udp) {
  5556. mg_call(c, MG_EV_CONNECT, NULL);
  5557. } else {
  5558. send_syn(c);
  5559. settmout(c, MIP_TTYPE_SYN);
  5560. c->is_connecting = 1;
  5561. }
  5562. }
  5563. }
  5564. bool mg_open_listener(struct mg_connection *c, const char *url) {
  5565. c->loc.port = mg_htons(mg_url_port(url));
  5566. return true;
  5567. }
  5568. static void write_conn(struct mg_connection *c) {
  5569. long len = c->is_tls ? mg_tls_send(c, c->send.buf, c->send.len)
  5570. : mg_io_send(c, c->send.buf, c->send.len);
  5571. if (len == MG_IO_ERR) {
  5572. mg_error(c, "tx err");
  5573. } else if (len > 0) {
  5574. mg_iobuf_del(&c->send, 0, (size_t) len);
  5575. mg_call(c, MG_EV_WRITE, &len);
  5576. }
  5577. }
  5578. static void init_closure(struct mg_connection *c) {
  5579. struct connstate *s = (struct connstate *) (c + 1);
  5580. if (c->is_udp == false && c->is_listening == false &&
  5581. c->is_connecting == false) { // For TCP conns,
  5582. struct mg_tcpip_if *ifp =
  5583. (struct mg_tcpip_if *) c->mgr->priv; // send TCP FIN
  5584. uint32_t rem_ip;
  5585. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5586. tx_tcp(ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port, c->rem.port,
  5587. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5588. settmout(c, MIP_TTYPE_FIN);
  5589. }
  5590. }
  5591. static void close_conn(struct mg_connection *c) {
  5592. struct connstate *s = (struct connstate *) (c + 1);
  5593. mg_iobuf_free(&s->raw); // For TLS connections, release raw data
  5594. mg_close_conn(c);
  5595. }
  5596. static bool can_write(struct mg_connection *c) {
  5597. return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 &&
  5598. c->is_tls_hs == 0 && c->is_arplooking == 0;
  5599. }
  5600. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  5601. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) mgr->priv;
  5602. struct mg_connection *c, *tmp;
  5603. uint64_t now = mg_millis();
  5604. mg_timer_poll(&mgr->timers, now);
  5605. if (ifp == NULL || ifp->driver == NULL) return;
  5606. mg_tcpip_poll(ifp, now);
  5607. for (c = mgr->conns; c != NULL; c = tmp) {
  5608. tmp = c->next;
  5609. struct connstate *s = (struct connstate *) (c + 1);
  5610. mg_call(c, MG_EV_POLL, &now);
  5611. MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't',
  5612. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  5613. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  5614. if (c->is_tls && mg_tls_pending(c) > 0)
  5615. handle_tls_recv(c, (struct mg_iobuf *) &c->rtls);
  5616. if (can_write(c)) write_conn(c);
  5617. if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN)
  5618. init_closure(c);
  5619. if (c->is_closing) close_conn(c);
  5620. }
  5621. (void) ms;
  5622. }
  5623. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  5624. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5625. bool res = false;
  5626. uint32_t rem_ip;
  5627. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5628. if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) {
  5629. mg_error(c, "net down");
  5630. } else if (c->is_udp) {
  5631. struct connstate *s = (struct connstate *) (c + 1);
  5632. len = trim_len(c, len); // Trimming length if necessary
  5633. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len);
  5634. res = true;
  5635. } else {
  5636. res = mg_iobuf_add(&c->send, c->send.len, buf, len);
  5637. }
  5638. return res;
  5639. }
  5640. #endif // MG_ENABLE_TCPIP
  5641. #ifdef MG_ENABLE_LINES
  5642. #line 1 "src/ota_dummy.c"
  5643. #endif
  5644. #if MG_OTA == MG_OTA_NONE
  5645. bool mg_ota_begin(size_t new_firmware_size) {
  5646. (void) new_firmware_size;
  5647. return true;
  5648. }
  5649. bool mg_ota_write(const void *buf, size_t len) {
  5650. (void) buf, (void) len;
  5651. return true;
  5652. }
  5653. bool mg_ota_end(void) {
  5654. return true;
  5655. }
  5656. bool mg_ota_commit(void) {
  5657. return true;
  5658. }
  5659. bool mg_ota_rollback(void) {
  5660. return true;
  5661. }
  5662. int mg_ota_status(int fw) {
  5663. (void) fw;
  5664. return 0;
  5665. }
  5666. uint32_t mg_ota_crc32(int fw) {
  5667. (void) fw;
  5668. return 0;
  5669. }
  5670. uint32_t mg_ota_timestamp(int fw) {
  5671. (void) fw;
  5672. return 0;
  5673. }
  5674. size_t mg_ota_size(int fw) {
  5675. (void) fw;
  5676. return 0;
  5677. }
  5678. MG_IRAM void mg_ota_boot(void) {
  5679. }
  5680. #endif
  5681. #ifdef MG_ENABLE_LINES
  5682. #line 1 "src/ota_esp32.c"
  5683. #endif
  5684. #if MG_ARCH == MG_ARCH_ESP32 && MG_OTA == MG_OTA_ESP32
  5685. static const esp_partition_t *s_ota_update_partition;
  5686. static esp_ota_handle_t s_ota_update_handle;
  5687. static bool s_ota_success;
  5688. // Those empty macros do nothing, but mark places in the code which could
  5689. // potentially trigger a watchdog reboot due to the log flash erase operation
  5690. #define disable_wdt()
  5691. #define enable_wdt()
  5692. bool mg_ota_begin(size_t new_firmware_size) {
  5693. if (s_ota_update_partition != NULL) {
  5694. MG_ERROR(("Update in progress. Call mg_ota_end() ?"));
  5695. return false;
  5696. } else {
  5697. s_ota_success = false;
  5698. disable_wdt();
  5699. s_ota_update_partition = esp_ota_get_next_update_partition(NULL);
  5700. esp_err_t err = esp_ota_begin(s_ota_update_partition, new_firmware_size,
  5701. &s_ota_update_handle);
  5702. enable_wdt();
  5703. MG_DEBUG(("esp_ota_begin(): %d", err));
  5704. s_ota_success = (err == ESP_OK);
  5705. }
  5706. return s_ota_success;
  5707. }
  5708. bool mg_ota_write(const void *buf, size_t len) {
  5709. disable_wdt();
  5710. esp_err_t err = esp_ota_write(s_ota_update_handle, buf, len);
  5711. enable_wdt();
  5712. MG_INFO(("esp_ota_write(): %d", err));
  5713. s_ota_success = err == ESP_OK;
  5714. return s_ota_success;
  5715. }
  5716. bool mg_ota_end(void) {
  5717. esp_err_t err = esp_ota_end(s_ota_update_handle);
  5718. MG_DEBUG(("esp_ota_end(%p): %d", s_ota_update_handle, err));
  5719. if (s_ota_success && err == ESP_OK) {
  5720. err = esp_ota_set_boot_partition(s_ota_update_partition);
  5721. s_ota_success = (err == ESP_OK);
  5722. }
  5723. MG_DEBUG(("Finished ESP32 OTA, success: %d", s_ota_success));
  5724. s_ota_update_partition = NULL;
  5725. return s_ota_success;
  5726. }
  5727. #endif
  5728. #ifdef MG_ENABLE_LINES
  5729. #line 1 "src/ota_flash.c"
  5730. #endif
  5731. // This OTA implementation uses the internal flash API outlined in device.h
  5732. // It splits flash into 2 equal partitions, and stores OTA status in the
  5733. // last sector of the partition.
  5734. #if MG_OTA == MG_OTA_FLASH
  5735. #define MG_OTADATA_KEY 0xb07afed0
  5736. static char *s_addr; // Current address to write to
  5737. static size_t s_size; // Firmware size to flash. In-progress indicator
  5738. static uint32_t s_crc32; // Firmware checksum
  5739. struct mg_otadata {
  5740. uint32_t crc32, size, timestamp, status;
  5741. };
  5742. bool mg_ota_begin(size_t new_firmware_size) {
  5743. bool ok = false;
  5744. if (s_size) {
  5745. MG_ERROR(("OTA already in progress. Call mg_ota_end()"));
  5746. } else {
  5747. size_t half = mg_flash_size() / 2, max = half - mg_flash_sector_size();
  5748. s_crc32 = 0;
  5749. s_addr = (char *) mg_flash_start() + half;
  5750. MG_DEBUG(("Firmware %lu bytes, max %lu", new_firmware_size, max));
  5751. if (new_firmware_size < max) {
  5752. ok = true;
  5753. s_size = new_firmware_size;
  5754. MG_INFO(("Starting OTA, firmware size %lu", s_size));
  5755. } else {
  5756. MG_ERROR(("Firmware %lu is too big to fit %lu", new_firmware_size, max));
  5757. }
  5758. }
  5759. return ok;
  5760. }
  5761. bool mg_ota_write(const void *buf, size_t len) {
  5762. bool ok = false;
  5763. if (s_size == 0) {
  5764. MG_ERROR(("OTA is not started, call mg_ota_begin()"));
  5765. } else {
  5766. size_t align = mg_flash_write_align();
  5767. size_t len_aligned_down = MG_ROUND_DOWN(len, align);
  5768. if (len_aligned_down) ok = mg_flash_write(s_addr, buf, len_aligned_down);
  5769. if (len_aligned_down < len) {
  5770. size_t left = len - len_aligned_down;
  5771. char tmp[align];
  5772. memset(tmp, 0xff, sizeof(tmp));
  5773. memcpy(tmp, (char *) buf + len_aligned_down, left);
  5774. ok = mg_flash_write(s_addr + len_aligned_down, tmp, sizeof(tmp));
  5775. }
  5776. s_crc32 = mg_crc32(s_crc32, (char *) buf, len); // Update CRC
  5777. MG_DEBUG(("%#x %p %lu -> %d", s_addr - len, buf, len, ok));
  5778. s_addr += len;
  5779. }
  5780. return ok;
  5781. }
  5782. MG_IRAM static uint32_t mg_fwkey(int fw) {
  5783. uint32_t key = MG_OTADATA_KEY + fw;
  5784. int bank = mg_flash_bank();
  5785. if (bank == 2 && fw == MG_FIRMWARE_PREVIOUS) key--;
  5786. if (bank == 2 && fw == MG_FIRMWARE_CURRENT) key++;
  5787. return key;
  5788. }
  5789. bool mg_ota_end(void) {
  5790. char *base = (char *) mg_flash_start() + mg_flash_size() / 2;
  5791. bool ok = false;
  5792. if (s_size) {
  5793. size_t size = s_addr - base;
  5794. uint32_t crc32 = mg_crc32(0, base, s_size);
  5795. if (size == s_size && crc32 == s_crc32) {
  5796. uint32_t now = (uint32_t) (mg_now() / 1000);
  5797. struct mg_otadata od = {crc32, size, now, MG_OTA_FIRST_BOOT};
  5798. uint32_t key = mg_fwkey(MG_FIRMWARE_PREVIOUS);
  5799. ok = mg_flash_save(NULL, key, &od, sizeof(od));
  5800. }
  5801. MG_DEBUG(("CRC: %x/%x, size: %lu/%lu, status: %s", s_crc32, crc32, s_size,
  5802. size, ok ? "ok" : "fail"));
  5803. s_size = 0;
  5804. if (ok) ok = mg_flash_swap_bank();
  5805. }
  5806. MG_INFO(("Finishing OTA: %s", ok ? "ok" : "fail"));
  5807. return ok;
  5808. }
  5809. MG_IRAM static struct mg_otadata mg_otadata(int fw) {
  5810. uint32_t key = mg_fwkey(fw);
  5811. struct mg_otadata od = {};
  5812. MG_INFO(("Loading %s OTA data", fw == MG_FIRMWARE_CURRENT ? "curr" : "prev"));
  5813. mg_flash_load(NULL, key, &od, sizeof(od));
  5814. // MG_DEBUG(("Loaded OTA data. fw %d, bank %d, key %p", fw, bank, key));
  5815. // mg_hexdump(&od, sizeof(od));
  5816. return od;
  5817. }
  5818. int mg_ota_status(int fw) {
  5819. struct mg_otadata od = mg_otadata(fw);
  5820. return od.status;
  5821. }
  5822. uint32_t mg_ota_crc32(int fw) {
  5823. struct mg_otadata od = mg_otadata(fw);
  5824. return od.crc32;
  5825. }
  5826. uint32_t mg_ota_timestamp(int fw) {
  5827. struct mg_otadata od = mg_otadata(fw);
  5828. return od.timestamp;
  5829. }
  5830. size_t mg_ota_size(int fw) {
  5831. struct mg_otadata od = mg_otadata(fw);
  5832. return od.size;
  5833. }
  5834. MG_IRAM bool mg_ota_commit(void) {
  5835. bool ok = true;
  5836. struct mg_otadata od = mg_otadata(MG_FIRMWARE_CURRENT);
  5837. if (od.status != MG_OTA_COMMITTED) {
  5838. od.status = MG_OTA_COMMITTED;
  5839. MG_INFO(("Committing current firmware, OD size %lu", sizeof(od)));
  5840. ok = mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &od, sizeof(od));
  5841. }
  5842. return ok;
  5843. }
  5844. bool mg_ota_rollback(void) {
  5845. MG_DEBUG(("Rolling firmware back"));
  5846. if (mg_flash_bank() == 0) {
  5847. // No dual bank support. Mark previous firmware as FIRST_BOOT
  5848. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5849. prev.status = MG_OTA_FIRST_BOOT;
  5850. return mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &prev,
  5851. sizeof(prev));
  5852. } else {
  5853. return mg_flash_swap_bank();
  5854. }
  5855. }
  5856. MG_IRAM void mg_ota_boot(void) {
  5857. MG_INFO(("Booting. Flash bank: %d", mg_flash_bank()));
  5858. struct mg_otadata curr = mg_otadata(MG_FIRMWARE_CURRENT);
  5859. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5860. if (curr.status == MG_OTA_FIRST_BOOT) {
  5861. if (prev.status == MG_OTA_UNAVAILABLE) {
  5862. MG_INFO(("Setting previous firmware state to committed"));
  5863. prev.status = MG_OTA_COMMITTED;
  5864. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_PREVIOUS), &prev, sizeof(prev));
  5865. }
  5866. curr.status = MG_OTA_UNCOMMITTED;
  5867. MG_INFO(("First boot, setting status to UNCOMMITTED"));
  5868. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &curr, sizeof(curr));
  5869. } else if (prev.status == MG_OTA_FIRST_BOOT && mg_flash_bank() == 0) {
  5870. // Swap paritions. Pray power does not disappear
  5871. size_t fs = mg_flash_size(), ss = mg_flash_sector_size();
  5872. char *partition1 = mg_flash_start();
  5873. char *partition2 = mg_flash_start() + fs / 2;
  5874. size_t ofs, max = fs / 2 - ss; // Set swap size to the whole partition
  5875. if (curr.status != MG_OTA_UNAVAILABLE &&
  5876. prev.status != MG_OTA_UNAVAILABLE) {
  5877. // We know exact sizes of both firmwares.
  5878. // Shrink swap size to the MAX(firmware1, firmware2)
  5879. size_t sz = curr.size > prev.size ? curr.size : prev.size;
  5880. if (sz > 0 && sz < max) max = sz;
  5881. }
  5882. // MG_OTA_FIRST_BOOT -> MG_OTA_UNCOMMITTED
  5883. prev.status = MG_OTA_UNCOMMITTED;
  5884. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_CURRENT, &prev,
  5885. sizeof(prev));
  5886. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &curr,
  5887. sizeof(curr));
  5888. MG_INFO(("Swapping partitions, size %u (%u sectors)", max, max / ss));
  5889. MG_INFO(("Do NOT power off..."));
  5890. mg_log_level = MG_LL_NONE;
  5891. // We use the last sector of partition2 for OTA data/config storage
  5892. // Therefore we can use last sector of partition1 for swapping
  5893. char *tmpsector = partition1 + fs / 2 - ss; // Last sector of partition1
  5894. (void) tmpsector;
  5895. for (ofs = 0; ofs < max; ofs += ss) {
  5896. // mg_flash_erase(tmpsector);
  5897. mg_flash_write(tmpsector, partition1 + ofs, ss);
  5898. // mg_flash_erase(partition1 + ofs);
  5899. mg_flash_write(partition1 + ofs, partition2 + ofs, ss);
  5900. // mg_flash_erase(partition2 + ofs);
  5901. mg_flash_write(partition2 + ofs, tmpsector, ss);
  5902. }
  5903. mg_device_reset();
  5904. }
  5905. }
  5906. #endif
  5907. #ifdef MG_ENABLE_LINES
  5908. #line 1 "src/printf.c"
  5909. #endif
  5910. size_t mg_queue_vprintf(struct mg_queue *q, const char *fmt, va_list *ap) {
  5911. size_t len = mg_snprintf(NULL, 0, fmt, ap);
  5912. char *buf;
  5913. if (len == 0 || mg_queue_book(q, &buf, len + 1) < len + 1) {
  5914. len = 0; // Nah. Not enough space
  5915. } else {
  5916. len = mg_vsnprintf((char *) buf, len + 1, fmt, ap);
  5917. mg_queue_add(q, len);
  5918. }
  5919. return len;
  5920. }
  5921. size_t mg_queue_printf(struct mg_queue *q, const char *fmt, ...) {
  5922. va_list ap;
  5923. size_t len;
  5924. va_start(ap, fmt);
  5925. len = mg_queue_vprintf(q, fmt, &ap);
  5926. va_end(ap);
  5927. return len;
  5928. }
  5929. static void mg_pfn_iobuf_private(char ch, void *param, bool expand) {
  5930. struct mg_iobuf *io = (struct mg_iobuf *) param;
  5931. if (expand && io->len + 2 > io->size) mg_iobuf_resize(io, io->len + 2);
  5932. if (io->len + 2 <= io->size) {
  5933. io->buf[io->len++] = (uint8_t) ch;
  5934. io->buf[io->len] = 0;
  5935. } else if (io->len < io->size) {
  5936. io->buf[io->len++] = 0; // Guarantee to 0-terminate
  5937. }
  5938. }
  5939. static void mg_putchar_iobuf_static(char ch, void *param) {
  5940. mg_pfn_iobuf_private(ch, param, false);
  5941. }
  5942. void mg_pfn_iobuf(char ch, void *param) {
  5943. mg_pfn_iobuf_private(ch, param, true);
  5944. }
  5945. size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap) {
  5946. struct mg_iobuf io = {(uint8_t *) buf, len, 0, 0};
  5947. size_t n = mg_vxprintf(mg_putchar_iobuf_static, &io, fmt, ap);
  5948. if (n < len) buf[n] = '\0';
  5949. return n;
  5950. }
  5951. size_t mg_snprintf(char *buf, size_t len, const char *fmt, ...) {
  5952. va_list ap;
  5953. size_t n;
  5954. va_start(ap, fmt);
  5955. n = mg_vsnprintf(buf, len, fmt, &ap);
  5956. va_end(ap);
  5957. return n;
  5958. }
  5959. char *mg_vmprintf(const char *fmt, va_list *ap) {
  5960. struct mg_iobuf io = {0, 0, 0, 256};
  5961. mg_vxprintf(mg_pfn_iobuf, &io, fmt, ap);
  5962. return (char *) io.buf;
  5963. }
  5964. char *mg_mprintf(const char *fmt, ...) {
  5965. char *s;
  5966. va_list ap;
  5967. va_start(ap, fmt);
  5968. s = mg_vmprintf(fmt, &ap);
  5969. va_end(ap);
  5970. return s;
  5971. }
  5972. void mg_pfn_stdout(char c, void *param) {
  5973. putchar(c);
  5974. (void) param;
  5975. }
  5976. static size_t print_ip4(void (*out)(char, void *), void *arg, uint8_t *p) {
  5977. return mg_xprintf(out, arg, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  5978. }
  5979. static size_t print_ip6(void (*out)(char, void *), void *arg, uint16_t *p) {
  5980. return mg_xprintf(out, arg, "[%x:%x:%x:%x:%x:%x:%x:%x]", mg_ntohs(p[0]),
  5981. mg_ntohs(p[1]), mg_ntohs(p[2]), mg_ntohs(p[3]),
  5982. mg_ntohs(p[4]), mg_ntohs(p[5]), mg_ntohs(p[6]),
  5983. mg_ntohs(p[7]));
  5984. }
  5985. size_t mg_print_ip4(void (*out)(char, void *), void *arg, va_list *ap) {
  5986. uint8_t *p = va_arg(*ap, uint8_t *);
  5987. return print_ip4(out, arg, p);
  5988. }
  5989. size_t mg_print_ip6(void (*out)(char, void *), void *arg, va_list *ap) {
  5990. uint16_t *p = va_arg(*ap, uint16_t *);
  5991. return print_ip6(out, arg, p);
  5992. }
  5993. size_t mg_print_ip(void (*out)(char, void *), void *arg, va_list *ap) {
  5994. struct mg_addr *addr = va_arg(*ap, struct mg_addr *);
  5995. if (addr->is_ip6) return print_ip6(out, arg, (uint16_t *) addr->ip);
  5996. return print_ip4(out, arg, (uint8_t *) &addr->ip);
  5997. }
  5998. size_t mg_print_ip_port(void (*out)(char, void *), void *arg, va_list *ap) {
  5999. struct mg_addr *a = va_arg(*ap, struct mg_addr *);
  6000. return mg_xprintf(out, arg, "%M:%hu", mg_print_ip, a, mg_ntohs(a->port));
  6001. }
  6002. size_t mg_print_mac(void (*out)(char, void *), void *arg, va_list *ap) {
  6003. uint8_t *p = va_arg(*ap, uint8_t *);
  6004. return mg_xprintf(out, arg, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2],
  6005. p[3], p[4], p[5]);
  6006. }
  6007. static char mg_esc(int c, bool esc) {
  6008. const char *p, *esc1 = "\b\f\n\r\t\\\"", *esc2 = "bfnrt\\\"";
  6009. for (p = esc ? esc1 : esc2; *p != '\0'; p++) {
  6010. if (*p == c) return esc ? esc2[p - esc1] : esc1[p - esc2];
  6011. }
  6012. return 0;
  6013. }
  6014. static char mg_escape(int c) {
  6015. return mg_esc(c, true);
  6016. }
  6017. static size_t qcpy(void (*out)(char, void *), void *ptr, char *buf,
  6018. size_t len) {
  6019. size_t i = 0, extra = 0;
  6020. for (i = 0; i < len && buf[i] != '\0'; i++) {
  6021. char c = mg_escape(buf[i]);
  6022. if (c) {
  6023. out('\\', ptr), out(c, ptr), extra++;
  6024. } else {
  6025. out(buf[i], ptr);
  6026. }
  6027. }
  6028. return i + extra;
  6029. }
  6030. static size_t bcpy(void (*out)(char, void *), void *arg, uint8_t *buf,
  6031. size_t len) {
  6032. size_t i, j, n = 0;
  6033. const char *t =
  6034. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6035. for (i = 0; i < len; i += 3) {
  6036. uint8_t c1 = buf[i], c2 = i + 1 < len ? buf[i + 1] : 0,
  6037. c3 = i + 2 < len ? buf[i + 2] : 0;
  6038. char tmp[4] = {t[c1 >> 2], t[(c1 & 3) << 4 | (c2 >> 4)], '=', '='};
  6039. if (i + 1 < len) tmp[2] = t[(c2 & 15) << 2 | (c3 >> 6)];
  6040. if (i + 2 < len) tmp[3] = t[c3 & 63];
  6041. for (j = 0; j < sizeof(tmp) && tmp[j] != '\0'; j++) out(tmp[j], arg);
  6042. n += j;
  6043. }
  6044. return n;
  6045. }
  6046. size_t mg_print_hex(void (*out)(char, void *), void *arg, va_list *ap) {
  6047. size_t bl = (size_t) va_arg(*ap, int);
  6048. uint8_t *p = va_arg(*ap, uint8_t *);
  6049. const char *hex = "0123456789abcdef";
  6050. size_t j;
  6051. for (j = 0; j < bl; j++) {
  6052. out(hex[(p[j] >> 4) & 0x0F], arg);
  6053. out(hex[p[j] & 0x0F], arg);
  6054. }
  6055. return 2 * bl;
  6056. }
  6057. size_t mg_print_base64(void (*out)(char, void *), void *arg, va_list *ap) {
  6058. size_t len = (size_t) va_arg(*ap, int);
  6059. uint8_t *buf = va_arg(*ap, uint8_t *);
  6060. return bcpy(out, arg, buf, len);
  6061. }
  6062. size_t mg_print_esc(void (*out)(char, void *), void *arg, va_list *ap) {
  6063. size_t len = (size_t) va_arg(*ap, int);
  6064. char *p = va_arg(*ap, char *);
  6065. if (len == 0) len = p == NULL ? 0 : strlen(p);
  6066. return qcpy(out, arg, p, len);
  6067. }
  6068. #ifdef MG_ENABLE_LINES
  6069. #line 1 "src/queue.c"
  6070. #endif
  6071. #if (defined(__GNUC__) && (__GNUC__ > 4) || \
  6072. (defined(__GNUC_MINOR__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
  6073. defined(__clang__)
  6074. #define MG_MEMORY_BARRIER() __sync_synchronize()
  6075. #elif defined(_MSC_VER) && _MSC_VER >= 1700
  6076. #define MG_MEMORY_BARRIER() MemoryBarrier()
  6077. #elif !defined(MG_MEMORY_BARRIER)
  6078. #define MG_MEMORY_BARRIER()
  6079. #endif
  6080. // Every message in a queue is prepended by a 32-bit message length (ML).
  6081. // If ML is 0, then it is the end, and reader must wrap to the beginning.
  6082. //
  6083. // Queue when q->tail <= q->head:
  6084. // |----- free -----| ML | message1 | ML | message2 | ----- free ------|
  6085. // ^ ^ ^ ^
  6086. // buf tail head len
  6087. //
  6088. // Queue when q->tail > q->head:
  6089. // | ML | message2 |----- free ------| ML | message1 | 0 |---- free ----|
  6090. // ^ ^ ^ ^
  6091. // buf head tail len
  6092. void mg_queue_init(struct mg_queue *q, char *buf, size_t size) {
  6093. q->size = size;
  6094. q->buf = buf;
  6095. q->head = q->tail = 0;
  6096. }
  6097. static size_t mg_queue_read_len(struct mg_queue *q) {
  6098. uint32_t n = 0;
  6099. MG_MEMORY_BARRIER();
  6100. memcpy(&n, q->buf + q->tail, sizeof(n));
  6101. assert(q->tail + n + sizeof(n) <= q->size);
  6102. return n;
  6103. }
  6104. static void mg_queue_write_len(struct mg_queue *q, size_t len) {
  6105. uint32_t n = (uint32_t) len;
  6106. memcpy(q->buf + q->head, &n, sizeof(n));
  6107. MG_MEMORY_BARRIER();
  6108. }
  6109. size_t mg_queue_book(struct mg_queue *q, char **buf, size_t len) {
  6110. size_t space = 0, hs = sizeof(uint32_t) * 2; // *2 is for the 0 marker
  6111. if (q->head >= q->tail && q->head + len + hs <= q->size) {
  6112. space = q->size - q->head - hs; // There is enough space
  6113. } else if (q->head >= q->tail && q->tail > hs) {
  6114. mg_queue_write_len(q, 0); // Not enough space ahead
  6115. q->head = 0; // Wrap head to the beginning
  6116. }
  6117. if (q->head + hs + len < q->tail) space = q->tail - q->head - hs;
  6118. if (buf != NULL) *buf = q->buf + q->head + sizeof(uint32_t);
  6119. return space;
  6120. }
  6121. size_t mg_queue_next(struct mg_queue *q, char **buf) {
  6122. size_t len = 0;
  6123. if (q->tail != q->head) {
  6124. len = mg_queue_read_len(q);
  6125. if (len == 0) { // Zero (head wrapped) ?
  6126. q->tail = 0; // Reset tail to the start
  6127. if (q->head > q->tail) len = mg_queue_read_len(q); // Read again
  6128. }
  6129. }
  6130. if (buf != NULL) *buf = q->buf + q->tail + sizeof(uint32_t);
  6131. assert(q->tail + len <= q->size);
  6132. return len;
  6133. }
  6134. void mg_queue_add(struct mg_queue *q, size_t len) {
  6135. assert(len > 0);
  6136. mg_queue_write_len(q, len);
  6137. assert(q->head + sizeof(uint32_t) * 2 + len <= q->size);
  6138. q->head += len + sizeof(uint32_t);
  6139. }
  6140. void mg_queue_del(struct mg_queue *q, size_t len) {
  6141. q->tail += len + sizeof(uint32_t);
  6142. assert(q->tail + sizeof(uint32_t) <= q->size);
  6143. }
  6144. #ifdef MG_ENABLE_LINES
  6145. #line 1 "src/rpc.c"
  6146. #endif
  6147. void mg_rpc_add(struct mg_rpc **head, struct mg_str method,
  6148. void (*fn)(struct mg_rpc_req *), void *fn_data) {
  6149. struct mg_rpc *rpc = (struct mg_rpc *) calloc(1, sizeof(*rpc));
  6150. if (rpc != NULL) {
  6151. rpc->method.buf = mg_mprintf("%.*s", method.len, method.buf);
  6152. rpc->method.len = method.len;
  6153. rpc->fn = fn;
  6154. rpc->fn_data = fn_data;
  6155. rpc->next = *head, *head = rpc;
  6156. }
  6157. }
  6158. void mg_rpc_del(struct mg_rpc **head, void (*fn)(struct mg_rpc_req *)) {
  6159. struct mg_rpc *r;
  6160. while ((r = *head) != NULL) {
  6161. if (r->fn == fn || fn == NULL) {
  6162. *head = r->next;
  6163. free((void *) r->method.buf);
  6164. free(r);
  6165. } else {
  6166. head = &(*head)->next;
  6167. }
  6168. }
  6169. }
  6170. static void mg_rpc_call(struct mg_rpc_req *r, struct mg_str method) {
  6171. struct mg_rpc *h = r->head == NULL ? NULL : *r->head;
  6172. while (h != NULL && !mg_match(method, h->method, NULL)) h = h->next;
  6173. if (h != NULL) {
  6174. r->rpc = h;
  6175. h->fn(r);
  6176. } else {
  6177. mg_rpc_err(r, -32601, "\"%.*s not found\"", (int) method.len, method.buf);
  6178. }
  6179. }
  6180. void mg_rpc_process(struct mg_rpc_req *r) {
  6181. int len, off = mg_json_get(r->frame, "$.method", &len);
  6182. if (off > 0 && r->frame.buf[off] == '"') {
  6183. struct mg_str method = mg_str_n(&r->frame.buf[off + 1], (size_t) len - 2);
  6184. mg_rpc_call(r, method);
  6185. } else if ((off = mg_json_get(r->frame, "$.result", &len)) > 0 ||
  6186. (off = mg_json_get(r->frame, "$.error", &len)) > 0) {
  6187. mg_rpc_call(r, mg_str("")); // JSON response! call "" method handler
  6188. } else {
  6189. mg_rpc_err(r, -32700, "%m", mg_print_esc, (int) r->frame.len,
  6190. r->frame.buf); // Invalid
  6191. }
  6192. }
  6193. void mg_rpc_vok(struct mg_rpc_req *r, const char *fmt, va_list *ap) {
  6194. int len, off = mg_json_get(r->frame, "$.id", &len);
  6195. if (off > 0) {
  6196. mg_xprintf(r->pfn, r->pfn_data, "{%m:%.*s,%m:", mg_print_esc, 0, "id", len,
  6197. &r->frame.buf[off], mg_print_esc, 0, "result");
  6198. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  6199. mg_xprintf(r->pfn, r->pfn_data, "}");
  6200. }
  6201. }
  6202. void mg_rpc_ok(struct mg_rpc_req *r, const char *fmt, ...) {
  6203. va_list ap;
  6204. va_start(ap, fmt);
  6205. mg_rpc_vok(r, fmt, &ap);
  6206. va_end(ap);
  6207. }
  6208. void mg_rpc_verr(struct mg_rpc_req *r, int code, const char *fmt, va_list *ap) {
  6209. int len, off = mg_json_get(r->frame, "$.id", &len);
  6210. mg_xprintf(r->pfn, r->pfn_data, "{");
  6211. if (off > 0) {
  6212. mg_xprintf(r->pfn, r->pfn_data, "%m:%.*s,", mg_print_esc, 0, "id", len,
  6213. &r->frame.buf[off]);
  6214. }
  6215. mg_xprintf(r->pfn, r->pfn_data, "%m:{%m:%d,%m:", mg_print_esc, 0, "error",
  6216. mg_print_esc, 0, "code", code, mg_print_esc, 0, "message");
  6217. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  6218. mg_xprintf(r->pfn, r->pfn_data, "}}");
  6219. }
  6220. void mg_rpc_err(struct mg_rpc_req *r, int code, const char *fmt, ...) {
  6221. va_list ap;
  6222. va_start(ap, fmt);
  6223. mg_rpc_verr(r, code, fmt, &ap);
  6224. va_end(ap);
  6225. }
  6226. static size_t print_methods(mg_pfn_t pfn, void *pfn_data, va_list *ap) {
  6227. struct mg_rpc *h, **head = (struct mg_rpc **) va_arg(*ap, void **);
  6228. size_t len = 0;
  6229. for (h = *head; h != NULL; h = h->next) {
  6230. if (h->method.len == 0) continue; // Ignore response handler
  6231. len += mg_xprintf(pfn, pfn_data, "%s%m", h == *head ? "" : ",",
  6232. mg_print_esc, (int) h->method.len, h->method.buf);
  6233. }
  6234. return len;
  6235. }
  6236. void mg_rpc_list(struct mg_rpc_req *r) {
  6237. mg_rpc_ok(r, "[%M]", print_methods, r->head);
  6238. }
  6239. #ifdef MG_ENABLE_LINES
  6240. #line 1 "src/sha1.c"
  6241. #endif
  6242. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  6243. /* 100% Public Domain */
  6244. union char64long16 {
  6245. unsigned char c[64];
  6246. uint32_t l[16];
  6247. };
  6248. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  6249. static uint32_t blk0(union char64long16 *block, int i) {
  6250. if (MG_BIG_ENDIAN) {
  6251. } else {
  6252. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  6253. (rol(block->l[i], 8) & 0x00FF00FF);
  6254. }
  6255. return block->l[i];
  6256. }
  6257. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  6258. #undef blk
  6259. #undef R0
  6260. #undef R1
  6261. #undef R2
  6262. #undef R3
  6263. #undef R4
  6264. #define blk(i) \
  6265. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  6266. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  6267. 1))
  6268. #define R0(v, w, x, y, z, i) \
  6269. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  6270. w = rol(w, 30);
  6271. #define R1(v, w, x, y, z, i) \
  6272. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  6273. w = rol(w, 30);
  6274. #define R2(v, w, x, y, z, i) \
  6275. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  6276. w = rol(w, 30);
  6277. #define R3(v, w, x, y, z, i) \
  6278. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  6279. w = rol(w, 30);
  6280. #define R4(v, w, x, y, z, i) \
  6281. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  6282. w = rol(w, 30);
  6283. static void mg_sha1_transform(uint32_t state[5],
  6284. const unsigned char *buffer) {
  6285. uint32_t a, b, c, d, e;
  6286. union char64long16 block[1];
  6287. memcpy(block, buffer, 64);
  6288. a = state[0];
  6289. b = state[1];
  6290. c = state[2];
  6291. d = state[3];
  6292. e = state[4];
  6293. R0(a, b, c, d, e, 0);
  6294. R0(e, a, b, c, d, 1);
  6295. R0(d, e, a, b, c, 2);
  6296. R0(c, d, e, a, b, 3);
  6297. R0(b, c, d, e, a, 4);
  6298. R0(a, b, c, d, e, 5);
  6299. R0(e, a, b, c, d, 6);
  6300. R0(d, e, a, b, c, 7);
  6301. R0(c, d, e, a, b, 8);
  6302. R0(b, c, d, e, a, 9);
  6303. R0(a, b, c, d, e, 10);
  6304. R0(e, a, b, c, d, 11);
  6305. R0(d, e, a, b, c, 12);
  6306. R0(c, d, e, a, b, 13);
  6307. R0(b, c, d, e, a, 14);
  6308. R0(a, b, c, d, e, 15);
  6309. R1(e, a, b, c, d, 16);
  6310. R1(d, e, a, b, c, 17);
  6311. R1(c, d, e, a, b, 18);
  6312. R1(b, c, d, e, a, 19);
  6313. R2(a, b, c, d, e, 20);
  6314. R2(e, a, b, c, d, 21);
  6315. R2(d, e, a, b, c, 22);
  6316. R2(c, d, e, a, b, 23);
  6317. R2(b, c, d, e, a, 24);
  6318. R2(a, b, c, d, e, 25);
  6319. R2(e, a, b, c, d, 26);
  6320. R2(d, e, a, b, c, 27);
  6321. R2(c, d, e, a, b, 28);
  6322. R2(b, c, d, e, a, 29);
  6323. R2(a, b, c, d, e, 30);
  6324. R2(e, a, b, c, d, 31);
  6325. R2(d, e, a, b, c, 32);
  6326. R2(c, d, e, a, b, 33);
  6327. R2(b, c, d, e, a, 34);
  6328. R2(a, b, c, d, e, 35);
  6329. R2(e, a, b, c, d, 36);
  6330. R2(d, e, a, b, c, 37);
  6331. R2(c, d, e, a, b, 38);
  6332. R2(b, c, d, e, a, 39);
  6333. R3(a, b, c, d, e, 40);
  6334. R3(e, a, b, c, d, 41);
  6335. R3(d, e, a, b, c, 42);
  6336. R3(c, d, e, a, b, 43);
  6337. R3(b, c, d, e, a, 44);
  6338. R3(a, b, c, d, e, 45);
  6339. R3(e, a, b, c, d, 46);
  6340. R3(d, e, a, b, c, 47);
  6341. R3(c, d, e, a, b, 48);
  6342. R3(b, c, d, e, a, 49);
  6343. R3(a, b, c, d, e, 50);
  6344. R3(e, a, b, c, d, 51);
  6345. R3(d, e, a, b, c, 52);
  6346. R3(c, d, e, a, b, 53);
  6347. R3(b, c, d, e, a, 54);
  6348. R3(a, b, c, d, e, 55);
  6349. R3(e, a, b, c, d, 56);
  6350. R3(d, e, a, b, c, 57);
  6351. R3(c, d, e, a, b, 58);
  6352. R3(b, c, d, e, a, 59);
  6353. R4(a, b, c, d, e, 60);
  6354. R4(e, a, b, c, d, 61);
  6355. R4(d, e, a, b, c, 62);
  6356. R4(c, d, e, a, b, 63);
  6357. R4(b, c, d, e, a, 64);
  6358. R4(a, b, c, d, e, 65);
  6359. R4(e, a, b, c, d, 66);
  6360. R4(d, e, a, b, c, 67);
  6361. R4(c, d, e, a, b, 68);
  6362. R4(b, c, d, e, a, 69);
  6363. R4(a, b, c, d, e, 70);
  6364. R4(e, a, b, c, d, 71);
  6365. R4(d, e, a, b, c, 72);
  6366. R4(c, d, e, a, b, 73);
  6367. R4(b, c, d, e, a, 74);
  6368. R4(a, b, c, d, e, 75);
  6369. R4(e, a, b, c, d, 76);
  6370. R4(d, e, a, b, c, 77);
  6371. R4(c, d, e, a, b, 78);
  6372. R4(b, c, d, e, a, 79);
  6373. state[0] += a;
  6374. state[1] += b;
  6375. state[2] += c;
  6376. state[3] += d;
  6377. state[4] += e;
  6378. /* Erase working structures. The order of operations is important,
  6379. * used to ensure that compiler doesn't optimize those out. */
  6380. memset(block, 0, sizeof(block));
  6381. a = b = c = d = e = 0;
  6382. (void) a;
  6383. (void) b;
  6384. (void) c;
  6385. (void) d;
  6386. (void) e;
  6387. }
  6388. void mg_sha1_init(mg_sha1_ctx *context) {
  6389. context->state[0] = 0x67452301;
  6390. context->state[1] = 0xEFCDAB89;
  6391. context->state[2] = 0x98BADCFE;
  6392. context->state[3] = 0x10325476;
  6393. context->state[4] = 0xC3D2E1F0;
  6394. context->count[0] = context->count[1] = 0;
  6395. }
  6396. void mg_sha1_update(mg_sha1_ctx *context, const unsigned char *data,
  6397. size_t len) {
  6398. size_t i, j;
  6399. j = context->count[0];
  6400. if ((context->count[0] += (uint32_t) len << 3) < j) context->count[1]++;
  6401. context->count[1] += (uint32_t) (len >> 29);
  6402. j = (j >> 3) & 63;
  6403. if ((j + len) > 63) {
  6404. memcpy(&context->buffer[j], data, (i = 64 - j));
  6405. mg_sha1_transform(context->state, context->buffer);
  6406. for (; i + 63 < len; i += 64) {
  6407. mg_sha1_transform(context->state, &data[i]);
  6408. }
  6409. j = 0;
  6410. } else
  6411. i = 0;
  6412. memcpy(&context->buffer[j], &data[i], len - i);
  6413. }
  6414. void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *context) {
  6415. unsigned i;
  6416. unsigned char finalcount[8], c;
  6417. for (i = 0; i < 8; i++) {
  6418. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  6419. ((3 - (i & 3)) * 8)) &
  6420. 255);
  6421. }
  6422. c = 0200;
  6423. mg_sha1_update(context, &c, 1);
  6424. while ((context->count[0] & 504) != 448) {
  6425. c = 0000;
  6426. mg_sha1_update(context, &c, 1);
  6427. }
  6428. mg_sha1_update(context, finalcount, 8);
  6429. for (i = 0; i < 20; i++) {
  6430. digest[i] =
  6431. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  6432. }
  6433. memset(context, '\0', sizeof(*context));
  6434. memset(&finalcount, '\0', sizeof(finalcount));
  6435. }
  6436. #ifdef MG_ENABLE_LINES
  6437. #line 1 "src/sha256.c"
  6438. #endif
  6439. // https://github.com/B-Con/crypto-algorithms
  6440. // Author: Brad Conte (brad AT bradconte.com)
  6441. // Disclaimer: This code is presented "as is" without any guarantees.
  6442. // Details: Defines the API for the corresponding SHA1 implementation.
  6443. // Copyright: public domain
  6444. #define ror(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
  6445. #define ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
  6446. #define maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
  6447. #define ep0(x) (ror(x, 2) ^ ror(x, 13) ^ ror(x, 22))
  6448. #define ep1(x) (ror(x, 6) ^ ror(x, 11) ^ ror(x, 25))
  6449. #define sig0(x) (ror(x, 7) ^ ror(x, 18) ^ ((x) >> 3))
  6450. #define sig1(x) (ror(x, 17) ^ ror(x, 19) ^ ((x) >> 10))
  6451. static const uint32_t mg_sha256_k[64] = {
  6452. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
  6453. 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  6454. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
  6455. 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  6456. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
  6457. 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  6458. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
  6459. 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  6460. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
  6461. 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  6462. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
  6463. void mg_sha256_init(mg_sha256_ctx *ctx) {
  6464. ctx->len = 0;
  6465. ctx->bits = 0;
  6466. ctx->state[0] = 0x6a09e667;
  6467. ctx->state[1] = 0xbb67ae85;
  6468. ctx->state[2] = 0x3c6ef372;
  6469. ctx->state[3] = 0xa54ff53a;
  6470. ctx->state[4] = 0x510e527f;
  6471. ctx->state[5] = 0x9b05688c;
  6472. ctx->state[6] = 0x1f83d9ab;
  6473. ctx->state[7] = 0x5be0cd19;
  6474. }
  6475. static void mg_sha256_chunk(mg_sha256_ctx *ctx) {
  6476. int i, j;
  6477. uint32_t a, b, c, d, e, f, g, h;
  6478. uint32_t m[64];
  6479. for (i = 0, j = 0; i < 16; ++i, j += 4)
  6480. m[i] = (uint32_t) (((uint32_t) ctx->buffer[j] << 24) |
  6481. ((uint32_t) ctx->buffer[j + 1] << 16) |
  6482. ((uint32_t) ctx->buffer[j + 2] << 8) |
  6483. ((uint32_t) ctx->buffer[j + 3]));
  6484. for (; i < 64; ++i)
  6485. m[i] = sig1(m[i - 2]) + m[i - 7] + sig0(m[i - 15]) + m[i - 16];
  6486. a = ctx->state[0];
  6487. b = ctx->state[1];
  6488. c = ctx->state[2];
  6489. d = ctx->state[3];
  6490. e = ctx->state[4];
  6491. f = ctx->state[5];
  6492. g = ctx->state[6];
  6493. h = ctx->state[7];
  6494. for (i = 0; i < 64; ++i) {
  6495. uint32_t t1 = h + ep1(e) + ch(e, f, g) + mg_sha256_k[i] + m[i];
  6496. uint32_t t2 = ep0(a) + maj(a, b, c);
  6497. h = g;
  6498. g = f;
  6499. f = e;
  6500. e = d + t1;
  6501. d = c;
  6502. c = b;
  6503. b = a;
  6504. a = t1 + t2;
  6505. }
  6506. ctx->state[0] += a;
  6507. ctx->state[1] += b;
  6508. ctx->state[2] += c;
  6509. ctx->state[3] += d;
  6510. ctx->state[4] += e;
  6511. ctx->state[5] += f;
  6512. ctx->state[6] += g;
  6513. ctx->state[7] += h;
  6514. }
  6515. void mg_sha256_update(mg_sha256_ctx *ctx, const unsigned char *data,
  6516. size_t len) {
  6517. size_t i;
  6518. for (i = 0; i < len; i++) {
  6519. ctx->buffer[ctx->len] = data[i];
  6520. if ((++ctx->len) == 64) {
  6521. mg_sha256_chunk(ctx);
  6522. ctx->bits += 512;
  6523. ctx->len = 0;
  6524. }
  6525. }
  6526. }
  6527. // TODO: make final reusable (remove side effects)
  6528. void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *ctx) {
  6529. uint32_t i = ctx->len;
  6530. if (i < 56) {
  6531. ctx->buffer[i++] = 0x80;
  6532. while (i < 56) {
  6533. ctx->buffer[i++] = 0x00;
  6534. }
  6535. } else {
  6536. ctx->buffer[i++] = 0x80;
  6537. while (i < 64) {
  6538. ctx->buffer[i++] = 0x00;
  6539. }
  6540. mg_sha256_chunk(ctx);
  6541. memset(ctx->buffer, 0, 56);
  6542. }
  6543. ctx->bits += ctx->len * 8;
  6544. ctx->buffer[63] = (uint8_t) ((ctx->bits) & 0xff);
  6545. ctx->buffer[62] = (uint8_t) ((ctx->bits >> 8) & 0xff);
  6546. ctx->buffer[61] = (uint8_t) ((ctx->bits >> 16) & 0xff);
  6547. ctx->buffer[60] = (uint8_t) ((ctx->bits >> 24) & 0xff);
  6548. ctx->buffer[59] = (uint8_t) ((ctx->bits >> 32) & 0xff);
  6549. ctx->buffer[58] = (uint8_t) ((ctx->bits >> 40) & 0xff);
  6550. ctx->buffer[57] = (uint8_t) ((ctx->bits >> 48) & 0xff);
  6551. ctx->buffer[56] = (uint8_t) ((ctx->bits >> 56) & 0xff);
  6552. mg_sha256_chunk(ctx);
  6553. for (i = 0; i < 4; ++i) {
  6554. digest[i] = (uint8_t) ((ctx->state[0] >> (24 - i * 8)) & 0xff);
  6555. digest[i + 4] = (uint8_t) ((ctx->state[1] >> (24 - i * 8)) & 0xff);
  6556. digest[i + 8] = (uint8_t) ((ctx->state[2] >> (24 - i * 8)) & 0xff);
  6557. digest[i + 12] = (uint8_t) ((ctx->state[3] >> (24 - i * 8)) & 0xff);
  6558. digest[i + 16] = (uint8_t) ((ctx->state[4] >> (24 - i * 8)) & 0xff);
  6559. digest[i + 20] = (uint8_t) ((ctx->state[5] >> (24 - i * 8)) & 0xff);
  6560. digest[i + 24] = (uint8_t) ((ctx->state[6] >> (24 - i * 8)) & 0xff);
  6561. digest[i + 28] = (uint8_t) ((ctx->state[7] >> (24 - i * 8)) & 0xff);
  6562. }
  6563. }
  6564. void mg_hmac_sha256(uint8_t dst[32], uint8_t *key, size_t keysz, uint8_t *data,
  6565. size_t datasz) {
  6566. mg_sha256_ctx ctx;
  6567. uint8_t k[64] = {0};
  6568. uint8_t o_pad[64], i_pad[64];
  6569. unsigned int i;
  6570. memset(i_pad, 0x36, sizeof(i_pad));
  6571. memset(o_pad, 0x5c, sizeof(o_pad));
  6572. if (keysz < 64) {
  6573. if (keysz > 0) memmove(k, key, keysz);
  6574. } else {
  6575. mg_sha256_init(&ctx);
  6576. mg_sha256_update(&ctx, key, keysz);
  6577. mg_sha256_final(k, &ctx);
  6578. }
  6579. for (i = 0; i < sizeof(k); i++) {
  6580. i_pad[i] ^= k[i];
  6581. o_pad[i] ^= k[i];
  6582. }
  6583. mg_sha256_init(&ctx);
  6584. mg_sha256_update(&ctx, i_pad, sizeof(i_pad));
  6585. mg_sha256_update(&ctx, data, datasz);
  6586. mg_sha256_final(dst, &ctx);
  6587. mg_sha256_init(&ctx);
  6588. mg_sha256_update(&ctx, o_pad, sizeof(o_pad));
  6589. mg_sha256_update(&ctx, dst, 32);
  6590. mg_sha256_final(dst, &ctx);
  6591. }
  6592. #ifdef MG_ENABLE_LINES
  6593. #line 1 "src/sntp.c"
  6594. #endif
  6595. #define SNTP_TIME_OFFSET 2208988800U // (1970 - 1900) in seconds
  6596. #define SNTP_MAX_FRAC 4294967295.0 // 2 ** 32 - 1
  6597. static int64_t gettimestamp(const uint32_t *data) {
  6598. uint32_t sec = mg_ntohl(data[0]), frac = mg_ntohl(data[1]);
  6599. if (sec) sec -= SNTP_TIME_OFFSET;
  6600. return ((int64_t) sec) * 1000 + (int64_t) (frac / SNTP_MAX_FRAC * 1000.0);
  6601. }
  6602. int64_t mg_sntp_parse(const unsigned char *buf, size_t len) {
  6603. int64_t res = -1;
  6604. int mode = len > 0 ? buf[0] & 7 : 0;
  6605. int version = len > 0 ? (buf[0] >> 3) & 7 : 0;
  6606. if (len < 48) {
  6607. MG_ERROR(("%s", "corrupt packet"));
  6608. } else if (mode != 4 && mode != 5) {
  6609. MG_ERROR(("%s", "not a server reply"));
  6610. } else if (buf[1] == 0) {
  6611. MG_ERROR(("%s", "server sent a kiss of death"));
  6612. } else if (version == 4 || version == 3) {
  6613. // int64_t ref = gettimestamp((uint32_t *) &buf[16]);
  6614. int64_t t0 = gettimestamp((uint32_t *) &buf[24]);
  6615. int64_t t1 = gettimestamp((uint32_t *) &buf[32]);
  6616. int64_t t2 = gettimestamp((uint32_t *) &buf[40]);
  6617. int64_t t3 = (int64_t) mg_millis();
  6618. int64_t delta = (t3 - t0) - (t2 - t1);
  6619. MG_VERBOSE(("%lld %lld %lld %lld delta:%lld", t0, t1, t2, t3, delta));
  6620. res = t2 + delta / 2;
  6621. } else {
  6622. MG_ERROR(("unexpected version: %d", version));
  6623. }
  6624. return res;
  6625. }
  6626. static void sntp_cb(struct mg_connection *c, int ev, void *ev_data) {
  6627. if (ev == MG_EV_READ) {
  6628. int64_t milliseconds = mg_sntp_parse(c->recv.buf, c->recv.len);
  6629. if (milliseconds > 0) {
  6630. MG_DEBUG(("%lu got time: %lld ms from epoch", c->id, milliseconds));
  6631. mg_call(c, MG_EV_SNTP_TIME, (uint64_t *) &milliseconds);
  6632. MG_VERBOSE(("%u.%u", (unsigned) (milliseconds / 1000),
  6633. (unsigned) (milliseconds % 1000)));
  6634. }
  6635. mg_iobuf_del(&c->recv, 0, c->recv.len); // Free receive buffer
  6636. } else if (ev == MG_EV_CONNECT) {
  6637. mg_sntp_request(c);
  6638. } else if (ev == MG_EV_CLOSE) {
  6639. }
  6640. (void) ev_data;
  6641. }
  6642. void mg_sntp_request(struct mg_connection *c) {
  6643. if (c->is_resolving) {
  6644. MG_ERROR(("%lu wait until resolved", c->id));
  6645. } else {
  6646. int64_t now = (int64_t) mg_millis(); // Use int64_t, for vc98
  6647. uint8_t buf[48] = {0};
  6648. uint32_t *t = (uint32_t *) &buf[40];
  6649. double frac = ((double) (now % 1000)) / 1000.0 * SNTP_MAX_FRAC;
  6650. buf[0] = (0 << 6) | (4 << 3) | 3;
  6651. t[0] = mg_htonl((uint32_t) (now / 1000) + SNTP_TIME_OFFSET);
  6652. t[1] = mg_htonl((uint32_t) frac);
  6653. mg_send(c, buf, sizeof(buf));
  6654. }
  6655. }
  6656. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url,
  6657. mg_event_handler_t fn, void *fnd) {
  6658. struct mg_connection *c = NULL;
  6659. if (url == NULL) url = "udp://time.google.com:123";
  6660. if ((c = mg_connect(mgr, url, fn, fnd)) != NULL) c->pfn = sntp_cb;
  6661. return c;
  6662. }
  6663. #ifdef MG_ENABLE_LINES
  6664. #line 1 "src/sock.c"
  6665. #endif
  6666. #if MG_ENABLE_SOCKET
  6667. #ifndef closesocket
  6668. #define closesocket(x) close(x)
  6669. #endif
  6670. #define FD(c_) ((MG_SOCKET_TYPE) (size_t) (c_)->fd)
  6671. #define S2PTR(s_) ((void *) (size_t) (s_))
  6672. #ifndef MSG_NONBLOCKING
  6673. #define MSG_NONBLOCKING 0
  6674. #endif
  6675. #ifndef AF_INET6
  6676. #define AF_INET6 10
  6677. #endif
  6678. #ifndef MG_SOCK_ERR
  6679. #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? errno : 0)
  6680. #endif
  6681. #ifndef MG_SOCK_INTR
  6682. #define MG_SOCK_INTR(fd) (fd == MG_INVALID_SOCKET && MG_SOCK_ERR(-1) == EINTR)
  6683. #endif
  6684. #ifndef MG_SOCK_PENDING
  6685. #define MG_SOCK_PENDING(errcode) \
  6686. (((errcode) < 0) && (errno == EINPROGRESS || errno == EWOULDBLOCK))
  6687. #endif
  6688. #ifndef MG_SOCK_RESET
  6689. #define MG_SOCK_RESET(errcode) \
  6690. (((errcode) < 0) && (errno == EPIPE || errno == ECONNRESET))
  6691. #endif
  6692. union usa {
  6693. struct sockaddr sa;
  6694. struct sockaddr_in sin;
  6695. #if MG_ENABLE_IPV6
  6696. struct sockaddr_in6 sin6;
  6697. #endif
  6698. };
  6699. static socklen_t tousa(struct mg_addr *a, union usa *usa) {
  6700. socklen_t len = sizeof(usa->sin);
  6701. memset(usa, 0, sizeof(*usa));
  6702. usa->sin.sin_family = AF_INET;
  6703. usa->sin.sin_port = a->port;
  6704. memcpy(&usa->sin.sin_addr, a->ip, sizeof(uint32_t));
  6705. #if MG_ENABLE_IPV6
  6706. if (a->is_ip6) {
  6707. usa->sin.sin_family = AF_INET6;
  6708. usa->sin6.sin6_port = a->port;
  6709. usa->sin6.sin6_scope_id = a->scope_id;
  6710. memcpy(&usa->sin6.sin6_addr, a->ip, sizeof(a->ip));
  6711. len = sizeof(usa->sin6);
  6712. }
  6713. #endif
  6714. return len;
  6715. }
  6716. static void tomgaddr(union usa *usa, struct mg_addr *a, bool is_ip6) {
  6717. a->is_ip6 = is_ip6;
  6718. a->port = usa->sin.sin_port;
  6719. memcpy(&a->ip, &usa->sin.sin_addr, sizeof(uint32_t));
  6720. #if MG_ENABLE_IPV6
  6721. if (is_ip6) {
  6722. memcpy(a->ip, &usa->sin6.sin6_addr, sizeof(a->ip));
  6723. a->port = usa->sin6.sin6_port;
  6724. a->scope_id = (uint8_t) usa->sin6.sin6_scope_id;
  6725. }
  6726. #endif
  6727. }
  6728. static void setlocaddr(MG_SOCKET_TYPE fd, struct mg_addr *addr) {
  6729. union usa usa;
  6730. socklen_t n = sizeof(usa);
  6731. if (getsockname(fd, &usa.sa, &n) == 0) {
  6732. tomgaddr(&usa, addr, n != sizeof(usa.sin));
  6733. }
  6734. }
  6735. static void iolog(struct mg_connection *c, char *buf, long n, bool r) {
  6736. if (n == MG_IO_WAIT) {
  6737. // Do nothing
  6738. } else if (n <= 0) {
  6739. c->is_closing = 1; // Termination. Don't call mg_error(): #1529
  6740. } else if (n > 0) {
  6741. if (c->is_hexdumping) {
  6742. MG_INFO(("\n-- %lu %M %s %M %ld", c->id, mg_print_ip_port, &c->loc,
  6743. r ? "<-" : "->", mg_print_ip_port, &c->rem, n));
  6744. mg_hexdump(buf, (size_t) n);
  6745. }
  6746. if (r) {
  6747. c->recv.len += (size_t) n;
  6748. mg_call(c, MG_EV_READ, &n);
  6749. } else {
  6750. mg_iobuf_del(&c->send, 0, (size_t) n);
  6751. // if (c->send.len == 0) mg_iobuf_resize(&c->send, 0);
  6752. if (c->send.len == 0) {
  6753. MG_EPOLL_MOD(c, 0);
  6754. }
  6755. mg_call(c, MG_EV_WRITE, &n);
  6756. }
  6757. }
  6758. }
  6759. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  6760. long n;
  6761. if (c->is_udp) {
  6762. union usa usa;
  6763. socklen_t slen = tousa(&c->rem, &usa);
  6764. n = sendto(FD(c), (char *) buf, len, 0, &usa.sa, slen);
  6765. if (n > 0) setlocaddr(FD(c), &c->loc);
  6766. } else {
  6767. n = send(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6768. }
  6769. MG_VERBOSE(("%lu %ld %d", c->id, n, MG_SOCK_ERR(n)));
  6770. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6771. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6772. if (n <= 0) return MG_IO_ERR;
  6773. return n;
  6774. }
  6775. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  6776. if (c->is_udp) {
  6777. long n = mg_io_send(c, buf, len);
  6778. MG_DEBUG(("%lu %ld %lu:%lu:%lu %ld err %d", c->id, c->fd, c->send.len,
  6779. c->recv.len, c->rtls.len, n, MG_SOCK_ERR(n)));
  6780. iolog(c, (char *) buf, n, false);
  6781. return n > 0;
  6782. } else {
  6783. return mg_iobuf_add(&c->send, c->send.len, buf, len);
  6784. }
  6785. }
  6786. static void mg_set_non_blocking_mode(MG_SOCKET_TYPE fd) {
  6787. #if defined(MG_CUSTOM_NONBLOCK)
  6788. MG_CUSTOM_NONBLOCK(fd);
  6789. #elif MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  6790. unsigned long on = 1;
  6791. ioctlsocket(fd, FIONBIO, &on);
  6792. #elif MG_ENABLE_RL
  6793. unsigned long on = 1;
  6794. ioctlsocket(fd, FIONBIO, &on);
  6795. #elif MG_ENABLE_FREERTOS_TCP
  6796. const BaseType_t off = 0;
  6797. if (setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6798. if (setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6799. #elif MG_ENABLE_LWIP
  6800. lwip_fcntl(fd, F_SETFL, O_NONBLOCK);
  6801. #elif MG_ARCH == MG_ARCH_AZURERTOS
  6802. fcntl(fd, F_SETFL, O_NONBLOCK);
  6803. #elif MG_ARCH == MG_ARCH_TIRTOS
  6804. int val = 0;
  6805. setsockopt(fd, SOL_SOCKET, SO_BLOCKING, &val, sizeof(val));
  6806. // SPRU524J section 3.3.3 page 63, SO_SNDLOWAT
  6807. int sz = sizeof(val);
  6808. getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &val, &sz);
  6809. val /= 2; // set send low-water mark at half send buffer size
  6810. setsockopt(fd, SOL_SOCKET, SO_SNDLOWAT, &val, sizeof(val));
  6811. #else
  6812. fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); // Non-blocking mode
  6813. fcntl(fd, F_SETFD, FD_CLOEXEC); // Set close-on-exec
  6814. #endif
  6815. }
  6816. bool mg_open_listener(struct mg_connection *c, const char *url) {
  6817. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6818. bool success = false;
  6819. c->loc.port = mg_htons(mg_url_port(url));
  6820. if (!mg_aton(mg_url_host(url), &c->loc)) {
  6821. MG_ERROR(("invalid listening URL: %s", url));
  6822. } else {
  6823. union usa usa;
  6824. socklen_t slen = tousa(&c->loc, &usa);
  6825. int rc, on = 1, af = c->loc.is_ip6 ? AF_INET6 : AF_INET;
  6826. int type = strncmp(url, "udp:", 4) == 0 ? SOCK_DGRAM : SOCK_STREAM;
  6827. int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP;
  6828. (void) on;
  6829. if ((fd = socket(af, type, proto)) == MG_INVALID_SOCKET) {
  6830. MG_ERROR(("socket: %d", MG_SOCK_ERR(-1)));
  6831. #if defined(SO_EXCLUSIVEADDRUSE)
  6832. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  6833. (char *) &on, sizeof(on))) != 0) {
  6834. // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE"
  6835. MG_ERROR(("setsockopt(SO_EXCLUSIVEADDRUSE): %d %d", on, MG_SOCK_ERR(rc)));
  6836. #elif defined(SO_REUSEADDR) && (!defined(LWIP_SOCKET) || SO_REUSE)
  6837. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on,
  6838. sizeof(on))) != 0) {
  6839. // 1. SO_REUSEADDR semantics on UNIX and Windows is different. On
  6840. // Windows, SO_REUSEADDR allows to bind a socket to a port without error
  6841. // even if the port is already open by another program. This is not the
  6842. // behavior SO_REUSEADDR was designed for, and leads to hard-to-track
  6843. // failure scenarios.
  6844. //
  6845. // 2. For LWIP, SO_REUSEADDR should be explicitly enabled by defining
  6846. // SO_REUSE = 1 in lwipopts.h, otherwise the code below will compile but
  6847. // won't work! (setsockopt will return EINVAL)
  6848. MG_ERROR(("setsockopt(SO_REUSEADDR): %d", MG_SOCK_ERR(rc)));
  6849. #endif
  6850. #if MG_IPV6_V6ONLY
  6851. // Bind only to the V6 address, not V4 address on this port
  6852. } else if (c->loc.is_ip6 &&
  6853. (rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &on,
  6854. sizeof(on))) != 0) {
  6855. // See #2089. Allow to bind v4 and v6 sockets on the same port
  6856. MG_ERROR(("setsockopt(IPV6_V6ONLY): %d", MG_SOCK_ERR(rc)));
  6857. #endif
  6858. } else if ((rc = bind(fd, &usa.sa, slen)) != 0) {
  6859. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6860. } else if ((type == SOCK_STREAM &&
  6861. (rc = listen(fd, MG_SOCK_LISTEN_BACKLOG_SIZE)) != 0)) {
  6862. // NOTE(lsm): FreeRTOS uses backlog value as a connection limit
  6863. // In case port was set to 0, get the real port number
  6864. MG_ERROR(("listen: %d", MG_SOCK_ERR(rc)));
  6865. } else {
  6866. setlocaddr(fd, &c->loc);
  6867. mg_set_non_blocking_mode(fd);
  6868. c->fd = S2PTR(fd);
  6869. MG_EPOLL_ADD(c);
  6870. success = true;
  6871. }
  6872. }
  6873. if (success == false && fd != MG_INVALID_SOCKET) closesocket(fd);
  6874. return success;
  6875. }
  6876. static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
  6877. long n = 0;
  6878. if (c->is_udp) {
  6879. union usa usa;
  6880. socklen_t slen = tousa(&c->rem, &usa);
  6881. n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
  6882. if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
  6883. } else {
  6884. n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6885. }
  6886. MG_VERBOSE(("%lu %ld %d", c->id, n, MG_SOCK_ERR(n)));
  6887. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6888. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6889. if (n <= 0) return MG_IO_ERR;
  6890. return n;
  6891. }
  6892. static bool ioalloc(struct mg_connection *c, struct mg_iobuf *io) {
  6893. bool res = false;
  6894. if (io->len >= MG_MAX_RECV_SIZE) {
  6895. mg_error(c, "MG_MAX_RECV_SIZE");
  6896. } else if (io->size <= io->len &&
  6897. !mg_iobuf_resize(io, io->size + MG_IO_SIZE)) {
  6898. mg_error(c, "OOM");
  6899. } else {
  6900. res = true;
  6901. }
  6902. return res;
  6903. }
  6904. // NOTE(lsm): do only one iteration of reads, cause some systems
  6905. // (e.g. FreeRTOS stack) return 0 instead of -1/EWOULDBLOCK when no data
  6906. static void read_conn(struct mg_connection *c) {
  6907. if (ioalloc(c, &c->recv)) {
  6908. char *buf = (char *) &c->recv.buf[c->recv.len];
  6909. size_t len = c->recv.size - c->recv.len;
  6910. long n = -1;
  6911. if (c->is_tls) {
  6912. if (!ioalloc(c, &c->rtls)) return;
  6913. n = recv_raw(c, (char *) &c->rtls.buf[c->rtls.len],
  6914. c->rtls.size - c->rtls.len);
  6915. if (n == MG_IO_ERR && c->rtls.len == 0) {
  6916. // Close only if we have fully drained both raw (rtls) and TLS buffers
  6917. c->is_closing = 1;
  6918. } else {
  6919. if (n > 0) c->rtls.len += (size_t) n;
  6920. if (c->is_tls_hs) mg_tls_handshake(c);
  6921. n = c->is_tls_hs ? (long) MG_IO_WAIT : mg_tls_recv(c, buf, len);
  6922. }
  6923. } else {
  6924. n = recv_raw(c, buf, len);
  6925. }
  6926. MG_DEBUG(("%lu %ld %lu:%lu:%lu %ld err %d", c->id, c->fd, c->send.len,
  6927. c->recv.len, c->rtls.len, n, MG_SOCK_ERR(n)));
  6928. iolog(c, buf, n, true);
  6929. }
  6930. }
  6931. static void write_conn(struct mg_connection *c) {
  6932. char *buf = (char *) c->send.buf;
  6933. size_t len = c->send.len;
  6934. long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len);
  6935. MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6936. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6937. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6938. iolog(c, buf, n, false);
  6939. }
  6940. static void close_conn(struct mg_connection *c) {
  6941. if (FD(c) != MG_INVALID_SOCKET) {
  6942. #if MG_ENABLE_EPOLL
  6943. epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_DEL, FD(c), NULL);
  6944. #endif
  6945. closesocket(FD(c));
  6946. #if MG_ENABLE_FREERTOS_TCP
  6947. FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL);
  6948. #endif
  6949. }
  6950. mg_close_conn(c);
  6951. }
  6952. static void connect_conn(struct mg_connection *c) {
  6953. union usa usa;
  6954. socklen_t n = sizeof(usa);
  6955. // Use getpeername() to test whether we have connected
  6956. if (getpeername(FD(c), &usa.sa, &n) == 0) {
  6957. c->is_connecting = 0;
  6958. setlocaddr(FD(c), &c->loc);
  6959. mg_call(c, MG_EV_CONNECT, NULL);
  6960. MG_EPOLL_MOD(c, 0);
  6961. if (c->is_tls_hs) mg_tls_handshake(c);
  6962. } else {
  6963. mg_error(c, "socket error");
  6964. }
  6965. }
  6966. static void setsockopts(struct mg_connection *c) {
  6967. #if MG_ENABLE_FREERTOS_TCP || MG_ARCH == MG_ARCH_AZURERTOS || \
  6968. MG_ARCH == MG_ARCH_TIRTOS
  6969. (void) c;
  6970. #else
  6971. int on = 1;
  6972. #if !defined(SOL_TCP)
  6973. #define SOL_TCP IPPROTO_TCP
  6974. #endif
  6975. if (setsockopt(FD(c), SOL_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) != 0)
  6976. (void) 0;
  6977. if (setsockopt(FD(c), SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) !=
  6978. 0)
  6979. (void) 0;
  6980. #endif
  6981. }
  6982. void mg_connect_resolved(struct mg_connection *c) {
  6983. int type = c->is_udp ? SOCK_DGRAM : SOCK_STREAM;
  6984. int rc, af = c->rem.is_ip6 ? AF_INET6 : AF_INET; // c->rem has resolved IP
  6985. c->fd = S2PTR(socket(af, type, 0)); // Create outbound socket
  6986. c->is_resolving = 0; // Clear resolving flag
  6987. if (FD(c) == MG_INVALID_SOCKET) {
  6988. mg_error(c, "socket(): %d", MG_SOCK_ERR(-1));
  6989. } else if (c->is_udp) {
  6990. MG_EPOLL_ADD(c);
  6991. #if MG_ARCH == MG_ARCH_TIRTOS
  6992. union usa usa; // TI-RTOS NDK requires binding to receive on UDP sockets
  6993. socklen_t slen = tousa(&c->loc, &usa);
  6994. if ((rc = bind(c->fd, &usa.sa, slen)) != 0)
  6995. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6996. #endif
  6997. setlocaddr(FD(c), &c->loc);
  6998. mg_call(c, MG_EV_RESOLVE, NULL);
  6999. mg_call(c, MG_EV_CONNECT, NULL);
  7000. } else {
  7001. union usa usa;
  7002. socklen_t slen = tousa(&c->rem, &usa);
  7003. mg_set_non_blocking_mode(FD(c));
  7004. setsockopts(c);
  7005. MG_EPOLL_ADD(c);
  7006. mg_call(c, MG_EV_RESOLVE, NULL);
  7007. rc = connect(FD(c), &usa.sa, slen); // Attempt to connect
  7008. if (rc == 0) { // Success
  7009. setlocaddr(FD(c), &c->loc);
  7010. mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user
  7011. } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake
  7012. MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem));
  7013. c->is_connecting = 1;
  7014. } else {
  7015. mg_error(c, "connect: %d", MG_SOCK_ERR(rc));
  7016. }
  7017. }
  7018. }
  7019. static MG_SOCKET_TYPE raccept(MG_SOCKET_TYPE sock, union usa *usa,
  7020. socklen_t *len) {
  7021. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  7022. do {
  7023. memset(usa, 0, sizeof(*usa));
  7024. fd = accept(sock, &usa->sa, len);
  7025. } while (MG_SOCK_INTR(fd));
  7026. return fd;
  7027. }
  7028. static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) {
  7029. struct mg_connection *c = NULL;
  7030. union usa usa;
  7031. socklen_t sa_len = sizeof(usa);
  7032. MG_SOCKET_TYPE fd = raccept(FD(lsn), &usa, &sa_len);
  7033. if (fd == MG_INVALID_SOCKET) {
  7034. #if MG_ARCH == MG_ARCH_AZURERTOS || defined(__ECOS)
  7035. // AzureRTOS, in non-block socket mode can mark listening socket readable
  7036. // even it is not. See comment for 'select' func implementation in
  7037. // nx_bsd.c That's not an error, just should try later
  7038. if (errno != EAGAIN)
  7039. #endif
  7040. MG_ERROR(("%lu accept failed, errno %d", lsn->id, MG_SOCK_ERR(-1)));
  7041. #if (MG_ARCH != MG_ARCH_WIN32) && !MG_ENABLE_FREERTOS_TCP && \
  7042. (MG_ARCH != MG_ARCH_TIRTOS) && !MG_ENABLE_POLL && !MG_ENABLE_EPOLL
  7043. } else if ((long) fd >= FD_SETSIZE) {
  7044. MG_ERROR(("%ld > %ld", (long) fd, (long) FD_SETSIZE));
  7045. closesocket(fd);
  7046. #endif
  7047. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  7048. MG_ERROR(("%lu OOM", lsn->id));
  7049. closesocket(fd);
  7050. } else {
  7051. tomgaddr(&usa, &c->rem, sa_len != sizeof(usa.sin));
  7052. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  7053. c->fd = S2PTR(fd);
  7054. MG_EPOLL_ADD(c);
  7055. mg_set_non_blocking_mode(FD(c));
  7056. setsockopts(c);
  7057. c->is_accepted = 1;
  7058. c->is_hexdumping = lsn->is_hexdumping;
  7059. c->loc = lsn->loc;
  7060. c->pfn = lsn->pfn;
  7061. c->pfn_data = lsn->pfn_data;
  7062. c->fn = lsn->fn;
  7063. c->fn_data = lsn->fn_data;
  7064. MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port,
  7065. &c->rem, mg_print_ip_port, &c->loc));
  7066. mg_call(c, MG_EV_OPEN, NULL);
  7067. mg_call(c, MG_EV_ACCEPT, NULL);
  7068. }
  7069. }
  7070. static bool can_read(const struct mg_connection *c) {
  7071. return c->is_full == false;
  7072. }
  7073. static bool can_write(const struct mg_connection *c) {
  7074. return c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0);
  7075. }
  7076. static bool skip_iotest(const struct mg_connection *c) {
  7077. return (c->is_closing || c->is_resolving || FD(c) == MG_INVALID_SOCKET) ||
  7078. (can_read(c) == false && can_write(c) == false);
  7079. }
  7080. static void mg_iotest(struct mg_mgr *mgr, int ms) {
  7081. #if MG_ENABLE_FREERTOS_TCP
  7082. struct mg_connection *c;
  7083. for (c = mgr->conns; c != NULL; c = c->next) {
  7084. c->is_readable = c->is_writable = 0;
  7085. if (skip_iotest(c)) continue;
  7086. if (can_read(c))
  7087. FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_READ | eSELECT_EXCEPT);
  7088. if (can_write(c)) FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_WRITE);
  7089. if (c->is_closing) ms = 1;
  7090. }
  7091. FreeRTOS_select(mgr->ss, pdMS_TO_TICKS(ms));
  7092. for (c = mgr->conns; c != NULL; c = c->next) {
  7093. EventBits_t bits = FreeRTOS_FD_ISSET(c->fd, mgr->ss);
  7094. c->is_readable = bits & (eSELECT_READ | eSELECT_EXCEPT) ? 1U : 0;
  7095. c->is_writable = bits & eSELECT_WRITE ? 1U : 0;
  7096. if (c->fd != MG_INVALID_SOCKET)
  7097. FreeRTOS_FD_CLR(c->fd, mgr->ss,
  7098. eSELECT_READ | eSELECT_EXCEPT | eSELECT_WRITE);
  7099. }
  7100. #elif MG_ENABLE_EPOLL
  7101. size_t max = 1;
  7102. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7103. c->is_readable = c->is_writable = 0;
  7104. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) ms = 1, c->is_readable = 1;
  7105. if (can_write(c)) MG_EPOLL_MOD(c, 1);
  7106. if (c->is_closing) ms = 1;
  7107. max++;
  7108. }
  7109. struct epoll_event *evs = (struct epoll_event *) alloca(max * sizeof(evs[0]));
  7110. int n = epoll_wait(mgr->epoll_fd, evs, (int) max, ms);
  7111. for (int i = 0; i < n; i++) {
  7112. struct mg_connection *c = (struct mg_connection *) evs[i].data.ptr;
  7113. if (evs[i].events & EPOLLERR) {
  7114. mg_error(c, "socket error");
  7115. } else if (c->is_readable == 0) {
  7116. bool rd = evs[i].events & (EPOLLIN | EPOLLHUP);
  7117. bool wr = evs[i].events & EPOLLOUT;
  7118. c->is_readable = can_read(c) && rd ? 1U : 0;
  7119. c->is_writable = can_write(c) && wr ? 1U : 0;
  7120. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7121. }
  7122. }
  7123. (void) skip_iotest;
  7124. #elif MG_ENABLE_POLL
  7125. nfds_t n = 0;
  7126. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) n++;
  7127. struct pollfd *fds = (struct pollfd *) alloca(n * sizeof(fds[0]));
  7128. memset(fds, 0, n * sizeof(fds[0]));
  7129. n = 0;
  7130. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7131. c->is_readable = c->is_writable = 0;
  7132. if (skip_iotest(c)) {
  7133. // Socket not valid, ignore
  7134. } else if (c->rtls.len > 0 || mg_tls_pending(c) > 0) {
  7135. ms = 1; // Don't wait if TLS is ready
  7136. } else {
  7137. fds[n].fd = FD(c);
  7138. if (can_read(c)) fds[n].events |= POLLIN;
  7139. if (can_write(c)) fds[n].events |= POLLOUT;
  7140. if (c->is_closing) ms = 1;
  7141. n++;
  7142. }
  7143. }
  7144. // MG_INFO(("poll n=%d ms=%d", (int) n, ms));
  7145. if (poll(fds, n, ms) < 0) {
  7146. #if MG_ARCH == MG_ARCH_WIN32
  7147. if (n == 0) Sleep(ms); // On Windows, poll fails if no sockets
  7148. #endif
  7149. memset(fds, 0, n * sizeof(fds[0]));
  7150. }
  7151. n = 0;
  7152. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  7153. if (skip_iotest(c)) {
  7154. // Socket not valid, ignore
  7155. } else if (c->rtls.len > 0 || mg_tls_pending(c) > 0) {
  7156. c->is_readable = 1;
  7157. } else {
  7158. if (fds[n].revents & POLLERR) {
  7159. mg_error(c, "socket error");
  7160. } else {
  7161. c->is_readable =
  7162. (unsigned) (fds[n].revents & (POLLIN | POLLHUP) ? 1 : 0);
  7163. c->is_writable = (unsigned) (fds[n].revents & POLLOUT ? 1 : 0);
  7164. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7165. }
  7166. n++;
  7167. }
  7168. }
  7169. #else
  7170. struct timeval tv = {ms / 1000, (ms % 1000) * 1000}, tv_zero = {0, 0}, *tvp;
  7171. struct mg_connection *c;
  7172. fd_set rset, wset, eset;
  7173. MG_SOCKET_TYPE maxfd = 0;
  7174. int rc;
  7175. FD_ZERO(&rset);
  7176. FD_ZERO(&wset);
  7177. FD_ZERO(&eset);
  7178. tvp = ms < 0 ? NULL : &tv;
  7179. for (c = mgr->conns; c != NULL; c = c->next) {
  7180. c->is_readable = c->is_writable = 0;
  7181. if (skip_iotest(c)) continue;
  7182. FD_SET(FD(c), &eset);
  7183. if (can_read(c)) FD_SET(FD(c), &rset);
  7184. if (can_write(c)) FD_SET(FD(c), &wset);
  7185. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) tvp = &tv_zero;
  7186. if (FD(c) > maxfd) maxfd = FD(c);
  7187. if (c->is_closing) ms = 1;
  7188. }
  7189. if ((rc = select((int) maxfd + 1, &rset, &wset, &eset, tvp)) < 0) {
  7190. #if MG_ARCH == MG_ARCH_WIN32
  7191. if (maxfd == 0) Sleep(ms); // On Windows, select fails if no sockets
  7192. #else
  7193. MG_ERROR(("select: %d %d", rc, MG_SOCK_ERR(rc)));
  7194. #endif
  7195. FD_ZERO(&rset);
  7196. FD_ZERO(&wset);
  7197. FD_ZERO(&eset);
  7198. }
  7199. for (c = mgr->conns; c != NULL; c = c->next) {
  7200. if (FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &eset)) {
  7201. mg_error(c, "socket error");
  7202. } else {
  7203. c->is_readable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &rset);
  7204. c->is_writable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &wset);
  7205. if (c->rtls.len > 0 || mg_tls_pending(c) > 0) c->is_readable = 1;
  7206. }
  7207. }
  7208. #endif
  7209. }
  7210. static bool mg_socketpair(MG_SOCKET_TYPE sp[2], union usa usa[2]) {
  7211. socklen_t n = sizeof(usa[0].sin);
  7212. bool success = false;
  7213. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7214. (void) memset(&usa[0], 0, sizeof(usa[0]));
  7215. usa[0].sin.sin_family = AF_INET;
  7216. *(uint32_t *) &usa->sin.sin_addr = mg_htonl(0x7f000001U); // 127.0.0.1
  7217. usa[1] = usa[0];
  7218. if ((sp[0] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  7219. (sp[1] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  7220. bind(sp[0], &usa[0].sa, n) == 0 && //
  7221. bind(sp[1], &usa[1].sa, n) == 0 && //
  7222. getsockname(sp[0], &usa[0].sa, &n) == 0 && //
  7223. getsockname(sp[1], &usa[1].sa, &n) == 0 && //
  7224. connect(sp[0], &usa[1].sa, n) == 0 && //
  7225. connect(sp[1], &usa[0].sa, n) == 0) { //
  7226. success = true;
  7227. }
  7228. if (!success) {
  7229. if (sp[0] != MG_INVALID_SOCKET) closesocket(sp[0]);
  7230. if (sp[1] != MG_INVALID_SOCKET) closesocket(sp[1]);
  7231. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7232. }
  7233. return success;
  7234. }
  7235. // mg_wakeup() event handler
  7236. static void wufn(struct mg_connection *c, int ev, void *ev_data) {
  7237. if (ev == MG_EV_READ) {
  7238. unsigned long *id = (unsigned long *) c->recv.buf;
  7239. // MG_INFO(("Got data"));
  7240. // mg_hexdump(c->recv.buf, c->recv.len);
  7241. if (c->recv.len >= sizeof(*id)) {
  7242. struct mg_connection *t;
  7243. for (t = c->mgr->conns; t != NULL; t = t->next) {
  7244. if (t->id == *id) {
  7245. struct mg_str data = mg_str_n((char *) c->recv.buf + sizeof(*id),
  7246. c->recv.len - sizeof(*id));
  7247. mg_call(t, MG_EV_WAKEUP, &data);
  7248. }
  7249. }
  7250. }
  7251. c->recv.len = 0; // Consume received data
  7252. } else if (ev == MG_EV_CLOSE) {
  7253. closesocket(c->mgr->pipe); // When we're closing, close the other
  7254. c->mgr->pipe = MG_INVALID_SOCKET; // side of the socketpair, too
  7255. }
  7256. (void) ev_data;
  7257. }
  7258. bool mg_wakeup_init(struct mg_mgr *mgr) {
  7259. bool ok = false;
  7260. if (mgr->pipe == MG_INVALID_SOCKET) {
  7261. union usa usa[2];
  7262. MG_SOCKET_TYPE sp[2] = {MG_INVALID_SOCKET, MG_INVALID_SOCKET};
  7263. struct mg_connection *c = NULL;
  7264. if (!mg_socketpair(sp, usa)) {
  7265. MG_ERROR(("Cannot create socket pair"));
  7266. } else if ((c = mg_wrapfd(mgr, (int) sp[1], wufn, NULL)) == NULL) {
  7267. closesocket(sp[0]);
  7268. closesocket(sp[1]);
  7269. sp[0] = sp[1] = MG_INVALID_SOCKET;
  7270. } else {
  7271. tomgaddr(&usa[0], &c->rem, false);
  7272. MG_DEBUG(("%lu %p pipe %lu", c->id, c->fd, (unsigned long) sp[0]));
  7273. mgr->pipe = sp[0];
  7274. ok = true;
  7275. }
  7276. }
  7277. return ok;
  7278. }
  7279. bool mg_wakeup(struct mg_mgr *mgr, unsigned long conn_id, const void *buf,
  7280. size_t len) {
  7281. if (mgr->pipe != MG_INVALID_SOCKET && conn_id > 0) {
  7282. char *extended_buf = (char *) alloca(len + sizeof(conn_id));
  7283. memcpy(extended_buf, &conn_id, sizeof(conn_id));
  7284. memcpy(extended_buf + sizeof(conn_id), buf, len);
  7285. send(mgr->pipe, extended_buf, len + sizeof(conn_id), MSG_NONBLOCKING);
  7286. return true;
  7287. }
  7288. return false;
  7289. }
  7290. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  7291. struct mg_connection *c, *tmp;
  7292. uint64_t now;
  7293. mg_iotest(mgr, ms);
  7294. now = mg_millis();
  7295. mg_timer_poll(&mgr->timers, now);
  7296. for (c = mgr->conns; c != NULL; c = tmp) {
  7297. bool is_resp = c->is_resp;
  7298. tmp = c->next;
  7299. mg_call(c, MG_EV_POLL, &now);
  7300. if (is_resp && !c->is_resp) {
  7301. long n = 0;
  7302. mg_call(c, MG_EV_READ, &n);
  7303. }
  7304. MG_VERBOSE(("%lu %c%c %c%c%c%c%c %lu %lu", c->id,
  7305. c->is_readable ? 'r' : '-', c->is_writable ? 'w' : '-',
  7306. c->is_tls ? 'T' : 't', c->is_connecting ? 'C' : 'c',
  7307. c->is_tls_hs ? 'H' : 'h', c->is_resolving ? 'R' : 'r',
  7308. c->is_closing ? 'C' : 'c', mg_tls_pending(c), c->rtls.len));
  7309. if (c->is_resolving || c->is_closing) {
  7310. // Do nothing
  7311. } else if (c->is_listening && c->is_udp == 0) {
  7312. if (c->is_readable) accept_conn(mgr, c);
  7313. } else if (c->is_connecting) {
  7314. if (c->is_readable || c->is_writable) connect_conn(c);
  7315. //} else if (c->is_tls_hs) {
  7316. // if ((c->is_readable || c->is_writable)) mg_tls_handshake(c);
  7317. } else {
  7318. if (c->is_readable) read_conn(c);
  7319. if (c->is_writable) write_conn(c);
  7320. }
  7321. if (c->is_draining && c->send.len == 0) c->is_closing = 1;
  7322. if (c->is_closing) close_conn(c);
  7323. }
  7324. }
  7325. #endif
  7326. #ifdef MG_ENABLE_LINES
  7327. #line 1 "src/ssi.c"
  7328. #endif
  7329. #ifndef MG_MAX_SSI_DEPTH
  7330. #define MG_MAX_SSI_DEPTH 5
  7331. #endif
  7332. #ifndef MG_SSI_BUFSIZ
  7333. #define MG_SSI_BUFSIZ 1024
  7334. #endif
  7335. #if MG_ENABLE_SSI
  7336. static char *mg_ssi(const char *path, const char *root, int depth) {
  7337. struct mg_iobuf b = {NULL, 0, 0, MG_IO_SIZE};
  7338. FILE *fp = fopen(path, "rb");
  7339. if (fp != NULL) {
  7340. char buf[MG_SSI_BUFSIZ], arg[sizeof(buf)];
  7341. int ch, intag = 0;
  7342. size_t len = 0;
  7343. buf[0] = arg[0] = '\0';
  7344. while ((ch = fgetc(fp)) != EOF) {
  7345. if (intag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  7346. buf[len++] = (char) (ch & 0xff);
  7347. buf[len] = '\0';
  7348. if (sscanf(buf, "<!--#include file=\"%[^\"]", arg)) {
  7349. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10],
  7350. *p = (char *) path + strlen(path), *data;
  7351. while (p > path && p[-1] != MG_DIRSEP && p[-1] != '/') p--;
  7352. mg_snprintf(tmp, sizeof(tmp), "%.*s%s", (int) (p - path), path, 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: file=%s error or too deep", path, arg));
  7359. }
  7360. } else if (sscanf(buf, "<!--#include virtual=\"%[^\"]", arg)) {
  7361. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10], *data;
  7362. mg_snprintf(tmp, sizeof(tmp), "%s%s", root, arg);
  7363. if (depth < MG_MAX_SSI_DEPTH &&
  7364. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  7365. mg_iobuf_add(&b, b.len, data, strlen(data));
  7366. free(data);
  7367. } else {
  7368. MG_ERROR(("%s: virtual=%s error or too deep", path, arg));
  7369. }
  7370. } else {
  7371. // Unknown SSI tag
  7372. MG_ERROR(("Unknown SSI tag: %.*s", (int) len, buf));
  7373. mg_iobuf_add(&b, b.len, buf, len);
  7374. }
  7375. intag = 0;
  7376. len = 0;
  7377. } else if (ch == '<') {
  7378. intag = 1;
  7379. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  7380. len = 0;
  7381. buf[len++] = (char) (ch & 0xff);
  7382. } else if (intag) {
  7383. if (len == 5 && strncmp(buf, "<!--#", 5) != 0) {
  7384. intag = 0;
  7385. } else if (len >= sizeof(buf) - 2) {
  7386. MG_ERROR(("%s: SSI tag is too large", path));
  7387. len = 0;
  7388. }
  7389. buf[len++] = (char) (ch & 0xff);
  7390. } else {
  7391. buf[len++] = (char) (ch & 0xff);
  7392. if (len >= sizeof(buf)) {
  7393. mg_iobuf_add(&b, b.len, buf, len);
  7394. len = 0;
  7395. }
  7396. }
  7397. }
  7398. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  7399. if (b.len > 0) mg_iobuf_add(&b, b.len, "", 1); // nul-terminate
  7400. fclose(fp);
  7401. }
  7402. (void) depth;
  7403. (void) root;
  7404. return (char *) b.buf;
  7405. }
  7406. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  7407. const char *fullpath) {
  7408. const char *headers = "Content-Type: text/html; charset=utf-8\r\n";
  7409. char *data = mg_ssi(fullpath, root, 0);
  7410. mg_http_reply(c, 200, headers, "%s", data == NULL ? "" : data);
  7411. free(data);
  7412. }
  7413. #else
  7414. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  7415. const char *fullpath) {
  7416. mg_http_reply(c, 501, NULL, "SSI not enabled");
  7417. (void) root, (void) fullpath;
  7418. }
  7419. #endif
  7420. #ifdef MG_ENABLE_LINES
  7421. #line 1 "src/str.c"
  7422. #endif
  7423. struct mg_str mg_str_s(const char *s) {
  7424. struct mg_str str = {(char *) s, s == NULL ? 0 : strlen(s)};
  7425. return str;
  7426. }
  7427. struct mg_str mg_str_n(const char *s, size_t n) {
  7428. struct mg_str str = {(char *) s, n};
  7429. return str;
  7430. }
  7431. static int mg_tolc(char c) {
  7432. return (c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c;
  7433. }
  7434. int mg_casecmp(const char *s1, const char *s2) {
  7435. int diff = 0;
  7436. do {
  7437. int c = mg_tolc(*s1++), d = mg_tolc(*s2++);
  7438. diff = c - d;
  7439. } while (diff == 0 && s1[-1] != '\0');
  7440. return diff;
  7441. }
  7442. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  7443. size_t i = 0;
  7444. while (i < str1.len && i < str2.len) {
  7445. int c1 = str1.buf[i];
  7446. int c2 = str2.buf[i];
  7447. if (c1 < c2) return -1;
  7448. if (c1 > c2) return 1;
  7449. i++;
  7450. }
  7451. if (i < str1.len) return 1;
  7452. if (i < str2.len) return -1;
  7453. return 0;
  7454. }
  7455. int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2) {
  7456. size_t i = 0;
  7457. while (i < str1.len && i < str2.len) {
  7458. int c1 = mg_tolc(str1.buf[i]);
  7459. int c2 = mg_tolc(str2.buf[i]);
  7460. if (c1 < c2) return -1;
  7461. if (c1 > c2) return 1;
  7462. i++;
  7463. }
  7464. if (i < str1.len) return 1;
  7465. if (i < str2.len) return -1;
  7466. return 0;
  7467. }
  7468. bool mg_match(struct mg_str s, struct mg_str p, struct mg_str *caps) {
  7469. size_t i = 0, j = 0, ni = 0, nj = 0;
  7470. if (caps) caps->buf = NULL, caps->len = 0;
  7471. while (i < p.len || j < s.len) {
  7472. if (i < p.len && j < s.len && (p.buf[i] == '?' || s.buf[j] == p.buf[i])) {
  7473. if (caps == NULL) {
  7474. } else if (p.buf[i] == '?') {
  7475. caps->buf = &s.buf[j], caps->len = 1; // Finalize `?` cap
  7476. caps++, caps->buf = NULL, caps->len = 0; // Init next cap
  7477. } else if (caps->buf != NULL && caps->len == 0) {
  7478. caps->len = (size_t) (&s.buf[j] - caps->buf); // Finalize current cap
  7479. caps++, caps->len = 0, caps->buf = NULL; // Init next cap
  7480. }
  7481. i++, j++;
  7482. } else if (i < p.len && (p.buf[i] == '*' || p.buf[i] == '#')) {
  7483. if (caps && !caps->buf) caps->len = 0, caps->buf = &s.buf[j]; // Init cap
  7484. ni = i++, nj = j + 1;
  7485. } else if (nj > 0 && nj <= s.len && (p.buf[ni] == '#' || s.buf[j] != '/')) {
  7486. i = ni, j = nj;
  7487. if (caps && caps->buf == NULL && caps->len == 0) {
  7488. caps--, caps->len = 0; // Restart previous cap
  7489. }
  7490. } else {
  7491. return false;
  7492. }
  7493. }
  7494. if (caps && caps->buf && caps->len == 0) {
  7495. caps->len = (size_t) (&s.buf[j] - caps->buf);
  7496. }
  7497. return true;
  7498. }
  7499. bool mg_span(struct mg_str s, struct mg_str *a, struct mg_str *b, char sep) {
  7500. if (s.len == 0 || s.buf == NULL) {
  7501. return false; // Empty string, nothing to span - fail
  7502. } else {
  7503. size_t len = 0;
  7504. while (len < s.len && s.buf[len] != sep) len++; // Find separator
  7505. if (a) *a = mg_str_n(s.buf, len); // Init a
  7506. if (b) *b = mg_str_n(s.buf + len, s.len - len); // Init b
  7507. if (b && len < s.len) b->buf++, b->len--; // Skip separator
  7508. return true;
  7509. }
  7510. }
  7511. bool mg_str_to_num(struct mg_str str, int base, void *val, size_t val_len) {
  7512. size_t i = 0, ndigits = 0;
  7513. uint64_t max = val_len == sizeof(uint8_t) ? 0xFF
  7514. : val_len == sizeof(uint16_t) ? 0xFFFF
  7515. : val_len == sizeof(uint32_t) ? 0xFFFFFFFF
  7516. : (uint64_t) ~0;
  7517. uint64_t result = 0;
  7518. if (max == (uint64_t) ~0 && val_len != sizeof(uint64_t)) return false;
  7519. if (base == 0 && str.len >= 2) {
  7520. if (str.buf[i] == '0') {
  7521. i++;
  7522. base = str.buf[i] == 'b' ? 2 : str.buf[i] == 'x' ? 16 : 10;
  7523. if (base != 10) ++i;
  7524. } else {
  7525. base = 10;
  7526. }
  7527. }
  7528. switch (base) {
  7529. case 2:
  7530. while (i < str.len && (str.buf[i] == '0' || str.buf[i] == '1')) {
  7531. uint64_t digit = (uint64_t) (str.buf[i] - '0');
  7532. if (result > max/2) return false; // Overflow
  7533. result *= 2;
  7534. if (result > max - digit) return false; // Overflow
  7535. result += digit;
  7536. i++, ndigits++;
  7537. }
  7538. break;
  7539. case 10:
  7540. while (i < str.len && str.buf[i] >= '0' && str.buf[i] <= '9') {
  7541. uint64_t digit = (uint64_t) (str.buf[i] - '0');
  7542. if (result > max/10) return false; // Overflow
  7543. result *= 10;
  7544. if (result > max - digit) return false; // Overflow
  7545. result += digit;
  7546. i++, ndigits++;
  7547. }
  7548. break;
  7549. case 16:
  7550. while (i < str.len) {
  7551. char c = str.buf[i];
  7552. uint64_t digit = (c >= '0' && c <= '9') ? (uint64_t) (c - '0')
  7553. : (c >= 'A' && c <= 'F') ? (uint64_t) (c - '7')
  7554. : (c >= 'a' && c <= 'f') ? (uint64_t) (c - 'W')
  7555. : (uint64_t) ~0;
  7556. if (digit == (uint64_t) ~0) break;
  7557. if (result > max/16) return false; // Overflow
  7558. result *= 16;
  7559. if (result > max - digit) return false; // Overflow
  7560. result += digit;
  7561. i++, ndigits++;
  7562. }
  7563. break;
  7564. default:
  7565. return false;
  7566. }
  7567. if (ndigits == 0) return false;
  7568. if (i != str.len) return false;
  7569. if (val_len == 1) {
  7570. *((uint8_t *) val) = (uint8_t) result;
  7571. } else if (val_len == 2) {
  7572. *((uint16_t *) val) = (uint16_t) result;
  7573. } else if (val_len == 4) {
  7574. *((uint32_t *) val) = (uint32_t) result;
  7575. } else {
  7576. *((uint64_t *) val) = (uint64_t) result;
  7577. }
  7578. return true;
  7579. }
  7580. #ifdef MG_ENABLE_LINES
  7581. #line 1 "src/timer.c"
  7582. #endif
  7583. #define MG_TIMER_CALLED 4
  7584. void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
  7585. unsigned flags, void (*fn)(void *), void *arg) {
  7586. t->id = 0, t->period_ms = ms, t->expire = 0;
  7587. t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
  7588. *head = t;
  7589. }
  7590. void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
  7591. while (*head && *head != t) head = &(*head)->next;
  7592. if (*head) *head = t->next;
  7593. }
  7594. // t: expiration time, prd: period, now: current time. Return true if expired
  7595. bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
  7596. if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
  7597. if (*t == 0) *t = now + prd; // Firt poll? Set expiration
  7598. if (*t > now) return false; // Not expired yet, return
  7599. *t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
  7600. return true; // Expired, return true
  7601. }
  7602. void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
  7603. struct mg_timer *t, *tmp;
  7604. for (t = *head; t != NULL; t = tmp) {
  7605. bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
  7606. !(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
  7607. bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
  7608. tmp = t->next;
  7609. if (!once && !expired) continue;
  7610. if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
  7611. t->fn(t->arg);
  7612. }
  7613. t->flags |= MG_TIMER_CALLED;
  7614. }
  7615. }
  7616. #ifdef MG_ENABLE_LINES
  7617. #line 1 "src/tls_aes128.c"
  7618. #endif
  7619. /******************************************************************************
  7620. *
  7621. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7622. *
  7623. * This is a simple and straightforward implementation of the AES Rijndael
  7624. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7625. * of this work was correctness & accuracy. It is written in 'C' without any
  7626. * particular focus upon optimization or speed. It should be endian (memory
  7627. * byte order) neutral since the few places that care are handled explicitly.
  7628. *
  7629. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7630. *
  7631. * It is intended for general purpose use, but was written in support of GRC's
  7632. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7633. *
  7634. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7635. *
  7636. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7637. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7638. *
  7639. *******************************************************************************/
  7640. /******************************************************************************/
  7641. #define AES_DECRYPTION 1 // whether AES decryption is supported
  7642. /******************************************************************************/
  7643. #define MG_ENCRYPT 1 // specify whether we're encrypting
  7644. #define MG_DECRYPT 0 // or decrypting
  7645. #if MG_TLS == MG_TLS_BUILTIN
  7646. /******************************************************************************
  7647. * AES_INIT_KEYGEN_TABLES : MUST be called once before any AES use
  7648. ******************************************************************************/
  7649. static void aes_init_keygen_tables(void);
  7650. /******************************************************************************
  7651. * AES_SETKEY : called to expand the key for encryption or decryption
  7652. ******************************************************************************/
  7653. static int aes_setkey(aes_context *ctx, // pointer to context
  7654. int mode, // 1 or 0 for Encrypt/Decrypt
  7655. const uchar *key, // AES input key
  7656. uint keysize); // size in bytes (must be 16, 24, 32 for
  7657. // 128, 192 or 256-bit keys respectively)
  7658. // returns 0 for success
  7659. /******************************************************************************
  7660. * AES_CIPHER : called to encrypt or decrypt ONE 128-bit block of data
  7661. ******************************************************************************/
  7662. static int aes_cipher(aes_context *ctx, // pointer to context
  7663. const uchar input[16], // 128-bit block to en/decipher
  7664. uchar output[16]); // 128-bit output result block
  7665. // returns 0 for success
  7666. /******************************************************************************
  7667. * GCM_CONTEXT : GCM context / holds keytables, instance data, and AES ctx
  7668. ******************************************************************************/
  7669. typedef struct {
  7670. int mode; // cipher direction: encrypt/decrypt
  7671. uint64_t len; // cipher data length processed so far
  7672. uint64_t add_len; // total add data length
  7673. uint64_t HL[16]; // precalculated lo-half HTable
  7674. uint64_t HH[16]; // precalculated hi-half HTable
  7675. uchar base_ectr[16]; // first counter-mode cipher output for tag
  7676. uchar y[16]; // the current cipher-input IV|Counter value
  7677. uchar buf[16]; // buf working value
  7678. aes_context aes_ctx; // cipher context used
  7679. } gcm_context;
  7680. /******************************************************************************
  7681. * GCM_SETKEY : sets the GCM (and AES) keying material for use
  7682. ******************************************************************************/
  7683. static int gcm_setkey(
  7684. gcm_context *ctx, // caller-provided context ptr
  7685. const uchar *key, // pointer to cipher key
  7686. const uint keysize // size in bytes (must be 16, 24, 32 for
  7687. // 128, 192 or 256-bit keys respectively)
  7688. ); // returns 0 for success
  7689. /******************************************************************************
  7690. *
  7691. * GCM_CRYPT_AND_TAG
  7692. *
  7693. * This either encrypts or decrypts the user-provided data and, either
  7694. * way, generates an authentication tag of the requested length. It must be
  7695. * called with a GCM context whose key has already been set with GCM_SETKEY.
  7696. *
  7697. * The user would typically call this explicitly to ENCRYPT a buffer of data
  7698. * and optional associated data, and produce its an authentication tag.
  7699. *
  7700. * To reverse the process the user would typically call the companion
  7701. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  7702. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  7703. * to perform its decryption and tag generation, which it then compares.
  7704. *
  7705. ******************************************************************************/
  7706. static int gcm_crypt_and_tag(
  7707. gcm_context *ctx, // gcm context with key already setup
  7708. int mode, // cipher direction: MG_ENCRYPT (1) or MG_DECRYPT (0)
  7709. const uchar *iv, // pointer to the 12-byte initialization vector
  7710. size_t iv_len, // byte length if the IV. should always be 12
  7711. const uchar *add, // pointer to the non-ciphered additional data
  7712. size_t add_len, // byte length of the additional AEAD data
  7713. const uchar *input, // pointer to the cipher data source
  7714. uchar *output, // pointer to the cipher data destination
  7715. size_t length, // byte length of the cipher data
  7716. uchar *tag, // pointer to the tag to be generated
  7717. size_t tag_len); // byte length of the tag to be generated
  7718. /******************************************************************************
  7719. *
  7720. * GCM_START
  7721. *
  7722. * Given a user-provided GCM context, this initializes it, sets the encryption
  7723. * mode, and preprocesses the initialization vector and additional AEAD data.
  7724. *
  7725. ******************************************************************************/
  7726. static int gcm_start(
  7727. gcm_context *ctx, // pointer to user-provided GCM context
  7728. int mode, // MG_ENCRYPT (1) or MG_DECRYPT (0)
  7729. const uchar *iv, // pointer to initialization vector
  7730. size_t iv_len, // IV length in bytes (should == 12)
  7731. const uchar *add, // pointer to additional AEAD data (NULL if none)
  7732. size_t add_len); // length of additional AEAD data (bytes)
  7733. /******************************************************************************
  7734. *
  7735. * GCM_UPDATE
  7736. *
  7737. * This is called once or more to process bulk plaintext or ciphertext data.
  7738. * We give this some number of bytes of input and it returns the same number
  7739. * of output bytes. If called multiple times (which is fine) all but the final
  7740. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  7741. * have a partial block length of < 128 bits.)
  7742. *
  7743. ******************************************************************************/
  7744. static int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  7745. size_t length, // length, in bytes, of data to process
  7746. const uchar *input, // pointer to source data
  7747. uchar *output); // pointer to destination data
  7748. /******************************************************************************
  7749. *
  7750. * GCM_FINISH
  7751. *
  7752. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  7753. * It performs the final GHASH to produce the resulting authentication TAG.
  7754. *
  7755. ******************************************************************************/
  7756. static int gcm_finish(
  7757. gcm_context *ctx, // pointer to user-provided GCM context
  7758. uchar *tag, // ptr to tag buffer - NULL if tag_len = 0
  7759. size_t tag_len); // length, in bytes, of the tag-receiving buf
  7760. /******************************************************************************
  7761. *
  7762. * GCM_ZERO_CTX
  7763. *
  7764. * The GCM context contains both the GCM context and the AES context.
  7765. * This includes keying and key-related material which is security-
  7766. * sensitive, so it MUST be zeroed after use. This function does that.
  7767. *
  7768. ******************************************************************************/
  7769. static void gcm_zero_ctx(gcm_context *ctx);
  7770. /******************************************************************************
  7771. *
  7772. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7773. *
  7774. * This is a simple and straightforward implementation of the AES Rijndael
  7775. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7776. * of this work was correctness & accuracy. It is written in 'C' without any
  7777. * particular focus upon optimization or speed. It should be endian (memory
  7778. * byte order) neutral since the few places that care are handled explicitly.
  7779. *
  7780. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7781. *
  7782. * It is intended for general purpose use, but was written in support of GRC's
  7783. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7784. *
  7785. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7786. *
  7787. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7788. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7789. *
  7790. *******************************************************************************/
  7791. static int aes_tables_inited = 0; // run-once flag for performing key
  7792. // expasion table generation (see below)
  7793. /*
  7794. * The following static local tables must be filled-in before the first use of
  7795. * the GCM or AES ciphers. They are used for the AES key expansion/scheduling
  7796. * and once built are read-only and thread safe. The "gcm_initialize" function
  7797. * must be called once during system initialization to populate these arrays
  7798. * for subsequent use by the AES key scheduler. If they have not been built
  7799. * before attempted use, an error will be returned to the caller.
  7800. *
  7801. * NOTE: GCM Encryption/Decryption does NOT REQUIRE AES decryption. Since
  7802. * GCM uses AES in counter-mode, where the AES cipher output is XORed with
  7803. * the GCM input, we ONLY NEED AES encryption. Thus, to save space AES
  7804. * decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.
  7805. */
  7806. // We always need our forward tables
  7807. static uchar FSb[256]; // Forward substitution box (FSb)
  7808. static uint32_t FT0[256]; // Forward key schedule assembly tables
  7809. static uint32_t FT1[256];
  7810. static uint32_t FT2[256];
  7811. static uint32_t FT3[256];
  7812. #if AES_DECRYPTION // We ONLY need reverse for decryption
  7813. static uchar RSb[256]; // Reverse substitution box (RSb)
  7814. static uint32_t RT0[256]; // Reverse key schedule assembly tables
  7815. static uint32_t RT1[256];
  7816. static uint32_t RT2[256];
  7817. static uint32_t RT3[256];
  7818. #endif /* AES_DECRYPTION */
  7819. static uint32_t RCON[10]; // AES round constants
  7820. /*
  7821. * Platform Endianness Neutralizing Load and Store Macro definitions
  7822. * AES wants platform-neutral Little Endian (LE) byte ordering
  7823. */
  7824. #define GET_UINT32_LE(n, b, i) \
  7825. { \
  7826. (n) = ((uint32_t) (b)[(i)]) | ((uint32_t) (b)[(i) + 1] << 8) | \
  7827. ((uint32_t) (b)[(i) + 2] << 16) | ((uint32_t) (b)[(i) + 3] << 24); \
  7828. }
  7829. #define PUT_UINT32_LE(n, b, i) \
  7830. { \
  7831. (b)[(i)] = (uchar) ((n)); \
  7832. (b)[(i) + 1] = (uchar) ((n) >> 8); \
  7833. (b)[(i) + 2] = (uchar) ((n) >> 16); \
  7834. (b)[(i) + 3] = (uchar) ((n) >> 24); \
  7835. }
  7836. /*
  7837. * AES forward and reverse encryption round processing macros
  7838. */
  7839. #define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7840. { \
  7841. X0 = *RK++ ^ FT0[(Y0) & 0xFF] ^ FT1[(Y1 >> 8) & 0xFF] ^ \
  7842. FT2[(Y2 >> 16) & 0xFF] ^ FT3[(Y3 >> 24) & 0xFF]; \
  7843. \
  7844. X1 = *RK++ ^ FT0[(Y1) & 0xFF] ^ FT1[(Y2 >> 8) & 0xFF] ^ \
  7845. FT2[(Y3 >> 16) & 0xFF] ^ FT3[(Y0 >> 24) & 0xFF]; \
  7846. \
  7847. X2 = *RK++ ^ FT0[(Y2) & 0xFF] ^ FT1[(Y3 >> 8) & 0xFF] ^ \
  7848. FT2[(Y0 >> 16) & 0xFF] ^ FT3[(Y1 >> 24) & 0xFF]; \
  7849. \
  7850. X3 = *RK++ ^ FT0[(Y3) & 0xFF] ^ FT1[(Y0 >> 8) & 0xFF] ^ \
  7851. FT2[(Y1 >> 16) & 0xFF] ^ FT3[(Y2 >> 24) & 0xFF]; \
  7852. }
  7853. #define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7854. { \
  7855. X0 = *RK++ ^ RT0[(Y0) & 0xFF] ^ RT1[(Y3 >> 8) & 0xFF] ^ \
  7856. RT2[(Y2 >> 16) & 0xFF] ^ RT3[(Y1 >> 24) & 0xFF]; \
  7857. \
  7858. X1 = *RK++ ^ RT0[(Y1) & 0xFF] ^ RT1[(Y0 >> 8) & 0xFF] ^ \
  7859. RT2[(Y3 >> 16) & 0xFF] ^ RT3[(Y2 >> 24) & 0xFF]; \
  7860. \
  7861. X2 = *RK++ ^ RT0[(Y2) & 0xFF] ^ RT1[(Y1 >> 8) & 0xFF] ^ \
  7862. RT2[(Y0 >> 16) & 0xFF] ^ RT3[(Y3 >> 24) & 0xFF]; \
  7863. \
  7864. X3 = *RK++ ^ RT0[(Y3) & 0xFF] ^ RT1[(Y2 >> 8) & 0xFF] ^ \
  7865. RT2[(Y1 >> 16) & 0xFF] ^ RT3[(Y0 >> 24) & 0xFF]; \
  7866. }
  7867. /*
  7868. * These macros improve the readability of the key
  7869. * generation initialization code by collapsing
  7870. * repetitive common operations into logical pieces.
  7871. */
  7872. #define ROTL8(x) ((x << 8) & 0xFFFFFFFF) | (x >> 24)
  7873. #define XTIME(x) ((x << 1) ^ ((x & 0x80) ? 0x1B : 0x00))
  7874. #define MUL(x, y) ((x && y) ? pow[(log[x] + log[y]) % 255] : 0)
  7875. #define MIX(x, y) \
  7876. { \
  7877. y = ((y << 1) | (y >> 7)) & 0xFF; \
  7878. x ^= y; \
  7879. }
  7880. #define CPY128 \
  7881. { \
  7882. *RK++ = *SK++; \
  7883. *RK++ = *SK++; \
  7884. *RK++ = *SK++; \
  7885. *RK++ = *SK++; \
  7886. }
  7887. /******************************************************************************
  7888. *
  7889. * AES_INIT_KEYGEN_TABLES
  7890. *
  7891. * Fills the AES key expansion tables allocated above with their static
  7892. * data. This is not "per key" data, but static system-wide read-only
  7893. * table data. THIS FUNCTION IS NOT THREAD SAFE. It must be called once
  7894. * at system initialization to setup the tables for all subsequent use.
  7895. *
  7896. ******************************************************************************/
  7897. void aes_init_keygen_tables(void) {
  7898. int i, x, y, z; // general purpose iteration and computation locals
  7899. int pow[256];
  7900. int log[256];
  7901. if (aes_tables_inited) return;
  7902. // fill the 'pow' and 'log' tables over GF(2^8)
  7903. for (i = 0, x = 1; i < 256; i++) {
  7904. pow[i] = x;
  7905. log[x] = i;
  7906. x = (x ^ XTIME(x)) & 0xFF;
  7907. }
  7908. // compute the round constants
  7909. for (i = 0, x = 1; i < 10; i++) {
  7910. RCON[i] = (uint32_t) x;
  7911. x = XTIME(x) & 0xFF;
  7912. }
  7913. // fill the forward and reverse substitution boxes
  7914. FSb[0x00] = 0x63;
  7915. #if AES_DECRYPTION // whether AES decryption is supported
  7916. RSb[0x63] = 0x00;
  7917. #endif /* AES_DECRYPTION */
  7918. for (i = 1; i < 256; i++) {
  7919. x = y = pow[255 - log[i]];
  7920. MIX(x, y);
  7921. MIX(x, y);
  7922. MIX(x, y);
  7923. MIX(x, y);
  7924. FSb[i] = (uchar) (x ^= 0x63);
  7925. #if AES_DECRYPTION // whether AES decryption is supported
  7926. RSb[x] = (uchar) i;
  7927. #endif /* AES_DECRYPTION */
  7928. }
  7929. // generate the forward and reverse key expansion tables
  7930. for (i = 0; i < 256; i++) {
  7931. x = FSb[i];
  7932. y = XTIME(x) & 0xFF;
  7933. z = (y ^ x) & 0xFF;
  7934. FT0[i] = ((uint32_t) y) ^ ((uint32_t) x << 8) ^ ((uint32_t) x << 16) ^
  7935. ((uint32_t) z << 24);
  7936. FT1[i] = ROTL8(FT0[i]);
  7937. FT2[i] = ROTL8(FT1[i]);
  7938. FT3[i] = ROTL8(FT2[i]);
  7939. #if AES_DECRYPTION // whether AES decryption is supported
  7940. x = RSb[i];
  7941. RT0[i] = ((uint32_t) MUL(0x0E, x)) ^ ((uint32_t) MUL(0x09, x) << 8) ^
  7942. ((uint32_t) MUL(0x0D, x) << 16) ^ ((uint32_t) MUL(0x0B, x) << 24);
  7943. RT1[i] = ROTL8(RT0[i]);
  7944. RT2[i] = ROTL8(RT1[i]);
  7945. RT3[i] = ROTL8(RT2[i]);
  7946. #endif /* AES_DECRYPTION */
  7947. }
  7948. aes_tables_inited = 1; // flag that the tables have been generated
  7949. } // to permit subsequent use of the AES cipher
  7950. /******************************************************************************
  7951. *
  7952. * AES_SET_ENCRYPTION_KEY
  7953. *
  7954. * This is called by 'aes_setkey' when we're establishing a key for
  7955. * subsequent encryption. We give it a pointer to the encryption
  7956. * context, a pointer to the key, and the key's length in bytes.
  7957. * Valid lengths are: 16, 24 or 32 bytes (128, 192, 256 bits).
  7958. *
  7959. ******************************************************************************/
  7960. static int aes_set_encryption_key(aes_context *ctx, const uchar *key,
  7961. uint keysize) {
  7962. uint i; // general purpose iteration local
  7963. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7964. for (i = 0; i < (keysize >> 2); i++) {
  7965. GET_UINT32_LE(RK[i], key, i << 2);
  7966. }
  7967. switch (ctx->rounds) {
  7968. case 10:
  7969. for (i = 0; i < 10; i++, RK += 4) {
  7970. RK[4] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[3] >> 8) & 0xFF]) ^
  7971. ((uint32_t) FSb[(RK[3] >> 16) & 0xFF] << 8) ^
  7972. ((uint32_t) FSb[(RK[3] >> 24) & 0xFF] << 16) ^
  7973. ((uint32_t) FSb[(RK[3]) & 0xFF] << 24);
  7974. RK[5] = RK[1] ^ RK[4];
  7975. RK[6] = RK[2] ^ RK[5];
  7976. RK[7] = RK[3] ^ RK[6];
  7977. }
  7978. break;
  7979. case 12:
  7980. for (i = 0; i < 8; i++, RK += 6) {
  7981. RK[6] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[5] >> 8) & 0xFF]) ^
  7982. ((uint32_t) FSb[(RK[5] >> 16) & 0xFF] << 8) ^
  7983. ((uint32_t) FSb[(RK[5] >> 24) & 0xFF] << 16) ^
  7984. ((uint32_t) FSb[(RK[5]) & 0xFF] << 24);
  7985. RK[7] = RK[1] ^ RK[6];
  7986. RK[8] = RK[2] ^ RK[7];
  7987. RK[9] = RK[3] ^ RK[8];
  7988. RK[10] = RK[4] ^ RK[9];
  7989. RK[11] = RK[5] ^ RK[10];
  7990. }
  7991. break;
  7992. case 14:
  7993. for (i = 0; i < 7; i++, RK += 8) {
  7994. RK[8] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[7] >> 8) & 0xFF]) ^
  7995. ((uint32_t) FSb[(RK[7] >> 16) & 0xFF] << 8) ^
  7996. ((uint32_t) FSb[(RK[7] >> 24) & 0xFF] << 16) ^
  7997. ((uint32_t) FSb[(RK[7]) & 0xFF] << 24);
  7998. RK[9] = RK[1] ^ RK[8];
  7999. RK[10] = RK[2] ^ RK[9];
  8000. RK[11] = RK[3] ^ RK[10];
  8001. RK[12] = RK[4] ^ ((uint32_t) FSb[(RK[11]) & 0xFF]) ^
  8002. ((uint32_t) FSb[(RK[11] >> 8) & 0xFF] << 8) ^
  8003. ((uint32_t) FSb[(RK[11] >> 16) & 0xFF] << 16) ^
  8004. ((uint32_t) FSb[(RK[11] >> 24) & 0xFF] << 24);
  8005. RK[13] = RK[5] ^ RK[12];
  8006. RK[14] = RK[6] ^ RK[13];
  8007. RK[15] = RK[7] ^ RK[14];
  8008. }
  8009. break;
  8010. default:
  8011. return -1;
  8012. }
  8013. return (0);
  8014. }
  8015. #if AES_DECRYPTION // whether AES decryption is supported
  8016. /******************************************************************************
  8017. *
  8018. * AES_SET_DECRYPTION_KEY
  8019. *
  8020. * This is called by 'aes_setkey' when we're establishing a
  8021. * key for subsequent decryption. We give it a pointer to
  8022. * the encryption context, a pointer to the key, and the key's
  8023. * length in bits. Valid lengths are: 128, 192, or 256 bits.
  8024. *
  8025. ******************************************************************************/
  8026. static int aes_set_decryption_key(aes_context *ctx, const uchar *key,
  8027. uint keysize) {
  8028. int i, j;
  8029. aes_context cty; // a calling aes context for set_encryption_key
  8030. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  8031. uint32_t *SK;
  8032. int ret;
  8033. cty.rounds = ctx->rounds; // initialize our local aes context
  8034. cty.rk = cty.buf; // round count and key buf pointer
  8035. if ((ret = aes_set_encryption_key(&cty, key, keysize)) != 0) return (ret);
  8036. SK = cty.rk + cty.rounds * 4;
  8037. CPY128 // copy a 128-bit block from *SK to *RK
  8038. for (i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8) {
  8039. for (j = 0; j < 4; j++, SK++) {
  8040. *RK++ = RT0[FSb[(*SK) & 0xFF]] ^ RT1[FSb[(*SK >> 8) & 0xFF]] ^
  8041. RT2[FSb[(*SK >> 16) & 0xFF]] ^ RT3[FSb[(*SK >> 24) & 0xFF]];
  8042. }
  8043. }
  8044. CPY128 // copy a 128-bit block from *SK to *RK
  8045. memset(&cty, 0, sizeof(aes_context)); // clear local aes context
  8046. return (0);
  8047. }
  8048. #endif /* AES_DECRYPTION */
  8049. /******************************************************************************
  8050. *
  8051. * AES_SETKEY
  8052. *
  8053. * Invoked to establish the key schedule for subsequent encryption/decryption
  8054. *
  8055. ******************************************************************************/
  8056. static int aes_setkey(aes_context *ctx, // AES context provided by our caller
  8057. int mode, // ENCRYPT or DECRYPT flag
  8058. const uchar *key, // pointer to the key
  8059. uint keysize) // key length in bytes
  8060. {
  8061. // since table initialization is not thread safe, we could either add
  8062. // system-specific mutexes and init the AES key generation tables on
  8063. // demand, or ask the developer to simply call "gcm_initialize" once during
  8064. // application startup before threading begins. That's what we choose.
  8065. if (!aes_tables_inited) return (-1); // fail the call when not inited.
  8066. ctx->mode = mode; // capture the key type we're creating
  8067. ctx->rk = ctx->buf; // initialize our round key pointer
  8068. switch (keysize) // set the rounds count based upon the keysize
  8069. {
  8070. case 16:
  8071. ctx->rounds = 10;
  8072. break; // 16-byte, 128-bit key
  8073. case 24:
  8074. ctx->rounds = 12;
  8075. break; // 24-byte, 192-bit key
  8076. case 32:
  8077. ctx->rounds = 14;
  8078. break; // 32-byte, 256-bit key
  8079. default:
  8080. return (-1);
  8081. }
  8082. #if AES_DECRYPTION
  8083. if (mode == MG_DECRYPT) // expand our key for encryption or decryption
  8084. return (aes_set_decryption_key(ctx, key, keysize));
  8085. else /* MG_ENCRYPT */
  8086. #endif /* AES_DECRYPTION */
  8087. return (aes_set_encryption_key(ctx, key, keysize));
  8088. }
  8089. /******************************************************************************
  8090. *
  8091. * AES_CIPHER
  8092. *
  8093. * Perform AES encryption and decryption.
  8094. * The AES context will have been setup with the encryption mode
  8095. * and all keying information appropriate for the task.
  8096. *
  8097. ******************************************************************************/
  8098. static int aes_cipher(aes_context *ctx, const uchar input[16],
  8099. uchar output[16]) {
  8100. int i;
  8101. uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; // general purpose locals
  8102. RK = ctx->rk;
  8103. GET_UINT32_LE(X0, input, 0);
  8104. X0 ^= *RK++; // load our 128-bit
  8105. GET_UINT32_LE(X1, input, 4);
  8106. X1 ^= *RK++; // input buffer in a storage
  8107. GET_UINT32_LE(X2, input, 8);
  8108. X2 ^= *RK++; // memory endian-neutral way
  8109. GET_UINT32_LE(X3, input, 12);
  8110. X3 ^= *RK++;
  8111. #if AES_DECRYPTION // whether AES decryption is supported
  8112. if (ctx->mode == MG_DECRYPT) {
  8113. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  8114. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8115. AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  8116. }
  8117. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8118. X0 = *RK++ ^ ((uint32_t) RSb[(Y0) & 0xFF]) ^
  8119. ((uint32_t) RSb[(Y3 >> 8) & 0xFF] << 8) ^
  8120. ((uint32_t) RSb[(Y2 >> 16) & 0xFF] << 16) ^
  8121. ((uint32_t) RSb[(Y1 >> 24) & 0xFF] << 24);
  8122. X1 = *RK++ ^ ((uint32_t) RSb[(Y1) & 0xFF]) ^
  8123. ((uint32_t) RSb[(Y0 >> 8) & 0xFF] << 8) ^
  8124. ((uint32_t) RSb[(Y3 >> 16) & 0xFF] << 16) ^
  8125. ((uint32_t) RSb[(Y2 >> 24) & 0xFF] << 24);
  8126. X2 = *RK++ ^ ((uint32_t) RSb[(Y2) & 0xFF]) ^
  8127. ((uint32_t) RSb[(Y1 >> 8) & 0xFF] << 8) ^
  8128. ((uint32_t) RSb[(Y0 >> 16) & 0xFF] << 16) ^
  8129. ((uint32_t) RSb[(Y3 >> 24) & 0xFF] << 24);
  8130. X3 = *RK++ ^ ((uint32_t) RSb[(Y3) & 0xFF]) ^
  8131. ((uint32_t) RSb[(Y2 >> 8) & 0xFF] << 8) ^
  8132. ((uint32_t) RSb[(Y1 >> 16) & 0xFF] << 16) ^
  8133. ((uint32_t) RSb[(Y0 >> 24) & 0xFF] << 24);
  8134. } else /* MG_ENCRYPT */
  8135. {
  8136. #endif /* AES_DECRYPTION */
  8137. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  8138. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8139. AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  8140. }
  8141. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  8142. X0 = *RK++ ^ ((uint32_t) FSb[(Y0) & 0xFF]) ^
  8143. ((uint32_t) FSb[(Y1 >> 8) & 0xFF] << 8) ^
  8144. ((uint32_t) FSb[(Y2 >> 16) & 0xFF] << 16) ^
  8145. ((uint32_t) FSb[(Y3 >> 24) & 0xFF] << 24);
  8146. X1 = *RK++ ^ ((uint32_t) FSb[(Y1) & 0xFF]) ^
  8147. ((uint32_t) FSb[(Y2 >> 8) & 0xFF] << 8) ^
  8148. ((uint32_t) FSb[(Y3 >> 16) & 0xFF] << 16) ^
  8149. ((uint32_t) FSb[(Y0 >> 24) & 0xFF] << 24);
  8150. X2 = *RK++ ^ ((uint32_t) FSb[(Y2) & 0xFF]) ^
  8151. ((uint32_t) FSb[(Y3 >> 8) & 0xFF] << 8) ^
  8152. ((uint32_t) FSb[(Y0 >> 16) & 0xFF] << 16) ^
  8153. ((uint32_t) FSb[(Y1 >> 24) & 0xFF] << 24);
  8154. X3 = *RK++ ^ ((uint32_t) FSb[(Y3) & 0xFF]) ^
  8155. ((uint32_t) FSb[(Y0 >> 8) & 0xFF] << 8) ^
  8156. ((uint32_t) FSb[(Y1 >> 16) & 0xFF] << 16) ^
  8157. ((uint32_t) FSb[(Y2 >> 24) & 0xFF] << 24);
  8158. #if AES_DECRYPTION // whether AES decryption is supported
  8159. }
  8160. #endif /* AES_DECRYPTION */
  8161. PUT_UINT32_LE(X0, output, 0);
  8162. PUT_UINT32_LE(X1, output, 4);
  8163. PUT_UINT32_LE(X2, output, 8);
  8164. PUT_UINT32_LE(X3, output, 12);
  8165. return (0);
  8166. }
  8167. /* end of aes.c */
  8168. /******************************************************************************
  8169. *
  8170. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  8171. *
  8172. * This is a simple and straightforward implementation of AES-GCM authenticated
  8173. * encryption. The focus of this work was correctness & accuracy. It is written
  8174. * in straight 'C' without any particular focus upon optimization or speed. It
  8175. * should be endian (memory byte order) neutral since the few places that care
  8176. * are handled explicitly.
  8177. *
  8178. * This implementation of AES-GCM was created by Steven M. Gibson of GRC.com.
  8179. *
  8180. * It is intended for general purpose use, but was written in support of GRC's
  8181. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  8182. *
  8183. * See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  8184. * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/
  8185. * gcm/gcm-revised-spec.pdf
  8186. *
  8187. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  8188. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  8189. *
  8190. *******************************************************************************/
  8191. /******************************************************************************
  8192. * ==== IMPLEMENTATION WARNING ====
  8193. *
  8194. * This code was developed for use within SQRL's fixed environmnent. Thus, it
  8195. * is somewhat less "general purpose" than it would be if it were designed as
  8196. * a general purpose AES-GCM library. Specifically, it bothers with almost NO
  8197. * error checking on parameter limits, buffer bounds, etc. It assumes that it
  8198. * is being invoked by its author or by someone who understands the values it
  8199. * expects to receive. Its behavior will be undefined otherwise.
  8200. *
  8201. * All functions that might fail are defined to return 'ints' to indicate a
  8202. * problem. Most do not do so now. But this allows for error propagation out
  8203. * of internal functions if robust error checking should ever be desired.
  8204. *
  8205. ******************************************************************************/
  8206. /* Calculating the "GHASH"
  8207. *
  8208. * There are many ways of calculating the so-called GHASH in software, each with
  8209. * a traditional size vs performance tradeoff. The GHASH (Galois field hash) is
  8210. * an intriguing construction which takes two 128-bit strings (also the cipher's
  8211. * block size and the fundamental operation size for the system) and hashes them
  8212. * into a third 128-bit result.
  8213. *
  8214. * Many implementation solutions have been worked out that use large precomputed
  8215. * table lookups in place of more time consuming bit fiddling, and this approach
  8216. * can be scaled easily upward or downward as needed to change the time/space
  8217. * tradeoff. It's been studied extensively and there's a solid body of theory
  8218. * and practice. For example, without using any lookup tables an implementation
  8219. * might obtain 119 cycles per byte throughput, whereas using a simple, though
  8220. * large, key-specific 64 kbyte 8-bit lookup table the performance jumps to 13
  8221. * cycles per byte.
  8222. *
  8223. * And Intel's processors have, since 2010, included an instruction which does
  8224. * the entire 128x128->128 bit job in just several 64x64->128 bit pieces.
  8225. *
  8226. * Since SQRL is interactive, and only processing a few 128-bit blocks, I've
  8227. * settled upon a relatively slower but appealing small-table compromise which
  8228. * folds a bunch of not only time consuming but also bit twiddling into a simple
  8229. * 16-entry table which is attributed to Victor Shoup's 1996 work while at
  8230. * Bellcore: "On Fast and Provably Secure MessageAuthentication Based on
  8231. * Universal Hashing." See: http://www.shoup.net/papers/macs.pdf
  8232. * See, also section 4.1 of the "gcm-revised-spec" cited above.
  8233. */
  8234. /*
  8235. * This 16-entry table of pre-computed constants is used by the
  8236. * GHASH multiplier to improve over a strictly table-free but
  8237. * significantly slower 128x128 bit multiple within GF(2^128).
  8238. */
  8239. static const uint64_t last4[16] = {
  8240. 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
  8241. 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0};
  8242. /*
  8243. * Platform Endianness Neutralizing Load and Store Macro definitions
  8244. * GCM wants platform-neutral Big Endian (BE) byte ordering
  8245. */
  8246. #define GET_UINT32_BE(n, b, i) \
  8247. { \
  8248. (n) = ((uint32_t) (b)[(i)] << 24) | ((uint32_t) (b)[(i) + 1] << 16) | \
  8249. ((uint32_t) (b)[(i) + 2] << 8) | ((uint32_t) (b)[(i) + 3]); \
  8250. }
  8251. #define PUT_UINT32_BE(n, b, i) \
  8252. { \
  8253. (b)[(i)] = (uchar) ((n) >> 24); \
  8254. (b)[(i) + 1] = (uchar) ((n) >> 16); \
  8255. (b)[(i) + 2] = (uchar) ((n) >> 8); \
  8256. (b)[(i) + 3] = (uchar) ((n)); \
  8257. }
  8258. /******************************************************************************
  8259. *
  8260. * GCM_INITIALIZE
  8261. *
  8262. * Must be called once to initialize the GCM library.
  8263. *
  8264. * At present, this only calls the AES keygen table generator, which expands
  8265. * the AES keying tables for use. This is NOT A THREAD-SAFE function, so it
  8266. * MUST be called during system initialization before a multi-threading
  8267. * environment is running.
  8268. *
  8269. ******************************************************************************/
  8270. int mg_gcm_initialize(void) {
  8271. aes_init_keygen_tables();
  8272. return (0);
  8273. }
  8274. /******************************************************************************
  8275. *
  8276. * GCM_MULT
  8277. *
  8278. * Performs a GHASH operation on the 128-bit input vector 'x', setting
  8279. * the 128-bit output vector to 'x' times H using our precomputed tables.
  8280. * 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  8281. *
  8282. ******************************************************************************/
  8283. static void gcm_mult(gcm_context *ctx, // pointer to established context
  8284. const uchar x[16], // pointer to 128-bit input vector
  8285. uchar output[16]) // pointer to 128-bit output vector
  8286. {
  8287. int i;
  8288. uchar lo, hi, rem;
  8289. uint64_t zh, zl;
  8290. lo = (uchar) (x[15] & 0x0f);
  8291. hi = (uchar) (x[15] >> 4);
  8292. zh = ctx->HH[lo];
  8293. zl = ctx->HL[lo];
  8294. for (i = 15; i >= 0; i--) {
  8295. lo = (uchar) (x[i] & 0x0f);
  8296. hi = (uchar) (x[i] >> 4);
  8297. if (i != 15) {
  8298. rem = (uchar) (zl & 0x0f);
  8299. zl = (zh << 60) | (zl >> 4);
  8300. zh = (zh >> 4);
  8301. zh ^= (uint64_t) last4[rem] << 48;
  8302. zh ^= ctx->HH[lo];
  8303. zl ^= ctx->HL[lo];
  8304. }
  8305. rem = (uchar) (zl & 0x0f);
  8306. zl = (zh << 60) | (zl >> 4);
  8307. zh = (zh >> 4);
  8308. zh ^= (uint64_t) last4[rem] << 48;
  8309. zh ^= ctx->HH[hi];
  8310. zl ^= ctx->HL[hi];
  8311. }
  8312. PUT_UINT32_BE(zh >> 32, output, 0);
  8313. PUT_UINT32_BE(zh, output, 4);
  8314. PUT_UINT32_BE(zl >> 32, output, 8);
  8315. PUT_UINT32_BE(zl, output, 12);
  8316. }
  8317. /******************************************************************************
  8318. *
  8319. * GCM_SETKEY
  8320. *
  8321. * This is called to set the AES-GCM key. It initializes the AES key
  8322. * and populates the gcm context's pre-calculated HTables.
  8323. *
  8324. ******************************************************************************/
  8325. static int gcm_setkey(
  8326. gcm_context *ctx, // pointer to caller-provided gcm context
  8327. const uchar *key, // pointer to the AES encryption key
  8328. const uint keysize) // size in bytes (must be 16, 24, 32 for
  8329. // 128, 192 or 256-bit keys respectively)
  8330. {
  8331. int ret, i, j;
  8332. uint64_t hi, lo;
  8333. uint64_t vl, vh;
  8334. unsigned char h[16];
  8335. memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
  8336. memset(h, 0, 16); // initialize the block to encrypt
  8337. // encrypt the null 128-bit block to generate a key-based value
  8338. // which is then used to initialize our GHASH lookup tables
  8339. if ((ret = aes_setkey(&ctx->aes_ctx, MG_ENCRYPT, key, keysize)) != 0)
  8340. return (ret);
  8341. if ((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
  8342. GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
  8343. GET_UINT32_BE(lo, h, 4);
  8344. vh = (uint64_t) hi << 32 | lo;
  8345. GET_UINT32_BE(hi, h, 8);
  8346. GET_UINT32_BE(lo, h, 12);
  8347. vl = (uint64_t) hi << 32 | lo;
  8348. ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
  8349. ctx->HH[8] = vh;
  8350. ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
  8351. ctx->HL[0] = 0;
  8352. for (i = 4; i > 0; i >>= 1) {
  8353. uint32_t T = (uint32_t) (vl & 1) * 0xe1000000U;
  8354. vl = (vh << 63) | (vl >> 1);
  8355. vh = (vh >> 1) ^ ((uint64_t) T << 32);
  8356. ctx->HL[i] = vl;
  8357. ctx->HH[i] = vh;
  8358. }
  8359. for (i = 2; i < 16; i <<= 1) {
  8360. uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
  8361. vh = *HiH;
  8362. vl = *HiL;
  8363. for (j = 1; j < i; j++) {
  8364. HiH[j] = vh ^ ctx->HH[j];
  8365. HiL[j] = vl ^ ctx->HL[j];
  8366. }
  8367. }
  8368. return (0);
  8369. }
  8370. /******************************************************************************
  8371. *
  8372. * GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
  8373. *
  8374. * SETKEY:
  8375. *
  8376. * START: Sets the Encryption/Decryption mode.
  8377. * Accepts the initialization vector and additional data.
  8378. *
  8379. * UPDATE: Encrypts or decrypts the plaintext or ciphertext.
  8380. *
  8381. * FINISH: Performs a final GHASH to generate the authentication tag.
  8382. *
  8383. ******************************************************************************
  8384. *
  8385. * GCM_START
  8386. *
  8387. * Given a user-provided GCM context, this initializes it, sets the encryption
  8388. * mode, and preprocesses the initialization vector and additional AEAD data.
  8389. *
  8390. ******************************************************************************/
  8391. int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context
  8392. int mode, // GCM_ENCRYPT or GCM_DECRYPT
  8393. const uchar *iv, // pointer to initialization vector
  8394. size_t iv_len, // IV length in bytes (should == 12)
  8395. const uchar *add, // ptr to additional AEAD data (NULL if none)
  8396. size_t add_len) // length of additional AEAD data (bytes)
  8397. {
  8398. int ret; // our error return if the AES encrypt fails
  8399. uchar work_buf[16]; // XOR source built from provided IV if len != 16
  8400. const uchar *p; // general purpose array pointer
  8401. size_t use_len; // byte count to process, up to 16 bytes
  8402. size_t i; // local loop iterator
  8403. // since the context might be reused under the same key
  8404. // we zero the working buffers for this next new process
  8405. memset(ctx->y, 0x00, sizeof(ctx->y));
  8406. memset(ctx->buf, 0x00, sizeof(ctx->buf));
  8407. ctx->len = 0;
  8408. ctx->add_len = 0;
  8409. ctx->mode = mode; // set the GCM encryption/decryption mode
  8410. ctx->aes_ctx.mode = MG_ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
  8411. if (iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
  8412. memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
  8413. ctx->y[15] = 1; // start "counting" from 1 (not 0)
  8414. } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
  8415. {
  8416. memset(work_buf, 0x00, 16); // clear the working buffer
  8417. PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
  8418. p = iv;
  8419. while (iv_len > 0) {
  8420. use_len = (iv_len < 16) ? iv_len : 16;
  8421. for (i = 0; i < use_len; i++) ctx->y[i] ^= p[i];
  8422. gcm_mult(ctx, ctx->y, ctx->y);
  8423. iv_len -= use_len;
  8424. p += use_len;
  8425. }
  8426. for (i = 0; i < 16; i++) ctx->y[i] ^= work_buf[i];
  8427. gcm_mult(ctx, ctx->y, ctx->y);
  8428. }
  8429. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0)
  8430. return (ret);
  8431. ctx->add_len = add_len;
  8432. p = add;
  8433. while (add_len > 0) {
  8434. use_len = (add_len < 16) ? add_len : 16;
  8435. for (i = 0; i < use_len; i++) ctx->buf[i] ^= p[i];
  8436. gcm_mult(ctx, ctx->buf, ctx->buf);
  8437. add_len -= use_len;
  8438. p += use_len;
  8439. }
  8440. return (0);
  8441. }
  8442. /******************************************************************************
  8443. *
  8444. * GCM_UPDATE
  8445. *
  8446. * This is called once or more to process bulk plaintext or ciphertext data.
  8447. * We give this some number of bytes of input and it returns the same number
  8448. * of output bytes. If called multiple times (which is fine) all but the final
  8449. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  8450. * have a partial block length of < 128 bits.)
  8451. *
  8452. ******************************************************************************/
  8453. int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  8454. size_t length, // length, in bytes, of data to process
  8455. const uchar *input, // pointer to source data
  8456. uchar *output) // pointer to destination data
  8457. {
  8458. int ret; // our error return if the AES encrypt fails
  8459. uchar ectr[16]; // counter-mode cipher output for XORing
  8460. size_t use_len; // byte count to process, up to 16 bytes
  8461. size_t i; // local loop iterator
  8462. ctx->len += length; // bump the GCM context's running length count
  8463. while (length > 0) {
  8464. // clamp the length to process at 16 bytes
  8465. use_len = (length < 16) ? length : 16;
  8466. // increment the context's 128-bit IV||Counter 'y' vector
  8467. for (i = 16; i > 12; i--)
  8468. if (++ctx->y[i - 1] != 0) break;
  8469. // encrypt the context's 'y' vector under the established key
  8470. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
  8471. // encrypt or decrypt the input to the output
  8472. if (ctx->mode == MG_ENCRYPT) {
  8473. for (i = 0; i < use_len; i++) {
  8474. // XOR the cipher's ouptut vector (ectr) with our input
  8475. output[i] = (uchar) (ectr[i] ^ input[i]);
  8476. // now we mix in our data into the authentication hash.
  8477. // if we're ENcrypting we XOR in the post-XOR (output)
  8478. // results, but if we're DEcrypting we XOR in the input
  8479. // data
  8480. ctx->buf[i] ^= output[i];
  8481. }
  8482. } else {
  8483. for (i = 0; i < use_len; i++) {
  8484. // but if we're DEcrypting we XOR in the input data first,
  8485. // i.e. before saving to ouput data, otherwise if the input
  8486. // and output buffer are the same (inplace decryption) we
  8487. // would not get the correct auth tag
  8488. ctx->buf[i] ^= input[i];
  8489. // XOR the cipher's ouptut vector (ectr) with our input
  8490. output[i] = (uchar) (ectr[i] ^ input[i]);
  8491. }
  8492. }
  8493. gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
  8494. length -= use_len; // drop the remaining byte count to process
  8495. input += use_len; // bump our input pointer forward
  8496. output += use_len; // bump our output pointer forward
  8497. }
  8498. return (0);
  8499. }
  8500. /******************************************************************************
  8501. *
  8502. * GCM_FINISH
  8503. *
  8504. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  8505. * It performs the final GHASH to produce the resulting authentication TAG.
  8506. *
  8507. ******************************************************************************/
  8508. int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context
  8509. uchar *tag, // pointer to buffer which receives the tag
  8510. size_t tag_len) // length, in bytes, of the tag-receiving buf
  8511. {
  8512. uchar work_buf[16];
  8513. uint64_t orig_len = ctx->len * 8;
  8514. uint64_t orig_add_len = ctx->add_len * 8;
  8515. size_t i;
  8516. if (tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
  8517. if (orig_len || orig_add_len) {
  8518. memset(work_buf, 0x00, 16);
  8519. PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
  8520. PUT_UINT32_BE((orig_add_len), work_buf, 4);
  8521. PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
  8522. PUT_UINT32_BE((orig_len), work_buf, 12);
  8523. for (i = 0; i < 16; i++) ctx->buf[i] ^= work_buf[i];
  8524. gcm_mult(ctx, ctx->buf, ctx->buf);
  8525. for (i = 0; i < tag_len; i++) tag[i] ^= ctx->buf[i];
  8526. }
  8527. return (0);
  8528. }
  8529. /******************************************************************************
  8530. *
  8531. * GCM_CRYPT_AND_TAG
  8532. *
  8533. * This either encrypts or decrypts the user-provided data and, either
  8534. * way, generates an authentication tag of the requested length. It must be
  8535. * called with a GCM context whose key has already been set with GCM_SETKEY.
  8536. *
  8537. * The user would typically call this explicitly to ENCRYPT a buffer of data
  8538. * and optional associated data, and produce its an authentication tag.
  8539. *
  8540. * To reverse the process the user would typically call the companion
  8541. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  8542. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  8543. * to perform its decryption and tag generation, which it then compares.
  8544. *
  8545. ******************************************************************************/
  8546. int gcm_crypt_and_tag(
  8547. gcm_context *ctx, // gcm context with key already setup
  8548. int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
  8549. const uchar *iv, // pointer to the 12-byte initialization vector
  8550. size_t iv_len, // byte length if the IV. should always be 12
  8551. const uchar *add, // pointer to the non-ciphered additional data
  8552. size_t add_len, // byte length of the additional AEAD data
  8553. const uchar *input, // pointer to the cipher data source
  8554. uchar *output, // pointer to the cipher data destination
  8555. size_t length, // byte length of the cipher data
  8556. uchar *tag, // pointer to the tag to be generated
  8557. size_t tag_len) // byte length of the tag to be generated
  8558. { /*
  8559. assuming that the caller has already invoked gcm_setkey to
  8560. prepare the gcm context with the keying material, we simply
  8561. invoke each of the three GCM sub-functions in turn...
  8562. */
  8563. gcm_start(ctx, mode, iv, iv_len, add, add_len);
  8564. gcm_update(ctx, length, input, output);
  8565. gcm_finish(ctx, tag, tag_len);
  8566. return (0);
  8567. }
  8568. /******************************************************************************
  8569. *
  8570. * GCM_ZERO_CTX
  8571. *
  8572. * The GCM context contains both the GCM context and the AES context.
  8573. * This includes keying and key-related material which is security-
  8574. * sensitive, so it MUST be zeroed after use. This function does that.
  8575. *
  8576. ******************************************************************************/
  8577. void gcm_zero_ctx(gcm_context *ctx) {
  8578. // zero the context originally provided to us
  8579. memset(ctx, 0, sizeof(gcm_context));
  8580. }
  8581. //
  8582. // aes-gcm.c
  8583. // Pods
  8584. //
  8585. // Created by Markus Kosmal on 20/11/14.
  8586. //
  8587. //
  8588. int mg_aes_gcm_encrypt(unsigned char *output, //
  8589. const unsigned char *input, size_t input_length,
  8590. const unsigned char *key, const size_t key_len,
  8591. const unsigned char *iv, const size_t iv_len,
  8592. unsigned char *aead, size_t aead_len, unsigned char *tag,
  8593. const size_t tag_len) {
  8594. int ret = 0; // our return value
  8595. gcm_context ctx; // includes the AES context structure
  8596. gcm_setkey(&ctx, key, (uint) key_len);
  8597. ret = gcm_crypt_and_tag(&ctx, MG_ENCRYPT, iv, iv_len, aead, aead_len, input,
  8598. output, input_length, tag, tag_len);
  8599. gcm_zero_ctx(&ctx);
  8600. return (ret);
  8601. }
  8602. int mg_aes_gcm_decrypt(unsigned char *output, const unsigned char *input,
  8603. size_t input_length, const unsigned char *key,
  8604. const size_t key_len, const unsigned char *iv,
  8605. const size_t iv_len) {
  8606. int ret = 0; // our return value
  8607. gcm_context ctx; // includes the AES context structure
  8608. size_t tag_len = 0;
  8609. unsigned char *tag_buf = NULL;
  8610. gcm_setkey(&ctx, key, (uint) key_len);
  8611. ret = gcm_crypt_and_tag(&ctx, MG_DECRYPT, iv, iv_len, NULL, 0, input, output,
  8612. input_length, tag_buf, tag_len);
  8613. gcm_zero_ctx(&ctx);
  8614. return (ret);
  8615. }
  8616. #endif
  8617. // End of aes128 PD
  8618. #ifdef MG_ENABLE_LINES
  8619. #line 1 "src/tls_builtin.c"
  8620. #endif
  8621. #if MG_TLS == MG_TLS_BUILTIN
  8622. /* TLS 1.3 Record Content Type (RFC8446 B.1) */
  8623. #define MG_TLS_CHANGE_CIPHER 20
  8624. #define MG_TLS_ALERT 21
  8625. #define MG_TLS_HANDSHAKE 22
  8626. #define MG_TLS_APP_DATA 23
  8627. #define MG_TLS_HEARTBEAT 24
  8628. /* TLS 1.3 Handshake Message Type (RFC8446 B.3) */
  8629. #define MG_TLS_CLIENT_HELLO 1
  8630. #define MG_TLS_SERVER_HELLO 2
  8631. #define MG_TLS_ENCRYPTED_EXTENSIONS 8
  8632. #define MG_TLS_CERTIFICATE 11
  8633. #define MG_TLS_CERTIFICATE_VERIFY 15
  8634. #define MG_TLS_FINISHED 20
  8635. // handshake is re-entrant, so we need to keep track of its state state names
  8636. // refer to RFC8446#A.1
  8637. enum mg_tls_hs_state {
  8638. // Client state machine:
  8639. MG_TLS_STATE_CLIENT_START, // Send ClientHello
  8640. MG_TLS_STATE_CLIENT_WAIT_SH, // Wait for ServerHello
  8641. MG_TLS_STATE_CLIENT_WAIT_EE, // Wait for EncryptedExtensions
  8642. MG_TLS_STATE_CLIENT_WAIT_CERT, // Wait for Certificate
  8643. MG_TLS_STATE_CLIENT_WAIT_CV, // Wait for CertificateVerify
  8644. MG_TLS_STATE_CLIENT_WAIT_FINISHED, // Wait for Finished
  8645. MG_TLS_STATE_CLIENT_CONNECTED, // Done
  8646. // Server state machine:
  8647. MG_TLS_STATE_SERVER_START, // Wait for ClientHello
  8648. MG_TLS_STATE_SERVER_NEGOTIATED, // Wait for Finished
  8649. MG_TLS_STATE_SERVER_CONNECTED // Done
  8650. };
  8651. // per-connection TLS data
  8652. struct tls_data {
  8653. enum mg_tls_hs_state state; // keep track of connection handshake progress
  8654. struct mg_iobuf send; // For the receive path, we're reusing c->rtls
  8655. struct mg_iobuf recv; // While c->rtls contains full records, recv reuses
  8656. // the same underlying buffer but points at individual
  8657. // decrypted messages
  8658. uint8_t content_type; // Last received record content type
  8659. mg_sha256_ctx sha256; // incremental SHA-256 hash for TLS handshake
  8660. uint32_t sseq; // server sequence number, used in encryption
  8661. uint32_t cseq; // client sequence number, used in decryption
  8662. uint8_t random[32]; // client random from ClientHello
  8663. uint8_t session_id[32]; // client session ID between the handshake states
  8664. uint8_t x25519_cli[32]; // client X25519 key between the handshake states
  8665. uint8_t x25519_sec[32]; // x25519 secret between the handshake states
  8666. int skip_verification; // perform checks on server certificate?
  8667. struct mg_str server_cert_der; // server certificate in DER format
  8668. uint8_t server_key[32]; // server EC private key
  8669. char hostname[254]; // server hostname (client extension)
  8670. uint8_t certhash[32]; // certificate message hash
  8671. uint8_t pubkey[64]; // server EC public key to verify cert
  8672. uint8_t sighash[32]; // server EC public key to verify cert
  8673. // keys for AES encryption
  8674. uint8_t handshake_secret[32];
  8675. uint8_t server_write_key[16];
  8676. uint8_t server_write_iv[12];
  8677. uint8_t server_finished_key[32];
  8678. uint8_t client_write_key[16];
  8679. uint8_t client_write_iv[12];
  8680. uint8_t client_finished_key[32];
  8681. };
  8682. #define MG_LOAD_BE16(p) ((uint16_t) ((MG_U8P(p)[0] << 8U) | MG_U8P(p)[1]))
  8683. #define MG_LOAD_BE24(p) \
  8684. ((uint32_t) ((MG_U8P(p)[0] << 16U) | (MG_U8P(p)[1] << 8U) | MG_U8P(p)[2]))
  8685. #define MG_STORE_BE16(p, n) \
  8686. do { \
  8687. MG_U8P(p)[0] = ((n) >> 8U) & 255; \
  8688. MG_U8P(p)[1] = (n) & 255; \
  8689. } while (0)
  8690. #define TLS_RECHDR_SIZE 5 // 1 byte type, 2 bytes version, 2 bytes length
  8691. #define TLS_MSGHDR_SIZE 4 // 1 byte type, 3 bytes length
  8692. #if 1
  8693. static void mg_ssl_key_log(const char *label, uint8_t client_random[32],
  8694. uint8_t *secret, size_t secretsz) {
  8695. (void) label;
  8696. (void) client_random;
  8697. (void) secret;
  8698. (void) secretsz;
  8699. }
  8700. #else
  8701. #include <stdio.h>
  8702. static void mg_ssl_key_log(const char *label, uint8_t client_random[32],
  8703. uint8_t *secret, size_t secretsz) {
  8704. char *keylogfile = getenv("SSLKEYLOGFILE");
  8705. if (keylogfile == NULL) {
  8706. return;
  8707. }
  8708. FILE *f = fopen(keylogfile, "a");
  8709. fprintf(f, "%s ", label);
  8710. for (int i = 0; i < 32; i++) {
  8711. fprintf(f, "%02x", client_random[i]);
  8712. }
  8713. fprintf(f, " ");
  8714. for (unsigned int i = 0; i < secretsz; i++) {
  8715. fprintf(f, "%02x", secret[i]);
  8716. }
  8717. fprintf(f, "\n");
  8718. fclose(f);
  8719. }
  8720. #endif
  8721. // for derived tls keys we need SHA256([0]*32)
  8722. static uint8_t zeros[32] = {0};
  8723. static uint8_t zeros_sha256_digest[32] = {
  8724. 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4,
  8725. 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b,
  8726. 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55};
  8727. // helper to hexdump buffers inline
  8728. static void mg_tls_hexdump(const char *msg, uint8_t *buf, size_t bufsz) {
  8729. MG_VERBOSE(("%s: %M", msg, mg_print_hex, bufsz, buf));
  8730. }
  8731. // helper utilities to parse ASN.1 DER
  8732. struct mg_der_tlv {
  8733. uint8_t type;
  8734. uint32_t len;
  8735. uint8_t *value;
  8736. };
  8737. // parse DER into a TLV record
  8738. static int mg_der_to_tlv(uint8_t *der, size_t dersz, struct mg_der_tlv *tlv) {
  8739. if (dersz < 2) {
  8740. return -1;
  8741. }
  8742. tlv->type = der[0];
  8743. tlv->len = der[1];
  8744. tlv->value = der + 2;
  8745. if (tlv->len > 0x7f) {
  8746. uint32_t i, n = tlv->len - 0x80;
  8747. tlv->len = 0;
  8748. for (i = 0; i < n; i++) {
  8749. tlv->len = (tlv->len << 8) | (der[2 + i]);
  8750. }
  8751. tlv->value = der + 2 + n;
  8752. }
  8753. if (der + dersz < tlv->value + tlv->len) {
  8754. return -1;
  8755. }
  8756. return 0;
  8757. }
  8758. static int mg_der_find(uint8_t *der, size_t dersz, uint8_t *oid, size_t oidsz,
  8759. struct mg_der_tlv *tlv) {
  8760. uint8_t *p, *end;
  8761. struct mg_der_tlv child = {0, 0, NULL};
  8762. if (mg_der_to_tlv(der, dersz, tlv) < 0) {
  8763. return -1; // invalid DER
  8764. } else if (tlv->type == 6) { // found OID, check value
  8765. return (tlv->len == oidsz && memcmp(tlv->value, oid, oidsz) == 0);
  8766. } else if ((tlv->type & 0x20) == 0) {
  8767. return 0; // Primitive, but not OID: not found
  8768. }
  8769. // Constructed object: scan children
  8770. p = tlv->value;
  8771. end = tlv->value + tlv->len;
  8772. while (end > p) {
  8773. int r;
  8774. mg_der_to_tlv(p, (size_t) (end - p), &child);
  8775. r = mg_der_find(p, (size_t) (end - p), oid, oidsz, tlv);
  8776. if (r < 0) return -1; // error
  8777. if (r > 0) return 1; // found OID!
  8778. p = child.value + child.len;
  8779. }
  8780. return 0; // not found
  8781. }
  8782. // Did we receive a full TLS record in the c->rtls buffer?
  8783. static bool mg_tls_got_record(struct mg_connection *c) {
  8784. return c->rtls.len >= (size_t) TLS_RECHDR_SIZE &&
  8785. c->rtls.len >=
  8786. (size_t) (TLS_RECHDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
  8787. }
  8788. // Remove a single TLS record from the recv buffer
  8789. static void mg_tls_drop_record(struct mg_connection *c) {
  8790. struct mg_iobuf *rio = &c->rtls;
  8791. uint16_t n = MG_LOAD_BE16(rio->buf + 3) + TLS_RECHDR_SIZE;
  8792. mg_iobuf_del(rio, 0, n);
  8793. }
  8794. // Remove a single TLS message from decrypted buffer, remove the wrapping
  8795. // record if it was the last message within a record
  8796. static void mg_tls_drop_message(struct mg_connection *c) {
  8797. uint32_t len;
  8798. struct tls_data *tls = (struct tls_data *) c->tls;
  8799. if (tls->recv.len == 0) {
  8800. return;
  8801. }
  8802. len = MG_LOAD_BE24(tls->recv.buf + 1);
  8803. mg_sha256_update(&tls->sha256, tls->recv.buf, len + TLS_MSGHDR_SIZE);
  8804. tls->recv.buf += len + TLS_MSGHDR_SIZE;
  8805. tls->recv.len -= len + TLS_MSGHDR_SIZE;
  8806. if (tls->recv.len == 0) {
  8807. mg_tls_drop_record(c);
  8808. }
  8809. }
  8810. // TLS1.3 secret derivation based on the key label
  8811. static void mg_tls_derive_secret(const char *label, uint8_t *key, size_t keysz,
  8812. uint8_t *data, size_t datasz, uint8_t *hash,
  8813. size_t hashsz) {
  8814. size_t labelsz = strlen(label);
  8815. uint8_t secret[32];
  8816. uint8_t packed[256] = {0, (uint8_t) hashsz, (uint8_t) labelsz};
  8817. // TODO: assert lengths of label, key, data and hash
  8818. if (labelsz > 0) memmove(packed + 3, label, labelsz);
  8819. packed[3 + labelsz] = (uint8_t) datasz;
  8820. if (datasz > 0) memmove(packed + labelsz + 4, data, datasz);
  8821. packed[4 + labelsz + datasz] = 1;
  8822. mg_hmac_sha256(secret, key, keysz, packed, 5 + labelsz + datasz);
  8823. memmove(hash, secret, hashsz);
  8824. }
  8825. // at this point we have x25519 shared secret, we can generate a set of derived
  8826. // handshake encryption keys
  8827. static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
  8828. struct tls_data *tls = (struct tls_data *) c->tls;
  8829. mg_sha256_ctx sha256;
  8830. uint8_t early_secret[32];
  8831. uint8_t pre_extract_secret[32];
  8832. uint8_t hello_hash[32];
  8833. uint8_t server_hs_secret[32];
  8834. uint8_t client_hs_secret[32];
  8835. mg_hmac_sha256(early_secret, NULL, 0, zeros, sizeof(zeros));
  8836. mg_tls_derive_secret("tls13 derived", early_secret, 32, zeros_sha256_digest,
  8837. 32, pre_extract_secret, 32);
  8838. mg_hmac_sha256(tls->handshake_secret, pre_extract_secret,
  8839. sizeof(pre_extract_secret), tls->x25519_sec,
  8840. sizeof(tls->x25519_sec));
  8841. mg_tls_hexdump("hs secret", tls->handshake_secret, 32);
  8842. // mg_sha256_final is not idempotent, need to copy sha256 context to calculate
  8843. // the digest
  8844. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8845. mg_sha256_final(hello_hash, &sha256);
  8846. mg_tls_hexdump("hello hash", hello_hash, 32);
  8847. // derive keys needed for the rest of the handshake
  8848. mg_tls_derive_secret("tls13 s hs traffic", tls->handshake_secret, 32,
  8849. hello_hash, 32, server_hs_secret, 32);
  8850. mg_tls_derive_secret("tls13 key", server_hs_secret, 32, NULL, 0,
  8851. tls->server_write_key, 16);
  8852. mg_tls_derive_secret("tls13 iv", server_hs_secret, 32, NULL, 0,
  8853. tls->server_write_iv, 12);
  8854. mg_tls_derive_secret("tls13 finished", server_hs_secret, 32, NULL, 0,
  8855. tls->server_finished_key, 32);
  8856. mg_tls_derive_secret("tls13 c hs traffic", tls->handshake_secret, 32,
  8857. hello_hash, 32, client_hs_secret, 32);
  8858. mg_tls_derive_secret("tls13 key", client_hs_secret, 32, NULL, 0,
  8859. tls->client_write_key, 16);
  8860. mg_tls_derive_secret("tls13 iv", client_hs_secret, 32, NULL, 0,
  8861. tls->client_write_iv, 12);
  8862. mg_tls_derive_secret("tls13 finished", client_hs_secret, 32, NULL, 0,
  8863. tls->client_finished_key, 32);
  8864. mg_tls_hexdump("s hs traffic", server_hs_secret, 32);
  8865. mg_tls_hexdump("s key", tls->server_write_key, 16);
  8866. mg_tls_hexdump("s iv", tls->server_write_iv, 12);
  8867. mg_tls_hexdump("s finished", tls->server_finished_key, 32);
  8868. mg_tls_hexdump("c hs traffic", client_hs_secret, 32);
  8869. mg_tls_hexdump("c key", tls->client_write_key, 16);
  8870. mg_tls_hexdump("c iv", tls->client_write_iv, 16);
  8871. mg_tls_hexdump("c finished", tls->client_finished_key, 32);
  8872. mg_ssl_key_log("SERVER_HANDSHAKE_TRAFFIC_SECRET", tls->random,
  8873. server_hs_secret, 32);
  8874. mg_ssl_key_log("CLIENT_HANDSHAKE_TRAFFIC_SECRET", tls->random,
  8875. client_hs_secret, 32);
  8876. }
  8877. static void mg_tls_generate_application_keys(struct mg_connection *c) {
  8878. struct tls_data *tls = (struct tls_data *) c->tls;
  8879. uint8_t hash[32];
  8880. uint8_t premaster_secret[32];
  8881. uint8_t master_secret[32];
  8882. uint8_t server_secret[32];
  8883. uint8_t client_secret[32];
  8884. mg_sha256_ctx sha256;
  8885. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8886. mg_sha256_final(hash, &sha256);
  8887. mg_tls_derive_secret("tls13 derived", tls->handshake_secret, 32,
  8888. zeros_sha256_digest, 32, premaster_secret, 32);
  8889. mg_hmac_sha256(master_secret, premaster_secret, 32, zeros, 32);
  8890. mg_tls_derive_secret("tls13 s ap traffic", master_secret, 32, hash, 32,
  8891. server_secret, 32);
  8892. mg_tls_derive_secret("tls13 key", server_secret, 32, NULL, 0,
  8893. tls->server_write_key, 16);
  8894. mg_tls_derive_secret("tls13 iv", server_secret, 32, NULL, 0,
  8895. tls->server_write_iv, 12);
  8896. mg_tls_derive_secret("tls13 c ap traffic", master_secret, 32, hash, 32,
  8897. client_secret, 32);
  8898. mg_tls_derive_secret("tls13 key", client_secret, 32, NULL, 0,
  8899. tls->client_write_key, 16);
  8900. mg_tls_derive_secret("tls13 iv", client_secret, 32, NULL, 0,
  8901. tls->client_write_iv, 12);
  8902. mg_tls_hexdump("s ap traffic", server_secret, 32);
  8903. mg_tls_hexdump("s key", tls->server_write_key, 16);
  8904. mg_tls_hexdump("s iv", tls->server_write_iv, 12);
  8905. mg_tls_hexdump("s finished", tls->server_finished_key, 32);
  8906. mg_tls_hexdump("c ap traffic", client_secret, 32);
  8907. mg_tls_hexdump("c key", tls->client_write_key, 16);
  8908. mg_tls_hexdump("c iv", tls->client_write_iv, 16);
  8909. mg_tls_hexdump("c finished", tls->client_finished_key, 32);
  8910. tls->sseq = tls->cseq = 0;
  8911. mg_ssl_key_log("SERVER_TRAFFIC_SECRET_0", tls->random, server_secret, 32);
  8912. mg_ssl_key_log("CLIENT_TRAFFIC_SECRET_0", tls->random, client_secret, 32);
  8913. }
  8914. // AES GCM encryption of the message + put encoded data into the write buffer
  8915. static void mg_tls_encrypt(struct mg_connection *c, const uint8_t *msg,
  8916. size_t msgsz, uint8_t msgtype) {
  8917. struct tls_data *tls = (struct tls_data *) c->tls;
  8918. struct mg_iobuf *wio = &tls->send;
  8919. uint8_t *outmsg;
  8920. uint8_t *tag;
  8921. size_t encsz = msgsz + 16 + 1;
  8922. uint8_t hdr[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
  8923. (uint8_t) ((encsz >> 8) & 0xff), (uint8_t) (encsz & 0xff)};
  8924. uint8_t associated_data[5] = {MG_TLS_APP_DATA, 0x03, 0x03,
  8925. (uint8_t) ((encsz >> 8) & 0xff),
  8926. (uint8_t) (encsz & 0xff)};
  8927. uint8_t nonce[12];
  8928. mg_gcm_initialize();
  8929. if (c->is_client) {
  8930. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  8931. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  8932. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  8933. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  8934. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  8935. } else {
  8936. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8937. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8938. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8939. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8940. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8941. }
  8942. mg_iobuf_add(wio, wio->len, hdr, sizeof(hdr));
  8943. mg_iobuf_resize(wio, wio->len + encsz);
  8944. outmsg = wio->buf + wio->len;
  8945. tag = wio->buf + wio->len + msgsz + 1;
  8946. memmove(outmsg, msg, msgsz);
  8947. outmsg[msgsz] = msgtype;
  8948. if (c->is_client) {
  8949. mg_aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->client_write_key,
  8950. sizeof(tls->client_write_key), nonce, sizeof(nonce),
  8951. associated_data, sizeof(associated_data), tag, 16);
  8952. tls->cseq++;
  8953. } else {
  8954. mg_aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->server_write_key,
  8955. sizeof(tls->server_write_key), nonce, sizeof(nonce),
  8956. associated_data, sizeof(associated_data), tag, 16);
  8957. tls->sseq++;
  8958. }
  8959. wio->len += encsz;
  8960. }
  8961. // read an encrypted record, decrypt it in place
  8962. static int mg_tls_recv_record(struct mg_connection *c) {
  8963. struct tls_data *tls = (struct tls_data *) c->tls;
  8964. struct mg_iobuf *rio = &c->rtls;
  8965. uint16_t msgsz;
  8966. uint8_t *msg;
  8967. uint8_t nonce[12];
  8968. int r;
  8969. if (tls->recv.len > 0) {
  8970. return 0; /* some data from previous record is still present */
  8971. }
  8972. for (;;) {
  8973. if (!mg_tls_got_record(c)) {
  8974. return MG_IO_WAIT;
  8975. }
  8976. if (rio->buf[0] == MG_TLS_APP_DATA) {
  8977. break;
  8978. } else if (rio->buf[0] ==
  8979. MG_TLS_CHANGE_CIPHER) { // Skip ChangeCipher messages
  8980. mg_tls_drop_record(c);
  8981. } else if (rio->buf[0] == MG_TLS_ALERT) { // Skip Alerts
  8982. MG_INFO(("TLS ALERT packet received"));
  8983. mg_tls_drop_record(c);
  8984. } else {
  8985. mg_error(c, "unexpected packet");
  8986. return -1;
  8987. }
  8988. }
  8989. mg_gcm_initialize();
  8990. msgsz = MG_LOAD_BE16(rio->buf + 3);
  8991. msg = rio->buf + 5;
  8992. if (c->is_client) {
  8993. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8994. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8995. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8996. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8997. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8998. mg_aes_gcm_decrypt(msg, msg, msgsz - 16, tls->server_write_key,
  8999. sizeof(tls->server_write_key), nonce, sizeof(nonce));
  9000. tls->sseq++;
  9001. } else {
  9002. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  9003. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  9004. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  9005. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  9006. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  9007. mg_aes_gcm_decrypt(msg, msg, msgsz - 16, tls->client_write_key,
  9008. sizeof(tls->client_write_key), nonce, sizeof(nonce));
  9009. tls->cseq++;
  9010. }
  9011. r = msgsz - 16 - 1;
  9012. tls->content_type = msg[msgsz - 16 - 1];
  9013. tls->recv.buf = msg;
  9014. tls->recv.size = tls->recv.len = msgsz - 16 - 1;
  9015. return r;
  9016. }
  9017. static void mg_tls_calc_cert_verify_hash(struct mg_connection *c,
  9018. uint8_t hash[32]) {
  9019. struct tls_data *tls = (struct tls_data *) c->tls;
  9020. uint8_t sig_content[130] = {
  9021. " "
  9022. " "
  9023. "TLS 1.3, server CertificateVerify\0"};
  9024. mg_sha256_ctx sha256;
  9025. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9026. mg_sha256_final(sig_content + 98, &sha256);
  9027. mg_sha256_init(&sha256);
  9028. mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
  9029. mg_sha256_final(hash, &sha256);
  9030. }
  9031. // read and parse ClientHello record
  9032. static int mg_tls_server_recv_hello(struct mg_connection *c) {
  9033. struct tls_data *tls = (struct tls_data *) c->tls;
  9034. struct mg_iobuf *rio = &c->rtls;
  9035. uint8_t session_id_len;
  9036. uint16_t j;
  9037. uint16_t cipher_suites_len;
  9038. uint16_t ext_len;
  9039. uint8_t *ext;
  9040. uint16_t msgsz;
  9041. if (!mg_tls_got_record(c)) {
  9042. return MG_IO_WAIT;
  9043. }
  9044. if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_CLIENT_HELLO) {
  9045. mg_error(c, "not a client hello packet");
  9046. return -1;
  9047. }
  9048. msgsz = MG_LOAD_BE16(rio->buf + 3);
  9049. mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
  9050. // store client random
  9051. memmove(tls->random, rio->buf + 11, sizeof(tls->random));
  9052. // store session_id
  9053. session_id_len = rio->buf[43];
  9054. if (session_id_len == sizeof(tls->session_id)) {
  9055. memmove(tls->session_id, rio->buf + 44, session_id_len);
  9056. } else if (session_id_len != 0) {
  9057. MG_INFO(("bad session id len"));
  9058. }
  9059. cipher_suites_len = MG_LOAD_BE16(rio->buf + 44 + session_id_len);
  9060. ext_len = MG_LOAD_BE16(rio->buf + 48 + session_id_len + cipher_suites_len);
  9061. ext = rio->buf + 50 + session_id_len + cipher_suites_len;
  9062. for (j = 0; j < ext_len;) {
  9063. uint16_t k;
  9064. uint16_t key_exchange_len;
  9065. uint8_t *key_exchange;
  9066. uint16_t n = MG_LOAD_BE16(ext + j + 2);
  9067. if (ext[j] != 0x00 ||
  9068. ext[j + 1] != 0x33) { // not a key share extension, ignore
  9069. j += (uint16_t) (n + 4);
  9070. continue;
  9071. }
  9072. key_exchange_len = MG_LOAD_BE16(ext + j + 5);
  9073. key_exchange = ext + j + 6;
  9074. for (k = 0; k < key_exchange_len;) {
  9075. uint16_t m = MG_LOAD_BE16(key_exchange + k + 2);
  9076. if (m == 32 && key_exchange[k] == 0x00 && key_exchange[k + 1] == 0x1d) {
  9077. memmove(tls->x25519_cli, key_exchange + k + 4, m);
  9078. mg_tls_drop_record(c);
  9079. return 0;
  9080. }
  9081. k += (uint16_t) (m + 4);
  9082. }
  9083. j += (uint16_t) (n + 4);
  9084. }
  9085. mg_error(c, "bad client hello");
  9086. return -1;
  9087. }
  9088. #define PLACEHOLDER_8B 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X'
  9089. #define PLACEHOLDER_16B PLACEHOLDER_8B, PLACEHOLDER_8B
  9090. #define PLACEHOLDER_32B PLACEHOLDER_16B, PLACEHOLDER_16B
  9091. // put ServerHello record into wio buffer
  9092. static void mg_tls_server_send_hello(struct mg_connection *c) {
  9093. struct tls_data *tls = (struct tls_data *) c->tls;
  9094. struct mg_iobuf *wio = &tls->send;
  9095. uint8_t msg_server_hello[122] = {
  9096. // server hello, tls 1.2
  9097. 0x02,
  9098. 0x00,
  9099. 0x00,
  9100. 0x76,
  9101. 0x03,
  9102. 0x03,
  9103. // random (32 bytes)
  9104. PLACEHOLDER_32B,
  9105. // session ID length + session ID (32 bytes)
  9106. 0x20,
  9107. PLACEHOLDER_32B,
  9108. #if defined(CHACHA20) && CHACHA20
  9109. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  9110. 0x13,
  9111. 0x03,
  9112. 0x00,
  9113. #else
  9114. // TLS_AES_128_GCM_SHA256 + no compression
  9115. 0x13,
  9116. 0x01,
  9117. 0x00,
  9118. #endif
  9119. // extensions + keyshare
  9120. 0x00,
  9121. 0x2e,
  9122. 0x00,
  9123. 0x33,
  9124. 0x00,
  9125. 0x24,
  9126. 0x00,
  9127. 0x1d,
  9128. 0x00,
  9129. 0x20,
  9130. // x25519 keyshare
  9131. PLACEHOLDER_32B,
  9132. // supported versions (tls1.3 == 0x304)
  9133. 0x00,
  9134. 0x2b,
  9135. 0x00,
  9136. 0x02,
  9137. 0x03,
  9138. 0x04
  9139. };
  9140. // calculate keyshare
  9141. uint8_t x25519_pub[X25519_BYTES];
  9142. uint8_t x25519_prv[X25519_BYTES];
  9143. mg_random(x25519_prv, sizeof(x25519_prv));
  9144. mg_tls_x25519(x25519_pub, x25519_prv, X25519_BASE_POINT, 1);
  9145. mg_tls_x25519(tls->x25519_sec, x25519_prv, tls->x25519_cli, 1);
  9146. mg_tls_hexdump("s x25519 sec", tls->x25519_sec, sizeof(tls->x25519_sec));
  9147. // fill in the gaps: random + session ID + keyshare
  9148. memmove(msg_server_hello + 6, tls->random, sizeof(tls->random));
  9149. memmove(msg_server_hello + 39, tls->session_id, sizeof(tls->session_id));
  9150. memmove(msg_server_hello + 84, x25519_pub, sizeof(x25519_pub));
  9151. // server hello message
  9152. mg_iobuf_add(wio, wio->len, "\x16\x03\x03\x00\x7a", 5);
  9153. mg_iobuf_add(wio, wio->len, msg_server_hello, sizeof(msg_server_hello));
  9154. mg_sha256_update(&tls->sha256, msg_server_hello, sizeof(msg_server_hello));
  9155. // change cipher message
  9156. mg_iobuf_add(wio, wio->len, "\x14\x03\x03\x00\x01\x01", 6);
  9157. }
  9158. static void mg_tls_server_send_ext(struct mg_connection *c) {
  9159. struct tls_data *tls = (struct tls_data *) c->tls;
  9160. // server extensions
  9161. uint8_t ext[6] = {0x08, 0, 0, 2, 0, 0};
  9162. mg_sha256_update(&tls->sha256, ext, sizeof(ext));
  9163. mg_tls_encrypt(c, ext, sizeof(ext), MG_TLS_HANDSHAKE);
  9164. }
  9165. static void mg_tls_server_send_cert(struct mg_connection *c) {
  9166. struct tls_data *tls = (struct tls_data *) c->tls;
  9167. // server DER certificate (empty)
  9168. size_t n = tls->server_cert_der.len;
  9169. uint8_t *cert = (uint8_t *) calloc(1, 13 + n);
  9170. if (cert == NULL) {
  9171. mg_error(c, "tls cert oom");
  9172. return;
  9173. }
  9174. cert[0] = 0x0b; // handshake header
  9175. cert[1] = (uint8_t) (((n + 9) >> 16) & 255U); // 3 bytes: payload length
  9176. cert[2] = (uint8_t) (((n + 9) >> 8) & 255U);
  9177. cert[3] = (uint8_t) ((n + 9) & 255U);
  9178. cert[4] = 0; // request context
  9179. cert[5] = (uint8_t) (((n + 5) >> 16) & 255U); // 3 bytes: cert (s) length
  9180. cert[6] = (uint8_t) (((n + 5) >> 8) & 255U);
  9181. cert[7] = (uint8_t) ((n + 5) & 255U);
  9182. cert[8] =
  9183. (uint8_t) (((n) >> 16) & 255U); // 3 bytes: first (and only) cert len
  9184. cert[9] = (uint8_t) (((n) >> 8) & 255U);
  9185. cert[10] = (uint8_t) (n & 255U);
  9186. // bytes 11+ are certificate in DER format
  9187. memmove(cert + 11, tls->server_cert_der.buf, n);
  9188. cert[11 + n] = cert[12 + n] = 0; // certificate extensions (none)
  9189. mg_sha256_update(&tls->sha256, cert, 13 + n);
  9190. mg_tls_encrypt(c, cert, 13 + n, MG_TLS_HANDSHAKE);
  9191. free(cert);
  9192. }
  9193. // type adapter between uECC hash context and our sha256 implementation
  9194. typedef struct SHA256_HashContext {
  9195. MG_UECC_HashContext uECC;
  9196. mg_sha256_ctx ctx;
  9197. } SHA256_HashContext;
  9198. static void init_SHA256(const MG_UECC_HashContext *base) {
  9199. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9200. mg_sha256_init(&c->ctx);
  9201. }
  9202. static void update_SHA256(const MG_UECC_HashContext *base,
  9203. const uint8_t *message, unsigned message_size) {
  9204. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9205. mg_sha256_update(&c->ctx, message, message_size);
  9206. }
  9207. static void finish_SHA256(const MG_UECC_HashContext *base,
  9208. uint8_t *hash_result) {
  9209. SHA256_HashContext *c = (SHA256_HashContext *) base;
  9210. mg_sha256_final(hash_result, &c->ctx);
  9211. }
  9212. static void mg_tls_server_send_cert_verify(struct mg_connection *c) {
  9213. struct tls_data *tls = (struct tls_data *) c->tls;
  9214. // server certificate verify packet
  9215. uint8_t verify[82] = {0x0f, 0x00, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00};
  9216. size_t sigsz, verifysz = 0;
  9217. uint8_t hash[32] = {0}, tmp[2 * 32 + 64] = {0};
  9218. struct SHA256_HashContext ctx = {
  9219. {&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp},
  9220. {{0}, 0, 0, {0}}};
  9221. int neg1, neg2;
  9222. uint8_t sig[64] = {0};
  9223. mg_tls_calc_cert_verify_hash(c, (uint8_t *) hash);
  9224. mg_uecc_sign_deterministic(tls->server_key, hash, sizeof(hash), &ctx.uECC,
  9225. sig, mg_uecc_secp256r1());
  9226. neg1 = !!(sig[0] & 0x80);
  9227. neg2 = !!(sig[32] & 0x80);
  9228. verify[8] = 0x30; // ASN.1 SEQUENCE
  9229. verify[9] = (uint8_t) (68 + neg1 + neg2);
  9230. verify[10] = 0x02; // ASN.1 INTEGER
  9231. verify[11] = (uint8_t) (32 + neg1);
  9232. memmove(verify + 12 + neg1, sig, 32);
  9233. verify[12 + 32 + neg1] = 0x02; // ASN.1 INTEGER
  9234. verify[13 + 32 + neg1] = (uint8_t) (32 + neg2);
  9235. memmove(verify + 14 + 32 + neg1 + neg2, sig + 32, 32);
  9236. sigsz = (size_t) (70 + neg1 + neg2);
  9237. verifysz = 8U + sigsz;
  9238. verify[3] = (uint8_t) (sigsz + 4);
  9239. verify[7] = (uint8_t) sigsz;
  9240. mg_sha256_update(&tls->sha256, verify, verifysz);
  9241. mg_tls_encrypt(c, verify, verifysz, MG_TLS_HANDSHAKE);
  9242. }
  9243. static void mg_tls_server_send_finish(struct mg_connection *c) {
  9244. struct tls_data *tls = (struct tls_data *) c->tls;
  9245. struct mg_iobuf *wio = &tls->send;
  9246. mg_sha256_ctx sha256;
  9247. uint8_t hash[32];
  9248. uint8_t finish[36] = {0x14, 0, 0, 32};
  9249. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9250. mg_sha256_final(hash, &sha256);
  9251. mg_hmac_sha256(finish + 4, tls->server_finished_key, 32, hash, 32);
  9252. mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
  9253. mg_io_send(c, wio->buf, wio->len);
  9254. wio->len = 0;
  9255. mg_sha256_update(&tls->sha256, finish, sizeof(finish));
  9256. }
  9257. static int mg_tls_server_recv_finish(struct mg_connection *c) {
  9258. struct tls_data *tls = (struct tls_data *) c->tls;
  9259. // we have to backup sha256 value to restore it later, since Finished record
  9260. // is exceptional and is not supposed to be added to the rolling hash
  9261. // calculation.
  9262. mg_sha256_ctx sha256 = tls->sha256;
  9263. if (mg_tls_recv_record(c) < 0) {
  9264. return -1;
  9265. }
  9266. if (tls->recv.buf[0] != MG_TLS_FINISHED) {
  9267. mg_error(c, "expected Finish but got msg 0x%02x", tls->recv.buf[0]);
  9268. return -1;
  9269. }
  9270. mg_tls_drop_message(c);
  9271. // restore hash
  9272. tls->sha256 = sha256;
  9273. return 0;
  9274. }
  9275. static void mg_tls_client_send_hello(struct mg_connection *c) {
  9276. struct tls_data *tls = (struct tls_data *) c->tls;
  9277. struct mg_iobuf *wio = &tls->send;
  9278. const char *hostname = tls->hostname;
  9279. size_t hostnamesz = strlen(tls->hostname);
  9280. uint8_t x25519_pub[X25519_BYTES];
  9281. uint8_t msg_client_hello[162 + 32] = {
  9282. // TLS Client Hello header reported as TLS1.2 (5)
  9283. 0x16,
  9284. 0x03,
  9285. 0x01,
  9286. 0x00,
  9287. 0xfe,
  9288. // server hello, tls 1.2 (6)
  9289. 0x01,
  9290. 0x00,
  9291. 0x00,
  9292. 0x8c,
  9293. 0x03,
  9294. 0x03,
  9295. // random (32 bytes)
  9296. PLACEHOLDER_32B,
  9297. // session ID length + session ID (32 bytes)
  9298. 0x20,
  9299. PLACEHOLDER_32B,
  9300. #if defined(CHACHA20) && CHACHA20
  9301. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  9302. 0x13,
  9303. 0x03,
  9304. 0x00,
  9305. #else
  9306. 0x00,
  9307. 0x02, // size = 2 bytes
  9308. 0x13,
  9309. 0x01, // TLS_AES_128_GCM_SHA256
  9310. 0x01,
  9311. 0x00, // no compression
  9312. #endif
  9313. // extensions + keyshare
  9314. 0x00,
  9315. 0xfe,
  9316. // x25519 keyshare
  9317. 0x00,
  9318. 0x33,
  9319. 0x00,
  9320. 0x26,
  9321. 0x00,
  9322. 0x24,
  9323. 0x00,
  9324. 0x1d,
  9325. 0x00,
  9326. 0x20,
  9327. PLACEHOLDER_32B,
  9328. // supported groups (x25519)
  9329. 0x00,
  9330. 0x0a,
  9331. 0x00,
  9332. 0x04,
  9333. 0x00,
  9334. 0x02,
  9335. 0x00,
  9336. 0x1d,
  9337. // supported versions (tls1.3 == 0x304)
  9338. 0x00,
  9339. 0x2b,
  9340. 0x00,
  9341. 0x03,
  9342. 0x02,
  9343. 0x03,
  9344. 0x04,
  9345. // session ticket (none)
  9346. 0x00,
  9347. 0x23,
  9348. 0x00,
  9349. 0x00,
  9350. // signature algorithms (we don't care, so list all the common ones)
  9351. 0x00,
  9352. 0x0d,
  9353. 0x00,
  9354. 0x24,
  9355. 0x00,
  9356. 0x22,
  9357. 0x04,
  9358. 0x03,
  9359. 0x05,
  9360. 0x03,
  9361. 0x06,
  9362. 0x03,
  9363. 0x08,
  9364. 0x07,
  9365. 0x08,
  9366. 0x08,
  9367. 0x08,
  9368. 0x1a,
  9369. 0x08,
  9370. 0x1b,
  9371. 0x08,
  9372. 0x1c,
  9373. 0x08,
  9374. 0x09,
  9375. 0x08,
  9376. 0x0a,
  9377. 0x08,
  9378. 0x0b,
  9379. 0x08,
  9380. 0x04,
  9381. 0x08,
  9382. 0x05,
  9383. 0x08,
  9384. 0x06,
  9385. 0x04,
  9386. 0x01,
  9387. 0x05,
  9388. 0x01,
  9389. 0x06,
  9390. 0x01,
  9391. // server name
  9392. 0x00,
  9393. 0x00,
  9394. 0x00,
  9395. 0xfe,
  9396. 0x00,
  9397. 0xfe,
  9398. 0x00,
  9399. 0x00,
  9400. 0xfe
  9401. };
  9402. // patch ClientHello with correct hostname length + offset:
  9403. MG_STORE_BE16(msg_client_hello + 3, hostnamesz + 189);
  9404. MG_STORE_BE16(msg_client_hello + 7, hostnamesz + 185);
  9405. MG_STORE_BE16(msg_client_hello + 82, hostnamesz + 110);
  9406. MG_STORE_BE16(msg_client_hello + 187, hostnamesz + 5);
  9407. MG_STORE_BE16(msg_client_hello + 189, hostnamesz + 3);
  9408. MG_STORE_BE16(msg_client_hello + 192, hostnamesz);
  9409. // calculate keyshare
  9410. mg_random(tls->x25519_cli, sizeof(tls->x25519_cli));
  9411. mg_tls_x25519(x25519_pub, tls->x25519_cli, X25519_BASE_POINT, 1);
  9412. // fill in the gaps: random + session ID + keyshare
  9413. mg_random(tls->session_id, sizeof(tls->session_id));
  9414. mg_random(tls->random, sizeof(tls->random));
  9415. memmove(msg_client_hello + 11, tls->random, sizeof(tls->random));
  9416. memmove(msg_client_hello + 44, tls->session_id, sizeof(tls->session_id));
  9417. memmove(msg_client_hello + 94, x25519_pub, sizeof(x25519_pub));
  9418. // server hello message
  9419. mg_iobuf_add(wio, wio->len, msg_client_hello, sizeof(msg_client_hello));
  9420. mg_iobuf_add(wio, wio->len, hostname, strlen(hostname));
  9421. mg_sha256_update(&tls->sha256, msg_client_hello + 5,
  9422. sizeof(msg_client_hello) - 5);
  9423. mg_sha256_update(&tls->sha256, (uint8_t *) hostname, strlen(hostname));
  9424. // change cipher message
  9425. mg_iobuf_add(wio, wio->len, (const char *) "\x14\x03\x03\x00\x01\x01", 6);
  9426. mg_io_send(c, wio->buf, wio->len);
  9427. wio->len = 0;
  9428. }
  9429. static int mg_tls_client_recv_hello(struct mg_connection *c) {
  9430. struct tls_data *tls = (struct tls_data *) c->tls;
  9431. struct mg_iobuf *rio = &c->rtls;
  9432. uint16_t msgsz;
  9433. uint8_t *ext;
  9434. uint16_t ext_len;
  9435. int j;
  9436. if (!mg_tls_got_record(c)) {
  9437. return MG_IO_WAIT;
  9438. }
  9439. if (rio->buf[0] != MG_TLS_HANDSHAKE || rio->buf[5] != MG_TLS_SERVER_HELLO) {
  9440. if (rio->buf[0] == MG_TLS_ALERT && rio->len >= 7) {
  9441. mg_error(c, "tls alert %d", rio->buf[6]);
  9442. return -1;
  9443. }
  9444. MG_INFO(("got packet type 0x%02x/0x%02x", rio->buf[0], rio->buf[5]));
  9445. mg_error(c, "not a server hello packet");
  9446. return -1;
  9447. }
  9448. msgsz = MG_LOAD_BE16(rio->buf + 3);
  9449. mg_sha256_update(&tls->sha256, rio->buf + 5, msgsz);
  9450. ext_len = MG_LOAD_BE16(rio->buf + 5 + 39 + 32 + 3);
  9451. ext = rio->buf + 5 + 39 + 32 + 3 + 2;
  9452. for (j = 0; j < ext_len;) {
  9453. uint16_t ext_type = MG_LOAD_BE16(ext + j);
  9454. uint16_t ext_len2 = MG_LOAD_BE16(ext + j + 2);
  9455. uint16_t group;
  9456. uint8_t *key_exchange;
  9457. uint16_t key_exchange_len;
  9458. if (ext_type != 0x0033) { // not a key share extension, ignore
  9459. j += (uint16_t) (ext_len2 + 4);
  9460. continue;
  9461. }
  9462. group = MG_LOAD_BE16(ext + j + 4);
  9463. if (group != 0x001d) {
  9464. mg_error(c, "bad key exchange group");
  9465. return -1;
  9466. }
  9467. key_exchange_len = MG_LOAD_BE16(ext + j + 6);
  9468. key_exchange = ext + j + 8;
  9469. if (key_exchange_len != 32) {
  9470. mg_error(c, "bad key exchange length");
  9471. return -1;
  9472. }
  9473. mg_tls_x25519(tls->x25519_sec, tls->x25519_cli, key_exchange, 1);
  9474. mg_tls_hexdump("c x25519 sec", tls->x25519_sec, 32);
  9475. mg_tls_drop_record(c);
  9476. /* generate handshake keys */
  9477. mg_tls_generate_handshake_keys(c);
  9478. return 0;
  9479. }
  9480. mg_error(c, "bad client hello");
  9481. return -1;
  9482. }
  9483. static int mg_tls_client_recv_ext(struct mg_connection *c) {
  9484. struct tls_data *tls = (struct tls_data *) c->tls;
  9485. if (mg_tls_recv_record(c) < 0) {
  9486. return -1;
  9487. }
  9488. if (tls->recv.buf[0] != MG_TLS_ENCRYPTED_EXTENSIONS) {
  9489. mg_error(c, "expected server extensions but got msg 0x%02x",
  9490. tls->recv.buf[0]);
  9491. return -1;
  9492. }
  9493. mg_tls_drop_message(c);
  9494. return 0;
  9495. }
  9496. static int mg_tls_client_recv_cert(struct mg_connection *c) {
  9497. uint8_t *cert;
  9498. uint32_t certsz;
  9499. struct mg_der_tlv oid, pubkey, seq, subj;
  9500. int subj_match = 0;
  9501. struct tls_data *tls = (struct tls_data *) c->tls;
  9502. if (mg_tls_recv_record(c) < 0) {
  9503. return -1;
  9504. }
  9505. if (tls->recv.buf[0] != MG_TLS_CERTIFICATE) {
  9506. mg_error(c, "expected server certificate but got msg 0x%02x",
  9507. tls->recv.buf[0]);
  9508. return -1;
  9509. }
  9510. if (tls->skip_verification) {
  9511. mg_tls_drop_message(c);
  9512. return 0;
  9513. }
  9514. if (tls->recv.len < 11) {
  9515. mg_error(c, "certificate list too short");
  9516. return -1;
  9517. }
  9518. cert = tls->recv.buf + 11;
  9519. certsz = MG_LOAD_BE24(tls->recv.buf + 8);
  9520. if (certsz > tls->recv.len - 11) {
  9521. mg_error(c, "certificate too long: %d vs %d", certsz, tls->recv.len - 11);
  9522. return -1;
  9523. }
  9524. do {
  9525. // secp256r1 public key
  9526. if (mg_der_find(cert, certsz,
  9527. (uint8_t *) "\x2A\x86\x48\xCE\x3D\x03\x01\x07", 8,
  9528. &oid) < 0) {
  9529. mg_error(c, "certificate secp256r1 public key OID not found");
  9530. return -1;
  9531. }
  9532. if (mg_der_to_tlv(oid.value + oid.len,
  9533. (size_t) (cert + certsz - (oid.value + oid.len)),
  9534. &pubkey) < 0) {
  9535. mg_error(c, "certificate secp256r1 public key not found");
  9536. return -1;
  9537. }
  9538. // expect BIT STRING, unpadded, uncompressed: [0]+[4]+32+32 content bytes
  9539. if (pubkey.type != 3 || pubkey.len != 66 || pubkey.value[0] != 0 ||
  9540. pubkey.value[1] != 4) {
  9541. mg_error(c, "unsupported public key bitstring encoding");
  9542. return -1;
  9543. }
  9544. memmove(tls->pubkey, pubkey.value + 2, pubkey.len - 2);
  9545. } while (0);
  9546. // Subject Alternative Names
  9547. do {
  9548. if (mg_der_find(cert, certsz, (uint8_t *) "\x55\x1d\x11", 3, &oid) < 0) {
  9549. mg_error(c, "certificate does not contain subject alternative names");
  9550. return -1;
  9551. }
  9552. if (mg_der_to_tlv(oid.value + oid.len,
  9553. (size_t) (cert + certsz - (oid.value + oid.len)),
  9554. &seq) < 0) {
  9555. mg_error(c, "certificate subject alternative names not found");
  9556. return -1;
  9557. }
  9558. if (mg_der_to_tlv(seq.value, seq.len, &seq) < 0) {
  9559. mg_error(
  9560. c,
  9561. "certificate subject alternative names is not a constructed object");
  9562. return -1;
  9563. }
  9564. MG_VERBOSE(("verify hostname %s", tls->hostname));
  9565. while (seq.len > 0) {
  9566. if (mg_der_to_tlv(seq.value, seq.len, &subj) < 0) {
  9567. mg_error(c, "bad subject alternative name");
  9568. return -1;
  9569. }
  9570. MG_VERBOSE(("subj=%.*s", subj.len, subj.value));
  9571. if (mg_match(mg_str((const char *) tls->hostname),
  9572. mg_str_n((const char *) subj.value, subj.len), NULL)) {
  9573. subj_match = 1;
  9574. break;
  9575. }
  9576. seq.len = (uint32_t) (seq.value + seq.len - (subj.value + subj.len));
  9577. seq.value = subj.value + subj.len;
  9578. }
  9579. if (!subj_match) {
  9580. mg_error(c, "certificate did not match the hostname");
  9581. return -1;
  9582. }
  9583. } while (0);
  9584. mg_tls_drop_message(c);
  9585. mg_tls_calc_cert_verify_hash(c, tls->sighash);
  9586. return 0;
  9587. }
  9588. static int mg_tls_client_recv_cert_verify(struct mg_connection *c) {
  9589. struct tls_data *tls = (struct tls_data *) c->tls;
  9590. if (mg_tls_recv_record(c) < 0) {
  9591. return -1;
  9592. }
  9593. if (tls->recv.buf[0] != MG_TLS_CERTIFICATE_VERIFY) {
  9594. mg_error(c, "expected server certificate verify but got msg 0x%02x",
  9595. tls->recv.buf[0]);
  9596. return -1;
  9597. }
  9598. // Ignore CertificateVerify is strict checks are not required
  9599. if (tls->skip_verification) {
  9600. mg_tls_drop_message(c);
  9601. return 0;
  9602. }
  9603. // Extract certificate signature and verify it using pubkey and sighash
  9604. do {
  9605. uint8_t sig[64];
  9606. struct mg_der_tlv seq, a, b;
  9607. if (mg_der_to_tlv(tls->recv.buf + 8, tls->recv.len - 8, &seq) < 0) {
  9608. mg_error(c, "verification message is not an ASN.1 DER sequence");
  9609. return -1;
  9610. }
  9611. if (mg_der_to_tlv(seq.value, seq.len, &a) < 0) {
  9612. mg_error(c, "missing first part of the signature");
  9613. return -1;
  9614. }
  9615. if (mg_der_to_tlv(a.value + a.len, seq.len - a.len, &b) < 0) {
  9616. mg_error(c, "missing second part of the signature");
  9617. return -1;
  9618. }
  9619. // Integers may be padded with zeroes
  9620. if (a.len > 32) {
  9621. a.value = a.value + (a.len - 32);
  9622. a.len = 32;
  9623. }
  9624. if (b.len > 32) {
  9625. b.value = b.value + (b.len - 32);
  9626. b.len = 32;
  9627. }
  9628. memmove(sig, a.value, a.len);
  9629. memmove(sig + 32, b.value, b.len);
  9630. if (mg_uecc_verify(tls->pubkey, tls->sighash, sizeof(tls->sighash), sig,
  9631. mg_uecc_secp256r1()) != 1) {
  9632. mg_error(c, "failed to verify certificate");
  9633. return -1;
  9634. }
  9635. } while (0);
  9636. mg_tls_drop_message(c);
  9637. return 0;
  9638. }
  9639. static int mg_tls_client_recv_finish(struct mg_connection *c) {
  9640. struct tls_data *tls = (struct tls_data *) c->tls;
  9641. if (mg_tls_recv_record(c) < 0) {
  9642. return -1;
  9643. }
  9644. if (tls->recv.buf[0] != MG_TLS_FINISHED) {
  9645. mg_error(c, "expected server finished but got msg 0x%02x",
  9646. tls->recv.buf[0]);
  9647. return -1;
  9648. }
  9649. mg_tls_drop_message(c);
  9650. return 0;
  9651. }
  9652. static void mg_tls_client_send_finish(struct mg_connection *c) {
  9653. struct tls_data *tls = (struct tls_data *) c->tls;
  9654. struct mg_iobuf *wio = &tls->send;
  9655. mg_sha256_ctx sha256;
  9656. uint8_t hash[32];
  9657. uint8_t finish[36] = {0x14, 0, 0, 32};
  9658. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  9659. mg_sha256_final(hash, &sha256);
  9660. mg_hmac_sha256(finish + 4, tls->client_finished_key, 32, hash, 32);
  9661. mg_tls_encrypt(c, finish, sizeof(finish), MG_TLS_HANDSHAKE);
  9662. mg_io_send(c, wio->buf, wio->len);
  9663. wio->len = 0;
  9664. }
  9665. static void mg_tls_client_handshake(struct mg_connection *c) {
  9666. struct tls_data *tls = (struct tls_data *) c->tls;
  9667. switch (tls->state) {
  9668. case MG_TLS_STATE_CLIENT_START:
  9669. mg_tls_client_send_hello(c);
  9670. tls->state = MG_TLS_STATE_CLIENT_WAIT_SH;
  9671. // Fallthrough
  9672. case MG_TLS_STATE_CLIENT_WAIT_SH:
  9673. if (mg_tls_client_recv_hello(c) < 0) {
  9674. break;
  9675. }
  9676. tls->state = MG_TLS_STATE_CLIENT_WAIT_EE;
  9677. // Fallthrough
  9678. case MG_TLS_STATE_CLIENT_WAIT_EE:
  9679. if (mg_tls_client_recv_ext(c) < 0) {
  9680. break;
  9681. }
  9682. tls->state = MG_TLS_STATE_CLIENT_WAIT_CERT;
  9683. // Fallthrough
  9684. case MG_TLS_STATE_CLIENT_WAIT_CERT:
  9685. if (mg_tls_client_recv_cert(c) < 0) {
  9686. break;
  9687. }
  9688. tls->state = MG_TLS_STATE_CLIENT_WAIT_CV;
  9689. // Fallthrough
  9690. case MG_TLS_STATE_CLIENT_WAIT_CV:
  9691. if (mg_tls_client_recv_cert_verify(c) < 0) {
  9692. break;
  9693. }
  9694. tls->state = MG_TLS_STATE_CLIENT_WAIT_FINISHED;
  9695. // Fallthrough
  9696. case MG_TLS_STATE_CLIENT_WAIT_FINISHED:
  9697. if (mg_tls_client_recv_finish(c) < 0) {
  9698. break;
  9699. }
  9700. mg_tls_client_send_finish(c);
  9701. mg_tls_generate_application_keys(c);
  9702. tls->state = MG_TLS_STATE_CLIENT_CONNECTED;
  9703. c->is_tls_hs = 0;
  9704. break;
  9705. default: mg_error(c, "unexpected client state: %d", tls->state); break;
  9706. }
  9707. }
  9708. static void mg_tls_server_handshake(struct mg_connection *c) {
  9709. struct tls_data *tls = (struct tls_data *) c->tls;
  9710. switch (tls->state) {
  9711. case MG_TLS_STATE_SERVER_START:
  9712. if (mg_tls_server_recv_hello(c) < 0) {
  9713. return;
  9714. }
  9715. mg_tls_server_send_hello(c);
  9716. mg_tls_generate_handshake_keys(c);
  9717. mg_tls_server_send_ext(c);
  9718. mg_tls_server_send_cert(c);
  9719. mg_tls_server_send_cert_verify(c);
  9720. mg_tls_server_send_finish(c);
  9721. tls->state = MG_TLS_STATE_SERVER_NEGOTIATED;
  9722. // fallthrough
  9723. case MG_TLS_STATE_SERVER_NEGOTIATED:
  9724. if (mg_tls_server_recv_finish(c) < 0) {
  9725. return;
  9726. }
  9727. mg_tls_generate_application_keys(c);
  9728. tls->state = MG_TLS_STATE_SERVER_CONNECTED;
  9729. c->is_tls_hs = 0;
  9730. return;
  9731. default: mg_error(c, "unexpected server state: %d", tls->state); break;
  9732. }
  9733. }
  9734. void mg_tls_handshake(struct mg_connection *c) {
  9735. if (c->is_client) {
  9736. mg_tls_client_handshake(c);
  9737. } else {
  9738. mg_tls_server_handshake(c);
  9739. }
  9740. }
  9741. static int mg_parse_pem(const struct mg_str pem, const struct mg_str label,
  9742. struct mg_str *der) {
  9743. size_t n = 0, m = 0;
  9744. char *s;
  9745. const char *c;
  9746. struct mg_str caps[5];
  9747. if (!mg_match(pem, mg_str("#-----BEGIN #-----#-----END #-----#"), caps)) {
  9748. der->buf = mg_mprintf("%.*s", pem.len, pem.buf);
  9749. der->len = pem.len;
  9750. return 0;
  9751. }
  9752. if (mg_strcmp(caps[1], label) != 0 || mg_strcmp(caps[3], label) != 0) {
  9753. return -1; // bad label
  9754. }
  9755. if ((s = (char *) calloc(1, caps[2].len)) == NULL) {
  9756. return -1;
  9757. }
  9758. for (c = caps[2].buf; c < caps[2].buf + caps[2].len; c++) {
  9759. if (*c == ' ' || *c == '\n' || *c == '\r' || *c == '\t') {
  9760. continue;
  9761. }
  9762. s[n++] = *c;
  9763. }
  9764. m = mg_base64_decode(s, n, s, n);
  9765. if (m == 0) {
  9766. free(s);
  9767. return -1;
  9768. }
  9769. der->buf = s;
  9770. der->len = m;
  9771. return 0;
  9772. }
  9773. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9774. struct mg_str key;
  9775. struct tls_data *tls = (struct tls_data *) calloc(1, sizeof(struct tls_data));
  9776. if (tls == NULL) {
  9777. mg_error(c, "tls oom");
  9778. return;
  9779. }
  9780. tls->state =
  9781. c->is_client ? MG_TLS_STATE_CLIENT_START : MG_TLS_STATE_SERVER_START;
  9782. tls->skip_verification = opts->skip_verification;
  9783. tls->send.align = MG_IO_SIZE;
  9784. c->tls = tls;
  9785. c->is_tls = c->is_tls_hs = 1;
  9786. mg_sha256_init(&tls->sha256);
  9787. // save hostname (client extension)
  9788. if (opts->name.len > 0) {
  9789. if (opts->name.len >= sizeof(tls->hostname) - 1) {
  9790. mg_error(c, "hostname too long");
  9791. }
  9792. strncpy((char *) tls->hostname, opts->name.buf, sizeof(tls->hostname) - 1);
  9793. tls->hostname[opts->name.len] = 0;
  9794. }
  9795. if (c->is_client) {
  9796. tls->server_cert_der.buf = NULL;
  9797. return;
  9798. }
  9799. // parse PEM or DER certificate
  9800. if (mg_parse_pem(opts->cert, mg_str_s("CERTIFICATE"), &tls->server_cert_der) <
  9801. 0) {
  9802. MG_ERROR(("Failed to load certificate"));
  9803. return;
  9804. }
  9805. // parse PEM or DER EC key
  9806. if (opts->key.buf == NULL) {
  9807. mg_error(c, "certificate provided without a private key");
  9808. return;
  9809. }
  9810. if (mg_parse_pem(opts->key, mg_str_s("EC PRIVATE KEY"), &key) == 0) {
  9811. if (key.len < 39) {
  9812. MG_ERROR(("EC private key too short"));
  9813. return;
  9814. }
  9815. // expect ASN.1 SEQUENCE=[INTEGER=1, BITSTRING of 32 bytes, ...]
  9816. // 30 nn 02 01 01 04 20 [key] ...
  9817. if (key.buf[0] != 0x30 || (key.buf[1] & 0x80) != 0) {
  9818. MG_ERROR(("EC private key: ASN.1 bad sequence"));
  9819. return;
  9820. }
  9821. if (memcmp(key.buf + 2, "\x02\x01\x01\x04\x20", 5) != 0) {
  9822. MG_ERROR(("EC private key: ASN.1 bad data"));
  9823. }
  9824. memmove(tls->server_key, key.buf + 7, 32);
  9825. free((void *) key.buf);
  9826. } else if (mg_parse_pem(opts->key, mg_str_s("PRIVATE KEY"), &key) == 0) {
  9827. mg_error(c, "PKCS8 private key format is not supported");
  9828. } else {
  9829. mg_error(c, "expected EC PRIVATE KEY or PRIVATE KEY");
  9830. }
  9831. }
  9832. void mg_tls_free(struct mg_connection *c) {
  9833. struct tls_data *tls = (struct tls_data *) c->tls;
  9834. if (tls != NULL) {
  9835. mg_iobuf_free(&tls->send);
  9836. free((void *) tls->server_cert_der.buf);
  9837. }
  9838. free(c->tls);
  9839. c->tls = NULL;
  9840. }
  9841. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9842. struct tls_data *tls = (struct tls_data *) c->tls;
  9843. long n = MG_IO_WAIT;
  9844. if (len > MG_IO_SIZE) len = MG_IO_SIZE;
  9845. mg_tls_encrypt(c, (const uint8_t *) buf, len, MG_TLS_APP_DATA);
  9846. while (tls->send.len > 0 &&
  9847. (n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {
  9848. mg_iobuf_del(&tls->send, 0, (size_t) n);
  9849. }
  9850. if (n == MG_IO_ERR || n == MG_IO_WAIT) return n;
  9851. return (long) len;
  9852. }
  9853. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9854. int r = 0;
  9855. struct tls_data *tls = (struct tls_data *) c->tls;
  9856. size_t minlen;
  9857. r = mg_tls_recv_record(c);
  9858. if (r < 0) {
  9859. return r;
  9860. }
  9861. if (tls->content_type != MG_TLS_APP_DATA) {
  9862. tls->recv.len = 0;
  9863. mg_tls_drop_record(c);
  9864. return MG_IO_WAIT;
  9865. }
  9866. minlen = len < tls->recv.len ? len : tls->recv.len;
  9867. memmove(buf, tls->recv.buf, minlen);
  9868. tls->recv.buf += minlen;
  9869. tls->recv.len -= minlen;
  9870. if (tls->recv.len == 0) {
  9871. mg_tls_drop_record(c);
  9872. }
  9873. return (long) minlen;
  9874. }
  9875. size_t mg_tls_pending(struct mg_connection *c) {
  9876. return mg_tls_got_record(c) ? 1 : 0;
  9877. }
  9878. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9879. (void) mgr;
  9880. }
  9881. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9882. (void) mgr;
  9883. }
  9884. #endif
  9885. #ifdef MG_ENABLE_LINES
  9886. #line 1 "src/tls_dummy.c"
  9887. #endif
  9888. #if MG_TLS == MG_TLS_NONE
  9889. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9890. (void) opts;
  9891. mg_error(c, "TLS is not enabled");
  9892. }
  9893. void mg_tls_handshake(struct mg_connection *c) {
  9894. (void) c;
  9895. }
  9896. void mg_tls_free(struct mg_connection *c) {
  9897. (void) c;
  9898. }
  9899. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9900. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  9901. }
  9902. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9903. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  9904. }
  9905. size_t mg_tls_pending(struct mg_connection *c) {
  9906. (void) c;
  9907. return 0;
  9908. }
  9909. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9910. (void) mgr;
  9911. }
  9912. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9913. (void) mgr;
  9914. }
  9915. #endif
  9916. #ifdef MG_ENABLE_LINES
  9917. #line 1 "src/tls_mbed.c"
  9918. #endif
  9919. #if MG_TLS == MG_TLS_MBED
  9920. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000
  9921. #define MG_MBEDTLS_RNG_GET , mg_mbed_rng, NULL
  9922. #else
  9923. #define MG_MBEDTLS_RNG_GET
  9924. #endif
  9925. static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) {
  9926. mg_random(buf, len);
  9927. (void) ctx;
  9928. return 0;
  9929. }
  9930. static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *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_x509_crt_parse(p, (uint8_t *) str.buf, str.len)) != 0) {
  9935. MG_ERROR(("cert err %#x", -rc));
  9936. return false;
  9937. }
  9938. return true;
  9939. }
  9940. static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) {
  9941. int rc;
  9942. if (str.buf == NULL || str.buf[0] == '\0' || str.buf[0] == '*') return true;
  9943. if (str.buf[0] == '-') str.len++; // PEM, include trailing NUL
  9944. if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.buf, str.len, NULL,
  9945. 0 MG_MBEDTLS_RNG_GET)) != 0) {
  9946. MG_ERROR(("key err %#x", -rc));
  9947. return false;
  9948. }
  9949. return true;
  9950. }
  9951. void mg_tls_free(struct mg_connection *c) {
  9952. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9953. if (tls != NULL) {
  9954. mbedtls_ssl_free(&tls->ssl);
  9955. mbedtls_pk_free(&tls->pk);
  9956. mbedtls_x509_crt_free(&tls->ca);
  9957. mbedtls_x509_crt_free(&tls->cert);
  9958. mbedtls_ssl_config_free(&tls->conf);
  9959. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  9960. mbedtls_ssl_ticket_free(&tls->ticket);
  9961. #endif
  9962. free(tls);
  9963. c->tls = NULL;
  9964. }
  9965. }
  9966. static int mg_net_send(void *ctx, const unsigned char *buf, size_t len) {
  9967. long n = mg_io_send((struct mg_connection *) ctx, buf, len);
  9968. MG_VERBOSE(("%lu n=%ld e=%d", ((struct mg_connection *) ctx)->id, n, errno));
  9969. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  9970. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  9971. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_SEND_FAILED;
  9972. return (int) n;
  9973. }
  9974. static int mg_net_recv(void *ctx, unsigned char *buf, size_t len) {
  9975. long n = mg_io_recv((struct mg_connection *) ctx, buf, len);
  9976. MG_VERBOSE(("%lu n=%ld", ((struct mg_connection *) ctx)->id, n));
  9977. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  9978. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  9979. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_RECV_FAILED;
  9980. return (int) n;
  9981. }
  9982. void mg_tls_handshake(struct mg_connection *c) {
  9983. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9984. int rc = mbedtls_ssl_handshake(&tls->ssl);
  9985. if (rc == 0) { // Success
  9986. MG_DEBUG(("%lu success", c->id));
  9987. c->is_tls_hs = 0;
  9988. mg_call(c, MG_EV_TLS_HS, NULL);
  9989. } else if (rc == MBEDTLS_ERR_SSL_WANT_READ ||
  9990. rc == MBEDTLS_ERR_SSL_WANT_WRITE) { // Still pending
  9991. MG_VERBOSE(("%lu pending, %d%d %d (-%#x)", c->id, c->is_connecting,
  9992. c->is_tls_hs, rc, -rc));
  9993. } else {
  9994. mg_error(c, "TLS handshake: -%#x", -rc); // Error
  9995. }
  9996. }
  9997. static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) {
  9998. n = (int) strlen(s2) - 1;
  9999. MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2));
  10000. (void) s;
  10001. }
  10002. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  10003. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  10004. int rc = 0;
  10005. c->tls = tls;
  10006. if (c->tls == NULL) {
  10007. mg_error(c, "TLS OOM");
  10008. goto fail;
  10009. }
  10010. if (c->is_listening) goto fail;
  10011. MG_DEBUG(("%lu Setting TLS", c->id));
  10012. MG_PROF_ADD(c, "mbedtls_init_start");
  10013. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000 && \
  10014. defined(MBEDTLS_PSA_CRYPTO_C)
  10015. psa_crypto_init(); // https://github.com/Mbed-TLS/mbedtls/issues/9072#issuecomment-2084845711
  10016. #endif
  10017. mbedtls_ssl_init(&tls->ssl);
  10018. mbedtls_ssl_config_init(&tls->conf);
  10019. mbedtls_x509_crt_init(&tls->ca);
  10020. mbedtls_x509_crt_init(&tls->cert);
  10021. mbedtls_pk_init(&tls->pk);
  10022. mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c);
  10023. #if defined(MG_MBEDTLS_DEBUG_LEVEL)
  10024. mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL);
  10025. #endif
  10026. if ((rc = mbedtls_ssl_config_defaults(
  10027. &tls->conf,
  10028. c->is_client ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
  10029. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  10030. mg_error(c, "tls defaults %#x", -rc);
  10031. goto fail;
  10032. }
  10033. mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c);
  10034. if (opts->ca.len == 0 || mg_strcmp(opts->ca, mg_str("*")) == 0) {
  10035. // NOTE: MBEDTLS_SSL_VERIFY_NONE is not supported for TLS1.3 on client side
  10036. // See https://github.com/Mbed-TLS/mbedtls/issues/7075
  10037. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
  10038. } else {
  10039. if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail;
  10040. mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL);
  10041. if (c->is_client && opts->name.buf != NULL && opts->name.buf[0] != '\0') {
  10042. char *host = mg_mprintf("%.*s", opts->name.len, opts->name.buf);
  10043. mbedtls_ssl_set_hostname(&tls->ssl, host);
  10044. MG_DEBUG(("%lu hostname verification: %s", c->id, host));
  10045. free(host);
  10046. }
  10047. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  10048. }
  10049. if (!mg_load_cert(opts->cert, &tls->cert)) goto fail;
  10050. if (!mg_load_key(opts->key, &tls->pk)) goto fail;
  10051. if (tls->cert.version &&
  10052. (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) {
  10053. mg_error(c, "own cert %#x", -rc);
  10054. goto fail;
  10055. }
  10056. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  10057. mbedtls_ssl_conf_session_tickets_cb(
  10058. &tls->conf, mbedtls_ssl_ticket_write, mbedtls_ssl_ticket_parse,
  10059. &((struct mg_tls_ctx *) c->mgr->tls_ctx)->tickets);
  10060. #endif
  10061. if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) {
  10062. mg_error(c, "setup err %#x", -rc);
  10063. goto fail;
  10064. }
  10065. c->is_tls = 1;
  10066. c->is_tls_hs = 1;
  10067. mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0);
  10068. MG_PROF_ADD(c, "mbedtls_init_end");
  10069. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  10070. mg_tls_handshake(c);
  10071. }
  10072. return;
  10073. fail:
  10074. mg_tls_free(c);
  10075. }
  10076. size_t mg_tls_pending(struct mg_connection *c) {
  10077. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10078. return tls == NULL ? 0 : mbedtls_ssl_get_bytes_avail(&tls->ssl);
  10079. }
  10080. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  10081. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10082. long n = mbedtls_ssl_read(&tls->ssl, (unsigned char *) buf, len);
  10083. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  10084. return MG_IO_WAIT;
  10085. #if defined(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET)
  10086. if (n == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) {
  10087. return MG_IO_WAIT;
  10088. }
  10089. #endif
  10090. if (n <= 0) return MG_IO_ERR;
  10091. return n;
  10092. }
  10093. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  10094. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10095. long n = mbedtls_ssl_write(&tls->ssl, (unsigned char *) buf, len);
  10096. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  10097. return MG_IO_WAIT;
  10098. if (n <= 0) return MG_IO_ERR;
  10099. return n;
  10100. }
  10101. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  10102. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx));
  10103. if (ctx == NULL) {
  10104. MG_ERROR(("TLS context init OOM"));
  10105. } else {
  10106. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  10107. int rc;
  10108. mbedtls_ssl_ticket_init(&ctx->tickets);
  10109. if ((rc = mbedtls_ssl_ticket_setup(&ctx->tickets, mg_mbed_rng, NULL,
  10110. MBEDTLS_CIPHER_AES_128_GCM, 86400)) !=
  10111. 0) {
  10112. MG_ERROR((" mbedtls_ssl_ticket_setup %#x", -rc));
  10113. }
  10114. #endif
  10115. mgr->tls_ctx = ctx;
  10116. }
  10117. }
  10118. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  10119. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx;
  10120. if (ctx != NULL) {
  10121. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  10122. mbedtls_ssl_ticket_free(&ctx->tickets);
  10123. #endif
  10124. free(ctx);
  10125. mgr->tls_ctx = NULL;
  10126. }
  10127. }
  10128. #endif
  10129. #ifdef MG_ENABLE_LINES
  10130. #line 1 "src/tls_openssl.c"
  10131. #endif
  10132. #if MG_TLS == MG_TLS_OPENSSL || MG_TLS == MG_TLS_WOLFSSL
  10133. static int tls_err_cb(const char *s, size_t len, void *c) {
  10134. int n = (int) len - 1;
  10135. MG_ERROR(("%lu %.*s", ((struct mg_connection *) c)->id, n, s));
  10136. return 0; // undocumented
  10137. }
  10138. static int mg_tls_err(struct mg_connection *c, struct mg_tls *tls, int res) {
  10139. int err = SSL_get_error(tls->ssl, res);
  10140. // We've just fetched the last error from the queue.
  10141. // Now we need to clear the error queue. If we do not, then the following
  10142. // can happen (actually reported):
  10143. // - A new connection is accept()-ed with cert error (e.g. self-signed cert)
  10144. // - Since all accept()-ed connections share listener's context,
  10145. // - *ALL* SSL accepted connection report read error on the next poll cycle.
  10146. // Thus a single errored connection can close all the rest, unrelated ones.
  10147. // Clearing the error keeps the shared SSL_CTX in an OK state.
  10148. if (err != 0) ERR_print_errors_cb(tls_err_cb, c);
  10149. ERR_clear_error();
  10150. if (err == SSL_ERROR_WANT_READ) return 0;
  10151. if (err == SSL_ERROR_WANT_WRITE) return 0;
  10152. return err;
  10153. }
  10154. static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) {
  10155. BIO *bio = BIO_new_mem_buf(ca.buf, (int) ca.len);
  10156. STACK_OF(X509_INFO) *certs =
  10157. bio ? PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL) : NULL;
  10158. if (bio) BIO_free(bio);
  10159. return certs;
  10160. }
  10161. static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) {
  10162. X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx);
  10163. for (int i = 0; i < sk_X509_INFO_num(certs); i++) {
  10164. X509_INFO *cert_info = sk_X509_INFO_value(certs, i);
  10165. if (cert_info->x509 && !X509_STORE_add_cert(cert_store, cert_info->x509))
  10166. return false;
  10167. }
  10168. return true;
  10169. }
  10170. static EVP_PKEY *load_key(struct mg_str s) {
  10171. BIO *bio = BIO_new_mem_buf(s.buf, (int) (long) s.len);
  10172. EVP_PKEY *key = bio ? PEM_read_bio_PrivateKey(bio, NULL, 0, NULL) : NULL;
  10173. if (bio) BIO_free(bio);
  10174. return key;
  10175. }
  10176. static X509 *load_cert(struct mg_str s) {
  10177. BIO *bio = BIO_new_mem_buf(s.buf, (int) (long) s.len);
  10178. X509 *cert = bio == NULL ? NULL
  10179. : s.buf[0] == '-'
  10180. ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM
  10181. : d2i_X509_bio(bio, NULL); // DER
  10182. if (bio) BIO_free(bio);
  10183. return cert;
  10184. }
  10185. static long mg_bio_ctrl(BIO *b, int cmd, long larg, void *pargs) {
  10186. long ret = 0;
  10187. if (cmd == BIO_CTRL_PUSH) ret = 1;
  10188. if (cmd == BIO_CTRL_POP) ret = 1;
  10189. if (cmd == BIO_CTRL_FLUSH) ret = 1;
  10190. #if MG_TLS == MG_TLS_OPENSSL
  10191. if (cmd == BIO_C_SET_NBIO) ret = 1;
  10192. #endif
  10193. // MG_DEBUG(("%d -> %ld", cmd, ret));
  10194. (void) b, (void) cmd, (void) larg, (void) pargs;
  10195. return ret;
  10196. }
  10197. static int mg_bio_read(BIO *bio, char *buf, int len) {
  10198. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  10199. long res = mg_io_recv(c, buf, (size_t) len);
  10200. // MG_DEBUG(("%p %d %ld", buf, len, res));
  10201. len = res > 0 ? (int) res : -1;
  10202. if (res == MG_IO_WAIT) BIO_set_retry_read(bio);
  10203. return len;
  10204. }
  10205. static int mg_bio_write(BIO *bio, const char *buf, int len) {
  10206. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  10207. long res = mg_io_send(c, buf, (size_t) len);
  10208. // MG_DEBUG(("%p %d %ld", buf, len, res));
  10209. len = res > 0 ? (int) res : -1;
  10210. if (res == MG_IO_WAIT) BIO_set_retry_write(bio);
  10211. return len;
  10212. }
  10213. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  10214. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  10215. const char *id = "mongoose";
  10216. static unsigned char s_initialised = 0;
  10217. BIO *bio = NULL;
  10218. int rc;
  10219. if (tls == NULL) {
  10220. mg_error(c, "TLS OOM");
  10221. goto fail;
  10222. }
  10223. if (!s_initialised) {
  10224. #if (CHIP_TYPE != CHIP_T113s)
  10225. SSL_library_init();
  10226. #else
  10227. //OPENSSL_init_ssl(0, NULL);
  10228. #endif
  10229. s_initialised++;
  10230. }
  10231. MG_DEBUG(("%lu Setting TLS", c->id));
  10232. tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method())
  10233. : SSL_CTX_new(SSLv23_server_method());
  10234. if ((tls->ssl = SSL_new(tls->ctx)) == NULL) {
  10235. mg_error(c, "SSL_new");
  10236. goto fail;
  10237. }
  10238. SSL_set_session_id_context(tls->ssl, (const uint8_t *) id,
  10239. (unsigned) strlen(id));
  10240. // Disable deprecated protocols
  10241. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2);
  10242. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3);
  10243. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1);
  10244. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1);
  10245. #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION
  10246. SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION);
  10247. #endif
  10248. #ifdef MG_ENABLE_OPENSSL_CIPHER_SERVER_PREFERENCE
  10249. SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10250. #endif
  10251. #if MG_TLS == MG_TLS_WOLFSSL && !defined(OPENSSL_COMPATIBLE_DEFAULTS)
  10252. if (opts->ca.len == 0 || mg_strcmp(opts->ca, mg_str("*")) == 0) {
  10253. // Older versions require that either the CA is loaded or SSL_VERIFY_NONE
  10254. // explicitly set
  10255. SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, NULL);
  10256. }
  10257. #endif
  10258. if (opts->ca.buf != NULL && opts->ca.buf[0] != '\0') {
  10259. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10260. NULL);
  10261. STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca);
  10262. rc = add_ca_certs(tls->ctx, certs);
  10263. sk_X509_INFO_pop_free(certs, X509_INFO_free);
  10264. if (!rc) {
  10265. mg_error(c, "CA err");
  10266. goto fail;
  10267. }
  10268. }
  10269. if (opts->cert.buf != NULL && opts->cert.buf[0] != '\0') {
  10270. X509 *cert = load_cert(opts->cert);
  10271. rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert);
  10272. X509_free(cert);
  10273. if (cert == NULL || rc != 1) {
  10274. mg_error(c, "CERT err %d", mg_tls_err(c, tls, rc));
  10275. goto fail;
  10276. }
  10277. }
  10278. if (opts->key.buf != NULL && opts->key.buf[0] != '\0') {
  10279. EVP_PKEY *key = load_key(opts->key);
  10280. rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key);
  10281. EVP_PKEY_free(key);
  10282. if (key == NULL || rc != 1) {
  10283. mg_error(c, "KEY err %d", mg_tls_err(c, tls, rc));
  10284. goto fail;
  10285. }
  10286. }
  10287. SSL_set_mode(tls->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  10288. #if MG_TLS == MG_TLS_OPENSSL && OPENSSL_VERSION_NUMBER > 0x10002000L
  10289. #if (CHIP_TYPE != CHIP_T113s)
  10290. (void) SSL_set_ecdh_auto(tls->ssl, 1);
  10291. #endif
  10292. #endif
  10293. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  10294. if (opts->name.len > 0) {
  10295. char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.buf);
  10296. #if MG_TLS != MG_TLS_WOLFSSL || LIBWOLFSSL_VERSION_HEX >= 0x05005002
  10297. SSL_set1_host(tls->ssl, s);
  10298. #else
  10299. X509_VERIFY_PARAM_set1_host(SSL_get0_param(tls->ssl), s, 0);
  10300. #endif
  10301. SSL_set_tlsext_host_name(tls->ssl, s);
  10302. free(s);
  10303. }
  10304. #endif
  10305. #if MG_TLS == MG_TLS_WOLFSSL
  10306. tls->bm = BIO_meth_new(0, "bio_mg");
  10307. #else
  10308. tls->bm = BIO_meth_new(BIO_get_new_index() | BIO_TYPE_SOURCE_SINK, "bio_mg");
  10309. #endif
  10310. BIO_meth_set_write(tls->bm, mg_bio_write);
  10311. BIO_meth_set_read(tls->bm, mg_bio_read);
  10312. BIO_meth_set_ctrl(tls->bm, mg_bio_ctrl);
  10313. bio = BIO_new(tls->bm);
  10314. BIO_set_data(bio, c);
  10315. SSL_set_bio(tls->ssl, bio, bio);
  10316. c->tls = tls;
  10317. c->is_tls = 1;
  10318. c->is_tls_hs = 1;
  10319. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  10320. mg_tls_handshake(c);
  10321. }
  10322. MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client"));
  10323. return;
  10324. fail:
  10325. free(tls);
  10326. }
  10327. void mg_tls_handshake(struct mg_connection *c) {
  10328. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10329. int rc = c->is_client ? SSL_connect(tls->ssl) : SSL_accept(tls->ssl);
  10330. if (rc == 1) {
  10331. MG_DEBUG(("%lu success", c->id));
  10332. c->is_tls_hs = 0;
  10333. mg_call(c, MG_EV_TLS_HS, NULL);
  10334. } else {
  10335. int code = mg_tls_err(c, tls, rc);
  10336. if (code != 0) mg_error(c, "tls hs: rc %d, err %d", rc, code);
  10337. }
  10338. }
  10339. void mg_tls_free(struct mg_connection *c) {
  10340. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10341. if (tls == NULL) return;
  10342. SSL_free(tls->ssl);
  10343. SSL_CTX_free(tls->ctx);
  10344. BIO_meth_free(tls->bm);
  10345. free(tls);
  10346. c->tls = NULL;
  10347. }
  10348. size_t mg_tls_pending(struct mg_connection *c) {
  10349. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10350. return tls == NULL ? 0 : (size_t) SSL_pending(tls->ssl);
  10351. }
  10352. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  10353. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10354. int n = SSL_read(tls->ssl, buf, (int) len);
  10355. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  10356. if (n <= 0) return MG_IO_ERR;
  10357. return n;
  10358. }
  10359. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  10360. struct mg_tls *tls = (struct mg_tls *) c->tls;
  10361. int n = SSL_write(tls->ssl, buf, (int) len);
  10362. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  10363. if (n <= 0) return MG_IO_ERR;
  10364. return n;
  10365. }
  10366. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  10367. (void) mgr;
  10368. }
  10369. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  10370. (void) mgr;
  10371. }
  10372. #endif
  10373. #ifdef MG_ENABLE_LINES
  10374. #line 1 "src/tls_uecc.c"
  10375. #endif
  10376. /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  10377. #if MG_TLS == MG_TLS_BUILTIN
  10378. #ifndef MG_UECC_RNG_MAX_TRIES
  10379. #define MG_UECC_RNG_MAX_TRIES 64
  10380. #endif
  10381. #if MG_UECC_ENABLE_VLI_API
  10382. #define MG_UECC_VLI_API
  10383. #else
  10384. #define MG_UECC_VLI_API static
  10385. #endif
  10386. #if (MG_UECC_PLATFORM == mg_uecc_avr) || (MG_UECC_PLATFORM == mg_uecc_arm) || \
  10387. (MG_UECC_PLATFORM == mg_uecc_arm_thumb) || \
  10388. (MG_UECC_PLATFORM == mg_uecc_arm_thumb2)
  10389. #define CONCATX(a, ...) a##__VA_ARGS__
  10390. #define CONCAT(a, ...) CONCATX(a, __VA_ARGS__)
  10391. #define STRX(a) #a
  10392. #define STR(a) STRX(a)
  10393. #define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__))))
  10394. #define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__))))
  10395. #define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__))))
  10396. #define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__))))
  10397. #define EVAL4(...) __VA_ARGS__
  10398. #define DEC_1 0
  10399. #define DEC_2 1
  10400. #define DEC_3 2
  10401. #define DEC_4 3
  10402. #define DEC_5 4
  10403. #define DEC_6 5
  10404. #define DEC_7 6
  10405. #define DEC_8 7
  10406. #define DEC_9 8
  10407. #define DEC_10 9
  10408. #define DEC_11 10
  10409. #define DEC_12 11
  10410. #define DEC_13 12
  10411. #define DEC_14 13
  10412. #define DEC_15 14
  10413. #define DEC_16 15
  10414. #define DEC_17 16
  10415. #define DEC_18 17
  10416. #define DEC_19 18
  10417. #define DEC_20 19
  10418. #define DEC_21 20
  10419. #define DEC_22 21
  10420. #define DEC_23 22
  10421. #define DEC_24 23
  10422. #define DEC_25 24
  10423. #define DEC_26 25
  10424. #define DEC_27 26
  10425. #define DEC_28 27
  10426. #define DEC_29 28
  10427. #define DEC_30 29
  10428. #define DEC_31 30
  10429. #define DEC_32 31
  10430. #define DEC(N) CONCAT(DEC_, N)
  10431. #define SECOND_ARG(_, val, ...) val
  10432. #define SOME_CHECK_0 ~, 0
  10433. #define GET_SECOND_ARG(...) SECOND_ARG(__VA_ARGS__, SOME, )
  10434. #define SOME_OR_0(N) GET_SECOND_ARG(CONCAT(SOME_CHECK_, N))
  10435. #define EMPTY(...)
  10436. #define DEFER(...) __VA_ARGS__ EMPTY()
  10437. #define REPEAT_NAME_0() REPEAT_0
  10438. #define REPEAT_NAME_SOME() REPEAT_SOME
  10439. #define REPEAT_0(...)
  10440. #define REPEAT_SOME(N, stuff) \
  10441. DEFER(CONCAT(REPEAT_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), stuff) stuff
  10442. #define REPEAT(N, stuff) EVAL(REPEAT_SOME(N, stuff))
  10443. #define REPEATM_NAME_0() REPEATM_0
  10444. #define REPEATM_NAME_SOME() REPEATM_SOME
  10445. #define REPEATM_0(...)
  10446. #define REPEATM_SOME(N, macro) \
  10447. macro(N) DEFER(CONCAT(REPEATM_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), macro)
  10448. #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro))
  10449. #endif
  10450. //
  10451. #if (MG_UECC_WORD_SIZE == 1)
  10452. #if MG_UECC_SUPPORTS_secp160r1
  10453. #define MG_UECC_MAX_WORDS 21 /* Due to the size of curve_n. */
  10454. #endif
  10455. #if MG_UECC_SUPPORTS_secp192r1
  10456. #undef MG_UECC_MAX_WORDS
  10457. #define MG_UECC_MAX_WORDS 24
  10458. #endif
  10459. #if MG_UECC_SUPPORTS_secp224r1
  10460. #undef MG_UECC_MAX_WORDS
  10461. #define MG_UECC_MAX_WORDS 28
  10462. #endif
  10463. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10464. #undef MG_UECC_MAX_WORDS
  10465. #define MG_UECC_MAX_WORDS 32
  10466. #endif
  10467. #elif (MG_UECC_WORD_SIZE == 4)
  10468. #if MG_UECC_SUPPORTS_secp160r1
  10469. #define MG_UECC_MAX_WORDS 6 /* Due to the size of curve_n. */
  10470. #endif
  10471. #if MG_UECC_SUPPORTS_secp192r1
  10472. #undef MG_UECC_MAX_WORDS
  10473. #define MG_UECC_MAX_WORDS 6
  10474. #endif
  10475. #if MG_UECC_SUPPORTS_secp224r1
  10476. #undef MG_UECC_MAX_WORDS
  10477. #define MG_UECC_MAX_WORDS 7
  10478. #endif
  10479. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10480. #undef MG_UECC_MAX_WORDS
  10481. #define MG_UECC_MAX_WORDS 8
  10482. #endif
  10483. #elif (MG_UECC_WORD_SIZE == 8)
  10484. #if MG_UECC_SUPPORTS_secp160r1
  10485. #define MG_UECC_MAX_WORDS 3
  10486. #endif
  10487. #if MG_UECC_SUPPORTS_secp192r1
  10488. #undef MG_UECC_MAX_WORDS
  10489. #define MG_UECC_MAX_WORDS 3
  10490. #endif
  10491. #if MG_UECC_SUPPORTS_secp224r1
  10492. #undef MG_UECC_MAX_WORDS
  10493. #define MG_UECC_MAX_WORDS 4
  10494. #endif
  10495. #if (MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1)
  10496. #undef MG_UECC_MAX_WORDS
  10497. #define MG_UECC_MAX_WORDS 4
  10498. #endif
  10499. #endif /* MG_UECC_WORD_SIZE */
  10500. #define BITS_TO_WORDS(num_bits) \
  10501. ((wordcount_t) ((num_bits + ((MG_UECC_WORD_SIZE * 8) - 1)) / \
  10502. (MG_UECC_WORD_SIZE * 8)))
  10503. #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
  10504. struct MG_UECC_Curve_t {
  10505. wordcount_t num_words;
  10506. wordcount_t num_bytes;
  10507. bitcount_t num_n_bits;
  10508. mg_uecc_word_t p[MG_UECC_MAX_WORDS];
  10509. mg_uecc_word_t n[MG_UECC_MAX_WORDS];
  10510. mg_uecc_word_t G[MG_UECC_MAX_WORDS * 2];
  10511. mg_uecc_word_t b[MG_UECC_MAX_WORDS];
  10512. void (*double_jacobian)(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  10513. mg_uecc_word_t *Z1, MG_UECC_Curve curve);
  10514. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  10515. void (*mod_sqrt)(mg_uecc_word_t *a, MG_UECC_Curve curve);
  10516. #endif
  10517. void (*x_side)(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  10518. MG_UECC_Curve curve);
  10519. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10520. void (*mmod_fast)(mg_uecc_word_t *result, mg_uecc_word_t *product);
  10521. #endif
  10522. };
  10523. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  10524. static void bcopy(uint8_t *dst, const uint8_t *src, unsigned num_bytes) {
  10525. while (0 != num_bytes) {
  10526. num_bytes--;
  10527. dst[num_bytes] = src[num_bytes];
  10528. }
  10529. }
  10530. #endif
  10531. static cmpresult_t mg_uecc_vli_cmp_unsafe(const mg_uecc_word_t *left,
  10532. const mg_uecc_word_t *right,
  10533. wordcount_t num_words);
  10534. #if (MG_UECC_PLATFORM == mg_uecc_arm || \
  10535. MG_UECC_PLATFORM == mg_uecc_arm_thumb || \
  10536. MG_UECC_PLATFORM == mg_uecc_arm_thumb2)
  10537. #endif
  10538. #if (MG_UECC_PLATFORM == mg_uecc_avr)
  10539. #endif
  10540. #ifndef asm_clear
  10541. #define asm_clear 0
  10542. #endif
  10543. #ifndef asm_set
  10544. #define asm_set 0
  10545. #endif
  10546. #ifndef asm_add
  10547. #define asm_add 0
  10548. #endif
  10549. #ifndef asm_sub
  10550. #define asm_sub 0
  10551. #endif
  10552. #ifndef asm_mult
  10553. #define asm_mult 0
  10554. #endif
  10555. #ifndef asm_rshift1
  10556. #define asm_rshift1 0
  10557. #endif
  10558. #ifndef asm_mmod_fast_secp256r1
  10559. #define asm_mmod_fast_secp256r1 0
  10560. #endif
  10561. #if defined(default_RNG_defined) && default_RNG_defined
  10562. static MG_UECC_RNG_Function g_rng_function = &default_RNG;
  10563. #else
  10564. static MG_UECC_RNG_Function g_rng_function = 0;
  10565. #endif
  10566. void mg_uecc_set_rng(MG_UECC_RNG_Function rng_function) {
  10567. g_rng_function = rng_function;
  10568. }
  10569. MG_UECC_RNG_Function mg_uecc_get_rng(void) {
  10570. return g_rng_function;
  10571. }
  10572. int mg_uecc_curve_private_key_size(MG_UECC_Curve curve) {
  10573. return BITS_TO_BYTES(curve->num_n_bits);
  10574. }
  10575. int mg_uecc_curve_public_key_size(MG_UECC_Curve curve) {
  10576. return 2 * curve->num_bytes;
  10577. }
  10578. #if !asm_clear
  10579. MG_UECC_VLI_API void mg_uecc_vli_clear(mg_uecc_word_t *vli,
  10580. wordcount_t num_words) {
  10581. wordcount_t i;
  10582. for (i = 0; i < num_words; ++i) {
  10583. vli[i] = 0;
  10584. }
  10585. }
  10586. #endif /* !asm_clear */
  10587. /* Constant-time comparison to zero - secure way to compare long integers */
  10588. /* Returns 1 if vli == 0, 0 otherwise. */
  10589. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_isZero(const mg_uecc_word_t *vli,
  10590. wordcount_t num_words) {
  10591. mg_uecc_word_t bits = 0;
  10592. wordcount_t i;
  10593. for (i = 0; i < num_words; ++i) {
  10594. bits |= vli[i];
  10595. }
  10596. return (bits == 0);
  10597. }
  10598. /* Returns nonzero if bit 'bit' of vli is set. */
  10599. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_testBit(const mg_uecc_word_t *vli,
  10600. bitcount_t bit) {
  10601. return (vli[bit >> MG_UECC_WORD_BITS_SHIFT] &
  10602. ((mg_uecc_word_t) 1 << (bit & MG_UECC_WORD_BITS_MASK)));
  10603. }
  10604. /* Counts the number of words in vli. */
  10605. static wordcount_t vli_numDigits(const mg_uecc_word_t *vli,
  10606. const wordcount_t max_words) {
  10607. wordcount_t i;
  10608. /* Search from the end until we find a non-zero digit.
  10609. We do it in reverse because we expect that most digits will be nonzero. */
  10610. for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
  10611. }
  10612. return (i + 1);
  10613. }
  10614. /* Counts the number of bits required to represent vli. */
  10615. MG_UECC_VLI_API bitcount_t mg_uecc_vli_numBits(const mg_uecc_word_t *vli,
  10616. const wordcount_t max_words) {
  10617. mg_uecc_word_t i;
  10618. mg_uecc_word_t digit;
  10619. wordcount_t num_digits = vli_numDigits(vli, max_words);
  10620. if (num_digits == 0) {
  10621. return 0;
  10622. }
  10623. digit = vli[num_digits - 1];
  10624. for (i = 0; digit; ++i) {
  10625. digit >>= 1;
  10626. }
  10627. return (((bitcount_t) ((num_digits - 1) << MG_UECC_WORD_BITS_SHIFT)) +
  10628. (bitcount_t) i);
  10629. }
  10630. /* Sets dest = src. */
  10631. #if !asm_set
  10632. MG_UECC_VLI_API void mg_uecc_vli_set(mg_uecc_word_t *dest,
  10633. const mg_uecc_word_t *src,
  10634. wordcount_t num_words) {
  10635. wordcount_t i;
  10636. for (i = 0; i < num_words; ++i) {
  10637. dest[i] = src[i];
  10638. }
  10639. }
  10640. #endif /* !asm_set */
  10641. /* Returns sign of left - right. */
  10642. static cmpresult_t mg_uecc_vli_cmp_unsafe(const mg_uecc_word_t *left,
  10643. const mg_uecc_word_t *right,
  10644. wordcount_t num_words) {
  10645. wordcount_t i;
  10646. for (i = num_words - 1; i >= 0; --i) {
  10647. if (left[i] > right[i]) {
  10648. return 1;
  10649. } else if (left[i] < right[i]) {
  10650. return -1;
  10651. }
  10652. }
  10653. return 0;
  10654. }
  10655. /* Constant-time comparison function - secure way to compare long integers */
  10656. /* Returns one if left == right, zero otherwise. */
  10657. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_equal(const mg_uecc_word_t *left,
  10658. const mg_uecc_word_t *right,
  10659. wordcount_t num_words) {
  10660. mg_uecc_word_t diff = 0;
  10661. wordcount_t i;
  10662. for (i = num_words - 1; i >= 0; --i) {
  10663. diff |= (left[i] ^ right[i]);
  10664. }
  10665. return (diff == 0);
  10666. }
  10667. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_sub(mg_uecc_word_t *result,
  10668. const mg_uecc_word_t *left,
  10669. const mg_uecc_word_t *right,
  10670. wordcount_t num_words);
  10671. /* Returns sign of left - right, in constant time. */
  10672. MG_UECC_VLI_API cmpresult_t mg_uecc_vli_cmp(const mg_uecc_word_t *left,
  10673. const mg_uecc_word_t *right,
  10674. wordcount_t num_words) {
  10675. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  10676. mg_uecc_word_t neg = !!mg_uecc_vli_sub(tmp, left, right, num_words);
  10677. mg_uecc_word_t equal = mg_uecc_vli_isZero(tmp, num_words);
  10678. return (cmpresult_t) (!equal - 2 * neg);
  10679. }
  10680. /* Computes vli = vli >> 1. */
  10681. #if !asm_rshift1
  10682. MG_UECC_VLI_API void mg_uecc_vli_rshift1(mg_uecc_word_t *vli,
  10683. wordcount_t num_words) {
  10684. mg_uecc_word_t *end = vli;
  10685. mg_uecc_word_t carry = 0;
  10686. vli += num_words;
  10687. while (vli-- > end) {
  10688. mg_uecc_word_t temp = *vli;
  10689. *vli = (temp >> 1) | carry;
  10690. carry = temp << (MG_UECC_WORD_BITS - 1);
  10691. }
  10692. }
  10693. #endif /* !asm_rshift1 */
  10694. /* Computes result = left + right, returning carry. Can modify in place. */
  10695. #if !asm_add
  10696. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_add(mg_uecc_word_t *result,
  10697. const mg_uecc_word_t *left,
  10698. const mg_uecc_word_t *right,
  10699. wordcount_t num_words) {
  10700. mg_uecc_word_t carry = 0;
  10701. wordcount_t i;
  10702. for (i = 0; i < num_words; ++i) {
  10703. mg_uecc_word_t sum = left[i] + right[i] + carry;
  10704. if (sum != left[i]) {
  10705. carry = (sum < left[i]);
  10706. }
  10707. result[i] = sum;
  10708. }
  10709. return carry;
  10710. }
  10711. #endif /* !asm_add */
  10712. /* Computes result = left - right, returning borrow. Can modify in place. */
  10713. #if !asm_sub
  10714. MG_UECC_VLI_API mg_uecc_word_t mg_uecc_vli_sub(mg_uecc_word_t *result,
  10715. const mg_uecc_word_t *left,
  10716. const mg_uecc_word_t *right,
  10717. wordcount_t num_words) {
  10718. mg_uecc_word_t borrow = 0;
  10719. wordcount_t i;
  10720. for (i = 0; i < num_words; ++i) {
  10721. mg_uecc_word_t diff = left[i] - right[i] - borrow;
  10722. if (diff != left[i]) {
  10723. borrow = (diff > left[i]);
  10724. }
  10725. result[i] = diff;
  10726. }
  10727. return borrow;
  10728. }
  10729. #endif /* !asm_sub */
  10730. #if !asm_mult || (MG_UECC_SQUARE_FUNC && !asm_square) || \
  10731. (MG_UECC_SUPPORTS_secp256k1 && (MG_UECC_OPTIMIZATION_LEVEL > 0) && \
  10732. ((MG_UECC_WORD_SIZE == 1) || (MG_UECC_WORD_SIZE == 8)))
  10733. static void muladd(mg_uecc_word_t a, mg_uecc_word_t b, mg_uecc_word_t *r0,
  10734. mg_uecc_word_t *r1, mg_uecc_word_t *r2) {
  10735. #if MG_UECC_WORD_SIZE == 8
  10736. uint64_t a0 = a & 0xffffffff;
  10737. uint64_t a1 = a >> 32;
  10738. uint64_t b0 = b & 0xffffffff;
  10739. uint64_t b1 = b >> 32;
  10740. uint64_t i0 = a0 * b0;
  10741. uint64_t i1 = a0 * b1;
  10742. uint64_t i2 = a1 * b0;
  10743. uint64_t i3 = a1 * b1;
  10744. uint64_t p0, p1;
  10745. i2 += (i0 >> 32);
  10746. i2 += i1;
  10747. if (i2 < i1) { /* overflow */
  10748. i3 += 0x100000000;
  10749. }
  10750. p0 = (i0 & 0xffffffff) | (i2 << 32);
  10751. p1 = i3 + (i2 >> 32);
  10752. *r0 += p0;
  10753. *r1 += (p1 + (*r0 < p0));
  10754. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  10755. #else
  10756. mg_uecc_dword_t p = (mg_uecc_dword_t) a * b;
  10757. mg_uecc_dword_t r01 = ((mg_uecc_dword_t) (*r1) << MG_UECC_WORD_BITS) | *r0;
  10758. r01 += p;
  10759. *r2 += (r01 < p);
  10760. *r1 = (mg_uecc_word_t) (r01 >> MG_UECC_WORD_BITS);
  10761. *r0 = (mg_uecc_word_t) r01;
  10762. #endif
  10763. }
  10764. #endif /* muladd needed */
  10765. #if !asm_mult
  10766. MG_UECC_VLI_API void mg_uecc_vli_mult(mg_uecc_word_t *result,
  10767. const mg_uecc_word_t *left,
  10768. const mg_uecc_word_t *right,
  10769. wordcount_t num_words) {
  10770. mg_uecc_word_t r0 = 0;
  10771. mg_uecc_word_t r1 = 0;
  10772. mg_uecc_word_t r2 = 0;
  10773. wordcount_t i, k;
  10774. /* Compute each digit of result in sequence, maintaining the carries. */
  10775. for (k = 0; k < num_words; ++k) {
  10776. for (i = 0; i <= k; ++i) {
  10777. muladd(left[i], right[k - i], &r0, &r1, &r2);
  10778. }
  10779. result[k] = r0;
  10780. r0 = r1;
  10781. r1 = r2;
  10782. r2 = 0;
  10783. }
  10784. for (k = num_words; k < num_words * 2 - 1; ++k) {
  10785. for (i = (wordcount_t) ((k + 1) - num_words); i < num_words; ++i) {
  10786. muladd(left[i], right[k - i], &r0, &r1, &r2);
  10787. }
  10788. result[k] = r0;
  10789. r0 = r1;
  10790. r1 = r2;
  10791. r2 = 0;
  10792. }
  10793. result[num_words * 2 - 1] = r0;
  10794. }
  10795. #endif /* !asm_mult */
  10796. #if MG_UECC_SQUARE_FUNC
  10797. #if !asm_square
  10798. static void mul2add(mg_uecc_word_t a, mg_uecc_word_t b, mg_uecc_word_t *r0,
  10799. mg_uecc_word_t *r1, mg_uecc_word_t *r2) {
  10800. #if MG_UECC_WORD_SIZE == 8
  10801. uint64_t a0 = a & 0xffffffffull;
  10802. uint64_t a1 = a >> 32;
  10803. uint64_t b0 = b & 0xffffffffull;
  10804. uint64_t b1 = b >> 32;
  10805. uint64_t i0 = a0 * b0;
  10806. uint64_t i1 = a0 * b1;
  10807. uint64_t i2 = a1 * b0;
  10808. uint64_t i3 = a1 * b1;
  10809. uint64_t p0, p1;
  10810. i2 += (i0 >> 32);
  10811. i2 += i1;
  10812. if (i2 < i1) { /* overflow */
  10813. i3 += 0x100000000ull;
  10814. }
  10815. p0 = (i0 & 0xffffffffull) | (i2 << 32);
  10816. p1 = i3 + (i2 >> 32);
  10817. *r2 += (p1 >> 63);
  10818. p1 = (p1 << 1) | (p0 >> 63);
  10819. p0 <<= 1;
  10820. *r0 += p0;
  10821. *r1 += (p1 + (*r0 < p0));
  10822. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  10823. #else
  10824. mg_uecc_dword_t p = (mg_uecc_dword_t) a * b;
  10825. mg_uecc_dword_t r01 = ((mg_uecc_dword_t) (*r1) << MG_UECC_WORD_BITS) | *r0;
  10826. *r2 += (p >> (MG_UECC_WORD_BITS * 2 - 1));
  10827. p *= 2;
  10828. r01 += p;
  10829. *r2 += (r01 < p);
  10830. *r1 = r01 >> MG_UECC_WORD_BITS;
  10831. *r0 = (mg_uecc_word_t) r01;
  10832. #endif
  10833. }
  10834. MG_UECC_VLI_API void mg_uecc_vli_square(mg_uecc_word_t *result,
  10835. const mg_uecc_word_t *left,
  10836. wordcount_t num_words) {
  10837. mg_uecc_word_t r0 = 0;
  10838. mg_uecc_word_t r1 = 0;
  10839. mg_uecc_word_t r2 = 0;
  10840. wordcount_t i, k;
  10841. for (k = 0; k < num_words * 2 - 1; ++k) {
  10842. mg_uecc_word_t min = (k < num_words ? 0 : (k + 1) - num_words);
  10843. for (i = min; i <= k && i <= k - i; ++i) {
  10844. if (i < k - i) {
  10845. mul2add(left[i], left[k - i], &r0, &r1, &r2);
  10846. } else {
  10847. muladd(left[i], left[k - i], &r0, &r1, &r2);
  10848. }
  10849. }
  10850. result[k] = r0;
  10851. r0 = r1;
  10852. r1 = r2;
  10853. r2 = 0;
  10854. }
  10855. result[num_words * 2 - 1] = r0;
  10856. }
  10857. #endif /* !asm_square */
  10858. #else /* MG_UECC_SQUARE_FUNC */
  10859. #if MG_UECC_ENABLE_VLI_API
  10860. MG_UECC_VLI_API void mg_uecc_vli_square(mg_uecc_word_t *result,
  10861. const mg_uecc_word_t *left,
  10862. wordcount_t num_words) {
  10863. mg_uecc_vli_mult(result, left, left, num_words);
  10864. }
  10865. #endif /* MG_UECC_ENABLE_VLI_API */
  10866. #endif /* MG_UECC_SQUARE_FUNC */
  10867. /* Computes result = (left + right) % mod.
  10868. Assumes that left < mod and right < mod, and that result does not overlap
  10869. mod. */
  10870. MG_UECC_VLI_API void mg_uecc_vli_modAdd(mg_uecc_word_t *result,
  10871. const mg_uecc_word_t *left,
  10872. const mg_uecc_word_t *right,
  10873. const mg_uecc_word_t *mod,
  10874. wordcount_t num_words) {
  10875. mg_uecc_word_t carry = mg_uecc_vli_add(result, left, right, num_words);
  10876. if (carry || mg_uecc_vli_cmp_unsafe(mod, result, num_words) != 1) {
  10877. /* result > mod (result = mod + remainder), so subtract mod to get
  10878. * remainder. */
  10879. mg_uecc_vli_sub(result, result, mod, num_words);
  10880. }
  10881. }
  10882. /* Computes result = (left - right) % mod.
  10883. Assumes that left < mod and right < mod, and that result does not overlap
  10884. mod. */
  10885. MG_UECC_VLI_API void mg_uecc_vli_modSub(mg_uecc_word_t *result,
  10886. const mg_uecc_word_t *left,
  10887. const mg_uecc_word_t *right,
  10888. const mg_uecc_word_t *mod,
  10889. wordcount_t num_words) {
  10890. mg_uecc_word_t l_borrow = mg_uecc_vli_sub(result, left, right, num_words);
  10891. if (l_borrow) {
  10892. /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
  10893. we can get the correct result from result + mod (with overflow). */
  10894. mg_uecc_vli_add(result, result, mod, num_words);
  10895. }
  10896. }
  10897. /* Computes result = product % mod, where product is 2N words long. */
  10898. /* Currently only designed to work for curve_p or curve_n. */
  10899. MG_UECC_VLI_API void mg_uecc_vli_mmod(mg_uecc_word_t *result,
  10900. mg_uecc_word_t *product,
  10901. const mg_uecc_word_t *mod,
  10902. wordcount_t num_words) {
  10903. mg_uecc_word_t mod_multiple[2 * MG_UECC_MAX_WORDS];
  10904. mg_uecc_word_t tmp[2 * MG_UECC_MAX_WORDS];
  10905. mg_uecc_word_t *v[2] = {tmp, product};
  10906. mg_uecc_word_t index;
  10907. /* Shift mod so its highest set bit is at the maximum position. */
  10908. bitcount_t shift = (bitcount_t) ((num_words * 2 * MG_UECC_WORD_BITS) -
  10909. mg_uecc_vli_numBits(mod, num_words));
  10910. wordcount_t word_shift = (wordcount_t) (shift / MG_UECC_WORD_BITS);
  10911. wordcount_t bit_shift = (wordcount_t) (shift % MG_UECC_WORD_BITS);
  10912. mg_uecc_word_t carry = 0;
  10913. mg_uecc_vli_clear(mod_multiple, word_shift);
  10914. if (bit_shift > 0) {
  10915. for (index = 0; index < (mg_uecc_word_t) num_words; ++index) {
  10916. mod_multiple[(mg_uecc_word_t) word_shift + index] =
  10917. (mg_uecc_word_t) (mod[index] << bit_shift) | carry;
  10918. carry = mod[index] >> (MG_UECC_WORD_BITS - bit_shift);
  10919. }
  10920. } else {
  10921. mg_uecc_vli_set(mod_multiple + word_shift, mod, num_words);
  10922. }
  10923. for (index = 1; shift >= 0; --shift) {
  10924. mg_uecc_word_t borrow = 0;
  10925. wordcount_t i;
  10926. for (i = 0; i < num_words * 2; ++i) {
  10927. mg_uecc_word_t diff = v[index][i] - mod_multiple[i] - borrow;
  10928. if (diff != v[index][i]) {
  10929. borrow = (diff > v[index][i]);
  10930. }
  10931. v[1 - index][i] = diff;
  10932. }
  10933. index = !(index ^ borrow); /* Swap the index if there was no borrow */
  10934. mg_uecc_vli_rshift1(mod_multiple, num_words);
  10935. mod_multiple[num_words - 1] |= mod_multiple[num_words]
  10936. << (MG_UECC_WORD_BITS - 1);
  10937. mg_uecc_vli_rshift1(mod_multiple + num_words, num_words);
  10938. }
  10939. mg_uecc_vli_set(result, v[index], num_words);
  10940. }
  10941. /* Computes result = (left * right) % mod. */
  10942. MG_UECC_VLI_API void mg_uecc_vli_modMult(mg_uecc_word_t *result,
  10943. const mg_uecc_word_t *left,
  10944. const mg_uecc_word_t *right,
  10945. const mg_uecc_word_t *mod,
  10946. wordcount_t num_words) {
  10947. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10948. mg_uecc_vli_mult(product, left, right, num_words);
  10949. mg_uecc_vli_mmod(result, product, mod, num_words);
  10950. }
  10951. MG_UECC_VLI_API void mg_uecc_vli_modMult_fast(mg_uecc_word_t *result,
  10952. const mg_uecc_word_t *left,
  10953. const mg_uecc_word_t *right,
  10954. MG_UECC_Curve curve) {
  10955. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10956. mg_uecc_vli_mult(product, left, right, curve->num_words);
  10957. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10958. curve->mmod_fast(result, product);
  10959. #else
  10960. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  10961. #endif
  10962. }
  10963. #if MG_UECC_SQUARE_FUNC
  10964. #if MG_UECC_ENABLE_VLI_API
  10965. /* Computes result = left^2 % mod. */
  10966. MG_UECC_VLI_API void mg_uecc_vli_modSquare(mg_uecc_word_t *result,
  10967. const mg_uecc_word_t *left,
  10968. const mg_uecc_word_t *mod,
  10969. wordcount_t num_words) {
  10970. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10971. mg_uecc_vli_square(product, left, num_words);
  10972. mg_uecc_vli_mmod(result, product, mod, num_words);
  10973. }
  10974. #endif /* MG_UECC_ENABLE_VLI_API */
  10975. MG_UECC_VLI_API void mg_uecc_vli_modSquare_fast(mg_uecc_word_t *result,
  10976. const mg_uecc_word_t *left,
  10977. MG_UECC_Curve curve) {
  10978. mg_uecc_word_t product[2 * MG_UECC_MAX_WORDS];
  10979. mg_uecc_vli_square(product, left, curve->num_words);
  10980. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  10981. curve->mmod_fast(result, product);
  10982. #else
  10983. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  10984. #endif
  10985. }
  10986. #else /* MG_UECC_SQUARE_FUNC */
  10987. #if MG_UECC_ENABLE_VLI_API
  10988. MG_UECC_VLI_API void mg_uecc_vli_modSquare(mg_uecc_word_t *result,
  10989. const mg_uecc_word_t *left,
  10990. const mg_uecc_word_t *mod,
  10991. wordcount_t num_words) {
  10992. mg_uecc_vli_modMult(result, left, left, mod, num_words);
  10993. }
  10994. #endif /* MG_UECC_ENABLE_VLI_API */
  10995. MG_UECC_VLI_API void mg_uecc_vli_modSquare_fast(mg_uecc_word_t *result,
  10996. const mg_uecc_word_t *left,
  10997. MG_UECC_Curve curve) {
  10998. mg_uecc_vli_modMult_fast(result, left, left, curve);
  10999. }
  11000. #endif /* MG_UECC_SQUARE_FUNC */
  11001. #define EVEN(vli) (!(vli[0] & 1))
  11002. static void vli_modInv_update(mg_uecc_word_t *uv, const mg_uecc_word_t *mod,
  11003. wordcount_t num_words) {
  11004. mg_uecc_word_t carry = 0;
  11005. if (!EVEN(uv)) {
  11006. carry = mg_uecc_vli_add(uv, uv, mod, num_words);
  11007. }
  11008. mg_uecc_vli_rshift1(uv, num_words);
  11009. if (carry) {
  11010. uv[num_words - 1] |= HIGH_BIT_SET;
  11011. }
  11012. }
  11013. /* Computes result = (1 / input) % mod. All VLIs are the same size.
  11014. See "From Euclid's GCD to Montgomery Multiplication to the Great Divide" */
  11015. MG_UECC_VLI_API void mg_uecc_vli_modInv(mg_uecc_word_t *result,
  11016. const mg_uecc_word_t *input,
  11017. const mg_uecc_word_t *mod,
  11018. wordcount_t num_words) {
  11019. mg_uecc_word_t a[MG_UECC_MAX_WORDS], b[MG_UECC_MAX_WORDS],
  11020. u[MG_UECC_MAX_WORDS], v[MG_UECC_MAX_WORDS];
  11021. cmpresult_t cmpResult;
  11022. if (mg_uecc_vli_isZero(input, num_words)) {
  11023. mg_uecc_vli_clear(result, num_words);
  11024. return;
  11025. }
  11026. mg_uecc_vli_set(a, input, num_words);
  11027. mg_uecc_vli_set(b, mod, num_words);
  11028. mg_uecc_vli_clear(u, num_words);
  11029. u[0] = 1;
  11030. mg_uecc_vli_clear(v, num_words);
  11031. while ((cmpResult = mg_uecc_vli_cmp_unsafe(a, b, num_words)) != 0) {
  11032. if (EVEN(a)) {
  11033. mg_uecc_vli_rshift1(a, num_words);
  11034. vli_modInv_update(u, mod, num_words);
  11035. } else if (EVEN(b)) {
  11036. mg_uecc_vli_rshift1(b, num_words);
  11037. vli_modInv_update(v, mod, num_words);
  11038. } else if (cmpResult > 0) {
  11039. mg_uecc_vli_sub(a, a, b, num_words);
  11040. mg_uecc_vli_rshift1(a, num_words);
  11041. if (mg_uecc_vli_cmp_unsafe(u, v, num_words) < 0) {
  11042. mg_uecc_vli_add(u, u, mod, num_words);
  11043. }
  11044. mg_uecc_vli_sub(u, u, v, num_words);
  11045. vli_modInv_update(u, mod, num_words);
  11046. } else {
  11047. mg_uecc_vli_sub(b, b, a, num_words);
  11048. mg_uecc_vli_rshift1(b, num_words);
  11049. if (mg_uecc_vli_cmp_unsafe(v, u, num_words) < 0) {
  11050. mg_uecc_vli_add(v, v, mod, num_words);
  11051. }
  11052. mg_uecc_vli_sub(v, v, u, num_words);
  11053. vli_modInv_update(v, mod, num_words);
  11054. }
  11055. }
  11056. mg_uecc_vli_set(result, u, num_words);
  11057. }
  11058. /* ------ Point operations ------ */
  11059. /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  11060. #ifndef _UECC_CURVE_SPECIFIC_H_
  11061. #define _UECC_CURVE_SPECIFIC_H_
  11062. #define num_bytes_secp160r1 20
  11063. #define num_bytes_secp192r1 24
  11064. #define num_bytes_secp224r1 28
  11065. #define num_bytes_secp256r1 32
  11066. #define num_bytes_secp256k1 32
  11067. #if (MG_UECC_WORD_SIZE == 1)
  11068. #define num_words_secp160r1 20
  11069. #define num_words_secp192r1 24
  11070. #define num_words_secp224r1 28
  11071. #define num_words_secp256r1 32
  11072. #define num_words_secp256k1 32
  11073. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) \
  11074. 0x##a, 0x##b, 0x##c, 0x##d, 0x##e, 0x##f, 0x##g, 0x##h
  11075. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##a, 0x##b, 0x##c, 0x##d
  11076. #elif (MG_UECC_WORD_SIZE == 4)
  11077. #define num_words_secp160r1 5
  11078. #define num_words_secp192r1 6
  11079. #define num_words_secp224r1 7
  11080. #define num_words_secp256r1 8
  11081. #define num_words_secp256k1 8
  11082. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
  11083. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
  11084. #elif (MG_UECC_WORD_SIZE == 8)
  11085. #define num_words_secp160r1 3
  11086. #define num_words_secp192r1 3
  11087. #define num_words_secp224r1 4
  11088. #define num_words_secp256r1 4
  11089. #define num_words_secp256k1 4
  11090. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##h##g##f##e##d##c##b##a##U
  11091. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a##U
  11092. #endif /* MG_UECC_WORD_SIZE */
  11093. #if MG_UECC_SUPPORTS_secp160r1 || MG_UECC_SUPPORTS_secp192r1 || \
  11094. MG_UECC_SUPPORTS_secp224r1 || MG_UECC_SUPPORTS_secp256r1
  11095. static void double_jacobian_default(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  11096. mg_uecc_word_t *Z1, MG_UECC_Curve curve) {
  11097. /* t1 = X, t2 = Y, t3 = Z */
  11098. mg_uecc_word_t t4[MG_UECC_MAX_WORDS];
  11099. mg_uecc_word_t t5[MG_UECC_MAX_WORDS];
  11100. wordcount_t num_words = curve->num_words;
  11101. if (mg_uecc_vli_isZero(Z1, num_words)) {
  11102. return;
  11103. }
  11104. mg_uecc_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */
  11105. mg_uecc_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
  11106. mg_uecc_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */
  11107. mg_uecc_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
  11108. mg_uecc_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */
  11109. mg_uecc_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
  11110. mg_uecc_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
  11111. mg_uecc_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
  11112. mg_uecc_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */
  11113. mg_uecc_vli_modAdd(Z1, X1, X1, curve->p,
  11114. num_words); /* t3 = 2*(x1^2 - z1^4) */
  11115. mg_uecc_vli_modAdd(X1, X1, Z1, curve->p,
  11116. num_words); /* t1 = 3*(x1^2 - z1^4) */
  11117. if (mg_uecc_vli_testBit(X1, 0)) {
  11118. mg_uecc_word_t l_carry = mg_uecc_vli_add(X1, X1, curve->p, num_words);
  11119. mg_uecc_vli_rshift1(X1, num_words);
  11120. X1[num_words - 1] |= l_carry << (MG_UECC_WORD_BITS - 1);
  11121. } else {
  11122. mg_uecc_vli_rshift1(X1, num_words);
  11123. }
  11124. /* t1 = 3/2*(x1^2 - z1^4) = B */
  11125. mg_uecc_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */
  11126. mg_uecc_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
  11127. mg_uecc_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
  11128. mg_uecc_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
  11129. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */
  11130. mg_uecc_vli_modSub(t4, X1, t4, curve->p,
  11131. num_words); /* t4 = B * (A - x3) - y1^4 = y3 */
  11132. mg_uecc_vli_set(X1, Z1, num_words);
  11133. mg_uecc_vli_set(Z1, Y1, num_words);
  11134. mg_uecc_vli_set(Y1, t4, num_words);
  11135. }
  11136. /* Computes result = x^3 + ax + b. result must not overlap x. */
  11137. static void x_side_default(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  11138. MG_UECC_Curve curve) {
  11139. mg_uecc_word_t _3[MG_UECC_MAX_WORDS] = {3}; /* -a = 3 */
  11140. wordcount_t num_words = curve->num_words;
  11141. mg_uecc_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  11142. mg_uecc_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
  11143. mg_uecc_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */
  11144. mg_uecc_vli_modAdd(result, result, curve->b, curve->p,
  11145. num_words); /* r = x^3 - 3x + b */
  11146. }
  11147. #endif /* MG_UECC_SUPPORTS_secp... */
  11148. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11149. #if MG_UECC_SUPPORTS_secp160r1 || MG_UECC_SUPPORTS_secp192r1 || \
  11150. MG_UECC_SUPPORTS_secp256r1 || MG_UECC_SUPPORTS_secp256k1
  11151. /* Compute a = sqrt(a) (mod curve_p). */
  11152. static void mod_sqrt_default(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  11153. bitcount_t i;
  11154. mg_uecc_word_t p1[MG_UECC_MAX_WORDS] = {1};
  11155. mg_uecc_word_t l_result[MG_UECC_MAX_WORDS] = {1};
  11156. wordcount_t num_words = curve->num_words;
  11157. /* When curve->p == 3 (mod 4), we can compute
  11158. sqrt(a) = a^((curve->p + 1) / 4) (mod curve->p). */
  11159. mg_uecc_vli_add(p1, curve->p, p1, num_words); /* p1 = curve_p + 1 */
  11160. for (i = mg_uecc_vli_numBits(p1, num_words) - 1; i > 1; --i) {
  11161. mg_uecc_vli_modSquare_fast(l_result, l_result, curve);
  11162. if (mg_uecc_vli_testBit(p1, i)) {
  11163. mg_uecc_vli_modMult_fast(l_result, l_result, a, curve);
  11164. }
  11165. }
  11166. mg_uecc_vli_set(a, l_result, num_words);
  11167. }
  11168. #endif /* MG_UECC_SUPPORTS_secp... */
  11169. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  11170. #if MG_UECC_SUPPORTS_secp160r1
  11171. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11172. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11173. mg_uecc_word_t *product);
  11174. #endif
  11175. static const struct MG_UECC_Curve_t curve_secp160r1 = {
  11176. num_words_secp160r1,
  11177. num_bytes_secp160r1,
  11178. 161, /* num_n_bits */
  11179. {BYTES_TO_WORDS_8(FF, FF, FF, 7F, FF, FF, FF, FF),
  11180. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11181. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11182. {BYTES_TO_WORDS_8(57, 22, 75, CA, D3, AE, 27, F9),
  11183. BYTES_TO_WORDS_8(C8, F4, 01, 00, 00, 00, 00, 00),
  11184. BYTES_TO_WORDS_8(00, 00, 00, 00, 01, 00, 00, 00)},
  11185. {BYTES_TO_WORDS_8(82, FC, CB, 13, B9, 8B, C3, 68),
  11186. BYTES_TO_WORDS_8(89, 69, 64, 46, 28, 73, F5, 8E),
  11187. BYTES_TO_WORDS_4(68, B5, 96, 4A),
  11188. BYTES_TO_WORDS_8(32, FB, C5, 7A, 37, 51, 23, 04),
  11189. BYTES_TO_WORDS_8(12, C9, DC, 59, 7D, 94, 68, 31),
  11190. BYTES_TO_WORDS_4(55, 28, A6, 23)},
  11191. {BYTES_TO_WORDS_8(45, FA, 65, C5, AD, D4, D4, 81),
  11192. BYTES_TO_WORDS_8(9F, F8, AC, 65, 8B, 7A, BD, 54),
  11193. BYTES_TO_WORDS_4(FC, BE, 97, 1C)},
  11194. &double_jacobian_default,
  11195. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11196. &mod_sqrt_default,
  11197. #endif
  11198. &x_side_default,
  11199. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11200. &vli_mmod_fast_secp160r1
  11201. #endif
  11202. };
  11203. MG_UECC_Curve mg_uecc_secp160r1(void) {
  11204. return &curve_secp160r1;
  11205. }
  11206. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1)
  11207. /* Computes result = product % curve_p
  11208. see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
  11209. Note that this only works if log2(omega) < log2(p) / 2 */
  11210. static void omega_mult_secp160r1(mg_uecc_word_t *result,
  11211. const mg_uecc_word_t *right);
  11212. #if MG_UECC_WORD_SIZE == 8
  11213. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11214. mg_uecc_word_t *product) {
  11215. mg_uecc_word_t tmp[2 * num_words_secp160r1];
  11216. mg_uecc_word_t copy;
  11217. mg_uecc_vli_clear(tmp, num_words_secp160r1);
  11218. mg_uecc_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  11219. omega_mult_secp160r1(tmp,
  11220. product + num_words_secp160r1 - 1); /* (Rq, q) = q * c */
  11221. product[num_words_secp160r1 - 1] &= 0xffffffff;
  11222. copy = tmp[num_words_secp160r1 - 1];
  11223. tmp[num_words_secp160r1 - 1] &= 0xffffffff;
  11224. mg_uecc_vli_add(result, product, tmp,
  11225. num_words_secp160r1); /* (C, r) = r + q */
  11226. mg_uecc_vli_clear(product, num_words_secp160r1);
  11227. tmp[num_words_secp160r1 - 1] = copy;
  11228. omega_mult_secp160r1(product, tmp + num_words_secp160r1 - 1); /* Rq*c */
  11229. mg_uecc_vli_add(result, result, product,
  11230. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  11231. while (mg_uecc_vli_cmp_unsafe(result, curve_secp160r1.p,
  11232. num_words_secp160r1) > 0) {
  11233. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11234. }
  11235. }
  11236. static void omega_mult_secp160r1(uint64_t *result, const uint64_t *right) {
  11237. uint32_t carry;
  11238. unsigned i;
  11239. /* Multiply by (2^31 + 1). */
  11240. carry = 0;
  11241. for (i = 0; i < num_words_secp160r1; ++i) {
  11242. uint64_t tmp = (right[i] >> 32) | (right[i + 1] << 32);
  11243. result[i] = (tmp << 31) + tmp + carry;
  11244. carry = (tmp >> 33) + (result[i] < tmp || (carry && result[i] == tmp));
  11245. }
  11246. result[i] = carry;
  11247. }
  11248. #else
  11249. static void vli_mmod_fast_secp160r1(mg_uecc_word_t *result,
  11250. mg_uecc_word_t *product) {
  11251. mg_uecc_word_t tmp[2 * num_words_secp160r1];
  11252. mg_uecc_word_t carry;
  11253. mg_uecc_vli_clear(tmp, num_words_secp160r1);
  11254. mg_uecc_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  11255. omega_mult_secp160r1(tmp,
  11256. product + num_words_secp160r1); /* (Rq, q) = q * c */
  11257. carry = mg_uecc_vli_add(result, product, tmp,
  11258. num_words_secp160r1); /* (C, r) = r + q */
  11259. mg_uecc_vli_clear(product, num_words_secp160r1);
  11260. omega_mult_secp160r1(product, tmp + num_words_secp160r1); /* Rq*c */
  11261. carry += mg_uecc_vli_add(result, result, product,
  11262. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  11263. while (carry > 0) {
  11264. --carry;
  11265. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11266. }
  11267. if (mg_uecc_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) >
  11268. 0) {
  11269. mg_uecc_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  11270. }
  11271. }
  11272. #endif
  11273. #if MG_UECC_WORD_SIZE == 1
  11274. static void omega_mult_secp160r1(uint8_t *result, const uint8_t *right) {
  11275. uint8_t carry;
  11276. uint8_t i;
  11277. /* Multiply by (2^31 + 1). */
  11278. mg_uecc_vli_set(result + 4, right, num_words_secp160r1); /* 2^32 */
  11279. mg_uecc_vli_rshift1(result + 4, num_words_secp160r1); /* 2^31 */
  11280. result[3] = right[0] << 7; /* get last bit from shift */
  11281. carry = mg_uecc_vli_add(result, result, right,
  11282. num_words_secp160r1); /* 2^31 + 1 */
  11283. for (i = num_words_secp160r1; carry; ++i) {
  11284. uint16_t sum = (uint16_t) result[i] + carry;
  11285. result[i] = (uint8_t) sum;
  11286. carry = sum >> 8;
  11287. }
  11288. }
  11289. #elif MG_UECC_WORD_SIZE == 4
  11290. static void omega_mult_secp160r1(uint32_t *result, const uint32_t *right) {
  11291. uint32_t carry;
  11292. unsigned i;
  11293. /* Multiply by (2^31 + 1). */
  11294. mg_uecc_vli_set(result + 1, right, num_words_secp160r1); /* 2^32 */
  11295. mg_uecc_vli_rshift1(result + 1, num_words_secp160r1); /* 2^31 */
  11296. result[0] = right[0] << 31; /* get last bit from shift */
  11297. carry = mg_uecc_vli_add(result, result, right,
  11298. num_words_secp160r1); /* 2^31 + 1 */
  11299. for (i = num_words_secp160r1; carry; ++i) {
  11300. uint64_t sum = (uint64_t) result[i] + carry;
  11301. result[i] = (uint32_t) sum;
  11302. carry = sum >> 32;
  11303. }
  11304. }
  11305. #endif /* MG_UECC_WORD_SIZE */
  11306. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) */
  11307. #endif /* MG_UECC_SUPPORTS_secp160r1 */
  11308. #if MG_UECC_SUPPORTS_secp192r1
  11309. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11310. static void vli_mmod_fast_secp192r1(mg_uecc_word_t *result,
  11311. mg_uecc_word_t *product);
  11312. #endif
  11313. static const struct MG_UECC_Curve_t curve_secp192r1 = {
  11314. num_words_secp192r1,
  11315. num_bytes_secp192r1,
  11316. 192, /* num_n_bits */
  11317. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11318. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  11319. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11320. {BYTES_TO_WORDS_8(31, 28, D2, B4, B1, C9, 6B, 14),
  11321. BYTES_TO_WORDS_8(36, F8, DE, 99, FF, FF, FF, FF),
  11322. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11323. {BYTES_TO_WORDS_8(12, 10, FF, 82, FD, 0A, FF, F4),
  11324. BYTES_TO_WORDS_8(00, 88, A1, 43, EB, 20, BF, 7C),
  11325. BYTES_TO_WORDS_8(F6, 90, 30, B0, 0E, A8, 8D, 18),
  11326. BYTES_TO_WORDS_8(11, 48, 79, 1E, A1, 77, F9, 73),
  11327. BYTES_TO_WORDS_8(D5, CD, 24, 6B, ED, 11, 10, 63),
  11328. BYTES_TO_WORDS_8(78, DA, C8, FF, 95, 2B, 19, 07)},
  11329. {BYTES_TO_WORDS_8(B1, B9, 46, C1, EC, DE, B8, FE),
  11330. BYTES_TO_WORDS_8(49, 30, 24, 72, AB, E9, A7, 0F),
  11331. BYTES_TO_WORDS_8(E7, 80, 9C, E5, 19, 05, 21, 64)},
  11332. &double_jacobian_default,
  11333. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11334. &mod_sqrt_default,
  11335. #endif
  11336. &x_side_default,
  11337. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11338. &vli_mmod_fast_secp192r1
  11339. #endif
  11340. };
  11341. MG_UECC_Curve mg_uecc_secp192r1(void) {
  11342. return &curve_secp192r1;
  11343. }
  11344. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11345. /* Computes result = product % curve_p.
  11346. See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf
  11347. */
  11348. #if MG_UECC_WORD_SIZE == 1
  11349. static void vli_mmod_fast_secp192r1(uint8_t *result, uint8_t *product) {
  11350. uint8_t tmp[num_words_secp192r1];
  11351. uint8_t carry;
  11352. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11353. mg_uecc_vli_set(tmp, &product[24], num_words_secp192r1);
  11354. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11355. tmp[0] = tmp[1] = tmp[2] = tmp[3] = tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11356. tmp[8] = product[24];
  11357. tmp[9] = product[25];
  11358. tmp[10] = product[26];
  11359. tmp[11] = product[27];
  11360. tmp[12] = product[28];
  11361. tmp[13] = product[29];
  11362. tmp[14] = product[30];
  11363. tmp[15] = product[31];
  11364. tmp[16] = product[32];
  11365. tmp[17] = product[33];
  11366. tmp[18] = product[34];
  11367. tmp[19] = product[35];
  11368. tmp[20] = product[36];
  11369. tmp[21] = product[37];
  11370. tmp[22] = product[38];
  11371. tmp[23] = product[39];
  11372. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11373. tmp[0] = tmp[8] = product[40];
  11374. tmp[1] = tmp[9] = product[41];
  11375. tmp[2] = tmp[10] = product[42];
  11376. tmp[3] = tmp[11] = product[43];
  11377. tmp[4] = tmp[12] = product[44];
  11378. tmp[5] = tmp[13] = product[45];
  11379. tmp[6] = tmp[14] = product[46];
  11380. tmp[7] = tmp[15] = product[47];
  11381. tmp[16] = tmp[17] = tmp[18] = tmp[19] = tmp[20] = tmp[21] = tmp[22] =
  11382. tmp[23] = 0;
  11383. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11384. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11385. num_words_secp192r1) != 1) {
  11386. carry -=
  11387. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11388. }
  11389. }
  11390. #elif MG_UECC_WORD_SIZE == 4
  11391. static void vli_mmod_fast_secp192r1(uint32_t *result, uint32_t *product) {
  11392. uint32_t tmp[num_words_secp192r1];
  11393. int carry;
  11394. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11395. mg_uecc_vli_set(tmp, &product[6], num_words_secp192r1);
  11396. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11397. tmp[0] = tmp[1] = 0;
  11398. tmp[2] = product[6];
  11399. tmp[3] = product[7];
  11400. tmp[4] = product[8];
  11401. tmp[5] = product[9];
  11402. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11403. tmp[0] = tmp[2] = product[10];
  11404. tmp[1] = tmp[3] = product[11];
  11405. tmp[4] = tmp[5] = 0;
  11406. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11407. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11408. num_words_secp192r1) != 1) {
  11409. carry -=
  11410. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11411. }
  11412. }
  11413. #else
  11414. static void vli_mmod_fast_secp192r1(uint64_t *result, uint64_t *product) {
  11415. uint64_t tmp[num_words_secp192r1];
  11416. int carry;
  11417. mg_uecc_vli_set(result, product, num_words_secp192r1);
  11418. mg_uecc_vli_set(tmp, &product[3], num_words_secp192r1);
  11419. carry = (int) mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11420. tmp[0] = 0;
  11421. tmp[1] = product[3];
  11422. tmp[2] = product[4];
  11423. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11424. tmp[0] = tmp[1] = product[5];
  11425. tmp[2] = 0;
  11426. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp192r1);
  11427. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp192r1.p, result,
  11428. num_words_secp192r1) != 1) {
  11429. carry -=
  11430. mg_uecc_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  11431. }
  11432. }
  11433. #endif /* MG_UECC_WORD_SIZE */
  11434. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0) */
  11435. #endif /* MG_UECC_SUPPORTS_secp192r1 */
  11436. #if MG_UECC_SUPPORTS_secp224r1
  11437. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11438. static void mod_sqrt_secp224r1(mg_uecc_word_t *a, MG_UECC_Curve curve);
  11439. #endif
  11440. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11441. static void vli_mmod_fast_secp224r1(mg_uecc_word_t *result,
  11442. mg_uecc_word_t *product);
  11443. #endif
  11444. static const struct MG_UECC_Curve_t curve_secp224r1 = {
  11445. num_words_secp224r1,
  11446. num_bytes_secp224r1,
  11447. 224, /* num_n_bits */
  11448. {BYTES_TO_WORDS_8(01, 00, 00, 00, 00, 00, 00, 00),
  11449. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF),
  11450. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11451. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11452. {BYTES_TO_WORDS_8(3D, 2A, 5C, 5C, 45, 29, DD, 13),
  11453. BYTES_TO_WORDS_8(3E, F0, B8, E0, A2, 16, FF, FF),
  11454. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11455. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  11456. {BYTES_TO_WORDS_8(21, 1D, 5C, 11, D6, 80, 32, 34),
  11457. BYTES_TO_WORDS_8(22, 11, C2, 56, D3, C1, 03, 4A),
  11458. BYTES_TO_WORDS_8(B9, 90, 13, 32, 7F, BF, B4, 6B),
  11459. BYTES_TO_WORDS_4(BD, 0C, 0E, B7),
  11460. BYTES_TO_WORDS_8(34, 7E, 00, 85, 99, 81, D5, 44),
  11461. BYTES_TO_WORDS_8(64, 47, 07, 5A, A0, 75, 43, CD),
  11462. BYTES_TO_WORDS_8(E6, DF, 22, 4C, FB, 23, F7, B5),
  11463. BYTES_TO_WORDS_4(88, 63, 37, BD)},
  11464. {BYTES_TO_WORDS_8(B4, FF, 55, 23, 43, 39, 0B, 27),
  11465. BYTES_TO_WORDS_8(BA, D8, BF, D7, B7, B0, 44, 50),
  11466. BYTES_TO_WORDS_8(56, 32, 41, F5, AB, B3, 04, 0C),
  11467. BYTES_TO_WORDS_4(85, 0A, 05, B4)},
  11468. &double_jacobian_default,
  11469. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11470. &mod_sqrt_secp224r1,
  11471. #endif
  11472. &x_side_default,
  11473. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11474. &vli_mmod_fast_secp224r1
  11475. #endif
  11476. };
  11477. MG_UECC_Curve mg_uecc_secp224r1(void) {
  11478. return &curve_secp224r1;
  11479. }
  11480. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11481. /* Routine 3.2.4 RS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11482. static void mod_sqrt_secp224r1_rs(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11483. mg_uecc_word_t *f1, const mg_uecc_word_t *d0,
  11484. const mg_uecc_word_t *e0,
  11485. const mg_uecc_word_t *f0) {
  11486. mg_uecc_word_t t[num_words_secp224r1];
  11487. mg_uecc_vli_modSquare_fast(t, d0, &curve_secp224r1); /* t <-- d0 ^ 2 */
  11488. mg_uecc_vli_modMult_fast(e1, d0, e0, &curve_secp224r1); /* e1 <-- d0 * e0 */
  11489. mg_uecc_vli_modAdd(d1, t, f0, curve_secp224r1.p,
  11490. num_words_secp224r1); /* d1 <-- t + f0 */
  11491. mg_uecc_vli_modAdd(e1, e1, e1, curve_secp224r1.p,
  11492. num_words_secp224r1); /* e1 <-- e1 + e1 */
  11493. mg_uecc_vli_modMult_fast(f1, t, f0, &curve_secp224r1); /* f1 <-- t * f0 */
  11494. mg_uecc_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  11495. num_words_secp224r1); /* f1 <-- f1 + f1 */
  11496. mg_uecc_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  11497. num_words_secp224r1); /* f1 <-- f1 + f1 */
  11498. }
  11499. /* Routine 3.2.5 RSS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11500. static void mod_sqrt_secp224r1_rss(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11501. mg_uecc_word_t *f1, const mg_uecc_word_t *d0,
  11502. const mg_uecc_word_t *e0,
  11503. const mg_uecc_word_t *f0,
  11504. const bitcount_t j) {
  11505. bitcount_t i;
  11506. mg_uecc_vli_set(d1, d0, num_words_secp224r1); /* d1 <-- d0 */
  11507. mg_uecc_vli_set(e1, e0, num_words_secp224r1); /* e1 <-- e0 */
  11508. mg_uecc_vli_set(f1, f0, num_words_secp224r1); /* f1 <-- f0 */
  11509. for (i = 1; i <= j; i++) {
  11510. mod_sqrt_secp224r1_rs(d1, e1, f1, d1, e1, f1); /* RS (d1,e1,f1,d1,e1,f1) */
  11511. }
  11512. }
  11513. /* Routine 3.2.6 RM; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11514. static void mod_sqrt_secp224r1_rm(mg_uecc_word_t *d2, mg_uecc_word_t *e2,
  11515. mg_uecc_word_t *f2, const mg_uecc_word_t *c,
  11516. const mg_uecc_word_t *d0,
  11517. const mg_uecc_word_t *e0,
  11518. const mg_uecc_word_t *d1,
  11519. const mg_uecc_word_t *e1) {
  11520. mg_uecc_word_t t1[num_words_secp224r1];
  11521. mg_uecc_word_t t2[num_words_secp224r1];
  11522. mg_uecc_vli_modMult_fast(t1, e0, e1, &curve_secp224r1); /* t1 <-- e0 * e1 */
  11523. mg_uecc_vli_modMult_fast(t1, t1, c, &curve_secp224r1); /* t1 <-- t1 * c */
  11524. /* t1 <-- p - t1 */
  11525. mg_uecc_vli_modSub(t1, curve_secp224r1.p, t1, curve_secp224r1.p,
  11526. num_words_secp224r1);
  11527. mg_uecc_vli_modMult_fast(t2, d0, d1, &curve_secp224r1); /* t2 <-- d0 * d1 */
  11528. mg_uecc_vli_modAdd(t2, t2, t1, curve_secp224r1.p,
  11529. num_words_secp224r1); /* t2 <-- t2 + t1 */
  11530. mg_uecc_vli_modMult_fast(t1, d0, e1, &curve_secp224r1); /* t1 <-- d0 * e1 */
  11531. mg_uecc_vli_modMult_fast(e2, d1, e0, &curve_secp224r1); /* e2 <-- d1 * e0 */
  11532. mg_uecc_vli_modAdd(e2, e2, t1, curve_secp224r1.p,
  11533. num_words_secp224r1); /* e2 <-- e2 + t1 */
  11534. mg_uecc_vli_modSquare_fast(f2, e2, &curve_secp224r1); /* f2 <-- e2^2 */
  11535. mg_uecc_vli_modMult_fast(f2, f2, c, &curve_secp224r1); /* f2 <-- f2 * c */
  11536. /* f2 <-- p - f2 */
  11537. mg_uecc_vli_modSub(f2, curve_secp224r1.p, f2, curve_secp224r1.p,
  11538. num_words_secp224r1);
  11539. mg_uecc_vli_set(d2, t2, num_words_secp224r1); /* d2 <-- t2 */
  11540. }
  11541. /* Routine 3.2.7 RP; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11542. static void mod_sqrt_secp224r1_rp(mg_uecc_word_t *d1, mg_uecc_word_t *e1,
  11543. mg_uecc_word_t *f1, const mg_uecc_word_t *c,
  11544. const mg_uecc_word_t *r) {
  11545. wordcount_t i;
  11546. wordcount_t pow2i = 1;
  11547. mg_uecc_word_t d0[num_words_secp224r1];
  11548. mg_uecc_word_t e0[num_words_secp224r1] = {1}; /* e0 <-- 1 */
  11549. mg_uecc_word_t f0[num_words_secp224r1];
  11550. mg_uecc_vli_set(d0, r, num_words_secp224r1); /* d0 <-- r */
  11551. /* f0 <-- p - c */
  11552. mg_uecc_vli_modSub(f0, curve_secp224r1.p, c, curve_secp224r1.p,
  11553. num_words_secp224r1);
  11554. for (i = 0; i <= 6; i++) {
  11555. mod_sqrt_secp224r1_rss(d1, e1, f1, d0, e0, f0,
  11556. pow2i); /* RSS (d1,e1,f1,d0,e0,f0,2^i) */
  11557. mod_sqrt_secp224r1_rm(d1, e1, f1, c, d1, e1, d0,
  11558. e0); /* RM (d1,e1,f1,c,d1,e1,d0,e0) */
  11559. mg_uecc_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  11560. mg_uecc_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  11561. mg_uecc_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  11562. pow2i *= 2;
  11563. }
  11564. }
  11565. /* Compute a = sqrt(a) (mod curve_p). */
  11566. /* Routine 3.2.8 mp_mod_sqrt_224; from
  11567. * http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11568. static void mod_sqrt_secp224r1(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  11569. (void) curve;
  11570. bitcount_t i;
  11571. mg_uecc_word_t e1[num_words_secp224r1];
  11572. mg_uecc_word_t f1[num_words_secp224r1];
  11573. mg_uecc_word_t d0[num_words_secp224r1];
  11574. mg_uecc_word_t e0[num_words_secp224r1];
  11575. mg_uecc_word_t f0[num_words_secp224r1];
  11576. mg_uecc_word_t d1[num_words_secp224r1];
  11577. /* s = a; using constant instead of random value */
  11578. mod_sqrt_secp224r1_rp(d0, e0, f0, a, a); /* RP (d0, e0, f0, c, s) */
  11579. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  11580. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  11581. for (i = 1; i <= 95; i++) {
  11582. mg_uecc_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  11583. mg_uecc_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  11584. mg_uecc_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  11585. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  11586. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  11587. if (mg_uecc_vli_isZero(d1, num_words_secp224r1)) { /* if d1 == 0 */
  11588. break;
  11589. }
  11590. }
  11591. mg_uecc_vli_modInv(f1, e0, curve_secp224r1.p,
  11592. num_words_secp224r1); /* f1 <-- 1 / e0 */
  11593. mg_uecc_vli_modMult_fast(a, d0, f1, &curve_secp224r1); /* a <-- d0 / e0 */
  11594. }
  11595. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  11596. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11597. /* Computes result = product % curve_p
  11598. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11599. #if MG_UECC_WORD_SIZE == 1
  11600. static void vli_mmod_fast_secp224r1(uint8_t *result, uint8_t *product) {
  11601. uint8_t tmp[num_words_secp224r1];
  11602. int8_t carry;
  11603. /* t */
  11604. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11605. /* s1 */
  11606. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  11607. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11608. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  11609. tmp[12] = product[28];
  11610. tmp[13] = product[29];
  11611. tmp[14] = product[30];
  11612. tmp[15] = product[31];
  11613. tmp[16] = product[32];
  11614. tmp[17] = product[33];
  11615. tmp[18] = product[34];
  11616. tmp[19] = product[35];
  11617. tmp[20] = product[36];
  11618. tmp[21] = product[37];
  11619. tmp[22] = product[38];
  11620. tmp[23] = product[39];
  11621. tmp[24] = product[40];
  11622. tmp[25] = product[41];
  11623. tmp[26] = product[42];
  11624. tmp[27] = product[43];
  11625. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11626. /* s2 */
  11627. tmp[12] = product[44];
  11628. tmp[13] = product[45];
  11629. tmp[14] = product[46];
  11630. tmp[15] = product[47];
  11631. tmp[16] = product[48];
  11632. tmp[17] = product[49];
  11633. tmp[18] = product[50];
  11634. tmp[19] = product[51];
  11635. tmp[20] = product[52];
  11636. tmp[21] = product[53];
  11637. tmp[22] = product[54];
  11638. tmp[23] = product[55];
  11639. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  11640. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11641. /* d1 */
  11642. tmp[0] = product[28];
  11643. tmp[1] = product[29];
  11644. tmp[2] = product[30];
  11645. tmp[3] = product[31];
  11646. tmp[4] = product[32];
  11647. tmp[5] = product[33];
  11648. tmp[6] = product[34];
  11649. tmp[7] = product[35];
  11650. tmp[8] = product[36];
  11651. tmp[9] = product[37];
  11652. tmp[10] = product[38];
  11653. tmp[11] = product[39];
  11654. tmp[12] = product[40];
  11655. tmp[13] = product[41];
  11656. tmp[14] = product[42];
  11657. tmp[15] = product[43];
  11658. tmp[16] = product[44];
  11659. tmp[17] = product[45];
  11660. tmp[18] = product[46];
  11661. tmp[19] = product[47];
  11662. tmp[20] = product[48];
  11663. tmp[21] = product[49];
  11664. tmp[22] = product[50];
  11665. tmp[23] = product[51];
  11666. tmp[24] = product[52];
  11667. tmp[25] = product[53];
  11668. tmp[26] = product[54];
  11669. tmp[27] = product[55];
  11670. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11671. /* d2 */
  11672. tmp[0] = product[44];
  11673. tmp[1] = product[45];
  11674. tmp[2] = product[46];
  11675. tmp[3] = product[47];
  11676. tmp[4] = product[48];
  11677. tmp[5] = product[49];
  11678. tmp[6] = product[50];
  11679. tmp[7] = product[51];
  11680. tmp[8] = product[52];
  11681. tmp[9] = product[53];
  11682. tmp[10] = product[54];
  11683. tmp[11] = product[55];
  11684. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11685. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11686. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11687. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  11688. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11689. if (carry < 0) {
  11690. do {
  11691. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11692. num_words_secp224r1);
  11693. } while (carry < 0);
  11694. } else {
  11695. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11696. num_words_secp224r1) != 1) {
  11697. carry -= mg_uecc_vli_sub(result, result, curve_secp224r1.p,
  11698. num_words_secp224r1);
  11699. }
  11700. }
  11701. }
  11702. #elif MG_UECC_WORD_SIZE == 4
  11703. static void vli_mmod_fast_secp224r1(uint32_t *result, uint32_t *product) {
  11704. uint32_t tmp[num_words_secp224r1];
  11705. int carry;
  11706. /* t */
  11707. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11708. /* s1 */
  11709. tmp[0] = tmp[1] = tmp[2] = 0;
  11710. tmp[3] = product[7];
  11711. tmp[4] = product[8];
  11712. tmp[5] = product[9];
  11713. tmp[6] = product[10];
  11714. carry = mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11715. /* s2 */
  11716. tmp[3] = product[11];
  11717. tmp[4] = product[12];
  11718. tmp[5] = product[13];
  11719. tmp[6] = 0;
  11720. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11721. /* d1 */
  11722. tmp[0] = product[7];
  11723. tmp[1] = product[8];
  11724. tmp[2] = product[9];
  11725. tmp[3] = product[10];
  11726. tmp[4] = product[11];
  11727. tmp[5] = product[12];
  11728. tmp[6] = product[13];
  11729. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11730. /* d2 */
  11731. tmp[0] = product[11];
  11732. tmp[1] = product[12];
  11733. tmp[2] = product[13];
  11734. tmp[3] = tmp[4] = tmp[5] = tmp[6] = 0;
  11735. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11736. if (carry < 0) {
  11737. do {
  11738. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11739. num_words_secp224r1);
  11740. } while (carry < 0);
  11741. } else {
  11742. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11743. num_words_secp224r1) != 1) {
  11744. carry -= mg_uecc_vli_sub(result, result, curve_secp224r1.p,
  11745. num_words_secp224r1);
  11746. }
  11747. }
  11748. }
  11749. #else
  11750. static void vli_mmod_fast_secp224r1(uint64_t *result, uint64_t *product) {
  11751. uint64_t tmp[num_words_secp224r1];
  11752. int carry = 0;
  11753. /* t */
  11754. mg_uecc_vli_set(result, product, num_words_secp224r1);
  11755. result[num_words_secp224r1 - 1] &= 0xffffffff;
  11756. /* s1 */
  11757. tmp[0] = 0;
  11758. tmp[1] = product[3] & 0xffffffff00000000ull;
  11759. tmp[2] = product[4];
  11760. tmp[3] = product[5] & 0xffffffff;
  11761. mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11762. /* s2 */
  11763. tmp[1] = product[5] & 0xffffffff00000000ull;
  11764. tmp[2] = product[6];
  11765. tmp[3] = 0;
  11766. mg_uecc_vli_add(result, result, tmp, num_words_secp224r1);
  11767. /* d1 */
  11768. tmp[0] = (product[3] >> 32) | (product[4] << 32);
  11769. tmp[1] = (product[4] >> 32) | (product[5] << 32);
  11770. tmp[2] = (product[5] >> 32) | (product[6] << 32);
  11771. tmp[3] = product[6] >> 32;
  11772. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11773. /* d2 */
  11774. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  11775. tmp[1] = product[6] >> 32;
  11776. tmp[2] = tmp[3] = 0;
  11777. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp224r1);
  11778. if (carry < 0) {
  11779. do {
  11780. carry += mg_uecc_vli_add(result, result, curve_secp224r1.p,
  11781. num_words_secp224r1);
  11782. } while (carry < 0);
  11783. } else {
  11784. while (mg_uecc_vli_cmp_unsafe(curve_secp224r1.p, result,
  11785. num_words_secp224r1) != 1) {
  11786. mg_uecc_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  11787. }
  11788. }
  11789. }
  11790. #endif /* MG_UECC_WORD_SIZE */
  11791. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0) */
  11792. #endif /* MG_UECC_SUPPORTS_secp224r1 */
  11793. #if MG_UECC_SUPPORTS_secp256r1
  11794. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11795. static void vli_mmod_fast_secp256r1(mg_uecc_word_t *result,
  11796. mg_uecc_word_t *product);
  11797. #endif
  11798. static const struct MG_UECC_Curve_t curve_secp256r1 = {
  11799. num_words_secp256r1,
  11800. num_bytes_secp256r1,
  11801. 256, /* num_n_bits */
  11802. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11803. BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00),
  11804. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  11805. BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF)},
  11806. {BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3),
  11807. BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC),
  11808. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11809. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF)},
  11810. {BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4),
  11811. BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77),
  11812. BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8),
  11813. BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B),
  11814. BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB),
  11815. BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B),
  11816. BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E),
  11817. BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F)},
  11818. {BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B),
  11819. BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65),
  11820. BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3),
  11821. BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A)},
  11822. &double_jacobian_default,
  11823. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  11824. &mod_sqrt_default,
  11825. #endif
  11826. &x_side_default,
  11827. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  11828. &vli_mmod_fast_secp256r1
  11829. #endif
  11830. };
  11831. MG_UECC_Curve mg_uecc_secp256r1(void) {
  11832. return &curve_secp256r1;
  11833. }
  11834. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1)
  11835. /* Computes result = product % curve_p
  11836. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  11837. #if MG_UECC_WORD_SIZE == 1
  11838. static void vli_mmod_fast_secp256r1(uint8_t *result, uint8_t *product) {
  11839. uint8_t tmp[num_words_secp256r1];
  11840. int8_t carry;
  11841. /* t */
  11842. mg_uecc_vli_set(result, product, num_words_secp256r1);
  11843. /* s1 */
  11844. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  11845. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  11846. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  11847. tmp[12] = product[44];
  11848. tmp[13] = product[45];
  11849. tmp[14] = product[46];
  11850. tmp[15] = product[47];
  11851. tmp[16] = product[48];
  11852. tmp[17] = product[49];
  11853. tmp[18] = product[50];
  11854. tmp[19] = product[51];
  11855. tmp[20] = product[52];
  11856. tmp[21] = product[53];
  11857. tmp[22] = product[54];
  11858. tmp[23] = product[55];
  11859. tmp[24] = product[56];
  11860. tmp[25] = product[57];
  11861. tmp[26] = product[58];
  11862. tmp[27] = product[59];
  11863. tmp[28] = product[60];
  11864. tmp[29] = product[61];
  11865. tmp[30] = product[62];
  11866. tmp[31] = product[63];
  11867. carry = mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  11868. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11869. /* s2 */
  11870. tmp[12] = product[48];
  11871. tmp[13] = product[49];
  11872. tmp[14] = product[50];
  11873. tmp[15] = product[51];
  11874. tmp[16] = product[52];
  11875. tmp[17] = product[53];
  11876. tmp[18] = product[54];
  11877. tmp[19] = product[55];
  11878. tmp[20] = product[56];
  11879. tmp[21] = product[57];
  11880. tmp[22] = product[58];
  11881. tmp[23] = product[59];
  11882. tmp[24] = product[60];
  11883. tmp[25] = product[61];
  11884. tmp[26] = product[62];
  11885. tmp[27] = product[63];
  11886. tmp[28] = tmp[29] = tmp[30] = tmp[31] = 0;
  11887. carry += mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  11888. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11889. /* s3 */
  11890. tmp[0] = product[32];
  11891. tmp[1] = product[33];
  11892. tmp[2] = product[34];
  11893. tmp[3] = product[35];
  11894. tmp[4] = product[36];
  11895. tmp[5] = product[37];
  11896. tmp[6] = product[38];
  11897. tmp[7] = product[39];
  11898. tmp[8] = product[40];
  11899. tmp[9] = product[41];
  11900. tmp[10] = product[42];
  11901. tmp[11] = product[43];
  11902. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11903. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11904. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11905. tmp[24] = product[56];
  11906. tmp[25] = product[57];
  11907. tmp[26] = product[58];
  11908. tmp[27] = product[59];
  11909. tmp[28] = product[60];
  11910. tmp[29] = product[61];
  11911. tmp[30] = product[62];
  11912. tmp[31] = product[63];
  11913. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11914. /* s4 */
  11915. tmp[0] = product[36];
  11916. tmp[1] = product[37];
  11917. tmp[2] = product[38];
  11918. tmp[3] = product[39];
  11919. tmp[4] = product[40];
  11920. tmp[5] = product[41];
  11921. tmp[6] = product[42];
  11922. tmp[7] = product[43];
  11923. tmp[8] = product[44];
  11924. tmp[9] = product[45];
  11925. tmp[10] = product[46];
  11926. tmp[11] = product[47];
  11927. tmp[12] = product[52];
  11928. tmp[13] = product[53];
  11929. tmp[14] = product[54];
  11930. tmp[15] = product[55];
  11931. tmp[16] = product[56];
  11932. tmp[17] = product[57];
  11933. tmp[18] = product[58];
  11934. tmp[19] = product[59];
  11935. tmp[20] = product[60];
  11936. tmp[21] = product[61];
  11937. tmp[22] = product[62];
  11938. tmp[23] = product[63];
  11939. tmp[24] = product[52];
  11940. tmp[25] = product[53];
  11941. tmp[26] = product[54];
  11942. tmp[27] = product[55];
  11943. tmp[28] = product[32];
  11944. tmp[29] = product[33];
  11945. tmp[30] = product[34];
  11946. tmp[31] = product[35];
  11947. carry += mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  11948. /* d1 */
  11949. tmp[0] = product[44];
  11950. tmp[1] = product[45];
  11951. tmp[2] = product[46];
  11952. tmp[3] = product[47];
  11953. tmp[4] = product[48];
  11954. tmp[5] = product[49];
  11955. tmp[6] = product[50];
  11956. tmp[7] = product[51];
  11957. tmp[8] = product[52];
  11958. tmp[9] = product[53];
  11959. tmp[10] = product[54];
  11960. tmp[11] = product[55];
  11961. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  11962. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11963. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11964. tmp[24] = product[32];
  11965. tmp[25] = product[33];
  11966. tmp[26] = product[34];
  11967. tmp[27] = product[35];
  11968. tmp[28] = product[40];
  11969. tmp[29] = product[41];
  11970. tmp[30] = product[42];
  11971. tmp[31] = product[43];
  11972. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  11973. /* d2 */
  11974. tmp[0] = product[48];
  11975. tmp[1] = product[49];
  11976. tmp[2] = product[50];
  11977. tmp[3] = product[51];
  11978. tmp[4] = product[52];
  11979. tmp[5] = product[53];
  11980. tmp[6] = product[54];
  11981. tmp[7] = product[55];
  11982. tmp[8] = product[56];
  11983. tmp[9] = product[57];
  11984. tmp[10] = product[58];
  11985. tmp[11] = product[59];
  11986. tmp[12] = product[60];
  11987. tmp[13] = product[61];
  11988. tmp[14] = product[62];
  11989. tmp[15] = product[63];
  11990. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  11991. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  11992. tmp[24] = product[36];
  11993. tmp[25] = product[37];
  11994. tmp[26] = product[38];
  11995. tmp[27] = product[39];
  11996. tmp[28] = product[44];
  11997. tmp[29] = product[45];
  11998. tmp[30] = product[46];
  11999. tmp[31] = product[47];
  12000. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12001. /* d3 */
  12002. tmp[0] = product[52];
  12003. tmp[1] = product[53];
  12004. tmp[2] = product[54];
  12005. tmp[3] = product[55];
  12006. tmp[4] = product[56];
  12007. tmp[5] = product[57];
  12008. tmp[6] = product[58];
  12009. tmp[7] = product[59];
  12010. tmp[8] = product[60];
  12011. tmp[9] = product[61];
  12012. tmp[10] = product[62];
  12013. tmp[11] = product[63];
  12014. tmp[12] = product[32];
  12015. tmp[13] = product[33];
  12016. tmp[14] = product[34];
  12017. tmp[15] = product[35];
  12018. tmp[16] = product[36];
  12019. tmp[17] = product[37];
  12020. tmp[18] = product[38];
  12021. tmp[19] = product[39];
  12022. tmp[20] = product[40];
  12023. tmp[21] = product[41];
  12024. tmp[22] = product[42];
  12025. tmp[23] = product[43];
  12026. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  12027. tmp[28] = product[48];
  12028. tmp[29] = product[49];
  12029. tmp[30] = product[50];
  12030. tmp[31] = product[51];
  12031. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12032. /* d4 */
  12033. tmp[0] = product[56];
  12034. tmp[1] = product[57];
  12035. tmp[2] = product[58];
  12036. tmp[3] = product[59];
  12037. tmp[4] = product[60];
  12038. tmp[5] = product[61];
  12039. tmp[6] = product[62];
  12040. tmp[7] = product[63];
  12041. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  12042. tmp[12] = product[36];
  12043. tmp[13] = product[37];
  12044. tmp[14] = product[38];
  12045. tmp[15] = product[39];
  12046. tmp[16] = product[40];
  12047. tmp[17] = product[41];
  12048. tmp[18] = product[42];
  12049. tmp[19] = product[43];
  12050. tmp[20] = product[44];
  12051. tmp[21] = product[45];
  12052. tmp[22] = product[46];
  12053. tmp[23] = product[47];
  12054. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  12055. tmp[28] = product[52];
  12056. tmp[29] = product[53];
  12057. tmp[30] = product[54];
  12058. tmp[31] = product[55];
  12059. carry -= mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12060. if (carry < 0) {
  12061. do {
  12062. carry += mg_uecc_vli_add(result, result, curve_secp256r1.p,
  12063. num_words_secp256r1);
  12064. } while (carry < 0);
  12065. } else {
  12066. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  12067. num_words_secp256r1) != 1) {
  12068. carry -= mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  12069. num_words_secp256r1);
  12070. }
  12071. }
  12072. }
  12073. #elif MG_UECC_WORD_SIZE == 4
  12074. static void vli_mmod_fast_secp256r1(uint32_t *result, uint32_t *product) {
  12075. uint32_t tmp[num_words_secp256r1];
  12076. int carry;
  12077. /* t */
  12078. mg_uecc_vli_set(result, product, num_words_secp256r1);
  12079. /* s1 */
  12080. tmp[0] = tmp[1] = tmp[2] = 0;
  12081. tmp[3] = product[11];
  12082. tmp[4] = product[12];
  12083. tmp[5] = product[13];
  12084. tmp[6] = product[14];
  12085. tmp[7] = product[15];
  12086. carry = (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12087. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12088. /* s2 */
  12089. tmp[3] = product[12];
  12090. tmp[4] = product[13];
  12091. tmp[5] = product[14];
  12092. tmp[6] = product[15];
  12093. tmp[7] = 0;
  12094. carry += (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12095. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12096. /* s3 */
  12097. tmp[0] = product[8];
  12098. tmp[1] = product[9];
  12099. tmp[2] = product[10];
  12100. tmp[3] = tmp[4] = tmp[5] = 0;
  12101. tmp[6] = product[14];
  12102. tmp[7] = product[15];
  12103. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12104. /* s4 */
  12105. tmp[0] = product[9];
  12106. tmp[1] = product[10];
  12107. tmp[2] = product[11];
  12108. tmp[3] = product[13];
  12109. tmp[4] = product[14];
  12110. tmp[5] = product[15];
  12111. tmp[6] = product[13];
  12112. tmp[7] = product[8];
  12113. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12114. /* d1 */
  12115. tmp[0] = product[11];
  12116. tmp[1] = product[12];
  12117. tmp[2] = product[13];
  12118. tmp[3] = tmp[4] = tmp[5] = 0;
  12119. tmp[6] = product[8];
  12120. tmp[7] = product[10];
  12121. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12122. /* d2 */
  12123. tmp[0] = product[12];
  12124. tmp[1] = product[13];
  12125. tmp[2] = product[14];
  12126. tmp[3] = product[15];
  12127. tmp[4] = tmp[5] = 0;
  12128. tmp[6] = product[9];
  12129. tmp[7] = product[11];
  12130. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12131. /* d3 */
  12132. tmp[0] = product[13];
  12133. tmp[1] = product[14];
  12134. tmp[2] = product[15];
  12135. tmp[3] = product[8];
  12136. tmp[4] = product[9];
  12137. tmp[5] = product[10];
  12138. tmp[6] = 0;
  12139. tmp[7] = product[12];
  12140. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12141. /* d4 */
  12142. tmp[0] = product[14];
  12143. tmp[1] = product[15];
  12144. tmp[2] = 0;
  12145. tmp[3] = product[9];
  12146. tmp[4] = product[10];
  12147. tmp[5] = product[11];
  12148. tmp[6] = 0;
  12149. tmp[7] = product[13];
  12150. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12151. if (carry < 0) {
  12152. do {
  12153. carry += (int) mg_uecc_vli_add(result, result, curve_secp256r1.p,
  12154. num_words_secp256r1);
  12155. } while (carry < 0);
  12156. } else {
  12157. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  12158. num_words_secp256r1) != 1) {
  12159. carry -= (int) mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  12160. num_words_secp256r1);
  12161. }
  12162. }
  12163. }
  12164. #else
  12165. static void vli_mmod_fast_secp256r1(uint64_t *result, uint64_t *product) {
  12166. uint64_t tmp[num_words_secp256r1];
  12167. int carry;
  12168. /* t */
  12169. mg_uecc_vli_set(result, product, num_words_secp256r1);
  12170. /* s1 */
  12171. tmp[0] = 0;
  12172. tmp[1] = product[5] & 0xffffffff00000000U;
  12173. tmp[2] = product[6];
  12174. tmp[3] = product[7];
  12175. carry = (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12176. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12177. /* s2 */
  12178. tmp[1] = product[6] << 32;
  12179. tmp[2] = (product[6] >> 32) | (product[7] << 32);
  12180. tmp[3] = product[7] >> 32;
  12181. carry += (int) mg_uecc_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  12182. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12183. /* s3 */
  12184. tmp[0] = product[4];
  12185. tmp[1] = product[5] & 0xffffffff;
  12186. tmp[2] = 0;
  12187. tmp[3] = product[7];
  12188. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12189. /* s4 */
  12190. tmp[0] = (product[4] >> 32) | (product[5] << 32);
  12191. tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000U);
  12192. tmp[2] = product[7];
  12193. tmp[3] = (product[6] >> 32) | (product[4] << 32);
  12194. carry += (int) mg_uecc_vli_add(result, result, tmp, num_words_secp256r1);
  12195. /* d1 */
  12196. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  12197. tmp[1] = (product[6] >> 32);
  12198. tmp[2] = 0;
  12199. tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32);
  12200. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12201. /* d2 */
  12202. tmp[0] = product[6];
  12203. tmp[1] = product[7];
  12204. tmp[2] = 0;
  12205. tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000);
  12206. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12207. /* d3 */
  12208. tmp[0] = (product[6] >> 32) | (product[7] << 32);
  12209. tmp[1] = (product[7] >> 32) | (product[4] << 32);
  12210. tmp[2] = (product[4] >> 32) | (product[5] << 32);
  12211. tmp[3] = (product[6] << 32);
  12212. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12213. /* d4 */
  12214. tmp[0] = product[7];
  12215. tmp[1] = product[4] & 0xffffffff00000000U;
  12216. tmp[2] = product[5];
  12217. tmp[3] = product[6] & 0xffffffff00000000U;
  12218. carry -= (int) mg_uecc_vli_sub(result, result, tmp, num_words_secp256r1);
  12219. if (carry < 0) {
  12220. do {
  12221. carry += (int) mg_uecc_vli_add(result, result, curve_secp256r1.p,
  12222. num_words_secp256r1);
  12223. } while (carry < 0);
  12224. } else {
  12225. while (carry || mg_uecc_vli_cmp_unsafe(curve_secp256r1.p, result,
  12226. num_words_secp256r1) != 1) {
  12227. carry -= (int) mg_uecc_vli_sub(result, result, curve_secp256r1.p,
  12228. num_words_secp256r1);
  12229. }
  12230. }
  12231. }
  12232. #endif /* MG_UECC_WORD_SIZE */
  12233. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) */
  12234. #endif /* MG_UECC_SUPPORTS_secp256r1 */
  12235. #if MG_UECC_SUPPORTS_secp256k1
  12236. static void double_jacobian_secp256k1(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12237. mg_uecc_word_t *Z1, MG_UECC_Curve curve);
  12238. static void x_side_secp256k1(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  12239. MG_UECC_Curve curve);
  12240. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12241. static void vli_mmod_fast_secp256k1(mg_uecc_word_t *result,
  12242. mg_uecc_word_t *product);
  12243. #endif
  12244. static const struct MG_UECC_Curve_t curve_secp256k1 = {
  12245. num_words_secp256k1,
  12246. num_bytes_secp256k1,
  12247. 256, /* num_n_bits */
  12248. {BYTES_TO_WORDS_8(2F, FC, FF, FF, FE, FF, FF, FF),
  12249. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12250. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  12251. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  12252. {BYTES_TO_WORDS_8(41, 41, 36, D0, 8C, 5E, D2, BF),
  12253. BYTES_TO_WORDS_8(3B, A0, 48, AF, E6, DC, AE, BA),
  12254. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  12255. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  12256. {BYTES_TO_WORDS_8(98, 17, F8, 16, 5B, 81, F2, 59),
  12257. BYTES_TO_WORDS_8(D9, 28, CE, 2D, DB, FC, 9B, 02),
  12258. BYTES_TO_WORDS_8(07, 0B, 87, CE, 95, 62, A0, 55),
  12259. BYTES_TO_WORDS_8(AC, BB, DC, F9, 7E, 66, BE, 79),
  12260. BYTES_TO_WORDS_8(B8, D4, 10, FB, 8F, D0, 47, 9C),
  12261. BYTES_TO_WORDS_8(19, 54, 85, A6, 48, B4, 17, FD),
  12262. BYTES_TO_WORDS_8(A8, 08, 11, 0E, FC, FB, A4, 5D),
  12263. BYTES_TO_WORDS_8(65, C4, A3, 26, 77, DA, 3A, 48)},
  12264. {BYTES_TO_WORDS_8(07, 00, 00, 00, 00, 00, 00, 00),
  12265. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  12266. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  12267. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00)},
  12268. &double_jacobian_secp256k1,
  12269. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12270. &mod_sqrt_default,
  12271. #endif
  12272. &x_side_secp256k1,
  12273. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  12274. &vli_mmod_fast_secp256k1
  12275. #endif
  12276. };
  12277. MG_UECC_Curve mg_uecc_secp256k1(void) {
  12278. return &curve_secp256k1;
  12279. }
  12280. /* Double in place */
  12281. static void double_jacobian_secp256k1(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12282. mg_uecc_word_t *Z1, MG_UECC_Curve curve) {
  12283. /* t1 = X, t2 = Y, t3 = Z */
  12284. mg_uecc_word_t t4[num_words_secp256k1];
  12285. mg_uecc_word_t t5[num_words_secp256k1];
  12286. if (mg_uecc_vli_isZero(Z1, num_words_secp256k1)) {
  12287. return;
  12288. }
  12289. mg_uecc_vli_modSquare_fast(t5, Y1, curve); /* t5 = y1^2 */
  12290. mg_uecc_vli_modMult_fast(t4, X1, t5, curve); /* t4 = x1*y1^2 = A */
  12291. mg_uecc_vli_modSquare_fast(X1, X1, curve); /* t1 = x1^2 */
  12292. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = y1^4 */
  12293. mg_uecc_vli_modMult_fast(Z1, Y1, Z1, curve); /* t3 = y1*z1 = z3 */
  12294. mg_uecc_vli_modAdd(Y1, X1, X1, curve->p,
  12295. num_words_secp256k1); /* t2 = 2*x1^2 */
  12296. mg_uecc_vli_modAdd(Y1, Y1, X1, curve->p,
  12297. num_words_secp256k1); /* t2 = 3*x1^2 */
  12298. if (mg_uecc_vli_testBit(Y1, 0)) {
  12299. mg_uecc_word_t carry =
  12300. mg_uecc_vli_add(Y1, Y1, curve->p, num_words_secp256k1);
  12301. mg_uecc_vli_rshift1(Y1, num_words_secp256k1);
  12302. Y1[num_words_secp256k1 - 1] |= carry << (MG_UECC_WORD_BITS - 1);
  12303. } else {
  12304. mg_uecc_vli_rshift1(Y1, num_words_secp256k1);
  12305. }
  12306. /* t2 = 3/2*(x1^2) = B */
  12307. mg_uecc_vli_modSquare_fast(X1, Y1, curve); /* t1 = B^2 */
  12308. mg_uecc_vli_modSub(X1, X1, t4, curve->p,
  12309. num_words_secp256k1); /* t1 = B^2 - A */
  12310. mg_uecc_vli_modSub(X1, X1, t4, curve->p,
  12311. num_words_secp256k1); /* t1 = B^2 - 2A = x3 */
  12312. mg_uecc_vli_modSub(t4, t4, X1, curve->p,
  12313. num_words_secp256k1); /* t4 = A - x3 */
  12314. mg_uecc_vli_modMult_fast(Y1, Y1, t4, curve); /* t2 = B * (A - x3) */
  12315. mg_uecc_vli_modSub(Y1, Y1, t5, curve->p,
  12316. num_words_secp256k1); /* t2 = B * (A - x3) - y1^4 = y3 */
  12317. }
  12318. /* Computes result = x^3 + b. result must not overlap x. */
  12319. static void x_side_secp256k1(mg_uecc_word_t *result, const mg_uecc_word_t *x,
  12320. MG_UECC_Curve curve) {
  12321. mg_uecc_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  12322. mg_uecc_vli_modMult_fast(result, result, x, curve); /* r = x^3 */
  12323. mg_uecc_vli_modAdd(result, result, curve->b, curve->p,
  12324. num_words_secp256k1); /* r = x^3 + b */
  12325. }
  12326. #if (MG_UECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256k1)
  12327. static void omega_mult_secp256k1(mg_uecc_word_t *result,
  12328. const mg_uecc_word_t *right);
  12329. static void vli_mmod_fast_secp256k1(mg_uecc_word_t *result,
  12330. mg_uecc_word_t *product) {
  12331. mg_uecc_word_t tmp[2 * num_words_secp256k1];
  12332. mg_uecc_word_t carry;
  12333. mg_uecc_vli_clear(tmp, num_words_secp256k1);
  12334. mg_uecc_vli_clear(tmp + num_words_secp256k1, num_words_secp256k1);
  12335. omega_mult_secp256k1(tmp,
  12336. product + num_words_secp256k1); /* (Rq, q) = q * c */
  12337. carry = mg_uecc_vli_add(result, product, tmp,
  12338. num_words_secp256k1); /* (C, r) = r + q */
  12339. mg_uecc_vli_clear(product, num_words_secp256k1);
  12340. omega_mult_secp256k1(product, tmp + num_words_secp256k1); /* Rq*c */
  12341. carry += mg_uecc_vli_add(result, result, product,
  12342. num_words_secp256k1); /* (C1, r) = r + Rq*c */
  12343. while (carry > 0) {
  12344. --carry;
  12345. mg_uecc_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  12346. }
  12347. if (mg_uecc_vli_cmp_unsafe(result, curve_secp256k1.p, num_words_secp256k1) >
  12348. 0) {
  12349. mg_uecc_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  12350. }
  12351. }
  12352. #if MG_UECC_WORD_SIZE == 1
  12353. static void omega_mult_secp256k1(uint8_t *result, const uint8_t *right) {
  12354. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12355. mg_uecc_word_t r0 = 0;
  12356. mg_uecc_word_t r1 = 0;
  12357. mg_uecc_word_t r2 = 0;
  12358. wordcount_t k;
  12359. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12360. muladd(0xD1, right[0], &r0, &r1, &r2);
  12361. result[0] = r0;
  12362. r0 = r1;
  12363. r1 = r2;
  12364. /* r2 is still 0 */
  12365. for (k = 1; k < num_words_secp256k1; ++k) {
  12366. muladd(0x03, right[k - 1], &r0, &r1, &r2);
  12367. muladd(0xD1, right[k], &r0, &r1, &r2);
  12368. result[k] = r0;
  12369. r0 = r1;
  12370. r1 = r2;
  12371. r2 = 0;
  12372. }
  12373. muladd(0x03, right[num_words_secp256k1 - 1], &r0, &r1, &r2);
  12374. result[num_words_secp256k1] = r0;
  12375. result[num_words_secp256k1 + 1] = r1;
  12376. /* add the 2^32 multiple */
  12377. result[4 + num_words_secp256k1] =
  12378. mg_uecc_vli_add(result + 4, result + 4, right, num_words_secp256k1);
  12379. }
  12380. #elif MG_UECC_WORD_SIZE == 4
  12381. static void omega_mult_secp256k1(uint32_t *result, const uint32_t *right) {
  12382. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12383. uint32_t carry = 0;
  12384. wordcount_t k;
  12385. for (k = 0; k < num_words_secp256k1; ++k) {
  12386. uint64_t p = (uint64_t) 0x3D1 * right[k] + carry;
  12387. result[k] = (uint32_t) p;
  12388. carry = p >> 32;
  12389. }
  12390. result[num_words_secp256k1] = carry;
  12391. /* add the 2^32 multiple */
  12392. result[1 + num_words_secp256k1] =
  12393. mg_uecc_vli_add(result + 1, result + 1, right, num_words_secp256k1);
  12394. }
  12395. #else
  12396. static void omega_mult_secp256k1(uint64_t *result, const uint64_t *right) {
  12397. mg_uecc_word_t r0 = 0;
  12398. mg_uecc_word_t r1 = 0;
  12399. mg_uecc_word_t r2 = 0;
  12400. wordcount_t k;
  12401. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  12402. for (k = 0; k < num_words_secp256k1; ++k) {
  12403. muladd(0x1000003D1ull, right[k], &r0, &r1, &r2);
  12404. result[k] = r0;
  12405. r0 = r1;
  12406. r1 = r2;
  12407. r2 = 0;
  12408. }
  12409. result[num_words_secp256k1] = r0;
  12410. }
  12411. #endif /* MG_UECC_WORD_SIZE */
  12412. #endif /* (MG_UECC_OPTIMIZATION_LEVEL > 0 && && !asm_mmod_fast_secp256k1) */
  12413. #endif /* MG_UECC_SUPPORTS_secp256k1 */
  12414. #endif /* _UECC_CURVE_SPECIFIC_H_ */
  12415. /* Returns 1 if 'point' is the point at infinity, 0 otherwise. */
  12416. #define EccPoint_isZero(point, curve) \
  12417. mg_uecc_vli_isZero((point), (wordcount_t) ((curve)->num_words * 2))
  12418. /* Point multiplication algorithm using Montgomery's ladder with co-Z
  12419. coordinates. From http://eprint.iacr.org/2011/338.pdf
  12420. */
  12421. /* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
  12422. static void apply_z(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12423. const mg_uecc_word_t *const Z, MG_UECC_Curve curve) {
  12424. mg_uecc_word_t t1[MG_UECC_MAX_WORDS];
  12425. mg_uecc_vli_modSquare_fast(t1, Z, curve); /* z^2 */
  12426. mg_uecc_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
  12427. mg_uecc_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */
  12428. mg_uecc_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
  12429. }
  12430. /* P = (x1, y1) => 2P, (x2, y2) => P' */
  12431. static void XYcZ_initial_double(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12432. mg_uecc_word_t *X2, mg_uecc_word_t *Y2,
  12433. const mg_uecc_word_t *const initial_Z,
  12434. MG_UECC_Curve curve) {
  12435. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  12436. wordcount_t num_words = curve->num_words;
  12437. if (initial_Z) {
  12438. mg_uecc_vli_set(z, initial_Z, num_words);
  12439. } else {
  12440. mg_uecc_vli_clear(z, num_words);
  12441. z[0] = 1;
  12442. }
  12443. mg_uecc_vli_set(X2, X1, num_words);
  12444. mg_uecc_vli_set(Y2, Y1, num_words);
  12445. apply_z(X1, Y1, z, curve);
  12446. curve->double_jacobian(X1, Y1, z, curve);
  12447. apply_z(X2, Y2, z, curve);
  12448. }
  12449. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  12450. Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
  12451. or P => P', Q => P + Q
  12452. */
  12453. static void XYcZ_add(mg_uecc_word_t *X1, mg_uecc_word_t *Y1, mg_uecc_word_t *X2,
  12454. mg_uecc_word_t *Y2, MG_UECC_Curve curve) {
  12455. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  12456. mg_uecc_word_t t5[MG_UECC_MAX_WORDS] = {0};
  12457. wordcount_t num_words = curve->num_words;
  12458. mg_uecc_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  12459. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  12460. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  12461. mg_uecc_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  12462. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  12463. mg_uecc_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */
  12464. mg_uecc_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
  12465. mg_uecc_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
  12466. mg_uecc_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
  12467. mg_uecc_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */
  12468. mg_uecc_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
  12469. mg_uecc_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */
  12470. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
  12471. mg_uecc_vli_set(X2, t5, num_words);
  12472. }
  12473. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  12474. Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
  12475. or P => P - Q, Q => P + Q
  12476. */
  12477. static void XYcZ_addC(mg_uecc_word_t *X1, mg_uecc_word_t *Y1,
  12478. mg_uecc_word_t *X2, mg_uecc_word_t *Y2,
  12479. MG_UECC_Curve curve) {
  12480. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  12481. mg_uecc_word_t t5[MG_UECC_MAX_WORDS] = {0};
  12482. mg_uecc_word_t t6[MG_UECC_MAX_WORDS];
  12483. mg_uecc_word_t t7[MG_UECC_MAX_WORDS];
  12484. wordcount_t num_words = curve->num_words;
  12485. mg_uecc_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  12486. mg_uecc_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  12487. mg_uecc_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  12488. mg_uecc_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  12489. mg_uecc_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
  12490. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  12491. mg_uecc_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
  12492. mg_uecc_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */
  12493. mg_uecc_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
  12494. mg_uecc_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */
  12495. mg_uecc_vli_modSub(X2, X2, t6, curve->p,
  12496. num_words); /* t3 = D - (B + C) = x3 */
  12497. mg_uecc_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
  12498. mg_uecc_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */
  12499. mg_uecc_vli_modSub(Y2, Y2, Y1, curve->p,
  12500. num_words); /* t4 = (y2 - y1)*(B - x3) - E = y3 */
  12501. mg_uecc_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */
  12502. mg_uecc_vli_modSub(t7, t7, t6, curve->p,
  12503. num_words); /* t7 = F - (B + C) = x3' */
  12504. mg_uecc_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
  12505. mg_uecc_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */
  12506. mg_uecc_vli_modSub(Y1, t6, Y1, curve->p,
  12507. num_words); /* t2 = (y2+y1)*(x3' - B) - E = y3' */
  12508. mg_uecc_vli_set(X1, t7, num_words);
  12509. }
  12510. /* result may overlap point. */
  12511. static void EccPoint_mult(mg_uecc_word_t *result, const mg_uecc_word_t *point,
  12512. const mg_uecc_word_t *scalar,
  12513. const mg_uecc_word_t *initial_Z, bitcount_t num_bits,
  12514. MG_UECC_Curve curve) {
  12515. /* R0 and R1 */
  12516. mg_uecc_word_t Rx[2][MG_UECC_MAX_WORDS];
  12517. mg_uecc_word_t Ry[2][MG_UECC_MAX_WORDS];
  12518. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  12519. bitcount_t i;
  12520. mg_uecc_word_t nb;
  12521. wordcount_t num_words = curve->num_words;
  12522. mg_uecc_vli_set(Rx[1], point, num_words);
  12523. mg_uecc_vli_set(Ry[1], point + num_words, num_words);
  12524. XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
  12525. for (i = num_bits - 2; i > 0; --i) {
  12526. nb = !mg_uecc_vli_testBit(scalar, i);
  12527. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  12528. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  12529. }
  12530. nb = !mg_uecc_vli_testBit(scalar, 0);
  12531. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  12532. /* Find final 1/Z value. */
  12533. mg_uecc_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
  12534. mg_uecc_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */
  12535. mg_uecc_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */
  12536. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0)) */
  12537. /* yP / (xP * Yb * (X1 - X0)) */
  12538. mg_uecc_vli_modMult_fast(z, z, point + num_words, curve);
  12539. mg_uecc_vli_modMult_fast(z, z, Rx[1 - nb],
  12540. curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */
  12541. /* End 1/Z calculation */
  12542. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  12543. apply_z(Rx[0], Ry[0], z, curve);
  12544. mg_uecc_vli_set(result, Rx[0], num_words);
  12545. mg_uecc_vli_set(result + num_words, Ry[0], num_words);
  12546. }
  12547. static mg_uecc_word_t regularize_k(const mg_uecc_word_t *const k,
  12548. mg_uecc_word_t *k0, mg_uecc_word_t *k1,
  12549. MG_UECC_Curve curve) {
  12550. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12551. bitcount_t num_n_bits = curve->num_n_bits;
  12552. mg_uecc_word_t carry =
  12553. mg_uecc_vli_add(k0, k, curve->n, num_n_words) ||
  12554. (num_n_bits < ((bitcount_t) num_n_words * MG_UECC_WORD_SIZE * 8) &&
  12555. mg_uecc_vli_testBit(k0, num_n_bits));
  12556. mg_uecc_vli_add(k1, k0, curve->n, num_n_words);
  12557. return carry;
  12558. }
  12559. /* Generates a random integer in the range 0 < random < top.
  12560. Both random and top have num_words words. */
  12561. MG_UECC_VLI_API int mg_uecc_generate_random_int(mg_uecc_word_t *random,
  12562. const mg_uecc_word_t *top,
  12563. wordcount_t num_words) {
  12564. mg_uecc_word_t mask = (mg_uecc_word_t) -1;
  12565. mg_uecc_word_t tries;
  12566. bitcount_t num_bits = mg_uecc_vli_numBits(top, num_words);
  12567. if (!g_rng_function) {
  12568. return 0;
  12569. }
  12570. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12571. if (!g_rng_function((uint8_t *) random,
  12572. (unsigned int) (num_words * MG_UECC_WORD_SIZE))) {
  12573. return 0;
  12574. }
  12575. random[num_words - 1] &=
  12576. mask >> ((bitcount_t) (num_words * MG_UECC_WORD_SIZE * 8 - num_bits));
  12577. if (!mg_uecc_vli_isZero(random, num_words) &&
  12578. mg_uecc_vli_cmp(top, random, num_words) == 1) {
  12579. return 1;
  12580. }
  12581. }
  12582. return 0;
  12583. }
  12584. static mg_uecc_word_t EccPoint_compute_public_key(mg_uecc_word_t *result,
  12585. mg_uecc_word_t *private_key,
  12586. MG_UECC_Curve curve) {
  12587. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  12588. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  12589. mg_uecc_word_t *p2[2] = {tmp1, tmp2};
  12590. mg_uecc_word_t *initial_Z = 0;
  12591. mg_uecc_word_t carry;
  12592. /* Regularize the bitcount for the private key so that attackers cannot use a
  12593. side channel attack to learn the number of leading zeros. */
  12594. carry = regularize_k(private_key, tmp1, tmp2, curve);
  12595. /* If an RNG function was specified, try to get a random initial Z value to
  12596. improve protection against side-channel attacks. */
  12597. if (g_rng_function) {
  12598. if (!mg_uecc_generate_random_int(p2[carry], curve->p, curve->num_words)) {
  12599. return 0;
  12600. }
  12601. initial_Z = p2[carry];
  12602. }
  12603. EccPoint_mult(result, curve->G, p2[!carry], initial_Z,
  12604. (bitcount_t) (curve->num_n_bits + 1), curve);
  12605. if (EccPoint_isZero(result, curve)) {
  12606. return 0;
  12607. }
  12608. return 1;
  12609. }
  12610. #if MG_UECC_WORD_SIZE == 1
  12611. MG_UECC_VLI_API void mg_uecc_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  12612. const uint8_t *native) {
  12613. wordcount_t i;
  12614. for (i = 0; i < num_bytes; ++i) {
  12615. bytes[i] = native[(num_bytes - 1) - i];
  12616. }
  12617. }
  12618. MG_UECC_VLI_API void mg_uecc_vli_bytesToNative(uint8_t *native,
  12619. const uint8_t *bytes,
  12620. int num_bytes) {
  12621. mg_uecc_vli_nativeToBytes(native, num_bytes, bytes);
  12622. }
  12623. #else
  12624. MG_UECC_VLI_API void mg_uecc_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  12625. const mg_uecc_word_t *native) {
  12626. int i;
  12627. for (i = 0; i < num_bytes; ++i) {
  12628. unsigned b = (unsigned) (num_bytes - 1 - i);
  12629. bytes[i] = (uint8_t) (native[b / MG_UECC_WORD_SIZE] >>
  12630. (8 * (b % MG_UECC_WORD_SIZE)));
  12631. }
  12632. }
  12633. MG_UECC_VLI_API void mg_uecc_vli_bytesToNative(mg_uecc_word_t *native,
  12634. const uint8_t *bytes,
  12635. int num_bytes) {
  12636. int i;
  12637. mg_uecc_vli_clear(native,
  12638. (wordcount_t) ((num_bytes + (MG_UECC_WORD_SIZE - 1)) /
  12639. MG_UECC_WORD_SIZE));
  12640. for (i = 0; i < num_bytes; ++i) {
  12641. unsigned b = (unsigned) (num_bytes - 1 - i);
  12642. native[b / MG_UECC_WORD_SIZE] |= (mg_uecc_word_t) bytes[i]
  12643. << (8 * (b % MG_UECC_WORD_SIZE));
  12644. }
  12645. }
  12646. #endif /* MG_UECC_WORD_SIZE */
  12647. int mg_uecc_make_key(uint8_t *public_key, uint8_t *private_key,
  12648. MG_UECC_Curve curve) {
  12649. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12650. mg_uecc_word_t *_private = (mg_uecc_word_t *) private_key;
  12651. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12652. #else
  12653. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12654. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12655. #endif
  12656. mg_uecc_word_t tries;
  12657. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12658. if (!mg_uecc_generate_random_int(_private, curve->n,
  12659. BITS_TO_WORDS(curve->num_n_bits))) {
  12660. return 0;
  12661. }
  12662. if (EccPoint_compute_public_key(_public, _private, curve)) {
  12663. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12664. mg_uecc_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits),
  12665. _private);
  12666. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  12667. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  12668. _public + curve->num_words);
  12669. #endif
  12670. return 1;
  12671. }
  12672. }
  12673. return 0;
  12674. }
  12675. int mg_uecc_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
  12676. uint8_t *secret, MG_UECC_Curve curve) {
  12677. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12678. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12679. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  12680. mg_uecc_word_t *p2[2] = {_private, tmp};
  12681. mg_uecc_word_t *initial_Z = 0;
  12682. mg_uecc_word_t carry;
  12683. wordcount_t num_words = curve->num_words;
  12684. wordcount_t num_bytes = curve->num_bytes;
  12685. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12686. bcopy((uint8_t *) _private, private_key, num_bytes);
  12687. bcopy((uint8_t *) _public, public_key, num_bytes * 2);
  12688. #else
  12689. mg_uecc_vli_bytesToNative(_private, private_key,
  12690. BITS_TO_BYTES(curve->num_n_bits));
  12691. mg_uecc_vli_bytesToNative(_public, public_key, num_bytes);
  12692. mg_uecc_vli_bytesToNative(_public + num_words, public_key + num_bytes,
  12693. num_bytes);
  12694. #endif
  12695. /* Regularize the bitcount for the private key so that attackers cannot use a
  12696. side channel attack to learn the number of leading zeros. */
  12697. carry = regularize_k(_private, _private, tmp, curve);
  12698. /* If an RNG function was specified, try to get a random initial Z value to
  12699. improve protection against side-channel attacks. */
  12700. if (g_rng_function) {
  12701. if (!mg_uecc_generate_random_int(p2[carry], curve->p, num_words)) {
  12702. return 0;
  12703. }
  12704. initial_Z = p2[carry];
  12705. }
  12706. EccPoint_mult(_public, _public, p2[!carry], initial_Z,
  12707. (bitcount_t) (curve->num_n_bits + 1), curve);
  12708. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12709. bcopy((uint8_t *) secret, (uint8_t *) _public, num_bytes);
  12710. #else
  12711. mg_uecc_vli_nativeToBytes(secret, num_bytes, _public);
  12712. #endif
  12713. return !EccPoint_isZero(_public, curve);
  12714. }
  12715. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  12716. void mg_uecc_compress(const uint8_t *public_key, uint8_t *compressed,
  12717. MG_UECC_Curve curve) {
  12718. wordcount_t i;
  12719. for (i = 0; i < curve->num_bytes; ++i) {
  12720. compressed[i + 1] = public_key[i];
  12721. }
  12722. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12723. compressed[0] = 2 + (public_key[curve->num_bytes] & 0x01);
  12724. #else
  12725. compressed[0] = 2 + (public_key[curve->num_bytes * 2 - 1] & 0x01);
  12726. #endif
  12727. }
  12728. void mg_uecc_decompress(const uint8_t *compressed, uint8_t *public_key,
  12729. MG_UECC_Curve curve) {
  12730. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12731. mg_uecc_word_t *point = (mg_uecc_word_t *) public_key;
  12732. #else
  12733. mg_uecc_word_t point[MG_UECC_MAX_WORDS * 2];
  12734. #endif
  12735. mg_uecc_word_t *y = point + curve->num_words;
  12736. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12737. bcopy(public_key, compressed + 1, curve->num_bytes);
  12738. #else
  12739. mg_uecc_vli_bytesToNative(point, compressed + 1, curve->num_bytes);
  12740. #endif
  12741. curve->x_side(y, point, curve);
  12742. curve->mod_sqrt(y, curve);
  12743. if ((uint8_t) (y[0] & 0x01) != (compressed[0] & 0x01)) {
  12744. mg_uecc_vli_sub(y, curve->p, y, curve->num_words);
  12745. }
  12746. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12747. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, point);
  12748. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, y);
  12749. #endif
  12750. }
  12751. #endif /* MG_UECC_SUPPORT_COMPRESSED_POINT */
  12752. MG_UECC_VLI_API int mg_uecc_valid_point(const mg_uecc_word_t *point,
  12753. MG_UECC_Curve curve) {
  12754. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  12755. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  12756. wordcount_t num_words = curve->num_words;
  12757. /* The point at infinity is invalid. */
  12758. if (EccPoint_isZero(point, curve)) {
  12759. return 0;
  12760. }
  12761. /* x and y must be smaller than p. */
  12762. if (mg_uecc_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
  12763. mg_uecc_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
  12764. return 0;
  12765. }
  12766. mg_uecc_vli_modSquare_fast(tmp1, point + num_words, curve);
  12767. curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
  12768. /* Make sure that y^2 == x^3 + ax + b */
  12769. return (int) (mg_uecc_vli_equal(tmp1, tmp2, num_words));
  12770. }
  12771. int mg_uecc_valid_public_key(const uint8_t *public_key, MG_UECC_Curve curve) {
  12772. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12773. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12774. #else
  12775. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12776. #endif
  12777. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12778. mg_uecc_vli_bytesToNative(_public, public_key, curve->num_bytes);
  12779. mg_uecc_vli_bytesToNative(_public + curve->num_words,
  12780. public_key + curve->num_bytes, curve->num_bytes);
  12781. #endif
  12782. return mg_uecc_valid_point(_public, curve);
  12783. }
  12784. int mg_uecc_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
  12785. MG_UECC_Curve curve) {
  12786. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12787. mg_uecc_word_t *_private = (mg_uecc_word_t *) private_key;
  12788. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  12789. #else
  12790. mg_uecc_word_t _private[MG_UECC_MAX_WORDS];
  12791. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  12792. #endif
  12793. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12794. mg_uecc_vli_bytesToNative(_private, private_key,
  12795. BITS_TO_BYTES(curve->num_n_bits));
  12796. #endif
  12797. /* Make sure the private key is in the range [1, n-1]. */
  12798. if (mg_uecc_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
  12799. return 0;
  12800. }
  12801. if (mg_uecc_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) !=
  12802. 1) {
  12803. return 0;
  12804. }
  12805. /* Compute public key. */
  12806. if (!EccPoint_compute_public_key(_public, _private, curve)) {
  12807. return 0;
  12808. }
  12809. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12810. mg_uecc_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  12811. mg_uecc_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  12812. _public + curve->num_words);
  12813. #endif
  12814. return 1;
  12815. }
  12816. /* -------- ECDSA code -------- */
  12817. static void bits2int(mg_uecc_word_t *native, const uint8_t *bits,
  12818. unsigned bits_size, MG_UECC_Curve curve) {
  12819. unsigned num_n_bytes = (unsigned) BITS_TO_BYTES(curve->num_n_bits);
  12820. unsigned num_n_words = (unsigned) BITS_TO_WORDS(curve->num_n_bits);
  12821. int shift;
  12822. mg_uecc_word_t carry;
  12823. mg_uecc_word_t *ptr;
  12824. if (bits_size > num_n_bytes) {
  12825. bits_size = num_n_bytes;
  12826. }
  12827. mg_uecc_vli_clear(native, (wordcount_t) num_n_words);
  12828. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12829. bcopy((uint8_t *) native, bits, bits_size);
  12830. #else
  12831. mg_uecc_vli_bytesToNative(native, bits, (int) bits_size);
  12832. #endif
  12833. if (bits_size * 8 <= (unsigned) curve->num_n_bits) {
  12834. return;
  12835. }
  12836. shift = (int) bits_size * 8 - curve->num_n_bits;
  12837. carry = 0;
  12838. ptr = native + num_n_words;
  12839. while (ptr-- > native) {
  12840. mg_uecc_word_t temp = *ptr;
  12841. *ptr = (temp >> shift) | carry;
  12842. carry = temp << (MG_UECC_WORD_BITS - shift);
  12843. }
  12844. /* Reduce mod curve_n */
  12845. if (mg_uecc_vli_cmp_unsafe(curve->n, native, (wordcount_t) num_n_words) !=
  12846. 1) {
  12847. mg_uecc_vli_sub(native, native, curve->n, (wordcount_t) num_n_words);
  12848. }
  12849. }
  12850. static int mg_uecc_sign_with_k_internal(const uint8_t *private_key,
  12851. const uint8_t *message_hash,
  12852. unsigned hash_size, mg_uecc_word_t *k,
  12853. uint8_t *signature,
  12854. MG_UECC_Curve curve) {
  12855. mg_uecc_word_t tmp[MG_UECC_MAX_WORDS];
  12856. mg_uecc_word_t s[MG_UECC_MAX_WORDS];
  12857. mg_uecc_word_t *k2[2] = {tmp, s};
  12858. mg_uecc_word_t *initial_Z = 0;
  12859. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12860. mg_uecc_word_t *p = (mg_uecc_word_t *) signature;
  12861. #else
  12862. mg_uecc_word_t p[MG_UECC_MAX_WORDS * 2];
  12863. #endif
  12864. mg_uecc_word_t carry;
  12865. wordcount_t num_words = curve->num_words;
  12866. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  12867. bitcount_t num_n_bits = curve->num_n_bits;
  12868. /* Make sure 0 < k < curve_n */
  12869. if (mg_uecc_vli_isZero(k, num_words) ||
  12870. mg_uecc_vli_cmp(curve->n, k, num_n_words) != 1) {
  12871. return 0;
  12872. }
  12873. carry = regularize_k(k, tmp, s, curve);
  12874. /* If an RNG function was specified, try to get a random initial Z value to
  12875. improve protection against side-channel attacks. */
  12876. if (g_rng_function) {
  12877. if (!mg_uecc_generate_random_int(k2[carry], curve->p, num_words)) {
  12878. return 0;
  12879. }
  12880. initial_Z = k2[carry];
  12881. }
  12882. EccPoint_mult(p, curve->G, k2[!carry], initial_Z,
  12883. (bitcount_t) (num_n_bits + 1), curve);
  12884. if (mg_uecc_vli_isZero(p, num_words)) {
  12885. return 0;
  12886. }
  12887. /* If an RNG function was specified, get a random number
  12888. to prevent side channel analysis of k. */
  12889. if (!g_rng_function) {
  12890. mg_uecc_vli_clear(tmp, num_n_words);
  12891. tmp[0] = 1;
  12892. } else if (!mg_uecc_generate_random_int(tmp, curve->n, num_n_words)) {
  12893. return 0;
  12894. }
  12895. /* Prevent side channel analysis of mg_uecc_vli_modInv() to determine
  12896. bits of k / the private key by premultiplying by a random number */
  12897. mg_uecc_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
  12898. mg_uecc_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */
  12899. mg_uecc_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
  12900. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  12901. mg_uecc_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
  12902. #endif
  12903. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12904. bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
  12905. #else
  12906. mg_uecc_vli_bytesToNative(tmp, private_key,
  12907. BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */
  12908. #endif
  12909. s[num_n_words - 1] = 0;
  12910. mg_uecc_vli_set(s, p, num_words);
  12911. mg_uecc_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
  12912. bits2int(tmp, message_hash, hash_size, curve);
  12913. mg_uecc_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
  12914. mg_uecc_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */
  12915. if (mg_uecc_vli_numBits(s, num_n_words) > (bitcount_t) curve->num_bytes * 8) {
  12916. return 0;
  12917. }
  12918. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  12919. bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s,
  12920. curve->num_bytes);
  12921. #else
  12922. mg_uecc_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
  12923. #endif
  12924. return 1;
  12925. }
  12926. #if 0
  12927. /* For testing - sign with an explicitly specified k value */
  12928. int mg_uecc_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
  12929. unsigned hash_size, const uint8_t *k, uint8_t *signature,
  12930. MG_UECC_Curve curve) {
  12931. mg_uecc_word_t k2[MG_UECC_MAX_WORDS];
  12932. bits2int(k2, k, (unsigned) BITS_TO_BYTES(curve->num_n_bits), curve);
  12933. return mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, k2,
  12934. signature, curve);
  12935. }
  12936. #endif
  12937. int mg_uecc_sign(const uint8_t *private_key, const uint8_t *message_hash,
  12938. unsigned hash_size, uint8_t *signature, MG_UECC_Curve curve) {
  12939. mg_uecc_word_t k[MG_UECC_MAX_WORDS];
  12940. mg_uecc_word_t tries;
  12941. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  12942. if (!mg_uecc_generate_random_int(k, curve->n,
  12943. BITS_TO_WORDS(curve->num_n_bits))) {
  12944. return 0;
  12945. }
  12946. if (mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, k,
  12947. signature, curve)) {
  12948. return 1;
  12949. }
  12950. }
  12951. return 0;
  12952. }
  12953. /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always
  12954. the same size as the hash result size. */
  12955. static void HMAC_init(const MG_UECC_HashContext *hash_context,
  12956. const uint8_t *K) {
  12957. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  12958. unsigned i;
  12959. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x36;
  12960. for (; i < hash_context->block_size; ++i) pad[i] = 0x36;
  12961. hash_context->init_hash(hash_context);
  12962. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  12963. }
  12964. static void HMAC_update(const MG_UECC_HashContext *hash_context,
  12965. const uint8_t *message, unsigned message_size) {
  12966. hash_context->update_hash(hash_context, message, message_size);
  12967. }
  12968. static void HMAC_finish(const MG_UECC_HashContext *hash_context,
  12969. const uint8_t *K, uint8_t *result) {
  12970. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  12971. unsigned i;
  12972. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x5c;
  12973. for (; i < hash_context->block_size; ++i) pad[i] = 0x5c;
  12974. hash_context->finish_hash(hash_context, result);
  12975. hash_context->init_hash(hash_context);
  12976. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  12977. hash_context->update_hash(hash_context, result, hash_context->result_size);
  12978. hash_context->finish_hash(hash_context, result);
  12979. }
  12980. /* V = HMAC_K(V) */
  12981. static void update_V(const MG_UECC_HashContext *hash_context, uint8_t *K,
  12982. uint8_t *V) {
  12983. HMAC_init(hash_context, K);
  12984. HMAC_update(hash_context, V, hash_context->result_size);
  12985. HMAC_finish(hash_context, K, V);
  12986. }
  12987. /* Deterministic signing, similar to RFC 6979. Differences are:
  12988. * We just use H(m) directly rather than bits2octets(H(m))
  12989. (it is not reduced modulo curve_n).
  12990. * We generate a value for k (aka T) directly rather than converting
  12991. endianness.
  12992. Layout of hash_context->tmp: <K> | <V> | (1 byte overlapped 0x00 or 0x01) /
  12993. <HMAC pad> */
  12994. int mg_uecc_sign_deterministic(const uint8_t *private_key,
  12995. const uint8_t *message_hash, unsigned hash_size,
  12996. const MG_UECC_HashContext *hash_context,
  12997. uint8_t *signature, MG_UECC_Curve curve) {
  12998. uint8_t *K = hash_context->tmp;
  12999. uint8_t *V = K + hash_context->result_size;
  13000. wordcount_t num_bytes = curve->num_bytes;
  13001. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  13002. bitcount_t num_n_bits = curve->num_n_bits;
  13003. mg_uecc_word_t tries;
  13004. unsigned i;
  13005. for (i = 0; i < hash_context->result_size; ++i) {
  13006. V[i] = 0x01;
  13007. K[i] = 0;
  13008. }
  13009. /* K = HMAC_K(V || 0x00 || int2octets(x) || h(m)) */
  13010. HMAC_init(hash_context, K);
  13011. V[hash_context->result_size] = 0x00;
  13012. HMAC_update(hash_context, V, hash_context->result_size + 1);
  13013. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  13014. HMAC_update(hash_context, message_hash, hash_size);
  13015. HMAC_finish(hash_context, K, K);
  13016. update_V(hash_context, K, V);
  13017. /* K = HMAC_K(V || 0x01 || int2octets(x) || h(m)) */
  13018. HMAC_init(hash_context, K);
  13019. V[hash_context->result_size] = 0x01;
  13020. HMAC_update(hash_context, V, hash_context->result_size + 1);
  13021. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  13022. HMAC_update(hash_context, message_hash, hash_size);
  13023. HMAC_finish(hash_context, K, K);
  13024. update_V(hash_context, K, V);
  13025. for (tries = 0; tries < MG_UECC_RNG_MAX_TRIES; ++tries) {
  13026. mg_uecc_word_t T[MG_UECC_MAX_WORDS];
  13027. uint8_t *T_ptr = (uint8_t *) T;
  13028. wordcount_t T_bytes = 0;
  13029. for (;;) {
  13030. update_V(hash_context, K, V);
  13031. for (i = 0; i < hash_context->result_size; ++i) {
  13032. T_ptr[T_bytes++] = V[i];
  13033. if (T_bytes >= num_n_words * MG_UECC_WORD_SIZE) {
  13034. goto filled;
  13035. }
  13036. }
  13037. }
  13038. filled:
  13039. if ((bitcount_t) num_n_words * MG_UECC_WORD_SIZE * 8 > num_n_bits) {
  13040. mg_uecc_word_t mask = (mg_uecc_word_t) -1;
  13041. T[num_n_words - 1] &=
  13042. mask >>
  13043. ((bitcount_t) (num_n_words * MG_UECC_WORD_SIZE * 8 - num_n_bits));
  13044. }
  13045. if (mg_uecc_sign_with_k_internal(private_key, message_hash, hash_size, T,
  13046. signature, curve)) {
  13047. return 1;
  13048. }
  13049. /* K = HMAC_K(V || 0x00) */
  13050. HMAC_init(hash_context, K);
  13051. V[hash_context->result_size] = 0x00;
  13052. HMAC_update(hash_context, V, hash_context->result_size + 1);
  13053. HMAC_finish(hash_context, K, K);
  13054. update_V(hash_context, K, V);
  13055. }
  13056. return 0;
  13057. }
  13058. static bitcount_t smax(bitcount_t a, bitcount_t b) {
  13059. return (a > b ? a : b);
  13060. }
  13061. int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash,
  13062. unsigned hash_size, const uint8_t *signature,
  13063. MG_UECC_Curve curve) {
  13064. mg_uecc_word_t u1[MG_UECC_MAX_WORDS], u2[MG_UECC_MAX_WORDS];
  13065. mg_uecc_word_t z[MG_UECC_MAX_WORDS];
  13066. mg_uecc_word_t sum[MG_UECC_MAX_WORDS * 2];
  13067. mg_uecc_word_t rx[MG_UECC_MAX_WORDS];
  13068. mg_uecc_word_t ry[MG_UECC_MAX_WORDS];
  13069. mg_uecc_word_t tx[MG_UECC_MAX_WORDS];
  13070. mg_uecc_word_t ty[MG_UECC_MAX_WORDS];
  13071. mg_uecc_word_t tz[MG_UECC_MAX_WORDS];
  13072. const mg_uecc_word_t *points[4];
  13073. const mg_uecc_word_t *point;
  13074. bitcount_t num_bits;
  13075. bitcount_t i;
  13076. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  13077. mg_uecc_word_t *_public = (mg_uecc_word_t *) public_key;
  13078. #else
  13079. mg_uecc_word_t _public[MG_UECC_MAX_WORDS * 2];
  13080. #endif
  13081. mg_uecc_word_t r[MG_UECC_MAX_WORDS], s[MG_UECC_MAX_WORDS];
  13082. wordcount_t num_words = curve->num_words;
  13083. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  13084. rx[num_n_words - 1] = 0;
  13085. r[num_n_words - 1] = 0;
  13086. s[num_n_words - 1] = 0;
  13087. #if MG_UECC_VLI_NATIVE_LITTLE_ENDIAN
  13088. bcopy((uint8_t *) r, signature, curve->num_bytes);
  13089. bcopy((uint8_t *) s, signature + curve->num_bytes, curve->num_bytes);
  13090. #else
  13091. mg_uecc_vli_bytesToNative(_public, public_key, curve->num_bytes);
  13092. mg_uecc_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
  13093. curve->num_bytes);
  13094. mg_uecc_vli_bytesToNative(r, signature, curve->num_bytes);
  13095. mg_uecc_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
  13096. #endif
  13097. /* r, s must not be 0. */
  13098. if (mg_uecc_vli_isZero(r, num_words) || mg_uecc_vli_isZero(s, num_words)) {
  13099. return 0;
  13100. }
  13101. /* r, s must be < n. */
  13102. if (mg_uecc_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
  13103. mg_uecc_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
  13104. return 0;
  13105. }
  13106. /* Calculate u1 and u2. */
  13107. mg_uecc_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
  13108. u1[num_n_words - 1] = 0;
  13109. bits2int(u1, message_hash, hash_size, curve);
  13110. mg_uecc_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
  13111. mg_uecc_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */
  13112. /* Calculate sum = G + Q. */
  13113. mg_uecc_vli_set(sum, _public, num_words);
  13114. mg_uecc_vli_set(sum + num_words, _public + num_words, num_words);
  13115. mg_uecc_vli_set(tx, curve->G, num_words);
  13116. mg_uecc_vli_set(ty, curve->G + num_words, num_words);
  13117. mg_uecc_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
  13118. XYcZ_add(tx, ty, sum, sum + num_words, curve);
  13119. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
  13120. apply_z(sum, sum + num_words, z, curve);
  13121. /* Use Shamir's trick to calculate u1*G + u2*Q */
  13122. points[0] = 0;
  13123. points[1] = curve->G;
  13124. points[2] = _public;
  13125. points[3] = sum;
  13126. num_bits = smax(mg_uecc_vli_numBits(u1, num_n_words),
  13127. mg_uecc_vli_numBits(u2, num_n_words));
  13128. point =
  13129. points[(!!mg_uecc_vli_testBit(u1, (bitcount_t) (num_bits - 1))) |
  13130. ((!!mg_uecc_vli_testBit(u2, (bitcount_t) (num_bits - 1))) << 1)];
  13131. mg_uecc_vli_set(rx, point, num_words);
  13132. mg_uecc_vli_set(ry, point + num_words, num_words);
  13133. mg_uecc_vli_clear(z, num_words);
  13134. z[0] = 1;
  13135. for (i = num_bits - 2; i >= 0; --i) {
  13136. mg_uecc_word_t index;
  13137. curve->double_jacobian(rx, ry, z, curve);
  13138. index = (!!mg_uecc_vli_testBit(u1, i)) |
  13139. (mg_uecc_word_t) ((!!mg_uecc_vli_testBit(u2, i)) << 1);
  13140. point = points[index];
  13141. if (point) {
  13142. mg_uecc_vli_set(tx, point, num_words);
  13143. mg_uecc_vli_set(ty, point + num_words, num_words);
  13144. apply_z(tx, ty, z, curve);
  13145. mg_uecc_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
  13146. XYcZ_add(tx, ty, rx, ry, curve);
  13147. mg_uecc_vli_modMult_fast(z, z, tz, curve);
  13148. }
  13149. }
  13150. mg_uecc_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
  13151. apply_z(rx, ry, z, curve);
  13152. /* v = x1 (mod n) */
  13153. if (mg_uecc_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
  13154. mg_uecc_vli_sub(rx, rx, curve->n, num_n_words);
  13155. }
  13156. /* Accept only if v == r. */
  13157. return (int) (mg_uecc_vli_equal(rx, r, num_words));
  13158. }
  13159. #if MG_UECC_ENABLE_VLI_API
  13160. unsigned mg_uecc_curve_num_words(MG_UECC_Curve curve) {
  13161. return curve->num_words;
  13162. }
  13163. unsigned mg_uecc_curve_num_bytes(MG_UECC_Curve curve) {
  13164. return curve->num_bytes;
  13165. }
  13166. unsigned mg_uecc_curve_num_bits(MG_UECC_Curve curve) {
  13167. return curve->num_bytes * 8;
  13168. }
  13169. unsigned mg_uecc_curve_num_n_words(MG_UECC_Curve curve) {
  13170. return BITS_TO_WORDS(curve->num_n_bits);
  13171. }
  13172. unsigned mg_uecc_curve_num_n_bytes(MG_UECC_Curve curve) {
  13173. return BITS_TO_BYTES(curve->num_n_bits);
  13174. }
  13175. unsigned mg_uecc_curve_num_n_bits(MG_UECC_Curve curve) {
  13176. return curve->num_n_bits;
  13177. }
  13178. const mg_uecc_word_t *mg_uecc_curve_p(MG_UECC_Curve curve) {
  13179. return curve->p;
  13180. }
  13181. const mg_uecc_word_t *mg_uecc_curve_n(MG_UECC_Curve curve) {
  13182. return curve->n;
  13183. }
  13184. const mg_uecc_word_t *mg_uecc_curve_G(MG_UECC_Curve curve) {
  13185. return curve->G;
  13186. }
  13187. const mg_uecc_word_t *mg_uecc_curve_b(MG_UECC_Curve curve) {
  13188. return curve->b;
  13189. }
  13190. #if MG_UECC_SUPPORT_COMPRESSED_POINT
  13191. void mg_uecc_vli_mod_sqrt(mg_uecc_word_t *a, MG_UECC_Curve curve) {
  13192. curve->mod_sqrt(a, curve);
  13193. }
  13194. #endif
  13195. void mg_uecc_vli_mmod_fast(mg_uecc_word_t *result, mg_uecc_word_t *product,
  13196. MG_UECC_Curve curve) {
  13197. #if (MG_UECC_OPTIMIZATION_LEVEL > 0)
  13198. curve->mmod_fast(result, product);
  13199. #else
  13200. mg_uecc_vli_mmod(result, product, curve->p, curve->num_words);
  13201. #endif
  13202. }
  13203. void mg_uecc_point_mult(mg_uecc_word_t *result, const mg_uecc_word_t *point,
  13204. const mg_uecc_word_t *scalar, MG_UECC_Curve curve) {
  13205. mg_uecc_word_t tmp1[MG_UECC_MAX_WORDS];
  13206. mg_uecc_word_t tmp2[MG_UECC_MAX_WORDS];
  13207. mg_uecc_word_t *p2[2] = {tmp1, tmp2};
  13208. mg_uecc_word_t carry = regularize_k(scalar, tmp1, tmp2, curve);
  13209. EccPoint_mult(result, point, p2[!carry], 0, curve->num_n_bits + 1, curve);
  13210. }
  13211. #endif /* MG_UECC_ENABLE_VLI_API */
  13212. #endif // MG_TLS_BUILTIN
  13213. // End of uecc BSD-2
  13214. #ifdef MG_ENABLE_LINES
  13215. #line 1 "src/tls_x25519.c"
  13216. #endif
  13217. /**
  13218. * Adapted from STROBE: https://strobe.sourceforge.io/
  13219. * Copyright (c) 2015-2016 Cryptography Research, Inc.
  13220. * Author: Mike Hamburg
  13221. * License: MIT License
  13222. */
  13223. const uint8_t X25519_BASE_POINT[X25519_BYTES] = {9};
  13224. #define X25519_WBITS 32
  13225. typedef uint32_t limb_t;
  13226. typedef uint64_t dlimb_t;
  13227. typedef int64_t sdlimb_t;
  13228. #define NLIMBS (256 / X25519_WBITS)
  13229. typedef limb_t mg_fe[NLIMBS];
  13230. static limb_t umaal(limb_t *carry, limb_t acc, limb_t mand, limb_t mier) {
  13231. dlimb_t tmp = (dlimb_t) mand * mier + acc + *carry;
  13232. *carry = (limb_t) (tmp >> X25519_WBITS);
  13233. return (limb_t) tmp;
  13234. }
  13235. // These functions are implemented in terms of umaal on ARM
  13236. static limb_t adc(limb_t *carry, limb_t acc, limb_t mand) {
  13237. dlimb_t total = (dlimb_t) *carry + acc + mand;
  13238. *carry = (limb_t) (total >> X25519_WBITS);
  13239. return (limb_t) total;
  13240. }
  13241. static limb_t adc0(limb_t *carry, limb_t acc) {
  13242. dlimb_t total = (dlimb_t) *carry + acc;
  13243. *carry = (limb_t) (total >> X25519_WBITS);
  13244. return (limb_t) total;
  13245. }
  13246. // - Precondition: carry is small.
  13247. // - Invariant: result of propagate is < 2^255 + 1 word
  13248. // - In particular, always less than 2p.
  13249. // - Also, output x >= min(x,19)
  13250. static void propagate(mg_fe x, limb_t over) {
  13251. unsigned i;
  13252. limb_t carry;
  13253. over = x[NLIMBS - 1] >> (X25519_WBITS - 1) | over << 1;
  13254. x[NLIMBS - 1] &= ~((limb_t) 1 << (X25519_WBITS - 1));
  13255. carry = over * 19;
  13256. for (i = 0; i < NLIMBS; i++) {
  13257. x[i] = adc0(&carry, x[i]);
  13258. }
  13259. }
  13260. static void add(mg_fe out, const mg_fe a, const mg_fe b) {
  13261. unsigned i;
  13262. limb_t carry = 0;
  13263. for (i = 0; i < NLIMBS; i++) {
  13264. out[i] = adc(&carry, a[i], b[i]);
  13265. }
  13266. propagate(out, carry);
  13267. }
  13268. static void sub(mg_fe out, const mg_fe a, const mg_fe b) {
  13269. unsigned i;
  13270. sdlimb_t carry = -38;
  13271. for (i = 0; i < NLIMBS; i++) {
  13272. carry = carry + a[i] - b[i];
  13273. out[i] = (limb_t) carry;
  13274. carry >>= X25519_WBITS;
  13275. }
  13276. propagate(out, (limb_t) (1 + carry));
  13277. }
  13278. // `b` can contain less than 8 limbs, thus we use `limb_t *` instead of `mg_fe`
  13279. // to avoid build warnings
  13280. static void mul(mg_fe out, const mg_fe a, const limb_t *b, unsigned nb) {
  13281. limb_t accum[2 * NLIMBS] = {0};
  13282. unsigned i, j;
  13283. limb_t carry2;
  13284. for (i = 0; i < nb; i++) {
  13285. limb_t mand = b[i];
  13286. carry2 = 0;
  13287. for (j = 0; j < NLIMBS; j++) {
  13288. limb_t tmp; // "a" may be misaligned
  13289. memcpy(&tmp, &a[j], sizeof(tmp)); // So make an aligned copy
  13290. accum[i + j] = umaal(&carry2, accum[i + j], mand, tmp);
  13291. }
  13292. accum[i + j] = carry2;
  13293. }
  13294. carry2 = 0;
  13295. for (j = 0; j < NLIMBS; j++) {
  13296. out[j] = umaal(&carry2, accum[j], 38, accum[j + NLIMBS]);
  13297. }
  13298. propagate(out, carry2);
  13299. }
  13300. static void sqr(mg_fe out, const mg_fe a) {
  13301. mul(out, a, a, NLIMBS);
  13302. }
  13303. static void mul1(mg_fe out, const mg_fe a) {
  13304. mul(out, a, out, NLIMBS);
  13305. }
  13306. static void sqr1(mg_fe a) {
  13307. mul1(a, a);
  13308. }
  13309. static void condswap(limb_t a[2 * NLIMBS], limb_t b[2 * NLIMBS],
  13310. limb_t doswap) {
  13311. unsigned i;
  13312. for (i = 0; i < 2 * NLIMBS; i++) {
  13313. limb_t xor_ab = (a[i] ^ b[i]) & doswap;
  13314. a[i] ^= xor_ab;
  13315. b[i] ^= xor_ab;
  13316. }
  13317. }
  13318. // Canonicalize a field element x, reducing it to the least residue which is
  13319. // congruent to it mod 2^255-19
  13320. // - Precondition: x < 2^255 + 1 word
  13321. static limb_t canon(mg_fe x) {
  13322. // First, add 19.
  13323. unsigned i;
  13324. limb_t carry0 = 19;
  13325. limb_t res;
  13326. sdlimb_t carry;
  13327. for (i = 0; i < NLIMBS; i++) {
  13328. x[i] = adc0(&carry0, x[i]);
  13329. }
  13330. propagate(x, carry0);
  13331. // Here, 19 <= x2 < 2^255
  13332. // - This is because we added 19, so before propagate it can't be less
  13333. // than 19. After propagate, it still can't be less than 19, because if
  13334. // propagate does anything it adds 19.
  13335. // - We know that the high bit must be clear, because either the input was ~
  13336. // 2^255 + one word + 19 (in which case it propagates to at most 2 words) or
  13337. // it was < 2^255. So now, if we subtract 19, we will get back to something in
  13338. // [0,2^255-19).
  13339. carry = -19;
  13340. res = 0;
  13341. for (i = 0; i < NLIMBS; i++) {
  13342. carry += x[i];
  13343. res |= x[i] = (limb_t) carry;
  13344. carry >>= X25519_WBITS;
  13345. }
  13346. return (limb_t) (((dlimb_t) res - 1) >> X25519_WBITS);
  13347. }
  13348. static const limb_t a24[1] = {121665};
  13349. static void ladder_part1(mg_fe xs[5]) {
  13350. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  13351. add(t1, x2, z2); // t1 = A
  13352. sub(z2, x2, z2); // z2 = B
  13353. add(x2, x3, z3); // x2 = C
  13354. sub(z3, x3, z3); // z3 = D
  13355. mul1(z3, t1); // z3 = DA
  13356. mul1(x2, z2); // x3 = BC
  13357. add(x3, z3, x2); // x3 = DA+CB
  13358. sub(z3, z3, x2); // z3 = DA-CB
  13359. sqr1(t1); // t1 = AA
  13360. sqr1(z2); // z2 = BB
  13361. sub(x2, t1, z2); // x2 = E = AA-BB
  13362. mul(z2, x2, a24, sizeof(a24) / sizeof(a24[0])); // z2 = E*a24
  13363. add(z2, z2, t1); // z2 = E*a24 + AA
  13364. }
  13365. static void ladder_part2(mg_fe xs[5], const mg_fe x1) {
  13366. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  13367. sqr1(z3); // z3 = (DA-CB)^2
  13368. mul1(z3, x1); // z3 = x1 * (DA-CB)^2
  13369. sqr1(x3); // x3 = (DA+CB)^2
  13370. mul1(z2, x2); // z2 = AA*(E*a24+AA)
  13371. sub(x2, t1, x2); // x2 = BB again
  13372. mul1(x2, t1); // x2 = AA*BB
  13373. }
  13374. static void x25519_core(mg_fe xs[5], const uint8_t scalar[X25519_BYTES],
  13375. const uint8_t *x1, int clamp) {
  13376. int i;
  13377. mg_fe x1_limbs;
  13378. limb_t swap = 0;
  13379. limb_t *x2 = xs[0], *x3 = xs[2], *z3 = xs[3];
  13380. memset(xs, 0, 4 * sizeof(mg_fe));
  13381. x2[0] = z3[0] = 1;
  13382. for (i = 0; i < NLIMBS; i++) {
  13383. x3[i] = x1_limbs[i] =
  13384. MG_U32(x1[i * 4 + 3], x1[i * 4 + 2], x1[i * 4 + 1], x1[i * 4]);
  13385. }
  13386. for (i = 255; i >= 0; i--) {
  13387. uint8_t bytei = scalar[i / 8];
  13388. limb_t doswap;
  13389. if (clamp) {
  13390. if (i / 8 == 0) {
  13391. bytei &= (uint8_t) ~7U;
  13392. } else if (i / 8 == X25519_BYTES - 1) {
  13393. bytei &= 0x7F;
  13394. bytei |= 0x40;
  13395. }
  13396. }
  13397. doswap = 0 - (limb_t) ((bytei >> (i % 8)) & 1);
  13398. condswap(x2, x3, swap ^ doswap);
  13399. swap = doswap;
  13400. ladder_part1(xs);
  13401. ladder_part2(xs, (const limb_t *) x1_limbs);
  13402. }
  13403. condswap(x2, x3, swap);
  13404. }
  13405. int mg_tls_x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES],
  13406. const uint8_t x1[X25519_BYTES], int clamp) {
  13407. int i, ret;
  13408. mg_fe xs[5], out_limbs;
  13409. limb_t *x2, *z2, *z3, *prev;
  13410. static const struct {
  13411. uint8_t a, c, n;
  13412. } steps[13] = {{2, 1, 1}, {2, 1, 1}, {4, 2, 3}, {2, 4, 6}, {3, 1, 1},
  13413. {3, 2, 12}, {4, 3, 25}, {2, 3, 25}, {2, 4, 50}, {3, 2, 125},
  13414. {3, 1, 2}, {3, 1, 2}, {3, 1, 1}};
  13415. x25519_core(xs, scalar, x1, clamp);
  13416. // Precomputed inversion chain
  13417. x2 = xs[0];
  13418. z2 = xs[1];
  13419. z3 = xs[3];
  13420. prev = z2;
  13421. for (i = 0; i < 13; i++) {
  13422. int j;
  13423. limb_t *a = xs[steps[i].a];
  13424. for (j = steps[i].n; j > 0; j--) {
  13425. sqr(a, prev);
  13426. prev = a;
  13427. }
  13428. mul1(a, xs[steps[i].c]);
  13429. }
  13430. // Here prev = z3
  13431. // x2 /= z2
  13432. mul(out_limbs, x2, z3, NLIMBS);
  13433. ret = (int) canon(out_limbs);
  13434. if (!clamp) ret = 0;
  13435. for (i = 0; i < NLIMBS; i++) {
  13436. uint32_t n = out_limbs[i];
  13437. out[i * 4] = (uint8_t) (n & 0xff);
  13438. out[i * 4 + 1] = (uint8_t) ((n >> 8) & 0xff);
  13439. out[i * 4 + 2] = (uint8_t) ((n >> 16) & 0xff);
  13440. out[i * 4 + 3] = (uint8_t) ((n >> 24) & 0xff);
  13441. }
  13442. return ret;
  13443. }
  13444. #ifdef MG_ENABLE_LINES
  13445. #line 1 "src/url.c"
  13446. #endif
  13447. struct url {
  13448. size_t key, user, pass, host, port, uri, end;
  13449. };
  13450. int mg_url_is_ssl(const char *url) {
  13451. return strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0 ||
  13452. strncmp(url, "mqtts:", 6) == 0 || strncmp(url, "ssl:", 4) == 0 ||
  13453. strncmp(url, "tls:", 4) == 0 || strncmp(url, "tcps:", 5) == 0;
  13454. }
  13455. static struct url urlparse(const char *url) {
  13456. size_t i;
  13457. struct url u;
  13458. memset(&u, 0, sizeof(u));
  13459. for (i = 0; url[i] != '\0'; i++) {
  13460. if (url[i] == '/' && i > 0 && u.host == 0 && url[i - 1] == '/') {
  13461. u.host = i + 1;
  13462. u.port = 0;
  13463. } else if (url[i] == ']') {
  13464. u.port = 0; // IPv6 URLs, like http://[::1]/bar
  13465. } else if (url[i] == ':' && u.port == 0 && u.uri == 0) {
  13466. u.port = i + 1;
  13467. } else if (url[i] == '@' && u.user == 0 && u.pass == 0 && u.uri == 0) {
  13468. u.user = u.host;
  13469. u.pass = u.port;
  13470. u.host = i + 1;
  13471. u.port = 0;
  13472. } else if (url[i] == '/' && u.host && u.uri == 0) {
  13473. u.uri = i;
  13474. }
  13475. }
  13476. u.end = i;
  13477. #if 0
  13478. printf("[%s] %d %d %d %d %d\n", url, u.user, u.pass, u.host, u.port, u.uri);
  13479. #endif
  13480. return u;
  13481. }
  13482. struct mg_str mg_url_host(const char *url) {
  13483. struct url u = urlparse(url);
  13484. size_t n = u.port ? u.port - u.host - 1
  13485. : u.uri ? u.uri - u.host
  13486. : u.end - u.host;
  13487. struct mg_str s = mg_str_n(url + u.host, n);
  13488. return s;
  13489. }
  13490. const char *mg_url_uri(const char *url) {
  13491. struct url u = urlparse(url);
  13492. return u.uri ? url + u.uri : "/";
  13493. }
  13494. unsigned short mg_url_port(const char *url) {
  13495. struct url u = urlparse(url);
  13496. unsigned short port = 0;
  13497. if (strncmp(url, "http:", 5) == 0 || strncmp(url, "ws:", 3) == 0) port = 80;
  13498. if (strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0)
  13499. port = 443;
  13500. if (strncmp(url, "mqtt:", 5) == 0) port = 1883;
  13501. if (strncmp(url, "mqtts:", 6) == 0) port = 8883;
  13502. if (u.port) port = (unsigned short) atoi(url + u.port);
  13503. return port;
  13504. }
  13505. struct mg_str mg_url_user(const char *url) {
  13506. struct url u = urlparse(url);
  13507. struct mg_str s = mg_str("");
  13508. if (u.user && (u.pass || u.host)) {
  13509. size_t n = u.pass ? u.pass - u.user - 1 : u.host - u.user - 1;
  13510. s = mg_str_n(url + u.user, n);
  13511. }
  13512. return s;
  13513. }
  13514. struct mg_str mg_url_pass(const char *url) {
  13515. struct url u = urlparse(url);
  13516. struct mg_str s = mg_str_n("", 0UL);
  13517. if (u.pass && u.host) {
  13518. size_t n = u.host - u.pass - 1;
  13519. s = mg_str_n(url + u.pass, n);
  13520. }
  13521. return s;
  13522. }
  13523. #ifdef MG_ENABLE_LINES
  13524. #line 1 "src/util.c"
  13525. #endif
  13526. // Not using memset for zeroing memory, cause it can be dropped by compiler
  13527. // See https://github.com/cesanta/mongoose/pull/1265
  13528. void mg_bzero(volatile unsigned char *buf, size_t len) {
  13529. if (buf != NULL) {
  13530. while (len--) *buf++ = 0;
  13531. }
  13532. }
  13533. #if MG_ENABLE_CUSTOM_RANDOM
  13534. #else
  13535. void mg_random(void *buf, size_t len) {
  13536. bool done = false;
  13537. unsigned char *p = (unsigned char *) buf;
  13538. #if MG_ARCH == MG_ARCH_ESP32
  13539. while (len--) *p++ = (unsigned char) (esp_random() & 255);
  13540. done = true;
  13541. #elif MG_ARCH == MG_ARCH_WIN32
  13542. #elif MG_ARCH == MG_ARCH_UNIX
  13543. FILE *fp = fopen("/dev/urandom", "rb");
  13544. if (fp != NULL) {
  13545. if (fread(buf, 1, len, fp) == len) done = true;
  13546. fclose(fp);
  13547. }
  13548. #endif
  13549. // If everything above did not work, fallback to a pseudo random generator
  13550. while (!done && len--) *p++ = (unsigned char) (rand() & 255);
  13551. }
  13552. #endif
  13553. char *mg_random_str(char *buf, size_t len) {
  13554. size_t i;
  13555. mg_random(buf, len);
  13556. for (i = 0; i < len; i++) {
  13557. uint8_t c = ((uint8_t *) buf)[i] % 62U;
  13558. buf[i] = i == len - 1 ? (char) '\0' // 0-terminate last byte
  13559. : c < 26 ? (char) ('a' + c) // lowercase
  13560. : c < 52 ? (char) ('A' + c - 26) // uppercase
  13561. : (char) ('0' + c - 52); // numeric
  13562. }
  13563. return buf;
  13564. }
  13565. uint32_t mg_ntohl(uint32_t net) {
  13566. uint8_t data[4] = {0, 0, 0, 0};
  13567. memcpy(&data, &net, sizeof(data));
  13568. return (((uint32_t) data[3]) << 0) | (((uint32_t) data[2]) << 8) |
  13569. (((uint32_t) data[1]) << 16) | (((uint32_t) data[0]) << 24);
  13570. }
  13571. uint16_t mg_ntohs(uint16_t net) {
  13572. uint8_t data[2] = {0, 0};
  13573. memcpy(&data, &net, sizeof(data));
  13574. return (uint16_t) ((uint16_t) data[1] | (((uint16_t) data[0]) << 8));
  13575. }
  13576. uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len) {
  13577. static const uint32_t crclut[16] = {
  13578. // table for polynomial 0xEDB88320 (reflected)
  13579. 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
  13580. 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
  13581. 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
  13582. crc = ~crc;
  13583. while (len--) {
  13584. uint8_t b = *(uint8_t *) buf++;
  13585. crc = crclut[(crc ^ b) & 0x0F] ^ (crc >> 4);
  13586. crc = crclut[(crc ^ (b >> 4)) & 0x0F] ^ (crc >> 4);
  13587. }
  13588. return ~crc;
  13589. }
  13590. static int isbyte(int n) {
  13591. return n >= 0 && n <= 255;
  13592. }
  13593. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  13594. int n, a, b, c, d, slash = 32, len = 0;
  13595. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  13596. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  13597. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  13598. slash < 33) {
  13599. len = n;
  13600. *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) |
  13601. (uint32_t) d;
  13602. *mask = slash ? (uint32_t) (0xffffffffU << (32 - slash)) : (uint32_t) 0;
  13603. }
  13604. return len;
  13605. }
  13606. int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) {
  13607. struct mg_str entry;
  13608. int allowed = acl.len == 0 ? '+' : '-'; // If any ACL is set, deny by default
  13609. uint32_t remote_ip4;
  13610. if (remote_ip->is_ip6) {
  13611. return -1; // TODO(): handle IPv6 ACL and addresses
  13612. } else { // IPv4
  13613. memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4));
  13614. while (mg_span(acl, &entry, &acl, ',')) {
  13615. uint32_t net, mask;
  13616. if (entry.buf[0] != '+' && entry.buf[0] != '-') return -1;
  13617. if (parse_net(&entry.buf[1], &net, &mask) == 0) return -2;
  13618. if ((mg_ntohl(remote_ip4) & mask) == net) allowed = entry.buf[0];
  13619. }
  13620. }
  13621. return allowed == '+';
  13622. }
  13623. bool mg_path_is_sane(const struct mg_str path) {
  13624. const char *s = path.buf;
  13625. size_t n = path.len;
  13626. if (path.buf[0] == '.' && path.buf[1] == '.') return false; // Starts with ..
  13627. for (; s[0] != '\0' && n > 0; s++, n--) {
  13628. if ((s[0] == '/' || s[0] == '\\') && n >= 2) { // Subdir?
  13629. if (s[1] == '.' && s[2] == '.') return false; // Starts with ..
  13630. }
  13631. }
  13632. return true;
  13633. }
  13634. #if MG_ENABLE_CUSTOM_MILLIS
  13635. #else
  13636. uint64_t mg_millis(void) {
  13637. #if MG_ARCH == MG_ARCH_WIN32
  13638. return GetTickCount();
  13639. #elif MG_ARCH == MG_ARCH_RP2040
  13640. return time_us_64() / 1000;
  13641. #elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \
  13642. MG_ARCH == MG_ARCH_FREERTOS
  13643. return xTaskGetTickCount() * portTICK_PERIOD_MS;
  13644. #elif MG_ARCH == MG_ARCH_AZURERTOS
  13645. return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND);
  13646. #elif MG_ARCH == MG_ARCH_TIRTOS
  13647. return (uint64_t) Clock_getTicks();
  13648. #elif MG_ARCH == MG_ARCH_ZEPHYR
  13649. return (uint64_t) k_uptime_get();
  13650. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
  13651. return (uint64_t) rt_time_get();
  13652. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
  13653. return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq());
  13654. #elif MG_ARCH == MG_ARCH_RTTHREAD
  13655. return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND);
  13656. #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
  13657. // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
  13658. // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
  13659. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000;
  13660. #elif MG_ARCH == MG_ARCH_UNIX
  13661. struct timespec ts = {0, 0};
  13662. // See #1615 - prefer monotonic clock
  13663. #if defined(CLOCK_MONOTONIC_RAW)
  13664. // Raw hardware-based time that is not subject to NTP adjustment
  13665. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  13666. #elif defined(CLOCK_MONOTONIC)
  13667. // Affected by the incremental adjustments performed by adjtime and NTP
  13668. clock_gettime(CLOCK_MONOTONIC, &ts);
  13669. #else
  13670. // Affected by discontinuous jumps in the system time and by the incremental
  13671. // adjustments performed by adjtime and NTP
  13672. clock_gettime(CLOCK_REALTIME, &ts);
  13673. #endif
  13674. return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000);
  13675. #elif defined(ARDUINO)
  13676. return (uint64_t) millis();
  13677. #else
  13678. return (uint64_t) (time(NULL) * 1000);
  13679. #endif
  13680. }
  13681. #endif
  13682. #ifdef MG_ENABLE_LINES
  13683. #line 1 "src/ws.c"
  13684. #endif
  13685. struct ws_msg {
  13686. uint8_t flags;
  13687. size_t header_len;
  13688. size_t data_len;
  13689. };
  13690. size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
  13691. va_list *ap) {
  13692. size_t len = c->send.len;
  13693. size_t n = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  13694. mg_ws_wrap(c, c->send.len - len, op);
  13695. return n;
  13696. }
  13697. size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...) {
  13698. size_t len = 0;
  13699. va_list ap;
  13700. va_start(ap, fmt);
  13701. len = mg_ws_vprintf(c, op, fmt, &ap);
  13702. va_end(ap);
  13703. return len;
  13704. }
  13705. static void ws_handshake(struct mg_connection *c, const struct mg_str *wskey,
  13706. const struct mg_str *wsproto, const char *fmt,
  13707. va_list *ap) {
  13708. const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  13709. unsigned char sha[20], b64_sha[30];
  13710. mg_sha1_ctx sha_ctx;
  13711. mg_sha1_init(&sha_ctx);
  13712. mg_sha1_update(&sha_ctx, (unsigned char *) wskey->buf, wskey->len);
  13713. mg_sha1_update(&sha_ctx, (unsigned char *) magic, 36);
  13714. mg_sha1_final(sha, &sha_ctx);
  13715. mg_base64_encode(sha, sizeof(sha), (char *) b64_sha, sizeof(b64_sha));
  13716. mg_xprintf(mg_pfn_iobuf, &c->send,
  13717. "HTTP/1.1 101 Switching Protocols\r\n"
  13718. "Upgrade: websocket\r\n"
  13719. "Connection: Upgrade\r\n"
  13720. "Sec-WebSocket-Accept: %s\r\n",
  13721. b64_sha);
  13722. if (fmt != NULL) mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  13723. if (wsproto != NULL) {
  13724. mg_printf(c, "Sec-WebSocket-Protocol: %.*s\r\n", (int) wsproto->len,
  13725. wsproto->buf);
  13726. }
  13727. mg_send(c, "\r\n", 2);
  13728. }
  13729. static uint32_t be32(const uint8_t *p) {
  13730. return (((uint32_t) p[3]) << 0) | (((uint32_t) p[2]) << 8) |
  13731. (((uint32_t) p[1]) << 16) | (((uint32_t) p[0]) << 24);
  13732. }
  13733. static size_t ws_process(uint8_t *buf, size_t len, struct ws_msg *msg) {
  13734. size_t i, n = 0, mask_len = 0;
  13735. memset(msg, 0, sizeof(*msg));
  13736. if (len >= 2) {
  13737. n = buf[1] & 0x7f; // Frame length
  13738. mask_len = buf[1] & 128 ? 4 : 0; // last bit is a mask bit
  13739. msg->flags = buf[0];
  13740. if (n < 126 && len >= mask_len) {
  13741. msg->data_len = n;
  13742. msg->header_len = 2 + mask_len;
  13743. } else if (n == 126 && len >= 4 + mask_len) {
  13744. msg->header_len = 4 + mask_len;
  13745. msg->data_len = (((size_t) buf[2]) << 8) | buf[3];
  13746. } else if (len >= 10 + mask_len) {
  13747. msg->header_len = 10 + mask_len;
  13748. msg->data_len =
  13749. (size_t) (((uint64_t) be32(buf + 2) << 32) + be32(buf + 6));
  13750. }
  13751. }
  13752. // Sanity check, and integer overflow protection for the boundary check below
  13753. // data_len should not be larger than 1 Gb
  13754. if (msg->data_len > 1024 * 1024 * 1024) return 0;
  13755. if (msg->header_len + msg->data_len > len) return 0;
  13756. if (mask_len > 0) {
  13757. uint8_t *p = buf + msg->header_len, *m = p - mask_len;
  13758. for (i = 0; i < msg->data_len; i++) p[i] ^= m[i & 3];
  13759. }
  13760. return msg->header_len + msg->data_len;
  13761. }
  13762. static size_t mkhdr(size_t len, int op, bool is_client, uint8_t *buf) {
  13763. size_t n = 0;
  13764. buf[0] = (uint8_t) (op | 128);
  13765. if (len < 126) {
  13766. buf[1] = (unsigned char) len;
  13767. n = 2;
  13768. } else if (len < 65536) {
  13769. uint16_t tmp = mg_htons((uint16_t) len);
  13770. buf[1] = 126;
  13771. memcpy(&buf[2], &tmp, sizeof(tmp));
  13772. n = 4;
  13773. } else {
  13774. uint32_t tmp;
  13775. buf[1] = 127;
  13776. tmp = mg_htonl((uint32_t) (((uint64_t) len) >> 32));
  13777. memcpy(&buf[2], &tmp, sizeof(tmp));
  13778. tmp = mg_htonl((uint32_t) (len & 0xffffffffU));
  13779. memcpy(&buf[6], &tmp, sizeof(tmp));
  13780. n = 10;
  13781. }
  13782. if (is_client) {
  13783. buf[1] |= 1 << 7; // Set masking flag
  13784. mg_random(&buf[n], 4);
  13785. n += 4;
  13786. }
  13787. return n;
  13788. }
  13789. static void mg_ws_mask(struct mg_connection *c, size_t len) {
  13790. if (c->is_client && c->send.buf != NULL) {
  13791. size_t i;
  13792. uint8_t *p = c->send.buf + c->send.len - len, *mask = p - 4;
  13793. for (i = 0; i < len; i++) p[i] ^= mask[i & 3];
  13794. }
  13795. }
  13796. size_t mg_ws_send(struct mg_connection *c, const void *buf, size_t len,
  13797. int op) {
  13798. uint8_t header[14];
  13799. size_t header_len = mkhdr(len, op, c->is_client, header);
  13800. mg_send(c, header, header_len);
  13801. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  13802. mg_send(c, buf, len);
  13803. mg_ws_mask(c, len);
  13804. return header_len + len;
  13805. }
  13806. size_t mg_ws_send2(struct mg_connection *c, const void *buf, size_t len, int op, int max_tlen) {
  13807. uint8_t header[14];
  13808. if(!c) return -1;
  13809. if(max_tlen>0 && c->send.len>max_tlen) {
  13810. mg_iobuf_resize(&c->send, 0);
  13811. }
  13812. size_t header_len = mkhdr(len, op, c->is_client, header);
  13813. mg_send(c, header, header_len);
  13814. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  13815. mg_send(c, buf, len);
  13816. mg_ws_mask(c, len);
  13817. return header_len + len;
  13818. }
  13819. static bool mg_ws_client_handshake(struct mg_connection *c) {
  13820. int n = mg_http_get_request_len(c->recv.buf, c->recv.len);
  13821. if (n < 0) {
  13822. mg_error(c, "not http"); // Some just, not an HTTP request
  13823. } else if (n > 0) {
  13824. if (n < 15 || memcmp(c->recv.buf + 9, "101", 3) != 0) {
  13825. mg_error(c, "ws handshake error");
  13826. } else {
  13827. struct mg_http_message hm;
  13828. if (mg_http_parse((char *) c->recv.buf, c->recv.len, &hm)) {
  13829. c->is_websocket = 1;
  13830. mg_call(c, MG_EV_WS_OPEN, &hm);
  13831. } else {
  13832. mg_error(c, "ws handshake error");
  13833. }
  13834. }
  13835. mg_iobuf_del(&c->recv, 0, (size_t) n);
  13836. } else {
  13837. return true; // Request is not yet received, quit event handler
  13838. }
  13839. return false; // Continue event handler
  13840. }
  13841. static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
  13842. struct ws_msg msg;
  13843. size_t ofs = (size_t) c->pfn_data;
  13844. // assert(ofs < c->recv.len);
  13845. if (ev == MG_EV_READ) {
  13846. if (c->is_client && !c->is_websocket && mg_ws_client_handshake(c)) return;
  13847. while (ws_process(c->recv.buf + ofs, c->recv.len - ofs, &msg) > 0) {
  13848. char *s = (char *) c->recv.buf + ofs + msg.header_len;
  13849. struct mg_ws_message m = {{s, msg.data_len}, msg.flags};
  13850. size_t len = msg.header_len + msg.data_len;
  13851. uint8_t final = msg.flags & 128, op = msg.flags & 15;
  13852. // MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
  13853. // (int) m.data.len, (int) m.data.len, m.data.buf));
  13854. switch (op) {
  13855. case WEBSOCKET_OP_CONTINUE:
  13856. mg_call(c, MG_EV_WS_CTL, &m);
  13857. break;
  13858. case WEBSOCKET_OP_PING:
  13859. MG_DEBUG(("%s", "WS PONG"));
  13860. mg_ws_send(c, s, msg.data_len, WEBSOCKET_OP_PONG);
  13861. mg_call(c, MG_EV_WS_CTL, &m);
  13862. break;
  13863. case WEBSOCKET_OP_PONG:
  13864. mg_call(c, MG_EV_WS_CTL, &m);
  13865. break;
  13866. case WEBSOCKET_OP_TEXT:
  13867. case WEBSOCKET_OP_BINARY:
  13868. if (final) mg_call(c, MG_EV_WS_MSG, &m);
  13869. break;
  13870. case WEBSOCKET_OP_CLOSE:
  13871. MG_DEBUG(("%lu WS CLOSE", c->id));
  13872. mg_call(c, MG_EV_WS_CTL, &m);
  13873. // Echo the payload of the received CLOSE message back to the sender
  13874. mg_ws_send(c, m.data.buf, m.data.len, WEBSOCKET_OP_CLOSE);
  13875. c->is_draining = 1;
  13876. break;
  13877. default:
  13878. // Per RFC6455, close conn when an unknown op is recvd
  13879. mg_error(c, "unknown WS op %d", op);
  13880. break;
  13881. }
  13882. // Handle fragmented frames: strip header, keep in c->recv
  13883. if (final == 0 || op == 0) {
  13884. if (op) ofs++, len--, msg.header_len--; // First frame
  13885. mg_iobuf_del(&c->recv, ofs, msg.header_len); // Strip header
  13886. len -= msg.header_len;
  13887. ofs += len;
  13888. c->pfn_data = (void *) ofs;
  13889. // MG_INFO(("FRAG %d [%.*s]", (int) ofs, (int) ofs, c->recv.buf));
  13890. }
  13891. // Remove non-fragmented frame
  13892. if (final && op) mg_iobuf_del(&c->recv, ofs, len);
  13893. // Last chunk of the fragmented frame
  13894. if (final && !op) {
  13895. m.flags = c->recv.buf[0];
  13896. m.data = mg_str_n((char *) &c->recv.buf[1], (size_t) (ofs - 1));
  13897. mg_call(c, MG_EV_WS_MSG, &m);
  13898. mg_iobuf_del(&c->recv, 0, ofs);
  13899. ofs = 0;
  13900. c->pfn_data = NULL;
  13901. }
  13902. }
  13903. }
  13904. (void) ev_data;
  13905. }
  13906. struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
  13907. mg_event_handler_t fn, void *fn_data,
  13908. const char *fmt, ...) {
  13909. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  13910. if (c != NULL) {
  13911. char nonce[16], key[30];
  13912. struct mg_str host = mg_url_host(url);
  13913. mg_random(nonce, sizeof(nonce));
  13914. mg_base64_encode((unsigned char *) nonce, sizeof(nonce), key, sizeof(key));
  13915. mg_xprintf(mg_pfn_iobuf, &c->send,
  13916. "GET %s HTTP/1.1\r\n"
  13917. "Upgrade: websocket\r\n"
  13918. "Host: %.*s\r\n"
  13919. "Connection: Upgrade\r\n"
  13920. "Sec-WebSocket-Version: 13\r\n"
  13921. "Sec-WebSocket-Key: %s\r\n",
  13922. mg_url_uri(url), (int) host.len, host.buf, key);
  13923. if (fmt != NULL) {
  13924. va_list ap;
  13925. va_start(ap, fmt);
  13926. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  13927. va_end(ap);
  13928. }
  13929. mg_xprintf(mg_pfn_iobuf, &c->send, "\r\n");
  13930. c->pfn = mg_ws_cb;
  13931. c->pfn_data = NULL;
  13932. }
  13933. return c;
  13934. }
  13935. void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
  13936. const char *fmt, ...) {
  13937. struct mg_str *wskey = mg_http_get_header(hm, "Sec-WebSocket-Key");
  13938. c->pfn = mg_ws_cb;
  13939. c->pfn_data = NULL;
  13940. if (wskey == NULL) {
  13941. mg_http_reply(c, 426, "", "WS upgrade expected\n");
  13942. c->is_draining = 1;
  13943. } else {
  13944. struct mg_str *wsproto = mg_http_get_header(hm, "Sec-WebSocket-Protocol");
  13945. va_list ap;
  13946. va_start(ap, fmt);
  13947. ws_handshake(c, wskey, wsproto, fmt, &ap);
  13948. va_end(ap);
  13949. c->is_websocket = 1;
  13950. c->is_resp = 0;
  13951. mg_call(c, MG_EV_WS_OPEN, hm);
  13952. }
  13953. }
  13954. size_t mg_ws_wrap(struct mg_connection *c, size_t len, int op) {
  13955. uint8_t header[14], *p;
  13956. size_t header_len = mkhdr(len, op, c->is_client, header);
  13957. // NOTE: order of operations is important!
  13958. mg_iobuf_add(&c->send, c->send.len, NULL, header_len);
  13959. p = &c->send.buf[c->send.len - len]; // p points to data
  13960. memmove(p, p - header_len, len); // Shift data
  13961. memcpy(p - header_len, header, header_len); // Prepend header
  13962. mg_ws_mask(c, len); // Mask data
  13963. return c->send.len;
  13964. }
  13965. #ifdef MG_ENABLE_LINES
  13966. #line 1 "src/drivers/cmsis.c"
  13967. #endif
  13968. // https://arm-software.github.io/CMSIS_5/Driver/html/index.html
  13969. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
  13970. extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0;
  13971. extern ARM_DRIVER_ETH_PHY Driver_ETH_PHY0;
  13972. static struct mg_tcpip_if *s_ifp;
  13973. static void mac_cb(uint32_t);
  13974. static bool cmsis_init(struct mg_tcpip_if *);
  13975. static bool cmsis_up(struct mg_tcpip_if *);
  13976. static size_t cmsis_tx(const void *, size_t, struct mg_tcpip_if *);
  13977. static size_t cmsis_rx(void *, size_t, struct mg_tcpip_if *);
  13978. struct mg_tcpip_driver mg_tcpip_driver_cmsis = {cmsis_init, cmsis_tx, NULL,
  13979. cmsis_up};
  13980. static bool cmsis_init(struct mg_tcpip_if *ifp) {
  13981. ARM_ETH_MAC_ADDR addr;
  13982. s_ifp = ifp;
  13983. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  13984. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  13985. ARM_ETH_MAC_CAPABILITIES cap = mac->GetCapabilities();
  13986. if (mac->Initialize(mac_cb) != ARM_DRIVER_OK) return false;
  13987. if (phy->Initialize(mac->PHY_Read, mac->PHY_Write) != ARM_DRIVER_OK)
  13988. return false;
  13989. if (cap.event_rx_frame == 0) // polled mode driver
  13990. mg_tcpip_driver_cmsis.rx = cmsis_rx;
  13991. mac->PowerControl(ARM_POWER_FULL);
  13992. if (cap.mac_address) { // driver provides MAC address
  13993. mac->GetMacAddress(&addr);
  13994. memcpy(ifp->mac, &addr, sizeof(ifp->mac));
  13995. } else { // we provide MAC address
  13996. memcpy(&addr, ifp->mac, sizeof(addr));
  13997. mac->SetMacAddress(&addr);
  13998. }
  13999. phy->PowerControl(ARM_POWER_FULL);
  14000. phy->SetInterface(cap.media_interface);
  14001. phy->SetMode(ARM_ETH_PHY_AUTO_NEGOTIATE);
  14002. return true;
  14003. }
  14004. static size_t cmsis_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
  14005. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  14006. if (mac->SendFrame(buf, (uint32_t) len, 0) != ARM_DRIVER_OK) {
  14007. ifp->nerr++;
  14008. return 0;
  14009. }
  14010. ifp->nsent++;
  14011. return len;
  14012. }
  14013. static bool cmsis_up(struct mg_tcpip_if *ifp) {
  14014. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  14015. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  14016. bool up = (phy->GetLinkState() == ARM_ETH_LINK_UP) ? 1 : 0; // link state
  14017. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // just went up
  14018. ARM_ETH_LINK_INFO st = phy->GetLinkInfo();
  14019. mac->Control(ARM_ETH_MAC_CONFIGURE,
  14020. (st.speed << ARM_ETH_MAC_SPEED_Pos) |
  14021. (st.duplex << ARM_ETH_MAC_DUPLEX_Pos) |
  14022. ARM_ETH_MAC_ADDRESS_BROADCAST);
  14023. MG_DEBUG(("Link is %uM %s-duplex",
  14024. (st.speed == 2) ? 1000
  14025. : st.speed ? 100
  14026. : 10,
  14027. st.duplex ? "full" : "half"));
  14028. mac->Control(ARM_ETH_MAC_CONTROL_TX, 1);
  14029. mac->Control(ARM_ETH_MAC_CONTROL_RX, 1);
  14030. } else if ((ifp->state != MG_TCPIP_STATE_DOWN) && !up) { // just went down
  14031. mac->Control(ARM_ETH_MAC_FLUSH,
  14032. ARM_ETH_MAC_FLUSH_TX | ARM_ETH_MAC_FLUSH_RX);
  14033. mac->Control(ARM_ETH_MAC_CONTROL_TX, 0);
  14034. mac->Control(ARM_ETH_MAC_CONTROL_RX, 0);
  14035. }
  14036. return up;
  14037. }
  14038. static void mac_cb(uint32_t ev) {
  14039. if ((ev & ARM_ETH_MAC_EVENT_RX_FRAME) == 0) return;
  14040. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  14041. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  14042. if (len >= 60 && len <= 1518) { // proper frame
  14043. char *p;
  14044. if (mg_queue_book(&s_ifp->recv_queue, &p, len) >= len) { // have room
  14045. if ((len = mac->ReadFrame((uint8_t *) p, len)) > 0) { // copy succeeds
  14046. mg_queue_add(&s_ifp->recv_queue, len);
  14047. s_ifp->nrecv++;
  14048. }
  14049. return;
  14050. }
  14051. s_ifp->ndrop++;
  14052. }
  14053. mac->ReadFrame(NULL, 0); // otherwise, discard
  14054. }
  14055. static size_t cmsis_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  14056. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  14057. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  14058. if (len >= 60 && len <= 1518 &&
  14059. ((len = mac->ReadFrame(buf, (uint32_t) buflen)) > 0))
  14060. return len;
  14061. if (len > 0) mac->ReadFrame(NULL, 0); // discard bad frames
  14062. (void) ifp;
  14063. return 0;
  14064. }
  14065. #endif
  14066. #ifdef MG_ENABLE_LINES
  14067. #line 1 "src/drivers/imxrt.c"
  14068. #endif
  14069. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_IMXRT) && MG_ENABLE_DRIVER_IMXRT
  14070. struct imxrt_enet {
  14071. volatile uint32_t RESERVED0, EIR, EIMR, RESERVED1, RDAR, TDAR, RESERVED2[3],
  14072. ECR, RESERVED3[6], MMFR, MSCR, RESERVED4[7], MIBC, RESERVED5[7], RCR,
  14073. RESERVED6[15], TCR, RESERVED7[7], PALR, PAUR, OPD, TXIC0, TXIC1, TXIC2,
  14074. RESERVED8, RXIC0, RXIC1, RXIC2, RESERVED9[3], IAUR, IALR, GAUR, GALR,
  14075. RESERVED10[7], TFWR, RESERVED11[14], RDSR, TDSR, MRBR[2], RSFL, RSEM,
  14076. RAEM, RAFL, TSEM, TAEM, TAFL, TIPG, FTRL, RESERVED12[3], TACC, RACC,
  14077. RESERVED13[15], RMON_T_PACKETS, RMON_T_BC_PKT, RMON_T_MC_PKT,
  14078. RMON_T_CRC_ALIGN, RMON_T_UNDERSIZE, RMON_T_OVERSIZE, RMON_T_FRAG,
  14079. RMON_T_JAB, RMON_T_COL, RMON_T_P64, RMON_T_P65TO127, RMON_T_P128TO255,
  14080. RMON_T_P256TO511, RMON_T_P512TO1023, RMON_T_P1024TO2048, RMON_T_GTE2048,
  14081. RMON_T_OCTETS, IEEE_T_DROP, IEEE_T_FRAME_OK, IEEE_T_1COL, IEEE_T_MCOL,
  14082. IEEE_T_DEF, IEEE_T_LCOL, IEEE_T_EXCOL, IEEE_T_MACERR, IEEE_T_CSERR,
  14083. IEEE_T_SQE, IEEE_T_FDXFC, IEEE_T_OCTETS_OK, RESERVED14[3], RMON_R_PACKETS,
  14084. RMON_R_BC_PKT, RMON_R_MC_PKT, RMON_R_CRC_ALIGN, RMON_R_UNDERSIZE,
  14085. RMON_R_OVERSIZE, RMON_R_FRAG, RMON_R_JAB, RESERVED15, RMON_R_P64,
  14086. RMON_R_P65TO127, RMON_R_P128TO255, RMON_R_P256TO511, RMON_R_P512TO1023,
  14087. RMON_R_P1024TO2047, RMON_R_GTE2048, RMON_R_OCTETS, IEEE_R_DROP,
  14088. IEEE_R_FRAME_OK, IEEE_R_CRC, IEEE_R_ALIGN, IEEE_R_MACERR, IEEE_R_FDXFC,
  14089. IEEE_R_OCTETS_OK, RESERVED16[71], ATCR, ATVR, ATOFF, ATPER, ATCOR, ATINC,
  14090. ATSTMP, RESERVED17[122], TGSR, TCSR0, TCCR0, TCSR1, TCCR1, TCSR2, TCCR2,
  14091. TCSR3;
  14092. };
  14093. #undef ENET
  14094. #if defined(MG_DRIVER_IMXRT_RT11) && MG_DRIVER_IMXRT_RT11
  14095. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x40424000U)
  14096. #define ETH_DESC_CNT 5 // Descriptors count
  14097. #else
  14098. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x402D8000U)
  14099. #define ETH_DESC_CNT 4 // Descriptors count
  14100. #endif
  14101. #define ETH_PKT_SIZE 1536 // Max frame size, 64-bit aligned
  14102. struct enet_desc {
  14103. uint16_t length; // Data length
  14104. uint16_t control; // Control and status
  14105. uint32_t *buffer; // Data ptr
  14106. };
  14107. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  14108. #define MG_64BYTE_ALIGNED __attribute__((aligned((64U))))
  14109. // Descriptors: in non-cached area (TODO(scaprile)), (37.5.1.22.2 37.5.1.23.2)
  14110. // Buffers: 64-byte aligned (37.3.14)
  14111. static volatile struct enet_desc s_rxdesc[ETH_DESC_CNT] MG_64BYTE_ALIGNED;
  14112. static volatile struct enet_desc s_txdesc[ETH_DESC_CNT] MG_64BYTE_ALIGNED;
  14113. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BYTE_ALIGNED;
  14114. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BYTE_ALIGNED;
  14115. static struct mg_tcpip_if *s_ifp; // MIP interface
  14116. static uint16_t enet_read_phy(uint8_t addr, uint8_t reg) {
  14117. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  14118. ENET->MMFR = (1 << 30) | (2 << 28) | (addr << 23) | (reg << 18) | (2 << 16);
  14119. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  14120. return ENET->MMFR & 0xffff;
  14121. }
  14122. static void enet_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14123. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  14124. ENET->MMFR =
  14125. (1 << 30) | (1 << 28) | (addr << 23) | (reg << 18) | (2 << 16) | val;
  14126. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  14127. }
  14128. // MDC clock is generated from IPS Bus clock (ipg_clk); as per 802.3,
  14129. // it must not exceed 2.5MHz
  14130. // The PHY receives the PLL6-generated 50MHz clock
  14131. static bool mg_tcpip_driver_imxrt_init(struct mg_tcpip_if *ifp) {
  14132. struct mg_tcpip_driver_imxrt_data *d =
  14133. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  14134. s_ifp = ifp;
  14135. // Init RX descriptors
  14136. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14137. s_rxdesc[i].control = MG_BIT(15); // Own (E)
  14138. s_rxdesc[i].buffer = (uint32_t *) s_rxbuf[i]; // Point to data buffer
  14139. }
  14140. s_rxdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  14141. // Init TX descriptors
  14142. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14143. // s_txdesc[i].control = MG_BIT(10); // Own (TC)
  14144. s_txdesc[i].buffer = (uint32_t *) s_txbuf[i];
  14145. }
  14146. s_txdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  14147. ENET->ECR = MG_BIT(0); // Software reset, disable
  14148. while ((ENET->ECR & MG_BIT(0))) (void) 0; // Wait until done
  14149. // Set MDC clock divider. If user told us the value, use it.
  14150. // TODO(): Otherwise, guess (currently assuming max freq)
  14151. int cr = (d == NULL || d->mdc_cr < 0) ? 24 : d->mdc_cr;
  14152. ENET->MSCR = (1 << 8) | ((cr & 0x3f) << 1); // HOLDTIME 2 clks
  14153. struct mg_phy phy = {enet_read_phy, enet_write_phy};
  14154. mg_phy_init(&phy, d->phy_addr, MG_PHY_LEDS_ACTIVE_HIGH); // MAC clocks PHY
  14155. // Select RMII mode, 100M, keep CRC, set max rx length, disable loop
  14156. ENET->RCR = (1518 << 16) | MG_BIT(8) | MG_BIT(2);
  14157. // ENET->RCR |= MG_BIT(3); // Receive all
  14158. ENET->TCR = MG_BIT(2); // Full-duplex
  14159. ENET->RDSR = (uint32_t) (uintptr_t) s_rxdesc;
  14160. ENET->TDSR = (uint32_t) (uintptr_t) s_txdesc;
  14161. ENET->MRBR[0] = ETH_PKT_SIZE; // Same size for RX/TX buffers
  14162. // MAC address filtering (bytes in reversed order)
  14163. ENET->PAUR = ((uint32_t) ifp->mac[4] << 24U) | (uint32_t) ifp->mac[5] << 16U;
  14164. ENET->PALR = (uint32_t) (ifp->mac[0] << 24U) |
  14165. ((uint32_t) ifp->mac[1] << 16U) |
  14166. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  14167. ENET->ECR = MG_BIT(8) | MG_BIT(1); // Little-endian CPU, Enable
  14168. ENET->EIMR = MG_BIT(25); // Set interrupt mask
  14169. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  14170. ENET->TDAR = MG_BIT(24); // Transmit Descriptors have changed
  14171. // ENET->OPD = 0x10014;
  14172. return true;
  14173. }
  14174. // Transmit frame
  14175. static size_t mg_tcpip_driver_imxrt_tx(const void *buf, size_t len,
  14176. struct mg_tcpip_if *ifp) {
  14177. static int s_txno; // Current descriptor index
  14178. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  14179. MG_ERROR(("Frame too big, %ld", (long) len));
  14180. len = (size_t) -1; // fail
  14181. } else if ((s_txdesc[s_txno].control & MG_BIT(15))) {
  14182. ifp->nerr++;
  14183. MG_ERROR(("No descriptors available"));
  14184. len = 0; // retry later
  14185. } else {
  14186. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14187. s_txdesc[s_txno].length = (uint16_t) len; // Set data len
  14188. // Table 37-34, R, L, TC (Ready, last, transmit CRC after frame
  14189. s_txdesc[s_txno].control |=
  14190. (uint16_t) (MG_BIT(15) | MG_BIT(11) | MG_BIT(10));
  14191. ENET->TDAR = MG_BIT(24); // Descriptor ring updated
  14192. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14193. }
  14194. (void) ifp;
  14195. return len;
  14196. }
  14197. static bool mg_tcpip_driver_imxrt_up(struct mg_tcpip_if *ifp) {
  14198. struct mg_tcpip_driver_imxrt_data *d =
  14199. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  14200. uint8_t speed = MG_PHY_SPEED_10M;
  14201. bool up = false, full_duplex = false;
  14202. struct mg_phy phy = {enet_read_phy, enet_write_phy};
  14203. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  14204. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14205. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14206. // if(link is slow or half) set flags otherwise
  14207. // reg = tmp
  14208. uint32_t tcr = ENET->TCR | MG_BIT(2); // Full-duplex
  14209. uint32_t rcr = ENET->RCR & ~MG_BIT(9); // 100M
  14210. if (speed == MG_PHY_SPEED_10M) rcr |= MG_BIT(9); // 10M
  14211. if (full_duplex == false) tcr &= ~MG_BIT(2); // Half-duplex
  14212. ENET->TCR = tcr; // IRQ handler does not fiddle with these registers
  14213. ENET->RCR = rcr;
  14214. MG_DEBUG(("Link is %uM %s-duplex", rcr & MG_BIT(9) ? 10 : 100,
  14215. tcr & MG_BIT(2) ? "full" : "half"));
  14216. }
  14217. return up;
  14218. }
  14219. void ENET_IRQHandler(void);
  14220. static uint32_t s_rxno;
  14221. void ENET_IRQHandler(void) {
  14222. ENET->EIR = MG_BIT(25); // Ack IRQ
  14223. // Frame received, loop
  14224. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14225. uint32_t r = s_rxdesc[s_rxno].control;
  14226. if (r & MG_BIT(15)) break; // exit when done
  14227. // skip partial/errored frames (Table 37-32)
  14228. if ((r & MG_BIT(11)) &&
  14229. !(r & (MG_BIT(5) | MG_BIT(4) | MG_BIT(2) | MG_BIT(1) | MG_BIT(0)))) {
  14230. size_t len = s_rxdesc[s_rxno].length;
  14231. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  14232. }
  14233. s_rxdesc[s_rxno].control |= MG_BIT(15);
  14234. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14235. }
  14236. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  14237. // If b24 == 0, descriptors were exhausted and probably frames were dropped
  14238. }
  14239. struct mg_tcpip_driver mg_tcpip_driver_imxrt = {mg_tcpip_driver_imxrt_init,
  14240. mg_tcpip_driver_imxrt_tx, NULL,
  14241. mg_tcpip_driver_imxrt_up};
  14242. #endif
  14243. #ifdef MG_ENABLE_LINES
  14244. #line 1 "src/drivers/phy.c"
  14245. #endif
  14246. enum { // ID1 ID2
  14247. MG_PHY_KSZ8x = 0x22, // 0022 1561 - KSZ8081RNB
  14248. MG_PHY_DP83x = 0x2000, // 2000 a140 - TI DP83825I
  14249. MG_PHY_DP83867 = 0xa231, // 2000 a231 - TI DP83867I
  14250. MG_PHY_LAN87x = 0x7, // 0007 c0fx - LAN8720
  14251. MG_PHY_RTL8201 = 0x1C // 001c c816 - RTL8201
  14252. };
  14253. enum {
  14254. MG_PHY_REG_BCR = 0,
  14255. MG_PHY_REG_BSR = 1,
  14256. MG_PHY_REG_ID1 = 2,
  14257. MG_PHY_REG_ID2 = 3,
  14258. MG_PHY_DP83x_REG_PHYSTS = 16,
  14259. MG_PHY_DP83867_REG_PHYSTS = 17,
  14260. MG_PHY_DP83x_REG_RCSR = 23,
  14261. MG_PHY_DP83x_REG_LEDCR = 24,
  14262. MG_PHY_KSZ8x_REG_PC1R = 30,
  14263. MG_PHY_KSZ8x_REG_PC2R = 31,
  14264. MG_PHY_LAN87x_REG_SCSR = 31,
  14265. MG_PHY_RTL8201_REG_RMSR = 16, // in page 7
  14266. MG_PHY_RTL8201_REG_PAGESEL = 31
  14267. };
  14268. static const char *mg_phy_id_to_str(uint16_t id1, uint16_t id2) {
  14269. switch (id1) {
  14270. case MG_PHY_DP83x:
  14271. switch (id2) {
  14272. case MG_PHY_DP83867:
  14273. return "DP83867";
  14274. default:
  14275. return "DP83x";
  14276. }
  14277. case MG_PHY_KSZ8x:
  14278. return "KSZ8x";
  14279. case MG_PHY_LAN87x:
  14280. return "LAN87x";
  14281. case MG_PHY_RTL8201:
  14282. return "RTL8201";
  14283. default:
  14284. return "unknown";
  14285. }
  14286. (void) id2;
  14287. }
  14288. void mg_phy_init(struct mg_phy *phy, uint8_t phy_addr, uint8_t config) {
  14289. uint16_t id1, id2;
  14290. phy->write_reg(phy_addr, MG_PHY_REG_BCR, MG_BIT(15)); // Reset PHY
  14291. while (phy->read_reg(phy_addr, MG_PHY_REG_BCR) & MG_BIT(15)) (void) 0;
  14292. // MG_PHY_REG_BCR[12]: Autonegotiation is default unless hw says otherwise
  14293. id1 = phy->read_reg(phy_addr, MG_PHY_REG_ID1);
  14294. id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
  14295. MG_INFO(("PHY ID: %#04x %#04x (%s)", id1, id2, mg_phy_id_to_str(id1, id2)));
  14296. if (id1 == MG_PHY_DP83x && id2 == MG_PHY_DP83867) {
  14297. phy->write_reg(phy_addr, 0x0d, 0x1f); // write 0x10d to IO_MUX_CFG (0x0170)
  14298. phy->write_reg(phy_addr, 0x0e, 0x170);
  14299. phy->write_reg(phy_addr, 0x0d, 0x401f);
  14300. phy->write_reg(phy_addr, 0x0e, 0x10d);
  14301. }
  14302. if (config & MG_PHY_CLOCKS_MAC) {
  14303. // Use PHY crystal oscillator (preserve defaults)
  14304. // nothing to do
  14305. } else { // MAC clocks PHY, PHY has no xtal
  14306. // Enable 50 MHz external ref clock at XI (preserve defaults)
  14307. if (id1 == MG_PHY_DP83x && id2 != MG_PHY_DP83867) {
  14308. phy->write_reg(phy_addr, MG_PHY_DP83x_REG_RCSR, MG_BIT(7) | MG_BIT(0));
  14309. } else if (id1 == MG_PHY_KSZ8x) {
  14310. phy->write_reg(phy_addr, MG_PHY_KSZ8x_REG_PC2R,
  14311. MG_BIT(15) | MG_BIT(8) | MG_BIT(7));
  14312. } else if (id1 == MG_PHY_LAN87x) {
  14313. // nothing to do
  14314. } else if (id1 == MG_PHY_RTL8201) {
  14315. // assume PHY has been hardware strapped properly
  14316. #if 0
  14317. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_PAGESEL, 7); // Select page 7
  14318. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_RMSR, 0x1ffa);
  14319. phy->write_reg(phy_addr, MG_PHY_RTL8201_REG_PAGESEL, 0); // Select page 0
  14320. #endif
  14321. }
  14322. }
  14323. if (config & MG_PHY_LEDS_ACTIVE_HIGH && id1 == MG_PHY_DP83x) {
  14324. phy->write_reg(phy_addr, MG_PHY_DP83x_REG_LEDCR,
  14325. MG_BIT(9) | MG_BIT(7)); // LED status, active high
  14326. } // Other PHYs do not support this feature
  14327. }
  14328. bool mg_phy_up(struct mg_phy *phy, uint8_t phy_addr, bool *full_duplex,
  14329. uint8_t *speed) {
  14330. bool up = false;
  14331. uint16_t bsr = phy->read_reg(phy_addr, MG_PHY_REG_BSR);
  14332. if ((bsr & MG_BIT(5)) && !(bsr & MG_BIT(2))) // some PHYs latch down events
  14333. bsr = phy->read_reg(phy_addr, MG_PHY_REG_BSR); // read again
  14334. up = bsr & MG_BIT(2);
  14335. if (up && full_duplex != NULL && speed != NULL) {
  14336. uint16_t id1 = phy->read_reg(phy_addr, MG_PHY_REG_ID1);
  14337. if (id1 == MG_PHY_DP83x) {
  14338. uint16_t id2 = phy->read_reg(phy_addr, MG_PHY_REG_ID2);
  14339. if (id2 == MG_PHY_DP83867) {
  14340. uint16_t physts = phy->read_reg(phy_addr, MG_PHY_DP83867_REG_PHYSTS);
  14341. *full_duplex = physts & MG_BIT(13);
  14342. *speed = (physts & MG_BIT(15)) ? MG_PHY_SPEED_1000M
  14343. : (physts & MG_BIT(14)) ? MG_PHY_SPEED_100M
  14344. : MG_PHY_SPEED_10M;
  14345. } else {
  14346. uint16_t physts = phy->read_reg(phy_addr, MG_PHY_DP83x_REG_PHYSTS);
  14347. *full_duplex = physts & MG_BIT(2);
  14348. *speed = (physts & MG_BIT(1)) ? MG_PHY_SPEED_10M : MG_PHY_SPEED_100M;
  14349. }
  14350. } else if (id1 == MG_PHY_KSZ8x) {
  14351. uint16_t pc1r = phy->read_reg(phy_addr, MG_PHY_KSZ8x_REG_PC1R);
  14352. *full_duplex = pc1r & MG_BIT(2);
  14353. *speed = (pc1r & 3) == 1 ? MG_PHY_SPEED_10M : MG_PHY_SPEED_100M;
  14354. } else if (id1 == MG_PHY_LAN87x) {
  14355. uint16_t scsr = phy->read_reg(phy_addr, MG_PHY_LAN87x_REG_SCSR);
  14356. *full_duplex = scsr & MG_BIT(4);
  14357. *speed = (scsr & MG_BIT(3)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
  14358. } else if (id1 == MG_PHY_RTL8201) {
  14359. uint16_t bcr = phy->read_reg(phy_addr, MG_PHY_REG_BCR);
  14360. *full_duplex = bcr & MG_BIT(8);
  14361. *speed = (bcr & MG_BIT(13)) ? MG_PHY_SPEED_100M : MG_PHY_SPEED_10M;
  14362. }
  14363. }
  14364. return up;
  14365. }
  14366. #ifdef MG_ENABLE_LINES
  14367. #line 1 "src/drivers/ra.c"
  14368. #endif
  14369. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RA) && MG_ENABLE_DRIVER_RA
  14370. struct ra_etherc {
  14371. volatile uint32_t ECMR, RESERVED, RFLR, RESERVED1, ECSR, RESERVED2, ECSIPR,
  14372. RESERVED3, PIR, RESERVED4, PSR, RESERVED5[5], RDMLR, RESERVED6[3], IPGR,
  14373. APR, MPR, RESERVED7, RFCF, TPAUSER, TPAUSECR, BCFRR, RESERVED8[20], MAHR,
  14374. RESERVED9, MALR, RESERVED10, TROCR, CDCR, LCCR, CNDCR, RESERVED11, CEFCR,
  14375. FRECR, TSFRCR, TLFRCR, RFCR, MAFCR;
  14376. };
  14377. struct ra_edmac {
  14378. volatile uint32_t EDMR, RESERVED, EDTRR, RESERVED1, EDRRR, RESERVED2, TDLAR,
  14379. RESERVED3, RDLAR, RESERVED4, EESR, RESERVED5, EESIPR, RESERVED6, TRSCER,
  14380. RESERVED7, RMFCR, RESERVED8, TFTR, RESERVED9, FDR, RESERVED10, RMCR,
  14381. RESERVED11[2], TFUCR, RFOCR, IOSR, FCFTR, RESERVED12, RPADIR, TRIMD,
  14382. RESERVED13[18], RBWAR, RDFAR, RESERVED14, TBRAR, TDFAR;
  14383. };
  14384. #undef ETHERC
  14385. #define ETHERC ((struct ra_etherc *) (uintptr_t) 0x40114100U)
  14386. #undef EDMAC
  14387. #define EDMAC ((struct ra_edmac *) (uintptr_t) 0x40114000U)
  14388. #undef RASYSC
  14389. #define RASYSC ((uint32_t *) (uintptr_t) 0x4001E000U)
  14390. #undef ICU_IELSR
  14391. #define ICU_IELSR ((uint32_t *) (uintptr_t) 0x40006300U)
  14392. #define ETH_PKT_SIZE 1536 // Max frame size, multiple of 32
  14393. #define ETH_DESC_CNT 4 // Descriptors count
  14394. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  14395. #define MG_16BYTE_ALIGNED __attribute__((aligned((16U))))
  14396. #define MG_32BYTE_ALIGNED __attribute__((aligned((32U))))
  14397. // Descriptors: 16-byte aligned
  14398. // Buffers: 32-byte aligned (27.3.1)
  14399. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][4] MG_16BYTE_ALIGNED;
  14400. static volatile uint32_t s_txdesc[ETH_DESC_CNT][4] MG_16BYTE_ALIGNED;
  14401. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_32BYTE_ALIGNED;
  14402. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_32BYTE_ALIGNED;
  14403. static struct mg_tcpip_if *s_ifp; // MIP interface
  14404. // fastest is 3 cycles (SUB + BNE) on a 3-stage pipeline or equivalent
  14405. static inline void raspin(volatile uint32_t count) {
  14406. while (count--) (void) 0;
  14407. }
  14408. // count to get the 200ns SMC semi-cycle period (2.5MHz) calling raspin():
  14409. // SYS_FREQUENCY * 200ns / 3 = SYS_FREQUENCY / 15000000
  14410. static uint32_t s_smispin;
  14411. // Bit-banged SMI
  14412. static void smi_preamble(void) {
  14413. unsigned int i = 32;
  14414. uint32_t pir = MG_BIT(1) | MG_BIT(2); // write, mdio = 1, mdc = 0
  14415. ETHERC->PIR = pir;
  14416. while (i--) {
  14417. pir &= ~MG_BIT(0); // mdc = 0
  14418. ETHERC->PIR = pir;
  14419. raspin(s_smispin);
  14420. pir |= MG_BIT(0); // mdc = 1
  14421. ETHERC->PIR = pir;
  14422. raspin(s_smispin);
  14423. }
  14424. }
  14425. static void smi_wr(uint16_t header, uint16_t data) {
  14426. uint32_t word = (header << 16) | data;
  14427. smi_preamble();
  14428. unsigned int i = 32;
  14429. while (i--) {
  14430. uint32_t pir = MG_BIT(1) |
  14431. (word & 0x80000000 ? MG_BIT(2) : 0); // write, mdc = 0, data
  14432. ETHERC->PIR = pir;
  14433. raspin(s_smispin);
  14434. pir |= MG_BIT(0); // mdc = 1
  14435. ETHERC->PIR = pir;
  14436. raspin(s_smispin);
  14437. word <<= 1;
  14438. }
  14439. }
  14440. static uint16_t smi_rd(uint16_t header) {
  14441. smi_preamble();
  14442. unsigned int i = 16; // 2 LSb as turnaround
  14443. uint32_t pir;
  14444. while (i--) {
  14445. pir = (i > 1 ? MG_BIT(1) : 0) |
  14446. (header & 0x8000
  14447. ? MG_BIT(2)
  14448. : 0); // mdc = 0, header, set read direction at turnaround
  14449. ETHERC->PIR = pir;
  14450. raspin(s_smispin);
  14451. pir |= MG_BIT(0); // mdc = 1
  14452. ETHERC->PIR = pir;
  14453. raspin(s_smispin);
  14454. header <<= 1;
  14455. }
  14456. i = 16;
  14457. uint16_t data = 0;
  14458. while (i--) {
  14459. data <<= 1;
  14460. pir = 0; // read, mdc = 0
  14461. ETHERC->PIR = pir;
  14462. raspin(s_smispin / 2); // 1/4 clock period, 300ns max access time
  14463. data |= (uint16_t)(ETHERC->PIR & MG_BIT(3) ? 1 : 0); // read mdio
  14464. raspin(s_smispin / 2); // 1/4 clock period
  14465. pir |= MG_BIT(0); // mdc = 1
  14466. ETHERC->PIR = pir;
  14467. raspin(s_smispin);
  14468. }
  14469. return data;
  14470. }
  14471. static uint16_t raeth_read_phy(uint8_t addr, uint8_t reg) {
  14472. return smi_rd((uint16_t)((1 << 14) | (2 << 12) | (addr << 7) | (reg << 2) | (2 << 0)));
  14473. }
  14474. static void raeth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14475. smi_wr((uint16_t)((1 << 14) | (1 << 12) | (addr << 7) | (reg << 2) | (2 << 0)), val);
  14476. }
  14477. // MDC clock is generated manually; as per 802.3, it must not exceed 2.5MHz
  14478. static bool mg_tcpip_driver_ra_init(struct mg_tcpip_if *ifp) {
  14479. struct mg_tcpip_driver_ra_data *d =
  14480. (struct mg_tcpip_driver_ra_data *) ifp->driver_data;
  14481. s_ifp = ifp;
  14482. // Init SMI clock timing. If user told us the clock value, use it.
  14483. // TODO(): Otherwise, guess
  14484. s_smispin = d->clock / 15000000;
  14485. // Init RX descriptors
  14486. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14487. s_rxdesc[i][0] = MG_BIT(31); // RACT
  14488. s_rxdesc[i][1] = ETH_PKT_SIZE << 16; // RBL
  14489. s_rxdesc[i][2] = (uint32_t) s_rxbuf[i]; // Point to data buffer
  14490. }
  14491. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(30); // Wrap last descriptor
  14492. // Init TX descriptors
  14493. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14494. // TACT = 0
  14495. s_txdesc[i][2] = (uint32_t) s_txbuf[i];
  14496. }
  14497. s_txdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(30); // Wrap last descriptor
  14498. EDMAC->EDMR = MG_BIT(0); // Software reset, wait 64 PCLKA clocks (27.2.1)
  14499. uint32_t sckdivcr = RASYSC[8]; // get divisors from SCKDIVCR (8.2.2)
  14500. uint32_t ick = 1 << ((sckdivcr >> 24) & 7); // sys_clock div
  14501. uint32_t pcka = 1 << ((sckdivcr >> 12) & 7); // pclka div
  14502. raspin((64U * pcka) / (3U * ick));
  14503. EDMAC->EDMR = MG_BIT(6); // Initialize, little-endian (27.2.1)
  14504. MG_DEBUG(("PHY addr: %d, smispin: %d", d->phy_addr, s_smispin));
  14505. struct mg_phy phy = {raeth_read_phy, raeth_write_phy};
  14506. mg_phy_init(&phy, d->phy_addr, 0); // MAC clocks PHY
  14507. // Select RMII mode,
  14508. ETHERC->ECMR = MG_BIT(2) | MG_BIT(1); // 100M, Full-duplex, CRC
  14509. // ETHERC->ECMR |= MG_BIT(0); // Receive all
  14510. ETHERC->RFLR = 1518; // Set max rx length
  14511. EDMAC->RDLAR = (uint32_t) (uintptr_t) s_rxdesc;
  14512. EDMAC->TDLAR = (uint32_t) (uintptr_t) s_txdesc;
  14513. // MAC address filtering (bytes in reversed order)
  14514. ETHERC->MAHR = (uint32_t) (ifp->mac[0] << 24U) |
  14515. ((uint32_t) ifp->mac[1] << 16U) |
  14516. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  14517. ETHERC->MALR = ((uint32_t) ifp->mac[4] << 8U) | ifp->mac[5];
  14518. EDMAC->TFTR = 0; // Store and forward (27.2.10)
  14519. EDMAC->FDR = 0x070f; // (27.2.11)
  14520. EDMAC->RMCR = MG_BIT(0); // (27.2.12)
  14521. ETHERC->ECMR |= MG_BIT(6) | MG_BIT(5); // TE RE
  14522. EDMAC->EESIPR = MG_BIT(18); // Enable Rx IRQ
  14523. EDMAC->EDRRR = MG_BIT(0); // Receive Descriptors have changed
  14524. EDMAC->EDTRR = MG_BIT(0); // Transmit Descriptors have changed
  14525. return true;
  14526. }
  14527. // Transmit frame
  14528. static size_t mg_tcpip_driver_ra_tx(const void *buf, size_t len,
  14529. struct mg_tcpip_if *ifp) {
  14530. static int s_txno; // Current descriptor index
  14531. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  14532. MG_ERROR(("Frame too big, %ld", (long) len));
  14533. len = (size_t) -1; // fail
  14534. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  14535. ifp->nerr++;
  14536. MG_ERROR(("No descriptors available"));
  14537. len = 0; // retry later
  14538. } else {
  14539. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14540. s_txdesc[s_txno][1] = len << 16; // Set data len
  14541. s_txdesc[s_txno][0] |= MG_BIT(31) | 3 << 28; // (27.3.1.1) mark valid
  14542. EDMAC->EDTRR = MG_BIT(0); // Transmit request
  14543. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14544. }
  14545. return len;
  14546. }
  14547. static bool mg_tcpip_driver_ra_up(struct mg_tcpip_if *ifp) {
  14548. struct mg_tcpip_driver_ra_data *d =
  14549. (struct mg_tcpip_driver_ra_data *) ifp->driver_data;
  14550. uint8_t speed = MG_PHY_SPEED_10M;
  14551. bool up = false, full_duplex = false;
  14552. struct mg_phy phy = {raeth_read_phy, raeth_write_phy};
  14553. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  14554. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14555. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14556. // if(link is slow or half) set flags otherwise
  14557. // reg = tmp
  14558. uint32_t ecmr = ETHERC->ECMR | MG_BIT(2) | MG_BIT(1); // 100M Full-duplex
  14559. if (speed == MG_PHY_SPEED_10M) ecmr &= ~MG_BIT(2); // 10M
  14560. if (full_duplex == false) ecmr &= ~MG_BIT(1); // Half-duplex
  14561. ETHERC->ECMR = ecmr; // IRQ handler does not fiddle with these registers
  14562. MG_DEBUG(("Link is %uM %s-duplex", ecmr & MG_BIT(2) ? 100 : 10,
  14563. ecmr & MG_BIT(1) ? "full" : "half"));
  14564. }
  14565. return up;
  14566. }
  14567. void EDMAC_IRQHandler(void);
  14568. static uint32_t s_rxno;
  14569. void EDMAC_IRQHandler(void) {
  14570. struct mg_tcpip_driver_ra_data *d =
  14571. (struct mg_tcpip_driver_ra_data *) s_ifp->driver_data;
  14572. EDMAC->EESR = MG_BIT(18); // Ack IRQ in EDMAC 1st
  14573. ICU_IELSR[d->irqno] &= ~MG_BIT(16); // Ack IRQ in ICU last
  14574. // Frame received, loop
  14575. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14576. uint32_t r = s_rxdesc[s_rxno][0];
  14577. if (r & MG_BIT(31)) break; // exit when done
  14578. // skip partial/errored frames (27.3.1.2)
  14579. if ((r & (MG_BIT(29) | MG_BIT(28)) && !(r & MG_BIT(27)))) {
  14580. size_t len = s_rxdesc[s_rxno][1] & 0xffff;
  14581. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp); // CRC already stripped
  14582. }
  14583. s_rxdesc[s_rxno][0] |= MG_BIT(31);
  14584. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14585. }
  14586. EDMAC->EDRRR = MG_BIT(0); // Receive Descriptors have changed
  14587. // If b0 == 0, descriptors were exhausted and probably frames were dropped,
  14588. // (27.2.9 RMFCR counts them)
  14589. }
  14590. struct mg_tcpip_driver mg_tcpip_driver_ra = {mg_tcpip_driver_ra_init,
  14591. mg_tcpip_driver_ra_tx, NULL,
  14592. mg_tcpip_driver_ra_up};
  14593. #endif
  14594. #ifdef MG_ENABLE_LINES
  14595. #line 1 "src/drivers/same54.c"
  14596. #endif
  14597. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && MG_ENABLE_DRIVER_SAME54
  14598. #include <sam.h>
  14599. #define ETH_PKT_SIZE 1536 // Max frame size
  14600. #define ETH_DESC_CNT 4 // Descriptors count
  14601. #define ETH_DS 2 // Descriptor size (words)
  14602. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  14603. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  14604. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  14605. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  14606. static uint8_t s_txno; // Current TX descriptor
  14607. static uint8_t s_rxno; // Current RX descriptor
  14608. static struct mg_tcpip_if *s_ifp; // MIP interface
  14609. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  14610. #define MG_PHYREGBIT_BCR_DUPLEX_MODE MG_BIT(8)
  14611. #define MG_PHYREGBIT_BCR_SPEED MG_BIT(13)
  14612. #define MG_PHYREGBIT_BSR_LINK_STATUS MG_BIT(2)
  14613. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  14614. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk |
  14615. GMAC_MAN_OP(2) | // Setting the read operation
  14616. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  14617. GMAC_MAN_REGA(reg); // Setting the register
  14618. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)) (void) 0;
  14619. return GMAC_REGS->GMAC_MAN & GMAC_MAN_DATA_Msk; // Getting the read value
  14620. }
  14621. #if 0
  14622. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14623. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk | GMAC_MAN_OP(1) | // Setting the write operation
  14624. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  14625. GMAC_MAN_REGA(reg) | GMAC_MAN_DATA(val); // Setting the register
  14626. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)); // Waiting until the write op is complete
  14627. }
  14628. #endif
  14629. int get_clock_rate(struct mg_tcpip_driver_same54_data *d) {
  14630. if (d && d->mdc_cr >= 0 && d->mdc_cr <= 5) {
  14631. return d->mdc_cr;
  14632. } else {
  14633. // get MCLK from GCLK_GENERATOR 0
  14634. uint32_t div = 512;
  14635. uint32_t mclk;
  14636. if (!(GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_DIVSEL_Msk)) {
  14637. div = ((GCLK_REGS->GCLK_GENCTRL[0] & 0x00FF0000) >> 16);
  14638. if (div == 0) div = 1;
  14639. }
  14640. switch (GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_SRC_Msk) {
  14641. case GCLK_GENCTRL_SRC_XOSC0_Val:
  14642. mclk = 32000000UL; /* 32MHz */
  14643. break;
  14644. case GCLK_GENCTRL_SRC_XOSC1_Val:
  14645. mclk = 32000000UL; /* 32MHz */
  14646. break;
  14647. case GCLK_GENCTRL_SRC_OSCULP32K_Val:
  14648. mclk = 32000UL;
  14649. break;
  14650. case GCLK_GENCTRL_SRC_XOSC32K_Val:
  14651. mclk = 32000UL;
  14652. break;
  14653. case GCLK_GENCTRL_SRC_DFLL_Val:
  14654. mclk = 48000000UL; /* 48MHz */
  14655. break;
  14656. case GCLK_GENCTRL_SRC_DPLL0_Val:
  14657. mclk = 200000000UL; /* 200MHz */
  14658. break;
  14659. case GCLK_GENCTRL_SRC_DPLL1_Val:
  14660. mclk = 200000000UL; /* 200MHz */
  14661. break;
  14662. default:
  14663. mclk = 200000000UL; /* 200MHz */
  14664. }
  14665. mclk /= div;
  14666. uint8_t crs[] = {0, 1, 2, 3, 4, 5}; // GMAC->NCFGR::CLK values
  14667. uint8_t dividers[] = {8, 16, 32, 48, 64, 96}; // Respective CLK dividers
  14668. for (int i = 0; i < 6; i++) {
  14669. if (mclk / dividers[i] <= 2375000UL /* 2.5MHz - 5% */) {
  14670. return crs[i];
  14671. }
  14672. }
  14673. return 5;
  14674. }
  14675. }
  14676. static bool mg_tcpip_driver_same54_init(struct mg_tcpip_if *ifp) {
  14677. struct mg_tcpip_driver_same54_data *d =
  14678. (struct mg_tcpip_driver_same54_data *) ifp->driver_data;
  14679. s_ifp = ifp;
  14680. MCLK_REGS->MCLK_APBCMASK |= MCLK_APBCMASK_GMAC_Msk;
  14681. MCLK_REGS->MCLK_AHBMASK |= MCLK_AHBMASK_GMAC_Msk;
  14682. GMAC_REGS->GMAC_NCFGR = GMAC_NCFGR_CLK(get_clock_rate(d)); // Set MDC divider
  14683. GMAC_REGS->GMAC_NCR = 0; // Disable RX & TX
  14684. GMAC_REGS->GMAC_NCR |= GMAC_NCR_MPE_Msk; // Enable MDC & MDIO
  14685. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init TX descriptors
  14686. s_txdesc[i][0] = (uint32_t) s_txbuf[i]; // Point to data buffer
  14687. s_txdesc[i][1] = MG_BIT(31); // OWN bit
  14688. }
  14689. s_txdesc[ETH_DESC_CNT - 1][1] |= MG_BIT(30); // Last tx descriptor - wrap
  14690. GMAC_REGS->GMAC_DCFGR = GMAC_DCFGR_DRBS(0x18) // DMA recv buf 1536
  14691. | GMAC_DCFGR_RXBMS(GMAC_DCFGR_RXBMS_FULL_Val) |
  14692. GMAC_DCFGR_TXPBMS(1); // See #2487
  14693. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init RX descriptors
  14694. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i]; // Address of the data buffer
  14695. s_rxdesc[i][1] = 0; // Clear status
  14696. }
  14697. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(1); // Last rx descriptor - wrap
  14698. GMAC_REGS->GMAC_TBQB = (uint32_t) s_txdesc; // about the descriptor addresses
  14699. GMAC_REGS->GMAC_RBQB = (uint32_t) s_rxdesc; // Let the controller know
  14700. GMAC_REGS->SA[0].GMAC_SAB =
  14701. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  14702. GMAC_REGS->SA[0].GMAC_SAT = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  14703. GMAC_REGS->GMAC_UR &= ~GMAC_UR_MII_Msk; // Disable MII, use RMII
  14704. GMAC_REGS->GMAC_NCFGR |= GMAC_NCFGR_MAXFS_Msk | GMAC_NCFGR_MTIHEN_Msk |
  14705. GMAC_NCFGR_EFRHD_Msk | GMAC_NCFGR_CAF_Msk;
  14706. GMAC_REGS->GMAC_TSR = GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk |
  14707. GMAC_TSR_TXCOMP_Msk | GMAC_TSR_TFC_Msk |
  14708. GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  14709. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk;
  14710. GMAC_REGS->GMAC_RSR = GMAC_RSR_HNO_Msk | GMAC_RSR_RXOVR_Msk |
  14711. GMAC_RSR_REC_Msk | GMAC_RSR_BNA_Msk;
  14712. GMAC_REGS->GMAC_IDR = ~0U; // Disable interrupts, then enable required
  14713. GMAC_REGS->GMAC_IER = GMAC_IER_HRESP_Msk | GMAC_IER_ROVR_Msk |
  14714. GMAC_IER_TCOMP_Msk | GMAC_IER_TFC_Msk |
  14715. GMAC_IER_RLEX_Msk | GMAC_IER_TUR_Msk |
  14716. GMAC_IER_RXUBR_Msk | GMAC_IER_RCOMP_Msk;
  14717. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TXEN_Msk | GMAC_NCR_RXEN_Msk;
  14718. NVIC_EnableIRQ(GMAC_IRQn);
  14719. return true;
  14720. }
  14721. static size_t mg_tcpip_driver_same54_tx(const void *buf, size_t len,
  14722. struct mg_tcpip_if *ifp) {
  14723. if (len > sizeof(s_txbuf[s_txno])) {
  14724. MG_ERROR(("Frame too big, %ld", (long) len));
  14725. len = 0; // Frame is too big
  14726. } else if ((s_txdesc[s_txno][1] & MG_BIT(31)) == 0) {
  14727. ifp->nerr++;
  14728. MG_ERROR(("No free descriptors"));
  14729. len = 0; // All descriptors are busy, fail
  14730. } else {
  14731. uint32_t status = len | MG_BIT(15); // Frame length, last chunk
  14732. if (s_txno == ETH_DESC_CNT - 1) status |= MG_BIT(30); // wrap
  14733. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14734. s_txdesc[s_txno][1] = status;
  14735. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14736. }
  14737. __DSB(); // Ensure descriptors have been written
  14738. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TSTART_Msk; // Enable transmission
  14739. return len;
  14740. }
  14741. static bool mg_tcpip_driver_same54_up(struct mg_tcpip_if *ifp) {
  14742. uint16_t bsr = eth_read_phy(MG_PHY_ADDR, MG_PHYREG_BSR);
  14743. bool up = bsr & MG_PHYREGBIT_BSR_LINK_STATUS ? 1 : 0;
  14744. // If PHY is ready, update NCFGR accordingly
  14745. if (ifp->state == MG_TCPIP_STATE_DOWN && up) {
  14746. uint16_t bcr = eth_read_phy(MG_PHY_ADDR, MG_PHYREG_BCR);
  14747. bool fd = bcr & MG_PHYREGBIT_BCR_DUPLEX_MODE ? 1 : 0;
  14748. bool spd = bcr & MG_PHYREGBIT_BCR_SPEED ? 1 : 0;
  14749. GMAC_REGS->GMAC_NCFGR = (GMAC_REGS->GMAC_NCFGR &
  14750. ~(GMAC_NCFGR_SPD_Msk | MG_PHYREGBIT_BCR_SPEED)) |
  14751. GMAC_NCFGR_SPD(spd) | GMAC_NCFGR_FD(fd);
  14752. }
  14753. return up;
  14754. }
  14755. void GMAC_Handler(void);
  14756. void GMAC_Handler(void) {
  14757. uint32_t isr = GMAC_REGS->GMAC_ISR;
  14758. uint32_t rsr = GMAC_REGS->GMAC_RSR;
  14759. uint32_t tsr = GMAC_REGS->GMAC_TSR;
  14760. if (isr & GMAC_ISR_RCOMP_Msk) {
  14761. if (rsr & GMAC_ISR_RCOMP_Msk) {
  14762. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  14763. if ((s_rxdesc[s_rxno][0] & MG_BIT(0)) == 0) break;
  14764. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  14765. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  14766. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // Disown
  14767. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14768. }
  14769. }
  14770. }
  14771. if ((tsr & (GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk | GMAC_TSR_TXCOMP_Msk |
  14772. GMAC_TSR_TFC_Msk | GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  14773. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk)) != 0) {
  14774. // MG_INFO((" --> %#x %#x", s_txdesc[s_txno][1], tsr));
  14775. if (!(s_txdesc[s_txno][1] & MG_BIT(31))) s_txdesc[s_txno][1] |= MG_BIT(31);
  14776. }
  14777. GMAC_REGS->GMAC_RSR = rsr;
  14778. GMAC_REGS->GMAC_TSR = tsr;
  14779. }
  14780. struct mg_tcpip_driver mg_tcpip_driver_same54 = {
  14781. mg_tcpip_driver_same54_init, mg_tcpip_driver_same54_tx, NULL,
  14782. mg_tcpip_driver_same54_up};
  14783. #endif
  14784. #ifdef MG_ENABLE_LINES
  14785. #line 1 "src/drivers/stm32f.c"
  14786. #endif
  14787. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
  14788. MG_ENABLE_DRIVER_STM32F
  14789. struct stm32f_eth {
  14790. volatile uint32_t MACCR, MACFFR, MACHTHR, MACHTLR, MACMIIAR, MACMIIDR, MACFCR,
  14791. MACVLANTR, RESERVED0[2], MACRWUFFR, MACPMTCSR, RESERVED1, MACDBGR, MACSR,
  14792. MACIMR, MACA0HR, MACA0LR, MACA1HR, MACA1LR, MACA2HR, MACA2LR, MACA3HR,
  14793. MACA3LR, RESERVED2[40], MMCCR, MMCRIR, MMCTIR, MMCRIMR, MMCTIMR,
  14794. RESERVED3[14], MMCTGFSCCR, MMCTGFMSCCR, RESERVED4[5], MMCTGFCR,
  14795. RESERVED5[10], MMCRFCECR, MMCRFAECR, RESERVED6[10], MMCRGUFCR,
  14796. RESERVED7[334], PTPTSCR, PTPSSIR, PTPTSHR, PTPTSLR, PTPTSHUR, PTPTSLUR,
  14797. PTPTSAR, PTPTTHR, PTPTTLR, RESERVED8, PTPTSSR, PTPPPSCR, RESERVED9[564],
  14798. DMABMR, DMATPDR, DMARPDR, DMARDLAR, DMATDLAR, DMASR, DMAOMR, DMAIER,
  14799. DMAMFBOCR, DMARSWTR, RESERVED10[8], DMACHTDR, DMACHRDR, DMACHTBAR,
  14800. DMACHRBAR;
  14801. };
  14802. #undef ETH
  14803. #define ETH ((struct stm32f_eth *) (uintptr_t) 0x40028000)
  14804. #define ETH_PKT_SIZE 1540 // Max frame size
  14805. #define ETH_DESC_CNT 4 // Descriptors count
  14806. #define ETH_DS 4 // Descriptor size (words)
  14807. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  14808. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  14809. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  14810. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  14811. static uint8_t s_txno; // Current TX descriptor
  14812. static uint8_t s_rxno; // Current RX descriptor
  14813. static struct mg_tcpip_if *s_ifp; // MIP interface
  14814. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  14815. ETH->MACMIIAR &= (7 << 2);
  14816. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  14817. ETH->MACMIIAR |= MG_BIT(0);
  14818. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  14819. return ETH->MACMIIDR & 0xffff;
  14820. }
  14821. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  14822. ETH->MACMIIDR = val;
  14823. ETH->MACMIIAR &= (7 << 2);
  14824. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  14825. ETH->MACMIIAR |= MG_BIT(0);
  14826. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  14827. }
  14828. static uint32_t get_hclk(void) {
  14829. struct rcc {
  14830. volatile uint32_t CR, PLLCFGR, CFGR;
  14831. } *rcc = (struct rcc *) 0x40023800;
  14832. uint32_t clk = 0, hsi = 16000000 /* 16 MHz */, hse = 8000000 /* 8MHz */;
  14833. if (rcc->CFGR & (1 << 2)) {
  14834. clk = hse;
  14835. } else if (rcc->CFGR & (1 << 3)) {
  14836. uint32_t vco, m, n, p;
  14837. m = (rcc->PLLCFGR & (0x3f << 0)) >> 0;
  14838. n = (rcc->PLLCFGR & (0x1ff << 6)) >> 6;
  14839. p = (((rcc->PLLCFGR & (3 << 16)) >> 16) + 1) * 2;
  14840. clk = (rcc->PLLCFGR & (1 << 22)) ? hse : hsi;
  14841. vco = (uint32_t) ((uint64_t) clk * n / m);
  14842. clk = vco / p;
  14843. } else {
  14844. clk = hsi;
  14845. }
  14846. uint32_t hpre = (rcc->CFGR & (15 << 4)) >> 4;
  14847. if (hpre < 8) return clk;
  14848. uint8_t ahbptab[8] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  14849. return ((uint32_t) clk) >> ahbptab[hpre - 8];
  14850. }
  14851. // Guess CR from HCLK. MDC clock is generated from HCLK (AHB); as per 802.3,
  14852. // it must not exceed 2.5MHz As the AHB clock can be (and usually is) derived
  14853. // from the HSI (internal RC), and it can go above specs, the datasheets
  14854. // specify a range of frequencies and activate one of a series of dividers to
  14855. // keep the MDC clock safely below 2.5MHz. We guess a divider setting based on
  14856. // HCLK with a +5% drift. If the user uses a different clock from our
  14857. // defaults, needs to set the macros on top Valid for STM32F74xxx/75xxx
  14858. // (38.8.1) and STM32F42xxx/43xxx (33.8.1) (both 4.5% worst case drift)
  14859. static int guess_mdc_cr(void) {
  14860. uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMIIAR::CR values
  14861. uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  14862. uint32_t hclk = get_hclk(); // Guess system HCLK
  14863. int result = -1; // Invalid CR value
  14864. if (hclk < 25000000) {
  14865. MG_ERROR(("HCLK too low"));
  14866. } else {
  14867. for (int i = 0; i < 6; i++) {
  14868. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  14869. result = crs[i];
  14870. break;
  14871. }
  14872. }
  14873. if (result < 0) MG_ERROR(("HCLK too high"));
  14874. }
  14875. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  14876. return result;
  14877. }
  14878. static bool mg_tcpip_driver_stm32f_init(struct mg_tcpip_if *ifp) {
  14879. struct mg_tcpip_driver_stm32f_data *d =
  14880. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  14881. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  14882. s_ifp = ifp;
  14883. // Init RX descriptors
  14884. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14885. s_rxdesc[i][0] = MG_BIT(31); // Own
  14886. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  14887. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  14888. s_rxdesc[i][3] =
  14889. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  14890. }
  14891. // Init TX descriptors
  14892. for (int i = 0; i < ETH_DESC_CNT; i++) {
  14893. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  14894. s_txdesc[i][3] =
  14895. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  14896. }
  14897. ETH->DMABMR |= MG_BIT(0); // Software reset
  14898. while ((ETH->DMABMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  14899. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  14900. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  14901. ETH->MACMIIAR = ((uint32_t) cr & 7) << 2;
  14902. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  14903. // hardware checksum. Therefore, descriptor size is 4, not 8
  14904. // ETH->DMABMR = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) |
  14905. // MG_BIT(25);
  14906. ETH->MACIMR = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  14907. ETH->MACFCR = MG_BIT(7); // Disable zero quarta pause
  14908. // ETH->MACFFR = MG_BIT(31); // Receive all
  14909. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  14910. mg_phy_init(&phy, phy_addr, MG_PHY_CLOCKS_MAC);
  14911. ETH->DMARDLAR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  14912. ETH->DMATDLAR = (uint32_t) (uintptr_t) s_txdesc; // RX descriptors
  14913. ETH->DMAIER = MG_BIT(6) | MG_BIT(16); // RIE, NISE
  14914. ETH->MACCR =
  14915. MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  14916. ETH->DMAOMR =
  14917. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  14918. // MAC address filtering
  14919. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  14920. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  14921. ((uint32_t) ifp->mac[2] << 16) |
  14922. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  14923. return true;
  14924. }
  14925. static size_t mg_tcpip_driver_stm32f_tx(const void *buf, size_t len,
  14926. struct mg_tcpip_if *ifp) {
  14927. if (len > sizeof(s_txbuf[s_txno])) {
  14928. MG_ERROR(("Frame too big, %ld", (long) len));
  14929. len = 0; // Frame is too big
  14930. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  14931. ifp->nerr++;
  14932. MG_ERROR(("No free descriptors"));
  14933. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long) ETH->DMASR);
  14934. len = 0; // All descriptors are busy, fail
  14935. } else {
  14936. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  14937. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  14938. s_txdesc[s_txno][0] = MG_BIT(20) | MG_BIT(28) | MG_BIT(29); // Chain,FS,LS
  14939. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  14940. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  14941. }
  14942. MG_DSB(); // ensure descriptors have been written
  14943. ETH->DMASR = MG_BIT(2) | MG_BIT(5); // Clear any prior TBUS/TUS
  14944. ETH->DMATPDR = 0; // and resume
  14945. return len;
  14946. }
  14947. static bool mg_tcpip_driver_stm32f_up(struct mg_tcpip_if *ifp) {
  14948. struct mg_tcpip_driver_stm32f_data *d =
  14949. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  14950. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  14951. uint8_t speed = MG_PHY_SPEED_10M;
  14952. bool up = false, full_duplex = false;
  14953. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  14954. up = mg_phy_up(&phy, phy_addr, &full_duplex, &speed);
  14955. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  14956. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  14957. // if(link is slow or half) set flags otherwise
  14958. // reg = tmp
  14959. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  14960. if (speed == MG_PHY_SPEED_10M) maccr &= ~MG_BIT(14); // 10M
  14961. if (full_duplex == false) maccr &= ~MG_BIT(11); // Half-duplex
  14962. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  14963. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  14964. maccr & MG_BIT(11) ? "full" : "half"));
  14965. }
  14966. return up;
  14967. }
  14968. #ifdef __riscv
  14969. __attribute__((interrupt())) // For RISCV CH32V307, which share the same MAC
  14970. #endif
  14971. void ETH_IRQHandler(void);
  14972. void ETH_IRQHandler(void) {
  14973. if (ETH->DMASR & MG_BIT(6)) { // Frame received, loop
  14974. ETH->DMASR = MG_BIT(16) | MG_BIT(6); // Clear flag
  14975. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  14976. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  14977. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) ==
  14978. (MG_BIT(8) | MG_BIT(9))) &&
  14979. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  14980. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  14981. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  14982. // ETH->DMASR);
  14983. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  14984. }
  14985. s_rxdesc[s_rxno][0] = MG_BIT(31);
  14986. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  14987. }
  14988. }
  14989. // Cleanup flags
  14990. ETH->DMASR = MG_BIT(16) // NIS, normal interrupt summary
  14991. | MG_BIT(7); // Clear possible RBUS while processing
  14992. ETH->DMARPDR = 0; // and resume RX
  14993. }
  14994. struct mg_tcpip_driver mg_tcpip_driver_stm32f = {
  14995. mg_tcpip_driver_stm32f_init, mg_tcpip_driver_stm32f_tx, NULL,
  14996. mg_tcpip_driver_stm32f_up};
  14997. #endif
  14998. #ifdef MG_ENABLE_LINES
  14999. #line 1 "src/drivers/stm32h.c"
  15000. #endif
  15001. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32H) && \
  15002. MG_ENABLE_DRIVER_STM32H
  15003. struct stm32h_eth {
  15004. volatile uint32_t MACCR, MACECR, MACPFR, MACWTR, MACHT0R, MACHT1R,
  15005. RESERVED1[14], MACVTR, RESERVED2, MACVHTR, RESERVED3, MACVIR, MACIVIR,
  15006. RESERVED4[2], MACTFCR, RESERVED5[7], MACRFCR, RESERVED6[7], MACISR,
  15007. MACIER, MACRXTXSR, RESERVED7, MACPCSR, MACRWKPFR, RESERVED8[2], MACLCSR,
  15008. MACLTCR, MACLETR, MAC1USTCR, RESERVED9[12], MACVR, MACDR, RESERVED10,
  15009. MACHWF0R, MACHWF1R, MACHWF2R, RESERVED11[54], MACMDIOAR, MACMDIODR,
  15010. RESERVED12[2], MACARPAR, RESERVED13[59], MACA0HR, MACA0LR, MACA1HR,
  15011. MACA1LR, MACA2HR, MACA2LR, MACA3HR, MACA3LR, RESERVED14[248], MMCCR,
  15012. MMCRIR, MMCTIR, MMCRIMR, MMCTIMR, RESERVED15[14], MMCTSCGPR, MMCTMCGPR,
  15013. RESERVED16[5], MMCTPCGR, RESERVED17[10], MMCRCRCEPR, MMCRAEPR,
  15014. RESERVED18[10], MMCRUPGR, RESERVED19[9], MMCTLPIMSTR, MMCTLPITCR,
  15015. MMCRLPIMSTR, MMCRLPITCR, RESERVED20[65], MACL3L4C0R, MACL4A0R,
  15016. RESERVED21[2], MACL3A0R0R, MACL3A1R0R, MACL3A2R0R, MACL3A3R0R,
  15017. RESERVED22[4], MACL3L4C1R, MACL4A1R, RESERVED23[2], MACL3A0R1R,
  15018. MACL3A1R1R, MACL3A2R1R, MACL3A3R1R, RESERVED24[108], MACTSCR, MACSSIR,
  15019. MACSTSR, MACSTNR, MACSTSUR, MACSTNUR, MACTSAR, RESERVED25, MACTSSR,
  15020. RESERVED26[3], MACTTSSNR, MACTTSSSR, RESERVED27[2], MACACR, RESERVED28,
  15021. MACATSNR, MACATSSR, MACTSIACR, MACTSEACR, MACTSICNR, MACTSECNR,
  15022. RESERVED29[4], MACPPSCR, RESERVED30[3], MACPPSTTSR, MACPPSTTNR, MACPPSIR,
  15023. MACPPSWR, RESERVED31[12], MACPOCR, MACSPI0R, MACSPI1R, MACSPI2R, MACLMIR,
  15024. RESERVED32[11], MTLOMR, RESERVED33[7], MTLISR, RESERVED34[55], MTLTQOMR,
  15025. MTLTQUR, MTLTQDR, RESERVED35[8], MTLQICSR, MTLRQOMR, MTLRQMPOCR, MTLRQDR,
  15026. RESERVED36[177], DMAMR, DMASBMR, DMAISR, DMADSR, RESERVED37[60], DMACCR,
  15027. DMACTCR, DMACRCR, RESERVED38[2], DMACTDLAR, RESERVED39, DMACRDLAR,
  15028. DMACTDTPR, RESERVED40, DMACRDTPR, DMACTDRLR, DMACRDRLR, DMACIER,
  15029. DMACRIWTR, DMACSFCSR, RESERVED41, DMACCATDR, RESERVED42, DMACCARDR,
  15030. RESERVED43, DMACCATBR, RESERVED44, DMACCARBR, DMACSR, RESERVED45[2],
  15031. DMACMFCR;
  15032. };
  15033. #undef ETH
  15034. #define ETH \
  15035. ((struct stm32h_eth *) (uintptr_t) (0x40000000UL + 0x00020000UL + 0x8000UL))
  15036. #define ETH_PKT_SIZE 1540 // Max frame size
  15037. #define ETH_DESC_CNT 4 // Descriptors count
  15038. #define ETH_DS 4 // Descriptor size (words)
  15039. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15040. static volatile uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15041. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  15042. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  15043. static struct mg_tcpip_if *s_ifp; // MIP interface
  15044. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  15045. ETH->MACMDIOAR &= (0xF << 8);
  15046. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 3 << 2;
  15047. ETH->MACMDIOAR |= MG_BIT(0);
  15048. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  15049. return (uint16_t) ETH->MACMDIODR;
  15050. }
  15051. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15052. ETH->MACMDIODR = val;
  15053. ETH->MACMDIOAR &= (0xF << 8);
  15054. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 1 << 2;
  15055. ETH->MACMDIOAR |= MG_BIT(0);
  15056. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  15057. }
  15058. static uint32_t get_hclk(void) {
  15059. struct rcc {
  15060. volatile uint32_t CR, HSICFGR, CRRCR, CSICFGR, CFGR, RESERVED1, D1CFGR,
  15061. D2CFGR, D3CFGR, RESERVED2, PLLCKSELR, PLLCFGR, PLL1DIVR, PLL1FRACR,
  15062. PLL2DIVR, PLL2FRACR, PLL3DIVR, PLL3FRACR, RESERVED3, D1CCIPR, D2CCIP1R,
  15063. D2CCIP2R, D3CCIPR, RESERVED4, CIER, CIFR, CICR, RESERVED5, BDCR, CSR,
  15064. RESERVED6, AHB3RSTR, AHB1RSTR, AHB2RSTR, AHB4RSTR, APB3RSTR, APB1LRSTR,
  15065. APB1HRSTR, APB2RSTR, APB4RSTR, GCR, RESERVED8, D3AMR, RESERVED11[9],
  15066. RSR, AHB3ENR, AHB1ENR, AHB2ENR, AHB4ENR, APB3ENR, APB1LENR, APB1HENR,
  15067. APB2ENR, APB4ENR, RESERVED12, AHB3LPENR, AHB1LPENR, AHB2LPENR,
  15068. AHB4LPENR, APB3LPENR, APB1LLPENR, APB1HLPENR, APB2LPENR, APB4LPENR,
  15069. RESERVED13[4];
  15070. } *rcc = ((struct rcc *) (0x40000000 + 0x18020000 + 0x4400));
  15071. uint32_t clk = 0, hsi = 64000000 /* 64 MHz */, hse = 8000000 /* 8MHz */,
  15072. csi = 4000000 /* 4MHz */;
  15073. unsigned int sel = (rcc->CFGR & (7 << 3)) >> 3;
  15074. if (sel == 1) {
  15075. clk = csi;
  15076. } else if (sel == 2) {
  15077. clk = hse;
  15078. } else if (sel == 3) {
  15079. uint32_t vco, m, n, p;
  15080. unsigned int src = (rcc->PLLCKSELR & (3 << 0)) >> 0;
  15081. m = ((rcc->PLLCKSELR & (0x3F << 4)) >> 4);
  15082. n = ((rcc->PLL1DIVR & (0x1FF << 0)) >> 0) + 1 +
  15083. ((rcc->PLLCFGR & MG_BIT(0)) ? 1 : 0); // round-up in fractional mode
  15084. p = ((rcc->PLL1DIVR & (0x7F << 9)) >> 9) + 1;
  15085. if (src == 1) {
  15086. clk = csi;
  15087. } else if (src == 2) {
  15088. clk = hse;
  15089. } else {
  15090. clk = hsi;
  15091. clk >>= ((rcc->CR & 3) >> 3);
  15092. }
  15093. vco = (uint32_t) ((uint64_t) clk * n / m);
  15094. clk = vco / p;
  15095. } else {
  15096. clk = hsi;
  15097. clk >>= ((rcc->CR & 3) >> 3);
  15098. }
  15099. const uint8_t cptab[12] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  15100. uint32_t d1cpre = (rcc->D1CFGR & (0x0F << 8)) >> 8;
  15101. if (d1cpre >= 8) clk >>= cptab[d1cpre - 8];
  15102. MG_DEBUG(("D1 CLK: %u", clk));
  15103. uint32_t hpre = (rcc->D1CFGR & (0x0F << 0)) >> 0;
  15104. if (hpre < 8) return clk;
  15105. return ((uint32_t) clk) >> cptab[hpre - 8];
  15106. }
  15107. // Guess CR from AHB1 clock. MDC clock is generated from the ETH peripheral
  15108. // clock (AHB1); as per 802.3, it must not exceed 2. As the AHB clock can
  15109. // be derived from HSI or CSI (internal RC) clocks, and those can go above
  15110. // specs, the datasheets specify a range of frequencies and activate one of a
  15111. // series of dividers to keep the MDC clock safely below 2.5MHz. We guess a
  15112. // divider setting based on HCLK with some drift. If the user uses a different
  15113. // clock from our defaults, needs to set the macros on top. Valid for
  15114. // STM32H74xxx/75xxx (58.11.4)(4.5% worst case drift)(CSI clock has a 7.5 %
  15115. // worst case drift @ max temp)
  15116. static int guess_mdc_cr(void) {
  15117. const uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMDIOAR::CR values
  15118. const uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  15119. uint32_t hclk = get_hclk(); // Guess system HCLK
  15120. int result = -1; // Invalid CR value
  15121. for (int i = 0; i < 6; i++) {
  15122. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  15123. result = crs[i];
  15124. break;
  15125. }
  15126. }
  15127. if (result < 0) MG_ERROR(("HCLK too high"));
  15128. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  15129. return result;
  15130. }
  15131. static bool mg_tcpip_driver_stm32h_init(struct mg_tcpip_if *ifp) {
  15132. struct mg_tcpip_driver_stm32h_data *d =
  15133. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  15134. s_ifp = ifp;
  15135. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  15136. uint8_t phy_conf = d == NULL ? MG_PHY_CLOCKS_MAC : d->phy_conf;
  15137. // Init RX descriptors
  15138. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15139. s_rxdesc[i][0] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  15140. s_rxdesc[i][3] = MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  15141. }
  15142. // Init TX descriptors
  15143. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15144. s_txdesc[i][0] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  15145. }
  15146. ETH->DMAMR |= MG_BIT(0); // Software reset
  15147. while ((ETH->DMAMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  15148. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  15149. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  15150. ETH->MACMDIOAR = ((uint32_t) cr & 0xF) << 8;
  15151. // NOTE(scaprile): We do not use timing facilities so the DMA engine does not
  15152. // re-write buffer address
  15153. ETH->DMAMR = 0 << 16; // use interrupt mode 0 (58.8.1) (reset value)
  15154. ETH->DMASBMR |= MG_BIT(12); // AAL NOTE(scaprile): is this actually needed
  15155. ETH->MACIER = 0; // Do not enable additional irq sources (reset value)
  15156. ETH->MACTFCR = MG_BIT(7); // Disable zero-quanta pause
  15157. // ETH->MACPFR = MG_BIT(31); // Receive all
  15158. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15159. mg_phy_init(&phy, phy_addr, phy_conf);
  15160. ETH->DMACRDLAR =
  15161. (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors start address
  15162. ETH->DMACRDRLR = ETH_DESC_CNT - 1; // ring length
  15163. ETH->DMACRDTPR =
  15164. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT -
  15165. 1]; // last valid descriptor address
  15166. ETH->DMACTDLAR =
  15167. (uint32_t) (uintptr_t) s_txdesc; // TX descriptors start address
  15168. ETH->DMACTDRLR = ETH_DESC_CNT - 1; // ring length
  15169. ETH->DMACTDTPR =
  15170. (uint32_t) (uintptr_t) s_txdesc; // first available descriptor address
  15171. ETH->DMACCR = 0; // DSL = 0 (contiguous descriptor table) (reset value)
  15172. ETH->DMACIER = MG_BIT(6) | MG_BIT(15); // RIE, NIE
  15173. ETH->MACCR = MG_BIT(0) | MG_BIT(1) | MG_BIT(13) | MG_BIT(14) |
  15174. MG_BIT(15); // RE, TE, Duplex, Fast, Reserved
  15175. ETH->MTLTQOMR |= MG_BIT(1); // TSF
  15176. ETH->MTLRQOMR |= MG_BIT(5); // RSF
  15177. ETH->DMACTCR |= MG_BIT(0); // ST
  15178. ETH->DMACRCR |= MG_BIT(0); // SR
  15179. // MAC address filtering
  15180. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  15181. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  15182. ((uint32_t) ifp->mac[2] << 16) |
  15183. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  15184. return true;
  15185. }
  15186. static uint32_t s_txno;
  15187. static size_t mg_tcpip_driver_stm32h_tx(const void *buf, size_t len,
  15188. struct mg_tcpip_if *ifp) {
  15189. if (len > sizeof(s_txbuf[s_txno])) {
  15190. MG_ERROR(("Frame too big, %ld", (long) len));
  15191. len = 0; // Frame is too big
  15192. } else if ((s_txdesc[s_txno][3] & MG_BIT(31))) {
  15193. ifp->nerr++;
  15194. MG_ERROR(("No free descriptors: %u %08X %08X %08X", s_txno,
  15195. s_txdesc[s_txno][3], ETH->DMACSR, ETH->DMACTCR));
  15196. for (int i = 0; i < ETH_DESC_CNT; i++) MG_ERROR(("%08X", s_txdesc[i][3]));
  15197. len = 0; // All descriptors are busy, fail
  15198. } else {
  15199. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  15200. s_txdesc[s_txno][2] = (uint32_t) len; // Set data len
  15201. s_txdesc[s_txno][3] = MG_BIT(28) | MG_BIT(29); // FD, LD
  15202. s_txdesc[s_txno][3] |= MG_BIT(31); // Set OWN bit - let DMA take over
  15203. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15204. }
  15205. ETH->DMACSR |= MG_BIT(2) | MG_BIT(1); // Clear any prior TBU, TPS
  15206. ETH->DMACTDTPR = (uint32_t) (uintptr_t) &s_txdesc[s_txno]; // and resume
  15207. return len;
  15208. (void) ifp;
  15209. }
  15210. static bool mg_tcpip_driver_stm32h_up(struct mg_tcpip_if *ifp) {
  15211. struct mg_tcpip_driver_stm32h_data *d =
  15212. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  15213. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  15214. uint8_t speed = MG_PHY_SPEED_10M;
  15215. bool up = false, full_duplex = false;
  15216. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15217. up = mg_phy_up(&phy, phy_addr, &full_duplex, &speed);
  15218. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15219. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  15220. // if(link is slow or half) set flags otherwise
  15221. // reg = tmp
  15222. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(13); // 100M, Full-duplex
  15223. if (speed == MG_PHY_SPEED_10M) maccr &= ~MG_BIT(14); // 10M
  15224. if (full_duplex == false) maccr &= ~MG_BIT(13); // Half-duplex
  15225. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  15226. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  15227. maccr & MG_BIT(13) ? "full" : "half"));
  15228. }
  15229. return up;
  15230. }
  15231. void ETH_IRQHandler(void);
  15232. static uint32_t s_rxno;
  15233. void ETH_IRQHandler(void) {
  15234. if (ETH->DMACSR & MG_BIT(6)) { // Frame received, loop
  15235. ETH->DMACSR = MG_BIT(15) | MG_BIT(6); // Clear flag
  15236. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  15237. if (s_rxdesc[s_rxno][3] & MG_BIT(31)) break; // exit when done
  15238. if (((s_rxdesc[s_rxno][3] & (MG_BIT(28) | MG_BIT(29))) ==
  15239. (MG_BIT(28) | MG_BIT(29))) &&
  15240. !(s_rxdesc[s_rxno][3] & MG_BIT(15))) { // skip partial/errored frames
  15241. uint32_t len = s_rxdesc[s_rxno][3] & (MG_BIT(15) - 1);
  15242. // MG_DEBUG(("%lx %lu %lx %08lx", s_rxno, len, s_rxdesc[s_rxno][3],
  15243. // ETH->DMACSR));
  15244. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  15245. }
  15246. s_rxdesc[s_rxno][3] =
  15247. MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  15248. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15249. }
  15250. }
  15251. ETH->DMACSR =
  15252. MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing
  15253. ETH->DMACRDTPR =
  15254. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT - 1]; // and resume RX
  15255. }
  15256. struct mg_tcpip_driver mg_tcpip_driver_stm32h = {
  15257. mg_tcpip_driver_stm32h_init, mg_tcpip_driver_stm32h_tx, NULL,
  15258. mg_tcpip_driver_stm32h_up};
  15259. #endif
  15260. #ifdef MG_ENABLE_LINES
  15261. #line 1 "src/drivers/tm4c.c"
  15262. #endif
  15263. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
  15264. struct tm4c_emac {
  15265. volatile uint32_t EMACCFG, EMACFRAMEFLTR, EMACHASHTBLH, EMACHASHTBLL,
  15266. EMACMIIADDR, EMACMIIDATA, EMACFLOWCTL, EMACVLANTG, RESERVED0, EMACSTATUS,
  15267. EMACRWUFF, EMACPMTCTLSTAT, RESERVED1[2], EMACRIS, EMACIM, EMACADDR0H,
  15268. EMACADDR0L, EMACADDR1H, EMACADDR1L, EMACADDR2H, EMACADDR2L, EMACADDR3H,
  15269. EMACADDR3L, RESERVED2[31], EMACWDOGTO, RESERVED3[8], EMACMMCCTRL,
  15270. EMACMMCRXRIS, EMACMMCTXRIS, EMACMMCRXIM, EMACMMCTXIM, RESERVED4,
  15271. EMACTXCNTGB, RESERVED5[12], EMACTXCNTSCOL, EMACTXCNTMCOL, RESERVED6[4],
  15272. EMACTXOCTCNTG, RESERVED7[6], EMACRXCNTGB, RESERVED8[4], EMACRXCNTCRCERR,
  15273. EMACRXCNTALGNERR, RESERVED9[10], EMACRXCNTGUNI, RESERVED10[239],
  15274. EMACVLNINCREP, EMACVLANHASH, RESERVED11[93], EMACTIMSTCTRL, EMACSUBSECINC,
  15275. EMACTIMSEC, EMACTIMNANO, EMACTIMSECU, EMACTIMNANOU, EMACTIMADD,
  15276. EMACTARGSEC, EMACTARGNANO, EMACHWORDSEC, EMACTIMSTAT, EMACPPSCTRL,
  15277. RESERVED12[12], EMACPPS0INTVL, EMACPPS0WIDTH, RESERVED13[294],
  15278. EMACDMABUSMOD, EMACTXPOLLD, EMACRXPOLLD, EMACRXDLADDR, EMACTXDLADDR,
  15279. EMACDMARIS, EMACDMAOPMODE, EMACDMAIM, EMACMFBOC, EMACRXINTWDT,
  15280. RESERVED14[8], EMACHOSTXDESC, EMACHOSRXDESC, EMACHOSTXBA, EMACHOSRXBA,
  15281. RESERVED15[218], EMACPP, EMACPC, EMACCC, RESERVED16, EMACEPHYRIS,
  15282. EMACEPHYIM, EMACEPHYIMSC;
  15283. };
  15284. #undef EMAC
  15285. #define EMAC ((struct tm4c_emac *) (uintptr_t) 0x400EC000)
  15286. #define ETH_PKT_SIZE 1540 // Max frame size
  15287. #define ETH_DESC_CNT 4 // Descriptors count
  15288. #define ETH_DS 4 // Descriptor size (words)
  15289. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15290. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15291. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  15292. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  15293. static struct mg_tcpip_if *s_ifp; // MIP interface
  15294. enum {
  15295. EPHY_ADDR = 0,
  15296. EPHYBMCR = 0,
  15297. EPHYBMSR = 1,
  15298. EPHYSTS = 16
  15299. }; // PHY constants
  15300. static inline void tm4cspin(volatile uint32_t count) {
  15301. while (count--) (void) 0;
  15302. }
  15303. static uint32_t emac_read_phy(uint8_t addr, uint8_t reg) {
  15304. EMAC->EMACMIIADDR &= (0xf << 2);
  15305. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  15306. EMAC->EMACMIIADDR |= MG_BIT(0);
  15307. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  15308. return EMAC->EMACMIIDATA;
  15309. }
  15310. static void emac_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  15311. EMAC->EMACMIIDATA = val;
  15312. EMAC->EMACMIIADDR &= (0xf << 2);
  15313. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  15314. EMAC->EMACMIIADDR |= MG_BIT(0);
  15315. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  15316. }
  15317. static uint32_t get_sysclk(void) {
  15318. struct sysctl {
  15319. volatile uint32_t DONTCARE0[44], RSCLKCFG, DONTCARE1[43], PLLFREQ0,
  15320. PLLFREQ1;
  15321. } *sysctl = (struct sysctl *) 0x400FE000;
  15322. uint32_t clk = 0, piosc = 16000000 /* 16 MHz */, mosc = 25000000 /* 25MHz */;
  15323. if (sysctl->RSCLKCFG & (1 << 28)) { // USEPLL
  15324. uint32_t fin, vco, mdiv, n, q, psysdiv;
  15325. uint32_t pllsrc = (sysctl->RSCLKCFG & (0xf << 24)) >> 24;
  15326. if (pllsrc == 0) {
  15327. clk = piosc;
  15328. } else if (pllsrc == 3) {
  15329. clk = mosc;
  15330. } else {
  15331. MG_ERROR(("Unsupported clock source"));
  15332. }
  15333. q = (sysctl->PLLFREQ1 & (0x1f << 8)) >> 8;
  15334. n = (sysctl->PLLFREQ1 & (0x1f << 0)) >> 0;
  15335. fin = clk / ((q + 1) * (n + 1));
  15336. mdiv = (sysctl->PLLFREQ0 & (0x3ff << 0)) >>
  15337. 0; // mint + (mfrac / 1024); MFRAC not supported
  15338. psysdiv = (sysctl->RSCLKCFG & (0x3f << 0)) >> 0;
  15339. vco = (uint32_t) ((uint64_t) fin * mdiv);
  15340. return vco / (psysdiv + 1);
  15341. }
  15342. uint32_t oscsrc = (sysctl->RSCLKCFG & (0xf << 20)) >> 20;
  15343. if (oscsrc == 0) {
  15344. clk = piosc;
  15345. } else if (oscsrc == 3) {
  15346. clk = mosc;
  15347. } else {
  15348. MG_ERROR(("Unsupported clock source"));
  15349. }
  15350. uint32_t osysdiv = (sysctl->RSCLKCFG & (0xf << 16)) >> 16;
  15351. return clk / (osysdiv + 1);
  15352. }
  15353. // Guess CR from SYSCLK. MDC clock is generated from SYSCLK (AHB); as per
  15354. // 802.3, it must not exceed 2.5MHz (also 20.4.2.6) As the AHB clock can be
  15355. // derived from the PIOSC (internal RC), and it can go above specs, the
  15356. // datasheets specify a range of frequencies and activate one of a series of
  15357. // dividers to keep the MDC clock safely below 2.5MHz. We guess a divider
  15358. // setting based on SYSCLK with a +5% drift. If the user uses a different clock
  15359. // from our defaults, needs to set the macros on top Valid for TM4C129x (20.7)
  15360. // (4.5% worst case drift)
  15361. // The PHY receives the main oscillator (MOSC) (20.3.1)
  15362. static int guess_mdc_cr(void) {
  15363. uint8_t crs[] = {2, 3, 0, 1}; // EMAC->MACMIIAR::CR values
  15364. uint8_t div[] = {16, 26, 42, 62}; // Respective HCLK dividers
  15365. uint32_t sysclk = get_sysclk(); // Guess system SYSCLK
  15366. int result = -1; // Invalid CR value
  15367. if (sysclk < 25000000) {
  15368. MG_ERROR(("SYSCLK too low"));
  15369. } else {
  15370. for (int i = 0; i < 4; i++) {
  15371. if (sysclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  15372. result = crs[i];
  15373. break;
  15374. }
  15375. }
  15376. if (result < 0) MG_ERROR(("SYSCLK too high"));
  15377. }
  15378. MG_DEBUG(("SYSCLK: %u, CR: %d", sysclk, result));
  15379. return result;
  15380. }
  15381. static bool mg_tcpip_driver_tm4c_init(struct mg_tcpip_if *ifp) {
  15382. struct mg_tcpip_driver_tm4c_data *d =
  15383. (struct mg_tcpip_driver_tm4c_data *) ifp->driver_data;
  15384. s_ifp = ifp;
  15385. // Init RX descriptors
  15386. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15387. s_rxdesc[i][0] = MG_BIT(31); // Own
  15388. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  15389. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  15390. s_rxdesc[i][3] =
  15391. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  15392. // MG_DEBUG(("%d %p", i, s_rxdesc[i]));
  15393. }
  15394. // Init TX descriptors
  15395. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15396. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  15397. s_txdesc[i][3] =
  15398. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  15399. }
  15400. EMAC->EMACDMABUSMOD |= MG_BIT(0); // Software reset
  15401. while ((EMAC->EMACDMABUSMOD & MG_BIT(0)) != 0) tm4cspin(1); // Wait until done
  15402. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  15403. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  15404. EMAC->EMACMIIADDR = ((uint32_t) cr & 0xf) << 2;
  15405. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  15406. // hardware checksum. Therefore, descriptor size is 4, not 8
  15407. // EMAC->EMACDMABUSMOD = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) | MG_BIT(25);
  15408. EMAC->EMACIM = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  15409. EMAC->EMACFLOWCTL = MG_BIT(7); // Disable zero-quanta pause
  15410. // EMAC->EMACFRAMEFLTR = MG_BIT(31); // Receive all
  15411. // EMAC->EMACPC defaults to internal PHY (EPHY) in MMI mode
  15412. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(15)); // Reset internal PHY (EPHY)
  15413. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(12)); // Set autonegotiation
  15414. EMAC->EMACRXDLADDR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  15415. EMAC->EMACTXDLADDR = (uint32_t) (uintptr_t) s_txdesc; // TX descriptors
  15416. EMAC->EMACDMAIM = MG_BIT(6) | MG_BIT(16); // RIE, NIE
  15417. EMAC->EMACCFG = MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  15418. EMAC->EMACDMAOPMODE =
  15419. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  15420. EMAC->EMACADDR0H = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  15421. EMAC->EMACADDR0L = (uint32_t) (ifp->mac[3] << 24) |
  15422. ((uint32_t) ifp->mac[2] << 16) |
  15423. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  15424. // NOTE(scaprile) There are 3 additional slots for filtering, disabled by
  15425. // default. This also applies to the STM32 driver (at least for F7)
  15426. return true;
  15427. }
  15428. static uint32_t s_txno;
  15429. static size_t mg_tcpip_driver_tm4c_tx(const void *buf, size_t len,
  15430. struct mg_tcpip_if *ifp) {
  15431. if (len > sizeof(s_txbuf[s_txno])) {
  15432. MG_ERROR(("Frame too big, %ld", (long) len));
  15433. len = 0; // fail
  15434. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  15435. ifp->nerr++;
  15436. MG_ERROR(("No descriptors available"));
  15437. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long)
  15438. // EMAC->EMACDMARIS);
  15439. len = 0; // fail
  15440. } else {
  15441. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  15442. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  15443. s_txdesc[s_txno][0] =
  15444. MG_BIT(20) | MG_BIT(28) | MG_BIT(29) | MG_BIT(30); // Chain,FS,LS,IC
  15445. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  15446. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15447. }
  15448. EMAC->EMACDMARIS = MG_BIT(2) | MG_BIT(5); // Clear any prior TU/UNF
  15449. EMAC->EMACTXPOLLD = 0; // and resume
  15450. return len;
  15451. (void) ifp;
  15452. }
  15453. static bool mg_tcpip_driver_tm4c_up(struct mg_tcpip_if *ifp) {
  15454. uint32_t bmsr = emac_read_phy(EPHY_ADDR, EPHYBMSR);
  15455. bool up = (bmsr & MG_BIT(2)) ? 1 : 0;
  15456. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15457. uint32_t sts = emac_read_phy(EPHY_ADDR, EPHYSTS);
  15458. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  15459. // if(link is slow or half) set flags otherwise
  15460. // reg = tmp
  15461. uint32_t emaccfg = EMAC->EMACCFG | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  15462. if (sts & MG_BIT(1)) emaccfg &= ~MG_BIT(14); // 10M
  15463. if ((sts & MG_BIT(2)) == 0) emaccfg &= ~MG_BIT(11); // Half-duplex
  15464. EMAC->EMACCFG = emaccfg; // IRQ handler does not fiddle with this register
  15465. MG_DEBUG(("Link is %uM %s-duplex", emaccfg & MG_BIT(14) ? 100 : 10,
  15466. emaccfg & MG_BIT(11) ? "full" : "half"));
  15467. }
  15468. return up;
  15469. }
  15470. void EMAC0_IRQHandler(void);
  15471. static uint32_t s_rxno;
  15472. void EMAC0_IRQHandler(void) {
  15473. if (EMAC->EMACDMARIS & MG_BIT(6)) { // Frame received, loop
  15474. EMAC->EMACDMARIS = MG_BIT(16) | MG_BIT(6); // Clear flag
  15475. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  15476. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  15477. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) == (MG_BIT(8) | MG_BIT(9))) &&
  15478. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  15479. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  15480. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  15481. // EMAC->EMACDMARIS);
  15482. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  15483. }
  15484. s_rxdesc[s_rxno][0] = MG_BIT(31);
  15485. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15486. }
  15487. }
  15488. EMAC->EMACDMARIS = MG_BIT(7); // Clear possible RU while processing
  15489. EMAC->EMACRXPOLLD = 0; // and resume RX
  15490. }
  15491. struct mg_tcpip_driver mg_tcpip_driver_tm4c = {mg_tcpip_driver_tm4c_init,
  15492. mg_tcpip_driver_tm4c_tx, NULL,
  15493. mg_tcpip_driver_tm4c_up};
  15494. #endif
  15495. #ifdef MG_ENABLE_LINES
  15496. #line 1 "src/drivers/w5500.c"
  15497. #endif
  15498. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5500) && MG_ENABLE_DRIVER_W5500
  15499. enum { W5500_CR = 0, W5500_S0 = 1, W5500_TX0 = 2, W5500_RX0 = 3 };
  15500. static void w5500_txn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr,
  15501. bool wr, void *buf, size_t len) {
  15502. size_t i;
  15503. uint8_t *p = (uint8_t *) buf;
  15504. uint8_t cmd[] = {(uint8_t) (addr >> 8), (uint8_t) (addr & 255),
  15505. (uint8_t) ((block << 3) | (wr ? 4 : 0))};
  15506. s->begin(s->spi);
  15507. for (i = 0; i < sizeof(cmd); i++) s->txn(s->spi, cmd[i]);
  15508. for (i = 0; i < len; i++) {
  15509. uint8_t r = s->txn(s->spi, p[i]);
  15510. if (!wr) p[i] = r;
  15511. }
  15512. s->end(s->spi);
  15513. }
  15514. // clang-format off
  15515. 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); }
  15516. 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); }
  15517. 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)); }
  15518. 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); }
  15519. 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; }
  15520. 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]); }
  15521. // clang-format on
  15522. static size_t w5500_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  15523. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15524. uint16_t r = 0, n = 0, len = (uint16_t) buflen, n2; // Read recv len
  15525. while ((n2 = w5500_r2(s, W5500_S0, 0x26)) > n) n = n2; // Until it is stable
  15526. // printf("RSR: %d\n", (int) n);
  15527. if (n > 0) {
  15528. uint16_t ptr = w5500_r2(s, W5500_S0, 0x28); // Get read pointer
  15529. n = w5500_r2(s, W5500_RX0, ptr); // Read frame length
  15530. if (n <= len + 2 && n > 1) {
  15531. r = (uint16_t) (n - 2);
  15532. w5500_rn(s, W5500_RX0, (uint16_t) (ptr + 2), buf, r);
  15533. }
  15534. w5500_w2(s, W5500_S0, 0x28, (uint16_t) (ptr + n)); // Advance read pointer
  15535. w5500_w1(s, W5500_S0, 1, 0x40); // Sock0 CR -> RECV
  15536. // printf(" RX_RD: tot=%u n=%u r=%u\n", n2, n, r);
  15537. }
  15538. return r;
  15539. }
  15540. static size_t w5500_tx(const void *buf, size_t buflen,
  15541. struct mg_tcpip_if *ifp) {
  15542. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15543. uint16_t i, ptr, n = 0, len = (uint16_t) buflen;
  15544. while (n < len) n = w5500_r2(s, W5500_S0, 0x20); // Wait for space
  15545. ptr = w5500_r2(s, W5500_S0, 0x24); // Get write pointer
  15546. w5500_wn(s, W5500_TX0, ptr, (void *) buf, len); // Write data
  15547. w5500_w2(s, W5500_S0, 0x24, (uint16_t) (ptr + len)); // Advance write pointer
  15548. w5500_w1(s, W5500_S0, 1, 0x20); // Sock0 CR -> SEND
  15549. for (i = 0; i < 40; i++) {
  15550. uint8_t ir = w5500_r1(s, W5500_S0, 2); // Read S0 IR
  15551. if (ir == 0) continue;
  15552. // printf("IR %d, len=%d, free=%d, ptr %d\n", ir, (int) len, (int) n, ptr);
  15553. w5500_w1(s, W5500_S0, 2, ir); // Write S0 IR: clear it!
  15554. if (ir & 8) len = 0; // Timeout. Report error
  15555. if (ir & (16 | 8)) break; // Stop on SEND_OK or timeout
  15556. }
  15557. return len;
  15558. }
  15559. static bool w5500_init(struct mg_tcpip_if *ifp) {
  15560. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  15561. s->end(s->spi);
  15562. w5500_w1(s, W5500_CR, 0, 0x80); // Reset chip: CR -> 0x80
  15563. w5500_w1(s, W5500_CR, 0x2e, 0); // CR PHYCFGR -> reset
  15564. w5500_w1(s, W5500_CR, 0x2e, 0xf8); // CR PHYCFGR -> set
  15565. // w5500_wn(s, W5500_CR, 9, s->mac, 6); // Set source MAC
  15566. w5500_w1(s, W5500_S0, 0x1e, 16); // Sock0 RX buf size
  15567. w5500_w1(s, W5500_S0, 0x1f, 16); // Sock0 TX buf size
  15568. w5500_w1(s, W5500_S0, 0, 4); // Sock0 MR -> MACRAW
  15569. w5500_w1(s, W5500_S0, 1, 1); // Sock0 CR -> OPEN
  15570. return w5500_r1(s, W5500_S0, 3) == 0x42; // Sock0 SR == MACRAW
  15571. }
  15572. static bool w5500_up(struct mg_tcpip_if *ifp) {
  15573. struct mg_tcpip_spi *spi = (struct mg_tcpip_spi *) ifp->driver_data;
  15574. uint8_t phycfgr = w5500_r1(spi, W5500_CR, 0x2e);
  15575. return phycfgr & 1; // Bit 0 of PHYCFGR is LNK (0 - down, 1 - up)
  15576. }
  15577. struct mg_tcpip_driver mg_tcpip_driver_w5500 = {w5500_init, w5500_tx, w5500_rx,
  15578. w5500_up};
  15579. #endif
  15580. #ifdef MG_ENABLE_LINES
  15581. #line 1 "src/drivers/xmc.c"
  15582. #endif
  15583. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC
  15584. struct ETH_GLOBAL_TypeDef {
  15585. volatile uint32_t MAC_CONFIGURATION, MAC_FRAME_FILTER, HASH_TABLE_HIGH,
  15586. HASH_TABLE_LOW, GMII_ADDRESS, GMII_DATA, FLOW_CONTROL, VLAN_TAG, VERSION,
  15587. DEBUG, REMOTE_WAKE_UP_FRAME_FILTER, PMT_CONTROL_STATUS, RESERVED[2],
  15588. INTERRUPT_STATUS, INTERRUPT_MASK, MAC_ADDRESS0_HIGH, MAC_ADDRESS0_LOW,
  15589. MAC_ADDRESS1_HIGH, MAC_ADDRESS1_LOW, MAC_ADDRESS2_HIGH, MAC_ADDRESS2_LOW,
  15590. MAC_ADDRESS3_HIGH, MAC_ADDRESS3_LOW, RESERVED1[40], MMC_CONTROL,
  15591. MMC_RECEIVE_INTERRUPT, MMC_TRANSMIT_INTERRUPT, MMC_RECEIVE_INTERRUPT_MASK,
  15592. MMC_TRANSMIT_INTERRUPT_MASK, TX_STATISTICS[26], RESERVED2,
  15593. RX_STATISTICS_1[26], RESERVED3[6], MMC_IPC_RECEIVE_INTERRUPT_MASK,
  15594. RESERVED4, MMC_IPC_RECEIVE_INTERRUPT, RESERVED5, RX_STATISTICS_2[30],
  15595. RESERVED7[286], TIMESTAMP_CONTROL, SUB_SECOND_INCREMENT,
  15596. SYSTEM_TIME_SECONDS, SYSTEM_TIME_NANOSECONDS,
  15597. SYSTEM_TIME_SECONDS_UPDATE, SYSTEM_TIME_NANOSECONDS_UPDATE,
  15598. TIMESTAMP_ADDEND, TARGET_TIME_SECONDS, TARGET_TIME_NANOSECONDS,
  15599. SYSTEM_TIME_HIGHER_WORD_SECONDS, TIMESTAMP_STATUS,
  15600. PPS_CONTROL, RESERVED8[564], BUS_MODE, TRANSMIT_POLL_DEMAND,
  15601. RECEIVE_POLL_DEMAND, RECEIVE_DESCRIPTOR_LIST_ADDRESS,
  15602. TRANSMIT_DESCRIPTOR_LIST_ADDRESS, STATUS, OPERATION_MODE,
  15603. INTERRUPT_ENABLE, MISSED_FRAME_AND_BUFFER_OVERFLOW_COUNTER,
  15604. RECEIVE_INTERRUPT_WATCHDOG_TIMER, RESERVED9, AHB_STATUS,
  15605. RESERVED10[6], CURRENT_HOST_TRANSMIT_DESCRIPTOR,
  15606. CURRENT_HOST_RECEIVE_DESCRIPTOR, CURRENT_HOST_TRANSMIT_BUFFER_ADDRESS,
  15607. CURRENT_HOST_RECEIVE_BUFFER_ADDRESS, HW_FEATURE;
  15608. };
  15609. #undef ETH0
  15610. #define ETH0 ((struct ETH_GLOBAL_TypeDef*) 0x5000C000UL)
  15611. #define ETH_PKT_SIZE 1536 // Max frame size
  15612. #define ETH_DESC_CNT 4 // Descriptors count
  15613. #define ETH_DS 4 // Descriptor size (words)
  15614. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15615. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15616. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15617. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15618. static uint8_t s_txno; // Current TX descriptor
  15619. static uint8_t s_rxno; // Current RX descriptor
  15620. static struct mg_tcpip_if *s_ifp; // MIP interface
  15621. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  15622. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  15623. ETH0->GMII_ADDRESS = (ETH0->GMII_ADDRESS & 0x3c) |
  15624. ((uint32_t)addr << 11) |
  15625. ((uint32_t)reg << 6) | 1;
  15626. while ((ETH0->GMII_ADDRESS & 1) != 0) (void) 0;
  15627. return (uint16_t)(ETH0->GMII_DATA & 0xffff);
  15628. }
  15629. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15630. ETH0->GMII_DATA = val;
  15631. ETH0->GMII_ADDRESS = (ETH0->GMII_ADDRESS & 0x3c) |
  15632. ((uint32_t)addr << 11) |
  15633. ((uint32_t)reg << 6) | 3;
  15634. while ((ETH0->GMII_ADDRESS & 1) != 0) (void) 0;
  15635. }
  15636. static uint32_t get_clock_rate(struct mg_tcpip_driver_xmc_data *d) {
  15637. if (d->mdc_cr == -1) {
  15638. // assume ETH clock is 60MHz by default
  15639. // then according to 13.2.8.1, we need to set value 3
  15640. return 3;
  15641. }
  15642. return d->mdc_cr;
  15643. }
  15644. static bool mg_tcpip_driver_xmc_init(struct mg_tcpip_if *ifp) {
  15645. struct mg_tcpip_driver_xmc_data *d =
  15646. (struct mg_tcpip_driver_xmc_data *) ifp->driver_data;
  15647. s_ifp = ifp;
  15648. // reset MAC
  15649. ETH0->BUS_MODE |= 1;
  15650. while (ETH0->BUS_MODE & 1) (void) 0;
  15651. // set clock rate
  15652. ETH0->GMII_ADDRESS = get_clock_rate(d) << 2;
  15653. // init phy
  15654. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15655. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  15656. // configure MAC: DO, DM, FES, TC
  15657. ETH0->MAC_CONFIGURATION = MG_BIT(13) | MG_BIT(11) | MG_BIT(14) | MG_BIT(24);
  15658. // set the MAC address
  15659. ETH0->MAC_ADDRESS0_HIGH = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  15660. ETH0->MAC_ADDRESS0_LOW =
  15661. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  15662. // Configure the receive filter
  15663. ETH0->MAC_FRAME_FILTER = MG_BIT(10) | MG_BIT(2); // HFP, HMC
  15664. // Disable flow control
  15665. ETH0->FLOW_CONTROL = 0;
  15666. // Enable store and forward mode
  15667. ETH0->OPERATION_MODE = MG_BIT(25) | MG_BIT(21); // RSF, TSF
  15668. // Configure DMA bus mode (AAL, USP, RPBL, PBL)
  15669. ETH0->BUS_MODE = MG_BIT(25) | MG_BIT(23) | (32 << 17) | (32 << 8);
  15670. // init RX descriptors
  15671. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15672. s_rxdesc[i][0] = MG_BIT(31); // OWN descriptor
  15673. s_rxdesc[i][1] = MG_BIT(14) | ETH_PKT_SIZE;
  15674. s_rxdesc[i][2] = (uint32_t) s_rxbuf[i];
  15675. if (i == ETH_DESC_CNT - 1) {
  15676. s_rxdesc[i][3] = (uint32_t) &s_rxdesc[0][0];
  15677. } else {
  15678. s_rxdesc[i][3] = (uint32_t) &s_rxdesc[i + 1][0];
  15679. }
  15680. }
  15681. ETH0->RECEIVE_DESCRIPTOR_LIST_ADDRESS = (uint32_t) &s_rxdesc[0][0];
  15682. // init TX descriptors
  15683. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15684. s_txdesc[i][0] = MG_BIT(30) | MG_BIT(20);
  15685. s_txdesc[i][2] = (uint32_t) s_txbuf[i];
  15686. if (i == ETH_DESC_CNT - 1) {
  15687. s_txdesc[i][3] = (uint32_t) &s_txdesc[0][0];
  15688. } else {
  15689. s_txdesc[i][3] = (uint32_t) &s_txdesc[i + 1][0];
  15690. }
  15691. }
  15692. ETH0->TRANSMIT_DESCRIPTOR_LIST_ADDRESS = (uint32_t) &s_txdesc[0][0];
  15693. // Clear interrupts
  15694. ETH0->STATUS = 0xFFFFFFFF;
  15695. // Disable MAC interrupts
  15696. ETH0->MMC_TRANSMIT_INTERRUPT_MASK = 0xFFFFFFFF;
  15697. ETH0->MMC_RECEIVE_INTERRUPT_MASK = 0xFFFFFFFF;
  15698. ETH0->MMC_IPC_RECEIVE_INTERRUPT_MASK = 0xFFFFFFFF;
  15699. ETH0->INTERRUPT_MASK = MG_BIT(9) | MG_BIT(3); // TSIM, PMTIM
  15700. //Enable interrupts (NIE, RIE, TIE)
  15701. ETH0->INTERRUPT_ENABLE = MG_BIT(16) | MG_BIT(6) | MG_BIT(0);
  15702. // Enable MAC transmission and reception (TE, RE)
  15703. ETH0->MAC_CONFIGURATION |= MG_BIT(3) | MG_BIT(2);
  15704. // Enable DMA transmission and reception (ST, SR)
  15705. ETH0->OPERATION_MODE |= MG_BIT(13) | MG_BIT(1);
  15706. return true;
  15707. }
  15708. static size_t mg_tcpip_driver_xmc_tx(const void *buf, size_t len,
  15709. struct mg_tcpip_if *ifp) {
  15710. if (len > sizeof(s_txbuf[s_txno])) {
  15711. MG_ERROR(("Frame too big, %ld", (long) len));
  15712. len = 0; // Frame is too big
  15713. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  15714. ifp->nerr++;
  15715. MG_ERROR(("No free descriptors"));
  15716. len = 0; // All descriptors are busy, fail
  15717. } else {
  15718. memcpy(s_txbuf[s_txno], buf, len);
  15719. s_txdesc[s_txno][1] = len;
  15720. // Table 13-19 Transmit Descriptor Word 0 (IC, LS, FS, TCH)
  15721. s_txdesc[s_txno][0] = MG_BIT(30) | MG_BIT(29) | MG_BIT(28) | MG_BIT(20);
  15722. s_txdesc[s_txno][0] |= MG_BIT(31); // OWN bit: handle control to DMA
  15723. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15724. }
  15725. // Resume processing
  15726. ETH0->STATUS = MG_BIT(2); // clear Transmit unavailable
  15727. ETH0->TRANSMIT_POLL_DEMAND = 0;
  15728. return len;
  15729. }
  15730. static bool mg_tcpip_driver_xmc_up(struct mg_tcpip_if *ifp) {
  15731. struct mg_tcpip_driver_xmc_data *d =
  15732. (struct mg_tcpip_driver_xmc_data *) ifp->driver_data;
  15733. uint8_t speed = MG_PHY_SPEED_10M;
  15734. bool up = false, full_duplex = false;
  15735. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15736. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  15737. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15738. MG_DEBUG(("Link is %uM %s-duplex", speed == MG_PHY_SPEED_10M ? 10 : 100,
  15739. full_duplex ? "full" : "half"));
  15740. }
  15741. return up;
  15742. }
  15743. void ETH0_IRQHandler(void);
  15744. void ETH0_IRQHandler(void) {
  15745. uint32_t irq_status = ETH0->STATUS;
  15746. // check if a frame was received
  15747. if (irq_status & MG_BIT(6)) {
  15748. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  15749. if ((s_rxdesc[s_rxno][0] & MG_BIT(31)) == 0) {
  15750. size_t len = (s_rxdesc[s_rxno][0] & 0x3fff0000) >> 16;
  15751. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  15752. s_rxdesc[s_rxno][0] = MG_BIT(31); // OWN bit: handle control to DMA
  15753. // Resume processing
  15754. ETH0->STATUS = MG_BIT(7) | MG_BIT(6); // clear RU and RI
  15755. ETH0->RECEIVE_POLL_DEMAND = 0;
  15756. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15757. }
  15758. }
  15759. ETH0->STATUS = MG_BIT(6);
  15760. }
  15761. // clear Successful transmission interrupt
  15762. if (irq_status & 1) {
  15763. ETH0->STATUS = 1;
  15764. }
  15765. // clear normal interrupt
  15766. if (irq_status & MG_BIT(16)) {
  15767. ETH0->STATUS = MG_BIT(16);
  15768. }
  15769. }
  15770. struct mg_tcpip_driver mg_tcpip_driver_xmc = {
  15771. mg_tcpip_driver_xmc_init, mg_tcpip_driver_xmc_tx, NULL,
  15772. mg_tcpip_driver_xmc_up};
  15773. #endif
  15774. #ifdef MG_ENABLE_LINES
  15775. #line 1 "src/drivers/xmc7.c"
  15776. #endif
  15777. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7
  15778. struct ETH_Type {
  15779. volatile uint32_t CTL, STATUS, RESERVED[1022], NETWORK_CONTROL,
  15780. NETWORK_CONFIG, NETWORK_STATUS, USER_IO_REGISTER, DMA_CONFIG,
  15781. TRANSMIT_STATUS, RECEIVE_Q_PTR, TRANSMIT_Q_PTR, RECEIVE_STATUS,
  15782. INT_STATUS, INT_ENABLE, INT_DISABLE, INT_MASK, PHY_MANAGEMENT, PAUSE_TIME,
  15783. TX_PAUSE_QUANTUM, PBUF_TXCUTTHRU, PBUF_RXCUTTHRU, JUMBO_MAX_LENGTH,
  15784. EXTERNAL_FIFO_INTERFACE, RESERVED1, AXI_MAX_PIPELINE, RSC_CONTROL,
  15785. INT_MODERATION, SYS_WAKE_TIME, RESERVED2[7], HASH_BOTTOM, HASH_TOP,
  15786. SPEC_ADD1_BOTTOM, SPEC_ADD1_TOP, SPEC_ADD2_BOTTOM, SPEC_ADD2_TOP,
  15787. SPEC_ADD3_BOTTOM, SPEC_ADD3_TOP, SPEC_ADD4_BOTTOM, SPEC_ADD4_TOP,
  15788. SPEC_TYPE1, SPEC_TYPE2, SPEC_TYPE3, SPEC_TYPE4, WOL_REGISTER,
  15789. STRETCH_RATIO, STACKED_VLAN, TX_PFC_PAUSE, MASK_ADD1_BOTTOM,
  15790. MASK_ADD1_TOP, DMA_ADDR_OR_MASK, RX_PTP_UNICAST, TX_PTP_UNICAST,
  15791. TSU_NSEC_CMP, TSU_SEC_CMP, TSU_MSB_SEC_CMP, TSU_PTP_TX_MSB_SEC,
  15792. TSU_PTP_RX_MSB_SEC, TSU_PEER_TX_MSB_SEC, TSU_PEER_RX_MSB_SEC,
  15793. DPRAM_FILL_DBG, REVISION_REG, OCTETS_TXED_BOTTOM, OCTETS_TXED_TOP,
  15794. FRAMES_TXED_OK, BROADCAST_TXED, MULTICAST_TXED, PAUSE_FRAMES_TXED,
  15795. FRAMES_TXED_64, FRAMES_TXED_65, FRAMES_TXED_128, FRAMES_TXED_256,
  15796. FRAMES_TXED_512, FRAMES_TXED_1024, FRAMES_TXED_1519, TX_UNDERRUNS,
  15797. SINGLE_COLLISIONS, MULTIPLE_COLLISIONS, EXCESSIVE_COLLISIONS,
  15798. LATE_COLLISIONS, DEFERRED_FRAMES, CRS_ERRORS, OCTETS_RXED_BOTTOM,
  15799. OCTETS_RXED_TOP, FRAMES_RXED_OK, BROADCAST_RXED, MULTICAST_RXED,
  15800. PAUSE_FRAMES_RXED, FRAMES_RXED_64, FRAMES_RXED_65, FRAMES_RXED_128,
  15801. FRAMES_RXED_256, FRAMES_RXED_512, FRAMES_RXED_1024, FRAMES_RXED_1519,
  15802. UNDERSIZE_FRAMES, EXCESSIVE_RX_LENGTH, RX_JABBERS, FCS_ERRORS,
  15803. RX_LENGTH_ERRORS, RX_SYMBOL_ERRORS, ALIGNMENT_ERRORS, RX_RESOURCE_ERRORS,
  15804. RX_OVERRUNS, RX_IP_CK_ERRORS, RX_TCP_CK_ERRORS, RX_UDP_CK_ERRORS,
  15805. AUTO_FLUSHED_PKTS, RESERVED3, TSU_TIMER_INCR_SUB_NSEC, TSU_TIMER_MSB_SEC,
  15806. TSU_STROBE_MSB_SEC, TSU_STROBE_SEC, TSU_STROBE_NSEC, TSU_TIMER_SEC,
  15807. TSU_TIMER_NSEC, TSU_TIMER_ADJUST, TSU_TIMER_INCR, TSU_PTP_TX_SEC,
  15808. TSU_PTP_TX_NSEC, TSU_PTP_RX_SEC, TSU_PTP_RX_NSEC, TSU_PEER_TX_SEC,
  15809. TSU_PEER_TX_NSEC, TSU_PEER_RX_SEC, TSU_PEER_RX_NSEC, PCS_CONTROL,
  15810. PCS_STATUS, RESERVED4[2], PCS_AN_ADV, PCS_AN_LP_BASE, PCS_AN_EXP,
  15811. PCS_AN_NP_TX, PCS_AN_LP_NP, RESERVED5[6], PCS_AN_EXT_STATUS, RESERVED6[8],
  15812. TX_PAUSE_QUANTUM1, TX_PAUSE_QUANTUM2, TX_PAUSE_QUANTUM3, RESERVED7,
  15813. RX_LPI, RX_LPI_TIME, TX_LPI, TX_LPI_TIME, DESIGNCFG_DEBUG1,
  15814. DESIGNCFG_DEBUG2, DESIGNCFG_DEBUG3, DESIGNCFG_DEBUG4, DESIGNCFG_DEBUG5,
  15815. DESIGNCFG_DEBUG6, DESIGNCFG_DEBUG7, DESIGNCFG_DEBUG8, DESIGNCFG_DEBUG9,
  15816. DESIGNCFG_DEBUG10, RESERVED8[22], SPEC_ADD5_BOTTOM, SPEC_ADD5_TOP,
  15817. RESERVED9[60], SPEC_ADD36_BOTTOM, SPEC_ADD36_TOP, INT_Q1_STATUS,
  15818. INT_Q2_STATUS, INT_Q3_STATUS, RESERVED10[11], INT_Q15_STATUS, RESERVED11,
  15819. TRANSMIT_Q1_PTR, TRANSMIT_Q2_PTR, TRANSMIT_Q3_PTR, RESERVED12[11],
  15820. TRANSMIT_Q15_PTR, RESERVED13, RECEIVE_Q1_PTR, RECEIVE_Q2_PTR,
  15821. RECEIVE_Q3_PTR, RESERVED14[3], RECEIVE_Q7_PTR, RESERVED15,
  15822. DMA_RXBUF_SIZE_Q1, DMA_RXBUF_SIZE_Q2, DMA_RXBUF_SIZE_Q3, RESERVED16[3],
  15823. DMA_RXBUF_SIZE_Q7, CBS_CONTROL, CBS_IDLESLOPE_Q_A, CBS_IDLESLOPE_Q_B,
  15824. UPPER_TX_Q_BASE_ADDR, TX_BD_CONTROL, RX_BD_CONTROL, UPPER_RX_Q_BASE_ADDR,
  15825. RESERVED17[2], HIDDEN_REG0, HIDDEN_REG1, HIDDEN_REG2, HIDDEN_REG3,
  15826. RESERVED18[2], HIDDEN_REG4, HIDDEN_REG5;
  15827. };
  15828. #define ETH0 ((struct ETH_Type *) 0x40490000)
  15829. #define ETH_PKT_SIZE 1536 // Max frame size
  15830. #define ETH_DESC_CNT 4 // Descriptors count
  15831. #define ETH_DS 2 // Descriptor size (words)
  15832. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15833. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  15834. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  15835. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  15836. static uint8_t s_txno; // Current TX descriptor
  15837. static uint8_t s_rxno; // Current RX descriptor
  15838. static struct mg_tcpip_if *s_ifp; // MIP interface
  15839. enum { MG_PHY_ADDR = 0, MG_PHYREG_BCR = 0, MG_PHYREG_BSR = 1 };
  15840. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  15841. // WRITE1, READ OPERATION, PHY, REG, WRITE10
  15842. ETH0->PHY_MANAGEMENT = MG_BIT(30) | MG_BIT(29) | ((addr & 0xf) << 24) |
  15843. ((reg & 0x1f) << 18) | MG_BIT(17);
  15844. while ((ETH0->NETWORK_STATUS & MG_BIT(2)) == 0) (void) 0;
  15845. return ETH0->PHY_MANAGEMENT & 0xffff;
  15846. }
  15847. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  15848. ETH0->PHY_MANAGEMENT = MG_BIT(30) | MG_BIT(28) | ((addr & 0xf) << 24) |
  15849. ((reg & 0x1f) << 18) | MG_BIT(17) | val;
  15850. while ((ETH0->NETWORK_STATUS & MG_BIT(2)) == 0) (void) 0;
  15851. }
  15852. static uint32_t get_clock_rate(struct mg_tcpip_driver_xmc7_data *d) {
  15853. // see ETH0 -> NETWORK_CONFIG register
  15854. (void) d;
  15855. return 3;
  15856. }
  15857. static bool mg_tcpip_driver_xmc7_init(struct mg_tcpip_if *ifp) {
  15858. struct mg_tcpip_driver_xmc7_data *d =
  15859. (struct mg_tcpip_driver_xmc7_data *) ifp->driver_data;
  15860. s_ifp = ifp;
  15861. // enable controller, set RGMII mode
  15862. ETH0->CTL = MG_BIT(31) | 2;
  15863. uint32_t cr = get_clock_rate(d);
  15864. // set NSP change, ignore RX FCS, data bus width, clock rate
  15865. // frame length 1536, full duplex, speed
  15866. ETH0->NETWORK_CONFIG = MG_BIT(29) | MG_BIT(26) | MG_BIT(21) |
  15867. ((cr & 7) << 18) | MG_BIT(8) | MG_BIT(4) |
  15868. MG_BIT(1) | MG_BIT(0);
  15869. // config DMA settings: Force TX burst, Discard on Error, set RX buffer size
  15870. // to 1536, TX_PBUF_SIZE, RX_PBUF_SIZE, AMBA_BURST_LENGTH
  15871. ETH0->DMA_CONFIG =
  15872. MG_BIT(26) | MG_BIT(24) | (0x18 << 16) | MG_BIT(10) | (3 << 8) | 4;
  15873. // initialize descriptors
  15874. for (int i = 0; i < ETH_DESC_CNT; i++) {
  15875. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i];
  15876. if (i == ETH_DESC_CNT - 1) {
  15877. s_rxdesc[i][0] |= MG_BIT(1); // mark last descriptor
  15878. }
  15879. s_txdesc[i][0] = (uint32_t) s_txbuf[i];
  15880. s_txdesc[i][1] = MG_BIT(31); // OWN descriptor
  15881. if (i == ETH_DESC_CNT - 1) {
  15882. s_txdesc[i][1] |= MG_BIT(30); // mark last descriptor
  15883. }
  15884. }
  15885. ETH0->RECEIVE_Q_PTR = (uint32_t) s_rxdesc;
  15886. ETH0->TRANSMIT_Q_PTR = (uint32_t) s_txdesc;
  15887. // disable other queues
  15888. ETH0->TRANSMIT_Q2_PTR = 1;
  15889. ETH0->TRANSMIT_Q1_PTR = 1;
  15890. ETH0->RECEIVE_Q2_PTR = 1;
  15891. ETH0->RECEIVE_Q1_PTR = 1;
  15892. // enable interrupts (TX and RX complete)
  15893. ETH0->INT_ENABLE = MG_BIT(7) | MG_BIT(1);
  15894. // set MAC address
  15895. ETH0->SPEC_ADD1_BOTTOM =
  15896. ifp->mac[3] << 24 | ifp->mac[2] << 16 | ifp->mac[1] << 8 | ifp->mac[0];
  15897. ETH0->SPEC_ADD1_TOP = ifp->mac[5] << 8 | ifp->mac[4];
  15898. // enable MDIO, TX, RX
  15899. ETH0->NETWORK_CONTROL = MG_BIT(4) | MG_BIT(3) | MG_BIT(2);
  15900. // start transmission
  15901. ETH0->NETWORK_CONTROL |= MG_BIT(9);
  15902. // init phy
  15903. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15904. mg_phy_init(&phy, d->phy_addr, MG_PHY_CLOCKS_MAC);
  15905. (void) d;
  15906. return true;
  15907. }
  15908. static size_t mg_tcpip_driver_xmc7_tx(const void *buf, size_t len,
  15909. struct mg_tcpip_if *ifp) {
  15910. if (len > sizeof(s_txbuf[s_txno])) {
  15911. MG_ERROR(("Frame too big, %ld", (long) len));
  15912. len = 0; // Frame is too big
  15913. } else if (((s_txdesc[s_txno][1] & MG_BIT(31)) == 0)) {
  15914. ifp->nerr++;
  15915. MG_ERROR(("No free descriptors"));
  15916. len = 0; // All descriptors are busy, fail
  15917. } else {
  15918. memcpy(s_txbuf[s_txno], buf, len);
  15919. s_txdesc[s_txno][1] = (s_txno == ETH_DESC_CNT - 1 ? MG_BIT(30) : 0) |
  15920. MG_BIT(15) | len; // Last buffer and length
  15921. ETH0->NETWORK_CONTROL |= MG_BIT(9); // enable transmission
  15922. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  15923. }
  15924. MG_DSB();
  15925. ETH0->TRANSMIT_STATUS = ETH0->TRANSMIT_STATUS;
  15926. ETH0->NETWORK_CONTROL |= MG_BIT(9); // enable transmission
  15927. return len;
  15928. }
  15929. static bool mg_tcpip_driver_xmc7_up(struct mg_tcpip_if *ifp) {
  15930. struct mg_tcpip_driver_xmc7_data *d =
  15931. (struct mg_tcpip_driver_xmc7_data *) ifp->driver_data;
  15932. uint8_t speed = MG_PHY_SPEED_10M;
  15933. bool up = false, full_duplex = false;
  15934. struct mg_phy phy = {eth_read_phy, eth_write_phy};
  15935. up = mg_phy_up(&phy, d->phy_addr, &full_duplex, &speed);
  15936. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  15937. if (speed == MG_PHY_SPEED_1000M) {
  15938. ETH0->NETWORK_CONFIG |= MG_BIT(10);
  15939. }
  15940. MG_DEBUG(("Link is %uM %s-duplex",
  15941. speed == MG_PHY_SPEED_10M ? 10 :
  15942. (speed == MG_PHY_SPEED_100M ? 100 : 1000),
  15943. full_duplex ? "full" : "half"));
  15944. }
  15945. (void) d;
  15946. return up;
  15947. }
  15948. void ETH_IRQHandler(void) {
  15949. uint32_t irq_status = ETH0->INT_STATUS;
  15950. if (irq_status & MG_BIT(1)) {
  15951. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  15952. if (s_rxdesc[s_rxno][0] & MG_BIT(0)) {
  15953. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  15954. //MG_INFO(("Receive complete: %ld bytes", len));
  15955. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  15956. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // OWN bit: handle control to DMA
  15957. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  15958. }
  15959. }
  15960. }
  15961. ETH0->INT_STATUS = irq_status;
  15962. }
  15963. struct mg_tcpip_driver mg_tcpip_driver_xmc7 = {mg_tcpip_driver_xmc7_init,
  15964. mg_tcpip_driver_xmc7_tx, NULL,
  15965. mg_tcpip_driver_xmc7_up};
  15966. #endif