mongoose.c 513 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297
  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. // Flash can be written only if it is erased. Erased flash is 0xff (all bits 1)
  220. // Writes must be mg_flash_write_align() - aligned. Thus if we want to save an
  221. // object, we pad it at the end for alignment.
  222. //
  223. // Objects in the flash sector are stored sequentially:
  224. // | 32-bit size | 32-bit KEY | ..data.. | ..pad.. | 32-bit size | ......
  225. //
  226. // In order to get to the next object, read its size, then align up.
  227. // Traverse the list of saved objects
  228. size_t mg_flash_next(char *p, char *end, uint32_t *key, size_t *size) {
  229. size_t aligned_size = 0, align = mg_flash_write_align(), left = end - p;
  230. uint32_t *p32 = (uint32_t *) p, min_size = sizeof(uint32_t) * 2;
  231. if (p32[0] != 0xffffffff && left > MG_ROUND_UP(min_size, align)) {
  232. if (size) *size = (size_t) p32[0];
  233. if (key) *key = p32[1];
  234. aligned_size = MG_ROUND_UP(p32[0] + sizeof(uint32_t) * 2, align);
  235. if (left < aligned_size) aligned_size = 0; // Out of bounds, fail
  236. }
  237. return aligned_size;
  238. }
  239. // Return the last sector of Bank 2
  240. static char *flash_last_sector(void) {
  241. size_t ss = mg_flash_sector_size(), size = mg_flash_size();
  242. char *base = (char *) mg_flash_start(), *last = base + size - ss;
  243. if (mg_flash_bank() == 2) last -= size / 2;
  244. return last;
  245. }
  246. // Find a saved object with a given key
  247. bool mg_flash_load(void *sector, uint32_t key, void *buf, size_t len) {
  248. char *base = (char *) mg_flash_start(), *s = (char *) sector, *res = NULL;
  249. size_t ss = mg_flash_sector_size(), ofs = 0, n, sz;
  250. bool ok = false;
  251. if (s == NULL) s = flash_last_sector();
  252. if (s < base || s >= base + mg_flash_size()) {
  253. MG_ERROR(("%p is outsize of flash", sector));
  254. } else if (((s - base) % ss) != 0) {
  255. MG_ERROR(("%p is not a sector boundary", sector));
  256. } else {
  257. uint32_t k, scanned = 0;
  258. while ((n = mg_flash_next(s + ofs, s + ss, &k, &sz)) > 0) {
  259. // MG_DEBUG((" > obj %lu, ofs %lu, key %x/%x", scanned, ofs, k, key));
  260. // mg_hexdump(s + ofs, n);
  261. if (k == key && sz == len) {
  262. res = s + ofs + sizeof(uint32_t) * 2;
  263. memcpy(buf, res, len); // Copy object
  264. ok = true; // Keep scanning for the newer versions of it
  265. }
  266. ofs += n, scanned++;
  267. }
  268. MG_DEBUG(("Scanned %u objects, key %x is @ %p", scanned, key, res));
  269. }
  270. return ok;
  271. }
  272. // For all saved objects in the sector, delete old versions of objects
  273. static void mg_flash_sector_cleanup(char *sector) {
  274. // Buffer all saved objects into an IO buffer (backed by RAM)
  275. // erase sector, and re-save them.
  276. struct mg_iobuf io = {0, 0, 0, 2048};
  277. size_t ss = mg_flash_sector_size();
  278. size_t n, size, size2, ofs = 0, hs = sizeof(uint32_t) * 2;
  279. uint32_t key;
  280. // Traverse all objects
  281. MG_DEBUG(("Cleaning up sector %p", sector));
  282. while ((n = mg_flash_next(sector + ofs, sector + ss, &key, &size)) > 0) {
  283. // Delete an old copy of this object in the cache
  284. for (size_t o = 0; o < io.len; o += size2 + hs) {
  285. uint32_t k = *(uint32_t *) (io.buf + o + sizeof(uint32_t));
  286. size2 = *(uint32_t *) (io.buf + o);
  287. if (k == key) {
  288. mg_iobuf_del(&io, o, size2 + hs);
  289. break;
  290. }
  291. }
  292. // And add the new copy
  293. mg_iobuf_add(&io, io.len, sector + ofs, size + hs);
  294. ofs += n;
  295. }
  296. // All objects are cached in RAM now
  297. if (mg_flash_erase(sector)) { // Erase sector. If successful,
  298. for (ofs = 0; ofs < io.len; ofs += size + hs) { // Traverse cached objects
  299. size = *(uint32_t *) (io.buf + ofs);
  300. key = *(uint32_t *) (io.buf + ofs + sizeof(uint32_t));
  301. mg_flash_save(sector, key, io.buf + ofs + hs, size); // Save to flash
  302. }
  303. }
  304. mg_iobuf_free(&io);
  305. }
  306. // Save an object with a given key - append to the end of an object list
  307. bool mg_flash_save(void *sector, uint32_t key, const void *buf, size_t len) {
  308. char *base = (char *) mg_flash_start(), *s = (char *) sector;
  309. size_t ss = mg_flash_sector_size(), ofs = 0, n;
  310. bool ok = false;
  311. if (s == NULL) s = flash_last_sector();
  312. if (s < base || s >= base + mg_flash_size()) {
  313. MG_ERROR(("%p is outsize of flash", sector));
  314. } else if (((s - base) % ss) != 0) {
  315. MG_ERROR(("%p is not a sector boundary", sector));
  316. } else {
  317. char ab[mg_flash_write_align()]; // Aligned write block
  318. uint32_t hdr[2] = {(uint32_t) len, key};
  319. size_t needed = sizeof(hdr) + len;
  320. size_t needed_aligned = MG_ROUND_UP(needed, sizeof(ab));
  321. while ((n = mg_flash_next(s + ofs, s + ss, NULL, NULL)) > 0) ofs += n;
  322. // If there is not enough space left, cleanup sector and re-eval ofs
  323. if (ofs + needed_aligned > ss) {
  324. mg_flash_sector_cleanup(s);
  325. ofs = 0;
  326. while ((n = mg_flash_next(s + ofs, s + ss, NULL, NULL)) > 0) ofs += n;
  327. }
  328. if (ofs + needed_aligned <= ss) {
  329. // Enough space to save this object
  330. if (sizeof(ab) < sizeof(hdr)) {
  331. // Flash write granularity is 32 bit or less, write with no buffering
  332. ok = mg_flash_write(s + ofs, hdr, sizeof(hdr));
  333. if (ok) mg_flash_write(s + ofs + sizeof(hdr), buf, len);
  334. } else {
  335. // Flash granularity is sizeof(hdr) or more. We need to save in
  336. // 3 chunks: initial block, bulk, rest. This is because we have
  337. // two memory chunks to write: hdr and buf, on aligned boundaries.
  338. n = sizeof(ab) - sizeof(hdr); // Initial chunk that we write
  339. if (n > len) n = len; // is
  340. memset(ab, 0xff, sizeof(ab)); // initialized to all-one
  341. memcpy(ab, hdr, sizeof(hdr)); // contains the header (key + size)
  342. memcpy(ab + sizeof(hdr), buf, n); // and an initial part of buf
  343. MG_INFO(("saving initial block of %lu", sizeof(ab)));
  344. ok = mg_flash_write(s + ofs, ab, sizeof(ab));
  345. if (ok && len > n) {
  346. size_t n2 = MG_ROUND_DOWN(len - n, sizeof(ab));
  347. if (n2 > 0) {
  348. MG_INFO(("saving bulk, %lu", n2));
  349. ok = mg_flash_write(s + ofs + sizeof(ab), (char *) buf + n, n2);
  350. }
  351. if (ok && len > n) {
  352. size_t n3 = len - n - n2;
  353. if (n3 > sizeof(ab)) n3 = sizeof(ab);
  354. memset(ab, 0xff, sizeof(ab));
  355. memcpy(ab, (char *) buf + n + n2, n3);
  356. MG_INFO(("saving rest, %lu", n3));
  357. ok = mg_flash_write(s + ofs + sizeof(ab) + n2, ab, sizeof(ab));
  358. }
  359. }
  360. }
  361. MG_DEBUG(("Saved %lu/%lu bytes @ %p, key %x: %d", len, needed_aligned,
  362. s + ofs, key, ok));
  363. MG_DEBUG(("Sector space left: %lu bytes", ss - ofs - needed_aligned));
  364. } else {
  365. MG_ERROR(("Sector is full"));
  366. }
  367. }
  368. return ok;
  369. }
  370. #else
  371. bool mg_flash_save(void *sector, uint32_t key, const void *buf, size_t len) {
  372. (void) sector, (void) key, (void) buf, (void) len;
  373. return false;
  374. }
  375. bool mg_flash_load(void *sector, uint32_t key, void *buf, size_t len) {
  376. (void) sector, (void) key, (void) buf, (void) len;
  377. return false;
  378. }
  379. #endif
  380. #ifdef MG_ENABLE_LINES
  381. #line 1 "src/device_stm32h5.c"
  382. #endif
  383. #if MG_DEVICE == MG_DEVICE_STM32H5
  384. #define FLASH_BASE 0x40022000 // Base address of the flash controller
  385. #define FLASH_KEYR (FLASH_BASE + 0x4) // See RM0481 7.11
  386. #define FLASH_OPTKEYR (FLASH_BASE + 0xc)
  387. #define FLASH_OPTCR (FLASH_BASE + 0x1c)
  388. #define FLASH_NSSR (FLASH_BASE + 0x20)
  389. #define FLASH_NSCR (FLASH_BASE + 0x28)
  390. #define FLASH_NSCCR (FLASH_BASE + 0x30)
  391. #define FLASH_OPTSR_CUR (FLASH_BASE + 0x50)
  392. #define FLASH_OPTSR_PRG (FLASH_BASE + 0x54)
  393. void *mg_flash_start(void) {
  394. return (void *) 0x08000000;
  395. }
  396. size_t mg_flash_size(void) {
  397. return 2 * 1024 * 1024; // 2Mb
  398. }
  399. size_t mg_flash_sector_size(void) {
  400. return 8 * 1024; // 8k
  401. }
  402. size_t mg_flash_write_align(void) {
  403. return 16; // 128 bit
  404. }
  405. int mg_flash_bank(void) {
  406. return MG_REG(FLASH_OPTCR) & MG_BIT(31) ? 2 : 1;
  407. }
  408. static void flash_unlock(void) {
  409. static bool unlocked = false;
  410. if (unlocked == false) {
  411. MG_REG(FLASH_KEYR) = 0x45670123;
  412. MG_REG(FLASH_KEYR) = 0Xcdef89ab;
  413. MG_REG(FLASH_OPTKEYR) = 0x08192a3b;
  414. MG_REG(FLASH_OPTKEYR) = 0x4c5d6e7f;
  415. unlocked = true;
  416. }
  417. }
  418. static int flash_page_start(volatile uint32_t *dst) {
  419. char *base = (char *) mg_flash_start(), *end = base + mg_flash_size();
  420. volatile char *p = (char *) dst;
  421. return p >= base && p < end && ((p - base) % mg_flash_sector_size()) == 0;
  422. }
  423. static bool flash_is_err(void) {
  424. return MG_REG(FLASH_NSSR) & ((MG_BIT(8) - 1) << 17); // RM0481 7.11.9
  425. }
  426. static void flash_wait(void) {
  427. while ((MG_REG(FLASH_NSSR) & MG_BIT(0)) &&
  428. (MG_REG(FLASH_NSSR) & MG_BIT(16)) == 0) {
  429. (void) 0;
  430. }
  431. }
  432. static void flash_clear_err(void) {
  433. flash_wait(); // Wait until ready
  434. MG_REG(FLASH_NSCCR) = ((MG_BIT(9) - 1) << 16U); // Clear all errors
  435. }
  436. static bool flash_bank_is_swapped(void) {
  437. return MG_REG(FLASH_OPTCR) & MG_BIT(31); // RM0481 7.11.8
  438. }
  439. bool mg_flash_erase(void *location) {
  440. bool ok = false;
  441. if (flash_page_start(location) == false) {
  442. MG_ERROR(("%p is not on a sector boundary"));
  443. } else {
  444. uintptr_t diff = (char *) location - (char *) mg_flash_start();
  445. uint32_t sector = diff / mg_flash_sector_size();
  446. uint32_t saved_cr = MG_REG(FLASH_NSCR); // Save CR value
  447. flash_unlock();
  448. flash_clear_err();
  449. MG_REG(FLASH_NSCR) = 0;
  450. if ((sector < 128 && flash_bank_is_swapped()) ||
  451. (sector > 127 && !flash_bank_is_swapped())) {
  452. MG_REG(FLASH_NSCR) |= MG_BIT(31); // Set FLASH_CR_BKSEL
  453. }
  454. if (sector > 127) sector -= 128;
  455. MG_REG(FLASH_NSCR) |= MG_BIT(2) | (sector << 6); // Erase | sector_num
  456. MG_REG(FLASH_NSCR) |= MG_BIT(5); // Start erasing
  457. flash_wait();
  458. ok = !flash_is_err();
  459. MG_DEBUG(("Erase sector %lu @ %p: %s. CR %#lx SR %#lx", sector, location,
  460. ok ? "ok" : "fail", MG_REG(FLASH_NSCR), MG_REG(FLASH_NSSR)));
  461. // mg_hexdump(location, 32);
  462. MG_REG(FLASH_NSCR) = saved_cr; // Restore saved CR
  463. }
  464. return ok;
  465. }
  466. bool mg_flash_swap_bank(void) {
  467. uint32_t desired = flash_bank_is_swapped() ? 0 : MG_BIT(31);
  468. flash_unlock();
  469. flash_clear_err();
  470. // printf("OPTSR_PRG 1 %#lx\n", FLASH->OPTSR_PRG);
  471. MG_SET_BITS(MG_REG(FLASH_OPTSR_PRG), MG_BIT(31), desired);
  472. // printf("OPTSR_PRG 2 %#lx\n", FLASH->OPTSR_PRG);
  473. MG_REG(FLASH_OPTCR) |= MG_BIT(1); // OPTSTART
  474. while ((MG_REG(FLASH_OPTSR_CUR) & MG_BIT(31)) != desired) (void) 0;
  475. return true;
  476. }
  477. bool mg_flash_write(void *addr, const void *buf, size_t len) {
  478. if ((len % mg_flash_write_align()) != 0) {
  479. MG_ERROR(("%lu is not aligned to %lu", len, mg_flash_write_align()));
  480. return false;
  481. }
  482. uint32_t *dst = (uint32_t *) addr;
  483. uint32_t *src = (uint32_t *) buf;
  484. uint32_t *end = (uint32_t *) ((char *) buf + len);
  485. bool ok = true;
  486. flash_unlock();
  487. flash_clear_err();
  488. MG_ARM_DISABLE_IRQ();
  489. // MG_DEBUG(("Starting flash write %lu bytes @ %p", len, addr));
  490. MG_REG(FLASH_NSCR) = MG_BIT(1); // Set programming flag
  491. while (ok && src < end) {
  492. if (flash_page_start(dst) && mg_flash_erase(dst) == false) break;
  493. *(volatile uint32_t *) dst++ = *src++;
  494. flash_wait();
  495. if (flash_is_err()) ok = false;
  496. }
  497. MG_ARM_ENABLE_IRQ();
  498. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  499. flash_is_err() ? "fail" : "ok", MG_REG(FLASH_NSCR),
  500. MG_REG(FLASH_NSSR)));
  501. MG_REG(FLASH_NSCR) = 0; // Clear flags
  502. return ok;
  503. }
  504. void mg_device_reset(void) {
  505. // SCB->AIRCR = ((0x5fa << SCB_AIRCR_VECTKEY_Pos)|SCB_AIRCR_SYSRESETREQ_Msk);
  506. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  507. }
  508. #endif
  509. #ifdef MG_ENABLE_LINES
  510. #line 1 "src/device_stm32h7.c"
  511. #endif
  512. #if MG_DEVICE == MG_DEVICE_STM32H7
  513. #define FLASH_BASE1 0x52002000 // Base address for bank1
  514. #define FLASH_BASE2 0x52002100 // Base address for bank2
  515. #define FLASH_KEYR 0x04 // See RM0433 4.9.2
  516. #define FLASH_OPTKEYR 0x08
  517. #define FLASH_OPTCR 0x18
  518. #define FLASH_SR 0x10
  519. #define FLASH_CR 0x0c
  520. #define FLASH_CCR 0x14
  521. #define FLASH_OPTSR_CUR 0x1c
  522. #define FLASH_OPTSR_PRG 0x20
  523. #define FLASH_SIZE_REG 0x1ff1e880
  524. MG_IRAM void *mg_flash_start(void) {
  525. return (void *) 0x08000000;
  526. }
  527. MG_IRAM size_t mg_flash_size(void) {
  528. return MG_REG(FLASH_SIZE_REG) * 1024;
  529. }
  530. MG_IRAM size_t mg_flash_sector_size(void) {
  531. return 128 * 1024; // 128k
  532. }
  533. MG_IRAM size_t mg_flash_write_align(void) {
  534. return 32; // 256 bit
  535. }
  536. MG_IRAM int mg_flash_bank(void) {
  537. if (mg_flash_size() < 2 * 1024 * 1024) return 0; // No dual bank support
  538. return MG_REG(FLASH_BASE1 + FLASH_OPTCR) & MG_BIT(31) ? 2 : 1;
  539. }
  540. MG_IRAM static void flash_unlock(void) {
  541. static bool unlocked = false;
  542. if (unlocked == false) {
  543. MG_REG(FLASH_BASE1 + FLASH_KEYR) = 0x45670123;
  544. MG_REG(FLASH_BASE1 + FLASH_KEYR) = 0xcdef89ab;
  545. if (mg_flash_bank() > 0) {
  546. MG_REG(FLASH_BASE2 + FLASH_KEYR) = 0x45670123;
  547. MG_REG(FLASH_BASE2 + FLASH_KEYR) = 0xcdef89ab;
  548. }
  549. MG_REG(FLASH_BASE1 + FLASH_OPTKEYR) = 0x08192a3b; // opt reg is "shared"
  550. MG_REG(FLASH_BASE1 + FLASH_OPTKEYR) = 0x4c5d6e7f; // thus unlock once
  551. unlocked = true;
  552. }
  553. }
  554. MG_IRAM static bool flash_page_start(volatile uint32_t *dst) {
  555. char *base = (char *) mg_flash_start(), *end = base + mg_flash_size();
  556. volatile char *p = (char *) dst;
  557. return p >= base && p < end && ((p - base) % mg_flash_sector_size()) == 0;
  558. }
  559. MG_IRAM static bool flash_is_err(uint32_t bank) {
  560. return MG_REG(bank + FLASH_SR) & ((MG_BIT(11) - 1) << 17); // RM0433 4.9.5
  561. }
  562. MG_IRAM static void flash_wait(uint32_t bank) {
  563. while (MG_REG(bank + FLASH_SR) & (MG_BIT(0) | MG_BIT(2))) (void) 0;
  564. }
  565. MG_IRAM static void flash_clear_err(uint32_t bank) {
  566. flash_wait(bank); // Wait until ready
  567. MG_REG(bank + FLASH_CCR) = ((MG_BIT(11) - 1) << 16U); // Clear all errors
  568. }
  569. MG_IRAM static bool flash_bank_is_swapped(uint32_t bank) {
  570. return MG_REG(bank + FLASH_OPTCR) & MG_BIT(31); // RM0433 4.9.7
  571. }
  572. // Figure out flash bank based on the address
  573. MG_IRAM static uint32_t flash_bank(void *addr) {
  574. size_t ofs = (char *) addr - (char *) mg_flash_start();
  575. if (mg_flash_bank() == 0) return FLASH_BASE1;
  576. return ofs < mg_flash_size() / 2 ? FLASH_BASE1 : FLASH_BASE2;
  577. }
  578. MG_IRAM bool mg_flash_erase(void *addr) {
  579. bool ok = false;
  580. if (flash_page_start(addr) == false) {
  581. MG_ERROR(("%p is not on a sector boundary", addr));
  582. } else {
  583. uintptr_t diff = (char *) addr - (char *) mg_flash_start();
  584. uint32_t sector = diff / mg_flash_sector_size();
  585. uint32_t bank = flash_bank(addr);
  586. uint32_t saved_cr = MG_REG(bank + FLASH_CR); // Save CR value
  587. flash_unlock();
  588. if (sector > 7) sector -= 8;
  589. flash_clear_err(bank);
  590. MG_REG(bank + FLASH_CR) = MG_BIT(5); // 32-bit write parallelism
  591. MG_REG(bank + FLASH_CR) |= (sector & 7U) << 8U; // Sector to erase
  592. MG_REG(bank + FLASH_CR) |= MG_BIT(2); // Sector erase bit
  593. MG_REG(bank + FLASH_CR) |= MG_BIT(7); // Start erasing
  594. ok = !flash_is_err(bank);
  595. MG_DEBUG(("Erase sector %lu @ %p %s. CR %#lx SR %#lx", sector, addr,
  596. ok ? "ok" : "fail", MG_REG(bank + FLASH_CR),
  597. MG_REG(bank + FLASH_SR)));
  598. MG_REG(bank + FLASH_CR) = saved_cr; // Restore CR
  599. }
  600. return ok;
  601. }
  602. MG_IRAM bool mg_flash_swap_bank() {
  603. if (mg_flash_bank() == 0) return true;
  604. uint32_t bank = FLASH_BASE1;
  605. uint32_t desired = flash_bank_is_swapped(bank) ? 0 : MG_BIT(31);
  606. flash_unlock();
  607. flash_clear_err(bank);
  608. // printf("OPTSR_PRG 1 %#lx\n", FLASH->OPTSR_PRG);
  609. MG_SET_BITS(MG_REG(bank + FLASH_OPTSR_PRG), MG_BIT(31), desired);
  610. // printf("OPTSR_PRG 2 %#lx\n", FLASH->OPTSR_PRG);
  611. MG_REG(bank + FLASH_OPTCR) |= MG_BIT(1); // OPTSTART
  612. while ((MG_REG(bank + FLASH_OPTSR_CUR) & MG_BIT(31)) != desired) (void) 0;
  613. return true;
  614. }
  615. MG_IRAM bool mg_flash_write(void *addr, const void *buf, size_t len) {
  616. if ((len % mg_flash_write_align()) != 0) {
  617. MG_ERROR(("%lu is not aligned to %lu", len, mg_flash_write_align()));
  618. return false;
  619. }
  620. uint32_t bank = flash_bank(addr);
  621. uint32_t *dst = (uint32_t *) addr;
  622. uint32_t *src = (uint32_t *) buf;
  623. uint32_t *end = (uint32_t *) ((char *) buf + len);
  624. bool ok = true;
  625. flash_unlock();
  626. flash_clear_err(bank);
  627. MG_REG(bank + FLASH_CR) = MG_BIT(1); // Set programming flag
  628. MG_REG(bank + FLASH_CR) |= MG_BIT(5); // 32-bit write parallelism
  629. MG_DEBUG(("Writing flash @ %p, %lu bytes", addr, len));
  630. MG_ARM_DISABLE_IRQ();
  631. while (ok && src < end) {
  632. if (flash_page_start(dst) && mg_flash_erase(dst) == false) break;
  633. *(volatile uint32_t *) dst++ = *src++;
  634. flash_wait(bank);
  635. if (flash_is_err(bank)) ok = false;
  636. }
  637. MG_ARM_ENABLE_IRQ();
  638. MG_DEBUG(("Flash write %lu bytes @ %p: %s. CR %#lx SR %#lx", len, dst,
  639. ok ? "ok" : "fail", MG_REG(bank + FLASH_CR),
  640. MG_REG(bank + FLASH_SR)));
  641. MG_REG(bank + FLASH_CR) &= ~MG_BIT(1); // Clear programming flag
  642. return ok;
  643. }
  644. MG_IRAM void mg_device_reset(void) {
  645. // SCB->AIRCR = ((0x5fa << SCB_AIRCR_VECTKEY_Pos)|SCB_AIRCR_SYSRESETREQ_Msk);
  646. *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004;
  647. }
  648. #endif
  649. #ifdef MG_ENABLE_LINES
  650. #line 1 "src/dns.c"
  651. #endif
  652. struct dns_data {
  653. struct dns_data *next;
  654. struct mg_connection *c;
  655. uint64_t expire;
  656. uint16_t txnid;
  657. };
  658. static void mg_sendnsreq(struct mg_connection *, struct mg_str *, int,
  659. struct mg_dns *, bool);
  660. static void mg_dns_free(struct dns_data **head, struct dns_data *d) {
  661. LIST_DELETE(struct dns_data, head, d);
  662. free(d);
  663. }
  664. void mg_resolve_cancel(struct mg_connection *c) {
  665. struct dns_data *tmp, *d;
  666. struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests;
  667. for (d = *head; d != NULL; d = tmp) {
  668. tmp = d->next;
  669. if (d->c == c) mg_dns_free(head, d);
  670. }
  671. }
  672. static size_t mg_dns_parse_name_depth(const uint8_t *s, size_t len, size_t ofs,
  673. char *to, size_t tolen, size_t j,
  674. int depth) {
  675. size_t i = 0;
  676. if (tolen > 0 && depth == 0) to[0] = '\0';
  677. if (depth > 5) return 0;
  678. // MG_INFO(("ofs %lx %x %x", (unsigned long) ofs, s[ofs], s[ofs + 1]));
  679. while (ofs + i + 1 < len) {
  680. size_t n = s[ofs + i];
  681. if (n == 0) {
  682. i++;
  683. break;
  684. }
  685. if (n & 0xc0) {
  686. size_t ptr = (((n & 0x3f) << 8) | s[ofs + i + 1]); // 12 is hdr len
  687. // MG_INFO(("PTR %lx", (unsigned long) ptr));
  688. if (ptr + 1 < len && (s[ptr] & 0xc0) == 0 &&
  689. mg_dns_parse_name_depth(s, len, ptr, to, tolen, j, depth + 1) == 0)
  690. return 0;
  691. i += 2;
  692. break;
  693. }
  694. if (ofs + i + n + 1 >= len) return 0;
  695. if (j > 0) {
  696. if (j < tolen) to[j] = '.';
  697. j++;
  698. }
  699. if (j + n < tolen) memcpy(&to[j], &s[ofs + i + 1], n);
  700. j += n;
  701. i += n + 1;
  702. if (j < tolen) to[j] = '\0'; // Zero-terminate this chunk
  703. // MG_INFO(("--> [%s]", to));
  704. }
  705. if (tolen > 0) to[tolen - 1] = '\0'; // Make sure make sure it is nul-term
  706. return i;
  707. }
  708. static size_t mg_dns_parse_name(const uint8_t *s, size_t n, size_t ofs,
  709. char *dst, size_t dstlen) {
  710. return mg_dns_parse_name_depth(s, n, ofs, dst, dstlen, 0, 0);
  711. }
  712. size_t mg_dns_parse_rr(const uint8_t *buf, size_t len, size_t ofs,
  713. bool is_question, struct mg_dns_rr *rr) {
  714. const uint8_t *s = buf + ofs, *e = &buf[len];
  715. memset(rr, 0, sizeof(*rr));
  716. if (len < sizeof(struct mg_dns_header)) return 0; // Too small
  717. if (len > 512) return 0; // Too large, we don't expect that
  718. if (s >= e) return 0; // Overflow
  719. if ((rr->nlen = (uint16_t) mg_dns_parse_name(buf, len, ofs, NULL, 0)) == 0)
  720. return 0;
  721. s += rr->nlen + 4;
  722. if (s > e) return 0;
  723. rr->atype = (uint16_t) (((uint16_t) s[-4] << 8) | s[-3]);
  724. rr->aclass = (uint16_t) (((uint16_t) s[-2] << 8) | s[-1]);
  725. if (is_question) return (size_t) (rr->nlen + 4);
  726. s += 6;
  727. if (s > e) return 0;
  728. rr->alen = (uint16_t) (((uint16_t) s[-2] << 8) | s[-1]);
  729. if (s + rr->alen > e) return 0;
  730. return (size_t) (rr->nlen + rr->alen + 10);
  731. }
  732. bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) {
  733. const struct mg_dns_header *h = (struct mg_dns_header *) buf;
  734. struct mg_dns_rr rr;
  735. size_t i, n, ofs = sizeof(*h);
  736. memset(dm, 0, sizeof(*dm));
  737. if (len < sizeof(*h)) return 0; // Too small, headers dont fit
  738. if (mg_ntohs(h->num_questions) > 1) return 0; // Sanity
  739. if (mg_ntohs(h->num_answers) > 15) return 0; // Sanity
  740. dm->txnid = mg_ntohs(h->txnid);
  741. for (i = 0; i < mg_ntohs(h->num_questions); i++) {
  742. if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false;
  743. // MG_INFO(("Q %lu %lu %hu/%hu", ofs, n, rr.atype, rr.aclass));
  744. ofs += n;
  745. }
  746. for (i = 0; i < mg_ntohs(h->num_answers); i++) {
  747. if ((n = mg_dns_parse_rr(buf, len, ofs, false, &rr)) == 0) return false;
  748. // MG_INFO(("A -- %lu %lu %hu/%hu %s", ofs, n, rr.atype, rr.aclass,
  749. // dm->name));
  750. mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name));
  751. ofs += n;
  752. if (rr.alen == 4 && rr.atype == 1 && rr.aclass == 1) {
  753. dm->addr.is_ip6 = false;
  754. memcpy(&dm->addr.ip, &buf[ofs - 4], 4);
  755. dm->resolved = true;
  756. break; // Return success
  757. } else if (rr.alen == 16 && rr.atype == 28 && rr.aclass == 1) {
  758. dm->addr.is_ip6 = true;
  759. memcpy(&dm->addr.ip, &buf[ofs - 16], 16);
  760. dm->resolved = true;
  761. break; // Return success
  762. }
  763. }
  764. return true;
  765. }
  766. static void dns_cb(struct mg_connection *c, int ev, void *ev_data) {
  767. struct dns_data *d, *tmp;
  768. struct dns_data **head = (struct dns_data **) &c->mgr->active_dns_requests;
  769. if (ev == MG_EV_POLL) {
  770. uint64_t now = *(uint64_t *) ev_data;
  771. for (d = *head; d != NULL; d = tmp) {
  772. tmp = d->next;
  773. // MG_DEBUG ("%lu %lu dns poll", d->expire, now));
  774. if (now > d->expire) mg_error(d->c, "DNS timeout");
  775. }
  776. } else if (ev == MG_EV_READ) {
  777. struct mg_dns_message dm;
  778. int resolved = 0;
  779. if (mg_dns_parse(c->recv.buf, c->recv.len, &dm) == false) {
  780. MG_ERROR(("Unexpected DNS response:"));
  781. mg_hexdump(c->recv.buf, c->recv.len);
  782. } else {
  783. // MG_VERBOSE(("%s %d", dm.name, dm.resolved));
  784. for (d = *head; d != NULL; d = tmp) {
  785. tmp = d->next;
  786. // MG_INFO(("d %p %hu %hu", d, d->txnid, dm.txnid));
  787. if (dm.txnid != d->txnid) continue;
  788. if (d->c->is_resolving) {
  789. if (dm.resolved) {
  790. dm.addr.port = d->c->rem.port; // Save port
  791. d->c->rem = dm.addr; // Copy resolved address
  792. MG_DEBUG(
  793. ("%lu %s is %M", d->c->id, dm.name, mg_print_ip, &d->c->rem));
  794. mg_connect_resolved(d->c);
  795. #if MG_ENABLE_IPV6
  796. } else if (dm.addr.is_ip6 == false && dm.name[0] != '\0' &&
  797. c->mgr->use_dns6 == false) {
  798. struct mg_str x = mg_str(dm.name);
  799. mg_sendnsreq(d->c, &x, c->mgr->dnstimeout, &c->mgr->dns6, true);
  800. #endif
  801. } else {
  802. mg_error(d->c, "%s DNS lookup failed", dm.name);
  803. }
  804. } else {
  805. MG_ERROR(("%lu already resolved", d->c->id));
  806. }
  807. mg_dns_free(head, d);
  808. resolved = 1;
  809. }
  810. }
  811. if (!resolved) MG_ERROR(("stray DNS reply"));
  812. c->recv.len = 0;
  813. } else if (ev == MG_EV_CLOSE) {
  814. for (d = *head; d != NULL; d = tmp) {
  815. tmp = d->next;
  816. mg_error(d->c, "DNS error");
  817. mg_dns_free(head, d);
  818. }
  819. }
  820. }
  821. static bool mg_dns_send(struct mg_connection *c, const struct mg_str *name,
  822. uint16_t txnid, bool ipv6) {
  823. struct {
  824. struct mg_dns_header header;
  825. uint8_t data[256];
  826. } pkt;
  827. size_t i, n;
  828. memset(&pkt, 0, sizeof(pkt));
  829. pkt.header.txnid = mg_htons(txnid);
  830. pkt.header.flags = mg_htons(0x100);
  831. pkt.header.num_questions = mg_htons(1);
  832. for (i = n = 0; i < sizeof(pkt.data) - 5; i++) {
  833. if (name->ptr[i] == '.' || i >= name->len) {
  834. pkt.data[n] = (uint8_t) (i - n);
  835. memcpy(&pkt.data[n + 1], name->ptr + n, i - n);
  836. n = i + 1;
  837. }
  838. if (i >= name->len) break;
  839. }
  840. memcpy(&pkt.data[n], "\x00\x00\x01\x00\x01", 5); // A query
  841. n += 5;
  842. if (ipv6) pkt.data[n - 3] = 0x1c; // AAAA query
  843. // memcpy(&pkt.data[n], "\xc0\x0c\x00\x1c\x00\x01", 6); // AAAA query
  844. // n += 6;
  845. return mg_send(c, &pkt, sizeof(pkt.header) + n);
  846. }
  847. static void mg_sendnsreq(struct mg_connection *c, struct mg_str *name, int ms,
  848. struct mg_dns *dnsc, bool ipv6) {
  849. struct dns_data *d = NULL;
  850. if (dnsc->url == NULL) {
  851. mg_error(c, "DNS server URL is NULL. Call mg_mgr_init()");
  852. } else if (dnsc->c == NULL) {
  853. dnsc->c = mg_connect(c->mgr, dnsc->url, NULL, NULL);
  854. if (dnsc->c != NULL) {
  855. dnsc->c->pfn = dns_cb;
  856. // dnsc->c->is_hexdumping = 1;
  857. }
  858. }
  859. if (dnsc->c == NULL) {
  860. mg_error(c, "resolver");
  861. } else if ((d = (struct dns_data *) calloc(1, sizeof(*d))) == NULL) {
  862. mg_error(c, "resolve OOM");
  863. } else {
  864. struct dns_data *reqs = (struct dns_data *) c->mgr->active_dns_requests;
  865. d->txnid = reqs ? (uint16_t) (reqs->txnid + 1) : 1;
  866. d->next = (struct dns_data *) c->mgr->active_dns_requests;
  867. c->mgr->active_dns_requests = d;
  868. d->expire = mg_millis() + (uint64_t) ms;
  869. d->c = c;
  870. c->is_resolving = 1;
  871. MG_VERBOSE(("%lu resolving %.*s @ %s, txnid %hu", c->id, (int) name->len,
  872. name->ptr, dnsc->url, d->txnid));
  873. if (!mg_dns_send(dnsc->c, name, d->txnid, ipv6)) {
  874. mg_error(dnsc->c, "DNS send");
  875. }
  876. }
  877. }
  878. void mg_resolve(struct mg_connection *c, const char *url) {
  879. struct mg_str host = mg_url_host(url);
  880. c->rem.port = mg_htons(mg_url_port(url));
  881. if (mg_aton(host, &c->rem)) {
  882. // host is an IP address, do not fire name resolution
  883. mg_connect_resolved(c);
  884. } else {
  885. // host is not an IP, send DNS resolution request
  886. struct mg_dns *dns = c->mgr->use_dns6 ? &c->mgr->dns6 : &c->mgr->dns4;
  887. mg_sendnsreq(c, &host, c->mgr->dnstimeout, dns, c->mgr->use_dns6);
  888. }
  889. }
  890. #ifdef MG_ENABLE_LINES
  891. #line 1 "src/event.c"
  892. #endif
  893. void mg_call(struct mg_connection *c, int ev, void *ev_data) {
  894. #if MG_ENABLE_PROFILE
  895. const char *names[] = {
  896. "EV_ERROR", "EV_OPEN", "EV_POLL", "EV_RESOLVE",
  897. "EV_CONNECT", "EV_ACCEPT", "EV_TLS_HS", "EV_READ",
  898. "EV_WRITE", "EV_CLOSE", "EV_HTTP_MSG", "EV_HTTP_CHUNK",
  899. "EV_WS_OPEN", "EV_WS_MSG", "EV_WS_CTL", "EV_MQTT_CMD",
  900. "EV_MQTT_MSG", "EV_MQTT_OPEN", "EV_SNTP_TIME", "EV_USER"};
  901. if (ev != MG_EV_POLL && ev < (int) (sizeof(names) / sizeof(names[0]))) {
  902. MG_PROF_ADD(c, names[ev]);
  903. }
  904. #endif
  905. // Run user-defined handler first, in order to give it an ability
  906. // to intercept processing (e.g. clean input buffer) before the
  907. // protocol handler kicks in
  908. if (c->fn != NULL) c->fn(c, ev, ev_data);
  909. if (c->pfn != NULL) c->pfn(c, ev, ev_data);
  910. }
  911. void mg_error(struct mg_connection *c, const char *fmt, ...) {
  912. char buf[64];
  913. va_list ap;
  914. va_start(ap, fmt);
  915. mg_vsnprintf(buf, sizeof(buf), fmt, &ap);
  916. va_end(ap);
  917. MG_ERROR(("%lu %ld %s", c->id, c->fd, buf));
  918. c->is_closing = 1; // Set is_closing before sending MG_EV_CALL
  919. mg_call(c, MG_EV_ERROR, buf); // Let user handler override it
  920. }
  921. #ifdef MG_ENABLE_LINES
  922. #line 1 "src/fmt.c"
  923. #endif
  924. static bool is_digit(int c) {
  925. return c >= '0' && c <= '9';
  926. }
  927. static int addexp(char *buf, int e, int sign) {
  928. int n = 0;
  929. buf[n++] = 'e';
  930. buf[n++] = (char) sign;
  931. if (e > 400) return 0;
  932. if (e < 10) buf[n++] = '0';
  933. if (e >= 100) buf[n++] = (char) (e / 100 + '0'), e -= 100 * (e / 100);
  934. if (e >= 10) buf[n++] = (char) (e / 10 + '0'), e -= 10 * (e / 10);
  935. buf[n++] = (char) (e + '0');
  936. return n;
  937. }
  938. static int xisinf(double x) {
  939. union {
  940. double f;
  941. uint64_t u;
  942. } ieee754 = {x};
  943. return ((unsigned) (ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
  944. ((unsigned) ieee754.u == 0);
  945. }
  946. static int xisnan(double x) {
  947. union {
  948. double f;
  949. uint64_t u;
  950. } ieee754 = {x};
  951. return ((unsigned) (ieee754.u >> 32) & 0x7fffffff) +
  952. ((unsigned) ieee754.u != 0) >
  953. 0x7ff00000;
  954. }
  955. static size_t mg_dtoa(char *dst, size_t dstlen, double d, int width, bool tz) {
  956. char buf[40];
  957. int i, s = 0, n = 0, e = 0;
  958. double t, mul, saved;
  959. if (d == 0.0) return mg_snprintf(dst, dstlen, "%s", "0");
  960. if (xisinf(d)) return mg_snprintf(dst, dstlen, "%s", d > 0 ? "inf" : "-inf");
  961. if (xisnan(d)) return mg_snprintf(dst, dstlen, "%s", "nan");
  962. if (d < 0.0) d = -d, buf[s++] = '-';
  963. // Round
  964. saved = d;
  965. mul = 1.0;
  966. while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0;
  967. while (d <= 1.0 && d / mul <= 1.0) mul /= 10.0;
  968. for (i = 0, t = mul * 5; i < width; i++) t /= 10.0;
  969. d += t;
  970. // Calculate exponent, and 'mul' for scientific representation
  971. mul = 1.0;
  972. while (d >= 10.0 && d / mul >= 10.0) mul *= 10.0, e++;
  973. while (d < 1.0 && d / mul < 1.0) mul /= 10.0, e--;
  974. // printf(" --> %g %d %g %g\n", saved, e, t, mul);
  975. if (e >= width && width > 1) {
  976. n = (int) mg_dtoa(buf, sizeof(buf), saved / mul, width, tz);
  977. // printf(" --> %.*g %d [%.*s]\n", 10, d / t, e, n, buf);
  978. n += addexp(buf + s + n, e, '+');
  979. return mg_snprintf(dst, dstlen, "%.*s", n, buf);
  980. } else if (e <= -width && width > 1) {
  981. n = (int) mg_dtoa(buf, sizeof(buf), saved / mul, width, tz);
  982. // printf(" --> %.*g %d [%.*s]\n", 10, d / mul, e, n, buf);
  983. n += addexp(buf + s + n, -e, '-');
  984. return mg_snprintf(dst, dstlen, "%.*s", n, buf);
  985. } else {
  986. for (i = 0, t = mul; t >= 1.0 && s + n < (int) sizeof(buf); i++) {
  987. int ch = (int) (d / t);
  988. if (n > 0 || ch > 0) buf[s + n++] = (char) (ch + '0');
  989. d -= ch * t;
  990. t /= 10.0;
  991. }
  992. // printf(" --> [%g] -> %g %g (%d) [%.*s]\n", saved, d, t, n, s + n, buf);
  993. if (n == 0) buf[s++] = '0';
  994. while (t >= 1.0 && n + s < (int) sizeof(buf)) buf[n++] = '0', t /= 10.0;
  995. if (s + n < (int) sizeof(buf)) buf[n + s++] = '.';
  996. // printf(" 1--> [%g] -> [%.*s]\n", saved, s + n, buf);
  997. for (i = 0, t = 0.1; s + n < (int) sizeof(buf) && n < width; i++) {
  998. int ch = (int) (d / t);
  999. buf[s + n++] = (char) (ch + '0');
  1000. d -= ch * t;
  1001. t /= 10.0;
  1002. }
  1003. }
  1004. while (tz && n > 0 && buf[s + n - 1] == '0') n--; // Trim trailing zeroes
  1005. if (n > 0 && buf[s + n - 1] == '.') n--; // Trim trailing dot
  1006. n += s;
  1007. if (n >= (int) sizeof(buf)) n = (int) sizeof(buf) - 1;
  1008. buf[n] = '\0';
  1009. return mg_snprintf(dst, dstlen, "%s", buf);
  1010. }
  1011. static size_t mg_lld(char *buf, int64_t val, bool is_signed, bool is_hex) {
  1012. const char *letters = "0123456789abcdef";
  1013. uint64_t v = (uint64_t) val;
  1014. size_t s = 0, n, i;
  1015. if (is_signed && val < 0) buf[s++] = '-', v = (uint64_t) (-val);
  1016. // This loop prints a number in reverse order. I guess this is because we
  1017. // write numbers from right to left: least significant digit comes last.
  1018. // Maybe because we use Arabic numbers, and Arabs write RTL?
  1019. if (is_hex) {
  1020. for (n = 0; v; v >>= 4) buf[s + n++] = letters[v & 15];
  1021. } else {
  1022. for (n = 0; v; v /= 10) buf[s + n++] = letters[v % 10];
  1023. }
  1024. // Reverse a string
  1025. for (i = 0; i < n / 2; i++) {
  1026. char t = buf[s + i];
  1027. buf[s + i] = buf[s + n - i - 1], buf[s + n - i - 1] = t;
  1028. }
  1029. if (val == 0) buf[n++] = '0'; // Handle special case
  1030. return n + s;
  1031. }
  1032. static size_t scpy(void (*out)(char, void *), void *ptr, char *buf,
  1033. size_t len) {
  1034. size_t i = 0;
  1035. while (i < len && buf[i] != '\0') out(buf[i++], ptr);
  1036. return i;
  1037. }
  1038. size_t mg_xprintf(void (*out)(char, void *), void *ptr, const char *fmt, ...) {
  1039. size_t len = 0;
  1040. va_list ap;
  1041. va_start(ap, fmt);
  1042. len = mg_vxprintf(out, ptr, fmt, &ap);
  1043. va_end(ap);
  1044. return len;
  1045. }
  1046. size_t mg_vxprintf(void (*out)(char, void *), void *param, const char *fmt,
  1047. va_list *ap) {
  1048. size_t i = 0, n = 0;
  1049. while (fmt[i] != '\0') {
  1050. if (fmt[i] == '%') {
  1051. size_t j, k, x = 0, is_long = 0, w = 0 /* width */, pr = ~0U /* prec */;
  1052. char pad = ' ', minus = 0, c = fmt[++i];
  1053. if (c == '#') x++, c = fmt[++i];
  1054. if (c == '-') minus++, c = fmt[++i];
  1055. if (c == '0') pad = '0', c = fmt[++i];
  1056. while (is_digit(c)) w *= 10, w += (size_t) (c - '0'), c = fmt[++i];
  1057. if (c == '.') {
  1058. c = fmt[++i];
  1059. if (c == '*') {
  1060. pr = (size_t) va_arg(*ap, int);
  1061. c = fmt[++i];
  1062. } else {
  1063. pr = 0;
  1064. while (is_digit(c)) pr *= 10, pr += (size_t) (c - '0'), c = fmt[++i];
  1065. }
  1066. }
  1067. while (c == 'h') c = fmt[++i]; // Treat h and hh as int
  1068. if (c == 'l') {
  1069. is_long++, c = fmt[++i];
  1070. if (c == 'l') is_long++, c = fmt[++i];
  1071. }
  1072. if (c == 'p') x = 1, is_long = 1;
  1073. if (c == 'd' || c == 'u' || c == 'x' || c == 'X' || c == 'p' ||
  1074. c == 'g' || c == 'f') {
  1075. bool s = (c == 'd'), h = (c == 'x' || c == 'X' || c == 'p');
  1076. char tmp[40];
  1077. size_t xl = x ? 2 : 0;
  1078. if (c == 'g' || c == 'f') {
  1079. double v = va_arg(*ap, double);
  1080. if (pr == ~0U) pr = 6;
  1081. k = mg_dtoa(tmp, sizeof(tmp), v, (int) pr, c == 'g');
  1082. } else if (is_long == 2) {
  1083. int64_t v = va_arg(*ap, int64_t);
  1084. k = mg_lld(tmp, v, s, h);
  1085. } else if (is_long == 1) {
  1086. long v = va_arg(*ap, long);
  1087. k = mg_lld(tmp, s ? (int64_t) v : (int64_t) (unsigned long) v, s, h);
  1088. } else {
  1089. int v = va_arg(*ap, int);
  1090. k = mg_lld(tmp, s ? (int64_t) v : (int64_t) (unsigned) v, s, h);
  1091. }
  1092. for (j = 0; j < xl && w > 0; j++) w--;
  1093. for (j = 0; pad == ' ' && !minus && k < w && j + k < w; j++)
  1094. n += scpy(out, param, &pad, 1);
  1095. n += scpy(out, param, (char *) "0x", xl);
  1096. for (j = 0; pad == '0' && k < w && j + k < w; j++)
  1097. n += scpy(out, param, &pad, 1);
  1098. n += scpy(out, param, tmp, k);
  1099. for (j = 0; pad == ' ' && minus && k < w && j + k < w; j++)
  1100. n += scpy(out, param, &pad, 1);
  1101. } else if (c == 'm' || c == 'M') {
  1102. mg_pm_t f = va_arg(*ap, mg_pm_t);
  1103. if (c == 'm') out('"', param);
  1104. n += f(out, param, ap);
  1105. if (c == 'm') n += 2, out('"', param);
  1106. } else if (c == 'c') {
  1107. int ch = va_arg(*ap, int);
  1108. out((char) ch, param);
  1109. n++;
  1110. } else if (c == 's') {
  1111. char *p = va_arg(*ap, char *);
  1112. if (pr == ~0U) pr = p == NULL ? 0 : strlen(p);
  1113. for (j = 0; !minus && pr < w && j + pr < w; j++)
  1114. n += scpy(out, param, &pad, 1);
  1115. n += scpy(out, param, p, pr);
  1116. for (j = 0; minus && pr < w && j + pr < w; j++)
  1117. n += scpy(out, param, &pad, 1);
  1118. } else if (c == '%') {
  1119. out('%', param);
  1120. n++;
  1121. } else {
  1122. out('%', param);
  1123. out(c, param);
  1124. n += 2;
  1125. }
  1126. i++;
  1127. } else {
  1128. out(fmt[i], param), n++, i++;
  1129. }
  1130. }
  1131. return n;
  1132. }
  1133. #ifdef MG_ENABLE_LINES
  1134. #line 1 "src/fs.c"
  1135. #endif
  1136. struct mg_fd *mg_fs_open(struct mg_fs *fs, const char *path, int flags) {
  1137. struct mg_fd *fd = (struct mg_fd *) calloc(1, sizeof(*fd));
  1138. if (fd != NULL) {
  1139. fd->fd = fs->op(path, flags);
  1140. fd->fs = fs;
  1141. if (fd->fd == NULL) {
  1142. free(fd);
  1143. fd = NULL;
  1144. }
  1145. }
  1146. return fd;
  1147. }
  1148. void mg_fs_close(struct mg_fd *fd) {
  1149. if (fd != NULL) {
  1150. fd->fs->cl(fd->fd);
  1151. free(fd);
  1152. }
  1153. }
  1154. char *mg_file_read(struct mg_fs *fs, const char *path, size_t *sizep) {
  1155. struct mg_fd *fd;
  1156. char *data = NULL;
  1157. size_t size = 0;
  1158. fs->st(path, &size, NULL);
  1159. if ((fd = mg_fs_open(fs, path, MG_FS_READ)) != NULL) {
  1160. data = (char *) calloc(1, size + 1);
  1161. if (data != NULL) {
  1162. if (fs->rd(fd->fd, data, size) != size) {
  1163. free(data);
  1164. data = NULL;
  1165. } else {
  1166. data[size] = '\0';
  1167. if (sizep != NULL) *sizep = size;
  1168. }
  1169. }
  1170. mg_fs_close(fd);
  1171. }
  1172. return data;
  1173. }
  1174. bool mg_file_write(struct mg_fs *fs, const char *path, const void *buf,
  1175. size_t len) {
  1176. bool result = false;
  1177. struct mg_fd *fd;
  1178. char tmp[MG_PATH_MAX];
  1179. mg_snprintf(tmp, sizeof(tmp), "%s..%d", path, rand());
  1180. if ((fd = mg_fs_open(fs, tmp, MG_FS_WRITE)) != NULL) {
  1181. result = fs->wr(fd->fd, buf, len) == len;
  1182. mg_fs_close(fd);
  1183. if (result) {
  1184. fs->rm(path);
  1185. fs->mv(tmp, path);
  1186. } else {
  1187. fs->rm(tmp);
  1188. }
  1189. }
  1190. return result;
  1191. }
  1192. bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...) {
  1193. va_list ap;
  1194. char *data;
  1195. bool result = false;
  1196. va_start(ap, fmt);
  1197. data = mg_vmprintf(fmt, &ap);
  1198. va_end(ap);
  1199. result = mg_file_write(fs, path, data, strlen(data));
  1200. free(data);
  1201. return result;
  1202. }
  1203. #ifdef MG_ENABLE_LINES
  1204. #line 1 "src/fs_fat.c"
  1205. #endif
  1206. #if MG_ENABLE_FATFS
  1207. #include <ff.h>
  1208. static int mg_days_from_epoch(int y, int m, int d) {
  1209. y -= m <= 2;
  1210. int era = y / 400;
  1211. int yoe = y - era * 400;
  1212. int doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
  1213. int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
  1214. return era * 146097 + doe - 719468;
  1215. }
  1216. static time_t mg_timegm(const struct tm *t) {
  1217. int year = t->tm_year + 1900;
  1218. int month = t->tm_mon; // 0-11
  1219. if (month > 11) {
  1220. year += month / 12;
  1221. month %= 12;
  1222. } else if (month < 0) {
  1223. int years_diff = (11 - month) / 12;
  1224. year -= years_diff;
  1225. month += 12 * years_diff;
  1226. }
  1227. int x = mg_days_from_epoch(year, month + 1, t->tm_mday);
  1228. return 60 * (60 * (24L * x + t->tm_hour) + t->tm_min) + t->tm_sec;
  1229. }
  1230. static time_t ff_time_to_epoch(uint16_t fdate, uint16_t ftime) {
  1231. struct tm tm;
  1232. memset(&tm, 0, sizeof(struct tm));
  1233. tm.tm_sec = (ftime << 1) & 0x3e;
  1234. tm.tm_min = ((ftime >> 5) & 0x3f);
  1235. tm.tm_hour = ((ftime >> 11) & 0x1f);
  1236. tm.tm_mday = (fdate & 0x1f);
  1237. tm.tm_mon = ((fdate >> 5) & 0x0f) - 1;
  1238. tm.tm_year = ((fdate >> 9) & 0x7f) + 80;
  1239. return mg_timegm(&tm);
  1240. }
  1241. static int ff_stat(const char *path, size_t *size, time_t *mtime) {
  1242. FILINFO fi;
  1243. if (path[0] == '\0') {
  1244. if (size) *size = 0;
  1245. if (mtime) *mtime = 0;
  1246. return MG_FS_DIR;
  1247. } else if (f_stat(path, &fi) == 0) {
  1248. if (size) *size = (size_t) fi.fsize;
  1249. if (mtime) *mtime = ff_time_to_epoch(fi.fdate, fi.ftime);
  1250. return MG_FS_READ | MG_FS_WRITE | ((fi.fattrib & AM_DIR) ? MG_FS_DIR : 0);
  1251. } else {
  1252. return 0;
  1253. }
  1254. }
  1255. static void ff_list(const char *dir, void (*fn)(const char *, void *),
  1256. void *userdata) {
  1257. DIR d;
  1258. FILINFO fi;
  1259. if (f_opendir(&d, dir) == FR_OK) {
  1260. while (f_readdir(&d, &fi) == FR_OK && fi.fname[0] != '\0') {
  1261. if (!strcmp(fi.fname, ".") || !strcmp(fi.fname, "..")) continue;
  1262. fn(fi.fname, userdata);
  1263. }
  1264. f_closedir(&d);
  1265. }
  1266. }
  1267. static void *ff_open(const char *path, int flags) {
  1268. FIL f;
  1269. unsigned char mode = FA_READ;
  1270. if (flags & MG_FS_WRITE) mode |= FA_WRITE | FA_OPEN_ALWAYS | FA_OPEN_APPEND;
  1271. if (f_open(&f, path, mode) == 0) {
  1272. FIL *fp;
  1273. if ((fp = calloc(1, sizeof(*fp))) != NULL) {
  1274. memcpy(fp, &f, sizeof(*fp));
  1275. return fp;
  1276. }
  1277. }
  1278. return NULL;
  1279. }
  1280. static void ff_close(void *fp) {
  1281. if (fp != NULL) {
  1282. f_close((FIL *) fp);
  1283. free(fp);
  1284. }
  1285. }
  1286. static size_t ff_read(void *fp, void *buf, size_t len) {
  1287. UINT n = 0, misalign = ((size_t) buf) & 3;
  1288. if (misalign) {
  1289. char aligned[4];
  1290. f_read((FIL *) fp, aligned, len > misalign ? misalign : len, &n);
  1291. memcpy(buf, aligned, n);
  1292. } else {
  1293. f_read((FIL *) fp, buf, len, &n);
  1294. }
  1295. return n;
  1296. }
  1297. static size_t ff_write(void *fp, const void *buf, size_t len) {
  1298. UINT n = 0;
  1299. return f_write((FIL *) fp, (char *) buf, len, &n) == FR_OK ? n : 0;
  1300. }
  1301. static size_t ff_seek(void *fp, size_t offset) {
  1302. f_lseek((FIL *) fp, offset);
  1303. return offset;
  1304. }
  1305. static bool ff_rename(const char *from, const char *to) {
  1306. return f_rename(from, to) == FR_OK;
  1307. }
  1308. static bool ff_remove(const char *path) {
  1309. return f_unlink(path) == FR_OK;
  1310. }
  1311. static bool ff_mkdir(const char *path) {
  1312. return f_mkdir(path) == FR_OK;
  1313. }
  1314. struct mg_fs mg_fs_fat = {ff_stat, ff_list, ff_open, ff_close, ff_read,
  1315. ff_write, ff_seek, ff_rename, ff_remove, ff_mkdir};
  1316. #endif
  1317. #ifdef MG_ENABLE_LINES
  1318. #line 1 "src/fs_packed.c"
  1319. #endif
  1320. struct packed_file {
  1321. const char *data;
  1322. size_t size;
  1323. size_t pos;
  1324. };
  1325. #if MG_ENABLE_PACKED_FS
  1326. #else
  1327. const char *mg_unpack(const char *path, size_t *size, time_t *mtime) {
  1328. *size = 0, *mtime = 0;
  1329. (void) path;
  1330. return NULL;
  1331. }
  1332. const char *mg_unlist(size_t no) {
  1333. (void) no;
  1334. return NULL;
  1335. }
  1336. #endif
  1337. struct mg_str mg_unpacked(const char *path) {
  1338. size_t len = 0;
  1339. const char *buf = mg_unpack(path, &len, NULL);
  1340. return mg_str_n(buf, len);
  1341. }
  1342. static int is_dir_prefix(const char *prefix, size_t n, const char *path) {
  1343. // MG_INFO(("[%.*s] [%s] %c", (int) n, prefix, path, path[n]));
  1344. return n < strlen(path) && strncmp(prefix, path, n) == 0 &&
  1345. (n == 0 || path[n] == '/' || path[n - 1] == '/');
  1346. }
  1347. static int packed_stat(const char *path, size_t *size, time_t *mtime) {
  1348. const char *p;
  1349. size_t i, n = strlen(path);
  1350. if (mg_unpack(path, size, mtime)) return MG_FS_READ; // Regular file
  1351. // Scan all files. If `path` is a dir prefix for any of them, it's a dir
  1352. for (i = 0; (p = mg_unlist(i)) != NULL; i++) {
  1353. if (is_dir_prefix(path, n, p)) return MG_FS_DIR;
  1354. }
  1355. return 0;
  1356. }
  1357. static void packed_list(const char *dir, void (*fn)(const char *, void *),
  1358. void *userdata) {
  1359. char buf[MG_PATH_MAX], tmp[sizeof(buf)];
  1360. const char *path, *begin, *end;
  1361. size_t i, n = strlen(dir);
  1362. tmp[0] = '\0'; // Previously listed entry
  1363. for (i = 0; (path = mg_unlist(i)) != NULL; i++) {
  1364. if (!is_dir_prefix(dir, n, path)) continue;
  1365. begin = &path[n + 1];
  1366. end = strchr(begin, '/');
  1367. if (end == NULL) end = begin + strlen(begin);
  1368. mg_snprintf(buf, sizeof(buf), "%.*s", (int) (end - begin), begin);
  1369. buf[sizeof(buf) - 1] = '\0';
  1370. // If this entry has been already listed, skip
  1371. // NOTE: we're assuming that file list is sorted alphabetically
  1372. if (strcmp(buf, tmp) == 0) continue;
  1373. fn(buf, userdata); // Not yet listed, call user function
  1374. strcpy(tmp, buf); // And save this entry as listed
  1375. }
  1376. }
  1377. static void *packed_open(const char *path, int flags) {
  1378. size_t size = 0;
  1379. const char *data = mg_unpack(path, &size, NULL);
  1380. struct packed_file *fp = NULL;
  1381. if (data == NULL) return NULL;
  1382. if (flags & MG_FS_WRITE) return NULL;
  1383. if ((fp = (struct packed_file *) calloc(1, sizeof(*fp))) != NULL) {
  1384. fp->size = size;
  1385. fp->data = data;
  1386. }
  1387. return (void *) fp;
  1388. }
  1389. static void packed_close(void *fp) {
  1390. if (fp != NULL) free(fp);
  1391. }
  1392. static size_t packed_read(void *fd, void *buf, size_t len) {
  1393. struct packed_file *fp = (struct packed_file *) fd;
  1394. if (fp->pos + len > fp->size) len = fp->size - fp->pos;
  1395. memcpy(buf, &fp->data[fp->pos], len);
  1396. fp->pos += len;
  1397. return len;
  1398. }
  1399. static size_t packed_write(void *fd, const void *buf, size_t len) {
  1400. (void) fd, (void) buf, (void) len;
  1401. return 0;
  1402. }
  1403. static size_t packed_seek(void *fd, size_t offset) {
  1404. struct packed_file *fp = (struct packed_file *) fd;
  1405. fp->pos = offset;
  1406. if (fp->pos > fp->size) fp->pos = fp->size;
  1407. return fp->pos;
  1408. }
  1409. static bool packed_rename(const char *from, const char *to) {
  1410. (void) from, (void) to;
  1411. return false;
  1412. }
  1413. static bool packed_remove(const char *path) {
  1414. (void) path;
  1415. return false;
  1416. }
  1417. static bool packed_mkdir(const char *path) {
  1418. (void) path;
  1419. return false;
  1420. }
  1421. struct mg_fs mg_fs_packed = {
  1422. packed_stat, packed_list, packed_open, packed_close, packed_read,
  1423. packed_write, packed_seek, packed_rename, packed_remove, packed_mkdir};
  1424. #ifdef MG_ENABLE_LINES
  1425. #line 1 "src/fs_posix.c"
  1426. #endif
  1427. #if MG_ENABLE_FILE
  1428. #ifndef MG_STAT_STRUCT
  1429. #define MG_STAT_STRUCT stat
  1430. #endif
  1431. #ifndef MG_STAT_FUNC
  1432. #define MG_STAT_FUNC stat
  1433. #endif
  1434. static int p_stat(const char *path, size_t *size, time_t *mtime) {
  1435. #if !defined(S_ISDIR)
  1436. MG_ERROR(("stat() API is not supported. %p %p %p", path, size, mtime));
  1437. return 0;
  1438. #else
  1439. #if MG_ARCH == MG_ARCH_WIN32
  1440. struct _stati64 st;
  1441. wchar_t tmp[MG_PATH_MAX];
  1442. MultiByteToWideChar(CP_UTF8, 0, path, -1, tmp, sizeof(tmp) / sizeof(tmp[0]));
  1443. if (_wstati64(tmp, &st) != 0) return 0;
  1444. // If path is a symlink, windows reports 0 in st.st_size.
  1445. // Get a real file size by opening it and jumping to the end
  1446. if (st.st_size == 0 && (st.st_mode & _S_IFREG)) {
  1447. FILE *fp = _wfopen(tmp, L"rb");
  1448. if (fp != NULL) {
  1449. fseek(fp, 0, SEEK_END);
  1450. if (ftell(fp) > 0) st.st_size = ftell(fp); // Use _ftelli64 on win10+
  1451. fclose(fp);
  1452. }
  1453. }
  1454. #else
  1455. struct MG_STAT_STRUCT st;
  1456. if (MG_STAT_FUNC(path, &st) != 0) return 0;
  1457. #endif
  1458. if (size) *size = (size_t) st.st_size;
  1459. if (mtime) *mtime = st.st_mtime;
  1460. return MG_FS_READ | MG_FS_WRITE | (S_ISDIR(st.st_mode) ? MG_FS_DIR : 0);
  1461. #endif
  1462. }
  1463. #if MG_ARCH == MG_ARCH_WIN32
  1464. struct dirent {
  1465. char d_name[MAX_PATH];
  1466. };
  1467. typedef struct win32_dir {
  1468. HANDLE handle;
  1469. WIN32_FIND_DATAW info;
  1470. struct dirent result;
  1471. } DIR;
  1472. #if 0
  1473. int gettimeofday(struct timeval *tv, void *tz) {
  1474. FILETIME ft;
  1475. unsigned __int64 tmpres = 0;
  1476. if (tv != NULL) {
  1477. GetSystemTimeAsFileTime(&ft);
  1478. tmpres |= ft.dwHighDateTime;
  1479. tmpres <<= 32;
  1480. tmpres |= ft.dwLowDateTime;
  1481. tmpres /= 10; // convert into microseconds
  1482. tmpres -= (int64_t) 11644473600000000;
  1483. tv->tv_sec = (long) (tmpres / 1000000UL);
  1484. tv->tv_usec = (long) (tmpres % 1000000UL);
  1485. }
  1486. (void) tz;
  1487. return 0;
  1488. }
  1489. #endif
  1490. static int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1491. int ret;
  1492. char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
  1493. strncpy(buf, path, sizeof(buf));
  1494. buf[sizeof(buf) - 1] = '\0';
  1495. // Trim trailing slashes. Leave backslash for paths like "X:\"
  1496. p = buf + strlen(buf) - 1;
  1497. while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
  1498. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1499. ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1500. // Convert back to Unicode. If doubly-converted string does not match the
  1501. // original, something is fishy, reject.
  1502. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1503. NULL, NULL);
  1504. if (strcmp(buf, buf2) != 0) {
  1505. wbuf[0] = L'\0';
  1506. ret = 0;
  1507. }
  1508. return ret;
  1509. }
  1510. DIR *opendir(const char *name) {
  1511. DIR *d = NULL;
  1512. wchar_t wpath[MAX_PATH];
  1513. DWORD attrs;
  1514. if (name == NULL) {
  1515. SetLastError(ERROR_BAD_ARGUMENTS);
  1516. } else if ((d = (DIR *) calloc(1, sizeof(*d))) == NULL) {
  1517. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1518. } else {
  1519. to_wchar(name, wpath, sizeof(wpath) / sizeof(wpath[0]));
  1520. attrs = GetFileAttributesW(wpath);
  1521. if (attrs != 0Xffffffff && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
  1522. (void) wcscat(wpath, L"\\*");
  1523. d->handle = FindFirstFileW(wpath, &d->info);
  1524. d->result.d_name[0] = '\0';
  1525. } else {
  1526. free(d);
  1527. d = NULL;
  1528. }
  1529. }
  1530. return d;
  1531. }
  1532. int closedir(DIR *d) {
  1533. int result = 0;
  1534. if (d != NULL) {
  1535. if (d->handle != INVALID_HANDLE_VALUE)
  1536. result = FindClose(d->handle) ? 0 : -1;
  1537. free(d);
  1538. } else {
  1539. result = -1;
  1540. SetLastError(ERROR_BAD_ARGUMENTS);
  1541. }
  1542. return result;
  1543. }
  1544. struct dirent *readdir(DIR *d) {
  1545. struct dirent *result = NULL;
  1546. if (d != NULL) {
  1547. memset(&d->result, 0, sizeof(d->result));
  1548. if (d->handle != INVALID_HANDLE_VALUE) {
  1549. result = &d->result;
  1550. WideCharToMultiByte(CP_UTF8, 0, d->info.cFileName, -1, result->d_name,
  1551. sizeof(result->d_name), NULL, NULL);
  1552. if (!FindNextFileW(d->handle, &d->info)) {
  1553. FindClose(d->handle);
  1554. d->handle = INVALID_HANDLE_VALUE;
  1555. }
  1556. } else {
  1557. SetLastError(ERROR_FILE_NOT_FOUND);
  1558. }
  1559. } else {
  1560. SetLastError(ERROR_BAD_ARGUMENTS);
  1561. }
  1562. return result;
  1563. }
  1564. #endif
  1565. static void p_list(const char *dir, void (*fn)(const char *, void *),
  1566. void *userdata) {
  1567. #if MG_ENABLE_DIRLIST
  1568. struct dirent *dp;
  1569. DIR *dirp;
  1570. if ((dirp = (opendir(dir))) == NULL) return;
  1571. while ((dp = readdir(dirp)) != NULL) {
  1572. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
  1573. fn(dp->d_name, userdata);
  1574. }
  1575. closedir(dirp);
  1576. #else
  1577. (void) dir, (void) fn, (void) userdata;
  1578. #endif
  1579. }
  1580. static void *p_open(const char *path, int flags) {
  1581. #if MG_ARCH == MG_ARCH_WIN32
  1582. const char *mode = flags == MG_FS_READ ? "rb" : "a+b";
  1583. wchar_t b1[MG_PATH_MAX], b2[10];
  1584. MultiByteToWideChar(CP_UTF8, 0, path, -1, b1, sizeof(b1) / sizeof(b1[0]));
  1585. MultiByteToWideChar(CP_UTF8, 0, mode, -1, b2, sizeof(b2) / sizeof(b2[0]));
  1586. return (void *) _wfopen(b1, b2);
  1587. #else
  1588. const char *mode = flags == MG_FS_READ ? "rbe" : "a+be"; // e for CLOEXEC
  1589. return (void *) fopen(path, mode);
  1590. #endif
  1591. }
  1592. static void p_close(void *fp) {
  1593. fclose((FILE *) fp);
  1594. }
  1595. static size_t p_read(void *fp, void *buf, size_t len) {
  1596. return fread(buf, 1, len, (FILE *) fp);
  1597. }
  1598. static size_t p_write(void *fp, const void *buf, size_t len) {
  1599. return fwrite(buf, 1, len, (FILE *) fp);
  1600. }
  1601. static size_t p_seek(void *fp, size_t offset) {
  1602. #if (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64) || \
  1603. (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) || \
  1604. (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
  1605. if (fseeko((FILE *) fp, (off_t) offset, SEEK_SET) != 0) (void) 0;
  1606. #else
  1607. if (fseek((FILE *) fp, (long) offset, SEEK_SET) != 0) (void) 0;
  1608. #endif
  1609. return (size_t) ftell((FILE *) fp);
  1610. }
  1611. static bool p_rename(const char *from, const char *to) {
  1612. return rename(from, to) == 0;
  1613. }
  1614. static bool p_remove(const char *path) {
  1615. return remove(path) == 0;
  1616. }
  1617. static bool p_mkdir(const char *path) {
  1618. return mkdir(path, 0775) == 0;
  1619. }
  1620. #else
  1621. static int p_stat(const char *path, size_t *size, time_t *mtime) {
  1622. (void) path, (void) size, (void) mtime;
  1623. return 0;
  1624. }
  1625. static void p_list(const char *path, void (*fn)(const char *, void *),
  1626. void *userdata) {
  1627. (void) path, (void) fn, (void) userdata;
  1628. }
  1629. static void *p_open(const char *path, int flags) {
  1630. (void) path, (void) flags;
  1631. return NULL;
  1632. }
  1633. static void p_close(void *fp) {
  1634. (void) fp;
  1635. }
  1636. static size_t p_read(void *fd, void *buf, size_t len) {
  1637. (void) fd, (void) buf, (void) len;
  1638. return 0;
  1639. }
  1640. static size_t p_write(void *fd, const void *buf, size_t len) {
  1641. (void) fd, (void) buf, (void) len;
  1642. return 0;
  1643. }
  1644. static size_t p_seek(void *fd, size_t offset) {
  1645. (void) fd, (void) offset;
  1646. return (size_t) ~0;
  1647. }
  1648. static bool p_rename(const char *from, const char *to) {
  1649. (void) from, (void) to;
  1650. return false;
  1651. }
  1652. static bool p_remove(const char *path) {
  1653. (void) path;
  1654. return false;
  1655. }
  1656. static bool p_mkdir(const char *path) {
  1657. (void) path;
  1658. return false;
  1659. }
  1660. #endif
  1661. struct mg_fs mg_fs_posix = {p_stat, p_list, p_open, p_close, p_read,
  1662. p_write, p_seek, p_rename, p_remove, p_mkdir};
  1663. #ifdef MG_ENABLE_LINES
  1664. #line 1 "src/http.c"
  1665. #endif
  1666. bool mg_to_size_t(struct mg_str str, size_t *val);
  1667. bool mg_to_size_t(struct mg_str str, size_t *val) {
  1668. size_t i = 0, max = (size_t) -1, max2 = max / 10, result = 0, ndigits = 0;
  1669. while (i < str.len && (str.ptr[i] == ' ' || str.ptr[i] == '\t')) i++;
  1670. if (i < str.len && str.ptr[i] == '-') return false;
  1671. while (i < str.len && str.ptr[i] >= '0' && str.ptr[i] <= '9') {
  1672. size_t digit = (size_t) (str.ptr[i] - '0');
  1673. if (result > max2) return false; // Overflow
  1674. result *= 10;
  1675. if (result > max - digit) return false; // Overflow
  1676. result += digit;
  1677. i++, ndigits++;
  1678. }
  1679. while (i < str.len && (str.ptr[i] == ' ' || str.ptr[i] == '\t')) i++;
  1680. if (ndigits == 0) return false; // #2322: Content-Length = 1 * DIGIT
  1681. if (i != str.len) return false; // Ditto
  1682. *val = (size_t) result;
  1683. return true;
  1684. }
  1685. // Chunk deletion marker is the MSB in the "processed" counter
  1686. #define MG_DMARK ((size_t) 1 << (sizeof(size_t) * 8 - 1))
  1687. // Multipart POST example:
  1688. // --xyz
  1689. // Content-Disposition: form-data; name="val"
  1690. //
  1691. // abcdef
  1692. // --xyz
  1693. // Content-Disposition: form-data; name="foo"; filename="a.txt"
  1694. // Content-Type: text/plain
  1695. //
  1696. // hello world
  1697. //
  1698. // --xyz--
  1699. size_t mg_http_next_multipart(struct mg_str body, size_t ofs,
  1700. struct mg_http_part *part) {
  1701. struct mg_str cd = mg_str_n("Content-Disposition", 19);
  1702. const char *s = body.ptr;
  1703. size_t b = ofs, h1, h2, b1, b2, max = body.len;
  1704. // Init part params
  1705. if (part != NULL) part->name = part->filename = part->body = mg_str_n(0, 0);
  1706. // Skip boundary
  1707. while (b + 2 < max && s[b] != '\r' && s[b + 1] != '\n') b++;
  1708. if (b <= ofs || b + 2 >= max) return 0;
  1709. // MG_INFO(("B: %zu %zu [%.*s]", ofs, b - ofs, (int) (b - ofs), s));
  1710. // Skip headers
  1711. h1 = h2 = b + 2;
  1712. for (;;) {
  1713. while (h2 + 2 < max && s[h2] != '\r' && s[h2 + 1] != '\n') h2++;
  1714. if (h2 == h1) break;
  1715. if (h2 + 2 >= max) return 0;
  1716. // MG_INFO(("Header: [%.*s]", (int) (h2 - h1), &s[h1]));
  1717. if (part != NULL && h1 + cd.len + 2 < h2 && s[h1 + cd.len] == ':' &&
  1718. mg_ncasecmp(&s[h1], cd.ptr, cd.len) == 0) {
  1719. struct mg_str v = mg_str_n(&s[h1 + cd.len + 2], h2 - (h1 + cd.len + 2));
  1720. part->name = mg_http_get_header_var(v, mg_str_n("name", 4));
  1721. part->filename = mg_http_get_header_var(v, mg_str_n("filename", 8));
  1722. }
  1723. h1 = h2 = h2 + 2;
  1724. }
  1725. b1 = b2 = h2 + 2;
  1726. while (b2 + 2 + (b - ofs) + 2 < max && !(s[b2] == '\r' && s[b2 + 1] == '\n' &&
  1727. memcmp(&s[b2 + 2], s, b - ofs) == 0))
  1728. b2++;
  1729. if (b2 + 2 >= max) return 0;
  1730. if (part != NULL) part->body = mg_str_n(&s[b1], b2 - b1);
  1731. // MG_INFO(("Body: [%.*s]", (int) (b2 - b1), &s[b1]));
  1732. return b2 + 2;
  1733. }
  1734. void mg_http_bauth(struct mg_connection *c, const char *user,
  1735. const char *pass) {
  1736. struct mg_str u = mg_str(user), p = mg_str(pass);
  1737. size_t need = c->send.len + 36 + (u.len + p.len) * 2;
  1738. if (c->send.size < need) mg_iobuf_resize(&c->send, need);
  1739. if (c->send.size >= need) {
  1740. size_t i, n = 0;
  1741. char *buf = (char *) &c->send.buf[c->send.len];
  1742. memcpy(buf, "Authorization: Basic ", 21); // DON'T use mg_send!
  1743. for (i = 0; i < u.len; i++) {
  1744. n = mg_base64_update(((unsigned char *) u.ptr)[i], buf + 21, n);
  1745. }
  1746. if (p.len > 0) {
  1747. n = mg_base64_update(':', buf + 21, n);
  1748. for (i = 0; i < p.len; i++) {
  1749. n = mg_base64_update(((unsigned char *) p.ptr)[i], buf + 21, n);
  1750. }
  1751. }
  1752. n = mg_base64_final(buf + 21, n);
  1753. c->send.len += 21 + (size_t) n + 2;
  1754. memcpy(&c->send.buf[c->send.len - 2], "\r\n", 2);
  1755. } else {
  1756. MG_ERROR(("%lu oom %d->%d ", c->id, (int) c->send.size, (int) need));
  1757. }
  1758. }
  1759. struct mg_str mg_http_var(struct mg_str buf, struct mg_str name) {
  1760. struct mg_str k, v, result = mg_str_n(NULL, 0);
  1761. while (mg_split(&buf, &k, &v, '&')) {
  1762. if (name.len == k.len && mg_ncasecmp(name.ptr, k.ptr, k.len) == 0) {
  1763. result = v;
  1764. break;
  1765. }
  1766. }
  1767. return result;
  1768. }
  1769. int mg_http_get_var(const struct mg_str *buf, const char *name, char *dst,
  1770. size_t dst_len) {
  1771. int len;
  1772. if (dst == NULL || dst_len == 0) {
  1773. len = -2; // Bad destination
  1774. } else if (buf->ptr == NULL || name == NULL || buf->len == 0) {
  1775. len = -1; // Bad source
  1776. dst[0] = '\0';
  1777. } else {
  1778. struct mg_str v = mg_http_var(*buf, mg_str(name));
  1779. if (v.ptr == NULL) {
  1780. len = -4; // Name does not exist
  1781. } else {
  1782. len = mg_url_decode(v.ptr, v.len, dst, dst_len, 1);
  1783. if (len < 0) len = -3; // Failed to decode
  1784. }
  1785. }
  1786. return len;
  1787. }
  1788. static bool isx(int c) {
  1789. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  1790. (c >= 'A' && c <= 'F');
  1791. }
  1792. int mg_url_decode(const char *src, size_t src_len, char *dst, size_t dst_len,
  1793. int is_form_url_encoded) {
  1794. size_t i, j;
  1795. for (i = j = 0; i < src_len && j + 1 < dst_len; i++, j++) {
  1796. if (src[i] == '%') {
  1797. // Use `i + 2 < src_len`, not `i < src_len - 2`, note small src_len
  1798. if (i + 2 < src_len && isx(src[i + 1]) && isx(src[i + 2])) {
  1799. mg_unhex(src + i + 1, 2, (uint8_t *) &dst[j]);
  1800. i += 2;
  1801. } else {
  1802. return -1;
  1803. }
  1804. } else if (is_form_url_encoded && src[i] == '+') {
  1805. dst[j] = ' ';
  1806. } else {
  1807. dst[j] = src[i];
  1808. }
  1809. }
  1810. if (j < dst_len) dst[j] = '\0'; // Null-terminate the destination
  1811. return i >= src_len && j < dst_len ? (int) j : -1;
  1812. }
  1813. static bool isok(uint8_t c) {
  1814. return c == '\n' || c == '\r' || c >= ' ';
  1815. }
  1816. int mg_http_get_request_len(const unsigned char *buf, size_t buf_len) {
  1817. size_t i;
  1818. for (i = 0; i < buf_len; i++) {
  1819. if (!isok(buf[i])) return -1;
  1820. if ((i > 0 && buf[i] == '\n' && buf[i - 1] == '\n') ||
  1821. (i > 3 && buf[i] == '\n' && buf[i - 1] == '\r' && buf[i - 2] == '\n'))
  1822. return (int) i + 1;
  1823. }
  1824. return 0;
  1825. }
  1826. struct mg_str *mg_http_get_header(struct mg_http_message *h, const char *name) {
  1827. size_t i, n = strlen(name), max = sizeof(h->headers) / sizeof(h->headers[0]);
  1828. for (i = 0; i < max && h->headers[i].name.len > 0; i++) {
  1829. struct mg_str *k = &h->headers[i].name, *v = &h->headers[i].value;
  1830. if (n == k->len && mg_ncasecmp(k->ptr, name, n) == 0) return v;
  1831. }
  1832. return NULL;
  1833. }
  1834. // Is it a valid utf-8 continuation byte
  1835. static bool vcb(uint8_t c) {
  1836. return (c & 0xc0) == 0x80;
  1837. }
  1838. // Get character length (valid utf-8). Used to parse method, URI, headers
  1839. static size_t clen(const char *s, const char *end) {
  1840. const unsigned char *u = (unsigned char *) s, c = *u;
  1841. long n = (long) (end - s);
  1842. if (c > ' ' && c < '~') return 1; // Usual ascii printed char
  1843. if ((c & 0xe0) == 0xc0 && n > 1 && vcb(u[1])) return 2; // 2-byte UTF8
  1844. if ((c & 0xf0) == 0xe0 && n > 2 && vcb(u[1]) && vcb(u[2])) return 3;
  1845. if ((c & 0xf8) == 0xf0 && n > 3 && vcb(u[1]) && vcb(u[2]) && vcb(u[3]))
  1846. return 4;
  1847. return 0;
  1848. }
  1849. // Skip until the newline. Return advanced `s`, or NULL on error
  1850. static const char *skiptorn(const char *s, const char *end, struct mg_str *v) {
  1851. v->ptr = s;
  1852. while (s < end && s[0] != '\n' && s[0] != '\r') s++, v->len++; // To newline
  1853. if (s >= end || (s[0] == '\r' && s[1] != '\n')) return NULL; // Stray \r
  1854. if (s < end && s[0] == '\r') s++; // Skip \r
  1855. if (s >= end || *s++ != '\n') return NULL; // Skip \n
  1856. return s;
  1857. }
  1858. static bool mg_http_parse_headers(const char *s, const char *end,
  1859. struct mg_http_header *h, size_t max_hdrs) {
  1860. size_t i, n;
  1861. for (i = 0; i < max_hdrs; i++) {
  1862. struct mg_str k = {NULL, 0}, v = {NULL, 0};
  1863. if (s >= end) return false;
  1864. if (s[0] == '\n' || (s[0] == '\r' && s[1] == '\n')) break;
  1865. k.ptr = s;
  1866. while (s < end && s[0] != ':' && (n = clen(s, end)) > 0) s += n, k.len += n;
  1867. if (k.len == 0) return false; // Empty name
  1868. if (s >= end || clen(s, end) == 0) return false; // Invalid UTF-8
  1869. if (*s++ != ':') return false; // Invalid, not followed by :
  1870. // if (clen(s, end) == 0) return false; // Invalid UTF-8
  1871. while (s < end && s[0] == ' ') s++; // Skip spaces
  1872. if ((s = skiptorn(s, end, &v)) == NULL) return false;
  1873. while (v.len > 0 && v.ptr[v.len - 1] == ' ') v.len--; // Trim spaces
  1874. // MG_INFO(("--HH [%.*s] [%.*s]", (int) k.len, k.ptr, (int) v.len, v.ptr));
  1875. h[i].name = k, h[i].value = v; // Success. Assign values
  1876. }
  1877. return true;
  1878. }
  1879. int mg_http_parse(const char *s, size_t len, struct mg_http_message *hm) {
  1880. int is_response, req_len = mg_http_get_request_len((unsigned char *) s, len);
  1881. const char *end = s == NULL ? NULL : s + req_len, *qs; // Cannot add to NULL
  1882. struct mg_str *cl;
  1883. size_t n;
  1884. memset(hm, 0, sizeof(*hm));
  1885. if (req_len <= 0) return req_len;
  1886. hm->message.ptr = hm->head.ptr = s;
  1887. hm->body.ptr = end;
  1888. hm->head.len = (size_t) req_len;
  1889. hm->message.len = hm->body.len = (size_t) -1; // Set body length to infinite
  1890. // Parse request line
  1891. hm->method.ptr = s;
  1892. while (s < end && (n = clen(s, end)) > 0) s += n, hm->method.len += n;
  1893. while (s < end && s[0] == ' ') s++; // Skip spaces
  1894. hm->uri.ptr = s;
  1895. while (s < end && (n = clen(s, end)) > 0) s += n, hm->uri.len += n;
  1896. while (s < end && s[0] == ' ') s++; // Skip spaces
  1897. if ((s = skiptorn(s, end, &hm->proto)) == NULL) return false;
  1898. // If URI contains '?' character, setup query string
  1899. if ((qs = (const char *) memchr(hm->uri.ptr, '?', hm->uri.len)) != NULL) {
  1900. hm->query.ptr = qs + 1;
  1901. hm->query.len = (size_t) (&hm->uri.ptr[hm->uri.len] - (qs + 1));
  1902. hm->uri.len = (size_t) (qs - hm->uri.ptr);
  1903. }
  1904. // Sanity check. Allow protocol/reason to be empty
  1905. // Do this check after hm->method.len and hm->uri.len are finalised
  1906. if (hm->method.len == 0 || hm->uri.len == 0) return -1;
  1907. if (!mg_http_parse_headers(s, end, hm->headers,
  1908. sizeof(hm->headers) / sizeof(hm->headers[0])))
  1909. return -1; // error when parsing
  1910. if ((cl = mg_http_get_header(hm, "Content-Length")) != NULL) {
  1911. if (mg_to_size_t(*cl, &hm->body.len) == false) return -1;
  1912. hm->message.len = (size_t) req_len + hm->body.len;
  1913. }
  1914. // mg_http_parse() is used to parse both HTTP requests and HTTP
  1915. // responses. If HTTP response does not have Content-Length set, then
  1916. // body is read until socket is closed, i.e. body.len is infinite (~0).
  1917. //
  1918. // For HTTP requests though, according to
  1919. // http://tools.ietf.org/html/rfc7231#section-8.1.3,
  1920. // only POST and PUT methods have defined body semantics.
  1921. // Therefore, if Content-Length is not specified and methods are
  1922. // not one of PUT or POST, set body length to 0.
  1923. //
  1924. // So, if it is HTTP request, and Content-Length is not set,
  1925. // and method is not (PUT or POST) then reset body length to zero.
  1926. is_response = mg_ncasecmp(hm->method.ptr, "HTTP/", 5) == 0;
  1927. if (hm->body.len == (size_t) ~0 && !is_response &&
  1928. mg_vcasecmp(&hm->method, "PUT") != 0 &&
  1929. mg_vcasecmp(&hm->method, "POST") != 0) {
  1930. hm->body.len = 0;
  1931. hm->message.len = (size_t) req_len;
  1932. }
  1933. // The 204 (No content) responses also have 0 body length
  1934. if (hm->body.len == (size_t) ~0 && is_response &&
  1935. mg_vcasecmp(&hm->uri, "204") == 0) {
  1936. hm->body.len = 0;
  1937. hm->message.len = (size_t) req_len;
  1938. }
  1939. if (hm->message.len < (size_t) req_len) return -1; // Overflow protection
  1940. return req_len;
  1941. }
  1942. static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt,
  1943. va_list *ap) {
  1944. size_t len = c->send.len;
  1945. mg_send(c, " \r\n", 10);
  1946. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  1947. if (c->send.len >= len + 10) {
  1948. mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10);
  1949. c->send.buf[len + 8] = '\r';
  1950. if (c->send.len == len + 10) c->is_resp = 0; // Last chunk, reset marker
  1951. }
  1952. mg_send(c, "\r\n", 2);
  1953. }
  1954. void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) {
  1955. va_list ap;
  1956. va_start(ap, fmt);
  1957. mg_http_vprintf_chunk(c, fmt, &ap);
  1958. va_end(ap);
  1959. }
  1960. void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) {
  1961. mg_printf(c, "%lx\r\n", (unsigned long) len);
  1962. mg_send(c, buf, len);
  1963. mg_send(c, "\r\n", 2);
  1964. if (len == 0) c->is_resp = 0;
  1965. }
  1966. // clang-format off
  1967. static const char *mg_http_status_code_str(int status_code) {
  1968. switch (status_code) {
  1969. case 100: return "Continue";
  1970. case 101: return "Switching Protocols";
  1971. case 102: return "Processing";
  1972. case 200: return "OK";
  1973. case 201: return "Created";
  1974. case 202: return "Accepted";
  1975. case 203: return "Non-authoritative Information";
  1976. case 204: return "No Content";
  1977. case 205: return "Reset Content";
  1978. case 206: return "Partial Content";
  1979. case 207: return "Multi-Status";
  1980. case 208: return "Already Reported";
  1981. case 226: return "IM Used";
  1982. case 300: return "Multiple Choices";
  1983. case 301: return "Moved Permanently";
  1984. case 302: return "Found";
  1985. case 303: return "See Other";
  1986. case 304: return "Not Modified";
  1987. case 305: return "Use Proxy";
  1988. case 307: return "Temporary Redirect";
  1989. case 308: return "Permanent Redirect";
  1990. case 400: return "Bad Request";
  1991. case 401: return "Unauthorized";
  1992. case 402: return "Payment Required";
  1993. case 403: return "Forbidden";
  1994. case 404: return "Not Found";
  1995. case 405: return "Method Not Allowed";
  1996. case 406: return "Not Acceptable";
  1997. case 407: return "Proxy Authentication Required";
  1998. case 408: return "Request Timeout";
  1999. case 409: return "Conflict";
  2000. case 410: return "Gone";
  2001. case 411: return "Length Required";
  2002. case 412: return "Precondition Failed";
  2003. case 413: return "Payload Too Large";
  2004. case 414: return "Request-URI Too Long";
  2005. case 415: return "Unsupported Media Type";
  2006. case 416: return "Requested Range Not Satisfiable";
  2007. case 417: return "Expectation Failed";
  2008. case 418: return "I'm a teapot";
  2009. case 421: return "Misdirected Request";
  2010. case 422: return "Unprocessable Entity";
  2011. case 423: return "Locked";
  2012. case 424: return "Failed Dependency";
  2013. case 426: return "Upgrade Required";
  2014. case 428: return "Precondition Required";
  2015. case 429: return "Too Many Requests";
  2016. case 431: return "Request Header Fields Too Large";
  2017. case 444: return "Connection Closed Without Response";
  2018. case 451: return "Unavailable For Legal Reasons";
  2019. case 499: return "Client Closed Request";
  2020. case 500: return "Internal Server Error";
  2021. case 501: return "Not Implemented";
  2022. case 502: return "Bad Gateway";
  2023. case 503: return "Service Unavailable";
  2024. case 504: return "Gateway Timeout";
  2025. case 505: return "HTTP Version Not Supported";
  2026. case 506: return "Variant Also Negotiates";
  2027. case 507: return "Insufficient Storage";
  2028. case 508: return "Loop Detected";
  2029. case 510: return "Not Extended";
  2030. case 511: return "Network Authentication Required";
  2031. case 599: return "Network Connect Timeout Error";
  2032. default: return "";
  2033. }
  2034. }
  2035. // clang-format on
  2036. void mg_http_reply(struct mg_connection *c, int code, const char *headers,
  2037. const char *fmt, ...) {
  2038. va_list ap;
  2039. size_t len;
  2040. mg_printf(c, "HTTP/1.1 %d %s\r\n%sContent-Length: \r\n\r\n", code,
  2041. mg_http_status_code_str(code), headers == NULL ? "" : headers);
  2042. len = c->send.len;
  2043. va_start(ap, fmt);
  2044. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  2045. va_end(ap);
  2046. if (c->send.len > 16) {
  2047. size_t n = mg_snprintf((char *) &c->send.buf[len - 15], 11, "%-10lu",
  2048. (unsigned long) (c->send.len - len));
  2049. c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space
  2050. }
  2051. c->is_resp = 0;
  2052. }
  2053. static void http_cb(struct mg_connection *, int, void *);
  2054. static void restore_http_cb(struct mg_connection *c) {
  2055. mg_fs_close((struct mg_fd *) c->pfn_data);
  2056. c->pfn_data = NULL;
  2057. c->pfn = http_cb;
  2058. c->is_resp = 0;
  2059. }
  2060. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
  2061. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime) {
  2062. mg_snprintf(buf, len, "\"%lld.%lld\"", (int64_t) mtime, (int64_t) size);
  2063. return buf;
  2064. }
  2065. static void static_cb(struct mg_connection *c, int ev, void *ev_data) {
  2066. if (ev == MG_EV_WRITE || ev == MG_EV_POLL) {
  2067. struct mg_fd *fd = (struct mg_fd *) c->pfn_data;
  2068. // Read to send IO buffer directly, avoid extra on-stack buffer
  2069. size_t n, max = MG_IO_SIZE, space;
  2070. size_t *cl = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2071. sizeof(size_t) * sizeof(size_t)];
  2072. if (c->send.size < max) mg_iobuf_resize(&c->send, max);
  2073. if (c->send.len >= c->send.size) return; // Rate limit
  2074. if ((space = c->send.size - c->send.len) > *cl) space = *cl;
  2075. n = fd->fs->rd(fd->fd, c->send.buf + c->send.len, space);
  2076. c->send.len += n;
  2077. *cl -= n;
  2078. if (n == 0) restore_http_cb(c);
  2079. } else if (ev == MG_EV_CLOSE) {
  2080. restore_http_cb(c);
  2081. }
  2082. (void) ev_data;
  2083. }
  2084. // Known mime types. Keep it outside guess_content_type() function, since
  2085. // some environments don't like it defined there.
  2086. // clang-format off
  2087. static struct mg_str s_known_types[] = {
  2088. MG_C_STR("html"), MG_C_STR("text/html; charset=utf-8"),
  2089. MG_C_STR("htm"), MG_C_STR("text/html; charset=utf-8"),
  2090. MG_C_STR("css"), MG_C_STR("text/css; charset=utf-8"),
  2091. MG_C_STR("js"), MG_C_STR("text/javascript; charset=utf-8"),
  2092. MG_C_STR("gif"), MG_C_STR("image/gif"),
  2093. MG_C_STR("png"), MG_C_STR("image/png"),
  2094. MG_C_STR("jpg"), MG_C_STR("image/jpeg"),
  2095. MG_C_STR("jpeg"), MG_C_STR("image/jpeg"),
  2096. MG_C_STR("woff"), MG_C_STR("font/woff"),
  2097. MG_C_STR("ttf"), MG_C_STR("font/ttf"),
  2098. MG_C_STR("svg"), MG_C_STR("image/svg+xml"),
  2099. MG_C_STR("txt"), MG_C_STR("text/plain; charset=utf-8"),
  2100. MG_C_STR("avi"), MG_C_STR("video/x-msvideo"),
  2101. MG_C_STR("csv"), MG_C_STR("text/csv"),
  2102. MG_C_STR("doc"), MG_C_STR("application/msword"),
  2103. MG_C_STR("exe"), MG_C_STR("application/octet-stream"),
  2104. MG_C_STR("gz"), MG_C_STR("application/gzip"),
  2105. MG_C_STR("ico"), MG_C_STR("image/x-icon"),
  2106. MG_C_STR("json"), MG_C_STR("application/json"),
  2107. MG_C_STR("mov"), MG_C_STR("video/quicktime"),
  2108. MG_C_STR("mp3"), MG_C_STR("audio/mpeg"),
  2109. MG_C_STR("mp4"), MG_C_STR("video/mp4"),
  2110. MG_C_STR("mpeg"), MG_C_STR("video/mpeg"),
  2111. MG_C_STR("pdf"), MG_C_STR("application/pdf"),
  2112. MG_C_STR("shtml"), MG_C_STR("text/html; charset=utf-8"),
  2113. MG_C_STR("tgz"), MG_C_STR("application/tar-gz"),
  2114. MG_C_STR("wav"), MG_C_STR("audio/wav"),
  2115. MG_C_STR("webp"), MG_C_STR("image/webp"),
  2116. MG_C_STR("zip"), MG_C_STR("application/zip"),
  2117. MG_C_STR("3gp"), MG_C_STR("video/3gpp"),
  2118. {0, 0},
  2119. };
  2120. // clang-format on
  2121. static struct mg_str guess_content_type(struct mg_str path, const char *extra) {
  2122. struct mg_str k, v, s = mg_str(extra);
  2123. size_t i = 0;
  2124. // Shrink path to its extension only
  2125. while (i < path.len && path.ptr[path.len - i - 1] != '.') i++;
  2126. path.ptr += path.len - i;
  2127. path.len = i;
  2128. // Process user-provided mime type overrides, if any
  2129. while (mg_commalist(&s, &k, &v)) {
  2130. if (mg_strcmp(path, k) == 0) return v;
  2131. }
  2132. // Process built-in mime types
  2133. for (i = 0; s_known_types[i].ptr != NULL; i += 2) {
  2134. if (mg_strcmp(path, s_known_types[i]) == 0) return s_known_types[i + 1];
  2135. }
  2136. return mg_str("text/plain; charset=utf-8");
  2137. }
  2138. static int getrange(struct mg_str *s, size_t *a, size_t *b) {
  2139. size_t i, numparsed = 0;
  2140. for (i = 0; i + 6 < s->len; i++) {
  2141. struct mg_str k, v = mg_str_n(s->ptr + i + 6, s->len - i - 6);
  2142. if (memcmp(&s->ptr[i], "bytes=", 6) != 0) continue;
  2143. if (mg_split(&v, &k, NULL, '-')) {
  2144. if (mg_to_size_t(k, a)) numparsed++;
  2145. if (v.len > 0 && mg_to_size_t(v, b)) numparsed++;
  2146. } else {
  2147. if (mg_to_size_t(v, a)) numparsed++;
  2148. }
  2149. break;
  2150. }
  2151. return (int) numparsed;
  2152. }
  2153. void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
  2154. const char *path,
  2155. const struct mg_http_serve_opts *opts) {
  2156. char etag[64], tmp[MG_PATH_MAX];
  2157. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2158. struct mg_fd *fd = NULL;
  2159. size_t size = 0;
  2160. time_t mtime = 0;
  2161. struct mg_str *inm = NULL;
  2162. struct mg_str mime = guess_content_type(mg_str(path), opts->mime_types);
  2163. bool gzip = false;
  2164. if (path != NULL) {
  2165. // If a browser sends us "Accept-Encoding: gzip", try to open .gz first
  2166. struct mg_str *ae = mg_http_get_header(hm, "Accept-Encoding");
  2167. if (ae != NULL && mg_strstr(*ae, mg_str("gzip")) != NULL) {
  2168. mg_snprintf(tmp, sizeof(tmp), "%s.gz", path);
  2169. fd = mg_fs_open(fs, tmp, MG_FS_READ);
  2170. if (fd != NULL) gzip = true, path = tmp;
  2171. }
  2172. // No luck opening .gz? Open what we've told to open
  2173. if (fd == NULL) fd = mg_fs_open(fs, path, MG_FS_READ);
  2174. }
  2175. // Failed to open, and page404 is configured? Open it, then
  2176. if (fd == NULL && opts->page404 != NULL) {
  2177. fd = mg_fs_open(fs, opts->page404, MG_FS_READ);
  2178. mime = guess_content_type(mg_str(path), opts->mime_types);
  2179. path = opts->page404;
  2180. }
  2181. if (fd == NULL || fs->st(path, &size, &mtime) == 0) {
  2182. mg_http_reply(c, 404, opts->extra_headers, "Not found\n");
  2183. mg_fs_close(fd);
  2184. // NOTE: mg_http_etag() call should go first!
  2185. } else if (mg_http_etag(etag, sizeof(etag), size, mtime) != NULL &&
  2186. (inm = mg_http_get_header(hm, "If-None-Match")) != NULL &&
  2187. mg_vcasecmp(inm, etag) == 0) {
  2188. mg_fs_close(fd);
  2189. mg_http_reply(c, 304, opts->extra_headers, "");
  2190. } else {
  2191. int n, status = 200;
  2192. char range[100];
  2193. size_t r1 = 0, r2 = 0, cl = size;
  2194. // Handle Range header
  2195. struct mg_str *rh = mg_http_get_header(hm, "Range");
  2196. range[0] = '\0';
  2197. if (rh != NULL && (n = getrange(rh, &r1, &r2)) > 0) {
  2198. // If range is specified like "400-", set second limit to content len
  2199. if (n == 1) r2 = cl - 1;
  2200. if (r1 > r2 || r2 >= cl) {
  2201. status = 416;
  2202. cl = 0;
  2203. mg_snprintf(range, sizeof(range), "Content-Range: bytes */%lld\r\n",
  2204. (int64_t) size);
  2205. } else {
  2206. status = 206;
  2207. cl = r2 - r1 + 1;
  2208. mg_snprintf(range, sizeof(range),
  2209. "Content-Range: bytes %llu-%llu/%llu\r\n", (uint64_t) r1,
  2210. (uint64_t) (r1 + cl - 1), (uint64_t) size);
  2211. fs->sk(fd->fd, r1);
  2212. }
  2213. }
  2214. mg_printf(c,
  2215. "HTTP/1.1 %d %s\r\n"
  2216. "Content-Type: %.*s\r\n"
  2217. "Etag: %s\r\n"
  2218. "Content-Length: %llu\r\n"
  2219. "%s%s%s\r\n",
  2220. status, mg_http_status_code_str(status), (int) mime.len, mime.ptr,
  2221. etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
  2222. range, opts->extra_headers ? opts->extra_headers : "");
  2223. if (mg_vcasecmp(&hm->method, "HEAD") == 0) {
  2224. c->is_draining = 1;
  2225. c->is_resp = 0;
  2226. mg_fs_close(fd);
  2227. } else {
  2228. // Track to-be-sent content length at the end of c->data, aligned
  2229. size_t *clp = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2230. sizeof(size_t) * sizeof(size_t)];
  2231. c->pfn = static_cb;
  2232. c->pfn_data = fd;
  2233. *clp = cl;
  2234. }
  2235. }
  2236. }
  2237. struct printdirentrydata {
  2238. struct mg_connection *c;
  2239. struct mg_http_message *hm;
  2240. const struct mg_http_serve_opts *opts;
  2241. const char *dir;
  2242. };
  2243. #if MG_ENABLE_DIRLIST
  2244. static void printdirentry(const char *name, void *userdata) {
  2245. struct printdirentrydata *d = (struct printdirentrydata *) userdata;
  2246. struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs;
  2247. size_t size = 0;
  2248. time_t t = 0;
  2249. char path[MG_PATH_MAX], sz[40], mod[40];
  2250. int flags, n = 0;
  2251. // MG_DEBUG(("[%s] [%s]", d->dir, name));
  2252. if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >
  2253. sizeof(path)) {
  2254. MG_ERROR(("%s truncated", name));
  2255. } else if ((flags = fs->st(path, &size, &t)) == 0) {
  2256. MG_ERROR(("%lu stat(%s): %d", d->c->id, path, errno));
  2257. } else {
  2258. const char *slash = flags & MG_FS_DIR ? "/" : "";
  2259. if (flags & MG_FS_DIR) {
  2260. mg_snprintf(sz, sizeof(sz), "%s", "[DIR]");
  2261. } else {
  2262. mg_snprintf(sz, sizeof(sz), "%lld", (uint64_t) size);
  2263. }
  2264. #if defined(MG_HTTP_DIRLIST_TIME_FMT)
  2265. {
  2266. char time_str[40];
  2267. struct tm *time_info = localtime(&t);
  2268. strftime(time_str, sizeof time_str, "%Y/%m/%d %H:%M:%S", time_info);
  2269. mg_snprintf(mod, sizeof(mod), "%s", time_str);
  2270. }
  2271. #else
  2272. mg_snprintf(mod, sizeof(mod), "%lu", (unsigned long) t);
  2273. #endif
  2274. n = (int) mg_url_encode(name, strlen(name), path, sizeof(path));
  2275. mg_printf(d->c,
  2276. " <tr><td><a href=\"%.*s%s\">%s%s</a></td>"
  2277. "<td name=%lu>%s</td><td name=%lld>%s</td></tr>\n",
  2278. n, path, slash, name, slash, (unsigned long) t, mod,
  2279. flags & MG_FS_DIR ? (int64_t) -1 : (int64_t) size, sz);
  2280. }
  2281. }
  2282. static void listdir(struct mg_connection *c, struct mg_http_message *hm,
  2283. const struct mg_http_serve_opts *opts, char *dir) {
  2284. const char *sort_js_code =
  2285. "<script>function srt(tb, sc, so, d) {"
  2286. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  2287. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  2288. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  2289. "t1 = a.cells[2].getAttribute('name'), "
  2290. "t2 = b.cells[2].getAttribute('name'); "
  2291. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  2292. "n1 ? parseInt(n2) - parseInt(n1) : "
  2293. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  2294. const char *sort_js_code2 =
  2295. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  2296. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  2297. "};"
  2298. "window.onload = function() {"
  2299. "var tb = document.getElementById('tb');"
  2300. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  2301. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  2302. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  2303. "sc = c; ev.preventDefault();}};"
  2304. "srt(tb, sc, so, true);"
  2305. "}"
  2306. "</script>";
  2307. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2308. struct printdirentrydata d = {c, hm, opts, dir};
  2309. char tmp[10], buf[MG_PATH_MAX];
  2310. size_t off, n;
  2311. int len = mg_url_decode(hm->uri.ptr, hm->uri.len, buf, sizeof(buf), 0);
  2312. struct mg_str uri = len > 0 ? mg_str_n(buf, (size_t) len) : hm->uri;
  2313. mg_printf(c,
  2314. "HTTP/1.1 200 OK\r\n"
  2315. "Content-Type: text/html; charset=utf-8\r\n"
  2316. "%s"
  2317. "Content-Length: \r\n\r\n",
  2318. opts->extra_headers == NULL ? "" : opts->extra_headers);
  2319. off = c->send.len; // Start of body
  2320. mg_printf(c,
  2321. "<!DOCTYPE html><html><head><title>Index of %.*s</title>%s%s"
  2322. "<style>th,td {text-align: left; padding-right: 1em; "
  2323. "font-family: monospace; }</style></head>"
  2324. "<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>"
  2325. "<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
  2326. "<a href=\"#\" rel=\"1\">Modified</a></th>"
  2327. "<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
  2328. "<tr><td colspan=\"3\"><hr></td></tr>"
  2329. "</thead>"
  2330. "<tbody id=\"tb\">\n",
  2331. (int) uri.len, uri.ptr, sort_js_code, sort_js_code2, (int) uri.len,
  2332. uri.ptr);
  2333. mg_printf(c, "%s",
  2334. " <tr><td><a href=\"..\">..</a></td>"
  2335. "<td name=-1></td><td name=-1>[DIR]</td></tr>\n");
  2336. fs->ls(dir, printdirentry, &d);
  2337. mg_printf(c,
  2338. "</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
  2339. "</table><address>Mongoose v.%s</address></body></html>\n",
  2340. MG_VERSION);
  2341. n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
  2342. if (n > sizeof(tmp)) n = 0;
  2343. memcpy(c->send.buf + off - 12, tmp, n); // Set content length
  2344. c->is_resp = 0; // Mark response end
  2345. }
  2346. #endif
  2347. // Resolve requested file into `path` and return its fs->st() result
  2348. static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
  2349. struct mg_fs *fs, struct mg_str url, struct mg_str dir,
  2350. char *path, size_t path_size) {
  2351. int flags, tmp;
  2352. // Append URI to the root_dir, and sanitize it
  2353. size_t n = mg_snprintf(path, path_size, "%.*s", (int) dir.len, dir.ptr);
  2354. if (n + 2 >= path_size) {
  2355. mg_http_reply(c, 400, "", "Exceeded path size");
  2356. return -1;
  2357. }
  2358. path[path_size - 1] = '\0';
  2359. // Terminate root dir with slash
  2360. if (n > 0 && path[n - 1] != '/') path[n++] = '/', path[n] = '\0';
  2361. if (url.len < hm->uri.len) {
  2362. mg_url_decode(hm->uri.ptr + url.len, hm->uri.len - url.len, path + n,
  2363. path_size - n, 0);
  2364. }
  2365. path[path_size - 1] = '\0'; // Double-check
  2366. if (!mg_path_is_sane(path)) {
  2367. mg_http_reply(c, 400, "", "Invalid path");
  2368. return -1;
  2369. }
  2370. n = strlen(path);
  2371. while (n > 1 && path[n - 1] == '/') path[--n] = 0; // Trim trailing slashes
  2372. flags = mg_vcmp(&hm->uri, "/") == 0 ? MG_FS_DIR : fs->st(path, NULL, NULL);
  2373. MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.ptr, path,
  2374. flags));
  2375. if (flags == 0) {
  2376. // Do nothing - let's caller decide
  2377. } else if ((flags & MG_FS_DIR) && hm->uri.len > 0 &&
  2378. hm->uri.ptr[hm->uri.len - 1] != '/') {
  2379. mg_printf(c,
  2380. "HTTP/1.1 301 Moved\r\n"
  2381. "Location: %.*s/\r\n"
  2382. "Content-Length: 0\r\n"
  2383. "\r\n",
  2384. (int) hm->uri.len, hm->uri.ptr);
  2385. c->is_resp = 0;
  2386. flags = -1;
  2387. } else if (flags & MG_FS_DIR) {
  2388. if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
  2389. (tmp = fs->st(path, NULL, NULL)) != 0) ||
  2390. (mg_snprintf(path + n, path_size - n, "/index.shtml") > 0 &&
  2391. (tmp = fs->st(path, NULL, NULL)) != 0))) {
  2392. flags = tmp;
  2393. } else if ((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX ".gz") >
  2394. 0 &&
  2395. (tmp = fs->st(path, NULL, NULL)) !=
  2396. 0)) { // check for gzipped index
  2397. flags = tmp;
  2398. path[n + 1 + strlen(MG_HTTP_INDEX)] =
  2399. '\0'; // Remove appended .gz in index file name
  2400. } else {
  2401. path[n] = '\0'; // Remove appended index file name
  2402. }
  2403. }
  2404. return flags;
  2405. }
  2406. static int uri_to_path(struct mg_connection *c, struct mg_http_message *hm,
  2407. const struct mg_http_serve_opts *opts, char *path,
  2408. size_t path_size) {
  2409. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2410. struct mg_str k, v, s = mg_str(opts->root_dir), u = {0, 0}, p = {0, 0};
  2411. while (mg_commalist(&s, &k, &v)) {
  2412. if (v.len == 0) v = k, k = mg_str("/"), u = k, p = v;
  2413. if (hm->uri.len < k.len) continue;
  2414. if (mg_strcmp(k, mg_str_n(hm->uri.ptr, k.len)) != 0) continue;
  2415. u = k, p = v;
  2416. }
  2417. return uri_to_path2(c, hm, fs, u, p, path, path_size);
  2418. }
  2419. void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
  2420. const struct mg_http_serve_opts *opts) {
  2421. char path[MG_PATH_MAX];
  2422. const char *sp = opts->ssi_pattern;
  2423. int flags = uri_to_path(c, hm, opts, path, sizeof(path));
  2424. if (flags < 0) {
  2425. // Do nothing: the response has already been sent by uri_to_path()
  2426. } else if (flags & MG_FS_DIR) {
  2427. #if MG_ENABLE_DIRLIST
  2428. listdir(c, hm, opts, path);
  2429. #else
  2430. mg_http_reply(c, 403, "", "Forbidden\n");
  2431. #endif
  2432. } else if (flags && sp != NULL &&
  2433. mg_globmatch(sp, strlen(sp), path, strlen(path))) {
  2434. mg_http_serve_ssi(c, opts->root_dir, path);
  2435. } else {
  2436. mg_http_serve_file(c, hm, path, opts);
  2437. }
  2438. }
  2439. static bool mg_is_url_safe(int c) {
  2440. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
  2441. (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~';
  2442. }
  2443. size_t mg_url_encode(const char *s, size_t sl, char *buf, size_t len) {
  2444. size_t i, n = 0;
  2445. for (i = 0; i < sl; i++) {
  2446. int c = *(unsigned char *) &s[i];
  2447. if (n + 4 >= len) return 0;
  2448. if (mg_is_url_safe(c)) {
  2449. buf[n++] = s[i];
  2450. } else {
  2451. buf[n++] = '%';
  2452. mg_hex(&s[i], 1, &buf[n]);
  2453. n += 2;
  2454. }
  2455. }
  2456. if (len > 0 && n < len - 1) buf[n] = '\0'; // Null-terminate the destination
  2457. if (len > 0) buf[len - 1] = '\0'; // Always.
  2458. return n;
  2459. }
  2460. void mg_http_creds(struct mg_http_message *hm, char *user, size_t userlen,
  2461. char *pass, size_t passlen) {
  2462. struct mg_str *v = mg_http_get_header(hm, "Authorization");
  2463. user[0] = pass[0] = '\0';
  2464. if (v != NULL && v->len > 6 && memcmp(v->ptr, "Basic ", 6) == 0) {
  2465. char buf[256];
  2466. size_t n = mg_base64_decode(v->ptr + 6, v->len - 6, buf, sizeof(buf));
  2467. const char *p = (const char *) memchr(buf, ':', n > 0 ? n : 0);
  2468. if (p != NULL) {
  2469. mg_snprintf(user, userlen, "%.*s", p - buf, buf);
  2470. mg_snprintf(pass, passlen, "%.*s", n - (size_t) (p - buf) - 1, p + 1);
  2471. }
  2472. } else if (v != NULL && v->len > 7 && memcmp(v->ptr, "Bearer ", 7) == 0) {
  2473. mg_snprintf(pass, passlen, "%.*s", (int) v->len - 7, v->ptr + 7);
  2474. } else if ((v = mg_http_get_header(hm, "Cookie")) != NULL) {
  2475. struct mg_str t = mg_http_get_header_var(*v, mg_str_n("access_token", 12));
  2476. if (t.len > 0) mg_snprintf(pass, passlen, "%.*s", (int) t.len, t.ptr);
  2477. } else {
  2478. mg_http_get_var(&hm->query, "access_token", pass, passlen);
  2479. }
  2480. }
  2481. static struct mg_str stripquotes(struct mg_str s) {
  2482. return s.len > 1 && s.ptr[0] == '"' && s.ptr[s.len - 1] == '"'
  2483. ? mg_str_n(s.ptr + 1, s.len - 2)
  2484. : s;
  2485. }
  2486. struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v) {
  2487. size_t i;
  2488. for (i = 0; v.len > 0 && i + v.len + 2 < s.len; i++) {
  2489. if (s.ptr[i + v.len] == '=' && memcmp(&s.ptr[i], v.ptr, v.len) == 0) {
  2490. const char *p = &s.ptr[i + v.len + 1], *b = p, *x = &s.ptr[s.len];
  2491. int q = p < x && *p == '"' ? 1 : 0;
  2492. while (p < x &&
  2493. (q ? p == b || *p != '"' : *p != ';' && *p != ' ' && *p != ','))
  2494. p++;
  2495. // MG_INFO(("[%.*s] [%.*s] [%.*s]", (int) s.len, s.ptr, (int) v.len,
  2496. // v.ptr, (int) (p - b), b));
  2497. return stripquotes(mg_str_n(b, (size_t) (p - b + q)));
  2498. }
  2499. }
  2500. return mg_str_n(NULL, 0);
  2501. }
  2502. bool mg_http_match_uri(const struct mg_http_message *hm, const char *glob) {
  2503. return mg_match(hm->uri, mg_str(glob), NULL);
  2504. }
  2505. long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
  2506. struct mg_fs *fs, const char *path, size_t max_size) {
  2507. char buf[20] = "0";
  2508. long res = 0, offset;
  2509. mg_http_get_var(&hm->query, "offset", buf, sizeof(buf));
  2510. offset = strtol(buf, NULL, 0);
  2511. if (hm->body.len == 0) {
  2512. mg_http_reply(c, 200, "", "%ld", res); // Nothing to write
  2513. } else {
  2514. struct mg_fd *fd;
  2515. size_t current_size = 0;
  2516. MG_DEBUG(("%s -> %d bytes @ %ld", path, (int) hm->body.len, offset));
  2517. if (offset == 0) fs->rm(path); // If offset if 0, truncate file
  2518. fs->st(path, &current_size, NULL);
  2519. if (offset < 0) {
  2520. mg_http_reply(c, 400, "", "offset required");
  2521. res = -1;
  2522. } else if (offset > 0 && current_size != (size_t) offset) {
  2523. mg_http_reply(c, 400, "", "%s: offset mismatch", path);
  2524. res = -2;
  2525. } else if ((size_t) offset + hm->body.len > max_size) {
  2526. mg_http_reply(c, 400, "", "%s: over max size of %lu", path,
  2527. (unsigned long) max_size);
  2528. res = -3;
  2529. } else if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
  2530. mg_http_reply(c, 400, "", "open(%s): %d", path, errno);
  2531. res = -4;
  2532. } else {
  2533. res = offset + (long) fs->wr(fd->fd, hm->body.ptr, hm->body.len);
  2534. mg_fs_close(fd);
  2535. mg_http_reply(c, 200, "", "%ld", res);
  2536. }
  2537. }
  2538. return res;
  2539. }
  2540. int mg_http_status(const struct mg_http_message *hm) {
  2541. return atoi(hm->uri.ptr);
  2542. }
  2543. static bool is_hex_digit(int c) {
  2544. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  2545. (c >= 'A' && c <= 'F');
  2546. }
  2547. static int skip_chunk(const char *buf, int len, int *pl, int *dl) {
  2548. int i = 0, n = 0;
  2549. if (len < 3) return 0;
  2550. while (i < len && is_hex_digit(buf[i])) i++;
  2551. if (i > (int) sizeof(int) * 2) return -1; // Chunk length is too big
  2552. if (len < i + 1 || buf[i] != '\r' || buf[i + 1] != '\n') return -1; // Error
  2553. n = (int) mg_unhexn(buf, (size_t) i); // Decode chunk length
  2554. if (n < 0) return -1; // Error
  2555. if (n > len - i - 4) return 0; // Chunk not yet fully buffered
  2556. if (buf[i + n + 2] != '\r' || buf[i + n + 3] != '\n') return -1; // Error
  2557. *pl = i + 2, *dl = n;
  2558. return i + 2 + n + 2;
  2559. }
  2560. static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
  2561. if (ev == MG_EV_READ || ev == MG_EV_CLOSE) {
  2562. struct mg_http_message hm;
  2563. size_t ofs = 0; // Parsing offset
  2564. while (c->is_resp == 0 && ofs < c->recv.len) {
  2565. const char *buf = (char *) c->recv.buf + ofs;
  2566. int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
  2567. struct mg_str *te; // Transfer - encoding header
  2568. bool is_chunked = false;
  2569. if (n < 0) {
  2570. mg_error(c, "HTTP parse, %lu bytes", c->recv.len);
  2571. mg_hexdump(c->recv.buf, c->recv.len > 16 ? 16 : c->recv.len);
  2572. return;
  2573. }
  2574. if (n == 0) break; // Request is not buffered yet
  2575. if (ev == MG_EV_CLOSE) { // If client did not set Content-Length
  2576. hm.message.len = c->recv.len - ofs; // and closes now, deliver MSG
  2577. hm.body.len = hm.message.len - (size_t) (hm.body.ptr - hm.message.ptr);
  2578. }
  2579. if ((te = mg_http_get_header(&hm, "Transfer-Encoding")) != NULL) {
  2580. if (mg_vcasecmp(te, "chunked") == 0) {
  2581. is_chunked = true;
  2582. } else {
  2583. mg_error(c, "Invalid Transfer-Encoding"); // See #2460
  2584. return;
  2585. }
  2586. }
  2587. if (is_chunked) {
  2588. // For chunked data, strip off prefixes and suffixes from chunks
  2589. // and relocate them right after the headers, then report a message
  2590. char *s = (char *) c->recv.buf + ofs + n;
  2591. int o = 0, pl, dl, cl, len = (int) (c->recv.len - ofs - (size_t) n);
  2592. // Find zero-length chunk (the end of the body)
  2593. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0 && dl) o += cl;
  2594. if (cl == 0) break; // No zero-len chunk, buffer more data
  2595. if (cl < 0) {
  2596. mg_error(c, "Invalid chunk");
  2597. break;
  2598. }
  2599. // Zero chunk found. Second pass: strip + relocate
  2600. o = 0, hm.body.len = 0, hm.message.len = (size_t) n;
  2601. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0) {
  2602. memmove(s + hm.body.len, s + o + pl, (size_t) dl);
  2603. o += cl, hm.body.len += (size_t) dl, hm.message.len += (size_t) dl;
  2604. if (dl == 0) break;
  2605. }
  2606. ofs += (size_t) (n + o);
  2607. } else { // Normal, non-chunked data
  2608. size_t len = c->recv.len - ofs - (size_t) n;
  2609. if (hm.body.len > len) break; // Buffer more data
  2610. ofs += (size_t) n + hm.body.len;
  2611. }
  2612. if (c->is_accepted) c->is_resp = 1; // Start generating response
  2613. mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp
  2614. }
  2615. if (ofs > 0) mg_iobuf_del(&c->recv, 0, ofs); // Delete processed data
  2616. }
  2617. (void) ev_data;
  2618. }
  2619. static void mg_hfn(struct mg_connection *c, int ev, void *ev_data) {
  2620. if (ev == MG_EV_HTTP_MSG) {
  2621. struct mg_http_message *hm = (struct mg_http_message *) ev_data;
  2622. if (mg_http_match_uri(hm, "/quit")) {
  2623. mg_http_reply(c, 200, "", "ok\n");
  2624. c->is_draining = 1;
  2625. c->data[0] = 'X';
  2626. } else if (mg_http_match_uri(hm, "/debug")) {
  2627. int level = (int) mg_json_get_long(hm->body, "$.level", MG_LL_DEBUG);
  2628. mg_log_set(level);
  2629. mg_http_reply(c, 200, "", "Debug level set to %d\n", level);
  2630. } else {
  2631. mg_http_reply(c, 200, "", "hi\n");
  2632. }
  2633. } else if (ev == MG_EV_CLOSE) {
  2634. if (c->data[0] == 'X') *(bool *) c->fn_data = true;
  2635. }
  2636. }
  2637. void mg_hello(const char *url) {
  2638. struct mg_mgr mgr;
  2639. bool done = false;
  2640. mg_mgr_init(&mgr);
  2641. if (mg_http_listen(&mgr, url, mg_hfn, &done) == NULL) done = true;
  2642. while (done == false) mg_mgr_poll(&mgr, 100);
  2643. mg_mgr_free(&mgr);
  2644. }
  2645. struct mg_connection *mg_http_connect(struct mg_mgr *mgr, const char *url,
  2646. mg_event_handler_t fn, void *fn_data) {
  2647. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  2648. if (c != NULL) c->pfn = http_cb;
  2649. return c;
  2650. }
  2651. struct mg_connection *mg_http_listen(struct mg_mgr *mgr, const char *url,
  2652. mg_event_handler_t fn, void *fn_data) {
  2653. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  2654. if (c != NULL) c->pfn = http_cb;
  2655. return c;
  2656. }
  2657. #ifdef MG_ENABLE_LINES
  2658. #line 1 "src/iobuf.c"
  2659. #endif
  2660. static size_t roundup(size_t size, size_t align) {
  2661. return align == 0 ? size : (size + align - 1) / align * align;
  2662. }
  2663. int mg_iobuf_resize(struct mg_iobuf *io, size_t new_size) {
  2664. int ok = 1;
  2665. new_size = roundup(new_size, io->align);
  2666. if (new_size == 0) {
  2667. mg_bzero(io->buf, io->size);
  2668. free(io->buf);
  2669. io->buf = NULL;
  2670. io->len = io->size = 0;
  2671. } else if (new_size != io->size) {
  2672. // NOTE(lsm): do not use realloc here. Use calloc/free only, to ease the
  2673. // porting to some obscure platforms like FreeRTOS
  2674. void *p = calloc(1, new_size);
  2675. if (p != NULL) {
  2676. size_t len = new_size < io->len ? new_size : io->len;
  2677. if (len > 0 && io->buf != NULL) memmove(p, io->buf, len);
  2678. mg_bzero(io->buf, io->size);
  2679. free(io->buf);
  2680. io->buf = (unsigned char *) p;
  2681. io->size = new_size;
  2682. } else {
  2683. ok = 0;
  2684. MG_ERROR(("%lld->%lld", (uint64_t) io->size, (uint64_t) new_size));
  2685. }
  2686. }
  2687. return ok;
  2688. }
  2689. int mg_iobuf_init(struct mg_iobuf *io, size_t size, size_t align) {
  2690. io->buf = NULL;
  2691. io->align = align;
  2692. io->size = io->len = 0;
  2693. return mg_iobuf_resize(io, size);
  2694. }
  2695. size_t mg_iobuf_add(struct mg_iobuf *io, size_t ofs, const void *buf,
  2696. size_t len) {
  2697. size_t new_size = roundup(io->len + len, io->align);
  2698. mg_iobuf_resize(io, new_size); // Attempt to resize
  2699. if (new_size != io->size) len = 0; // Resize failure, append nothing
  2700. if (ofs < io->len) memmove(io->buf + ofs + len, io->buf + ofs, io->len - ofs);
  2701. if (buf != NULL) memmove(io->buf + ofs, buf, len);
  2702. if (ofs > io->len) io->len += ofs - io->len;
  2703. io->len += len;
  2704. return len;
  2705. }
  2706. size_t mg_iobuf_del(struct mg_iobuf *io, size_t ofs, size_t len) {
  2707. if (ofs > io->len) ofs = io->len;
  2708. if (ofs + len > io->len) len = io->len - ofs;
  2709. if (io->buf) memmove(io->buf + ofs, io->buf + ofs + len, io->len - ofs - len);
  2710. if (io->buf) mg_bzero(io->buf + io->len - len, len);
  2711. io->len -= len;
  2712. return len;
  2713. }
  2714. void mg_iobuf_free(struct mg_iobuf *io) {
  2715. mg_iobuf_resize(io, 0);
  2716. }
  2717. #ifdef MG_ENABLE_LINES
  2718. #line 1 "src/json.c"
  2719. #endif
  2720. static const char *escapeseq(int esc) {
  2721. return esc ? "\b\f\n\r\t\\\"" : "bfnrt\\\"";
  2722. }
  2723. static char json_esc(int c, int esc) {
  2724. const char *p, *esc1 = escapeseq(esc), *esc2 = escapeseq(!esc);
  2725. for (p = esc1; *p != '\0'; p++) {
  2726. if (*p == c) return esc2[p - esc1];
  2727. }
  2728. return 0;
  2729. }
  2730. static int mg_pass_string(const char *s, int len) {
  2731. int i;
  2732. for (i = 0; i < len; i++) {
  2733. if (s[i] == '\\' && i + 1 < len && json_esc(s[i + 1], 1)) {
  2734. i++;
  2735. } else if (s[i] == '\0') {
  2736. return MG_JSON_INVALID;
  2737. } else if (s[i] == '"') {
  2738. return i;
  2739. }
  2740. }
  2741. return MG_JSON_INVALID;
  2742. }
  2743. static double mg_atod(const char *p, int len, int *numlen) {
  2744. double d = 0.0;
  2745. int i = 0, sign = 1;
  2746. // Sign
  2747. if (i < len && *p == '-') {
  2748. sign = -1, i++;
  2749. } else if (i < len && *p == '+') {
  2750. i++;
  2751. }
  2752. // Decimal
  2753. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  2754. d *= 10.0;
  2755. d += p[i] - '0';
  2756. }
  2757. d *= sign;
  2758. // Fractional
  2759. if (i < len && p[i] == '.') {
  2760. double frac = 0.0, base = 0.1;
  2761. i++;
  2762. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  2763. frac += base * (p[i] - '0');
  2764. base /= 10.0;
  2765. }
  2766. d += frac * sign;
  2767. }
  2768. // Exponential
  2769. if (i < len && (p[i] == 'e' || p[i] == 'E')) {
  2770. int j, exp = 0, minus = 0;
  2771. i++;
  2772. if (i < len && p[i] == '-') minus = 1, i++;
  2773. if (i < len && p[i] == '+') i++;
  2774. while (i < len && p[i] >= '0' && p[i] <= '9' && exp < 308)
  2775. exp = exp * 10 + (p[i++] - '0');
  2776. if (minus) exp = -exp;
  2777. for (j = 0; j < exp; j++) d *= 10.0;
  2778. for (j = 0; j < -exp; j++) d /= 10.0;
  2779. }
  2780. if (numlen != NULL) *numlen = i;
  2781. return d;
  2782. }
  2783. // Iterate over object or array elements
  2784. size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key,
  2785. struct mg_str *val) {
  2786. if (ofs >= obj.len) {
  2787. ofs = 0; // Out of boundaries, stop scanning
  2788. } else if (obj.len < 2 || (*obj.ptr != '{' && *obj.ptr != '[')) {
  2789. ofs = 0; // Not an array or object, stop
  2790. } else {
  2791. struct mg_str sub = mg_str_n(obj.ptr + ofs, obj.len - ofs);
  2792. if (ofs == 0) ofs++, sub.ptr++, sub.len--;
  2793. if (*obj.ptr == '[') { // Iterate over an array
  2794. int n = 0, o = mg_json_get(sub, "$", &n);
  2795. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2796. ofs = 0; // Error parsing key, stop scanning
  2797. } else {
  2798. if (key) *key = mg_str_n(NULL, 0);
  2799. if (val) *val = mg_str_n(sub.ptr + o, (size_t) n);
  2800. ofs = (size_t) (&sub.ptr[o + n] - obj.ptr);
  2801. }
  2802. } else { // Iterate over an object
  2803. int n = 0, o = mg_json_get(sub, "$", &n);
  2804. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2805. ofs = 0; // Error parsing key, stop scanning
  2806. } else {
  2807. if (key) *key = mg_str_n(sub.ptr + o, (size_t) n);
  2808. sub.ptr += o + n, sub.len -= (size_t) (o + n);
  2809. while (sub.len > 0 && *sub.ptr != ':') sub.len--, sub.ptr++;
  2810. if (sub.len > 0 && *sub.ptr == ':') sub.len--, sub.ptr++;
  2811. n = 0, o = mg_json_get(sub, "$", &n);
  2812. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2813. ofs = 0; // Error parsing value, stop scanning
  2814. } else {
  2815. if (val) *val = mg_str_n(sub.ptr + o, (size_t) n);
  2816. ofs = (size_t) (&sub.ptr[o + n] - obj.ptr);
  2817. }
  2818. }
  2819. }
  2820. //MG_INFO(("SUB ofs %u %.*s", ofs, sub.len, sub.ptr));
  2821. while (ofs && ofs < obj.len &&
  2822. (obj.ptr[ofs] == ' ' || obj.ptr[ofs] == '\t' ||
  2823. obj.ptr[ofs] == '\n' || obj.ptr[ofs] == '\r')) {
  2824. ofs++;
  2825. }
  2826. if (ofs && ofs < obj.len && obj.ptr[ofs] == ',') ofs++;
  2827. if (ofs > obj.len) ofs = 0;
  2828. }
  2829. return ofs;
  2830. }
  2831. int mg_json_get(struct mg_str json, const char *path, int *toklen) {
  2832. const char *s = json.ptr;
  2833. int len = (int) json.len;
  2834. enum { S_VALUE, S_KEY, S_COLON, S_COMMA_OR_EOO } expecting = S_VALUE;
  2835. unsigned char nesting[MG_JSON_MAX_DEPTH];
  2836. int i = 0; // Current offset in `s`
  2837. int j = 0; // Offset in `s` we're looking for (return value)
  2838. int depth = 0; // Current depth (nesting level)
  2839. int ed = 0; // Expected depth
  2840. int pos = 1; // Current position in `path`
  2841. int ci = -1, ei = -1; // Current and expected index in array
  2842. if (toklen) *toklen = 0;
  2843. if (path[0] != '$') return MG_JSON_INVALID;
  2844. #define MG_CHECKRET(x) \
  2845. do { \
  2846. if (depth == ed && path[pos] == '\0' && ci == ei) { \
  2847. if (toklen) *toklen = i - j + 1; \
  2848. return j; \
  2849. } \
  2850. } while (0)
  2851. // In the ascii table, the distance between `[` and `]` is 2.
  2852. // Ditto for `{` and `}`. Hence +2 in the code below.
  2853. #define MG_EOO(x) \
  2854. do { \
  2855. if (depth == ed && ci != ei) return MG_JSON_NOT_FOUND; \
  2856. if (c != nesting[depth - 1] + 2) return MG_JSON_INVALID; \
  2857. depth--; \
  2858. MG_CHECKRET(x); \
  2859. } while (0)
  2860. for (i = 0; i < len; i++) {
  2861. unsigned char c = ((unsigned char *) s)[i];
  2862. if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
  2863. switch (expecting) {
  2864. case S_VALUE:
  2865. // p("V %s [%.*s] %d %d %d %d\n", path, pos, path, depth, ed, ci, ei);
  2866. if (depth == ed) j = i;
  2867. if (c == '{') {
  2868. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  2869. if (depth == ed && path[pos] == '.' && ci == ei) {
  2870. // If we start the object, reset array indices
  2871. ed++, pos++, ci = ei = -1;
  2872. }
  2873. nesting[depth++] = c;
  2874. expecting = S_KEY;
  2875. break;
  2876. } else if (c == '[') {
  2877. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  2878. if (depth == ed && path[pos] == '[' && ei == ci) {
  2879. ed++, pos++, ci = 0;
  2880. for (ei = 0; path[pos] != ']' && path[pos] != '\0'; pos++) {
  2881. ei *= 10;
  2882. ei += path[pos] - '0';
  2883. }
  2884. if (path[pos] != 0) pos++;
  2885. }
  2886. nesting[depth++] = c;
  2887. break;
  2888. } else if (c == ']' && depth > 0) { // Empty array
  2889. MG_EOO(']');
  2890. } else if (c == 't' && i + 3 < len && memcmp(&s[i], "true", 4) == 0) {
  2891. i += 3;
  2892. } else if (c == 'n' && i + 3 < len && memcmp(&s[i], "null", 4) == 0) {
  2893. i += 3;
  2894. } else if (c == 'f' && i + 4 < len && memcmp(&s[i], "false", 5) == 0) {
  2895. i += 4;
  2896. } else if (c == '-' || ((c >= '0' && c <= '9'))) {
  2897. int numlen = 0;
  2898. mg_atod(&s[i], len - i, &numlen);
  2899. i += numlen - 1;
  2900. } else if (c == '"') {
  2901. int n = mg_pass_string(&s[i + 1], len - i - 1);
  2902. if (n < 0) return n;
  2903. i += n + 1;
  2904. } else {
  2905. return MG_JSON_INVALID;
  2906. }
  2907. MG_CHECKRET('V');
  2908. if (depth == ed && ei >= 0) ci++;
  2909. expecting = S_COMMA_OR_EOO;
  2910. break;
  2911. case S_KEY:
  2912. if (c == '"') {
  2913. int n = mg_pass_string(&s[i + 1], len - i - 1);
  2914. if (n < 0) return n;
  2915. if (i + 1 + n >= len) return MG_JSON_NOT_FOUND;
  2916. if (depth < ed) return MG_JSON_NOT_FOUND;
  2917. if (depth == ed && path[pos - 1] != '.') return MG_JSON_NOT_FOUND;
  2918. // printf("K %s [%.*s] [%.*s] %d %d %d %d %d\n", path, pos, path, n,
  2919. // &s[i + 1], n, depth, ed, ci, ei);
  2920. // NOTE(cpq): in the check sequence below is important.
  2921. // strncmp() must go first: it fails fast if the remaining length
  2922. // of the path is smaller than `n`.
  2923. if (depth == ed && path[pos - 1] == '.' &&
  2924. strncmp(&s[i + 1], &path[pos], (size_t) n) == 0 &&
  2925. (path[pos + n] == '\0' || path[pos + n] == '.' ||
  2926. path[pos + n] == '[')) {
  2927. pos += n;
  2928. }
  2929. i += n + 1;
  2930. expecting = S_COLON;
  2931. } else if (c == '}') { // Empty object
  2932. MG_EOO('}');
  2933. expecting = S_COMMA_OR_EOO;
  2934. if (depth == ed && ei >= 0) ci++;
  2935. } else {
  2936. return MG_JSON_INVALID;
  2937. }
  2938. break;
  2939. case S_COLON:
  2940. if (c == ':') {
  2941. expecting = S_VALUE;
  2942. } else {
  2943. return MG_JSON_INVALID;
  2944. }
  2945. break;
  2946. case S_COMMA_OR_EOO:
  2947. if (depth <= 0) {
  2948. return MG_JSON_INVALID;
  2949. } else if (c == ',') {
  2950. expecting = (nesting[depth - 1] == '{') ? S_KEY : S_VALUE;
  2951. } else if (c == ']' || c == '}') {
  2952. if (depth == ed && c == '}' && path[pos - 1] == '.')
  2953. return MG_JSON_NOT_FOUND;
  2954. if (depth == ed && c == ']' && path[pos - 1] == ',')
  2955. return MG_JSON_NOT_FOUND;
  2956. MG_EOO('O');
  2957. if (depth == ed && ei >= 0) ci++;
  2958. } else {
  2959. return MG_JSON_INVALID;
  2960. }
  2961. break;
  2962. }
  2963. }
  2964. return MG_JSON_NOT_FOUND;
  2965. }
  2966. bool mg_json_get_num(struct mg_str json, const char *path, double *v) {
  2967. int n, toklen, found = 0;
  2968. if ((n = mg_json_get(json, path, &toklen)) >= 0 &&
  2969. (json.ptr[n] == '-' || (json.ptr[n] >= '0' && json.ptr[n] <= '9'))) {
  2970. if (v != NULL) *v = mg_atod(json.ptr + n, toklen, NULL);
  2971. found = 1;
  2972. }
  2973. return found;
  2974. }
  2975. bool mg_json_get_bool(struct mg_str json, const char *path, bool *v) {
  2976. int found = 0, off = mg_json_get(json, path, NULL);
  2977. if (off >= 0 && (json.ptr[off] == 't' || json.ptr[off] == 'f')) {
  2978. if (v != NULL) *v = json.ptr[off] == 't';
  2979. found = 1;
  2980. }
  2981. return found;
  2982. }
  2983. bool mg_json_unescape(struct mg_str s, char *to, size_t n) {
  2984. size_t i, j;
  2985. for (i = 0, j = 0; i < s.len && j < n; i++, j++) {
  2986. if (s.ptr[i] == '\\' && i + 5 < s.len && s.ptr[i + 1] == 'u') {
  2987. // \uXXXX escape. We could process a simple one-byte chars
  2988. // \u00xx from the ASCII range. More complex chars would require
  2989. // dragging in a UTF8 library, which is too much for us
  2990. if (s.ptr[i + 2] != '0' || s.ptr[i + 3] != '0') return false; // Give up
  2991. ((unsigned char *) to)[j] = (unsigned char) mg_unhexn(s.ptr + i + 4, 2);
  2992. i += 5;
  2993. } else if (s.ptr[i] == '\\' && i + 1 < s.len) {
  2994. char c = json_esc(s.ptr[i + 1], 0);
  2995. if (c == 0) return false;
  2996. to[j] = c;
  2997. i++;
  2998. } else {
  2999. to[j] = s.ptr[i];
  3000. }
  3001. }
  3002. if (j >= n) return false;
  3003. if (n > 0) to[j] = '\0';
  3004. return true;
  3005. }
  3006. char *mg_json_get_str(struct mg_str json, const char *path) {
  3007. char *result = NULL;
  3008. int len = 0, off = mg_json_get(json, path, &len);
  3009. if (off >= 0 && len > 1 && json.ptr[off] == '"') {
  3010. if ((result = (char *) calloc(1, (size_t) len)) != NULL &&
  3011. !mg_json_unescape(mg_str_n(json.ptr + off + 1, (size_t) (len - 2)),
  3012. result, (size_t) len)) {
  3013. free(result);
  3014. result = NULL;
  3015. }
  3016. }
  3017. return result;
  3018. }
  3019. char *mg_json_get_b64(struct mg_str json, const char *path, int *slen) {
  3020. char *result = NULL;
  3021. int len = 0, off = mg_json_get(json, path, &len);
  3022. if (off >= 0 && json.ptr[off] == '"' && len > 1 &&
  3023. (result = (char *) calloc(1, (size_t) len)) != NULL) {
  3024. size_t k = mg_base64_decode(json.ptr + off + 1, (size_t) (len - 2), result,
  3025. (size_t) len);
  3026. if (slen != NULL) *slen = (int) k;
  3027. }
  3028. return result;
  3029. }
  3030. char *mg_json_get_hex(struct mg_str json, const char *path, int *slen) {
  3031. char *result = NULL;
  3032. int len = 0, off = mg_json_get(json, path, &len);
  3033. if (off >= 0 && json.ptr[off] == '"' && len > 1 &&
  3034. (result = (char *) calloc(1, (size_t) len / 2)) != NULL) {
  3035. mg_unhex(json.ptr + off + 1, (size_t) (len - 2), (uint8_t *) result);
  3036. result[len / 2 - 1] = '\0';
  3037. if (slen != NULL) *slen = len / 2 - 1;
  3038. }
  3039. return result;
  3040. }
  3041. long mg_json_get_long(struct mg_str json, const char *path, long dflt) {
  3042. double dv;
  3043. long result = dflt;
  3044. if (mg_json_get_num(json, path, &dv)) result = (long) dv;
  3045. return result;
  3046. }
  3047. #ifdef MG_ENABLE_LINES
  3048. #line 1 "src/log.c"
  3049. #endif
  3050. int mg_log_level = MG_LL_INFO;
  3051. static mg_pfn_t s_log_func = mg_pfn_stdout;
  3052. static void *s_log_func_param = NULL;
  3053. void mg_log_set_fn(mg_pfn_t fn, void *param) {
  3054. s_log_func = fn;
  3055. s_log_func_param = param;
  3056. }
  3057. static void logc(unsigned char c) {
  3058. s_log_func((char) c, s_log_func_param);
  3059. }
  3060. static void logs(const char *buf, size_t len) {
  3061. size_t i;
  3062. for (i = 0; i < len; i++) logc(((unsigned char *) buf)[i]);
  3063. }
  3064. #if MG_ENABLE_CUSTOM_LOG
  3065. // Let user define their own mg_log_prefix() and mg_log()
  3066. #else
  3067. void mg_log_prefix(int level, const char *file, int line, const char *fname) {
  3068. const char *p = strrchr(file, '/');
  3069. char buf[41];
  3070. size_t n;
  3071. if (p == NULL) p = strrchr(file, '\\');
  3072. n = mg_snprintf(buf, sizeof(buf), "%-6llx %d %s:%d:%s", mg_millis(), level,
  3073. p == NULL ? file : p + 1, line, fname);
  3074. if (n > sizeof(buf) - 2) n = sizeof(buf) - 2;
  3075. while (n < sizeof(buf)) buf[n++] = ' ';
  3076. logs(buf, n - 1);
  3077. }
  3078. void mg_log(const char *fmt, ...) {
  3079. va_list ap;
  3080. va_start(ap, fmt);
  3081. mg_vxprintf(s_log_func, s_log_func_param, fmt, &ap);
  3082. va_end(ap);
  3083. logs("\r\n", 2);
  3084. }
  3085. #endif
  3086. static unsigned char nibble(unsigned c) {
  3087. return (unsigned char) (c < 10 ? c + '0' : c + 'W');
  3088. }
  3089. #define ISPRINT(x) ((x) >= ' ' && (x) <= '~')
  3090. void mg_hexdump(const void *buf, size_t len) {
  3091. const unsigned char *p = (const unsigned char *) buf;
  3092. unsigned char ascii[16], alen = 0;
  3093. size_t i;
  3094. for (i = 0; i < len; i++) {
  3095. if ((i % 16) == 0) {
  3096. // Print buffered ascii chars
  3097. if (i > 0) logs(" ", 2), logs((char *) ascii, 16), logc('\n'), alen = 0;
  3098. // Print hex address, then \t
  3099. logc(nibble((i >> 12) & 15)), logc(nibble((i >> 8) & 15)),
  3100. logc(nibble((i >> 4) & 15)), logc('0'), logs(" ", 3);
  3101. }
  3102. logc(nibble(p[i] >> 4)), logc(nibble(p[i] & 15)); // Two nibbles, e.g. c5
  3103. logc(' '); // Space after hex number
  3104. ascii[alen++] = ISPRINT(p[i]) ? p[i] : '.'; // Add to the ascii buf
  3105. }
  3106. while (alen < 16) logs(" ", 3), ascii[alen++] = ' ';
  3107. logs(" ", 2), logs((char *) ascii, 16), logc('\n');
  3108. }
  3109. #ifdef MG_ENABLE_LINES
  3110. #line 1 "src/md5.c"
  3111. #endif
  3112. // This code implements the MD5 message-digest algorithm.
  3113. // The algorithm is due to Ron Rivest. This code was
  3114. // written by Colin Plumb in 1993, no copyright is claimed.
  3115. // This code is in the public domain; do with it what you wish.
  3116. //
  3117. // Equivalent code is available from RSA Data Security, Inc.
  3118. // This code has been tested against that, and is equivalent,
  3119. // except that you don't need to include two pages of legalese
  3120. // with every copy.
  3121. //
  3122. // To compute the message digest of a chunk of bytes, declare an
  3123. // MD5Context structure, pass it to MD5Init, call MD5Update as
  3124. // needed on buffers full of bytes, and then call MD5Final, which
  3125. // will fill a supplied 16-byte array with the digest.
  3126. #if defined(MG_ENABLE_MD5) && MG_ENABLE_MD5
  3127. static void mg_byte_reverse(unsigned char *buf, unsigned longs) {
  3128. if (MG_BIG_ENDIAN) {
  3129. do {
  3130. uint32_t t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  3131. ((unsigned) buf[1] << 8 | buf[0]);
  3132. *(uint32_t *) buf = t;
  3133. buf += 4;
  3134. } while (--longs);
  3135. } else {
  3136. (void) buf, (void) longs; // Little endian. Do nothing
  3137. }
  3138. }
  3139. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  3140. #define F2(x, y, z) F1(z, x, y)
  3141. #define F3(x, y, z) (x ^ y ^ z)
  3142. #define F4(x, y, z) (y ^ (x | ~z))
  3143. #define MD5STEP(f, w, x, y, z, data, s) \
  3144. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  3145. /*
  3146. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  3147. * initialization constants.
  3148. */
  3149. void mg_md5_init(mg_md5_ctx *ctx) {
  3150. ctx->buf[0] = 0x67452301;
  3151. ctx->buf[1] = 0xefcdab89;
  3152. ctx->buf[2] = 0x98badcfe;
  3153. ctx->buf[3] = 0x10325476;
  3154. ctx->bits[0] = 0;
  3155. ctx->bits[1] = 0;
  3156. }
  3157. static void mg_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
  3158. uint32_t a, b, c, d;
  3159. a = buf[0];
  3160. b = buf[1];
  3161. c = buf[2];
  3162. d = buf[3];
  3163. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  3164. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  3165. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  3166. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  3167. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  3168. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  3169. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  3170. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  3171. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  3172. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  3173. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  3174. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  3175. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  3176. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  3177. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  3178. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  3179. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  3180. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  3181. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  3182. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  3183. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  3184. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  3185. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  3186. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  3187. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  3188. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  3189. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  3190. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  3191. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  3192. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  3193. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  3194. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  3195. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  3196. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  3197. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  3198. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  3199. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  3200. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  3201. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  3202. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  3203. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  3204. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  3205. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  3206. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  3207. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  3208. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  3209. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  3210. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  3211. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  3212. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  3213. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  3214. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  3215. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  3216. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  3217. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  3218. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  3219. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  3220. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  3221. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  3222. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  3223. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  3224. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  3225. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  3226. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  3227. buf[0] += a;
  3228. buf[1] += b;
  3229. buf[2] += c;
  3230. buf[3] += d;
  3231. }
  3232. void mg_md5_update(mg_md5_ctx *ctx, const unsigned char *buf, size_t len) {
  3233. uint32_t t;
  3234. t = ctx->bits[0];
  3235. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  3236. ctx->bits[1] += (uint32_t) len >> 29;
  3237. t = (t >> 3) & 0x3f;
  3238. if (t) {
  3239. unsigned char *p = (unsigned char *) ctx->in + t;
  3240. t = 64 - t;
  3241. if (len < t) {
  3242. memcpy(p, buf, len);
  3243. return;
  3244. }
  3245. memcpy(p, buf, t);
  3246. mg_byte_reverse(ctx->in, 16);
  3247. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3248. buf += t;
  3249. len -= t;
  3250. }
  3251. while (len >= 64) {
  3252. memcpy(ctx->in, buf, 64);
  3253. mg_byte_reverse(ctx->in, 16);
  3254. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3255. buf += 64;
  3256. len -= 64;
  3257. }
  3258. memcpy(ctx->in, buf, len);
  3259. }
  3260. void mg_md5_final(mg_md5_ctx *ctx, unsigned char digest[16]) {
  3261. unsigned count;
  3262. unsigned char *p;
  3263. uint32_t *a;
  3264. count = (ctx->bits[0] >> 3) & 0x3F;
  3265. p = ctx->in + count;
  3266. *p++ = 0x80;
  3267. count = 64 - 1 - count;
  3268. if (count < 8) {
  3269. memset(p, 0, count);
  3270. mg_byte_reverse(ctx->in, 16);
  3271. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3272. memset(ctx->in, 0, 56);
  3273. } else {
  3274. memset(p, 0, count - 8);
  3275. }
  3276. mg_byte_reverse(ctx->in, 14);
  3277. a = (uint32_t *) ctx->in;
  3278. a[14] = ctx->bits[0];
  3279. a[15] = ctx->bits[1];
  3280. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3281. mg_byte_reverse((unsigned char *) ctx->buf, 4);
  3282. memcpy(digest, ctx->buf, 16);
  3283. memset((char *) ctx, 0, sizeof(*ctx));
  3284. }
  3285. #endif
  3286. #ifdef MG_ENABLE_LINES
  3287. #line 1 "src/mqtt.c"
  3288. #endif
  3289. #define MQTT_CLEAN_SESSION 0x02
  3290. #define MQTT_HAS_WILL 0x04
  3291. #define MQTT_WILL_RETAIN 0x20
  3292. #define MQTT_HAS_PASSWORD 0x40
  3293. #define MQTT_HAS_USER_NAME 0x80
  3294. struct mg_mqtt_pmap {
  3295. uint8_t id;
  3296. uint8_t type;
  3297. };
  3298. static const struct mg_mqtt_pmap s_prop_map[] = {
  3299. {MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, MQTT_PROP_TYPE_BYTE},
  3300. {MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3301. {MQTT_PROP_CONTENT_TYPE, MQTT_PROP_TYPE_STRING},
  3302. {MQTT_PROP_RESPONSE_TOPIC, MQTT_PROP_TYPE_STRING},
  3303. {MQTT_PROP_CORRELATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3304. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER, MQTT_PROP_TYPE_VARIABLE_INT},
  3305. {MQTT_PROP_SESSION_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3306. {MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, MQTT_PROP_TYPE_STRING},
  3307. {MQTT_PROP_SERVER_KEEP_ALIVE, MQTT_PROP_TYPE_SHORT},
  3308. {MQTT_PROP_AUTHENTICATION_METHOD, MQTT_PROP_TYPE_STRING},
  3309. {MQTT_PROP_AUTHENTICATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3310. {MQTT_PROP_REQUEST_PROBLEM_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3311. {MQTT_PROP_WILL_DELAY_INTERVAL, MQTT_PROP_TYPE_INT},
  3312. {MQTT_PROP_REQUEST_RESPONSE_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3313. {MQTT_PROP_RESPONSE_INFORMATION, MQTT_PROP_TYPE_STRING},
  3314. {MQTT_PROP_SERVER_REFERENCE, MQTT_PROP_TYPE_STRING},
  3315. {MQTT_PROP_REASON_STRING, MQTT_PROP_TYPE_STRING},
  3316. {MQTT_PROP_RECEIVE_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3317. {MQTT_PROP_TOPIC_ALIAS_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3318. {MQTT_PROP_TOPIC_ALIAS, MQTT_PROP_TYPE_SHORT},
  3319. {MQTT_PROP_MAXIMUM_QOS, MQTT_PROP_TYPE_BYTE},
  3320. {MQTT_PROP_RETAIN_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3321. {MQTT_PROP_USER_PROPERTY, MQTT_PROP_TYPE_STRING_PAIR},
  3322. {MQTT_PROP_MAXIMUM_PACKET_SIZE, MQTT_PROP_TYPE_INT},
  3323. {MQTT_PROP_WILDCARD_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3324. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3325. {MQTT_PROP_SHARED_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE}};
  3326. void mg_mqtt_send_header(struct mg_connection *c, uint8_t cmd, uint8_t flags,
  3327. uint32_t len) {
  3328. uint8_t buf[1 + sizeof(len)], *vlen = &buf[1];
  3329. buf[0] = (uint8_t) ((cmd << 4) | flags);
  3330. do {
  3331. *vlen = len % 0x80;
  3332. len /= 0x80;
  3333. if (len > 0) *vlen |= 0x80;
  3334. vlen++;
  3335. } while (len > 0 && vlen < &buf[sizeof(buf)]);
  3336. mg_send(c, buf, (size_t) (vlen - buf));
  3337. }
  3338. static void mg_send_u16(struct mg_connection *c, uint16_t value) {
  3339. mg_send(c, &value, sizeof(value));
  3340. }
  3341. static void mg_send_u32(struct mg_connection *c, uint32_t value) {
  3342. mg_send(c, &value, sizeof(value));
  3343. }
  3344. static uint8_t varint_size(size_t length) {
  3345. uint8_t bytes_needed = 0;
  3346. do {
  3347. bytes_needed++;
  3348. length /= 0x80;
  3349. } while (length > 0);
  3350. return bytes_needed;
  3351. }
  3352. static size_t encode_varint(uint8_t *buf, size_t value) {
  3353. size_t len = 0;
  3354. do {
  3355. uint8_t byte = (uint8_t) (value % 128);
  3356. value /= 128;
  3357. if (value > 0) byte |= 0x80;
  3358. buf[len++] = byte;
  3359. } while (value > 0);
  3360. return len;
  3361. }
  3362. static size_t decode_varint(const uint8_t *buf, size_t len, size_t *value) {
  3363. size_t multiplier = 1, offset;
  3364. *value = 0;
  3365. for (offset = 0; offset < 4 && offset < len; offset++) {
  3366. uint8_t encoded_byte = buf[offset];
  3367. *value += (encoded_byte & 0x7f) * multiplier;
  3368. multiplier *= 128;
  3369. if ((encoded_byte & 0x80) == 0) return offset + 1;
  3370. }
  3371. return 0;
  3372. }
  3373. static int mqtt_prop_type_by_id(uint8_t prop_id) {
  3374. size_t i, num_properties = sizeof(s_prop_map) / sizeof(s_prop_map[0]);
  3375. for (i = 0; i < num_properties; ++i) {
  3376. if (s_prop_map[i].id == prop_id) return s_prop_map[i].type;
  3377. }
  3378. return -1; // Property ID not found
  3379. }
  3380. // Returns the size of the properties section, without the
  3381. // size of the content's length
  3382. static size_t get_properties_length(struct mg_mqtt_prop *props, size_t count) {
  3383. size_t i, size = 0;
  3384. for (i = 0; i < count; i++) {
  3385. size++; // identifier
  3386. switch (mqtt_prop_type_by_id(props[i].id)) {
  3387. case MQTT_PROP_TYPE_STRING_PAIR:
  3388. size += (uint32_t) (props[i].val.len + props[i].key.len +
  3389. 2 * sizeof(uint16_t));
  3390. break;
  3391. case MQTT_PROP_TYPE_STRING:
  3392. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3393. break;
  3394. case MQTT_PROP_TYPE_BINARY_DATA:
  3395. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3396. break;
  3397. case MQTT_PROP_TYPE_VARIABLE_INT:
  3398. size += varint_size((uint32_t) props[i].iv);
  3399. break;
  3400. case MQTT_PROP_TYPE_INT:
  3401. size += (uint32_t) sizeof(uint32_t);
  3402. break;
  3403. case MQTT_PROP_TYPE_SHORT:
  3404. size += (uint32_t) sizeof(uint16_t);
  3405. break;
  3406. case MQTT_PROP_TYPE_BYTE:
  3407. size += (uint32_t) sizeof(uint8_t);
  3408. break;
  3409. default:
  3410. return size; // cannot parse further down
  3411. }
  3412. }
  3413. return size;
  3414. }
  3415. // returns the entire size of the properties section, including the
  3416. // size of the variable length of the content
  3417. static size_t get_props_size(struct mg_mqtt_prop *props, size_t count) {
  3418. size_t size = get_properties_length(props, count);
  3419. size += varint_size(size);
  3420. return size;
  3421. }
  3422. static void mg_send_mqtt_properties(struct mg_connection *c,
  3423. struct mg_mqtt_prop *props, size_t nprops) {
  3424. size_t total_size = get_properties_length(props, nprops);
  3425. uint8_t buf_v[4] = {0, 0, 0, 0};
  3426. uint8_t buf[4] = {0, 0, 0, 0};
  3427. size_t i, len = encode_varint(buf, total_size);
  3428. mg_send(c, buf, (size_t) len);
  3429. for (i = 0; i < nprops; i++) {
  3430. mg_send(c, &props[i].id, sizeof(props[i].id));
  3431. switch (mqtt_prop_type_by_id(props[i].id)) {
  3432. case MQTT_PROP_TYPE_STRING_PAIR:
  3433. mg_send_u16(c, mg_htons((uint16_t) props[i].key.len));
  3434. mg_send(c, props[i].key.ptr, props[i].key.len);
  3435. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3436. mg_send(c, props[i].val.ptr, props[i].val.len);
  3437. break;
  3438. case MQTT_PROP_TYPE_BYTE:
  3439. mg_send(c, &props[i].iv, sizeof(uint8_t));
  3440. break;
  3441. case MQTT_PROP_TYPE_SHORT:
  3442. mg_send_u16(c, mg_htons((uint16_t) props[i].iv));
  3443. break;
  3444. case MQTT_PROP_TYPE_INT:
  3445. mg_send_u32(c, mg_htonl((uint32_t) props[i].iv));
  3446. break;
  3447. case MQTT_PROP_TYPE_STRING:
  3448. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3449. mg_send(c, props[i].val.ptr, props[i].val.len);
  3450. break;
  3451. case MQTT_PROP_TYPE_BINARY_DATA:
  3452. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3453. mg_send(c, props[i].val.ptr, props[i].val.len);
  3454. break;
  3455. case MQTT_PROP_TYPE_VARIABLE_INT:
  3456. len = encode_varint(buf_v, props[i].iv);
  3457. mg_send(c, buf_v, (size_t) len);
  3458. break;
  3459. }
  3460. }
  3461. }
  3462. size_t mg_mqtt_next_prop(struct mg_mqtt_message *msg, struct mg_mqtt_prop *prop,
  3463. size_t ofs) {
  3464. uint8_t *i = (uint8_t *) msg->dgram.ptr + msg->props_start + ofs;
  3465. uint8_t *end = (uint8_t *) msg->dgram.ptr + msg->dgram.len;
  3466. size_t new_pos = ofs, len;
  3467. prop->id = i[0];
  3468. if (ofs >= msg->dgram.len || ofs >= msg->props_start + msg->props_size)
  3469. return 0;
  3470. i++, new_pos++;
  3471. switch (mqtt_prop_type_by_id(prop->id)) {
  3472. case MQTT_PROP_TYPE_STRING_PAIR:
  3473. prop->key.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3474. prop->key.ptr = (char *) i + 2;
  3475. i += 2 + prop->key.len;
  3476. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3477. prop->val.ptr = (char *) i + 2;
  3478. new_pos += 2 * sizeof(uint16_t) + prop->val.len + prop->key.len;
  3479. break;
  3480. case MQTT_PROP_TYPE_BYTE:
  3481. prop->iv = (uint8_t) i[0];
  3482. new_pos++;
  3483. break;
  3484. case MQTT_PROP_TYPE_SHORT:
  3485. prop->iv = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3486. new_pos += sizeof(uint16_t);
  3487. break;
  3488. case MQTT_PROP_TYPE_INT:
  3489. prop->iv = ((uint32_t) i[0] << 24) | ((uint32_t) i[1] << 16) |
  3490. ((uint32_t) i[2] << 8) | i[3];
  3491. new_pos += sizeof(uint32_t);
  3492. break;
  3493. case MQTT_PROP_TYPE_STRING:
  3494. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3495. prop->val.ptr = (char *) i + 2;
  3496. new_pos += 2 + prop->val.len;
  3497. break;
  3498. case MQTT_PROP_TYPE_BINARY_DATA:
  3499. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3500. prop->val.ptr = (char *) i + 2;
  3501. new_pos += 2 + prop->val.len;
  3502. break;
  3503. case MQTT_PROP_TYPE_VARIABLE_INT:
  3504. len = decode_varint(i, (size_t) (end - i), (size_t *) &prop->iv);
  3505. new_pos = (!len) ? 0 : new_pos + len;
  3506. break;
  3507. default:
  3508. new_pos = 0;
  3509. }
  3510. return new_pos;
  3511. }
  3512. void mg_mqtt_login(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3513. char rnd[10], client_id[21];
  3514. struct mg_str cid = opts->client_id;
  3515. size_t total_len = 7 + 1 + 2 + 2;
  3516. uint8_t hdr[8] = {0, 4, 'M', 'Q', 'T', 'T', opts->version, 0};
  3517. if (cid.len == 0) {
  3518. mg_random(rnd, sizeof(rnd));
  3519. mg_hex(rnd, sizeof(rnd), client_id);
  3520. client_id[sizeof(client_id) - 1] = '\0';
  3521. cid = mg_str(client_id);
  3522. }
  3523. if (hdr[6] == 0) hdr[6] = 4; // If version is not set, use 4 (3.1.1)
  3524. c->is_mqtt5 = hdr[6] == 5; // Set version 5 flag
  3525. hdr[7] = (uint8_t) ((opts->qos & 3) << 3); // Connection flags
  3526. if (opts->user.len > 0) {
  3527. total_len += 2 + (uint32_t) opts->user.len;
  3528. hdr[7] |= MQTT_HAS_USER_NAME;
  3529. }
  3530. if (opts->pass.len > 0) {
  3531. total_len += 2 + (uint32_t) opts->pass.len;
  3532. hdr[7] |= MQTT_HAS_PASSWORD;
  3533. }
  3534. if (opts->topic.len > 0 && opts->message.len > 0) {
  3535. total_len += 4 + (uint32_t) opts->topic.len + (uint32_t) opts->message.len;
  3536. hdr[7] |= MQTT_HAS_WILL;
  3537. }
  3538. if (opts->clean || cid.len == 0) hdr[7] |= MQTT_CLEAN_SESSION;
  3539. if (opts->retain) hdr[7] |= MQTT_WILL_RETAIN;
  3540. total_len += (uint32_t) cid.len;
  3541. if (c->is_mqtt5) {
  3542. total_len += get_props_size(opts->props, opts->num_props);
  3543. if (hdr[7] & MQTT_HAS_WILL)
  3544. total_len += get_props_size(opts->will_props, opts->num_will_props);
  3545. }
  3546. mg_mqtt_send_header(c, MQTT_CMD_CONNECT, 0, (uint32_t) total_len);
  3547. mg_send(c, hdr, sizeof(hdr));
  3548. // keepalive == 0 means "do not disconnect us!"
  3549. mg_send_u16(c, mg_htons((uint16_t) opts->keepalive));
  3550. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3551. mg_send_u16(c, mg_htons((uint16_t) cid.len));
  3552. mg_send(c, cid.ptr, cid.len);
  3553. if (hdr[7] & MQTT_HAS_WILL) {
  3554. if (c->is_mqtt5)
  3555. mg_send_mqtt_properties(c, opts->will_props, opts->num_will_props);
  3556. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3557. mg_send(c, opts->topic.ptr, opts->topic.len);
  3558. mg_send_u16(c, mg_htons((uint16_t) opts->message.len));
  3559. mg_send(c, opts->message.ptr, opts->message.len);
  3560. }
  3561. if (opts->user.len > 0) {
  3562. mg_send_u16(c, mg_htons((uint16_t) opts->user.len));
  3563. mg_send(c, opts->user.ptr, opts->user.len);
  3564. }
  3565. if (opts->pass.len > 0) {
  3566. mg_send_u16(c, mg_htons((uint16_t) opts->pass.len));
  3567. mg_send(c, opts->pass.ptr, opts->pass.len);
  3568. }
  3569. }
  3570. void mg_mqtt_pub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3571. uint8_t flags = (uint8_t) (((opts->qos & 3) << 1) | (opts->retain ? 1 : 0));
  3572. size_t len = 2 + opts->topic.len + opts->message.len;
  3573. MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) opts->topic.len,
  3574. (char *) opts->topic.ptr, (int) opts->message.len,
  3575. (char *) opts->message.ptr));
  3576. if (opts->qos > 0) len += 2;
  3577. if (c->is_mqtt5) len += get_props_size(opts->props, opts->num_props);
  3578. mg_mqtt_send_header(c, MQTT_CMD_PUBLISH, flags, (uint32_t) len);
  3579. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3580. mg_send(c, opts->topic.ptr, opts->topic.len);
  3581. if (opts->qos > 0) {
  3582. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  3583. mg_send_u16(c, mg_htons(c->mgr->mqtt_id));
  3584. }
  3585. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3586. if (opts->message.len > 0) mg_send(c, opts->message.ptr, opts->message.len);
  3587. }
  3588. void mg_mqtt_sub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3589. uint8_t qos_ = opts->qos & 3;
  3590. size_t plen = c->is_mqtt5 ? get_props_size(opts->props, opts->num_props) : 0;
  3591. size_t len = 2 + opts->topic.len + 2 + 1 + plen;
  3592. mg_mqtt_send_header(c, MQTT_CMD_SUBSCRIBE, 2, (uint32_t) len);
  3593. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  3594. mg_send_u16(c, mg_htons(c->mgr->mqtt_id));
  3595. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3596. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3597. mg_send(c, opts->topic.ptr, opts->topic.len);
  3598. mg_send(c, &qos_, sizeof(qos_));
  3599. }
  3600. int mg_mqtt_parse(const uint8_t *buf, size_t len, uint8_t version,
  3601. struct mg_mqtt_message *m) {
  3602. uint8_t lc = 0, *p, *end;
  3603. uint32_t n = 0, len_len = 0;
  3604. memset(m, 0, sizeof(*m));
  3605. m->dgram.ptr = (char *) buf;
  3606. if (len < 2) return MQTT_INCOMPLETE;
  3607. m->cmd = (uint8_t) (buf[0] >> 4);
  3608. m->qos = (buf[0] >> 1) & 3;
  3609. n = len_len = 0;
  3610. p = (uint8_t *) buf + 1;
  3611. while ((size_t) (p - buf) < len) {
  3612. lc = *((uint8_t *) p++);
  3613. n += (uint32_t) ((lc & 0x7f) << 7 * len_len);
  3614. len_len++;
  3615. if (!(lc & 0x80)) break;
  3616. if (len_len >= 4) return MQTT_MALFORMED;
  3617. }
  3618. end = p + n;
  3619. if ((lc & 0x80) || (end > buf + len)) return MQTT_INCOMPLETE;
  3620. m->dgram.len = (size_t) (end - buf);
  3621. switch (m->cmd) {
  3622. case MQTT_CMD_CONNACK:
  3623. if (end - p < 2) return MQTT_MALFORMED;
  3624. m->ack = p[1];
  3625. break;
  3626. case MQTT_CMD_PUBACK:
  3627. case MQTT_CMD_PUBREC:
  3628. case MQTT_CMD_PUBREL:
  3629. case MQTT_CMD_PUBCOMP:
  3630. case MQTT_CMD_SUBSCRIBE:
  3631. case MQTT_CMD_SUBACK:
  3632. case MQTT_CMD_UNSUBSCRIBE:
  3633. case MQTT_CMD_UNSUBACK:
  3634. if (p + 2 > end) return MQTT_MALFORMED;
  3635. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3636. p += 2;
  3637. break;
  3638. case MQTT_CMD_PUBLISH: {
  3639. if (p + 2 > end) return MQTT_MALFORMED;
  3640. m->topic.len = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3641. m->topic.ptr = (char *) p + 2;
  3642. p += 2 + m->topic.len;
  3643. if (p > end) return MQTT_MALFORMED;
  3644. if (m->qos > 0) {
  3645. if (p + 2 > end) return MQTT_MALFORMED;
  3646. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3647. p += 2;
  3648. }
  3649. if (p > end) return MQTT_MALFORMED;
  3650. if (version == 5 && p + 2 < end) {
  3651. len_len =
  3652. (uint32_t) decode_varint(p, (size_t) (end - p), &m->props_size);
  3653. if (!len_len) return MQTT_MALFORMED;
  3654. m->props_start = (size_t) (p + len_len - buf);
  3655. p += len_len + m->props_size;
  3656. }
  3657. if (p > end) return MQTT_MALFORMED;
  3658. m->data.ptr = (char *) p;
  3659. m->data.len = (size_t) (end - p);
  3660. break;
  3661. }
  3662. default:
  3663. break;
  3664. }
  3665. return MQTT_OK;
  3666. }
  3667. static void mqtt_cb(struct mg_connection *c, int ev, void *ev_data) {
  3668. if (ev == MG_EV_READ) {
  3669. for (;;) {
  3670. uint8_t version = c->is_mqtt5 ? 5 : 4;
  3671. struct mg_mqtt_message mm;
  3672. int rc = mg_mqtt_parse(c->recv.buf, c->recv.len, version, &mm);
  3673. if (rc == MQTT_MALFORMED) {
  3674. MG_ERROR(("%lu MQTT malformed message", c->id));
  3675. c->is_closing = 1;
  3676. break;
  3677. } else if (rc == MQTT_OK) {
  3678. MG_VERBOSE(("%lu MQTT CMD %d len %d [%.*s]", c->id, mm.cmd,
  3679. (int) mm.dgram.len, (int) mm.data.len, mm.data.ptr));
  3680. switch (mm.cmd) {
  3681. case MQTT_CMD_CONNACK:
  3682. mg_call(c, MG_EV_MQTT_OPEN, &mm.ack);
  3683. if (mm.ack == 0) {
  3684. MG_DEBUG(("%lu Connected", c->id));
  3685. } else {
  3686. MG_ERROR(("%lu MQTT auth failed, code %d", c->id, mm.ack));
  3687. c->is_closing = 1;
  3688. }
  3689. break;
  3690. case MQTT_CMD_PUBLISH: {
  3691. /*MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) mm.topic.len,
  3692. mm.topic.ptr, (int) mm.data.len, mm.data.ptr));*/
  3693. if (mm.qos > 0) {
  3694. uint16_t id = mg_ntohs(mm.id);
  3695. uint32_t remaining_len = sizeof(id);
  3696. if (c->is_mqtt5) remaining_len += 2; // 3.4.2
  3697. mg_mqtt_send_header(
  3698. c,
  3699. (uint8_t) (mm.qos == 2 ? MQTT_CMD_PUBREC : MQTT_CMD_PUBACK),
  3700. 0, remaining_len);
  3701. mg_send(c, &id, sizeof(id));
  3702. if (c->is_mqtt5) {
  3703. uint16_t zero = 0;
  3704. mg_send(c, &zero, sizeof(zero));
  3705. }
  3706. }
  3707. mg_call(c, MG_EV_MQTT_MSG, &mm); // let the app handle qos stuff
  3708. break;
  3709. }
  3710. case MQTT_CMD_PUBREC: { // MQTT5: 3.5.2-1 TODO(): variable header rc
  3711. uint16_t id = mg_ntohs(mm.id);
  3712. uint32_t remaining_len = sizeof(id); // MQTT5 3.6.2-1
  3713. mg_mqtt_send_header(c, MQTT_CMD_PUBREL, 2, remaining_len);
  3714. mg_send(c, &id, sizeof(id)); // MQTT5 3.6.1-1, flags = 2
  3715. break;
  3716. }
  3717. case MQTT_CMD_PUBREL: { // MQTT5: 3.6.2-1 TODO(): variable header rc
  3718. uint16_t id = mg_ntohs(mm.id);
  3719. uint32_t remaining_len = sizeof(id); // MQTT5 3.7.2-1
  3720. mg_mqtt_send_header(c, MQTT_CMD_PUBCOMP, 0, remaining_len);
  3721. mg_send(c, &id, sizeof(id));
  3722. break;
  3723. }
  3724. }
  3725. mg_call(c, MG_EV_MQTT_CMD, &mm);
  3726. mg_iobuf_del(&c->recv, 0, mm.dgram.len);
  3727. } else {
  3728. break;
  3729. }
  3730. }
  3731. }
  3732. (void) ev_data;
  3733. }
  3734. void mg_mqtt_ping(struct mg_connection *nc) {
  3735. mg_mqtt_send_header(nc, MQTT_CMD_PINGREQ, 0, 0);
  3736. }
  3737. void mg_mqtt_pong(struct mg_connection *nc) {
  3738. mg_mqtt_send_header(nc, MQTT_CMD_PINGRESP, 0, 0);
  3739. }
  3740. void mg_mqtt_disconnect(struct mg_connection *c,
  3741. const struct mg_mqtt_opts *opts) {
  3742. size_t len = 0;
  3743. if (c->is_mqtt5) len = 1 + get_props_size(opts->props, opts->num_props);
  3744. mg_mqtt_send_header(c, MQTT_CMD_DISCONNECT, 0, (uint32_t) len);
  3745. if (c->is_mqtt5) {
  3746. uint8_t zero = 0;
  3747. mg_send(c, &zero, sizeof(zero)); // reason code
  3748. mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3749. }
  3750. }
  3751. struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url,
  3752. const struct mg_mqtt_opts *opts,
  3753. mg_event_handler_t fn, void *fn_data) {
  3754. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  3755. if (c != NULL) {
  3756. struct mg_mqtt_opts empty;
  3757. memset(&empty, 0, sizeof(empty));
  3758. mg_mqtt_login(c, opts == NULL ? &empty : opts);
  3759. c->pfn = mqtt_cb;
  3760. }
  3761. return c;
  3762. }
  3763. struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url,
  3764. mg_event_handler_t fn, void *fn_data) {
  3765. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  3766. if (c != NULL) c->pfn = mqtt_cb, c->pfn_data = mgr;
  3767. return c;
  3768. }
  3769. #ifdef MG_ENABLE_LINES
  3770. #line 1 "src/net.c"
  3771. #endif
  3772. size_t mg_vprintf(struct mg_connection *c, const char *fmt, va_list *ap) {
  3773. size_t old = c->send.len;
  3774. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  3775. return c->send.len - old;
  3776. }
  3777. size_t mg_printf(struct mg_connection *c, const char *fmt, ...) {
  3778. size_t len = 0;
  3779. va_list ap;
  3780. va_start(ap, fmt);
  3781. len = mg_vprintf(c, fmt, &ap);
  3782. va_end(ap);
  3783. return len;
  3784. }
  3785. static bool mg_atonl(struct mg_str str, struct mg_addr *addr) {
  3786. uint32_t localhost = mg_htonl(0x7f000001);
  3787. if (mg_vcasecmp(&str, "localhost") != 0) return false;
  3788. memcpy(addr->ip, &localhost, sizeof(uint32_t));
  3789. addr->is_ip6 = false;
  3790. return true;
  3791. }
  3792. static bool mg_atone(struct mg_str str, struct mg_addr *addr) {
  3793. if (str.len > 0) return false;
  3794. memset(addr->ip, 0, sizeof(addr->ip));
  3795. addr->is_ip6 = false;
  3796. return true;
  3797. }
  3798. static bool mg_aton4(struct mg_str str, struct mg_addr *addr) {
  3799. uint8_t data[4] = {0, 0, 0, 0};
  3800. size_t i, num_dots = 0;
  3801. for (i = 0; i < str.len; i++) {
  3802. if (str.ptr[i] >= '0' && str.ptr[i] <= '9') {
  3803. int octet = data[num_dots] * 10 + (str.ptr[i] - '0');
  3804. if (octet > 255) return false;
  3805. data[num_dots] = (uint8_t) octet;
  3806. } else if (str.ptr[i] == '.') {
  3807. if (num_dots >= 3 || i == 0 || str.ptr[i - 1] == '.') return false;
  3808. num_dots++;
  3809. } else {
  3810. return false;
  3811. }
  3812. }
  3813. if (num_dots != 3 || str.ptr[i - 1] == '.') return false;
  3814. memcpy(&addr->ip, data, sizeof(data));
  3815. addr->is_ip6 = false;
  3816. return true;
  3817. }
  3818. static bool mg_v4mapped(struct mg_str str, struct mg_addr *addr) {
  3819. int i;
  3820. uint32_t ipv4;
  3821. if (str.len < 14) return false;
  3822. if (str.ptr[0] != ':' || str.ptr[1] != ':' || str.ptr[6] != ':') return false;
  3823. for (i = 2; i < 6; i++) {
  3824. if (str.ptr[i] != 'f' && str.ptr[i] != 'F') return false;
  3825. }
  3826. // struct mg_str s = mg_str_n(&str.ptr[7], str.len - 7);
  3827. if (!mg_aton4(mg_str_n(&str.ptr[7], str.len - 7), addr)) return false;
  3828. memcpy(&ipv4, addr->ip, sizeof(ipv4));
  3829. memset(addr->ip, 0, sizeof(addr->ip));
  3830. addr->ip[10] = addr->ip[11] = 255;
  3831. memcpy(&addr->ip[12], &ipv4, 4);
  3832. addr->is_ip6 = true;
  3833. return true;
  3834. }
  3835. static bool mg_aton6(struct mg_str str, struct mg_addr *addr) {
  3836. size_t i, j = 0, n = 0, dc = 42;
  3837. addr->scope_id = 0;
  3838. if (str.len > 2 && str.ptr[0] == '[') str.ptr++, str.len -= 2;
  3839. if (mg_v4mapped(str, addr)) return true;
  3840. for (i = 0; i < str.len; i++) {
  3841. if ((str.ptr[i] >= '0' && str.ptr[i] <= '9') ||
  3842. (str.ptr[i] >= 'a' && str.ptr[i] <= 'f') ||
  3843. (str.ptr[i] >= 'A' && str.ptr[i] <= 'F')) {
  3844. unsigned long val;
  3845. if (i > j + 3) return false;
  3846. // MG_DEBUG(("%lu %lu [%.*s]", i, j, (int) (i - j + 1), &str.ptr[j]));
  3847. val = mg_unhexn(&str.ptr[j], i - j + 1);
  3848. addr->ip[n] = (uint8_t) ((val >> 8) & 255);
  3849. addr->ip[n + 1] = (uint8_t) (val & 255);
  3850. } else if (str.ptr[i] == ':') {
  3851. j = i + 1;
  3852. if (i > 0 && str.ptr[i - 1] == ':') {
  3853. dc = n; // Double colon
  3854. if (i > 1 && str.ptr[i - 2] == ':') return false;
  3855. } else if (i > 0) {
  3856. n += 2;
  3857. }
  3858. if (n > 14) return false;
  3859. addr->ip[n] = addr->ip[n + 1] = 0; // For trailing ::
  3860. } else if (str.ptr[i] == '%') { // Scope ID
  3861. for (i = i + 1; i < str.len; i++) {
  3862. if (str.ptr[i] < '0' || str.ptr[i] > '9') return false;
  3863. addr->scope_id = (uint8_t) (addr->scope_id * 10);
  3864. addr->scope_id = (uint8_t) (addr->scope_id + (str.ptr[i] - '0'));
  3865. }
  3866. } else {
  3867. return false;
  3868. }
  3869. }
  3870. if (n < 14 && dc == 42) return false;
  3871. if (n < 14) {
  3872. memmove(&addr->ip[dc + (14 - n)], &addr->ip[dc], n - dc + 2);
  3873. memset(&addr->ip[dc], 0, 14 - n);
  3874. }
  3875. addr->is_ip6 = true;
  3876. return true;
  3877. }
  3878. bool mg_aton(struct mg_str str, struct mg_addr *addr) {
  3879. // MG_INFO(("[%.*s]", (int) str.len, str.ptr));
  3880. return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) ||
  3881. mg_aton6(str, addr);
  3882. }
  3883. struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) {
  3884. struct mg_connection *c =
  3885. (struct mg_connection *) calloc(1, sizeof(*c) + mgr->extraconnsize);
  3886. if (c != NULL) {
  3887. c->mgr = mgr;
  3888. c->send.align = c->recv.align = c->rtls.align = MG_IO_SIZE;
  3889. c->id = ++mgr->nextid;
  3890. MG_PROF_INIT(c);
  3891. }
  3892. return c;
  3893. }
  3894. void mg_close_conn(struct mg_connection *c) {
  3895. mg_resolve_cancel(c); // Close any pending DNS query
  3896. LIST_DELETE(struct mg_connection, &c->mgr->conns, c);
  3897. if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL;
  3898. if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL;
  3899. // Order of operations is important. `MG_EV_CLOSE` event must be fired
  3900. // before we deallocate received data, see #1331
  3901. mg_call(c, MG_EV_CLOSE, NULL);
  3902. MG_DEBUG(("%lu %ld closed", c->id, c->fd));
  3903. MG_PROF_DUMP(c);
  3904. MG_PROF_FREE(c);
  3905. mg_tls_free(c);
  3906. mg_iobuf_free(&c->recv);
  3907. mg_iobuf_free(&c->send);
  3908. mg_iobuf_free(&c->rtls);
  3909. mg_bzero((unsigned char *) c, sizeof(*c));
  3910. free(c);
  3911. }
  3912. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url,
  3913. mg_event_handler_t fn, void *fn_data) {
  3914. struct mg_connection *c = NULL;
  3915. if (url == NULL || url[0] == '\0') {
  3916. MG_ERROR(("null url"));
  3917. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  3918. MG_ERROR(("OOM"));
  3919. } else {
  3920. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3921. c->is_udp = (strncmp(url, "udp:", 4) == 0);
  3922. c->fd = (void *) (size_t) MG_INVALID_SOCKET;
  3923. c->fn = fn;
  3924. c->is_client = true;
  3925. c->fn_data = fn_data;
  3926. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  3927. mg_call(c, MG_EV_OPEN, (void *) url);
  3928. mg_resolve(c, url);
  3929. }
  3930. return c;
  3931. }
  3932. struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url,
  3933. mg_event_handler_t fn, void *fn_data) {
  3934. struct mg_connection *c = NULL;
  3935. if ((c = mg_alloc_conn(mgr)) == NULL) {
  3936. MG_ERROR(("OOM %s", url));
  3937. } else if (!mg_open_listener(c, url)) {
  3938. MG_ERROR(("Failed: %s, errno %d", url, errno));
  3939. MG_PROF_FREE(c);
  3940. free(c);
  3941. c = NULL;
  3942. } else {
  3943. c->is_listening = 1;
  3944. c->is_udp = strncmp(url, "udp:", 4) == 0;
  3945. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3946. c->fn = fn;
  3947. c->fn_data = fn_data;
  3948. mg_call(c, MG_EV_OPEN, NULL);
  3949. if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must
  3950. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  3951. }
  3952. return c;
  3953. }
  3954. struct mg_connection *mg_wrapfd(struct mg_mgr *mgr, int fd,
  3955. mg_event_handler_t fn, void *fn_data) {
  3956. struct mg_connection *c = mg_alloc_conn(mgr);
  3957. if (c != NULL) {
  3958. c->fd = (void *) (size_t) fd;
  3959. c->fn = fn;
  3960. c->fn_data = fn_data;
  3961. MG_EPOLL_ADD(c);
  3962. mg_call(c, MG_EV_OPEN, NULL);
  3963. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3964. }
  3965. return c;
  3966. }
  3967. struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds,
  3968. unsigned flags, void (*fn)(void *), void *arg) {
  3969. struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t));
  3970. if (t != NULL) {
  3971. mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg);
  3972. t->id = mgr->timerid++;
  3973. }
  3974. return t;
  3975. }
  3976. long mg_io_recv(struct mg_connection *c, void *buf, size_t len) {
  3977. if (c->rtls.len == 0) return MG_IO_WAIT;
  3978. if (len > c->rtls.len) len = c->rtls.len;
  3979. memcpy(buf, c->rtls.buf, len);
  3980. mg_iobuf_del(&c->rtls, 0, len);
  3981. return (long) len;
  3982. }
  3983. void mg_mgr_free(struct mg_mgr *mgr) {
  3984. struct mg_connection *c;
  3985. struct mg_timer *tmp, *t = mgr->timers;
  3986. while (t != NULL) tmp = t->next, free(t), t = tmp;
  3987. mgr->timers = NULL; // Important. Next call to poll won't touch timers
  3988. for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1;
  3989. mg_mgr_poll(mgr, 0);
  3990. #if MG_ENABLE_FREERTOS_TCP
  3991. FreeRTOS_DeleteSocketSet(mgr->ss);
  3992. #endif
  3993. MG_DEBUG(("All connections closed"));
  3994. #if MG_ENABLE_EPOLL
  3995. if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1;
  3996. #endif
  3997. mg_tls_ctx_free(mgr);
  3998. }
  3999. void mg_mgr_init(struct mg_mgr *mgr) {
  4000. memset(mgr, 0, sizeof(*mgr));
  4001. #if MG_ENABLE_EPOLL
  4002. if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
  4003. MG_ERROR(("epoll_create1 errno %d", errno));
  4004. #else
  4005. mgr->epoll_fd = -1;
  4006. #endif
  4007. #if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  4008. // clang-format off
  4009. { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
  4010. // clang-format on
  4011. #elif MG_ENABLE_FREERTOS_TCP
  4012. mgr->ss = FreeRTOS_CreateSocketSet();
  4013. #elif defined(__unix) || defined(__unix__) || defined(__APPLE__)
  4014. // Ignore SIGPIPE signal, so if client cancels the request, it
  4015. // won't kill the whole process.
  4016. signal(SIGPIPE, SIG_IGN);
  4017. #endif
  4018. mgr->pipe = MG_INVALID_SOCKET;
  4019. mgr->dnstimeout = 3000;
  4020. mgr->dns4.url = "udp://8.8.8.8:53";
  4021. mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
  4022. mg_tls_ctx_init(mgr);
  4023. }
  4024. #ifdef MG_ENABLE_LINES
  4025. #line 1 "src/net_builtin.c"
  4026. #endif
  4027. #if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP
  4028. #define MG_EPHEMERAL_PORT_BASE 32768
  4029. #define PDIFF(a, b) ((size_t) (((char *) (b)) - ((char *) (a))))
  4030. #ifndef MIP_TCP_KEEPALIVE_MS
  4031. #define MIP_TCP_KEEPALIVE_MS 45000 // TCP keep-alive period, ms
  4032. #endif
  4033. #define MIP_TCP_ACK_MS 150 // Timeout for ACKing
  4034. #define MIP_TCP_ARP_MS 100 // Timeout for ARP response
  4035. #define MIP_TCP_SYN_MS 15000 // Timeout for connection establishment
  4036. #define MIP_TCP_FIN_MS 1000 // Timeout for closing connection
  4037. struct connstate {
  4038. uint32_t seq, ack; // TCP seq/ack counters
  4039. uint64_t timer; // TCP keep-alive / ACK timer
  4040. uint8_t mac[6]; // Peer MAC address
  4041. uint8_t ttype; // Timer type. 0: ack, 1: keep-alive
  4042. #define MIP_TTYPE_KEEPALIVE 0 // Connection is idle for long, send keepalive
  4043. #define MIP_TTYPE_ACK 1 // Peer sent us data, we have to ack it soon
  4044. #define MIP_TTYPE_ARP 2 // ARP resolve sent, waiting for response
  4045. #define MIP_TTYPE_SYN 3 // SYN sent, waiting for response
  4046. #define MIP_TTYPE_FIN 4 // FIN sent, waiting until terminating the connection
  4047. uint8_t tmiss; // Number of keep-alive misses
  4048. struct mg_iobuf raw; // For TLS only. Incoming raw data
  4049. };
  4050. #pragma pack(push, 1)
  4051. struct lcp {
  4052. uint8_t addr, ctrl, proto[2], code, id, len[2];
  4053. };
  4054. struct eth {
  4055. uint8_t dst[6]; // Destination MAC address
  4056. uint8_t src[6]; // Source MAC address
  4057. uint16_t type; // Ethernet type
  4058. };
  4059. struct ip {
  4060. uint8_t ver; // Version
  4061. uint8_t tos; // Unused
  4062. uint16_t len; // Length
  4063. uint16_t id; // Unused
  4064. uint16_t frag; // Fragmentation
  4065. #define IP_FRAG_OFFSET_MSK 0xFF1F
  4066. #define IP_MORE_FRAGS_MSK 0x20
  4067. uint8_t ttl; // Time to live
  4068. uint8_t proto; // Upper level protocol
  4069. uint16_t csum; // Checksum
  4070. uint32_t src; // Source IP
  4071. uint32_t dst; // Destination IP
  4072. };
  4073. struct ip6 {
  4074. uint8_t ver; // Version
  4075. uint8_t opts[3]; // Options
  4076. uint16_t len; // Length
  4077. uint8_t proto; // Upper level protocol
  4078. uint8_t ttl; // Time to live
  4079. uint8_t src[16]; // Source IP
  4080. uint8_t dst[16]; // Destination IP
  4081. };
  4082. struct icmp {
  4083. uint8_t type;
  4084. uint8_t code;
  4085. uint16_t csum;
  4086. };
  4087. struct arp {
  4088. uint16_t fmt; // Format of hardware address
  4089. uint16_t pro; // Format of protocol address
  4090. uint8_t hlen; // Length of hardware address
  4091. uint8_t plen; // Length of protocol address
  4092. uint16_t op; // Operation
  4093. uint8_t sha[6]; // Sender hardware address
  4094. uint32_t spa; // Sender protocol address
  4095. uint8_t tha[6]; // Target hardware address
  4096. uint32_t tpa; // Target protocol address
  4097. };
  4098. struct tcp {
  4099. uint16_t sport; // Source port
  4100. uint16_t dport; // Destination port
  4101. uint32_t seq; // Sequence number
  4102. uint32_t ack; // Acknowledgement number
  4103. uint8_t off; // Data offset
  4104. uint8_t flags; // TCP flags
  4105. #define TH_FIN 0x01
  4106. #define TH_SYN 0x02
  4107. #define TH_RST 0x04
  4108. #define TH_PUSH 0x08
  4109. #define TH_ACK 0x10
  4110. #define TH_URG 0x20
  4111. #define TH_ECE 0x40
  4112. #define TH_CWR 0x80
  4113. uint16_t win; // Window
  4114. uint16_t csum; // Checksum
  4115. uint16_t urp; // Urgent pointer
  4116. };
  4117. struct udp {
  4118. uint16_t sport; // Source port
  4119. uint16_t dport; // Destination port
  4120. uint16_t len; // UDP length
  4121. uint16_t csum; // UDP checksum
  4122. };
  4123. struct dhcp {
  4124. uint8_t op, htype, hlen, hops;
  4125. uint32_t xid;
  4126. uint16_t secs, flags;
  4127. uint32_t ciaddr, yiaddr, siaddr, giaddr;
  4128. uint8_t hwaddr[208];
  4129. uint32_t magic;
  4130. uint8_t options[32];
  4131. };
  4132. #pragma pack(pop)
  4133. struct pkt {
  4134. struct mg_str raw; // Raw packet data
  4135. struct mg_str pay; // Payload data
  4136. struct eth *eth;
  4137. struct llc *llc;
  4138. struct arp *arp;
  4139. struct ip *ip;
  4140. struct ip6 *ip6;
  4141. struct icmp *icmp;
  4142. struct tcp *tcp;
  4143. struct udp *udp;
  4144. struct dhcp *dhcp;
  4145. };
  4146. static void send_syn(struct mg_connection *c);
  4147. static void mkpay(struct pkt *pkt, void *p) {
  4148. pkt->pay =
  4149. mg_str_n((char *) p, (size_t) (&pkt->raw.ptr[pkt->raw.len] - (char *) p));
  4150. }
  4151. static uint32_t csumup(uint32_t sum, const void *buf, size_t len) {
  4152. const uint8_t *p = (const uint8_t *) buf;
  4153. for (size_t i = 0; i < len; i++) sum += i & 1 ? p[i] : (uint32_t) (p[i] << 8);
  4154. return sum;
  4155. }
  4156. static uint16_t csumfin(uint32_t sum) {
  4157. while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
  4158. return mg_htons(~sum & 0xffff);
  4159. }
  4160. static uint16_t ipcsum(const void *buf, size_t len) {
  4161. uint32_t sum = csumup(0, buf, len);
  4162. return csumfin(sum);
  4163. }
  4164. static void settmout(struct mg_connection *c, uint8_t type) {
  4165. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4166. struct connstate *s = (struct connstate *) (c + 1);
  4167. unsigned n = type == MIP_TTYPE_ACK ? MIP_TCP_ACK_MS
  4168. : type == MIP_TTYPE_ARP ? MIP_TCP_ARP_MS
  4169. : type == MIP_TTYPE_SYN ? MIP_TCP_SYN_MS
  4170. : type == MIP_TTYPE_FIN ? MIP_TCP_FIN_MS
  4171. : MIP_TCP_KEEPALIVE_MS;
  4172. s->timer = ifp->now + n;
  4173. s->ttype = type;
  4174. MG_VERBOSE(("%lu %d -> %llx", c->id, type, s->timer));
  4175. }
  4176. static size_t ether_output(struct mg_tcpip_if *ifp, size_t len) {
  4177. size_t n = ifp->driver->tx(ifp->tx.ptr, len, ifp);
  4178. if (n == len) ifp->nsent++;
  4179. return n;
  4180. }
  4181. static void arp_ask(struct mg_tcpip_if *ifp, uint32_t ip) {
  4182. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4183. struct arp *arp = (struct arp *) (eth + 1);
  4184. memset(eth->dst, 255, sizeof(eth->dst));
  4185. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4186. eth->type = mg_htons(0x806);
  4187. memset(arp, 0, sizeof(*arp));
  4188. arp->fmt = mg_htons(1), arp->pro = mg_htons(0x800), arp->hlen = 6,
  4189. arp->plen = 4;
  4190. arp->op = mg_htons(1), arp->tpa = ip, arp->spa = ifp->ip;
  4191. memcpy(arp->sha, ifp->mac, sizeof(arp->sha));
  4192. ether_output(ifp, PDIFF(eth, arp + 1));
  4193. }
  4194. static void onstatechange(struct mg_tcpip_if *ifp) {
  4195. if (ifp->state == MG_TCPIP_STATE_READY) {
  4196. MG_INFO(("READY, IP: %M", mg_print_ip4, &ifp->ip));
  4197. MG_INFO((" GW: %M", mg_print_ip4, &ifp->gw));
  4198. MG_INFO((" MAC: %M", mg_print_mac, &ifp->mac));
  4199. arp_ask(ifp, ifp->gw);
  4200. } else if (ifp->state == MG_TCPIP_STATE_UP) {
  4201. MG_ERROR(("Link up"));
  4202. srand((unsigned int) mg_millis());
  4203. } else if (ifp->state == MG_TCPIP_STATE_DOWN) {
  4204. MG_ERROR(("Link down"));
  4205. }
  4206. }
  4207. static struct ip *tx_ip(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4208. uint8_t proto, uint32_t ip_src, uint32_t ip_dst,
  4209. size_t plen) {
  4210. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4211. struct ip *ip = (struct ip *) (eth + 1);
  4212. memcpy(eth->dst, mac_dst, sizeof(eth->dst));
  4213. memcpy(eth->src, ifp->mac, sizeof(eth->src)); // Use our MAC
  4214. eth->type = mg_htons(0x800);
  4215. memset(ip, 0, sizeof(*ip));
  4216. ip->ver = 0x45; // Version 4, header length 5 words
  4217. ip->frag = 0x40; // Don't fragment
  4218. ip->len = mg_htons((uint16_t) (sizeof(*ip) + plen));
  4219. ip->ttl = 64;
  4220. ip->proto = proto;
  4221. ip->src = ip_src;
  4222. ip->dst = ip_dst;
  4223. ip->csum = ipcsum(ip, sizeof(*ip));
  4224. return ip;
  4225. }
  4226. static void tx_udp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4227. uint16_t sport, uint32_t ip_dst, uint16_t dport,
  4228. const void *buf, size_t len) {
  4229. struct ip *ip =
  4230. tx_ip(ifp, mac_dst, 17, ip_src, ip_dst, len + sizeof(struct udp));
  4231. struct udp *udp = (struct udp *) (ip + 1);
  4232. // MG_DEBUG(("UDP XX LEN %d %d", (int) len, (int) ifp->tx.len));
  4233. udp->sport = sport;
  4234. udp->dport = dport;
  4235. udp->len = mg_htons((uint16_t) (sizeof(*udp) + len));
  4236. udp->csum = 0;
  4237. uint32_t cs = csumup(0, udp, sizeof(*udp));
  4238. cs = csumup(cs, buf, len);
  4239. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4240. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4241. cs += (uint32_t) (ip->proto + sizeof(*udp) + len);
  4242. udp->csum = csumfin(cs);
  4243. memmove(udp + 1, buf, len);
  4244. // MG_DEBUG(("UDP LEN %d %d", (int) len, (int) ifp->frame_len));
  4245. ether_output(ifp, sizeof(struct eth) + sizeof(*ip) + sizeof(*udp) + len);
  4246. }
  4247. static void tx_dhcp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4248. uint32_t ip_dst, uint8_t *opts, size_t optslen,
  4249. bool ciaddr) {
  4250. // https://datatracker.ietf.org/doc/html/rfc2132#section-9.6
  4251. struct dhcp dhcp = {1, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4252. dhcp.magic = mg_htonl(0x63825363);
  4253. memcpy(&dhcp.hwaddr, ifp->mac, sizeof(ifp->mac));
  4254. memcpy(&dhcp.xid, ifp->mac + 2, sizeof(dhcp.xid));
  4255. memcpy(&dhcp.options, opts, optslen);
  4256. if (ciaddr) dhcp.ciaddr = ip_src;
  4257. tx_udp(ifp, mac_dst, ip_src, mg_htons(68), ip_dst, mg_htons(67), &dhcp,
  4258. sizeof(dhcp));
  4259. }
  4260. static const uint8_t broadcast[] = {255, 255, 255, 255, 255, 255};
  4261. // RFC-2131 #4.3.6, #4.4.1
  4262. static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
  4263. uint32_t ip_srv) {
  4264. uint8_t opts[] = {
  4265. 53, 1, 3, // Type: DHCP request
  4266. 55, 2, 1, 3, // GW and mask
  4267. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4268. 54, 4, 0, 0, 0, 0, // DHCP server ID
  4269. 50, 4, 0, 0, 0, 0, // Requested IP
  4270. 255 // End of options
  4271. };
  4272. memcpy(opts + 14, &ip_srv, sizeof(ip_srv));
  4273. memcpy(opts + 20, &ip_req, sizeof(ip_req));
  4274. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4275. MG_DEBUG(("DHCP req sent"));
  4276. }
  4277. // RFC-2131 #4.3.6, #4.4.5 (renewing: unicast, rebinding: bcast)
  4278. static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4279. uint32_t ip_src, uint32_t ip_dst) {
  4280. uint8_t opts[] = {
  4281. 53, 1, 3, // Type: DHCP request
  4282. 255 // End of options
  4283. };
  4284. tx_dhcp(ifp, mac_dst, ip_src, ip_dst, opts, sizeof(opts), true);
  4285. MG_DEBUG(("DHCP req sent"));
  4286. }
  4287. static void tx_dhcp_discover(struct mg_tcpip_if *ifp) {
  4288. uint8_t opts[] = {
  4289. 53, 1, 1, // Type: DHCP discover
  4290. 55, 2, 1, 3, // Parameters: ip, mask
  4291. 255 // End of options
  4292. };
  4293. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4294. MG_DEBUG(("DHCP discover sent. Our MAC: %M", mg_print_mac, ifp->mac));
  4295. }
  4296. static struct mg_connection *getpeer(struct mg_mgr *mgr, struct pkt *pkt,
  4297. bool lsn) {
  4298. struct mg_connection *c = NULL;
  4299. for (c = mgr->conns; c != NULL; c = c->next) {
  4300. if (c->is_arplooking && pkt->arp &&
  4301. memcmp(&pkt->arp->spa, c->rem.ip, sizeof(pkt->arp->spa)) == 0)
  4302. break;
  4303. if (c->is_udp && pkt->udp && c->loc.port == pkt->udp->dport) break;
  4304. if (!c->is_udp && pkt->tcp && c->loc.port == pkt->tcp->dport &&
  4305. lsn == c->is_listening && (lsn || c->rem.port == pkt->tcp->sport))
  4306. break;
  4307. }
  4308. return c;
  4309. }
  4310. static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4311. if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) {
  4312. // ARP request. Make a response, then send
  4313. // MG_DEBUG(("ARP op %d %M: %M", mg_ntohs(pkt->arp->op), mg_print_ip4,
  4314. // &pkt->arp->spa, mg_print_ip4, &pkt->arp->tpa));
  4315. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4316. struct arp *arp = (struct arp *) (eth + 1);
  4317. memcpy(eth->dst, pkt->eth->src, sizeof(eth->dst));
  4318. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4319. eth->type = mg_htons(0x806);
  4320. *arp = *pkt->arp;
  4321. arp->op = mg_htons(2);
  4322. memcpy(arp->tha, pkt->arp->sha, sizeof(pkt->arp->tha));
  4323. memcpy(arp->sha, ifp->mac, sizeof(pkt->arp->sha));
  4324. arp->tpa = pkt->arp->spa;
  4325. arp->spa = ifp->ip;
  4326. MG_DEBUG(("ARP: tell %M we're %M", mg_print_ip4, &arp->tpa, mg_print_mac,
  4327. &ifp->mac));
  4328. ether_output(ifp, PDIFF(eth, arp + 1));
  4329. } else if (pkt->arp->op == mg_htons(2)) {
  4330. if (memcmp(pkt->arp->tha, ifp->mac, sizeof(pkt->arp->tha)) != 0) return;
  4331. if (pkt->arp->spa == ifp->gw) {
  4332. // Got response for the GW ARP request. Set ifp->gwmac
  4333. memcpy(ifp->gwmac, pkt->arp->sha, sizeof(ifp->gwmac));
  4334. } else {
  4335. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4336. if (c != NULL && c->is_arplooking) {
  4337. struct connstate *s = (struct connstate *) (c + 1);
  4338. memcpy(s->mac, pkt->arp->sha, sizeof(s->mac));
  4339. MG_DEBUG(("%lu ARP resolved %M -> %M", c->id, mg_print_ip4, c->rem.ip,
  4340. mg_print_mac, s->mac));
  4341. c->is_arplooking = 0;
  4342. send_syn(c);
  4343. settmout(c, MIP_TTYPE_SYN);
  4344. }
  4345. }
  4346. }
  4347. }
  4348. static void rx_icmp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4349. // MG_DEBUG(("ICMP %d", (int) len));
  4350. if (pkt->icmp->type == 8 && pkt->ip != NULL && pkt->ip->dst == ifp->ip) {
  4351. size_t hlen = sizeof(struct eth) + sizeof(struct ip) + sizeof(struct icmp);
  4352. size_t space = ifp->tx.len - hlen, plen = pkt->pay.len;
  4353. if (plen > space) plen = space;
  4354. struct ip *ip = tx_ip(ifp, pkt->eth->src, 1, ifp->ip, pkt->ip->src,
  4355. sizeof(struct icmp) + plen);
  4356. struct icmp *icmp = (struct icmp *) (ip + 1);
  4357. memset(icmp, 0, sizeof(*icmp)); // Set csum to 0
  4358. memcpy(icmp + 1, pkt->pay.ptr, plen); // Copy RX payload to TX
  4359. icmp->csum = ipcsum(icmp, sizeof(*icmp) + plen);
  4360. ether_output(ifp, hlen + plen);
  4361. }
  4362. }
  4363. static void rx_dhcp_client(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4364. uint32_t ip = 0, gw = 0, mask = 0, lease = 0;
  4365. uint8_t msgtype = 0, state = ifp->state;
  4366. // perform size check first, then access fields
  4367. uint8_t *p = pkt->dhcp->options,
  4368. *end = (uint8_t *) &pkt->raw.ptr[pkt->raw.len];
  4369. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4370. if (memcmp(&pkt->dhcp->xid, ifp->mac + 2, sizeof(pkt->dhcp->xid))) return;
  4371. while (p + 1 < end && p[0] != 255) { // Parse options RFC-1533 #9
  4372. if (p[0] == 1 && p[1] == sizeof(ifp->mask) && p + 6 < end) { // Mask
  4373. memcpy(&mask, p + 2, sizeof(mask));
  4374. } else if (p[0] == 3 && p[1] == sizeof(ifp->gw) && p + 6 < end) { // GW
  4375. memcpy(&gw, p + 2, sizeof(gw));
  4376. ip = pkt->dhcp->yiaddr;
  4377. } else if (p[0] == 51 && p[1] == 4 && p + 6 < end) { // Lease
  4378. memcpy(&lease, p + 2, sizeof(lease));
  4379. lease = mg_ntohl(lease);
  4380. } else if (p[0] == 53 && p[1] == 1 && p + 6 < end) { // Msg Type
  4381. msgtype = p[2];
  4382. }
  4383. p += p[1] + 2;
  4384. }
  4385. // Process message type, RFC-1533 (9.4); RFC-2131 (3.1, 4)
  4386. if (msgtype == 6 && ifp->ip == ip) { // DHCPNACK, release IP
  4387. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0;
  4388. } else if (msgtype == 2 && ifp->state == MG_TCPIP_STATE_UP && ip && gw &&
  4389. lease) { // DHCPOFFER
  4390. tx_dhcp_request_sel(ifp, ip, pkt->dhcp->siaddr); // select IP, (4.4.1)
  4391. ifp->state = MG_TCPIP_STATE_REQ; // REQUESTING state
  4392. } else if (msgtype == 5) { // DHCPACK
  4393. if (ifp->state == MG_TCPIP_STATE_REQ && ip && gw && lease) { // got an IP
  4394. ifp->lease_expire = ifp->now + lease * 1000;
  4395. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4396. // assume DHCP server = router until ARP resolves
  4397. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4398. ifp->ip = ip, ifp->gw = gw, ifp->mask = mask;
  4399. ifp->state = MG_TCPIP_STATE_READY; // BOUND state
  4400. uint64_t rand;
  4401. mg_random(&rand, sizeof(rand));
  4402. srand((unsigned int) (rand + mg_millis()));
  4403. } else if (ifp->state == MG_TCPIP_STATE_READY && ifp->ip == ip) { // renew
  4404. ifp->lease_expire = ifp->now + lease * 1000;
  4405. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4406. } // TODO(): accept provided T1/T2 and store server IP for renewal (4.4)
  4407. }
  4408. if (ifp->state != state) onstatechange(ifp);
  4409. }
  4410. // Simple DHCP server that assigns a next IP address: ifp->ip + 1
  4411. static void rx_dhcp_server(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4412. uint8_t op = 0, *p = pkt->dhcp->options,
  4413. *end = (uint8_t *) &pkt->raw.ptr[pkt->raw.len];
  4414. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4415. // struct dhcp *req = pkt->dhcp;
  4416. struct dhcp res = {2, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4417. res.yiaddr = ifp->ip;
  4418. ((uint8_t *) (&res.yiaddr))[3]++; // Offer our IP + 1
  4419. while (p + 1 < end && p[0] != 255) { // Parse options
  4420. if (p[0] == 53 && p[1] == 1 && p + 2 < end) { // Message type
  4421. op = p[2];
  4422. }
  4423. p += p[1] + 2;
  4424. }
  4425. if (op == 1 || op == 3) { // DHCP Discover or DHCP Request
  4426. uint8_t msg = op == 1 ? 2 : 5; // Message type: DHCP OFFER or DHCP ACK
  4427. uint8_t opts[] = {
  4428. 53, 1, msg, // Message type
  4429. 1, 4, 0, 0, 0, 0, // Subnet mask
  4430. 54, 4, 0, 0, 0, 0, // Server ID
  4431. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4432. 51, 4, 255, 255, 255, 255, // Lease time
  4433. 255 // End of options
  4434. };
  4435. memcpy(&res.hwaddr, pkt->dhcp->hwaddr, 6);
  4436. memcpy(opts + 5, &ifp->mask, sizeof(ifp->mask));
  4437. memcpy(opts + 11, &ifp->ip, sizeof(ifp->ip));
  4438. memcpy(&res.options, opts, sizeof(opts));
  4439. res.magic = pkt->dhcp->magic;
  4440. res.xid = pkt->dhcp->xid;
  4441. if (ifp->enable_get_gateway) {
  4442. ifp->gw = res.yiaddr;
  4443. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4444. }
  4445. tx_udp(ifp, pkt->eth->src, ifp->ip, mg_htons(67),
  4446. op == 1 ? ~0U : res.yiaddr, mg_htons(68), &res, sizeof(res));
  4447. }
  4448. }
  4449. static void rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4450. struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
  4451. if (c == NULL) {
  4452. // No UDP listener on this port. Should send ICMP, but keep silent.
  4453. } else {
  4454. c->rem.port = pkt->udp->sport;
  4455. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4456. struct connstate *s = (struct connstate *) (c + 1);
  4457. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4458. if (c->recv.len >= MG_MAX_RECV_SIZE) {
  4459. mg_error(c, "max_recv_buf_size reached");
  4460. } else if (c->recv.size - c->recv.len < pkt->pay.len &&
  4461. !mg_iobuf_resize(&c->recv, c->recv.len + pkt->pay.len)) {
  4462. mg_error(c, "oom");
  4463. } else {
  4464. memcpy(&c->recv.buf[c->recv.len], pkt->pay.ptr, pkt->pay.len);
  4465. c->recv.len += pkt->pay.len;
  4466. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4467. }
  4468. }
  4469. }
  4470. static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *dst_mac, uint32_t dst_ip,
  4471. uint8_t flags, uint16_t sport, uint16_t dport,
  4472. uint32_t seq, uint32_t ack, const void *buf, size_t len) {
  4473. struct ip *ip =
  4474. tx_ip(ifp, dst_mac, 6, ifp->ip, dst_ip, sizeof(struct tcp) + len);
  4475. struct tcp *tcp = (struct tcp *) (ip + 1);
  4476. memset(tcp, 0, sizeof(*tcp));
  4477. if (buf != NULL && len) memmove(tcp + 1, buf, len);
  4478. tcp->sport = sport;
  4479. tcp->dport = dport;
  4480. tcp->seq = seq;
  4481. tcp->ack = ack;
  4482. tcp->flags = flags;
  4483. tcp->win = mg_htons(8192);
  4484. tcp->off = (uint8_t) (sizeof(*tcp) / 4 << 4);
  4485. uint32_t cs = 0;
  4486. uint16_t n = (uint16_t) (sizeof(*tcp) + len);
  4487. uint8_t pseudo[] = {0, ip->proto, (uint8_t) (n >> 8), (uint8_t) (n & 255)};
  4488. cs = csumup(cs, tcp, n);
  4489. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4490. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4491. cs = csumup(cs, pseudo, sizeof(pseudo));
  4492. tcp->csum = csumfin(cs);
  4493. MG_VERBOSE(("TCP %M:%hu -> %M:%hu fl %x len %u", mg_print_ip4, &ip->src,
  4494. mg_ntohs(tcp->sport), mg_print_ip4, &ip->dst,
  4495. mg_ntohs(tcp->dport), tcp->flags, (int) len));
  4496. // mg_hexdump(ifp->tx.ptr, PDIFF(ifp->tx.ptr, tcp + 1) + len);
  4497. return ether_output(ifp, PDIFF(ifp->tx.ptr, tcp + 1) + len);
  4498. }
  4499. static size_t tx_tcp_pkt(struct mg_tcpip_if *ifp, struct pkt *pkt,
  4500. uint8_t flags, uint32_t seq, const void *buf,
  4501. size_t len) {
  4502. uint32_t delta = (pkt->tcp->flags & (TH_SYN | TH_FIN)) ? 1 : 0;
  4503. return tx_tcp(ifp, pkt->eth->src, pkt->ip->src, flags, pkt->tcp->dport,
  4504. pkt->tcp->sport, seq, mg_htonl(mg_ntohl(pkt->tcp->seq) + delta),
  4505. buf, len);
  4506. }
  4507. static struct mg_connection *accept_conn(struct mg_connection *lsn,
  4508. struct pkt *pkt) {
  4509. struct mg_connection *c = mg_alloc_conn(lsn->mgr);
  4510. if (c == NULL) {
  4511. MG_ERROR(("OOM"));
  4512. return NULL;
  4513. }
  4514. struct connstate *s = (struct connstate *) (c + 1);
  4515. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq);
  4516. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4517. settmout(c, MIP_TTYPE_KEEPALIVE);
  4518. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4519. c->rem.port = pkt->tcp->sport;
  4520. MG_DEBUG(("%lu accepted %M", c->id, mg_print_ip_port, &c->rem));
  4521. LIST_ADD_HEAD(struct mg_connection, &lsn->mgr->conns, c);
  4522. c->is_accepted = 1;
  4523. c->is_hexdumping = lsn->is_hexdumping;
  4524. c->pfn = lsn->pfn;
  4525. c->loc = lsn->loc;
  4526. c->pfn_data = lsn->pfn_data;
  4527. c->fn = lsn->fn;
  4528. c->fn_data = lsn->fn_data;
  4529. mg_call(c, MG_EV_OPEN, NULL);
  4530. mg_call(c, MG_EV_ACCEPT, NULL);
  4531. return c;
  4532. }
  4533. static size_t trim_len(struct mg_connection *c, size_t len) {
  4534. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4535. size_t eth_h_len = 14, ip_max_h_len = 24, tcp_max_h_len = 60, udp_h_len = 8;
  4536. size_t max_headers_len =
  4537. eth_h_len + ip_max_h_len + (c->is_udp ? udp_h_len : tcp_max_h_len);
  4538. size_t min_mtu = c->is_udp ? 68 /* RFC-791 */ : max_headers_len - eth_h_len;
  4539. // If the frame exceeds the available buffer, trim the length
  4540. if (len + max_headers_len > ifp->tx.len) {
  4541. len = ifp->tx.len - max_headers_len;
  4542. }
  4543. // Ensure the MTU isn't lower than the minimum allowed value
  4544. if (ifp->mtu < min_mtu) {
  4545. MG_ERROR(("MTU is lower than minimum, capping to %lu", min_mtu));
  4546. ifp->mtu = (uint16_t) min_mtu;
  4547. }
  4548. // If the total packet size exceeds the MTU, trim the length
  4549. if (len + max_headers_len - eth_h_len > ifp->mtu) {
  4550. len = ifp->mtu - max_headers_len + eth_h_len;
  4551. if (c->is_udp) {
  4552. MG_ERROR(("UDP datagram exceeds MTU. Truncating it."));
  4553. }
  4554. }
  4555. return len;
  4556. }
  4557. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  4558. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4559. struct connstate *s = (struct connstate *) (c + 1);
  4560. uint32_t dst_ip = *(uint32_t *) c->rem.ip;
  4561. len = trim_len(c, len);
  4562. if (c->is_udp) {
  4563. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, dst_ip, c->rem.port, buf, len);
  4564. } else {
  4565. size_t sent =
  4566. tx_tcp(ifp, s->mac, dst_ip, TH_PUSH | TH_ACK, c->loc.port, c->rem.port,
  4567. mg_htonl(s->seq), mg_htonl(s->ack), buf, len);
  4568. if (sent == 0) {
  4569. return MG_IO_WAIT;
  4570. } else if (sent == (size_t) -1) {
  4571. return MG_IO_ERR;
  4572. } else {
  4573. s->seq += (uint32_t) len;
  4574. if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
  4575. }
  4576. }
  4577. return (long) len;
  4578. }
  4579. static void read_conn(struct mg_connection *c, struct pkt *pkt) {
  4580. struct connstate *s = (struct connstate *) (c + 1);
  4581. struct mg_iobuf *io = c->is_tls ? &c->rtls : &c->recv;
  4582. uint32_t seq = mg_ntohl(pkt->tcp->seq);
  4583. uint32_t rem_ip;
  4584. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4585. if (pkt->tcp->flags & TH_FIN) {
  4586. // If we initiated the closure, we reply with ACK upon receiving FIN
  4587. // If we didn't initiate it, we reply with FIN as part of the normal TCP
  4588. // closure process
  4589. uint8_t flags = TH_ACK;
  4590. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len + 1);
  4591. if (c->is_draining && s->ttype == MIP_TTYPE_FIN) {
  4592. if (s->seq == mg_htonl(pkt->tcp->ack)) { // Simultaneous closure ?
  4593. s->seq++; // Yes. Increment our SEQ
  4594. } else { // Otherwise,
  4595. s->seq = mg_htonl(pkt->tcp->ack); // Set to peer's ACK
  4596. }
  4597. } else {
  4598. flags |= TH_FIN;
  4599. c->is_draining = 1;
  4600. settmout(c, MIP_TTYPE_FIN);
  4601. }
  4602. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, flags,
  4603. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4604. } else if (pkt->pay.len == 0) {
  4605. // TODO(cpq): handle this peer's ACK
  4606. } else if (seq != s->ack) {
  4607. uint32_t ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  4608. if (s->ack == ack) {
  4609. MG_VERBOSE(("ignoring duplicate pkt"));
  4610. } else {
  4611. MG_VERBOSE(("SEQ != ACK: %x %x %x", seq, s->ack, ack));
  4612. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  4613. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "",
  4614. 0);
  4615. }
  4616. } else if (io->size - io->len < pkt->pay.len &&
  4617. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  4618. mg_error(c, "oom");
  4619. } else {
  4620. // Copy TCP payload into the IO buffer. If the connection is plain text,
  4621. // we copy to c->recv. If the connection is TLS, this data is encrypted,
  4622. // therefore we copy that encrypted data to the c->rtls iobuffer instead,
  4623. // and then call mg_tls_recv() to decrypt it. NOTE: mg_tls_recv() will
  4624. // call back mg_io_recv() which grabs raw data from c->rtls
  4625. memcpy(&io->buf[io->len], pkt->pay.ptr, pkt->pay.len);
  4626. io->len += pkt->pay.len;
  4627. MG_VERBOSE(("%lu SEQ %x -> %x", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  4628. // Advance ACK counter
  4629. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  4630. #if 0
  4631. // Send ACK immediately
  4632. uint32_t rem_ip;
  4633. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4634. MG_DEBUG((" imm ACK", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  4635. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK, c->loc.port,
  4636. c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4637. #else
  4638. // if not already running, setup a timer to send an ACK later
  4639. if (s->ttype != MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_ACK);
  4640. #endif
  4641. if (c->is_tls && c->is_tls_hs) {
  4642. mg_tls_handshake(c);
  4643. } else if (c->is_tls) {
  4644. // TLS connection. Make room for decrypted data in c->recv
  4645. io = &c->recv;
  4646. if (io->size - io->len < pkt->pay.len &&
  4647. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  4648. mg_error(c, "oom");
  4649. } else {
  4650. // Decrypt data directly into c->recv
  4651. long n = mg_tls_recv(c, &io->buf[io->len], io->size - io->len);
  4652. if (n == MG_IO_ERR) {
  4653. mg_error(c, "TLS recv error");
  4654. } else if (n > 0) {
  4655. // Decrypted successfully - trigger MG_EV_READ
  4656. io->len += (size_t) n;
  4657. mg_call(c, MG_EV_READ, &n);
  4658. }
  4659. }
  4660. } else {
  4661. // Plain text connection, data is already in c->recv, trigger
  4662. // MG_EV_READ
  4663. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4664. }
  4665. }
  4666. }
  4667. static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4668. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4669. struct connstate *s = c == NULL ? NULL : (struct connstate *) (c + 1);
  4670. #if 0
  4671. MG_INFO(("%lu %hhu %d", c ? c->id : 0, pkt->tcp->flags, (int) pkt->pay.len));
  4672. #endif
  4673. if (c != NULL && c->is_connecting && pkt->tcp->flags == (TH_SYN | TH_ACK)) {
  4674. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq) + 1;
  4675. tx_tcp_pkt(ifp, pkt, TH_ACK, pkt->tcp->ack, NULL, 0);
  4676. c->is_connecting = 0; // Client connected
  4677. settmout(c, MIP_TTYPE_KEEPALIVE);
  4678. mg_call(c, MG_EV_CONNECT, NULL); // Let user know
  4679. } else if (c != NULL && c->is_connecting && pkt->tcp->flags != TH_ACK) {
  4680. // mg_hexdump(pkt->raw.ptr, pkt->raw.len);
  4681. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4682. } else if (c != NULL && pkt->tcp->flags & TH_RST) {
  4683. mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  4684. } else if (c != NULL) {
  4685. #if 0
  4686. MG_DEBUG(("%lu %d %M:%hu -> %M:%hu", c->id, (int) pkt->raw.len,
  4687. mg_print_ip4, &pkt->ip->src, mg_ntohs(pkt->tcp->sport),
  4688. mg_print_ip4, &pkt->ip->dst, mg_ntohs(pkt->tcp->dport)));
  4689. mg_hexdump(pkt->pay.ptr, pkt->pay.len);
  4690. #endif
  4691. s->tmiss = 0; // Reset missed keep-alive counter
  4692. if (s->ttype == MIP_TTYPE_KEEPALIVE) // Advance keep-alive timer
  4693. settmout(c,
  4694. MIP_TTYPE_KEEPALIVE); // unless a former ACK timeout is pending
  4695. read_conn(c, pkt); // Override timer with ACK timeout if needed
  4696. } else if ((c = getpeer(ifp->mgr, pkt, true)) == NULL) {
  4697. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4698. } else if (pkt->tcp->flags & TH_RST) {
  4699. if (c->is_accepted) mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  4700. // ignore RST if not connected
  4701. } else if (pkt->tcp->flags & TH_SYN) {
  4702. // Use peer's source port as ISN, in order to recognise the handshake
  4703. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(pkt->tcp->sport));
  4704. tx_tcp_pkt(ifp, pkt, TH_SYN | TH_ACK, isn, NULL, 0);
  4705. } else if (pkt->tcp->flags & TH_FIN) {
  4706. tx_tcp_pkt(ifp, pkt, TH_FIN | TH_ACK, pkt->tcp->ack, NULL, 0);
  4707. } else if (mg_htonl(pkt->tcp->ack) == mg_htons(pkt->tcp->sport) + 1U) {
  4708. accept_conn(c, pkt);
  4709. } else if (!c->is_accepted) { // no peer
  4710. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4711. } else {
  4712. // MG_VERBOSE(("dropped silently.."));
  4713. }
  4714. }
  4715. static void rx_ip(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4716. if (pkt->ip->frag & IP_MORE_FRAGS_MSK || pkt->ip->frag & IP_FRAG_OFFSET_MSK) {
  4717. if (pkt->ip->proto == 17) pkt->udp = (struct udp *) (pkt->ip + 1);
  4718. if (pkt->ip->proto == 6) pkt->tcp = (struct tcp *) (pkt->ip + 1);
  4719. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4720. if (c) mg_error(c, "Received fragmented packet");
  4721. } else if (pkt->ip->proto == 1) {
  4722. pkt->icmp = (struct icmp *) (pkt->ip + 1);
  4723. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  4724. mkpay(pkt, pkt->icmp + 1);
  4725. rx_icmp(ifp, pkt);
  4726. } else if (pkt->ip->proto == 17) {
  4727. pkt->udp = (struct udp *) (pkt->ip + 1);
  4728. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  4729. mkpay(pkt, pkt->udp + 1);
  4730. MG_VERBOSE(("UDP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  4731. mg_ntohs(pkt->udp->sport), mg_print_ip4, &pkt->ip->dst,
  4732. mg_ntohs(pkt->udp->dport), (int) pkt->pay.len));
  4733. if (ifp->enable_dhcp_client && pkt->udp->dport == mg_htons(68)) {
  4734. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  4735. mkpay(pkt, pkt->dhcp + 1);
  4736. rx_dhcp_client(ifp, pkt);
  4737. } else if (ifp->enable_dhcp_server && pkt->udp->dport == mg_htons(67)) {
  4738. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  4739. mkpay(pkt, pkt->dhcp + 1);
  4740. rx_dhcp_server(ifp, pkt);
  4741. } else {
  4742. rx_udp(ifp, pkt);
  4743. }
  4744. } else if (pkt->ip->proto == 6) {
  4745. pkt->tcp = (struct tcp *) (pkt->ip + 1);
  4746. if (pkt->pay.len < sizeof(*pkt->tcp)) return;
  4747. mkpay(pkt, pkt->tcp + 1);
  4748. uint16_t iplen = mg_ntohs(pkt->ip->len);
  4749. uint16_t off = (uint16_t) (sizeof(*pkt->ip) + ((pkt->tcp->off >> 4) * 4U));
  4750. if (iplen >= off) pkt->pay.len = (size_t) (iplen - off);
  4751. MG_VERBOSE(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  4752. mg_ntohs(pkt->tcp->sport), mg_print_ip4, &pkt->ip->dst,
  4753. mg_ntohs(pkt->tcp->dport), (int) pkt->pay.len));
  4754. rx_tcp(ifp, pkt);
  4755. }
  4756. }
  4757. static void rx_ip6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4758. // MG_DEBUG(("IP %d", (int) len));
  4759. if (pkt->ip6->proto == 1 || pkt->ip6->proto == 58) {
  4760. pkt->icmp = (struct icmp *) (pkt->ip6 + 1);
  4761. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  4762. mkpay(pkt, pkt->icmp + 1);
  4763. rx_icmp(ifp, pkt);
  4764. } else if (pkt->ip6->proto == 17) {
  4765. pkt->udp = (struct udp *) (pkt->ip6 + 1);
  4766. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  4767. // MG_DEBUG((" UDP %u %u -> %u", len, mg_htons(udp->sport),
  4768. // mg_htons(udp->dport)));
  4769. mkpay(pkt, pkt->udp + 1);
  4770. }
  4771. }
  4772. static void mg_tcpip_rx(struct mg_tcpip_if *ifp, void *buf, size_t len) {
  4773. struct pkt pkt;
  4774. memset(&pkt, 0, sizeof(pkt));
  4775. pkt.raw.ptr = (char *) buf;
  4776. pkt.raw.len = len;
  4777. pkt.eth = (struct eth *) buf;
  4778. // mg_hexdump(buf, len > 16 ? 16: len);
  4779. if (pkt.raw.len < sizeof(*pkt.eth)) return; // Truncated - runt?
  4780. if (ifp->enable_mac_check &&
  4781. memcmp(pkt.eth->dst, ifp->mac, sizeof(pkt.eth->dst)) != 0 &&
  4782. memcmp(pkt.eth->dst, broadcast, sizeof(pkt.eth->dst)) != 0)
  4783. return;
  4784. if (ifp->enable_crc32_check && len > 4) {
  4785. len -= 4; // TODO(scaprile): check on bigendian
  4786. uint32_t crc = mg_crc32(0, (const char *) buf, len);
  4787. if (memcmp((void *) ((size_t) buf + len), &crc, sizeof(crc))) return;
  4788. }
  4789. if (pkt.eth->type == mg_htons(0x806)) {
  4790. pkt.arp = (struct arp *) (pkt.eth + 1);
  4791. if (sizeof(*pkt.eth) + sizeof(*pkt.arp) > pkt.raw.len) return; // Truncated
  4792. rx_arp(ifp, &pkt);
  4793. } else if (pkt.eth->type == mg_htons(0x86dd)) {
  4794. pkt.ip6 = (struct ip6 *) (pkt.eth + 1);
  4795. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip6)) return; // Truncated
  4796. if ((pkt.ip6->ver >> 4) != 0x6) return; // Not IP
  4797. mkpay(&pkt, pkt.ip6 + 1);
  4798. rx_ip6(ifp, &pkt);
  4799. } else if (pkt.eth->type == mg_htons(0x800)) {
  4800. pkt.ip = (struct ip *) (pkt.eth + 1);
  4801. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  4802. // Truncate frame to what IP header tells us
  4803. if ((size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth) < pkt.raw.len) {
  4804. pkt.raw.len = (size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth);
  4805. }
  4806. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  4807. if ((pkt.ip->ver >> 4) != 4) return; // Not IP
  4808. mkpay(&pkt, pkt.ip + 1);
  4809. rx_ip(ifp, &pkt);
  4810. } else {
  4811. MG_DEBUG(("Unknown eth type %x", mg_htons(pkt.eth->type)));
  4812. if (mg_log_level >= MG_LL_VERBOSE) mg_hexdump(buf, len >= 32 ? 32 : len);
  4813. }
  4814. }
  4815. static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t uptime_ms) {
  4816. if (ifp == NULL || ifp->driver == NULL) return;
  4817. bool expired_1000ms = mg_timer_expired(&ifp->timer_1000ms, 1000, uptime_ms);
  4818. ifp->now = uptime_ms;
  4819. // Handle physical interface up/down status
  4820. if (expired_1000ms && ifp->driver->up) {
  4821. bool up = ifp->driver->up(ifp);
  4822. bool current = ifp->state != MG_TCPIP_STATE_DOWN;
  4823. if (up != current) {
  4824. ifp->state = up == false ? MG_TCPIP_STATE_DOWN
  4825. : ifp->enable_dhcp_client ? MG_TCPIP_STATE_UP
  4826. : MG_TCPIP_STATE_READY;
  4827. if (!up && ifp->enable_dhcp_client) ifp->ip = 0;
  4828. onstatechange(ifp);
  4829. }
  4830. }
  4831. if (ifp->state == MG_TCPIP_STATE_DOWN) return;
  4832. // DHCP RFC-2131 (4.4)
  4833. if (ifp->state == MG_TCPIP_STATE_UP && expired_1000ms) {
  4834. tx_dhcp_discover(ifp); // INIT (4.4.1)
  4835. } else if (expired_1000ms && ifp->state == MG_TCPIP_STATE_READY &&
  4836. ifp->lease_expire > 0) { // BOUND / RENEWING / REBINDING
  4837. if (ifp->now >= ifp->lease_expire) {
  4838. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0; // expired, release IP
  4839. onstatechange(ifp);
  4840. } else if (ifp->now + 30UL * 60UL * 1000UL > ifp->lease_expire &&
  4841. ((ifp->now / 1000) % 60) == 0) {
  4842. // hack: 30 min before deadline, try to rebind (4.3.6) every min
  4843. tx_dhcp_request_re(ifp, (uint8_t *) broadcast, ifp->ip, 0xffffffff);
  4844. } // TODO(): Handle T1 (RENEWING) and T2 (REBINDING) (4.4.5)
  4845. }
  4846. // Read data from the network
  4847. if (ifp->driver->rx != NULL) { // Polling driver. We must call it
  4848. size_t len =
  4849. ifp->driver->rx(ifp->recv_queue.buf, ifp->recv_queue.size, ifp);
  4850. if (len > 0) {
  4851. ifp->nrecv++;
  4852. mg_tcpip_rx(ifp, ifp->recv_queue.buf, len);
  4853. }
  4854. } else { // Interrupt-based driver. Fills recv queue itself
  4855. char *buf;
  4856. size_t len = mg_queue_next(&ifp->recv_queue, &buf);
  4857. if (len > 0) {
  4858. mg_tcpip_rx(ifp, buf, len);
  4859. mg_queue_del(&ifp->recv_queue, len);
  4860. }
  4861. }
  4862. // Process timeouts
  4863. for (struct mg_connection *c = ifp->mgr->conns; c != NULL; c = c->next) {
  4864. if (c->is_udp || c->is_listening || c->is_resolving) continue;
  4865. struct connstate *s = (struct connstate *) (c + 1);
  4866. uint32_t rem_ip;
  4867. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4868. if (uptime_ms > s->timer) {
  4869. if (s->ttype == MIP_TTYPE_ACK) {
  4870. MG_VERBOSE(("%lu ack %x %x", c->id, s->seq, s->ack));
  4871. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4872. mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4873. } else if (s->ttype == MIP_TTYPE_ARP) {
  4874. mg_error(c, "ARP timeout");
  4875. } else if (s->ttype == MIP_TTYPE_SYN) {
  4876. mg_error(c, "Connection timeout");
  4877. } else if (s->ttype == MIP_TTYPE_FIN) {
  4878. c->is_closing = 1;
  4879. continue;
  4880. } else {
  4881. if (s->tmiss++ > 2) {
  4882. mg_error(c, "keepalive");
  4883. } else {
  4884. MG_VERBOSE(("%lu keepalive", c->id));
  4885. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4886. mg_htonl(s->seq - 1), mg_htonl(s->ack), "", 0);
  4887. }
  4888. }
  4889. settmout(c, MIP_TTYPE_KEEPALIVE);
  4890. }
  4891. }
  4892. }
  4893. // This function executes in interrupt context, thus it should copy data
  4894. // somewhere fast. Note that newlib's malloc is not thread safe, thus use
  4895. // our lock-free queue with preallocated buffer to copy data and return asap
  4896. void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) {
  4897. char *p;
  4898. if (mg_queue_book(&ifp->recv_queue, &p, len) >= len) {
  4899. memcpy(p, buf, len);
  4900. mg_queue_add(&ifp->recv_queue, len);
  4901. ifp->nrecv++;
  4902. } else {
  4903. ifp->ndrop++;
  4904. }
  4905. }
  4906. void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
  4907. // If MAC address is not set, make a random one
  4908. if (ifp->mac[0] == 0 && ifp->mac[1] == 0 && ifp->mac[2] == 0 &&
  4909. ifp->mac[3] == 0 && ifp->mac[4] == 0 && ifp->mac[5] == 0) {
  4910. ifp->mac[0] = 0x02; // Locally administered, unicast
  4911. mg_random(&ifp->mac[1], sizeof(ifp->mac) - 1);
  4912. MG_INFO(("MAC not set. Generated random: %M", mg_print_mac, ifp->mac));
  4913. }
  4914. if (ifp->driver->init && !ifp->driver->init(ifp)) {
  4915. MG_ERROR(("driver init failed"));
  4916. } else {
  4917. size_t framesize = 1540;
  4918. ifp->tx.ptr = (char *) calloc(1, framesize), ifp->tx.len = framesize;
  4919. if (ifp->recv_queue.size == 0)
  4920. ifp->recv_queue.size = ifp->driver->rx ? framesize : 8192;
  4921. ifp->recv_queue.buf = (char *) calloc(1, ifp->recv_queue.size);
  4922. ifp->timer_1000ms = mg_millis();
  4923. mgr->priv = ifp;
  4924. ifp->mgr = mgr;
  4925. ifp->mtu = MG_TCPIP_MTU_DEFAULT;
  4926. mgr->extraconnsize = sizeof(struct connstate);
  4927. if (ifp->ip == 0) ifp->enable_dhcp_client = true;
  4928. memset(ifp->gwmac, 255, sizeof(ifp->gwmac)); // Set to broadcast
  4929. mg_random(&ifp->eport, sizeof(ifp->eport)); // Random from 0 to 65535
  4930. ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
  4931. // MG_EPHEMERAL_PORT_BASE to 65535
  4932. if (ifp->tx.ptr == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
  4933. }
  4934. }
  4935. void mg_tcpip_free(struct mg_tcpip_if *ifp) {
  4936. free(ifp->recv_queue.buf);
  4937. free((char *) ifp->tx.ptr);
  4938. }
  4939. static void send_syn(struct mg_connection *c) {
  4940. struct connstate *s = (struct connstate *) (c + 1);
  4941. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(c->loc.port));
  4942. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4943. uint32_t rem_ip;
  4944. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4945. tx_tcp(ifp, s->mac, rem_ip, TH_SYN, c->loc.port, c->rem.port, isn, 0, NULL,
  4946. 0);
  4947. }
  4948. void mg_connect_resolved(struct mg_connection *c) {
  4949. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4950. uint32_t rem_ip;
  4951. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4952. c->is_resolving = 0;
  4953. if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
  4954. memcpy(c->loc.ip, &ifp->ip, sizeof(uint32_t));
  4955. c->loc.port = mg_htons(ifp->eport++);
  4956. MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
  4957. &c->rem));
  4958. mg_call(c, MG_EV_RESOLVE, NULL);
  4959. if (c->is_udp && (rem_ip == 0xffffffff || rem_ip == (ifp->ip | ~ifp->mask))) {
  4960. struct connstate *s = (struct connstate *) (c + 1);
  4961. memset(s->mac, 0xFF, sizeof(s->mac)); // global or local broadcast
  4962. } else if (((rem_ip & ifp->mask) == (ifp->ip & ifp->mask))) {
  4963. // If we're in the same LAN, fire an ARP lookup.
  4964. MG_DEBUG(("%lu ARP lookup...", c->id));
  4965. arp_ask(ifp, rem_ip);
  4966. settmout(c, MIP_TTYPE_ARP);
  4967. c->is_arplooking = 1;
  4968. c->is_connecting = 1;
  4969. } else if ((*((uint8_t *) &rem_ip) & 0xE0) == 0xE0) {
  4970. struct connstate *s = (struct connstate *) (c + 1); // 224 to 239, E0 to EF
  4971. uint8_t mcastp[3] = {0x01, 0x00, 0x5E}; // multicast group
  4972. memcpy(s->mac, mcastp, 3);
  4973. memcpy(s->mac + 3, ((uint8_t *) &rem_ip) + 1, 3); // 23 LSb
  4974. s->mac[3] &= 0x7F;
  4975. } else {
  4976. struct connstate *s = (struct connstate *) (c + 1);
  4977. memcpy(s->mac, ifp->gwmac, sizeof(ifp->gwmac));
  4978. if (c->is_udp) {
  4979. mg_call(c, MG_EV_CONNECT, NULL);
  4980. } else {
  4981. send_syn(c);
  4982. settmout(c, MIP_TTYPE_SYN);
  4983. c->is_connecting = 1;
  4984. }
  4985. }
  4986. }
  4987. bool mg_open_listener(struct mg_connection *c, const char *url) {
  4988. c->loc.port = mg_htons(mg_url_port(url));
  4989. return true;
  4990. }
  4991. static void write_conn(struct mg_connection *c) {
  4992. long len = c->is_tls ? mg_tls_send(c, c->send.buf, c->send.len)
  4993. : mg_io_send(c, c->send.buf, c->send.len);
  4994. if (len == MG_IO_ERR) {
  4995. mg_error(c, "tx err");
  4996. } else if (len > 0) {
  4997. mg_iobuf_del(&c->send, 0, (size_t) len);
  4998. mg_call(c, MG_EV_WRITE, &len);
  4999. }
  5000. }
  5001. static void init_closure(struct mg_connection *c) {
  5002. struct connstate *s = (struct connstate *) (c + 1);
  5003. if (c->is_udp == false && c->is_listening == false &&
  5004. c->is_connecting == false) { // For TCP conns,
  5005. struct mg_tcpip_if *ifp =
  5006. (struct mg_tcpip_if *) c->mgr->priv; // send TCP FIN
  5007. uint32_t rem_ip;
  5008. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5009. tx_tcp(ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port, c->rem.port,
  5010. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5011. settmout(c, MIP_TTYPE_FIN);
  5012. }
  5013. }
  5014. static void close_conn(struct mg_connection *c) {
  5015. struct connstate *s = (struct connstate *) (c + 1);
  5016. mg_iobuf_free(&s->raw); // For TLS connections, release raw data
  5017. mg_close_conn(c);
  5018. }
  5019. static bool can_write(struct mg_connection *c) {
  5020. return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 &&
  5021. c->is_tls_hs == 0 && c->is_arplooking == 0;
  5022. }
  5023. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  5024. struct mg_connection *c, *tmp;
  5025. uint64_t now = mg_millis();
  5026. mg_tcpip_poll((struct mg_tcpip_if *) mgr->priv, now);
  5027. mg_timer_poll(&mgr->timers, now);
  5028. for (c = mgr->conns; c != NULL; c = tmp) {
  5029. tmp = c->next;
  5030. struct connstate *s = (struct connstate *) (c + 1);
  5031. mg_call(c, MG_EV_POLL, &now);
  5032. MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't',
  5033. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  5034. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  5035. if (can_write(c)) write_conn(c);
  5036. if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN)
  5037. init_closure(c);
  5038. if (c->is_closing) close_conn(c);
  5039. }
  5040. (void) ms;
  5041. }
  5042. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  5043. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5044. bool res = false;
  5045. uint32_t rem_ip;
  5046. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5047. if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) {
  5048. mg_error(c, "net down");
  5049. } else if (c->is_udp) {
  5050. struct connstate *s = (struct connstate *) (c + 1);
  5051. len = trim_len(c, len); // Trimming length if necessary
  5052. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len);
  5053. res = true;
  5054. } else {
  5055. res = mg_iobuf_add(&c->send, c->send.len, buf, len);
  5056. }
  5057. return res;
  5058. }
  5059. #endif // MG_ENABLE_TCPIP
  5060. #ifdef MG_ENABLE_LINES
  5061. #line 1 "src/ota_dummy.c"
  5062. #endif
  5063. #if MG_OTA == MG_OTA_NONE
  5064. bool mg_ota_begin(size_t new_firmware_size) {
  5065. (void) new_firmware_size;
  5066. return true;
  5067. }
  5068. bool mg_ota_write(const void *buf, size_t len) {
  5069. (void) buf, (void) len;
  5070. return true;
  5071. }
  5072. bool mg_ota_end(void) {
  5073. return true;
  5074. }
  5075. bool mg_ota_commit(void) {
  5076. return true;
  5077. }
  5078. bool mg_ota_rollback(void) {
  5079. return true;
  5080. }
  5081. int mg_ota_status(int fw) {
  5082. (void) fw;
  5083. return 0;
  5084. }
  5085. uint32_t mg_ota_crc32(int fw) {
  5086. (void) fw;
  5087. return 0;
  5088. }
  5089. uint32_t mg_ota_timestamp(int fw) {
  5090. (void) fw;
  5091. return 0;
  5092. }
  5093. size_t mg_ota_size(int fw) {
  5094. (void) fw;
  5095. return 0;
  5096. }
  5097. MG_IRAM void mg_ota_boot(void) {
  5098. }
  5099. #endif
  5100. #ifdef MG_ENABLE_LINES
  5101. #line 1 "src/ota_flash.c"
  5102. #endif
  5103. // This OTA implementation uses the internal flash API outlined in device.h
  5104. // It splits flash into 2 equal partitions, and stores OTA status in the
  5105. // last sector of the partition.
  5106. #if MG_OTA == MG_OTA_FLASH
  5107. #define MG_OTADATA_KEY 0xb07afed0
  5108. static char *s_addr; // Current address to write to
  5109. static size_t s_size; // Firmware size to flash. In-progress indicator
  5110. static uint32_t s_crc32; // Firmware checksum
  5111. struct mg_otadata {
  5112. uint32_t crc32, size, timestamp, status;
  5113. };
  5114. bool mg_ota_begin(size_t new_firmware_size) {
  5115. bool ok = false;
  5116. if (s_size) {
  5117. MG_ERROR(("OTA already in progress. Call mg_ota_end()"));
  5118. } else {
  5119. size_t half = mg_flash_size() / 2, max = half - mg_flash_sector_size();
  5120. s_crc32 = 0;
  5121. s_addr = (char *) mg_flash_start() + half;
  5122. MG_DEBUG(("Firmware %lu bytes, max %lu", new_firmware_size, max));
  5123. if (new_firmware_size < max) {
  5124. ok = true;
  5125. s_size = new_firmware_size;
  5126. MG_INFO(("Starting OTA, firmware size %lu", s_size));
  5127. } else {
  5128. MG_ERROR(("Firmware %lu is too big to fit %lu", new_firmware_size, max));
  5129. }
  5130. }
  5131. return ok;
  5132. }
  5133. bool mg_ota_write(const void *buf, size_t len) {
  5134. bool ok = false;
  5135. if (s_size == 0) {
  5136. MG_ERROR(("OTA is not started, call mg_ota_begin()"));
  5137. } else {
  5138. size_t align = mg_flash_write_align();
  5139. size_t len_aligned_down = MG_ROUND_DOWN(len, align);
  5140. if (len_aligned_down) ok = mg_flash_write(s_addr, buf, len_aligned_down);
  5141. if (len_aligned_down < len) {
  5142. size_t left = len - len_aligned_down;
  5143. char tmp[align];
  5144. memset(tmp, 0xff, sizeof(tmp));
  5145. memcpy(tmp, (char *) buf + len_aligned_down, left);
  5146. ok = mg_flash_write(s_addr + len_aligned_down, tmp, sizeof(tmp));
  5147. }
  5148. s_crc32 = mg_crc32(s_crc32, (char *) buf, len); // Update CRC
  5149. MG_DEBUG(("%#x %p %lu -> %d", s_addr - len, buf, len, ok));
  5150. s_addr += len;
  5151. }
  5152. return ok;
  5153. }
  5154. MG_IRAM static uint32_t mg_fwkey(int fw) {
  5155. uint32_t key = MG_OTADATA_KEY + fw;
  5156. int bank = mg_flash_bank();
  5157. if (bank == 2 && fw == MG_FIRMWARE_PREVIOUS) key--;
  5158. if (bank == 2 && fw == MG_FIRMWARE_CURRENT) key++;
  5159. return key;
  5160. }
  5161. bool mg_ota_end(void) {
  5162. char *base = (char *) mg_flash_start() + mg_flash_size() / 2;
  5163. bool ok = false;
  5164. if (s_size) {
  5165. size_t size = s_addr - base;
  5166. uint32_t crc32 = mg_crc32(0, base, s_size);
  5167. if (size == s_size && crc32 == s_crc32) {
  5168. uint32_t now = (uint32_t) (mg_now() / 1000);
  5169. struct mg_otadata od = {crc32, size, now, MG_OTA_FIRST_BOOT};
  5170. uint32_t key = mg_fwkey(MG_FIRMWARE_PREVIOUS);
  5171. ok = mg_flash_save(NULL, key, &od, sizeof(od));
  5172. }
  5173. MG_DEBUG(("CRC: %x/%x, size: %lu/%lu, status: %s", s_crc32, crc32, s_size,
  5174. size, ok ? "ok" : "fail"));
  5175. s_size = 0;
  5176. if (ok) ok = mg_flash_swap_bank();
  5177. }
  5178. MG_INFO(("Finishing OTA: %s", ok ? "ok" : "fail"));
  5179. return ok;
  5180. }
  5181. MG_IRAM static struct mg_otadata mg_otadata(int fw) {
  5182. uint32_t key = mg_fwkey(fw);
  5183. struct mg_otadata od = {};
  5184. MG_INFO(("Loading %s OTA data", fw == MG_FIRMWARE_CURRENT ? "curr" : "prev"));
  5185. mg_flash_load(NULL, key, &od, sizeof(od));
  5186. // MG_DEBUG(("Loaded OTA data. fw %d, bank %d, key %p", fw, bank, key));
  5187. // mg_hexdump(&od, sizeof(od));
  5188. return od;
  5189. }
  5190. int mg_ota_status(int fw) {
  5191. struct mg_otadata od = mg_otadata(fw);
  5192. return od.status;
  5193. }
  5194. uint32_t mg_ota_crc32(int fw) {
  5195. struct mg_otadata od = mg_otadata(fw);
  5196. return od.crc32;
  5197. }
  5198. uint32_t mg_ota_timestamp(int fw) {
  5199. struct mg_otadata od = mg_otadata(fw);
  5200. return od.timestamp;
  5201. }
  5202. size_t mg_ota_size(int fw) {
  5203. struct mg_otadata od = mg_otadata(fw);
  5204. return od.size;
  5205. }
  5206. MG_IRAM bool mg_ota_commit(void) {
  5207. bool ok = true;
  5208. struct mg_otadata od = mg_otadata(MG_FIRMWARE_CURRENT);
  5209. if (od.status != MG_OTA_COMMITTED) {
  5210. od.status = MG_OTA_COMMITTED;
  5211. MG_INFO(("Committing current firmware, OD size %lu", sizeof(od)));
  5212. ok = mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &od, sizeof(od));
  5213. }
  5214. return ok;
  5215. }
  5216. bool mg_ota_rollback(void) {
  5217. MG_DEBUG(("Rolling firmware back"));
  5218. if (mg_flash_bank() == 0) {
  5219. // No dual bank support. Mark previous firmware as FIRST_BOOT
  5220. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5221. prev.status = MG_OTA_FIRST_BOOT;
  5222. return mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &prev,
  5223. sizeof(prev));
  5224. } else {
  5225. return mg_flash_swap_bank();
  5226. }
  5227. }
  5228. MG_IRAM void mg_ota_boot(void) {
  5229. MG_INFO(("Booting. Flash bank: %d", mg_flash_bank()));
  5230. struct mg_otadata curr = mg_otadata(MG_FIRMWARE_CURRENT);
  5231. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5232. if (curr.status == MG_OTA_FIRST_BOOT) {
  5233. if (prev.status == MG_OTA_UNAVAILABLE) {
  5234. MG_INFO(("Setting previous firmware state to committed"));
  5235. prev.status = MG_OTA_COMMITTED;
  5236. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_PREVIOUS), &prev, sizeof(prev));
  5237. }
  5238. curr.status = MG_OTA_UNCOMMITTED;
  5239. MG_INFO(("First boot, setting status to UNCOMMITTED"));
  5240. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &curr, sizeof(curr));
  5241. } else if (prev.status == MG_OTA_FIRST_BOOT && mg_flash_bank() == 0) {
  5242. // Swap paritions. Pray power does not disappear
  5243. size_t fs = mg_flash_size(), ss = mg_flash_sector_size();
  5244. char *partition1 = mg_flash_start();
  5245. char *partition2 = mg_flash_start() + fs / 2;
  5246. size_t ofs, max = fs / 2 - ss; // Set swap size to the whole partition
  5247. if (curr.status != MG_OTA_UNAVAILABLE &&
  5248. prev.status != MG_OTA_UNAVAILABLE) {
  5249. // We know exact sizes of both firmwares.
  5250. // Shrink swap size to the MAX(firmware1, firmware2)
  5251. size_t sz = curr.size > prev.size ? curr.size : prev.size;
  5252. if (sz > 0 && sz < max) max = sz;
  5253. }
  5254. // MG_OTA_FIRST_BOOT -> MG_OTA_UNCOMMITTED
  5255. prev.status = MG_OTA_UNCOMMITTED;
  5256. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_CURRENT, &prev,
  5257. sizeof(prev));
  5258. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &curr,
  5259. sizeof(curr));
  5260. MG_INFO(("Swapping partitions, size %u (%u sectors)", max, max / ss));
  5261. MG_INFO(("Do NOT power off..."));
  5262. mg_log_level = MG_LL_NONE;
  5263. // We use the last sector of partition2 for OTA data/config storage
  5264. // Therefore we can use last sector of partition1 for swapping
  5265. char *tmpsector = partition1 + fs / 2 - ss; // Last sector of partition1
  5266. (void) tmpsector;
  5267. for (ofs = 0; ofs < max; ofs += ss) {
  5268. // mg_flash_erase(tmpsector);
  5269. mg_flash_write(tmpsector, partition1 + ofs, ss);
  5270. // mg_flash_erase(partition1 + ofs);
  5271. mg_flash_write(partition1 + ofs, partition2 + ofs, ss);
  5272. // mg_flash_erase(partition2 + ofs);
  5273. mg_flash_write(partition2 + ofs, tmpsector, ss);
  5274. }
  5275. mg_device_reset();
  5276. }
  5277. }
  5278. #endif
  5279. #ifdef MG_ENABLE_LINES
  5280. #line 1 "src/printf.c"
  5281. #endif
  5282. size_t mg_queue_vprintf(struct mg_queue *q, const char *fmt, va_list *ap) {
  5283. size_t len = mg_snprintf(NULL, 0, fmt, ap);
  5284. char *buf;
  5285. if (len == 0 || mg_queue_book(q, &buf, len + 1) < len + 1) {
  5286. len = 0; // Nah. Not enough space
  5287. } else {
  5288. len = mg_vsnprintf((char *) buf, len + 1, fmt, ap);
  5289. mg_queue_add(q, len);
  5290. }
  5291. return len;
  5292. }
  5293. size_t mg_queue_printf(struct mg_queue *q, const char *fmt, ...) {
  5294. va_list ap;
  5295. size_t len;
  5296. va_start(ap, fmt);
  5297. len = mg_queue_vprintf(q, fmt, &ap);
  5298. va_end(ap);
  5299. return len;
  5300. }
  5301. static void mg_pfn_iobuf_private(char ch, void *param, bool expand) {
  5302. struct mg_iobuf *io = (struct mg_iobuf *) param;
  5303. if (expand && io->len + 2 > io->size) mg_iobuf_resize(io, io->len + 2);
  5304. if (io->len + 2 <= io->size) {
  5305. io->buf[io->len++] = (uint8_t) ch;
  5306. io->buf[io->len] = 0;
  5307. } else if (io->len < io->size) {
  5308. io->buf[io->len++] = 0; // Guarantee to 0-terminate
  5309. }
  5310. }
  5311. static void mg_putchar_iobuf_static(char ch, void *param) {
  5312. mg_pfn_iobuf_private(ch, param, false);
  5313. }
  5314. void mg_pfn_iobuf(char ch, void *param) {
  5315. mg_pfn_iobuf_private(ch, param, true);
  5316. }
  5317. size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap) {
  5318. struct mg_iobuf io = {(uint8_t *) buf, len, 0, 0};
  5319. size_t n = mg_vxprintf(mg_putchar_iobuf_static, &io, fmt, ap);
  5320. if (n < len) buf[n] = '\0';
  5321. return n;
  5322. }
  5323. size_t mg_snprintf(char *buf, size_t len, const char *fmt, ...) {
  5324. va_list ap;
  5325. size_t n;
  5326. va_start(ap, fmt);
  5327. n = mg_vsnprintf(buf, len, fmt, &ap);
  5328. va_end(ap);
  5329. return n;
  5330. }
  5331. char *mg_vmprintf(const char *fmt, va_list *ap) {
  5332. struct mg_iobuf io = {0, 0, 0, 256};
  5333. mg_vxprintf(mg_pfn_iobuf, &io, fmt, ap);
  5334. return (char *) io.buf;
  5335. }
  5336. char *mg_mprintf(const char *fmt, ...) {
  5337. char *s;
  5338. va_list ap;
  5339. va_start(ap, fmt);
  5340. s = mg_vmprintf(fmt, &ap);
  5341. va_end(ap);
  5342. return s;
  5343. }
  5344. void mg_pfn_stdout(char c, void *param) {
  5345. putchar(c);
  5346. (void) param;
  5347. }
  5348. static size_t print_ip4(void (*out)(char, void *), void *arg, uint8_t *p) {
  5349. return mg_xprintf(out, arg, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  5350. }
  5351. static size_t print_ip6(void (*out)(char, void *), void *arg, uint16_t *p) {
  5352. return mg_xprintf(out, arg, "[%x:%x:%x:%x:%x:%x:%x:%x]", mg_ntohs(p[0]),
  5353. mg_ntohs(p[1]), mg_ntohs(p[2]), mg_ntohs(p[3]),
  5354. mg_ntohs(p[4]), mg_ntohs(p[5]), mg_ntohs(p[6]),
  5355. mg_ntohs(p[7]));
  5356. }
  5357. size_t mg_print_ip4(void (*out)(char, void *), void *arg, va_list *ap) {
  5358. uint8_t *p = va_arg(*ap, uint8_t *);
  5359. return print_ip4(out, arg, p);
  5360. }
  5361. size_t mg_print_ip6(void (*out)(char, void *), void *arg, va_list *ap) {
  5362. uint16_t *p = va_arg(*ap, uint16_t *);
  5363. return print_ip6(out, arg, p);
  5364. }
  5365. size_t mg_print_ip(void (*out)(char, void *), void *arg, va_list *ap) {
  5366. struct mg_addr *addr = va_arg(*ap, struct mg_addr *);
  5367. if (addr->is_ip6) return print_ip6(out, arg, (uint16_t *) addr->ip);
  5368. return print_ip4(out, arg, (uint8_t *) &addr->ip);
  5369. }
  5370. size_t mg_print_ip_port(void (*out)(char, void *), void *arg, va_list *ap) {
  5371. struct mg_addr *a = va_arg(*ap, struct mg_addr *);
  5372. return mg_xprintf(out, arg, "%M:%hu", mg_print_ip, a, mg_ntohs(a->port));
  5373. }
  5374. size_t mg_print_mac(void (*out)(char, void *), void *arg, va_list *ap) {
  5375. uint8_t *p = va_arg(*ap, uint8_t *);
  5376. return mg_xprintf(out, arg, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2],
  5377. p[3], p[4], p[5]);
  5378. }
  5379. static char mg_esc(int c, bool esc) {
  5380. const char *p, *esc1 = "\b\f\n\r\t\\\"", *esc2 = "bfnrt\\\"";
  5381. for (p = esc ? esc1 : esc2; *p != '\0'; p++) {
  5382. if (*p == c) return esc ? esc2[p - esc1] : esc1[p - esc2];
  5383. }
  5384. return 0;
  5385. }
  5386. static char mg_escape(int c) {
  5387. return mg_esc(c, true);
  5388. }
  5389. static size_t qcpy(void (*out)(char, void *), void *ptr, char *buf,
  5390. size_t len) {
  5391. size_t i = 0, extra = 0;
  5392. for (i = 0; i < len && buf[i] != '\0'; i++) {
  5393. char c = mg_escape(buf[i]);
  5394. if (c) {
  5395. out('\\', ptr), out(c, ptr), extra++;
  5396. } else {
  5397. out(buf[i], ptr);
  5398. }
  5399. }
  5400. return i + extra;
  5401. }
  5402. static size_t bcpy(void (*out)(char, void *), void *arg, uint8_t *buf,
  5403. size_t len) {
  5404. size_t i, j, n = 0;
  5405. const char *t =
  5406. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5407. for (i = 0; i < len; i += 3) {
  5408. uint8_t c1 = buf[i], c2 = i + 1 < len ? buf[i + 1] : 0,
  5409. c3 = i + 2 < len ? buf[i + 2] : 0;
  5410. char tmp[4] = {t[c1 >> 2], t[(c1 & 3) << 4 | (c2 >> 4)], '=', '='};
  5411. if (i + 1 < len) tmp[2] = t[(c2 & 15) << 2 | (c3 >> 6)];
  5412. if (i + 2 < len) tmp[3] = t[c3 & 63];
  5413. for (j = 0; j < sizeof(tmp) && tmp[j] != '\0'; j++) out(tmp[j], arg);
  5414. n += j;
  5415. }
  5416. return n;
  5417. }
  5418. size_t mg_print_hex(void (*out)(char, void *), void *arg, va_list *ap) {
  5419. size_t bl = (size_t) va_arg(*ap, int);
  5420. uint8_t *p = va_arg(*ap, uint8_t *);
  5421. const char *hex = "0123456789abcdef";
  5422. size_t j;
  5423. for (j = 0; j < bl; j++) {
  5424. out(hex[(p[j] >> 4) & 0x0F], arg);
  5425. out(hex[p[j] & 0x0F], arg);
  5426. }
  5427. return 2 * bl;
  5428. }
  5429. size_t mg_print_base64(void (*out)(char, void *), void *arg, va_list *ap) {
  5430. size_t len = (size_t) va_arg(*ap, int);
  5431. uint8_t *buf = va_arg(*ap, uint8_t *);
  5432. return bcpy(out, arg, buf, len);
  5433. }
  5434. size_t mg_print_esc(void (*out)(char, void *), void *arg, va_list *ap) {
  5435. size_t len = (size_t) va_arg(*ap, int);
  5436. char *p = va_arg(*ap, char *);
  5437. if (len == 0) len = p == NULL ? 0 : strlen(p);
  5438. return qcpy(out, arg, p, len);
  5439. }
  5440. #ifdef MG_ENABLE_LINES
  5441. #line 1 "src/queue.c"
  5442. #endif
  5443. #if (defined(__GNUC__) && (__GNUC__ > 4) || \
  5444. (defined(__GNUC_MINOR__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
  5445. defined(__clang__)
  5446. #define MG_MEMORY_BARRIER() __sync_synchronize()
  5447. #elif defined(_MSC_VER) && _MSC_VER >= 1700
  5448. #define MG_MEMORY_BARRIER() MemoryBarrier()
  5449. #elif !defined(MG_MEMORY_BARRIER)
  5450. #define MG_MEMORY_BARRIER()
  5451. #endif
  5452. // Every message in a queue is prepended by a 32-bit message length (ML).
  5453. // If ML is 0, then it is the end, and reader must wrap to the beginning.
  5454. //
  5455. // Queue when q->tail <= q->head:
  5456. // |----- free -----| ML | message1 | ML | message2 | ----- free ------|
  5457. // ^ ^ ^ ^
  5458. // buf tail head len
  5459. //
  5460. // Queue when q->tail > q->head:
  5461. // | ML | message2 |----- free ------| ML | message1 | 0 |---- free ----|
  5462. // ^ ^ ^ ^
  5463. // buf head tail len
  5464. void mg_queue_init(struct mg_queue *q, char *buf, size_t size) {
  5465. q->size = size;
  5466. q->buf = buf;
  5467. q->head = q->tail = 0;
  5468. }
  5469. static size_t mg_queue_read_len(struct mg_queue *q) {
  5470. uint32_t n = 0;
  5471. MG_MEMORY_BARRIER();
  5472. memcpy(&n, q->buf + q->tail, sizeof(n));
  5473. assert(q->tail + n + sizeof(n) <= q->size);
  5474. return n;
  5475. }
  5476. static void mg_queue_write_len(struct mg_queue *q, size_t len) {
  5477. uint32_t n = (uint32_t) len;
  5478. memcpy(q->buf + q->head, &n, sizeof(n));
  5479. MG_MEMORY_BARRIER();
  5480. }
  5481. size_t mg_queue_book(struct mg_queue *q, char **buf, size_t len) {
  5482. size_t space = 0, hs = sizeof(uint32_t) * 2; // *2 is for the 0 marker
  5483. if (q->head >= q->tail && q->head + len + hs <= q->size) {
  5484. space = q->size - q->head - hs; // There is enough space
  5485. } else if (q->head >= q->tail && q->tail > hs) {
  5486. mg_queue_write_len(q, 0); // Not enough space ahead
  5487. q->head = 0; // Wrap head to the beginning
  5488. }
  5489. if (q->head + hs + len < q->tail) space = q->tail - q->head - hs;
  5490. if (buf != NULL) *buf = q->buf + q->head + sizeof(uint32_t);
  5491. return space;
  5492. }
  5493. size_t mg_queue_next(struct mg_queue *q, char **buf) {
  5494. size_t len = 0;
  5495. if (q->tail != q->head) {
  5496. len = mg_queue_read_len(q);
  5497. if (len == 0) { // Zero (head wrapped) ?
  5498. q->tail = 0; // Reset tail to the start
  5499. if (q->head > q->tail) len = mg_queue_read_len(q); // Read again
  5500. }
  5501. }
  5502. if (buf != NULL) *buf = q->buf + q->tail + sizeof(uint32_t);
  5503. assert(q->tail + len <= q->size);
  5504. return len;
  5505. }
  5506. void mg_queue_add(struct mg_queue *q, size_t len) {
  5507. assert(len > 0);
  5508. mg_queue_write_len(q, len);
  5509. assert(q->head + sizeof(uint32_t) * 2 + len <= q->size);
  5510. q->head += len + sizeof(uint32_t);
  5511. }
  5512. void mg_queue_del(struct mg_queue *q, size_t len) {
  5513. q->tail += len + sizeof(uint32_t);
  5514. assert(q->tail + sizeof(uint32_t) <= q->size);
  5515. }
  5516. #ifdef MG_ENABLE_LINES
  5517. #line 1 "src/rpc.c"
  5518. #endif
  5519. void mg_rpc_add(struct mg_rpc **head, struct mg_str method,
  5520. void (*fn)(struct mg_rpc_req *), void *fn_data) {
  5521. struct mg_rpc *rpc = (struct mg_rpc *) calloc(1, sizeof(*rpc));
  5522. if (rpc != NULL) {
  5523. rpc->method = mg_strdup(method), rpc->fn = fn, rpc->fn_data = fn_data;
  5524. rpc->next = *head, *head = rpc;
  5525. }
  5526. }
  5527. void mg_rpc_del(struct mg_rpc **head, void (*fn)(struct mg_rpc_req *)) {
  5528. struct mg_rpc *r;
  5529. while ((r = *head) != NULL) {
  5530. if (r->fn == fn || fn == NULL) {
  5531. *head = r->next;
  5532. free((void *) r->method.ptr);
  5533. free(r);
  5534. } else {
  5535. head = &(*head)->next;
  5536. }
  5537. }
  5538. }
  5539. static void mg_rpc_call(struct mg_rpc_req *r, struct mg_str method) {
  5540. struct mg_rpc *h = r->head == NULL ? NULL : *r->head;
  5541. while (h != NULL && !mg_match(method, h->method, NULL)) h = h->next;
  5542. if (h != NULL) {
  5543. r->rpc = h;
  5544. h->fn(r);
  5545. } else {
  5546. mg_rpc_err(r, -32601, "\"%.*s not found\"", (int) method.len, method.ptr);
  5547. }
  5548. }
  5549. void mg_rpc_process(struct mg_rpc_req *r) {
  5550. int len, off = mg_json_get(r->frame, "$.method", &len);
  5551. if (off > 0 && r->frame.ptr[off] == '"') {
  5552. struct mg_str method = mg_str_n(&r->frame.ptr[off + 1], (size_t) len - 2);
  5553. mg_rpc_call(r, method);
  5554. } else if ((off = mg_json_get(r->frame, "$.result", &len)) > 0 ||
  5555. (off = mg_json_get(r->frame, "$.error", &len)) > 0) {
  5556. mg_rpc_call(r, mg_str("")); // JSON response! call "" method handler
  5557. } else {
  5558. mg_rpc_err(r, -32700, "%m", mg_print_esc, (int) r->frame.len,
  5559. r->frame.ptr); // Invalid
  5560. }
  5561. }
  5562. void mg_rpc_vok(struct mg_rpc_req *r, const char *fmt, va_list *ap) {
  5563. int len, off = mg_json_get(r->frame, "$.id", &len);
  5564. if (off > 0) {
  5565. mg_xprintf(r->pfn, r->pfn_data, "{%m:%.*s,%m:", mg_print_esc, 0, "id", len,
  5566. &r->frame.ptr[off], mg_print_esc, 0, "result");
  5567. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  5568. mg_xprintf(r->pfn, r->pfn_data, "}");
  5569. }
  5570. }
  5571. void mg_rpc_ok(struct mg_rpc_req *r, const char *fmt, ...) {
  5572. va_list ap;
  5573. va_start(ap, fmt);
  5574. mg_rpc_vok(r, fmt, &ap);
  5575. va_end(ap);
  5576. }
  5577. void mg_rpc_verr(struct mg_rpc_req *r, int code, const char *fmt, va_list *ap) {
  5578. int len, off = mg_json_get(r->frame, "$.id", &len);
  5579. mg_xprintf(r->pfn, r->pfn_data, "{");
  5580. if (off > 0) {
  5581. mg_xprintf(r->pfn, r->pfn_data, "%m:%.*s,", mg_print_esc, 0, "id", len,
  5582. &r->frame.ptr[off]);
  5583. }
  5584. mg_xprintf(r->pfn, r->pfn_data, "%m:{%m:%d,%m:", mg_print_esc, 0, "error",
  5585. mg_print_esc, 0, "code", code, mg_print_esc, 0, "message");
  5586. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  5587. mg_xprintf(r->pfn, r->pfn_data, "}}");
  5588. }
  5589. void mg_rpc_err(struct mg_rpc_req *r, int code, const char *fmt, ...) {
  5590. va_list ap;
  5591. va_start(ap, fmt);
  5592. mg_rpc_verr(r, code, fmt, &ap);
  5593. va_end(ap);
  5594. }
  5595. static size_t print_methods(mg_pfn_t pfn, void *pfn_data, va_list *ap) {
  5596. struct mg_rpc *h, **head = (struct mg_rpc **) va_arg(*ap, void **);
  5597. size_t len = 0;
  5598. for (h = *head; h != NULL; h = h->next) {
  5599. if (h->method.len == 0) continue; // Ignore response handler
  5600. len += mg_xprintf(pfn, pfn_data, "%s%m", h == *head ? "" : ",",
  5601. mg_print_esc, (int) h->method.len, h->method.ptr);
  5602. }
  5603. return len;
  5604. }
  5605. void mg_rpc_list(struct mg_rpc_req *r) {
  5606. mg_rpc_ok(r, "[%M]", print_methods, r->head);
  5607. }
  5608. #ifdef MG_ENABLE_LINES
  5609. #line 1 "src/sha1.c"
  5610. #endif
  5611. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  5612. /* 100% Public Domain */
  5613. union char64long16 {
  5614. unsigned char c[64];
  5615. uint32_t l[16];
  5616. };
  5617. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  5618. static uint32_t blk0(union char64long16 *block, int i) {
  5619. if (MG_BIG_ENDIAN) {
  5620. } else {
  5621. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  5622. (rol(block->l[i], 8) & 0x00FF00FF);
  5623. }
  5624. return block->l[i];
  5625. }
  5626. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  5627. #undef blk
  5628. #undef R0
  5629. #undef R1
  5630. #undef R2
  5631. #undef R3
  5632. #undef R4
  5633. #define blk(i) \
  5634. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  5635. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  5636. 1))
  5637. #define R0(v, w, x, y, z, i) \
  5638. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  5639. w = rol(w, 30);
  5640. #define R1(v, w, x, y, z, i) \
  5641. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  5642. w = rol(w, 30);
  5643. #define R2(v, w, x, y, z, i) \
  5644. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  5645. w = rol(w, 30);
  5646. #define R3(v, w, x, y, z, i) \
  5647. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  5648. w = rol(w, 30);
  5649. #define R4(v, w, x, y, z, i) \
  5650. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  5651. w = rol(w, 30);
  5652. static void mg_sha1_transform(uint32_t state[5],
  5653. const unsigned char *buffer) {
  5654. uint32_t a, b, c, d, e;
  5655. union char64long16 block[1];
  5656. memcpy(block, buffer, 64);
  5657. a = state[0];
  5658. b = state[1];
  5659. c = state[2];
  5660. d = state[3];
  5661. e = state[4];
  5662. R0(a, b, c, d, e, 0);
  5663. R0(e, a, b, c, d, 1);
  5664. R0(d, e, a, b, c, 2);
  5665. R0(c, d, e, a, b, 3);
  5666. R0(b, c, d, e, a, 4);
  5667. R0(a, b, c, d, e, 5);
  5668. R0(e, a, b, c, d, 6);
  5669. R0(d, e, a, b, c, 7);
  5670. R0(c, d, e, a, b, 8);
  5671. R0(b, c, d, e, a, 9);
  5672. R0(a, b, c, d, e, 10);
  5673. R0(e, a, b, c, d, 11);
  5674. R0(d, e, a, b, c, 12);
  5675. R0(c, d, e, a, b, 13);
  5676. R0(b, c, d, e, a, 14);
  5677. R0(a, b, c, d, e, 15);
  5678. R1(e, a, b, c, d, 16);
  5679. R1(d, e, a, b, c, 17);
  5680. R1(c, d, e, a, b, 18);
  5681. R1(b, c, d, e, a, 19);
  5682. R2(a, b, c, d, e, 20);
  5683. R2(e, a, b, c, d, 21);
  5684. R2(d, e, a, b, c, 22);
  5685. R2(c, d, e, a, b, 23);
  5686. R2(b, c, d, e, a, 24);
  5687. R2(a, b, c, d, e, 25);
  5688. R2(e, a, b, c, d, 26);
  5689. R2(d, e, a, b, c, 27);
  5690. R2(c, d, e, a, b, 28);
  5691. R2(b, c, d, e, a, 29);
  5692. R2(a, b, c, d, e, 30);
  5693. R2(e, a, b, c, d, 31);
  5694. R2(d, e, a, b, c, 32);
  5695. R2(c, d, e, a, b, 33);
  5696. R2(b, c, d, e, a, 34);
  5697. R2(a, b, c, d, e, 35);
  5698. R2(e, a, b, c, d, 36);
  5699. R2(d, e, a, b, c, 37);
  5700. R2(c, d, e, a, b, 38);
  5701. R2(b, c, d, e, a, 39);
  5702. R3(a, b, c, d, e, 40);
  5703. R3(e, a, b, c, d, 41);
  5704. R3(d, e, a, b, c, 42);
  5705. R3(c, d, e, a, b, 43);
  5706. R3(b, c, d, e, a, 44);
  5707. R3(a, b, c, d, e, 45);
  5708. R3(e, a, b, c, d, 46);
  5709. R3(d, e, a, b, c, 47);
  5710. R3(c, d, e, a, b, 48);
  5711. R3(b, c, d, e, a, 49);
  5712. R3(a, b, c, d, e, 50);
  5713. R3(e, a, b, c, d, 51);
  5714. R3(d, e, a, b, c, 52);
  5715. R3(c, d, e, a, b, 53);
  5716. R3(b, c, d, e, a, 54);
  5717. R3(a, b, c, d, e, 55);
  5718. R3(e, a, b, c, d, 56);
  5719. R3(d, e, a, b, c, 57);
  5720. R3(c, d, e, a, b, 58);
  5721. R3(b, c, d, e, a, 59);
  5722. R4(a, b, c, d, e, 60);
  5723. R4(e, a, b, c, d, 61);
  5724. R4(d, e, a, b, c, 62);
  5725. R4(c, d, e, a, b, 63);
  5726. R4(b, c, d, e, a, 64);
  5727. R4(a, b, c, d, e, 65);
  5728. R4(e, a, b, c, d, 66);
  5729. R4(d, e, a, b, c, 67);
  5730. R4(c, d, e, a, b, 68);
  5731. R4(b, c, d, e, a, 69);
  5732. R4(a, b, c, d, e, 70);
  5733. R4(e, a, b, c, d, 71);
  5734. R4(d, e, a, b, c, 72);
  5735. R4(c, d, e, a, b, 73);
  5736. R4(b, c, d, e, a, 74);
  5737. R4(a, b, c, d, e, 75);
  5738. R4(e, a, b, c, d, 76);
  5739. R4(d, e, a, b, c, 77);
  5740. R4(c, d, e, a, b, 78);
  5741. R4(b, c, d, e, a, 79);
  5742. state[0] += a;
  5743. state[1] += b;
  5744. state[2] += c;
  5745. state[3] += d;
  5746. state[4] += e;
  5747. /* Erase working structures. The order of operations is important,
  5748. * used to ensure that compiler doesn't optimize those out. */
  5749. memset(block, 0, sizeof(block));
  5750. a = b = c = d = e = 0;
  5751. (void) a;
  5752. (void) b;
  5753. (void) c;
  5754. (void) d;
  5755. (void) e;
  5756. }
  5757. void mg_sha1_init(mg_sha1_ctx *context) {
  5758. context->state[0] = 0x67452301;
  5759. context->state[1] = 0xEFCDAB89;
  5760. context->state[2] = 0x98BADCFE;
  5761. context->state[3] = 0x10325476;
  5762. context->state[4] = 0xC3D2E1F0;
  5763. context->count[0] = context->count[1] = 0;
  5764. }
  5765. void mg_sha1_update(mg_sha1_ctx *context, const unsigned char *data,
  5766. size_t len) {
  5767. size_t i, j;
  5768. j = context->count[0];
  5769. if ((context->count[0] += (uint32_t) len << 3) < j) context->count[1]++;
  5770. context->count[1] += (uint32_t) (len >> 29);
  5771. j = (j >> 3) & 63;
  5772. if ((j + len) > 63) {
  5773. memcpy(&context->buffer[j], data, (i = 64 - j));
  5774. mg_sha1_transform(context->state, context->buffer);
  5775. for (; i + 63 < len; i += 64) {
  5776. mg_sha1_transform(context->state, &data[i]);
  5777. }
  5778. j = 0;
  5779. } else
  5780. i = 0;
  5781. memcpy(&context->buffer[j], &data[i], len - i);
  5782. }
  5783. void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *context) {
  5784. unsigned i;
  5785. unsigned char finalcount[8], c;
  5786. for (i = 0; i < 8; i++) {
  5787. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  5788. ((3 - (i & 3)) * 8)) &
  5789. 255);
  5790. }
  5791. c = 0200;
  5792. mg_sha1_update(context, &c, 1);
  5793. while ((context->count[0] & 504) != 448) {
  5794. c = 0000;
  5795. mg_sha1_update(context, &c, 1);
  5796. }
  5797. mg_sha1_update(context, finalcount, 8);
  5798. for (i = 0; i < 20; i++) {
  5799. digest[i] =
  5800. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  5801. }
  5802. memset(context, '\0', sizeof(*context));
  5803. memset(&finalcount, '\0', sizeof(finalcount));
  5804. }
  5805. #ifdef MG_ENABLE_LINES
  5806. #line 1 "src/sha256.c"
  5807. #endif
  5808. #define ror(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
  5809. #define ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
  5810. #define maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
  5811. #define ep0(x) (ror(x, 2) ^ ror(x, 13) ^ ror(x, 22))
  5812. #define ep1(x) (ror(x, 6) ^ ror(x, 11) ^ ror(x, 25))
  5813. #define sig0(x) (ror(x, 7) ^ ror(x, 18) ^ ((x) >> 3))
  5814. #define sig1(x) (ror(x, 17) ^ ror(x, 19) ^ ((x) >> 10))
  5815. static const uint32_t mg_sha256_k[64] = {
  5816. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
  5817. 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  5818. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
  5819. 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  5820. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
  5821. 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  5822. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
  5823. 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  5824. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
  5825. 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  5826. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
  5827. void mg_sha256_init(mg_sha256_ctx *ctx) {
  5828. ctx->len = 0;
  5829. ctx->bits = 0;
  5830. ctx->state[0] = 0x6a09e667;
  5831. ctx->state[1] = 0xbb67ae85;
  5832. ctx->state[2] = 0x3c6ef372;
  5833. ctx->state[3] = 0xa54ff53a;
  5834. ctx->state[4] = 0x510e527f;
  5835. ctx->state[5] = 0x9b05688c;
  5836. ctx->state[6] = 0x1f83d9ab;
  5837. ctx->state[7] = 0x5be0cd19;
  5838. }
  5839. static void mg_sha256_chunk(mg_sha256_ctx *ctx) {
  5840. int i, j;
  5841. uint32_t a, b, c, d, e, f, g, h;
  5842. uint32_t m[64];
  5843. for (i = 0, j = 0; i < 16; ++i, j += 4)
  5844. m[i] = (uint32_t) ((ctx->buffer[j] << 24) | (ctx->buffer[j + 1] << 16) |
  5845. (ctx->buffer[j + 2] << 8) | (ctx->buffer[j + 3]));
  5846. for (; i < 64; ++i)
  5847. m[i] = sig1(m[i - 2]) + m[i - 7] + sig0(m[i - 15]) + m[i - 16];
  5848. a = ctx->state[0];
  5849. b = ctx->state[1];
  5850. c = ctx->state[2];
  5851. d = ctx->state[3];
  5852. e = ctx->state[4];
  5853. f = ctx->state[5];
  5854. g = ctx->state[6];
  5855. h = ctx->state[7];
  5856. for (i = 0; i < 64; ++i) {
  5857. uint32_t t1 = h + ep1(e) + ch(e, f, g) + mg_sha256_k[i] + m[i];
  5858. uint32_t t2 = ep0(a) + maj(a, b, c);
  5859. h = g;
  5860. g = f;
  5861. f = e;
  5862. e = d + t1;
  5863. d = c;
  5864. c = b;
  5865. b = a;
  5866. a = t1 + t2;
  5867. }
  5868. ctx->state[0] += a;
  5869. ctx->state[1] += b;
  5870. ctx->state[2] += c;
  5871. ctx->state[3] += d;
  5872. ctx->state[4] += e;
  5873. ctx->state[5] += f;
  5874. ctx->state[6] += g;
  5875. ctx->state[7] += h;
  5876. }
  5877. void mg_sha256_update(mg_sha256_ctx *ctx, const unsigned char *data,
  5878. size_t len) {
  5879. size_t i;
  5880. for (i = 0; i < len; i++) {
  5881. ctx->buffer[ctx->len] = data[i];
  5882. if ((++ctx->len) == 64) {
  5883. mg_sha256_chunk(ctx);
  5884. ctx->bits += 512;
  5885. ctx->len = 0;
  5886. }
  5887. }
  5888. }
  5889. // TODO: make final reusable (remove side effects)
  5890. void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *ctx) {
  5891. uint32_t i = ctx->len;
  5892. if (i < 56) {
  5893. ctx->buffer[i++] = 0x80;
  5894. while (i < 56) {
  5895. ctx->buffer[i++] = 0x00;
  5896. }
  5897. } else {
  5898. ctx->buffer[i++] = 0x80;
  5899. while (i < 64) {
  5900. ctx->buffer[i++] = 0x00;
  5901. }
  5902. mg_sha256_chunk(ctx);
  5903. memset(ctx->buffer, 0, 56);
  5904. }
  5905. ctx->bits += ctx->len * 8;
  5906. ctx->buffer[63] = (uint8_t) ((ctx->bits) & 0xff);
  5907. ctx->buffer[62] = (uint8_t) ((ctx->bits >> 8) & 0xff);
  5908. ctx->buffer[61] = (uint8_t) ((ctx->bits >> 16) & 0xff);
  5909. ctx->buffer[60] = (uint8_t) ((ctx->bits >> 24) & 0xff);
  5910. ctx->buffer[59] = (uint8_t) ((ctx->bits >> 32) & 0xff);
  5911. ctx->buffer[58] = (uint8_t) ((ctx->bits >> 40) & 0xff);
  5912. ctx->buffer[57] = (uint8_t) ((ctx->bits >> 48) & 0xff);
  5913. ctx->buffer[56] = (uint8_t) ((ctx->bits >> 56) & 0xff);
  5914. mg_sha256_chunk(ctx);
  5915. for (i = 0; i < 4; ++i) {
  5916. digest[i] = (ctx->state[0] >> (24 - i * 8)) & 0xff;
  5917. digest[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0xff;
  5918. digest[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0xff;
  5919. digest[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0xff;
  5920. digest[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0xff;
  5921. digest[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0xff;
  5922. digest[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0xff;
  5923. digest[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0xff;
  5924. }
  5925. }
  5926. void mg_hmac_sha256(uint8_t dst[32], uint8_t *key, size_t keysz, uint8_t *data,
  5927. size_t datasz) {
  5928. mg_sha256_ctx ctx;
  5929. uint8_t k[64] = {0};
  5930. uint8_t o_pad[64], i_pad[64];
  5931. unsigned int i;
  5932. memset(i_pad, 0x36, sizeof(i_pad));
  5933. memset(o_pad, 0x5c, sizeof(o_pad));
  5934. if (keysz < 64) {
  5935. memmove(k, key, keysz);
  5936. } else {
  5937. mg_sha256_init(&ctx);
  5938. mg_sha256_update(&ctx, key, keysz);
  5939. mg_sha256_final(k, &ctx);
  5940. }
  5941. for (i = 0; i < sizeof(k); i++) {
  5942. i_pad[i] ^= k[i];
  5943. o_pad[i] ^= k[i];
  5944. }
  5945. mg_sha256_init(&ctx);
  5946. mg_sha256_update(&ctx, i_pad, sizeof(i_pad));
  5947. mg_sha256_update(&ctx, data, datasz);
  5948. mg_sha256_final(dst, &ctx);
  5949. mg_sha256_init(&ctx);
  5950. mg_sha256_update(&ctx, o_pad, sizeof(o_pad));
  5951. mg_sha256_update(&ctx, dst, 32);
  5952. mg_sha256_final(dst, &ctx);
  5953. }
  5954. #ifdef MG_ENABLE_LINES
  5955. #line 1 "src/sntp.c"
  5956. #endif
  5957. #define SNTP_TIME_OFFSET 2208988800U // (1970 - 1900) in seconds
  5958. #define SNTP_MAX_FRAC 4294967295.0 // 2 ** 32 - 1
  5959. static int64_t gettimestamp(const uint32_t *data) {
  5960. uint32_t sec = mg_ntohl(data[0]), frac = mg_ntohl(data[1]);
  5961. if (sec) sec -= SNTP_TIME_OFFSET;
  5962. return ((int64_t) sec) * 1000 + (int64_t) (frac / SNTP_MAX_FRAC * 1000.0);
  5963. }
  5964. int64_t mg_sntp_parse(const unsigned char *buf, size_t len) {
  5965. int64_t res = -1;
  5966. int mode = len > 0 ? buf[0] & 7 : 0;
  5967. int version = len > 0 ? (buf[0] >> 3) & 7 : 0;
  5968. if (len < 48) {
  5969. MG_ERROR(("%s", "corrupt packet"));
  5970. } else if (mode != 4 && mode != 5) {
  5971. MG_ERROR(("%s", "not a server reply"));
  5972. } else if (buf[1] == 0) {
  5973. MG_ERROR(("%s", "server sent a kiss of death"));
  5974. } else if (version == 4 || version == 3) {
  5975. // int64_t ref = gettimestamp((uint32_t *) &buf[16]);
  5976. int64_t t0 = gettimestamp((uint32_t *) &buf[24]);
  5977. int64_t t1 = gettimestamp((uint32_t *) &buf[32]);
  5978. int64_t t2 = gettimestamp((uint32_t *) &buf[40]);
  5979. int64_t t3 = (int64_t) mg_millis();
  5980. int64_t delta = (t3 - t0) - (t2 - t1);
  5981. MG_VERBOSE(("%lld %lld %lld %lld delta:%lld", t0, t1, t2, t3, delta));
  5982. res = t2 + delta / 2;
  5983. } else {
  5984. MG_ERROR(("unexpected version: %d", version));
  5985. }
  5986. return res;
  5987. }
  5988. static void sntp_cb(struct mg_connection *c, int ev, void *ev_data) {
  5989. if (ev == MG_EV_READ) {
  5990. int64_t milliseconds = mg_sntp_parse(c->recv.buf, c->recv.len);
  5991. if (milliseconds > 0) {
  5992. MG_INFO(("%lu got time: %lld ms from epoch", c->id, milliseconds));
  5993. mg_call(c, MG_EV_SNTP_TIME, (uint64_t *) &milliseconds);
  5994. MG_VERBOSE(("%u.%u", (unsigned) (milliseconds / 1000),
  5995. (unsigned) (milliseconds % 1000)));
  5996. }
  5997. mg_iobuf_del(&c->recv, 0, c->recv.len); // Free receive buffer
  5998. } else if (ev == MG_EV_CONNECT) {
  5999. mg_sntp_request(c);
  6000. } else if (ev == MG_EV_CLOSE) {
  6001. }
  6002. (void) ev_data;
  6003. }
  6004. void mg_sntp_request(struct mg_connection *c) {
  6005. if (c->is_resolving) {
  6006. MG_ERROR(("%lu wait until resolved", c->id));
  6007. } else {
  6008. int64_t now = (int64_t) mg_millis(); // Use int64_t, for vc98
  6009. uint8_t buf[48] = {0};
  6010. uint32_t *t = (uint32_t *) &buf[40];
  6011. double frac = ((double) (now % 1000)) / 1000.0 * SNTP_MAX_FRAC;
  6012. buf[0] = (0 << 6) | (4 << 3) | 3;
  6013. t[0] = mg_htonl((uint32_t) (now / 1000) + SNTP_TIME_OFFSET);
  6014. t[1] = mg_htonl((uint32_t) frac);
  6015. mg_send(c, buf, sizeof(buf));
  6016. }
  6017. }
  6018. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url,
  6019. mg_event_handler_t fn, void *fnd) {
  6020. struct mg_connection *c = NULL;
  6021. if (url == NULL) url = "udp://time.google.com:123";
  6022. if ((c = mg_connect(mgr, url, fn, fnd)) != NULL) c->pfn = sntp_cb;
  6023. return c;
  6024. }
  6025. #ifdef MG_ENABLE_LINES
  6026. #line 1 "src/sock.c"
  6027. #endif
  6028. #if MG_ENABLE_SOCKET
  6029. #ifndef closesocket
  6030. #define closesocket(x) close(x)
  6031. #endif
  6032. #define FD(c_) ((MG_SOCKET_TYPE) (size_t) (c_)->fd)
  6033. #define S2PTR(s_) ((void *) (size_t) (s_))
  6034. #ifndef MSG_NONBLOCKING
  6035. #define MSG_NONBLOCKING 0
  6036. #endif
  6037. #ifndef AF_INET6
  6038. #define AF_INET6 10
  6039. #endif
  6040. #ifndef MG_SOCK_ERR
  6041. #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? errno : 0)
  6042. #endif
  6043. #ifndef MG_SOCK_INTR
  6044. #define MG_SOCK_INTR(fd) (fd == MG_INVALID_SOCKET && MG_SOCK_ERR(-1) == EINTR)
  6045. #endif
  6046. #ifndef MG_SOCK_PENDING
  6047. #define MG_SOCK_PENDING(errcode) \
  6048. (((errcode) < 0) && (errno == EINPROGRESS || errno == EWOULDBLOCK))
  6049. #endif
  6050. #ifndef MG_SOCK_RESET
  6051. #define MG_SOCK_RESET(errcode) \
  6052. (((errcode) < 0) && (errno == EPIPE || errno == ECONNRESET))
  6053. #endif
  6054. union usa {
  6055. struct sockaddr sa;
  6056. struct sockaddr_in sin;
  6057. #if MG_ENABLE_IPV6
  6058. struct sockaddr_in6 sin6;
  6059. #endif
  6060. };
  6061. static socklen_t tousa(struct mg_addr *a, union usa *usa) {
  6062. socklen_t len = sizeof(usa->sin);
  6063. memset(usa, 0, sizeof(*usa));
  6064. usa->sin.sin_family = AF_INET;
  6065. usa->sin.sin_port = a->port;
  6066. memcpy(&usa->sin.sin_addr, a->ip, sizeof(uint32_t));
  6067. #if MG_ENABLE_IPV6
  6068. if (a->is_ip6) {
  6069. usa->sin.sin_family = AF_INET6;
  6070. usa->sin6.sin6_port = a->port;
  6071. usa->sin6.sin6_scope_id = a->scope_id;
  6072. memcpy(&usa->sin6.sin6_addr, a->ip, sizeof(a->ip));
  6073. len = sizeof(usa->sin6);
  6074. }
  6075. #endif
  6076. return len;
  6077. }
  6078. static void tomgaddr(union usa *usa, struct mg_addr *a, bool is_ip6) {
  6079. a->is_ip6 = is_ip6;
  6080. a->port = usa->sin.sin_port;
  6081. memcpy(&a->ip, &usa->sin.sin_addr, sizeof(uint32_t));
  6082. #if MG_ENABLE_IPV6
  6083. if (is_ip6) {
  6084. memcpy(a->ip, &usa->sin6.sin6_addr, sizeof(a->ip));
  6085. a->port = usa->sin6.sin6_port;
  6086. a->scope_id = (uint8_t) usa->sin6.sin6_scope_id;
  6087. }
  6088. #endif
  6089. }
  6090. static void setlocaddr(MG_SOCKET_TYPE fd, struct mg_addr *addr) {
  6091. union usa usa;
  6092. socklen_t n = sizeof(usa);
  6093. if (getsockname(fd, &usa.sa, &n) == 0) {
  6094. tomgaddr(&usa, addr, n != sizeof(usa.sin));
  6095. }
  6096. }
  6097. static void iolog(struct mg_connection *c, char *buf, long n, bool r) {
  6098. if (n == MG_IO_WAIT) {
  6099. // Do nothing
  6100. } else if (n <= 0) {
  6101. c->is_closing = 1; // Termination. Don't call mg_error(): #1529
  6102. } else if (n > 0) {
  6103. if (c->is_hexdumping) {
  6104. union usa usa;
  6105. socklen_t slen = sizeof(usa.sin);
  6106. if (getsockname(FD(c), &usa.sa, &slen) < 0) (void) 0; // Ignore result
  6107. MG_INFO(("\n-- %lu %M %s %M %ld", c->id, mg_print_ip_port, &c->loc,
  6108. r ? "<-" : "->", mg_print_ip_port, &c->rem, n));
  6109. mg_hexdump(buf, (size_t) n);
  6110. }
  6111. if (r) {
  6112. c->recv.len += (size_t) n;
  6113. mg_call(c, MG_EV_READ, &n);
  6114. } else {
  6115. mg_iobuf_del(&c->send, 0, (size_t) n);
  6116. // if (c->send.len == 0) mg_iobuf_resize(&c->send, 0);
  6117. if (c->send.len == 0) {
  6118. MG_EPOLL_MOD(c, 0);
  6119. }
  6120. mg_call(c, MG_EV_WRITE, &n);
  6121. }
  6122. }
  6123. }
  6124. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  6125. long n;
  6126. if (c->is_udp) {
  6127. union usa usa;
  6128. socklen_t slen = tousa(&c->rem, &usa);
  6129. n = sendto(FD(c), (char *) buf, len, 0, &usa.sa, slen);
  6130. if (n > 0) setlocaddr(FD(c), &c->loc);
  6131. } else {
  6132. n = send(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6133. }
  6134. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6135. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6136. if (n <= 0) return MG_IO_ERR;
  6137. return n;
  6138. }
  6139. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  6140. if (c->is_udp) {
  6141. long n = mg_io_send(c, buf, len);
  6142. MG_DEBUG(("%lu %ld %d:%d %ld err %d", c->id, c->fd, (int) c->send.len,
  6143. (int) c->recv.len, n, MG_SOCK_ERR(n)));
  6144. iolog(c, (char *) buf, n, false);
  6145. return n > 0;
  6146. } else {
  6147. return mg_iobuf_add(&c->send, c->send.len, buf, len);
  6148. }
  6149. }
  6150. static void mg_set_non_blocking_mode(MG_SOCKET_TYPE fd) {
  6151. #if defined(MG_CUSTOM_NONBLOCK)
  6152. MG_CUSTOM_NONBLOCK(fd);
  6153. #elif MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  6154. unsigned long on = 1;
  6155. ioctlsocket(fd, FIONBIO, &on);
  6156. #elif MG_ENABLE_RL
  6157. unsigned long on = 1;
  6158. ioctlsocket(fd, FIONBIO, &on);
  6159. #elif MG_ENABLE_FREERTOS_TCP
  6160. const BaseType_t off = 0;
  6161. if (setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6162. if (setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6163. #elif MG_ENABLE_LWIP
  6164. lwip_fcntl(fd, F_SETFL, O_NONBLOCK);
  6165. #elif MG_ARCH == MG_ARCH_AZURERTOS
  6166. fcntl(fd, F_SETFL, O_NONBLOCK);
  6167. #elif MG_ARCH == MG_ARCH_TIRTOS
  6168. int val = 0;
  6169. setsockopt(fd, SOL_SOCKET, SO_BLOCKING, &val, sizeof(val));
  6170. // SPRU524J section 3.3.3 page 63, SO_SNDLOWAT
  6171. int sz = sizeof(val);
  6172. getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &val, &sz);
  6173. val /= 2; // set send low-water mark at half send buffer size
  6174. setsockopt(fd, SOL_SOCKET, SO_SNDLOWAT, &val, sizeof(val));
  6175. #else
  6176. fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); // Non-blocking mode
  6177. fcntl(fd, F_SETFD, FD_CLOEXEC); // Set close-on-exec
  6178. #endif
  6179. }
  6180. bool mg_open_listener(struct mg_connection *c, const char *url) {
  6181. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6182. bool success = false;
  6183. c->loc.port = mg_htons(mg_url_port(url));
  6184. if (!mg_aton(mg_url_host(url), &c->loc)) {
  6185. MG_ERROR(("invalid listening URL: %s", url));
  6186. } else {
  6187. union usa usa;
  6188. socklen_t slen = tousa(&c->loc, &usa);
  6189. int rc, on = 1, af = c->loc.is_ip6 ? AF_INET6 : AF_INET;
  6190. int type = strncmp(url, "udp:", 4) == 0 ? SOCK_DGRAM : SOCK_STREAM;
  6191. int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP;
  6192. (void) on;
  6193. if ((fd = socket(af, type, proto)) == MG_INVALID_SOCKET) {
  6194. MG_ERROR(("socket: %d", MG_SOCK_ERR(-1)));
  6195. #if defined(SO_EXCLUSIVEADDRUSE)
  6196. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  6197. (char *) &on, sizeof(on))) != 0) {
  6198. // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE"
  6199. MG_ERROR(("setsockopt(SO_EXCLUSIVEADDRUSE): %d %d", on, MG_SOCK_ERR(rc)));
  6200. #elif defined(SO_REUSEADDR) && (!defined(LWIP_SOCKET) || SO_REUSE)
  6201. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on,
  6202. sizeof(on))) != 0) {
  6203. // 1. SO_REUSEADDR semantics on UNIX and Windows is different. On
  6204. // Windows, SO_REUSEADDR allows to bind a socket to a port without error
  6205. // even if the port is already open by another program. This is not the
  6206. // behavior SO_REUSEADDR was designed for, and leads to hard-to-track
  6207. // failure scenarios.
  6208. //
  6209. // 2. For LWIP, SO_REUSEADDR should be explicitly enabled by defining
  6210. // SO_REUSE = 1 in lwipopts.h, otherwise the code below will compile but
  6211. // won't work! (setsockopt will return EINVAL)
  6212. MG_ERROR(("setsockopt(SO_REUSEADDR): %d", MG_SOCK_ERR(rc)));
  6213. #endif
  6214. #if MG_IPV6_V6ONLY
  6215. // Bind only to the V6 address, not V4 address on this port
  6216. } else if (c->loc.is_ip6 &&
  6217. (rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &on,
  6218. sizeof(on))) != 0) {
  6219. // See #2089. Allow to bind v4 and v6 sockets on the same port
  6220. MG_ERROR(("setsockopt(IPV6_V6ONLY): %d", MG_SOCK_ERR(rc)));
  6221. #endif
  6222. } else if ((rc = bind(fd, &usa.sa, slen)) != 0) {
  6223. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6224. } else if ((type == SOCK_STREAM &&
  6225. (rc = listen(fd, MG_SOCK_LISTEN_BACKLOG_SIZE)) != 0)) {
  6226. // NOTE(lsm): FreeRTOS uses backlog value as a connection limit
  6227. // In case port was set to 0, get the real port number
  6228. MG_ERROR(("listen: %d", MG_SOCK_ERR(rc)));
  6229. } else {
  6230. setlocaddr(fd, &c->loc);
  6231. mg_set_non_blocking_mode(fd);
  6232. c->fd = S2PTR(fd);
  6233. MG_EPOLL_ADD(c);
  6234. success = true;
  6235. }
  6236. }
  6237. if (success == false && fd != MG_INVALID_SOCKET) closesocket(fd);
  6238. return success;
  6239. }
  6240. static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
  6241. long n = 0;
  6242. if (c->is_udp) {
  6243. union usa usa;
  6244. socklen_t slen = tousa(&c->rem, &usa);
  6245. n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
  6246. if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
  6247. } else {
  6248. n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6249. }
  6250. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6251. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6252. if (n <= 0) return MG_IO_ERR;
  6253. return n;
  6254. }
  6255. static bool ioalloc(struct mg_connection *c, struct mg_iobuf *io) {
  6256. bool res = false;
  6257. if (io->len >= MG_MAX_RECV_SIZE) {
  6258. mg_error(c, "MG_MAX_RECV_SIZE");
  6259. } else if (io->size <= io->len &&
  6260. !mg_iobuf_resize(io, io->size + MG_IO_SIZE)) {
  6261. mg_error(c, "OOM");
  6262. } else {
  6263. res = true;
  6264. }
  6265. return res;
  6266. }
  6267. // NOTE(lsm): do only one iteration of reads, cause some systems
  6268. // (e.g. FreeRTOS stack) return 0 instead of -1/EWOULDBLOCK when no data
  6269. static void read_conn(struct mg_connection *c) {
  6270. if (ioalloc(c, &c->recv)) {
  6271. char *buf = (char *) &c->recv.buf[c->recv.len];
  6272. size_t len = c->recv.size - c->recv.len;
  6273. long n = -1;
  6274. if (c->is_tls) {
  6275. if (!ioalloc(c, &c->rtls)) return;
  6276. n = recv_raw(c, (char *) &c->rtls.buf[c->rtls.len],
  6277. c->rtls.size - c->rtls.len);
  6278. // MG_DEBUG(("%lu %ld", c->id, n));
  6279. if (n == MG_IO_ERR) {
  6280. c->is_closing = 1;
  6281. } else if (n > 0) {
  6282. c->rtls.len += (size_t) n;
  6283. if (c->is_tls_hs) mg_tls_handshake(c);
  6284. if (c->is_tls_hs) return;
  6285. n = mg_tls_recv(c, buf, len);
  6286. } else if (n == MG_IO_WAIT) {
  6287. n = mg_tls_recv(c, buf, len);
  6288. }
  6289. } else {
  6290. n = recv_raw(c, buf, len);
  6291. }
  6292. MG_DEBUG(("%lu %p snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6293. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6294. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6295. iolog(c, buf, n, true);
  6296. }
  6297. }
  6298. static void write_conn(struct mg_connection *c) {
  6299. char *buf = (char *) c->send.buf;
  6300. size_t len = c->send.len;
  6301. long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len);
  6302. MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6303. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6304. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6305. iolog(c, buf, n, false);
  6306. }
  6307. static void close_conn(struct mg_connection *c) {
  6308. if (FD(c) != MG_INVALID_SOCKET) {
  6309. #if MG_ENABLE_EPOLL
  6310. epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_DEL, FD(c), NULL);
  6311. #endif
  6312. closesocket(FD(c));
  6313. #if MG_ENABLE_FREERTOS_TCP
  6314. FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL);
  6315. #endif
  6316. }
  6317. mg_close_conn(c);
  6318. }
  6319. static void connect_conn(struct mg_connection *c) {
  6320. union usa usa;
  6321. socklen_t n = sizeof(usa);
  6322. // Use getpeername() to test whether we have connected
  6323. if (getpeername(FD(c), &usa.sa, &n) == 0) {
  6324. c->is_connecting = 0;
  6325. mg_call(c, MG_EV_CONNECT, NULL);
  6326. MG_EPOLL_MOD(c, 0);
  6327. if (c->is_tls_hs) mg_tls_handshake(c);
  6328. } else {
  6329. mg_error(c, "socket error");
  6330. }
  6331. }
  6332. static void setsockopts(struct mg_connection *c) {
  6333. #if MG_ENABLE_FREERTOS_TCP || MG_ARCH == MG_ARCH_AZURERTOS || \
  6334. MG_ARCH == MG_ARCH_TIRTOS
  6335. (void) c;
  6336. #else
  6337. int on = 1;
  6338. #if !defined(SOL_TCP)
  6339. #define SOL_TCP IPPROTO_TCP
  6340. #endif
  6341. if (setsockopt(FD(c), SOL_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) != 0)
  6342. (void) 0;
  6343. if (setsockopt(FD(c), SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) !=
  6344. 0)
  6345. (void) 0;
  6346. #endif
  6347. }
  6348. void mg_connect_resolved(struct mg_connection *c) {
  6349. int type = c->is_udp ? SOCK_DGRAM : SOCK_STREAM;
  6350. int rc, af = c->rem.is_ip6 ? AF_INET6 : AF_INET; // c->rem has resolved IP
  6351. c->fd = S2PTR(socket(af, type, 0)); // Create outbound socket
  6352. c->is_resolving = 0; // Clear resolving flag
  6353. if (FD(c) == MG_INVALID_SOCKET) {
  6354. mg_error(c, "socket(): %d", MG_SOCK_ERR(-1));
  6355. } else if (c->is_udp) {
  6356. MG_EPOLL_ADD(c);
  6357. #if MG_ARCH == MG_ARCH_TIRTOS
  6358. union usa usa; // TI-RTOS NDK requires binding to receive on UDP sockets
  6359. socklen_t slen = tousa(&c->loc, &usa);
  6360. if ((rc = bind(c->fd, &usa.sa, slen)) != 0)
  6361. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6362. #endif
  6363. mg_call(c, MG_EV_RESOLVE, NULL);
  6364. mg_call(c, MG_EV_CONNECT, NULL);
  6365. } else {
  6366. union usa usa;
  6367. socklen_t slen = tousa(&c->rem, &usa);
  6368. mg_set_non_blocking_mode(FD(c));
  6369. setsockopts(c);
  6370. MG_EPOLL_ADD(c);
  6371. mg_call(c, MG_EV_RESOLVE, NULL);
  6372. rc = connect(FD(c), &usa.sa, slen); // Attempt to connect
  6373. if (rc == 0) { // Success
  6374. mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user
  6375. } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake
  6376. MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem));
  6377. c->is_connecting = 1;
  6378. } else {
  6379. mg_error(c, "connect: %d", MG_SOCK_ERR(rc));
  6380. }
  6381. }
  6382. }
  6383. static MG_SOCKET_TYPE raccept(MG_SOCKET_TYPE sock, union usa *usa,
  6384. socklen_t *len) {
  6385. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6386. do {
  6387. memset(usa, 0, sizeof(*usa));
  6388. fd = accept(sock, &usa->sa, len);
  6389. } while (MG_SOCK_INTR(fd));
  6390. return fd;
  6391. }
  6392. static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) {
  6393. struct mg_connection *c = NULL;
  6394. union usa usa;
  6395. socklen_t sa_len = sizeof(usa);
  6396. MG_SOCKET_TYPE fd = raccept(FD(lsn), &usa, &sa_len);
  6397. if (fd == MG_INVALID_SOCKET) {
  6398. #if MG_ARCH == MG_ARCH_AZURERTOS || defined(__ECOS)
  6399. // AzureRTOS, in non-block socket mode can mark listening socket readable
  6400. // even it is not. See comment for 'select' func implementation in
  6401. // nx_bsd.c That's not an error, just should try later
  6402. if (errno != EAGAIN)
  6403. #endif
  6404. MG_ERROR(("%lu accept failed, errno %d", lsn->id, MG_SOCK_ERR(-1)));
  6405. #if (MG_ARCH != MG_ARCH_WIN32) && !MG_ENABLE_FREERTOS_TCP && \
  6406. (MG_ARCH != MG_ARCH_TIRTOS) && !MG_ENABLE_POLL && !MG_ENABLE_EPOLL
  6407. } else if ((long) fd >= FD_SETSIZE) {
  6408. MG_ERROR(("%ld > %ld", (long) fd, (long) FD_SETSIZE));
  6409. closesocket(fd);
  6410. #endif
  6411. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  6412. MG_ERROR(("%lu OOM", lsn->id));
  6413. closesocket(fd);
  6414. } else {
  6415. tomgaddr(&usa, &c->rem, sa_len != sizeof(usa.sin));
  6416. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  6417. c->fd = S2PTR(fd);
  6418. MG_EPOLL_ADD(c);
  6419. mg_set_non_blocking_mode(FD(c));
  6420. setsockopts(c);
  6421. c->is_accepted = 1;
  6422. c->is_hexdumping = lsn->is_hexdumping;
  6423. c->loc = lsn->loc;
  6424. c->pfn = lsn->pfn;
  6425. c->pfn_data = lsn->pfn_data;
  6426. c->fn = lsn->fn;
  6427. c->fn_data = lsn->fn_data;
  6428. MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port,
  6429. &c->rem, mg_print_ip_port, &c->loc));
  6430. mg_call(c, MG_EV_OPEN, NULL);
  6431. mg_call(c, MG_EV_ACCEPT, NULL);
  6432. }
  6433. }
  6434. static bool can_read(const struct mg_connection *c) {
  6435. return c->is_full == false;
  6436. }
  6437. static bool can_write(const struct mg_connection *c) {
  6438. return c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0);
  6439. }
  6440. static bool skip_iotest(const struct mg_connection *c) {
  6441. return (c->is_closing || c->is_resolving || FD(c) == MG_INVALID_SOCKET) ||
  6442. (can_read(c) == false && can_write(c) == false);
  6443. }
  6444. static void mg_iotest(struct mg_mgr *mgr, int ms) {
  6445. #if MG_ENABLE_FREERTOS_TCP
  6446. struct mg_connection *c;
  6447. for (c = mgr->conns; c != NULL; c = c->next) {
  6448. c->is_readable = c->is_writable = 0;
  6449. if (skip_iotest(c)) continue;
  6450. if (can_read(c))
  6451. FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_READ | eSELECT_EXCEPT);
  6452. if (can_write(c)) FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_WRITE);
  6453. if (c->is_closing) ms = 1;
  6454. }
  6455. FreeRTOS_select(mgr->ss, pdMS_TO_TICKS(ms));
  6456. for (c = mgr->conns; c != NULL; c = c->next) {
  6457. EventBits_t bits = FreeRTOS_FD_ISSET(c->fd, mgr->ss);
  6458. c->is_readable = bits & (eSELECT_READ | eSELECT_EXCEPT) ? 1U : 0;
  6459. c->is_writable = bits & eSELECT_WRITE ? 1U : 0;
  6460. if (c->fd != MG_INVALID_SOCKET)
  6461. FreeRTOS_FD_CLR(c->fd, mgr->ss,
  6462. eSELECT_READ | eSELECT_EXCEPT | eSELECT_WRITE);
  6463. }
  6464. #elif MG_ENABLE_EPOLL
  6465. size_t max = 1;
  6466. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6467. c->is_readable = c->is_writable = 0;
  6468. if (mg_tls_pending(c) > 0) ms = 1, c->is_readable = 1;
  6469. if (can_write(c)) MG_EPOLL_MOD(c, 1);
  6470. if (c->is_closing) ms = 1;
  6471. max++;
  6472. }
  6473. struct epoll_event *evs = (struct epoll_event *) alloca(max * sizeof(evs[0]));
  6474. int n = epoll_wait(mgr->epoll_fd, evs, (int) max, ms);
  6475. for (int i = 0; i < n; i++) {
  6476. struct mg_connection *c = (struct mg_connection *) evs[i].data.ptr;
  6477. if (evs[i].events & EPOLLERR) {
  6478. mg_error(c, "socket error");
  6479. } else if (c->is_readable == 0) {
  6480. bool rd = evs[i].events & (EPOLLIN | EPOLLHUP);
  6481. bool wr = evs[i].events & EPOLLOUT;
  6482. c->is_readable = can_read(c) && rd ? 1U : 0;
  6483. c->is_writable = can_write(c) && wr ? 1U : 0;
  6484. }
  6485. }
  6486. (void) skip_iotest;
  6487. #elif MG_ENABLE_POLL
  6488. nfds_t n = 0;
  6489. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) n++;
  6490. struct pollfd *fds = (struct pollfd *) alloca(n * sizeof(fds[0]));
  6491. memset(fds, 0, n * sizeof(fds[0]));
  6492. n = 0;
  6493. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6494. c->is_readable = c->is_writable = 0;
  6495. if (skip_iotest(c)) {
  6496. // Socket not valid, ignore
  6497. } else if (mg_tls_pending(c) > 0) {
  6498. ms = 1; // Don't wait if TLS is ready
  6499. } else {
  6500. fds[n].fd = FD(c);
  6501. if (can_read(c)) fds[n].events |= POLLIN;
  6502. if (can_write(c)) fds[n].events |= POLLOUT;
  6503. if (c->is_closing) ms = 1;
  6504. n++;
  6505. }
  6506. }
  6507. // MG_INFO(("poll n=%d ms=%d", (int) n, ms));
  6508. if (poll(fds, n, ms) < 0) {
  6509. #if MG_ARCH == MG_ARCH_WIN32
  6510. if (n == 0) Sleep(ms); // On Windows, poll fails if no sockets
  6511. #endif
  6512. memset(fds, 0, n * sizeof(fds[0]));
  6513. }
  6514. n = 0;
  6515. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6516. if (skip_iotest(c)) {
  6517. // Socket not valid, ignore
  6518. } else if (mg_tls_pending(c) > 0) {
  6519. c->is_readable = 1;
  6520. } else {
  6521. if (fds[n].revents & POLLERR) {
  6522. mg_error(c, "socket error");
  6523. } else {
  6524. c->is_readable =
  6525. (unsigned) (fds[n].revents & (POLLIN | POLLHUP) ? 1 : 0);
  6526. c->is_writable = (unsigned) (fds[n].revents & POLLOUT ? 1 : 0);
  6527. }
  6528. n++;
  6529. }
  6530. }
  6531. #else
  6532. struct timeval tv = {ms / 1000, (ms % 1000) * 1000}, tv_zero = {0, 0}, *tvp;
  6533. struct mg_connection *c;
  6534. fd_set rset, wset, eset;
  6535. MG_SOCKET_TYPE maxfd = 0;
  6536. int rc;
  6537. FD_ZERO(&rset);
  6538. FD_ZERO(&wset);
  6539. FD_ZERO(&eset);
  6540. tvp = ms < 0 ? NULL : &tv;
  6541. for (c = mgr->conns; c != NULL; c = c->next) {
  6542. c->is_readable = c->is_writable = 0;
  6543. if (skip_iotest(c)) continue;
  6544. FD_SET(FD(c), &eset);
  6545. if (can_read(c)) FD_SET(FD(c), &rset);
  6546. if (can_write(c)) FD_SET(FD(c), &wset);
  6547. if (mg_tls_pending(c) > 0) tvp = &tv_zero;
  6548. if (FD(c) > maxfd) maxfd = FD(c);
  6549. if (c->is_closing) ms = 1;
  6550. }
  6551. if ((rc = select((int) maxfd + 1, &rset, &wset, &eset, tvp)) < 0) {
  6552. #if MG_ARCH == MG_ARCH_WIN32
  6553. if (maxfd == 0) Sleep(ms); // On Windows, select fails if no sockets
  6554. #else
  6555. MG_ERROR(("select: %d %d", rc, MG_SOCK_ERR(rc)));
  6556. #endif
  6557. FD_ZERO(&rset);
  6558. FD_ZERO(&wset);
  6559. FD_ZERO(&eset);
  6560. }
  6561. for (c = mgr->conns; c != NULL; c = c->next) {
  6562. if (FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &eset)) {
  6563. mg_error(c, "socket error");
  6564. } else {
  6565. c->is_readable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &rset);
  6566. c->is_writable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &wset);
  6567. if (mg_tls_pending(c) > 0) c->is_readable = 1;
  6568. }
  6569. }
  6570. #endif
  6571. }
  6572. static bool mg_socketpair(MG_SOCKET_TYPE sp[2], union usa usa[2]) {
  6573. socklen_t n = sizeof(usa[0].sin);
  6574. bool success = false;
  6575. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6576. (void) memset(&usa[0], 0, sizeof(usa[0]));
  6577. usa[0].sin.sin_family = AF_INET;
  6578. *(uint32_t *) &usa->sin.sin_addr = mg_htonl(0x7f000001U); // 127.0.0.1
  6579. usa[1] = usa[0];
  6580. if ((sp[0] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  6581. (sp[1] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  6582. bind(sp[0], &usa[0].sa, n) == 0 && //
  6583. bind(sp[1], &usa[1].sa, n) == 0 && //
  6584. getsockname(sp[0], &usa[0].sa, &n) == 0 && //
  6585. getsockname(sp[1], &usa[1].sa, &n) == 0 && //
  6586. connect(sp[0], &usa[1].sa, n) == 0 && //
  6587. connect(sp[1], &usa[0].sa, n) == 0) { //
  6588. success = true;
  6589. }
  6590. if (!success) {
  6591. if (sp[0] != MG_INVALID_SOCKET) closesocket(sp[0]);
  6592. if (sp[1] != MG_INVALID_SOCKET) closesocket(sp[1]);
  6593. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6594. }
  6595. return success;
  6596. }
  6597. // mg_wakeup() event handler
  6598. static void wufn(struct mg_connection *c, int ev, void *ev_data) {
  6599. if (ev == MG_EV_READ) {
  6600. unsigned long *id = (unsigned long *) c->recv.buf;
  6601. // MG_INFO(("Got data"));
  6602. // mg_hexdump(c->recv.buf, c->recv.len);
  6603. if (c->recv.len >= sizeof(*id)) {
  6604. struct mg_connection *t;
  6605. for (t = c->mgr->conns; t != NULL; t = t->next) {
  6606. if (t->id == *id) {
  6607. struct mg_str data = mg_str_n((char *) c->recv.buf + sizeof(*id),
  6608. c->recv.len - sizeof(*id));
  6609. mg_call(t, MG_EV_WAKEUP, &data);
  6610. }
  6611. }
  6612. }
  6613. c->recv.len = 0; // Consume received data
  6614. } else if (ev == MG_EV_CLOSE) {
  6615. closesocket(c->mgr->pipe); // When we're closing, close the other
  6616. c->mgr->pipe = MG_INVALID_SOCKET; // side of the socketpair, too
  6617. }
  6618. (void) ev_data;
  6619. }
  6620. bool mg_wakeup_init(struct mg_mgr *mgr) {
  6621. bool ok = false;
  6622. if (mgr->pipe == MG_INVALID_SOCKET) {
  6623. union usa usa[2];
  6624. MG_SOCKET_TYPE sp[2] = {MG_INVALID_SOCKET, MG_INVALID_SOCKET};
  6625. struct mg_connection *c = NULL;
  6626. if (!mg_socketpair(sp, usa)) {
  6627. MG_ERROR(("Cannot create socket pair"));
  6628. } else if ((c = mg_wrapfd(mgr, (int) sp[1], wufn, NULL)) == NULL) {
  6629. closesocket(sp[0]);
  6630. closesocket(sp[1]);
  6631. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6632. } else {
  6633. tomgaddr(&usa[0], &c->rem, false);
  6634. MG_DEBUG(("%lu %p pipe %lu", c->id, c->fd, (unsigned long) sp[0]));
  6635. mgr->pipe = sp[0];
  6636. ok = true;
  6637. }
  6638. }
  6639. return ok;
  6640. }
  6641. bool mg_wakeup(struct mg_mgr *mgr, unsigned long conn_id, const void *buf,
  6642. size_t len) {
  6643. if (mgr->pipe != MG_INVALID_SOCKET && conn_id > 0) {
  6644. char *extended_buf = (char *) alloca(len + sizeof(conn_id));
  6645. memcpy(extended_buf, &conn_id, sizeof(conn_id));
  6646. memcpy(extended_buf + sizeof(conn_id), buf, len);
  6647. send(mgr->pipe, extended_buf, len + sizeof(conn_id), MSG_NONBLOCKING);
  6648. return true;
  6649. }
  6650. return false;
  6651. }
  6652. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  6653. struct mg_connection *c, *tmp;
  6654. uint64_t now;
  6655. mg_iotest(mgr, ms);
  6656. now = mg_millis();
  6657. mg_timer_poll(&mgr->timers, now);
  6658. for (c = mgr->conns; c != NULL; c = tmp) {
  6659. bool is_resp = c->is_resp;
  6660. tmp = c->next;
  6661. mg_call(c, MG_EV_POLL, &now);
  6662. if (is_resp && !c->is_resp) {
  6663. long n = 0;
  6664. mg_call(c, MG_EV_READ, &n);
  6665. }
  6666. MG_VERBOSE(("%lu %c%c %c%c%c%c%c", c->id, c->is_readable ? 'r' : '-',
  6667. c->is_writable ? 'w' : '-', c->is_tls ? 'T' : 't',
  6668. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  6669. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  6670. if (c->is_resolving || c->is_closing) {
  6671. // Do nothing
  6672. } else if (c->is_listening && c->is_udp == 0) {
  6673. if (c->is_readable) accept_conn(mgr, c);
  6674. } else if (c->is_connecting) {
  6675. if (c->is_readable || c->is_writable) connect_conn(c);
  6676. //} else if (c->is_tls_hs) {
  6677. // if ((c->is_readable || c->is_writable)) mg_tls_handshake(c);
  6678. } else {
  6679. if (c->is_readable) read_conn(c);
  6680. if (c->is_writable) write_conn(c);
  6681. }
  6682. if (c->is_draining && c->send.len == 0) c->is_closing = 1;
  6683. if (c->is_closing) close_conn(c);
  6684. }
  6685. }
  6686. #endif
  6687. #ifdef MG_ENABLE_LINES
  6688. #line 1 "src/ssi.c"
  6689. #endif
  6690. #ifndef MG_MAX_SSI_DEPTH
  6691. #define MG_MAX_SSI_DEPTH 5
  6692. #endif
  6693. #ifndef MG_SSI_BUFSIZ
  6694. #define MG_SSI_BUFSIZ 1024
  6695. #endif
  6696. #if MG_ENABLE_SSI
  6697. static char *mg_ssi(const char *path, const char *root, int depth) {
  6698. struct mg_iobuf b = {NULL, 0, 0, MG_IO_SIZE};
  6699. FILE *fp = fopen(path, "rb");
  6700. if (fp != NULL) {
  6701. char buf[MG_SSI_BUFSIZ], arg[sizeof(buf)];
  6702. int ch, intag = 0;
  6703. size_t len = 0;
  6704. buf[0] = arg[0] = '\0';
  6705. while ((ch = fgetc(fp)) != EOF) {
  6706. if (intag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  6707. buf[len++] = (char) (ch & 0xff);
  6708. buf[len] = '\0';
  6709. if (sscanf(buf, "<!--#include file=\"%[^\"]", arg)) {
  6710. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10],
  6711. *p = (char *) path + strlen(path), *data;
  6712. while (p > path && p[-1] != MG_DIRSEP && p[-1] != '/') p--;
  6713. mg_snprintf(tmp, sizeof(tmp), "%.*s%s", (int) (p - path), path, arg);
  6714. if (depth < MG_MAX_SSI_DEPTH &&
  6715. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  6716. mg_iobuf_add(&b, b.len, data, strlen(data));
  6717. free(data);
  6718. } else {
  6719. MG_ERROR(("%s: file=%s error or too deep", path, arg));
  6720. }
  6721. } else if (sscanf(buf, "<!--#include virtual=\"%[^\"]", arg)) {
  6722. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10], *data;
  6723. mg_snprintf(tmp, sizeof(tmp), "%s%s", root, arg);
  6724. if (depth < MG_MAX_SSI_DEPTH &&
  6725. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  6726. mg_iobuf_add(&b, b.len, data, strlen(data));
  6727. free(data);
  6728. } else {
  6729. MG_ERROR(("%s: virtual=%s error or too deep", path, arg));
  6730. }
  6731. } else {
  6732. // Unknown SSI tag
  6733. MG_ERROR(("Unknown SSI tag: %.*s", (int) len, buf));
  6734. mg_iobuf_add(&b, b.len, buf, len);
  6735. }
  6736. intag = 0;
  6737. len = 0;
  6738. } else if (ch == '<') {
  6739. intag = 1;
  6740. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  6741. len = 0;
  6742. buf[len++] = (char) (ch & 0xff);
  6743. } else if (intag) {
  6744. if (len == 5 && strncmp(buf, "<!--#", 5) != 0) {
  6745. intag = 0;
  6746. } else if (len >= sizeof(buf) - 2) {
  6747. MG_ERROR(("%s: SSI tag is too large", path));
  6748. len = 0;
  6749. }
  6750. buf[len++] = (char) (ch & 0xff);
  6751. } else {
  6752. buf[len++] = (char) (ch & 0xff);
  6753. if (len >= sizeof(buf)) {
  6754. mg_iobuf_add(&b, b.len, buf, len);
  6755. len = 0;
  6756. }
  6757. }
  6758. }
  6759. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  6760. if (b.len > 0) mg_iobuf_add(&b, b.len, "", 1); // nul-terminate
  6761. fclose(fp);
  6762. }
  6763. (void) depth;
  6764. (void) root;
  6765. return (char *) b.buf;
  6766. }
  6767. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  6768. const char *fullpath) {
  6769. const char *headers = "Content-Type: text/html; charset=utf-8\r\n";
  6770. char *data = mg_ssi(fullpath, root, 0);
  6771. mg_http_reply(c, 200, headers, "%s", data == NULL ? "" : data);
  6772. free(data);
  6773. }
  6774. #else
  6775. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  6776. const char *fullpath) {
  6777. mg_http_reply(c, 501, NULL, "SSI not enabled");
  6778. (void) root, (void) fullpath;
  6779. }
  6780. #endif
  6781. #ifdef MG_ENABLE_LINES
  6782. #line 1 "src/str.c"
  6783. #endif
  6784. struct mg_str mg_str_s(const char *s) {
  6785. struct mg_str str = {s, s == NULL ? 0 : strlen(s)};
  6786. return str;
  6787. }
  6788. struct mg_str mg_str_n(const char *s, size_t n) {
  6789. struct mg_str str = {s, n};
  6790. return str;
  6791. }
  6792. int mg_lower(const char *s) {
  6793. int c = *s;
  6794. if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
  6795. return c;
  6796. }
  6797. int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  6798. int diff = 0;
  6799. if (len > 0) do {
  6800. diff = mg_lower(s1++) - mg_lower(s2++);
  6801. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  6802. return diff;
  6803. }
  6804. int mg_casecmp(const char *s1, const char *s2) {
  6805. return mg_ncasecmp(s1, s2, (size_t) ~0);
  6806. }
  6807. int mg_vcmp(const struct mg_str *s1, const char *s2) {
  6808. size_t n2 = strlen(s2), n1 = s1->len;
  6809. int r = strncmp(s1->ptr, s2, (n1 < n2) ? n1 : n2);
  6810. if (r == 0) return (int) (n1 - n2);
  6811. return r;
  6812. }
  6813. int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
  6814. size_t n2 = strlen(str2), n1 = str1->len;
  6815. int r = mg_ncasecmp(str1->ptr, str2, (n1 < n2) ? n1 : n2);
  6816. if (r == 0) return (int) (n1 - n2);
  6817. return r;
  6818. }
  6819. struct mg_str mg_strdup(const struct mg_str s) {
  6820. struct mg_str r = {NULL, 0};
  6821. if (s.len > 0 && s.ptr != NULL) {
  6822. char *sc = (char *) calloc(1, s.len + 1);
  6823. if (sc != NULL) {
  6824. memcpy(sc, s.ptr, s.len);
  6825. sc[s.len] = '\0';
  6826. r.ptr = sc;
  6827. r.len = s.len;
  6828. }
  6829. }
  6830. return r;
  6831. }
  6832. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  6833. size_t i = 0;
  6834. while (i < str1.len && i < str2.len) {
  6835. int c1 = str1.ptr[i];
  6836. int c2 = str2.ptr[i];
  6837. if (c1 < c2) return -1;
  6838. if (c1 > c2) return 1;
  6839. i++;
  6840. }
  6841. if (i < str1.len) return 1;
  6842. if (i < str2.len) return -1;
  6843. return 0;
  6844. }
  6845. const char *mg_strstr(const struct mg_str haystack,
  6846. const struct mg_str needle) {
  6847. size_t i;
  6848. if (needle.len > haystack.len) return NULL;
  6849. if (needle.len == 0) return haystack.ptr;
  6850. for (i = 0; i <= haystack.len - needle.len; i++) {
  6851. if (memcmp(haystack.ptr + i, needle.ptr, needle.len) == 0) {
  6852. return haystack.ptr + i;
  6853. }
  6854. }
  6855. return NULL;
  6856. }
  6857. static bool is_space(int c) {
  6858. return c == ' ' || c == '\r' || c == '\n' || c == '\t';
  6859. }
  6860. struct mg_str mg_strstrip(struct mg_str s) {
  6861. while (s.len > 0 && is_space((int) *s.ptr)) s.ptr++, s.len--;
  6862. while (s.len > 0 && is_space((int) *(s.ptr + s.len - 1))) s.len--;
  6863. return s;
  6864. }
  6865. bool mg_match(struct mg_str s, struct mg_str p, struct mg_str *caps) {
  6866. size_t i = 0, j = 0, ni = 0, nj = 0;
  6867. if (caps) caps->ptr = NULL, caps->len = 0;
  6868. while (i < p.len || j < s.len) {
  6869. if (i < p.len && j < s.len && (p.ptr[i] == '?' || s.ptr[j] == p.ptr[i])) {
  6870. if (caps == NULL) {
  6871. } else if (p.ptr[i] == '?') {
  6872. caps->ptr = &s.ptr[j], caps->len = 1; // Finalize `?` cap
  6873. caps++, caps->ptr = NULL, caps->len = 0; // Init next cap
  6874. } else if (caps->ptr != NULL && caps->len == 0) {
  6875. caps->len = (size_t) (&s.ptr[j] - caps->ptr); // Finalize current cap
  6876. caps++, caps->len = 0, caps->ptr = NULL; // Init next cap
  6877. }
  6878. i++, j++;
  6879. } else if (i < p.len && (p.ptr[i] == '*' || p.ptr[i] == '#')) {
  6880. if (caps && !caps->ptr) caps->len = 0, caps->ptr = &s.ptr[j]; // Init cap
  6881. ni = i++, nj = j + 1;
  6882. } else if (nj > 0 && nj <= s.len && (p.ptr[ni] == '#' || s.ptr[j] != '/')) {
  6883. i = ni, j = nj;
  6884. if (caps && caps->ptr == NULL && caps->len == 0) {
  6885. caps--, caps->len = 0; // Restart previous cap
  6886. }
  6887. } else {
  6888. return false;
  6889. }
  6890. }
  6891. if (caps && caps->ptr && caps->len == 0) {
  6892. caps->len = (size_t) (&s.ptr[j] - caps->ptr);
  6893. }
  6894. return true;
  6895. }
  6896. bool mg_globmatch(const char *s1, size_t n1, const char *s2, size_t n2) {
  6897. return mg_match(mg_str_n(s2, n2), mg_str_n(s1, n1), NULL);
  6898. }
  6899. static size_t mg_nce(const char *s, size_t n, size_t ofs, size_t *koff,
  6900. size_t *klen, size_t *voff, size_t *vlen, char delim) {
  6901. size_t kvlen, kl;
  6902. for (kvlen = 0; ofs + kvlen < n && s[ofs + kvlen] != delim;) kvlen++;
  6903. for (kl = 0; kl < kvlen && s[ofs + kl] != '=';) kl++;
  6904. if (koff != NULL) *koff = ofs;
  6905. if (klen != NULL) *klen = kl;
  6906. if (voff != NULL) *voff = kl < kvlen ? ofs + kl + 1 : 0;
  6907. if (vlen != NULL) *vlen = kl < kvlen ? kvlen - kl - 1 : 0;
  6908. ofs += kvlen + 1;
  6909. return ofs > n ? n : ofs;
  6910. }
  6911. bool mg_split(struct mg_str *s, struct mg_str *k, struct mg_str *v, char sep) {
  6912. size_t koff = 0, klen = 0, voff = 0, vlen = 0, off = 0;
  6913. if (s->ptr == NULL || s->len == 0) return 0;
  6914. off = mg_nce(s->ptr, s->len, 0, &koff, &klen, &voff, &vlen, sep);
  6915. if (k != NULL) *k = mg_str_n(s->ptr + koff, klen);
  6916. if (v != NULL) *v = mg_str_n(s->ptr + voff, vlen);
  6917. *s = mg_str_n(s->ptr + off, s->len - off);
  6918. return off > 0;
  6919. }
  6920. bool mg_commalist(struct mg_str *s, struct mg_str *k, struct mg_str *v) {
  6921. return mg_split(s, k, v, ',');
  6922. }
  6923. char *mg_hex(const void *buf, size_t len, char *to) {
  6924. const unsigned char *p = (const unsigned char *) buf;
  6925. const char *hex = "0123456789abcdef";
  6926. size_t i = 0;
  6927. for (; len--; p++) {
  6928. to[i++] = hex[p[0] >> 4];
  6929. to[i++] = hex[p[0] & 0x0f];
  6930. }
  6931. to[i] = '\0';
  6932. return to;
  6933. }
  6934. static unsigned char mg_unhex_nimble(unsigned char c) {
  6935. return (c >= '0' && c <= '9') ? (unsigned char) (c - '0')
  6936. : (c >= 'A' && c <= 'F') ? (unsigned char) (c - '7')
  6937. : (unsigned char) (c - 'W');
  6938. }
  6939. unsigned long mg_unhexn(const char *s, size_t len) {
  6940. unsigned long i = 0, v = 0;
  6941. for (i = 0; i < len; i++) v <<= 4, v |= mg_unhex_nimble(((uint8_t *) s)[i]);
  6942. return v;
  6943. }
  6944. void mg_unhex(const char *buf, size_t len, unsigned char *to) {
  6945. size_t i;
  6946. for (i = 0; i < len; i += 2) {
  6947. to[i >> 1] = (unsigned char) mg_unhexn(&buf[i], 2);
  6948. }
  6949. }
  6950. bool mg_path_is_sane(const char *path) {
  6951. const char *s = path;
  6952. for (; s[0] != '\0'; s++) {
  6953. if (s == path || s[0] == '/' || s[0] == '\\') { // Subdir?
  6954. if (s[1] == '.' && s[2] == '.') return false; // Starts with ..
  6955. }
  6956. }
  6957. return true;
  6958. }
  6959. #ifdef MG_ENABLE_LINES
  6960. #line 1 "src/timer.c"
  6961. #endif
  6962. #define MG_TIMER_CALLED 4
  6963. void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
  6964. unsigned flags, void (*fn)(void *), void *arg) {
  6965. t->id = 0, t->period_ms = ms, t->expire = 0;
  6966. t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
  6967. *head = t;
  6968. }
  6969. void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
  6970. while (*head && *head != t) head = &(*head)->next;
  6971. if (*head) *head = t->next;
  6972. }
  6973. // t: expiration time, prd: period, now: current time. Return true if expired
  6974. bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
  6975. if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
  6976. if (*t == 0) *t = now + prd; // Firt poll? Set expiration
  6977. if (*t > now) return false; // Not expired yet, return
  6978. *t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
  6979. return true; // Expired, return true
  6980. }
  6981. void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
  6982. struct mg_timer *t, *tmp;
  6983. for (t = *head; t != NULL; t = tmp) {
  6984. bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
  6985. !(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
  6986. bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
  6987. tmp = t->next;
  6988. if (!once && !expired) continue;
  6989. if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
  6990. t->fn(t->arg);
  6991. }
  6992. t->flags |= MG_TIMER_CALLED;
  6993. }
  6994. }
  6995. #ifdef MG_ENABLE_LINES
  6996. #line 1 "src/tls_aes128.c"
  6997. #endif
  6998. /******************************************************************************
  6999. *
  7000. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7001. *
  7002. * This is a simple and straightforward implementation of the AES Rijndael
  7003. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7004. * of this work was correctness & accuracy. It is written in 'C' without any
  7005. * particular focus upon optimization or speed. It should be endian (memory
  7006. * byte order) neutral since the few places that care are handled explicitly.
  7007. *
  7008. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7009. *
  7010. * It is intended for general purpose use, but was written in support of GRC's
  7011. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7012. *
  7013. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7014. *
  7015. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7016. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7017. *
  7018. *******************************************************************************/
  7019. #if MG_TLS == MG_TLS_BUILTIN
  7020. static int aes_tables_inited = 0; // run-once flag for performing key
  7021. // expasion table generation (see below)
  7022. /*
  7023. * The following static local tables must be filled-in before the first use of
  7024. * the GCM or AES ciphers. They are used for the AES key expansion/scheduling
  7025. * and once built are read-only and thread safe. The "gcm_initialize" function
  7026. * must be called once during system initialization to populate these arrays
  7027. * for subsequent use by the AES key scheduler. If they have not been built
  7028. * before attempted use, an error will be returned to the caller.
  7029. *
  7030. * NOTE: GCM Encryption/Decryption does NOT REQUIRE AES decryption. Since
  7031. * GCM uses AES in counter-mode, where the AES cipher output is XORed with
  7032. * the GCM input, we ONLY NEED AES encryption. Thus, to save space AES
  7033. * decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.
  7034. */
  7035. // We always need our forward tables
  7036. static uchar FSb[256]; // Forward substitution box (FSb)
  7037. static uint32_t FT0[256]; // Forward key schedule assembly tables
  7038. static uint32_t FT1[256];
  7039. static uint32_t FT2[256];
  7040. static uint32_t FT3[256];
  7041. #if AES_DECRYPTION // We ONLY need reverse for decryption
  7042. static uchar RSb[256]; // Reverse substitution box (RSb)
  7043. static uint32_t RT0[256]; // Reverse key schedule assembly tables
  7044. static uint32_t RT1[256];
  7045. static uint32_t RT2[256];
  7046. static uint32_t RT3[256];
  7047. #endif /* AES_DECRYPTION */
  7048. static uint32_t RCON[10]; // AES round constants
  7049. /*
  7050. * Platform Endianness Neutralizing Load and Store Macro definitions
  7051. * AES wants platform-neutral Little Endian (LE) byte ordering
  7052. */
  7053. #define GET_UINT32_LE(n, b, i) \
  7054. { \
  7055. (n) = ((uint32_t) (b)[(i)]) | ((uint32_t) (b)[(i) + 1] << 8) | \
  7056. ((uint32_t) (b)[(i) + 2] << 16) | ((uint32_t) (b)[(i) + 3] << 24); \
  7057. }
  7058. #define PUT_UINT32_LE(n, b, i) \
  7059. { \
  7060. (b)[(i)] = (uchar) ((n)); \
  7061. (b)[(i) + 1] = (uchar) ((n) >> 8); \
  7062. (b)[(i) + 2] = (uchar) ((n) >> 16); \
  7063. (b)[(i) + 3] = (uchar) ((n) >> 24); \
  7064. }
  7065. /*
  7066. * AES forward and reverse encryption round processing macros
  7067. */
  7068. #define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7069. { \
  7070. X0 = *RK++ ^ FT0[(Y0) &0xFF] ^ FT1[(Y1 >> 8) & 0xFF] ^ \
  7071. FT2[(Y2 >> 16) & 0xFF] ^ FT3[(Y3 >> 24) & 0xFF]; \
  7072. \
  7073. X1 = *RK++ ^ FT0[(Y1) &0xFF] ^ FT1[(Y2 >> 8) & 0xFF] ^ \
  7074. FT2[(Y3 >> 16) & 0xFF] ^ FT3[(Y0 >> 24) & 0xFF]; \
  7075. \
  7076. X2 = *RK++ ^ FT0[(Y2) &0xFF] ^ FT1[(Y3 >> 8) & 0xFF] ^ \
  7077. FT2[(Y0 >> 16) & 0xFF] ^ FT3[(Y1 >> 24) & 0xFF]; \
  7078. \
  7079. X3 = *RK++ ^ FT0[(Y3) &0xFF] ^ FT1[(Y0 >> 8) & 0xFF] ^ \
  7080. FT2[(Y1 >> 16) & 0xFF] ^ FT3[(Y2 >> 24) & 0xFF]; \
  7081. }
  7082. #define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7083. { \
  7084. X0 = *RK++ ^ RT0[(Y0) &0xFF] ^ RT1[(Y3 >> 8) & 0xFF] ^ \
  7085. RT2[(Y2 >> 16) & 0xFF] ^ RT3[(Y1 >> 24) & 0xFF]; \
  7086. \
  7087. X1 = *RK++ ^ RT0[(Y1) &0xFF] ^ RT1[(Y0 >> 8) & 0xFF] ^ \
  7088. RT2[(Y3 >> 16) & 0xFF] ^ RT3[(Y2 >> 24) & 0xFF]; \
  7089. \
  7090. X2 = *RK++ ^ RT0[(Y2) &0xFF] ^ RT1[(Y1 >> 8) & 0xFF] ^ \
  7091. RT2[(Y0 >> 16) & 0xFF] ^ RT3[(Y3 >> 24) & 0xFF]; \
  7092. \
  7093. X3 = *RK++ ^ RT0[(Y3) &0xFF] ^ RT1[(Y2 >> 8) & 0xFF] ^ \
  7094. RT2[(Y1 >> 16) & 0xFF] ^ RT3[(Y0 >> 24) & 0xFF]; \
  7095. }
  7096. /*
  7097. * These macros improve the readability of the key
  7098. * generation initialization code by collapsing
  7099. * repetitive common operations into logical pieces.
  7100. */
  7101. #define ROTL8(x) ((x << 8) & 0xFFFFFFFF) | (x >> 24)
  7102. #define XTIME(x) ((x << 1) ^ ((x & 0x80) ? 0x1B : 0x00))
  7103. #define MUL(x, y) ((x && y) ? pow[(log[x] + log[y]) % 255] : 0)
  7104. #define MIX(x, y) \
  7105. { \
  7106. y = ((y << 1) | (y >> 7)) & 0xFF; \
  7107. x ^= y; \
  7108. }
  7109. #define CPY128 \
  7110. { \
  7111. *RK++ = *SK++; \
  7112. *RK++ = *SK++; \
  7113. *RK++ = *SK++; \
  7114. *RK++ = *SK++; \
  7115. }
  7116. /******************************************************************************
  7117. *
  7118. * AES_INIT_KEYGEN_TABLES
  7119. *
  7120. * Fills the AES key expansion tables allocated above with their static
  7121. * data. This is not "per key" data, but static system-wide read-only
  7122. * table data. THIS FUNCTION IS NOT THREAD SAFE. It must be called once
  7123. * at system initialization to setup the tables for all subsequent use.
  7124. *
  7125. ******************************************************************************/
  7126. void aes_init_keygen_tables(void) {
  7127. int i, x, y, z; // general purpose iteration and computation locals
  7128. int pow[256];
  7129. int log[256];
  7130. if (aes_tables_inited) return;
  7131. // fill the 'pow' and 'log' tables over GF(2^8)
  7132. for (i = 0, x = 1; i < 256; i++) {
  7133. pow[i] = x;
  7134. log[x] = i;
  7135. x = (x ^ XTIME(x)) & 0xFF;
  7136. }
  7137. // compute the round constants
  7138. for (i = 0, x = 1; i < 10; i++) {
  7139. RCON[i] = (uint32_t) x;
  7140. x = XTIME(x) & 0xFF;
  7141. }
  7142. // fill the forward and reverse substitution boxes
  7143. FSb[0x00] = 0x63;
  7144. #if AES_DECRYPTION // whether AES decryption is supported
  7145. RSb[0x63] = 0x00;
  7146. #endif /* AES_DECRYPTION */
  7147. for (i = 1; i < 256; i++) {
  7148. x = y = pow[255 - log[i]];
  7149. MIX(x, y);
  7150. MIX(x, y);
  7151. MIX(x, y);
  7152. MIX(x, y);
  7153. FSb[i] = (uchar) (x ^= 0x63);
  7154. #if AES_DECRYPTION // whether AES decryption is supported
  7155. RSb[x] = (uchar) i;
  7156. #endif /* AES_DECRYPTION */
  7157. }
  7158. // generate the forward and reverse key expansion tables
  7159. for (i = 0; i < 256; i++) {
  7160. x = FSb[i];
  7161. y = XTIME(x) & 0xFF;
  7162. z = (y ^ x) & 0xFF;
  7163. FT0[i] = ((uint32_t) y) ^ ((uint32_t) x << 8) ^ ((uint32_t) x << 16) ^
  7164. ((uint32_t) z << 24);
  7165. FT1[i] = ROTL8(FT0[i]);
  7166. FT2[i] = ROTL8(FT1[i]);
  7167. FT3[i] = ROTL8(FT2[i]);
  7168. #if AES_DECRYPTION // whether AES decryption is supported
  7169. x = RSb[i];
  7170. RT0[i] = ((uint32_t) MUL(0x0E, x)) ^ ((uint32_t) MUL(0x09, x) << 8) ^
  7171. ((uint32_t) MUL(0x0D, x) << 16) ^ ((uint32_t) MUL(0x0B, x) << 24);
  7172. RT1[i] = ROTL8(RT0[i]);
  7173. RT2[i] = ROTL8(RT1[i]);
  7174. RT3[i] = ROTL8(RT2[i]);
  7175. #endif /* AES_DECRYPTION */
  7176. }
  7177. aes_tables_inited = 1; // flag that the tables have been generated
  7178. } // to permit subsequent use of the AES cipher
  7179. /******************************************************************************
  7180. *
  7181. * AES_SET_ENCRYPTION_KEY
  7182. *
  7183. * This is called by 'aes_setkey' when we're establishing a key for
  7184. * subsequent encryption. We give it a pointer to the encryption
  7185. * context, a pointer to the key, and the key's length in bytes.
  7186. * Valid lengths are: 16, 24 or 32 bytes (128, 192, 256 bits).
  7187. *
  7188. ******************************************************************************/
  7189. static int aes_set_encryption_key(aes_context *ctx, const uchar *key, uint keysize) {
  7190. uint i; // general purpose iteration local
  7191. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7192. for (i = 0; i < (keysize >> 2); i++) {
  7193. GET_UINT32_LE(RK[i], key, i << 2);
  7194. }
  7195. switch (ctx->rounds) {
  7196. case 10:
  7197. for (i = 0; i < 10; i++, RK += 4) {
  7198. RK[4] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[3] >> 8) & 0xFF]) ^
  7199. ((uint32_t) FSb[(RK[3] >> 16) & 0xFF] << 8) ^
  7200. ((uint32_t) FSb[(RK[3] >> 24) & 0xFF] << 16) ^
  7201. ((uint32_t) FSb[(RK[3]) & 0xFF] << 24);
  7202. RK[5] = RK[1] ^ RK[4];
  7203. RK[6] = RK[2] ^ RK[5];
  7204. RK[7] = RK[3] ^ RK[6];
  7205. }
  7206. break;
  7207. case 12:
  7208. for (i = 0; i < 8; i++, RK += 6) {
  7209. RK[6] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[5] >> 8) & 0xFF]) ^
  7210. ((uint32_t) FSb[(RK[5] >> 16) & 0xFF] << 8) ^
  7211. ((uint32_t) FSb[(RK[5] >> 24) & 0xFF] << 16) ^
  7212. ((uint32_t) FSb[(RK[5]) & 0xFF] << 24);
  7213. RK[7] = RK[1] ^ RK[6];
  7214. RK[8] = RK[2] ^ RK[7];
  7215. RK[9] = RK[3] ^ RK[8];
  7216. RK[10] = RK[4] ^ RK[9];
  7217. RK[11] = RK[5] ^ RK[10];
  7218. }
  7219. break;
  7220. case 14:
  7221. for (i = 0; i < 7; i++, RK += 8) {
  7222. RK[8] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[7] >> 8) & 0xFF]) ^
  7223. ((uint32_t) FSb[(RK[7] >> 16) & 0xFF] << 8) ^
  7224. ((uint32_t) FSb[(RK[7] >> 24) & 0xFF] << 16) ^
  7225. ((uint32_t) FSb[(RK[7]) & 0xFF] << 24);
  7226. RK[9] = RK[1] ^ RK[8];
  7227. RK[10] = RK[2] ^ RK[9];
  7228. RK[11] = RK[3] ^ RK[10];
  7229. RK[12] = RK[4] ^ ((uint32_t) FSb[(RK[11]) & 0xFF]) ^
  7230. ((uint32_t) FSb[(RK[11] >> 8) & 0xFF] << 8) ^
  7231. ((uint32_t) FSb[(RK[11] >> 16) & 0xFF] << 16) ^
  7232. ((uint32_t) FSb[(RK[11] >> 24) & 0xFF] << 24);
  7233. RK[13] = RK[5] ^ RK[12];
  7234. RK[14] = RK[6] ^ RK[13];
  7235. RK[15] = RK[7] ^ RK[14];
  7236. }
  7237. break;
  7238. default:
  7239. return -1;
  7240. }
  7241. return (0);
  7242. }
  7243. #if AES_DECRYPTION // whether AES decryption is supported
  7244. /******************************************************************************
  7245. *
  7246. * AES_SET_DECRYPTION_KEY
  7247. *
  7248. * This is called by 'aes_setkey' when we're establishing a
  7249. * key for subsequent decryption. We give it a pointer to
  7250. * the encryption context, a pointer to the key, and the key's
  7251. * length in bits. Valid lengths are: 128, 192, or 256 bits.
  7252. *
  7253. ******************************************************************************/
  7254. static int aes_set_decryption_key(aes_context *ctx, const uchar *key, uint keysize) {
  7255. int i, j;
  7256. aes_context cty; // a calling aes context for set_encryption_key
  7257. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7258. uint32_t *SK;
  7259. int ret;
  7260. cty.rounds = ctx->rounds; // initialize our local aes context
  7261. cty.rk = cty.buf; // round count and key buf pointer
  7262. if ((ret = aes_set_encryption_key(&cty, key, keysize)) != 0) return (ret);
  7263. SK = cty.rk + cty.rounds * 4;
  7264. CPY128 // copy a 128-bit block from *SK to *RK
  7265. for (i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8) {
  7266. for (j = 0; j < 4; j++, SK++) {
  7267. *RK++ = RT0[FSb[(*SK) & 0xFF]] ^ RT1[FSb[(*SK >> 8) & 0xFF]] ^
  7268. RT2[FSb[(*SK >> 16) & 0xFF]] ^ RT3[FSb[(*SK >> 24) & 0xFF]];
  7269. }
  7270. }
  7271. CPY128 // copy a 128-bit block from *SK to *RK
  7272. memset(&cty, 0, sizeof(aes_context)); // clear local aes context
  7273. return (0);
  7274. }
  7275. #endif /* AES_DECRYPTION */
  7276. /******************************************************************************
  7277. *
  7278. * AES_SETKEY
  7279. *
  7280. * Invoked to establish the key schedule for subsequent encryption/decryption
  7281. *
  7282. ******************************************************************************/
  7283. int aes_setkey(aes_context *ctx, // AES context provided by our caller
  7284. int mode, // ENCRYPT or DECRYPT flag
  7285. const uchar *key, // pointer to the key
  7286. uint keysize) // key length in bytes
  7287. {
  7288. // since table initialization is not thread safe, we could either add
  7289. // system-specific mutexes and init the AES key generation tables on
  7290. // demand, or ask the developer to simply call "gcm_initialize" once during
  7291. // application startup before threading begins. That's what we choose.
  7292. if (!aes_tables_inited) return (-1); // fail the call when not inited.
  7293. ctx->mode = mode; // capture the key type we're creating
  7294. ctx->rk = ctx->buf; // initialize our round key pointer
  7295. switch (keysize) // set the rounds count based upon the keysize
  7296. {
  7297. case 16:
  7298. ctx->rounds = 10;
  7299. break; // 16-byte, 128-bit key
  7300. case 24:
  7301. ctx->rounds = 12;
  7302. break; // 24-byte, 192-bit key
  7303. case 32:
  7304. ctx->rounds = 14;
  7305. break; // 32-byte, 256-bit key
  7306. default:
  7307. return (-1);
  7308. }
  7309. #if AES_DECRYPTION
  7310. if (mode == DECRYPT) // expand our key for encryption or decryption
  7311. return (aes_set_decryption_key(ctx, key, keysize));
  7312. else /* ENCRYPT */
  7313. #endif /* AES_DECRYPTION */
  7314. return (aes_set_encryption_key(ctx, key, keysize));
  7315. }
  7316. /******************************************************************************
  7317. *
  7318. * AES_CIPHER
  7319. *
  7320. * Perform AES encryption and decryption.
  7321. * The AES context will have been setup with the encryption mode
  7322. * and all keying information appropriate for the task.
  7323. *
  7324. ******************************************************************************/
  7325. int aes_cipher(aes_context *ctx, const uchar input[16], uchar output[16]) {
  7326. int i;
  7327. uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; // general purpose locals
  7328. RK = ctx->rk;
  7329. GET_UINT32_LE(X0, input, 0);
  7330. X0 ^= *RK++; // load our 128-bit
  7331. GET_UINT32_LE(X1, input, 4);
  7332. X1 ^= *RK++; // input buffer in a storage
  7333. GET_UINT32_LE(X2, input, 8);
  7334. X2 ^= *RK++; // memory endian-neutral way
  7335. GET_UINT32_LE(X3, input, 12);
  7336. X3 ^= *RK++;
  7337. #if AES_DECRYPTION // whether AES decryption is supported
  7338. if (ctx->mode == DECRYPT) {
  7339. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  7340. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7341. AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  7342. }
  7343. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7344. X0 = *RK++ ^ ((uint32_t) RSb[(Y0) &0xFF]) ^
  7345. ((uint32_t) RSb[(Y3 >> 8) & 0xFF] << 8) ^
  7346. ((uint32_t) RSb[(Y2 >> 16) & 0xFF] << 16) ^
  7347. ((uint32_t) RSb[(Y1 >> 24) & 0xFF] << 24);
  7348. X1 = *RK++ ^ ((uint32_t) RSb[(Y1) &0xFF]) ^
  7349. ((uint32_t) RSb[(Y0 >> 8) & 0xFF] << 8) ^
  7350. ((uint32_t) RSb[(Y3 >> 16) & 0xFF] << 16) ^
  7351. ((uint32_t) RSb[(Y2 >> 24) & 0xFF] << 24);
  7352. X2 = *RK++ ^ ((uint32_t) RSb[(Y2) &0xFF]) ^
  7353. ((uint32_t) RSb[(Y1 >> 8) & 0xFF] << 8) ^
  7354. ((uint32_t) RSb[(Y0 >> 16) & 0xFF] << 16) ^
  7355. ((uint32_t) RSb[(Y3 >> 24) & 0xFF] << 24);
  7356. X3 = *RK++ ^ ((uint32_t) RSb[(Y3) &0xFF]) ^
  7357. ((uint32_t) RSb[(Y2 >> 8) & 0xFF] << 8) ^
  7358. ((uint32_t) RSb[(Y1 >> 16) & 0xFF] << 16) ^
  7359. ((uint32_t) RSb[(Y0 >> 24) & 0xFF] << 24);
  7360. } else /* ENCRYPT */
  7361. {
  7362. #endif /* AES_DECRYPTION */
  7363. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  7364. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7365. AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  7366. }
  7367. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7368. X0 = *RK++ ^ ((uint32_t) FSb[(Y0) &0xFF]) ^
  7369. ((uint32_t) FSb[(Y1 >> 8) & 0xFF] << 8) ^
  7370. ((uint32_t) FSb[(Y2 >> 16) & 0xFF] << 16) ^
  7371. ((uint32_t) FSb[(Y3 >> 24) & 0xFF] << 24);
  7372. X1 = *RK++ ^ ((uint32_t) FSb[(Y1) &0xFF]) ^
  7373. ((uint32_t) FSb[(Y2 >> 8) & 0xFF] << 8) ^
  7374. ((uint32_t) FSb[(Y3 >> 16) & 0xFF] << 16) ^
  7375. ((uint32_t) FSb[(Y0 >> 24) & 0xFF] << 24);
  7376. X2 = *RK++ ^ ((uint32_t) FSb[(Y2) &0xFF]) ^
  7377. ((uint32_t) FSb[(Y3 >> 8) & 0xFF] << 8) ^
  7378. ((uint32_t) FSb[(Y0 >> 16) & 0xFF] << 16) ^
  7379. ((uint32_t) FSb[(Y1 >> 24) & 0xFF] << 24);
  7380. X3 = *RK++ ^ ((uint32_t) FSb[(Y3) &0xFF]) ^
  7381. ((uint32_t) FSb[(Y0 >> 8) & 0xFF] << 8) ^
  7382. ((uint32_t) FSb[(Y1 >> 16) & 0xFF] << 16) ^
  7383. ((uint32_t) FSb[(Y2 >> 24) & 0xFF] << 24);
  7384. #if AES_DECRYPTION // whether AES decryption is supported
  7385. }
  7386. #endif /* AES_DECRYPTION */
  7387. PUT_UINT32_LE(X0, output, 0);
  7388. PUT_UINT32_LE(X1, output, 4);
  7389. PUT_UINT32_LE(X2, output, 8);
  7390. PUT_UINT32_LE(X3, output, 12);
  7391. return (0);
  7392. }
  7393. /* end of aes.c */
  7394. /******************************************************************************
  7395. *
  7396. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7397. *
  7398. * This is a simple and straightforward implementation of AES-GCM authenticated
  7399. * encryption. The focus of this work was correctness & accuracy. It is written
  7400. * in straight 'C' without any particular focus upon optimization or speed. It
  7401. * should be endian (memory byte order) neutral since the few places that care
  7402. * are handled explicitly.
  7403. *
  7404. * This implementation of AES-GCM was created by Steven M. Gibson of GRC.com.
  7405. *
  7406. * It is intended for general purpose use, but was written in support of GRC's
  7407. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7408. *
  7409. * See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  7410. * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/
  7411. * gcm/gcm-revised-spec.pdf
  7412. *
  7413. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7414. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7415. *
  7416. *******************************************************************************/
  7417. /******************************************************************************
  7418. * ==== IMPLEMENTATION WARNING ====
  7419. *
  7420. * This code was developed for use within SQRL's fixed environmnent. Thus, it
  7421. * is somewhat less "general purpose" than it would be if it were designed as
  7422. * a general purpose AES-GCM library. Specifically, it bothers with almost NO
  7423. * error checking on parameter limits, buffer bounds, etc. It assumes that it
  7424. * is being invoked by its author or by someone who understands the values it
  7425. * expects to receive. Its behavior will be undefined otherwise.
  7426. *
  7427. * All functions that might fail are defined to return 'ints' to indicate a
  7428. * problem. Most do not do so now. But this allows for error propagation out
  7429. * of internal functions if robust error checking should ever be desired.
  7430. *
  7431. ******************************************************************************/
  7432. /* Calculating the "GHASH"
  7433. *
  7434. * There are many ways of calculating the so-called GHASH in software, each with
  7435. * a traditional size vs performance tradeoff. The GHASH (Galois field hash) is
  7436. * an intriguing construction which takes two 128-bit strings (also the cipher's
  7437. * block size and the fundamental operation size for the system) and hashes them
  7438. * into a third 128-bit result.
  7439. *
  7440. * Many implementation solutions have been worked out that use large precomputed
  7441. * table lookups in place of more time consuming bit fiddling, and this approach
  7442. * can be scaled easily upward or downward as needed to change the time/space
  7443. * tradeoff. It's been studied extensively and there's a solid body of theory
  7444. * and practice. For example, without using any lookup tables an implementation
  7445. * might obtain 119 cycles per byte throughput, whereas using a simple, though
  7446. * large, key-specific 64 kbyte 8-bit lookup table the performance jumps to 13
  7447. * cycles per byte.
  7448. *
  7449. * And Intel's processors have, since 2010, included an instruction which does
  7450. * the entire 128x128->128 bit job in just several 64x64->128 bit pieces.
  7451. *
  7452. * Since SQRL is interactive, and only processing a few 128-bit blocks, I've
  7453. * settled upon a relatively slower but appealing small-table compromise which
  7454. * folds a bunch of not only time consuming but also bit twiddling into a simple
  7455. * 16-entry table which is attributed to Victor Shoup's 1996 work while at
  7456. * Bellcore: "On Fast and Provably Secure MessageAuthentication Based on
  7457. * Universal Hashing." See: http://www.shoup.net/papers/macs.pdf
  7458. * See, also section 4.1 of the "gcm-revised-spec" cited above.
  7459. */
  7460. /*
  7461. * This 16-entry table of pre-computed constants is used by the
  7462. * GHASH multiplier to improve over a strictly table-free but
  7463. * significantly slower 128x128 bit multiple within GF(2^128).
  7464. */
  7465. static const uint64_t last4[16] = {
  7466. 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
  7467. 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0};
  7468. /*
  7469. * Platform Endianness Neutralizing Load and Store Macro definitions
  7470. * GCM wants platform-neutral Big Endian (BE) byte ordering
  7471. */
  7472. #define GET_UINT32_BE(n, b, i) \
  7473. { \
  7474. (n) = ((uint32_t) (b)[(i)] << 24) | ((uint32_t) (b)[(i) + 1] << 16) | \
  7475. ((uint32_t) (b)[(i) + 2] << 8) | ((uint32_t) (b)[(i) + 3]); \
  7476. }
  7477. #define PUT_UINT32_BE(n, b, i) \
  7478. { \
  7479. (b)[(i)] = (uchar) ((n) >> 24); \
  7480. (b)[(i) + 1] = (uchar) ((n) >> 16); \
  7481. (b)[(i) + 2] = (uchar) ((n) >> 8); \
  7482. (b)[(i) + 3] = (uchar) ((n)); \
  7483. }
  7484. /******************************************************************************
  7485. *
  7486. * GCM_INITIALIZE
  7487. *
  7488. * Must be called once to initialize the GCM library.
  7489. *
  7490. * At present, this only calls the AES keygen table generator, which expands
  7491. * the AES keying tables for use. This is NOT A THREAD-SAFE function, so it
  7492. * MUST be called during system initialization before a multi-threading
  7493. * environment is running.
  7494. *
  7495. ******************************************************************************/
  7496. int gcm_initialize(void) {
  7497. aes_init_keygen_tables();
  7498. return (0);
  7499. }
  7500. /******************************************************************************
  7501. *
  7502. * GCM_MULT
  7503. *
  7504. * Performs a GHASH operation on the 128-bit input vector 'x', setting
  7505. * the 128-bit output vector to 'x' times H using our precomputed tables.
  7506. * 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  7507. *
  7508. ******************************************************************************/
  7509. static void gcm_mult(gcm_context *ctx, // pointer to established context
  7510. const uchar x[16], // pointer to 128-bit input vector
  7511. uchar output[16]) // pointer to 128-bit output vector
  7512. {
  7513. int i;
  7514. uchar lo, hi, rem;
  7515. uint64_t zh, zl;
  7516. lo = (uchar) (x[15] & 0x0f);
  7517. hi = (uchar) (x[15] >> 4);
  7518. zh = ctx->HH[lo];
  7519. zl = ctx->HL[lo];
  7520. for (i = 15; i >= 0; i--) {
  7521. lo = (uchar) (x[i] & 0x0f);
  7522. hi = (uchar) (x[i] >> 4);
  7523. if (i != 15) {
  7524. rem = (uchar) (zl & 0x0f);
  7525. zl = (zh << 60) | (zl >> 4);
  7526. zh = (zh >> 4);
  7527. zh ^= (uint64_t) last4[rem] << 48;
  7528. zh ^= ctx->HH[lo];
  7529. zl ^= ctx->HL[lo];
  7530. }
  7531. rem = (uchar) (zl & 0x0f);
  7532. zl = (zh << 60) | (zl >> 4);
  7533. zh = (zh >> 4);
  7534. zh ^= (uint64_t) last4[rem] << 48;
  7535. zh ^= ctx->HH[hi];
  7536. zl ^= ctx->HL[hi];
  7537. }
  7538. PUT_UINT32_BE(zh >> 32, output, 0);
  7539. PUT_UINT32_BE(zh, output, 4);
  7540. PUT_UINT32_BE(zl >> 32, output, 8);
  7541. PUT_UINT32_BE(zl, output, 12);
  7542. }
  7543. /******************************************************************************
  7544. *
  7545. * GCM_SETKEY
  7546. *
  7547. * This is called to set the AES-GCM key. It initializes the AES key
  7548. * and populates the gcm context's pre-calculated HTables.
  7549. *
  7550. ******************************************************************************/
  7551. int gcm_setkey(gcm_context *ctx, // pointer to caller-provided gcm context
  7552. const uchar *key, // pointer to the AES encryption key
  7553. const uint keysize) // size in bytes (must be 16, 24, 32 for
  7554. // 128, 192 or 256-bit keys respectively)
  7555. {
  7556. int ret, i, j;
  7557. uint64_t hi, lo;
  7558. uint64_t vl, vh;
  7559. unsigned char h[16];
  7560. memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
  7561. memset(h, 0, 16); // initialize the block to encrypt
  7562. // encrypt the null 128-bit block to generate a key-based value
  7563. // which is then used to initialize our GHASH lookup tables
  7564. if ((ret = aes_setkey(&ctx->aes_ctx, ENCRYPT, key, keysize)) != 0)
  7565. return (ret);
  7566. if ((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
  7567. GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
  7568. GET_UINT32_BE(lo, h, 4);
  7569. vh = (uint64_t) hi << 32 | lo;
  7570. GET_UINT32_BE(hi, h, 8);
  7571. GET_UINT32_BE(lo, h, 12);
  7572. vl = (uint64_t) hi << 32 | lo;
  7573. ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
  7574. ctx->HH[8] = vh;
  7575. ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
  7576. ctx->HL[0] = 0;
  7577. for (i = 4; i > 0; i >>= 1) {
  7578. uint32_t T = (uint32_t) (vl & 1) * 0xe1000000U;
  7579. vl = (vh << 63) | (vl >> 1);
  7580. vh = (vh >> 1) ^ ((uint64_t) T << 32);
  7581. ctx->HL[i] = vl;
  7582. ctx->HH[i] = vh;
  7583. }
  7584. for (i = 2; i < 16; i <<= 1) {
  7585. uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
  7586. vh = *HiH;
  7587. vl = *HiL;
  7588. for (j = 1; j < i; j++) {
  7589. HiH[j] = vh ^ ctx->HH[j];
  7590. HiL[j] = vl ^ ctx->HL[j];
  7591. }
  7592. }
  7593. return (0);
  7594. }
  7595. /******************************************************************************
  7596. *
  7597. * GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
  7598. *
  7599. * SETKEY:
  7600. *
  7601. * START: Sets the Encryption/Decryption mode.
  7602. * Accepts the initialization vector and additional data.
  7603. *
  7604. * UPDATE: Encrypts or decrypts the plaintext or ciphertext.
  7605. *
  7606. * FINISH: Performs a final GHASH to generate the authentication tag.
  7607. *
  7608. ******************************************************************************
  7609. *
  7610. * GCM_START
  7611. *
  7612. * Given a user-provided GCM context, this initializes it, sets the encryption
  7613. * mode, and preprocesses the initialization vector and additional AEAD data.
  7614. *
  7615. ******************************************************************************/
  7616. int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context
  7617. int mode, // GCM_ENCRYPT or GCM_DECRYPT
  7618. const uchar *iv, // pointer to initialization vector
  7619. size_t iv_len, // IV length in bytes (should == 12)
  7620. const uchar *add, // ptr to additional AEAD data (NULL if none)
  7621. size_t add_len) // length of additional AEAD data (bytes)
  7622. {
  7623. int ret; // our error return if the AES encrypt fails
  7624. uchar work_buf[16]; // XOR source built from provided IV if len != 16
  7625. const uchar *p; // general purpose array pointer
  7626. size_t use_len; // byte count to process, up to 16 bytes
  7627. size_t i; // local loop iterator
  7628. // since the context might be reused under the same key
  7629. // we zero the working buffers for this next new process
  7630. memset(ctx->y, 0x00, sizeof(ctx->y));
  7631. memset(ctx->buf, 0x00, sizeof(ctx->buf));
  7632. ctx->len = 0;
  7633. ctx->add_len = 0;
  7634. ctx->mode = mode; // set the GCM encryption/decryption mode
  7635. ctx->aes_ctx.mode = ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
  7636. if (iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
  7637. memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
  7638. ctx->y[15] = 1; // start "counting" from 1 (not 0)
  7639. } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
  7640. {
  7641. memset(work_buf, 0x00, 16); // clear the working buffer
  7642. PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
  7643. p = iv;
  7644. while (iv_len > 0) {
  7645. use_len = (iv_len < 16) ? iv_len : 16;
  7646. for (i = 0; i < use_len; i++) ctx->y[i] ^= p[i];
  7647. gcm_mult(ctx, ctx->y, ctx->y);
  7648. iv_len -= use_len;
  7649. p += use_len;
  7650. }
  7651. for (i = 0; i < 16; i++) ctx->y[i] ^= work_buf[i];
  7652. gcm_mult(ctx, ctx->y, ctx->y);
  7653. }
  7654. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0)
  7655. return (ret);
  7656. ctx->add_len = add_len;
  7657. p = add;
  7658. while (add_len > 0) {
  7659. use_len = (add_len < 16) ? add_len : 16;
  7660. for (i = 0; i < use_len; i++) ctx->buf[i] ^= p[i];
  7661. gcm_mult(ctx, ctx->buf, ctx->buf);
  7662. add_len -= use_len;
  7663. p += use_len;
  7664. }
  7665. return (0);
  7666. }
  7667. /******************************************************************************
  7668. *
  7669. * GCM_UPDATE
  7670. *
  7671. * This is called once or more to process bulk plaintext or ciphertext data.
  7672. * We give this some number of bytes of input and it returns the same number
  7673. * of output bytes. If called multiple times (which is fine) all but the final
  7674. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  7675. * have a partial block length of < 128 bits.)
  7676. *
  7677. ******************************************************************************/
  7678. int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  7679. size_t length, // length, in bytes, of data to process
  7680. const uchar *input, // pointer to source data
  7681. uchar *output) // pointer to destination data
  7682. {
  7683. int ret; // our error return if the AES encrypt fails
  7684. uchar ectr[16]; // counter-mode cipher output for XORing
  7685. size_t use_len; // byte count to process, up to 16 bytes
  7686. size_t i; // local loop iterator
  7687. ctx->len += length; // bump the GCM context's running length count
  7688. while (length > 0) {
  7689. // clamp the length to process at 16 bytes
  7690. use_len = (length < 16) ? length : 16;
  7691. // increment the context's 128-bit IV||Counter 'y' vector
  7692. for (i = 16; i > 12; i--)
  7693. if (++ctx->y[i - 1] != 0) break;
  7694. // encrypt the context's 'y' vector under the established key
  7695. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
  7696. // encrypt or decrypt the input to the output
  7697. if (ctx->mode == ENCRYPT) {
  7698. for (i = 0; i < use_len; i++) {
  7699. // XOR the cipher's ouptut vector (ectr) with our input
  7700. output[i] = (uchar) (ectr[i] ^ input[i]);
  7701. // now we mix in our data into the authentication hash.
  7702. // if we're ENcrypting we XOR in the post-XOR (output)
  7703. // results, but if we're DEcrypting we XOR in the input
  7704. // data
  7705. ctx->buf[i] ^= output[i];
  7706. }
  7707. } else {
  7708. for (i = 0; i < use_len; i++) {
  7709. // but if we're DEcrypting we XOR in the input data first,
  7710. // i.e. before saving to ouput data, otherwise if the input
  7711. // and output buffer are the same (inplace decryption) we
  7712. // would not get the correct auth tag
  7713. ctx->buf[i] ^= input[i];
  7714. // XOR the cipher's ouptut vector (ectr) with our input
  7715. output[i] = (uchar) (ectr[i] ^ input[i]);
  7716. }
  7717. }
  7718. gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
  7719. length -= use_len; // drop the remaining byte count to process
  7720. input += use_len; // bump our input pointer forward
  7721. output += use_len; // bump our output pointer forward
  7722. }
  7723. return (0);
  7724. }
  7725. /******************************************************************************
  7726. *
  7727. * GCM_FINISH
  7728. *
  7729. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  7730. * It performs the final GHASH to produce the resulting authentication TAG.
  7731. *
  7732. ******************************************************************************/
  7733. int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context
  7734. uchar *tag, // pointer to buffer which receives the tag
  7735. size_t tag_len) // length, in bytes, of the tag-receiving buf
  7736. {
  7737. uchar work_buf[16];
  7738. uint64_t orig_len = ctx->len * 8;
  7739. uint64_t orig_add_len = ctx->add_len * 8;
  7740. size_t i;
  7741. if (tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
  7742. if (orig_len || orig_add_len) {
  7743. memset(work_buf, 0x00, 16);
  7744. PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
  7745. PUT_UINT32_BE((orig_add_len), work_buf, 4);
  7746. PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
  7747. PUT_UINT32_BE((orig_len), work_buf, 12);
  7748. for (i = 0; i < 16; i++) ctx->buf[i] ^= work_buf[i];
  7749. gcm_mult(ctx, ctx->buf, ctx->buf);
  7750. for (i = 0; i < tag_len; i++) tag[i] ^= ctx->buf[i];
  7751. }
  7752. return (0);
  7753. }
  7754. /******************************************************************************
  7755. *
  7756. * GCM_CRYPT_AND_TAG
  7757. *
  7758. * This either encrypts or decrypts the user-provided data and, either
  7759. * way, generates an authentication tag of the requested length. It must be
  7760. * called with a GCM context whose key has already been set with GCM_SETKEY.
  7761. *
  7762. * The user would typically call this explicitly to ENCRYPT a buffer of data
  7763. * and optional associated data, and produce its an authentication tag.
  7764. *
  7765. * To reverse the process the user would typically call the companion
  7766. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  7767. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  7768. * to perform its decryption and tag generation, which it then compares.
  7769. *
  7770. ******************************************************************************/
  7771. int gcm_crypt_and_tag(
  7772. gcm_context *ctx, // gcm context with key already setup
  7773. int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
  7774. const uchar *iv, // pointer to the 12-byte initialization vector
  7775. size_t iv_len, // byte length if the IV. should always be 12
  7776. const uchar *add, // pointer to the non-ciphered additional data
  7777. size_t add_len, // byte length of the additional AEAD data
  7778. const uchar *input, // pointer to the cipher data source
  7779. uchar *output, // pointer to the cipher data destination
  7780. size_t length, // byte length of the cipher data
  7781. uchar *tag, // pointer to the tag to be generated
  7782. size_t tag_len) // byte length of the tag to be generated
  7783. { /*
  7784. assuming that the caller has already invoked gcm_setkey to
  7785. prepare the gcm context with the keying material, we simply
  7786. invoke each of the three GCM sub-functions in turn...
  7787. */
  7788. gcm_start(ctx, mode, iv, iv_len, add, add_len);
  7789. gcm_update(ctx, length, input, output);
  7790. gcm_finish(ctx, tag, tag_len);
  7791. return (0);
  7792. }
  7793. /******************************************************************************
  7794. *
  7795. * GCM_AUTH_DECRYPT
  7796. *
  7797. * This DECRYPTS a user-provided data buffer with optional associated data.
  7798. * It then verifies a user-supplied authentication tag against the tag just
  7799. * re-created during decryption to verify that the data has not been altered.
  7800. *
  7801. * This function calls GCM_CRYPT_AND_TAG (above) to perform the decryption
  7802. * and authentication tag generation.
  7803. *
  7804. ******************************************************************************/
  7805. int gcm_auth_decrypt(
  7806. gcm_context *ctx, // gcm context with key already setup
  7807. const uchar *iv, // pointer to the 12-byte initialization vector
  7808. size_t iv_len, // byte length if the IV. should always be 12
  7809. const uchar *add, // pointer to the non-ciphered additional data
  7810. size_t add_len, // byte length of the additional AEAD data
  7811. const uchar *input, // pointer to the cipher data source
  7812. uchar *output, // pointer to the cipher data destination
  7813. size_t length, // byte length of the cipher data
  7814. const uchar *tag, // pointer to the tag to be authenticated
  7815. size_t tag_len) // byte length of the tag <= 16
  7816. {
  7817. uchar check_tag[16]; // the tag generated and returned by decryption
  7818. int diff; // an ORed flag to detect authentication errors
  7819. size_t i; // our local iterator
  7820. /*
  7821. we use GCM_DECRYPT_AND_TAG (above) to perform our decryption
  7822. (which is an identical XORing to reverse the previous one)
  7823. and also to re-generate the matching authentication tag
  7824. */
  7825. gcm_crypt_and_tag(ctx, DECRYPT, iv, iv_len, add, add_len, input, output,
  7826. length, check_tag, tag_len);
  7827. // now we verify the authentication tag in 'constant time'
  7828. for (diff = 0, i = 0; i < tag_len; i++) diff |= tag[i] ^ check_tag[i];
  7829. if (diff != 0) { // see whether any bits differed?
  7830. memset(output, 0, length); // if so... wipe the output data
  7831. return (GCM_AUTH_FAILURE); // return GCM_AUTH_FAILURE
  7832. }
  7833. return (0);
  7834. }
  7835. /******************************************************************************
  7836. *
  7837. * GCM_ZERO_CTX
  7838. *
  7839. * The GCM context contains both the GCM context and the AES context.
  7840. * This includes keying and key-related material which is security-
  7841. * sensitive, so it MUST be zeroed after use. This function does that.
  7842. *
  7843. ******************************************************************************/
  7844. void gcm_zero_ctx(gcm_context *ctx) {
  7845. // zero the context originally provided to us
  7846. memset(ctx, 0, sizeof(gcm_context));
  7847. }
  7848. //
  7849. // aes-gcm.c
  7850. // Pods
  7851. //
  7852. // Created by Markus Kosmal on 20/11/14.
  7853. //
  7854. //
  7855. int aes_gcm_encrypt(unsigned char *output, //
  7856. const unsigned char *input, size_t input_length,
  7857. const unsigned char *key, const size_t key_len,
  7858. const unsigned char *iv, const size_t iv_len,
  7859. unsigned char *aead, size_t aead_len, unsigned char *tag,
  7860. const size_t tag_len) {
  7861. int ret = 0; // our return value
  7862. gcm_context ctx; // includes the AES context structure
  7863. gcm_setkey(&ctx, key, (const uint) key_len);
  7864. ret = gcm_crypt_and_tag(&ctx, ENCRYPT, iv, iv_len, aead, aead_len, input, output,
  7865. input_length, tag, tag_len);
  7866. gcm_zero_ctx(&ctx);
  7867. return (ret);
  7868. }
  7869. int aes_gcm_decrypt(unsigned char *output, const unsigned char *input,
  7870. size_t input_length, const unsigned char *key,
  7871. const size_t key_len, const unsigned char *iv,
  7872. const size_t iv_len) {
  7873. int ret = 0; // our return value
  7874. gcm_context ctx; // includes the AES context structure
  7875. size_t tag_len = 0;
  7876. unsigned char *tag_buf = NULL;
  7877. gcm_setkey(&ctx, key, (const uint) key_len);
  7878. ret = gcm_crypt_and_tag(&ctx, DECRYPT, iv, iv_len, NULL, 0, input, output,
  7879. input_length, tag_buf, tag_len);
  7880. gcm_zero_ctx(&ctx);
  7881. return (ret);
  7882. }
  7883. #endif
  7884. // End of aes128 PD
  7885. #ifdef MG_ENABLE_LINES
  7886. #line 1 "src/tls_builtin.c"
  7887. #endif
  7888. #if MG_TLS == MG_TLS_BUILTIN
  7889. // handshake is re-entrant, so we need to keep track of its state
  7890. enum mg_tls_hs_state {
  7891. MG_TLS_HS_CLIENT_HELLO, // first, wait for ClientHello
  7892. MG_TLS_HS_SERVER_HELLO, // then, send all server handshake data at once
  7893. MG_TLS_HS_CLIENT_CHANGE_CIPHER, // finally wait for ClientChangeCipher
  7894. MG_TLS_HS_CLIENT_FINISH, // and ClientFinish (encrypted)
  7895. MG_TLS_HS_DONE, // finish handshake, start application data flow
  7896. };
  7897. // per-connection TLS data
  7898. struct tls_data {
  7899. enum mg_tls_hs_state state; // keep track of connection handshake progress
  7900. struct mg_iobuf send; // For the receive path, we're reusing c->rtls
  7901. mg_sha256_ctx sha256; // incremental SHA-256 hash for TLS handshake
  7902. uint32_t sseq; // server sequence number, used in encryption
  7903. uint32_t cseq; // client sequence number, used in decryption
  7904. uint8_t session_id[32]; // client session ID between the handshake states
  7905. uint8_t x25519_cli[32]; // client X25519 key between the handshake states
  7906. uint8_t x25519_sec[32]; // x25519 secret between the handshake states
  7907. struct mg_str server_cert_der; // server certificate in DER format
  7908. uint8_t server_key[32]; // server EC private key
  7909. // keys for AES encryption
  7910. uint8_t handshake_secret[32];
  7911. uint8_t server_write_key[16];
  7912. uint8_t server_write_iv[12];
  7913. uint8_t server_finished_key[32];
  7914. uint8_t client_write_key[16];
  7915. uint8_t client_write_iv[12];
  7916. uint8_t client_finished_key[32];
  7917. };
  7918. #define MG_LOAD_BE16(p) ((uint16_t) ((MG_U8P(p)[0] << 8U) | MG_U8P(p)[1]))
  7919. #define TLS_HDR_SIZE 5 // 1 byte type, 2 bytes version, 2 bytes len
  7920. // for derived tls keys we need SHA256([0]*32)
  7921. static uint8_t zeros[32] = {0};
  7922. static uint8_t zeros_sha256_digest[32] =
  7923. "\xe3\xb0\xc4\x42\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99\x6f\xb9\x24"
  7924. "\x27\xae\x41\xe4\x64\x9b\x93\x4c\xa4\x95\x99\x1b\x78\x52\xb8\x55";
  7925. #define X25519_BYTES 32
  7926. const uint8_t X25519_BASE_POINT[X25519_BYTES] = {9};
  7927. #define X25519_WBITS 32
  7928. typedef uint32_t limb_t;
  7929. typedef uint64_t dlimb_t;
  7930. typedef int64_t sdlimb_t;
  7931. #define LIMB(x) (uint32_t)(x##ull), (uint32_t) ((x##ull) >> 32)
  7932. #define NLIMBS (256 / X25519_WBITS)
  7933. typedef limb_t fe[NLIMBS];
  7934. static limb_t umaal(limb_t *carry, limb_t acc, limb_t mand, limb_t mier) {
  7935. dlimb_t tmp = (dlimb_t) mand * mier + acc + *carry;
  7936. *carry = (limb_t) (tmp >> X25519_WBITS);
  7937. return (limb_t) tmp;
  7938. }
  7939. // These functions are implemented in terms of umaal on ARM
  7940. static limb_t adc(limb_t *carry, limb_t acc, limb_t mand) {
  7941. dlimb_t total = (dlimb_t) *carry + acc + mand;
  7942. *carry = (limb_t) (total >> X25519_WBITS);
  7943. return (limb_t) total;
  7944. }
  7945. static limb_t adc0(limb_t *carry, limb_t acc) {
  7946. dlimb_t total = (dlimb_t) *carry + acc;
  7947. *carry = (limb_t) (total >> X25519_WBITS);
  7948. return (limb_t) total;
  7949. }
  7950. // - Precondition: carry is small.
  7951. // - Invariant: result of propagate is < 2^255 + 1 word
  7952. // - In particular, always less than 2p.
  7953. // - Also, output x >= min(x,19)
  7954. static void propagate(fe x, limb_t over) {
  7955. unsigned i;
  7956. limb_t carry;
  7957. over = x[NLIMBS - 1] >> (X25519_WBITS - 1) | over << 1;
  7958. x[NLIMBS - 1] &= ~((limb_t) 1 << (X25519_WBITS - 1));
  7959. carry = over * 19;
  7960. for (i = 0; i < NLIMBS; i++) {
  7961. x[i] = adc0(&carry, x[i]);
  7962. }
  7963. }
  7964. static void add(fe out, const fe a, const fe b) {
  7965. unsigned i;
  7966. limb_t carry = 0;
  7967. for (i = 0; i < NLIMBS; i++) {
  7968. out[i] = adc(&carry, a[i], b[i]);
  7969. }
  7970. propagate(out, carry);
  7971. }
  7972. static void sub(fe out, const fe a, const fe b) {
  7973. unsigned i;
  7974. sdlimb_t carry = -38;
  7975. for (i = 0; i < NLIMBS; i++) {
  7976. carry = carry + a[i] - b[i];
  7977. out[i] = (limb_t) carry;
  7978. carry >>= X25519_WBITS;
  7979. }
  7980. propagate(out, (limb_t) (1 + carry));
  7981. }
  7982. static void mul(fe out, const fe a, const fe b, unsigned nb) {
  7983. limb_t accum[2 * NLIMBS] = {0};
  7984. unsigned i, j;
  7985. limb_t carry2;
  7986. for (i = 0; i < nb; i++) {
  7987. limb_t mand = b[i];
  7988. carry2 = 0;
  7989. for (j = 0; j < NLIMBS; j++) {
  7990. accum[i + j] = umaal(&carry2, accum[i + j], mand, a[j]);
  7991. }
  7992. accum[i + j] = carry2;
  7993. }
  7994. carry2 = 0;
  7995. for (j = 0; j < NLIMBS; j++) {
  7996. out[j] = umaal(&carry2, accum[j], 38, accum[j + NLIMBS]);
  7997. }
  7998. propagate(out, carry2);
  7999. }
  8000. static void sqr(fe out, const fe a) {
  8001. mul(out, a, a, NLIMBS);
  8002. }
  8003. static void mul1(fe out, const fe a) {
  8004. mul(out, a, out, NLIMBS);
  8005. }
  8006. static void sqr1(fe a) {
  8007. mul1(a, a);
  8008. }
  8009. static void condswap(limb_t a[2 * NLIMBS], limb_t b[2 * NLIMBS],
  8010. limb_t doswap) {
  8011. unsigned i;
  8012. for (i = 0; i < 2 * NLIMBS; i++) {
  8013. limb_t xor = (a[i] ^ b[i]) & doswap;
  8014. a[i] ^= xor;
  8015. b[i] ^= xor;
  8016. }
  8017. }
  8018. // Canonicalize a field element x, reducing it to the least residue which is
  8019. // congruent to it mod 2^255-19
  8020. // - Precondition: x < 2^255 + 1 word
  8021. static limb_t canon(fe x) {
  8022. // First, add 19.
  8023. unsigned i;
  8024. limb_t carry0 = 19;
  8025. limb_t res;
  8026. sdlimb_t carry;
  8027. for (i = 0; i < NLIMBS; i++) {
  8028. x[i] = adc0(&carry0, x[i]);
  8029. }
  8030. propagate(x, carry0);
  8031. // Here, 19 <= x2 < 2^255
  8032. // - This is because we added 19, so before propagate it can't be less
  8033. // than 19. After propagate, it still can't be less than 19, because if
  8034. // propagate does anything it adds 19.
  8035. // - We know that the high bit must be clear, because either the input was ~
  8036. // 2^255 + one word + 19 (in which case it propagates to at most 2 words) or
  8037. // it was < 2^255. So now, if we subtract 19, we will get back to something in
  8038. // [0,2^255-19).
  8039. carry = -19;
  8040. res = 0;
  8041. for (i = 0; i < NLIMBS; i++) {
  8042. carry += x[i];
  8043. res |= x[i] = (limb_t) carry;
  8044. carry >>= X25519_WBITS;
  8045. }
  8046. return (limb_t) (((dlimb_t) res - 1) >> X25519_WBITS);
  8047. }
  8048. static const limb_t a24[1] = {121665};
  8049. static void ladder_part1(fe xs[5]) {
  8050. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  8051. add(t1, x2, z2); // t1 = A
  8052. sub(z2, x2, z2); // z2 = B
  8053. add(x2, x3, z3); // x2 = C
  8054. sub(z3, x3, z3); // z3 = D
  8055. mul1(z3, t1); // z3 = DA
  8056. mul1(x2, z2); // x3 = BC
  8057. add(x3, z3, x2); // x3 = DA+CB
  8058. sub(z3, z3, x2); // z3 = DA-CB
  8059. sqr1(t1); // t1 = AA
  8060. sqr1(z2); // z2 = BB
  8061. sub(x2, t1, z2); // x2 = E = AA-BB
  8062. mul(z2, x2, a24, sizeof(a24) / sizeof(a24[0])); // z2 = E*a24
  8063. add(z2, z2, t1); // z2 = E*a24 + AA
  8064. }
  8065. static void ladder_part2(fe xs[5], const fe x1) {
  8066. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  8067. sqr1(z3); // z3 = (DA-CB)^2
  8068. mul1(z3, x1); // z3 = x1 * (DA-CB)^2
  8069. sqr1(x3); // x3 = (DA+CB)^2
  8070. mul1(z2, x2); // z2 = AA*(E*a24+AA)
  8071. sub(x2, t1, x2); // x2 = BB again
  8072. mul1(x2, t1); // x2 = AA*BB
  8073. }
  8074. static void x25519_core(fe xs[5], const uint8_t scalar[X25519_BYTES],
  8075. const uint8_t *x1, int clamp) {
  8076. int i;
  8077. limb_t swap = 0;
  8078. limb_t *x2 = xs[0], *x3 = xs[2], *z3 = xs[3];
  8079. memset(xs, 0, 4 * sizeof(fe));
  8080. x2[0] = z3[0] = 1;
  8081. memcpy(x3, x1, sizeof(fe));
  8082. for (i = 255; i >= 0; i--) {
  8083. uint8_t bytei = scalar[i / 8];
  8084. limb_t doswap;
  8085. if (clamp) {
  8086. if (i / 8 == 0) {
  8087. bytei &= (uint8_t) ~7U;
  8088. } else if (i / 8 == X25519_BYTES - 1) {
  8089. bytei &= 0x7F;
  8090. bytei |= 0x40;
  8091. }
  8092. }
  8093. doswap = 0 - (limb_t) ((bytei >> (i % 8)) & 1);
  8094. condswap(x2, x3, swap ^ doswap);
  8095. swap = doswap;
  8096. ladder_part1(xs);
  8097. ladder_part2(xs, (const limb_t *) x1);
  8098. }
  8099. condswap(x2, x3, swap);
  8100. }
  8101. static int x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES],
  8102. const uint8_t x1[X25519_BYTES], int clamp) {
  8103. int i, ret;
  8104. fe xs[5];
  8105. limb_t *x2, *z2, *z3, *prev;
  8106. static const struct {
  8107. uint8_t a, c, n;
  8108. } steps[13] = {{2, 1, 1}, {2, 1, 1}, {4, 2, 3}, {2, 4, 6}, {3, 1, 1},
  8109. {3, 2, 12}, {4, 3, 25}, {2, 3, 25}, {2, 4, 50}, {3, 2, 125},
  8110. {3, 1, 2}, {3, 1, 2}, {3, 1, 1}};
  8111. x25519_core(xs, scalar, x1, clamp);
  8112. // Precomputed inversion chain
  8113. x2 = xs[0];
  8114. z2 = xs[1];
  8115. z3 = xs[3];
  8116. prev = z2;
  8117. for (i = 0; i < 13; i++) {
  8118. int j;
  8119. limb_t *a = xs[steps[i].a];
  8120. for (j = steps[i].n; j > 0; j--) {
  8121. sqr(a, prev);
  8122. prev = a;
  8123. }
  8124. mul1(a, xs[steps[i].c]);
  8125. }
  8126. // Here prev = z3
  8127. // x2 /= z2
  8128. mul((limb_t *) out, x2, z3, NLIMBS);
  8129. ret = (int) canon((limb_t *) out);
  8130. if (!clamp) ret = 0;
  8131. return ret;
  8132. }
  8133. // helper to hexdump buffers inline
  8134. static void mg_tls_hexdump(const char *msg, uint8_t *buf, size_t bufsz) {
  8135. char p[2048];
  8136. MG_INFO(("%s: %s", msg, mg_hex(buf, bufsz, p)));
  8137. }
  8138. // TLS1.3 secret derivation based on the key label
  8139. static void mg_tls_derive_secret(const char *label, uint8_t *key, size_t keysz,
  8140. uint8_t *data, size_t datasz, uint8_t *hash,
  8141. size_t hashsz) {
  8142. size_t labelsz = strlen(label);
  8143. uint8_t secret[32];
  8144. uint8_t packed[256] = {0, (uint8_t) hashsz, (uint8_t) labelsz};
  8145. // TODO: assert lengths of label, key, data and hash
  8146. memmove(packed + 3, label, labelsz);
  8147. packed[3 + labelsz] = (uint8_t) datasz;
  8148. memmove(packed + labelsz + 4, data, datasz);
  8149. packed[4 + labelsz + datasz] = 1;
  8150. mg_hmac_sha256(secret, key, keysz, packed, 5 + labelsz + datasz);
  8151. memmove(hash, secret, hashsz);
  8152. }
  8153. // Did we receive a full TLS message in the c->rtls buffer?
  8154. static bool mg_tls_got_msg(struct mg_connection *c) {
  8155. return c->rtls.len >= TLS_HDR_SIZE &&
  8156. c->rtls.len >= (TLS_HDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
  8157. }
  8158. // Remove a single TLS record from the recv buffer
  8159. static void mg_tls_drop_packet(struct mg_iobuf *rio) {
  8160. uint16_t n = MG_LOAD_BE16(rio->buf + 3) + TLS_HDR_SIZE;
  8161. mg_iobuf_del(rio, 0, n);
  8162. }
  8163. // read and parse ClientHello record
  8164. static int mg_tls_client_hello(struct mg_connection *c) {
  8165. struct tls_data *tls = c->tls;
  8166. struct mg_iobuf *rio = &c->rtls;
  8167. uint8_t session_id_len;
  8168. uint16_t j;
  8169. uint16_t cipher_suites_len;
  8170. uint16_t ext_len;
  8171. uint8_t *ext;
  8172. if (!mg_tls_got_msg(c)) {
  8173. return MG_IO_WAIT;
  8174. }
  8175. if (rio->buf[0] != 0x16 || rio->buf[5] != 0x01) {
  8176. mg_error(c, "not a hello packet");
  8177. return -1;
  8178. }
  8179. mg_sha256_update(&tls->sha256, rio->buf + 5, rio->len - 5);
  8180. session_id_len = rio->buf[43];
  8181. if (session_id_len == sizeof(tls->session_id)) {
  8182. memmove(tls->session_id, rio->buf + 44, session_id_len);
  8183. } else if (session_id_len != 0) {
  8184. MG_INFO(("bad session id len"));
  8185. }
  8186. cipher_suites_len = MG_LOAD_BE16(rio->buf + 44 + session_id_len);
  8187. ext_len = MG_LOAD_BE16(rio->buf + 48 + session_id_len + cipher_suites_len);
  8188. ext = rio->buf + 50 + session_id_len + cipher_suites_len;
  8189. for (j = 0; j < ext_len;) {
  8190. uint16_t k;
  8191. uint16_t key_exchange_len;
  8192. uint8_t *key_exchange;
  8193. uint16_t n = MG_LOAD_BE16(ext + j + 2);
  8194. if (ext[j] != 0x00 ||
  8195. ext[j + 1] != 0x33) { // not a key share extension, ignore
  8196. j += (uint16_t) (n + 4);
  8197. continue;
  8198. }
  8199. key_exchange_len = MG_LOAD_BE16(ext + j + 5);
  8200. key_exchange = ext + j + 6;
  8201. for (k = 0; k < key_exchange_len;) {
  8202. uint16_t m = MG_LOAD_BE16(key_exchange + k + 2);
  8203. if (m == 32 && key_exchange[k] == 0x00 && key_exchange[k + 1] == 0x1d) {
  8204. memmove(tls->x25519_cli, key_exchange + k + 4, m);
  8205. mg_tls_drop_packet(rio);
  8206. return 0;
  8207. }
  8208. k += (uint16_t) (m + 4);
  8209. }
  8210. j += (uint16_t) (n + 4);
  8211. }
  8212. mg_error(c, "bad client hello");
  8213. return -1;
  8214. }
  8215. // put ServerHello record into wio buffer
  8216. static void mg_tls_server_hello(struct mg_connection *c) {
  8217. struct tls_data *tls = c->tls;
  8218. struct mg_iobuf *wio = &tls->send;
  8219. uint8_t msg_server_hello[122] =
  8220. // server hello, tls 1.2
  8221. "\x02\x00\x00\x76\x03\x03"
  8222. // random (32 bytes)
  8223. "\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe"
  8224. "\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe"
  8225. // session ID length + session ID (32 bytes)
  8226. "\x20"
  8227. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
  8228. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
  8229. #if defined(CHACHA20) && CHACHA20
  8230. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  8231. "\x13\x03\x00"
  8232. #else
  8233. // TLS_AES_128_GCM_SHA256 + no compression
  8234. "\x13\x01\x00"
  8235. #endif
  8236. // extensions + keyshare
  8237. "\x00\x2e\x00\x33\x00\x24\x00\x1d\x00\x20"
  8238. // x25519 keyshare
  8239. "\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab"
  8240. "\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab"
  8241. // supported versions (tls1.3 == 0x304)
  8242. "\x00\x2b\x00\x02\x03\x04";
  8243. // calculate keyshare
  8244. uint8_t x25519_pub[X25519_BYTES];
  8245. uint8_t x25519_prv[X25519_BYTES];
  8246. mg_random(x25519_prv, sizeof(x25519_prv));
  8247. x25519(x25519_pub, x25519_prv, X25519_BASE_POINT, 1);
  8248. x25519(tls->x25519_sec, x25519_prv, tls->x25519_cli, 1);
  8249. mg_tls_hexdump("x25519 sec", tls->x25519_sec, sizeof(tls->x25519_sec));
  8250. // fill in the gaps: session ID + keyshare
  8251. memmove(msg_server_hello + 39, tls->session_id, sizeof(tls->session_id));
  8252. memmove(msg_server_hello + 84, x25519_pub, sizeof(x25519_pub));
  8253. // server hello message
  8254. mg_iobuf_add(wio, wio->len, "\x16\x03\x03\x00\x7a", 5);
  8255. mg_iobuf_add(wio, wio->len, msg_server_hello, sizeof(msg_server_hello));
  8256. mg_sha256_update(&tls->sha256, msg_server_hello, sizeof(msg_server_hello));
  8257. // change cipher message
  8258. mg_iobuf_add(wio, wio->len, "\x14\x03\x03\x00\x01\x01", 6);
  8259. }
  8260. // at this point we have x25519 shared secret, we can generate a set of derived
  8261. // handshake encryption keys
  8262. static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
  8263. struct tls_data *tls = c->tls;
  8264. mg_sha256_ctx sha256;
  8265. uint8_t early_secret[32];
  8266. uint8_t pre_extract_secret[32];
  8267. uint8_t hello_hash[32];
  8268. uint8_t server_hs_secret[32];
  8269. uint8_t client_hs_secret[32];
  8270. mg_hmac_sha256(early_secret, NULL, 0, zeros, sizeof(zeros));
  8271. mg_tls_derive_secret("tls13 derived", early_secret, 32, zeros_sha256_digest,
  8272. 32, pre_extract_secret, 32);
  8273. mg_hmac_sha256(tls->handshake_secret, pre_extract_secret,
  8274. sizeof(pre_extract_secret), tls->x25519_sec,
  8275. sizeof(tls->x25519_sec));
  8276. mg_tls_hexdump("hs secret", tls->handshake_secret, 32);
  8277. // mg_sha256_final is not idempotent, need to copy sha256 context to calculate
  8278. // the digest
  8279. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8280. mg_sha256_final(hello_hash, &sha256);
  8281. // derive keys needed for the rest of the handshake
  8282. mg_tls_derive_secret("tls13 s hs traffic", tls->handshake_secret, 32,
  8283. hello_hash, 32, server_hs_secret, 32);
  8284. mg_tls_derive_secret("tls13 key", server_hs_secret, 32, NULL, 0,
  8285. tls->server_write_key, 16);
  8286. mg_tls_derive_secret("tls13 iv", server_hs_secret, 32, NULL, 0,
  8287. tls->server_write_iv, 12);
  8288. mg_tls_derive_secret("tls13 finished", server_hs_secret, 32, NULL, 0,
  8289. tls->server_finished_key, 32);
  8290. mg_tls_hexdump("s hs traffic", server_hs_secret, 32);
  8291. mg_tls_derive_secret("tls13 c hs traffic", tls->handshake_secret, 32,
  8292. hello_hash, 32, client_hs_secret, 32);
  8293. mg_tls_derive_secret("tls13 key", client_hs_secret, 32, NULL, 0,
  8294. tls->client_write_key, 16);
  8295. mg_tls_derive_secret("tls13 iv", client_hs_secret, 32, NULL, 0,
  8296. tls->client_write_iv, 12);
  8297. mg_tls_derive_secret("tls13 finished", client_hs_secret, 32, NULL, 0,
  8298. tls->client_finished_key, 32);
  8299. }
  8300. // AES GCM encryption of the message + put encoded data into the write buffer
  8301. static void mg_tls_encrypt(struct mg_connection *c, const uint8_t *msg,
  8302. size_t msgsz, uint8_t msgtype) {
  8303. struct tls_data *tls = c->tls;
  8304. struct mg_iobuf *wio = &tls->send;
  8305. uint8_t *outmsg;
  8306. uint8_t *tag;
  8307. size_t encsz = msgsz + 16 + 1;
  8308. uint8_t hdr[5] = {0x17, 0x03, 0x03, (encsz >> 8) & 0xff, encsz & 0xff};
  8309. uint8_t associated_data[5] = {0x17, 0x03, 0x03, (encsz >> 8) & 0xff,
  8310. encsz & 0xff};
  8311. uint8_t nonce[12];
  8312. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8313. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8314. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8315. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8316. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8317. gcm_initialize();
  8318. mg_iobuf_add(wio, wio->len, hdr, sizeof(hdr));
  8319. mg_iobuf_resize(wio, wio->len + encsz);
  8320. outmsg = wio->buf + wio->len;
  8321. tag = wio->buf + wio->len + msgsz + 1;
  8322. memmove(outmsg, msg, msgsz);
  8323. outmsg[msgsz] = msgtype;
  8324. aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->server_write_key,
  8325. sizeof(tls->server_write_key), nonce, sizeof(nonce),
  8326. associated_data, sizeof(associated_data), tag, 16);
  8327. wio->len += encsz;
  8328. tls->sseq++;
  8329. }
  8330. // read an encrypted message, decrypt it into read buffer (AES GCM)
  8331. static int mg_tls_recv_decrypt(struct mg_connection *c, void *buf,
  8332. size_t bufsz) {
  8333. struct tls_data *tls = c->tls;
  8334. struct mg_iobuf *rio = &c->rtls;
  8335. // struct mg_iobuf *rio = &tls->recv;
  8336. uint16_t msgsz;
  8337. uint8_t *msg;
  8338. uint8_t nonce[12];
  8339. int r;
  8340. for (;;) {
  8341. if (!mg_tls_got_msg(c)) {
  8342. return MG_IO_WAIT;
  8343. }
  8344. if (rio->buf[0] == 0x17) {
  8345. break;
  8346. } else if (rio->buf[0] == 0x15) {
  8347. MG_INFO(("TLS ALERT packet received")); // TODO: drop packet?
  8348. } else {
  8349. mg_error(c, "unexpected packet");
  8350. return -1;
  8351. }
  8352. }
  8353. msgsz = MG_LOAD_BE16(rio->buf + 3);
  8354. msg = rio->buf + 5;
  8355. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  8356. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  8357. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  8358. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  8359. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  8360. aes_gcm_decrypt(msg, msg, msgsz - 16, tls->client_write_key,
  8361. sizeof(tls->client_write_key), nonce, sizeof(nonce));
  8362. r = msgsz - 16 - 1;
  8363. if (msg[r] == 0x17) {
  8364. if (bufsz > 0) {
  8365. memmove(buf, msg, msgsz - 16);
  8366. }
  8367. } else {
  8368. r = 0;
  8369. }
  8370. tls->cseq++;
  8371. mg_tls_drop_packet(rio);
  8372. return r;
  8373. }
  8374. static void mg_tls_server_extensions(struct mg_connection *c) {
  8375. struct tls_data *tls = c->tls;
  8376. // server extensions
  8377. uint8_t ext[6] = {0x08, 0, 0, 2, 0, 0};
  8378. mg_sha256_update(&tls->sha256, ext, sizeof(ext));
  8379. mg_tls_encrypt(c, ext, sizeof(ext), 0x16);
  8380. }
  8381. static void mg_tls_server_cert(struct mg_connection *c) {
  8382. struct tls_data *tls = c->tls;
  8383. // server DER certificate (empty)
  8384. size_t n = tls->server_cert_der.len;
  8385. uint8_t *cert = calloc(1, 13 + n); // FIXME: free
  8386. cert[0] = 0x0b; // handshake header
  8387. cert[1] = (uint8_t) (((n + 9) >> 16) & 255U); // 3 bytes: payload length
  8388. cert[2] = (uint8_t) (((n + 9) >> 8) & 255U);
  8389. cert[3] = (uint8_t) ((n + 9) & 255U);
  8390. cert[4] = 0; // request context
  8391. cert[5] = (uint8_t) (((n + 5) >> 16) & 255U); // 3 bytes: cert (s) length
  8392. cert[6] = (uint8_t) (((n + 5) >> 8) & 255U);
  8393. cert[7] = (uint8_t) ((n + 5) & 255U);
  8394. cert[8] =
  8395. (uint8_t) (((n) >> 16) & 255U); // 3 bytes: first (and only) cert len
  8396. cert[9] = (uint8_t) (((n) >> 8) & 255U);
  8397. cert[10] = (uint8_t) (n & 255U);
  8398. // bytes 11+ are certificate in DER format
  8399. memmove(cert + 11, tls->server_cert_der.ptr, n);
  8400. cert[11 + n] = cert[12 + n] = 0; // certificate extensions (none)
  8401. mg_sha256_update(&tls->sha256, cert, 13 + n);
  8402. mg_tls_encrypt(c, cert, 13 + n, 0x16);
  8403. }
  8404. // type adapter between uECC hash context and our sha256 implementation
  8405. typedef struct SHA256_HashContext {
  8406. uECC_HashContext uECC;
  8407. mg_sha256_ctx ctx;
  8408. } SHA256_HashContext;
  8409. static void init_SHA256(const uECC_HashContext *base) {
  8410. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8411. mg_sha256_init(&c->ctx);
  8412. }
  8413. static void update_SHA256(const uECC_HashContext *base, const uint8_t *message,
  8414. unsigned message_size) {
  8415. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8416. mg_sha256_update(&c->ctx, message, message_size);
  8417. }
  8418. static void finish_SHA256(const uECC_HashContext *base, uint8_t *hash_result) {
  8419. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8420. mg_sha256_final(hash_result, &c->ctx);
  8421. }
  8422. static void mg_tls_server_verify_ecdsa(struct mg_connection *c) {
  8423. struct tls_data *tls = c->tls;
  8424. // server certificate verify packet
  8425. uint8_t verify[82] = {0x0f, 0x00, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00};
  8426. size_t sigsz, verifysz = 0;
  8427. uint8_t hash[32] = {0}, tmp[2 * 32 + 64] = {0};
  8428. struct SHA256_HashContext ctx = {
  8429. {&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp},
  8430. {{0}, 0, 0, {0}}};
  8431. int neg1, neg2;
  8432. uint8_t sig[64], sig_content[130] = {
  8433. " "
  8434. " "
  8435. "TLS 1.3, server CertificateVerify\0"};
  8436. mg_sha256_ctx sha256;
  8437. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8438. mg_sha256_final(sig_content + 98, &sha256);
  8439. mg_sha256_init(&sha256);
  8440. mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
  8441. mg_sha256_final(hash, &sha256);
  8442. uECC_sign_deterministic(tls->server_key, hash, sizeof(hash), &ctx.uECC, sig,
  8443. uECC_secp256r1());
  8444. neg1 = !!(sig[0] & 0x80);
  8445. neg2 = !!(sig[32] & 0x80);
  8446. verify[8] = 0x30; // ASN.1 SEQUENCE
  8447. verify[9] = (uint8_t) (68 + neg1 + neg2);
  8448. verify[10] = 0x02; // ASN.1 INTEGER
  8449. verify[11] = (uint8_t) (32 + neg1);
  8450. memmove(verify + 12 + neg1, sig, 32);
  8451. verify[12 + 32 + neg1] = 0x02; // ASN.1 INTEGER
  8452. verify[13 + 32 + neg1] = (uint8_t) (32 + neg2);
  8453. memmove(verify + 14 + 32 + neg1 + neg2, sig + 32, 32);
  8454. sigsz = (size_t) (70 + neg1 + neg2);
  8455. verifysz = 8U + sigsz;
  8456. verify[3] = (uint8_t) (sigsz + 4);
  8457. verify[7] = (uint8_t) sigsz;
  8458. mg_tls_hexdump("verify", verify, verifysz);
  8459. mg_sha256_update(&tls->sha256, verify, verifysz);
  8460. mg_tls_encrypt(c, verify, verifysz, 0x16);
  8461. }
  8462. static void mg_tls_server_finish(struct mg_connection *c) {
  8463. struct tls_data *tls = c->tls;
  8464. struct mg_iobuf *wio = &tls->send;
  8465. mg_sha256_ctx sha256;
  8466. uint8_t hash[32];
  8467. uint8_t finish[36] = {0x14, 0, 0, 32};
  8468. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8469. mg_sha256_final(hash, &sha256);
  8470. mg_hmac_sha256(finish + 4, tls->server_finished_key, 32, hash, 32);
  8471. mg_tls_hexdump("hash", hash, sizeof(hash));
  8472. mg_tls_hexdump("key", tls->server_finished_key,
  8473. sizeof(tls->server_finished_key));
  8474. mg_tls_encrypt(c, finish, sizeof(finish), 0x16);
  8475. mg_io_send(c, wio->buf, wio->len);
  8476. wio->len = 0;
  8477. mg_sha256_update(&tls->sha256, finish, sizeof(finish));
  8478. }
  8479. static int mg_tls_client_change_cipher(struct mg_connection *c) {
  8480. // struct tls_data *tls = c->tls;
  8481. struct mg_iobuf *rio = &c->rtls;
  8482. for (;;) {
  8483. if (!mg_tls_got_msg(c)) {
  8484. return MG_IO_WAIT;
  8485. }
  8486. if (rio->buf[0] == 0x14) { // got a ChangeCipher record
  8487. break;
  8488. } else if (rio->buf[0] == 0x15) { // skip Alert records
  8489. MG_DEBUG(("TLS ALERT packet received"));
  8490. mg_tls_drop_packet(rio);
  8491. } else {
  8492. mg_error(c, "unexpected packet");
  8493. return MG_IO_ERR;
  8494. }
  8495. }
  8496. // consume ChangeCipher packet
  8497. mg_tls_drop_packet(rio);
  8498. return 0;
  8499. }
  8500. static int mg_tls_client_finish(struct mg_connection *c) {
  8501. uint8_t tmp[2048];
  8502. int n = mg_tls_recv_decrypt(c, tmp, sizeof(tmp));
  8503. if (n < 0) {
  8504. return -1;
  8505. }
  8506. // TODO: make sure it's a ClientFinish record
  8507. return 0;
  8508. }
  8509. static void mg_tls_generate_application_keys(struct mg_connection *c) {
  8510. struct tls_data *tls = c->tls;
  8511. uint8_t hash[32];
  8512. uint8_t premaster_secret[32];
  8513. uint8_t master_secret[32];
  8514. uint8_t server_secret[32];
  8515. uint8_t client_secret[32];
  8516. mg_sha256_ctx sha256;
  8517. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8518. mg_sha256_final(hash, &sha256);
  8519. mg_tls_derive_secret("tls13 derived", tls->handshake_secret, 32,
  8520. zeros_sha256_digest, 32, premaster_secret, 32);
  8521. mg_hmac_sha256(master_secret, premaster_secret, 32, zeros, 32);
  8522. mg_tls_derive_secret("tls13 s ap traffic", master_secret, 32, hash, 32,
  8523. server_secret, 32);
  8524. mg_tls_derive_secret("tls13 key", server_secret, 32, NULL, 0,
  8525. tls->server_write_key, 16);
  8526. mg_tls_derive_secret("tls13 iv", server_secret, 32, NULL, 0,
  8527. tls->server_write_iv, 12);
  8528. mg_tls_derive_secret("tls13 c ap traffic", master_secret, 32, hash, 32,
  8529. client_secret, 32);
  8530. mg_tls_derive_secret("tls13 key", client_secret, 32, NULL, 0,
  8531. tls->client_write_key, 16);
  8532. mg_tls_derive_secret("tls13 iv", client_secret, 32, NULL, 0,
  8533. tls->client_write_iv, 12);
  8534. tls->sseq = tls->cseq = 0;
  8535. }
  8536. void mg_tls_handshake(struct mg_connection *c) {
  8537. struct tls_data *tls = c->tls;
  8538. switch (tls->state) {
  8539. case MG_TLS_HS_CLIENT_HELLO:
  8540. if (mg_tls_client_hello(c) < 0) {
  8541. return;
  8542. }
  8543. tls->state = MG_TLS_HS_SERVER_HELLO;
  8544. // fallthrough
  8545. case MG_TLS_HS_SERVER_HELLO:
  8546. mg_tls_server_hello(c);
  8547. mg_tls_generate_handshake_keys(c);
  8548. mg_tls_server_extensions(c);
  8549. mg_tls_server_cert(c);
  8550. mg_tls_server_verify_ecdsa(c);
  8551. mg_tls_server_finish(c);
  8552. tls->state = MG_TLS_HS_CLIENT_CHANGE_CIPHER;
  8553. // fallthrough
  8554. case MG_TLS_HS_CLIENT_CHANGE_CIPHER:
  8555. if (mg_tls_client_change_cipher(c) < 0) {
  8556. return;
  8557. }
  8558. tls->state = MG_TLS_HS_CLIENT_FINISH;
  8559. // fallthrough
  8560. case MG_TLS_HS_CLIENT_FINISH:
  8561. if (mg_tls_client_finish(c) < 0) {
  8562. return;
  8563. }
  8564. mg_tls_generate_application_keys(c);
  8565. tls->state = MG_TLS_HS_DONE;
  8566. // fallthrough
  8567. case MG_TLS_HS_DONE: c->is_tls_hs = 0; return;
  8568. }
  8569. }
  8570. static int mg_parse_pem(const struct mg_str pem, const struct mg_str label,
  8571. struct mg_str *der) {
  8572. size_t n = 0, m = 0;
  8573. char *s;
  8574. const char *c;
  8575. struct mg_str caps[5];
  8576. if (!mg_match(pem, mg_str("#-----BEGIN #-----#-----END #-----#"), caps)) {
  8577. *der = mg_strdup(pem);
  8578. return 0;
  8579. }
  8580. if (mg_strcmp(caps[1], label) != 0 || mg_strcmp(caps[3], label) != 0) {
  8581. return -1; // bad label
  8582. }
  8583. if ((s = calloc(1, caps[2].len)) == NULL) {
  8584. return -1;
  8585. }
  8586. for (c = caps[2].ptr; c < caps[2].ptr + caps[2].len; c++) {
  8587. if (*c == ' ' || *c == '\n' || *c == '\r' || *c == '\t') {
  8588. continue;
  8589. }
  8590. s[n++] = *c;
  8591. }
  8592. m = mg_base64_decode(s, n, s, n);
  8593. if (m == 0) {
  8594. free(s);
  8595. return -1;
  8596. }
  8597. der->ptr = s;
  8598. der->len = m;
  8599. return 0;
  8600. }
  8601. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8602. struct mg_str key;
  8603. struct tls_data *tls = (struct tls_data *) calloc(1, sizeof(struct tls_data));
  8604. if (tls == NULL) {
  8605. mg_error(c, "tls oom");
  8606. return;
  8607. }
  8608. // parse PEM or DER EC key
  8609. if (opts->key.ptr == NULL ||
  8610. mg_parse_pem(opts->key, mg_str_s("EC PRIVATE KEY"), &key) < 0) {
  8611. MG_ERROR(("Failed to load EC private key"));
  8612. return;
  8613. }
  8614. if (key.len < 39) {
  8615. MG_ERROR(("EC private key too short"));
  8616. return;
  8617. }
  8618. // expect ASN.1 SEQUENCE=[INTEGER=1, BITSTRING of 32 bytes, ...]
  8619. // 30 nn 02 01 01 04 20 [key] ...
  8620. if (key.ptr[0] != 0x30 || (key.ptr[1] & 0x80) != 0) {
  8621. MG_ERROR(("EC private key: ASN.1 bad sequence"));
  8622. return;
  8623. }
  8624. if (memcmp(key.ptr + 2, "\x02\x01\x01\x04\x20", 5) != 0) {
  8625. MG_ERROR(("EC private key: ASN.1 bad data"));
  8626. }
  8627. memmove(tls->server_key, key.ptr + 7, 32);
  8628. free((void *) key.ptr);
  8629. // parse PEM or DER certificate
  8630. if (mg_parse_pem(opts->cert, mg_str_s("CERTIFICATE"), &tls->server_cert_der) <
  8631. 0) {
  8632. MG_ERROR(("Failed to load certificate"));
  8633. return;
  8634. }
  8635. // tls->send.align = tls->recv.align = MG_IO_SIZE;
  8636. tls->send.align = MG_IO_SIZE;
  8637. c->tls = tls;
  8638. c->is_tls = c->is_tls_hs = 1;
  8639. mg_sha256_init(&tls->sha256);
  8640. }
  8641. void mg_tls_free(struct mg_connection *c) {
  8642. struct tls_data *tls = c->tls;
  8643. if (tls != NULL) {
  8644. mg_iobuf_free(&tls->send);
  8645. free((void *) tls->server_cert_der.ptr);
  8646. }
  8647. free(c->tls);
  8648. c->tls = NULL;
  8649. }
  8650. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8651. struct tls_data *tls = c->tls;
  8652. long n = MG_IO_WAIT;
  8653. if (len > MG_IO_SIZE) len = MG_IO_SIZE;
  8654. mg_tls_encrypt(c, buf, len, 0x17);
  8655. while (tls->send.len > 0 &&
  8656. (n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {
  8657. mg_iobuf_del(&tls->send, 0, (size_t) n);
  8658. }
  8659. if (n == MG_IO_ERR || n == MG_IO_WAIT) return n;
  8660. return (long) len;
  8661. }
  8662. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8663. return mg_tls_recv_decrypt(c, buf, len);
  8664. }
  8665. size_t mg_tls_pending(struct mg_connection *c) {
  8666. return mg_tls_got_msg(c) ? 1 : 0;
  8667. }
  8668. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8669. (void) mgr;
  8670. }
  8671. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8672. (void) mgr;
  8673. }
  8674. #endif
  8675. #ifdef MG_ENABLE_LINES
  8676. #line 1 "src/tls_dummy.c"
  8677. #endif
  8678. #if MG_TLS == MG_TLS_NONE
  8679. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8680. (void) opts;
  8681. mg_error(c, "TLS is not enabled");
  8682. }
  8683. void mg_tls_handshake(struct mg_connection *c) {
  8684. (void) c;
  8685. }
  8686. void mg_tls_free(struct mg_connection *c) {
  8687. (void) c;
  8688. }
  8689. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8690. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  8691. }
  8692. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8693. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  8694. }
  8695. size_t mg_tls_pending(struct mg_connection *c) {
  8696. (void) c;
  8697. return 0;
  8698. }
  8699. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8700. (void) mgr;
  8701. }
  8702. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8703. (void) mgr;
  8704. }
  8705. #endif
  8706. #ifdef MG_ENABLE_LINES
  8707. #line 1 "src/tls_mbed.c"
  8708. #endif
  8709. #if MG_TLS == MG_TLS_MBED
  8710. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000
  8711. #define MG_MBEDTLS_RNG_GET , mg_mbed_rng, NULL
  8712. #else
  8713. #define MG_MBEDTLS_RNG_GET
  8714. #endif
  8715. static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) {
  8716. mg_random(buf, len);
  8717. (void) ctx;
  8718. return 0;
  8719. }
  8720. static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *p) {
  8721. int rc;
  8722. if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true;
  8723. if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL
  8724. if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.ptr, str.len)) != 0) {
  8725. MG_ERROR(("cert err %#x", -rc));
  8726. return false;
  8727. }
  8728. return true;
  8729. }
  8730. static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) {
  8731. int rc;
  8732. if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true;
  8733. if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL
  8734. if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.ptr, str.len, NULL,
  8735. 0 MG_MBEDTLS_RNG_GET)) != 0) {
  8736. MG_ERROR(("key err %#x", -rc));
  8737. return false;
  8738. }
  8739. return true;
  8740. }
  8741. void mg_tls_free(struct mg_connection *c) {
  8742. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8743. if (tls != NULL) {
  8744. mbedtls_ssl_free(&tls->ssl);
  8745. mbedtls_pk_free(&tls->pk);
  8746. mbedtls_x509_crt_free(&tls->ca);
  8747. mbedtls_x509_crt_free(&tls->cert);
  8748. mbedtls_ssl_config_free(&tls->conf);
  8749. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8750. mbedtls_ssl_ticket_free(&tls->ticket);
  8751. #endif
  8752. free(tls);
  8753. c->tls = NULL;
  8754. }
  8755. }
  8756. static int mg_net_send(void *ctx, const unsigned char *buf, size_t len) {
  8757. long n = mg_io_send((struct mg_connection *) ctx, buf, len);
  8758. MG_VERBOSE(("%lu n=%ld e=%d", ((struct mg_connection *) ctx)->id, n, errno));
  8759. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  8760. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  8761. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_SEND_FAILED;
  8762. return (int) n;
  8763. }
  8764. static int mg_net_recv(void *ctx, unsigned char *buf, size_t len) {
  8765. long n = mg_io_recv((struct mg_connection *) ctx, buf, len);
  8766. MG_VERBOSE(("%lu n=%ld", ((struct mg_connection *) ctx)->id, n));
  8767. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  8768. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  8769. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_RECV_FAILED;
  8770. return (int) n;
  8771. }
  8772. void mg_tls_handshake(struct mg_connection *c) {
  8773. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8774. int rc = mbedtls_ssl_handshake(&tls->ssl);
  8775. if (rc == 0) { // Success
  8776. MG_DEBUG(("%lu success", c->id));
  8777. c->is_tls_hs = 0;
  8778. mg_call(c, MG_EV_TLS_HS, NULL);
  8779. } else if (rc == MBEDTLS_ERR_SSL_WANT_READ ||
  8780. rc == MBEDTLS_ERR_SSL_WANT_WRITE) { // Still pending
  8781. MG_VERBOSE(("%lu pending, %d%d %d (-%#x)", c->id, c->is_connecting,
  8782. c->is_tls_hs, rc, -rc));
  8783. } else {
  8784. mg_error(c, "TLS handshake: -%#x", -rc); // Error
  8785. }
  8786. }
  8787. static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) {
  8788. n = (int) strlen(s2) - 1;
  8789. MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2));
  8790. (void) s;
  8791. }
  8792. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8793. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  8794. int rc = 0;
  8795. c->tls = tls;
  8796. if (c->tls == NULL) {
  8797. mg_error(c, "TLS OOM");
  8798. goto fail;
  8799. }
  8800. if (c->is_listening) goto fail;
  8801. MG_DEBUG(("%lu Setting TLS", c->id));
  8802. MG_PROF_ADD(c, "mbedtls_init_start");
  8803. mbedtls_ssl_init(&tls->ssl);
  8804. mbedtls_ssl_config_init(&tls->conf);
  8805. mbedtls_x509_crt_init(&tls->ca);
  8806. mbedtls_x509_crt_init(&tls->cert);
  8807. mbedtls_pk_init(&tls->pk);
  8808. mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c);
  8809. #if defined(MG_MBEDTLS_DEBUG_LEVEL)
  8810. mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL);
  8811. #endif
  8812. if ((rc = mbedtls_ssl_config_defaults(
  8813. &tls->conf,
  8814. c->is_client ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
  8815. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  8816. mg_error(c, "tls defaults %#x", -rc);
  8817. goto fail;
  8818. }
  8819. mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c);
  8820. if (opts->ca.len == 0 || mg_vcmp(&opts->ca, "*") == 0) {
  8821. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
  8822. } else {
  8823. if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail;
  8824. mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL);
  8825. if (c->is_client && opts->name.ptr != NULL && opts->name.ptr[0] != '\0') {
  8826. char *host = mg_mprintf("%.*s", opts->name.len, opts->name.ptr);
  8827. mbedtls_ssl_set_hostname(&tls->ssl, host);
  8828. MG_DEBUG(("%lu hostname verification: %s", c->id, host));
  8829. free(host);
  8830. }
  8831. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  8832. }
  8833. if (!mg_load_cert(opts->cert, &tls->cert)) goto fail;
  8834. if (!mg_load_key(opts->key, &tls->pk)) goto fail;
  8835. if (tls->cert.version &&
  8836. (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) {
  8837. mg_error(c, "own cert %#x", -rc);
  8838. goto fail;
  8839. }
  8840. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8841. mbedtls_ssl_conf_session_tickets_cb(
  8842. &tls->conf, mbedtls_ssl_ticket_write, mbedtls_ssl_ticket_parse,
  8843. &((struct mg_tls_ctx *) c->mgr->tls_ctx)->tickets);
  8844. #endif
  8845. if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) {
  8846. mg_error(c, "setup err %#x", -rc);
  8847. goto fail;
  8848. }
  8849. c->is_tls = 1;
  8850. c->is_tls_hs = 1;
  8851. mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0);
  8852. MG_PROF_ADD(c, "mbedtls_init_end");
  8853. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  8854. mg_tls_handshake(c);
  8855. }
  8856. return;
  8857. fail:
  8858. mg_tls_free(c);
  8859. }
  8860. size_t mg_tls_pending(struct mg_connection *c) {
  8861. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8862. return tls == NULL ? 0 : mbedtls_ssl_get_bytes_avail(&tls->ssl);
  8863. }
  8864. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8865. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8866. long n = mbedtls_ssl_read(&tls->ssl, (unsigned char *) buf, len);
  8867. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  8868. return MG_IO_WAIT;
  8869. if (n <= 0) return MG_IO_ERR;
  8870. return n;
  8871. }
  8872. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8873. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8874. long n = mbedtls_ssl_write(&tls->ssl, (unsigned char *) buf, len);
  8875. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  8876. return MG_IO_WAIT;
  8877. if (n <= 0) return MG_IO_ERR;
  8878. return n;
  8879. }
  8880. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8881. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx));
  8882. if (ctx == NULL) {
  8883. MG_ERROR(("TLS context init OOM"));
  8884. } else {
  8885. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8886. int rc;
  8887. mbedtls_ssl_ticket_init(&ctx->tickets);
  8888. if ((rc = mbedtls_ssl_ticket_setup(&ctx->tickets, mg_mbed_rng, NULL,
  8889. MBEDTLS_CIPHER_AES_128_GCM, 86400)) !=
  8890. 0) {
  8891. MG_ERROR((" mbedtls_ssl_ticket_setup %#x", -rc));
  8892. }
  8893. #endif
  8894. mgr->tls_ctx = ctx;
  8895. }
  8896. }
  8897. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8898. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx;
  8899. if (ctx != NULL) {
  8900. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8901. mbedtls_ssl_ticket_free(&ctx->tickets);
  8902. #endif
  8903. free(ctx);
  8904. mgr->tls_ctx = NULL;
  8905. }
  8906. }
  8907. #endif
  8908. #ifdef MG_ENABLE_LINES
  8909. #line 1 "src/tls_openssl.c"
  8910. #endif
  8911. #if MG_TLS == MG_TLS_OPENSSL
  8912. static int tls_err_cb(const char *s, size_t len, void *c) {
  8913. int n = (int) len - 1;
  8914. MG_ERROR(("%lu %.*s", ((struct mg_connection *) c)->id, n, s));
  8915. return 0; // undocumented
  8916. }
  8917. static int mg_tls_err(struct mg_connection *c, struct mg_tls *tls, int res) {
  8918. int err = SSL_get_error(tls->ssl, res);
  8919. // We've just fetched the last error from the queue.
  8920. // Now we need to clear the error queue. If we do not, then the following
  8921. // can happen (actually reported):
  8922. // - A new connection is accept()-ed with cert error (e.g. self-signed cert)
  8923. // - Since all accept()-ed connections share listener's context,
  8924. // - *ALL* SSL accepted connection report read error on the next poll cycle.
  8925. // Thus a single errored connection can close all the rest, unrelated ones.
  8926. // Clearing the error keeps the shared SSL_CTX in an OK state.
  8927. if (err != 0) ERR_print_errors_cb(tls_err_cb, c);
  8928. ERR_clear_error();
  8929. if (err == SSL_ERROR_WANT_READ) return 0;
  8930. if (err == SSL_ERROR_WANT_WRITE) return 0;
  8931. return err;
  8932. }
  8933. static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) {
  8934. BIO *bio = BIO_new_mem_buf(ca.ptr, (int) ca.len);
  8935. STACK_OF(X509_INFO) *certs =
  8936. bio ? PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL) : NULL;
  8937. if (bio) BIO_free(bio);
  8938. return certs;
  8939. }
  8940. static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) {
  8941. X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx);
  8942. for (int i = 0; i < sk_X509_INFO_num(certs); i++) {
  8943. X509_INFO *cert_info = sk_X509_INFO_value(certs, i);
  8944. if (cert_info->x509 && !X509_STORE_add_cert(cert_store, cert_info->x509))
  8945. return false;
  8946. }
  8947. return true;
  8948. }
  8949. static EVP_PKEY *load_key(struct mg_str s) {
  8950. BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len);
  8951. EVP_PKEY *key = bio ? PEM_read_bio_PrivateKey(bio, NULL, 0, NULL) : NULL;
  8952. if (bio) BIO_free(bio);
  8953. return key;
  8954. }
  8955. static X509 *load_cert(struct mg_str s) {
  8956. BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len);
  8957. X509 *cert = bio == NULL ? NULL
  8958. : s.ptr[0] == '-'
  8959. ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM
  8960. : d2i_X509_bio(bio, NULL); // DER
  8961. if (bio) BIO_free(bio);
  8962. return cert;
  8963. }
  8964. static long mg_bio_ctrl(BIO *b, int cmd, long larg, void *pargs) {
  8965. long ret = 0;
  8966. if (cmd == BIO_CTRL_PUSH) ret = 1;
  8967. if (cmd == BIO_CTRL_POP) ret = 1;
  8968. if (cmd == BIO_CTRL_FLUSH) ret = 1;
  8969. if (cmd == BIO_C_SET_NBIO) ret = 1;
  8970. // MG_DEBUG(("%d -> %ld", cmd, ret));
  8971. (void) b, (void) cmd, (void) larg, (void) pargs;
  8972. return ret;
  8973. }
  8974. static int mg_bio_read(BIO *bio, char *buf, int len) {
  8975. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  8976. long res = mg_io_recv(c, buf, (size_t) len);
  8977. // MG_DEBUG(("%p %d %ld", buf, len, res));
  8978. len = res > 0 ? (int) res : -1;
  8979. if (res == MG_IO_WAIT) BIO_set_retry_read(bio);
  8980. return len;
  8981. }
  8982. static int mg_bio_write(BIO *bio, const char *buf, int len) {
  8983. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  8984. long res = mg_io_send(c, buf, (size_t) len);
  8985. // MG_DEBUG(("%p %d %ld", buf, len, res));
  8986. len = res > 0 ? (int) res : -1;
  8987. if (res == MG_IO_WAIT) BIO_set_retry_write(bio);
  8988. return len;
  8989. }
  8990. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8991. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  8992. const char *id = "mongoose";
  8993. static unsigned char s_initialised = 0;
  8994. BIO *bio = NULL;
  8995. int rc;
  8996. if (tls == NULL) {
  8997. mg_error(c, "TLS OOM");
  8998. goto fail;
  8999. }
  9000. if (!s_initialised) {
  9001. SSL_library_init();
  9002. s_initialised++;
  9003. }
  9004. MG_DEBUG(("%lu Setting TLS", c->id));
  9005. tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method())
  9006. : SSL_CTX_new(SSLv23_server_method());
  9007. if ((tls->ssl = SSL_new(tls->ctx)) == NULL) {
  9008. mg_error(c, "SSL_new");
  9009. goto fail;
  9010. }
  9011. SSL_set_session_id_context(tls->ssl, (const uint8_t *) id,
  9012. (unsigned) strlen(id));
  9013. // Disable deprecated protocols
  9014. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2);
  9015. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3);
  9016. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1);
  9017. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1);
  9018. #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION
  9019. SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION);
  9020. #endif
  9021. #ifdef MG_ENABLE_OPENSSL_CIPHER_SERVER_PREFERENCE
  9022. SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
  9023. #endif
  9024. if (opts->ca.ptr != NULL && opts->ca.ptr[0] != '\0') {
  9025. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9026. NULL);
  9027. STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca);
  9028. rc = add_ca_certs(tls->ctx, certs);
  9029. sk_X509_INFO_pop_free(certs, X509_INFO_free);
  9030. if (!rc) {
  9031. mg_error(c, "CA err");
  9032. goto fail;
  9033. }
  9034. }
  9035. if (opts->cert.ptr != NULL && opts->cert.ptr[0] != '\0') {
  9036. X509 *cert = load_cert(opts->cert);
  9037. rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert);
  9038. X509_free(cert);
  9039. if (cert == NULL || rc != 1) {
  9040. mg_error(c, "CERT err %d", mg_tls_err(c, tls, rc));
  9041. goto fail;
  9042. }
  9043. }
  9044. if (opts->key.ptr != NULL && opts->key.ptr[0] != '\0') {
  9045. EVP_PKEY *key = load_key(opts->key);
  9046. rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key);
  9047. EVP_PKEY_free(key);
  9048. if (key == NULL || rc != 1) {
  9049. mg_error(c, "KEY err %d", mg_tls_err(c, tls, rc));
  9050. goto fail;
  9051. }
  9052. }
  9053. SSL_set_mode(tls->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  9054. #if OPENSSL_VERSION_NUMBER > 0x10002000L
  9055. (void) SSL_set_ecdh_auto(tls->ssl, 1);
  9056. #endif
  9057. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  9058. if (opts->name.len > 0) {
  9059. char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.ptr);
  9060. SSL_set1_host(tls->ssl, s);
  9061. SSL_set_tlsext_host_name(tls->ssl, s);
  9062. free(s);
  9063. }
  9064. #endif
  9065. tls->bm = BIO_meth_new(BIO_get_new_index() | BIO_TYPE_SOURCE_SINK, "bio_mg");
  9066. BIO_meth_set_write(tls->bm, mg_bio_write);
  9067. BIO_meth_set_read(tls->bm, mg_bio_read);
  9068. BIO_meth_set_ctrl(tls->bm, mg_bio_ctrl);
  9069. bio = BIO_new(tls->bm);
  9070. BIO_set_data(bio, c);
  9071. SSL_set_bio(tls->ssl, bio, bio);
  9072. c->tls = tls;
  9073. c->is_tls = 1;
  9074. c->is_tls_hs = 1;
  9075. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  9076. mg_tls_handshake(c);
  9077. }
  9078. MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client"));
  9079. return;
  9080. fail:
  9081. free(tls);
  9082. }
  9083. void mg_tls_handshake(struct mg_connection *c) {
  9084. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9085. int rc = c->is_client ? SSL_connect(tls->ssl) : SSL_accept(tls->ssl);
  9086. if (rc == 1) {
  9087. MG_DEBUG(("%lu success", c->id));
  9088. c->is_tls_hs = 0;
  9089. mg_call(c, MG_EV_TLS_HS, NULL);
  9090. } else {
  9091. int code = mg_tls_err(c, tls, rc);
  9092. if (code != 0) mg_error(c, "tls hs: rc %d, err %d", rc, code);
  9093. }
  9094. }
  9095. void mg_tls_free(struct mg_connection *c) {
  9096. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9097. if (tls == NULL) return;
  9098. SSL_free(tls->ssl);
  9099. SSL_CTX_free(tls->ctx);
  9100. BIO_meth_free(tls->bm);
  9101. free(tls);
  9102. c->tls = NULL;
  9103. }
  9104. size_t mg_tls_pending(struct mg_connection *c) {
  9105. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9106. return tls == NULL ? 0 : (size_t) SSL_pending(tls->ssl);
  9107. }
  9108. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9109. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9110. int n = SSL_read(tls->ssl, buf, (int) len);
  9111. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  9112. if (n <= 0) return MG_IO_ERR;
  9113. return n;
  9114. }
  9115. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9116. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9117. int n = SSL_write(tls->ssl, buf, (int) len);
  9118. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  9119. if (n <= 0) return MG_IO_ERR;
  9120. return n;
  9121. }
  9122. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9123. (void) mgr;
  9124. }
  9125. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9126. (void) mgr;
  9127. }
  9128. #endif
  9129. #ifdef MG_ENABLE_LINES
  9130. #line 1 "src/tls_uecc.c"
  9131. #endif
  9132. /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  9133. #if MG_TLS == MG_TLS_BUILTIN
  9134. #ifndef uECC_RNG_MAX_TRIES
  9135. #define uECC_RNG_MAX_TRIES 64
  9136. #endif
  9137. #if uECC_ENABLE_VLI_API
  9138. #define uECC_VLI_API
  9139. #else
  9140. #define uECC_VLI_API static
  9141. #endif
  9142. #if (uECC_PLATFORM == uECC_avr) || (uECC_PLATFORM == uECC_arm) || \
  9143. (uECC_PLATFORM == uECC_arm_thumb) || (uECC_PLATFORM == uECC_arm_thumb2)
  9144. #define CONCATX(a, ...) a##__VA_ARGS__
  9145. #define CONCAT(a, ...) CONCATX(a, __VA_ARGS__)
  9146. #define STRX(a) #a
  9147. #define STR(a) STRX(a)
  9148. #define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__))))
  9149. #define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__))))
  9150. #define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__))))
  9151. #define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__))))
  9152. #define EVAL4(...) __VA_ARGS__
  9153. #define DEC_1 0
  9154. #define DEC_2 1
  9155. #define DEC_3 2
  9156. #define DEC_4 3
  9157. #define DEC_5 4
  9158. #define DEC_6 5
  9159. #define DEC_7 6
  9160. #define DEC_8 7
  9161. #define DEC_9 8
  9162. #define DEC_10 9
  9163. #define DEC_11 10
  9164. #define DEC_12 11
  9165. #define DEC_13 12
  9166. #define DEC_14 13
  9167. #define DEC_15 14
  9168. #define DEC_16 15
  9169. #define DEC_17 16
  9170. #define DEC_18 17
  9171. #define DEC_19 18
  9172. #define DEC_20 19
  9173. #define DEC_21 20
  9174. #define DEC_22 21
  9175. #define DEC_23 22
  9176. #define DEC_24 23
  9177. #define DEC_25 24
  9178. #define DEC_26 25
  9179. #define DEC_27 26
  9180. #define DEC_28 27
  9181. #define DEC_29 28
  9182. #define DEC_30 29
  9183. #define DEC_31 30
  9184. #define DEC_32 31
  9185. #define DEC(N) CONCAT(DEC_, N)
  9186. #define SECOND_ARG(_, val, ...) val
  9187. #define SOME_CHECK_0 ~, 0
  9188. #define GET_SECOND_ARG(...) SECOND_ARG(__VA_ARGS__, SOME, )
  9189. #define SOME_OR_0(N) GET_SECOND_ARG(CONCAT(SOME_CHECK_, N))
  9190. #define EMPTY(...)
  9191. #define DEFER(...) __VA_ARGS__ EMPTY()
  9192. #define REPEAT_NAME_0() REPEAT_0
  9193. #define REPEAT_NAME_SOME() REPEAT_SOME
  9194. #define REPEAT_0(...)
  9195. #define REPEAT_SOME(N, stuff) \
  9196. DEFER(CONCAT(REPEAT_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), stuff) stuff
  9197. #define REPEAT(N, stuff) EVAL(REPEAT_SOME(N, stuff))
  9198. #define REPEATM_NAME_0() REPEATM_0
  9199. #define REPEATM_NAME_SOME() REPEATM_SOME
  9200. #define REPEATM_0(...)
  9201. #define REPEATM_SOME(N, macro) \
  9202. macro(N) DEFER(CONCAT(REPEATM_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), macro)
  9203. #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro))
  9204. #endif
  9205. //
  9206. #if (uECC_WORD_SIZE == 1)
  9207. #if uECC_SUPPORTS_secp160r1
  9208. #define uECC_MAX_WORDS 21 /* Due to the size of curve_n. */
  9209. #endif
  9210. #if uECC_SUPPORTS_secp192r1
  9211. #undef uECC_MAX_WORDS
  9212. #define uECC_MAX_WORDS 24
  9213. #endif
  9214. #if uECC_SUPPORTS_secp224r1
  9215. #undef uECC_MAX_WORDS
  9216. #define uECC_MAX_WORDS 28
  9217. #endif
  9218. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9219. #undef uECC_MAX_WORDS
  9220. #define uECC_MAX_WORDS 32
  9221. #endif
  9222. #elif (uECC_WORD_SIZE == 4)
  9223. #if uECC_SUPPORTS_secp160r1
  9224. #define uECC_MAX_WORDS 6 /* Due to the size of curve_n. */
  9225. #endif
  9226. #if uECC_SUPPORTS_secp192r1
  9227. #undef uECC_MAX_WORDS
  9228. #define uECC_MAX_WORDS 6
  9229. #endif
  9230. #if uECC_SUPPORTS_secp224r1
  9231. #undef uECC_MAX_WORDS
  9232. #define uECC_MAX_WORDS 7
  9233. #endif
  9234. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9235. #undef uECC_MAX_WORDS
  9236. #define uECC_MAX_WORDS 8
  9237. #endif
  9238. #elif (uECC_WORD_SIZE == 8)
  9239. #if uECC_SUPPORTS_secp160r1
  9240. #define uECC_MAX_WORDS 3
  9241. #endif
  9242. #if uECC_SUPPORTS_secp192r1
  9243. #undef uECC_MAX_WORDS
  9244. #define uECC_MAX_WORDS 3
  9245. #endif
  9246. #if uECC_SUPPORTS_secp224r1
  9247. #undef uECC_MAX_WORDS
  9248. #define uECC_MAX_WORDS 4
  9249. #endif
  9250. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9251. #undef uECC_MAX_WORDS
  9252. #define uECC_MAX_WORDS 4
  9253. #endif
  9254. #endif /* uECC_WORD_SIZE */
  9255. #define BITS_TO_WORDS(num_bits) \
  9256. ((wordcount_t) ((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / \
  9257. (uECC_WORD_SIZE * 8)))
  9258. #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
  9259. struct uECC_Curve_t {
  9260. wordcount_t num_words;
  9261. wordcount_t num_bytes;
  9262. bitcount_t num_n_bits;
  9263. uECC_word_t p[uECC_MAX_WORDS];
  9264. uECC_word_t n[uECC_MAX_WORDS];
  9265. uECC_word_t G[uECC_MAX_WORDS * 2];
  9266. uECC_word_t b[uECC_MAX_WORDS];
  9267. void (*double_jacobian)(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *Z1,
  9268. uECC_Curve curve);
  9269. #if uECC_SUPPORT_COMPRESSED_POINT
  9270. void (*mod_sqrt)(uECC_word_t *a, uECC_Curve curve);
  9271. #endif
  9272. void (*x_side)(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve);
  9273. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9274. void (*mmod_fast)(uECC_word_t *result, uECC_word_t *product);
  9275. #endif
  9276. };
  9277. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  9278. static void bcopy(uint8_t *dst, const uint8_t *src, unsigned num_bytes) {
  9279. while (0 != num_bytes) {
  9280. num_bytes--;
  9281. dst[num_bytes] = src[num_bytes];
  9282. }
  9283. }
  9284. #endif
  9285. static cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
  9286. const uECC_word_t *right,
  9287. wordcount_t num_words);
  9288. #if (uECC_PLATFORM == uECC_arm || uECC_PLATFORM == uECC_arm_thumb || \
  9289. uECC_PLATFORM == uECC_arm_thumb2)
  9290. #endif
  9291. #if (uECC_PLATFORM == uECC_avr)
  9292. #endif
  9293. #ifndef asm_clear
  9294. #define asm_clear 0
  9295. #endif
  9296. #ifndef asm_set
  9297. #define asm_set 0
  9298. #endif
  9299. #ifndef asm_add
  9300. #define asm_add 0
  9301. #endif
  9302. #ifndef asm_sub
  9303. #define asm_sub 0
  9304. #endif
  9305. #ifndef asm_mult
  9306. #define asm_mult 0
  9307. #endif
  9308. #ifndef asm_rshift1
  9309. #define asm_rshift1 0
  9310. #endif
  9311. #ifndef asm_mmod_fast_secp256r1
  9312. #define asm_mmod_fast_secp256r1 0
  9313. #endif
  9314. #if defined(default_RNG_defined) && default_RNG_defined
  9315. static uECC_RNG_Function g_rng_function = &default_RNG;
  9316. #else
  9317. static uECC_RNG_Function g_rng_function = 0;
  9318. #endif
  9319. void uECC_set_rng(uECC_RNG_Function rng_function) {
  9320. g_rng_function = rng_function;
  9321. }
  9322. uECC_RNG_Function uECC_get_rng(void) {
  9323. return g_rng_function;
  9324. }
  9325. int uECC_curve_private_key_size(uECC_Curve curve) {
  9326. return BITS_TO_BYTES(curve->num_n_bits);
  9327. }
  9328. int uECC_curve_public_key_size(uECC_Curve curve) {
  9329. return 2 * curve->num_bytes;
  9330. }
  9331. #if !asm_clear
  9332. uECC_VLI_API void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words) {
  9333. wordcount_t i;
  9334. for (i = 0; i < num_words; ++i) {
  9335. vli[i] = 0;
  9336. }
  9337. }
  9338. #endif /* !asm_clear */
  9339. /* Constant-time comparison to zero - secure way to compare long integers */
  9340. /* Returns 1 if vli == 0, 0 otherwise. */
  9341. uECC_VLI_API uECC_word_t uECC_vli_isZero(const uECC_word_t *vli,
  9342. wordcount_t num_words) {
  9343. uECC_word_t bits = 0;
  9344. wordcount_t i;
  9345. for (i = 0; i < num_words; ++i) {
  9346. bits |= vli[i];
  9347. }
  9348. return (bits == 0);
  9349. }
  9350. /* Returns nonzero if bit 'bit' of vli is set. */
  9351. uECC_VLI_API uECC_word_t uECC_vli_testBit(const uECC_word_t *vli,
  9352. bitcount_t bit) {
  9353. return (vli[bit >> uECC_WORD_BITS_SHIFT] &
  9354. ((uECC_word_t) 1 << (bit & uECC_WORD_BITS_MASK)));
  9355. }
  9356. /* Counts the number of words in vli. */
  9357. static wordcount_t vli_numDigits(const uECC_word_t *vli,
  9358. const wordcount_t max_words) {
  9359. wordcount_t i;
  9360. /* Search from the end until we find a non-zero digit.
  9361. We do it in reverse because we expect that most digits will be nonzero. */
  9362. for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
  9363. }
  9364. return (i + 1);
  9365. }
  9366. /* Counts the number of bits required to represent vli. */
  9367. uECC_VLI_API bitcount_t uECC_vli_numBits(const uECC_word_t *vli,
  9368. const wordcount_t max_words) {
  9369. uECC_word_t i;
  9370. uECC_word_t digit;
  9371. wordcount_t num_digits = vli_numDigits(vli, max_words);
  9372. if (num_digits == 0) {
  9373. return 0;
  9374. }
  9375. digit = vli[num_digits - 1];
  9376. for (i = 0; digit; ++i) {
  9377. digit >>= 1;
  9378. }
  9379. return (((bitcount_t) ((num_digits - 1) << uECC_WORD_BITS_SHIFT)) +
  9380. (bitcount_t) i);
  9381. }
  9382. /* Sets dest = src. */
  9383. #if !asm_set
  9384. uECC_VLI_API void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src,
  9385. wordcount_t num_words) {
  9386. wordcount_t i;
  9387. for (i = 0; i < num_words; ++i) {
  9388. dest[i] = src[i];
  9389. }
  9390. }
  9391. #endif /* !asm_set */
  9392. /* Returns sign of left - right. */
  9393. static cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
  9394. const uECC_word_t *right,
  9395. wordcount_t num_words) {
  9396. wordcount_t i;
  9397. for (i = num_words - 1; i >= 0; --i) {
  9398. if (left[i] > right[i]) {
  9399. return 1;
  9400. } else if (left[i] < right[i]) {
  9401. return -1;
  9402. }
  9403. }
  9404. return 0;
  9405. }
  9406. /* Constant-time comparison function - secure way to compare long integers */
  9407. /* Returns one if left == right, zero otherwise. */
  9408. uECC_VLI_API uECC_word_t uECC_vli_equal(const uECC_word_t *left,
  9409. const uECC_word_t *right,
  9410. wordcount_t num_words) {
  9411. uECC_word_t diff = 0;
  9412. wordcount_t i;
  9413. for (i = num_words - 1; i >= 0; --i) {
  9414. diff |= (left[i] ^ right[i]);
  9415. }
  9416. return (diff == 0);
  9417. }
  9418. uECC_VLI_API uECC_word_t uECC_vli_sub(uECC_word_t *result,
  9419. const uECC_word_t *left,
  9420. const uECC_word_t *right,
  9421. wordcount_t num_words);
  9422. /* Returns sign of left - right, in constant time. */
  9423. uECC_VLI_API cmpresult_t uECC_vli_cmp(const uECC_word_t *left,
  9424. const uECC_word_t *right,
  9425. wordcount_t num_words) {
  9426. uECC_word_t tmp[uECC_MAX_WORDS];
  9427. uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words);
  9428. uECC_word_t equal = uECC_vli_isZero(tmp, num_words);
  9429. return (cmpresult_t) (!equal - 2 * neg);
  9430. }
  9431. /* Computes vli = vli >> 1. */
  9432. #if !asm_rshift1
  9433. uECC_VLI_API void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words) {
  9434. uECC_word_t *end = vli;
  9435. uECC_word_t carry = 0;
  9436. vli += num_words;
  9437. while (vli-- > end) {
  9438. uECC_word_t temp = *vli;
  9439. *vli = (temp >> 1) | carry;
  9440. carry = temp << (uECC_WORD_BITS - 1);
  9441. }
  9442. }
  9443. #endif /* !asm_rshift1 */
  9444. /* Computes result = left + right, returning carry. Can modify in place. */
  9445. #if !asm_add
  9446. uECC_VLI_API uECC_word_t uECC_vli_add(uECC_word_t *result,
  9447. const uECC_word_t *left,
  9448. const uECC_word_t *right,
  9449. wordcount_t num_words) {
  9450. uECC_word_t carry = 0;
  9451. wordcount_t i;
  9452. for (i = 0; i < num_words; ++i) {
  9453. uECC_word_t sum = left[i] + right[i] + carry;
  9454. if (sum != left[i]) {
  9455. carry = (sum < left[i]);
  9456. }
  9457. result[i] = sum;
  9458. }
  9459. return carry;
  9460. }
  9461. #endif /* !asm_add */
  9462. /* Computes result = left - right, returning borrow. Can modify in place. */
  9463. #if !asm_sub
  9464. uECC_VLI_API uECC_word_t uECC_vli_sub(uECC_word_t *result,
  9465. const uECC_word_t *left,
  9466. const uECC_word_t *right,
  9467. wordcount_t num_words) {
  9468. uECC_word_t borrow = 0;
  9469. wordcount_t i;
  9470. for (i = 0; i < num_words; ++i) {
  9471. uECC_word_t diff = left[i] - right[i] - borrow;
  9472. if (diff != left[i]) {
  9473. borrow = (diff > left[i]);
  9474. }
  9475. result[i] = diff;
  9476. }
  9477. return borrow;
  9478. }
  9479. #endif /* !asm_sub */
  9480. #if !asm_mult || (uECC_SQUARE_FUNC && !asm_square) || \
  9481. (uECC_SUPPORTS_secp256k1 && (uECC_OPTIMIZATION_LEVEL > 0) && \
  9482. ((uECC_WORD_SIZE == 1) || (uECC_WORD_SIZE == 8)))
  9483. static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
  9484. uECC_word_t *r1, uECC_word_t *r2) {
  9485. #if uECC_WORD_SIZE == 8
  9486. uint64_t a0 = a & 0xffffffff;
  9487. uint64_t a1 = a >> 32;
  9488. uint64_t b0 = b & 0xffffffff;
  9489. uint64_t b1 = b >> 32;
  9490. uint64_t i0 = a0 * b0;
  9491. uint64_t i1 = a0 * b1;
  9492. uint64_t i2 = a1 * b0;
  9493. uint64_t i3 = a1 * b1;
  9494. uint64_t p0, p1;
  9495. i2 += (i0 >> 32);
  9496. i2 += i1;
  9497. if (i2 < i1) { /* overflow */
  9498. i3 += 0x100000000;
  9499. }
  9500. p0 = (i0 & 0xffffffff) | (i2 << 32);
  9501. p1 = i3 + (i2 >> 32);
  9502. *r0 += p0;
  9503. *r1 += (p1 + (*r0 < p0));
  9504. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  9505. #else
  9506. uECC_dword_t p = (uECC_dword_t) a * b;
  9507. uECC_dword_t r01 = ((uECC_dword_t) (*r1) << uECC_WORD_BITS) | *r0;
  9508. r01 += p;
  9509. *r2 += (r01 < p);
  9510. *r1 = (uECC_word_t) (r01 >> uECC_WORD_BITS);
  9511. *r0 = (uECC_word_t) r01;
  9512. #endif
  9513. }
  9514. #endif /* muladd needed */
  9515. #if !asm_mult
  9516. uECC_VLI_API void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left,
  9517. const uECC_word_t *right,
  9518. wordcount_t num_words) {
  9519. uECC_word_t r0 = 0;
  9520. uECC_word_t r1 = 0;
  9521. uECC_word_t r2 = 0;
  9522. wordcount_t i, k;
  9523. /* Compute each digit of result in sequence, maintaining the carries. */
  9524. for (k = 0; k < num_words; ++k) {
  9525. for (i = 0; i <= k; ++i) {
  9526. muladd(left[i], right[k - i], &r0, &r1, &r2);
  9527. }
  9528. result[k] = r0;
  9529. r0 = r1;
  9530. r1 = r2;
  9531. r2 = 0;
  9532. }
  9533. for (k = num_words; k < num_words * 2 - 1; ++k) {
  9534. for (i = (wordcount_t) ((k + 1) - num_words); i < num_words; ++i) {
  9535. muladd(left[i], right[k - i], &r0, &r1, &r2);
  9536. }
  9537. result[k] = r0;
  9538. r0 = r1;
  9539. r1 = r2;
  9540. r2 = 0;
  9541. }
  9542. result[num_words * 2 - 1] = r0;
  9543. }
  9544. #endif /* !asm_mult */
  9545. #if uECC_SQUARE_FUNC
  9546. #if !asm_square
  9547. static void mul2add(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
  9548. uECC_word_t *r1, uECC_word_t *r2) {
  9549. #if uECC_WORD_SIZE == 8
  9550. uint64_t a0 = a & 0xffffffffull;
  9551. uint64_t a1 = a >> 32;
  9552. uint64_t b0 = b & 0xffffffffull;
  9553. uint64_t b1 = b >> 32;
  9554. uint64_t i0 = a0 * b0;
  9555. uint64_t i1 = a0 * b1;
  9556. uint64_t i2 = a1 * b0;
  9557. uint64_t i3 = a1 * b1;
  9558. uint64_t p0, p1;
  9559. i2 += (i0 >> 32);
  9560. i2 += i1;
  9561. if (i2 < i1) { /* overflow */
  9562. i3 += 0x100000000ull;
  9563. }
  9564. p0 = (i0 & 0xffffffffull) | (i2 << 32);
  9565. p1 = i3 + (i2 >> 32);
  9566. *r2 += (p1 >> 63);
  9567. p1 = (p1 << 1) | (p0 >> 63);
  9568. p0 <<= 1;
  9569. *r0 += p0;
  9570. *r1 += (p1 + (*r0 < p0));
  9571. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  9572. #else
  9573. uECC_dword_t p = (uECC_dword_t) a * b;
  9574. uECC_dword_t r01 = ((uECC_dword_t) (*r1) << uECC_WORD_BITS) | *r0;
  9575. *r2 += (p >> (uECC_WORD_BITS * 2 - 1));
  9576. p *= 2;
  9577. r01 += p;
  9578. *r2 += (r01 < p);
  9579. *r1 = r01 >> uECC_WORD_BITS;
  9580. *r0 = (uECC_word_t) r01;
  9581. #endif
  9582. }
  9583. uECC_VLI_API void uECC_vli_square(uECC_word_t *result, const uECC_word_t *left,
  9584. wordcount_t num_words) {
  9585. uECC_word_t r0 = 0;
  9586. uECC_word_t r1 = 0;
  9587. uECC_word_t r2 = 0;
  9588. wordcount_t i, k;
  9589. for (k = 0; k < num_words * 2 - 1; ++k) {
  9590. uECC_word_t min = (k < num_words ? 0 : (k + 1) - num_words);
  9591. for (i = min; i <= k && i <= k - i; ++i) {
  9592. if (i < k - i) {
  9593. mul2add(left[i], left[k - i], &r0, &r1, &r2);
  9594. } else {
  9595. muladd(left[i], left[k - i], &r0, &r1, &r2);
  9596. }
  9597. }
  9598. result[k] = r0;
  9599. r0 = r1;
  9600. r1 = r2;
  9601. r2 = 0;
  9602. }
  9603. result[num_words * 2 - 1] = r0;
  9604. }
  9605. #endif /* !asm_square */
  9606. #else /* uECC_SQUARE_FUNC */
  9607. #if uECC_ENABLE_VLI_API
  9608. uECC_VLI_API void uECC_vli_square(uECC_word_t *result, const uECC_word_t *left,
  9609. wordcount_t num_words) {
  9610. uECC_vli_mult(result, left, left, num_words);
  9611. }
  9612. #endif /* uECC_ENABLE_VLI_API */
  9613. #endif /* uECC_SQUARE_FUNC */
  9614. /* Computes result = (left + right) % mod.
  9615. Assumes that left < mod and right < mod, and that result does not overlap
  9616. mod. */
  9617. uECC_VLI_API void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left,
  9618. const uECC_word_t *right,
  9619. const uECC_word_t *mod,
  9620. wordcount_t num_words) {
  9621. uECC_word_t carry = uECC_vli_add(result, left, right, num_words);
  9622. if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {
  9623. /* result > mod (result = mod + remainder), so subtract mod to get
  9624. * remainder. */
  9625. uECC_vli_sub(result, result, mod, num_words);
  9626. }
  9627. }
  9628. /* Computes result = (left - right) % mod.
  9629. Assumes that left < mod and right < mod, and that result does not overlap
  9630. mod. */
  9631. uECC_VLI_API void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left,
  9632. const uECC_word_t *right,
  9633. const uECC_word_t *mod,
  9634. wordcount_t num_words) {
  9635. uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);
  9636. if (l_borrow) {
  9637. /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
  9638. we can get the correct result from result + mod (with overflow). */
  9639. uECC_vli_add(result, result, mod, num_words);
  9640. }
  9641. }
  9642. /* Computes result = product % mod, where product is 2N words long. */
  9643. /* Currently only designed to work for curve_p or curve_n. */
  9644. uECC_VLI_API void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product,
  9645. const uECC_word_t *mod, wordcount_t num_words) {
  9646. uECC_word_t mod_multiple[2 * uECC_MAX_WORDS];
  9647. uECC_word_t tmp[2 * uECC_MAX_WORDS];
  9648. uECC_word_t *v[2] = {tmp, product};
  9649. uECC_word_t index;
  9650. /* Shift mod so its highest set bit is at the maximum position. */
  9651. bitcount_t shift = (bitcount_t) (
  9652. (num_words * 2 * uECC_WORD_BITS) - uECC_vli_numBits(mod, num_words));
  9653. wordcount_t word_shift = (wordcount_t) (shift / uECC_WORD_BITS);
  9654. wordcount_t bit_shift = (wordcount_t) (shift % uECC_WORD_BITS);
  9655. uECC_word_t carry = 0;
  9656. uECC_vli_clear(mod_multiple, word_shift);
  9657. if (bit_shift > 0) {
  9658. for (index = 0; index < (uECC_word_t) num_words; ++index) {
  9659. mod_multiple[(uECC_word_t) word_shift + index] =
  9660. (uECC_word_t) (mod[index] << bit_shift) | carry;
  9661. carry = mod[index] >> (uECC_WORD_BITS - bit_shift);
  9662. }
  9663. } else {
  9664. uECC_vli_set(mod_multiple + word_shift, mod, num_words);
  9665. }
  9666. for (index = 1; shift >= 0; --shift) {
  9667. uECC_word_t borrow = 0;
  9668. wordcount_t i;
  9669. for (i = 0; i < num_words * 2; ++i) {
  9670. uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow;
  9671. if (diff != v[index][i]) {
  9672. borrow = (diff > v[index][i]);
  9673. }
  9674. v[1 - index][i] = diff;
  9675. }
  9676. index = !(index ^ borrow); /* Swap the index if there was no borrow */
  9677. uECC_vli_rshift1(mod_multiple, num_words);
  9678. mod_multiple[num_words - 1] |= mod_multiple[num_words]
  9679. << (uECC_WORD_BITS - 1);
  9680. uECC_vli_rshift1(mod_multiple + num_words, num_words);
  9681. }
  9682. uECC_vli_set(result, v[index], num_words);
  9683. }
  9684. /* Computes result = (left * right) % mod. */
  9685. uECC_VLI_API void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left,
  9686. const uECC_word_t *right,
  9687. const uECC_word_t *mod,
  9688. wordcount_t num_words) {
  9689. uECC_word_t product[2 * uECC_MAX_WORDS];
  9690. uECC_vli_mult(product, left, right, num_words);
  9691. uECC_vli_mmod(result, product, mod, num_words);
  9692. }
  9693. uECC_VLI_API void uECC_vli_modMult_fast(uECC_word_t *result,
  9694. const uECC_word_t *left,
  9695. const uECC_word_t *right,
  9696. uECC_Curve curve) {
  9697. uECC_word_t product[2 * uECC_MAX_WORDS];
  9698. uECC_vli_mult(product, left, right, curve->num_words);
  9699. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9700. curve->mmod_fast(result, product);
  9701. #else
  9702. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  9703. #endif
  9704. }
  9705. #if uECC_SQUARE_FUNC
  9706. #if uECC_ENABLE_VLI_API
  9707. /* Computes result = left^2 % mod. */
  9708. uECC_VLI_API void uECC_vli_modSquare(uECC_word_t *result,
  9709. const uECC_word_t *left,
  9710. const uECC_word_t *mod,
  9711. wordcount_t num_words) {
  9712. uECC_word_t product[2 * uECC_MAX_WORDS];
  9713. uECC_vli_square(product, left, num_words);
  9714. uECC_vli_mmod(result, product, mod, num_words);
  9715. }
  9716. #endif /* uECC_ENABLE_VLI_API */
  9717. uECC_VLI_API void uECC_vli_modSquare_fast(uECC_word_t *result,
  9718. const uECC_word_t *left,
  9719. uECC_Curve curve) {
  9720. uECC_word_t product[2 * uECC_MAX_WORDS];
  9721. uECC_vli_square(product, left, curve->num_words);
  9722. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9723. curve->mmod_fast(result, product);
  9724. #else
  9725. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  9726. #endif
  9727. }
  9728. #else /* uECC_SQUARE_FUNC */
  9729. #if uECC_ENABLE_VLI_API
  9730. uECC_VLI_API void uECC_vli_modSquare(uECC_word_t *result,
  9731. const uECC_word_t *left,
  9732. const uECC_word_t *mod,
  9733. wordcount_t num_words) {
  9734. uECC_vli_modMult(result, left, left, mod, num_words);
  9735. }
  9736. #endif /* uECC_ENABLE_VLI_API */
  9737. uECC_VLI_API void uECC_vli_modSquare_fast(uECC_word_t *result,
  9738. const uECC_word_t *left,
  9739. uECC_Curve curve) {
  9740. uECC_vli_modMult_fast(result, left, left, curve);
  9741. }
  9742. #endif /* uECC_SQUARE_FUNC */
  9743. #define EVEN(vli) (!(vli[0] & 1))
  9744. static void vli_modInv_update(uECC_word_t *uv, const uECC_word_t *mod,
  9745. wordcount_t num_words) {
  9746. uECC_word_t carry = 0;
  9747. if (!EVEN(uv)) {
  9748. carry = uECC_vli_add(uv, uv, mod, num_words);
  9749. }
  9750. uECC_vli_rshift1(uv, num_words);
  9751. if (carry) {
  9752. uv[num_words - 1] |= HIGH_BIT_SET;
  9753. }
  9754. }
  9755. /* Computes result = (1 / input) % mod. All VLIs are the same size.
  9756. See "From Euclid's GCD to Montgomery Multiplication to the Great Divide" */
  9757. uECC_VLI_API void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input,
  9758. const uECC_word_t *mod,
  9759. wordcount_t num_words) {
  9760. uECC_word_t a[uECC_MAX_WORDS], b[uECC_MAX_WORDS], u[uECC_MAX_WORDS],
  9761. v[uECC_MAX_WORDS];
  9762. cmpresult_t cmpResult;
  9763. if (uECC_vli_isZero(input, num_words)) {
  9764. uECC_vli_clear(result, num_words);
  9765. return;
  9766. }
  9767. uECC_vli_set(a, input, num_words);
  9768. uECC_vli_set(b, mod, num_words);
  9769. uECC_vli_clear(u, num_words);
  9770. u[0] = 1;
  9771. uECC_vli_clear(v, num_words);
  9772. while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {
  9773. if (EVEN(a)) {
  9774. uECC_vli_rshift1(a, num_words);
  9775. vli_modInv_update(u, mod, num_words);
  9776. } else if (EVEN(b)) {
  9777. uECC_vli_rshift1(b, num_words);
  9778. vli_modInv_update(v, mod, num_words);
  9779. } else if (cmpResult > 0) {
  9780. uECC_vli_sub(a, a, b, num_words);
  9781. uECC_vli_rshift1(a, num_words);
  9782. if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {
  9783. uECC_vli_add(u, u, mod, num_words);
  9784. }
  9785. uECC_vli_sub(u, u, v, num_words);
  9786. vli_modInv_update(u, mod, num_words);
  9787. } else {
  9788. uECC_vli_sub(b, b, a, num_words);
  9789. uECC_vli_rshift1(b, num_words);
  9790. if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {
  9791. uECC_vli_add(v, v, mod, num_words);
  9792. }
  9793. uECC_vli_sub(v, v, u, num_words);
  9794. vli_modInv_update(v, mod, num_words);
  9795. }
  9796. }
  9797. uECC_vli_set(result, u, num_words);
  9798. }
  9799. /* ------ Point operations ------ */
  9800. /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  9801. #ifndef _UECC_CURVE_SPECIFIC_H_
  9802. #define _UECC_CURVE_SPECIFIC_H_
  9803. #define num_bytes_secp160r1 20
  9804. #define num_bytes_secp192r1 24
  9805. #define num_bytes_secp224r1 28
  9806. #define num_bytes_secp256r1 32
  9807. #define num_bytes_secp256k1 32
  9808. #if (uECC_WORD_SIZE == 1)
  9809. #define num_words_secp160r1 20
  9810. #define num_words_secp192r1 24
  9811. #define num_words_secp224r1 28
  9812. #define num_words_secp256r1 32
  9813. #define num_words_secp256k1 32
  9814. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) \
  9815. 0x##a, 0x##b, 0x##c, 0x##d, 0x##e, 0x##f, 0x##g, 0x##h
  9816. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##a, 0x##b, 0x##c, 0x##d
  9817. #elif (uECC_WORD_SIZE == 4)
  9818. #define num_words_secp160r1 5
  9819. #define num_words_secp192r1 6
  9820. #define num_words_secp224r1 7
  9821. #define num_words_secp256r1 8
  9822. #define num_words_secp256k1 8
  9823. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
  9824. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
  9825. #elif (uECC_WORD_SIZE == 8)
  9826. #define num_words_secp160r1 3
  9827. #define num_words_secp192r1 3
  9828. #define num_words_secp224r1 4
  9829. #define num_words_secp256r1 4
  9830. #define num_words_secp256k1 4
  9831. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##h##g##f##e##d##c##b##a##U
  9832. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a##U
  9833. #endif /* uECC_WORD_SIZE */
  9834. #if uECC_SUPPORTS_secp160r1 || uECC_SUPPORTS_secp192r1 || \
  9835. uECC_SUPPORTS_secp224r1 || uECC_SUPPORTS_secp256r1
  9836. static void double_jacobian_default(uECC_word_t *X1, uECC_word_t *Y1,
  9837. uECC_word_t *Z1, uECC_Curve curve) {
  9838. /* t1 = X, t2 = Y, t3 = Z */
  9839. uECC_word_t t4[uECC_MAX_WORDS];
  9840. uECC_word_t t5[uECC_MAX_WORDS];
  9841. wordcount_t num_words = curve->num_words;
  9842. if (uECC_vli_isZero(Z1, num_words)) {
  9843. return;
  9844. }
  9845. uECC_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */
  9846. uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
  9847. uECC_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */
  9848. uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
  9849. uECC_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */
  9850. uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
  9851. uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
  9852. uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
  9853. uECC_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */
  9854. uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */
  9855. uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */
  9856. if (uECC_vli_testBit(X1, 0)) {
  9857. uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words);
  9858. uECC_vli_rshift1(X1, num_words);
  9859. X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1);
  9860. } else {
  9861. uECC_vli_rshift1(X1, num_words);
  9862. }
  9863. /* t1 = 3/2*(x1^2 - z1^4) = B */
  9864. uECC_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */
  9865. uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
  9866. uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
  9867. uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
  9868. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */
  9869. uECC_vli_modSub(t4, X1, t4, curve->p,
  9870. num_words); /* t4 = B * (A - x3) - y1^4 = y3 */
  9871. uECC_vli_set(X1, Z1, num_words);
  9872. uECC_vli_set(Z1, Y1, num_words);
  9873. uECC_vli_set(Y1, t4, num_words);
  9874. }
  9875. /* Computes result = x^3 + ax + b. result must not overlap x. */
  9876. static void x_side_default(uECC_word_t *result, const uECC_word_t *x,
  9877. uECC_Curve curve) {
  9878. uECC_word_t _3[uECC_MAX_WORDS] = {3}; /* -a = 3 */
  9879. wordcount_t num_words = curve->num_words;
  9880. uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  9881. uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
  9882. uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */
  9883. uECC_vli_modAdd(result, result, curve->b, curve->p,
  9884. num_words); /* r = x^3 - 3x + b */
  9885. }
  9886. #endif /* uECC_SUPPORTS_secp... */
  9887. #if uECC_SUPPORT_COMPRESSED_POINT
  9888. #if uECC_SUPPORTS_secp160r1 || uECC_SUPPORTS_secp192r1 || \
  9889. uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1
  9890. /* Compute a = sqrt(a) (mod curve_p). */
  9891. static void mod_sqrt_default(uECC_word_t *a, uECC_Curve curve) {
  9892. bitcount_t i;
  9893. uECC_word_t p1[uECC_MAX_WORDS] = {1};
  9894. uECC_word_t l_result[uECC_MAX_WORDS] = {1};
  9895. wordcount_t num_words = curve->num_words;
  9896. /* When curve->p == 3 (mod 4), we can compute
  9897. sqrt(a) = a^((curve->p + 1) / 4) (mod curve->p). */
  9898. uECC_vli_add(p1, curve->p, p1, num_words); /* p1 = curve_p + 1 */
  9899. for (i = uECC_vli_numBits(p1, num_words) - 1; i > 1; --i) {
  9900. uECC_vli_modSquare_fast(l_result, l_result, curve);
  9901. if (uECC_vli_testBit(p1, i)) {
  9902. uECC_vli_modMult_fast(l_result, l_result, a, curve);
  9903. }
  9904. }
  9905. uECC_vli_set(a, l_result, num_words);
  9906. }
  9907. #endif /* uECC_SUPPORTS_secp... */
  9908. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  9909. #if uECC_SUPPORTS_secp160r1
  9910. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9911. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product);
  9912. #endif
  9913. static const struct uECC_Curve_t curve_secp160r1 = {
  9914. num_words_secp160r1,
  9915. num_bytes_secp160r1,
  9916. 161, /* num_n_bits */
  9917. {BYTES_TO_WORDS_8(FF, FF, FF, 7F, FF, FF, FF, FF),
  9918. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  9919. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  9920. {BYTES_TO_WORDS_8(57, 22, 75, CA, D3, AE, 27, F9),
  9921. BYTES_TO_WORDS_8(C8, F4, 01, 00, 00, 00, 00, 00),
  9922. BYTES_TO_WORDS_8(00, 00, 00, 00, 01, 00, 00, 00)},
  9923. {BYTES_TO_WORDS_8(82, FC, CB, 13, B9, 8B, C3, 68),
  9924. BYTES_TO_WORDS_8(89, 69, 64, 46, 28, 73, F5, 8E),
  9925. BYTES_TO_WORDS_4(68, B5, 96, 4A),
  9926. BYTES_TO_WORDS_8(32, FB, C5, 7A, 37, 51, 23, 04),
  9927. BYTES_TO_WORDS_8(12, C9, DC, 59, 7D, 94, 68, 31),
  9928. BYTES_TO_WORDS_4(55, 28, A6, 23)},
  9929. {BYTES_TO_WORDS_8(45, FA, 65, C5, AD, D4, D4, 81),
  9930. BYTES_TO_WORDS_8(9F, F8, AC, 65, 8B, 7A, BD, 54),
  9931. BYTES_TO_WORDS_4(FC, BE, 97, 1C)},
  9932. &double_jacobian_default,
  9933. #if uECC_SUPPORT_COMPRESSED_POINT
  9934. &mod_sqrt_default,
  9935. #endif
  9936. &x_side_default,
  9937. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9938. &vli_mmod_fast_secp160r1
  9939. #endif
  9940. };
  9941. uECC_Curve uECC_secp160r1(void) {
  9942. return &curve_secp160r1;
  9943. }
  9944. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1)
  9945. /* Computes result = product % curve_p
  9946. see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
  9947. Note that this only works if log2(omega) < log2(p) / 2 */
  9948. static void omega_mult_secp160r1(uECC_word_t *result, const uECC_word_t *right);
  9949. #if uECC_WORD_SIZE == 8
  9950. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product) {
  9951. uECC_word_t tmp[2 * num_words_secp160r1];
  9952. uECC_word_t copy;
  9953. uECC_vli_clear(tmp, num_words_secp160r1);
  9954. uECC_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  9955. omega_mult_secp160r1(tmp,
  9956. product + num_words_secp160r1 - 1); /* (Rq, q) = q * c */
  9957. product[num_words_secp160r1 - 1] &= 0xffffffff;
  9958. copy = tmp[num_words_secp160r1 - 1];
  9959. tmp[num_words_secp160r1 - 1] &= 0xffffffff;
  9960. uECC_vli_add(result, product, tmp, num_words_secp160r1); /* (C, r) = r + q */
  9961. uECC_vli_clear(product, num_words_secp160r1);
  9962. tmp[num_words_secp160r1 - 1] = copy;
  9963. omega_mult_secp160r1(product, tmp + num_words_secp160r1 - 1); /* Rq*c */
  9964. uECC_vli_add(result, result, product,
  9965. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  9966. while (uECC_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) >
  9967. 0) {
  9968. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  9969. }
  9970. }
  9971. static void omega_mult_secp160r1(uint64_t *result, const uint64_t *right) {
  9972. uint32_t carry;
  9973. unsigned i;
  9974. /* Multiply by (2^31 + 1). */
  9975. carry = 0;
  9976. for (i = 0; i < num_words_secp160r1; ++i) {
  9977. uint64_t tmp = (right[i] >> 32) | (right[i + 1] << 32);
  9978. result[i] = (tmp << 31) + tmp + carry;
  9979. carry = (tmp >> 33) + (result[i] < tmp || (carry && result[i] == tmp));
  9980. }
  9981. result[i] = carry;
  9982. }
  9983. #else
  9984. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product) {
  9985. uECC_word_t tmp[2 * num_words_secp160r1];
  9986. uECC_word_t carry;
  9987. uECC_vli_clear(tmp, num_words_secp160r1);
  9988. uECC_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  9989. omega_mult_secp160r1(tmp,
  9990. product + num_words_secp160r1); /* (Rq, q) = q * c */
  9991. carry = uECC_vli_add(result, product, tmp,
  9992. num_words_secp160r1); /* (C, r) = r + q */
  9993. uECC_vli_clear(product, num_words_secp160r1);
  9994. omega_mult_secp160r1(product, tmp + num_words_secp160r1); /* Rq*c */
  9995. carry += uECC_vli_add(result, result, product,
  9996. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  9997. while (carry > 0) {
  9998. --carry;
  9999. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  10000. }
  10001. if (uECC_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) > 0) {
  10002. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  10003. }
  10004. }
  10005. #endif
  10006. #if uECC_WORD_SIZE == 1
  10007. static void omega_mult_secp160r1(uint8_t *result, const uint8_t *right) {
  10008. uint8_t carry;
  10009. uint8_t i;
  10010. /* Multiply by (2^31 + 1). */
  10011. uECC_vli_set(result + 4, right, num_words_secp160r1); /* 2^32 */
  10012. uECC_vli_rshift1(result + 4, num_words_secp160r1); /* 2^31 */
  10013. result[3] = right[0] << 7; /* get last bit from shift */
  10014. carry =
  10015. uECC_vli_add(result, result, right, num_words_secp160r1); /* 2^31 + 1 */
  10016. for (i = num_words_secp160r1; carry; ++i) {
  10017. uint16_t sum = (uint16_t) result[i] + carry;
  10018. result[i] = (uint8_t) sum;
  10019. carry = sum >> 8;
  10020. }
  10021. }
  10022. #elif uECC_WORD_SIZE == 4
  10023. static void omega_mult_secp160r1(uint32_t *result, const uint32_t *right) {
  10024. uint32_t carry;
  10025. unsigned i;
  10026. /* Multiply by (2^31 + 1). */
  10027. uECC_vli_set(result + 1, right, num_words_secp160r1); /* 2^32 */
  10028. uECC_vli_rshift1(result + 1, num_words_secp160r1); /* 2^31 */
  10029. result[0] = right[0] << 31; /* get last bit from shift */
  10030. carry =
  10031. uECC_vli_add(result, result, right, num_words_secp160r1); /* 2^31 + 1 */
  10032. for (i = num_words_secp160r1; carry; ++i) {
  10033. uint64_t sum = (uint64_t) result[i] + carry;
  10034. result[i] = (uint32_t) sum;
  10035. carry = sum >> 32;
  10036. }
  10037. }
  10038. #endif /* uECC_WORD_SIZE */
  10039. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) */
  10040. #endif /* uECC_SUPPORTS_secp160r1 */
  10041. #if uECC_SUPPORTS_secp192r1
  10042. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10043. static void vli_mmod_fast_secp192r1(uECC_word_t *result, uECC_word_t *product);
  10044. #endif
  10045. static const struct uECC_Curve_t curve_secp192r1 = {
  10046. num_words_secp192r1,
  10047. num_bytes_secp192r1,
  10048. 192, /* num_n_bits */
  10049. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10050. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  10051. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  10052. {BYTES_TO_WORDS_8(31, 28, D2, B4, B1, C9, 6B, 14),
  10053. BYTES_TO_WORDS_8(36, F8, DE, 99, FF, FF, FF, FF),
  10054. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  10055. {BYTES_TO_WORDS_8(12, 10, FF, 82, FD, 0A, FF, F4),
  10056. BYTES_TO_WORDS_8(00, 88, A1, 43, EB, 20, BF, 7C),
  10057. BYTES_TO_WORDS_8(F6, 90, 30, B0, 0E, A8, 8D, 18),
  10058. BYTES_TO_WORDS_8(11, 48, 79, 1E, A1, 77, F9, 73),
  10059. BYTES_TO_WORDS_8(D5, CD, 24, 6B, ED, 11, 10, 63),
  10060. BYTES_TO_WORDS_8(78, DA, C8, FF, 95, 2B, 19, 07)},
  10061. {BYTES_TO_WORDS_8(B1, B9, 46, C1, EC, DE, B8, FE),
  10062. BYTES_TO_WORDS_8(49, 30, 24, 72, AB, E9, A7, 0F),
  10063. BYTES_TO_WORDS_8(E7, 80, 9C, E5, 19, 05, 21, 64)},
  10064. &double_jacobian_default,
  10065. #if uECC_SUPPORT_COMPRESSED_POINT
  10066. &mod_sqrt_default,
  10067. #endif
  10068. &x_side_default,
  10069. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10070. &vli_mmod_fast_secp192r1
  10071. #endif
  10072. };
  10073. uECC_Curve uECC_secp192r1(void) {
  10074. return &curve_secp192r1;
  10075. }
  10076. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10077. /* Computes result = product % curve_p.
  10078. See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf
  10079. */
  10080. #if uECC_WORD_SIZE == 1
  10081. static void vli_mmod_fast_secp192r1(uint8_t *result, uint8_t *product) {
  10082. uint8_t tmp[num_words_secp192r1];
  10083. uint8_t carry;
  10084. uECC_vli_set(result, product, num_words_secp192r1);
  10085. uECC_vli_set(tmp, &product[24], num_words_secp192r1);
  10086. carry = uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10087. tmp[0] = tmp[1] = tmp[2] = tmp[3] = tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10088. tmp[8] = product[24];
  10089. tmp[9] = product[25];
  10090. tmp[10] = product[26];
  10091. tmp[11] = product[27];
  10092. tmp[12] = product[28];
  10093. tmp[13] = product[29];
  10094. tmp[14] = product[30];
  10095. tmp[15] = product[31];
  10096. tmp[16] = product[32];
  10097. tmp[17] = product[33];
  10098. tmp[18] = product[34];
  10099. tmp[19] = product[35];
  10100. tmp[20] = product[36];
  10101. tmp[21] = product[37];
  10102. tmp[22] = product[38];
  10103. tmp[23] = product[39];
  10104. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10105. tmp[0] = tmp[8] = product[40];
  10106. tmp[1] = tmp[9] = product[41];
  10107. tmp[2] = tmp[10] = product[42];
  10108. tmp[3] = tmp[11] = product[43];
  10109. tmp[4] = tmp[12] = product[44];
  10110. tmp[5] = tmp[13] = product[45];
  10111. tmp[6] = tmp[14] = product[46];
  10112. tmp[7] = tmp[15] = product[47];
  10113. tmp[16] = tmp[17] = tmp[18] = tmp[19] = tmp[20] = tmp[21] = tmp[22] =
  10114. tmp[23] = 0;
  10115. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10116. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10117. num_words_secp192r1) != 1) {
  10118. carry -=
  10119. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10120. }
  10121. }
  10122. #elif uECC_WORD_SIZE == 4
  10123. static void vli_mmod_fast_secp192r1(uint32_t *result, uint32_t *product) {
  10124. uint32_t tmp[num_words_secp192r1];
  10125. int carry;
  10126. uECC_vli_set(result, product, num_words_secp192r1);
  10127. uECC_vli_set(tmp, &product[6], num_words_secp192r1);
  10128. carry = uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10129. tmp[0] = tmp[1] = 0;
  10130. tmp[2] = product[6];
  10131. tmp[3] = product[7];
  10132. tmp[4] = product[8];
  10133. tmp[5] = product[9];
  10134. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10135. tmp[0] = tmp[2] = product[10];
  10136. tmp[1] = tmp[3] = product[11];
  10137. tmp[4] = tmp[5] = 0;
  10138. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10139. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10140. num_words_secp192r1) != 1) {
  10141. carry -=
  10142. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10143. }
  10144. }
  10145. #else
  10146. static void vli_mmod_fast_secp192r1(uint64_t *result, uint64_t *product) {
  10147. uint64_t tmp[num_words_secp192r1];
  10148. int carry;
  10149. uECC_vli_set(result, product, num_words_secp192r1);
  10150. uECC_vli_set(tmp, &product[3], num_words_secp192r1);
  10151. carry = (int) uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10152. tmp[0] = 0;
  10153. tmp[1] = product[3];
  10154. tmp[2] = product[4];
  10155. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10156. tmp[0] = tmp[1] = product[5];
  10157. tmp[2] = 0;
  10158. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10159. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10160. num_words_secp192r1) != 1) {
  10161. carry -=
  10162. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10163. }
  10164. }
  10165. #endif /* uECC_WORD_SIZE */
  10166. #endif /* (uECC_OPTIMIZATION_LEVEL > 0) */
  10167. #endif /* uECC_SUPPORTS_secp192r1 */
  10168. #if uECC_SUPPORTS_secp224r1
  10169. #if uECC_SUPPORT_COMPRESSED_POINT
  10170. static void mod_sqrt_secp224r1(uECC_word_t *a, uECC_Curve curve);
  10171. #endif
  10172. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10173. static void vli_mmod_fast_secp224r1(uECC_word_t *result, uECC_word_t *product);
  10174. #endif
  10175. static const struct uECC_Curve_t curve_secp224r1 = {
  10176. num_words_secp224r1,
  10177. num_bytes_secp224r1,
  10178. 224, /* num_n_bits */
  10179. {BYTES_TO_WORDS_8(01, 00, 00, 00, 00, 00, 00, 00),
  10180. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF),
  10181. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10182. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  10183. {BYTES_TO_WORDS_8(3D, 2A, 5C, 5C, 45, 29, DD, 13),
  10184. BYTES_TO_WORDS_8(3E, F0, B8, E0, A2, 16, FF, FF),
  10185. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10186. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  10187. {BYTES_TO_WORDS_8(21, 1D, 5C, 11, D6, 80, 32, 34),
  10188. BYTES_TO_WORDS_8(22, 11, C2, 56, D3, C1, 03, 4A),
  10189. BYTES_TO_WORDS_8(B9, 90, 13, 32, 7F, BF, B4, 6B),
  10190. BYTES_TO_WORDS_4(BD, 0C, 0E, B7),
  10191. BYTES_TO_WORDS_8(34, 7E, 00, 85, 99, 81, D5, 44),
  10192. BYTES_TO_WORDS_8(64, 47, 07, 5A, A0, 75, 43, CD),
  10193. BYTES_TO_WORDS_8(E6, DF, 22, 4C, FB, 23, F7, B5),
  10194. BYTES_TO_WORDS_4(88, 63, 37, BD)},
  10195. {BYTES_TO_WORDS_8(B4, FF, 55, 23, 43, 39, 0B, 27),
  10196. BYTES_TO_WORDS_8(BA, D8, BF, D7, B7, B0, 44, 50),
  10197. BYTES_TO_WORDS_8(56, 32, 41, F5, AB, B3, 04, 0C),
  10198. BYTES_TO_WORDS_4(85, 0A, 05, B4)},
  10199. &double_jacobian_default,
  10200. #if uECC_SUPPORT_COMPRESSED_POINT
  10201. &mod_sqrt_secp224r1,
  10202. #endif
  10203. &x_side_default,
  10204. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10205. &vli_mmod_fast_secp224r1
  10206. #endif
  10207. };
  10208. uECC_Curve uECC_secp224r1(void) {
  10209. return &curve_secp224r1;
  10210. }
  10211. #if uECC_SUPPORT_COMPRESSED_POINT
  10212. /* Routine 3.2.4 RS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10213. static void mod_sqrt_secp224r1_rs(uECC_word_t *d1, uECC_word_t *e1,
  10214. uECC_word_t *f1, const uECC_word_t *d0,
  10215. const uECC_word_t *e0,
  10216. const uECC_word_t *f0) {
  10217. uECC_word_t t[num_words_secp224r1];
  10218. uECC_vli_modSquare_fast(t, d0, &curve_secp224r1); /* t <-- d0 ^ 2 */
  10219. uECC_vli_modMult_fast(e1, d0, e0, &curve_secp224r1); /* e1 <-- d0 * e0 */
  10220. uECC_vli_modAdd(d1, t, f0, curve_secp224r1.p,
  10221. num_words_secp224r1); /* d1 <-- t + f0 */
  10222. uECC_vli_modAdd(e1, e1, e1, curve_secp224r1.p,
  10223. num_words_secp224r1); /* e1 <-- e1 + e1 */
  10224. uECC_vli_modMult_fast(f1, t, f0, &curve_secp224r1); /* f1 <-- t * f0 */
  10225. uECC_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  10226. num_words_secp224r1); /* f1 <-- f1 + f1 */
  10227. uECC_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  10228. num_words_secp224r1); /* f1 <-- f1 + f1 */
  10229. }
  10230. /* Routine 3.2.5 RSS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10231. static void mod_sqrt_secp224r1_rss(uECC_word_t *d1, uECC_word_t *e1,
  10232. uECC_word_t *f1, const uECC_word_t *d0,
  10233. const uECC_word_t *e0, const uECC_word_t *f0,
  10234. const bitcount_t j) {
  10235. bitcount_t i;
  10236. uECC_vli_set(d1, d0, num_words_secp224r1); /* d1 <-- d0 */
  10237. uECC_vli_set(e1, e0, num_words_secp224r1); /* e1 <-- e0 */
  10238. uECC_vli_set(f1, f0, num_words_secp224r1); /* f1 <-- f0 */
  10239. for (i = 1; i <= j; i++) {
  10240. mod_sqrt_secp224r1_rs(d1, e1, f1, d1, e1, f1); /* RS (d1,e1,f1,d1,e1,f1) */
  10241. }
  10242. }
  10243. /* Routine 3.2.6 RM; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10244. static void mod_sqrt_secp224r1_rm(uECC_word_t *d2, uECC_word_t *e2,
  10245. uECC_word_t *f2, const uECC_word_t *c,
  10246. const uECC_word_t *d0, const uECC_word_t *e0,
  10247. const uECC_word_t *d1,
  10248. const uECC_word_t *e1) {
  10249. uECC_word_t t1[num_words_secp224r1];
  10250. uECC_word_t t2[num_words_secp224r1];
  10251. uECC_vli_modMult_fast(t1, e0, e1, &curve_secp224r1); /* t1 <-- e0 * e1 */
  10252. uECC_vli_modMult_fast(t1, t1, c, &curve_secp224r1); /* t1 <-- t1 * c */
  10253. /* t1 <-- p - t1 */
  10254. uECC_vli_modSub(t1, curve_secp224r1.p, t1, curve_secp224r1.p,
  10255. num_words_secp224r1);
  10256. uECC_vli_modMult_fast(t2, d0, d1, &curve_secp224r1); /* t2 <-- d0 * d1 */
  10257. uECC_vli_modAdd(t2, t2, t1, curve_secp224r1.p,
  10258. num_words_secp224r1); /* t2 <-- t2 + t1 */
  10259. uECC_vli_modMult_fast(t1, d0, e1, &curve_secp224r1); /* t1 <-- d0 * e1 */
  10260. uECC_vli_modMult_fast(e2, d1, e0, &curve_secp224r1); /* e2 <-- d1 * e0 */
  10261. uECC_vli_modAdd(e2, e2, t1, curve_secp224r1.p,
  10262. num_words_secp224r1); /* e2 <-- e2 + t1 */
  10263. uECC_vli_modSquare_fast(f2, e2, &curve_secp224r1); /* f2 <-- e2^2 */
  10264. uECC_vli_modMult_fast(f2, f2, c, &curve_secp224r1); /* f2 <-- f2 * c */
  10265. /* f2 <-- p - f2 */
  10266. uECC_vli_modSub(f2, curve_secp224r1.p, f2, curve_secp224r1.p,
  10267. num_words_secp224r1);
  10268. uECC_vli_set(d2, t2, num_words_secp224r1); /* d2 <-- t2 */
  10269. }
  10270. /* Routine 3.2.7 RP; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10271. static void mod_sqrt_secp224r1_rp(uECC_word_t *d1, uECC_word_t *e1,
  10272. uECC_word_t *f1, const uECC_word_t *c,
  10273. const uECC_word_t *r) {
  10274. wordcount_t i;
  10275. wordcount_t pow2i = 1;
  10276. uECC_word_t d0[num_words_secp224r1];
  10277. uECC_word_t e0[num_words_secp224r1] = {1}; /* e0 <-- 1 */
  10278. uECC_word_t f0[num_words_secp224r1];
  10279. uECC_vli_set(d0, r, num_words_secp224r1); /* d0 <-- r */
  10280. /* f0 <-- p - c */
  10281. uECC_vli_modSub(f0, curve_secp224r1.p, c, curve_secp224r1.p,
  10282. num_words_secp224r1);
  10283. for (i = 0; i <= 6; i++) {
  10284. mod_sqrt_secp224r1_rss(d1, e1, f1, d0, e0, f0,
  10285. pow2i); /* RSS (d1,e1,f1,d0,e0,f0,2^i) */
  10286. mod_sqrt_secp224r1_rm(d1, e1, f1, c, d1, e1, d0,
  10287. e0); /* RM (d1,e1,f1,c,d1,e1,d0,e0) */
  10288. uECC_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  10289. uECC_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  10290. uECC_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  10291. pow2i *= 2;
  10292. }
  10293. }
  10294. /* Compute a = sqrt(a) (mod curve_p). */
  10295. /* Routine 3.2.8 mp_mod_sqrt_224; from
  10296. * http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10297. static void mod_sqrt_secp224r1(uECC_word_t *a, uECC_Curve curve) {
  10298. (void) curve;
  10299. bitcount_t i;
  10300. uECC_word_t e1[num_words_secp224r1];
  10301. uECC_word_t f1[num_words_secp224r1];
  10302. uECC_word_t d0[num_words_secp224r1];
  10303. uECC_word_t e0[num_words_secp224r1];
  10304. uECC_word_t f0[num_words_secp224r1];
  10305. uECC_word_t d1[num_words_secp224r1];
  10306. /* s = a; using constant instead of random value */
  10307. mod_sqrt_secp224r1_rp(d0, e0, f0, a, a); /* RP (d0, e0, f0, c, s) */
  10308. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  10309. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  10310. for (i = 1; i <= 95; i++) {
  10311. uECC_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  10312. uECC_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  10313. uECC_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  10314. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  10315. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  10316. if (uECC_vli_isZero(d1, num_words_secp224r1)) { /* if d1 == 0 */
  10317. break;
  10318. }
  10319. }
  10320. uECC_vli_modInv(f1, e0, curve_secp224r1.p,
  10321. num_words_secp224r1); /* f1 <-- 1 / e0 */
  10322. uECC_vli_modMult_fast(a, d0, f1, &curve_secp224r1); /* a <-- d0 / e0 */
  10323. }
  10324. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  10325. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10326. /* Computes result = product % curve_p
  10327. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10328. #if uECC_WORD_SIZE == 1
  10329. static void vli_mmod_fast_secp224r1(uint8_t *result, uint8_t *product) {
  10330. uint8_t tmp[num_words_secp224r1];
  10331. int8_t carry;
  10332. /* t */
  10333. uECC_vli_set(result, product, num_words_secp224r1);
  10334. /* s1 */
  10335. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  10336. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10337. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10338. tmp[12] = product[28];
  10339. tmp[13] = product[29];
  10340. tmp[14] = product[30];
  10341. tmp[15] = product[31];
  10342. tmp[16] = product[32];
  10343. tmp[17] = product[33];
  10344. tmp[18] = product[34];
  10345. tmp[19] = product[35];
  10346. tmp[20] = product[36];
  10347. tmp[21] = product[37];
  10348. tmp[22] = product[38];
  10349. tmp[23] = product[39];
  10350. tmp[24] = product[40];
  10351. tmp[25] = product[41];
  10352. tmp[26] = product[42];
  10353. tmp[27] = product[43];
  10354. carry = uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10355. /* s2 */
  10356. tmp[12] = product[44];
  10357. tmp[13] = product[45];
  10358. tmp[14] = product[46];
  10359. tmp[15] = product[47];
  10360. tmp[16] = product[48];
  10361. tmp[17] = product[49];
  10362. tmp[18] = product[50];
  10363. tmp[19] = product[51];
  10364. tmp[20] = product[52];
  10365. tmp[21] = product[53];
  10366. tmp[22] = product[54];
  10367. tmp[23] = product[55];
  10368. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10369. carry += uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10370. /* d1 */
  10371. tmp[0] = product[28];
  10372. tmp[1] = product[29];
  10373. tmp[2] = product[30];
  10374. tmp[3] = product[31];
  10375. tmp[4] = product[32];
  10376. tmp[5] = product[33];
  10377. tmp[6] = product[34];
  10378. tmp[7] = product[35];
  10379. tmp[8] = product[36];
  10380. tmp[9] = product[37];
  10381. tmp[10] = product[38];
  10382. tmp[11] = product[39];
  10383. tmp[12] = product[40];
  10384. tmp[13] = product[41];
  10385. tmp[14] = product[42];
  10386. tmp[15] = product[43];
  10387. tmp[16] = product[44];
  10388. tmp[17] = product[45];
  10389. tmp[18] = product[46];
  10390. tmp[19] = product[47];
  10391. tmp[20] = product[48];
  10392. tmp[21] = product[49];
  10393. tmp[22] = product[50];
  10394. tmp[23] = product[51];
  10395. tmp[24] = product[52];
  10396. tmp[25] = product[53];
  10397. tmp[26] = product[54];
  10398. tmp[27] = product[55];
  10399. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10400. /* d2 */
  10401. tmp[0] = product[44];
  10402. tmp[1] = product[45];
  10403. tmp[2] = product[46];
  10404. tmp[3] = product[47];
  10405. tmp[4] = product[48];
  10406. tmp[5] = product[49];
  10407. tmp[6] = product[50];
  10408. tmp[7] = product[51];
  10409. tmp[8] = product[52];
  10410. tmp[9] = product[53];
  10411. tmp[10] = product[54];
  10412. tmp[11] = product[55];
  10413. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10414. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10415. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10416. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10417. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10418. if (carry < 0) {
  10419. do {
  10420. carry +=
  10421. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10422. } while (carry < 0);
  10423. } else {
  10424. while (carry || uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10425. num_words_secp224r1) != 1) {
  10426. carry -=
  10427. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10428. }
  10429. }
  10430. }
  10431. #elif uECC_WORD_SIZE == 4
  10432. static void vli_mmod_fast_secp224r1(uint32_t *result, uint32_t *product) {
  10433. uint32_t tmp[num_words_secp224r1];
  10434. int carry;
  10435. /* t */
  10436. uECC_vli_set(result, product, num_words_secp224r1);
  10437. /* s1 */
  10438. tmp[0] = tmp[1] = tmp[2] = 0;
  10439. tmp[3] = product[7];
  10440. tmp[4] = product[8];
  10441. tmp[5] = product[9];
  10442. tmp[6] = product[10];
  10443. carry = uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10444. /* s2 */
  10445. tmp[3] = product[11];
  10446. tmp[4] = product[12];
  10447. tmp[5] = product[13];
  10448. tmp[6] = 0;
  10449. carry += uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10450. /* d1 */
  10451. tmp[0] = product[7];
  10452. tmp[1] = product[8];
  10453. tmp[2] = product[9];
  10454. tmp[3] = product[10];
  10455. tmp[4] = product[11];
  10456. tmp[5] = product[12];
  10457. tmp[6] = product[13];
  10458. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10459. /* d2 */
  10460. tmp[0] = product[11];
  10461. tmp[1] = product[12];
  10462. tmp[2] = product[13];
  10463. tmp[3] = tmp[4] = tmp[5] = tmp[6] = 0;
  10464. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10465. if (carry < 0) {
  10466. do {
  10467. carry +=
  10468. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10469. } while (carry < 0);
  10470. } else {
  10471. while (carry || uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10472. num_words_secp224r1) != 1) {
  10473. carry -=
  10474. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10475. }
  10476. }
  10477. }
  10478. #else
  10479. static void vli_mmod_fast_secp224r1(uint64_t *result, uint64_t *product) {
  10480. uint64_t tmp[num_words_secp224r1];
  10481. int carry = 0;
  10482. /* t */
  10483. uECC_vli_set(result, product, num_words_secp224r1);
  10484. result[num_words_secp224r1 - 1] &= 0xffffffff;
  10485. /* s1 */
  10486. tmp[0] = 0;
  10487. tmp[1] = product[3] & 0xffffffff00000000ull;
  10488. tmp[2] = product[4];
  10489. tmp[3] = product[5] & 0xffffffff;
  10490. uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10491. /* s2 */
  10492. tmp[1] = product[5] & 0xffffffff00000000ull;
  10493. tmp[2] = product[6];
  10494. tmp[3] = 0;
  10495. uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10496. /* d1 */
  10497. tmp[0] = (product[3] >> 32) | (product[4] << 32);
  10498. tmp[1] = (product[4] >> 32) | (product[5] << 32);
  10499. tmp[2] = (product[5] >> 32) | (product[6] << 32);
  10500. tmp[3] = product[6] >> 32;
  10501. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10502. /* d2 */
  10503. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  10504. tmp[1] = product[6] >> 32;
  10505. tmp[2] = tmp[3] = 0;
  10506. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10507. if (carry < 0) {
  10508. do {
  10509. carry +=
  10510. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10511. } while (carry < 0);
  10512. } else {
  10513. while (uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10514. num_words_secp224r1) != 1) {
  10515. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10516. }
  10517. }
  10518. }
  10519. #endif /* uECC_WORD_SIZE */
  10520. #endif /* (uECC_OPTIMIZATION_LEVEL > 0) */
  10521. #endif /* uECC_SUPPORTS_secp224r1 */
  10522. #if uECC_SUPPORTS_secp256r1
  10523. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10524. static void vli_mmod_fast_secp256r1(uECC_word_t *result, uECC_word_t *product);
  10525. #endif
  10526. static const struct uECC_Curve_t curve_secp256r1 = {
  10527. num_words_secp256r1,
  10528. num_bytes_secp256r1,
  10529. 256, /* num_n_bits */
  10530. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10531. BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00),
  10532. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  10533. BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF)},
  10534. {BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3),
  10535. BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC),
  10536. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10537. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF)},
  10538. {BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4),
  10539. BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77),
  10540. BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8),
  10541. BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B),
  10542. BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB),
  10543. BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B),
  10544. BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E),
  10545. BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F)},
  10546. {BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B),
  10547. BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65),
  10548. BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3),
  10549. BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A)},
  10550. &double_jacobian_default,
  10551. #if uECC_SUPPORT_COMPRESSED_POINT
  10552. &mod_sqrt_default,
  10553. #endif
  10554. &x_side_default,
  10555. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10556. &vli_mmod_fast_secp256r1
  10557. #endif
  10558. };
  10559. uECC_Curve uECC_secp256r1(void) {
  10560. return &curve_secp256r1;
  10561. }
  10562. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1)
  10563. /* Computes result = product % curve_p
  10564. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10565. #if uECC_WORD_SIZE == 1
  10566. static void vli_mmod_fast_secp256r1(uint8_t *result, uint8_t *product) {
  10567. uint8_t tmp[num_words_secp256r1];
  10568. int8_t carry;
  10569. /* t */
  10570. uECC_vli_set(result, product, num_words_secp256r1);
  10571. /* s1 */
  10572. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  10573. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10574. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10575. tmp[12] = product[44];
  10576. tmp[13] = product[45];
  10577. tmp[14] = product[46];
  10578. tmp[15] = product[47];
  10579. tmp[16] = product[48];
  10580. tmp[17] = product[49];
  10581. tmp[18] = product[50];
  10582. tmp[19] = product[51];
  10583. tmp[20] = product[52];
  10584. tmp[21] = product[53];
  10585. tmp[22] = product[54];
  10586. tmp[23] = product[55];
  10587. tmp[24] = product[56];
  10588. tmp[25] = product[57];
  10589. tmp[26] = product[58];
  10590. tmp[27] = product[59];
  10591. tmp[28] = product[60];
  10592. tmp[29] = product[61];
  10593. tmp[30] = product[62];
  10594. tmp[31] = product[63];
  10595. carry = uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10596. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10597. /* s2 */
  10598. tmp[12] = product[48];
  10599. tmp[13] = product[49];
  10600. tmp[14] = product[50];
  10601. tmp[15] = product[51];
  10602. tmp[16] = product[52];
  10603. tmp[17] = product[53];
  10604. tmp[18] = product[54];
  10605. tmp[19] = product[55];
  10606. tmp[20] = product[56];
  10607. tmp[21] = product[57];
  10608. tmp[22] = product[58];
  10609. tmp[23] = product[59];
  10610. tmp[24] = product[60];
  10611. tmp[25] = product[61];
  10612. tmp[26] = product[62];
  10613. tmp[27] = product[63];
  10614. tmp[28] = tmp[29] = tmp[30] = tmp[31] = 0;
  10615. carry += uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10616. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10617. /* s3 */
  10618. tmp[0] = product[32];
  10619. tmp[1] = product[33];
  10620. tmp[2] = product[34];
  10621. tmp[3] = product[35];
  10622. tmp[4] = product[36];
  10623. tmp[5] = product[37];
  10624. tmp[6] = product[38];
  10625. tmp[7] = product[39];
  10626. tmp[8] = product[40];
  10627. tmp[9] = product[41];
  10628. tmp[10] = product[42];
  10629. tmp[11] = product[43];
  10630. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10631. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10632. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10633. tmp[24] = product[56];
  10634. tmp[25] = product[57];
  10635. tmp[26] = product[58];
  10636. tmp[27] = product[59];
  10637. tmp[28] = product[60];
  10638. tmp[29] = product[61];
  10639. tmp[30] = product[62];
  10640. tmp[31] = product[63];
  10641. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10642. /* s4 */
  10643. tmp[0] = product[36];
  10644. tmp[1] = product[37];
  10645. tmp[2] = product[38];
  10646. tmp[3] = product[39];
  10647. tmp[4] = product[40];
  10648. tmp[5] = product[41];
  10649. tmp[6] = product[42];
  10650. tmp[7] = product[43];
  10651. tmp[8] = product[44];
  10652. tmp[9] = product[45];
  10653. tmp[10] = product[46];
  10654. tmp[11] = product[47];
  10655. tmp[12] = product[52];
  10656. tmp[13] = product[53];
  10657. tmp[14] = product[54];
  10658. tmp[15] = product[55];
  10659. tmp[16] = product[56];
  10660. tmp[17] = product[57];
  10661. tmp[18] = product[58];
  10662. tmp[19] = product[59];
  10663. tmp[20] = product[60];
  10664. tmp[21] = product[61];
  10665. tmp[22] = product[62];
  10666. tmp[23] = product[63];
  10667. tmp[24] = product[52];
  10668. tmp[25] = product[53];
  10669. tmp[26] = product[54];
  10670. tmp[27] = product[55];
  10671. tmp[28] = product[32];
  10672. tmp[29] = product[33];
  10673. tmp[30] = product[34];
  10674. tmp[31] = product[35];
  10675. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10676. /* d1 */
  10677. tmp[0] = product[44];
  10678. tmp[1] = product[45];
  10679. tmp[2] = product[46];
  10680. tmp[3] = product[47];
  10681. tmp[4] = product[48];
  10682. tmp[5] = product[49];
  10683. tmp[6] = product[50];
  10684. tmp[7] = product[51];
  10685. tmp[8] = product[52];
  10686. tmp[9] = product[53];
  10687. tmp[10] = product[54];
  10688. tmp[11] = product[55];
  10689. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10690. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10691. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10692. tmp[24] = product[32];
  10693. tmp[25] = product[33];
  10694. tmp[26] = product[34];
  10695. tmp[27] = product[35];
  10696. tmp[28] = product[40];
  10697. tmp[29] = product[41];
  10698. tmp[30] = product[42];
  10699. tmp[31] = product[43];
  10700. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10701. /* d2 */
  10702. tmp[0] = product[48];
  10703. tmp[1] = product[49];
  10704. tmp[2] = product[50];
  10705. tmp[3] = product[51];
  10706. tmp[4] = product[52];
  10707. tmp[5] = product[53];
  10708. tmp[6] = product[54];
  10709. tmp[7] = product[55];
  10710. tmp[8] = product[56];
  10711. tmp[9] = product[57];
  10712. tmp[10] = product[58];
  10713. tmp[11] = product[59];
  10714. tmp[12] = product[60];
  10715. tmp[13] = product[61];
  10716. tmp[14] = product[62];
  10717. tmp[15] = product[63];
  10718. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10719. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10720. tmp[24] = product[36];
  10721. tmp[25] = product[37];
  10722. tmp[26] = product[38];
  10723. tmp[27] = product[39];
  10724. tmp[28] = product[44];
  10725. tmp[29] = product[45];
  10726. tmp[30] = product[46];
  10727. tmp[31] = product[47];
  10728. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10729. /* d3 */
  10730. tmp[0] = product[52];
  10731. tmp[1] = product[53];
  10732. tmp[2] = product[54];
  10733. tmp[3] = product[55];
  10734. tmp[4] = product[56];
  10735. tmp[5] = product[57];
  10736. tmp[6] = product[58];
  10737. tmp[7] = product[59];
  10738. tmp[8] = product[60];
  10739. tmp[9] = product[61];
  10740. tmp[10] = product[62];
  10741. tmp[11] = product[63];
  10742. tmp[12] = product[32];
  10743. tmp[13] = product[33];
  10744. tmp[14] = product[34];
  10745. tmp[15] = product[35];
  10746. tmp[16] = product[36];
  10747. tmp[17] = product[37];
  10748. tmp[18] = product[38];
  10749. tmp[19] = product[39];
  10750. tmp[20] = product[40];
  10751. tmp[21] = product[41];
  10752. tmp[22] = product[42];
  10753. tmp[23] = product[43];
  10754. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10755. tmp[28] = product[48];
  10756. tmp[29] = product[49];
  10757. tmp[30] = product[50];
  10758. tmp[31] = product[51];
  10759. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10760. /* d4 */
  10761. tmp[0] = product[56];
  10762. tmp[1] = product[57];
  10763. tmp[2] = product[58];
  10764. tmp[3] = product[59];
  10765. tmp[4] = product[60];
  10766. tmp[5] = product[61];
  10767. tmp[6] = product[62];
  10768. tmp[7] = product[63];
  10769. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10770. tmp[12] = product[36];
  10771. tmp[13] = product[37];
  10772. tmp[14] = product[38];
  10773. tmp[15] = product[39];
  10774. tmp[16] = product[40];
  10775. tmp[17] = product[41];
  10776. tmp[18] = product[42];
  10777. tmp[19] = product[43];
  10778. tmp[20] = product[44];
  10779. tmp[21] = product[45];
  10780. tmp[22] = product[46];
  10781. tmp[23] = product[47];
  10782. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10783. tmp[28] = product[52];
  10784. tmp[29] = product[53];
  10785. tmp[30] = product[54];
  10786. tmp[31] = product[55];
  10787. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10788. if (carry < 0) {
  10789. do {
  10790. carry +=
  10791. uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10792. } while (carry < 0);
  10793. } else {
  10794. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10795. num_words_secp256r1) != 1) {
  10796. carry -=
  10797. uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10798. }
  10799. }
  10800. }
  10801. #elif uECC_WORD_SIZE == 4
  10802. static void vli_mmod_fast_secp256r1(uint32_t *result, uint32_t *product) {
  10803. uint32_t tmp[num_words_secp256r1];
  10804. int carry;
  10805. /* t */
  10806. uECC_vli_set(result, product, num_words_secp256r1);
  10807. /* s1 */
  10808. tmp[0] = tmp[1] = tmp[2] = 0;
  10809. tmp[3] = product[11];
  10810. tmp[4] = product[12];
  10811. tmp[5] = product[13];
  10812. tmp[6] = product[14];
  10813. tmp[7] = product[15];
  10814. carry = (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10815. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10816. /* s2 */
  10817. tmp[3] = product[12];
  10818. tmp[4] = product[13];
  10819. tmp[5] = product[14];
  10820. tmp[6] = product[15];
  10821. tmp[7] = 0;
  10822. carry += (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10823. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10824. /* s3 */
  10825. tmp[0] = product[8];
  10826. tmp[1] = product[9];
  10827. tmp[2] = product[10];
  10828. tmp[3] = tmp[4] = tmp[5] = 0;
  10829. tmp[6] = product[14];
  10830. tmp[7] = product[15];
  10831. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10832. /* s4 */
  10833. tmp[0] = product[9];
  10834. tmp[1] = product[10];
  10835. tmp[2] = product[11];
  10836. tmp[3] = product[13];
  10837. tmp[4] = product[14];
  10838. tmp[5] = product[15];
  10839. tmp[6] = product[13];
  10840. tmp[7] = product[8];
  10841. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10842. /* d1 */
  10843. tmp[0] = product[11];
  10844. tmp[1] = product[12];
  10845. tmp[2] = product[13];
  10846. tmp[3] = tmp[4] = tmp[5] = 0;
  10847. tmp[6] = product[8];
  10848. tmp[7] = product[10];
  10849. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10850. /* d2 */
  10851. tmp[0] = product[12];
  10852. tmp[1] = product[13];
  10853. tmp[2] = product[14];
  10854. tmp[3] = product[15];
  10855. tmp[4] = tmp[5] = 0;
  10856. tmp[6] = product[9];
  10857. tmp[7] = product[11];
  10858. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10859. /* d3 */
  10860. tmp[0] = product[13];
  10861. tmp[1] = product[14];
  10862. tmp[2] = product[15];
  10863. tmp[3] = product[8];
  10864. tmp[4] = product[9];
  10865. tmp[5] = product[10];
  10866. tmp[6] = 0;
  10867. tmp[7] = product[12];
  10868. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10869. /* d4 */
  10870. tmp[0] = product[14];
  10871. tmp[1] = product[15];
  10872. tmp[2] = 0;
  10873. tmp[3] = product[9];
  10874. tmp[4] = product[10];
  10875. tmp[5] = product[11];
  10876. tmp[6] = 0;
  10877. tmp[7] = product[13];
  10878. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10879. if (carry < 0) {
  10880. do {
  10881. carry +=
  10882. (int) uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10883. } while (carry < 0);
  10884. } else {
  10885. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10886. num_words_secp256r1) != 1) {
  10887. carry -=
  10888. (int) uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10889. }
  10890. }
  10891. }
  10892. #else
  10893. static void vli_mmod_fast_secp256r1(uint64_t *result, uint64_t *product) {
  10894. uint64_t tmp[num_words_secp256r1];
  10895. int carry;
  10896. /* t */
  10897. uECC_vli_set(result, product, num_words_secp256r1);
  10898. /* s1 */
  10899. tmp[0] = 0;
  10900. tmp[1] = product[5] & 0xffffffff00000000U;
  10901. tmp[2] = product[6];
  10902. tmp[3] = product[7];
  10903. carry = (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10904. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10905. /* s2 */
  10906. tmp[1] = product[6] << 32;
  10907. tmp[2] = (product[6] >> 32) | (product[7] << 32);
  10908. tmp[3] = product[7] >> 32;
  10909. carry += (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10910. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10911. /* s3 */
  10912. tmp[0] = product[4];
  10913. tmp[1] = product[5] & 0xffffffff;
  10914. tmp[2] = 0;
  10915. tmp[3] = product[7];
  10916. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10917. /* s4 */
  10918. tmp[0] = (product[4] >> 32) | (product[5] << 32);
  10919. tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000U);
  10920. tmp[2] = product[7];
  10921. tmp[3] = (product[6] >> 32) | (product[4] << 32);
  10922. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10923. /* d1 */
  10924. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  10925. tmp[1] = (product[6] >> 32);
  10926. tmp[2] = 0;
  10927. tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32);
  10928. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10929. /* d2 */
  10930. tmp[0] = product[6];
  10931. tmp[1] = product[7];
  10932. tmp[2] = 0;
  10933. tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000);
  10934. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10935. /* d3 */
  10936. tmp[0] = (product[6] >> 32) | (product[7] << 32);
  10937. tmp[1] = (product[7] >> 32) | (product[4] << 32);
  10938. tmp[2] = (product[4] >> 32) | (product[5] << 32);
  10939. tmp[3] = (product[6] << 32);
  10940. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10941. /* d4 */
  10942. tmp[0] = product[7];
  10943. tmp[1] = product[4] & 0xffffffff00000000U;
  10944. tmp[2] = product[5];
  10945. tmp[3] = product[6] & 0xffffffff00000000U;
  10946. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10947. if (carry < 0) {
  10948. do {
  10949. carry +=
  10950. (int) uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10951. } while (carry < 0);
  10952. } else {
  10953. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10954. num_words_secp256r1) != 1) {
  10955. carry -=
  10956. (int) uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10957. }
  10958. }
  10959. }
  10960. #endif /* uECC_WORD_SIZE */
  10961. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) */
  10962. #endif /* uECC_SUPPORTS_secp256r1 */
  10963. #if uECC_SUPPORTS_secp256k1
  10964. static void double_jacobian_secp256k1(uECC_word_t *X1, uECC_word_t *Y1,
  10965. uECC_word_t *Z1, uECC_Curve curve);
  10966. static void x_side_secp256k1(uECC_word_t *result, const uECC_word_t *x,
  10967. uECC_Curve curve);
  10968. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10969. static void vli_mmod_fast_secp256k1(uECC_word_t *result, uECC_word_t *product);
  10970. #endif
  10971. static const struct uECC_Curve_t curve_secp256k1 = {
  10972. num_words_secp256k1,
  10973. num_bytes_secp256k1,
  10974. 256, /* num_n_bits */
  10975. {BYTES_TO_WORDS_8(2F, FC, FF, FF, FE, FF, FF, FF),
  10976. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10977. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10978. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  10979. {BYTES_TO_WORDS_8(41, 41, 36, D0, 8C, 5E, D2, BF),
  10980. BYTES_TO_WORDS_8(3B, A0, 48, AF, E6, DC, AE, BA),
  10981. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  10982. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  10983. {BYTES_TO_WORDS_8(98, 17, F8, 16, 5B, 81, F2, 59),
  10984. BYTES_TO_WORDS_8(D9, 28, CE, 2D, DB, FC, 9B, 02),
  10985. BYTES_TO_WORDS_8(07, 0B, 87, CE, 95, 62, A0, 55),
  10986. BYTES_TO_WORDS_8(AC, BB, DC, F9, 7E, 66, BE, 79),
  10987. BYTES_TO_WORDS_8(B8, D4, 10, FB, 8F, D0, 47, 9C),
  10988. BYTES_TO_WORDS_8(19, 54, 85, A6, 48, B4, 17, FD),
  10989. BYTES_TO_WORDS_8(A8, 08, 11, 0E, FC, FB, A4, 5D),
  10990. BYTES_TO_WORDS_8(65, C4, A3, 26, 77, DA, 3A, 48)},
  10991. {BYTES_TO_WORDS_8(07, 00, 00, 00, 00, 00, 00, 00),
  10992. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  10993. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  10994. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00)},
  10995. &double_jacobian_secp256k1,
  10996. #if uECC_SUPPORT_COMPRESSED_POINT
  10997. &mod_sqrt_default,
  10998. #endif
  10999. &x_side_secp256k1,
  11000. #if (uECC_OPTIMIZATION_LEVEL > 0)
  11001. &vli_mmod_fast_secp256k1
  11002. #endif
  11003. };
  11004. uECC_Curve uECC_secp256k1(void) {
  11005. return &curve_secp256k1;
  11006. }
  11007. /* Double in place */
  11008. static void double_jacobian_secp256k1(uECC_word_t *X1, uECC_word_t *Y1,
  11009. uECC_word_t *Z1, uECC_Curve curve) {
  11010. /* t1 = X, t2 = Y, t3 = Z */
  11011. uECC_word_t t4[num_words_secp256k1];
  11012. uECC_word_t t5[num_words_secp256k1];
  11013. if (uECC_vli_isZero(Z1, num_words_secp256k1)) {
  11014. return;
  11015. }
  11016. uECC_vli_modSquare_fast(t5, Y1, curve); /* t5 = y1^2 */
  11017. uECC_vli_modMult_fast(t4, X1, t5, curve); /* t4 = x1*y1^2 = A */
  11018. uECC_vli_modSquare_fast(X1, X1, curve); /* t1 = x1^2 */
  11019. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = y1^4 */
  11020. uECC_vli_modMult_fast(Z1, Y1, Z1, curve); /* t3 = y1*z1 = z3 */
  11021. uECC_vli_modAdd(Y1, X1, X1, curve->p, num_words_secp256k1); /* t2 = 2*x1^2 */
  11022. uECC_vli_modAdd(Y1, Y1, X1, curve->p, num_words_secp256k1); /* t2 = 3*x1^2 */
  11023. if (uECC_vli_testBit(Y1, 0)) {
  11024. uECC_word_t carry = uECC_vli_add(Y1, Y1, curve->p, num_words_secp256k1);
  11025. uECC_vli_rshift1(Y1, num_words_secp256k1);
  11026. Y1[num_words_secp256k1 - 1] |= carry << (uECC_WORD_BITS - 1);
  11027. } else {
  11028. uECC_vli_rshift1(Y1, num_words_secp256k1);
  11029. }
  11030. /* t2 = 3/2*(x1^2) = B */
  11031. uECC_vli_modSquare_fast(X1, Y1, curve); /* t1 = B^2 */
  11032. uECC_vli_modSub(X1, X1, t4, curve->p, num_words_secp256k1); /* t1 = B^2 - A */
  11033. uECC_vli_modSub(X1, X1, t4, curve->p,
  11034. num_words_secp256k1); /* t1 = B^2 - 2A = x3 */
  11035. uECC_vli_modSub(t4, t4, X1, curve->p, num_words_secp256k1); /* t4 = A - x3 */
  11036. uECC_vli_modMult_fast(Y1, Y1, t4, curve); /* t2 = B * (A - x3) */
  11037. uECC_vli_modSub(Y1, Y1, t5, curve->p,
  11038. num_words_secp256k1); /* t2 = B * (A - x3) - y1^4 = y3 */
  11039. }
  11040. /* Computes result = x^3 + b. result must not overlap x. */
  11041. static void x_side_secp256k1(uECC_word_t *result, const uECC_word_t *x,
  11042. uECC_Curve curve) {
  11043. uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  11044. uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 */
  11045. uECC_vli_modAdd(result, result, curve->b, curve->p,
  11046. num_words_secp256k1); /* r = x^3 + b */
  11047. }
  11048. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256k1)
  11049. static void omega_mult_secp256k1(uECC_word_t *result, const uECC_word_t *right);
  11050. static void vli_mmod_fast_secp256k1(uECC_word_t *result, uECC_word_t *product) {
  11051. uECC_word_t tmp[2 * num_words_secp256k1];
  11052. uECC_word_t carry;
  11053. uECC_vli_clear(tmp, num_words_secp256k1);
  11054. uECC_vli_clear(tmp + num_words_secp256k1, num_words_secp256k1);
  11055. omega_mult_secp256k1(tmp,
  11056. product + num_words_secp256k1); /* (Rq, q) = q * c */
  11057. carry = uECC_vli_add(result, product, tmp,
  11058. num_words_secp256k1); /* (C, r) = r + q */
  11059. uECC_vli_clear(product, num_words_secp256k1);
  11060. omega_mult_secp256k1(product, tmp + num_words_secp256k1); /* Rq*c */
  11061. carry += uECC_vli_add(result, result, product,
  11062. num_words_secp256k1); /* (C1, r) = r + Rq*c */
  11063. while (carry > 0) {
  11064. --carry;
  11065. uECC_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  11066. }
  11067. if (uECC_vli_cmp_unsafe(result, curve_secp256k1.p, num_words_secp256k1) > 0) {
  11068. uECC_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  11069. }
  11070. }
  11071. #if uECC_WORD_SIZE == 1
  11072. static void omega_mult_secp256k1(uint8_t *result, const uint8_t *right) {
  11073. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11074. uECC_word_t r0 = 0;
  11075. uECC_word_t r1 = 0;
  11076. uECC_word_t r2 = 0;
  11077. wordcount_t k;
  11078. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11079. muladd(0xD1, right[0], &r0, &r1, &r2);
  11080. result[0] = r0;
  11081. r0 = r1;
  11082. r1 = r2;
  11083. /* r2 is still 0 */
  11084. for (k = 1; k < num_words_secp256k1; ++k) {
  11085. muladd(0x03, right[k - 1], &r0, &r1, &r2);
  11086. muladd(0xD1, right[k], &r0, &r1, &r2);
  11087. result[k] = r0;
  11088. r0 = r1;
  11089. r1 = r2;
  11090. r2 = 0;
  11091. }
  11092. muladd(0x03, right[num_words_secp256k1 - 1], &r0, &r1, &r2);
  11093. result[num_words_secp256k1] = r0;
  11094. result[num_words_secp256k1 + 1] = r1;
  11095. /* add the 2^32 multiple */
  11096. result[4 + num_words_secp256k1] =
  11097. uECC_vli_add(result + 4, result + 4, right, num_words_secp256k1);
  11098. }
  11099. #elif uECC_WORD_SIZE == 4
  11100. static void omega_mult_secp256k1(uint32_t *result, const uint32_t *right) {
  11101. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11102. uint32_t carry = 0;
  11103. wordcount_t k;
  11104. for (k = 0; k < num_words_secp256k1; ++k) {
  11105. uint64_t p = (uint64_t) 0x3D1 * right[k] + carry;
  11106. result[k] = (uint32_t) p;
  11107. carry = p >> 32;
  11108. }
  11109. result[num_words_secp256k1] = carry;
  11110. /* add the 2^32 multiple */
  11111. result[1 + num_words_secp256k1] =
  11112. uECC_vli_add(result + 1, result + 1, right, num_words_secp256k1);
  11113. }
  11114. #else
  11115. static void omega_mult_secp256k1(uint64_t *result, const uint64_t *right) {
  11116. uECC_word_t r0 = 0;
  11117. uECC_word_t r1 = 0;
  11118. uECC_word_t r2 = 0;
  11119. wordcount_t k;
  11120. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11121. for (k = 0; k < num_words_secp256k1; ++k) {
  11122. muladd(0x1000003D1ull, right[k], &r0, &r1, &r2);
  11123. result[k] = r0;
  11124. r0 = r1;
  11125. r1 = r2;
  11126. r2 = 0;
  11127. }
  11128. result[num_words_secp256k1] = r0;
  11129. }
  11130. #endif /* uECC_WORD_SIZE */
  11131. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && && !asm_mmod_fast_secp256k1) */
  11132. #endif /* uECC_SUPPORTS_secp256k1 */
  11133. #endif /* _UECC_CURVE_SPECIFIC_H_ */
  11134. /* Returns 1 if 'point' is the point at infinity, 0 otherwise. */
  11135. #define EccPoint_isZero(point, curve) \
  11136. uECC_vli_isZero((point), (wordcount_t) ((curve)->num_words * 2))
  11137. /* Point multiplication algorithm using Montgomery's ladder with co-Z
  11138. coordinates. From http://eprint.iacr.org/2011/338.pdf
  11139. */
  11140. /* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
  11141. static void apply_z(uECC_word_t *X1, uECC_word_t *Y1,
  11142. const uECC_word_t *const Z, uECC_Curve curve) {
  11143. uECC_word_t t1[uECC_MAX_WORDS];
  11144. uECC_vli_modSquare_fast(t1, Z, curve); /* z^2 */
  11145. uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
  11146. uECC_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */
  11147. uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
  11148. }
  11149. /* P = (x1, y1) => 2P, (x2, y2) => P' */
  11150. static void XYcZ_initial_double(uECC_word_t *X1, uECC_word_t *Y1,
  11151. uECC_word_t *X2, uECC_word_t *Y2,
  11152. const uECC_word_t *const initial_Z,
  11153. uECC_Curve curve) {
  11154. uECC_word_t z[uECC_MAX_WORDS];
  11155. wordcount_t num_words = curve->num_words;
  11156. if (initial_Z) {
  11157. uECC_vli_set(z, initial_Z, num_words);
  11158. } else {
  11159. uECC_vli_clear(z, num_words);
  11160. z[0] = 1;
  11161. }
  11162. uECC_vli_set(X2, X1, num_words);
  11163. uECC_vli_set(Y2, Y1, num_words);
  11164. apply_z(X1, Y1, z, curve);
  11165. curve->double_jacobian(X1, Y1, z, curve);
  11166. apply_z(X2, Y2, z, curve);
  11167. }
  11168. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  11169. Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
  11170. or P => P', Q => P + Q
  11171. */
  11172. static void XYcZ_add(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2,
  11173. uECC_word_t *Y2, uECC_Curve curve) {
  11174. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  11175. uECC_word_t t5[uECC_MAX_WORDS] = {0};
  11176. wordcount_t num_words = curve->num_words;
  11177. uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  11178. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  11179. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  11180. uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  11181. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  11182. uECC_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */
  11183. uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
  11184. uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
  11185. uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
  11186. uECC_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */
  11187. uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
  11188. uECC_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */
  11189. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
  11190. uECC_vli_set(X2, t5, num_words);
  11191. }
  11192. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  11193. Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
  11194. or P => P - Q, Q => P + Q
  11195. */
  11196. static void XYcZ_addC(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2,
  11197. uECC_word_t *Y2, uECC_Curve curve) {
  11198. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  11199. uECC_word_t t5[uECC_MAX_WORDS] = {0};
  11200. uECC_word_t t6[uECC_MAX_WORDS];
  11201. uECC_word_t t7[uECC_MAX_WORDS];
  11202. wordcount_t num_words = curve->num_words;
  11203. uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  11204. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  11205. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  11206. uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  11207. uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
  11208. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  11209. uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
  11210. uECC_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */
  11211. uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
  11212. uECC_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */
  11213. uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */
  11214. uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
  11215. uECC_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */
  11216. uECC_vli_modSub(Y2, Y2, Y1, curve->p,
  11217. num_words); /* t4 = (y2 - y1)*(B - x3) - E = y3 */
  11218. uECC_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */
  11219. uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */
  11220. uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
  11221. uECC_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */
  11222. uECC_vli_modSub(Y1, t6, Y1, curve->p,
  11223. num_words); /* t2 = (y2+y1)*(x3' - B) - E = y3' */
  11224. uECC_vli_set(X1, t7, num_words);
  11225. }
  11226. /* result may overlap point. */
  11227. static void EccPoint_mult(uECC_word_t *result, const uECC_word_t *point,
  11228. const uECC_word_t *scalar,
  11229. const uECC_word_t *initial_Z, bitcount_t num_bits,
  11230. uECC_Curve curve) {
  11231. /* R0 and R1 */
  11232. uECC_word_t Rx[2][uECC_MAX_WORDS];
  11233. uECC_word_t Ry[2][uECC_MAX_WORDS];
  11234. uECC_word_t z[uECC_MAX_WORDS];
  11235. bitcount_t i;
  11236. uECC_word_t nb;
  11237. wordcount_t num_words = curve->num_words;
  11238. uECC_vli_set(Rx[1], point, num_words);
  11239. uECC_vli_set(Ry[1], point + num_words, num_words);
  11240. XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
  11241. for (i = num_bits - 2; i > 0; --i) {
  11242. nb = !uECC_vli_testBit(scalar, i);
  11243. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  11244. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  11245. }
  11246. nb = !uECC_vli_testBit(scalar, 0);
  11247. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  11248. /* Find final 1/Z value. */
  11249. uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
  11250. uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */
  11251. uECC_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */
  11252. uECC_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0)) */
  11253. /* yP / (xP * Yb * (X1 - X0)) */
  11254. uECC_vli_modMult_fast(z, z, point + num_words, curve);
  11255. uECC_vli_modMult_fast(z, z, Rx[1 - nb],
  11256. curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */
  11257. /* End 1/Z calculation */
  11258. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  11259. apply_z(Rx[0], Ry[0], z, curve);
  11260. uECC_vli_set(result, Rx[0], num_words);
  11261. uECC_vli_set(result + num_words, Ry[0], num_words);
  11262. }
  11263. static uECC_word_t regularize_k(const uECC_word_t *const k, uECC_word_t *k0,
  11264. uECC_word_t *k1, uECC_Curve curve) {
  11265. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11266. bitcount_t num_n_bits = curve->num_n_bits;
  11267. uECC_word_t carry =
  11268. uECC_vli_add(k0, k, curve->n, num_n_words) ||
  11269. (num_n_bits < ((bitcount_t) num_n_words * uECC_WORD_SIZE * 8) &&
  11270. uECC_vli_testBit(k0, num_n_bits));
  11271. uECC_vli_add(k1, k0, curve->n, num_n_words);
  11272. return carry;
  11273. }
  11274. /* Generates a random integer in the range 0 < random < top.
  11275. Both random and top have num_words words. */
  11276. uECC_VLI_API int uECC_generate_random_int(uECC_word_t *random,
  11277. const uECC_word_t *top,
  11278. wordcount_t num_words) {
  11279. uECC_word_t mask = (uECC_word_t) -1;
  11280. uECC_word_t tries;
  11281. bitcount_t num_bits = uECC_vli_numBits(top, num_words);
  11282. if (!g_rng_function) {
  11283. return 0;
  11284. }
  11285. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11286. if (!g_rng_function((uint8_t *) random,
  11287. (unsigned int) (num_words * uECC_WORD_SIZE))) {
  11288. return 0;
  11289. }
  11290. random[num_words - 1] &=
  11291. mask >> ((bitcount_t) (num_words * uECC_WORD_SIZE * 8 - num_bits));
  11292. if (!uECC_vli_isZero(random, num_words) &&
  11293. uECC_vli_cmp(top, random, num_words) == 1) {
  11294. return 1;
  11295. }
  11296. }
  11297. return 0;
  11298. }
  11299. static uECC_word_t EccPoint_compute_public_key(uECC_word_t *result,
  11300. uECC_word_t *private_key,
  11301. uECC_Curve curve) {
  11302. uECC_word_t tmp1[uECC_MAX_WORDS];
  11303. uECC_word_t tmp2[uECC_MAX_WORDS];
  11304. uECC_word_t *p2[2] = {tmp1, tmp2};
  11305. uECC_word_t *initial_Z = 0;
  11306. uECC_word_t carry;
  11307. /* Regularize the bitcount for the private key so that attackers cannot use a
  11308. side channel attack to learn the number of leading zeros. */
  11309. carry = regularize_k(private_key, tmp1, tmp2, curve);
  11310. /* If an RNG function was specified, try to get a random initial Z value to
  11311. improve protection against side-channel attacks. */
  11312. if (g_rng_function) {
  11313. if (!uECC_generate_random_int(p2[carry], curve->p, curve->num_words)) {
  11314. return 0;
  11315. }
  11316. initial_Z = p2[carry];
  11317. }
  11318. EccPoint_mult(result, curve->G, p2[!carry], initial_Z,
  11319. (bitcount_t) (curve->num_n_bits + 1), curve);
  11320. if (EccPoint_isZero(result, curve)) {
  11321. return 0;
  11322. }
  11323. return 1;
  11324. }
  11325. #if uECC_WORD_SIZE == 1
  11326. uECC_VLI_API void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  11327. const uint8_t *native) {
  11328. wordcount_t i;
  11329. for (i = 0; i < num_bytes; ++i) {
  11330. bytes[i] = native[(num_bytes - 1) - i];
  11331. }
  11332. }
  11333. uECC_VLI_API void uECC_vli_bytesToNative(uint8_t *native, const uint8_t *bytes,
  11334. int num_bytes) {
  11335. uECC_vli_nativeToBytes(native, num_bytes, bytes);
  11336. }
  11337. #else
  11338. uECC_VLI_API void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  11339. const uECC_word_t *native) {
  11340. int i;
  11341. for (i = 0; i < num_bytes; ++i) {
  11342. unsigned b = (unsigned) (num_bytes - 1 - i);
  11343. bytes[i] =
  11344. (uint8_t) (native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE)));
  11345. }
  11346. }
  11347. uECC_VLI_API void uECC_vli_bytesToNative(uECC_word_t *native,
  11348. const uint8_t *bytes, int num_bytes) {
  11349. int i;
  11350. uECC_vli_clear(native, (wordcount_t) ((num_bytes + (uECC_WORD_SIZE - 1)) /
  11351. uECC_WORD_SIZE));
  11352. for (i = 0; i < num_bytes; ++i) {
  11353. unsigned b = (unsigned) (num_bytes - 1 - i);
  11354. native[b / uECC_WORD_SIZE] |= (uECC_word_t) bytes[i]
  11355. << (8 * (b % uECC_WORD_SIZE));
  11356. }
  11357. }
  11358. #endif /* uECC_WORD_SIZE */
  11359. int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve) {
  11360. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11361. uECC_word_t *_private = (uECC_word_t *) private_key;
  11362. uECC_word_t *_public = (uECC_word_t *) public_key;
  11363. #else
  11364. uECC_word_t _private[uECC_MAX_WORDS];
  11365. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11366. #endif
  11367. uECC_word_t tries;
  11368. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11369. if (!uECC_generate_random_int(_private, curve->n,
  11370. BITS_TO_WORDS(curve->num_n_bits))) {
  11371. return 0;
  11372. }
  11373. if (EccPoint_compute_public_key(_public, _private, curve)) {
  11374. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11375. uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits),
  11376. _private);
  11377. uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  11378. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  11379. _public + curve->num_words);
  11380. #endif
  11381. return 1;
  11382. }
  11383. }
  11384. return 0;
  11385. }
  11386. int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
  11387. uint8_t *secret, uECC_Curve curve) {
  11388. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11389. uECC_word_t _private[uECC_MAX_WORDS];
  11390. uECC_word_t tmp[uECC_MAX_WORDS];
  11391. uECC_word_t *p2[2] = {_private, tmp};
  11392. uECC_word_t *initial_Z = 0;
  11393. uECC_word_t carry;
  11394. wordcount_t num_words = curve->num_words;
  11395. wordcount_t num_bytes = curve->num_bytes;
  11396. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11397. bcopy((uint8_t *) _private, private_key, num_bytes);
  11398. bcopy((uint8_t *) _public, public_key, num_bytes * 2);
  11399. #else
  11400. uECC_vli_bytesToNative(_private, private_key,
  11401. BITS_TO_BYTES(curve->num_n_bits));
  11402. uECC_vli_bytesToNative(_public, public_key, num_bytes);
  11403. uECC_vli_bytesToNative(_public + num_words, public_key + num_bytes,
  11404. num_bytes);
  11405. #endif
  11406. /* Regularize the bitcount for the private key so that attackers cannot use a
  11407. side channel attack to learn the number of leading zeros. */
  11408. carry = regularize_k(_private, _private, tmp, curve);
  11409. /* If an RNG function was specified, try to get a random initial Z value to
  11410. improve protection against side-channel attacks. */
  11411. if (g_rng_function) {
  11412. if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) {
  11413. return 0;
  11414. }
  11415. initial_Z = p2[carry];
  11416. }
  11417. EccPoint_mult(_public, _public, p2[!carry], initial_Z,
  11418. (bitcount_t) (curve->num_n_bits + 1), curve);
  11419. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11420. bcopy((uint8_t *) secret, (uint8_t *) _public, num_bytes);
  11421. #else
  11422. uECC_vli_nativeToBytes(secret, num_bytes, _public);
  11423. #endif
  11424. return !EccPoint_isZero(_public, curve);
  11425. }
  11426. #if uECC_SUPPORT_COMPRESSED_POINT
  11427. void uECC_compress(const uint8_t *public_key, uint8_t *compressed,
  11428. uECC_Curve curve) {
  11429. wordcount_t i;
  11430. for (i = 0; i < curve->num_bytes; ++i) {
  11431. compressed[i + 1] = public_key[i];
  11432. }
  11433. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11434. compressed[0] = 2 + (public_key[curve->num_bytes] & 0x01);
  11435. #else
  11436. compressed[0] = 2 + (public_key[curve->num_bytes * 2 - 1] & 0x01);
  11437. #endif
  11438. }
  11439. void uECC_decompress(const uint8_t *compressed, uint8_t *public_key,
  11440. uECC_Curve curve) {
  11441. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11442. uECC_word_t *point = (uECC_word_t *) public_key;
  11443. #else
  11444. uECC_word_t point[uECC_MAX_WORDS * 2];
  11445. #endif
  11446. uECC_word_t *y = point + curve->num_words;
  11447. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11448. bcopy(public_key, compressed + 1, curve->num_bytes);
  11449. #else
  11450. uECC_vli_bytesToNative(point, compressed + 1, curve->num_bytes);
  11451. #endif
  11452. curve->x_side(y, point, curve);
  11453. curve->mod_sqrt(y, curve);
  11454. if ((uint8_t) (y[0] & 0x01) != (compressed[0] & 0x01)) {
  11455. uECC_vli_sub(y, curve->p, y, curve->num_words);
  11456. }
  11457. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11458. uECC_vli_nativeToBytes(public_key, curve->num_bytes, point);
  11459. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, y);
  11460. #endif
  11461. }
  11462. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  11463. uECC_VLI_API int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve) {
  11464. uECC_word_t tmp1[uECC_MAX_WORDS];
  11465. uECC_word_t tmp2[uECC_MAX_WORDS];
  11466. wordcount_t num_words = curve->num_words;
  11467. /* The point at infinity is invalid. */
  11468. if (EccPoint_isZero(point, curve)) {
  11469. return 0;
  11470. }
  11471. /* x and y must be smaller than p. */
  11472. if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
  11473. uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
  11474. return 0;
  11475. }
  11476. uECC_vli_modSquare_fast(tmp1, point + num_words, curve);
  11477. curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
  11478. /* Make sure that y^2 == x^3 + ax + b */
  11479. return (int) (uECC_vli_equal(tmp1, tmp2, num_words));
  11480. }
  11481. int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve) {
  11482. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11483. uECC_word_t *_public = (uECC_word_t *) public_key;
  11484. #else
  11485. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11486. #endif
  11487. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11488. uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
  11489. uECC_vli_bytesToNative(_public + curve->num_words,
  11490. public_key + curve->num_bytes, curve->num_bytes);
  11491. #endif
  11492. return uECC_valid_point(_public, curve);
  11493. }
  11494. int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
  11495. uECC_Curve curve) {
  11496. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11497. uECC_word_t *_private = (uECC_word_t *) private_key;
  11498. uECC_word_t *_public = (uECC_word_t *) public_key;
  11499. #else
  11500. uECC_word_t _private[uECC_MAX_WORDS];
  11501. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11502. #endif
  11503. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11504. uECC_vli_bytesToNative(_private, private_key,
  11505. BITS_TO_BYTES(curve->num_n_bits));
  11506. #endif
  11507. /* Make sure the private key is in the range [1, n-1]. */
  11508. if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
  11509. return 0;
  11510. }
  11511. if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) {
  11512. return 0;
  11513. }
  11514. /* Compute public key. */
  11515. if (!EccPoint_compute_public_key(_public, _private, curve)) {
  11516. return 0;
  11517. }
  11518. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11519. uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  11520. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  11521. _public + curve->num_words);
  11522. #endif
  11523. return 1;
  11524. }
  11525. /* -------- ECDSA code -------- */
  11526. static void bits2int(uECC_word_t *native, const uint8_t *bits,
  11527. unsigned bits_size, uECC_Curve curve) {
  11528. unsigned num_n_bytes = (unsigned) BITS_TO_BYTES(curve->num_n_bits);
  11529. unsigned num_n_words = (unsigned) BITS_TO_WORDS(curve->num_n_bits);
  11530. int shift;
  11531. uECC_word_t carry;
  11532. uECC_word_t *ptr;
  11533. if (bits_size > num_n_bytes) {
  11534. bits_size = num_n_bytes;
  11535. }
  11536. uECC_vli_clear(native, (wordcount_t) num_n_words);
  11537. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11538. bcopy((uint8_t *) native, bits, bits_size);
  11539. #else
  11540. uECC_vli_bytesToNative(native, bits, (int) bits_size);
  11541. #endif
  11542. if (bits_size * 8 <= (unsigned) curve->num_n_bits) {
  11543. return;
  11544. }
  11545. shift = (int) bits_size * 8 - curve->num_n_bits;
  11546. carry = 0;
  11547. ptr = native + num_n_words;
  11548. while (ptr-- > native) {
  11549. uECC_word_t temp = *ptr;
  11550. *ptr = (temp >> shift) | carry;
  11551. carry = temp << (uECC_WORD_BITS - shift);
  11552. }
  11553. /* Reduce mod curve_n */
  11554. if (uECC_vli_cmp_unsafe(curve->n, native, (wordcount_t) num_n_words) != 1) {
  11555. uECC_vli_sub(native, native, curve->n, (wordcount_t) num_n_words);
  11556. }
  11557. }
  11558. static int uECC_sign_with_k_internal(const uint8_t *private_key,
  11559. const uint8_t *message_hash,
  11560. unsigned hash_size, uECC_word_t *k,
  11561. uint8_t *signature, uECC_Curve curve) {
  11562. uECC_word_t tmp[uECC_MAX_WORDS];
  11563. uECC_word_t s[uECC_MAX_WORDS];
  11564. uECC_word_t *k2[2] = {tmp, s};
  11565. uECC_word_t *initial_Z = 0;
  11566. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11567. uECC_word_t *p = (uECC_word_t *) signature;
  11568. #else
  11569. uECC_word_t p[uECC_MAX_WORDS * 2];
  11570. #endif
  11571. uECC_word_t carry;
  11572. wordcount_t num_words = curve->num_words;
  11573. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11574. bitcount_t num_n_bits = curve->num_n_bits;
  11575. /* Make sure 0 < k < curve_n */
  11576. if (uECC_vli_isZero(k, num_words) ||
  11577. uECC_vli_cmp(curve->n, k, num_n_words) != 1) {
  11578. return 0;
  11579. }
  11580. carry = regularize_k(k, tmp, s, curve);
  11581. /* If an RNG function was specified, try to get a random initial Z value to
  11582. improve protection against side-channel attacks. */
  11583. if (g_rng_function) {
  11584. if (!uECC_generate_random_int(k2[carry], curve->p, num_words)) {
  11585. return 0;
  11586. }
  11587. initial_Z = k2[carry];
  11588. }
  11589. EccPoint_mult(p, curve->G, k2[!carry], initial_Z,
  11590. (bitcount_t) (num_n_bits + 1), curve);
  11591. if (uECC_vli_isZero(p, num_words)) {
  11592. return 0;
  11593. }
  11594. /* If an RNG function was specified, get a random number
  11595. to prevent side channel analysis of k. */
  11596. if (!g_rng_function) {
  11597. uECC_vli_clear(tmp, num_n_words);
  11598. tmp[0] = 1;
  11599. } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {
  11600. return 0;
  11601. }
  11602. /* Prevent side channel analysis of uECC_vli_modInv() to determine
  11603. bits of k / the private key by premultiplying by a random number */
  11604. uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
  11605. uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */
  11606. uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
  11607. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11608. uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
  11609. #endif
  11610. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11611. bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
  11612. #else
  11613. uECC_vli_bytesToNative(tmp, private_key,
  11614. BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */
  11615. #endif
  11616. s[num_n_words - 1] = 0;
  11617. uECC_vli_set(s, p, num_words);
  11618. uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
  11619. bits2int(tmp, message_hash, hash_size, curve);
  11620. uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
  11621. uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */
  11622. if (uECC_vli_numBits(s, num_n_words) > (bitcount_t) curve->num_bytes * 8) {
  11623. return 0;
  11624. }
  11625. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11626. bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s,
  11627. curve->num_bytes);
  11628. #else
  11629. uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
  11630. #endif
  11631. return 1;
  11632. }
  11633. #if 0
  11634. /* For testing - sign with an explicitly specified k value */
  11635. int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
  11636. unsigned hash_size, const uint8_t *k, uint8_t *signature,
  11637. uECC_Curve curve) {
  11638. uECC_word_t k2[uECC_MAX_WORDS];
  11639. bits2int(k2, k, (unsigned) BITS_TO_BYTES(curve->num_n_bits), curve);
  11640. return uECC_sign_with_k_internal(private_key, message_hash, hash_size, k2,
  11641. signature, curve);
  11642. }
  11643. #endif
  11644. int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash,
  11645. unsigned hash_size, uint8_t *signature, uECC_Curve curve) {
  11646. uECC_word_t k[uECC_MAX_WORDS];
  11647. uECC_word_t tries;
  11648. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11649. if (!uECC_generate_random_int(k, curve->n,
  11650. BITS_TO_WORDS(curve->num_n_bits))) {
  11651. return 0;
  11652. }
  11653. if (uECC_sign_with_k_internal(private_key, message_hash, hash_size, k,
  11654. signature, curve)) {
  11655. return 1;
  11656. }
  11657. }
  11658. return 0;
  11659. }
  11660. /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always
  11661. the same size as the hash result size. */
  11662. static void HMAC_init(const uECC_HashContext *hash_context, const uint8_t *K) {
  11663. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  11664. unsigned i;
  11665. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x36;
  11666. for (; i < hash_context->block_size; ++i) pad[i] = 0x36;
  11667. hash_context->init_hash(hash_context);
  11668. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  11669. }
  11670. static void HMAC_update(const uECC_HashContext *hash_context,
  11671. const uint8_t *message, unsigned message_size) {
  11672. hash_context->update_hash(hash_context, message, message_size);
  11673. }
  11674. static void HMAC_finish(const uECC_HashContext *hash_context, const uint8_t *K,
  11675. uint8_t *result) {
  11676. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  11677. unsigned i;
  11678. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x5c;
  11679. for (; i < hash_context->block_size; ++i) pad[i] = 0x5c;
  11680. hash_context->finish_hash(hash_context, result);
  11681. hash_context->init_hash(hash_context);
  11682. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  11683. hash_context->update_hash(hash_context, result, hash_context->result_size);
  11684. hash_context->finish_hash(hash_context, result);
  11685. }
  11686. /* V = HMAC_K(V) */
  11687. static void update_V(const uECC_HashContext *hash_context, uint8_t *K,
  11688. uint8_t *V) {
  11689. HMAC_init(hash_context, K);
  11690. HMAC_update(hash_context, V, hash_context->result_size);
  11691. HMAC_finish(hash_context, K, V);
  11692. }
  11693. /* Deterministic signing, similar to RFC 6979. Differences are:
  11694. * We just use H(m) directly rather than bits2octets(H(m))
  11695. (it is not reduced modulo curve_n).
  11696. * We generate a value for k (aka T) directly rather than converting
  11697. endianness.
  11698. Layout of hash_context->tmp: <K> | <V> | (1 byte overlapped 0x00 or 0x01) /
  11699. <HMAC pad> */
  11700. int uECC_sign_deterministic(const uint8_t *private_key,
  11701. const uint8_t *message_hash, unsigned hash_size,
  11702. const uECC_HashContext *hash_context,
  11703. uint8_t *signature, uECC_Curve curve) {
  11704. uint8_t *K = hash_context->tmp;
  11705. uint8_t *V = K + hash_context->result_size;
  11706. wordcount_t num_bytes = curve->num_bytes;
  11707. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11708. bitcount_t num_n_bits = curve->num_n_bits;
  11709. uECC_word_t tries;
  11710. unsigned i;
  11711. for (i = 0; i < hash_context->result_size; ++i) {
  11712. V[i] = 0x01;
  11713. K[i] = 0;
  11714. }
  11715. /* K = HMAC_K(V || 0x00 || int2octets(x) || h(m)) */
  11716. HMAC_init(hash_context, K);
  11717. V[hash_context->result_size] = 0x00;
  11718. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11719. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  11720. HMAC_update(hash_context, message_hash, hash_size);
  11721. HMAC_finish(hash_context, K, K);
  11722. update_V(hash_context, K, V);
  11723. /* K = HMAC_K(V || 0x01 || int2octets(x) || h(m)) */
  11724. HMAC_init(hash_context, K);
  11725. V[hash_context->result_size] = 0x01;
  11726. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11727. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  11728. HMAC_update(hash_context, message_hash, hash_size);
  11729. HMAC_finish(hash_context, K, K);
  11730. update_V(hash_context, K, V);
  11731. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11732. uECC_word_t T[uECC_MAX_WORDS];
  11733. uint8_t *T_ptr = (uint8_t *) T;
  11734. wordcount_t T_bytes = 0;
  11735. for (;;) {
  11736. update_V(hash_context, K, V);
  11737. for (i = 0; i < hash_context->result_size; ++i) {
  11738. T_ptr[T_bytes++] = V[i];
  11739. if (T_bytes >= num_n_words * uECC_WORD_SIZE) {
  11740. goto filled;
  11741. }
  11742. }
  11743. }
  11744. filled:
  11745. if ((bitcount_t) num_n_words * uECC_WORD_SIZE * 8 > num_n_bits) {
  11746. uECC_word_t mask = (uECC_word_t) -1;
  11747. T[num_n_words - 1] &=
  11748. mask >>
  11749. ((bitcount_t) (num_n_words * uECC_WORD_SIZE * 8 - num_n_bits));
  11750. }
  11751. if (uECC_sign_with_k_internal(private_key, message_hash, hash_size, T,
  11752. signature, curve)) {
  11753. return 1;
  11754. }
  11755. /* K = HMAC_K(V || 0x00) */
  11756. HMAC_init(hash_context, K);
  11757. V[hash_context->result_size] = 0x00;
  11758. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11759. HMAC_finish(hash_context, K, K);
  11760. update_V(hash_context, K, V);
  11761. }
  11762. return 0;
  11763. }
  11764. static bitcount_t smax(bitcount_t a, bitcount_t b) {
  11765. return (a > b ? a : b);
  11766. }
  11767. int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash,
  11768. unsigned hash_size, const uint8_t *signature,
  11769. uECC_Curve curve) {
  11770. uECC_word_t u1[uECC_MAX_WORDS], u2[uECC_MAX_WORDS];
  11771. uECC_word_t z[uECC_MAX_WORDS];
  11772. uECC_word_t sum[uECC_MAX_WORDS * 2];
  11773. uECC_word_t rx[uECC_MAX_WORDS];
  11774. uECC_word_t ry[uECC_MAX_WORDS];
  11775. uECC_word_t tx[uECC_MAX_WORDS];
  11776. uECC_word_t ty[uECC_MAX_WORDS];
  11777. uECC_word_t tz[uECC_MAX_WORDS];
  11778. const uECC_word_t *points[4];
  11779. const uECC_word_t *point;
  11780. bitcount_t num_bits;
  11781. bitcount_t i;
  11782. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11783. uECC_word_t *_public = (uECC_word_t *) public_key;
  11784. #else
  11785. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11786. #endif
  11787. uECC_word_t r[uECC_MAX_WORDS], s[uECC_MAX_WORDS];
  11788. wordcount_t num_words = curve->num_words;
  11789. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11790. rx[num_n_words - 1] = 0;
  11791. r[num_n_words - 1] = 0;
  11792. s[num_n_words - 1] = 0;
  11793. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11794. bcopy((uint8_t *) r, signature, curve->num_bytes);
  11795. bcopy((uint8_t *) s, signature + curve->num_bytes, curve->num_bytes);
  11796. #else
  11797. uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
  11798. uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
  11799. curve->num_bytes);
  11800. uECC_vli_bytesToNative(r, signature, curve->num_bytes);
  11801. uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
  11802. #endif
  11803. /* r, s must not be 0. */
  11804. if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
  11805. return 0;
  11806. }
  11807. /* r, s must be < n. */
  11808. if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
  11809. uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
  11810. return 0;
  11811. }
  11812. /* Calculate u1 and u2. */
  11813. uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
  11814. u1[num_n_words - 1] = 0;
  11815. bits2int(u1, message_hash, hash_size, curve);
  11816. uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
  11817. uECC_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */
  11818. /* Calculate sum = G + Q. */
  11819. uECC_vli_set(sum, _public, num_words);
  11820. uECC_vli_set(sum + num_words, _public + num_words, num_words);
  11821. uECC_vli_set(tx, curve->G, num_words);
  11822. uECC_vli_set(ty, curve->G + num_words, num_words);
  11823. uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
  11824. XYcZ_add(tx, ty, sum, sum + num_words, curve);
  11825. uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
  11826. apply_z(sum, sum + num_words, z, curve);
  11827. /* Use Shamir's trick to calculate u1*G + u2*Q */
  11828. points[0] = 0;
  11829. points[1] = curve->G;
  11830. points[2] = _public;
  11831. points[3] = sum;
  11832. num_bits = smax(uECC_vli_numBits(u1, num_n_words),
  11833. uECC_vli_numBits(u2, num_n_words));
  11834. point = points[(!!uECC_vli_testBit(u1, (bitcount_t) (num_bits - 1))) |
  11835. ((!!uECC_vli_testBit(u2, (bitcount_t) (num_bits - 1))) << 1)];
  11836. uECC_vli_set(rx, point, num_words);
  11837. uECC_vli_set(ry, point + num_words, num_words);
  11838. uECC_vli_clear(z, num_words);
  11839. z[0] = 1;
  11840. for (i = num_bits - 2; i >= 0; --i) {
  11841. uECC_word_t index;
  11842. curve->double_jacobian(rx, ry, z, curve);
  11843. index = (!!uECC_vli_testBit(u1, i)) |
  11844. (uECC_word_t) ((!!uECC_vli_testBit(u2, i)) << 1);
  11845. point = points[index];
  11846. if (point) {
  11847. uECC_vli_set(tx, point, num_words);
  11848. uECC_vli_set(ty, point + num_words, num_words);
  11849. apply_z(tx, ty, z, curve);
  11850. uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
  11851. XYcZ_add(tx, ty, rx, ry, curve);
  11852. uECC_vli_modMult_fast(z, z, tz, curve);
  11853. }
  11854. }
  11855. uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
  11856. apply_z(rx, ry, z, curve);
  11857. /* v = x1 (mod n) */
  11858. if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
  11859. uECC_vli_sub(rx, rx, curve->n, num_n_words);
  11860. }
  11861. /* Accept only if v == r. */
  11862. return (int) (uECC_vli_equal(rx, r, num_words));
  11863. }
  11864. #if uECC_ENABLE_VLI_API
  11865. unsigned uECC_curve_num_words(uECC_Curve curve) {
  11866. return curve->num_words;
  11867. }
  11868. unsigned uECC_curve_num_bytes(uECC_Curve curve) {
  11869. return curve->num_bytes;
  11870. }
  11871. unsigned uECC_curve_num_bits(uECC_Curve curve) {
  11872. return curve->num_bytes * 8;
  11873. }
  11874. unsigned uECC_curve_num_n_words(uECC_Curve curve) {
  11875. return BITS_TO_WORDS(curve->num_n_bits);
  11876. }
  11877. unsigned uECC_curve_num_n_bytes(uECC_Curve curve) {
  11878. return BITS_TO_BYTES(curve->num_n_bits);
  11879. }
  11880. unsigned uECC_curve_num_n_bits(uECC_Curve curve) {
  11881. return curve->num_n_bits;
  11882. }
  11883. const uECC_word_t *uECC_curve_p(uECC_Curve curve) {
  11884. return curve->p;
  11885. }
  11886. const uECC_word_t *uECC_curve_n(uECC_Curve curve) {
  11887. return curve->n;
  11888. }
  11889. const uECC_word_t *uECC_curve_G(uECC_Curve curve) {
  11890. return curve->G;
  11891. }
  11892. const uECC_word_t *uECC_curve_b(uECC_Curve curve) {
  11893. return curve->b;
  11894. }
  11895. #if uECC_SUPPORT_COMPRESSED_POINT
  11896. void uECC_vli_mod_sqrt(uECC_word_t *a, uECC_Curve curve) {
  11897. curve->mod_sqrt(a, curve);
  11898. }
  11899. #endif
  11900. void uECC_vli_mmod_fast(uECC_word_t *result, uECC_word_t *product,
  11901. uECC_Curve curve) {
  11902. #if (uECC_OPTIMIZATION_LEVEL > 0)
  11903. curve->mmod_fast(result, product);
  11904. #else
  11905. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  11906. #endif
  11907. }
  11908. void uECC_point_mult(uECC_word_t *result, const uECC_word_t *point,
  11909. const uECC_word_t *scalar, uECC_Curve curve) {
  11910. uECC_word_t tmp1[uECC_MAX_WORDS];
  11911. uECC_word_t tmp2[uECC_MAX_WORDS];
  11912. uECC_word_t *p2[2] = {tmp1, tmp2};
  11913. uECC_word_t carry = regularize_k(scalar, tmp1, tmp2, curve);
  11914. EccPoint_mult(result, point, p2[!carry], 0, curve->num_n_bits + 1, curve);
  11915. }
  11916. #endif /* uECC_ENABLE_VLI_API */
  11917. #endif // MG_TLS_BUILTIN
  11918. // End of uecc BSD-2
  11919. #ifdef MG_ENABLE_LINES
  11920. #line 1 "src/url.c"
  11921. #endif
  11922. struct url {
  11923. size_t key, user, pass, host, port, uri, end;
  11924. };
  11925. int mg_url_is_ssl(const char *url) {
  11926. return strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0 ||
  11927. strncmp(url, "mqtts:", 6) == 0 || strncmp(url, "ssl:", 4) == 0 ||
  11928. strncmp(url, "tls:", 4) == 0 || strncmp(url, "tcps:", 5) == 0;
  11929. }
  11930. static struct url urlparse(const char *url) {
  11931. size_t i;
  11932. struct url u;
  11933. memset(&u, 0, sizeof(u));
  11934. for (i = 0; url[i] != '\0'; i++) {
  11935. if (url[i] == '/' && i > 0 && u.host == 0 && url[i - 1] == '/') {
  11936. u.host = i + 1;
  11937. u.port = 0;
  11938. } else if (url[i] == ']') {
  11939. u.port = 0; // IPv6 URLs, like http://[::1]/bar
  11940. } else if (url[i] == ':' && u.port == 0 && u.uri == 0) {
  11941. u.port = i + 1;
  11942. } else if (url[i] == '@' && u.user == 0 && u.pass == 0 && u.uri == 0) {
  11943. u.user = u.host;
  11944. u.pass = u.port;
  11945. u.host = i + 1;
  11946. u.port = 0;
  11947. } else if (url[i] == '/' && u.host && u.uri == 0) {
  11948. u.uri = i;
  11949. }
  11950. }
  11951. u.end = i;
  11952. #if 0
  11953. printf("[%s] %d %d %d %d %d\n", url, u.user, u.pass, u.host, u.port, u.uri);
  11954. #endif
  11955. return u;
  11956. }
  11957. struct mg_str mg_url_host(const char *url) {
  11958. struct url u = urlparse(url);
  11959. size_t n = u.port ? u.port - u.host - 1
  11960. : u.uri ? u.uri - u.host
  11961. : u.end - u.host;
  11962. struct mg_str s = mg_str_n(url + u.host, n);
  11963. return s;
  11964. }
  11965. const char *mg_url_uri(const char *url) {
  11966. struct url u = urlparse(url);
  11967. return u.uri ? url + u.uri : "/";
  11968. }
  11969. unsigned short mg_url_port(const char *url) {
  11970. struct url u = urlparse(url);
  11971. unsigned short port = 0;
  11972. if (strncmp(url, "http:", 5) == 0 || strncmp(url, "ws:", 3) == 0) port = 80;
  11973. if (strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0)
  11974. port = 443;
  11975. if (strncmp(url, "mqtt:", 5) == 0) port = 1883;
  11976. if (strncmp(url, "mqtts:", 6) == 0) port = 8883;
  11977. if (u.port) port = (unsigned short) atoi(url + u.port);
  11978. return port;
  11979. }
  11980. struct mg_str mg_url_user(const char *url) {
  11981. struct url u = urlparse(url);
  11982. struct mg_str s = mg_str("");
  11983. if (u.user && (u.pass || u.host)) {
  11984. size_t n = u.pass ? u.pass - u.user - 1 : u.host - u.user - 1;
  11985. s = mg_str_n(url + u.user, n);
  11986. }
  11987. return s;
  11988. }
  11989. struct mg_str mg_url_pass(const char *url) {
  11990. struct url u = urlparse(url);
  11991. struct mg_str s = mg_str_n("", 0UL);
  11992. if (u.pass && u.host) {
  11993. size_t n = u.host - u.pass - 1;
  11994. s = mg_str_n(url + u.pass, n);
  11995. }
  11996. return s;
  11997. }
  11998. #ifdef MG_ENABLE_LINES
  11999. #line 1 "src/util.c"
  12000. #endif
  12001. // Not using memset for zeroing memory, cause it can be dropped by compiler
  12002. // See https://github.com/cesanta/mongoose/pull/1265
  12003. void mg_bzero(volatile unsigned char *buf, size_t len) {
  12004. if (buf != NULL) {
  12005. while (len--) *buf++ = 0;
  12006. }
  12007. }
  12008. #if MG_ENABLE_CUSTOM_RANDOM
  12009. #else
  12010. void mg_random(void *buf, size_t len) {
  12011. bool done = false;
  12012. unsigned char *p = (unsigned char *) buf;
  12013. #if MG_ARCH == MG_ARCH_ESP32
  12014. while (len--) *p++ = (unsigned char) (esp_random() & 255);
  12015. done = true;
  12016. #elif MG_ARCH == MG_ARCH_WIN32
  12017. #elif MG_ARCH == MG_ARCH_UNIX
  12018. FILE *fp = fopen("/dev/urandom", "rb");
  12019. if (fp != NULL) {
  12020. if (fread(buf, 1, len, fp) == len) done = true;
  12021. fclose(fp);
  12022. }
  12023. #endif
  12024. // If everything above did not work, fallback to a pseudo random generator
  12025. while (!done && len--) *p++ = (unsigned char) (rand() & 255);
  12026. }
  12027. #endif
  12028. char *mg_random_str(char *buf, size_t len) {
  12029. size_t i;
  12030. mg_random(buf, len);
  12031. for (i = 0; i < len; i++) {
  12032. uint8_t c = ((uint8_t *) buf)[i] % 62U;
  12033. buf[i] = i == len - 1 ? (char) '\0' // 0-terminate last byte
  12034. : c < 26 ? (char) ('a' + c) // lowercase
  12035. : c < 52 ? (char) ('A' + c - 26) // uppercase
  12036. : (char) ('0' + c - 52); // numeric
  12037. }
  12038. return buf;
  12039. }
  12040. uint32_t mg_ntohl(uint32_t net) {
  12041. uint8_t data[4] = {0, 0, 0, 0};
  12042. memcpy(&data, &net, sizeof(data));
  12043. return (((uint32_t) data[3]) << 0) | (((uint32_t) data[2]) << 8) |
  12044. (((uint32_t) data[1]) << 16) | (((uint32_t) data[0]) << 24);
  12045. }
  12046. uint16_t mg_ntohs(uint16_t net) {
  12047. uint8_t data[2] = {0, 0};
  12048. memcpy(&data, &net, sizeof(data));
  12049. return (uint16_t) ((uint16_t) data[1] | (((uint16_t) data[0]) << 8));
  12050. }
  12051. uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len) {
  12052. static const uint32_t crclut[16] = {
  12053. // table for polynomial 0xEDB88320 (reflected)
  12054. 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
  12055. 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
  12056. 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
  12057. crc = ~crc;
  12058. while (len--) {
  12059. uint8_t byte = *(uint8_t *) buf++;
  12060. crc = crclut[(crc ^ byte) & 0x0F] ^ (crc >> 4);
  12061. crc = crclut[(crc ^ (byte >> 4)) & 0x0F] ^ (crc >> 4);
  12062. }
  12063. return ~crc;
  12064. }
  12065. static int isbyte(int n) {
  12066. return n >= 0 && n <= 255;
  12067. }
  12068. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  12069. int n, a, b, c, d, slash = 32, len = 0;
  12070. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  12071. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  12072. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  12073. slash < 33) {
  12074. len = n;
  12075. *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) |
  12076. (uint32_t) d;
  12077. *mask = slash ? (uint32_t) (0xffffffffU << (32 - slash)) : (uint32_t) 0;
  12078. }
  12079. return len;
  12080. }
  12081. int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) {
  12082. struct mg_str k, v;
  12083. int allowed = acl.len == 0 ? '+' : '-'; // If any ACL is set, deny by default
  12084. uint32_t remote_ip4;
  12085. if (remote_ip->is_ip6) {
  12086. return -1; // TODO(): handle IPv6 ACL and addresses
  12087. } else { // IPv4
  12088. memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4));
  12089. while (mg_commalist(&acl, &k, &v)) {
  12090. uint32_t net, mask;
  12091. if (k.ptr[0] != '+' && k.ptr[0] != '-') return -1;
  12092. if (parse_net(&k.ptr[1], &net, &mask) == 0) return -2;
  12093. if ((mg_ntohl(remote_ip4) & mask) == net) allowed = k.ptr[0];
  12094. }
  12095. }
  12096. return allowed == '+';
  12097. }
  12098. #if MG_ENABLE_CUSTOM_MILLIS
  12099. #else
  12100. uint64_t mg_millis(void) {
  12101. #if MG_ARCH == MG_ARCH_WIN32
  12102. return GetTickCount();
  12103. #elif MG_ARCH == MG_ARCH_RP2040
  12104. return time_us_64() / 1000;
  12105. #elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \
  12106. MG_ARCH == MG_ARCH_FREERTOS
  12107. return xTaskGetTickCount() * portTICK_PERIOD_MS;
  12108. #elif MG_ARCH == MG_ARCH_AZURERTOS
  12109. return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND);
  12110. #elif MG_ARCH == MG_ARCH_TIRTOS
  12111. return (uint64_t) Clock_getTicks();
  12112. #elif MG_ARCH == MG_ARCH_ZEPHYR
  12113. return (uint64_t) k_uptime_get();
  12114. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
  12115. return (uint64_t) rt_time_get();
  12116. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
  12117. return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq());
  12118. #elif MG_ARCH == MG_ARCH_RTTHREAD
  12119. return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND);
  12120. #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
  12121. // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
  12122. // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
  12123. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000;
  12124. #elif MG_ARCH == MG_ARCH_UNIX
  12125. struct timespec ts = {0, 0};
  12126. // See #1615 - prefer monotonic clock
  12127. #if defined(CLOCK_MONOTONIC_RAW)
  12128. // Raw hardware-based time that is not subject to NTP adjustment
  12129. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  12130. #elif defined(CLOCK_MONOTONIC)
  12131. // Affected by the incremental adjustments performed by adjtime and NTP
  12132. clock_gettime(CLOCK_MONOTONIC, &ts);
  12133. #else
  12134. // Affected by discontinuous jumps in the system time and by the incremental
  12135. // adjustments performed by adjtime and NTP
  12136. clock_gettime(CLOCK_REALTIME, &ts);
  12137. #endif
  12138. return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000);
  12139. #elif defined(ARDUINO)
  12140. return (uint64_t) millis();
  12141. #else
  12142. return (uint64_t) (time(NULL) * 1000);
  12143. #endif
  12144. }
  12145. #endif
  12146. #ifdef MG_ENABLE_LINES
  12147. #line 1 "src/ws.c"
  12148. #endif
  12149. struct ws_msg {
  12150. uint8_t flags;
  12151. size_t header_len;
  12152. size_t data_len;
  12153. };
  12154. size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
  12155. va_list *ap) {
  12156. size_t len = c->send.len;
  12157. size_t n = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  12158. mg_ws_wrap(c, c->send.len - len, op);
  12159. return n;
  12160. }
  12161. size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...) {
  12162. size_t len = 0;
  12163. va_list ap;
  12164. va_start(ap, fmt);
  12165. len = mg_ws_vprintf(c, op, fmt, &ap);
  12166. va_end(ap);
  12167. return len;
  12168. }
  12169. static void ws_handshake(struct mg_connection *c, const struct mg_str *wskey,
  12170. const struct mg_str *wsproto, const char *fmt,
  12171. va_list *ap) {
  12172. const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  12173. unsigned char sha[20], b64_sha[30];
  12174. mg_sha1_ctx sha_ctx;
  12175. mg_sha1_init(&sha_ctx);
  12176. mg_sha1_update(&sha_ctx, (unsigned char *) wskey->ptr, wskey->len);
  12177. mg_sha1_update(&sha_ctx, (unsigned char *) magic, 36);
  12178. mg_sha1_final(sha, &sha_ctx);
  12179. mg_base64_encode(sha, sizeof(sha), (char *) b64_sha, sizeof(b64_sha));
  12180. mg_xprintf(mg_pfn_iobuf, &c->send,
  12181. "HTTP/1.1 101 Switching Protocols\r\n"
  12182. "Upgrade: websocket\r\n"
  12183. "Connection: Upgrade\r\n"
  12184. "Sec-WebSocket-Accept: %s\r\n",
  12185. b64_sha);
  12186. if (fmt != NULL) mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  12187. if (wsproto != NULL) {
  12188. mg_printf(c, "Sec-WebSocket-Protocol: %.*s\r\n", (int) wsproto->len,
  12189. wsproto->ptr);
  12190. }
  12191. mg_send(c, "\r\n", 2);
  12192. }
  12193. static uint32_t be32(const uint8_t *p) {
  12194. return (((uint32_t) p[3]) << 0) | (((uint32_t) p[2]) << 8) |
  12195. (((uint32_t) p[1]) << 16) | (((uint32_t) p[0]) << 24);
  12196. }
  12197. static size_t ws_process(uint8_t *buf, size_t len, struct ws_msg *msg) {
  12198. size_t i, n = 0, mask_len = 0;
  12199. memset(msg, 0, sizeof(*msg));
  12200. if (len >= 2) {
  12201. n = buf[1] & 0x7f; // Frame length
  12202. mask_len = buf[1] & 128 ? 4 : 0; // last bit is a mask bit
  12203. msg->flags = buf[0];
  12204. if (n < 126 && len >= mask_len) {
  12205. msg->data_len = n;
  12206. msg->header_len = 2 + mask_len;
  12207. } else if (n == 126 && len >= 4 + mask_len) {
  12208. msg->header_len = 4 + mask_len;
  12209. msg->data_len = (((size_t) buf[2]) << 8) | buf[3];
  12210. } else if (len >= 10 + mask_len) {
  12211. msg->header_len = 10 + mask_len;
  12212. msg->data_len =
  12213. (size_t) (((uint64_t) be32(buf + 2) << 32) + be32(buf + 6));
  12214. }
  12215. }
  12216. // Sanity check, and integer overflow protection for the boundary check below
  12217. // data_len should not be larger than 1 Gb
  12218. if (msg->data_len > 1024 * 1024 * 1024) return 0;
  12219. if (msg->header_len + msg->data_len > len) return 0;
  12220. if (mask_len > 0) {
  12221. uint8_t *p = buf + msg->header_len, *m = p - mask_len;
  12222. for (i = 0; i < msg->data_len; i++) p[i] ^= m[i & 3];
  12223. }
  12224. return msg->header_len + msg->data_len;
  12225. }
  12226. static size_t mkhdr(size_t len, int op, bool is_client, uint8_t *buf) {
  12227. size_t n = 0;
  12228. buf[0] = (uint8_t) (op | 128);
  12229. if (len < 126) {
  12230. buf[1] = (unsigned char) len;
  12231. n = 2;
  12232. } else if (len < 65536) {
  12233. uint16_t tmp = mg_htons((uint16_t) len);
  12234. buf[1] = 126;
  12235. memcpy(&buf[2], &tmp, sizeof(tmp));
  12236. n = 4;
  12237. } else {
  12238. uint32_t tmp;
  12239. buf[1] = 127;
  12240. tmp = mg_htonl((uint32_t) (((uint64_t) len) >> 32));
  12241. memcpy(&buf[2], &tmp, sizeof(tmp));
  12242. tmp = mg_htonl((uint32_t) (len & 0xffffffffU));
  12243. memcpy(&buf[6], &tmp, sizeof(tmp));
  12244. n = 10;
  12245. }
  12246. if (is_client) {
  12247. buf[1] |= 1 << 7; // Set masking flag
  12248. mg_random(&buf[n], 4);
  12249. n += 4;
  12250. }
  12251. return n;
  12252. }
  12253. static void mg_ws_mask(struct mg_connection *c, size_t len) {
  12254. if (c->is_client && c->send.buf != NULL) {
  12255. size_t i;
  12256. uint8_t *p = c->send.buf + c->send.len - len, *mask = p - 4;
  12257. for (i = 0; i < len; i++) p[i] ^= mask[i & 3];
  12258. }
  12259. }
  12260. size_t mg_ws_send(struct mg_connection *c, const void *buf, size_t len,
  12261. int op) {
  12262. uint8_t header[14];
  12263. size_t header_len = mkhdr(len, op, c->is_client, header);
  12264. mg_send(c, header, header_len);
  12265. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  12266. mg_send(c, buf, len);
  12267. mg_ws_mask(c, len);
  12268. return header_len + len;
  12269. }
  12270. static bool mg_ws_client_handshake(struct mg_connection *c) {
  12271. int n = mg_http_get_request_len(c->recv.buf, c->recv.len);
  12272. if (n < 0) {
  12273. mg_error(c, "not http"); // Some just, not an HTTP request
  12274. } else if (n > 0) {
  12275. if (n < 15 || memcmp(c->recv.buf + 9, "101", 3) != 0) {
  12276. mg_error(c, "ws handshake error");
  12277. } else {
  12278. struct mg_http_message hm;
  12279. if (mg_http_parse((char *) c->recv.buf, c->recv.len, &hm)) {
  12280. c->is_websocket = 1;
  12281. mg_call(c, MG_EV_WS_OPEN, &hm);
  12282. } else {
  12283. mg_error(c, "ws handshake error");
  12284. }
  12285. }
  12286. mg_iobuf_del(&c->recv, 0, (size_t) n);
  12287. } else {
  12288. return true; // Request is not yet received, quit event handler
  12289. }
  12290. return false; // Continue event handler
  12291. }
  12292. static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
  12293. struct ws_msg msg;
  12294. size_t ofs = (size_t) c->pfn_data;
  12295. // assert(ofs < c->recv.len);
  12296. if (ev == MG_EV_READ) {
  12297. if (c->is_client && !c->is_websocket && mg_ws_client_handshake(c)) return;
  12298. while (ws_process(c->recv.buf + ofs, c->recv.len - ofs, &msg) > 0) {
  12299. char *s = (char *) c->recv.buf + ofs + msg.header_len;
  12300. struct mg_ws_message m = {{s, msg.data_len}, msg.flags};
  12301. size_t len = msg.header_len + msg.data_len;
  12302. uint8_t final = msg.flags & 128, op = msg.flags & 15;
  12303. // MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
  12304. // (int) m.data.len, (int) m.data.len, m.data.ptr));
  12305. switch (op) {
  12306. case WEBSOCKET_OP_CONTINUE:
  12307. mg_call(c, MG_EV_WS_CTL, &m);
  12308. break;
  12309. case WEBSOCKET_OP_PING:
  12310. MG_DEBUG(("%s", "WS PONG"));
  12311. mg_ws_send(c, s, msg.data_len, WEBSOCKET_OP_PONG);
  12312. mg_call(c, MG_EV_WS_CTL, &m);
  12313. break;
  12314. case WEBSOCKET_OP_PONG:
  12315. mg_call(c, MG_EV_WS_CTL, &m);
  12316. break;
  12317. case WEBSOCKET_OP_TEXT:
  12318. case WEBSOCKET_OP_BINARY:
  12319. if (final) mg_call(c, MG_EV_WS_MSG, &m);
  12320. break;
  12321. case WEBSOCKET_OP_CLOSE:
  12322. MG_DEBUG(("%lu WS CLOSE", c->id));
  12323. mg_call(c, MG_EV_WS_CTL, &m);
  12324. // Echo the payload of the received CLOSE message back to the sender
  12325. mg_ws_send(c, m.data.ptr, m.data.len, WEBSOCKET_OP_CLOSE);
  12326. c->is_draining = 1;
  12327. break;
  12328. default:
  12329. // Per RFC6455, close conn when an unknown op is recvd
  12330. mg_error(c, "unknown WS op %d", op);
  12331. break;
  12332. }
  12333. // Handle fragmented frames: strip header, keep in c->recv
  12334. if (final == 0 || op == 0) {
  12335. if (op) ofs++, len--, msg.header_len--; // First frame
  12336. mg_iobuf_del(&c->recv, ofs, msg.header_len); // Strip header
  12337. len -= msg.header_len;
  12338. ofs += len;
  12339. c->pfn_data = (void *) ofs;
  12340. // MG_INFO(("FRAG %d [%.*s]", (int) ofs, (int) ofs, c->recv.buf));
  12341. }
  12342. // Remove non-fragmented frame
  12343. if (final && op) mg_iobuf_del(&c->recv, ofs, len);
  12344. // Last chunk of the fragmented frame
  12345. if (final && !op) {
  12346. m.flags = c->recv.buf[0];
  12347. m.data = mg_str_n((char *) &c->recv.buf[1], (size_t) (ofs - 1));
  12348. mg_call(c, MG_EV_WS_MSG, &m);
  12349. mg_iobuf_del(&c->recv, 0, ofs);
  12350. ofs = 0;
  12351. c->pfn_data = NULL;
  12352. }
  12353. }
  12354. }
  12355. (void) ev_data;
  12356. }
  12357. struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
  12358. mg_event_handler_t fn, void *fn_data,
  12359. const char *fmt, ...) {
  12360. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  12361. if (c != NULL) {
  12362. char nonce[16], key[30];
  12363. struct mg_str host = mg_url_host(url);
  12364. mg_random(nonce, sizeof(nonce));
  12365. mg_base64_encode((unsigned char *) nonce, sizeof(nonce), key, sizeof(key));
  12366. mg_xprintf(mg_pfn_iobuf, &c->send,
  12367. "GET %s HTTP/1.1\r\n"
  12368. "Upgrade: websocket\r\n"
  12369. "Host: %.*s\r\n"
  12370. "Connection: Upgrade\r\n"
  12371. "Sec-WebSocket-Version: 13\r\n"
  12372. "Sec-WebSocket-Key: %s\r\n",
  12373. mg_url_uri(url), (int) host.len, host.ptr, key);
  12374. if (fmt != NULL) {
  12375. va_list ap;
  12376. va_start(ap, fmt);
  12377. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  12378. va_end(ap);
  12379. }
  12380. mg_xprintf(mg_pfn_iobuf, &c->send, "\r\n");
  12381. c->pfn = mg_ws_cb;
  12382. c->pfn_data = NULL;
  12383. }
  12384. return c;
  12385. }
  12386. void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
  12387. const char *fmt, ...) {
  12388. struct mg_str *wskey = mg_http_get_header(hm, "Sec-WebSocket-Key");
  12389. c->pfn = mg_ws_cb;
  12390. c->pfn_data = NULL;
  12391. if (wskey == NULL) {
  12392. mg_http_reply(c, 426, "", "WS upgrade expected\n");
  12393. c->is_draining = 1;
  12394. } else {
  12395. struct mg_str *wsproto = mg_http_get_header(hm, "Sec-WebSocket-Protocol");
  12396. va_list ap;
  12397. va_start(ap, fmt);
  12398. ws_handshake(c, wskey, wsproto, fmt, &ap);
  12399. va_end(ap);
  12400. c->is_websocket = 1;
  12401. c->is_resp = 0;
  12402. mg_call(c, MG_EV_WS_OPEN, hm);
  12403. }
  12404. }
  12405. size_t mg_ws_wrap(struct mg_connection *c, size_t len, int op) {
  12406. uint8_t header[14], *p;
  12407. size_t header_len = mkhdr(len, op, c->is_client, header);
  12408. // NOTE: order of operations is important!
  12409. mg_iobuf_add(&c->send, c->send.len, NULL, header_len);
  12410. p = &c->send.buf[c->send.len - len]; // p points to data
  12411. memmove(p, p - header_len, len); // Shift data
  12412. memcpy(p - header_len, header, header_len); // Prepend header
  12413. mg_ws_mask(c, len); // Mask data
  12414. return c->send.len;
  12415. }
  12416. #ifdef MG_ENABLE_LINES
  12417. #line 1 "src/drivers/cmsis.c"
  12418. #endif
  12419. // https://arm-software.github.io/CMSIS_5/Driver/html/index.html
  12420. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
  12421. extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0;
  12422. extern ARM_DRIVER_ETH_PHY Driver_ETH_PHY0;
  12423. static struct mg_tcpip_if *s_ifp;
  12424. static void mac_cb(uint32_t);
  12425. static bool cmsis_init(struct mg_tcpip_if *);
  12426. static bool cmsis_up(struct mg_tcpip_if *);
  12427. static size_t cmsis_tx(const void *, size_t, struct mg_tcpip_if *);
  12428. static size_t cmsis_rx(void *, size_t, struct mg_tcpip_if *);
  12429. struct mg_tcpip_driver mg_tcpip_driver_cmsis = {cmsis_init, cmsis_tx, NULL,
  12430. cmsis_up};
  12431. static bool cmsis_init(struct mg_tcpip_if *ifp) {
  12432. ARM_ETH_MAC_ADDR addr;
  12433. s_ifp = ifp;
  12434. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12435. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  12436. ARM_ETH_MAC_CAPABILITIES cap = mac->GetCapabilities();
  12437. if (mac->Initialize(mac_cb) != ARM_DRIVER_OK) return false;
  12438. if (phy->Initialize(mac->PHY_Read, mac->PHY_Write) != ARM_DRIVER_OK)
  12439. return false;
  12440. if (cap.event_rx_frame == 0) // polled mode driver
  12441. mg_tcpip_driver_cmsis.rx = cmsis_rx;
  12442. mac->PowerControl(ARM_POWER_FULL);
  12443. if (cap.mac_address) { // driver provides MAC address
  12444. mac->GetMacAddress(&addr);
  12445. memcpy(ifp->mac, &addr, sizeof(ifp->mac));
  12446. } else { // we provide MAC address
  12447. memcpy(&addr, ifp->mac, sizeof(addr));
  12448. mac->SetMacAddress(&addr);
  12449. }
  12450. phy->PowerControl(ARM_POWER_FULL);
  12451. phy->SetInterface(cap.media_interface);
  12452. phy->SetMode(ARM_ETH_PHY_AUTO_NEGOTIATE);
  12453. return true;
  12454. }
  12455. static size_t cmsis_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
  12456. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12457. if (mac->SendFrame(buf, (uint32_t) len, 0) != ARM_DRIVER_OK) {
  12458. ifp->nerr++;
  12459. return 0;
  12460. }
  12461. ifp->nsent++;
  12462. return len;
  12463. }
  12464. static bool cmsis_up(struct mg_tcpip_if *ifp) {
  12465. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  12466. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12467. bool up = (phy->GetLinkState() == ARM_ETH_LINK_UP) ? 1 : 0; // link state
  12468. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // just went up
  12469. ARM_ETH_LINK_INFO st = phy->GetLinkInfo();
  12470. mac->Control(ARM_ETH_MAC_CONFIGURE,
  12471. (st.speed << ARM_ETH_MAC_SPEED_Pos) |
  12472. (st.duplex << ARM_ETH_MAC_DUPLEX_Pos) |
  12473. ARM_ETH_MAC_ADDRESS_BROADCAST);
  12474. MG_DEBUG(("Link is %uM %s-duplex",
  12475. (st.speed == 2) ? 1000
  12476. : st.speed ? 100
  12477. : 10,
  12478. st.duplex ? "full" : "half"));
  12479. mac->Control(ARM_ETH_MAC_CONTROL_TX, 1);
  12480. mac->Control(ARM_ETH_MAC_CONTROL_RX, 1);
  12481. } else if ((ifp->state != MG_TCPIP_STATE_DOWN) && !up) { // just went down
  12482. mac->Control(ARM_ETH_MAC_FLUSH,
  12483. ARM_ETH_MAC_FLUSH_TX | ARM_ETH_MAC_FLUSH_RX);
  12484. mac->Control(ARM_ETH_MAC_CONTROL_TX, 0);
  12485. mac->Control(ARM_ETH_MAC_CONTROL_RX, 0);
  12486. }
  12487. return up;
  12488. }
  12489. static void mac_cb(uint32_t ev) {
  12490. if ((ev & ARM_ETH_MAC_EVENT_RX_FRAME) == 0) return;
  12491. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12492. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  12493. if (len >= 60 && len <= 1518) { // proper frame
  12494. char *p;
  12495. if (mg_queue_book(&s_ifp->recv_queue, &p, len) >= len) { // have room
  12496. if ((len = mac->ReadFrame((uint8_t *) p, len)) > 0) { // copy succeeds
  12497. mg_queue_add(&s_ifp->recv_queue, len);
  12498. s_ifp->nrecv++;
  12499. }
  12500. return;
  12501. }
  12502. s_ifp->ndrop++;
  12503. }
  12504. mac->ReadFrame(NULL, 0); // otherwise, discard
  12505. }
  12506. static size_t cmsis_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  12507. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12508. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  12509. if (len >= 60 && len <= 1518 &&
  12510. ((len = mac->ReadFrame(buf, (uint32_t) buflen)) > 0))
  12511. return len;
  12512. if (len > 0) mac->ReadFrame(NULL, 0); // discard bad frames
  12513. (void) ifp;
  12514. return 0;
  12515. }
  12516. #endif
  12517. #ifdef MG_ENABLE_LINES
  12518. #line 1 "src/drivers/imxrt.c"
  12519. #endif
  12520. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_IMXRT) && MG_ENABLE_DRIVER_IMXRT
  12521. struct imxrt_enet {
  12522. volatile uint32_t RESERVED0, EIR, EIMR, RESERVED1, RDAR, TDAR, RESERVED2[3],
  12523. ECR, RESERVED3[6], MMFR, MSCR, RESERVED4[7], MIBC, RESERVED5[7], RCR,
  12524. RESERVED6[15], TCR, RESERVED7[7], PALR, PAUR, OPD, TXIC0, TXIC1, TXIC2,
  12525. RESERVED8, RXIC0, RXIC1, RXIC2, RESERVED9[3], IAUR, IALR, GAUR, GALR,
  12526. RESERVED10[7], TFWR, RESERVED11[14], RDSR, TDSR, MRBR[2], RSFL, RSEM,
  12527. RAEM, RAFL, TSEM, TAEM, TAFL, TIPG, FTRL, RESERVED12[3], TACC, RACC,
  12528. RESERVED13[15], RMON_T_PACKETS, RMON_T_BC_PKT, RMON_T_MC_PKT,
  12529. RMON_T_CRC_ALIGN, RMON_T_UNDERSIZE, RMON_T_OVERSIZE, RMON_T_FRAG,
  12530. RMON_T_JAB, RMON_T_COL, RMON_T_P64, RMON_T_P65TO127, RMON_T_P128TO255,
  12531. RMON_T_P256TO511, RMON_T_P512TO1023, RMON_T_P1024TO2048, RMON_T_GTE2048,
  12532. RMON_T_OCTETS, IEEE_T_DROP, IEEE_T_FRAME_OK, IEEE_T_1COL, IEEE_T_MCOL,
  12533. IEEE_T_DEF, IEEE_T_LCOL, IEEE_T_EXCOL, IEEE_T_MACERR, IEEE_T_CSERR,
  12534. IEEE_T_SQE, IEEE_T_FDXFC, IEEE_T_OCTETS_OK, RESERVED14[3], RMON_R_PACKETS,
  12535. RMON_R_BC_PKT, RMON_R_MC_PKT, RMON_R_CRC_ALIGN, RMON_R_UNDERSIZE,
  12536. RMON_R_OVERSIZE, RMON_R_FRAG, RMON_R_JAB, RESERVED15, RMON_R_P64,
  12537. RMON_R_P65TO127, RMON_R_P128TO255, RMON_R_P256TO511, RMON_R_P512TO1023,
  12538. RMON_R_P1024TO2047, RMON_R_GTE2048, RMON_R_OCTETS, IEEE_R_DROP,
  12539. IEEE_R_FRAME_OK, IEEE_R_CRC, IEEE_R_ALIGN, IEEE_R_MACERR, IEEE_R_FDXFC,
  12540. IEEE_R_OCTETS_OK, RESERVED16[71], ATCR, ATVR, ATOFF, ATPER, ATCOR, ATINC,
  12541. ATSTMP, RESERVED17[122], TGSR, TCSR0, TCCR0, TCSR1, TCCR1, TCSR2, TCCR2,
  12542. TCSR3;
  12543. };
  12544. #undef ENET
  12545. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x402D8000U)
  12546. #define ETH_PKT_SIZE 1536 // Max frame size, 64-bit aligned
  12547. #define ETH_DESC_CNT 4 // Descriptors count
  12548. struct enet_desc {
  12549. uint16_t length; // Data length
  12550. uint16_t control; // Control and status
  12551. uint32_t *buffer; // Data ptr
  12552. };
  12553. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  12554. #define MG_64BIT_ALIGNED __attribute__((aligned((64U))))
  12555. // Descriptors: in non-cached area (TODO(scaprile)), 64-bit aligned
  12556. // Buffers: 64-bit aligned
  12557. static volatile struct enet_desc s_rxdesc[ETH_DESC_CNT] MG_64BIT_ALIGNED;
  12558. static volatile struct enet_desc s_txdesc[ETH_DESC_CNT] MG_64BIT_ALIGNED;
  12559. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BIT_ALIGNED;
  12560. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BIT_ALIGNED;
  12561. static struct mg_tcpip_if *s_ifp; // MIP interface
  12562. enum { PHY_BCR = 0, PHY_BSR = 1, PHY_ID1 = 2, PHY_ID2 = 3 };
  12563. static uint16_t enet_phy_read(uint8_t addr, uint8_t reg) {
  12564. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  12565. ENET->MMFR = (1 << 30) | (2 << 28) | (addr << 23) | (reg << 18) | (2 << 16);
  12566. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  12567. return ENET->MMFR & 0xffff;
  12568. }
  12569. static void enet_phy_write(uint8_t addr, uint8_t reg, uint16_t val) {
  12570. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  12571. ENET->MMFR =
  12572. (1 << 30) | (1 << 28) | (addr << 23) | (reg << 18) | (2 << 16) | val;
  12573. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  12574. }
  12575. static uint32_t enet_phy_id(uint8_t addr) {
  12576. uint16_t phy_id1 = enet_phy_read(addr, PHY_ID1);
  12577. uint16_t phy_id2 = enet_phy_read(addr, PHY_ID2);
  12578. return (uint32_t) phy_id1 << 16 | phy_id2;
  12579. }
  12580. // MDC clock is generated from IPS Bus clock (ipg_clk); as per 802.3,
  12581. // it must not exceed 2.5MHz
  12582. // The PHY receives the PLL6-generated 50MHz clock
  12583. static bool mg_tcpip_driver_imxrt_init(struct mg_tcpip_if *ifp) {
  12584. struct mg_tcpip_driver_imxrt_data *d =
  12585. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  12586. s_ifp = ifp;
  12587. // Init RX descriptors
  12588. for (int i = 0; i < ETH_DESC_CNT; i++) {
  12589. s_rxdesc[i].control = MG_BIT(15); // Own (E)
  12590. s_rxdesc[i].buffer = (uint32_t *) s_rxbuf[i]; // Point to data buffer
  12591. }
  12592. s_rxdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  12593. // Init TX descriptors
  12594. for (int i = 0; i < ETH_DESC_CNT; i++) {
  12595. // s_txdesc[i].control = MG_BIT(10); // Own (TC)
  12596. s_txdesc[i].buffer = (uint32_t *) s_txbuf[i];
  12597. }
  12598. s_txdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  12599. ENET->ECR = MG_BIT(0); // Software reset, disable
  12600. while ((ENET->ECR & MG_BIT(0))) (void) 0; // Wait until done
  12601. // Set MDC clock divider. If user told us the value, use it.
  12602. // TODO(): Otherwise, guess (currently assuming max freq)
  12603. int cr = (d == NULL || d->mdc_cr < 0) ? 24 : d->mdc_cr;
  12604. ENET->MSCR = (1 << 8) | ((cr & 0x3f) << 1); // HOLDTIME 2 clks
  12605. enet_phy_write(d->phy_addr, PHY_BCR, MG_BIT(15)); // Reset PHY
  12606. enet_phy_write(d->phy_addr, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  12607. // PHY: Enable 50 MHz external ref clock at XI (preserve defaults)
  12608. uint32_t id = enet_phy_id(d->phy_addr);
  12609. MG_INFO(("PHY ID: %#04x %#04x", (uint16_t) (id >> 16), (uint16_t) id));
  12610. // 2000 a140 - TI DP83825I
  12611. // 0007 c0fx - LAN8720
  12612. // 0022 1561 - KSZ8081RNB
  12613. if ((id & 0xffff0000) == 0x220000) { // KSZ8081RNB, like EVK-RTxxxx boards
  12614. enet_phy_write(d->phy_addr, 31,
  12615. MG_BIT(15) | MG_BIT(8) | MG_BIT(7)); // PC2R
  12616. } else if ((id & 0xffff0000) == 0x20000000) { // DP83825I, like Teensy4.1
  12617. enet_phy_write(d->phy_addr, 23, 0x81); // 50MHz clock input
  12618. enet_phy_write(d->phy_addr, 24, 0x280); // LED status, active high
  12619. } else { // Default to LAN8720
  12620. MG_INFO(("Defaulting to LAN8720 PHY...")); // TODO()
  12621. }
  12622. // Select RMII mode, 100M, keep CRC, set max rx length, disable loop
  12623. ENET->RCR = (1518 << 16) | MG_BIT(8) | MG_BIT(2);
  12624. // ENET->RCR |= MG_BIT(3); // Receive all
  12625. ENET->TCR = MG_BIT(2); // Full-duplex
  12626. ENET->RDSR = (uint32_t) (uintptr_t) s_rxdesc;
  12627. ENET->TDSR = (uint32_t) (uintptr_t) s_txdesc;
  12628. ENET->MRBR[0] = ETH_PKT_SIZE; // Same size for RX/TX buffers
  12629. // MAC address filtering (bytes in reversed order)
  12630. ENET->PAUR = ((uint32_t) ifp->mac[4] << 24U) | (uint32_t) ifp->mac[5] << 16U;
  12631. ENET->PALR = (uint32_t) (ifp->mac[0] << 24U) |
  12632. ((uint32_t) ifp->mac[1] << 16U) |
  12633. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  12634. ENET->ECR = MG_BIT(8) | MG_BIT(1); // Little-endian CPU, Enable
  12635. ENET->EIMR = MG_BIT(25); // Set interrupt mask
  12636. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  12637. ENET->TDAR = MG_BIT(24); // Transmit Descriptors have changed
  12638. // ENET->OPD = 0x10014;
  12639. return true;
  12640. }
  12641. // Transmit frame
  12642. static size_t mg_tcpip_driver_imxrt_tx(const void *buf, size_t len,
  12643. struct mg_tcpip_if *ifp) {
  12644. static int s_txno; // Current descriptor index
  12645. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  12646. ifp->nerr++;
  12647. MG_ERROR(("Frame too big, %ld", (long) len));
  12648. len = (size_t) -1; // fail
  12649. } else if ((s_txdesc[s_txno].control & MG_BIT(15))) {
  12650. MG_ERROR(("No descriptors available"));
  12651. len = 0; // retry later
  12652. } else {
  12653. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  12654. s_txdesc[s_txno].length = (uint16_t) len; // Set data len
  12655. // Table 37-34, R, L, TC (Ready, last, transmit CRC after frame
  12656. s_txdesc[s_txno].control |=
  12657. (uint16_t) (MG_BIT(15) | MG_BIT(11) | MG_BIT(10));
  12658. ENET->TDAR = MG_BIT(24); // Descriptor ring updated
  12659. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  12660. }
  12661. (void) ifp;
  12662. return len;
  12663. }
  12664. static bool mg_tcpip_driver_imxrt_up(struct mg_tcpip_if *ifp) {
  12665. struct mg_tcpip_driver_imxrt_data *d =
  12666. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  12667. uint32_t bsr = enet_phy_read(d->phy_addr, PHY_BSR);
  12668. bool up = bsr & MG_BIT(2) ? 1 : 0;
  12669. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  12670. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  12671. // if(link is slow or half) set flags otherwise
  12672. // reg = tmp
  12673. uint32_t tcr = ENET->TCR | MG_BIT(2); // Full-duplex
  12674. uint32_t rcr = ENET->RCR & ~MG_BIT(9); // 100M
  12675. uint32_t phy_id = enet_phy_id(d->phy_addr);
  12676. if ((phy_id & 0xffff0000) == 0x220000) { // KSZ8081RNB
  12677. uint16_t pc1r = enet_phy_read(d->phy_addr, 30); // Read PC1R
  12678. if ((pc1r & 3) == 1) rcr |= MG_BIT(9); // 10M
  12679. if ((pc1r & MG_BIT(2)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12680. } else if ((phy_id & 0xffff0000) == 0x20000000) { // DP83825I
  12681. uint16_t physts = enet_phy_read(d->phy_addr, 16); // Read PHYSTS
  12682. if (physts & MG_BIT(1)) rcr |= MG_BIT(9); // 10M
  12683. if ((physts & MG_BIT(2)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12684. } else { // Default to LAN8720
  12685. uint16_t scsr = enet_phy_read(d->phy_addr, 31); // Read CSCR
  12686. if ((scsr & MG_BIT(3)) == 0) rcr |= MG_BIT(9); // 10M
  12687. if ((scsr & MG_BIT(4)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12688. }
  12689. ENET->TCR = tcr; // IRQ handler does not fiddle with these registers
  12690. ENET->RCR = rcr;
  12691. MG_DEBUG(("Link is %uM %s-duplex", rcr & MG_BIT(9) ? 10 : 100,
  12692. tcr & MG_BIT(2) ? "full" : "half"));
  12693. }
  12694. return up;
  12695. }
  12696. void ENET_IRQHandler(void);
  12697. static uint32_t s_rxno;
  12698. void ENET_IRQHandler(void) {
  12699. ENET->EIR = MG_BIT(25); // Ack IRQ
  12700. // Frame received, loop
  12701. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  12702. uint32_t r = s_rxdesc[s_rxno].control;
  12703. if (r & MG_BIT(15)) break; // exit when done
  12704. // skip partial/errored frames (Table 37-32)
  12705. if ((r & MG_BIT(11)) &&
  12706. !(r & (MG_BIT(5) | MG_BIT(4) | MG_BIT(2) | MG_BIT(1) | MG_BIT(0)))) {
  12707. size_t len = s_rxdesc[s_rxno].length;
  12708. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  12709. }
  12710. s_rxdesc[s_rxno].control |= MG_BIT(15);
  12711. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  12712. }
  12713. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  12714. // If b24 == 0, descriptors were exhausted and probably frames were dropped
  12715. }
  12716. struct mg_tcpip_driver mg_tcpip_driver_imxrt = {mg_tcpip_driver_imxrt_init,
  12717. mg_tcpip_driver_imxrt_tx, NULL,
  12718. mg_tcpip_driver_imxrt_up};
  12719. #endif
  12720. #ifdef MG_ENABLE_LINES
  12721. #line 1 "src/drivers/same54.c"
  12722. #endif
  12723. #if defined(MG_ENABLE_DRIVER_SAME54) && MG_ENABLE_DRIVER_SAME54
  12724. #include <sam.h>
  12725. #define ETH_PKT_SIZE 1536 // Max frame size
  12726. #define ETH_DESC_CNT 4 // Descriptors count
  12727. #define ETH_DS 2 // Descriptor size (words)
  12728. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  12729. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  12730. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  12731. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  12732. static uint8_t s_txno; // Current TX descriptor
  12733. static uint8_t s_rxno; // Current RX descriptor
  12734. static struct mg_tcpip_if *s_ifp; // MIP interface
  12735. enum { PHY_ADDR = 0, PHY_BCR = 0, PHY_BSR = 1 };
  12736. #define PHY_BCR_DUPLEX_MODE_Msk MG_BIT(8)
  12737. #define PHY_BCR_SPEED_Msk MG_BIT(13)
  12738. #define PHY_BSR_LINK_STATUS_Msk MG_BIT(2)
  12739. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  12740. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk |
  12741. GMAC_MAN_OP(2) | // Setting the read operation
  12742. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  12743. GMAC_MAN_REGA(reg); // Setting the register
  12744. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)) (void) 0;
  12745. return GMAC_REGS->GMAC_MAN & GMAC_MAN_DATA_Msk; // Getting the read value
  12746. }
  12747. #if 0
  12748. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  12749. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk | GMAC_MAN_OP(1) | // Setting the write operation
  12750. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  12751. GMAC_MAN_REGA(reg) | GMAC_MAN_DATA(val); // Setting the register
  12752. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)); // Waiting until the write op is complete
  12753. }
  12754. #endif
  12755. int get_clock_rate(struct mg_tcpip_driver_same54_data *d) {
  12756. if (d && d->mdc_cr >= 0 && d->mdc_cr <= 5) {
  12757. return d->mdc_cr;
  12758. } else {
  12759. // get MCLK from GCLK_GENERATOR 0
  12760. uint32_t div = 512;
  12761. uint32_t mclk;
  12762. if (!(GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_DIVSEL_Msk)) {
  12763. div = ((GCLK_REGS->GCLK_GENCTRL[0] & 0x00FF0000) >> 16);
  12764. if (div == 0) div = 1;
  12765. }
  12766. switch (GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_SRC_Msk) {
  12767. case GCLK_GENCTRL_SRC_XOSC0_Val:
  12768. mclk = 32000000UL; /* 32MHz */
  12769. break;
  12770. case GCLK_GENCTRL_SRC_XOSC1_Val:
  12771. mclk = 32000000UL; /* 32MHz */
  12772. break;
  12773. case GCLK_GENCTRL_SRC_OSCULP32K_Val: mclk = 32000UL; break;
  12774. case GCLK_GENCTRL_SRC_XOSC32K_Val: mclk = 32000UL; break;
  12775. case GCLK_GENCTRL_SRC_DFLL_Val:
  12776. mclk = 48000000UL; /* 48MHz */
  12777. break;
  12778. case GCLK_GENCTRL_SRC_DPLL0_Val:
  12779. mclk = 200000000UL; /* 200MHz */
  12780. break;
  12781. case GCLK_GENCTRL_SRC_DPLL1_Val:
  12782. mclk = 200000000UL; /* 200MHz */
  12783. break;
  12784. default: mclk = 200000000UL; /* 200MHz */
  12785. }
  12786. mclk /= div;
  12787. uint8_t crs[] = {0, 1, 2, 3, 4, 5}; // GMAC->NCFGR::CLK values
  12788. uint8_t dividers[] = {8, 16, 32, 48, 64, 96}; // Respective CLK dividers
  12789. for (int i = 0; i < 6; i++) {
  12790. if (mclk / dividers[i] <= 2375000UL /* 2.5MHz - 5% */) {
  12791. return crs[i];
  12792. }
  12793. }
  12794. return 5;
  12795. }
  12796. }
  12797. static bool mg_tcpip_driver_same54_init(struct mg_tcpip_if *ifp) {
  12798. struct mg_tcpip_driver_same54_data *d =
  12799. (struct mg_tcpip_driver_same54_data *) ifp->driver_data;
  12800. s_ifp = ifp;
  12801. MCLK_REGS->MCLK_APBCMASK |= MCLK_APBCMASK_GMAC_Msk;
  12802. MCLK_REGS->MCLK_AHBMASK |= MCLK_AHBMASK_GMAC_Msk;
  12803. GMAC_REGS->GMAC_NCFGR = GMAC_NCFGR_CLK(get_clock_rate(d)); // Set MDC divider
  12804. GMAC_REGS->GMAC_NCR = 0; // Disable RX & TX
  12805. GMAC_REGS->GMAC_NCR |= GMAC_NCR_MPE_Msk; // Enable MDC & MDIO
  12806. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init TX descriptors
  12807. s_txdesc[i][0] = (uint32_t) s_txbuf[i]; // Point to data buffer
  12808. s_txdesc[i][1] = MG_BIT(31); // OWN bit
  12809. }
  12810. s_txdesc[ETH_DESC_CNT - 1][1] |= MG_BIT(30); // Last tx descriptor - wrap
  12811. GMAC_REGS->GMAC_DCFGR = GMAC_DCFGR_DRBS(0x18) // DMA recv buf 1536
  12812. | GMAC_DCFGR_RXBMS(GMAC_DCFGR_RXBMS_FULL_Val) |
  12813. GMAC_DCFGR_TXPBMS(1); // See #2487
  12814. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init RX descriptors
  12815. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i]; // Address of the data buffer
  12816. s_rxdesc[i][1] = 0; // Clear status
  12817. }
  12818. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(1); // Last rx descriptor - wrap
  12819. GMAC_REGS->GMAC_TBQB = (uint32_t) s_txdesc; // about the descriptor addresses
  12820. GMAC_REGS->GMAC_RBQB = (uint32_t) s_rxdesc; // Let the controller know
  12821. GMAC_REGS->SA[0].GMAC_SAB =
  12822. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  12823. GMAC_REGS->SA[0].GMAC_SAT = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  12824. GMAC_REGS->GMAC_UR &= ~GMAC_UR_MII_Msk; // Disable MII, use RMII
  12825. GMAC_REGS->GMAC_NCFGR |= GMAC_NCFGR_MAXFS_Msk | GMAC_NCFGR_MTIHEN_Msk |
  12826. GMAC_NCFGR_EFRHD_Msk | GMAC_NCFGR_CAF_Msk;
  12827. GMAC_REGS->GMAC_TSR = GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk |
  12828. GMAC_TSR_TXCOMP_Msk | GMAC_TSR_TFC_Msk |
  12829. GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  12830. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk;
  12831. GMAC_REGS->GMAC_RSR = GMAC_RSR_HNO_Msk | GMAC_RSR_RXOVR_Msk |
  12832. GMAC_RSR_REC_Msk | GMAC_RSR_BNA_Msk;
  12833. GMAC_REGS->GMAC_IDR = ~0U; // Disable interrupts, then enable required
  12834. GMAC_REGS->GMAC_IER = GMAC_IER_HRESP_Msk | GMAC_IER_ROVR_Msk |
  12835. GMAC_IER_TCOMP_Msk | GMAC_IER_TFC_Msk |
  12836. GMAC_IER_RLEX_Msk | GMAC_IER_TUR_Msk |
  12837. GMAC_IER_RXUBR_Msk | GMAC_IER_RCOMP_Msk;
  12838. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TXEN_Msk | GMAC_NCR_RXEN_Msk;
  12839. NVIC_EnableIRQ(GMAC_IRQn);
  12840. return true;
  12841. }
  12842. static size_t mg_tcpip_driver_same54_tx(const void *buf, size_t len,
  12843. struct mg_tcpip_if *ifp) {
  12844. if (len > sizeof(s_txbuf[s_txno])) {
  12845. MG_ERROR(("Frame too big, %ld", (long) len));
  12846. len = 0; // Frame is too big
  12847. } else if ((s_txdesc[s_txno][1] & MG_BIT(31)) == 0) {
  12848. ifp->nerr++;
  12849. MG_ERROR(("No free descriptors"));
  12850. len = 0; // All descriptors are busy, fail
  12851. } else {
  12852. uint32_t status = len | MG_BIT(15); // Frame length, last chunk
  12853. if (s_txno == ETH_DESC_CNT - 1) status |= MG_BIT(30); // wrap
  12854. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  12855. s_txdesc[s_txno][1] = status;
  12856. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  12857. }
  12858. __DSB(); // Ensure descriptors have been written
  12859. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TSTART_Msk; // Enable transmission
  12860. return len;
  12861. }
  12862. static bool mg_tcpip_driver_same54_up(struct mg_tcpip_if *ifp) {
  12863. uint16_t bsr = eth_read_phy(PHY_ADDR, PHY_BSR);
  12864. bool up = bsr & PHY_BSR_LINK_STATUS_Msk ? 1 : 0;
  12865. // If PHY is ready, update NCFGR accordingly
  12866. if (ifp->state == MG_TCPIP_STATE_DOWN && up) {
  12867. uint16_t bcr = eth_read_phy(PHY_ADDR, PHY_BCR);
  12868. bool fd = bcr & PHY_BCR_DUPLEX_MODE_Msk ? 1 : 0;
  12869. bool spd = bcr & PHY_BCR_SPEED_Msk ? 1 : 0;
  12870. GMAC_REGS->GMAC_NCFGR =
  12871. (GMAC_REGS->GMAC_NCFGR & ~(GMAC_NCFGR_SPD_Msk | PHY_BCR_SPEED_Msk)) |
  12872. GMAC_NCFGR_SPD(spd) | GMAC_NCFGR_FD(fd);
  12873. }
  12874. return up;
  12875. }
  12876. void GMAC_Handler(void);
  12877. void GMAC_Handler(void) {
  12878. uint32_t isr = GMAC_REGS->GMAC_ISR;
  12879. uint32_t rsr = GMAC_REGS->GMAC_RSR;
  12880. uint32_t tsr = GMAC_REGS->GMAC_TSR;
  12881. if (isr & GMAC_ISR_RCOMP_Msk) {
  12882. if (rsr & GMAC_ISR_RCOMP_Msk) {
  12883. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  12884. if ((s_rxdesc[s_rxno][0] & MG_BIT(0)) == 0) break;
  12885. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  12886. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  12887. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // Disown
  12888. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  12889. }
  12890. }
  12891. }
  12892. if ((tsr & (GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk | GMAC_TSR_TXCOMP_Msk |
  12893. GMAC_TSR_TFC_Msk | GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  12894. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk)) != 0) {
  12895. // MG_INFO((" --> %#x %#x", s_txdesc[s_txno][1], tsr));
  12896. if (!(s_txdesc[s_txno][1] & MG_BIT(31))) s_txdesc[s_txno][1] |= MG_BIT(31);
  12897. }
  12898. GMAC_REGS->GMAC_RSR = rsr;
  12899. GMAC_REGS->GMAC_TSR = tsr;
  12900. }
  12901. struct mg_tcpip_driver mg_tcpip_driver_same54 = {
  12902. mg_tcpip_driver_same54_init, mg_tcpip_driver_same54_tx, NULL,
  12903. mg_tcpip_driver_same54_up};
  12904. #endif
  12905. #ifdef MG_ENABLE_LINES
  12906. #line 1 "src/drivers/stm32f.c"
  12907. #endif
  12908. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
  12909. MG_ENABLE_DRIVER_STM32F
  12910. struct stm32f_eth {
  12911. volatile uint32_t MACCR, MACFFR, MACHTHR, MACHTLR, MACMIIAR, MACMIIDR, MACFCR,
  12912. MACVLANTR, RESERVED0[2], MACRWUFFR, MACPMTCSR, RESERVED1, MACDBGR, MACSR,
  12913. MACIMR, MACA0HR, MACA0LR, MACA1HR, MACA1LR, MACA2HR, MACA2LR, MACA3HR,
  12914. MACA3LR, RESERVED2[40], MMCCR, MMCRIR, MMCTIR, MMCRIMR, MMCTIMR,
  12915. RESERVED3[14], MMCTGFSCCR, MMCTGFMSCCR, RESERVED4[5], MMCTGFCR,
  12916. RESERVED5[10], MMCRFCECR, MMCRFAECR, RESERVED6[10], MMCRGUFCR,
  12917. RESERVED7[334], PTPTSCR, PTPSSIR, PTPTSHR, PTPTSLR, PTPTSHUR, PTPTSLUR,
  12918. PTPTSAR, PTPTTHR, PTPTTLR, RESERVED8, PTPTSSR, PTPPPSCR, RESERVED9[564],
  12919. DMABMR, DMATPDR, DMARPDR, DMARDLAR, DMATDLAR, DMASR, DMAOMR, DMAIER,
  12920. DMAMFBOCR, DMARSWTR, RESERVED10[8], DMACHTDR, DMACHRDR, DMACHTBAR,
  12921. DMACHRBAR;
  12922. };
  12923. #undef ETH
  12924. #define ETH ((struct stm32f_eth *) (uintptr_t) 0x40028000)
  12925. #define ETH_PKT_SIZE 1540 // Max frame size
  12926. #define ETH_DESC_CNT 4 // Descriptors count
  12927. #define ETH_DS 4 // Descriptor size (words)
  12928. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  12929. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  12930. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  12931. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  12932. static uint8_t s_txno; // Current TX descriptor
  12933. static uint8_t s_rxno; // Current RX descriptor
  12934. static struct mg_tcpip_if *s_ifp; // MIP interface
  12935. enum { PHY_BCR = 0, PHY_BSR = 1, PHY_ID1 = 2, PHY_ID2 = 3, PHY_CSCR = 31 };
  12936. static uint32_t eth_read_phy(uint8_t addr, uint8_t reg) {
  12937. ETH->MACMIIAR &= (7 << 2);
  12938. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  12939. ETH->MACMIIAR |= MG_BIT(0);
  12940. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  12941. return ETH->MACMIIDR;
  12942. }
  12943. static void eth_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  12944. ETH->MACMIIDR = val;
  12945. ETH->MACMIIAR &= (7 << 2);
  12946. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  12947. ETH->MACMIIAR |= MG_BIT(0);
  12948. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  12949. }
  12950. static uint32_t get_hclk(void) {
  12951. struct rcc {
  12952. volatile uint32_t CR, PLLCFGR, CFGR;
  12953. } *rcc = (struct rcc *) 0x40023800;
  12954. uint32_t clk = 0, hsi = 16000000 /* 16 MHz */, hse = 8000000 /* 8MHz */;
  12955. if (rcc->CFGR & (1 << 2)) {
  12956. clk = hse;
  12957. } else if (rcc->CFGR & (1 << 3)) {
  12958. uint32_t vco, m, n, p;
  12959. m = (rcc->PLLCFGR & (0x3f << 0)) >> 0;
  12960. n = (rcc->PLLCFGR & (0x1ff << 6)) >> 6;
  12961. p = (((rcc->PLLCFGR & (3 << 16)) >> 16) + 1) * 2;
  12962. clk = (rcc->PLLCFGR & (1 << 22)) ? hse : hsi;
  12963. vco = (uint32_t) ((uint64_t) clk * n / m);
  12964. clk = vco / p;
  12965. } else {
  12966. clk = hsi;
  12967. }
  12968. uint32_t hpre = (rcc->CFGR & (15 << 4)) >> 4;
  12969. if (hpre < 8) return clk;
  12970. uint8_t ahbptab[8] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  12971. return ((uint32_t) clk) >> ahbptab[hpre - 8];
  12972. }
  12973. // Guess CR from HCLK. MDC clock is generated from HCLK (AHB); as per 802.3,
  12974. // it must not exceed 2.5MHz As the AHB clock can be (and usually is) derived
  12975. // from the HSI (internal RC), and it can go above specs, the datasheets
  12976. // specify a range of frequencies and activate one of a series of dividers to
  12977. // keep the MDC clock safely below 2.5MHz. We guess a divider setting based on
  12978. // HCLK with a +5% drift. If the user uses a different clock from our
  12979. // defaults, needs to set the macros on top Valid for STM32F74xxx/75xxx
  12980. // (38.8.1) and STM32F42xxx/43xxx (33.8.1) (both 4.5% worst case drift)
  12981. static int guess_mdc_cr(void) {
  12982. uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMIIAR::CR values
  12983. uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  12984. uint32_t hclk = get_hclk(); // Guess system HCLK
  12985. int result = -1; // Invalid CR value
  12986. if (hclk < 25000000) {
  12987. MG_ERROR(("HCLK too low"));
  12988. } else {
  12989. for (int i = 0; i < 6; i++) {
  12990. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  12991. result = crs[i];
  12992. break;
  12993. }
  12994. }
  12995. if (result < 0) MG_ERROR(("HCLK too high"));
  12996. }
  12997. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  12998. return result;
  12999. }
  13000. static bool mg_tcpip_driver_stm32f_init(struct mg_tcpip_if *ifp) {
  13001. struct mg_tcpip_driver_stm32f_data *d =
  13002. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  13003. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  13004. s_ifp = ifp;
  13005. // Init RX descriptors
  13006. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13007. s_rxdesc[i][0] = MG_BIT(31); // Own
  13008. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  13009. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13010. s_rxdesc[i][3] =
  13011. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13012. }
  13013. // Init TX descriptors
  13014. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13015. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13016. s_txdesc[i][3] =
  13017. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13018. }
  13019. ETH->DMABMR |= MG_BIT(0); // Software reset
  13020. while ((ETH->DMABMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  13021. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13022. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13023. ETH->MACMIIAR = ((uint32_t) cr & 7) << 2;
  13024. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  13025. // hardware checksum. Therefore, descriptor size is 4, not 8
  13026. // ETH->DMABMR = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) |
  13027. // MG_BIT(25);
  13028. ETH->MACIMR = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  13029. ETH->MACFCR = MG_BIT(7); // Disable zero quarta pause
  13030. // ETH->MACFFR = MG_BIT(31); // Receive all
  13031. eth_write_phy(phy_addr, PHY_BCR, MG_BIT(15)); // Reset PHY
  13032. eth_write_phy(phy_addr, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  13033. ETH->DMARDLAR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  13034. ETH->DMATDLAR = (uint32_t) (uintptr_t) s_txdesc; // RX descriptors
  13035. ETH->DMAIER = MG_BIT(6) | MG_BIT(16); // RIE, NISE
  13036. ETH->MACCR =
  13037. MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  13038. ETH->DMAOMR =
  13039. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  13040. MG_DEBUG(("PHY ID: %#04hx %#04hx", eth_read_phy(phy_addr, PHY_ID1),
  13041. eth_read_phy(phy_addr, PHY_ID2)));
  13042. // MAC address filtering
  13043. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13044. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  13045. ((uint32_t) ifp->mac[2] << 16) |
  13046. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13047. return true;
  13048. }
  13049. static size_t mg_tcpip_driver_stm32f_tx(const void *buf, size_t len,
  13050. struct mg_tcpip_if *ifp) {
  13051. if (len > sizeof(s_txbuf[s_txno])) {
  13052. MG_ERROR(("Frame too big, %ld", (long) len));
  13053. len = 0; // Frame is too big
  13054. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  13055. ifp->nerr++;
  13056. MG_ERROR(("No free descriptors"));
  13057. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long) ETH->DMASR);
  13058. len = 0; // All descriptors are busy, fail
  13059. } else {
  13060. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13061. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  13062. s_txdesc[s_txno][0] = MG_BIT(20) | MG_BIT(28) | MG_BIT(29); // Chain,FS,LS
  13063. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13064. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13065. }
  13066. MG_DSB(); // ensure descriptors have been written
  13067. ETH->DMASR = MG_BIT(2) | MG_BIT(5); // Clear any prior TBUS/TUS
  13068. ETH->DMATPDR = 0; // and resume
  13069. return len;
  13070. }
  13071. static bool mg_tcpip_driver_stm32f_up(struct mg_tcpip_if *ifp) {
  13072. struct mg_tcpip_driver_stm32f_data *d =
  13073. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  13074. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  13075. uint32_t bsr = eth_read_phy(phy_addr, PHY_BSR);
  13076. bool up = bsr & MG_BIT(2) ? 1 : 0;
  13077. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13078. uint32_t scsr = eth_read_phy(phy_addr, PHY_CSCR);
  13079. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13080. // if(link is slow or half) set flags otherwise
  13081. // reg = tmp
  13082. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  13083. if ((scsr & MG_BIT(3)) == 0) maccr &= ~MG_BIT(14); // 10M
  13084. if ((scsr & MG_BIT(4)) == 0) maccr &= ~MG_BIT(11); // Half-duplex
  13085. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  13086. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  13087. maccr & MG_BIT(11) ? "full" : "half"));
  13088. }
  13089. return up;
  13090. }
  13091. #ifdef __riscv
  13092. __attribute__((interrupt())) // For RISCV CH32V307, which share the same MAC
  13093. #endif
  13094. void ETH_IRQHandler(void);
  13095. void ETH_IRQHandler(void) {
  13096. if (ETH->DMASR & MG_BIT(6)) { // Frame received, loop
  13097. ETH->DMASR = MG_BIT(16) | MG_BIT(6); // Clear flag
  13098. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13099. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  13100. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) ==
  13101. (MG_BIT(8) | MG_BIT(9))) &&
  13102. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  13103. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  13104. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  13105. // ETH->DMASR);
  13106. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13107. }
  13108. s_rxdesc[s_rxno][0] = MG_BIT(31);
  13109. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13110. }
  13111. }
  13112. // Cleanup flags
  13113. ETH->DMASR = MG_BIT(16) // NIS, normal interrupt summary
  13114. | MG_BIT(7); // Clear possible RBUS while processing
  13115. ETH->DMARPDR = 0; // and resume RX
  13116. }
  13117. struct mg_tcpip_driver mg_tcpip_driver_stm32f = {
  13118. mg_tcpip_driver_stm32f_init, mg_tcpip_driver_stm32f_tx, NULL,
  13119. mg_tcpip_driver_stm32f_up};
  13120. #endif
  13121. #ifdef MG_ENABLE_LINES
  13122. #line 1 "src/drivers/stm32h.c"
  13123. #endif
  13124. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32H) && \
  13125. MG_ENABLE_DRIVER_STM32H
  13126. struct stm32h_eth {
  13127. volatile uint32_t MACCR, MACECR, MACPFR, MACWTR, MACHT0R, MACHT1R,
  13128. RESERVED1[14], MACVTR, RESERVED2, MACVHTR, RESERVED3, MACVIR, MACIVIR,
  13129. RESERVED4[2], MACTFCR, RESERVED5[7], MACRFCR, RESERVED6[7], MACISR,
  13130. MACIER, MACRXTXSR, RESERVED7, MACPCSR, MACRWKPFR, RESERVED8[2], MACLCSR,
  13131. MACLTCR, MACLETR, MAC1USTCR, RESERVED9[12], MACVR, MACDR, RESERVED10,
  13132. MACHWF0R, MACHWF1R, MACHWF2R, RESERVED11[54], MACMDIOAR, MACMDIODR,
  13133. RESERVED12[2], MACARPAR, RESERVED13[59], MACA0HR, MACA0LR, MACA1HR,
  13134. MACA1LR, MACA2HR, MACA2LR, MACA3HR, MACA3LR, RESERVED14[248], MMCCR,
  13135. MMCRIR, MMCTIR, MMCRIMR, MMCTIMR, RESERVED15[14], MMCTSCGPR, MMCTMCGPR,
  13136. RESERVED16[5], MMCTPCGR, RESERVED17[10], MMCRCRCEPR, MMCRAEPR,
  13137. RESERVED18[10], MMCRUPGR, RESERVED19[9], MMCTLPIMSTR, MMCTLPITCR,
  13138. MMCRLPIMSTR, MMCRLPITCR, RESERVED20[65], MACL3L4C0R, MACL4A0R,
  13139. RESERVED21[2], MACL3A0R0R, MACL3A1R0R, MACL3A2R0R, MACL3A3R0R,
  13140. RESERVED22[4], MACL3L4C1R, MACL4A1R, RESERVED23[2], MACL3A0R1R,
  13141. MACL3A1R1R, MACL3A2R1R, MACL3A3R1R, RESERVED24[108], MACTSCR, MACSSIR,
  13142. MACSTSR, MACSTNR, MACSTSUR, MACSTNUR, MACTSAR, RESERVED25, MACTSSR,
  13143. RESERVED26[3], MACTTSSNR, MACTTSSSR, RESERVED27[2], MACACR, RESERVED28,
  13144. MACATSNR, MACATSSR, MACTSIACR, MACTSEACR, MACTSICNR, MACTSECNR,
  13145. RESERVED29[4], MACPPSCR, RESERVED30[3], MACPPSTTSR, MACPPSTTNR, MACPPSIR,
  13146. MACPPSWR, RESERVED31[12], MACPOCR, MACSPI0R, MACSPI1R, MACSPI2R, MACLMIR,
  13147. RESERVED32[11], MTLOMR, RESERVED33[7], MTLISR, RESERVED34[55], MTLTQOMR,
  13148. MTLTQUR, MTLTQDR, RESERVED35[8], MTLQICSR, MTLRQOMR, MTLRQMPOCR, MTLRQDR,
  13149. RESERVED36[177], DMAMR, DMASBMR, DMAISR, DMADSR, RESERVED37[60], DMACCR,
  13150. DMACTCR, DMACRCR, RESERVED38[2], DMACTDLAR, RESERVED39, DMACRDLAR,
  13151. DMACTDTPR, RESERVED40, DMACRDTPR, DMACTDRLR, DMACRDRLR, DMACIER,
  13152. DMACRIWTR, DMACSFCSR, RESERVED41, DMACCATDR, RESERVED42, DMACCARDR,
  13153. RESERVED43, DMACCATBR, RESERVED44, DMACCARBR, DMACSR, RESERVED45[2],
  13154. DMACMFCR;
  13155. };
  13156. #undef ETH
  13157. #define ETH \
  13158. ((struct stm32h_eth *) (uintptr_t) (0x40000000UL + 0x00020000UL + 0x8000UL))
  13159. #define ETH_PKT_SIZE 1540 // Max frame size
  13160. #define ETH_DESC_CNT 4 // Descriptors count
  13161. #define ETH_DS 4 // Descriptor size (words)
  13162. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  13163. static volatile uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  13164. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  13165. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  13166. static struct mg_tcpip_if *s_ifp; // MIP interface
  13167. enum {
  13168. PHY_ADDR = 0,
  13169. PHY_BCR = 0,
  13170. PHY_BSR = 1,
  13171. PHY_CSCR = 31
  13172. }; // PHY constants
  13173. static uint32_t eth_read_phy(uint8_t addr, uint8_t reg) {
  13174. ETH->MACMDIOAR &= (0xF << 8);
  13175. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 3 << 2;
  13176. ETH->MACMDIOAR |= MG_BIT(0);
  13177. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  13178. return ETH->MACMDIODR;
  13179. }
  13180. static void eth_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  13181. ETH->MACMDIODR = val;
  13182. ETH->MACMDIOAR &= (0xF << 8);
  13183. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 1 << 2;
  13184. ETH->MACMDIOAR |= MG_BIT(0);
  13185. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  13186. }
  13187. static uint32_t get_hclk(void) {
  13188. struct rcc {
  13189. volatile uint32_t CR, HSICFGR, CRRCR, CSICFGR, CFGR, RESERVED1, D1CFGR,
  13190. D2CFGR, D3CFGR, RESERVED2, PLLCKSELR, PLLCFGR, PLL1DIVR, PLL1FRACR,
  13191. PLL2DIVR, PLL2FRACR, PLL3DIVR, PLL3FRACR, RESERVED3, D1CCIPR, D2CCIP1R,
  13192. D2CCIP2R, D3CCIPR, RESERVED4, CIER, CIFR, CICR, RESERVED5, BDCR, CSR,
  13193. RESERVED6, AHB3RSTR, AHB1RSTR, AHB2RSTR, AHB4RSTR, APB3RSTR, APB1LRSTR,
  13194. APB1HRSTR, APB2RSTR, APB4RSTR, GCR, RESERVED8, D3AMR, RESERVED11[9],
  13195. RSR, AHB3ENR, AHB1ENR, AHB2ENR, AHB4ENR, APB3ENR, APB1LENR, APB1HENR,
  13196. APB2ENR, APB4ENR, RESERVED12, AHB3LPENR, AHB1LPENR, AHB2LPENR,
  13197. AHB4LPENR, APB3LPENR, APB1LLPENR, APB1HLPENR, APB2LPENR, APB4LPENR,
  13198. RESERVED13[4];
  13199. } *rcc = ((struct rcc *) (0x40000000 + 0x18020000 + 0x4400));
  13200. uint32_t clk = 0, hsi = 64000000 /* 64 MHz */, hse = 8000000 /* 8MHz */,
  13201. csi = 4000000 /* 4MHz */;
  13202. unsigned int sel = (rcc->CFGR & (7 << 3)) >> 3;
  13203. if (sel == 1) {
  13204. clk = csi;
  13205. } else if (sel == 2) {
  13206. clk = hse;
  13207. } else if (sel == 3) {
  13208. uint32_t vco, m, n, p;
  13209. unsigned int src = (rcc->PLLCKSELR & (3 << 0)) >> 0;
  13210. m = ((rcc->PLLCKSELR & (0x3F << 4)) >> 4);
  13211. n = ((rcc->PLL1DIVR & (0x1FF << 0)) >> 0) + 1 +
  13212. ((rcc->PLLCFGR & MG_BIT(0)) ? 1 : 0); // round-up in fractional mode
  13213. p = ((rcc->PLL1DIVR & (0x7F << 9)) >> 9) + 1;
  13214. if (src == 1) {
  13215. clk = csi;
  13216. } else if (src == 2) {
  13217. clk = hse;
  13218. } else {
  13219. clk = hsi;
  13220. clk >>= ((rcc->CR & 3) >> 3);
  13221. }
  13222. vco = (uint32_t) ((uint64_t) clk * n / m);
  13223. clk = vco / p;
  13224. } else {
  13225. clk = hsi;
  13226. clk >>= ((rcc->CR & 3) >> 3);
  13227. }
  13228. const uint8_t cptab[12] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  13229. uint32_t d1cpre = (rcc->D1CFGR & (0x0F << 8)) >> 8;
  13230. if (d1cpre >= 8) clk >>= cptab[d1cpre - 8];
  13231. MG_DEBUG(("D1 CLK: %u", clk));
  13232. uint32_t hpre = (rcc->D1CFGR & (0x0F << 0)) >> 0;
  13233. if (hpre < 8) return clk;
  13234. return ((uint32_t) clk) >> cptab[hpre - 8];
  13235. }
  13236. // Guess CR from AHB1 clock. MDC clock is generated from the ETH peripheral
  13237. // clock (AHB1); as per 802.3, it must not exceed 2. As the AHB clock can
  13238. // be derived from HSI or CSI (internal RC) clocks, and those can go above
  13239. // specs, the datasheets specify a range of frequencies and activate one of a
  13240. // series of dividers to keep the MDC clock safely below 2.5MHz. We guess a
  13241. // divider setting based on HCLK with some drift. If the user uses a different
  13242. // clock from our defaults, needs to set the macros on top. Valid for
  13243. // STM32H74xxx/75xxx (58.11.4)(4.5% worst case drift)(CSI clock has a 7.5 %
  13244. // worst case drift @ max temp)
  13245. static int guess_mdc_cr(void) {
  13246. const uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMDIOAR::CR values
  13247. const uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  13248. uint32_t hclk = get_hclk(); // Guess system HCLK
  13249. int result = -1; // Invalid CR value
  13250. for (int i = 0; i < 6; i++) {
  13251. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  13252. result = crs[i];
  13253. break;
  13254. }
  13255. }
  13256. if (result < 0) MG_ERROR(("HCLK too high"));
  13257. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  13258. return result;
  13259. }
  13260. static bool mg_tcpip_driver_stm32h_init(struct mg_tcpip_if *ifp) {
  13261. struct mg_tcpip_driver_stm32h_data *d =
  13262. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  13263. s_ifp = ifp;
  13264. // Init RX descriptors
  13265. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13266. s_rxdesc[i][0] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13267. s_rxdesc[i][3] = MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  13268. }
  13269. // Init TX descriptors
  13270. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13271. s_txdesc[i][0] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13272. }
  13273. ETH->DMAMR |= MG_BIT(0); // Software reset
  13274. while ((ETH->DMAMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  13275. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13276. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13277. ETH->MACMDIOAR = ((uint32_t) cr & 0xF) << 8;
  13278. // NOTE(scaprile): We do not use timing facilities so the DMA engine does not
  13279. // re-write buffer address
  13280. ETH->DMAMR = 0 << 16; // use interrupt mode 0 (58.8.1) (reset value)
  13281. ETH->DMASBMR |= MG_BIT(12); // AAL NOTE(scaprile): is this actually needed
  13282. ETH->MACIER = 0; // Do not enable additional irq sources (reset value)
  13283. ETH->MACTFCR = MG_BIT(7); // Disable zero-quanta pause
  13284. // ETH->MACPFR = MG_BIT(31); // Receive all
  13285. eth_write_phy(PHY_ADDR, PHY_BCR, MG_BIT(15)); // Reset PHY
  13286. eth_write_phy(PHY_ADDR, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  13287. ETH->DMACRDLAR =
  13288. (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors start address
  13289. ETH->DMACRDRLR = ETH_DESC_CNT - 1; // ring length
  13290. ETH->DMACRDTPR =
  13291. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT -
  13292. 1]; // last valid descriptor address
  13293. ETH->DMACTDLAR =
  13294. (uint32_t) (uintptr_t) s_txdesc; // TX descriptors start address
  13295. ETH->DMACTDRLR = ETH_DESC_CNT - 1; // ring length
  13296. ETH->DMACTDTPR =
  13297. (uint32_t) (uintptr_t) s_txdesc; // first available descriptor address
  13298. ETH->DMACCR = 0; // DSL = 0 (contiguous descriptor table) (reset value)
  13299. ETH->DMACIER = MG_BIT(6) | MG_BIT(15); // RIE, NIE
  13300. ETH->MACCR = MG_BIT(0) | MG_BIT(1) | MG_BIT(13) | MG_BIT(14) |
  13301. MG_BIT(15); // RE, TE, Duplex, Fast, Reserved
  13302. ETH->MTLTQOMR |= MG_BIT(1); // TSF
  13303. ETH->MTLRQOMR |= MG_BIT(5); // RSF
  13304. ETH->DMACTCR |= MG_BIT(0); // ST
  13305. ETH->DMACRCR |= MG_BIT(0); // SR
  13306. // MAC address filtering
  13307. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13308. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  13309. ((uint32_t) ifp->mac[2] << 16) |
  13310. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13311. return true;
  13312. }
  13313. static uint32_t s_txno;
  13314. static size_t mg_tcpip_driver_stm32h_tx(const void *buf, size_t len,
  13315. struct mg_tcpip_if *ifp) {
  13316. if (len > sizeof(s_txbuf[s_txno])) {
  13317. MG_ERROR(("Frame too big, %ld", (long) len));
  13318. len = 0; // Frame is too big
  13319. } else if ((s_txdesc[s_txno][3] & MG_BIT(31))) {
  13320. ifp->nerr++;
  13321. MG_ERROR(("No free descriptors: %u %08X %08X %08X", s_txno,
  13322. s_txdesc[s_txno][3], ETH->DMACSR, ETH->DMACTCR));
  13323. for (int i = 0; i < ETH_DESC_CNT; i++) MG_ERROR(("%08X", s_txdesc[i][3]));
  13324. len = 0; // All descriptors are busy, fail
  13325. } else {
  13326. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13327. s_txdesc[s_txno][2] = (uint32_t) len; // Set data len
  13328. s_txdesc[s_txno][3] = MG_BIT(28) | MG_BIT(29); // FD, LD
  13329. s_txdesc[s_txno][3] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13330. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13331. }
  13332. ETH->DMACSR |= MG_BIT(2) | MG_BIT(1); // Clear any prior TBU, TPS
  13333. ETH->DMACTDTPR = (uint32_t) (uintptr_t) &s_txdesc[s_txno]; // and resume
  13334. return len;
  13335. (void) ifp;
  13336. }
  13337. static bool mg_tcpip_driver_stm32h_up(struct mg_tcpip_if *ifp) {
  13338. uint32_t bsr = eth_read_phy(PHY_ADDR, PHY_BSR);
  13339. bool up = bsr & MG_BIT(2) ? 1 : 0;
  13340. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13341. uint32_t scsr = eth_read_phy(PHY_ADDR, PHY_CSCR);
  13342. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13343. // if(link is slow or half) set flags otherwise
  13344. // reg = tmp
  13345. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(13); // 100M, Full-duplex
  13346. if ((scsr & MG_BIT(3)) == 0) maccr &= ~MG_BIT(14); // 10M
  13347. if ((scsr & MG_BIT(4)) == 0) maccr &= ~MG_BIT(13); // Half-duplex
  13348. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  13349. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  13350. maccr & MG_BIT(13) ? "full" : "half"));
  13351. }
  13352. return up;
  13353. }
  13354. void ETH_IRQHandler(void);
  13355. static uint32_t s_rxno;
  13356. void ETH_IRQHandler(void) {
  13357. if (ETH->DMACSR & MG_BIT(6)) { // Frame received, loop
  13358. ETH->DMACSR = MG_BIT(15) | MG_BIT(6); // Clear flag
  13359. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13360. if (s_rxdesc[s_rxno][3] & MG_BIT(31)) break; // exit when done
  13361. if (((s_rxdesc[s_rxno][3] & (MG_BIT(28) | MG_BIT(29))) ==
  13362. (MG_BIT(28) | MG_BIT(29))) &&
  13363. !(s_rxdesc[s_rxno][3] & MG_BIT(15))) { // skip partial/errored frames
  13364. uint32_t len = s_rxdesc[s_rxno][3] & (MG_BIT(15) - 1);
  13365. // MG_DEBUG(("%lx %lu %lx %08lx", s_rxno, len, s_rxdesc[s_rxno][3],
  13366. // ETH->DMACSR));
  13367. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13368. }
  13369. s_rxdesc[s_rxno][3] =
  13370. MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  13371. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13372. }
  13373. }
  13374. ETH->DMACSR =
  13375. MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing
  13376. ETH->DMACRDTPR =
  13377. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT - 1]; // and resume RX
  13378. }
  13379. struct mg_tcpip_driver mg_tcpip_driver_stm32h = {
  13380. mg_tcpip_driver_stm32h_init, mg_tcpip_driver_stm32h_tx, NULL,
  13381. mg_tcpip_driver_stm32h_up};
  13382. #endif
  13383. #ifdef MG_ENABLE_LINES
  13384. #line 1 "src/drivers/tm4c.c"
  13385. #endif
  13386. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
  13387. struct tm4c_emac {
  13388. volatile uint32_t EMACCFG, EMACFRAMEFLTR, EMACHASHTBLH, EMACHASHTBLL,
  13389. EMACMIIADDR, EMACMIIDATA, EMACFLOWCTL, EMACVLANTG, RESERVED0, EMACSTATUS,
  13390. EMACRWUFF, EMACPMTCTLSTAT, RESERVED1[2], EMACRIS, EMACIM, EMACADDR0H,
  13391. EMACADDR0L, EMACADDR1H, EMACADDR1L, EMACADDR2H, EMACADDR2L, EMACADDR3H,
  13392. EMACADDR3L, RESERVED2[31], EMACWDOGTO, RESERVED3[8], EMACMMCCTRL,
  13393. EMACMMCRXRIS, EMACMMCTXRIS, EMACMMCRXIM, EMACMMCTXIM, RESERVED4,
  13394. EMACTXCNTGB, RESERVED5[12], EMACTXCNTSCOL, EMACTXCNTMCOL, RESERVED6[4],
  13395. EMACTXOCTCNTG, RESERVED7[6], EMACRXCNTGB, RESERVED8[4], EMACRXCNTCRCERR,
  13396. EMACRXCNTALGNERR, RESERVED9[10], EMACRXCNTGUNI, RESERVED10[239],
  13397. EMACVLNINCREP, EMACVLANHASH, RESERVED11[93], EMACTIMSTCTRL, EMACSUBSECINC,
  13398. EMACTIMSEC, EMACTIMNANO, EMACTIMSECU, EMACTIMNANOU, EMACTIMADD,
  13399. EMACTARGSEC, EMACTARGNANO, EMACHWORDSEC, EMACTIMSTAT, EMACPPSCTRL,
  13400. RESERVED12[12], EMACPPS0INTVL, EMACPPS0WIDTH, RESERVED13[294],
  13401. EMACDMABUSMOD, EMACTXPOLLD, EMACRXPOLLD, EMACRXDLADDR, EMACTXDLADDR,
  13402. EMACDMARIS, EMACDMAOPMODE, EMACDMAIM, EMACMFBOC, EMACRXINTWDT,
  13403. RESERVED14[8], EMACHOSTXDESC, EMACHOSRXDESC, EMACHOSTXBA, EMACHOSRXBA,
  13404. RESERVED15[218], EMACPP, EMACPC, EMACCC, RESERVED16, EMACEPHYRIS,
  13405. EMACEPHYIM, EMACEPHYIMSC;
  13406. };
  13407. #undef EMAC
  13408. #define EMAC ((struct tm4c_emac *) (uintptr_t) 0x400EC000)
  13409. #define ETH_PKT_SIZE 1540 // Max frame size
  13410. #define ETH_DESC_CNT 4 // Descriptors count
  13411. #define ETH_DS 4 // Descriptor size (words)
  13412. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  13413. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  13414. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  13415. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  13416. static struct mg_tcpip_if *s_ifp; // MIP interface
  13417. enum {
  13418. EPHY_ADDR = 0,
  13419. EPHYBMCR = 0,
  13420. EPHYBMSR = 1,
  13421. EPHYSTS = 16
  13422. }; // PHY constants
  13423. static inline void tm4cspin(volatile uint32_t count) {
  13424. while (count--) (void) 0;
  13425. }
  13426. static uint32_t emac_read_phy(uint8_t addr, uint8_t reg) {
  13427. EMAC->EMACMIIADDR &= (0xf << 2);
  13428. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  13429. EMAC->EMACMIIADDR |= MG_BIT(0);
  13430. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  13431. return EMAC->EMACMIIDATA;
  13432. }
  13433. static void emac_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  13434. EMAC->EMACMIIDATA = val;
  13435. EMAC->EMACMIIADDR &= (0xf << 2);
  13436. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  13437. EMAC->EMACMIIADDR |= MG_BIT(0);
  13438. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  13439. }
  13440. static uint32_t get_sysclk(void) {
  13441. struct sysctl {
  13442. volatile uint32_t DONTCARE0[44], RSCLKCFG, DONTCARE1[43], PLLFREQ0,
  13443. PLLFREQ1;
  13444. } *sysctl = (struct sysctl *) 0x400FE000;
  13445. uint32_t clk = 0, piosc = 16000000 /* 16 MHz */, mosc = 25000000 /* 25MHz */;
  13446. if (sysctl->RSCLKCFG & (1 << 28)) { // USEPLL
  13447. uint32_t fin, vco, mdiv, n, q, psysdiv;
  13448. uint32_t pllsrc = (sysctl->RSCLKCFG & (0xf << 24)) >> 24;
  13449. if (pllsrc == 0) {
  13450. clk = piosc;
  13451. } else if (pllsrc == 3) {
  13452. clk = mosc;
  13453. } else {
  13454. MG_ERROR(("Unsupported clock source"));
  13455. }
  13456. q = (sysctl->PLLFREQ1 & (0x1f << 8)) >> 8;
  13457. n = (sysctl->PLLFREQ1 & (0x1f << 0)) >> 0;
  13458. fin = clk / ((q + 1) * (n + 1));
  13459. mdiv = (sysctl->PLLFREQ0 & (0x3ff << 0)) >>
  13460. 0; // mint + (mfrac / 1024); MFRAC not supported
  13461. psysdiv = (sysctl->RSCLKCFG & (0x3f << 0)) >> 0;
  13462. vco = (uint32_t) ((uint64_t) fin * mdiv);
  13463. return vco / (psysdiv + 1);
  13464. }
  13465. uint32_t oscsrc = (sysctl->RSCLKCFG & (0xf << 20)) >> 20;
  13466. if (oscsrc == 0) {
  13467. clk = piosc;
  13468. } else if (oscsrc == 3) {
  13469. clk = mosc;
  13470. } else {
  13471. MG_ERROR(("Unsupported clock source"));
  13472. }
  13473. uint32_t osysdiv = (sysctl->RSCLKCFG & (0xf << 16)) >> 16;
  13474. return clk / (osysdiv + 1);
  13475. }
  13476. // Guess CR from SYSCLK. MDC clock is generated from SYSCLK (AHB); as per
  13477. // 802.3, it must not exceed 2.5MHz (also 20.4.2.6) As the AHB clock can be
  13478. // derived from the PIOSC (internal RC), and it can go above specs, the
  13479. // datasheets specify a range of frequencies and activate one of a series of
  13480. // dividers to keep the MDC clock safely below 2.5MHz. We guess a divider
  13481. // setting based on SYSCLK with a +5% drift. If the user uses a different clock
  13482. // from our defaults, needs to set the macros on top Valid for TM4C129x (20.7)
  13483. // (4.5% worst case drift)
  13484. // The PHY receives the main oscillator (MOSC) (20.3.1)
  13485. static int guess_mdc_cr(void) {
  13486. uint8_t crs[] = {2, 3, 0, 1}; // EMAC->MACMIIAR::CR values
  13487. uint8_t div[] = {16, 26, 42, 62}; // Respective HCLK dividers
  13488. uint32_t sysclk = get_sysclk(); // Guess system SYSCLK
  13489. int result = -1; // Invalid CR value
  13490. if (sysclk < 25000000) {
  13491. MG_ERROR(("SYSCLK too low"));
  13492. } else {
  13493. for (int i = 0; i < 4; i++) {
  13494. if (sysclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  13495. result = crs[i];
  13496. break;
  13497. }
  13498. }
  13499. if (result < 0) MG_ERROR(("SYSCLK too high"));
  13500. }
  13501. MG_DEBUG(("SYSCLK: %u, CR: %d", sysclk, result));
  13502. return result;
  13503. }
  13504. static bool mg_tcpip_driver_tm4c_init(struct mg_tcpip_if *ifp) {
  13505. struct mg_tcpip_driver_tm4c_data *d =
  13506. (struct mg_tcpip_driver_tm4c_data *) ifp->driver_data;
  13507. s_ifp = ifp;
  13508. // Init RX descriptors
  13509. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13510. s_rxdesc[i][0] = MG_BIT(31); // Own
  13511. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  13512. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13513. s_rxdesc[i][3] =
  13514. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13515. // MG_DEBUG(("%d %p", i, s_rxdesc[i]));
  13516. }
  13517. // Init TX descriptors
  13518. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13519. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13520. s_txdesc[i][3] =
  13521. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13522. }
  13523. EMAC->EMACDMABUSMOD |= MG_BIT(0); // Software reset
  13524. while ((EMAC->EMACDMABUSMOD & MG_BIT(0)) != 0) tm4cspin(1); // Wait until done
  13525. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13526. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13527. EMAC->EMACMIIADDR = ((uint32_t) cr & 0xf) << 2;
  13528. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  13529. // hardware checksum. Therefore, descriptor size is 4, not 8
  13530. // EMAC->EMACDMABUSMOD = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) | MG_BIT(25);
  13531. EMAC->EMACIM = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  13532. EMAC->EMACFLOWCTL = MG_BIT(7); // Disable zero-quanta pause
  13533. // EMAC->EMACFRAMEFLTR = MG_BIT(31); // Receive all
  13534. // EMAC->EMACPC defaults to internal PHY (EPHY) in MMI mode
  13535. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(15)); // Reset internal PHY (EPHY)
  13536. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(12)); // Set autonegotiation
  13537. EMAC->EMACRXDLADDR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  13538. EMAC->EMACTXDLADDR = (uint32_t) (uintptr_t) s_txdesc; // TX descriptors
  13539. EMAC->EMACDMAIM = MG_BIT(6) | MG_BIT(16); // RIE, NIE
  13540. EMAC->EMACCFG = MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  13541. EMAC->EMACDMAOPMODE =
  13542. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  13543. EMAC->EMACADDR0H = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13544. EMAC->EMACADDR0L = (uint32_t) (ifp->mac[3] << 24) |
  13545. ((uint32_t) ifp->mac[2] << 16) |
  13546. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13547. // NOTE(scaprile) There are 3 additional slots for filtering, disabled by
  13548. // default. This also applies to the STM32 driver (at least for F7)
  13549. return true;
  13550. }
  13551. static uint32_t s_txno;
  13552. static size_t mg_tcpip_driver_tm4c_tx(const void *buf, size_t len,
  13553. struct mg_tcpip_if *ifp) {
  13554. if (len > sizeof(s_txbuf[s_txno])) {
  13555. MG_ERROR(("Frame too big, %ld", (long) len));
  13556. len = 0; // fail
  13557. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  13558. ifp->nerr++;
  13559. MG_ERROR(("No descriptors available"));
  13560. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long)
  13561. // EMAC->EMACDMARIS);
  13562. len = 0; // fail
  13563. } else {
  13564. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13565. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  13566. s_txdesc[s_txno][0] =
  13567. MG_BIT(20) | MG_BIT(28) | MG_BIT(29) | MG_BIT(30); // Chain,FS,LS,IC
  13568. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13569. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13570. }
  13571. EMAC->EMACDMARIS = MG_BIT(2) | MG_BIT(5); // Clear any prior TU/UNF
  13572. EMAC->EMACTXPOLLD = 0; // and resume
  13573. return len;
  13574. (void) ifp;
  13575. }
  13576. static bool mg_tcpip_driver_tm4c_up(struct mg_tcpip_if *ifp) {
  13577. uint32_t bmsr = emac_read_phy(EPHY_ADDR, EPHYBMSR);
  13578. bool up = (bmsr & MG_BIT(2)) ? 1 : 0;
  13579. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13580. uint32_t sts = emac_read_phy(EPHY_ADDR, EPHYSTS);
  13581. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13582. // if(link is slow or half) set flags otherwise
  13583. // reg = tmp
  13584. uint32_t emaccfg = EMAC->EMACCFG | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  13585. if (sts & MG_BIT(1)) emaccfg &= ~MG_BIT(14); // 10M
  13586. if ((sts & MG_BIT(2)) == 0) emaccfg &= ~MG_BIT(11); // Half-duplex
  13587. EMAC->EMACCFG = emaccfg; // IRQ handler does not fiddle with this register
  13588. MG_DEBUG(("Link is %uM %s-duplex", emaccfg & MG_BIT(14) ? 100 : 10,
  13589. emaccfg & MG_BIT(11) ? "full" : "half"));
  13590. }
  13591. return up;
  13592. }
  13593. void EMAC0_IRQHandler(void);
  13594. static uint32_t s_rxno;
  13595. void EMAC0_IRQHandler(void) {
  13596. if (EMAC->EMACDMARIS & MG_BIT(6)) { // Frame received, loop
  13597. EMAC->EMACDMARIS = MG_BIT(16) | MG_BIT(6); // Clear flag
  13598. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13599. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  13600. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) == (MG_BIT(8) | MG_BIT(9))) &&
  13601. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  13602. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  13603. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  13604. // EMAC->EMACDMARIS);
  13605. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13606. }
  13607. s_rxdesc[s_rxno][0] = MG_BIT(31);
  13608. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13609. }
  13610. }
  13611. EMAC->EMACDMARIS = MG_BIT(7); // Clear possible RU while processing
  13612. EMAC->EMACRXPOLLD = 0; // and resume RX
  13613. }
  13614. struct mg_tcpip_driver mg_tcpip_driver_tm4c = {mg_tcpip_driver_tm4c_init,
  13615. mg_tcpip_driver_tm4c_tx, NULL,
  13616. mg_tcpip_driver_tm4c_up};
  13617. #endif
  13618. #ifdef MG_ENABLE_LINES
  13619. #line 1 "src/drivers/w5500.c"
  13620. #endif
  13621. #if MG_ENABLE_TCPIP
  13622. enum { W5500_CR = 0, W5500_S0 = 1, W5500_TX0 = 2, W5500_RX0 = 3 };
  13623. static void w5500_txn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr, bool wr,
  13624. void *buf, size_t len) {
  13625. uint8_t *p = (uint8_t *) buf;
  13626. uint8_t cmd[] = {(uint8_t) (addr >> 8), (uint8_t) (addr & 255),
  13627. (uint8_t) ((block << 3) | (wr ? 4 : 0))};
  13628. s->begin(s->spi);
  13629. for (size_t i = 0; i < sizeof(cmd); i++) s->txn(s->spi, cmd[i]);
  13630. for (size_t i = 0; i < len; i++) {
  13631. uint8_t r = s->txn(s->spi, p[i]);
  13632. if (!wr) p[i] = r;
  13633. }
  13634. s->end(s->spi);
  13635. }
  13636. // clang-format off
  13637. 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); }
  13638. 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); }
  13639. 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)); }
  13640. 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); }
  13641. 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; }
  13642. 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]); }
  13643. // clang-format on
  13644. static size_t w5500_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  13645. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13646. uint16_t r = 0, n = 0, len = (uint16_t) buflen, n2; // Read recv len
  13647. while ((n2 = w5500_r2(s, W5500_S0, 0x26)) > n) n = n2; // Until it is stable
  13648. // printf("RSR: %d\n", (int) n);
  13649. if (n > 0) {
  13650. uint16_t ptr = w5500_r2(s, W5500_S0, 0x28); // Get read pointer
  13651. n = w5500_r2(s, W5500_RX0, ptr); // Read frame length
  13652. if (n <= len + 2 && n > 1) {
  13653. r = (uint16_t) (n - 2);
  13654. w5500_rn(s, W5500_RX0, (uint16_t) (ptr + 2), buf, r);
  13655. }
  13656. w5500_w2(s, W5500_S0, 0x28, (uint16_t) (ptr + n)); // Advance read pointer
  13657. w5500_w1(s, W5500_S0, 1, 0x40); // Sock0 CR -> RECV
  13658. // printf(" RX_RD: tot=%u n=%u r=%u\n", n2, n, r);
  13659. }
  13660. return r;
  13661. }
  13662. static size_t w5500_tx(const void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  13663. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13664. uint16_t n = 0, len = (uint16_t) buflen;
  13665. while (n < len) n = w5500_r2(s, W5500_S0, 0x20); // Wait for space
  13666. uint16_t ptr = w5500_r2(s, W5500_S0, 0x24); // Get write pointer
  13667. w5500_wn(s, W5500_TX0, ptr, (void *) buf, len); // Write data
  13668. w5500_w2(s, W5500_S0, 0x24, (uint16_t) (ptr + len)); // Advance write pointer
  13669. w5500_w1(s, W5500_S0, 1, 0x20); // Sock0 CR -> SEND
  13670. for (int i = 0; i < 40; i++) {
  13671. uint8_t ir = w5500_r1(s, W5500_S0, 2); // Read S0 IR
  13672. if (ir == 0) continue;
  13673. // printf("IR %d, len=%d, free=%d, ptr %d\n", ir, (int) len, (int) n, ptr);
  13674. w5500_w1(s, W5500_S0, 2, ir); // Write S0 IR: clear it!
  13675. if (ir & 8) len = 0; // Timeout. Report error
  13676. if (ir & (16 | 8)) break; // Stop on SEND_OK or timeout
  13677. }
  13678. return len;
  13679. }
  13680. static bool w5500_init(struct mg_tcpip_if *ifp) {
  13681. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13682. s->end(s->spi);
  13683. w5500_w1(s, W5500_CR, 0, 0x80); // Reset chip: CR -> 0x80
  13684. w5500_w1(s, W5500_CR, 0x2e, 0); // CR PHYCFGR -> reset
  13685. w5500_w1(s, W5500_CR, 0x2e, 0xf8); // CR PHYCFGR -> set
  13686. // w5500_wn(s, W5500_CR, 9, s->mac, 6); // Set source MAC
  13687. w5500_w1(s, W5500_S0, 0x1e, 16); // Sock0 RX buf size
  13688. w5500_w1(s, W5500_S0, 0x1f, 16); // Sock0 TX buf size
  13689. w5500_w1(s, W5500_S0, 0, 4); // Sock0 MR -> MACRAW
  13690. w5500_w1(s, W5500_S0, 1, 1); // Sock0 CR -> OPEN
  13691. return w5500_r1(s, W5500_S0, 3) == 0x42; // Sock0 SR == MACRAW
  13692. }
  13693. static bool w5500_up(struct mg_tcpip_if *ifp) {
  13694. struct mg_tcpip_spi *spi = (struct mg_tcpip_spi *) ifp->driver_data;
  13695. uint8_t phycfgr = w5500_r1(spi, W5500_CR, 0x2e);
  13696. return phycfgr & 1; // Bit 0 of PHYCFGR is LNK (0 - down, 1 - up)
  13697. }
  13698. struct mg_tcpip_driver mg_tcpip_driver_w5500 = {w5500_init, w5500_tx, w5500_rx, w5500_up};
  13699. #endif