mongoose.c 514 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342
  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. bool mg_mgr_init(struct mg_mgr *mgr) {
  4000. // 初始化互斥锁
  4001. #if MG_ARCH == MG_ARCH_UNIX
  4002. if (pthread_mutex_init(&WSlock, NULL) != 0) {
  4003. return false;
  4004. }
  4005. #endif
  4006. memset(mgr, 0, sizeof(*mgr));
  4007. #if MG_ENABLE_EPOLL
  4008. if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
  4009. MG_ERROR(("epoll_create1 errno %d", errno));
  4010. #else
  4011. mgr->epoll_fd = -1;
  4012. #endif
  4013. #if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  4014. // clang-format off
  4015. { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
  4016. // clang-format on
  4017. #elif MG_ENABLE_FREERTOS_TCP
  4018. mgr->ss = FreeRTOS_CreateSocketSet();
  4019. #elif defined(__unix) || defined(__unix__) || defined(__APPLE__)
  4020. // Ignore SIGPIPE signal, so if client cancels the request, it
  4021. // won't kill the whole process.
  4022. signal(SIGPIPE, SIG_IGN);
  4023. #endif
  4024. mgr->pipe = MG_INVALID_SOCKET;
  4025. mgr->dnstimeout = 3000;
  4026. mgr->dns4.url = "udp://8.8.8.8:53";
  4027. mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
  4028. mg_tls_ctx_init(mgr);
  4029. return true;
  4030. }
  4031. #ifdef MG_ENABLE_LINES
  4032. #line 1 "src/net_builtin.c"
  4033. #endif
  4034. #if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP
  4035. #define MG_EPHEMERAL_PORT_BASE 32768
  4036. #define PDIFF(a, b) ((size_t) (((char *) (b)) - ((char *) (a))))
  4037. #ifndef MIP_TCP_KEEPALIVE_MS
  4038. #define MIP_TCP_KEEPALIVE_MS 45000 // TCP keep-alive period, ms
  4039. #endif
  4040. #define MIP_TCP_ACK_MS 150 // Timeout for ACKing
  4041. #define MIP_TCP_ARP_MS 100 // Timeout for ARP response
  4042. #define MIP_TCP_SYN_MS 15000 // Timeout for connection establishment
  4043. #define MIP_TCP_FIN_MS 1000 // Timeout for closing connection
  4044. struct connstate {
  4045. uint32_t seq, ack; // TCP seq/ack counters
  4046. uint64_t timer; // TCP keep-alive / ACK timer
  4047. uint8_t mac[6]; // Peer MAC address
  4048. uint8_t ttype; // Timer type. 0: ack, 1: keep-alive
  4049. #define MIP_TTYPE_KEEPALIVE 0 // Connection is idle for long, send keepalive
  4050. #define MIP_TTYPE_ACK 1 // Peer sent us data, we have to ack it soon
  4051. #define MIP_TTYPE_ARP 2 // ARP resolve sent, waiting for response
  4052. #define MIP_TTYPE_SYN 3 // SYN sent, waiting for response
  4053. #define MIP_TTYPE_FIN 4 // FIN sent, waiting until terminating the connection
  4054. uint8_t tmiss; // Number of keep-alive misses
  4055. struct mg_iobuf raw; // For TLS only. Incoming raw data
  4056. };
  4057. #pragma pack(push, 1)
  4058. struct lcp {
  4059. uint8_t addr, ctrl, proto[2], code, id, len[2];
  4060. };
  4061. struct eth {
  4062. uint8_t dst[6]; // Destination MAC address
  4063. uint8_t src[6]; // Source MAC address
  4064. uint16_t type; // Ethernet type
  4065. };
  4066. struct ip {
  4067. uint8_t ver; // Version
  4068. uint8_t tos; // Unused
  4069. uint16_t len; // Length
  4070. uint16_t id; // Unused
  4071. uint16_t frag; // Fragmentation
  4072. #define IP_FRAG_OFFSET_MSK 0xFF1F
  4073. #define IP_MORE_FRAGS_MSK 0x20
  4074. uint8_t ttl; // Time to live
  4075. uint8_t proto; // Upper level protocol
  4076. uint16_t csum; // Checksum
  4077. uint32_t src; // Source IP
  4078. uint32_t dst; // Destination IP
  4079. };
  4080. struct ip6 {
  4081. uint8_t ver; // Version
  4082. uint8_t opts[3]; // Options
  4083. uint16_t len; // Length
  4084. uint8_t proto; // Upper level protocol
  4085. uint8_t ttl; // Time to live
  4086. uint8_t src[16]; // Source IP
  4087. uint8_t dst[16]; // Destination IP
  4088. };
  4089. struct icmp {
  4090. uint8_t type;
  4091. uint8_t code;
  4092. uint16_t csum;
  4093. };
  4094. struct arp {
  4095. uint16_t fmt; // Format of hardware address
  4096. uint16_t pro; // Format of protocol address
  4097. uint8_t hlen; // Length of hardware address
  4098. uint8_t plen; // Length of protocol address
  4099. uint16_t op; // Operation
  4100. uint8_t sha[6]; // Sender hardware address
  4101. uint32_t spa; // Sender protocol address
  4102. uint8_t tha[6]; // Target hardware address
  4103. uint32_t tpa; // Target protocol address
  4104. };
  4105. struct tcp {
  4106. uint16_t sport; // Source port
  4107. uint16_t dport; // Destination port
  4108. uint32_t seq; // Sequence number
  4109. uint32_t ack; // Acknowledgement number
  4110. uint8_t off; // Data offset
  4111. uint8_t flags; // TCP flags
  4112. #define TH_FIN 0x01
  4113. #define TH_SYN 0x02
  4114. #define TH_RST 0x04
  4115. #define TH_PUSH 0x08
  4116. #define TH_ACK 0x10
  4117. #define TH_URG 0x20
  4118. #define TH_ECE 0x40
  4119. #define TH_CWR 0x80
  4120. uint16_t win; // Window
  4121. uint16_t csum; // Checksum
  4122. uint16_t urp; // Urgent pointer
  4123. };
  4124. struct udp {
  4125. uint16_t sport; // Source port
  4126. uint16_t dport; // Destination port
  4127. uint16_t len; // UDP length
  4128. uint16_t csum; // UDP checksum
  4129. };
  4130. struct dhcp {
  4131. uint8_t op, htype, hlen, hops;
  4132. uint32_t xid;
  4133. uint16_t secs, flags;
  4134. uint32_t ciaddr, yiaddr, siaddr, giaddr;
  4135. uint8_t hwaddr[208];
  4136. uint32_t magic;
  4137. uint8_t options[32];
  4138. };
  4139. #pragma pack(pop)
  4140. struct pkt {
  4141. struct mg_str raw; // Raw packet data
  4142. struct mg_str pay; // Payload data
  4143. struct eth *eth;
  4144. struct llc *llc;
  4145. struct arp *arp;
  4146. struct ip *ip;
  4147. struct ip6 *ip6;
  4148. struct icmp *icmp;
  4149. struct tcp *tcp;
  4150. struct udp *udp;
  4151. struct dhcp *dhcp;
  4152. };
  4153. static void send_syn(struct mg_connection *c);
  4154. static void mkpay(struct pkt *pkt, void *p) {
  4155. pkt->pay =
  4156. mg_str_n((char *) p, (size_t) (&pkt->raw.ptr[pkt->raw.len] - (char *) p));
  4157. }
  4158. static uint32_t csumup(uint32_t sum, const void *buf, size_t len) {
  4159. const uint8_t *p = (const uint8_t *) buf;
  4160. for (size_t i = 0; i < len; i++) sum += i & 1 ? p[i] : (uint32_t) (p[i] << 8);
  4161. return sum;
  4162. }
  4163. static uint16_t csumfin(uint32_t sum) {
  4164. while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
  4165. return mg_htons(~sum & 0xffff);
  4166. }
  4167. static uint16_t ipcsum(const void *buf, size_t len) {
  4168. uint32_t sum = csumup(0, buf, len);
  4169. return csumfin(sum);
  4170. }
  4171. static void settmout(struct mg_connection *c, uint8_t type) {
  4172. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4173. struct connstate *s = (struct connstate *) (c + 1);
  4174. unsigned n = type == MIP_TTYPE_ACK ? MIP_TCP_ACK_MS
  4175. : type == MIP_TTYPE_ARP ? MIP_TCP_ARP_MS
  4176. : type == MIP_TTYPE_SYN ? MIP_TCP_SYN_MS
  4177. : type == MIP_TTYPE_FIN ? MIP_TCP_FIN_MS
  4178. : MIP_TCP_KEEPALIVE_MS;
  4179. s->timer = ifp->now + n;
  4180. s->ttype = type;
  4181. MG_VERBOSE(("%lu %d -> %llx", c->id, type, s->timer));
  4182. }
  4183. static size_t ether_output(struct mg_tcpip_if *ifp, size_t len) {
  4184. size_t n = ifp->driver->tx(ifp->tx.ptr, len, ifp);
  4185. if (n == len) ifp->nsent++;
  4186. return n;
  4187. }
  4188. static void arp_ask(struct mg_tcpip_if *ifp, uint32_t ip) {
  4189. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4190. struct arp *arp = (struct arp *) (eth + 1);
  4191. memset(eth->dst, 255, sizeof(eth->dst));
  4192. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4193. eth->type = mg_htons(0x806);
  4194. memset(arp, 0, sizeof(*arp));
  4195. arp->fmt = mg_htons(1), arp->pro = mg_htons(0x800), arp->hlen = 6,
  4196. arp->plen = 4;
  4197. arp->op = mg_htons(1), arp->tpa = ip, arp->spa = ifp->ip;
  4198. memcpy(arp->sha, ifp->mac, sizeof(arp->sha));
  4199. ether_output(ifp, PDIFF(eth, arp + 1));
  4200. }
  4201. static void onstatechange(struct mg_tcpip_if *ifp) {
  4202. if (ifp->state == MG_TCPIP_STATE_READY) {
  4203. MG_INFO(("READY, IP: %M", mg_print_ip4, &ifp->ip));
  4204. MG_INFO((" GW: %M", mg_print_ip4, &ifp->gw));
  4205. MG_INFO((" MAC: %M", mg_print_mac, &ifp->mac));
  4206. arp_ask(ifp, ifp->gw);
  4207. } else if (ifp->state == MG_TCPIP_STATE_UP) {
  4208. MG_ERROR(("Link up"));
  4209. srand((unsigned int) mg_millis());
  4210. } else if (ifp->state == MG_TCPIP_STATE_DOWN) {
  4211. MG_ERROR(("Link down"));
  4212. }
  4213. }
  4214. static struct ip *tx_ip(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4215. uint8_t proto, uint32_t ip_src, uint32_t ip_dst,
  4216. size_t plen) {
  4217. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4218. struct ip *ip = (struct ip *) (eth + 1);
  4219. memcpy(eth->dst, mac_dst, sizeof(eth->dst));
  4220. memcpy(eth->src, ifp->mac, sizeof(eth->src)); // Use our MAC
  4221. eth->type = mg_htons(0x800);
  4222. memset(ip, 0, sizeof(*ip));
  4223. ip->ver = 0x45; // Version 4, header length 5 words
  4224. ip->frag = 0x40; // Don't fragment
  4225. ip->len = mg_htons((uint16_t) (sizeof(*ip) + plen));
  4226. ip->ttl = 64;
  4227. ip->proto = proto;
  4228. ip->src = ip_src;
  4229. ip->dst = ip_dst;
  4230. ip->csum = ipcsum(ip, sizeof(*ip));
  4231. return ip;
  4232. }
  4233. static void tx_udp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4234. uint16_t sport, uint32_t ip_dst, uint16_t dport,
  4235. const void *buf, size_t len) {
  4236. struct ip *ip =
  4237. tx_ip(ifp, mac_dst, 17, ip_src, ip_dst, len + sizeof(struct udp));
  4238. struct udp *udp = (struct udp *) (ip + 1);
  4239. // MG_DEBUG(("UDP XX LEN %d %d", (int) len, (int) ifp->tx.len));
  4240. udp->sport = sport;
  4241. udp->dport = dport;
  4242. udp->len = mg_htons((uint16_t) (sizeof(*udp) + len));
  4243. udp->csum = 0;
  4244. uint32_t cs = csumup(0, udp, sizeof(*udp));
  4245. cs = csumup(cs, buf, len);
  4246. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4247. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4248. cs += (uint32_t) (ip->proto + sizeof(*udp) + len);
  4249. udp->csum = csumfin(cs);
  4250. memmove(udp + 1, buf, len);
  4251. // MG_DEBUG(("UDP LEN %d %d", (int) len, (int) ifp->frame_len));
  4252. ether_output(ifp, sizeof(struct eth) + sizeof(*ip) + sizeof(*udp) + len);
  4253. }
  4254. static void tx_dhcp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4255. uint32_t ip_dst, uint8_t *opts, size_t optslen,
  4256. bool ciaddr) {
  4257. // https://datatracker.ietf.org/doc/html/rfc2132#section-9.6
  4258. struct dhcp dhcp = {1, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4259. dhcp.magic = mg_htonl(0x63825363);
  4260. memcpy(&dhcp.hwaddr, ifp->mac, sizeof(ifp->mac));
  4261. memcpy(&dhcp.xid, ifp->mac + 2, sizeof(dhcp.xid));
  4262. memcpy(&dhcp.options, opts, optslen);
  4263. if (ciaddr) dhcp.ciaddr = ip_src;
  4264. tx_udp(ifp, mac_dst, ip_src, mg_htons(68), ip_dst, mg_htons(67), &dhcp,
  4265. sizeof(dhcp));
  4266. }
  4267. static const uint8_t broadcast[] = {255, 255, 255, 255, 255, 255};
  4268. // RFC-2131 #4.3.6, #4.4.1
  4269. static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
  4270. uint32_t ip_srv) {
  4271. uint8_t opts[] = {
  4272. 53, 1, 3, // Type: DHCP request
  4273. 55, 2, 1, 3, // GW and mask
  4274. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4275. 54, 4, 0, 0, 0, 0, // DHCP server ID
  4276. 50, 4, 0, 0, 0, 0, // Requested IP
  4277. 255 // End of options
  4278. };
  4279. memcpy(opts + 14, &ip_srv, sizeof(ip_srv));
  4280. memcpy(opts + 20, &ip_req, sizeof(ip_req));
  4281. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4282. MG_DEBUG(("DHCP req sent"));
  4283. }
  4284. // RFC-2131 #4.3.6, #4.4.5 (renewing: unicast, rebinding: bcast)
  4285. static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4286. uint32_t ip_src, uint32_t ip_dst) {
  4287. uint8_t opts[] = {
  4288. 53, 1, 3, // Type: DHCP request
  4289. 255 // End of options
  4290. };
  4291. tx_dhcp(ifp, mac_dst, ip_src, ip_dst, opts, sizeof(opts), true);
  4292. MG_DEBUG(("DHCP req sent"));
  4293. }
  4294. static void tx_dhcp_discover(struct mg_tcpip_if *ifp) {
  4295. uint8_t opts[] = {
  4296. 53, 1, 1, // Type: DHCP discover
  4297. 55, 2, 1, 3, // Parameters: ip, mask
  4298. 255 // End of options
  4299. };
  4300. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4301. MG_DEBUG(("DHCP discover sent. Our MAC: %M", mg_print_mac, ifp->mac));
  4302. }
  4303. static struct mg_connection *getpeer(struct mg_mgr *mgr, struct pkt *pkt,
  4304. bool lsn) {
  4305. struct mg_connection *c = NULL;
  4306. for (c = mgr->conns; c != NULL; c = c->next) {
  4307. if (c->is_arplooking && pkt->arp &&
  4308. memcmp(&pkt->arp->spa, c->rem.ip, sizeof(pkt->arp->spa)) == 0)
  4309. break;
  4310. if (c->is_udp && pkt->udp && c->loc.port == pkt->udp->dport) break;
  4311. if (!c->is_udp && pkt->tcp && c->loc.port == pkt->tcp->dport &&
  4312. lsn == c->is_listening && (lsn || c->rem.port == pkt->tcp->sport))
  4313. break;
  4314. }
  4315. return c;
  4316. }
  4317. static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4318. if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) {
  4319. // ARP request. Make a response, then send
  4320. // MG_DEBUG(("ARP op %d %M: %M", mg_ntohs(pkt->arp->op), mg_print_ip4,
  4321. // &pkt->arp->spa, mg_print_ip4, &pkt->arp->tpa));
  4322. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4323. struct arp *arp = (struct arp *) (eth + 1);
  4324. memcpy(eth->dst, pkt->eth->src, sizeof(eth->dst));
  4325. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4326. eth->type = mg_htons(0x806);
  4327. *arp = *pkt->arp;
  4328. arp->op = mg_htons(2);
  4329. memcpy(arp->tha, pkt->arp->sha, sizeof(pkt->arp->tha));
  4330. memcpy(arp->sha, ifp->mac, sizeof(pkt->arp->sha));
  4331. arp->tpa = pkt->arp->spa;
  4332. arp->spa = ifp->ip;
  4333. MG_DEBUG(("ARP: tell %M we're %M", mg_print_ip4, &arp->tpa, mg_print_mac,
  4334. &ifp->mac));
  4335. ether_output(ifp, PDIFF(eth, arp + 1));
  4336. } else if (pkt->arp->op == mg_htons(2)) {
  4337. if (memcmp(pkt->arp->tha, ifp->mac, sizeof(pkt->arp->tha)) != 0) return;
  4338. if (pkt->arp->spa == ifp->gw) {
  4339. // Got response for the GW ARP request. Set ifp->gwmac
  4340. memcpy(ifp->gwmac, pkt->arp->sha, sizeof(ifp->gwmac));
  4341. } else {
  4342. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4343. if (c != NULL && c->is_arplooking) {
  4344. struct connstate *s = (struct connstate *) (c + 1);
  4345. memcpy(s->mac, pkt->arp->sha, sizeof(s->mac));
  4346. MG_DEBUG(("%lu ARP resolved %M -> %M", c->id, mg_print_ip4, c->rem.ip,
  4347. mg_print_mac, s->mac));
  4348. c->is_arplooking = 0;
  4349. send_syn(c);
  4350. settmout(c, MIP_TTYPE_SYN);
  4351. }
  4352. }
  4353. }
  4354. }
  4355. static void rx_icmp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4356. // MG_DEBUG(("ICMP %d", (int) len));
  4357. if (pkt->icmp->type == 8 && pkt->ip != NULL && pkt->ip->dst == ifp->ip) {
  4358. size_t hlen = sizeof(struct eth) + sizeof(struct ip) + sizeof(struct icmp);
  4359. size_t space = ifp->tx.len - hlen, plen = pkt->pay.len;
  4360. if (plen > space) plen = space;
  4361. struct ip *ip = tx_ip(ifp, pkt->eth->src, 1, ifp->ip, pkt->ip->src,
  4362. sizeof(struct icmp) + plen);
  4363. struct icmp *icmp = (struct icmp *) (ip + 1);
  4364. memset(icmp, 0, sizeof(*icmp)); // Set csum to 0
  4365. memcpy(icmp + 1, pkt->pay.ptr, plen); // Copy RX payload to TX
  4366. icmp->csum = ipcsum(icmp, sizeof(*icmp) + plen);
  4367. ether_output(ifp, hlen + plen);
  4368. }
  4369. }
  4370. static void rx_dhcp_client(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4371. uint32_t ip = 0, gw = 0, mask = 0, lease = 0;
  4372. uint8_t msgtype = 0, state = ifp->state;
  4373. // perform size check first, then access fields
  4374. uint8_t *p = pkt->dhcp->options,
  4375. *end = (uint8_t *) &pkt->raw.ptr[pkt->raw.len];
  4376. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4377. if (memcmp(&pkt->dhcp->xid, ifp->mac + 2, sizeof(pkt->dhcp->xid))) return;
  4378. while (p + 1 < end && p[0] != 255) { // Parse options RFC-1533 #9
  4379. if (p[0] == 1 && p[1] == sizeof(ifp->mask) && p + 6 < end) { // Mask
  4380. memcpy(&mask, p + 2, sizeof(mask));
  4381. } else if (p[0] == 3 && p[1] == sizeof(ifp->gw) && p + 6 < end) { // GW
  4382. memcpy(&gw, p + 2, sizeof(gw));
  4383. ip = pkt->dhcp->yiaddr;
  4384. } else if (p[0] == 51 && p[1] == 4 && p + 6 < end) { // Lease
  4385. memcpy(&lease, p + 2, sizeof(lease));
  4386. lease = mg_ntohl(lease);
  4387. } else if (p[0] == 53 && p[1] == 1 && p + 6 < end) { // Msg Type
  4388. msgtype = p[2];
  4389. }
  4390. p += p[1] + 2;
  4391. }
  4392. // Process message type, RFC-1533 (9.4); RFC-2131 (3.1, 4)
  4393. if (msgtype == 6 && ifp->ip == ip) { // DHCPNACK, release IP
  4394. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0;
  4395. } else if (msgtype == 2 && ifp->state == MG_TCPIP_STATE_UP && ip && gw &&
  4396. lease) { // DHCPOFFER
  4397. tx_dhcp_request_sel(ifp, ip, pkt->dhcp->siaddr); // select IP, (4.4.1)
  4398. ifp->state = MG_TCPIP_STATE_REQ; // REQUESTING state
  4399. } else if (msgtype == 5) { // DHCPACK
  4400. if (ifp->state == MG_TCPIP_STATE_REQ && ip && gw && lease) { // got an IP
  4401. ifp->lease_expire = ifp->now + lease * 1000;
  4402. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4403. // assume DHCP server = router until ARP resolves
  4404. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4405. ifp->ip = ip, ifp->gw = gw, ifp->mask = mask;
  4406. ifp->state = MG_TCPIP_STATE_READY; // BOUND state
  4407. uint64_t rand;
  4408. mg_random(&rand, sizeof(rand));
  4409. srand((unsigned int) (rand + mg_millis()));
  4410. } else if (ifp->state == MG_TCPIP_STATE_READY && ifp->ip == ip) { // renew
  4411. ifp->lease_expire = ifp->now + lease * 1000;
  4412. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4413. } // TODO(): accept provided T1/T2 and store server IP for renewal (4.4)
  4414. }
  4415. if (ifp->state != state) onstatechange(ifp);
  4416. }
  4417. // Simple DHCP server that assigns a next IP address: ifp->ip + 1
  4418. static void rx_dhcp_server(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4419. uint8_t op = 0, *p = pkt->dhcp->options,
  4420. *end = (uint8_t *) &pkt->raw.ptr[pkt->raw.len];
  4421. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4422. // struct dhcp *req = pkt->dhcp;
  4423. struct dhcp res = {2, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4424. res.yiaddr = ifp->ip;
  4425. ((uint8_t *) (&res.yiaddr))[3]++; // Offer our IP + 1
  4426. while (p + 1 < end && p[0] != 255) { // Parse options
  4427. if (p[0] == 53 && p[1] == 1 && p + 2 < end) { // Message type
  4428. op = p[2];
  4429. }
  4430. p += p[1] + 2;
  4431. }
  4432. if (op == 1 || op == 3) { // DHCP Discover or DHCP Request
  4433. uint8_t msg = op == 1 ? 2 : 5; // Message type: DHCP OFFER or DHCP ACK
  4434. uint8_t opts[] = {
  4435. 53, 1, msg, // Message type
  4436. 1, 4, 0, 0, 0, 0, // Subnet mask
  4437. 54, 4, 0, 0, 0, 0, // Server ID
  4438. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4439. 51, 4, 255, 255, 255, 255, // Lease time
  4440. 255 // End of options
  4441. };
  4442. memcpy(&res.hwaddr, pkt->dhcp->hwaddr, 6);
  4443. memcpy(opts + 5, &ifp->mask, sizeof(ifp->mask));
  4444. memcpy(opts + 11, &ifp->ip, sizeof(ifp->ip));
  4445. memcpy(&res.options, opts, sizeof(opts));
  4446. res.magic = pkt->dhcp->magic;
  4447. res.xid = pkt->dhcp->xid;
  4448. if (ifp->enable_get_gateway) {
  4449. ifp->gw = res.yiaddr;
  4450. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4451. }
  4452. tx_udp(ifp, pkt->eth->src, ifp->ip, mg_htons(67),
  4453. op == 1 ? ~0U : res.yiaddr, mg_htons(68), &res, sizeof(res));
  4454. }
  4455. }
  4456. static void rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4457. struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
  4458. if (c == NULL) {
  4459. // No UDP listener on this port. Should send ICMP, but keep silent.
  4460. } else {
  4461. c->rem.port = pkt->udp->sport;
  4462. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4463. struct connstate *s = (struct connstate *) (c + 1);
  4464. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4465. if (c->recv.len >= MG_MAX_RECV_SIZE) {
  4466. mg_error(c, "max_recv_buf_size reached");
  4467. } else if (c->recv.size - c->recv.len < pkt->pay.len &&
  4468. !mg_iobuf_resize(&c->recv, c->recv.len + pkt->pay.len)) {
  4469. mg_error(c, "oom");
  4470. } else {
  4471. memcpy(&c->recv.buf[c->recv.len], pkt->pay.ptr, pkt->pay.len);
  4472. c->recv.len += pkt->pay.len;
  4473. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4474. }
  4475. }
  4476. }
  4477. static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *dst_mac, uint32_t dst_ip,
  4478. uint8_t flags, uint16_t sport, uint16_t dport,
  4479. uint32_t seq, uint32_t ack, const void *buf, size_t len) {
  4480. struct ip *ip =
  4481. tx_ip(ifp, dst_mac, 6, ifp->ip, dst_ip, sizeof(struct tcp) + len);
  4482. struct tcp *tcp = (struct tcp *) (ip + 1);
  4483. memset(tcp, 0, sizeof(*tcp));
  4484. if (buf != NULL && len) memmove(tcp + 1, buf, len);
  4485. tcp->sport = sport;
  4486. tcp->dport = dport;
  4487. tcp->seq = seq;
  4488. tcp->ack = ack;
  4489. tcp->flags = flags;
  4490. tcp->win = mg_htons(8192);
  4491. tcp->off = (uint8_t) (sizeof(*tcp) / 4 << 4);
  4492. uint32_t cs = 0;
  4493. uint16_t n = (uint16_t) (sizeof(*tcp) + len);
  4494. uint8_t pseudo[] = {0, ip->proto, (uint8_t) (n >> 8), (uint8_t) (n & 255)};
  4495. cs = csumup(cs, tcp, n);
  4496. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4497. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4498. cs = csumup(cs, pseudo, sizeof(pseudo));
  4499. tcp->csum = csumfin(cs);
  4500. MG_VERBOSE(("TCP %M:%hu -> %M:%hu fl %x len %u", mg_print_ip4, &ip->src,
  4501. mg_ntohs(tcp->sport), mg_print_ip4, &ip->dst,
  4502. mg_ntohs(tcp->dport), tcp->flags, (int) len));
  4503. // mg_hexdump(ifp->tx.ptr, PDIFF(ifp->tx.ptr, tcp + 1) + len);
  4504. return ether_output(ifp, PDIFF(ifp->tx.ptr, tcp + 1) + len);
  4505. }
  4506. static size_t tx_tcp_pkt(struct mg_tcpip_if *ifp, struct pkt *pkt,
  4507. uint8_t flags, uint32_t seq, const void *buf,
  4508. size_t len) {
  4509. uint32_t delta = (pkt->tcp->flags & (TH_SYN | TH_FIN)) ? 1 : 0;
  4510. return tx_tcp(ifp, pkt->eth->src, pkt->ip->src, flags, pkt->tcp->dport,
  4511. pkt->tcp->sport, seq, mg_htonl(mg_ntohl(pkt->tcp->seq) + delta),
  4512. buf, len);
  4513. }
  4514. static struct mg_connection *accept_conn(struct mg_connection *lsn,
  4515. struct pkt *pkt) {
  4516. struct mg_connection *c = mg_alloc_conn(lsn->mgr);
  4517. if (c == NULL) {
  4518. MG_ERROR(("OOM"));
  4519. return NULL;
  4520. }
  4521. struct connstate *s = (struct connstate *) (c + 1);
  4522. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq);
  4523. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4524. settmout(c, MIP_TTYPE_KEEPALIVE);
  4525. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4526. c->rem.port = pkt->tcp->sport;
  4527. MG_DEBUG(("%lu accepted %M", c->id, mg_print_ip_port, &c->rem));
  4528. LIST_ADD_HEAD(struct mg_connection, &lsn->mgr->conns, c);
  4529. c->is_accepted = 1;
  4530. c->is_hexdumping = lsn->is_hexdumping;
  4531. c->pfn = lsn->pfn;
  4532. c->loc = lsn->loc;
  4533. c->pfn_data = lsn->pfn_data;
  4534. c->fn = lsn->fn;
  4535. c->fn_data = lsn->fn_data;
  4536. mg_call(c, MG_EV_OPEN, NULL);
  4537. mg_call(c, MG_EV_ACCEPT, NULL);
  4538. return c;
  4539. }
  4540. static size_t trim_len(struct mg_connection *c, size_t len) {
  4541. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4542. size_t eth_h_len = 14, ip_max_h_len = 24, tcp_max_h_len = 60, udp_h_len = 8;
  4543. size_t max_headers_len =
  4544. eth_h_len + ip_max_h_len + (c->is_udp ? udp_h_len : tcp_max_h_len);
  4545. size_t min_mtu = c->is_udp ? 68 /* RFC-791 */ : max_headers_len - eth_h_len;
  4546. // If the frame exceeds the available buffer, trim the length
  4547. if (len + max_headers_len > ifp->tx.len) {
  4548. len = ifp->tx.len - max_headers_len;
  4549. }
  4550. // Ensure the MTU isn't lower than the minimum allowed value
  4551. if (ifp->mtu < min_mtu) {
  4552. MG_ERROR(("MTU is lower than minimum, capping to %lu", min_mtu));
  4553. ifp->mtu = (uint16_t) min_mtu;
  4554. }
  4555. // If the total packet size exceeds the MTU, trim the length
  4556. if (len + max_headers_len - eth_h_len > ifp->mtu) {
  4557. len = ifp->mtu - max_headers_len + eth_h_len;
  4558. if (c->is_udp) {
  4559. MG_ERROR(("UDP datagram exceeds MTU. Truncating it."));
  4560. }
  4561. }
  4562. return len;
  4563. }
  4564. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  4565. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4566. struct connstate *s = (struct connstate *) (c + 1);
  4567. uint32_t dst_ip = *(uint32_t *) c->rem.ip;
  4568. len = trim_len(c, len);
  4569. if (c->is_udp) {
  4570. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, dst_ip, c->rem.port, buf, len);
  4571. } else {
  4572. size_t sent =
  4573. tx_tcp(ifp, s->mac, dst_ip, TH_PUSH | TH_ACK, c->loc.port, c->rem.port,
  4574. mg_htonl(s->seq), mg_htonl(s->ack), buf, len);
  4575. if (sent == 0) {
  4576. return MG_IO_WAIT;
  4577. } else if (sent == (size_t) -1) {
  4578. return MG_IO_ERR;
  4579. } else {
  4580. s->seq += (uint32_t) len;
  4581. if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
  4582. }
  4583. }
  4584. return (long) len;
  4585. }
  4586. static void read_conn(struct mg_connection *c, struct pkt *pkt) {
  4587. struct connstate *s = (struct connstate *) (c + 1);
  4588. struct mg_iobuf *io = c->is_tls ? &c->rtls : &c->recv;
  4589. uint32_t seq = mg_ntohl(pkt->tcp->seq);
  4590. uint32_t rem_ip;
  4591. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4592. if (pkt->tcp->flags & TH_FIN) {
  4593. // If we initiated the closure, we reply with ACK upon receiving FIN
  4594. // If we didn't initiate it, we reply with FIN as part of the normal TCP
  4595. // closure process
  4596. uint8_t flags = TH_ACK;
  4597. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len + 1);
  4598. if (c->is_draining && s->ttype == MIP_TTYPE_FIN) {
  4599. if (s->seq == mg_htonl(pkt->tcp->ack)) { // Simultaneous closure ?
  4600. s->seq++; // Yes. Increment our SEQ
  4601. } else { // Otherwise,
  4602. s->seq = mg_htonl(pkt->tcp->ack); // Set to peer's ACK
  4603. }
  4604. } else {
  4605. flags |= TH_FIN;
  4606. c->is_draining = 1;
  4607. settmout(c, MIP_TTYPE_FIN);
  4608. }
  4609. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, flags,
  4610. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4611. } else if (pkt->pay.len == 0) {
  4612. // TODO(cpq): handle this peer's ACK
  4613. } else if (seq != s->ack) {
  4614. uint32_t ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  4615. if (s->ack == ack) {
  4616. MG_VERBOSE(("ignoring duplicate pkt"));
  4617. } else {
  4618. MG_VERBOSE(("SEQ != ACK: %x %x %x", seq, s->ack, ack));
  4619. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  4620. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "",
  4621. 0);
  4622. }
  4623. } else if (io->size - io->len < pkt->pay.len &&
  4624. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  4625. mg_error(c, "oom");
  4626. } else {
  4627. // Copy TCP payload into the IO buffer. If the connection is plain text,
  4628. // we copy to c->recv. If the connection is TLS, this data is encrypted,
  4629. // therefore we copy that encrypted data to the c->rtls iobuffer instead,
  4630. // and then call mg_tls_recv() to decrypt it. NOTE: mg_tls_recv() will
  4631. // call back mg_io_recv() which grabs raw data from c->rtls
  4632. memcpy(&io->buf[io->len], pkt->pay.ptr, pkt->pay.len);
  4633. io->len += pkt->pay.len;
  4634. MG_VERBOSE(("%lu SEQ %x -> %x", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  4635. // Advance ACK counter
  4636. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  4637. #if 0
  4638. // Send ACK immediately
  4639. uint32_t rem_ip;
  4640. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4641. MG_DEBUG((" imm ACK", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  4642. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK, c->loc.port,
  4643. c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4644. #else
  4645. // if not already running, setup a timer to send an ACK later
  4646. if (s->ttype != MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_ACK);
  4647. #endif
  4648. if (c->is_tls && c->is_tls_hs) {
  4649. mg_tls_handshake(c);
  4650. } else if (c->is_tls) {
  4651. // TLS connection. Make room for decrypted data in c->recv
  4652. io = &c->recv;
  4653. if (io->size - io->len < pkt->pay.len &&
  4654. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  4655. mg_error(c, "oom");
  4656. } else {
  4657. // Decrypt data directly into c->recv
  4658. long n = mg_tls_recv(c, &io->buf[io->len], io->size - io->len);
  4659. if (n == MG_IO_ERR) {
  4660. mg_error(c, "TLS recv error");
  4661. } else if (n > 0) {
  4662. // Decrypted successfully - trigger MG_EV_READ
  4663. io->len += (size_t) n;
  4664. mg_call(c, MG_EV_READ, &n);
  4665. }
  4666. }
  4667. } else {
  4668. // Plain text connection, data is already in c->recv, trigger
  4669. // MG_EV_READ
  4670. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4671. }
  4672. }
  4673. }
  4674. static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4675. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4676. struct connstate *s = c == NULL ? NULL : (struct connstate *) (c + 1);
  4677. #if 0
  4678. MG_INFO(("%lu %hhu %d", c ? c->id : 0, pkt->tcp->flags, (int) pkt->pay.len));
  4679. #endif
  4680. if (c != NULL && c->is_connecting && pkt->tcp->flags == (TH_SYN | TH_ACK)) {
  4681. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq) + 1;
  4682. tx_tcp_pkt(ifp, pkt, TH_ACK, pkt->tcp->ack, NULL, 0);
  4683. c->is_connecting = 0; // Client connected
  4684. settmout(c, MIP_TTYPE_KEEPALIVE);
  4685. mg_call(c, MG_EV_CONNECT, NULL); // Let user know
  4686. } else if (c != NULL && c->is_connecting && pkt->tcp->flags != TH_ACK) {
  4687. // mg_hexdump(pkt->raw.ptr, pkt->raw.len);
  4688. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4689. } else if (c != NULL && pkt->tcp->flags & TH_RST) {
  4690. mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  4691. } else if (c != NULL) {
  4692. #if 0
  4693. MG_DEBUG(("%lu %d %M:%hu -> %M:%hu", c->id, (int) pkt->raw.len,
  4694. mg_print_ip4, &pkt->ip->src, mg_ntohs(pkt->tcp->sport),
  4695. mg_print_ip4, &pkt->ip->dst, mg_ntohs(pkt->tcp->dport)));
  4696. mg_hexdump(pkt->pay.ptr, pkt->pay.len);
  4697. #endif
  4698. s->tmiss = 0; // Reset missed keep-alive counter
  4699. if (s->ttype == MIP_TTYPE_KEEPALIVE) // Advance keep-alive timer
  4700. settmout(c,
  4701. MIP_TTYPE_KEEPALIVE); // unless a former ACK timeout is pending
  4702. read_conn(c, pkt); // Override timer with ACK timeout if needed
  4703. } else if ((c = getpeer(ifp->mgr, pkt, true)) == NULL) {
  4704. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4705. } else if (pkt->tcp->flags & TH_RST) {
  4706. if (c->is_accepted) mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  4707. // ignore RST if not connected
  4708. } else if (pkt->tcp->flags & TH_SYN) {
  4709. // Use peer's source port as ISN, in order to recognise the handshake
  4710. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(pkt->tcp->sport));
  4711. tx_tcp_pkt(ifp, pkt, TH_SYN | TH_ACK, isn, NULL, 0);
  4712. } else if (pkt->tcp->flags & TH_FIN) {
  4713. tx_tcp_pkt(ifp, pkt, TH_FIN | TH_ACK, pkt->tcp->ack, NULL, 0);
  4714. } else if (mg_htonl(pkt->tcp->ack) == mg_htons(pkt->tcp->sport) + 1U) {
  4715. accept_conn(c, pkt);
  4716. } else if (!c->is_accepted) { // no peer
  4717. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4718. } else {
  4719. // MG_VERBOSE(("dropped silently.."));
  4720. }
  4721. }
  4722. static void rx_ip(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4723. if (pkt->ip->frag & IP_MORE_FRAGS_MSK || pkt->ip->frag & IP_FRAG_OFFSET_MSK) {
  4724. if (pkt->ip->proto == 17) pkt->udp = (struct udp *) (pkt->ip + 1);
  4725. if (pkt->ip->proto == 6) pkt->tcp = (struct tcp *) (pkt->ip + 1);
  4726. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4727. if (c) mg_error(c, "Received fragmented packet");
  4728. } else if (pkt->ip->proto == 1) {
  4729. pkt->icmp = (struct icmp *) (pkt->ip + 1);
  4730. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  4731. mkpay(pkt, pkt->icmp + 1);
  4732. rx_icmp(ifp, pkt);
  4733. } else if (pkt->ip->proto == 17) {
  4734. pkt->udp = (struct udp *) (pkt->ip + 1);
  4735. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  4736. mkpay(pkt, pkt->udp + 1);
  4737. MG_VERBOSE(("UDP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  4738. mg_ntohs(pkt->udp->sport), mg_print_ip4, &pkt->ip->dst,
  4739. mg_ntohs(pkt->udp->dport), (int) pkt->pay.len));
  4740. if (ifp->enable_dhcp_client && pkt->udp->dport == mg_htons(68)) {
  4741. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  4742. mkpay(pkt, pkt->dhcp + 1);
  4743. rx_dhcp_client(ifp, pkt);
  4744. } else if (ifp->enable_dhcp_server && pkt->udp->dport == mg_htons(67)) {
  4745. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  4746. mkpay(pkt, pkt->dhcp + 1);
  4747. rx_dhcp_server(ifp, pkt);
  4748. } else {
  4749. rx_udp(ifp, pkt);
  4750. }
  4751. } else if (pkt->ip->proto == 6) {
  4752. pkt->tcp = (struct tcp *) (pkt->ip + 1);
  4753. if (pkt->pay.len < sizeof(*pkt->tcp)) return;
  4754. mkpay(pkt, pkt->tcp + 1);
  4755. uint16_t iplen = mg_ntohs(pkt->ip->len);
  4756. uint16_t off = (uint16_t) (sizeof(*pkt->ip) + ((pkt->tcp->off >> 4) * 4U));
  4757. if (iplen >= off) pkt->pay.len = (size_t) (iplen - off);
  4758. MG_VERBOSE(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  4759. mg_ntohs(pkt->tcp->sport), mg_print_ip4, &pkt->ip->dst,
  4760. mg_ntohs(pkt->tcp->dport), (int) pkt->pay.len));
  4761. rx_tcp(ifp, pkt);
  4762. }
  4763. }
  4764. static void rx_ip6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4765. // MG_DEBUG(("IP %d", (int) len));
  4766. if (pkt->ip6->proto == 1 || pkt->ip6->proto == 58) {
  4767. pkt->icmp = (struct icmp *) (pkt->ip6 + 1);
  4768. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  4769. mkpay(pkt, pkt->icmp + 1);
  4770. rx_icmp(ifp, pkt);
  4771. } else if (pkt->ip6->proto == 17) {
  4772. pkt->udp = (struct udp *) (pkt->ip6 + 1);
  4773. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  4774. // MG_DEBUG((" UDP %u %u -> %u", len, mg_htons(udp->sport),
  4775. // mg_htons(udp->dport)));
  4776. mkpay(pkt, pkt->udp + 1);
  4777. }
  4778. }
  4779. static void mg_tcpip_rx(struct mg_tcpip_if *ifp, void *buf, size_t len) {
  4780. struct pkt pkt;
  4781. memset(&pkt, 0, sizeof(pkt));
  4782. pkt.raw.ptr = (char *) buf;
  4783. pkt.raw.len = len;
  4784. pkt.eth = (struct eth *) buf;
  4785. // mg_hexdump(buf, len > 16 ? 16: len);
  4786. if (pkt.raw.len < sizeof(*pkt.eth)) return; // Truncated - runt?
  4787. if (ifp->enable_mac_check &&
  4788. memcmp(pkt.eth->dst, ifp->mac, sizeof(pkt.eth->dst)) != 0 &&
  4789. memcmp(pkt.eth->dst, broadcast, sizeof(pkt.eth->dst)) != 0)
  4790. return;
  4791. if (ifp->enable_crc32_check && len > 4) {
  4792. len -= 4; // TODO(scaprile): check on bigendian
  4793. uint32_t crc = mg_crc32(0, (const char *) buf, len);
  4794. if (memcmp((void *) ((size_t) buf + len), &crc, sizeof(crc))) return;
  4795. }
  4796. if (pkt.eth->type == mg_htons(0x806)) {
  4797. pkt.arp = (struct arp *) (pkt.eth + 1);
  4798. if (sizeof(*pkt.eth) + sizeof(*pkt.arp) > pkt.raw.len) return; // Truncated
  4799. rx_arp(ifp, &pkt);
  4800. } else if (pkt.eth->type == mg_htons(0x86dd)) {
  4801. pkt.ip6 = (struct ip6 *) (pkt.eth + 1);
  4802. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip6)) return; // Truncated
  4803. if ((pkt.ip6->ver >> 4) != 0x6) return; // Not IP
  4804. mkpay(&pkt, pkt.ip6 + 1);
  4805. rx_ip6(ifp, &pkt);
  4806. } else if (pkt.eth->type == mg_htons(0x800)) {
  4807. pkt.ip = (struct ip *) (pkt.eth + 1);
  4808. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  4809. // Truncate frame to what IP header tells us
  4810. if ((size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth) < pkt.raw.len) {
  4811. pkt.raw.len = (size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth);
  4812. }
  4813. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  4814. if ((pkt.ip->ver >> 4) != 4) return; // Not IP
  4815. mkpay(&pkt, pkt.ip + 1);
  4816. rx_ip(ifp, &pkt);
  4817. } else {
  4818. MG_DEBUG(("Unknown eth type %x", mg_htons(pkt.eth->type)));
  4819. if (mg_log_level >= MG_LL_VERBOSE) mg_hexdump(buf, len >= 32 ? 32 : len);
  4820. }
  4821. }
  4822. static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t uptime_ms) {
  4823. if (ifp == NULL || ifp->driver == NULL) return;
  4824. bool expired_1000ms = mg_timer_expired(&ifp->timer_1000ms, 1000, uptime_ms);
  4825. ifp->now = uptime_ms;
  4826. // Handle physical interface up/down status
  4827. if (expired_1000ms && ifp->driver->up) {
  4828. bool up = ifp->driver->up(ifp);
  4829. bool current = ifp->state != MG_TCPIP_STATE_DOWN;
  4830. if (up != current) {
  4831. ifp->state = up == false ? MG_TCPIP_STATE_DOWN
  4832. : ifp->enable_dhcp_client ? MG_TCPIP_STATE_UP
  4833. : MG_TCPIP_STATE_READY;
  4834. if (!up && ifp->enable_dhcp_client) ifp->ip = 0;
  4835. onstatechange(ifp);
  4836. }
  4837. }
  4838. if (ifp->state == MG_TCPIP_STATE_DOWN) return;
  4839. // DHCP RFC-2131 (4.4)
  4840. if (ifp->state == MG_TCPIP_STATE_UP && expired_1000ms) {
  4841. tx_dhcp_discover(ifp); // INIT (4.4.1)
  4842. } else if (expired_1000ms && ifp->state == MG_TCPIP_STATE_READY &&
  4843. ifp->lease_expire > 0) { // BOUND / RENEWING / REBINDING
  4844. if (ifp->now >= ifp->lease_expire) {
  4845. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0; // expired, release IP
  4846. onstatechange(ifp);
  4847. } else if (ifp->now + 30UL * 60UL * 1000UL > ifp->lease_expire &&
  4848. ((ifp->now / 1000) % 60) == 0) {
  4849. // hack: 30 min before deadline, try to rebind (4.3.6) every min
  4850. tx_dhcp_request_re(ifp, (uint8_t *) broadcast, ifp->ip, 0xffffffff);
  4851. } // TODO(): Handle T1 (RENEWING) and T2 (REBINDING) (4.4.5)
  4852. }
  4853. // Read data from the network
  4854. if (ifp->driver->rx != NULL) { // Polling driver. We must call it
  4855. size_t len =
  4856. ifp->driver->rx(ifp->recv_queue.buf, ifp->recv_queue.size, ifp);
  4857. if (len > 0) {
  4858. ifp->nrecv++;
  4859. mg_tcpip_rx(ifp, ifp->recv_queue.buf, len);
  4860. }
  4861. } else { // Interrupt-based driver. Fills recv queue itself
  4862. char *buf;
  4863. size_t len = mg_queue_next(&ifp->recv_queue, &buf);
  4864. if (len > 0) {
  4865. mg_tcpip_rx(ifp, buf, len);
  4866. mg_queue_del(&ifp->recv_queue, len);
  4867. }
  4868. }
  4869. // Process timeouts
  4870. for (struct mg_connection *c = ifp->mgr->conns; c != NULL; c = c->next) {
  4871. if (c->is_udp || c->is_listening || c->is_resolving) continue;
  4872. struct connstate *s = (struct connstate *) (c + 1);
  4873. uint32_t rem_ip;
  4874. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4875. if (uptime_ms > s->timer) {
  4876. if (s->ttype == MIP_TTYPE_ACK) {
  4877. MG_VERBOSE(("%lu ack %x %x", c->id, s->seq, s->ack));
  4878. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4879. mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4880. } else if (s->ttype == MIP_TTYPE_ARP) {
  4881. mg_error(c, "ARP timeout");
  4882. } else if (s->ttype == MIP_TTYPE_SYN) {
  4883. mg_error(c, "Connection timeout");
  4884. } else if (s->ttype == MIP_TTYPE_FIN) {
  4885. c->is_closing = 1;
  4886. continue;
  4887. } else {
  4888. if (s->tmiss++ > 2) {
  4889. mg_error(c, "keepalive");
  4890. } else {
  4891. MG_VERBOSE(("%lu keepalive", c->id));
  4892. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4893. mg_htonl(s->seq - 1), mg_htonl(s->ack), "", 0);
  4894. }
  4895. }
  4896. settmout(c, MIP_TTYPE_KEEPALIVE);
  4897. }
  4898. }
  4899. }
  4900. // This function executes in interrupt context, thus it should copy data
  4901. // somewhere fast. Note that newlib's malloc is not thread safe, thus use
  4902. // our lock-free queue with preallocated buffer to copy data and return asap
  4903. void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) {
  4904. char *p;
  4905. if (mg_queue_book(&ifp->recv_queue, &p, len) >= len) {
  4906. memcpy(p, buf, len);
  4907. mg_queue_add(&ifp->recv_queue, len);
  4908. ifp->nrecv++;
  4909. } else {
  4910. ifp->ndrop++;
  4911. }
  4912. }
  4913. void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
  4914. // If MAC address is not set, make a random one
  4915. if (ifp->mac[0] == 0 && ifp->mac[1] == 0 && ifp->mac[2] == 0 &&
  4916. ifp->mac[3] == 0 && ifp->mac[4] == 0 && ifp->mac[5] == 0) {
  4917. ifp->mac[0] = 0x02; // Locally administered, unicast
  4918. mg_random(&ifp->mac[1], sizeof(ifp->mac) - 1);
  4919. MG_INFO(("MAC not set. Generated random: %M", mg_print_mac, ifp->mac));
  4920. }
  4921. if (ifp->driver->init && !ifp->driver->init(ifp)) {
  4922. MG_ERROR(("driver init failed"));
  4923. } else {
  4924. size_t framesize = 1540;
  4925. ifp->tx.ptr = (char *) calloc(1, framesize), ifp->tx.len = framesize;
  4926. if (ifp->recv_queue.size == 0)
  4927. ifp->recv_queue.size = ifp->driver->rx ? framesize : 8192;
  4928. ifp->recv_queue.buf = (char *) calloc(1, ifp->recv_queue.size);
  4929. ifp->timer_1000ms = mg_millis();
  4930. mgr->priv = ifp;
  4931. ifp->mgr = mgr;
  4932. ifp->mtu = MG_TCPIP_MTU_DEFAULT;
  4933. mgr->extraconnsize = sizeof(struct connstate);
  4934. if (ifp->ip == 0) ifp->enable_dhcp_client = true;
  4935. memset(ifp->gwmac, 255, sizeof(ifp->gwmac)); // Set to broadcast
  4936. mg_random(&ifp->eport, sizeof(ifp->eport)); // Random from 0 to 65535
  4937. ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
  4938. // MG_EPHEMERAL_PORT_BASE to 65535
  4939. if (ifp->tx.ptr == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
  4940. }
  4941. }
  4942. void mg_tcpip_free(struct mg_tcpip_if *ifp) {
  4943. free(ifp->recv_queue.buf);
  4944. free((char *) ifp->tx.ptr);
  4945. }
  4946. static void send_syn(struct mg_connection *c) {
  4947. struct connstate *s = (struct connstate *) (c + 1);
  4948. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(c->loc.port));
  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. tx_tcp(ifp, s->mac, rem_ip, TH_SYN, c->loc.port, c->rem.port, isn, 0, NULL,
  4953. 0);
  4954. }
  4955. void mg_connect_resolved(struct mg_connection *c) {
  4956. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4957. uint32_t rem_ip;
  4958. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4959. c->is_resolving = 0;
  4960. if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
  4961. memcpy(c->loc.ip, &ifp->ip, sizeof(uint32_t));
  4962. c->loc.port = mg_htons(ifp->eport++);
  4963. MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
  4964. &c->rem));
  4965. mg_call(c, MG_EV_RESOLVE, NULL);
  4966. if (c->is_udp && (rem_ip == 0xffffffff || rem_ip == (ifp->ip | ~ifp->mask))) {
  4967. struct connstate *s = (struct connstate *) (c + 1);
  4968. memset(s->mac, 0xFF, sizeof(s->mac)); // global or local broadcast
  4969. } else if (((rem_ip & ifp->mask) == (ifp->ip & ifp->mask))) {
  4970. // If we're in the same LAN, fire an ARP lookup.
  4971. MG_DEBUG(("%lu ARP lookup...", c->id));
  4972. arp_ask(ifp, rem_ip);
  4973. settmout(c, MIP_TTYPE_ARP);
  4974. c->is_arplooking = 1;
  4975. c->is_connecting = 1;
  4976. } else if ((*((uint8_t *) &rem_ip) & 0xE0) == 0xE0) {
  4977. struct connstate *s = (struct connstate *) (c + 1); // 224 to 239, E0 to EF
  4978. uint8_t mcastp[3] = {0x01, 0x00, 0x5E}; // multicast group
  4979. memcpy(s->mac, mcastp, 3);
  4980. memcpy(s->mac + 3, ((uint8_t *) &rem_ip) + 1, 3); // 23 LSb
  4981. s->mac[3] &= 0x7F;
  4982. } else {
  4983. struct connstate *s = (struct connstate *) (c + 1);
  4984. memcpy(s->mac, ifp->gwmac, sizeof(ifp->gwmac));
  4985. if (c->is_udp) {
  4986. mg_call(c, MG_EV_CONNECT, NULL);
  4987. } else {
  4988. send_syn(c);
  4989. settmout(c, MIP_TTYPE_SYN);
  4990. c->is_connecting = 1;
  4991. }
  4992. }
  4993. }
  4994. bool mg_open_listener(struct mg_connection *c, const char *url) {
  4995. c->loc.port = mg_htons(mg_url_port(url));
  4996. return true;
  4997. }
  4998. static void write_conn(struct mg_connection *c) {
  4999. long len = c->is_tls ? mg_tls_send(c, c->send.buf, c->send.len)
  5000. : mg_io_send(c, c->send.buf, c->send.len);
  5001. if (len == MG_IO_ERR) {
  5002. mg_error(c, "tx err");
  5003. } else if (len > 0) {
  5004. mg_iobuf_del(&c->send, 0, (size_t) len);
  5005. mg_call(c, MG_EV_WRITE, &len);
  5006. }
  5007. }
  5008. static void init_closure(struct mg_connection *c) {
  5009. struct connstate *s = (struct connstate *) (c + 1);
  5010. if (c->is_udp == false && c->is_listening == false &&
  5011. c->is_connecting == false) { // For TCP conns,
  5012. struct mg_tcpip_if *ifp =
  5013. (struct mg_tcpip_if *) c->mgr->priv; // send TCP FIN
  5014. uint32_t rem_ip;
  5015. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5016. tx_tcp(ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port, c->rem.port,
  5017. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5018. settmout(c, MIP_TTYPE_FIN);
  5019. }
  5020. }
  5021. static void close_conn(struct mg_connection *c) {
  5022. struct connstate *s = (struct connstate *) (c + 1);
  5023. mg_iobuf_free(&s->raw); // For TLS connections, release raw data
  5024. mg_close_conn(c);
  5025. }
  5026. static bool can_write(struct mg_connection *c) {
  5027. return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 &&
  5028. c->is_tls_hs == 0 && c->is_arplooking == 0;
  5029. }
  5030. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  5031. struct mg_connection *c, *tmp;
  5032. uint64_t now = mg_millis();
  5033. mg_tcpip_poll((struct mg_tcpip_if *) mgr->priv, now);
  5034. mg_timer_poll(&mgr->timers, now);
  5035. for (c = mgr->conns; c != NULL; c = tmp) {
  5036. tmp = c->next;
  5037. struct connstate *s = (struct connstate *) (c + 1);
  5038. mg_call(c, MG_EV_POLL, &now);
  5039. MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't',
  5040. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  5041. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  5042. if (can_write(c)) write_conn(c);
  5043. if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN)
  5044. init_closure(c);
  5045. if (c->is_closing) close_conn(c);
  5046. }
  5047. (void) ms;
  5048. }
  5049. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  5050. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5051. bool res = false;
  5052. uint32_t rem_ip;
  5053. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5054. if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) {
  5055. mg_error(c, "net down");
  5056. } else if (c->is_udp) {
  5057. struct connstate *s = (struct connstate *) (c + 1);
  5058. len = trim_len(c, len); // Trimming length if necessary
  5059. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len);
  5060. res = true;
  5061. } else {
  5062. res = mg_iobuf_add(&c->send, c->send.len, buf, len);
  5063. }
  5064. return res;
  5065. }
  5066. #endif // MG_ENABLE_TCPIP
  5067. #ifdef MG_ENABLE_LINES
  5068. #line 1 "src/ota_dummy.c"
  5069. #endif
  5070. #if MG_OTA == MG_OTA_NONE
  5071. bool mg_ota_begin(size_t new_firmware_size) {
  5072. (void) new_firmware_size;
  5073. return true;
  5074. }
  5075. bool mg_ota_write(const void *buf, size_t len) {
  5076. (void) buf, (void) len;
  5077. return true;
  5078. }
  5079. bool mg_ota_end(void) {
  5080. return true;
  5081. }
  5082. bool mg_ota_commit(void) {
  5083. return true;
  5084. }
  5085. bool mg_ota_rollback(void) {
  5086. return true;
  5087. }
  5088. int mg_ota_status(int fw) {
  5089. (void) fw;
  5090. return 0;
  5091. }
  5092. uint32_t mg_ota_crc32(int fw) {
  5093. (void) fw;
  5094. return 0;
  5095. }
  5096. uint32_t mg_ota_timestamp(int fw) {
  5097. (void) fw;
  5098. return 0;
  5099. }
  5100. size_t mg_ota_size(int fw) {
  5101. (void) fw;
  5102. return 0;
  5103. }
  5104. MG_IRAM void mg_ota_boot(void) {
  5105. }
  5106. #endif
  5107. #ifdef MG_ENABLE_LINES
  5108. #line 1 "src/ota_flash.c"
  5109. #endif
  5110. // This OTA implementation uses the internal flash API outlined in device.h
  5111. // It splits flash into 2 equal partitions, and stores OTA status in the
  5112. // last sector of the partition.
  5113. #if MG_OTA == MG_OTA_FLASH
  5114. #define MG_OTADATA_KEY 0xb07afed0
  5115. static char *s_addr; // Current address to write to
  5116. static size_t s_size; // Firmware size to flash. In-progress indicator
  5117. static uint32_t s_crc32; // Firmware checksum
  5118. struct mg_otadata {
  5119. uint32_t crc32, size, timestamp, status;
  5120. };
  5121. bool mg_ota_begin(size_t new_firmware_size) {
  5122. bool ok = false;
  5123. if (s_size) {
  5124. MG_ERROR(("OTA already in progress. Call mg_ota_end()"));
  5125. } else {
  5126. size_t half = mg_flash_size() / 2, max = half - mg_flash_sector_size();
  5127. s_crc32 = 0;
  5128. s_addr = (char *) mg_flash_start() + half;
  5129. MG_DEBUG(("Firmware %lu bytes, max %lu", new_firmware_size, max));
  5130. if (new_firmware_size < max) {
  5131. ok = true;
  5132. s_size = new_firmware_size;
  5133. MG_INFO(("Starting OTA, firmware size %lu", s_size));
  5134. } else {
  5135. MG_ERROR(("Firmware %lu is too big to fit %lu", new_firmware_size, max));
  5136. }
  5137. }
  5138. return ok;
  5139. }
  5140. bool mg_ota_write(const void *buf, size_t len) {
  5141. bool ok = false;
  5142. if (s_size == 0) {
  5143. MG_ERROR(("OTA is not started, call mg_ota_begin()"));
  5144. } else {
  5145. size_t align = mg_flash_write_align();
  5146. size_t len_aligned_down = MG_ROUND_DOWN(len, align);
  5147. if (len_aligned_down) ok = mg_flash_write(s_addr, buf, len_aligned_down);
  5148. if (len_aligned_down < len) {
  5149. size_t left = len - len_aligned_down;
  5150. char tmp[align];
  5151. memset(tmp, 0xff, sizeof(tmp));
  5152. memcpy(tmp, (char *) buf + len_aligned_down, left);
  5153. ok = mg_flash_write(s_addr + len_aligned_down, tmp, sizeof(tmp));
  5154. }
  5155. s_crc32 = mg_crc32(s_crc32, (char *) buf, len); // Update CRC
  5156. MG_DEBUG(("%#x %p %lu -> %d", s_addr - len, buf, len, ok));
  5157. s_addr += len;
  5158. }
  5159. return ok;
  5160. }
  5161. MG_IRAM static uint32_t mg_fwkey(int fw) {
  5162. uint32_t key = MG_OTADATA_KEY + fw;
  5163. int bank = mg_flash_bank();
  5164. if (bank == 2 && fw == MG_FIRMWARE_PREVIOUS) key--;
  5165. if (bank == 2 && fw == MG_FIRMWARE_CURRENT) key++;
  5166. return key;
  5167. }
  5168. bool mg_ota_end(void) {
  5169. char *base = (char *) mg_flash_start() + mg_flash_size() / 2;
  5170. bool ok = false;
  5171. if (s_size) {
  5172. size_t size = s_addr - base;
  5173. uint32_t crc32 = mg_crc32(0, base, s_size);
  5174. if (size == s_size && crc32 == s_crc32) {
  5175. uint32_t now = (uint32_t) (mg_now() / 1000);
  5176. struct mg_otadata od = {crc32, size, now, MG_OTA_FIRST_BOOT};
  5177. uint32_t key = mg_fwkey(MG_FIRMWARE_PREVIOUS);
  5178. ok = mg_flash_save(NULL, key, &od, sizeof(od));
  5179. }
  5180. MG_DEBUG(("CRC: %x/%x, size: %lu/%lu, status: %s", s_crc32, crc32, s_size,
  5181. size, ok ? "ok" : "fail"));
  5182. s_size = 0;
  5183. if (ok) ok = mg_flash_swap_bank();
  5184. }
  5185. MG_INFO(("Finishing OTA: %s", ok ? "ok" : "fail"));
  5186. return ok;
  5187. }
  5188. MG_IRAM static struct mg_otadata mg_otadata(int fw) {
  5189. uint32_t key = mg_fwkey(fw);
  5190. struct mg_otadata od = {};
  5191. MG_INFO(("Loading %s OTA data", fw == MG_FIRMWARE_CURRENT ? "curr" : "prev"));
  5192. mg_flash_load(NULL, key, &od, sizeof(od));
  5193. // MG_DEBUG(("Loaded OTA data. fw %d, bank %d, key %p", fw, bank, key));
  5194. // mg_hexdump(&od, sizeof(od));
  5195. return od;
  5196. }
  5197. int mg_ota_status(int fw) {
  5198. struct mg_otadata od = mg_otadata(fw);
  5199. return od.status;
  5200. }
  5201. uint32_t mg_ota_crc32(int fw) {
  5202. struct mg_otadata od = mg_otadata(fw);
  5203. return od.crc32;
  5204. }
  5205. uint32_t mg_ota_timestamp(int fw) {
  5206. struct mg_otadata od = mg_otadata(fw);
  5207. return od.timestamp;
  5208. }
  5209. size_t mg_ota_size(int fw) {
  5210. struct mg_otadata od = mg_otadata(fw);
  5211. return od.size;
  5212. }
  5213. MG_IRAM bool mg_ota_commit(void) {
  5214. bool ok = true;
  5215. struct mg_otadata od = mg_otadata(MG_FIRMWARE_CURRENT);
  5216. if (od.status != MG_OTA_COMMITTED) {
  5217. od.status = MG_OTA_COMMITTED;
  5218. MG_INFO(("Committing current firmware, OD size %lu", sizeof(od)));
  5219. ok = mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &od, sizeof(od));
  5220. }
  5221. return ok;
  5222. }
  5223. bool mg_ota_rollback(void) {
  5224. MG_DEBUG(("Rolling firmware back"));
  5225. if (mg_flash_bank() == 0) {
  5226. // No dual bank support. Mark previous firmware as FIRST_BOOT
  5227. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5228. prev.status = MG_OTA_FIRST_BOOT;
  5229. return mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &prev,
  5230. sizeof(prev));
  5231. } else {
  5232. return mg_flash_swap_bank();
  5233. }
  5234. }
  5235. MG_IRAM void mg_ota_boot(void) {
  5236. MG_INFO(("Booting. Flash bank: %d", mg_flash_bank()));
  5237. struct mg_otadata curr = mg_otadata(MG_FIRMWARE_CURRENT);
  5238. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5239. if (curr.status == MG_OTA_FIRST_BOOT) {
  5240. if (prev.status == MG_OTA_UNAVAILABLE) {
  5241. MG_INFO(("Setting previous firmware state to committed"));
  5242. prev.status = MG_OTA_COMMITTED;
  5243. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_PREVIOUS), &prev, sizeof(prev));
  5244. }
  5245. curr.status = MG_OTA_UNCOMMITTED;
  5246. MG_INFO(("First boot, setting status to UNCOMMITTED"));
  5247. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &curr, sizeof(curr));
  5248. } else if (prev.status == MG_OTA_FIRST_BOOT && mg_flash_bank() == 0) {
  5249. // Swap paritions. Pray power does not disappear
  5250. size_t fs = mg_flash_size(), ss = mg_flash_sector_size();
  5251. char *partition1 = mg_flash_start();
  5252. char *partition2 = mg_flash_start() + fs / 2;
  5253. size_t ofs, max = fs / 2 - ss; // Set swap size to the whole partition
  5254. if (curr.status != MG_OTA_UNAVAILABLE &&
  5255. prev.status != MG_OTA_UNAVAILABLE) {
  5256. // We know exact sizes of both firmwares.
  5257. // Shrink swap size to the MAX(firmware1, firmware2)
  5258. size_t sz = curr.size > prev.size ? curr.size : prev.size;
  5259. if (sz > 0 && sz < max) max = sz;
  5260. }
  5261. // MG_OTA_FIRST_BOOT -> MG_OTA_UNCOMMITTED
  5262. prev.status = MG_OTA_UNCOMMITTED;
  5263. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_CURRENT, &prev,
  5264. sizeof(prev));
  5265. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &curr,
  5266. sizeof(curr));
  5267. MG_INFO(("Swapping partitions, size %u (%u sectors)", max, max / ss));
  5268. MG_INFO(("Do NOT power off..."));
  5269. mg_log_level = MG_LL_NONE;
  5270. // We use the last sector of partition2 for OTA data/config storage
  5271. // Therefore we can use last sector of partition1 for swapping
  5272. char *tmpsector = partition1 + fs / 2 - ss; // Last sector of partition1
  5273. (void) tmpsector;
  5274. for (ofs = 0; ofs < max; ofs += ss) {
  5275. // mg_flash_erase(tmpsector);
  5276. mg_flash_write(tmpsector, partition1 + ofs, ss);
  5277. // mg_flash_erase(partition1 + ofs);
  5278. mg_flash_write(partition1 + ofs, partition2 + ofs, ss);
  5279. // mg_flash_erase(partition2 + ofs);
  5280. mg_flash_write(partition2 + ofs, tmpsector, ss);
  5281. }
  5282. mg_device_reset();
  5283. }
  5284. }
  5285. #endif
  5286. #ifdef MG_ENABLE_LINES
  5287. #line 1 "src/printf.c"
  5288. #endif
  5289. size_t mg_queue_vprintf(struct mg_queue *q, const char *fmt, va_list *ap) {
  5290. size_t len = mg_snprintf(NULL, 0, fmt, ap);
  5291. char *buf;
  5292. if (len == 0 || mg_queue_book(q, &buf, len + 1) < len + 1) {
  5293. len = 0; // Nah. Not enough space
  5294. } else {
  5295. len = mg_vsnprintf((char *) buf, len + 1, fmt, ap);
  5296. mg_queue_add(q, len);
  5297. }
  5298. return len;
  5299. }
  5300. size_t mg_queue_printf(struct mg_queue *q, const char *fmt, ...) {
  5301. va_list ap;
  5302. size_t len;
  5303. va_start(ap, fmt);
  5304. len = mg_queue_vprintf(q, fmt, &ap);
  5305. va_end(ap);
  5306. return len;
  5307. }
  5308. static void mg_pfn_iobuf_private(char ch, void *param, bool expand) {
  5309. struct mg_iobuf *io = (struct mg_iobuf *) param;
  5310. if (expand && io->len + 2 > io->size) mg_iobuf_resize(io, io->len + 2);
  5311. if (io->len + 2 <= io->size) {
  5312. io->buf[io->len++] = (uint8_t) ch;
  5313. io->buf[io->len] = 0;
  5314. } else if (io->len < io->size) {
  5315. io->buf[io->len++] = 0; // Guarantee to 0-terminate
  5316. }
  5317. }
  5318. static void mg_putchar_iobuf_static(char ch, void *param) {
  5319. mg_pfn_iobuf_private(ch, param, false);
  5320. }
  5321. void mg_pfn_iobuf(char ch, void *param) {
  5322. mg_pfn_iobuf_private(ch, param, true);
  5323. }
  5324. size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap) {
  5325. struct mg_iobuf io = {(uint8_t *) buf, len, 0, 0};
  5326. size_t n = mg_vxprintf(mg_putchar_iobuf_static, &io, fmt, ap);
  5327. if (n < len) buf[n] = '\0';
  5328. return n;
  5329. }
  5330. size_t mg_snprintf(char *buf, size_t len, const char *fmt, ...) {
  5331. va_list ap;
  5332. size_t n;
  5333. va_start(ap, fmt);
  5334. n = mg_vsnprintf(buf, len, fmt, &ap);
  5335. va_end(ap);
  5336. return n;
  5337. }
  5338. char *mg_vmprintf(const char *fmt, va_list *ap) {
  5339. struct mg_iobuf io = {0, 0, 0, 256};
  5340. mg_vxprintf(mg_pfn_iobuf, &io, fmt, ap);
  5341. return (char *) io.buf;
  5342. }
  5343. char *mg_mprintf(const char *fmt, ...) {
  5344. char *s;
  5345. va_list ap;
  5346. va_start(ap, fmt);
  5347. s = mg_vmprintf(fmt, &ap);
  5348. va_end(ap);
  5349. return s;
  5350. }
  5351. void mg_pfn_stdout(char c, void *param) {
  5352. putchar(c);
  5353. (void) param;
  5354. }
  5355. static size_t print_ip4(void (*out)(char, void *), void *arg, uint8_t *p) {
  5356. return mg_xprintf(out, arg, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  5357. }
  5358. static size_t print_ip6(void (*out)(char, void *), void *arg, uint16_t *p) {
  5359. return mg_xprintf(out, arg, "[%x:%x:%x:%x:%x:%x:%x:%x]", mg_ntohs(p[0]),
  5360. mg_ntohs(p[1]), mg_ntohs(p[2]), mg_ntohs(p[3]),
  5361. mg_ntohs(p[4]), mg_ntohs(p[5]), mg_ntohs(p[6]),
  5362. mg_ntohs(p[7]));
  5363. }
  5364. size_t mg_print_ip4(void (*out)(char, void *), void *arg, va_list *ap) {
  5365. uint8_t *p = va_arg(*ap, uint8_t *);
  5366. return print_ip4(out, arg, p);
  5367. }
  5368. size_t mg_print_ip6(void (*out)(char, void *), void *arg, va_list *ap) {
  5369. uint16_t *p = va_arg(*ap, uint16_t *);
  5370. return print_ip6(out, arg, p);
  5371. }
  5372. size_t mg_print_ip(void (*out)(char, void *), void *arg, va_list *ap) {
  5373. struct mg_addr *addr = va_arg(*ap, struct mg_addr *);
  5374. if (addr->is_ip6) return print_ip6(out, arg, (uint16_t *) addr->ip);
  5375. return print_ip4(out, arg, (uint8_t *) &addr->ip);
  5376. }
  5377. size_t mg_print_ip_port(void (*out)(char, void *), void *arg, va_list *ap) {
  5378. struct mg_addr *a = va_arg(*ap, struct mg_addr *);
  5379. return mg_xprintf(out, arg, "%M:%hu", mg_print_ip, a, mg_ntohs(a->port));
  5380. }
  5381. size_t mg_print_mac(void (*out)(char, void *), void *arg, va_list *ap) {
  5382. uint8_t *p = va_arg(*ap, uint8_t *);
  5383. return mg_xprintf(out, arg, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2],
  5384. p[3], p[4], p[5]);
  5385. }
  5386. static char mg_esc(int c, bool esc) {
  5387. const char *p, *esc1 = "\b\f\n\r\t\\\"", *esc2 = "bfnrt\\\"";
  5388. for (p = esc ? esc1 : esc2; *p != '\0'; p++) {
  5389. if (*p == c) return esc ? esc2[p - esc1] : esc1[p - esc2];
  5390. }
  5391. return 0;
  5392. }
  5393. static char mg_escape(int c) {
  5394. return mg_esc(c, true);
  5395. }
  5396. static size_t qcpy(void (*out)(char, void *), void *ptr, char *buf,
  5397. size_t len) {
  5398. size_t i = 0, extra = 0;
  5399. for (i = 0; i < len && buf[i] != '\0'; i++) {
  5400. char c = mg_escape(buf[i]);
  5401. if (c) {
  5402. out('\\', ptr), out(c, ptr), extra++;
  5403. } else {
  5404. out(buf[i], ptr);
  5405. }
  5406. }
  5407. return i + extra;
  5408. }
  5409. static size_t bcpy(void (*out)(char, void *), void *arg, uint8_t *buf,
  5410. size_t len) {
  5411. size_t i, j, n = 0;
  5412. const char *t =
  5413. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5414. for (i = 0; i < len; i += 3) {
  5415. uint8_t c1 = buf[i], c2 = i + 1 < len ? buf[i + 1] : 0,
  5416. c3 = i + 2 < len ? buf[i + 2] : 0;
  5417. char tmp[4] = {t[c1 >> 2], t[(c1 & 3) << 4 | (c2 >> 4)], '=', '='};
  5418. if (i + 1 < len) tmp[2] = t[(c2 & 15) << 2 | (c3 >> 6)];
  5419. if (i + 2 < len) tmp[3] = t[c3 & 63];
  5420. for (j = 0; j < sizeof(tmp) && tmp[j] != '\0'; j++) out(tmp[j], arg);
  5421. n += j;
  5422. }
  5423. return n;
  5424. }
  5425. size_t mg_print_hex(void (*out)(char, void *), void *arg, va_list *ap) {
  5426. size_t bl = (size_t) va_arg(*ap, int);
  5427. uint8_t *p = va_arg(*ap, uint8_t *);
  5428. const char *hex = "0123456789abcdef";
  5429. size_t j;
  5430. for (j = 0; j < bl; j++) {
  5431. out(hex[(p[j] >> 4) & 0x0F], arg);
  5432. out(hex[p[j] & 0x0F], arg);
  5433. }
  5434. return 2 * bl;
  5435. }
  5436. size_t mg_print_base64(void (*out)(char, void *), void *arg, va_list *ap) {
  5437. size_t len = (size_t) va_arg(*ap, int);
  5438. uint8_t *buf = va_arg(*ap, uint8_t *);
  5439. return bcpy(out, arg, buf, len);
  5440. }
  5441. size_t mg_print_esc(void (*out)(char, void *), void *arg, va_list *ap) {
  5442. size_t len = (size_t) va_arg(*ap, int);
  5443. char *p = va_arg(*ap, char *);
  5444. if (len == 0) len = p == NULL ? 0 : strlen(p);
  5445. return qcpy(out, arg, p, len);
  5446. }
  5447. #ifdef MG_ENABLE_LINES
  5448. #line 1 "src/queue.c"
  5449. #endif
  5450. #if (defined(__GNUC__) && (__GNUC__ > 4) || \
  5451. (defined(__GNUC_MINOR__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
  5452. defined(__clang__)
  5453. #define MG_MEMORY_BARRIER() __sync_synchronize()
  5454. #elif defined(_MSC_VER) && _MSC_VER >= 1700
  5455. #define MG_MEMORY_BARRIER() MemoryBarrier()
  5456. #elif !defined(MG_MEMORY_BARRIER)
  5457. #define MG_MEMORY_BARRIER()
  5458. #endif
  5459. // Every message in a queue is prepended by a 32-bit message length (ML).
  5460. // If ML is 0, then it is the end, and reader must wrap to the beginning.
  5461. //
  5462. // Queue when q->tail <= q->head:
  5463. // |----- free -----| ML | message1 | ML | message2 | ----- free ------|
  5464. // ^ ^ ^ ^
  5465. // buf tail head len
  5466. //
  5467. // Queue when q->tail > q->head:
  5468. // | ML | message2 |----- free ------| ML | message1 | 0 |---- free ----|
  5469. // ^ ^ ^ ^
  5470. // buf head tail len
  5471. void mg_queue_init(struct mg_queue *q, char *buf, size_t size) {
  5472. q->size = size;
  5473. q->buf = buf;
  5474. q->head = q->tail = 0;
  5475. }
  5476. static size_t mg_queue_read_len(struct mg_queue *q) {
  5477. uint32_t n = 0;
  5478. MG_MEMORY_BARRIER();
  5479. memcpy(&n, q->buf + q->tail, sizeof(n));
  5480. assert(q->tail + n + sizeof(n) <= q->size);
  5481. return n;
  5482. }
  5483. static void mg_queue_write_len(struct mg_queue *q, size_t len) {
  5484. uint32_t n = (uint32_t) len;
  5485. memcpy(q->buf + q->head, &n, sizeof(n));
  5486. MG_MEMORY_BARRIER();
  5487. }
  5488. size_t mg_queue_book(struct mg_queue *q, char **buf, size_t len) {
  5489. size_t space = 0, hs = sizeof(uint32_t) * 2; // *2 is for the 0 marker
  5490. if (q->head >= q->tail && q->head + len + hs <= q->size) {
  5491. space = q->size - q->head - hs; // There is enough space
  5492. } else if (q->head >= q->tail && q->tail > hs) {
  5493. mg_queue_write_len(q, 0); // Not enough space ahead
  5494. q->head = 0; // Wrap head to the beginning
  5495. }
  5496. if (q->head + hs + len < q->tail) space = q->tail - q->head - hs;
  5497. if (buf != NULL) *buf = q->buf + q->head + sizeof(uint32_t);
  5498. return space;
  5499. }
  5500. size_t mg_queue_next(struct mg_queue *q, char **buf) {
  5501. size_t len = 0;
  5502. if (q->tail != q->head) {
  5503. len = mg_queue_read_len(q);
  5504. if (len == 0) { // Zero (head wrapped) ?
  5505. q->tail = 0; // Reset tail to the start
  5506. if (q->head > q->tail) len = mg_queue_read_len(q); // Read again
  5507. }
  5508. }
  5509. if (buf != NULL) *buf = q->buf + q->tail + sizeof(uint32_t);
  5510. assert(q->tail + len <= q->size);
  5511. return len;
  5512. }
  5513. void mg_queue_add(struct mg_queue *q, size_t len) {
  5514. assert(len > 0);
  5515. mg_queue_write_len(q, len);
  5516. assert(q->head + sizeof(uint32_t) * 2 + len <= q->size);
  5517. q->head += len + sizeof(uint32_t);
  5518. }
  5519. void mg_queue_del(struct mg_queue *q, size_t len) {
  5520. q->tail += len + sizeof(uint32_t);
  5521. assert(q->tail + sizeof(uint32_t) <= q->size);
  5522. }
  5523. #ifdef MG_ENABLE_LINES
  5524. #line 1 "src/rpc.c"
  5525. #endif
  5526. void mg_rpc_add(struct mg_rpc **head, struct mg_str method,
  5527. void (*fn)(struct mg_rpc_req *), void *fn_data) {
  5528. struct mg_rpc *rpc = (struct mg_rpc *) calloc(1, sizeof(*rpc));
  5529. if (rpc != NULL) {
  5530. rpc->method = mg_strdup(method), rpc->fn = fn, rpc->fn_data = fn_data;
  5531. rpc->next = *head, *head = rpc;
  5532. }
  5533. }
  5534. void mg_rpc_del(struct mg_rpc **head, void (*fn)(struct mg_rpc_req *)) {
  5535. struct mg_rpc *r;
  5536. while ((r = *head) != NULL) {
  5537. if (r->fn == fn || fn == NULL) {
  5538. *head = r->next;
  5539. free((void *) r->method.ptr);
  5540. free(r);
  5541. } else {
  5542. head = &(*head)->next;
  5543. }
  5544. }
  5545. }
  5546. static void mg_rpc_call(struct mg_rpc_req *r, struct mg_str method) {
  5547. struct mg_rpc *h = r->head == NULL ? NULL : *r->head;
  5548. while (h != NULL && !mg_match(method, h->method, NULL)) h = h->next;
  5549. if (h != NULL) {
  5550. r->rpc = h;
  5551. h->fn(r);
  5552. } else {
  5553. mg_rpc_err(r, -32601, "\"%.*s not found\"", (int) method.len, method.ptr);
  5554. }
  5555. }
  5556. void mg_rpc_process(struct mg_rpc_req *r) {
  5557. int len, off = mg_json_get(r->frame, "$.method", &len);
  5558. if (off > 0 && r->frame.ptr[off] == '"') {
  5559. struct mg_str method = mg_str_n(&r->frame.ptr[off + 1], (size_t) len - 2);
  5560. mg_rpc_call(r, method);
  5561. } else if ((off = mg_json_get(r->frame, "$.result", &len)) > 0 ||
  5562. (off = mg_json_get(r->frame, "$.error", &len)) > 0) {
  5563. mg_rpc_call(r, mg_str("")); // JSON response! call "" method handler
  5564. } else {
  5565. mg_rpc_err(r, -32700, "%m", mg_print_esc, (int) r->frame.len,
  5566. r->frame.ptr); // Invalid
  5567. }
  5568. }
  5569. void mg_rpc_vok(struct mg_rpc_req *r, const char *fmt, va_list *ap) {
  5570. int len, off = mg_json_get(r->frame, "$.id", &len);
  5571. if (off > 0) {
  5572. mg_xprintf(r->pfn, r->pfn_data, "{%m:%.*s,%m:", mg_print_esc, 0, "id", len,
  5573. &r->frame.ptr[off], mg_print_esc, 0, "result");
  5574. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  5575. mg_xprintf(r->pfn, r->pfn_data, "}");
  5576. }
  5577. }
  5578. void mg_rpc_ok(struct mg_rpc_req *r, const char *fmt, ...) {
  5579. va_list ap;
  5580. va_start(ap, fmt);
  5581. mg_rpc_vok(r, fmt, &ap);
  5582. va_end(ap);
  5583. }
  5584. void mg_rpc_verr(struct mg_rpc_req *r, int code, const char *fmt, va_list *ap) {
  5585. int len, off = mg_json_get(r->frame, "$.id", &len);
  5586. mg_xprintf(r->pfn, r->pfn_data, "{");
  5587. if (off > 0) {
  5588. mg_xprintf(r->pfn, r->pfn_data, "%m:%.*s,", mg_print_esc, 0, "id", len,
  5589. &r->frame.ptr[off]);
  5590. }
  5591. mg_xprintf(r->pfn, r->pfn_data, "%m:{%m:%d,%m:", mg_print_esc, 0, "error",
  5592. mg_print_esc, 0, "code", code, mg_print_esc, 0, "message");
  5593. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  5594. mg_xprintf(r->pfn, r->pfn_data, "}}");
  5595. }
  5596. void mg_rpc_err(struct mg_rpc_req *r, int code, const char *fmt, ...) {
  5597. va_list ap;
  5598. va_start(ap, fmt);
  5599. mg_rpc_verr(r, code, fmt, &ap);
  5600. va_end(ap);
  5601. }
  5602. static size_t print_methods(mg_pfn_t pfn, void *pfn_data, va_list *ap) {
  5603. struct mg_rpc *h, **head = (struct mg_rpc **) va_arg(*ap, void **);
  5604. size_t len = 0;
  5605. for (h = *head; h != NULL; h = h->next) {
  5606. if (h->method.len == 0) continue; // Ignore response handler
  5607. len += mg_xprintf(pfn, pfn_data, "%s%m", h == *head ? "" : ",",
  5608. mg_print_esc, (int) h->method.len, h->method.ptr);
  5609. }
  5610. return len;
  5611. }
  5612. void mg_rpc_list(struct mg_rpc_req *r) {
  5613. mg_rpc_ok(r, "[%M]", print_methods, r->head);
  5614. }
  5615. #ifdef MG_ENABLE_LINES
  5616. #line 1 "src/sha1.c"
  5617. #endif
  5618. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  5619. /* 100% Public Domain */
  5620. union char64long16 {
  5621. unsigned char c[64];
  5622. uint32_t l[16];
  5623. };
  5624. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  5625. static uint32_t blk0(union char64long16 *block, int i) {
  5626. if (MG_BIG_ENDIAN) {
  5627. } else {
  5628. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  5629. (rol(block->l[i], 8) & 0x00FF00FF);
  5630. }
  5631. return block->l[i];
  5632. }
  5633. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  5634. #undef blk
  5635. #undef R0
  5636. #undef R1
  5637. #undef R2
  5638. #undef R3
  5639. #undef R4
  5640. #define blk(i) \
  5641. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  5642. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  5643. 1))
  5644. #define R0(v, w, x, y, z, i) \
  5645. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  5646. w = rol(w, 30);
  5647. #define R1(v, w, x, y, z, i) \
  5648. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  5649. w = rol(w, 30);
  5650. #define R2(v, w, x, y, z, i) \
  5651. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  5652. w = rol(w, 30);
  5653. #define R3(v, w, x, y, z, i) \
  5654. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  5655. w = rol(w, 30);
  5656. #define R4(v, w, x, y, z, i) \
  5657. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  5658. w = rol(w, 30);
  5659. static void mg_sha1_transform(uint32_t state[5],
  5660. const unsigned char *buffer) {
  5661. uint32_t a, b, c, d, e;
  5662. union char64long16 block[1];
  5663. memcpy(block, buffer, 64);
  5664. a = state[0];
  5665. b = state[1];
  5666. c = state[2];
  5667. d = state[3];
  5668. e = state[4];
  5669. R0(a, b, c, d, e, 0);
  5670. R0(e, a, b, c, d, 1);
  5671. R0(d, e, a, b, c, 2);
  5672. R0(c, d, e, a, b, 3);
  5673. R0(b, c, d, e, a, 4);
  5674. R0(a, b, c, d, e, 5);
  5675. R0(e, a, b, c, d, 6);
  5676. R0(d, e, a, b, c, 7);
  5677. R0(c, d, e, a, b, 8);
  5678. R0(b, c, d, e, a, 9);
  5679. R0(a, b, c, d, e, 10);
  5680. R0(e, a, b, c, d, 11);
  5681. R0(d, e, a, b, c, 12);
  5682. R0(c, d, e, a, b, 13);
  5683. R0(b, c, d, e, a, 14);
  5684. R0(a, b, c, d, e, 15);
  5685. R1(e, a, b, c, d, 16);
  5686. R1(d, e, a, b, c, 17);
  5687. R1(c, d, e, a, b, 18);
  5688. R1(b, c, d, e, a, 19);
  5689. R2(a, b, c, d, e, 20);
  5690. R2(e, a, b, c, d, 21);
  5691. R2(d, e, a, b, c, 22);
  5692. R2(c, d, e, a, b, 23);
  5693. R2(b, c, d, e, a, 24);
  5694. R2(a, b, c, d, e, 25);
  5695. R2(e, a, b, c, d, 26);
  5696. R2(d, e, a, b, c, 27);
  5697. R2(c, d, e, a, b, 28);
  5698. R2(b, c, d, e, a, 29);
  5699. R2(a, b, c, d, e, 30);
  5700. R2(e, a, b, c, d, 31);
  5701. R2(d, e, a, b, c, 32);
  5702. R2(c, d, e, a, b, 33);
  5703. R2(b, c, d, e, a, 34);
  5704. R2(a, b, c, d, e, 35);
  5705. R2(e, a, b, c, d, 36);
  5706. R2(d, e, a, b, c, 37);
  5707. R2(c, d, e, a, b, 38);
  5708. R2(b, c, d, e, a, 39);
  5709. R3(a, b, c, d, e, 40);
  5710. R3(e, a, b, c, d, 41);
  5711. R3(d, e, a, b, c, 42);
  5712. R3(c, d, e, a, b, 43);
  5713. R3(b, c, d, e, a, 44);
  5714. R3(a, b, c, d, e, 45);
  5715. R3(e, a, b, c, d, 46);
  5716. R3(d, e, a, b, c, 47);
  5717. R3(c, d, e, a, b, 48);
  5718. R3(b, c, d, e, a, 49);
  5719. R3(a, b, c, d, e, 50);
  5720. R3(e, a, b, c, d, 51);
  5721. R3(d, e, a, b, c, 52);
  5722. R3(c, d, e, a, b, 53);
  5723. R3(b, c, d, e, a, 54);
  5724. R3(a, b, c, d, e, 55);
  5725. R3(e, a, b, c, d, 56);
  5726. R3(d, e, a, b, c, 57);
  5727. R3(c, d, e, a, b, 58);
  5728. R3(b, c, d, e, a, 59);
  5729. R4(a, b, c, d, e, 60);
  5730. R4(e, a, b, c, d, 61);
  5731. R4(d, e, a, b, c, 62);
  5732. R4(c, d, e, a, b, 63);
  5733. R4(b, c, d, e, a, 64);
  5734. R4(a, b, c, d, e, 65);
  5735. R4(e, a, b, c, d, 66);
  5736. R4(d, e, a, b, c, 67);
  5737. R4(c, d, e, a, b, 68);
  5738. R4(b, c, d, e, a, 69);
  5739. R4(a, b, c, d, e, 70);
  5740. R4(e, a, b, c, d, 71);
  5741. R4(d, e, a, b, c, 72);
  5742. R4(c, d, e, a, b, 73);
  5743. R4(b, c, d, e, a, 74);
  5744. R4(a, b, c, d, e, 75);
  5745. R4(e, a, b, c, d, 76);
  5746. R4(d, e, a, b, c, 77);
  5747. R4(c, d, e, a, b, 78);
  5748. R4(b, c, d, e, a, 79);
  5749. state[0] += a;
  5750. state[1] += b;
  5751. state[2] += c;
  5752. state[3] += d;
  5753. state[4] += e;
  5754. /* Erase working structures. The order of operations is important,
  5755. * used to ensure that compiler doesn't optimize those out. */
  5756. memset(block, 0, sizeof(block));
  5757. a = b = c = d = e = 0;
  5758. (void) a;
  5759. (void) b;
  5760. (void) c;
  5761. (void) d;
  5762. (void) e;
  5763. }
  5764. void mg_sha1_init(mg_sha1_ctx *context) {
  5765. context->state[0] = 0x67452301;
  5766. context->state[1] = 0xEFCDAB89;
  5767. context->state[2] = 0x98BADCFE;
  5768. context->state[3] = 0x10325476;
  5769. context->state[4] = 0xC3D2E1F0;
  5770. context->count[0] = context->count[1] = 0;
  5771. }
  5772. void mg_sha1_update(mg_sha1_ctx *context, const unsigned char *data,
  5773. size_t len) {
  5774. size_t i, j;
  5775. j = context->count[0];
  5776. if ((context->count[0] += (uint32_t) len << 3) < j) context->count[1]++;
  5777. context->count[1] += (uint32_t) (len >> 29);
  5778. j = (j >> 3) & 63;
  5779. if ((j + len) > 63) {
  5780. memcpy(&context->buffer[j], data, (i = 64 - j));
  5781. mg_sha1_transform(context->state, context->buffer);
  5782. for (; i + 63 < len; i += 64) {
  5783. mg_sha1_transform(context->state, &data[i]);
  5784. }
  5785. j = 0;
  5786. } else
  5787. i = 0;
  5788. memcpy(&context->buffer[j], &data[i], len - i);
  5789. }
  5790. void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *context) {
  5791. unsigned i;
  5792. unsigned char finalcount[8], c;
  5793. for (i = 0; i < 8; i++) {
  5794. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  5795. ((3 - (i & 3)) * 8)) &
  5796. 255);
  5797. }
  5798. c = 0200;
  5799. mg_sha1_update(context, &c, 1);
  5800. while ((context->count[0] & 504) != 448) {
  5801. c = 0000;
  5802. mg_sha1_update(context, &c, 1);
  5803. }
  5804. mg_sha1_update(context, finalcount, 8);
  5805. for (i = 0; i < 20; i++) {
  5806. digest[i] =
  5807. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  5808. }
  5809. memset(context, '\0', sizeof(*context));
  5810. memset(&finalcount, '\0', sizeof(finalcount));
  5811. }
  5812. #ifdef MG_ENABLE_LINES
  5813. #line 1 "src/sha256.c"
  5814. #endif
  5815. #define ror(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
  5816. #define ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
  5817. #define maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
  5818. #define ep0(x) (ror(x, 2) ^ ror(x, 13) ^ ror(x, 22))
  5819. #define ep1(x) (ror(x, 6) ^ ror(x, 11) ^ ror(x, 25))
  5820. #define sig0(x) (ror(x, 7) ^ ror(x, 18) ^ ((x) >> 3))
  5821. #define sig1(x) (ror(x, 17) ^ ror(x, 19) ^ ((x) >> 10))
  5822. static const uint32_t mg_sha256_k[64] = {
  5823. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
  5824. 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  5825. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
  5826. 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  5827. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
  5828. 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  5829. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
  5830. 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  5831. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
  5832. 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  5833. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
  5834. void mg_sha256_init(mg_sha256_ctx *ctx) {
  5835. ctx->len = 0;
  5836. ctx->bits = 0;
  5837. ctx->state[0] = 0x6a09e667;
  5838. ctx->state[1] = 0xbb67ae85;
  5839. ctx->state[2] = 0x3c6ef372;
  5840. ctx->state[3] = 0xa54ff53a;
  5841. ctx->state[4] = 0x510e527f;
  5842. ctx->state[5] = 0x9b05688c;
  5843. ctx->state[6] = 0x1f83d9ab;
  5844. ctx->state[7] = 0x5be0cd19;
  5845. }
  5846. static void mg_sha256_chunk(mg_sha256_ctx *ctx) {
  5847. int i, j;
  5848. uint32_t a, b, c, d, e, f, g, h;
  5849. uint32_t m[64];
  5850. for (i = 0, j = 0; i < 16; ++i, j += 4)
  5851. m[i] = (uint32_t) ((ctx->buffer[j] << 24) | (ctx->buffer[j + 1] << 16) |
  5852. (ctx->buffer[j + 2] << 8) | (ctx->buffer[j + 3]));
  5853. for (; i < 64; ++i)
  5854. m[i] = sig1(m[i - 2]) + m[i - 7] + sig0(m[i - 15]) + m[i - 16];
  5855. a = ctx->state[0];
  5856. b = ctx->state[1];
  5857. c = ctx->state[2];
  5858. d = ctx->state[3];
  5859. e = ctx->state[4];
  5860. f = ctx->state[5];
  5861. g = ctx->state[6];
  5862. h = ctx->state[7];
  5863. for (i = 0; i < 64; ++i) {
  5864. uint32_t t1 = h + ep1(e) + ch(e, f, g) + mg_sha256_k[i] + m[i];
  5865. uint32_t t2 = ep0(a) + maj(a, b, c);
  5866. h = g;
  5867. g = f;
  5868. f = e;
  5869. e = d + t1;
  5870. d = c;
  5871. c = b;
  5872. b = a;
  5873. a = t1 + t2;
  5874. }
  5875. ctx->state[0] += a;
  5876. ctx->state[1] += b;
  5877. ctx->state[2] += c;
  5878. ctx->state[3] += d;
  5879. ctx->state[4] += e;
  5880. ctx->state[5] += f;
  5881. ctx->state[6] += g;
  5882. ctx->state[7] += h;
  5883. }
  5884. void mg_sha256_update(mg_sha256_ctx *ctx, const unsigned char *data,
  5885. size_t len) {
  5886. size_t i;
  5887. for (i = 0; i < len; i++) {
  5888. ctx->buffer[ctx->len] = data[i];
  5889. if ((++ctx->len) == 64) {
  5890. mg_sha256_chunk(ctx);
  5891. ctx->bits += 512;
  5892. ctx->len = 0;
  5893. }
  5894. }
  5895. }
  5896. // TODO: make final reusable (remove side effects)
  5897. void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *ctx) {
  5898. uint32_t i = ctx->len;
  5899. if (i < 56) {
  5900. ctx->buffer[i++] = 0x80;
  5901. while (i < 56) {
  5902. ctx->buffer[i++] = 0x00;
  5903. }
  5904. } else {
  5905. ctx->buffer[i++] = 0x80;
  5906. while (i < 64) {
  5907. ctx->buffer[i++] = 0x00;
  5908. }
  5909. mg_sha256_chunk(ctx);
  5910. memset(ctx->buffer, 0, 56);
  5911. }
  5912. ctx->bits += ctx->len * 8;
  5913. ctx->buffer[63] = (uint8_t) ((ctx->bits) & 0xff);
  5914. ctx->buffer[62] = (uint8_t) ((ctx->bits >> 8) & 0xff);
  5915. ctx->buffer[61] = (uint8_t) ((ctx->bits >> 16) & 0xff);
  5916. ctx->buffer[60] = (uint8_t) ((ctx->bits >> 24) & 0xff);
  5917. ctx->buffer[59] = (uint8_t) ((ctx->bits >> 32) & 0xff);
  5918. ctx->buffer[58] = (uint8_t) ((ctx->bits >> 40) & 0xff);
  5919. ctx->buffer[57] = (uint8_t) ((ctx->bits >> 48) & 0xff);
  5920. ctx->buffer[56] = (uint8_t) ((ctx->bits >> 56) & 0xff);
  5921. mg_sha256_chunk(ctx);
  5922. for (i = 0; i < 4; ++i) {
  5923. digest[i] = (ctx->state[0] >> (24 - i * 8)) & 0xff;
  5924. digest[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0xff;
  5925. digest[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0xff;
  5926. digest[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0xff;
  5927. digest[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0xff;
  5928. digest[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0xff;
  5929. digest[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0xff;
  5930. digest[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0xff;
  5931. }
  5932. }
  5933. void mg_hmac_sha256(uint8_t dst[32], uint8_t *key, size_t keysz, uint8_t *data,
  5934. size_t datasz) {
  5935. mg_sha256_ctx ctx;
  5936. uint8_t k[64] = {0};
  5937. uint8_t o_pad[64], i_pad[64];
  5938. unsigned int i;
  5939. memset(i_pad, 0x36, sizeof(i_pad));
  5940. memset(o_pad, 0x5c, sizeof(o_pad));
  5941. if (keysz < 64) {
  5942. memmove(k, key, keysz);
  5943. } else {
  5944. mg_sha256_init(&ctx);
  5945. mg_sha256_update(&ctx, key, keysz);
  5946. mg_sha256_final(k, &ctx);
  5947. }
  5948. for (i = 0; i < sizeof(k); i++) {
  5949. i_pad[i] ^= k[i];
  5950. o_pad[i] ^= k[i];
  5951. }
  5952. mg_sha256_init(&ctx);
  5953. mg_sha256_update(&ctx, i_pad, sizeof(i_pad));
  5954. mg_sha256_update(&ctx, data, datasz);
  5955. mg_sha256_final(dst, &ctx);
  5956. mg_sha256_init(&ctx);
  5957. mg_sha256_update(&ctx, o_pad, sizeof(o_pad));
  5958. mg_sha256_update(&ctx, dst, 32);
  5959. mg_sha256_final(dst, &ctx);
  5960. }
  5961. #ifdef MG_ENABLE_LINES
  5962. #line 1 "src/sntp.c"
  5963. #endif
  5964. #define SNTP_TIME_OFFSET 2208988800U // (1970 - 1900) in seconds
  5965. #define SNTP_MAX_FRAC 4294967295.0 // 2 ** 32 - 1
  5966. static int64_t gettimestamp(const uint32_t *data) {
  5967. uint32_t sec = mg_ntohl(data[0]), frac = mg_ntohl(data[1]);
  5968. if (sec) sec -= SNTP_TIME_OFFSET;
  5969. return ((int64_t) sec) * 1000 + (int64_t) (frac / SNTP_MAX_FRAC * 1000.0);
  5970. }
  5971. int64_t mg_sntp_parse(const unsigned char *buf, size_t len) {
  5972. int64_t res = -1;
  5973. int mode = len > 0 ? buf[0] & 7 : 0;
  5974. int version = len > 0 ? (buf[0] >> 3) & 7 : 0;
  5975. if (len < 48) {
  5976. MG_ERROR(("%s", "corrupt packet"));
  5977. } else if (mode != 4 && mode != 5) {
  5978. MG_ERROR(("%s", "not a server reply"));
  5979. } else if (buf[1] == 0) {
  5980. MG_ERROR(("%s", "server sent a kiss of death"));
  5981. } else if (version == 4 || version == 3) {
  5982. // int64_t ref = gettimestamp((uint32_t *) &buf[16]);
  5983. int64_t t0 = gettimestamp((uint32_t *) &buf[24]);
  5984. int64_t t1 = gettimestamp((uint32_t *) &buf[32]);
  5985. int64_t t2 = gettimestamp((uint32_t *) &buf[40]);
  5986. int64_t t3 = (int64_t) mg_millis();
  5987. int64_t delta = (t3 - t0) - (t2 - t1);
  5988. MG_VERBOSE(("%lld %lld %lld %lld delta:%lld", t0, t1, t2, t3, delta));
  5989. res = t2 + delta / 2;
  5990. } else {
  5991. MG_ERROR(("unexpected version: %d", version));
  5992. }
  5993. return res;
  5994. }
  5995. static void sntp_cb(struct mg_connection *c, int ev, void *ev_data) {
  5996. if (ev == MG_EV_READ) {
  5997. int64_t milliseconds = mg_sntp_parse(c->recv.buf, c->recv.len);
  5998. if (milliseconds > 0) {
  5999. MG_INFO(("%lu got time: %lld ms from epoch", c->id, milliseconds));
  6000. mg_call(c, MG_EV_SNTP_TIME, (uint64_t *) &milliseconds);
  6001. MG_VERBOSE(("%u.%u", (unsigned) (milliseconds / 1000),
  6002. (unsigned) (milliseconds % 1000)));
  6003. }
  6004. mg_iobuf_del(&c->recv, 0, c->recv.len); // Free receive buffer
  6005. } else if (ev == MG_EV_CONNECT) {
  6006. mg_sntp_request(c);
  6007. } else if (ev == MG_EV_CLOSE) {
  6008. }
  6009. (void) ev_data;
  6010. }
  6011. void mg_sntp_request(struct mg_connection *c) {
  6012. if (c->is_resolving) {
  6013. MG_ERROR(("%lu wait until resolved", c->id));
  6014. } else {
  6015. int64_t now = (int64_t) mg_millis(); // Use int64_t, for vc98
  6016. uint8_t buf[48] = {0};
  6017. uint32_t *t = (uint32_t *) &buf[40];
  6018. double frac = ((double) (now % 1000)) / 1000.0 * SNTP_MAX_FRAC;
  6019. buf[0] = (0 << 6) | (4 << 3) | 3;
  6020. t[0] = mg_htonl((uint32_t) (now / 1000) + SNTP_TIME_OFFSET);
  6021. t[1] = mg_htonl((uint32_t) frac);
  6022. mg_send(c, buf, sizeof(buf));
  6023. }
  6024. }
  6025. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url,
  6026. mg_event_handler_t fn, void *fnd) {
  6027. struct mg_connection *c = NULL;
  6028. if (url == NULL) url = "udp://time.google.com:123";
  6029. if ((c = mg_connect(mgr, url, fn, fnd)) != NULL) c->pfn = sntp_cb;
  6030. return c;
  6031. }
  6032. #ifdef MG_ENABLE_LINES
  6033. #line 1 "src/sock.c"
  6034. #endif
  6035. #if MG_ENABLE_SOCKET
  6036. #ifndef closesocket
  6037. #define closesocket(x) close(x)
  6038. #endif
  6039. #define FD(c_) ((MG_SOCKET_TYPE) (size_t) (c_)->fd)
  6040. #define S2PTR(s_) ((void *) (size_t) (s_))
  6041. #ifndef MSG_NONBLOCKING
  6042. #define MSG_NONBLOCKING 0
  6043. #endif
  6044. #ifndef AF_INET6
  6045. #define AF_INET6 10
  6046. #endif
  6047. #ifndef MG_SOCK_ERR
  6048. #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? errno : 0)
  6049. #endif
  6050. #ifndef MG_SOCK_INTR
  6051. #define MG_SOCK_INTR(fd) (fd == MG_INVALID_SOCKET && MG_SOCK_ERR(-1) == EINTR)
  6052. #endif
  6053. #ifndef MG_SOCK_PENDING
  6054. #define MG_SOCK_PENDING(errcode) \
  6055. (((errcode) < 0) && (errno == EINPROGRESS || errno == EWOULDBLOCK))
  6056. #endif
  6057. #ifndef MG_SOCK_RESET
  6058. #define MG_SOCK_RESET(errcode) \
  6059. (((errcode) < 0) && (errno == EPIPE || errno == ECONNRESET))
  6060. #endif
  6061. union usa {
  6062. struct sockaddr sa;
  6063. struct sockaddr_in sin;
  6064. #if MG_ENABLE_IPV6
  6065. struct sockaddr_in6 sin6;
  6066. #endif
  6067. };
  6068. static socklen_t tousa(struct mg_addr *a, union usa *usa) {
  6069. socklen_t len = sizeof(usa->sin);
  6070. memset(usa, 0, sizeof(*usa));
  6071. usa->sin.sin_family = AF_INET;
  6072. usa->sin.sin_port = a->port;
  6073. memcpy(&usa->sin.sin_addr, a->ip, sizeof(uint32_t));
  6074. #if MG_ENABLE_IPV6
  6075. if (a->is_ip6) {
  6076. usa->sin.sin_family = AF_INET6;
  6077. usa->sin6.sin6_port = a->port;
  6078. usa->sin6.sin6_scope_id = a->scope_id;
  6079. memcpy(&usa->sin6.sin6_addr, a->ip, sizeof(a->ip));
  6080. len = sizeof(usa->sin6);
  6081. }
  6082. #endif
  6083. return len;
  6084. }
  6085. static void tomgaddr(union usa *usa, struct mg_addr *a, bool is_ip6) {
  6086. a->is_ip6 = is_ip6;
  6087. a->port = usa->sin.sin_port;
  6088. memcpy(&a->ip, &usa->sin.sin_addr, sizeof(uint32_t));
  6089. #if MG_ENABLE_IPV6
  6090. if (is_ip6) {
  6091. memcpy(a->ip, &usa->sin6.sin6_addr, sizeof(a->ip));
  6092. a->port = usa->sin6.sin6_port;
  6093. a->scope_id = (uint8_t) usa->sin6.sin6_scope_id;
  6094. }
  6095. #endif
  6096. }
  6097. static void setlocaddr(MG_SOCKET_TYPE fd, struct mg_addr *addr) {
  6098. union usa usa;
  6099. socklen_t n = sizeof(usa);
  6100. if (getsockname(fd, &usa.sa, &n) == 0) {
  6101. tomgaddr(&usa, addr, n != sizeof(usa.sin));
  6102. }
  6103. }
  6104. static void iolog(struct mg_connection *c, char *buf, long n, bool r) {
  6105. if (n == MG_IO_WAIT) {
  6106. // Do nothing
  6107. } else if (n <= 0) {
  6108. c->is_closing = 1; // Termination. Don't call mg_error(): #1529
  6109. } else if (n > 0) {
  6110. if (c->is_hexdumping) {
  6111. union usa usa;
  6112. socklen_t slen = sizeof(usa.sin);
  6113. if (getsockname(FD(c), &usa.sa, &slen) < 0) (void) 0; // Ignore result
  6114. MG_INFO(("\n-- %lu %M %s %M %ld", c->id, mg_print_ip_port, &c->loc,
  6115. r ? "<-" : "->", mg_print_ip_port, &c->rem, n));
  6116. mg_hexdump(buf, (size_t) n);
  6117. }
  6118. if (r) {
  6119. c->recv.len += (size_t) n;
  6120. mg_call(c, MG_EV_READ, &n);
  6121. } else {
  6122. mg_iobuf_del(&c->send, 0, (size_t) n);
  6123. // if (c->send.len == 0) mg_iobuf_resize(&c->send, 0);
  6124. if (c->send.len == 0) {
  6125. MG_EPOLL_MOD(c, 0);
  6126. }
  6127. mg_call(c, MG_EV_WRITE, &n);
  6128. }
  6129. }
  6130. }
  6131. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  6132. long n;
  6133. if (c->is_udp) {
  6134. union usa usa;
  6135. socklen_t slen = tousa(&c->rem, &usa);
  6136. n = sendto(FD(c), (char *) buf, len, 0, &usa.sa, slen);
  6137. if (n > 0) setlocaddr(FD(c), &c->loc);
  6138. } else {
  6139. n = send(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6140. }
  6141. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6142. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6143. if (n <= 0) return MG_IO_ERR;
  6144. return n;
  6145. }
  6146. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  6147. if (c->is_udp) {
  6148. long n = mg_io_send(c, buf, len);
  6149. MG_DEBUG(("%lu %ld %d:%d %ld err %d", c->id, c->fd, (int) c->send.len,
  6150. (int) c->recv.len, n, MG_SOCK_ERR(n)));
  6151. iolog(c, (char *) buf, n, false);
  6152. return n > 0;
  6153. } else {
  6154. return mg_iobuf_add(&c->send, c->send.len, buf, len);
  6155. }
  6156. }
  6157. static void mg_set_non_blocking_mode(MG_SOCKET_TYPE fd) {
  6158. #if defined(MG_CUSTOM_NONBLOCK)
  6159. MG_CUSTOM_NONBLOCK(fd);
  6160. #elif MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  6161. unsigned long on = 1;
  6162. ioctlsocket(fd, FIONBIO, &on);
  6163. #elif MG_ENABLE_RL
  6164. unsigned long on = 1;
  6165. ioctlsocket(fd, FIONBIO, &on);
  6166. #elif MG_ENABLE_FREERTOS_TCP
  6167. const BaseType_t off = 0;
  6168. if (setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6169. if (setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6170. #elif MG_ENABLE_LWIP
  6171. lwip_fcntl(fd, F_SETFL, O_NONBLOCK);
  6172. #elif MG_ARCH == MG_ARCH_AZURERTOS
  6173. fcntl(fd, F_SETFL, O_NONBLOCK);
  6174. #elif MG_ARCH == MG_ARCH_TIRTOS
  6175. int val = 0;
  6176. setsockopt(fd, SOL_SOCKET, SO_BLOCKING, &val, sizeof(val));
  6177. // SPRU524J section 3.3.3 page 63, SO_SNDLOWAT
  6178. int sz = sizeof(val);
  6179. getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &val, &sz);
  6180. val /= 2; // set send low-water mark at half send buffer size
  6181. setsockopt(fd, SOL_SOCKET, SO_SNDLOWAT, &val, sizeof(val));
  6182. #else
  6183. fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); // Non-blocking mode
  6184. fcntl(fd, F_SETFD, FD_CLOEXEC); // Set close-on-exec
  6185. #endif
  6186. }
  6187. bool mg_open_listener(struct mg_connection *c, const char *url) {
  6188. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6189. bool success = false;
  6190. c->loc.port = mg_htons(mg_url_port(url));
  6191. if (!mg_aton(mg_url_host(url), &c->loc)) {
  6192. MG_ERROR(("invalid listening URL: %s", url));
  6193. } else {
  6194. union usa usa;
  6195. socklen_t slen = tousa(&c->loc, &usa);
  6196. int rc, on = 1, af = c->loc.is_ip6 ? AF_INET6 : AF_INET;
  6197. int type = strncmp(url, "udp:", 4) == 0 ? SOCK_DGRAM : SOCK_STREAM;
  6198. int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP;
  6199. (void) on;
  6200. if ((fd = socket(af, type, proto)) == MG_INVALID_SOCKET) {
  6201. MG_ERROR(("socket: %d", MG_SOCK_ERR(-1)));
  6202. #if defined(SO_EXCLUSIVEADDRUSE)
  6203. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  6204. (char *) &on, sizeof(on))) != 0) {
  6205. // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE"
  6206. MG_ERROR(("setsockopt(SO_EXCLUSIVEADDRUSE): %d %d", on, MG_SOCK_ERR(rc)));
  6207. #elif defined(SO_REUSEADDR) && (!defined(LWIP_SOCKET) || SO_REUSE)
  6208. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on,
  6209. sizeof(on))) != 0) {
  6210. // 1. SO_REUSEADDR semantics on UNIX and Windows is different. On
  6211. // Windows, SO_REUSEADDR allows to bind a socket to a port without error
  6212. // even if the port is already open by another program. This is not the
  6213. // behavior SO_REUSEADDR was designed for, and leads to hard-to-track
  6214. // failure scenarios.
  6215. //
  6216. // 2. For LWIP, SO_REUSEADDR should be explicitly enabled by defining
  6217. // SO_REUSE = 1 in lwipopts.h, otherwise the code below will compile but
  6218. // won't work! (setsockopt will return EINVAL)
  6219. MG_ERROR(("setsockopt(SO_REUSEADDR): %d", MG_SOCK_ERR(rc)));
  6220. #endif
  6221. #if MG_IPV6_V6ONLY
  6222. // Bind only to the V6 address, not V4 address on this port
  6223. } else if (c->loc.is_ip6 &&
  6224. (rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &on,
  6225. sizeof(on))) != 0) {
  6226. // See #2089. Allow to bind v4 and v6 sockets on the same port
  6227. MG_ERROR(("setsockopt(IPV6_V6ONLY): %d", MG_SOCK_ERR(rc)));
  6228. #endif
  6229. } else if ((rc = bind(fd, &usa.sa, slen)) != 0) {
  6230. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6231. } else if ((type == SOCK_STREAM &&
  6232. (rc = listen(fd, MG_SOCK_LISTEN_BACKLOG_SIZE)) != 0)) {
  6233. // NOTE(lsm): FreeRTOS uses backlog value as a connection limit
  6234. // In case port was set to 0, get the real port number
  6235. MG_ERROR(("listen: %d", MG_SOCK_ERR(rc)));
  6236. } else {
  6237. setlocaddr(fd, &c->loc);
  6238. mg_set_non_blocking_mode(fd);
  6239. c->fd = S2PTR(fd);
  6240. MG_EPOLL_ADD(c);
  6241. success = true;
  6242. }
  6243. }
  6244. if (success == false && fd != MG_INVALID_SOCKET) closesocket(fd);
  6245. return success;
  6246. }
  6247. static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
  6248. long n = 0;
  6249. if (c->is_udp) {
  6250. union usa usa;
  6251. socklen_t slen = tousa(&c->rem, &usa);
  6252. n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
  6253. if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
  6254. } else {
  6255. n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6256. }
  6257. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6258. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6259. if (n <= 0) return MG_IO_ERR;
  6260. return n;
  6261. }
  6262. static bool ioalloc(struct mg_connection *c, struct mg_iobuf *io) {
  6263. bool res = false;
  6264. if (io->len >= MG_MAX_RECV_SIZE) {
  6265. mg_error(c, "MG_MAX_RECV_SIZE");
  6266. } else if (io->size <= io->len &&
  6267. !mg_iobuf_resize(io, io->size + MG_IO_SIZE)) {
  6268. mg_error(c, "OOM");
  6269. } else {
  6270. res = true;
  6271. }
  6272. return res;
  6273. }
  6274. // NOTE(lsm): do only one iteration of reads, cause some systems
  6275. // (e.g. FreeRTOS stack) return 0 instead of -1/EWOULDBLOCK when no data
  6276. static void read_conn(struct mg_connection *c) {
  6277. if (ioalloc(c, &c->recv)) {
  6278. char *buf = (char *) &c->recv.buf[c->recv.len];
  6279. size_t len = c->recv.size - c->recv.len;
  6280. long n = -1;
  6281. if (c->is_tls) {
  6282. if (!ioalloc(c, &c->rtls)) return;
  6283. n = recv_raw(c, (char *) &c->rtls.buf[c->rtls.len],
  6284. c->rtls.size - c->rtls.len);
  6285. // MG_DEBUG(("%lu %ld", c->id, n));
  6286. if (n == MG_IO_ERR) {
  6287. c->is_closing = 1;
  6288. } else if (n > 0) {
  6289. c->rtls.len += (size_t) n;
  6290. if (c->is_tls_hs) mg_tls_handshake(c);
  6291. if (c->is_tls_hs) return;
  6292. n = mg_tls_recv(c, buf, len);
  6293. } else if (n == MG_IO_WAIT) {
  6294. n = mg_tls_recv(c, buf, len);
  6295. }
  6296. } else {
  6297. n = recv_raw(c, buf, len);
  6298. }
  6299. MG_DEBUG(("%lu %p snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6300. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6301. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6302. iolog(c, buf, n, true);
  6303. }
  6304. }
  6305. static void write_conn(struct mg_connection *c) {
  6306. #if MG_ARCH == MG_ARCH_UNIX
  6307. pthread_mutex_lock(&WSlock);
  6308. #endif
  6309. char *buf = (char *) c->send.buf;
  6310. size_t len = c->send.len;
  6311. long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len);
  6312. MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6313. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6314. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6315. iolog(c, buf, n, false);
  6316. #if MG_ARCH == MG_ARCH_UNIX
  6317. pthread_mutex_unlock(&WSlock);
  6318. #endif
  6319. }
  6320. static void close_conn(struct mg_connection *c) {
  6321. #if MG_ARCH == MG_ARCH_UNIX
  6322. pthread_mutex_lock(&WSlock);
  6323. #endif
  6324. if (FD(c) != MG_INVALID_SOCKET) {
  6325. #if MG_ENABLE_EPOLL
  6326. epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_DEL, FD(c), NULL);
  6327. #endif
  6328. closesocket(FD(c));
  6329. #if MG_ENABLE_FREERTOS_TCP
  6330. FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL);
  6331. #endif
  6332. }
  6333. mg_close_conn(c);
  6334. #if MG_ARCH == MG_ARCH_UNIX
  6335. pthread_mutex_unlock(&WSlock);
  6336. #endif
  6337. }
  6338. static void connect_conn(struct mg_connection *c) {
  6339. union usa usa;
  6340. socklen_t n = sizeof(usa);
  6341. // Use getpeername() to test whether we have connected
  6342. if (getpeername(FD(c), &usa.sa, &n) == 0) {
  6343. c->is_connecting = 0;
  6344. mg_call(c, MG_EV_CONNECT, NULL);
  6345. MG_EPOLL_MOD(c, 0);
  6346. if (c->is_tls_hs) mg_tls_handshake(c);
  6347. } else {
  6348. mg_error(c, "socket error");
  6349. }
  6350. }
  6351. static void setsockopts(struct mg_connection *c) {
  6352. #if MG_ENABLE_FREERTOS_TCP || MG_ARCH == MG_ARCH_AZURERTOS || \
  6353. MG_ARCH == MG_ARCH_TIRTOS
  6354. (void) c;
  6355. #else
  6356. int on = 1;
  6357. #if !defined(SOL_TCP)
  6358. #define SOL_TCP IPPROTO_TCP
  6359. #endif
  6360. if (setsockopt(FD(c), SOL_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) != 0)
  6361. (void) 0;
  6362. if (setsockopt(FD(c), SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) !=
  6363. 0)
  6364. (void) 0;
  6365. #endif
  6366. }
  6367. void mg_connect_resolved(struct mg_connection *c) {
  6368. int type = c->is_udp ? SOCK_DGRAM : SOCK_STREAM;
  6369. int rc, af = c->rem.is_ip6 ? AF_INET6 : AF_INET; // c->rem has resolved IP
  6370. c->fd = S2PTR(socket(af, type, 0)); // Create outbound socket
  6371. c->is_resolving = 0; // Clear resolving flag
  6372. if (FD(c) == MG_INVALID_SOCKET) {
  6373. mg_error(c, "socket(): %d", MG_SOCK_ERR(-1));
  6374. } else if (c->is_udp) {
  6375. MG_EPOLL_ADD(c);
  6376. #if MG_ARCH == MG_ARCH_TIRTOS
  6377. union usa usa; // TI-RTOS NDK requires binding to receive on UDP sockets
  6378. socklen_t slen = tousa(&c->loc, &usa);
  6379. if ((rc = bind(c->fd, &usa.sa, slen)) != 0)
  6380. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6381. #endif
  6382. mg_call(c, MG_EV_RESOLVE, NULL);
  6383. mg_call(c, MG_EV_CONNECT, NULL);
  6384. } else {
  6385. union usa usa;
  6386. socklen_t slen = tousa(&c->rem, &usa);
  6387. mg_set_non_blocking_mode(FD(c));
  6388. setsockopts(c);
  6389. MG_EPOLL_ADD(c);
  6390. mg_call(c, MG_EV_RESOLVE, NULL);
  6391. rc = connect(FD(c), &usa.sa, slen); // Attempt to connect
  6392. if (rc == 0) { // Success
  6393. mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user
  6394. } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake
  6395. MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem));
  6396. c->is_connecting = 1;
  6397. } else {
  6398. mg_error(c, "connect: %d", MG_SOCK_ERR(rc));
  6399. }
  6400. }
  6401. }
  6402. static MG_SOCKET_TYPE raccept(MG_SOCKET_TYPE sock, union usa *usa,
  6403. socklen_t *len) {
  6404. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6405. do {
  6406. memset(usa, 0, sizeof(*usa));
  6407. fd = accept(sock, &usa->sa, len);
  6408. } while (MG_SOCK_INTR(fd));
  6409. return fd;
  6410. }
  6411. static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) {
  6412. #if MG_ARCH == MG_ARCH_UNIX
  6413. pthread_mutex_lock(&WSlock);
  6414. #endif
  6415. struct mg_connection *c = NULL;
  6416. union usa usa;
  6417. socklen_t sa_len = sizeof(usa);
  6418. MG_SOCKET_TYPE fd = raccept(FD(lsn), &usa, &sa_len);
  6419. if (fd == MG_INVALID_SOCKET) {
  6420. #if MG_ARCH == MG_ARCH_AZURERTOS || defined(__ECOS)
  6421. // AzureRTOS, in non-block socket mode can mark listening socket readable
  6422. // even it is not. See comment for 'select' func implementation in
  6423. // nx_bsd.c That's not an error, just should try later
  6424. if (errno != EAGAIN)
  6425. #endif
  6426. MG_ERROR(("%lu accept failed, errno %d", lsn->id, MG_SOCK_ERR(-1)));
  6427. #if (MG_ARCH != MG_ARCH_WIN32) && !MG_ENABLE_FREERTOS_TCP && \
  6428. (MG_ARCH != MG_ARCH_TIRTOS) && !MG_ENABLE_POLL && !MG_ENABLE_EPOLL
  6429. } else if ((long) fd >= FD_SETSIZE) {
  6430. MG_ERROR(("%ld > %ld", (long) fd, (long) FD_SETSIZE));
  6431. closesocket(fd);
  6432. #endif
  6433. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  6434. MG_ERROR(("%lu OOM", lsn->id));
  6435. closesocket(fd);
  6436. } else {
  6437. tomgaddr(&usa, &c->rem, sa_len != sizeof(usa.sin));
  6438. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  6439. c->fd = S2PTR(fd);
  6440. MG_EPOLL_ADD(c);
  6441. mg_set_non_blocking_mode(FD(c));
  6442. setsockopts(c);
  6443. c->is_accepted = 1;
  6444. c->is_hexdumping = lsn->is_hexdumping;
  6445. c->loc = lsn->loc;
  6446. c->pfn = lsn->pfn;
  6447. c->pfn_data = lsn->pfn_data;
  6448. c->fn = lsn->fn;
  6449. c->fn_data = lsn->fn_data;
  6450. MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port,
  6451. &c->rem, mg_print_ip_port, &c->loc));
  6452. mg_call(c, MG_EV_OPEN, NULL);
  6453. mg_call(c, MG_EV_ACCEPT, NULL);
  6454. }
  6455. #if MG_ARCH == MG_ARCH_UNIX
  6456. pthread_mutex_unlock(&WSlock);
  6457. #endif
  6458. }
  6459. static bool can_read(const struct mg_connection *c) {
  6460. return c->is_full == false;
  6461. }
  6462. static bool can_write(const struct mg_connection *c) {
  6463. return c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0);
  6464. }
  6465. static bool skip_iotest(const struct mg_connection *c) {
  6466. return (c->is_closing || c->is_resolving || FD(c) == MG_INVALID_SOCKET) ||
  6467. (can_read(c) == false && can_write(c) == false);
  6468. }
  6469. static void mg_iotest(struct mg_mgr *mgr, int ms) {
  6470. #if MG_ENABLE_FREERTOS_TCP
  6471. struct mg_connection *c;
  6472. for (c = mgr->conns; c != NULL; c = c->next) {
  6473. c->is_readable = c->is_writable = 0;
  6474. if (skip_iotest(c)) continue;
  6475. if (can_read(c))
  6476. FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_READ | eSELECT_EXCEPT);
  6477. if (can_write(c)) FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_WRITE);
  6478. if (c->is_closing) ms = 1;
  6479. }
  6480. FreeRTOS_select(mgr->ss, pdMS_TO_TICKS(ms));
  6481. for (c = mgr->conns; c != NULL; c = c->next) {
  6482. EventBits_t bits = FreeRTOS_FD_ISSET(c->fd, mgr->ss);
  6483. c->is_readable = bits & (eSELECT_READ | eSELECT_EXCEPT) ? 1U : 0;
  6484. c->is_writable = bits & eSELECT_WRITE ? 1U : 0;
  6485. if (c->fd != MG_INVALID_SOCKET)
  6486. FreeRTOS_FD_CLR(c->fd, mgr->ss,
  6487. eSELECT_READ | eSELECT_EXCEPT | eSELECT_WRITE);
  6488. }
  6489. #elif MG_ENABLE_EPOLL
  6490. size_t max = 1;
  6491. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6492. c->is_readable = c->is_writable = 0;
  6493. if (mg_tls_pending(c) > 0) ms = 1, c->is_readable = 1;
  6494. if (can_write(c)) MG_EPOLL_MOD(c, 1);
  6495. if (c->is_closing) ms = 1;
  6496. max++;
  6497. }
  6498. struct epoll_event *evs = (struct epoll_event *) alloca(max * sizeof(evs[0]));
  6499. int n = epoll_wait(mgr->epoll_fd, evs, (int) max, ms);
  6500. for (int i = 0; i < n; i++) {
  6501. struct mg_connection *c = (struct mg_connection *) evs[i].data.ptr;
  6502. if (evs[i].events & EPOLLERR) {
  6503. mg_error(c, "socket error");
  6504. } else if (c->is_readable == 0) {
  6505. bool rd = evs[i].events & (EPOLLIN | EPOLLHUP);
  6506. bool wr = evs[i].events & EPOLLOUT;
  6507. c->is_readable = can_read(c) && rd ? 1U : 0;
  6508. c->is_writable = can_write(c) && wr ? 1U : 0;
  6509. }
  6510. }
  6511. (void) skip_iotest;
  6512. #elif MG_ENABLE_POLL
  6513. nfds_t n = 0;
  6514. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) n++;
  6515. struct pollfd *fds = (struct pollfd *) alloca(n * sizeof(fds[0]));
  6516. memset(fds, 0, n * sizeof(fds[0]));
  6517. n = 0;
  6518. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6519. c->is_readable = c->is_writable = 0;
  6520. if (skip_iotest(c)) {
  6521. // Socket not valid, ignore
  6522. } else if (mg_tls_pending(c) > 0) {
  6523. ms = 1; // Don't wait if TLS is ready
  6524. } else {
  6525. fds[n].fd = FD(c);
  6526. if (can_read(c)) fds[n].events |= POLLIN;
  6527. if (can_write(c)) fds[n].events |= POLLOUT;
  6528. if (c->is_closing) ms = 1;
  6529. n++;
  6530. }
  6531. }
  6532. // MG_INFO(("poll n=%d ms=%d", (int) n, ms));
  6533. if (poll(fds, n, ms) < 0) {
  6534. #if MG_ARCH == MG_ARCH_WIN32
  6535. if (n == 0) Sleep(ms); // On Windows, poll fails if no sockets
  6536. #endif
  6537. memset(fds, 0, n * sizeof(fds[0]));
  6538. }
  6539. n = 0;
  6540. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6541. if (skip_iotest(c)) {
  6542. // Socket not valid, ignore
  6543. } else if (mg_tls_pending(c) > 0) {
  6544. c->is_readable = 1;
  6545. } else {
  6546. if (fds[n].revents & POLLERR) {
  6547. mg_error(c, "socket error");
  6548. } else {
  6549. c->is_readable =
  6550. (unsigned) (fds[n].revents & (POLLIN | POLLHUP) ? 1 : 0);
  6551. c->is_writable = (unsigned) (fds[n].revents & POLLOUT ? 1 : 0);
  6552. }
  6553. n++;
  6554. }
  6555. }
  6556. #else
  6557. struct timeval tv = {ms / 1000, (ms % 1000) * 1000}, tv_zero = {0, 0}, *tvp;
  6558. struct mg_connection *c;
  6559. fd_set rset, wset, eset;
  6560. MG_SOCKET_TYPE maxfd = 0;
  6561. int rc;
  6562. FD_ZERO(&rset);
  6563. FD_ZERO(&wset);
  6564. FD_ZERO(&eset);
  6565. tvp = ms < 0 ? NULL : &tv;
  6566. for (c = mgr->conns; c != NULL; c = c->next) {
  6567. c->is_readable = c->is_writable = 0;
  6568. if (skip_iotest(c)) continue;
  6569. FD_SET(FD(c), &eset);
  6570. if (can_read(c)) FD_SET(FD(c), &rset);
  6571. if (can_write(c)) FD_SET(FD(c), &wset);
  6572. if (mg_tls_pending(c) > 0) tvp = &tv_zero;
  6573. if (FD(c) > maxfd) maxfd = FD(c);
  6574. if (c->is_closing) ms = 1;
  6575. }
  6576. if ((rc = select((int) maxfd + 1, &rset, &wset, &eset, tvp)) < 0) {
  6577. #if MG_ARCH == MG_ARCH_WIN32
  6578. if (maxfd == 0) Sleep(ms); // On Windows, select fails if no sockets
  6579. #else
  6580. MG_ERROR(("select: %d %d", rc, MG_SOCK_ERR(rc)));
  6581. #endif
  6582. FD_ZERO(&rset);
  6583. FD_ZERO(&wset);
  6584. FD_ZERO(&eset);
  6585. }
  6586. for (c = mgr->conns; c != NULL; c = c->next) {
  6587. if (FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &eset)) {
  6588. mg_error(c, "socket error");
  6589. } else {
  6590. c->is_readable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &rset);
  6591. c->is_writable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &wset);
  6592. if (mg_tls_pending(c) > 0) c->is_readable = 1;
  6593. }
  6594. }
  6595. #endif
  6596. }
  6597. static bool mg_socketpair(MG_SOCKET_TYPE sp[2], union usa usa[2]) {
  6598. socklen_t n = sizeof(usa[0].sin);
  6599. bool success = false;
  6600. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6601. (void) memset(&usa[0], 0, sizeof(usa[0]));
  6602. usa[0].sin.sin_family = AF_INET;
  6603. *(uint32_t *) &usa->sin.sin_addr = mg_htonl(0x7f000001U); // 127.0.0.1
  6604. usa[1] = usa[0];
  6605. if ((sp[0] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  6606. (sp[1] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  6607. bind(sp[0], &usa[0].sa, n) == 0 && //
  6608. bind(sp[1], &usa[1].sa, n) == 0 && //
  6609. getsockname(sp[0], &usa[0].sa, &n) == 0 && //
  6610. getsockname(sp[1], &usa[1].sa, &n) == 0 && //
  6611. connect(sp[0], &usa[1].sa, n) == 0 && //
  6612. connect(sp[1], &usa[0].sa, n) == 0) { //
  6613. success = true;
  6614. }
  6615. if (!success) {
  6616. if (sp[0] != MG_INVALID_SOCKET) closesocket(sp[0]);
  6617. if (sp[1] != MG_INVALID_SOCKET) closesocket(sp[1]);
  6618. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6619. }
  6620. return success;
  6621. }
  6622. // mg_wakeup() event handler
  6623. static void wufn(struct mg_connection *c, int ev, void *ev_data) {
  6624. if (ev == MG_EV_READ) {
  6625. unsigned long *id = (unsigned long *) c->recv.buf;
  6626. // MG_INFO(("Got data"));
  6627. // mg_hexdump(c->recv.buf, c->recv.len);
  6628. if (c->recv.len >= sizeof(*id)) {
  6629. struct mg_connection *t;
  6630. for (t = c->mgr->conns; t != NULL; t = t->next) {
  6631. if (t->id == *id) {
  6632. struct mg_str data = mg_str_n((char *) c->recv.buf + sizeof(*id),
  6633. c->recv.len - sizeof(*id));
  6634. mg_call(t, MG_EV_WAKEUP, &data);
  6635. }
  6636. }
  6637. }
  6638. c->recv.len = 0; // Consume received data
  6639. } else if (ev == MG_EV_CLOSE) {
  6640. closesocket(c->mgr->pipe); // When we're closing, close the other
  6641. c->mgr->pipe = MG_INVALID_SOCKET; // side of the socketpair, too
  6642. }
  6643. (void) ev_data;
  6644. }
  6645. bool mg_wakeup_init(struct mg_mgr *mgr) {
  6646. bool ok = false;
  6647. if (mgr->pipe == MG_INVALID_SOCKET) {
  6648. union usa usa[2];
  6649. MG_SOCKET_TYPE sp[2] = {MG_INVALID_SOCKET, MG_INVALID_SOCKET};
  6650. struct mg_connection *c = NULL;
  6651. if (!mg_socketpair(sp, usa)) {
  6652. MG_ERROR(("Cannot create socket pair"));
  6653. } else if ((c = mg_wrapfd(mgr, (int) sp[1], wufn, NULL)) == NULL) {
  6654. closesocket(sp[0]);
  6655. closesocket(sp[1]);
  6656. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6657. } else {
  6658. tomgaddr(&usa[0], &c->rem, false);
  6659. MG_DEBUG(("%lu %p pipe %lu", c->id, c->fd, (unsigned long) sp[0]));
  6660. mgr->pipe = sp[0];
  6661. ok = true;
  6662. }
  6663. }
  6664. return ok;
  6665. }
  6666. bool mg_wakeup(struct mg_mgr *mgr, unsigned long conn_id, const void *buf,
  6667. size_t len) {
  6668. if (mgr->pipe != MG_INVALID_SOCKET && conn_id > 0) {
  6669. char *extended_buf = (char *) alloca(len + sizeof(conn_id));
  6670. memcpy(extended_buf, &conn_id, sizeof(conn_id));
  6671. memcpy(extended_buf + sizeof(conn_id), buf, len);
  6672. send(mgr->pipe, extended_buf, len + sizeof(conn_id), MSG_NONBLOCKING);
  6673. return true;
  6674. }
  6675. return false;
  6676. }
  6677. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  6678. struct mg_connection *c, *tmp;
  6679. uint64_t now;
  6680. mg_iotest(mgr, ms);
  6681. now = mg_millis();
  6682. mg_timer_poll(&mgr->timers, now);
  6683. for (c = mgr->conns; c != NULL; c = tmp) {
  6684. bool is_resp = c->is_resp;
  6685. tmp = c->next;
  6686. mg_call(c, MG_EV_POLL, &now);
  6687. if (is_resp && !c->is_resp) {
  6688. long n = 0;
  6689. mg_call(c, MG_EV_READ, &n);
  6690. }
  6691. MG_VERBOSE(("%lu %c%c %c%c%c%c%c", c->id, c->is_readable ? 'r' : '-',
  6692. c->is_writable ? 'w' : '-', c->is_tls ? 'T' : 't',
  6693. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  6694. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  6695. if (c->is_resolving || c->is_closing) {
  6696. // Do nothing
  6697. } else if (c->is_listening && c->is_udp == 0) {
  6698. if (c->is_readable) accept_conn(mgr, c);
  6699. } else if (c->is_connecting) {
  6700. if (c->is_readable || c->is_writable) connect_conn(c);
  6701. //} else if (c->is_tls_hs) {
  6702. // if ((c->is_readable || c->is_writable)) mg_tls_handshake(c);
  6703. } else {
  6704. if (c->is_readable) read_conn(c);
  6705. if (c->is_writable) write_conn(c);
  6706. }
  6707. if (c->is_draining && c->send.len == 0) c->is_closing = 1;
  6708. if (c->is_closing) close_conn(c);
  6709. }
  6710. }
  6711. #endif
  6712. #ifdef MG_ENABLE_LINES
  6713. #line 1 "src/ssi.c"
  6714. #endif
  6715. #ifndef MG_MAX_SSI_DEPTH
  6716. #define MG_MAX_SSI_DEPTH 5
  6717. #endif
  6718. #ifndef MG_SSI_BUFSIZ
  6719. #define MG_SSI_BUFSIZ 1024
  6720. #endif
  6721. #if MG_ENABLE_SSI
  6722. static char *mg_ssi(const char *path, const char *root, int depth) {
  6723. struct mg_iobuf b = {NULL, 0, 0, MG_IO_SIZE};
  6724. FILE *fp = fopen(path, "rb");
  6725. if (fp != NULL) {
  6726. char buf[MG_SSI_BUFSIZ], arg[sizeof(buf)];
  6727. int ch, intag = 0;
  6728. size_t len = 0;
  6729. buf[0] = arg[0] = '\0';
  6730. while ((ch = fgetc(fp)) != EOF) {
  6731. if (intag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  6732. buf[len++] = (char) (ch & 0xff);
  6733. buf[len] = '\0';
  6734. if (sscanf(buf, "<!--#include file=\"%[^\"]", arg)) {
  6735. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10],
  6736. *p = (char *) path + strlen(path), *data;
  6737. while (p > path && p[-1] != MG_DIRSEP && p[-1] != '/') p--;
  6738. mg_snprintf(tmp, sizeof(tmp), "%.*s%s", (int) (p - path), path, arg);
  6739. if (depth < MG_MAX_SSI_DEPTH &&
  6740. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  6741. mg_iobuf_add(&b, b.len, data, strlen(data));
  6742. free(data);
  6743. } else {
  6744. MG_ERROR(("%s: file=%s error or too deep", path, arg));
  6745. }
  6746. } else if (sscanf(buf, "<!--#include virtual=\"%[^\"]", arg)) {
  6747. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10], *data;
  6748. mg_snprintf(tmp, sizeof(tmp), "%s%s", root, arg);
  6749. if (depth < MG_MAX_SSI_DEPTH &&
  6750. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  6751. mg_iobuf_add(&b, b.len, data, strlen(data));
  6752. free(data);
  6753. } else {
  6754. MG_ERROR(("%s: virtual=%s error or too deep", path, arg));
  6755. }
  6756. } else {
  6757. // Unknown SSI tag
  6758. MG_ERROR(("Unknown SSI tag: %.*s", (int) len, buf));
  6759. mg_iobuf_add(&b, b.len, buf, len);
  6760. }
  6761. intag = 0;
  6762. len = 0;
  6763. } else if (ch == '<') {
  6764. intag = 1;
  6765. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  6766. len = 0;
  6767. buf[len++] = (char) (ch & 0xff);
  6768. } else if (intag) {
  6769. if (len == 5 && strncmp(buf, "<!--#", 5) != 0) {
  6770. intag = 0;
  6771. } else if (len >= sizeof(buf) - 2) {
  6772. MG_ERROR(("%s: SSI tag is too large", path));
  6773. len = 0;
  6774. }
  6775. buf[len++] = (char) (ch & 0xff);
  6776. } else {
  6777. buf[len++] = (char) (ch & 0xff);
  6778. if (len >= sizeof(buf)) {
  6779. mg_iobuf_add(&b, b.len, buf, len);
  6780. len = 0;
  6781. }
  6782. }
  6783. }
  6784. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  6785. if (b.len > 0) mg_iobuf_add(&b, b.len, "", 1); // nul-terminate
  6786. fclose(fp);
  6787. }
  6788. (void) depth;
  6789. (void) root;
  6790. return (char *) b.buf;
  6791. }
  6792. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  6793. const char *fullpath) {
  6794. const char *headers = "Content-Type: text/html; charset=utf-8\r\n";
  6795. char *data = mg_ssi(fullpath, root, 0);
  6796. mg_http_reply(c, 200, headers, "%s", data == NULL ? "" : data);
  6797. free(data);
  6798. }
  6799. #else
  6800. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  6801. const char *fullpath) {
  6802. mg_http_reply(c, 501, NULL, "SSI not enabled");
  6803. (void) root, (void) fullpath;
  6804. }
  6805. #endif
  6806. #ifdef MG_ENABLE_LINES
  6807. #line 1 "src/str.c"
  6808. #endif
  6809. struct mg_str mg_str_s(const char *s) {
  6810. struct mg_str str = {s, s == NULL ? 0 : strlen(s)};
  6811. return str;
  6812. }
  6813. struct mg_str mg_str_n(const char *s, size_t n) {
  6814. struct mg_str str = {s, n};
  6815. return str;
  6816. }
  6817. int mg_lower(const char *s) {
  6818. int c = *s;
  6819. if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
  6820. return c;
  6821. }
  6822. int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  6823. int diff = 0;
  6824. if (len > 0) do {
  6825. diff = mg_lower(s1++) - mg_lower(s2++);
  6826. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  6827. return diff;
  6828. }
  6829. int mg_casecmp(const char *s1, const char *s2) {
  6830. return mg_ncasecmp(s1, s2, (size_t) ~0);
  6831. }
  6832. int mg_vcmp(const struct mg_str *s1, const char *s2) {
  6833. size_t n2 = strlen(s2), n1 = s1->len;
  6834. int r = strncmp(s1->ptr, s2, (n1 < n2) ? n1 : n2);
  6835. if (r == 0) return (int) (n1 - n2);
  6836. return r;
  6837. }
  6838. int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
  6839. size_t n2 = strlen(str2), n1 = str1->len;
  6840. int r = mg_ncasecmp(str1->ptr, str2, (n1 < n2) ? n1 : n2);
  6841. if (r == 0) return (int) (n1 - n2);
  6842. return r;
  6843. }
  6844. struct mg_str mg_strdup(const struct mg_str s) {
  6845. struct mg_str r = {NULL, 0};
  6846. if (s.len > 0 && s.ptr != NULL) {
  6847. char *sc = (char *) calloc(1, s.len + 1);
  6848. if (sc != NULL) {
  6849. memcpy(sc, s.ptr, s.len);
  6850. sc[s.len] = '\0';
  6851. r.ptr = sc;
  6852. r.len = s.len;
  6853. }
  6854. }
  6855. return r;
  6856. }
  6857. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  6858. size_t i = 0;
  6859. while (i < str1.len && i < str2.len) {
  6860. int c1 = str1.ptr[i];
  6861. int c2 = str2.ptr[i];
  6862. if (c1 < c2) return -1;
  6863. if (c1 > c2) return 1;
  6864. i++;
  6865. }
  6866. if (i < str1.len) return 1;
  6867. if (i < str2.len) return -1;
  6868. return 0;
  6869. }
  6870. const char *mg_strstr(const struct mg_str haystack,
  6871. const struct mg_str needle) {
  6872. size_t i;
  6873. if (needle.len > haystack.len) return NULL;
  6874. if (needle.len == 0) return haystack.ptr;
  6875. for (i = 0; i <= haystack.len - needle.len; i++) {
  6876. if (memcmp(haystack.ptr + i, needle.ptr, needle.len) == 0) {
  6877. return haystack.ptr + i;
  6878. }
  6879. }
  6880. return NULL;
  6881. }
  6882. static bool is_space(int c) {
  6883. return c == ' ' || c == '\r' || c == '\n' || c == '\t';
  6884. }
  6885. struct mg_str mg_strstrip(struct mg_str s) {
  6886. while (s.len > 0 && is_space((int) *s.ptr)) s.ptr++, s.len--;
  6887. while (s.len > 0 && is_space((int) *(s.ptr + s.len - 1))) s.len--;
  6888. return s;
  6889. }
  6890. bool mg_match(struct mg_str s, struct mg_str p, struct mg_str *caps) {
  6891. size_t i = 0, j = 0, ni = 0, nj = 0;
  6892. if (caps) caps->ptr = NULL, caps->len = 0;
  6893. while (i < p.len || j < s.len) {
  6894. if (i < p.len && j < s.len && (p.ptr[i] == '?' || s.ptr[j] == p.ptr[i])) {
  6895. if (caps == NULL) {
  6896. } else if (p.ptr[i] == '?') {
  6897. caps->ptr = &s.ptr[j], caps->len = 1; // Finalize `?` cap
  6898. caps++, caps->ptr = NULL, caps->len = 0; // Init next cap
  6899. } else if (caps->ptr != NULL && caps->len == 0) {
  6900. caps->len = (size_t) (&s.ptr[j] - caps->ptr); // Finalize current cap
  6901. caps++, caps->len = 0, caps->ptr = NULL; // Init next cap
  6902. }
  6903. i++, j++;
  6904. } else if (i < p.len && (p.ptr[i] == '*' || p.ptr[i] == '#')) {
  6905. if (caps && !caps->ptr) caps->len = 0, caps->ptr = &s.ptr[j]; // Init cap
  6906. ni = i++, nj = j + 1;
  6907. } else if (nj > 0 && nj <= s.len && (p.ptr[ni] == '#' || s.ptr[j] != '/')) {
  6908. i = ni, j = nj;
  6909. if (caps && caps->ptr == NULL && caps->len == 0) {
  6910. caps--, caps->len = 0; // Restart previous cap
  6911. }
  6912. } else {
  6913. return false;
  6914. }
  6915. }
  6916. if (caps && caps->ptr && caps->len == 0) {
  6917. caps->len = (size_t) (&s.ptr[j] - caps->ptr);
  6918. }
  6919. return true;
  6920. }
  6921. bool mg_globmatch(const char *s1, size_t n1, const char *s2, size_t n2) {
  6922. return mg_match(mg_str_n(s2, n2), mg_str_n(s1, n1), NULL);
  6923. }
  6924. static size_t mg_nce(const char *s, size_t n, size_t ofs, size_t *koff,
  6925. size_t *klen, size_t *voff, size_t *vlen, char delim) {
  6926. size_t kvlen, kl;
  6927. for (kvlen = 0; ofs + kvlen < n && s[ofs + kvlen] != delim;) kvlen++;
  6928. for (kl = 0; kl < kvlen && s[ofs + kl] != '=';) kl++;
  6929. if (koff != NULL) *koff = ofs;
  6930. if (klen != NULL) *klen = kl;
  6931. if (voff != NULL) *voff = kl < kvlen ? ofs + kl + 1 : 0;
  6932. if (vlen != NULL) *vlen = kl < kvlen ? kvlen - kl - 1 : 0;
  6933. ofs += kvlen + 1;
  6934. return ofs > n ? n : ofs;
  6935. }
  6936. bool mg_split(struct mg_str *s, struct mg_str *k, struct mg_str *v, char sep) {
  6937. size_t koff = 0, klen = 0, voff = 0, vlen = 0, off = 0;
  6938. if (s->ptr == NULL || s->len == 0) return 0;
  6939. off = mg_nce(s->ptr, s->len, 0, &koff, &klen, &voff, &vlen, sep);
  6940. if (k != NULL) *k = mg_str_n(s->ptr + koff, klen);
  6941. if (v != NULL) *v = mg_str_n(s->ptr + voff, vlen);
  6942. *s = mg_str_n(s->ptr + off, s->len - off);
  6943. return off > 0;
  6944. }
  6945. bool mg_commalist(struct mg_str *s, struct mg_str *k, struct mg_str *v) {
  6946. return mg_split(s, k, v, ',');
  6947. }
  6948. char *mg_hex(const void *buf, size_t len, char *to) {
  6949. const unsigned char *p = (const unsigned char *) buf;
  6950. const char *hex = "0123456789abcdef";
  6951. size_t i = 0;
  6952. for (; len--; p++) {
  6953. to[i++] = hex[p[0] >> 4];
  6954. to[i++] = hex[p[0] & 0x0f];
  6955. }
  6956. to[i] = '\0';
  6957. return to;
  6958. }
  6959. static unsigned char mg_unhex_nimble(unsigned char c) {
  6960. return (c >= '0' && c <= '9') ? (unsigned char) (c - '0')
  6961. : (c >= 'A' && c <= 'F') ? (unsigned char) (c - '7')
  6962. : (unsigned char) (c - 'W');
  6963. }
  6964. unsigned long mg_unhexn(const char *s, size_t len) {
  6965. unsigned long i = 0, v = 0;
  6966. for (i = 0; i < len; i++) v <<= 4, v |= mg_unhex_nimble(((uint8_t *) s)[i]);
  6967. return v;
  6968. }
  6969. void mg_unhex(const char *buf, size_t len, unsigned char *to) {
  6970. size_t i;
  6971. for (i = 0; i < len; i += 2) {
  6972. to[i >> 1] = (unsigned char) mg_unhexn(&buf[i], 2);
  6973. }
  6974. }
  6975. bool mg_path_is_sane(const char *path) {
  6976. const char *s = path;
  6977. for (; s[0] != '\0'; s++) {
  6978. if (s == path || s[0] == '/' || s[0] == '\\') { // Subdir?
  6979. if (s[1] == '.' && s[2] == '.') return false; // Starts with ..
  6980. }
  6981. }
  6982. return true;
  6983. }
  6984. #ifdef MG_ENABLE_LINES
  6985. #line 1 "src/timer.c"
  6986. #endif
  6987. #define MG_TIMER_CALLED 4
  6988. void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
  6989. unsigned flags, void (*fn)(void *), void *arg) {
  6990. t->id = 0, t->period_ms = ms, t->expire = 0;
  6991. t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
  6992. *head = t;
  6993. }
  6994. void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
  6995. while (*head && *head != t) head = &(*head)->next;
  6996. if (*head) *head = t->next;
  6997. }
  6998. // t: expiration time, prd: period, now: current time. Return true if expired
  6999. bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
  7000. if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
  7001. if (*t == 0) *t = now + prd; // Firt poll? Set expiration
  7002. if (*t > now) return false; // Not expired yet, return
  7003. *t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
  7004. return true; // Expired, return true
  7005. }
  7006. void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
  7007. struct mg_timer *t, *tmp;
  7008. for (t = *head; t != NULL; t = tmp) {
  7009. bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
  7010. !(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
  7011. bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
  7012. tmp = t->next;
  7013. if (!once && !expired) continue;
  7014. if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
  7015. t->fn(t->arg);
  7016. }
  7017. t->flags |= MG_TIMER_CALLED;
  7018. }
  7019. }
  7020. #ifdef MG_ENABLE_LINES
  7021. #line 1 "src/tls_aes128.c"
  7022. #endif
  7023. /******************************************************************************
  7024. *
  7025. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7026. *
  7027. * This is a simple and straightforward implementation of the AES Rijndael
  7028. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7029. * of this work was correctness & accuracy. It is written in 'C' without any
  7030. * particular focus upon optimization or speed. It should be endian (memory
  7031. * byte order) neutral since the few places that care are handled explicitly.
  7032. *
  7033. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7034. *
  7035. * It is intended for general purpose use, but was written in support of GRC's
  7036. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7037. *
  7038. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7039. *
  7040. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7041. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7042. *
  7043. *******************************************************************************/
  7044. #if MG_TLS == MG_TLS_BUILTIN
  7045. static int aes_tables_inited = 0; // run-once flag for performing key
  7046. // expasion table generation (see below)
  7047. /*
  7048. * The following static local tables must be filled-in before the first use of
  7049. * the GCM or AES ciphers. They are used for the AES key expansion/scheduling
  7050. * and once built are read-only and thread safe. The "gcm_initialize" function
  7051. * must be called once during system initialization to populate these arrays
  7052. * for subsequent use by the AES key scheduler. If they have not been built
  7053. * before attempted use, an error will be returned to the caller.
  7054. *
  7055. * NOTE: GCM Encryption/Decryption does NOT REQUIRE AES decryption. Since
  7056. * GCM uses AES in counter-mode, where the AES cipher output is XORed with
  7057. * the GCM input, we ONLY NEED AES encryption. Thus, to save space AES
  7058. * decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.
  7059. */
  7060. // We always need our forward tables
  7061. static uchar FSb[256]; // Forward substitution box (FSb)
  7062. static uint32_t FT0[256]; // Forward key schedule assembly tables
  7063. static uint32_t FT1[256];
  7064. static uint32_t FT2[256];
  7065. static uint32_t FT3[256];
  7066. #if AES_DECRYPTION // We ONLY need reverse for decryption
  7067. static uchar RSb[256]; // Reverse substitution box (RSb)
  7068. static uint32_t RT0[256]; // Reverse key schedule assembly tables
  7069. static uint32_t RT1[256];
  7070. static uint32_t RT2[256];
  7071. static uint32_t RT3[256];
  7072. #endif /* AES_DECRYPTION */
  7073. static uint32_t RCON[10]; // AES round constants
  7074. /*
  7075. * Platform Endianness Neutralizing Load and Store Macro definitions
  7076. * AES wants platform-neutral Little Endian (LE) byte ordering
  7077. */
  7078. #define GET_UINT32_LE(n, b, i) \
  7079. { \
  7080. (n) = ((uint32_t) (b)[(i)]) | ((uint32_t) (b)[(i) + 1] << 8) | \
  7081. ((uint32_t) (b)[(i) + 2] << 16) | ((uint32_t) (b)[(i) + 3] << 24); \
  7082. }
  7083. #define PUT_UINT32_LE(n, b, i) \
  7084. { \
  7085. (b)[(i)] = (uchar) ((n)); \
  7086. (b)[(i) + 1] = (uchar) ((n) >> 8); \
  7087. (b)[(i) + 2] = (uchar) ((n) >> 16); \
  7088. (b)[(i) + 3] = (uchar) ((n) >> 24); \
  7089. }
  7090. /*
  7091. * AES forward and reverse encryption round processing macros
  7092. */
  7093. #define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7094. { \
  7095. X0 = *RK++ ^ FT0[(Y0) &0xFF] ^ FT1[(Y1 >> 8) & 0xFF] ^ \
  7096. FT2[(Y2 >> 16) & 0xFF] ^ FT3[(Y3 >> 24) & 0xFF]; \
  7097. \
  7098. X1 = *RK++ ^ FT0[(Y1) &0xFF] ^ FT1[(Y2 >> 8) & 0xFF] ^ \
  7099. FT2[(Y3 >> 16) & 0xFF] ^ FT3[(Y0 >> 24) & 0xFF]; \
  7100. \
  7101. X2 = *RK++ ^ FT0[(Y2) &0xFF] ^ FT1[(Y3 >> 8) & 0xFF] ^ \
  7102. FT2[(Y0 >> 16) & 0xFF] ^ FT3[(Y1 >> 24) & 0xFF]; \
  7103. \
  7104. X3 = *RK++ ^ FT0[(Y3) &0xFF] ^ FT1[(Y0 >> 8) & 0xFF] ^ \
  7105. FT2[(Y1 >> 16) & 0xFF] ^ FT3[(Y2 >> 24) & 0xFF]; \
  7106. }
  7107. #define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7108. { \
  7109. X0 = *RK++ ^ RT0[(Y0) &0xFF] ^ RT1[(Y3 >> 8) & 0xFF] ^ \
  7110. RT2[(Y2 >> 16) & 0xFF] ^ RT3[(Y1 >> 24) & 0xFF]; \
  7111. \
  7112. X1 = *RK++ ^ RT0[(Y1) &0xFF] ^ RT1[(Y0 >> 8) & 0xFF] ^ \
  7113. RT2[(Y3 >> 16) & 0xFF] ^ RT3[(Y2 >> 24) & 0xFF]; \
  7114. \
  7115. X2 = *RK++ ^ RT0[(Y2) &0xFF] ^ RT1[(Y1 >> 8) & 0xFF] ^ \
  7116. RT2[(Y0 >> 16) & 0xFF] ^ RT3[(Y3 >> 24) & 0xFF]; \
  7117. \
  7118. X3 = *RK++ ^ RT0[(Y3) &0xFF] ^ RT1[(Y2 >> 8) & 0xFF] ^ \
  7119. RT2[(Y1 >> 16) & 0xFF] ^ RT3[(Y0 >> 24) & 0xFF]; \
  7120. }
  7121. /*
  7122. * These macros improve the readability of the key
  7123. * generation initialization code by collapsing
  7124. * repetitive common operations into logical pieces.
  7125. */
  7126. #define ROTL8(x) ((x << 8) & 0xFFFFFFFF) | (x >> 24)
  7127. #define XTIME(x) ((x << 1) ^ ((x & 0x80) ? 0x1B : 0x00))
  7128. #define MUL(x, y) ((x && y) ? pow[(log[x] + log[y]) % 255] : 0)
  7129. #define MIX(x, y) \
  7130. { \
  7131. y = ((y << 1) | (y >> 7)) & 0xFF; \
  7132. x ^= y; \
  7133. }
  7134. #define CPY128 \
  7135. { \
  7136. *RK++ = *SK++; \
  7137. *RK++ = *SK++; \
  7138. *RK++ = *SK++; \
  7139. *RK++ = *SK++; \
  7140. }
  7141. /******************************************************************************
  7142. *
  7143. * AES_INIT_KEYGEN_TABLES
  7144. *
  7145. * Fills the AES key expansion tables allocated above with their static
  7146. * data. This is not "per key" data, but static system-wide read-only
  7147. * table data. THIS FUNCTION IS NOT THREAD SAFE. It must be called once
  7148. * at system initialization to setup the tables for all subsequent use.
  7149. *
  7150. ******************************************************************************/
  7151. void aes_init_keygen_tables(void) {
  7152. int i, x, y, z; // general purpose iteration and computation locals
  7153. int pow[256];
  7154. int log[256];
  7155. if (aes_tables_inited) return;
  7156. // fill the 'pow' and 'log' tables over GF(2^8)
  7157. for (i = 0, x = 1; i < 256; i++) {
  7158. pow[i] = x;
  7159. log[x] = i;
  7160. x = (x ^ XTIME(x)) & 0xFF;
  7161. }
  7162. // compute the round constants
  7163. for (i = 0, x = 1; i < 10; i++) {
  7164. RCON[i] = (uint32_t) x;
  7165. x = XTIME(x) & 0xFF;
  7166. }
  7167. // fill the forward and reverse substitution boxes
  7168. FSb[0x00] = 0x63;
  7169. #if AES_DECRYPTION // whether AES decryption is supported
  7170. RSb[0x63] = 0x00;
  7171. #endif /* AES_DECRYPTION */
  7172. for (i = 1; i < 256; i++) {
  7173. x = y = pow[255 - log[i]];
  7174. MIX(x, y);
  7175. MIX(x, y);
  7176. MIX(x, y);
  7177. MIX(x, y);
  7178. FSb[i] = (uchar) (x ^= 0x63);
  7179. #if AES_DECRYPTION // whether AES decryption is supported
  7180. RSb[x] = (uchar) i;
  7181. #endif /* AES_DECRYPTION */
  7182. }
  7183. // generate the forward and reverse key expansion tables
  7184. for (i = 0; i < 256; i++) {
  7185. x = FSb[i];
  7186. y = XTIME(x) & 0xFF;
  7187. z = (y ^ x) & 0xFF;
  7188. FT0[i] = ((uint32_t) y) ^ ((uint32_t) x << 8) ^ ((uint32_t) x << 16) ^
  7189. ((uint32_t) z << 24);
  7190. FT1[i] = ROTL8(FT0[i]);
  7191. FT2[i] = ROTL8(FT1[i]);
  7192. FT3[i] = ROTL8(FT2[i]);
  7193. #if AES_DECRYPTION // whether AES decryption is supported
  7194. x = RSb[i];
  7195. RT0[i] = ((uint32_t) MUL(0x0E, x)) ^ ((uint32_t) MUL(0x09, x) << 8) ^
  7196. ((uint32_t) MUL(0x0D, x) << 16) ^ ((uint32_t) MUL(0x0B, x) << 24);
  7197. RT1[i] = ROTL8(RT0[i]);
  7198. RT2[i] = ROTL8(RT1[i]);
  7199. RT3[i] = ROTL8(RT2[i]);
  7200. #endif /* AES_DECRYPTION */
  7201. }
  7202. aes_tables_inited = 1; // flag that the tables have been generated
  7203. } // to permit subsequent use of the AES cipher
  7204. /******************************************************************************
  7205. *
  7206. * AES_SET_ENCRYPTION_KEY
  7207. *
  7208. * This is called by 'aes_setkey' when we're establishing a key for
  7209. * subsequent encryption. We give it a pointer to the encryption
  7210. * context, a pointer to the key, and the key's length in bytes.
  7211. * Valid lengths are: 16, 24 or 32 bytes (128, 192, 256 bits).
  7212. *
  7213. ******************************************************************************/
  7214. static int aes_set_encryption_key(aes_context *ctx, const uchar *key, uint keysize) {
  7215. uint i; // general purpose iteration local
  7216. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7217. for (i = 0; i < (keysize >> 2); i++) {
  7218. GET_UINT32_LE(RK[i], key, i << 2);
  7219. }
  7220. switch (ctx->rounds) {
  7221. case 10:
  7222. for (i = 0; i < 10; i++, RK += 4) {
  7223. RK[4] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[3] >> 8) & 0xFF]) ^
  7224. ((uint32_t) FSb[(RK[3] >> 16) & 0xFF] << 8) ^
  7225. ((uint32_t) FSb[(RK[3] >> 24) & 0xFF] << 16) ^
  7226. ((uint32_t) FSb[(RK[3]) & 0xFF] << 24);
  7227. RK[5] = RK[1] ^ RK[4];
  7228. RK[6] = RK[2] ^ RK[5];
  7229. RK[7] = RK[3] ^ RK[6];
  7230. }
  7231. break;
  7232. case 12:
  7233. for (i = 0; i < 8; i++, RK += 6) {
  7234. RK[6] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[5] >> 8) & 0xFF]) ^
  7235. ((uint32_t) FSb[(RK[5] >> 16) & 0xFF] << 8) ^
  7236. ((uint32_t) FSb[(RK[5] >> 24) & 0xFF] << 16) ^
  7237. ((uint32_t) FSb[(RK[5]) & 0xFF] << 24);
  7238. RK[7] = RK[1] ^ RK[6];
  7239. RK[8] = RK[2] ^ RK[7];
  7240. RK[9] = RK[3] ^ RK[8];
  7241. RK[10] = RK[4] ^ RK[9];
  7242. RK[11] = RK[5] ^ RK[10];
  7243. }
  7244. break;
  7245. case 14:
  7246. for (i = 0; i < 7; i++, RK += 8) {
  7247. RK[8] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[7] >> 8) & 0xFF]) ^
  7248. ((uint32_t) FSb[(RK[7] >> 16) & 0xFF] << 8) ^
  7249. ((uint32_t) FSb[(RK[7] >> 24) & 0xFF] << 16) ^
  7250. ((uint32_t) FSb[(RK[7]) & 0xFF] << 24);
  7251. RK[9] = RK[1] ^ RK[8];
  7252. RK[10] = RK[2] ^ RK[9];
  7253. RK[11] = RK[3] ^ RK[10];
  7254. RK[12] = RK[4] ^ ((uint32_t) FSb[(RK[11]) & 0xFF]) ^
  7255. ((uint32_t) FSb[(RK[11] >> 8) & 0xFF] << 8) ^
  7256. ((uint32_t) FSb[(RK[11] >> 16) & 0xFF] << 16) ^
  7257. ((uint32_t) FSb[(RK[11] >> 24) & 0xFF] << 24);
  7258. RK[13] = RK[5] ^ RK[12];
  7259. RK[14] = RK[6] ^ RK[13];
  7260. RK[15] = RK[7] ^ RK[14];
  7261. }
  7262. break;
  7263. default:
  7264. return -1;
  7265. }
  7266. return (0);
  7267. }
  7268. #if AES_DECRYPTION // whether AES decryption is supported
  7269. /******************************************************************************
  7270. *
  7271. * AES_SET_DECRYPTION_KEY
  7272. *
  7273. * This is called by 'aes_setkey' when we're establishing a
  7274. * key for subsequent decryption. We give it a pointer to
  7275. * the encryption context, a pointer to the key, and the key's
  7276. * length in bits. Valid lengths are: 128, 192, or 256 bits.
  7277. *
  7278. ******************************************************************************/
  7279. static int aes_set_decryption_key(aes_context *ctx, const uchar *key, uint keysize) {
  7280. int i, j;
  7281. aes_context cty; // a calling aes context for set_encryption_key
  7282. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7283. uint32_t *SK;
  7284. int ret;
  7285. cty.rounds = ctx->rounds; // initialize our local aes context
  7286. cty.rk = cty.buf; // round count and key buf pointer
  7287. if ((ret = aes_set_encryption_key(&cty, key, keysize)) != 0) return (ret);
  7288. SK = cty.rk + cty.rounds * 4;
  7289. CPY128 // copy a 128-bit block from *SK to *RK
  7290. for (i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8) {
  7291. for (j = 0; j < 4; j++, SK++) {
  7292. *RK++ = RT0[FSb[(*SK) & 0xFF]] ^ RT1[FSb[(*SK >> 8) & 0xFF]] ^
  7293. RT2[FSb[(*SK >> 16) & 0xFF]] ^ RT3[FSb[(*SK >> 24) & 0xFF]];
  7294. }
  7295. }
  7296. CPY128 // copy a 128-bit block from *SK to *RK
  7297. memset(&cty, 0, sizeof(aes_context)); // clear local aes context
  7298. return (0);
  7299. }
  7300. #endif /* AES_DECRYPTION */
  7301. /******************************************************************************
  7302. *
  7303. * AES_SETKEY
  7304. *
  7305. * Invoked to establish the key schedule for subsequent encryption/decryption
  7306. *
  7307. ******************************************************************************/
  7308. int aes_setkey(aes_context *ctx, // AES context provided by our caller
  7309. int mode, // ENCRYPT or DECRYPT flag
  7310. const uchar *key, // pointer to the key
  7311. uint keysize) // key length in bytes
  7312. {
  7313. // since table initialization is not thread safe, we could either add
  7314. // system-specific mutexes and init the AES key generation tables on
  7315. // demand, or ask the developer to simply call "gcm_initialize" once during
  7316. // application startup before threading begins. That's what we choose.
  7317. if (!aes_tables_inited) return (-1); // fail the call when not inited.
  7318. ctx->mode = mode; // capture the key type we're creating
  7319. ctx->rk = ctx->buf; // initialize our round key pointer
  7320. switch (keysize) // set the rounds count based upon the keysize
  7321. {
  7322. case 16:
  7323. ctx->rounds = 10;
  7324. break; // 16-byte, 128-bit key
  7325. case 24:
  7326. ctx->rounds = 12;
  7327. break; // 24-byte, 192-bit key
  7328. case 32:
  7329. ctx->rounds = 14;
  7330. break; // 32-byte, 256-bit key
  7331. default:
  7332. return (-1);
  7333. }
  7334. #if AES_DECRYPTION
  7335. if (mode == DECRYPT) // expand our key for encryption or decryption
  7336. return (aes_set_decryption_key(ctx, key, keysize));
  7337. else /* ENCRYPT */
  7338. #endif /* AES_DECRYPTION */
  7339. return (aes_set_encryption_key(ctx, key, keysize));
  7340. }
  7341. /******************************************************************************
  7342. *
  7343. * AES_CIPHER
  7344. *
  7345. * Perform AES encryption and decryption.
  7346. * The AES context will have been setup with the encryption mode
  7347. * and all keying information appropriate for the task.
  7348. *
  7349. ******************************************************************************/
  7350. int aes_cipher(aes_context *ctx, const uchar input[16], uchar output[16]) {
  7351. int i;
  7352. uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; // general purpose locals
  7353. RK = ctx->rk;
  7354. GET_UINT32_LE(X0, input, 0);
  7355. X0 ^= *RK++; // load our 128-bit
  7356. GET_UINT32_LE(X1, input, 4);
  7357. X1 ^= *RK++; // input buffer in a storage
  7358. GET_UINT32_LE(X2, input, 8);
  7359. X2 ^= *RK++; // memory endian-neutral way
  7360. GET_UINT32_LE(X3, input, 12);
  7361. X3 ^= *RK++;
  7362. #if AES_DECRYPTION // whether AES decryption is supported
  7363. if (ctx->mode == DECRYPT) {
  7364. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  7365. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7366. AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  7367. }
  7368. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7369. X0 = *RK++ ^ ((uint32_t) RSb[(Y0) &0xFF]) ^
  7370. ((uint32_t) RSb[(Y3 >> 8) & 0xFF] << 8) ^
  7371. ((uint32_t) RSb[(Y2 >> 16) & 0xFF] << 16) ^
  7372. ((uint32_t) RSb[(Y1 >> 24) & 0xFF] << 24);
  7373. X1 = *RK++ ^ ((uint32_t) RSb[(Y1) &0xFF]) ^
  7374. ((uint32_t) RSb[(Y0 >> 8) & 0xFF] << 8) ^
  7375. ((uint32_t) RSb[(Y3 >> 16) & 0xFF] << 16) ^
  7376. ((uint32_t) RSb[(Y2 >> 24) & 0xFF] << 24);
  7377. X2 = *RK++ ^ ((uint32_t) RSb[(Y2) &0xFF]) ^
  7378. ((uint32_t) RSb[(Y1 >> 8) & 0xFF] << 8) ^
  7379. ((uint32_t) RSb[(Y0 >> 16) & 0xFF] << 16) ^
  7380. ((uint32_t) RSb[(Y3 >> 24) & 0xFF] << 24);
  7381. X3 = *RK++ ^ ((uint32_t) RSb[(Y3) &0xFF]) ^
  7382. ((uint32_t) RSb[(Y2 >> 8) & 0xFF] << 8) ^
  7383. ((uint32_t) RSb[(Y1 >> 16) & 0xFF] << 16) ^
  7384. ((uint32_t) RSb[(Y0 >> 24) & 0xFF] << 24);
  7385. } else /* ENCRYPT */
  7386. {
  7387. #endif /* AES_DECRYPTION */
  7388. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  7389. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7390. AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  7391. }
  7392. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7393. X0 = *RK++ ^ ((uint32_t) FSb[(Y0) &0xFF]) ^
  7394. ((uint32_t) FSb[(Y1 >> 8) & 0xFF] << 8) ^
  7395. ((uint32_t) FSb[(Y2 >> 16) & 0xFF] << 16) ^
  7396. ((uint32_t) FSb[(Y3 >> 24) & 0xFF] << 24);
  7397. X1 = *RK++ ^ ((uint32_t) FSb[(Y1) &0xFF]) ^
  7398. ((uint32_t) FSb[(Y2 >> 8) & 0xFF] << 8) ^
  7399. ((uint32_t) FSb[(Y3 >> 16) & 0xFF] << 16) ^
  7400. ((uint32_t) FSb[(Y0 >> 24) & 0xFF] << 24);
  7401. X2 = *RK++ ^ ((uint32_t) FSb[(Y2) &0xFF]) ^
  7402. ((uint32_t) FSb[(Y3 >> 8) & 0xFF] << 8) ^
  7403. ((uint32_t) FSb[(Y0 >> 16) & 0xFF] << 16) ^
  7404. ((uint32_t) FSb[(Y1 >> 24) & 0xFF] << 24);
  7405. X3 = *RK++ ^ ((uint32_t) FSb[(Y3) &0xFF]) ^
  7406. ((uint32_t) FSb[(Y0 >> 8) & 0xFF] << 8) ^
  7407. ((uint32_t) FSb[(Y1 >> 16) & 0xFF] << 16) ^
  7408. ((uint32_t) FSb[(Y2 >> 24) & 0xFF] << 24);
  7409. #if AES_DECRYPTION // whether AES decryption is supported
  7410. }
  7411. #endif /* AES_DECRYPTION */
  7412. PUT_UINT32_LE(X0, output, 0);
  7413. PUT_UINT32_LE(X1, output, 4);
  7414. PUT_UINT32_LE(X2, output, 8);
  7415. PUT_UINT32_LE(X3, output, 12);
  7416. return (0);
  7417. }
  7418. /* end of aes.c */
  7419. /******************************************************************************
  7420. *
  7421. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7422. *
  7423. * This is a simple and straightforward implementation of AES-GCM authenticated
  7424. * encryption. The focus of this work was correctness & accuracy. It is written
  7425. * in straight 'C' without any particular focus upon optimization or speed. It
  7426. * should be endian (memory byte order) neutral since the few places that care
  7427. * are handled explicitly.
  7428. *
  7429. * This implementation of AES-GCM was created by Steven M. Gibson of GRC.com.
  7430. *
  7431. * It is intended for general purpose use, but was written in support of GRC's
  7432. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7433. *
  7434. * See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  7435. * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/
  7436. * gcm/gcm-revised-spec.pdf
  7437. *
  7438. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7439. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7440. *
  7441. *******************************************************************************/
  7442. /******************************************************************************
  7443. * ==== IMPLEMENTATION WARNING ====
  7444. *
  7445. * This code was developed for use within SQRL's fixed environmnent. Thus, it
  7446. * is somewhat less "general purpose" than it would be if it were designed as
  7447. * a general purpose AES-GCM library. Specifically, it bothers with almost NO
  7448. * error checking on parameter limits, buffer bounds, etc. It assumes that it
  7449. * is being invoked by its author or by someone who understands the values it
  7450. * expects to receive. Its behavior will be undefined otherwise.
  7451. *
  7452. * All functions that might fail are defined to return 'ints' to indicate a
  7453. * problem. Most do not do so now. But this allows for error propagation out
  7454. * of internal functions if robust error checking should ever be desired.
  7455. *
  7456. ******************************************************************************/
  7457. /* Calculating the "GHASH"
  7458. *
  7459. * There are many ways of calculating the so-called GHASH in software, each with
  7460. * a traditional size vs performance tradeoff. The GHASH (Galois field hash) is
  7461. * an intriguing construction which takes two 128-bit strings (also the cipher's
  7462. * block size and the fundamental operation size for the system) and hashes them
  7463. * into a third 128-bit result.
  7464. *
  7465. * Many implementation solutions have been worked out that use large precomputed
  7466. * table lookups in place of more time consuming bit fiddling, and this approach
  7467. * can be scaled easily upward or downward as needed to change the time/space
  7468. * tradeoff. It's been studied extensively and there's a solid body of theory
  7469. * and practice. For example, without using any lookup tables an implementation
  7470. * might obtain 119 cycles per byte throughput, whereas using a simple, though
  7471. * large, key-specific 64 kbyte 8-bit lookup table the performance jumps to 13
  7472. * cycles per byte.
  7473. *
  7474. * And Intel's processors have, since 2010, included an instruction which does
  7475. * the entire 128x128->128 bit job in just several 64x64->128 bit pieces.
  7476. *
  7477. * Since SQRL is interactive, and only processing a few 128-bit blocks, I've
  7478. * settled upon a relatively slower but appealing small-table compromise which
  7479. * folds a bunch of not only time consuming but also bit twiddling into a simple
  7480. * 16-entry table which is attributed to Victor Shoup's 1996 work while at
  7481. * Bellcore: "On Fast and Provably Secure MessageAuthentication Based on
  7482. * Universal Hashing." See: http://www.shoup.net/papers/macs.pdf
  7483. * See, also section 4.1 of the "gcm-revised-spec" cited above.
  7484. */
  7485. /*
  7486. * This 16-entry table of pre-computed constants is used by the
  7487. * GHASH multiplier to improve over a strictly table-free but
  7488. * significantly slower 128x128 bit multiple within GF(2^128).
  7489. */
  7490. static const uint64_t last4[16] = {
  7491. 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
  7492. 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0};
  7493. /*
  7494. * Platform Endianness Neutralizing Load and Store Macro definitions
  7495. * GCM wants platform-neutral Big Endian (BE) byte ordering
  7496. */
  7497. #define GET_UINT32_BE(n, b, i) \
  7498. { \
  7499. (n) = ((uint32_t) (b)[(i)] << 24) | ((uint32_t) (b)[(i) + 1] << 16) | \
  7500. ((uint32_t) (b)[(i) + 2] << 8) | ((uint32_t) (b)[(i) + 3]); \
  7501. }
  7502. #define PUT_UINT32_BE(n, b, i) \
  7503. { \
  7504. (b)[(i)] = (uchar) ((n) >> 24); \
  7505. (b)[(i) + 1] = (uchar) ((n) >> 16); \
  7506. (b)[(i) + 2] = (uchar) ((n) >> 8); \
  7507. (b)[(i) + 3] = (uchar) ((n)); \
  7508. }
  7509. /******************************************************************************
  7510. *
  7511. * GCM_INITIALIZE
  7512. *
  7513. * Must be called once to initialize the GCM library.
  7514. *
  7515. * At present, this only calls the AES keygen table generator, which expands
  7516. * the AES keying tables for use. This is NOT A THREAD-SAFE function, so it
  7517. * MUST be called during system initialization before a multi-threading
  7518. * environment is running.
  7519. *
  7520. ******************************************************************************/
  7521. int gcm_initialize(void) {
  7522. aes_init_keygen_tables();
  7523. return (0);
  7524. }
  7525. /******************************************************************************
  7526. *
  7527. * GCM_MULT
  7528. *
  7529. * Performs a GHASH operation on the 128-bit input vector 'x', setting
  7530. * the 128-bit output vector to 'x' times H using our precomputed tables.
  7531. * 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  7532. *
  7533. ******************************************************************************/
  7534. static void gcm_mult(gcm_context *ctx, // pointer to established context
  7535. const uchar x[16], // pointer to 128-bit input vector
  7536. uchar output[16]) // pointer to 128-bit output vector
  7537. {
  7538. int i;
  7539. uchar lo, hi, rem;
  7540. uint64_t zh, zl;
  7541. lo = (uchar) (x[15] & 0x0f);
  7542. hi = (uchar) (x[15] >> 4);
  7543. zh = ctx->HH[lo];
  7544. zl = ctx->HL[lo];
  7545. for (i = 15; i >= 0; i--) {
  7546. lo = (uchar) (x[i] & 0x0f);
  7547. hi = (uchar) (x[i] >> 4);
  7548. if (i != 15) {
  7549. rem = (uchar) (zl & 0x0f);
  7550. zl = (zh << 60) | (zl >> 4);
  7551. zh = (zh >> 4);
  7552. zh ^= (uint64_t) last4[rem] << 48;
  7553. zh ^= ctx->HH[lo];
  7554. zl ^= ctx->HL[lo];
  7555. }
  7556. rem = (uchar) (zl & 0x0f);
  7557. zl = (zh << 60) | (zl >> 4);
  7558. zh = (zh >> 4);
  7559. zh ^= (uint64_t) last4[rem] << 48;
  7560. zh ^= ctx->HH[hi];
  7561. zl ^= ctx->HL[hi];
  7562. }
  7563. PUT_UINT32_BE(zh >> 32, output, 0);
  7564. PUT_UINT32_BE(zh, output, 4);
  7565. PUT_UINT32_BE(zl >> 32, output, 8);
  7566. PUT_UINT32_BE(zl, output, 12);
  7567. }
  7568. /******************************************************************************
  7569. *
  7570. * GCM_SETKEY
  7571. *
  7572. * This is called to set the AES-GCM key. It initializes the AES key
  7573. * and populates the gcm context's pre-calculated HTables.
  7574. *
  7575. ******************************************************************************/
  7576. int gcm_setkey(gcm_context *ctx, // pointer to caller-provided gcm context
  7577. const uchar *key, // pointer to the AES encryption key
  7578. const uint keysize) // size in bytes (must be 16, 24, 32 for
  7579. // 128, 192 or 256-bit keys respectively)
  7580. {
  7581. int ret, i, j;
  7582. uint64_t hi, lo;
  7583. uint64_t vl, vh;
  7584. unsigned char h[16];
  7585. memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
  7586. memset(h, 0, 16); // initialize the block to encrypt
  7587. // encrypt the null 128-bit block to generate a key-based value
  7588. // which is then used to initialize our GHASH lookup tables
  7589. if ((ret = aes_setkey(&ctx->aes_ctx, ENCRYPT, key, keysize)) != 0)
  7590. return (ret);
  7591. if ((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
  7592. GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
  7593. GET_UINT32_BE(lo, h, 4);
  7594. vh = (uint64_t) hi << 32 | lo;
  7595. GET_UINT32_BE(hi, h, 8);
  7596. GET_UINT32_BE(lo, h, 12);
  7597. vl = (uint64_t) hi << 32 | lo;
  7598. ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
  7599. ctx->HH[8] = vh;
  7600. ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
  7601. ctx->HL[0] = 0;
  7602. for (i = 4; i > 0; i >>= 1) {
  7603. uint32_t T = (uint32_t) (vl & 1) * 0xe1000000U;
  7604. vl = (vh << 63) | (vl >> 1);
  7605. vh = (vh >> 1) ^ ((uint64_t) T << 32);
  7606. ctx->HL[i] = vl;
  7607. ctx->HH[i] = vh;
  7608. }
  7609. for (i = 2; i < 16; i <<= 1) {
  7610. uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
  7611. vh = *HiH;
  7612. vl = *HiL;
  7613. for (j = 1; j < i; j++) {
  7614. HiH[j] = vh ^ ctx->HH[j];
  7615. HiL[j] = vl ^ ctx->HL[j];
  7616. }
  7617. }
  7618. return (0);
  7619. }
  7620. /******************************************************************************
  7621. *
  7622. * GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
  7623. *
  7624. * SETKEY:
  7625. *
  7626. * START: Sets the Encryption/Decryption mode.
  7627. * Accepts the initialization vector and additional data.
  7628. *
  7629. * UPDATE: Encrypts or decrypts the plaintext or ciphertext.
  7630. *
  7631. * FINISH: Performs a final GHASH to generate the authentication tag.
  7632. *
  7633. ******************************************************************************
  7634. *
  7635. * GCM_START
  7636. *
  7637. * Given a user-provided GCM context, this initializes it, sets the encryption
  7638. * mode, and preprocesses the initialization vector and additional AEAD data.
  7639. *
  7640. ******************************************************************************/
  7641. int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context
  7642. int mode, // GCM_ENCRYPT or GCM_DECRYPT
  7643. const uchar *iv, // pointer to initialization vector
  7644. size_t iv_len, // IV length in bytes (should == 12)
  7645. const uchar *add, // ptr to additional AEAD data (NULL if none)
  7646. size_t add_len) // length of additional AEAD data (bytes)
  7647. {
  7648. int ret; // our error return if the AES encrypt fails
  7649. uchar work_buf[16]; // XOR source built from provided IV if len != 16
  7650. const uchar *p; // general purpose array pointer
  7651. size_t use_len; // byte count to process, up to 16 bytes
  7652. size_t i; // local loop iterator
  7653. // since the context might be reused under the same key
  7654. // we zero the working buffers for this next new process
  7655. memset(ctx->y, 0x00, sizeof(ctx->y));
  7656. memset(ctx->buf, 0x00, sizeof(ctx->buf));
  7657. ctx->len = 0;
  7658. ctx->add_len = 0;
  7659. ctx->mode = mode; // set the GCM encryption/decryption mode
  7660. ctx->aes_ctx.mode = ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
  7661. if (iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
  7662. memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
  7663. ctx->y[15] = 1; // start "counting" from 1 (not 0)
  7664. } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
  7665. {
  7666. memset(work_buf, 0x00, 16); // clear the working buffer
  7667. PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
  7668. p = iv;
  7669. while (iv_len > 0) {
  7670. use_len = (iv_len < 16) ? iv_len : 16;
  7671. for (i = 0; i < use_len; i++) ctx->y[i] ^= p[i];
  7672. gcm_mult(ctx, ctx->y, ctx->y);
  7673. iv_len -= use_len;
  7674. p += use_len;
  7675. }
  7676. for (i = 0; i < 16; i++) ctx->y[i] ^= work_buf[i];
  7677. gcm_mult(ctx, ctx->y, ctx->y);
  7678. }
  7679. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0)
  7680. return (ret);
  7681. ctx->add_len = add_len;
  7682. p = add;
  7683. while (add_len > 0) {
  7684. use_len = (add_len < 16) ? add_len : 16;
  7685. for (i = 0; i < use_len; i++) ctx->buf[i] ^= p[i];
  7686. gcm_mult(ctx, ctx->buf, ctx->buf);
  7687. add_len -= use_len;
  7688. p += use_len;
  7689. }
  7690. return (0);
  7691. }
  7692. /******************************************************************************
  7693. *
  7694. * GCM_UPDATE
  7695. *
  7696. * This is called once or more to process bulk plaintext or ciphertext data.
  7697. * We give this some number of bytes of input and it returns the same number
  7698. * of output bytes. If called multiple times (which is fine) all but the final
  7699. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  7700. * have a partial block length of < 128 bits.)
  7701. *
  7702. ******************************************************************************/
  7703. int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  7704. size_t length, // length, in bytes, of data to process
  7705. const uchar *input, // pointer to source data
  7706. uchar *output) // pointer to destination data
  7707. {
  7708. int ret; // our error return if the AES encrypt fails
  7709. uchar ectr[16]; // counter-mode cipher output for XORing
  7710. size_t use_len; // byte count to process, up to 16 bytes
  7711. size_t i; // local loop iterator
  7712. ctx->len += length; // bump the GCM context's running length count
  7713. while (length > 0) {
  7714. // clamp the length to process at 16 bytes
  7715. use_len = (length < 16) ? length : 16;
  7716. // increment the context's 128-bit IV||Counter 'y' vector
  7717. for (i = 16; i > 12; i--)
  7718. if (++ctx->y[i - 1] != 0) break;
  7719. // encrypt the context's 'y' vector under the established key
  7720. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
  7721. // encrypt or decrypt the input to the output
  7722. if (ctx->mode == ENCRYPT) {
  7723. for (i = 0; i < use_len; i++) {
  7724. // XOR the cipher's ouptut vector (ectr) with our input
  7725. output[i] = (uchar) (ectr[i] ^ input[i]);
  7726. // now we mix in our data into the authentication hash.
  7727. // if we're ENcrypting we XOR in the post-XOR (output)
  7728. // results, but if we're DEcrypting we XOR in the input
  7729. // data
  7730. ctx->buf[i] ^= output[i];
  7731. }
  7732. } else {
  7733. for (i = 0; i < use_len; i++) {
  7734. // but if we're DEcrypting we XOR in the input data first,
  7735. // i.e. before saving to ouput data, otherwise if the input
  7736. // and output buffer are the same (inplace decryption) we
  7737. // would not get the correct auth tag
  7738. ctx->buf[i] ^= input[i];
  7739. // XOR the cipher's ouptut vector (ectr) with our input
  7740. output[i] = (uchar) (ectr[i] ^ input[i]);
  7741. }
  7742. }
  7743. gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
  7744. length -= use_len; // drop the remaining byte count to process
  7745. input += use_len; // bump our input pointer forward
  7746. output += use_len; // bump our output pointer forward
  7747. }
  7748. return (0);
  7749. }
  7750. /******************************************************************************
  7751. *
  7752. * GCM_FINISH
  7753. *
  7754. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  7755. * It performs the final GHASH to produce the resulting authentication TAG.
  7756. *
  7757. ******************************************************************************/
  7758. int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context
  7759. uchar *tag, // pointer to buffer which receives the tag
  7760. size_t tag_len) // length, in bytes, of the tag-receiving buf
  7761. {
  7762. uchar work_buf[16];
  7763. uint64_t orig_len = ctx->len * 8;
  7764. uint64_t orig_add_len = ctx->add_len * 8;
  7765. size_t i;
  7766. if (tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
  7767. if (orig_len || orig_add_len) {
  7768. memset(work_buf, 0x00, 16);
  7769. PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
  7770. PUT_UINT32_BE((orig_add_len), work_buf, 4);
  7771. PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
  7772. PUT_UINT32_BE((orig_len), work_buf, 12);
  7773. for (i = 0; i < 16; i++) ctx->buf[i] ^= work_buf[i];
  7774. gcm_mult(ctx, ctx->buf, ctx->buf);
  7775. for (i = 0; i < tag_len; i++) tag[i] ^= ctx->buf[i];
  7776. }
  7777. return (0);
  7778. }
  7779. /******************************************************************************
  7780. *
  7781. * GCM_CRYPT_AND_TAG
  7782. *
  7783. * This either encrypts or decrypts the user-provided data and, either
  7784. * way, generates an authentication tag of the requested length. It must be
  7785. * called with a GCM context whose key has already been set with GCM_SETKEY.
  7786. *
  7787. * The user would typically call this explicitly to ENCRYPT a buffer of data
  7788. * and optional associated data, and produce its an authentication tag.
  7789. *
  7790. * To reverse the process the user would typically call the companion
  7791. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  7792. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  7793. * to perform its decryption and tag generation, which it then compares.
  7794. *
  7795. ******************************************************************************/
  7796. int gcm_crypt_and_tag(
  7797. gcm_context *ctx, // gcm context with key already setup
  7798. int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
  7799. const uchar *iv, // pointer to the 12-byte initialization vector
  7800. size_t iv_len, // byte length if the IV. should always be 12
  7801. const uchar *add, // pointer to the non-ciphered additional data
  7802. size_t add_len, // byte length of the additional AEAD data
  7803. const uchar *input, // pointer to the cipher data source
  7804. uchar *output, // pointer to the cipher data destination
  7805. size_t length, // byte length of the cipher data
  7806. uchar *tag, // pointer to the tag to be generated
  7807. size_t tag_len) // byte length of the tag to be generated
  7808. { /*
  7809. assuming that the caller has already invoked gcm_setkey to
  7810. prepare the gcm context with the keying material, we simply
  7811. invoke each of the three GCM sub-functions in turn...
  7812. */
  7813. gcm_start(ctx, mode, iv, iv_len, add, add_len);
  7814. gcm_update(ctx, length, input, output);
  7815. gcm_finish(ctx, tag, tag_len);
  7816. return (0);
  7817. }
  7818. /******************************************************************************
  7819. *
  7820. * GCM_AUTH_DECRYPT
  7821. *
  7822. * This DECRYPTS a user-provided data buffer with optional associated data.
  7823. * It then verifies a user-supplied authentication tag against the tag just
  7824. * re-created during decryption to verify that the data has not been altered.
  7825. *
  7826. * This function calls GCM_CRYPT_AND_TAG (above) to perform the decryption
  7827. * and authentication tag generation.
  7828. *
  7829. ******************************************************************************/
  7830. int gcm_auth_decrypt(
  7831. gcm_context *ctx, // gcm context with key already setup
  7832. const uchar *iv, // pointer to the 12-byte initialization vector
  7833. size_t iv_len, // byte length if the IV. should always be 12
  7834. const uchar *add, // pointer to the non-ciphered additional data
  7835. size_t add_len, // byte length of the additional AEAD data
  7836. const uchar *input, // pointer to the cipher data source
  7837. uchar *output, // pointer to the cipher data destination
  7838. size_t length, // byte length of the cipher data
  7839. const uchar *tag, // pointer to the tag to be authenticated
  7840. size_t tag_len) // byte length of the tag <= 16
  7841. {
  7842. uchar check_tag[16]; // the tag generated and returned by decryption
  7843. int diff; // an ORed flag to detect authentication errors
  7844. size_t i; // our local iterator
  7845. /*
  7846. we use GCM_DECRYPT_AND_TAG (above) to perform our decryption
  7847. (which is an identical XORing to reverse the previous one)
  7848. and also to re-generate the matching authentication tag
  7849. */
  7850. gcm_crypt_and_tag(ctx, DECRYPT, iv, iv_len, add, add_len, input, output,
  7851. length, check_tag, tag_len);
  7852. // now we verify the authentication tag in 'constant time'
  7853. for (diff = 0, i = 0; i < tag_len; i++) diff |= tag[i] ^ check_tag[i];
  7854. if (diff != 0) { // see whether any bits differed?
  7855. memset(output, 0, length); // if so... wipe the output data
  7856. return (GCM_AUTH_FAILURE); // return GCM_AUTH_FAILURE
  7857. }
  7858. return (0);
  7859. }
  7860. /******************************************************************************
  7861. *
  7862. * GCM_ZERO_CTX
  7863. *
  7864. * The GCM context contains both the GCM context and the AES context.
  7865. * This includes keying and key-related material which is security-
  7866. * sensitive, so it MUST be zeroed after use. This function does that.
  7867. *
  7868. ******************************************************************************/
  7869. void gcm_zero_ctx(gcm_context *ctx) {
  7870. // zero the context originally provided to us
  7871. memset(ctx, 0, sizeof(gcm_context));
  7872. }
  7873. //
  7874. // aes-gcm.c
  7875. // Pods
  7876. //
  7877. // Created by Markus Kosmal on 20/11/14.
  7878. //
  7879. //
  7880. int aes_gcm_encrypt(unsigned char *output, //
  7881. const unsigned char *input, size_t input_length,
  7882. const unsigned char *key, const size_t key_len,
  7883. const unsigned char *iv, const size_t iv_len,
  7884. unsigned char *aead, size_t aead_len, unsigned char *tag,
  7885. const size_t tag_len) {
  7886. int ret = 0; // our return value
  7887. gcm_context ctx; // includes the AES context structure
  7888. gcm_setkey(&ctx, key, (const uint) key_len);
  7889. ret = gcm_crypt_and_tag(&ctx, ENCRYPT, iv, iv_len, aead, aead_len, input, output,
  7890. input_length, tag, tag_len);
  7891. gcm_zero_ctx(&ctx);
  7892. return (ret);
  7893. }
  7894. int aes_gcm_decrypt(unsigned char *output, const unsigned char *input,
  7895. size_t input_length, const unsigned char *key,
  7896. const size_t key_len, const unsigned char *iv,
  7897. const size_t iv_len) {
  7898. int ret = 0; // our return value
  7899. gcm_context ctx; // includes the AES context structure
  7900. size_t tag_len = 0;
  7901. unsigned char *tag_buf = NULL;
  7902. gcm_setkey(&ctx, key, (const uint) key_len);
  7903. ret = gcm_crypt_and_tag(&ctx, DECRYPT, iv, iv_len, NULL, 0, input, output,
  7904. input_length, tag_buf, tag_len);
  7905. gcm_zero_ctx(&ctx);
  7906. return (ret);
  7907. }
  7908. #endif
  7909. // End of aes128 PD
  7910. #ifdef MG_ENABLE_LINES
  7911. #line 1 "src/tls_builtin.c"
  7912. #endif
  7913. #if MG_TLS == MG_TLS_BUILTIN
  7914. // handshake is re-entrant, so we need to keep track of its state
  7915. enum mg_tls_hs_state {
  7916. MG_TLS_HS_CLIENT_HELLO, // first, wait for ClientHello
  7917. MG_TLS_HS_SERVER_HELLO, // then, send all server handshake data at once
  7918. MG_TLS_HS_CLIENT_CHANGE_CIPHER, // finally wait for ClientChangeCipher
  7919. MG_TLS_HS_CLIENT_FINISH, // and ClientFinish (encrypted)
  7920. MG_TLS_HS_DONE, // finish handshake, start application data flow
  7921. };
  7922. // per-connection TLS data
  7923. struct tls_data {
  7924. enum mg_tls_hs_state state; // keep track of connection handshake progress
  7925. struct mg_iobuf send; // For the receive path, we're reusing c->rtls
  7926. mg_sha256_ctx sha256; // incremental SHA-256 hash for TLS handshake
  7927. uint32_t sseq; // server sequence number, used in encryption
  7928. uint32_t cseq; // client sequence number, used in decryption
  7929. uint8_t session_id[32]; // client session ID between the handshake states
  7930. uint8_t x25519_cli[32]; // client X25519 key between the handshake states
  7931. uint8_t x25519_sec[32]; // x25519 secret between the handshake states
  7932. struct mg_str server_cert_der; // server certificate in DER format
  7933. uint8_t server_key[32]; // server EC private key
  7934. // keys for AES encryption
  7935. uint8_t handshake_secret[32];
  7936. uint8_t server_write_key[16];
  7937. uint8_t server_write_iv[12];
  7938. uint8_t server_finished_key[32];
  7939. uint8_t client_write_key[16];
  7940. uint8_t client_write_iv[12];
  7941. uint8_t client_finished_key[32];
  7942. };
  7943. #define MG_LOAD_BE16(p) ((uint16_t) ((MG_U8P(p)[0] << 8U) | MG_U8P(p)[1]))
  7944. #define TLS_HDR_SIZE 5 // 1 byte type, 2 bytes version, 2 bytes len
  7945. // for derived tls keys we need SHA256([0]*32)
  7946. static uint8_t zeros[32] = {0};
  7947. static uint8_t zeros_sha256_digest[32] =
  7948. "\xe3\xb0\xc4\x42\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99\x6f\xb9\x24"
  7949. "\x27\xae\x41\xe4\x64\x9b\x93\x4c\xa4\x95\x99\x1b\x78\x52\xb8\x55";
  7950. #define X25519_BYTES 32
  7951. const uint8_t X25519_BASE_POINT[X25519_BYTES] = {9};
  7952. #define X25519_WBITS 32
  7953. typedef uint32_t limb_t;
  7954. typedef uint64_t dlimb_t;
  7955. typedef int64_t sdlimb_t;
  7956. #define LIMB(x) (uint32_t)(x##ull), (uint32_t) ((x##ull) >> 32)
  7957. #define NLIMBS (256 / X25519_WBITS)
  7958. typedef limb_t fe[NLIMBS];
  7959. static limb_t umaal(limb_t *carry, limb_t acc, limb_t mand, limb_t mier) {
  7960. dlimb_t tmp = (dlimb_t) mand * mier + acc + *carry;
  7961. *carry = (limb_t) (tmp >> X25519_WBITS);
  7962. return (limb_t) tmp;
  7963. }
  7964. // These functions are implemented in terms of umaal on ARM
  7965. static limb_t adc(limb_t *carry, limb_t acc, limb_t mand) {
  7966. dlimb_t total = (dlimb_t) *carry + acc + mand;
  7967. *carry = (limb_t) (total >> X25519_WBITS);
  7968. return (limb_t) total;
  7969. }
  7970. static limb_t adc0(limb_t *carry, limb_t acc) {
  7971. dlimb_t total = (dlimb_t) *carry + acc;
  7972. *carry = (limb_t) (total >> X25519_WBITS);
  7973. return (limb_t) total;
  7974. }
  7975. // - Precondition: carry is small.
  7976. // - Invariant: result of propagate is < 2^255 + 1 word
  7977. // - In particular, always less than 2p.
  7978. // - Also, output x >= min(x,19)
  7979. static void propagate(fe x, limb_t over) {
  7980. unsigned i;
  7981. limb_t carry;
  7982. over = x[NLIMBS - 1] >> (X25519_WBITS - 1) | over << 1;
  7983. x[NLIMBS - 1] &= ~((limb_t) 1 << (X25519_WBITS - 1));
  7984. carry = over * 19;
  7985. for (i = 0; i < NLIMBS; i++) {
  7986. x[i] = adc0(&carry, x[i]);
  7987. }
  7988. }
  7989. static void add(fe out, const fe a, const fe b) {
  7990. unsigned i;
  7991. limb_t carry = 0;
  7992. for (i = 0; i < NLIMBS; i++) {
  7993. out[i] = adc(&carry, a[i], b[i]);
  7994. }
  7995. propagate(out, carry);
  7996. }
  7997. static void sub(fe out, const fe a, const fe b) {
  7998. unsigned i;
  7999. sdlimb_t carry = -38;
  8000. for (i = 0; i < NLIMBS; i++) {
  8001. carry = carry + a[i] - b[i];
  8002. out[i] = (limb_t) carry;
  8003. carry >>= X25519_WBITS;
  8004. }
  8005. propagate(out, (limb_t) (1 + carry));
  8006. }
  8007. static void mul(fe out, const fe a, const fe b, unsigned nb) {
  8008. limb_t accum[2 * NLIMBS] = {0};
  8009. unsigned i, j;
  8010. limb_t carry2;
  8011. for (i = 0; i < nb; i++) {
  8012. limb_t mand = b[i];
  8013. carry2 = 0;
  8014. for (j = 0; j < NLIMBS; j++) {
  8015. accum[i + j] = umaal(&carry2, accum[i + j], mand, a[j]);
  8016. }
  8017. accum[i + j] = carry2;
  8018. }
  8019. carry2 = 0;
  8020. for (j = 0; j < NLIMBS; j++) {
  8021. out[j] = umaal(&carry2, accum[j], 38, accum[j + NLIMBS]);
  8022. }
  8023. propagate(out, carry2);
  8024. }
  8025. static void sqr(fe out, const fe a) {
  8026. mul(out, a, a, NLIMBS);
  8027. }
  8028. static void mul1(fe out, const fe a) {
  8029. mul(out, a, out, NLIMBS);
  8030. }
  8031. static void sqr1(fe a) {
  8032. mul1(a, a);
  8033. }
  8034. static void condswap(limb_t a[2 * NLIMBS], limb_t b[2 * NLIMBS],
  8035. limb_t doswap) {
  8036. unsigned i;
  8037. for (i = 0; i < 2 * NLIMBS; i++) {
  8038. limb_t xor = (a[i] ^ b[i]) & doswap;
  8039. a[i] ^= xor;
  8040. b[i] ^= xor;
  8041. }
  8042. }
  8043. // Canonicalize a field element x, reducing it to the least residue which is
  8044. // congruent to it mod 2^255-19
  8045. // - Precondition: x < 2^255 + 1 word
  8046. static limb_t canon(fe x) {
  8047. // First, add 19.
  8048. unsigned i;
  8049. limb_t carry0 = 19;
  8050. limb_t res;
  8051. sdlimb_t carry;
  8052. for (i = 0; i < NLIMBS; i++) {
  8053. x[i] = adc0(&carry0, x[i]);
  8054. }
  8055. propagate(x, carry0);
  8056. // Here, 19 <= x2 < 2^255
  8057. // - This is because we added 19, so before propagate it can't be less
  8058. // than 19. After propagate, it still can't be less than 19, because if
  8059. // propagate does anything it adds 19.
  8060. // - We know that the high bit must be clear, because either the input was ~
  8061. // 2^255 + one word + 19 (in which case it propagates to at most 2 words) or
  8062. // it was < 2^255. So now, if we subtract 19, we will get back to something in
  8063. // [0,2^255-19).
  8064. carry = -19;
  8065. res = 0;
  8066. for (i = 0; i < NLIMBS; i++) {
  8067. carry += x[i];
  8068. res |= x[i] = (limb_t) carry;
  8069. carry >>= X25519_WBITS;
  8070. }
  8071. return (limb_t) (((dlimb_t) res - 1) >> X25519_WBITS);
  8072. }
  8073. static const limb_t a24[1] = {121665};
  8074. static void ladder_part1(fe xs[5]) {
  8075. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  8076. add(t1, x2, z2); // t1 = A
  8077. sub(z2, x2, z2); // z2 = B
  8078. add(x2, x3, z3); // x2 = C
  8079. sub(z3, x3, z3); // z3 = D
  8080. mul1(z3, t1); // z3 = DA
  8081. mul1(x2, z2); // x3 = BC
  8082. add(x3, z3, x2); // x3 = DA+CB
  8083. sub(z3, z3, x2); // z3 = DA-CB
  8084. sqr1(t1); // t1 = AA
  8085. sqr1(z2); // z2 = BB
  8086. sub(x2, t1, z2); // x2 = E = AA-BB
  8087. mul(z2, x2, a24, sizeof(a24) / sizeof(a24[0])); // z2 = E*a24
  8088. add(z2, z2, t1); // z2 = E*a24 + AA
  8089. }
  8090. static void ladder_part2(fe xs[5], const fe x1) {
  8091. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  8092. sqr1(z3); // z3 = (DA-CB)^2
  8093. mul1(z3, x1); // z3 = x1 * (DA-CB)^2
  8094. sqr1(x3); // x3 = (DA+CB)^2
  8095. mul1(z2, x2); // z2 = AA*(E*a24+AA)
  8096. sub(x2, t1, x2); // x2 = BB again
  8097. mul1(x2, t1); // x2 = AA*BB
  8098. }
  8099. static void x25519_core(fe xs[5], const uint8_t scalar[X25519_BYTES],
  8100. const uint8_t *x1, int clamp) {
  8101. int i;
  8102. limb_t swap = 0;
  8103. limb_t *x2 = xs[0], *x3 = xs[2], *z3 = xs[3];
  8104. memset(xs, 0, 4 * sizeof(fe));
  8105. x2[0] = z3[0] = 1;
  8106. memcpy(x3, x1, sizeof(fe));
  8107. for (i = 255; i >= 0; i--) {
  8108. uint8_t bytei = scalar[i / 8];
  8109. limb_t doswap;
  8110. if (clamp) {
  8111. if (i / 8 == 0) {
  8112. bytei &= (uint8_t) ~7U;
  8113. } else if (i / 8 == X25519_BYTES - 1) {
  8114. bytei &= 0x7F;
  8115. bytei |= 0x40;
  8116. }
  8117. }
  8118. doswap = 0 - (limb_t) ((bytei >> (i % 8)) & 1);
  8119. condswap(x2, x3, swap ^ doswap);
  8120. swap = doswap;
  8121. ladder_part1(xs);
  8122. ladder_part2(xs, (const limb_t *) x1);
  8123. }
  8124. condswap(x2, x3, swap);
  8125. }
  8126. static int x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES],
  8127. const uint8_t x1[X25519_BYTES], int clamp) {
  8128. int i, ret;
  8129. fe xs[5];
  8130. limb_t *x2, *z2, *z3, *prev;
  8131. static const struct {
  8132. uint8_t a, c, n;
  8133. } steps[13] = {{2, 1, 1}, {2, 1, 1}, {4, 2, 3}, {2, 4, 6}, {3, 1, 1},
  8134. {3, 2, 12}, {4, 3, 25}, {2, 3, 25}, {2, 4, 50}, {3, 2, 125},
  8135. {3, 1, 2}, {3, 1, 2}, {3, 1, 1}};
  8136. x25519_core(xs, scalar, x1, clamp);
  8137. // Precomputed inversion chain
  8138. x2 = xs[0];
  8139. z2 = xs[1];
  8140. z3 = xs[3];
  8141. prev = z2;
  8142. for (i = 0; i < 13; i++) {
  8143. int j;
  8144. limb_t *a = xs[steps[i].a];
  8145. for (j = steps[i].n; j > 0; j--) {
  8146. sqr(a, prev);
  8147. prev = a;
  8148. }
  8149. mul1(a, xs[steps[i].c]);
  8150. }
  8151. // Here prev = z3
  8152. // x2 /= z2
  8153. mul((limb_t *) out, x2, z3, NLIMBS);
  8154. ret = (int) canon((limb_t *) out);
  8155. if (!clamp) ret = 0;
  8156. return ret;
  8157. }
  8158. // helper to hexdump buffers inline
  8159. static void mg_tls_hexdump(const char *msg, uint8_t *buf, size_t bufsz) {
  8160. char p[512];
  8161. MG_VERBOSE(("%s: %s", msg, mg_hex(buf, bufsz, p)));
  8162. }
  8163. // TLS1.3 secret derivation based on the key label
  8164. static void mg_tls_derive_secret(const char *label, uint8_t *key, size_t keysz,
  8165. uint8_t *data, size_t datasz, uint8_t *hash,
  8166. size_t hashsz) {
  8167. size_t labelsz = strlen(label);
  8168. uint8_t secret[32];
  8169. uint8_t packed[256] = {0, (uint8_t) hashsz, (uint8_t) labelsz};
  8170. // TODO: assert lengths of label, key, data and hash
  8171. memmove(packed + 3, label, labelsz);
  8172. packed[3 + labelsz] = (uint8_t) datasz;
  8173. memmove(packed + labelsz + 4, data, datasz);
  8174. packed[4 + labelsz + datasz] = 1;
  8175. mg_hmac_sha256(secret, key, keysz, packed, 5 + labelsz + datasz);
  8176. memmove(hash, secret, hashsz);
  8177. }
  8178. // Did we receive a full TLS message in the c->rtls buffer?
  8179. static bool mg_tls_got_msg(struct mg_connection *c) {
  8180. return c->rtls.len >= (size_t) TLS_HDR_SIZE &&
  8181. c->rtls.len >= (size_t) (TLS_HDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
  8182. }
  8183. // Remove a single TLS record from the recv buffer
  8184. static void mg_tls_drop_packet(struct mg_iobuf *rio) {
  8185. uint16_t n = MG_LOAD_BE16(rio->buf + 3) + TLS_HDR_SIZE;
  8186. mg_iobuf_del(rio, 0, n);
  8187. }
  8188. // read and parse ClientHello record
  8189. static int mg_tls_client_hello(struct mg_connection *c) {
  8190. struct tls_data *tls = c->tls;
  8191. struct mg_iobuf *rio = &c->rtls;
  8192. uint8_t session_id_len;
  8193. uint16_t j;
  8194. uint16_t cipher_suites_len;
  8195. uint16_t ext_len;
  8196. uint8_t *ext;
  8197. if (!mg_tls_got_msg(c)) {
  8198. return MG_IO_WAIT;
  8199. }
  8200. if (rio->buf[0] != 0x16 || rio->buf[5] != 0x01) {
  8201. mg_error(c, "not a hello packet");
  8202. return -1;
  8203. }
  8204. mg_sha256_update(&tls->sha256, rio->buf + 5, rio->len - 5);
  8205. session_id_len = rio->buf[43];
  8206. if (session_id_len == sizeof(tls->session_id)) {
  8207. memmove(tls->session_id, rio->buf + 44, session_id_len);
  8208. } else if (session_id_len != 0) {
  8209. MG_INFO(("bad session id len"));
  8210. }
  8211. cipher_suites_len = MG_LOAD_BE16(rio->buf + 44 + session_id_len);
  8212. ext_len = MG_LOAD_BE16(rio->buf + 48 + session_id_len + cipher_suites_len);
  8213. ext = rio->buf + 50 + session_id_len + cipher_suites_len;
  8214. for (j = 0; j < ext_len;) {
  8215. uint16_t k;
  8216. uint16_t key_exchange_len;
  8217. uint8_t *key_exchange;
  8218. uint16_t n = MG_LOAD_BE16(ext + j + 2);
  8219. if (ext[j] != 0x00 ||
  8220. ext[j + 1] != 0x33) { // not a key share extension, ignore
  8221. j += (uint16_t) (n + 4);
  8222. continue;
  8223. }
  8224. key_exchange_len = MG_LOAD_BE16(ext + j + 5);
  8225. key_exchange = ext + j + 6;
  8226. for (k = 0; k < key_exchange_len;) {
  8227. uint16_t m = MG_LOAD_BE16(key_exchange + k + 2);
  8228. if (m == 32 && key_exchange[k] == 0x00 && key_exchange[k + 1] == 0x1d) {
  8229. memmove(tls->x25519_cli, key_exchange + k + 4, m);
  8230. mg_tls_drop_packet(rio);
  8231. return 0;
  8232. }
  8233. k += (uint16_t) (m + 4);
  8234. }
  8235. j += (uint16_t) (n + 4);
  8236. }
  8237. mg_error(c, "bad client hello");
  8238. return -1;
  8239. }
  8240. // put ServerHello record into wio buffer
  8241. static void mg_tls_server_hello(struct mg_connection *c) {
  8242. struct tls_data *tls = c->tls;
  8243. struct mg_iobuf *wio = &tls->send;
  8244. uint8_t msg_server_hello[122] =
  8245. // server hello, tls 1.2
  8246. "\x02\x00\x00\x76\x03\x03"
  8247. // random (32 bytes)
  8248. "\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe"
  8249. "\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe"
  8250. // session ID length + session ID (32 bytes)
  8251. "\x20"
  8252. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
  8253. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
  8254. #if defined(CHACHA20) && CHACHA20
  8255. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  8256. "\x13\x03\x00"
  8257. #else
  8258. // TLS_AES_128_GCM_SHA256 + no compression
  8259. "\x13\x01\x00"
  8260. #endif
  8261. // extensions + keyshare
  8262. "\x00\x2e\x00\x33\x00\x24\x00\x1d\x00\x20"
  8263. // x25519 keyshare
  8264. "\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab"
  8265. "\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab"
  8266. // supported versions (tls1.3 == 0x304)
  8267. "\x00\x2b\x00\x02\x03\x04";
  8268. // calculate keyshare
  8269. uint8_t x25519_pub[X25519_BYTES];
  8270. uint8_t x25519_prv[X25519_BYTES];
  8271. mg_random(x25519_prv, sizeof(x25519_prv));
  8272. x25519(x25519_pub, x25519_prv, X25519_BASE_POINT, 1);
  8273. x25519(tls->x25519_sec, x25519_prv, tls->x25519_cli, 1);
  8274. mg_tls_hexdump("x25519 sec", tls->x25519_sec, sizeof(tls->x25519_sec));
  8275. // fill in the gaps: session ID + keyshare
  8276. memmove(msg_server_hello + 39, tls->session_id, sizeof(tls->session_id));
  8277. memmove(msg_server_hello + 84, x25519_pub, sizeof(x25519_pub));
  8278. // server hello message
  8279. mg_iobuf_add(wio, wio->len, "\x16\x03\x03\x00\x7a", 5);
  8280. mg_iobuf_add(wio, wio->len, msg_server_hello, sizeof(msg_server_hello));
  8281. mg_sha256_update(&tls->sha256, msg_server_hello, sizeof(msg_server_hello));
  8282. // change cipher message
  8283. mg_iobuf_add(wio, wio->len, "\x14\x03\x03\x00\x01\x01", 6);
  8284. }
  8285. // at this point we have x25519 shared secret, we can generate a set of derived
  8286. // handshake encryption keys
  8287. static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
  8288. struct tls_data *tls = c->tls;
  8289. mg_sha256_ctx sha256;
  8290. uint8_t early_secret[32];
  8291. uint8_t pre_extract_secret[32];
  8292. uint8_t hello_hash[32];
  8293. uint8_t server_hs_secret[32];
  8294. uint8_t client_hs_secret[32];
  8295. mg_hmac_sha256(early_secret, NULL, 0, zeros, sizeof(zeros));
  8296. mg_tls_derive_secret("tls13 derived", early_secret, 32, zeros_sha256_digest,
  8297. 32, pre_extract_secret, 32);
  8298. mg_hmac_sha256(tls->handshake_secret, pre_extract_secret,
  8299. sizeof(pre_extract_secret), tls->x25519_sec,
  8300. sizeof(tls->x25519_sec));
  8301. mg_tls_hexdump("hs secret", tls->handshake_secret, 32);
  8302. // mg_sha256_final is not idempotent, need to copy sha256 context to calculate
  8303. // the digest
  8304. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8305. mg_sha256_final(hello_hash, &sha256);
  8306. // derive keys needed for the rest of the handshake
  8307. mg_tls_derive_secret("tls13 s hs traffic", tls->handshake_secret, 32,
  8308. hello_hash, 32, server_hs_secret, 32);
  8309. mg_tls_derive_secret("tls13 key", server_hs_secret, 32, NULL, 0,
  8310. tls->server_write_key, 16);
  8311. mg_tls_derive_secret("tls13 iv", server_hs_secret, 32, NULL, 0,
  8312. tls->server_write_iv, 12);
  8313. mg_tls_derive_secret("tls13 finished", server_hs_secret, 32, NULL, 0,
  8314. tls->server_finished_key, 32);
  8315. mg_tls_hexdump("s hs traffic", server_hs_secret, 32);
  8316. mg_tls_derive_secret("tls13 c hs traffic", tls->handshake_secret, 32,
  8317. hello_hash, 32, client_hs_secret, 32);
  8318. mg_tls_derive_secret("tls13 key", client_hs_secret, 32, NULL, 0,
  8319. tls->client_write_key, 16);
  8320. mg_tls_derive_secret("tls13 iv", client_hs_secret, 32, NULL, 0,
  8321. tls->client_write_iv, 12);
  8322. mg_tls_derive_secret("tls13 finished", client_hs_secret, 32, NULL, 0,
  8323. tls->client_finished_key, 32);
  8324. }
  8325. // AES GCM encryption of the message + put encoded data into the write buffer
  8326. static void mg_tls_encrypt(struct mg_connection *c, const uint8_t *msg,
  8327. size_t msgsz, uint8_t msgtype) {
  8328. struct tls_data *tls = c->tls;
  8329. struct mg_iobuf *wio = &tls->send;
  8330. uint8_t *outmsg;
  8331. uint8_t *tag;
  8332. size_t encsz = msgsz + 16 + 1;
  8333. uint8_t hdr[5] = {0x17, 0x03, 0x03, (encsz >> 8) & 0xff, encsz & 0xff};
  8334. uint8_t associated_data[5] = {0x17, 0x03, 0x03, (encsz >> 8) & 0xff,
  8335. encsz & 0xff};
  8336. uint8_t nonce[12];
  8337. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8338. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8339. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8340. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8341. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8342. gcm_initialize();
  8343. mg_iobuf_add(wio, wio->len, hdr, sizeof(hdr));
  8344. mg_iobuf_resize(wio, wio->len + encsz);
  8345. outmsg = wio->buf + wio->len;
  8346. tag = wio->buf + wio->len + msgsz + 1;
  8347. memmove(outmsg, msg, msgsz);
  8348. outmsg[msgsz] = msgtype;
  8349. aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->server_write_key,
  8350. sizeof(tls->server_write_key), nonce, sizeof(nonce),
  8351. associated_data, sizeof(associated_data), tag, 16);
  8352. wio->len += encsz;
  8353. tls->sseq++;
  8354. }
  8355. // read an encrypted message, decrypt it into read buffer (AES GCM)
  8356. static int mg_tls_recv_decrypt(struct mg_connection *c, void *buf,
  8357. size_t bufsz) {
  8358. struct tls_data *tls = c->tls;
  8359. struct mg_iobuf *rio = &c->rtls;
  8360. // struct mg_iobuf *rio = &tls->recv;
  8361. uint16_t msgsz;
  8362. uint8_t *msg;
  8363. uint8_t nonce[12];
  8364. int r;
  8365. for (;;) {
  8366. if (!mg_tls_got_msg(c)) {
  8367. return MG_IO_WAIT;
  8368. }
  8369. if (rio->buf[0] == 0x17) {
  8370. break;
  8371. } else if (rio->buf[0] == 0x15) {
  8372. MG_INFO(("TLS ALERT packet received")); // TODO: drop packet?
  8373. } else {
  8374. mg_error(c, "unexpected packet");
  8375. return -1;
  8376. }
  8377. }
  8378. msgsz = MG_LOAD_BE16(rio->buf + 3);
  8379. msg = rio->buf + 5;
  8380. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  8381. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  8382. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  8383. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  8384. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  8385. aes_gcm_decrypt(msg, msg, msgsz - 16, tls->client_write_key,
  8386. sizeof(tls->client_write_key), nonce, sizeof(nonce));
  8387. r = msgsz - 16 - 1;
  8388. if (msg[r] == 0x17) {
  8389. if (bufsz > 0) {
  8390. memmove(buf, msg, msgsz - 16);
  8391. }
  8392. } else {
  8393. r = 0;
  8394. }
  8395. tls->cseq++;
  8396. mg_tls_drop_packet(rio);
  8397. return r;
  8398. }
  8399. static void mg_tls_server_extensions(struct mg_connection *c) {
  8400. struct tls_data *tls = c->tls;
  8401. // server extensions
  8402. uint8_t ext[6] = {0x08, 0, 0, 2, 0, 0};
  8403. mg_sha256_update(&tls->sha256, ext, sizeof(ext));
  8404. mg_tls_encrypt(c, ext, sizeof(ext), 0x16);
  8405. }
  8406. static void mg_tls_server_cert(struct mg_connection *c) {
  8407. struct tls_data *tls = c->tls;
  8408. // server DER certificate (empty)
  8409. size_t n = tls->server_cert_der.len;
  8410. uint8_t *cert = calloc(1, 13 + n); // FIXME: free
  8411. cert[0] = 0x0b; // handshake header
  8412. cert[1] = (uint8_t) (((n + 9) >> 16) & 255U); // 3 bytes: payload length
  8413. cert[2] = (uint8_t) (((n + 9) >> 8) & 255U);
  8414. cert[3] = (uint8_t) ((n + 9) & 255U);
  8415. cert[4] = 0; // request context
  8416. cert[5] = (uint8_t) (((n + 5) >> 16) & 255U); // 3 bytes: cert (s) length
  8417. cert[6] = (uint8_t) (((n + 5) >> 8) & 255U);
  8418. cert[7] = (uint8_t) ((n + 5) & 255U);
  8419. cert[8] =
  8420. (uint8_t) (((n) >> 16) & 255U); // 3 bytes: first (and only) cert len
  8421. cert[9] = (uint8_t) (((n) >> 8) & 255U);
  8422. cert[10] = (uint8_t) (n & 255U);
  8423. // bytes 11+ are certificate in DER format
  8424. memmove(cert + 11, tls->server_cert_der.ptr, n);
  8425. cert[11 + n] = cert[12 + n] = 0; // certificate extensions (none)
  8426. mg_sha256_update(&tls->sha256, cert, 13 + n);
  8427. mg_tls_encrypt(c, cert, 13 + n, 0x16);
  8428. }
  8429. // type adapter between uECC hash context and our sha256 implementation
  8430. typedef struct SHA256_HashContext {
  8431. uECC_HashContext uECC;
  8432. mg_sha256_ctx ctx;
  8433. } SHA256_HashContext;
  8434. static void init_SHA256(const uECC_HashContext *base) {
  8435. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8436. mg_sha256_init(&c->ctx);
  8437. }
  8438. static void update_SHA256(const uECC_HashContext *base, const uint8_t *message,
  8439. unsigned message_size) {
  8440. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8441. mg_sha256_update(&c->ctx, message, message_size);
  8442. }
  8443. static void finish_SHA256(const uECC_HashContext *base, uint8_t *hash_result) {
  8444. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8445. mg_sha256_final(hash_result, &c->ctx);
  8446. }
  8447. static void mg_tls_server_verify_ecdsa(struct mg_connection *c) {
  8448. struct tls_data *tls = c->tls;
  8449. // server certificate verify packet
  8450. uint8_t verify[82] = {0x0f, 0x00, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00};
  8451. size_t sigsz, verifysz = 0;
  8452. uint8_t hash[32] = {0}, tmp[2 * 32 + 64] = {0};
  8453. struct SHA256_HashContext ctx = {
  8454. {&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp},
  8455. {{0}, 0, 0, {0}}};
  8456. int neg1, neg2;
  8457. uint8_t sig[64], sig_content[130] = {
  8458. " "
  8459. " "
  8460. "TLS 1.3, server CertificateVerify\0"};
  8461. mg_sha256_ctx sha256;
  8462. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8463. mg_sha256_final(sig_content + 98, &sha256);
  8464. mg_sha256_init(&sha256);
  8465. mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
  8466. mg_sha256_final(hash, &sha256);
  8467. uECC_sign_deterministic(tls->server_key, hash, sizeof(hash), &ctx.uECC, sig,
  8468. uECC_secp256r1());
  8469. neg1 = !!(sig[0] & 0x80);
  8470. neg2 = !!(sig[32] & 0x80);
  8471. verify[8] = 0x30; // ASN.1 SEQUENCE
  8472. verify[9] = (uint8_t) (68 + neg1 + neg2);
  8473. verify[10] = 0x02; // ASN.1 INTEGER
  8474. verify[11] = (uint8_t) (32 + neg1);
  8475. memmove(verify + 12 + neg1, sig, 32);
  8476. verify[12 + 32 + neg1] = 0x02; // ASN.1 INTEGER
  8477. verify[13 + 32 + neg1] = (uint8_t) (32 + neg2);
  8478. memmove(verify + 14 + 32 + neg1 + neg2, sig + 32, 32);
  8479. sigsz = (size_t) (70 + neg1 + neg2);
  8480. verifysz = 8U + sigsz;
  8481. verify[3] = (uint8_t) (sigsz + 4);
  8482. verify[7] = (uint8_t) sigsz;
  8483. mg_tls_hexdump("verify", verify, verifysz);
  8484. mg_sha256_update(&tls->sha256, verify, verifysz);
  8485. mg_tls_encrypt(c, verify, verifysz, 0x16);
  8486. }
  8487. static void mg_tls_server_finish(struct mg_connection *c) {
  8488. struct tls_data *tls = c->tls;
  8489. struct mg_iobuf *wio = &tls->send;
  8490. mg_sha256_ctx sha256;
  8491. uint8_t hash[32];
  8492. uint8_t finish[36] = {0x14, 0, 0, 32};
  8493. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8494. mg_sha256_final(hash, &sha256);
  8495. mg_hmac_sha256(finish + 4, tls->server_finished_key, 32, hash, 32);
  8496. mg_tls_hexdump("hash", hash, sizeof(hash));
  8497. mg_tls_hexdump("key", tls->server_finished_key,
  8498. sizeof(tls->server_finished_key));
  8499. mg_tls_encrypt(c, finish, sizeof(finish), 0x16);
  8500. mg_io_send(c, wio->buf, wio->len);
  8501. wio->len = 0;
  8502. mg_sha256_update(&tls->sha256, finish, sizeof(finish));
  8503. }
  8504. static int mg_tls_client_change_cipher(struct mg_connection *c) {
  8505. // struct tls_data *tls = c->tls;
  8506. struct mg_iobuf *rio = &c->rtls;
  8507. for (;;) {
  8508. if (!mg_tls_got_msg(c)) {
  8509. return MG_IO_WAIT;
  8510. }
  8511. if (rio->buf[0] == 0x14) { // got a ChangeCipher record
  8512. break;
  8513. } else if (rio->buf[0] == 0x15) { // skip Alert records
  8514. MG_DEBUG(("TLS ALERT packet received"));
  8515. mg_tls_drop_packet(rio);
  8516. } else {
  8517. mg_error(c, "unexpected packet");
  8518. return MG_IO_ERR;
  8519. }
  8520. }
  8521. // consume ChangeCipher packet
  8522. mg_tls_drop_packet(rio);
  8523. return 0;
  8524. }
  8525. static int mg_tls_client_finish(struct mg_connection *c) {
  8526. uint8_t tmp[2048];
  8527. int n = mg_tls_recv_decrypt(c, tmp, sizeof(tmp));
  8528. if (n < 0) {
  8529. return -1;
  8530. }
  8531. // TODO: make sure it's a ClientFinish record
  8532. return 0;
  8533. }
  8534. static void mg_tls_generate_application_keys(struct mg_connection *c) {
  8535. struct tls_data *tls = c->tls;
  8536. uint8_t hash[32];
  8537. uint8_t premaster_secret[32];
  8538. uint8_t master_secret[32];
  8539. uint8_t server_secret[32];
  8540. uint8_t client_secret[32];
  8541. mg_sha256_ctx sha256;
  8542. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8543. mg_sha256_final(hash, &sha256);
  8544. mg_tls_derive_secret("tls13 derived", tls->handshake_secret, 32,
  8545. zeros_sha256_digest, 32, premaster_secret, 32);
  8546. mg_hmac_sha256(master_secret, premaster_secret, 32, zeros, 32);
  8547. mg_tls_derive_secret("tls13 s ap traffic", master_secret, 32, hash, 32,
  8548. server_secret, 32);
  8549. mg_tls_derive_secret("tls13 key", server_secret, 32, NULL, 0,
  8550. tls->server_write_key, 16);
  8551. mg_tls_derive_secret("tls13 iv", server_secret, 32, NULL, 0,
  8552. tls->server_write_iv, 12);
  8553. mg_tls_derive_secret("tls13 c ap traffic", master_secret, 32, hash, 32,
  8554. client_secret, 32);
  8555. mg_tls_derive_secret("tls13 key", client_secret, 32, NULL, 0,
  8556. tls->client_write_key, 16);
  8557. mg_tls_derive_secret("tls13 iv", client_secret, 32, NULL, 0,
  8558. tls->client_write_iv, 12);
  8559. tls->sseq = tls->cseq = 0;
  8560. }
  8561. void mg_tls_handshake(struct mg_connection *c) {
  8562. struct tls_data *tls = c->tls;
  8563. switch (tls->state) {
  8564. case MG_TLS_HS_CLIENT_HELLO:
  8565. if (mg_tls_client_hello(c) < 0) {
  8566. return;
  8567. }
  8568. tls->state = MG_TLS_HS_SERVER_HELLO;
  8569. // fallthrough
  8570. case MG_TLS_HS_SERVER_HELLO:
  8571. mg_tls_server_hello(c);
  8572. mg_tls_generate_handshake_keys(c);
  8573. mg_tls_server_extensions(c);
  8574. mg_tls_server_cert(c);
  8575. mg_tls_server_verify_ecdsa(c);
  8576. mg_tls_server_finish(c);
  8577. tls->state = MG_TLS_HS_CLIENT_CHANGE_CIPHER;
  8578. // fallthrough
  8579. case MG_TLS_HS_CLIENT_CHANGE_CIPHER:
  8580. if (mg_tls_client_change_cipher(c) < 0) {
  8581. return;
  8582. }
  8583. tls->state = MG_TLS_HS_CLIENT_FINISH;
  8584. // fallthrough
  8585. case MG_TLS_HS_CLIENT_FINISH:
  8586. if (mg_tls_client_finish(c) < 0) {
  8587. return;
  8588. }
  8589. mg_tls_generate_application_keys(c);
  8590. tls->state = MG_TLS_HS_DONE;
  8591. // fallthrough
  8592. case MG_TLS_HS_DONE: c->is_tls_hs = 0; return;
  8593. }
  8594. }
  8595. static int mg_parse_pem(const struct mg_str pem, const struct mg_str label,
  8596. struct mg_str *der) {
  8597. size_t n = 0, m = 0;
  8598. char *s;
  8599. const char *c;
  8600. struct mg_str caps[5];
  8601. if (!mg_match(pem, mg_str("#-----BEGIN #-----#-----END #-----#"), caps)) {
  8602. *der = mg_strdup(pem);
  8603. return 0;
  8604. }
  8605. if (mg_strcmp(caps[1], label) != 0 || mg_strcmp(caps[3], label) != 0) {
  8606. return -1; // bad label
  8607. }
  8608. if ((s = calloc(1, caps[2].len)) == NULL) {
  8609. return -1;
  8610. }
  8611. for (c = caps[2].ptr; c < caps[2].ptr + caps[2].len; c++) {
  8612. if (*c == ' ' || *c == '\n' || *c == '\r' || *c == '\t') {
  8613. continue;
  8614. }
  8615. s[n++] = *c;
  8616. }
  8617. m = mg_base64_decode(s, n, s, n);
  8618. if (m == 0) {
  8619. free(s);
  8620. return -1;
  8621. }
  8622. der->ptr = s;
  8623. der->len = m;
  8624. return 0;
  8625. }
  8626. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8627. struct mg_str key;
  8628. struct tls_data *tls = (struct tls_data *) calloc(1, sizeof(struct tls_data));
  8629. if (tls == NULL) {
  8630. mg_error(c, "tls oom");
  8631. return;
  8632. }
  8633. // parse PEM or DER EC key
  8634. if (opts->key.ptr == NULL ||
  8635. mg_parse_pem(opts->key, mg_str_s("EC PRIVATE KEY"), &key) < 0) {
  8636. MG_ERROR(("Failed to load EC private key"));
  8637. return;
  8638. }
  8639. if (key.len < 39) {
  8640. MG_ERROR(("EC private key too short"));
  8641. return;
  8642. }
  8643. // expect ASN.1 SEQUENCE=[INTEGER=1, BITSTRING of 32 bytes, ...]
  8644. // 30 nn 02 01 01 04 20 [key] ...
  8645. if (key.ptr[0] != 0x30 || (key.ptr[1] & 0x80) != 0) {
  8646. MG_ERROR(("EC private key: ASN.1 bad sequence"));
  8647. return;
  8648. }
  8649. if (memcmp(key.ptr + 2, "\x02\x01\x01\x04\x20", 5) != 0) {
  8650. MG_ERROR(("EC private key: ASN.1 bad data"));
  8651. }
  8652. memmove(tls->server_key, key.ptr + 7, 32);
  8653. free((void *) key.ptr);
  8654. // parse PEM or DER certificate
  8655. if (mg_parse_pem(opts->cert, mg_str_s("CERTIFICATE"), &tls->server_cert_der) <
  8656. 0) {
  8657. MG_ERROR(("Failed to load certificate"));
  8658. return;
  8659. }
  8660. // tls->send.align = tls->recv.align = MG_IO_SIZE;
  8661. tls->send.align = MG_IO_SIZE;
  8662. c->tls = tls;
  8663. c->is_tls = c->is_tls_hs = 1;
  8664. mg_sha256_init(&tls->sha256);
  8665. }
  8666. void mg_tls_free(struct mg_connection *c) {
  8667. struct tls_data *tls = c->tls;
  8668. if (tls != NULL) {
  8669. mg_iobuf_free(&tls->send);
  8670. free((void *) tls->server_cert_der.ptr);
  8671. }
  8672. free(c->tls);
  8673. c->tls = NULL;
  8674. }
  8675. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8676. struct tls_data *tls = c->tls;
  8677. long n = MG_IO_WAIT;
  8678. if (len > MG_IO_SIZE) len = MG_IO_SIZE;
  8679. mg_tls_encrypt(c, buf, len, 0x17);
  8680. while (tls->send.len > 0 &&
  8681. (n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {
  8682. mg_iobuf_del(&tls->send, 0, (size_t) n);
  8683. }
  8684. if (n == MG_IO_ERR || n == MG_IO_WAIT) return n;
  8685. return (long) len;
  8686. }
  8687. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8688. return mg_tls_recv_decrypt(c, buf, len);
  8689. }
  8690. size_t mg_tls_pending(struct mg_connection *c) {
  8691. return mg_tls_got_msg(c) ? 1 : 0;
  8692. }
  8693. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8694. (void) mgr;
  8695. }
  8696. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8697. (void) mgr;
  8698. }
  8699. #endif
  8700. #ifdef MG_ENABLE_LINES
  8701. #line 1 "src/tls_dummy.c"
  8702. #endif
  8703. #if MG_TLS == MG_TLS_NONE
  8704. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8705. (void) opts;
  8706. mg_error(c, "TLS is not enabled");
  8707. }
  8708. void mg_tls_handshake(struct mg_connection *c) {
  8709. (void) c;
  8710. }
  8711. void mg_tls_free(struct mg_connection *c) {
  8712. (void) c;
  8713. }
  8714. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8715. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  8716. }
  8717. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8718. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  8719. }
  8720. size_t mg_tls_pending(struct mg_connection *c) {
  8721. (void) c;
  8722. return 0;
  8723. }
  8724. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8725. (void) mgr;
  8726. }
  8727. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8728. (void) mgr;
  8729. }
  8730. #endif
  8731. #ifdef MG_ENABLE_LINES
  8732. #line 1 "src/tls_mbed.c"
  8733. #endif
  8734. #if MG_TLS == MG_TLS_MBED
  8735. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000
  8736. #define MG_MBEDTLS_RNG_GET , mg_mbed_rng, NULL
  8737. #else
  8738. #define MG_MBEDTLS_RNG_GET
  8739. #endif
  8740. static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) {
  8741. mg_random(buf, len);
  8742. (void) ctx;
  8743. return 0;
  8744. }
  8745. static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *p) {
  8746. int rc;
  8747. if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true;
  8748. if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL
  8749. if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.ptr, str.len)) != 0) {
  8750. MG_ERROR(("cert err %#x", -rc));
  8751. return false;
  8752. }
  8753. return true;
  8754. }
  8755. static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) {
  8756. int rc;
  8757. if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true;
  8758. if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL
  8759. if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.ptr, str.len, NULL,
  8760. 0 MG_MBEDTLS_RNG_GET)) != 0) {
  8761. MG_ERROR(("key err %#x", -rc));
  8762. return false;
  8763. }
  8764. return true;
  8765. }
  8766. void mg_tls_free(struct mg_connection *c) {
  8767. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8768. if (tls != NULL) {
  8769. mbedtls_ssl_free(&tls->ssl);
  8770. mbedtls_pk_free(&tls->pk);
  8771. mbedtls_x509_crt_free(&tls->ca);
  8772. mbedtls_x509_crt_free(&tls->cert);
  8773. mbedtls_ssl_config_free(&tls->conf);
  8774. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8775. mbedtls_ssl_ticket_free(&tls->ticket);
  8776. #endif
  8777. free(tls);
  8778. c->tls = NULL;
  8779. }
  8780. }
  8781. static int mg_net_send(void *ctx, const unsigned char *buf, size_t len) {
  8782. long n = mg_io_send((struct mg_connection *) ctx, buf, len);
  8783. MG_VERBOSE(("%lu n=%ld e=%d", ((struct mg_connection *) ctx)->id, n, errno));
  8784. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  8785. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  8786. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_SEND_FAILED;
  8787. return (int) n;
  8788. }
  8789. static int mg_net_recv(void *ctx, unsigned char *buf, size_t len) {
  8790. long n = mg_io_recv((struct mg_connection *) ctx, buf, len);
  8791. MG_VERBOSE(("%lu n=%ld", ((struct mg_connection *) ctx)->id, n));
  8792. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  8793. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  8794. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_RECV_FAILED;
  8795. return (int) n;
  8796. }
  8797. void mg_tls_handshake(struct mg_connection *c) {
  8798. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8799. int rc = mbedtls_ssl_handshake(&tls->ssl);
  8800. if (rc == 0) { // Success
  8801. MG_DEBUG(("%lu success", c->id));
  8802. c->is_tls_hs = 0;
  8803. mg_call(c, MG_EV_TLS_HS, NULL);
  8804. } else if (rc == MBEDTLS_ERR_SSL_WANT_READ ||
  8805. rc == MBEDTLS_ERR_SSL_WANT_WRITE) { // Still pending
  8806. MG_VERBOSE(("%lu pending, %d%d %d (-%#x)", c->id, c->is_connecting,
  8807. c->is_tls_hs, rc, -rc));
  8808. } else {
  8809. mg_error(c, "TLS handshake: -%#x", -rc); // Error
  8810. }
  8811. }
  8812. static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) {
  8813. n = (int) strlen(s2) - 1;
  8814. MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2));
  8815. (void) s;
  8816. }
  8817. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8818. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  8819. int rc = 0;
  8820. c->tls = tls;
  8821. if (c->tls == NULL) {
  8822. mg_error(c, "TLS OOM");
  8823. goto fail;
  8824. }
  8825. if (c->is_listening) goto fail;
  8826. MG_DEBUG(("%lu Setting TLS", c->id));
  8827. MG_PROF_ADD(c, "mbedtls_init_start");
  8828. mbedtls_ssl_init(&tls->ssl);
  8829. mbedtls_ssl_config_init(&tls->conf);
  8830. mbedtls_x509_crt_init(&tls->ca);
  8831. mbedtls_x509_crt_init(&tls->cert);
  8832. mbedtls_pk_init(&tls->pk);
  8833. mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c);
  8834. #if defined(MG_MBEDTLS_DEBUG_LEVEL)
  8835. mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL);
  8836. #endif
  8837. if ((rc = mbedtls_ssl_config_defaults(
  8838. &tls->conf,
  8839. c->is_client ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
  8840. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  8841. mg_error(c, "tls defaults %#x", -rc);
  8842. goto fail;
  8843. }
  8844. mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c);
  8845. if (opts->ca.len == 0 || mg_vcmp(&opts->ca, "*") == 0) {
  8846. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
  8847. } else {
  8848. if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail;
  8849. mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL);
  8850. if (c->is_client && opts->name.ptr != NULL && opts->name.ptr[0] != '\0') {
  8851. char *host = mg_mprintf("%.*s", opts->name.len, opts->name.ptr);
  8852. mbedtls_ssl_set_hostname(&tls->ssl, host);
  8853. MG_DEBUG(("%lu hostname verification: %s", c->id, host));
  8854. free(host);
  8855. }
  8856. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  8857. }
  8858. if (!mg_load_cert(opts->cert, &tls->cert)) goto fail;
  8859. if (!mg_load_key(opts->key, &tls->pk)) goto fail;
  8860. if (tls->cert.version &&
  8861. (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) {
  8862. mg_error(c, "own cert %#x", -rc);
  8863. goto fail;
  8864. }
  8865. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8866. mbedtls_ssl_conf_session_tickets_cb(
  8867. &tls->conf, mbedtls_ssl_ticket_write, mbedtls_ssl_ticket_parse,
  8868. &((struct mg_tls_ctx *) c->mgr->tls_ctx)->tickets);
  8869. #endif
  8870. if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) {
  8871. mg_error(c, "setup err %#x", -rc);
  8872. goto fail;
  8873. }
  8874. c->is_tls = 1;
  8875. c->is_tls_hs = 1;
  8876. mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0);
  8877. MG_PROF_ADD(c, "mbedtls_init_end");
  8878. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  8879. mg_tls_handshake(c);
  8880. }
  8881. return;
  8882. fail:
  8883. mg_tls_free(c);
  8884. }
  8885. size_t mg_tls_pending(struct mg_connection *c) {
  8886. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8887. return tls == NULL ? 0 : mbedtls_ssl_get_bytes_avail(&tls->ssl);
  8888. }
  8889. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8890. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8891. long n = mbedtls_ssl_read(&tls->ssl, (unsigned char *) buf, len);
  8892. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  8893. return MG_IO_WAIT;
  8894. if (n <= 0) return MG_IO_ERR;
  8895. return n;
  8896. }
  8897. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8898. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8899. long n = mbedtls_ssl_write(&tls->ssl, (unsigned char *) buf, len);
  8900. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  8901. return MG_IO_WAIT;
  8902. if (n <= 0) return MG_IO_ERR;
  8903. return n;
  8904. }
  8905. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8906. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx));
  8907. if (ctx == NULL) {
  8908. MG_ERROR(("TLS context init OOM"));
  8909. } else {
  8910. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8911. int rc;
  8912. mbedtls_ssl_ticket_init(&ctx->tickets);
  8913. if ((rc = mbedtls_ssl_ticket_setup(&ctx->tickets, mg_mbed_rng, NULL,
  8914. MBEDTLS_CIPHER_AES_128_GCM, 86400)) !=
  8915. 0) {
  8916. MG_ERROR((" mbedtls_ssl_ticket_setup %#x", -rc));
  8917. }
  8918. #endif
  8919. mgr->tls_ctx = ctx;
  8920. }
  8921. }
  8922. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8923. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx;
  8924. if (ctx != NULL) {
  8925. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8926. mbedtls_ssl_ticket_free(&ctx->tickets);
  8927. #endif
  8928. free(ctx);
  8929. mgr->tls_ctx = NULL;
  8930. }
  8931. }
  8932. #endif
  8933. #ifdef MG_ENABLE_LINES
  8934. #line 1 "src/tls_openssl.c"
  8935. #endif
  8936. #if MG_TLS == MG_TLS_OPENSSL
  8937. static int tls_err_cb(const char *s, size_t len, void *c) {
  8938. int n = (int) len - 1;
  8939. MG_ERROR(("%lu %.*s", ((struct mg_connection *) c)->id, n, s));
  8940. return 0; // undocumented
  8941. }
  8942. static int mg_tls_err(struct mg_connection *c, struct mg_tls *tls, int res) {
  8943. int err = SSL_get_error(tls->ssl, res);
  8944. // We've just fetched the last error from the queue.
  8945. // Now we need to clear the error queue. If we do not, then the following
  8946. // can happen (actually reported):
  8947. // - A new connection is accept()-ed with cert error (e.g. self-signed cert)
  8948. // - Since all accept()-ed connections share listener's context,
  8949. // - *ALL* SSL accepted connection report read error on the next poll cycle.
  8950. // Thus a single errored connection can close all the rest, unrelated ones.
  8951. // Clearing the error keeps the shared SSL_CTX in an OK state.
  8952. if (err != 0) ERR_print_errors_cb(tls_err_cb, c);
  8953. ERR_clear_error();
  8954. if (err == SSL_ERROR_WANT_READ) return 0;
  8955. if (err == SSL_ERROR_WANT_WRITE) return 0;
  8956. return err;
  8957. }
  8958. static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) {
  8959. BIO *bio = BIO_new_mem_buf(ca.ptr, (int) ca.len);
  8960. STACK_OF(X509_INFO) *certs =
  8961. bio ? PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL) : NULL;
  8962. if (bio) BIO_free(bio);
  8963. return certs;
  8964. }
  8965. static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) {
  8966. X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx);
  8967. for (int i = 0; i < sk_X509_INFO_num(certs); i++) {
  8968. X509_INFO *cert_info = sk_X509_INFO_value(certs, i);
  8969. if (cert_info->x509 && !X509_STORE_add_cert(cert_store, cert_info->x509))
  8970. return false;
  8971. }
  8972. return true;
  8973. }
  8974. static EVP_PKEY *load_key(struct mg_str s) {
  8975. BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len);
  8976. EVP_PKEY *key = bio ? PEM_read_bio_PrivateKey(bio, NULL, 0, NULL) : NULL;
  8977. if (bio) BIO_free(bio);
  8978. return key;
  8979. }
  8980. static X509 *load_cert(struct mg_str s) {
  8981. BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len);
  8982. X509 *cert = bio == NULL ? NULL
  8983. : s.ptr[0] == '-'
  8984. ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM
  8985. : d2i_X509_bio(bio, NULL); // DER
  8986. if (bio) BIO_free(bio);
  8987. return cert;
  8988. }
  8989. static long mg_bio_ctrl(BIO *b, int cmd, long larg, void *pargs) {
  8990. long ret = 0;
  8991. if (cmd == BIO_CTRL_PUSH) ret = 1;
  8992. if (cmd == BIO_CTRL_POP) ret = 1;
  8993. if (cmd == BIO_CTRL_FLUSH) ret = 1;
  8994. if (cmd == BIO_C_SET_NBIO) ret = 1;
  8995. // MG_DEBUG(("%d -> %ld", cmd, ret));
  8996. (void) b, (void) cmd, (void) larg, (void) pargs;
  8997. return ret;
  8998. }
  8999. static int mg_bio_read(BIO *bio, char *buf, int len) {
  9000. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  9001. long res = mg_io_recv(c, buf, (size_t) len);
  9002. // MG_DEBUG(("%p %d %ld", buf, len, res));
  9003. len = res > 0 ? (int) res : -1;
  9004. if (res == MG_IO_WAIT) BIO_set_retry_read(bio);
  9005. return len;
  9006. }
  9007. static int mg_bio_write(BIO *bio, const char *buf, int len) {
  9008. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  9009. long res = mg_io_send(c, buf, (size_t) len);
  9010. // MG_DEBUG(("%p %d %ld", buf, len, res));
  9011. len = res > 0 ? (int) res : -1;
  9012. if (res == MG_IO_WAIT) BIO_set_retry_write(bio);
  9013. return len;
  9014. }
  9015. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9016. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  9017. const char *id = "mongoose";
  9018. static unsigned char s_initialised = 0;
  9019. BIO *bio = NULL;
  9020. int rc;
  9021. if (tls == NULL) {
  9022. mg_error(c, "TLS OOM");
  9023. goto fail;
  9024. }
  9025. if (!s_initialised) {
  9026. SSL_library_init();
  9027. s_initialised++;
  9028. }
  9029. MG_DEBUG(("%lu Setting TLS", c->id));
  9030. tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method())
  9031. : SSL_CTX_new(SSLv23_server_method());
  9032. if ((tls->ssl = SSL_new(tls->ctx)) == NULL) {
  9033. mg_error(c, "SSL_new");
  9034. goto fail;
  9035. }
  9036. SSL_set_session_id_context(tls->ssl, (const uint8_t *) id,
  9037. (unsigned) strlen(id));
  9038. // Disable deprecated protocols
  9039. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2);
  9040. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3);
  9041. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1);
  9042. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1);
  9043. #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION
  9044. SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION);
  9045. #endif
  9046. #ifdef MG_ENABLE_OPENSSL_CIPHER_SERVER_PREFERENCE
  9047. SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
  9048. #endif
  9049. if (opts->ca.ptr != NULL && opts->ca.ptr[0] != '\0') {
  9050. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9051. NULL);
  9052. STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca);
  9053. rc = add_ca_certs(tls->ctx, certs);
  9054. sk_X509_INFO_pop_free(certs, X509_INFO_free);
  9055. if (!rc) {
  9056. mg_error(c, "CA err");
  9057. goto fail;
  9058. }
  9059. }
  9060. if (opts->cert.ptr != NULL && opts->cert.ptr[0] != '\0') {
  9061. X509 *cert = load_cert(opts->cert);
  9062. rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert);
  9063. X509_free(cert);
  9064. if (cert == NULL || rc != 1) {
  9065. mg_error(c, "CERT err %d", mg_tls_err(c, tls, rc));
  9066. goto fail;
  9067. }
  9068. }
  9069. if (opts->key.ptr != NULL && opts->key.ptr[0] != '\0') {
  9070. EVP_PKEY *key = load_key(opts->key);
  9071. rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key);
  9072. EVP_PKEY_free(key);
  9073. if (key == NULL || rc != 1) {
  9074. mg_error(c, "KEY err %d", mg_tls_err(c, tls, rc));
  9075. goto fail;
  9076. }
  9077. }
  9078. SSL_set_mode(tls->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  9079. #if OPENSSL_VERSION_NUMBER > 0x10002000L
  9080. (void) SSL_set_ecdh_auto(tls->ssl, 1);
  9081. #endif
  9082. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  9083. if (opts->name.len > 0) {
  9084. char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.ptr);
  9085. SSL_set1_host(tls->ssl, s);
  9086. SSL_set_tlsext_host_name(tls->ssl, s);
  9087. free(s);
  9088. }
  9089. #endif
  9090. tls->bm = BIO_meth_new(BIO_get_new_index() | BIO_TYPE_SOURCE_SINK, "bio_mg");
  9091. BIO_meth_set_write(tls->bm, mg_bio_write);
  9092. BIO_meth_set_read(tls->bm, mg_bio_read);
  9093. BIO_meth_set_ctrl(tls->bm, mg_bio_ctrl);
  9094. bio = BIO_new(tls->bm);
  9095. BIO_set_data(bio, c);
  9096. SSL_set_bio(tls->ssl, bio, bio);
  9097. c->tls = tls;
  9098. c->is_tls = 1;
  9099. c->is_tls_hs = 1;
  9100. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  9101. mg_tls_handshake(c);
  9102. }
  9103. MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client"));
  9104. return;
  9105. fail:
  9106. free(tls);
  9107. }
  9108. void mg_tls_handshake(struct mg_connection *c) {
  9109. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9110. int rc = c->is_client ? SSL_connect(tls->ssl) : SSL_accept(tls->ssl);
  9111. if (rc == 1) {
  9112. MG_DEBUG(("%lu success", c->id));
  9113. c->is_tls_hs = 0;
  9114. mg_call(c, MG_EV_TLS_HS, NULL);
  9115. } else {
  9116. int code = mg_tls_err(c, tls, rc);
  9117. if (code != 0) mg_error(c, "tls hs: rc %d, err %d", rc, code);
  9118. }
  9119. }
  9120. void mg_tls_free(struct mg_connection *c) {
  9121. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9122. if (tls == NULL) return;
  9123. SSL_free(tls->ssl);
  9124. SSL_CTX_free(tls->ctx);
  9125. BIO_meth_free(tls->bm);
  9126. free(tls);
  9127. c->tls = NULL;
  9128. }
  9129. size_t mg_tls_pending(struct mg_connection *c) {
  9130. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9131. return tls == NULL ? 0 : (size_t) SSL_pending(tls->ssl);
  9132. }
  9133. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9134. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9135. int n = SSL_read(tls->ssl, buf, (int) len);
  9136. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  9137. if (n <= 0) return MG_IO_ERR;
  9138. return n;
  9139. }
  9140. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9141. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9142. int n = SSL_write(tls->ssl, buf, (int) len);
  9143. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  9144. if (n <= 0) return MG_IO_ERR;
  9145. return n;
  9146. }
  9147. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9148. (void) mgr;
  9149. }
  9150. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9151. (void) mgr;
  9152. }
  9153. #endif
  9154. #ifdef MG_ENABLE_LINES
  9155. #line 1 "src/tls_uecc.c"
  9156. #endif
  9157. /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  9158. #if MG_TLS == MG_TLS_BUILTIN
  9159. #ifndef uECC_RNG_MAX_TRIES
  9160. #define uECC_RNG_MAX_TRIES 64
  9161. #endif
  9162. #if uECC_ENABLE_VLI_API
  9163. #define uECC_VLI_API
  9164. #else
  9165. #define uECC_VLI_API static
  9166. #endif
  9167. #if (uECC_PLATFORM == uECC_avr) || (uECC_PLATFORM == uECC_arm) || \
  9168. (uECC_PLATFORM == uECC_arm_thumb) || (uECC_PLATFORM == uECC_arm_thumb2)
  9169. #define CONCATX(a, ...) a##__VA_ARGS__
  9170. #define CONCAT(a, ...) CONCATX(a, __VA_ARGS__)
  9171. #define STRX(a) #a
  9172. #define STR(a) STRX(a)
  9173. #define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__))))
  9174. #define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__))))
  9175. #define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__))))
  9176. #define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__))))
  9177. #define EVAL4(...) __VA_ARGS__
  9178. #define DEC_1 0
  9179. #define DEC_2 1
  9180. #define DEC_3 2
  9181. #define DEC_4 3
  9182. #define DEC_5 4
  9183. #define DEC_6 5
  9184. #define DEC_7 6
  9185. #define DEC_8 7
  9186. #define DEC_9 8
  9187. #define DEC_10 9
  9188. #define DEC_11 10
  9189. #define DEC_12 11
  9190. #define DEC_13 12
  9191. #define DEC_14 13
  9192. #define DEC_15 14
  9193. #define DEC_16 15
  9194. #define DEC_17 16
  9195. #define DEC_18 17
  9196. #define DEC_19 18
  9197. #define DEC_20 19
  9198. #define DEC_21 20
  9199. #define DEC_22 21
  9200. #define DEC_23 22
  9201. #define DEC_24 23
  9202. #define DEC_25 24
  9203. #define DEC_26 25
  9204. #define DEC_27 26
  9205. #define DEC_28 27
  9206. #define DEC_29 28
  9207. #define DEC_30 29
  9208. #define DEC_31 30
  9209. #define DEC_32 31
  9210. #define DEC(N) CONCAT(DEC_, N)
  9211. #define SECOND_ARG(_, val, ...) val
  9212. #define SOME_CHECK_0 ~, 0
  9213. #define GET_SECOND_ARG(...) SECOND_ARG(__VA_ARGS__, SOME, )
  9214. #define SOME_OR_0(N) GET_SECOND_ARG(CONCAT(SOME_CHECK_, N))
  9215. #define EMPTY(...)
  9216. #define DEFER(...) __VA_ARGS__ EMPTY()
  9217. #define REPEAT_NAME_0() REPEAT_0
  9218. #define REPEAT_NAME_SOME() REPEAT_SOME
  9219. #define REPEAT_0(...)
  9220. #define REPEAT_SOME(N, stuff) \
  9221. DEFER(CONCAT(REPEAT_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), stuff) stuff
  9222. #define REPEAT(N, stuff) EVAL(REPEAT_SOME(N, stuff))
  9223. #define REPEATM_NAME_0() REPEATM_0
  9224. #define REPEATM_NAME_SOME() REPEATM_SOME
  9225. #define REPEATM_0(...)
  9226. #define REPEATM_SOME(N, macro) \
  9227. macro(N) DEFER(CONCAT(REPEATM_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), macro)
  9228. #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro))
  9229. #endif
  9230. //
  9231. #if (uECC_WORD_SIZE == 1)
  9232. #if uECC_SUPPORTS_secp160r1
  9233. #define uECC_MAX_WORDS 21 /* Due to the size of curve_n. */
  9234. #endif
  9235. #if uECC_SUPPORTS_secp192r1
  9236. #undef uECC_MAX_WORDS
  9237. #define uECC_MAX_WORDS 24
  9238. #endif
  9239. #if uECC_SUPPORTS_secp224r1
  9240. #undef uECC_MAX_WORDS
  9241. #define uECC_MAX_WORDS 28
  9242. #endif
  9243. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9244. #undef uECC_MAX_WORDS
  9245. #define uECC_MAX_WORDS 32
  9246. #endif
  9247. #elif (uECC_WORD_SIZE == 4)
  9248. #if uECC_SUPPORTS_secp160r1
  9249. #define uECC_MAX_WORDS 6 /* Due to the size of curve_n. */
  9250. #endif
  9251. #if uECC_SUPPORTS_secp192r1
  9252. #undef uECC_MAX_WORDS
  9253. #define uECC_MAX_WORDS 6
  9254. #endif
  9255. #if uECC_SUPPORTS_secp224r1
  9256. #undef uECC_MAX_WORDS
  9257. #define uECC_MAX_WORDS 7
  9258. #endif
  9259. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9260. #undef uECC_MAX_WORDS
  9261. #define uECC_MAX_WORDS 8
  9262. #endif
  9263. #elif (uECC_WORD_SIZE == 8)
  9264. #if uECC_SUPPORTS_secp160r1
  9265. #define uECC_MAX_WORDS 3
  9266. #endif
  9267. #if uECC_SUPPORTS_secp192r1
  9268. #undef uECC_MAX_WORDS
  9269. #define uECC_MAX_WORDS 3
  9270. #endif
  9271. #if uECC_SUPPORTS_secp224r1
  9272. #undef uECC_MAX_WORDS
  9273. #define uECC_MAX_WORDS 4
  9274. #endif
  9275. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9276. #undef uECC_MAX_WORDS
  9277. #define uECC_MAX_WORDS 4
  9278. #endif
  9279. #endif /* uECC_WORD_SIZE */
  9280. #define BITS_TO_WORDS(num_bits) \
  9281. ((wordcount_t) ((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / \
  9282. (uECC_WORD_SIZE * 8)))
  9283. #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
  9284. struct uECC_Curve_t {
  9285. wordcount_t num_words;
  9286. wordcount_t num_bytes;
  9287. bitcount_t num_n_bits;
  9288. uECC_word_t p[uECC_MAX_WORDS];
  9289. uECC_word_t n[uECC_MAX_WORDS];
  9290. uECC_word_t G[uECC_MAX_WORDS * 2];
  9291. uECC_word_t b[uECC_MAX_WORDS];
  9292. void (*double_jacobian)(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *Z1,
  9293. uECC_Curve curve);
  9294. #if uECC_SUPPORT_COMPRESSED_POINT
  9295. void (*mod_sqrt)(uECC_word_t *a, uECC_Curve curve);
  9296. #endif
  9297. void (*x_side)(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve);
  9298. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9299. void (*mmod_fast)(uECC_word_t *result, uECC_word_t *product);
  9300. #endif
  9301. };
  9302. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  9303. static void bcopy(uint8_t *dst, const uint8_t *src, unsigned num_bytes) {
  9304. while (0 != num_bytes) {
  9305. num_bytes--;
  9306. dst[num_bytes] = src[num_bytes];
  9307. }
  9308. }
  9309. #endif
  9310. static cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
  9311. const uECC_word_t *right,
  9312. wordcount_t num_words);
  9313. #if (uECC_PLATFORM == uECC_arm || uECC_PLATFORM == uECC_arm_thumb || \
  9314. uECC_PLATFORM == uECC_arm_thumb2)
  9315. #endif
  9316. #if (uECC_PLATFORM == uECC_avr)
  9317. #endif
  9318. #ifndef asm_clear
  9319. #define asm_clear 0
  9320. #endif
  9321. #ifndef asm_set
  9322. #define asm_set 0
  9323. #endif
  9324. #ifndef asm_add
  9325. #define asm_add 0
  9326. #endif
  9327. #ifndef asm_sub
  9328. #define asm_sub 0
  9329. #endif
  9330. #ifndef asm_mult
  9331. #define asm_mult 0
  9332. #endif
  9333. #ifndef asm_rshift1
  9334. #define asm_rshift1 0
  9335. #endif
  9336. #ifndef asm_mmod_fast_secp256r1
  9337. #define asm_mmod_fast_secp256r1 0
  9338. #endif
  9339. #if defined(default_RNG_defined) && default_RNG_defined
  9340. static uECC_RNG_Function g_rng_function = &default_RNG;
  9341. #else
  9342. static uECC_RNG_Function g_rng_function = 0;
  9343. #endif
  9344. void uECC_set_rng(uECC_RNG_Function rng_function) {
  9345. g_rng_function = rng_function;
  9346. }
  9347. uECC_RNG_Function uECC_get_rng(void) {
  9348. return g_rng_function;
  9349. }
  9350. int uECC_curve_private_key_size(uECC_Curve curve) {
  9351. return BITS_TO_BYTES(curve->num_n_bits);
  9352. }
  9353. int uECC_curve_public_key_size(uECC_Curve curve) {
  9354. return 2 * curve->num_bytes;
  9355. }
  9356. #if !asm_clear
  9357. uECC_VLI_API void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words) {
  9358. wordcount_t i;
  9359. for (i = 0; i < num_words; ++i) {
  9360. vli[i] = 0;
  9361. }
  9362. }
  9363. #endif /* !asm_clear */
  9364. /* Constant-time comparison to zero - secure way to compare long integers */
  9365. /* Returns 1 if vli == 0, 0 otherwise. */
  9366. uECC_VLI_API uECC_word_t uECC_vli_isZero(const uECC_word_t *vli,
  9367. wordcount_t num_words) {
  9368. uECC_word_t bits = 0;
  9369. wordcount_t i;
  9370. for (i = 0; i < num_words; ++i) {
  9371. bits |= vli[i];
  9372. }
  9373. return (bits == 0);
  9374. }
  9375. /* Returns nonzero if bit 'bit' of vli is set. */
  9376. uECC_VLI_API uECC_word_t uECC_vli_testBit(const uECC_word_t *vli,
  9377. bitcount_t bit) {
  9378. return (vli[bit >> uECC_WORD_BITS_SHIFT] &
  9379. ((uECC_word_t) 1 << (bit & uECC_WORD_BITS_MASK)));
  9380. }
  9381. /* Counts the number of words in vli. */
  9382. static wordcount_t vli_numDigits(const uECC_word_t *vli,
  9383. const wordcount_t max_words) {
  9384. wordcount_t i;
  9385. /* Search from the end until we find a non-zero digit.
  9386. We do it in reverse because we expect that most digits will be nonzero. */
  9387. for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
  9388. }
  9389. return (i + 1);
  9390. }
  9391. /* Counts the number of bits required to represent vli. */
  9392. uECC_VLI_API bitcount_t uECC_vli_numBits(const uECC_word_t *vli,
  9393. const wordcount_t max_words) {
  9394. uECC_word_t i;
  9395. uECC_word_t digit;
  9396. wordcount_t num_digits = vli_numDigits(vli, max_words);
  9397. if (num_digits == 0) {
  9398. return 0;
  9399. }
  9400. digit = vli[num_digits - 1];
  9401. for (i = 0; digit; ++i) {
  9402. digit >>= 1;
  9403. }
  9404. return (((bitcount_t) ((num_digits - 1) << uECC_WORD_BITS_SHIFT)) +
  9405. (bitcount_t) i);
  9406. }
  9407. /* Sets dest = src. */
  9408. #if !asm_set
  9409. uECC_VLI_API void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src,
  9410. wordcount_t num_words) {
  9411. wordcount_t i;
  9412. for (i = 0; i < num_words; ++i) {
  9413. dest[i] = src[i];
  9414. }
  9415. }
  9416. #endif /* !asm_set */
  9417. /* Returns sign of left - right. */
  9418. static cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
  9419. const uECC_word_t *right,
  9420. wordcount_t num_words) {
  9421. wordcount_t i;
  9422. for (i = num_words - 1; i >= 0; --i) {
  9423. if (left[i] > right[i]) {
  9424. return 1;
  9425. } else if (left[i] < right[i]) {
  9426. return -1;
  9427. }
  9428. }
  9429. return 0;
  9430. }
  9431. /* Constant-time comparison function - secure way to compare long integers */
  9432. /* Returns one if left == right, zero otherwise. */
  9433. uECC_VLI_API uECC_word_t uECC_vli_equal(const uECC_word_t *left,
  9434. const uECC_word_t *right,
  9435. wordcount_t num_words) {
  9436. uECC_word_t diff = 0;
  9437. wordcount_t i;
  9438. for (i = num_words - 1; i >= 0; --i) {
  9439. diff |= (left[i] ^ right[i]);
  9440. }
  9441. return (diff == 0);
  9442. }
  9443. uECC_VLI_API uECC_word_t uECC_vli_sub(uECC_word_t *result,
  9444. const uECC_word_t *left,
  9445. const uECC_word_t *right,
  9446. wordcount_t num_words);
  9447. /* Returns sign of left - right, in constant time. */
  9448. uECC_VLI_API cmpresult_t uECC_vli_cmp(const uECC_word_t *left,
  9449. const uECC_word_t *right,
  9450. wordcount_t num_words) {
  9451. uECC_word_t tmp[uECC_MAX_WORDS];
  9452. uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words);
  9453. uECC_word_t equal = uECC_vli_isZero(tmp, num_words);
  9454. return (cmpresult_t) (!equal - 2 * neg);
  9455. }
  9456. /* Computes vli = vli >> 1. */
  9457. #if !asm_rshift1
  9458. uECC_VLI_API void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words) {
  9459. uECC_word_t *end = vli;
  9460. uECC_word_t carry = 0;
  9461. vli += num_words;
  9462. while (vli-- > end) {
  9463. uECC_word_t temp = *vli;
  9464. *vli = (temp >> 1) | carry;
  9465. carry = temp << (uECC_WORD_BITS - 1);
  9466. }
  9467. }
  9468. #endif /* !asm_rshift1 */
  9469. /* Computes result = left + right, returning carry. Can modify in place. */
  9470. #if !asm_add
  9471. uECC_VLI_API uECC_word_t uECC_vli_add(uECC_word_t *result,
  9472. const uECC_word_t *left,
  9473. const uECC_word_t *right,
  9474. wordcount_t num_words) {
  9475. uECC_word_t carry = 0;
  9476. wordcount_t i;
  9477. for (i = 0; i < num_words; ++i) {
  9478. uECC_word_t sum = left[i] + right[i] + carry;
  9479. if (sum != left[i]) {
  9480. carry = (sum < left[i]);
  9481. }
  9482. result[i] = sum;
  9483. }
  9484. return carry;
  9485. }
  9486. #endif /* !asm_add */
  9487. /* Computes result = left - right, returning borrow. Can modify in place. */
  9488. #if !asm_sub
  9489. uECC_VLI_API uECC_word_t uECC_vli_sub(uECC_word_t *result,
  9490. const uECC_word_t *left,
  9491. const uECC_word_t *right,
  9492. wordcount_t num_words) {
  9493. uECC_word_t borrow = 0;
  9494. wordcount_t i;
  9495. for (i = 0; i < num_words; ++i) {
  9496. uECC_word_t diff = left[i] - right[i] - borrow;
  9497. if (diff != left[i]) {
  9498. borrow = (diff > left[i]);
  9499. }
  9500. result[i] = diff;
  9501. }
  9502. return borrow;
  9503. }
  9504. #endif /* !asm_sub */
  9505. #if !asm_mult || (uECC_SQUARE_FUNC && !asm_square) || \
  9506. (uECC_SUPPORTS_secp256k1 && (uECC_OPTIMIZATION_LEVEL > 0) && \
  9507. ((uECC_WORD_SIZE == 1) || (uECC_WORD_SIZE == 8)))
  9508. static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
  9509. uECC_word_t *r1, uECC_word_t *r2) {
  9510. #if uECC_WORD_SIZE == 8
  9511. uint64_t a0 = a & 0xffffffff;
  9512. uint64_t a1 = a >> 32;
  9513. uint64_t b0 = b & 0xffffffff;
  9514. uint64_t b1 = b >> 32;
  9515. uint64_t i0 = a0 * b0;
  9516. uint64_t i1 = a0 * b1;
  9517. uint64_t i2 = a1 * b0;
  9518. uint64_t i3 = a1 * b1;
  9519. uint64_t p0, p1;
  9520. i2 += (i0 >> 32);
  9521. i2 += i1;
  9522. if (i2 < i1) { /* overflow */
  9523. i3 += 0x100000000;
  9524. }
  9525. p0 = (i0 & 0xffffffff) | (i2 << 32);
  9526. p1 = i3 + (i2 >> 32);
  9527. *r0 += p0;
  9528. *r1 += (p1 + (*r0 < p0));
  9529. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  9530. #else
  9531. uECC_dword_t p = (uECC_dword_t) a * b;
  9532. uECC_dword_t r01 = ((uECC_dword_t) (*r1) << uECC_WORD_BITS) | *r0;
  9533. r01 += p;
  9534. *r2 += (r01 < p);
  9535. *r1 = (uECC_word_t) (r01 >> uECC_WORD_BITS);
  9536. *r0 = (uECC_word_t) r01;
  9537. #endif
  9538. }
  9539. #endif /* muladd needed */
  9540. #if !asm_mult
  9541. uECC_VLI_API void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left,
  9542. const uECC_word_t *right,
  9543. wordcount_t num_words) {
  9544. uECC_word_t r0 = 0;
  9545. uECC_word_t r1 = 0;
  9546. uECC_word_t r2 = 0;
  9547. wordcount_t i, k;
  9548. /* Compute each digit of result in sequence, maintaining the carries. */
  9549. for (k = 0; k < num_words; ++k) {
  9550. for (i = 0; i <= k; ++i) {
  9551. muladd(left[i], right[k - i], &r0, &r1, &r2);
  9552. }
  9553. result[k] = r0;
  9554. r0 = r1;
  9555. r1 = r2;
  9556. r2 = 0;
  9557. }
  9558. for (k = num_words; k < num_words * 2 - 1; ++k) {
  9559. for (i = (wordcount_t) ((k + 1) - num_words); i < num_words; ++i) {
  9560. muladd(left[i], right[k - i], &r0, &r1, &r2);
  9561. }
  9562. result[k] = r0;
  9563. r0 = r1;
  9564. r1 = r2;
  9565. r2 = 0;
  9566. }
  9567. result[num_words * 2 - 1] = r0;
  9568. }
  9569. #endif /* !asm_mult */
  9570. #if uECC_SQUARE_FUNC
  9571. #if !asm_square
  9572. static void mul2add(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
  9573. uECC_word_t *r1, uECC_word_t *r2) {
  9574. #if uECC_WORD_SIZE == 8
  9575. uint64_t a0 = a & 0xffffffffull;
  9576. uint64_t a1 = a >> 32;
  9577. uint64_t b0 = b & 0xffffffffull;
  9578. uint64_t b1 = b >> 32;
  9579. uint64_t i0 = a0 * b0;
  9580. uint64_t i1 = a0 * b1;
  9581. uint64_t i2 = a1 * b0;
  9582. uint64_t i3 = a1 * b1;
  9583. uint64_t p0, p1;
  9584. i2 += (i0 >> 32);
  9585. i2 += i1;
  9586. if (i2 < i1) { /* overflow */
  9587. i3 += 0x100000000ull;
  9588. }
  9589. p0 = (i0 & 0xffffffffull) | (i2 << 32);
  9590. p1 = i3 + (i2 >> 32);
  9591. *r2 += (p1 >> 63);
  9592. p1 = (p1 << 1) | (p0 >> 63);
  9593. p0 <<= 1;
  9594. *r0 += p0;
  9595. *r1 += (p1 + (*r0 < p0));
  9596. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  9597. #else
  9598. uECC_dword_t p = (uECC_dword_t) a * b;
  9599. uECC_dword_t r01 = ((uECC_dword_t) (*r1) << uECC_WORD_BITS) | *r0;
  9600. *r2 += (p >> (uECC_WORD_BITS * 2 - 1));
  9601. p *= 2;
  9602. r01 += p;
  9603. *r2 += (r01 < p);
  9604. *r1 = r01 >> uECC_WORD_BITS;
  9605. *r0 = (uECC_word_t) r01;
  9606. #endif
  9607. }
  9608. uECC_VLI_API void uECC_vli_square(uECC_word_t *result, const uECC_word_t *left,
  9609. wordcount_t num_words) {
  9610. uECC_word_t r0 = 0;
  9611. uECC_word_t r1 = 0;
  9612. uECC_word_t r2 = 0;
  9613. wordcount_t i, k;
  9614. for (k = 0; k < num_words * 2 - 1; ++k) {
  9615. uECC_word_t min = (k < num_words ? 0 : (k + 1) - num_words);
  9616. for (i = min; i <= k && i <= k - i; ++i) {
  9617. if (i < k - i) {
  9618. mul2add(left[i], left[k - i], &r0, &r1, &r2);
  9619. } else {
  9620. muladd(left[i], left[k - i], &r0, &r1, &r2);
  9621. }
  9622. }
  9623. result[k] = r0;
  9624. r0 = r1;
  9625. r1 = r2;
  9626. r2 = 0;
  9627. }
  9628. result[num_words * 2 - 1] = r0;
  9629. }
  9630. #endif /* !asm_square */
  9631. #else /* uECC_SQUARE_FUNC */
  9632. #if uECC_ENABLE_VLI_API
  9633. uECC_VLI_API void uECC_vli_square(uECC_word_t *result, const uECC_word_t *left,
  9634. wordcount_t num_words) {
  9635. uECC_vli_mult(result, left, left, num_words);
  9636. }
  9637. #endif /* uECC_ENABLE_VLI_API */
  9638. #endif /* uECC_SQUARE_FUNC */
  9639. /* Computes result = (left + right) % mod.
  9640. Assumes that left < mod and right < mod, and that result does not overlap
  9641. mod. */
  9642. uECC_VLI_API void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left,
  9643. const uECC_word_t *right,
  9644. const uECC_word_t *mod,
  9645. wordcount_t num_words) {
  9646. uECC_word_t carry = uECC_vli_add(result, left, right, num_words);
  9647. if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {
  9648. /* result > mod (result = mod + remainder), so subtract mod to get
  9649. * remainder. */
  9650. uECC_vli_sub(result, result, mod, num_words);
  9651. }
  9652. }
  9653. /* Computes result = (left - right) % mod.
  9654. Assumes that left < mod and right < mod, and that result does not overlap
  9655. mod. */
  9656. uECC_VLI_API void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left,
  9657. const uECC_word_t *right,
  9658. const uECC_word_t *mod,
  9659. wordcount_t num_words) {
  9660. uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);
  9661. if (l_borrow) {
  9662. /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
  9663. we can get the correct result from result + mod (with overflow). */
  9664. uECC_vli_add(result, result, mod, num_words);
  9665. }
  9666. }
  9667. /* Computes result = product % mod, where product is 2N words long. */
  9668. /* Currently only designed to work for curve_p or curve_n. */
  9669. uECC_VLI_API void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product,
  9670. const uECC_word_t *mod, wordcount_t num_words) {
  9671. uECC_word_t mod_multiple[2 * uECC_MAX_WORDS];
  9672. uECC_word_t tmp[2 * uECC_MAX_WORDS];
  9673. uECC_word_t *v[2] = {tmp, product};
  9674. uECC_word_t index;
  9675. /* Shift mod so its highest set bit is at the maximum position. */
  9676. bitcount_t shift = (bitcount_t) (
  9677. (num_words * 2 * uECC_WORD_BITS) - uECC_vli_numBits(mod, num_words));
  9678. wordcount_t word_shift = (wordcount_t) (shift / uECC_WORD_BITS);
  9679. wordcount_t bit_shift = (wordcount_t) (shift % uECC_WORD_BITS);
  9680. uECC_word_t carry = 0;
  9681. uECC_vli_clear(mod_multiple, word_shift);
  9682. if (bit_shift > 0) {
  9683. for (index = 0; index < (uECC_word_t) num_words; ++index) {
  9684. mod_multiple[(uECC_word_t) word_shift + index] =
  9685. (uECC_word_t) (mod[index] << bit_shift) | carry;
  9686. carry = mod[index] >> (uECC_WORD_BITS - bit_shift);
  9687. }
  9688. } else {
  9689. uECC_vli_set(mod_multiple + word_shift, mod, num_words);
  9690. }
  9691. for (index = 1; shift >= 0; --shift) {
  9692. uECC_word_t borrow = 0;
  9693. wordcount_t i;
  9694. for (i = 0; i < num_words * 2; ++i) {
  9695. uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow;
  9696. if (diff != v[index][i]) {
  9697. borrow = (diff > v[index][i]);
  9698. }
  9699. v[1 - index][i] = diff;
  9700. }
  9701. index = !(index ^ borrow); /* Swap the index if there was no borrow */
  9702. uECC_vli_rshift1(mod_multiple, num_words);
  9703. mod_multiple[num_words - 1] |= mod_multiple[num_words]
  9704. << (uECC_WORD_BITS - 1);
  9705. uECC_vli_rshift1(mod_multiple + num_words, num_words);
  9706. }
  9707. uECC_vli_set(result, v[index], num_words);
  9708. }
  9709. /* Computes result = (left * right) % mod. */
  9710. uECC_VLI_API void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left,
  9711. const uECC_word_t *right,
  9712. const uECC_word_t *mod,
  9713. wordcount_t num_words) {
  9714. uECC_word_t product[2 * uECC_MAX_WORDS];
  9715. uECC_vli_mult(product, left, right, num_words);
  9716. uECC_vli_mmod(result, product, mod, num_words);
  9717. }
  9718. uECC_VLI_API void uECC_vli_modMult_fast(uECC_word_t *result,
  9719. const uECC_word_t *left,
  9720. const uECC_word_t *right,
  9721. uECC_Curve curve) {
  9722. uECC_word_t product[2 * uECC_MAX_WORDS];
  9723. uECC_vli_mult(product, left, right, curve->num_words);
  9724. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9725. curve->mmod_fast(result, product);
  9726. #else
  9727. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  9728. #endif
  9729. }
  9730. #if uECC_SQUARE_FUNC
  9731. #if uECC_ENABLE_VLI_API
  9732. /* Computes result = left^2 % mod. */
  9733. uECC_VLI_API void uECC_vli_modSquare(uECC_word_t *result,
  9734. const uECC_word_t *left,
  9735. const uECC_word_t *mod,
  9736. wordcount_t num_words) {
  9737. uECC_word_t product[2 * uECC_MAX_WORDS];
  9738. uECC_vli_square(product, left, num_words);
  9739. uECC_vli_mmod(result, product, mod, num_words);
  9740. }
  9741. #endif /* uECC_ENABLE_VLI_API */
  9742. uECC_VLI_API void uECC_vli_modSquare_fast(uECC_word_t *result,
  9743. const uECC_word_t *left,
  9744. uECC_Curve curve) {
  9745. uECC_word_t product[2 * uECC_MAX_WORDS];
  9746. uECC_vli_square(product, left, curve->num_words);
  9747. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9748. curve->mmod_fast(result, product);
  9749. #else
  9750. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  9751. #endif
  9752. }
  9753. #else /* uECC_SQUARE_FUNC */
  9754. #if uECC_ENABLE_VLI_API
  9755. uECC_VLI_API void uECC_vli_modSquare(uECC_word_t *result,
  9756. const uECC_word_t *left,
  9757. const uECC_word_t *mod,
  9758. wordcount_t num_words) {
  9759. uECC_vli_modMult(result, left, left, mod, num_words);
  9760. }
  9761. #endif /* uECC_ENABLE_VLI_API */
  9762. uECC_VLI_API void uECC_vli_modSquare_fast(uECC_word_t *result,
  9763. const uECC_word_t *left,
  9764. uECC_Curve curve) {
  9765. uECC_vli_modMult_fast(result, left, left, curve);
  9766. }
  9767. #endif /* uECC_SQUARE_FUNC */
  9768. #define EVEN(vli) (!(vli[0] & 1))
  9769. static void vli_modInv_update(uECC_word_t *uv, const uECC_word_t *mod,
  9770. wordcount_t num_words) {
  9771. uECC_word_t carry = 0;
  9772. if (!EVEN(uv)) {
  9773. carry = uECC_vli_add(uv, uv, mod, num_words);
  9774. }
  9775. uECC_vli_rshift1(uv, num_words);
  9776. if (carry) {
  9777. uv[num_words - 1] |= HIGH_BIT_SET;
  9778. }
  9779. }
  9780. /* Computes result = (1 / input) % mod. All VLIs are the same size.
  9781. See "From Euclid's GCD to Montgomery Multiplication to the Great Divide" */
  9782. uECC_VLI_API void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input,
  9783. const uECC_word_t *mod,
  9784. wordcount_t num_words) {
  9785. uECC_word_t a[uECC_MAX_WORDS], b[uECC_MAX_WORDS], u[uECC_MAX_WORDS],
  9786. v[uECC_MAX_WORDS];
  9787. cmpresult_t cmpResult;
  9788. if (uECC_vli_isZero(input, num_words)) {
  9789. uECC_vli_clear(result, num_words);
  9790. return;
  9791. }
  9792. uECC_vli_set(a, input, num_words);
  9793. uECC_vli_set(b, mod, num_words);
  9794. uECC_vli_clear(u, num_words);
  9795. u[0] = 1;
  9796. uECC_vli_clear(v, num_words);
  9797. while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {
  9798. if (EVEN(a)) {
  9799. uECC_vli_rshift1(a, num_words);
  9800. vli_modInv_update(u, mod, num_words);
  9801. } else if (EVEN(b)) {
  9802. uECC_vli_rshift1(b, num_words);
  9803. vli_modInv_update(v, mod, num_words);
  9804. } else if (cmpResult > 0) {
  9805. uECC_vli_sub(a, a, b, num_words);
  9806. uECC_vli_rshift1(a, num_words);
  9807. if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {
  9808. uECC_vli_add(u, u, mod, num_words);
  9809. }
  9810. uECC_vli_sub(u, u, v, num_words);
  9811. vli_modInv_update(u, mod, num_words);
  9812. } else {
  9813. uECC_vli_sub(b, b, a, num_words);
  9814. uECC_vli_rshift1(b, num_words);
  9815. if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {
  9816. uECC_vli_add(v, v, mod, num_words);
  9817. }
  9818. uECC_vli_sub(v, v, u, num_words);
  9819. vli_modInv_update(v, mod, num_words);
  9820. }
  9821. }
  9822. uECC_vli_set(result, u, num_words);
  9823. }
  9824. /* ------ Point operations ------ */
  9825. /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  9826. #ifndef _UECC_CURVE_SPECIFIC_H_
  9827. #define _UECC_CURVE_SPECIFIC_H_
  9828. #define num_bytes_secp160r1 20
  9829. #define num_bytes_secp192r1 24
  9830. #define num_bytes_secp224r1 28
  9831. #define num_bytes_secp256r1 32
  9832. #define num_bytes_secp256k1 32
  9833. #if (uECC_WORD_SIZE == 1)
  9834. #define num_words_secp160r1 20
  9835. #define num_words_secp192r1 24
  9836. #define num_words_secp224r1 28
  9837. #define num_words_secp256r1 32
  9838. #define num_words_secp256k1 32
  9839. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) \
  9840. 0x##a, 0x##b, 0x##c, 0x##d, 0x##e, 0x##f, 0x##g, 0x##h
  9841. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##a, 0x##b, 0x##c, 0x##d
  9842. #elif (uECC_WORD_SIZE == 4)
  9843. #define num_words_secp160r1 5
  9844. #define num_words_secp192r1 6
  9845. #define num_words_secp224r1 7
  9846. #define num_words_secp256r1 8
  9847. #define num_words_secp256k1 8
  9848. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
  9849. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
  9850. #elif (uECC_WORD_SIZE == 8)
  9851. #define num_words_secp160r1 3
  9852. #define num_words_secp192r1 3
  9853. #define num_words_secp224r1 4
  9854. #define num_words_secp256r1 4
  9855. #define num_words_secp256k1 4
  9856. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##h##g##f##e##d##c##b##a##U
  9857. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a##U
  9858. #endif /* uECC_WORD_SIZE */
  9859. #if uECC_SUPPORTS_secp160r1 || uECC_SUPPORTS_secp192r1 || \
  9860. uECC_SUPPORTS_secp224r1 || uECC_SUPPORTS_secp256r1
  9861. static void double_jacobian_default(uECC_word_t *X1, uECC_word_t *Y1,
  9862. uECC_word_t *Z1, uECC_Curve curve) {
  9863. /* t1 = X, t2 = Y, t3 = Z */
  9864. uECC_word_t t4[uECC_MAX_WORDS];
  9865. uECC_word_t t5[uECC_MAX_WORDS];
  9866. wordcount_t num_words = curve->num_words;
  9867. if (uECC_vli_isZero(Z1, num_words)) {
  9868. return;
  9869. }
  9870. uECC_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */
  9871. uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
  9872. uECC_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */
  9873. uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
  9874. uECC_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */
  9875. uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
  9876. uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
  9877. uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
  9878. uECC_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */
  9879. uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */
  9880. uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */
  9881. if (uECC_vli_testBit(X1, 0)) {
  9882. uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words);
  9883. uECC_vli_rshift1(X1, num_words);
  9884. X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1);
  9885. } else {
  9886. uECC_vli_rshift1(X1, num_words);
  9887. }
  9888. /* t1 = 3/2*(x1^2 - z1^4) = B */
  9889. uECC_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */
  9890. uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
  9891. uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
  9892. uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
  9893. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */
  9894. uECC_vli_modSub(t4, X1, t4, curve->p,
  9895. num_words); /* t4 = B * (A - x3) - y1^4 = y3 */
  9896. uECC_vli_set(X1, Z1, num_words);
  9897. uECC_vli_set(Z1, Y1, num_words);
  9898. uECC_vli_set(Y1, t4, num_words);
  9899. }
  9900. /* Computes result = x^3 + ax + b. result must not overlap x. */
  9901. static void x_side_default(uECC_word_t *result, const uECC_word_t *x,
  9902. uECC_Curve curve) {
  9903. uECC_word_t _3[uECC_MAX_WORDS] = {3}; /* -a = 3 */
  9904. wordcount_t num_words = curve->num_words;
  9905. uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  9906. uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
  9907. uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */
  9908. uECC_vli_modAdd(result, result, curve->b, curve->p,
  9909. num_words); /* r = x^3 - 3x + b */
  9910. }
  9911. #endif /* uECC_SUPPORTS_secp... */
  9912. #if uECC_SUPPORT_COMPRESSED_POINT
  9913. #if uECC_SUPPORTS_secp160r1 || uECC_SUPPORTS_secp192r1 || \
  9914. uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1
  9915. /* Compute a = sqrt(a) (mod curve_p). */
  9916. static void mod_sqrt_default(uECC_word_t *a, uECC_Curve curve) {
  9917. bitcount_t i;
  9918. uECC_word_t p1[uECC_MAX_WORDS] = {1};
  9919. uECC_word_t l_result[uECC_MAX_WORDS] = {1};
  9920. wordcount_t num_words = curve->num_words;
  9921. /* When curve->p == 3 (mod 4), we can compute
  9922. sqrt(a) = a^((curve->p + 1) / 4) (mod curve->p). */
  9923. uECC_vli_add(p1, curve->p, p1, num_words); /* p1 = curve_p + 1 */
  9924. for (i = uECC_vli_numBits(p1, num_words) - 1; i > 1; --i) {
  9925. uECC_vli_modSquare_fast(l_result, l_result, curve);
  9926. if (uECC_vli_testBit(p1, i)) {
  9927. uECC_vli_modMult_fast(l_result, l_result, a, curve);
  9928. }
  9929. }
  9930. uECC_vli_set(a, l_result, num_words);
  9931. }
  9932. #endif /* uECC_SUPPORTS_secp... */
  9933. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  9934. #if uECC_SUPPORTS_secp160r1
  9935. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9936. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product);
  9937. #endif
  9938. static const struct uECC_Curve_t curve_secp160r1 = {
  9939. num_words_secp160r1,
  9940. num_bytes_secp160r1,
  9941. 161, /* num_n_bits */
  9942. {BYTES_TO_WORDS_8(FF, FF, FF, 7F, FF, FF, FF, FF),
  9943. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  9944. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  9945. {BYTES_TO_WORDS_8(57, 22, 75, CA, D3, AE, 27, F9),
  9946. BYTES_TO_WORDS_8(C8, F4, 01, 00, 00, 00, 00, 00),
  9947. BYTES_TO_WORDS_8(00, 00, 00, 00, 01, 00, 00, 00)},
  9948. {BYTES_TO_WORDS_8(82, FC, CB, 13, B9, 8B, C3, 68),
  9949. BYTES_TO_WORDS_8(89, 69, 64, 46, 28, 73, F5, 8E),
  9950. BYTES_TO_WORDS_4(68, B5, 96, 4A),
  9951. BYTES_TO_WORDS_8(32, FB, C5, 7A, 37, 51, 23, 04),
  9952. BYTES_TO_WORDS_8(12, C9, DC, 59, 7D, 94, 68, 31),
  9953. BYTES_TO_WORDS_4(55, 28, A6, 23)},
  9954. {BYTES_TO_WORDS_8(45, FA, 65, C5, AD, D4, D4, 81),
  9955. BYTES_TO_WORDS_8(9F, F8, AC, 65, 8B, 7A, BD, 54),
  9956. BYTES_TO_WORDS_4(FC, BE, 97, 1C)},
  9957. &double_jacobian_default,
  9958. #if uECC_SUPPORT_COMPRESSED_POINT
  9959. &mod_sqrt_default,
  9960. #endif
  9961. &x_side_default,
  9962. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9963. &vli_mmod_fast_secp160r1
  9964. #endif
  9965. };
  9966. uECC_Curve uECC_secp160r1(void) {
  9967. return &curve_secp160r1;
  9968. }
  9969. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1)
  9970. /* Computes result = product % curve_p
  9971. see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
  9972. Note that this only works if log2(omega) < log2(p) / 2 */
  9973. static void omega_mult_secp160r1(uECC_word_t *result, const uECC_word_t *right);
  9974. #if uECC_WORD_SIZE == 8
  9975. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product) {
  9976. uECC_word_t tmp[2 * num_words_secp160r1];
  9977. uECC_word_t copy;
  9978. uECC_vli_clear(tmp, num_words_secp160r1);
  9979. uECC_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  9980. omega_mult_secp160r1(tmp,
  9981. product + num_words_secp160r1 - 1); /* (Rq, q) = q * c */
  9982. product[num_words_secp160r1 - 1] &= 0xffffffff;
  9983. copy = tmp[num_words_secp160r1 - 1];
  9984. tmp[num_words_secp160r1 - 1] &= 0xffffffff;
  9985. uECC_vli_add(result, product, tmp, num_words_secp160r1); /* (C, r) = r + q */
  9986. uECC_vli_clear(product, num_words_secp160r1);
  9987. tmp[num_words_secp160r1 - 1] = copy;
  9988. omega_mult_secp160r1(product, tmp + num_words_secp160r1 - 1); /* Rq*c */
  9989. uECC_vli_add(result, result, product,
  9990. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  9991. while (uECC_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) >
  9992. 0) {
  9993. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  9994. }
  9995. }
  9996. static void omega_mult_secp160r1(uint64_t *result, const uint64_t *right) {
  9997. uint32_t carry;
  9998. unsigned i;
  9999. /* Multiply by (2^31 + 1). */
  10000. carry = 0;
  10001. for (i = 0; i < num_words_secp160r1; ++i) {
  10002. uint64_t tmp = (right[i] >> 32) | (right[i + 1] << 32);
  10003. result[i] = (tmp << 31) + tmp + carry;
  10004. carry = (tmp >> 33) + (result[i] < tmp || (carry && result[i] == tmp));
  10005. }
  10006. result[i] = carry;
  10007. }
  10008. #else
  10009. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product) {
  10010. uECC_word_t tmp[2 * num_words_secp160r1];
  10011. uECC_word_t carry;
  10012. uECC_vli_clear(tmp, num_words_secp160r1);
  10013. uECC_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  10014. omega_mult_secp160r1(tmp,
  10015. product + num_words_secp160r1); /* (Rq, q) = q * c */
  10016. carry = uECC_vli_add(result, product, tmp,
  10017. num_words_secp160r1); /* (C, r) = r + q */
  10018. uECC_vli_clear(product, num_words_secp160r1);
  10019. omega_mult_secp160r1(product, tmp + num_words_secp160r1); /* Rq*c */
  10020. carry += uECC_vli_add(result, result, product,
  10021. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  10022. while (carry > 0) {
  10023. --carry;
  10024. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  10025. }
  10026. if (uECC_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) > 0) {
  10027. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  10028. }
  10029. }
  10030. #endif
  10031. #if uECC_WORD_SIZE == 1
  10032. static void omega_mult_secp160r1(uint8_t *result, const uint8_t *right) {
  10033. uint8_t carry;
  10034. uint8_t i;
  10035. /* Multiply by (2^31 + 1). */
  10036. uECC_vli_set(result + 4, right, num_words_secp160r1); /* 2^32 */
  10037. uECC_vli_rshift1(result + 4, num_words_secp160r1); /* 2^31 */
  10038. result[3] = right[0] << 7; /* get last bit from shift */
  10039. carry =
  10040. uECC_vli_add(result, result, right, num_words_secp160r1); /* 2^31 + 1 */
  10041. for (i = num_words_secp160r1; carry; ++i) {
  10042. uint16_t sum = (uint16_t) result[i] + carry;
  10043. result[i] = (uint8_t) sum;
  10044. carry = sum >> 8;
  10045. }
  10046. }
  10047. #elif uECC_WORD_SIZE == 4
  10048. static void omega_mult_secp160r1(uint32_t *result, const uint32_t *right) {
  10049. uint32_t carry;
  10050. unsigned i;
  10051. /* Multiply by (2^31 + 1). */
  10052. uECC_vli_set(result + 1, right, num_words_secp160r1); /* 2^32 */
  10053. uECC_vli_rshift1(result + 1, num_words_secp160r1); /* 2^31 */
  10054. result[0] = right[0] << 31; /* get last bit from shift */
  10055. carry =
  10056. uECC_vli_add(result, result, right, num_words_secp160r1); /* 2^31 + 1 */
  10057. for (i = num_words_secp160r1; carry; ++i) {
  10058. uint64_t sum = (uint64_t) result[i] + carry;
  10059. result[i] = (uint32_t) sum;
  10060. carry = sum >> 32;
  10061. }
  10062. }
  10063. #endif /* uECC_WORD_SIZE */
  10064. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) */
  10065. #endif /* uECC_SUPPORTS_secp160r1 */
  10066. #if uECC_SUPPORTS_secp192r1
  10067. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10068. static void vli_mmod_fast_secp192r1(uECC_word_t *result, uECC_word_t *product);
  10069. #endif
  10070. static const struct uECC_Curve_t curve_secp192r1 = {
  10071. num_words_secp192r1,
  10072. num_bytes_secp192r1,
  10073. 192, /* num_n_bits */
  10074. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10075. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  10076. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  10077. {BYTES_TO_WORDS_8(31, 28, D2, B4, B1, C9, 6B, 14),
  10078. BYTES_TO_WORDS_8(36, F8, DE, 99, FF, FF, FF, FF),
  10079. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  10080. {BYTES_TO_WORDS_8(12, 10, FF, 82, FD, 0A, FF, F4),
  10081. BYTES_TO_WORDS_8(00, 88, A1, 43, EB, 20, BF, 7C),
  10082. BYTES_TO_WORDS_8(F6, 90, 30, B0, 0E, A8, 8D, 18),
  10083. BYTES_TO_WORDS_8(11, 48, 79, 1E, A1, 77, F9, 73),
  10084. BYTES_TO_WORDS_8(D5, CD, 24, 6B, ED, 11, 10, 63),
  10085. BYTES_TO_WORDS_8(78, DA, C8, FF, 95, 2B, 19, 07)},
  10086. {BYTES_TO_WORDS_8(B1, B9, 46, C1, EC, DE, B8, FE),
  10087. BYTES_TO_WORDS_8(49, 30, 24, 72, AB, E9, A7, 0F),
  10088. BYTES_TO_WORDS_8(E7, 80, 9C, E5, 19, 05, 21, 64)},
  10089. &double_jacobian_default,
  10090. #if uECC_SUPPORT_COMPRESSED_POINT
  10091. &mod_sqrt_default,
  10092. #endif
  10093. &x_side_default,
  10094. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10095. &vli_mmod_fast_secp192r1
  10096. #endif
  10097. };
  10098. uECC_Curve uECC_secp192r1(void) {
  10099. return &curve_secp192r1;
  10100. }
  10101. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10102. /* Computes result = product % curve_p.
  10103. See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf
  10104. */
  10105. #if uECC_WORD_SIZE == 1
  10106. static void vli_mmod_fast_secp192r1(uint8_t *result, uint8_t *product) {
  10107. uint8_t tmp[num_words_secp192r1];
  10108. uint8_t carry;
  10109. uECC_vli_set(result, product, num_words_secp192r1);
  10110. uECC_vli_set(tmp, &product[24], num_words_secp192r1);
  10111. carry = uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10112. tmp[0] = tmp[1] = tmp[2] = tmp[3] = tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10113. tmp[8] = product[24];
  10114. tmp[9] = product[25];
  10115. tmp[10] = product[26];
  10116. tmp[11] = product[27];
  10117. tmp[12] = product[28];
  10118. tmp[13] = product[29];
  10119. tmp[14] = product[30];
  10120. tmp[15] = product[31];
  10121. tmp[16] = product[32];
  10122. tmp[17] = product[33];
  10123. tmp[18] = product[34];
  10124. tmp[19] = product[35];
  10125. tmp[20] = product[36];
  10126. tmp[21] = product[37];
  10127. tmp[22] = product[38];
  10128. tmp[23] = product[39];
  10129. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10130. tmp[0] = tmp[8] = product[40];
  10131. tmp[1] = tmp[9] = product[41];
  10132. tmp[2] = tmp[10] = product[42];
  10133. tmp[3] = tmp[11] = product[43];
  10134. tmp[4] = tmp[12] = product[44];
  10135. tmp[5] = tmp[13] = product[45];
  10136. tmp[6] = tmp[14] = product[46];
  10137. tmp[7] = tmp[15] = product[47];
  10138. tmp[16] = tmp[17] = tmp[18] = tmp[19] = tmp[20] = tmp[21] = tmp[22] =
  10139. tmp[23] = 0;
  10140. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10141. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10142. num_words_secp192r1) != 1) {
  10143. carry -=
  10144. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10145. }
  10146. }
  10147. #elif uECC_WORD_SIZE == 4
  10148. static void vli_mmod_fast_secp192r1(uint32_t *result, uint32_t *product) {
  10149. uint32_t tmp[num_words_secp192r1];
  10150. int carry;
  10151. uECC_vli_set(result, product, num_words_secp192r1);
  10152. uECC_vli_set(tmp, &product[6], num_words_secp192r1);
  10153. carry = uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10154. tmp[0] = tmp[1] = 0;
  10155. tmp[2] = product[6];
  10156. tmp[3] = product[7];
  10157. tmp[4] = product[8];
  10158. tmp[5] = product[9];
  10159. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10160. tmp[0] = tmp[2] = product[10];
  10161. tmp[1] = tmp[3] = product[11];
  10162. tmp[4] = tmp[5] = 0;
  10163. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10164. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10165. num_words_secp192r1) != 1) {
  10166. carry -=
  10167. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10168. }
  10169. }
  10170. #else
  10171. static void vli_mmod_fast_secp192r1(uint64_t *result, uint64_t *product) {
  10172. uint64_t tmp[num_words_secp192r1];
  10173. int carry;
  10174. uECC_vli_set(result, product, num_words_secp192r1);
  10175. uECC_vli_set(tmp, &product[3], num_words_secp192r1);
  10176. carry = (int) uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10177. tmp[0] = 0;
  10178. tmp[1] = product[3];
  10179. tmp[2] = product[4];
  10180. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10181. tmp[0] = tmp[1] = product[5];
  10182. tmp[2] = 0;
  10183. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10184. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10185. num_words_secp192r1) != 1) {
  10186. carry -=
  10187. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10188. }
  10189. }
  10190. #endif /* uECC_WORD_SIZE */
  10191. #endif /* (uECC_OPTIMIZATION_LEVEL > 0) */
  10192. #endif /* uECC_SUPPORTS_secp192r1 */
  10193. #if uECC_SUPPORTS_secp224r1
  10194. #if uECC_SUPPORT_COMPRESSED_POINT
  10195. static void mod_sqrt_secp224r1(uECC_word_t *a, uECC_Curve curve);
  10196. #endif
  10197. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10198. static void vli_mmod_fast_secp224r1(uECC_word_t *result, uECC_word_t *product);
  10199. #endif
  10200. static const struct uECC_Curve_t curve_secp224r1 = {
  10201. num_words_secp224r1,
  10202. num_bytes_secp224r1,
  10203. 224, /* num_n_bits */
  10204. {BYTES_TO_WORDS_8(01, 00, 00, 00, 00, 00, 00, 00),
  10205. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF),
  10206. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10207. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  10208. {BYTES_TO_WORDS_8(3D, 2A, 5C, 5C, 45, 29, DD, 13),
  10209. BYTES_TO_WORDS_8(3E, F0, B8, E0, A2, 16, FF, FF),
  10210. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10211. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  10212. {BYTES_TO_WORDS_8(21, 1D, 5C, 11, D6, 80, 32, 34),
  10213. BYTES_TO_WORDS_8(22, 11, C2, 56, D3, C1, 03, 4A),
  10214. BYTES_TO_WORDS_8(B9, 90, 13, 32, 7F, BF, B4, 6B),
  10215. BYTES_TO_WORDS_4(BD, 0C, 0E, B7),
  10216. BYTES_TO_WORDS_8(34, 7E, 00, 85, 99, 81, D5, 44),
  10217. BYTES_TO_WORDS_8(64, 47, 07, 5A, A0, 75, 43, CD),
  10218. BYTES_TO_WORDS_8(E6, DF, 22, 4C, FB, 23, F7, B5),
  10219. BYTES_TO_WORDS_4(88, 63, 37, BD)},
  10220. {BYTES_TO_WORDS_8(B4, FF, 55, 23, 43, 39, 0B, 27),
  10221. BYTES_TO_WORDS_8(BA, D8, BF, D7, B7, B0, 44, 50),
  10222. BYTES_TO_WORDS_8(56, 32, 41, F5, AB, B3, 04, 0C),
  10223. BYTES_TO_WORDS_4(85, 0A, 05, B4)},
  10224. &double_jacobian_default,
  10225. #if uECC_SUPPORT_COMPRESSED_POINT
  10226. &mod_sqrt_secp224r1,
  10227. #endif
  10228. &x_side_default,
  10229. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10230. &vli_mmod_fast_secp224r1
  10231. #endif
  10232. };
  10233. uECC_Curve uECC_secp224r1(void) {
  10234. return &curve_secp224r1;
  10235. }
  10236. #if uECC_SUPPORT_COMPRESSED_POINT
  10237. /* Routine 3.2.4 RS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10238. static void mod_sqrt_secp224r1_rs(uECC_word_t *d1, uECC_word_t *e1,
  10239. uECC_word_t *f1, const uECC_word_t *d0,
  10240. const uECC_word_t *e0,
  10241. const uECC_word_t *f0) {
  10242. uECC_word_t t[num_words_secp224r1];
  10243. uECC_vli_modSquare_fast(t, d0, &curve_secp224r1); /* t <-- d0 ^ 2 */
  10244. uECC_vli_modMult_fast(e1, d0, e0, &curve_secp224r1); /* e1 <-- d0 * e0 */
  10245. uECC_vli_modAdd(d1, t, f0, curve_secp224r1.p,
  10246. num_words_secp224r1); /* d1 <-- t + f0 */
  10247. uECC_vli_modAdd(e1, e1, e1, curve_secp224r1.p,
  10248. num_words_secp224r1); /* e1 <-- e1 + e1 */
  10249. uECC_vli_modMult_fast(f1, t, f0, &curve_secp224r1); /* f1 <-- t * f0 */
  10250. uECC_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  10251. num_words_secp224r1); /* f1 <-- f1 + f1 */
  10252. uECC_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  10253. num_words_secp224r1); /* f1 <-- f1 + f1 */
  10254. }
  10255. /* Routine 3.2.5 RSS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10256. static void mod_sqrt_secp224r1_rss(uECC_word_t *d1, uECC_word_t *e1,
  10257. uECC_word_t *f1, const uECC_word_t *d0,
  10258. const uECC_word_t *e0, const uECC_word_t *f0,
  10259. const bitcount_t j) {
  10260. bitcount_t i;
  10261. uECC_vli_set(d1, d0, num_words_secp224r1); /* d1 <-- d0 */
  10262. uECC_vli_set(e1, e0, num_words_secp224r1); /* e1 <-- e0 */
  10263. uECC_vli_set(f1, f0, num_words_secp224r1); /* f1 <-- f0 */
  10264. for (i = 1; i <= j; i++) {
  10265. mod_sqrt_secp224r1_rs(d1, e1, f1, d1, e1, f1); /* RS (d1,e1,f1,d1,e1,f1) */
  10266. }
  10267. }
  10268. /* Routine 3.2.6 RM; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10269. static void mod_sqrt_secp224r1_rm(uECC_word_t *d2, uECC_word_t *e2,
  10270. uECC_word_t *f2, const uECC_word_t *c,
  10271. const uECC_word_t *d0, const uECC_word_t *e0,
  10272. const uECC_word_t *d1,
  10273. const uECC_word_t *e1) {
  10274. uECC_word_t t1[num_words_secp224r1];
  10275. uECC_word_t t2[num_words_secp224r1];
  10276. uECC_vli_modMult_fast(t1, e0, e1, &curve_secp224r1); /* t1 <-- e0 * e1 */
  10277. uECC_vli_modMult_fast(t1, t1, c, &curve_secp224r1); /* t1 <-- t1 * c */
  10278. /* t1 <-- p - t1 */
  10279. uECC_vli_modSub(t1, curve_secp224r1.p, t1, curve_secp224r1.p,
  10280. num_words_secp224r1);
  10281. uECC_vli_modMult_fast(t2, d0, d1, &curve_secp224r1); /* t2 <-- d0 * d1 */
  10282. uECC_vli_modAdd(t2, t2, t1, curve_secp224r1.p,
  10283. num_words_secp224r1); /* t2 <-- t2 + t1 */
  10284. uECC_vli_modMult_fast(t1, d0, e1, &curve_secp224r1); /* t1 <-- d0 * e1 */
  10285. uECC_vli_modMult_fast(e2, d1, e0, &curve_secp224r1); /* e2 <-- d1 * e0 */
  10286. uECC_vli_modAdd(e2, e2, t1, curve_secp224r1.p,
  10287. num_words_secp224r1); /* e2 <-- e2 + t1 */
  10288. uECC_vli_modSquare_fast(f2, e2, &curve_secp224r1); /* f2 <-- e2^2 */
  10289. uECC_vli_modMult_fast(f2, f2, c, &curve_secp224r1); /* f2 <-- f2 * c */
  10290. /* f2 <-- p - f2 */
  10291. uECC_vli_modSub(f2, curve_secp224r1.p, f2, curve_secp224r1.p,
  10292. num_words_secp224r1);
  10293. uECC_vli_set(d2, t2, num_words_secp224r1); /* d2 <-- t2 */
  10294. }
  10295. /* Routine 3.2.7 RP; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10296. static void mod_sqrt_secp224r1_rp(uECC_word_t *d1, uECC_word_t *e1,
  10297. uECC_word_t *f1, const uECC_word_t *c,
  10298. const uECC_word_t *r) {
  10299. wordcount_t i;
  10300. wordcount_t pow2i = 1;
  10301. uECC_word_t d0[num_words_secp224r1];
  10302. uECC_word_t e0[num_words_secp224r1] = {1}; /* e0 <-- 1 */
  10303. uECC_word_t f0[num_words_secp224r1];
  10304. uECC_vli_set(d0, r, num_words_secp224r1); /* d0 <-- r */
  10305. /* f0 <-- p - c */
  10306. uECC_vli_modSub(f0, curve_secp224r1.p, c, curve_secp224r1.p,
  10307. num_words_secp224r1);
  10308. for (i = 0; i <= 6; i++) {
  10309. mod_sqrt_secp224r1_rss(d1, e1, f1, d0, e0, f0,
  10310. pow2i); /* RSS (d1,e1,f1,d0,e0,f0,2^i) */
  10311. mod_sqrt_secp224r1_rm(d1, e1, f1, c, d1, e1, d0,
  10312. e0); /* RM (d1,e1,f1,c,d1,e1,d0,e0) */
  10313. uECC_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  10314. uECC_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  10315. uECC_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  10316. pow2i *= 2;
  10317. }
  10318. }
  10319. /* Compute a = sqrt(a) (mod curve_p). */
  10320. /* Routine 3.2.8 mp_mod_sqrt_224; from
  10321. * http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10322. static void mod_sqrt_secp224r1(uECC_word_t *a, uECC_Curve curve) {
  10323. (void) curve;
  10324. bitcount_t i;
  10325. uECC_word_t e1[num_words_secp224r1];
  10326. uECC_word_t f1[num_words_secp224r1];
  10327. uECC_word_t d0[num_words_secp224r1];
  10328. uECC_word_t e0[num_words_secp224r1];
  10329. uECC_word_t f0[num_words_secp224r1];
  10330. uECC_word_t d1[num_words_secp224r1];
  10331. /* s = a; using constant instead of random value */
  10332. mod_sqrt_secp224r1_rp(d0, e0, f0, a, a); /* RP (d0, e0, f0, c, s) */
  10333. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  10334. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  10335. for (i = 1; i <= 95; i++) {
  10336. uECC_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  10337. uECC_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  10338. uECC_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  10339. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  10340. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  10341. if (uECC_vli_isZero(d1, num_words_secp224r1)) { /* if d1 == 0 */
  10342. break;
  10343. }
  10344. }
  10345. uECC_vli_modInv(f1, e0, curve_secp224r1.p,
  10346. num_words_secp224r1); /* f1 <-- 1 / e0 */
  10347. uECC_vli_modMult_fast(a, d0, f1, &curve_secp224r1); /* a <-- d0 / e0 */
  10348. }
  10349. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  10350. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10351. /* Computes result = product % curve_p
  10352. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10353. #if uECC_WORD_SIZE == 1
  10354. static void vli_mmod_fast_secp224r1(uint8_t *result, uint8_t *product) {
  10355. uint8_t tmp[num_words_secp224r1];
  10356. int8_t carry;
  10357. /* t */
  10358. uECC_vli_set(result, product, num_words_secp224r1);
  10359. /* s1 */
  10360. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  10361. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10362. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10363. tmp[12] = product[28];
  10364. tmp[13] = product[29];
  10365. tmp[14] = product[30];
  10366. tmp[15] = product[31];
  10367. tmp[16] = product[32];
  10368. tmp[17] = product[33];
  10369. tmp[18] = product[34];
  10370. tmp[19] = product[35];
  10371. tmp[20] = product[36];
  10372. tmp[21] = product[37];
  10373. tmp[22] = product[38];
  10374. tmp[23] = product[39];
  10375. tmp[24] = product[40];
  10376. tmp[25] = product[41];
  10377. tmp[26] = product[42];
  10378. tmp[27] = product[43];
  10379. carry = uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10380. /* s2 */
  10381. tmp[12] = product[44];
  10382. tmp[13] = product[45];
  10383. tmp[14] = product[46];
  10384. tmp[15] = product[47];
  10385. tmp[16] = product[48];
  10386. tmp[17] = product[49];
  10387. tmp[18] = product[50];
  10388. tmp[19] = product[51];
  10389. tmp[20] = product[52];
  10390. tmp[21] = product[53];
  10391. tmp[22] = product[54];
  10392. tmp[23] = product[55];
  10393. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10394. carry += uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10395. /* d1 */
  10396. tmp[0] = product[28];
  10397. tmp[1] = product[29];
  10398. tmp[2] = product[30];
  10399. tmp[3] = product[31];
  10400. tmp[4] = product[32];
  10401. tmp[5] = product[33];
  10402. tmp[6] = product[34];
  10403. tmp[7] = product[35];
  10404. tmp[8] = product[36];
  10405. tmp[9] = product[37];
  10406. tmp[10] = product[38];
  10407. tmp[11] = product[39];
  10408. tmp[12] = product[40];
  10409. tmp[13] = product[41];
  10410. tmp[14] = product[42];
  10411. tmp[15] = product[43];
  10412. tmp[16] = product[44];
  10413. tmp[17] = product[45];
  10414. tmp[18] = product[46];
  10415. tmp[19] = product[47];
  10416. tmp[20] = product[48];
  10417. tmp[21] = product[49];
  10418. tmp[22] = product[50];
  10419. tmp[23] = product[51];
  10420. tmp[24] = product[52];
  10421. tmp[25] = product[53];
  10422. tmp[26] = product[54];
  10423. tmp[27] = product[55];
  10424. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10425. /* d2 */
  10426. tmp[0] = product[44];
  10427. tmp[1] = product[45];
  10428. tmp[2] = product[46];
  10429. tmp[3] = product[47];
  10430. tmp[4] = product[48];
  10431. tmp[5] = product[49];
  10432. tmp[6] = product[50];
  10433. tmp[7] = product[51];
  10434. tmp[8] = product[52];
  10435. tmp[9] = product[53];
  10436. tmp[10] = product[54];
  10437. tmp[11] = product[55];
  10438. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10439. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10440. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10441. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10442. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10443. if (carry < 0) {
  10444. do {
  10445. carry +=
  10446. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10447. } while (carry < 0);
  10448. } else {
  10449. while (carry || uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10450. num_words_secp224r1) != 1) {
  10451. carry -=
  10452. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10453. }
  10454. }
  10455. }
  10456. #elif uECC_WORD_SIZE == 4
  10457. static void vli_mmod_fast_secp224r1(uint32_t *result, uint32_t *product) {
  10458. uint32_t tmp[num_words_secp224r1];
  10459. int carry;
  10460. /* t */
  10461. uECC_vli_set(result, product, num_words_secp224r1);
  10462. /* s1 */
  10463. tmp[0] = tmp[1] = tmp[2] = 0;
  10464. tmp[3] = product[7];
  10465. tmp[4] = product[8];
  10466. tmp[5] = product[9];
  10467. tmp[6] = product[10];
  10468. carry = uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10469. /* s2 */
  10470. tmp[3] = product[11];
  10471. tmp[4] = product[12];
  10472. tmp[5] = product[13];
  10473. tmp[6] = 0;
  10474. carry += uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10475. /* d1 */
  10476. tmp[0] = product[7];
  10477. tmp[1] = product[8];
  10478. tmp[2] = product[9];
  10479. tmp[3] = product[10];
  10480. tmp[4] = product[11];
  10481. tmp[5] = product[12];
  10482. tmp[6] = product[13];
  10483. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10484. /* d2 */
  10485. tmp[0] = product[11];
  10486. tmp[1] = product[12];
  10487. tmp[2] = product[13];
  10488. tmp[3] = tmp[4] = tmp[5] = tmp[6] = 0;
  10489. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10490. if (carry < 0) {
  10491. do {
  10492. carry +=
  10493. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10494. } while (carry < 0);
  10495. } else {
  10496. while (carry || uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10497. num_words_secp224r1) != 1) {
  10498. carry -=
  10499. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10500. }
  10501. }
  10502. }
  10503. #else
  10504. static void vli_mmod_fast_secp224r1(uint64_t *result, uint64_t *product) {
  10505. uint64_t tmp[num_words_secp224r1];
  10506. int carry = 0;
  10507. /* t */
  10508. uECC_vli_set(result, product, num_words_secp224r1);
  10509. result[num_words_secp224r1 - 1] &= 0xffffffff;
  10510. /* s1 */
  10511. tmp[0] = 0;
  10512. tmp[1] = product[3] & 0xffffffff00000000ull;
  10513. tmp[2] = product[4];
  10514. tmp[3] = product[5] & 0xffffffff;
  10515. uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10516. /* s2 */
  10517. tmp[1] = product[5] & 0xffffffff00000000ull;
  10518. tmp[2] = product[6];
  10519. tmp[3] = 0;
  10520. uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10521. /* d1 */
  10522. tmp[0] = (product[3] >> 32) | (product[4] << 32);
  10523. tmp[1] = (product[4] >> 32) | (product[5] << 32);
  10524. tmp[2] = (product[5] >> 32) | (product[6] << 32);
  10525. tmp[3] = product[6] >> 32;
  10526. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10527. /* d2 */
  10528. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  10529. tmp[1] = product[6] >> 32;
  10530. tmp[2] = tmp[3] = 0;
  10531. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10532. if (carry < 0) {
  10533. do {
  10534. carry +=
  10535. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10536. } while (carry < 0);
  10537. } else {
  10538. while (uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10539. num_words_secp224r1) != 1) {
  10540. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10541. }
  10542. }
  10543. }
  10544. #endif /* uECC_WORD_SIZE */
  10545. #endif /* (uECC_OPTIMIZATION_LEVEL > 0) */
  10546. #endif /* uECC_SUPPORTS_secp224r1 */
  10547. #if uECC_SUPPORTS_secp256r1
  10548. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10549. static void vli_mmod_fast_secp256r1(uECC_word_t *result, uECC_word_t *product);
  10550. #endif
  10551. static const struct uECC_Curve_t curve_secp256r1 = {
  10552. num_words_secp256r1,
  10553. num_bytes_secp256r1,
  10554. 256, /* num_n_bits */
  10555. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10556. BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00),
  10557. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  10558. BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF)},
  10559. {BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3),
  10560. BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC),
  10561. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10562. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF)},
  10563. {BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4),
  10564. BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77),
  10565. BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8),
  10566. BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B),
  10567. BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB),
  10568. BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B),
  10569. BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E),
  10570. BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F)},
  10571. {BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B),
  10572. BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65),
  10573. BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3),
  10574. BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A)},
  10575. &double_jacobian_default,
  10576. #if uECC_SUPPORT_COMPRESSED_POINT
  10577. &mod_sqrt_default,
  10578. #endif
  10579. &x_side_default,
  10580. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10581. &vli_mmod_fast_secp256r1
  10582. #endif
  10583. };
  10584. uECC_Curve uECC_secp256r1(void) {
  10585. return &curve_secp256r1;
  10586. }
  10587. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1)
  10588. /* Computes result = product % curve_p
  10589. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10590. #if uECC_WORD_SIZE == 1
  10591. static void vli_mmod_fast_secp256r1(uint8_t *result, uint8_t *product) {
  10592. uint8_t tmp[num_words_secp256r1];
  10593. int8_t carry;
  10594. /* t */
  10595. uECC_vli_set(result, product, num_words_secp256r1);
  10596. /* s1 */
  10597. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  10598. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10599. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10600. tmp[12] = product[44];
  10601. tmp[13] = product[45];
  10602. tmp[14] = product[46];
  10603. tmp[15] = product[47];
  10604. tmp[16] = product[48];
  10605. tmp[17] = product[49];
  10606. tmp[18] = product[50];
  10607. tmp[19] = product[51];
  10608. tmp[20] = product[52];
  10609. tmp[21] = product[53];
  10610. tmp[22] = product[54];
  10611. tmp[23] = product[55];
  10612. tmp[24] = product[56];
  10613. tmp[25] = product[57];
  10614. tmp[26] = product[58];
  10615. tmp[27] = product[59];
  10616. tmp[28] = product[60];
  10617. tmp[29] = product[61];
  10618. tmp[30] = product[62];
  10619. tmp[31] = product[63];
  10620. carry = uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10621. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10622. /* s2 */
  10623. tmp[12] = product[48];
  10624. tmp[13] = product[49];
  10625. tmp[14] = product[50];
  10626. tmp[15] = product[51];
  10627. tmp[16] = product[52];
  10628. tmp[17] = product[53];
  10629. tmp[18] = product[54];
  10630. tmp[19] = product[55];
  10631. tmp[20] = product[56];
  10632. tmp[21] = product[57];
  10633. tmp[22] = product[58];
  10634. tmp[23] = product[59];
  10635. tmp[24] = product[60];
  10636. tmp[25] = product[61];
  10637. tmp[26] = product[62];
  10638. tmp[27] = product[63];
  10639. tmp[28] = tmp[29] = tmp[30] = tmp[31] = 0;
  10640. carry += uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10641. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10642. /* s3 */
  10643. tmp[0] = product[32];
  10644. tmp[1] = product[33];
  10645. tmp[2] = product[34];
  10646. tmp[3] = product[35];
  10647. tmp[4] = product[36];
  10648. tmp[5] = product[37];
  10649. tmp[6] = product[38];
  10650. tmp[7] = product[39];
  10651. tmp[8] = product[40];
  10652. tmp[9] = product[41];
  10653. tmp[10] = product[42];
  10654. tmp[11] = product[43];
  10655. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10656. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10657. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10658. tmp[24] = product[56];
  10659. tmp[25] = product[57];
  10660. tmp[26] = product[58];
  10661. tmp[27] = product[59];
  10662. tmp[28] = product[60];
  10663. tmp[29] = product[61];
  10664. tmp[30] = product[62];
  10665. tmp[31] = product[63];
  10666. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10667. /* s4 */
  10668. tmp[0] = product[36];
  10669. tmp[1] = product[37];
  10670. tmp[2] = product[38];
  10671. tmp[3] = product[39];
  10672. tmp[4] = product[40];
  10673. tmp[5] = product[41];
  10674. tmp[6] = product[42];
  10675. tmp[7] = product[43];
  10676. tmp[8] = product[44];
  10677. tmp[9] = product[45];
  10678. tmp[10] = product[46];
  10679. tmp[11] = product[47];
  10680. tmp[12] = product[52];
  10681. tmp[13] = product[53];
  10682. tmp[14] = product[54];
  10683. tmp[15] = product[55];
  10684. tmp[16] = product[56];
  10685. tmp[17] = product[57];
  10686. tmp[18] = product[58];
  10687. tmp[19] = product[59];
  10688. tmp[20] = product[60];
  10689. tmp[21] = product[61];
  10690. tmp[22] = product[62];
  10691. tmp[23] = product[63];
  10692. tmp[24] = product[52];
  10693. tmp[25] = product[53];
  10694. tmp[26] = product[54];
  10695. tmp[27] = product[55];
  10696. tmp[28] = product[32];
  10697. tmp[29] = product[33];
  10698. tmp[30] = product[34];
  10699. tmp[31] = product[35];
  10700. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10701. /* d1 */
  10702. tmp[0] = product[44];
  10703. tmp[1] = product[45];
  10704. tmp[2] = product[46];
  10705. tmp[3] = product[47];
  10706. tmp[4] = product[48];
  10707. tmp[5] = product[49];
  10708. tmp[6] = product[50];
  10709. tmp[7] = product[51];
  10710. tmp[8] = product[52];
  10711. tmp[9] = product[53];
  10712. tmp[10] = product[54];
  10713. tmp[11] = product[55];
  10714. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10715. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10716. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10717. tmp[24] = product[32];
  10718. tmp[25] = product[33];
  10719. tmp[26] = product[34];
  10720. tmp[27] = product[35];
  10721. tmp[28] = product[40];
  10722. tmp[29] = product[41];
  10723. tmp[30] = product[42];
  10724. tmp[31] = product[43];
  10725. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10726. /* d2 */
  10727. tmp[0] = product[48];
  10728. tmp[1] = product[49];
  10729. tmp[2] = product[50];
  10730. tmp[3] = product[51];
  10731. tmp[4] = product[52];
  10732. tmp[5] = product[53];
  10733. tmp[6] = product[54];
  10734. tmp[7] = product[55];
  10735. tmp[8] = product[56];
  10736. tmp[9] = product[57];
  10737. tmp[10] = product[58];
  10738. tmp[11] = product[59];
  10739. tmp[12] = product[60];
  10740. tmp[13] = product[61];
  10741. tmp[14] = product[62];
  10742. tmp[15] = product[63];
  10743. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10744. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10745. tmp[24] = product[36];
  10746. tmp[25] = product[37];
  10747. tmp[26] = product[38];
  10748. tmp[27] = product[39];
  10749. tmp[28] = product[44];
  10750. tmp[29] = product[45];
  10751. tmp[30] = product[46];
  10752. tmp[31] = product[47];
  10753. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10754. /* d3 */
  10755. tmp[0] = product[52];
  10756. tmp[1] = product[53];
  10757. tmp[2] = product[54];
  10758. tmp[3] = product[55];
  10759. tmp[4] = product[56];
  10760. tmp[5] = product[57];
  10761. tmp[6] = product[58];
  10762. tmp[7] = product[59];
  10763. tmp[8] = product[60];
  10764. tmp[9] = product[61];
  10765. tmp[10] = product[62];
  10766. tmp[11] = product[63];
  10767. tmp[12] = product[32];
  10768. tmp[13] = product[33];
  10769. tmp[14] = product[34];
  10770. tmp[15] = product[35];
  10771. tmp[16] = product[36];
  10772. tmp[17] = product[37];
  10773. tmp[18] = product[38];
  10774. tmp[19] = product[39];
  10775. tmp[20] = product[40];
  10776. tmp[21] = product[41];
  10777. tmp[22] = product[42];
  10778. tmp[23] = product[43];
  10779. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10780. tmp[28] = product[48];
  10781. tmp[29] = product[49];
  10782. tmp[30] = product[50];
  10783. tmp[31] = product[51];
  10784. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10785. /* d4 */
  10786. tmp[0] = product[56];
  10787. tmp[1] = product[57];
  10788. tmp[2] = product[58];
  10789. tmp[3] = product[59];
  10790. tmp[4] = product[60];
  10791. tmp[5] = product[61];
  10792. tmp[6] = product[62];
  10793. tmp[7] = product[63];
  10794. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10795. tmp[12] = product[36];
  10796. tmp[13] = product[37];
  10797. tmp[14] = product[38];
  10798. tmp[15] = product[39];
  10799. tmp[16] = product[40];
  10800. tmp[17] = product[41];
  10801. tmp[18] = product[42];
  10802. tmp[19] = product[43];
  10803. tmp[20] = product[44];
  10804. tmp[21] = product[45];
  10805. tmp[22] = product[46];
  10806. tmp[23] = product[47];
  10807. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10808. tmp[28] = product[52];
  10809. tmp[29] = product[53];
  10810. tmp[30] = product[54];
  10811. tmp[31] = product[55];
  10812. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10813. if (carry < 0) {
  10814. do {
  10815. carry +=
  10816. uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10817. } while (carry < 0);
  10818. } else {
  10819. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10820. num_words_secp256r1) != 1) {
  10821. carry -=
  10822. uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10823. }
  10824. }
  10825. }
  10826. #elif uECC_WORD_SIZE == 4
  10827. static void vli_mmod_fast_secp256r1(uint32_t *result, uint32_t *product) {
  10828. uint32_t tmp[num_words_secp256r1];
  10829. int carry;
  10830. /* t */
  10831. uECC_vli_set(result, product, num_words_secp256r1);
  10832. /* s1 */
  10833. tmp[0] = tmp[1] = tmp[2] = 0;
  10834. tmp[3] = product[11];
  10835. tmp[4] = product[12];
  10836. tmp[5] = product[13];
  10837. tmp[6] = product[14];
  10838. tmp[7] = product[15];
  10839. carry = (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10840. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10841. /* s2 */
  10842. tmp[3] = product[12];
  10843. tmp[4] = product[13];
  10844. tmp[5] = product[14];
  10845. tmp[6] = product[15];
  10846. tmp[7] = 0;
  10847. carry += (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10848. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10849. /* s3 */
  10850. tmp[0] = product[8];
  10851. tmp[1] = product[9];
  10852. tmp[2] = product[10];
  10853. tmp[3] = tmp[4] = tmp[5] = 0;
  10854. tmp[6] = product[14];
  10855. tmp[7] = product[15];
  10856. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10857. /* s4 */
  10858. tmp[0] = product[9];
  10859. tmp[1] = product[10];
  10860. tmp[2] = product[11];
  10861. tmp[3] = product[13];
  10862. tmp[4] = product[14];
  10863. tmp[5] = product[15];
  10864. tmp[6] = product[13];
  10865. tmp[7] = product[8];
  10866. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10867. /* d1 */
  10868. tmp[0] = product[11];
  10869. tmp[1] = product[12];
  10870. tmp[2] = product[13];
  10871. tmp[3] = tmp[4] = tmp[5] = 0;
  10872. tmp[6] = product[8];
  10873. tmp[7] = product[10];
  10874. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10875. /* d2 */
  10876. tmp[0] = product[12];
  10877. tmp[1] = product[13];
  10878. tmp[2] = product[14];
  10879. tmp[3] = product[15];
  10880. tmp[4] = tmp[5] = 0;
  10881. tmp[6] = product[9];
  10882. tmp[7] = product[11];
  10883. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10884. /* d3 */
  10885. tmp[0] = product[13];
  10886. tmp[1] = product[14];
  10887. tmp[2] = product[15];
  10888. tmp[3] = product[8];
  10889. tmp[4] = product[9];
  10890. tmp[5] = product[10];
  10891. tmp[6] = 0;
  10892. tmp[7] = product[12];
  10893. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10894. /* d4 */
  10895. tmp[0] = product[14];
  10896. tmp[1] = product[15];
  10897. tmp[2] = 0;
  10898. tmp[3] = product[9];
  10899. tmp[4] = product[10];
  10900. tmp[5] = product[11];
  10901. tmp[6] = 0;
  10902. tmp[7] = product[13];
  10903. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10904. if (carry < 0) {
  10905. do {
  10906. carry +=
  10907. (int) uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10908. } while (carry < 0);
  10909. } else {
  10910. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10911. num_words_secp256r1) != 1) {
  10912. carry -=
  10913. (int) uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10914. }
  10915. }
  10916. }
  10917. #else
  10918. static void vli_mmod_fast_secp256r1(uint64_t *result, uint64_t *product) {
  10919. uint64_t tmp[num_words_secp256r1];
  10920. int carry;
  10921. /* t */
  10922. uECC_vli_set(result, product, num_words_secp256r1);
  10923. /* s1 */
  10924. tmp[0] = 0;
  10925. tmp[1] = product[5] & 0xffffffff00000000U;
  10926. tmp[2] = product[6];
  10927. tmp[3] = product[7];
  10928. carry = (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10929. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10930. /* s2 */
  10931. tmp[1] = product[6] << 32;
  10932. tmp[2] = (product[6] >> 32) | (product[7] << 32);
  10933. tmp[3] = product[7] >> 32;
  10934. carry += (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10935. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10936. /* s3 */
  10937. tmp[0] = product[4];
  10938. tmp[1] = product[5] & 0xffffffff;
  10939. tmp[2] = 0;
  10940. tmp[3] = product[7];
  10941. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10942. /* s4 */
  10943. tmp[0] = (product[4] >> 32) | (product[5] << 32);
  10944. tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000U);
  10945. tmp[2] = product[7];
  10946. tmp[3] = (product[6] >> 32) | (product[4] << 32);
  10947. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10948. /* d1 */
  10949. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  10950. tmp[1] = (product[6] >> 32);
  10951. tmp[2] = 0;
  10952. tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32);
  10953. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10954. /* d2 */
  10955. tmp[0] = product[6];
  10956. tmp[1] = product[7];
  10957. tmp[2] = 0;
  10958. tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000);
  10959. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10960. /* d3 */
  10961. tmp[0] = (product[6] >> 32) | (product[7] << 32);
  10962. tmp[1] = (product[7] >> 32) | (product[4] << 32);
  10963. tmp[2] = (product[4] >> 32) | (product[5] << 32);
  10964. tmp[3] = (product[6] << 32);
  10965. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10966. /* d4 */
  10967. tmp[0] = product[7];
  10968. tmp[1] = product[4] & 0xffffffff00000000U;
  10969. tmp[2] = product[5];
  10970. tmp[3] = product[6] & 0xffffffff00000000U;
  10971. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10972. if (carry < 0) {
  10973. do {
  10974. carry +=
  10975. (int) uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10976. } while (carry < 0);
  10977. } else {
  10978. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10979. num_words_secp256r1) != 1) {
  10980. carry -=
  10981. (int) uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10982. }
  10983. }
  10984. }
  10985. #endif /* uECC_WORD_SIZE */
  10986. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) */
  10987. #endif /* uECC_SUPPORTS_secp256r1 */
  10988. #if uECC_SUPPORTS_secp256k1
  10989. static void double_jacobian_secp256k1(uECC_word_t *X1, uECC_word_t *Y1,
  10990. uECC_word_t *Z1, uECC_Curve curve);
  10991. static void x_side_secp256k1(uECC_word_t *result, const uECC_word_t *x,
  10992. uECC_Curve curve);
  10993. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10994. static void vli_mmod_fast_secp256k1(uECC_word_t *result, uECC_word_t *product);
  10995. #endif
  10996. static const struct uECC_Curve_t curve_secp256k1 = {
  10997. num_words_secp256k1,
  10998. num_bytes_secp256k1,
  10999. 256, /* num_n_bits */
  11000. {BYTES_TO_WORDS_8(2F, FC, FF, FF, FE, FF, FF, FF),
  11001. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11002. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11003. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11004. {BYTES_TO_WORDS_8(41, 41, 36, D0, 8C, 5E, D2, BF),
  11005. BYTES_TO_WORDS_8(3B, A0, 48, AF, E6, DC, AE, BA),
  11006. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  11007. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11008. {BYTES_TO_WORDS_8(98, 17, F8, 16, 5B, 81, F2, 59),
  11009. BYTES_TO_WORDS_8(D9, 28, CE, 2D, DB, FC, 9B, 02),
  11010. BYTES_TO_WORDS_8(07, 0B, 87, CE, 95, 62, A0, 55),
  11011. BYTES_TO_WORDS_8(AC, BB, DC, F9, 7E, 66, BE, 79),
  11012. BYTES_TO_WORDS_8(B8, D4, 10, FB, 8F, D0, 47, 9C),
  11013. BYTES_TO_WORDS_8(19, 54, 85, A6, 48, B4, 17, FD),
  11014. BYTES_TO_WORDS_8(A8, 08, 11, 0E, FC, FB, A4, 5D),
  11015. BYTES_TO_WORDS_8(65, C4, A3, 26, 77, DA, 3A, 48)},
  11016. {BYTES_TO_WORDS_8(07, 00, 00, 00, 00, 00, 00, 00),
  11017. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  11018. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  11019. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00)},
  11020. &double_jacobian_secp256k1,
  11021. #if uECC_SUPPORT_COMPRESSED_POINT
  11022. &mod_sqrt_default,
  11023. #endif
  11024. &x_side_secp256k1,
  11025. #if (uECC_OPTIMIZATION_LEVEL > 0)
  11026. &vli_mmod_fast_secp256k1
  11027. #endif
  11028. };
  11029. uECC_Curve uECC_secp256k1(void) {
  11030. return &curve_secp256k1;
  11031. }
  11032. /* Double in place */
  11033. static void double_jacobian_secp256k1(uECC_word_t *X1, uECC_word_t *Y1,
  11034. uECC_word_t *Z1, uECC_Curve curve) {
  11035. /* t1 = X, t2 = Y, t3 = Z */
  11036. uECC_word_t t4[num_words_secp256k1];
  11037. uECC_word_t t5[num_words_secp256k1];
  11038. if (uECC_vli_isZero(Z1, num_words_secp256k1)) {
  11039. return;
  11040. }
  11041. uECC_vli_modSquare_fast(t5, Y1, curve); /* t5 = y1^2 */
  11042. uECC_vli_modMult_fast(t4, X1, t5, curve); /* t4 = x1*y1^2 = A */
  11043. uECC_vli_modSquare_fast(X1, X1, curve); /* t1 = x1^2 */
  11044. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = y1^4 */
  11045. uECC_vli_modMult_fast(Z1, Y1, Z1, curve); /* t3 = y1*z1 = z3 */
  11046. uECC_vli_modAdd(Y1, X1, X1, curve->p, num_words_secp256k1); /* t2 = 2*x1^2 */
  11047. uECC_vli_modAdd(Y1, Y1, X1, curve->p, num_words_secp256k1); /* t2 = 3*x1^2 */
  11048. if (uECC_vli_testBit(Y1, 0)) {
  11049. uECC_word_t carry = uECC_vli_add(Y1, Y1, curve->p, num_words_secp256k1);
  11050. uECC_vli_rshift1(Y1, num_words_secp256k1);
  11051. Y1[num_words_secp256k1 - 1] |= carry << (uECC_WORD_BITS - 1);
  11052. } else {
  11053. uECC_vli_rshift1(Y1, num_words_secp256k1);
  11054. }
  11055. /* t2 = 3/2*(x1^2) = B */
  11056. uECC_vli_modSquare_fast(X1, Y1, curve); /* t1 = B^2 */
  11057. uECC_vli_modSub(X1, X1, t4, curve->p, num_words_secp256k1); /* t1 = B^2 - A */
  11058. uECC_vli_modSub(X1, X1, t4, curve->p,
  11059. num_words_secp256k1); /* t1 = B^2 - 2A = x3 */
  11060. uECC_vli_modSub(t4, t4, X1, curve->p, num_words_secp256k1); /* t4 = A - x3 */
  11061. uECC_vli_modMult_fast(Y1, Y1, t4, curve); /* t2 = B * (A - x3) */
  11062. uECC_vli_modSub(Y1, Y1, t5, curve->p,
  11063. num_words_secp256k1); /* t2 = B * (A - x3) - y1^4 = y3 */
  11064. }
  11065. /* Computes result = x^3 + b. result must not overlap x. */
  11066. static void x_side_secp256k1(uECC_word_t *result, const uECC_word_t *x,
  11067. uECC_Curve curve) {
  11068. uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  11069. uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 */
  11070. uECC_vli_modAdd(result, result, curve->b, curve->p,
  11071. num_words_secp256k1); /* r = x^3 + b */
  11072. }
  11073. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256k1)
  11074. static void omega_mult_secp256k1(uECC_word_t *result, const uECC_word_t *right);
  11075. static void vli_mmod_fast_secp256k1(uECC_word_t *result, uECC_word_t *product) {
  11076. uECC_word_t tmp[2 * num_words_secp256k1];
  11077. uECC_word_t carry;
  11078. uECC_vli_clear(tmp, num_words_secp256k1);
  11079. uECC_vli_clear(tmp + num_words_secp256k1, num_words_secp256k1);
  11080. omega_mult_secp256k1(tmp,
  11081. product + num_words_secp256k1); /* (Rq, q) = q * c */
  11082. carry = uECC_vli_add(result, product, tmp,
  11083. num_words_secp256k1); /* (C, r) = r + q */
  11084. uECC_vli_clear(product, num_words_secp256k1);
  11085. omega_mult_secp256k1(product, tmp + num_words_secp256k1); /* Rq*c */
  11086. carry += uECC_vli_add(result, result, product,
  11087. num_words_secp256k1); /* (C1, r) = r + Rq*c */
  11088. while (carry > 0) {
  11089. --carry;
  11090. uECC_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  11091. }
  11092. if (uECC_vli_cmp_unsafe(result, curve_secp256k1.p, num_words_secp256k1) > 0) {
  11093. uECC_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  11094. }
  11095. }
  11096. #if uECC_WORD_SIZE == 1
  11097. static void omega_mult_secp256k1(uint8_t *result, const uint8_t *right) {
  11098. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11099. uECC_word_t r0 = 0;
  11100. uECC_word_t r1 = 0;
  11101. uECC_word_t r2 = 0;
  11102. wordcount_t k;
  11103. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11104. muladd(0xD1, right[0], &r0, &r1, &r2);
  11105. result[0] = r0;
  11106. r0 = r1;
  11107. r1 = r2;
  11108. /* r2 is still 0 */
  11109. for (k = 1; k < num_words_secp256k1; ++k) {
  11110. muladd(0x03, right[k - 1], &r0, &r1, &r2);
  11111. muladd(0xD1, right[k], &r0, &r1, &r2);
  11112. result[k] = r0;
  11113. r0 = r1;
  11114. r1 = r2;
  11115. r2 = 0;
  11116. }
  11117. muladd(0x03, right[num_words_secp256k1 - 1], &r0, &r1, &r2);
  11118. result[num_words_secp256k1] = r0;
  11119. result[num_words_secp256k1 + 1] = r1;
  11120. /* add the 2^32 multiple */
  11121. result[4 + num_words_secp256k1] =
  11122. uECC_vli_add(result + 4, result + 4, right, num_words_secp256k1);
  11123. }
  11124. #elif uECC_WORD_SIZE == 4
  11125. static void omega_mult_secp256k1(uint32_t *result, const uint32_t *right) {
  11126. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11127. uint32_t carry = 0;
  11128. wordcount_t k;
  11129. for (k = 0; k < num_words_secp256k1; ++k) {
  11130. uint64_t p = (uint64_t) 0x3D1 * right[k] + carry;
  11131. result[k] = (uint32_t) p;
  11132. carry = p >> 32;
  11133. }
  11134. result[num_words_secp256k1] = carry;
  11135. /* add the 2^32 multiple */
  11136. result[1 + num_words_secp256k1] =
  11137. uECC_vli_add(result + 1, result + 1, right, num_words_secp256k1);
  11138. }
  11139. #else
  11140. static void omega_mult_secp256k1(uint64_t *result, const uint64_t *right) {
  11141. uECC_word_t r0 = 0;
  11142. uECC_word_t r1 = 0;
  11143. uECC_word_t r2 = 0;
  11144. wordcount_t k;
  11145. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11146. for (k = 0; k < num_words_secp256k1; ++k) {
  11147. muladd(0x1000003D1ull, right[k], &r0, &r1, &r2);
  11148. result[k] = r0;
  11149. r0 = r1;
  11150. r1 = r2;
  11151. r2 = 0;
  11152. }
  11153. result[num_words_secp256k1] = r0;
  11154. }
  11155. #endif /* uECC_WORD_SIZE */
  11156. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && && !asm_mmod_fast_secp256k1) */
  11157. #endif /* uECC_SUPPORTS_secp256k1 */
  11158. #endif /* _UECC_CURVE_SPECIFIC_H_ */
  11159. /* Returns 1 if 'point' is the point at infinity, 0 otherwise. */
  11160. #define EccPoint_isZero(point, curve) \
  11161. uECC_vli_isZero((point), (wordcount_t) ((curve)->num_words * 2))
  11162. /* Point multiplication algorithm using Montgomery's ladder with co-Z
  11163. coordinates. From http://eprint.iacr.org/2011/338.pdf
  11164. */
  11165. /* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
  11166. static void apply_z(uECC_word_t *X1, uECC_word_t *Y1,
  11167. const uECC_word_t *const Z, uECC_Curve curve) {
  11168. uECC_word_t t1[uECC_MAX_WORDS];
  11169. uECC_vli_modSquare_fast(t1, Z, curve); /* z^2 */
  11170. uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
  11171. uECC_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */
  11172. uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
  11173. }
  11174. /* P = (x1, y1) => 2P, (x2, y2) => P' */
  11175. static void XYcZ_initial_double(uECC_word_t *X1, uECC_word_t *Y1,
  11176. uECC_word_t *X2, uECC_word_t *Y2,
  11177. const uECC_word_t *const initial_Z,
  11178. uECC_Curve curve) {
  11179. uECC_word_t z[uECC_MAX_WORDS];
  11180. wordcount_t num_words = curve->num_words;
  11181. if (initial_Z) {
  11182. uECC_vli_set(z, initial_Z, num_words);
  11183. } else {
  11184. uECC_vli_clear(z, num_words);
  11185. z[0] = 1;
  11186. }
  11187. uECC_vli_set(X2, X1, num_words);
  11188. uECC_vli_set(Y2, Y1, num_words);
  11189. apply_z(X1, Y1, z, curve);
  11190. curve->double_jacobian(X1, Y1, z, curve);
  11191. apply_z(X2, Y2, z, curve);
  11192. }
  11193. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  11194. Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
  11195. or P => P', Q => P + Q
  11196. */
  11197. static void XYcZ_add(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2,
  11198. uECC_word_t *Y2, uECC_Curve curve) {
  11199. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  11200. uECC_word_t t5[uECC_MAX_WORDS] = {0};
  11201. wordcount_t num_words = curve->num_words;
  11202. uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  11203. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  11204. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  11205. uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  11206. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  11207. uECC_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */
  11208. uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
  11209. uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
  11210. uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
  11211. uECC_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */
  11212. uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
  11213. uECC_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */
  11214. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
  11215. uECC_vli_set(X2, t5, num_words);
  11216. }
  11217. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  11218. Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
  11219. or P => P - Q, Q => P + Q
  11220. */
  11221. static void XYcZ_addC(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2,
  11222. uECC_word_t *Y2, uECC_Curve curve) {
  11223. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  11224. uECC_word_t t5[uECC_MAX_WORDS] = {0};
  11225. uECC_word_t t6[uECC_MAX_WORDS];
  11226. uECC_word_t t7[uECC_MAX_WORDS];
  11227. wordcount_t num_words = curve->num_words;
  11228. uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  11229. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  11230. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  11231. uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  11232. uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
  11233. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  11234. uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
  11235. uECC_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */
  11236. uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
  11237. uECC_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */
  11238. uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */
  11239. uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
  11240. uECC_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */
  11241. uECC_vli_modSub(Y2, Y2, Y1, curve->p,
  11242. num_words); /* t4 = (y2 - y1)*(B - x3) - E = y3 */
  11243. uECC_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */
  11244. uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */
  11245. uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
  11246. uECC_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */
  11247. uECC_vli_modSub(Y1, t6, Y1, curve->p,
  11248. num_words); /* t2 = (y2+y1)*(x3' - B) - E = y3' */
  11249. uECC_vli_set(X1, t7, num_words);
  11250. }
  11251. /* result may overlap point. */
  11252. static void EccPoint_mult(uECC_word_t *result, const uECC_word_t *point,
  11253. const uECC_word_t *scalar,
  11254. const uECC_word_t *initial_Z, bitcount_t num_bits,
  11255. uECC_Curve curve) {
  11256. /* R0 and R1 */
  11257. uECC_word_t Rx[2][uECC_MAX_WORDS];
  11258. uECC_word_t Ry[2][uECC_MAX_WORDS];
  11259. uECC_word_t z[uECC_MAX_WORDS];
  11260. bitcount_t i;
  11261. uECC_word_t nb;
  11262. wordcount_t num_words = curve->num_words;
  11263. uECC_vli_set(Rx[1], point, num_words);
  11264. uECC_vli_set(Ry[1], point + num_words, num_words);
  11265. XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
  11266. for (i = num_bits - 2; i > 0; --i) {
  11267. nb = !uECC_vli_testBit(scalar, i);
  11268. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  11269. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  11270. }
  11271. nb = !uECC_vli_testBit(scalar, 0);
  11272. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  11273. /* Find final 1/Z value. */
  11274. uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
  11275. uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */
  11276. uECC_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */
  11277. uECC_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0)) */
  11278. /* yP / (xP * Yb * (X1 - X0)) */
  11279. uECC_vli_modMult_fast(z, z, point + num_words, curve);
  11280. uECC_vli_modMult_fast(z, z, Rx[1 - nb],
  11281. curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */
  11282. /* End 1/Z calculation */
  11283. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  11284. apply_z(Rx[0], Ry[0], z, curve);
  11285. uECC_vli_set(result, Rx[0], num_words);
  11286. uECC_vli_set(result + num_words, Ry[0], num_words);
  11287. }
  11288. static uECC_word_t regularize_k(const uECC_word_t *const k, uECC_word_t *k0,
  11289. uECC_word_t *k1, uECC_Curve curve) {
  11290. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11291. bitcount_t num_n_bits = curve->num_n_bits;
  11292. uECC_word_t carry =
  11293. uECC_vli_add(k0, k, curve->n, num_n_words) ||
  11294. (num_n_bits < ((bitcount_t) num_n_words * uECC_WORD_SIZE * 8) &&
  11295. uECC_vli_testBit(k0, num_n_bits));
  11296. uECC_vli_add(k1, k0, curve->n, num_n_words);
  11297. return carry;
  11298. }
  11299. /* Generates a random integer in the range 0 < random < top.
  11300. Both random and top have num_words words. */
  11301. uECC_VLI_API int uECC_generate_random_int(uECC_word_t *random,
  11302. const uECC_word_t *top,
  11303. wordcount_t num_words) {
  11304. uECC_word_t mask = (uECC_word_t) -1;
  11305. uECC_word_t tries;
  11306. bitcount_t num_bits = uECC_vli_numBits(top, num_words);
  11307. if (!g_rng_function) {
  11308. return 0;
  11309. }
  11310. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11311. if (!g_rng_function((uint8_t *) random,
  11312. (unsigned int) (num_words * uECC_WORD_SIZE))) {
  11313. return 0;
  11314. }
  11315. random[num_words - 1] &=
  11316. mask >> ((bitcount_t) (num_words * uECC_WORD_SIZE * 8 - num_bits));
  11317. if (!uECC_vli_isZero(random, num_words) &&
  11318. uECC_vli_cmp(top, random, num_words) == 1) {
  11319. return 1;
  11320. }
  11321. }
  11322. return 0;
  11323. }
  11324. static uECC_word_t EccPoint_compute_public_key(uECC_word_t *result,
  11325. uECC_word_t *private_key,
  11326. uECC_Curve curve) {
  11327. uECC_word_t tmp1[uECC_MAX_WORDS];
  11328. uECC_word_t tmp2[uECC_MAX_WORDS];
  11329. uECC_word_t *p2[2] = {tmp1, tmp2};
  11330. uECC_word_t *initial_Z = 0;
  11331. uECC_word_t carry;
  11332. /* Regularize the bitcount for the private key so that attackers cannot use a
  11333. side channel attack to learn the number of leading zeros. */
  11334. carry = regularize_k(private_key, tmp1, tmp2, curve);
  11335. /* If an RNG function was specified, try to get a random initial Z value to
  11336. improve protection against side-channel attacks. */
  11337. if (g_rng_function) {
  11338. if (!uECC_generate_random_int(p2[carry], curve->p, curve->num_words)) {
  11339. return 0;
  11340. }
  11341. initial_Z = p2[carry];
  11342. }
  11343. EccPoint_mult(result, curve->G, p2[!carry], initial_Z,
  11344. (bitcount_t) (curve->num_n_bits + 1), curve);
  11345. if (EccPoint_isZero(result, curve)) {
  11346. return 0;
  11347. }
  11348. return 1;
  11349. }
  11350. #if uECC_WORD_SIZE == 1
  11351. uECC_VLI_API void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  11352. const uint8_t *native) {
  11353. wordcount_t i;
  11354. for (i = 0; i < num_bytes; ++i) {
  11355. bytes[i] = native[(num_bytes - 1) - i];
  11356. }
  11357. }
  11358. uECC_VLI_API void uECC_vli_bytesToNative(uint8_t *native, const uint8_t *bytes,
  11359. int num_bytes) {
  11360. uECC_vli_nativeToBytes(native, num_bytes, bytes);
  11361. }
  11362. #else
  11363. uECC_VLI_API void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  11364. const uECC_word_t *native) {
  11365. int i;
  11366. for (i = 0; i < num_bytes; ++i) {
  11367. unsigned b = (unsigned) (num_bytes - 1 - i);
  11368. bytes[i] =
  11369. (uint8_t) (native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE)));
  11370. }
  11371. }
  11372. uECC_VLI_API void uECC_vli_bytesToNative(uECC_word_t *native,
  11373. const uint8_t *bytes, int num_bytes) {
  11374. int i;
  11375. uECC_vli_clear(native, (wordcount_t) ((num_bytes + (uECC_WORD_SIZE - 1)) /
  11376. uECC_WORD_SIZE));
  11377. for (i = 0; i < num_bytes; ++i) {
  11378. unsigned b = (unsigned) (num_bytes - 1 - i);
  11379. native[b / uECC_WORD_SIZE] |= (uECC_word_t) bytes[i]
  11380. << (8 * (b % uECC_WORD_SIZE));
  11381. }
  11382. }
  11383. #endif /* uECC_WORD_SIZE */
  11384. int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve) {
  11385. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11386. uECC_word_t *_private = (uECC_word_t *) private_key;
  11387. uECC_word_t *_public = (uECC_word_t *) public_key;
  11388. #else
  11389. uECC_word_t _private[uECC_MAX_WORDS];
  11390. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11391. #endif
  11392. uECC_word_t tries;
  11393. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11394. if (!uECC_generate_random_int(_private, curve->n,
  11395. BITS_TO_WORDS(curve->num_n_bits))) {
  11396. return 0;
  11397. }
  11398. if (EccPoint_compute_public_key(_public, _private, curve)) {
  11399. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11400. uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits),
  11401. _private);
  11402. uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  11403. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  11404. _public + curve->num_words);
  11405. #endif
  11406. return 1;
  11407. }
  11408. }
  11409. return 0;
  11410. }
  11411. int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
  11412. uint8_t *secret, uECC_Curve curve) {
  11413. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11414. uECC_word_t _private[uECC_MAX_WORDS];
  11415. uECC_word_t tmp[uECC_MAX_WORDS];
  11416. uECC_word_t *p2[2] = {_private, tmp};
  11417. uECC_word_t *initial_Z = 0;
  11418. uECC_word_t carry;
  11419. wordcount_t num_words = curve->num_words;
  11420. wordcount_t num_bytes = curve->num_bytes;
  11421. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11422. bcopy((uint8_t *) _private, private_key, num_bytes);
  11423. bcopy((uint8_t *) _public, public_key, num_bytes * 2);
  11424. #else
  11425. uECC_vli_bytesToNative(_private, private_key,
  11426. BITS_TO_BYTES(curve->num_n_bits));
  11427. uECC_vli_bytesToNative(_public, public_key, num_bytes);
  11428. uECC_vli_bytesToNative(_public + num_words, public_key + num_bytes,
  11429. num_bytes);
  11430. #endif
  11431. /* Regularize the bitcount for the private key so that attackers cannot use a
  11432. side channel attack to learn the number of leading zeros. */
  11433. carry = regularize_k(_private, _private, tmp, curve);
  11434. /* If an RNG function was specified, try to get a random initial Z value to
  11435. improve protection against side-channel attacks. */
  11436. if (g_rng_function) {
  11437. if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) {
  11438. return 0;
  11439. }
  11440. initial_Z = p2[carry];
  11441. }
  11442. EccPoint_mult(_public, _public, p2[!carry], initial_Z,
  11443. (bitcount_t) (curve->num_n_bits + 1), curve);
  11444. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11445. bcopy((uint8_t *) secret, (uint8_t *) _public, num_bytes);
  11446. #else
  11447. uECC_vli_nativeToBytes(secret, num_bytes, _public);
  11448. #endif
  11449. return !EccPoint_isZero(_public, curve);
  11450. }
  11451. #if uECC_SUPPORT_COMPRESSED_POINT
  11452. void uECC_compress(const uint8_t *public_key, uint8_t *compressed,
  11453. uECC_Curve curve) {
  11454. wordcount_t i;
  11455. for (i = 0; i < curve->num_bytes; ++i) {
  11456. compressed[i + 1] = public_key[i];
  11457. }
  11458. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11459. compressed[0] = 2 + (public_key[curve->num_bytes] & 0x01);
  11460. #else
  11461. compressed[0] = 2 + (public_key[curve->num_bytes * 2 - 1] & 0x01);
  11462. #endif
  11463. }
  11464. void uECC_decompress(const uint8_t *compressed, uint8_t *public_key,
  11465. uECC_Curve curve) {
  11466. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11467. uECC_word_t *point = (uECC_word_t *) public_key;
  11468. #else
  11469. uECC_word_t point[uECC_MAX_WORDS * 2];
  11470. #endif
  11471. uECC_word_t *y = point + curve->num_words;
  11472. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11473. bcopy(public_key, compressed + 1, curve->num_bytes);
  11474. #else
  11475. uECC_vli_bytesToNative(point, compressed + 1, curve->num_bytes);
  11476. #endif
  11477. curve->x_side(y, point, curve);
  11478. curve->mod_sqrt(y, curve);
  11479. if ((uint8_t) (y[0] & 0x01) != (compressed[0] & 0x01)) {
  11480. uECC_vli_sub(y, curve->p, y, curve->num_words);
  11481. }
  11482. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11483. uECC_vli_nativeToBytes(public_key, curve->num_bytes, point);
  11484. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, y);
  11485. #endif
  11486. }
  11487. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  11488. uECC_VLI_API int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve) {
  11489. uECC_word_t tmp1[uECC_MAX_WORDS];
  11490. uECC_word_t tmp2[uECC_MAX_WORDS];
  11491. wordcount_t num_words = curve->num_words;
  11492. /* The point at infinity is invalid. */
  11493. if (EccPoint_isZero(point, curve)) {
  11494. return 0;
  11495. }
  11496. /* x and y must be smaller than p. */
  11497. if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
  11498. uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
  11499. return 0;
  11500. }
  11501. uECC_vli_modSquare_fast(tmp1, point + num_words, curve);
  11502. curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
  11503. /* Make sure that y^2 == x^3 + ax + b */
  11504. return (int) (uECC_vli_equal(tmp1, tmp2, num_words));
  11505. }
  11506. int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve) {
  11507. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11508. uECC_word_t *_public = (uECC_word_t *) public_key;
  11509. #else
  11510. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11511. #endif
  11512. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11513. uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
  11514. uECC_vli_bytesToNative(_public + curve->num_words,
  11515. public_key + curve->num_bytes, curve->num_bytes);
  11516. #endif
  11517. return uECC_valid_point(_public, curve);
  11518. }
  11519. int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
  11520. uECC_Curve curve) {
  11521. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11522. uECC_word_t *_private = (uECC_word_t *) private_key;
  11523. uECC_word_t *_public = (uECC_word_t *) public_key;
  11524. #else
  11525. uECC_word_t _private[uECC_MAX_WORDS];
  11526. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11527. #endif
  11528. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11529. uECC_vli_bytesToNative(_private, private_key,
  11530. BITS_TO_BYTES(curve->num_n_bits));
  11531. #endif
  11532. /* Make sure the private key is in the range [1, n-1]. */
  11533. if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
  11534. return 0;
  11535. }
  11536. if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) {
  11537. return 0;
  11538. }
  11539. /* Compute public key. */
  11540. if (!EccPoint_compute_public_key(_public, _private, curve)) {
  11541. return 0;
  11542. }
  11543. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11544. uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  11545. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  11546. _public + curve->num_words);
  11547. #endif
  11548. return 1;
  11549. }
  11550. /* -------- ECDSA code -------- */
  11551. static void bits2int(uECC_word_t *native, const uint8_t *bits,
  11552. unsigned bits_size, uECC_Curve curve) {
  11553. unsigned num_n_bytes = (unsigned) BITS_TO_BYTES(curve->num_n_bits);
  11554. unsigned num_n_words = (unsigned) BITS_TO_WORDS(curve->num_n_bits);
  11555. int shift;
  11556. uECC_word_t carry;
  11557. uECC_word_t *ptr;
  11558. if (bits_size > num_n_bytes) {
  11559. bits_size = num_n_bytes;
  11560. }
  11561. uECC_vli_clear(native, (wordcount_t) num_n_words);
  11562. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11563. bcopy((uint8_t *) native, bits, bits_size);
  11564. #else
  11565. uECC_vli_bytesToNative(native, bits, (int) bits_size);
  11566. #endif
  11567. if (bits_size * 8 <= (unsigned) curve->num_n_bits) {
  11568. return;
  11569. }
  11570. shift = (int) bits_size * 8 - curve->num_n_bits;
  11571. carry = 0;
  11572. ptr = native + num_n_words;
  11573. while (ptr-- > native) {
  11574. uECC_word_t temp = *ptr;
  11575. *ptr = (temp >> shift) | carry;
  11576. carry = temp << (uECC_WORD_BITS - shift);
  11577. }
  11578. /* Reduce mod curve_n */
  11579. if (uECC_vli_cmp_unsafe(curve->n, native, (wordcount_t) num_n_words) != 1) {
  11580. uECC_vli_sub(native, native, curve->n, (wordcount_t) num_n_words);
  11581. }
  11582. }
  11583. static int uECC_sign_with_k_internal(const uint8_t *private_key,
  11584. const uint8_t *message_hash,
  11585. unsigned hash_size, uECC_word_t *k,
  11586. uint8_t *signature, uECC_Curve curve) {
  11587. uECC_word_t tmp[uECC_MAX_WORDS];
  11588. uECC_word_t s[uECC_MAX_WORDS];
  11589. uECC_word_t *k2[2] = {tmp, s};
  11590. uECC_word_t *initial_Z = 0;
  11591. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11592. uECC_word_t *p = (uECC_word_t *) signature;
  11593. #else
  11594. uECC_word_t p[uECC_MAX_WORDS * 2];
  11595. #endif
  11596. uECC_word_t carry;
  11597. wordcount_t num_words = curve->num_words;
  11598. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11599. bitcount_t num_n_bits = curve->num_n_bits;
  11600. /* Make sure 0 < k < curve_n */
  11601. if (uECC_vli_isZero(k, num_words) ||
  11602. uECC_vli_cmp(curve->n, k, num_n_words) != 1) {
  11603. return 0;
  11604. }
  11605. carry = regularize_k(k, tmp, s, curve);
  11606. /* If an RNG function was specified, try to get a random initial Z value to
  11607. improve protection against side-channel attacks. */
  11608. if (g_rng_function) {
  11609. if (!uECC_generate_random_int(k2[carry], curve->p, num_words)) {
  11610. return 0;
  11611. }
  11612. initial_Z = k2[carry];
  11613. }
  11614. EccPoint_mult(p, curve->G, k2[!carry], initial_Z,
  11615. (bitcount_t) (num_n_bits + 1), curve);
  11616. if (uECC_vli_isZero(p, num_words)) {
  11617. return 0;
  11618. }
  11619. /* If an RNG function was specified, get a random number
  11620. to prevent side channel analysis of k. */
  11621. if (!g_rng_function) {
  11622. uECC_vli_clear(tmp, num_n_words);
  11623. tmp[0] = 1;
  11624. } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {
  11625. return 0;
  11626. }
  11627. /* Prevent side channel analysis of uECC_vli_modInv() to determine
  11628. bits of k / the private key by premultiplying by a random number */
  11629. uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
  11630. uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */
  11631. uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
  11632. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11633. uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
  11634. #endif
  11635. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11636. bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
  11637. #else
  11638. uECC_vli_bytesToNative(tmp, private_key,
  11639. BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */
  11640. #endif
  11641. s[num_n_words - 1] = 0;
  11642. uECC_vli_set(s, p, num_words);
  11643. uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
  11644. bits2int(tmp, message_hash, hash_size, curve);
  11645. uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
  11646. uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */
  11647. if (uECC_vli_numBits(s, num_n_words) > (bitcount_t) curve->num_bytes * 8) {
  11648. return 0;
  11649. }
  11650. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11651. bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s,
  11652. curve->num_bytes);
  11653. #else
  11654. uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
  11655. #endif
  11656. return 1;
  11657. }
  11658. #if 0
  11659. /* For testing - sign with an explicitly specified k value */
  11660. int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
  11661. unsigned hash_size, const uint8_t *k, uint8_t *signature,
  11662. uECC_Curve curve) {
  11663. uECC_word_t k2[uECC_MAX_WORDS];
  11664. bits2int(k2, k, (unsigned) BITS_TO_BYTES(curve->num_n_bits), curve);
  11665. return uECC_sign_with_k_internal(private_key, message_hash, hash_size, k2,
  11666. signature, curve);
  11667. }
  11668. #endif
  11669. int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash,
  11670. unsigned hash_size, uint8_t *signature, uECC_Curve curve) {
  11671. uECC_word_t k[uECC_MAX_WORDS];
  11672. uECC_word_t tries;
  11673. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11674. if (!uECC_generate_random_int(k, curve->n,
  11675. BITS_TO_WORDS(curve->num_n_bits))) {
  11676. return 0;
  11677. }
  11678. if (uECC_sign_with_k_internal(private_key, message_hash, hash_size, k,
  11679. signature, curve)) {
  11680. return 1;
  11681. }
  11682. }
  11683. return 0;
  11684. }
  11685. /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always
  11686. the same size as the hash result size. */
  11687. static void HMAC_init(const uECC_HashContext *hash_context, const uint8_t *K) {
  11688. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  11689. unsigned i;
  11690. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x36;
  11691. for (; i < hash_context->block_size; ++i) pad[i] = 0x36;
  11692. hash_context->init_hash(hash_context);
  11693. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  11694. }
  11695. static void HMAC_update(const uECC_HashContext *hash_context,
  11696. const uint8_t *message, unsigned message_size) {
  11697. hash_context->update_hash(hash_context, message, message_size);
  11698. }
  11699. static void HMAC_finish(const uECC_HashContext *hash_context, const uint8_t *K,
  11700. uint8_t *result) {
  11701. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  11702. unsigned i;
  11703. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x5c;
  11704. for (; i < hash_context->block_size; ++i) pad[i] = 0x5c;
  11705. hash_context->finish_hash(hash_context, result);
  11706. hash_context->init_hash(hash_context);
  11707. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  11708. hash_context->update_hash(hash_context, result, hash_context->result_size);
  11709. hash_context->finish_hash(hash_context, result);
  11710. }
  11711. /* V = HMAC_K(V) */
  11712. static void update_V(const uECC_HashContext *hash_context, uint8_t *K,
  11713. uint8_t *V) {
  11714. HMAC_init(hash_context, K);
  11715. HMAC_update(hash_context, V, hash_context->result_size);
  11716. HMAC_finish(hash_context, K, V);
  11717. }
  11718. /* Deterministic signing, similar to RFC 6979. Differences are:
  11719. * We just use H(m) directly rather than bits2octets(H(m))
  11720. (it is not reduced modulo curve_n).
  11721. * We generate a value for k (aka T) directly rather than converting
  11722. endianness.
  11723. Layout of hash_context->tmp: <K> | <V> | (1 byte overlapped 0x00 or 0x01) /
  11724. <HMAC pad> */
  11725. int uECC_sign_deterministic(const uint8_t *private_key,
  11726. const uint8_t *message_hash, unsigned hash_size,
  11727. const uECC_HashContext *hash_context,
  11728. uint8_t *signature, uECC_Curve curve) {
  11729. uint8_t *K = hash_context->tmp;
  11730. uint8_t *V = K + hash_context->result_size;
  11731. wordcount_t num_bytes = curve->num_bytes;
  11732. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11733. bitcount_t num_n_bits = curve->num_n_bits;
  11734. uECC_word_t tries;
  11735. unsigned i;
  11736. for (i = 0; i < hash_context->result_size; ++i) {
  11737. V[i] = 0x01;
  11738. K[i] = 0;
  11739. }
  11740. /* K = HMAC_K(V || 0x00 || int2octets(x) || h(m)) */
  11741. HMAC_init(hash_context, K);
  11742. V[hash_context->result_size] = 0x00;
  11743. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11744. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  11745. HMAC_update(hash_context, message_hash, hash_size);
  11746. HMAC_finish(hash_context, K, K);
  11747. update_V(hash_context, K, V);
  11748. /* K = HMAC_K(V || 0x01 || int2octets(x) || h(m)) */
  11749. HMAC_init(hash_context, K);
  11750. V[hash_context->result_size] = 0x01;
  11751. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11752. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  11753. HMAC_update(hash_context, message_hash, hash_size);
  11754. HMAC_finish(hash_context, K, K);
  11755. update_V(hash_context, K, V);
  11756. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11757. uECC_word_t T[uECC_MAX_WORDS];
  11758. uint8_t *T_ptr = (uint8_t *) T;
  11759. wordcount_t T_bytes = 0;
  11760. for (;;) {
  11761. update_V(hash_context, K, V);
  11762. for (i = 0; i < hash_context->result_size; ++i) {
  11763. T_ptr[T_bytes++] = V[i];
  11764. if (T_bytes >= num_n_words * uECC_WORD_SIZE) {
  11765. goto filled;
  11766. }
  11767. }
  11768. }
  11769. filled:
  11770. if ((bitcount_t) num_n_words * uECC_WORD_SIZE * 8 > num_n_bits) {
  11771. uECC_word_t mask = (uECC_word_t) -1;
  11772. T[num_n_words - 1] &=
  11773. mask >>
  11774. ((bitcount_t) (num_n_words * uECC_WORD_SIZE * 8 - num_n_bits));
  11775. }
  11776. if (uECC_sign_with_k_internal(private_key, message_hash, hash_size, T,
  11777. signature, curve)) {
  11778. return 1;
  11779. }
  11780. /* K = HMAC_K(V || 0x00) */
  11781. HMAC_init(hash_context, K);
  11782. V[hash_context->result_size] = 0x00;
  11783. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11784. HMAC_finish(hash_context, K, K);
  11785. update_V(hash_context, K, V);
  11786. }
  11787. return 0;
  11788. }
  11789. static bitcount_t smax(bitcount_t a, bitcount_t b) {
  11790. return (a > b ? a : b);
  11791. }
  11792. int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash,
  11793. unsigned hash_size, const uint8_t *signature,
  11794. uECC_Curve curve) {
  11795. uECC_word_t u1[uECC_MAX_WORDS], u2[uECC_MAX_WORDS];
  11796. uECC_word_t z[uECC_MAX_WORDS];
  11797. uECC_word_t sum[uECC_MAX_WORDS * 2];
  11798. uECC_word_t rx[uECC_MAX_WORDS];
  11799. uECC_word_t ry[uECC_MAX_WORDS];
  11800. uECC_word_t tx[uECC_MAX_WORDS];
  11801. uECC_word_t ty[uECC_MAX_WORDS];
  11802. uECC_word_t tz[uECC_MAX_WORDS];
  11803. const uECC_word_t *points[4];
  11804. const uECC_word_t *point;
  11805. bitcount_t num_bits;
  11806. bitcount_t i;
  11807. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11808. uECC_word_t *_public = (uECC_word_t *) public_key;
  11809. #else
  11810. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11811. #endif
  11812. uECC_word_t r[uECC_MAX_WORDS], s[uECC_MAX_WORDS];
  11813. wordcount_t num_words = curve->num_words;
  11814. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11815. rx[num_n_words - 1] = 0;
  11816. r[num_n_words - 1] = 0;
  11817. s[num_n_words - 1] = 0;
  11818. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11819. bcopy((uint8_t *) r, signature, curve->num_bytes);
  11820. bcopy((uint8_t *) s, signature + curve->num_bytes, curve->num_bytes);
  11821. #else
  11822. uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
  11823. uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
  11824. curve->num_bytes);
  11825. uECC_vli_bytesToNative(r, signature, curve->num_bytes);
  11826. uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
  11827. #endif
  11828. /* r, s must not be 0. */
  11829. if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
  11830. return 0;
  11831. }
  11832. /* r, s must be < n. */
  11833. if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
  11834. uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
  11835. return 0;
  11836. }
  11837. /* Calculate u1 and u2. */
  11838. uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
  11839. u1[num_n_words - 1] = 0;
  11840. bits2int(u1, message_hash, hash_size, curve);
  11841. uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
  11842. uECC_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */
  11843. /* Calculate sum = G + Q. */
  11844. uECC_vli_set(sum, _public, num_words);
  11845. uECC_vli_set(sum + num_words, _public + num_words, num_words);
  11846. uECC_vli_set(tx, curve->G, num_words);
  11847. uECC_vli_set(ty, curve->G + num_words, num_words);
  11848. uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
  11849. XYcZ_add(tx, ty, sum, sum + num_words, curve);
  11850. uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
  11851. apply_z(sum, sum + num_words, z, curve);
  11852. /* Use Shamir's trick to calculate u1*G + u2*Q */
  11853. points[0] = 0;
  11854. points[1] = curve->G;
  11855. points[2] = _public;
  11856. points[3] = sum;
  11857. num_bits = smax(uECC_vli_numBits(u1, num_n_words),
  11858. uECC_vli_numBits(u2, num_n_words));
  11859. point = points[(!!uECC_vli_testBit(u1, (bitcount_t) (num_bits - 1))) |
  11860. ((!!uECC_vli_testBit(u2, (bitcount_t) (num_bits - 1))) << 1)];
  11861. uECC_vli_set(rx, point, num_words);
  11862. uECC_vli_set(ry, point + num_words, num_words);
  11863. uECC_vli_clear(z, num_words);
  11864. z[0] = 1;
  11865. for (i = num_bits - 2; i >= 0; --i) {
  11866. uECC_word_t index;
  11867. curve->double_jacobian(rx, ry, z, curve);
  11868. index = (!!uECC_vli_testBit(u1, i)) |
  11869. (uECC_word_t) ((!!uECC_vli_testBit(u2, i)) << 1);
  11870. point = points[index];
  11871. if (point) {
  11872. uECC_vli_set(tx, point, num_words);
  11873. uECC_vli_set(ty, point + num_words, num_words);
  11874. apply_z(tx, ty, z, curve);
  11875. uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
  11876. XYcZ_add(tx, ty, rx, ry, curve);
  11877. uECC_vli_modMult_fast(z, z, tz, curve);
  11878. }
  11879. }
  11880. uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
  11881. apply_z(rx, ry, z, curve);
  11882. /* v = x1 (mod n) */
  11883. if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
  11884. uECC_vli_sub(rx, rx, curve->n, num_n_words);
  11885. }
  11886. /* Accept only if v == r. */
  11887. return (int) (uECC_vli_equal(rx, r, num_words));
  11888. }
  11889. #if uECC_ENABLE_VLI_API
  11890. unsigned uECC_curve_num_words(uECC_Curve curve) {
  11891. return curve->num_words;
  11892. }
  11893. unsigned uECC_curve_num_bytes(uECC_Curve curve) {
  11894. return curve->num_bytes;
  11895. }
  11896. unsigned uECC_curve_num_bits(uECC_Curve curve) {
  11897. return curve->num_bytes * 8;
  11898. }
  11899. unsigned uECC_curve_num_n_words(uECC_Curve curve) {
  11900. return BITS_TO_WORDS(curve->num_n_bits);
  11901. }
  11902. unsigned uECC_curve_num_n_bytes(uECC_Curve curve) {
  11903. return BITS_TO_BYTES(curve->num_n_bits);
  11904. }
  11905. unsigned uECC_curve_num_n_bits(uECC_Curve curve) {
  11906. return curve->num_n_bits;
  11907. }
  11908. const uECC_word_t *uECC_curve_p(uECC_Curve curve) {
  11909. return curve->p;
  11910. }
  11911. const uECC_word_t *uECC_curve_n(uECC_Curve curve) {
  11912. return curve->n;
  11913. }
  11914. const uECC_word_t *uECC_curve_G(uECC_Curve curve) {
  11915. return curve->G;
  11916. }
  11917. const uECC_word_t *uECC_curve_b(uECC_Curve curve) {
  11918. return curve->b;
  11919. }
  11920. #if uECC_SUPPORT_COMPRESSED_POINT
  11921. void uECC_vli_mod_sqrt(uECC_word_t *a, uECC_Curve curve) {
  11922. curve->mod_sqrt(a, curve);
  11923. }
  11924. #endif
  11925. void uECC_vli_mmod_fast(uECC_word_t *result, uECC_word_t *product,
  11926. uECC_Curve curve) {
  11927. #if (uECC_OPTIMIZATION_LEVEL > 0)
  11928. curve->mmod_fast(result, product);
  11929. #else
  11930. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  11931. #endif
  11932. }
  11933. void uECC_point_mult(uECC_word_t *result, const uECC_word_t *point,
  11934. const uECC_word_t *scalar, uECC_Curve curve) {
  11935. uECC_word_t tmp1[uECC_MAX_WORDS];
  11936. uECC_word_t tmp2[uECC_MAX_WORDS];
  11937. uECC_word_t *p2[2] = {tmp1, tmp2};
  11938. uECC_word_t carry = regularize_k(scalar, tmp1, tmp2, curve);
  11939. EccPoint_mult(result, point, p2[!carry], 0, curve->num_n_bits + 1, curve);
  11940. }
  11941. #endif /* uECC_ENABLE_VLI_API */
  11942. #endif // MG_TLS_BUILTIN
  11943. // End of uecc BSD-2
  11944. #ifdef MG_ENABLE_LINES
  11945. #line 1 "src/url.c"
  11946. #endif
  11947. struct url {
  11948. size_t key, user, pass, host, port, uri, end;
  11949. };
  11950. int mg_url_is_ssl(const char *url) {
  11951. return strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0 ||
  11952. strncmp(url, "mqtts:", 6) == 0 || strncmp(url, "ssl:", 4) == 0 ||
  11953. strncmp(url, "tls:", 4) == 0 || strncmp(url, "tcps:", 5) == 0;
  11954. }
  11955. static struct url urlparse(const char *url) {
  11956. size_t i;
  11957. struct url u;
  11958. memset(&u, 0, sizeof(u));
  11959. for (i = 0; url[i] != '\0'; i++) {
  11960. if (url[i] == '/' && i > 0 && u.host == 0 && url[i - 1] == '/') {
  11961. u.host = i + 1;
  11962. u.port = 0;
  11963. } else if (url[i] == ']') {
  11964. u.port = 0; // IPv6 URLs, like http://[::1]/bar
  11965. } else if (url[i] == ':' && u.port == 0 && u.uri == 0) {
  11966. u.port = i + 1;
  11967. } else if (url[i] == '@' && u.user == 0 && u.pass == 0 && u.uri == 0) {
  11968. u.user = u.host;
  11969. u.pass = u.port;
  11970. u.host = i + 1;
  11971. u.port = 0;
  11972. } else if (url[i] == '/' && u.host && u.uri == 0) {
  11973. u.uri = i;
  11974. }
  11975. }
  11976. u.end = i;
  11977. #if 0
  11978. printf("[%s] %d %d %d %d %d\n", url, u.user, u.pass, u.host, u.port, u.uri);
  11979. #endif
  11980. return u;
  11981. }
  11982. struct mg_str mg_url_host(const char *url) {
  11983. struct url u = urlparse(url);
  11984. size_t n = u.port ? u.port - u.host - 1
  11985. : u.uri ? u.uri - u.host
  11986. : u.end - u.host;
  11987. struct mg_str s = mg_str_n(url + u.host, n);
  11988. return s;
  11989. }
  11990. const char *mg_url_uri(const char *url) {
  11991. struct url u = urlparse(url);
  11992. return u.uri ? url + u.uri : "/";
  11993. }
  11994. unsigned short mg_url_port(const char *url) {
  11995. struct url u = urlparse(url);
  11996. unsigned short port = 0;
  11997. if (strncmp(url, "http:", 5) == 0 || strncmp(url, "ws:", 3) == 0) port = 80;
  11998. if (strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0)
  11999. port = 443;
  12000. if (strncmp(url, "mqtt:", 5) == 0) port = 1883;
  12001. if (strncmp(url, "mqtts:", 6) == 0) port = 8883;
  12002. if (u.port) port = (unsigned short) atoi(url + u.port);
  12003. return port;
  12004. }
  12005. struct mg_str mg_url_user(const char *url) {
  12006. struct url u = urlparse(url);
  12007. struct mg_str s = mg_str("");
  12008. if (u.user && (u.pass || u.host)) {
  12009. size_t n = u.pass ? u.pass - u.user - 1 : u.host - u.user - 1;
  12010. s = mg_str_n(url + u.user, n);
  12011. }
  12012. return s;
  12013. }
  12014. struct mg_str mg_url_pass(const char *url) {
  12015. struct url u = urlparse(url);
  12016. struct mg_str s = mg_str_n("", 0UL);
  12017. if (u.pass && u.host) {
  12018. size_t n = u.host - u.pass - 1;
  12019. s = mg_str_n(url + u.pass, n);
  12020. }
  12021. return s;
  12022. }
  12023. #ifdef MG_ENABLE_LINES
  12024. #line 1 "src/util.c"
  12025. #endif
  12026. // Not using memset for zeroing memory, cause it can be dropped by compiler
  12027. // See https://github.com/cesanta/mongoose/pull/1265
  12028. void mg_bzero(volatile unsigned char *buf, size_t len) {
  12029. if (buf != NULL) {
  12030. while (len--) *buf++ = 0;
  12031. }
  12032. }
  12033. #if MG_ENABLE_CUSTOM_RANDOM
  12034. #else
  12035. void mg_random(void *buf, size_t len) {
  12036. bool done = false;
  12037. unsigned char *p = (unsigned char *) buf;
  12038. #if MG_ARCH == MG_ARCH_ESP32
  12039. while (len--) *p++ = (unsigned char) (esp_random() & 255);
  12040. done = true;
  12041. #elif MG_ARCH == MG_ARCH_WIN32
  12042. #elif MG_ARCH == MG_ARCH_UNIX
  12043. FILE *fp = fopen("/dev/urandom", "rb");
  12044. if (fp != NULL) {
  12045. if (fread(buf, 1, len, fp) == len) done = true;
  12046. fclose(fp);
  12047. }
  12048. #endif
  12049. // If everything above did not work, fallback to a pseudo random generator
  12050. while (!done && len--) *p++ = (unsigned char) (rand() & 255);
  12051. }
  12052. #endif
  12053. char *mg_random_str(char *buf, size_t len) {
  12054. size_t i;
  12055. mg_random(buf, len);
  12056. for (i = 0; i < len; i++) {
  12057. uint8_t c = ((uint8_t *) buf)[i] % 62U;
  12058. buf[i] = i == len - 1 ? (char) '\0' // 0-terminate last byte
  12059. : c < 26 ? (char) ('a' + c) // lowercase
  12060. : c < 52 ? (char) ('A' + c - 26) // uppercase
  12061. : (char) ('0' + c - 52); // numeric
  12062. }
  12063. return buf;
  12064. }
  12065. uint32_t mg_ntohl(uint32_t net) {
  12066. uint8_t data[4] = {0, 0, 0, 0};
  12067. memcpy(&data, &net, sizeof(data));
  12068. return (((uint32_t) data[3]) << 0) | (((uint32_t) data[2]) << 8) |
  12069. (((uint32_t) data[1]) << 16) | (((uint32_t) data[0]) << 24);
  12070. }
  12071. uint16_t mg_ntohs(uint16_t net) {
  12072. uint8_t data[2] = {0, 0};
  12073. memcpy(&data, &net, sizeof(data));
  12074. return (uint16_t) ((uint16_t) data[1] | (((uint16_t) data[0]) << 8));
  12075. }
  12076. uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len) {
  12077. static const uint32_t crclut[16] = {
  12078. // table for polynomial 0xEDB88320 (reflected)
  12079. 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
  12080. 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
  12081. 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
  12082. crc = ~crc;
  12083. while (len--) {
  12084. uint8_t byte = *(uint8_t *) buf++;
  12085. crc = crclut[(crc ^ byte) & 0x0F] ^ (crc >> 4);
  12086. crc = crclut[(crc ^ (byte >> 4)) & 0x0F] ^ (crc >> 4);
  12087. }
  12088. return ~crc;
  12089. }
  12090. static int isbyte(int n) {
  12091. return n >= 0 && n <= 255;
  12092. }
  12093. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  12094. int n, a, b, c, d, slash = 32, len = 0;
  12095. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  12096. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  12097. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  12098. slash < 33) {
  12099. len = n;
  12100. *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) |
  12101. (uint32_t) d;
  12102. *mask = slash ? (uint32_t) (0xffffffffU << (32 - slash)) : (uint32_t) 0;
  12103. }
  12104. return len;
  12105. }
  12106. int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) {
  12107. struct mg_str k, v;
  12108. int allowed = acl.len == 0 ? '+' : '-'; // If any ACL is set, deny by default
  12109. uint32_t remote_ip4;
  12110. if (remote_ip->is_ip6) {
  12111. return -1; // TODO(): handle IPv6 ACL and addresses
  12112. } else { // IPv4
  12113. memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4));
  12114. while (mg_commalist(&acl, &k, &v)) {
  12115. uint32_t net, mask;
  12116. if (k.ptr[0] != '+' && k.ptr[0] != '-') return -1;
  12117. if (parse_net(&k.ptr[1], &net, &mask) == 0) return -2;
  12118. if ((mg_ntohl(remote_ip4) & mask) == net) allowed = k.ptr[0];
  12119. }
  12120. }
  12121. return allowed == '+';
  12122. }
  12123. #if MG_ENABLE_CUSTOM_MILLIS
  12124. #else
  12125. uint64_t mg_millis(void) {
  12126. #if MG_ARCH == MG_ARCH_WIN32
  12127. return GetTickCount();
  12128. #elif MG_ARCH == MG_ARCH_RP2040
  12129. return time_us_64() / 1000;
  12130. #elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \
  12131. MG_ARCH == MG_ARCH_FREERTOS
  12132. return xTaskGetTickCount() * portTICK_PERIOD_MS;
  12133. #elif MG_ARCH == MG_ARCH_AZURERTOS
  12134. return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND);
  12135. #elif MG_ARCH == MG_ARCH_TIRTOS
  12136. return (uint64_t) Clock_getTicks();
  12137. #elif MG_ARCH == MG_ARCH_ZEPHYR
  12138. return (uint64_t) k_uptime_get();
  12139. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
  12140. return (uint64_t) rt_time_get();
  12141. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
  12142. return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq());
  12143. #elif MG_ARCH == MG_ARCH_RTTHREAD
  12144. return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND);
  12145. #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
  12146. // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
  12147. // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
  12148. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000;
  12149. #elif MG_ARCH == MG_ARCH_UNIX
  12150. struct timespec ts = {0, 0};
  12151. // See #1615 - prefer monotonic clock
  12152. #if defined(CLOCK_MONOTONIC_RAW)
  12153. // Raw hardware-based time that is not subject to NTP adjustment
  12154. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  12155. #elif defined(CLOCK_MONOTONIC)
  12156. // Affected by the incremental adjustments performed by adjtime and NTP
  12157. clock_gettime(CLOCK_MONOTONIC, &ts);
  12158. #else
  12159. // Affected by discontinuous jumps in the system time and by the incremental
  12160. // adjustments performed by adjtime and NTP
  12161. clock_gettime(CLOCK_REALTIME, &ts);
  12162. #endif
  12163. return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000);
  12164. #elif defined(ARDUINO)
  12165. return (uint64_t) millis();
  12166. #else
  12167. return (uint64_t) (time(NULL) * 1000);
  12168. #endif
  12169. }
  12170. #endif
  12171. #ifdef MG_ENABLE_LINES
  12172. #line 1 "src/ws.c"
  12173. #endif
  12174. struct ws_msg {
  12175. uint8_t flags;
  12176. size_t header_len;
  12177. size_t data_len;
  12178. };
  12179. size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
  12180. va_list *ap) {
  12181. size_t len = c->send.len;
  12182. size_t n = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  12183. mg_ws_wrap(c, c->send.len - len, op);
  12184. return n;
  12185. }
  12186. size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...) {
  12187. size_t len = 0;
  12188. va_list ap;
  12189. va_start(ap, fmt);
  12190. len = mg_ws_vprintf(c, op, fmt, &ap);
  12191. va_end(ap);
  12192. return len;
  12193. }
  12194. static void ws_handshake(struct mg_connection *c, const struct mg_str *wskey,
  12195. const struct mg_str *wsproto, const char *fmt,
  12196. va_list *ap) {
  12197. const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  12198. unsigned char sha[20], b64_sha[30];
  12199. mg_sha1_ctx sha_ctx;
  12200. mg_sha1_init(&sha_ctx);
  12201. mg_sha1_update(&sha_ctx, (unsigned char *) wskey->ptr, wskey->len);
  12202. mg_sha1_update(&sha_ctx, (unsigned char *) magic, 36);
  12203. mg_sha1_final(sha, &sha_ctx);
  12204. mg_base64_encode(sha, sizeof(sha), (char *) b64_sha, sizeof(b64_sha));
  12205. mg_xprintf(mg_pfn_iobuf, &c->send,
  12206. "HTTP/1.1 101 Switching Protocols\r\n"
  12207. "Upgrade: websocket\r\n"
  12208. "Connection: Upgrade\r\n"
  12209. "Sec-WebSocket-Accept: %s\r\n",
  12210. b64_sha);
  12211. if (fmt != NULL) mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  12212. if (wsproto != NULL) {
  12213. mg_printf(c, "Sec-WebSocket-Protocol: %.*s\r\n", (int) wsproto->len,
  12214. wsproto->ptr);
  12215. }
  12216. mg_send(c, "\r\n", 2);
  12217. }
  12218. static uint32_t be32(const uint8_t *p) {
  12219. return (((uint32_t) p[3]) << 0) | (((uint32_t) p[2]) << 8) |
  12220. (((uint32_t) p[1]) << 16) | (((uint32_t) p[0]) << 24);
  12221. }
  12222. static size_t ws_process(uint8_t *buf, size_t len, struct ws_msg *msg) {
  12223. size_t i, n = 0, mask_len = 0;
  12224. memset(msg, 0, sizeof(*msg));
  12225. if (len >= 2) {
  12226. n = buf[1] & 0x7f; // Frame length
  12227. mask_len = buf[1] & 128 ? 4 : 0; // last bit is a mask bit
  12228. msg->flags = buf[0];
  12229. if (n < 126 && len >= mask_len) {
  12230. msg->data_len = n;
  12231. msg->header_len = 2 + mask_len;
  12232. } else if (n == 126 && len >= 4 + mask_len) {
  12233. msg->header_len = 4 + mask_len;
  12234. msg->data_len = (((size_t) buf[2]) << 8) | buf[3];
  12235. } else if (len >= 10 + mask_len) {
  12236. msg->header_len = 10 + mask_len;
  12237. msg->data_len =
  12238. (size_t) (((uint64_t) be32(buf + 2) << 32) + be32(buf + 6));
  12239. }
  12240. }
  12241. // Sanity check, and integer overflow protection for the boundary check below
  12242. // data_len should not be larger than 1 Gb
  12243. if (msg->data_len > 1024 * 1024 * 1024) return 0;
  12244. if (msg->header_len + msg->data_len > len) return 0;
  12245. if (mask_len > 0) {
  12246. uint8_t *p = buf + msg->header_len, *m = p - mask_len;
  12247. for (i = 0; i < msg->data_len; i++) p[i] ^= m[i & 3];
  12248. }
  12249. return msg->header_len + msg->data_len;
  12250. }
  12251. static size_t mkhdr(size_t len, int op, bool is_client, uint8_t *buf) {
  12252. size_t n = 0;
  12253. buf[0] = (uint8_t) (op | 128);
  12254. if (len < 126) {
  12255. buf[1] = (unsigned char) len;
  12256. n = 2;
  12257. } else if (len < 65536) {
  12258. uint16_t tmp = mg_htons((uint16_t) len);
  12259. buf[1] = 126;
  12260. memcpy(&buf[2], &tmp, sizeof(tmp));
  12261. n = 4;
  12262. } else {
  12263. uint32_t tmp;
  12264. buf[1] = 127;
  12265. tmp = mg_htonl((uint32_t) (((uint64_t) len) >> 32));
  12266. memcpy(&buf[2], &tmp, sizeof(tmp));
  12267. tmp = mg_htonl((uint32_t) (len & 0xffffffffU));
  12268. memcpy(&buf[6], &tmp, sizeof(tmp));
  12269. n = 10;
  12270. }
  12271. if (is_client) {
  12272. buf[1] |= 1 << 7; // Set masking flag
  12273. mg_random(&buf[n], 4);
  12274. n += 4;
  12275. }
  12276. return n;
  12277. }
  12278. static void mg_ws_mask(struct mg_connection *c, size_t len) {
  12279. if (c->is_client && c->send.buf != NULL) {
  12280. size_t i;
  12281. uint8_t *p = c->send.buf + c->send.len - len, *mask = p - 4;
  12282. for (i = 0; i < len; i++) p[i] ^= mask[i & 3];
  12283. }
  12284. }
  12285. size_t mg_ws_send(struct mg_connection *c, const void *buf, size_t len,
  12286. int op) {
  12287. #if MG_ARCH == MG_ARCH_UNIX
  12288. pthread_mutex_lock(&WSlock);
  12289. #endif
  12290. if (c==NULL || c->send.buf== NULL)
  12291. {
  12292. #if MG_ARCH == MG_ARCH_UNIX
  12293. pthread_mutex_unlock(&WSlock);
  12294. #endif
  12295. return 0;
  12296. }
  12297. uint8_t header[14];
  12298. size_t header_len = mkhdr(len, op, c->is_client, header);
  12299. //printf("WS out: %d [%.*s]", (int) len, (int) len, buf);
  12300. mg_send(c, header, header_len);
  12301. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  12302. mg_send(c, buf, len);
  12303. mg_ws_mask(c, len);
  12304. #if MG_ARCH == MG_ARCH_UNIX
  12305. pthread_mutex_unlock(&WSlock);
  12306. #endif
  12307. return header_len + len;
  12308. }
  12309. static bool mg_ws_client_handshake(struct mg_connection *c) {
  12310. int n = mg_http_get_request_len(c->recv.buf, c->recv.len);
  12311. if (n < 0) {
  12312. mg_error(c, "not http"); // Some just, not an HTTP request
  12313. } else if (n > 0) {
  12314. if (n < 15 || memcmp(c->recv.buf + 9, "101", 3) != 0) {
  12315. mg_error(c, "ws handshake error");
  12316. } else {
  12317. struct mg_http_message hm;
  12318. if (mg_http_parse((char *) c->recv.buf, c->recv.len, &hm)) {
  12319. c->is_websocket = 1;
  12320. mg_call(c, MG_EV_WS_OPEN, &hm);
  12321. } else {
  12322. mg_error(c, "ws handshake error");
  12323. }
  12324. }
  12325. mg_iobuf_del(&c->recv, 0, (size_t) n);
  12326. } else {
  12327. return true; // Request is not yet received, quit event handler
  12328. }
  12329. return false; // Continue event handler
  12330. }
  12331. static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
  12332. struct ws_msg msg;
  12333. size_t ofs = (size_t) c->pfn_data;
  12334. // assert(ofs < c->recv.len);
  12335. if (ev == MG_EV_READ) {
  12336. if (c->is_client && !c->is_websocket && mg_ws_client_handshake(c)) return;
  12337. while (ws_process(c->recv.buf + ofs, c->recv.len - ofs, &msg) > 0) {
  12338. char *s = (char *) c->recv.buf + ofs + msg.header_len;
  12339. struct mg_ws_message m = {{s, msg.data_len}, msg.flags};
  12340. size_t len = msg.header_len + msg.data_len;
  12341. uint8_t final = msg.flags & 128, op = msg.flags & 15;
  12342. // MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
  12343. // (int) m.data.len, (int) m.data.len, m.data.ptr));
  12344. switch (op) {
  12345. case WEBSOCKET_OP_CONTINUE:
  12346. mg_call(c, MG_EV_WS_CTL, &m);
  12347. break;
  12348. case WEBSOCKET_OP_PING:
  12349. MG_DEBUG(("%s", "WS PONG"));
  12350. mg_ws_send(c, s, msg.data_len, WEBSOCKET_OP_PONG);
  12351. mg_call(c, MG_EV_WS_CTL, &m);
  12352. break;
  12353. case WEBSOCKET_OP_PONG:
  12354. mg_call(c, MG_EV_WS_CTL, &m);
  12355. break;
  12356. case WEBSOCKET_OP_TEXT:
  12357. case WEBSOCKET_OP_BINARY:
  12358. if (final) mg_call(c, MG_EV_WS_MSG, &m);
  12359. break;
  12360. case WEBSOCKET_OP_CLOSE:
  12361. MG_DEBUG(("%lu WS CLOSE", c->id));
  12362. mg_call(c, MG_EV_WS_CTL, &m);
  12363. // Echo the payload of the received CLOSE message back to the sender
  12364. mg_ws_send(c, m.data.ptr, m.data.len, WEBSOCKET_OP_CLOSE);
  12365. c->is_draining = 1;
  12366. break;
  12367. default:
  12368. // Per RFC6455, close conn when an unknown op is recvd
  12369. mg_error(c, "unknown WS op %d", op);
  12370. break;
  12371. }
  12372. // Handle fragmented frames: strip header, keep in c->recv
  12373. if (final == 0 || op == 0) {
  12374. if (op) ofs++, len--, msg.header_len--; // First frame
  12375. mg_iobuf_del(&c->recv, ofs, msg.header_len); // Strip header
  12376. len -= msg.header_len;
  12377. ofs += len;
  12378. c->pfn_data = (void *) ofs;
  12379. // MG_INFO(("FRAG %d [%.*s]", (int) ofs, (int) ofs, c->recv.buf));
  12380. }
  12381. // Remove non-fragmented frame
  12382. if (final && op) mg_iobuf_del(&c->recv, ofs, len);
  12383. // Last chunk of the fragmented frame
  12384. if (final && !op) {
  12385. m.flags = c->recv.buf[0];
  12386. m.data = mg_str_n((char *) &c->recv.buf[1], (size_t) (ofs - 1));
  12387. mg_call(c, MG_EV_WS_MSG, &m);
  12388. mg_iobuf_del(&c->recv, 0, ofs);
  12389. ofs = 0;
  12390. c->pfn_data = NULL;
  12391. }
  12392. }
  12393. }
  12394. (void) ev_data;
  12395. }
  12396. struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
  12397. mg_event_handler_t fn, void *fn_data,
  12398. const char *fmt, ...) {
  12399. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  12400. if (c != NULL) {
  12401. char nonce[16], key[30];
  12402. struct mg_str host = mg_url_host(url);
  12403. mg_random(nonce, sizeof(nonce));
  12404. mg_base64_encode((unsigned char *) nonce, sizeof(nonce), key, sizeof(key));
  12405. mg_xprintf(mg_pfn_iobuf, &c->send,
  12406. "GET %s HTTP/1.1\r\n"
  12407. "Upgrade: websocket\r\n"
  12408. "Host: %.*s\r\n"
  12409. "Connection: Upgrade\r\n"
  12410. "Sec-WebSocket-Version: 13\r\n"
  12411. "Sec-WebSocket-Key: %s\r\n",
  12412. mg_url_uri(url), (int) host.len, host.ptr, key);
  12413. if (fmt != NULL) {
  12414. va_list ap;
  12415. va_start(ap, fmt);
  12416. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  12417. va_end(ap);
  12418. }
  12419. mg_xprintf(mg_pfn_iobuf, &c->send, "\r\n");
  12420. c->pfn = mg_ws_cb;
  12421. c->pfn_data = NULL;
  12422. }
  12423. return c;
  12424. }
  12425. void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
  12426. const char *fmt, ...) {
  12427. struct mg_str *wskey = mg_http_get_header(hm, "Sec-WebSocket-Key");
  12428. c->pfn = mg_ws_cb;
  12429. c->pfn_data = NULL;
  12430. if (wskey == NULL) {
  12431. mg_http_reply(c, 426, "", "WS upgrade expected\n");
  12432. c->is_draining = 1;
  12433. } else {
  12434. struct mg_str *wsproto = mg_http_get_header(hm, "Sec-WebSocket-Protocol");
  12435. va_list ap;
  12436. va_start(ap, fmt);
  12437. ws_handshake(c, wskey, wsproto, fmt, &ap);
  12438. va_end(ap);
  12439. c->is_websocket = 1;
  12440. c->is_resp = 0;
  12441. mg_call(c, MG_EV_WS_OPEN, hm);
  12442. }
  12443. }
  12444. size_t mg_ws_wrap(struct mg_connection *c, size_t len, int op) {
  12445. uint8_t header[14], *p;
  12446. size_t header_len = mkhdr(len, op, c->is_client, header);
  12447. // NOTE: order of operations is important!
  12448. mg_iobuf_add(&c->send, c->send.len, NULL, header_len);
  12449. p = &c->send.buf[c->send.len - len]; // p points to data
  12450. memmove(p, p - header_len, len); // Shift data
  12451. memcpy(p - header_len, header, header_len); // Prepend header
  12452. mg_ws_mask(c, len); // Mask data
  12453. return c->send.len;
  12454. }
  12455. #ifdef MG_ENABLE_LINES
  12456. #line 1 "src/drivers/cmsis.c"
  12457. #endif
  12458. // https://arm-software.github.io/CMSIS_5/Driver/html/index.html
  12459. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
  12460. extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0;
  12461. extern ARM_DRIVER_ETH_PHY Driver_ETH_PHY0;
  12462. static struct mg_tcpip_if *s_ifp;
  12463. static void mac_cb(uint32_t);
  12464. static bool cmsis_init(struct mg_tcpip_if *);
  12465. static bool cmsis_up(struct mg_tcpip_if *);
  12466. static size_t cmsis_tx(const void *, size_t, struct mg_tcpip_if *);
  12467. static size_t cmsis_rx(void *, size_t, struct mg_tcpip_if *);
  12468. struct mg_tcpip_driver mg_tcpip_driver_cmsis = {cmsis_init, cmsis_tx, NULL,
  12469. cmsis_up};
  12470. static bool cmsis_init(struct mg_tcpip_if *ifp) {
  12471. ARM_ETH_MAC_ADDR addr;
  12472. s_ifp = ifp;
  12473. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12474. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  12475. ARM_ETH_MAC_CAPABILITIES cap = mac->GetCapabilities();
  12476. if (mac->Initialize(mac_cb) != ARM_DRIVER_OK) return false;
  12477. if (phy->Initialize(mac->PHY_Read, mac->PHY_Write) != ARM_DRIVER_OK)
  12478. return false;
  12479. if (cap.event_rx_frame == 0) // polled mode driver
  12480. mg_tcpip_driver_cmsis.rx = cmsis_rx;
  12481. mac->PowerControl(ARM_POWER_FULL);
  12482. if (cap.mac_address) { // driver provides MAC address
  12483. mac->GetMacAddress(&addr);
  12484. memcpy(ifp->mac, &addr, sizeof(ifp->mac));
  12485. } else { // we provide MAC address
  12486. memcpy(&addr, ifp->mac, sizeof(addr));
  12487. mac->SetMacAddress(&addr);
  12488. }
  12489. phy->PowerControl(ARM_POWER_FULL);
  12490. phy->SetInterface(cap.media_interface);
  12491. phy->SetMode(ARM_ETH_PHY_AUTO_NEGOTIATE);
  12492. return true;
  12493. }
  12494. static size_t cmsis_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
  12495. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12496. if (mac->SendFrame(buf, (uint32_t) len, 0) != ARM_DRIVER_OK) {
  12497. ifp->nerr++;
  12498. return 0;
  12499. }
  12500. ifp->nsent++;
  12501. return len;
  12502. }
  12503. static bool cmsis_up(struct mg_tcpip_if *ifp) {
  12504. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  12505. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12506. bool up = (phy->GetLinkState() == ARM_ETH_LINK_UP) ? 1 : 0; // link state
  12507. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // just went up
  12508. ARM_ETH_LINK_INFO st = phy->GetLinkInfo();
  12509. mac->Control(ARM_ETH_MAC_CONFIGURE,
  12510. (st.speed << ARM_ETH_MAC_SPEED_Pos) |
  12511. (st.duplex << ARM_ETH_MAC_DUPLEX_Pos) |
  12512. ARM_ETH_MAC_ADDRESS_BROADCAST);
  12513. MG_DEBUG(("Link is %uM %s-duplex",
  12514. (st.speed == 2) ? 1000
  12515. : st.speed ? 100
  12516. : 10,
  12517. st.duplex ? "full" : "half"));
  12518. mac->Control(ARM_ETH_MAC_CONTROL_TX, 1);
  12519. mac->Control(ARM_ETH_MAC_CONTROL_RX, 1);
  12520. } else if ((ifp->state != MG_TCPIP_STATE_DOWN) && !up) { // just went down
  12521. mac->Control(ARM_ETH_MAC_FLUSH,
  12522. ARM_ETH_MAC_FLUSH_TX | ARM_ETH_MAC_FLUSH_RX);
  12523. mac->Control(ARM_ETH_MAC_CONTROL_TX, 0);
  12524. mac->Control(ARM_ETH_MAC_CONTROL_RX, 0);
  12525. }
  12526. return up;
  12527. }
  12528. static void mac_cb(uint32_t ev) {
  12529. if ((ev & ARM_ETH_MAC_EVENT_RX_FRAME) == 0) return;
  12530. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12531. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  12532. if (len >= 60 && len <= 1518) { // proper frame
  12533. char *p;
  12534. if (mg_queue_book(&s_ifp->recv_queue, &p, len) >= len) { // have room
  12535. if ((len = mac->ReadFrame((uint8_t *) p, len)) > 0) { // copy succeeds
  12536. mg_queue_add(&s_ifp->recv_queue, len);
  12537. s_ifp->nrecv++;
  12538. }
  12539. return;
  12540. }
  12541. s_ifp->ndrop++;
  12542. }
  12543. mac->ReadFrame(NULL, 0); // otherwise, discard
  12544. }
  12545. static size_t cmsis_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  12546. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12547. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  12548. if (len >= 60 && len <= 1518 &&
  12549. ((len = mac->ReadFrame(buf, (uint32_t) buflen)) > 0))
  12550. return len;
  12551. if (len > 0) mac->ReadFrame(NULL, 0); // discard bad frames
  12552. (void) ifp;
  12553. return 0;
  12554. }
  12555. #endif
  12556. #ifdef MG_ENABLE_LINES
  12557. #line 1 "src/drivers/imxrt.c"
  12558. #endif
  12559. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_IMXRT) && MG_ENABLE_DRIVER_IMXRT
  12560. struct imxrt_enet {
  12561. volatile uint32_t RESERVED0, EIR, EIMR, RESERVED1, RDAR, TDAR, RESERVED2[3],
  12562. ECR, RESERVED3[6], MMFR, MSCR, RESERVED4[7], MIBC, RESERVED5[7], RCR,
  12563. RESERVED6[15], TCR, RESERVED7[7], PALR, PAUR, OPD, TXIC0, TXIC1, TXIC2,
  12564. RESERVED8, RXIC0, RXIC1, RXIC2, RESERVED9[3], IAUR, IALR, GAUR, GALR,
  12565. RESERVED10[7], TFWR, RESERVED11[14], RDSR, TDSR, MRBR[2], RSFL, RSEM,
  12566. RAEM, RAFL, TSEM, TAEM, TAFL, TIPG, FTRL, RESERVED12[3], TACC, RACC,
  12567. RESERVED13[15], RMON_T_PACKETS, RMON_T_BC_PKT, RMON_T_MC_PKT,
  12568. RMON_T_CRC_ALIGN, RMON_T_UNDERSIZE, RMON_T_OVERSIZE, RMON_T_FRAG,
  12569. RMON_T_JAB, RMON_T_COL, RMON_T_P64, RMON_T_P65TO127, RMON_T_P128TO255,
  12570. RMON_T_P256TO511, RMON_T_P512TO1023, RMON_T_P1024TO2048, RMON_T_GTE2048,
  12571. RMON_T_OCTETS, IEEE_T_DROP, IEEE_T_FRAME_OK, IEEE_T_1COL, IEEE_T_MCOL,
  12572. IEEE_T_DEF, IEEE_T_LCOL, IEEE_T_EXCOL, IEEE_T_MACERR, IEEE_T_CSERR,
  12573. IEEE_T_SQE, IEEE_T_FDXFC, IEEE_T_OCTETS_OK, RESERVED14[3], RMON_R_PACKETS,
  12574. RMON_R_BC_PKT, RMON_R_MC_PKT, RMON_R_CRC_ALIGN, RMON_R_UNDERSIZE,
  12575. RMON_R_OVERSIZE, RMON_R_FRAG, RMON_R_JAB, RESERVED15, RMON_R_P64,
  12576. RMON_R_P65TO127, RMON_R_P128TO255, RMON_R_P256TO511, RMON_R_P512TO1023,
  12577. RMON_R_P1024TO2047, RMON_R_GTE2048, RMON_R_OCTETS, IEEE_R_DROP,
  12578. IEEE_R_FRAME_OK, IEEE_R_CRC, IEEE_R_ALIGN, IEEE_R_MACERR, IEEE_R_FDXFC,
  12579. IEEE_R_OCTETS_OK, RESERVED16[71], ATCR, ATVR, ATOFF, ATPER, ATCOR, ATINC,
  12580. ATSTMP, RESERVED17[122], TGSR, TCSR0, TCCR0, TCSR1, TCCR1, TCSR2, TCCR2,
  12581. TCSR3;
  12582. };
  12583. #undef ENET
  12584. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x402D8000U)
  12585. #define ETH_PKT_SIZE 1536 // Max frame size, 64-bit aligned
  12586. #define ETH_DESC_CNT 4 // Descriptors count
  12587. struct enet_desc {
  12588. uint16_t length; // Data length
  12589. uint16_t control; // Control and status
  12590. uint32_t *buffer; // Data ptr
  12591. };
  12592. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  12593. #define MG_64BIT_ALIGNED __attribute__((aligned((64U))))
  12594. // Descriptors: in non-cached area (TODO(scaprile)), 64-bit aligned
  12595. // Buffers: 64-bit aligned
  12596. static volatile struct enet_desc s_rxdesc[ETH_DESC_CNT] MG_64BIT_ALIGNED;
  12597. static volatile struct enet_desc s_txdesc[ETH_DESC_CNT] MG_64BIT_ALIGNED;
  12598. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BIT_ALIGNED;
  12599. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BIT_ALIGNED;
  12600. static struct mg_tcpip_if *s_ifp; // MIP interface
  12601. enum { PHY_BCR = 0, PHY_BSR = 1, PHY_ID1 = 2, PHY_ID2 = 3 };
  12602. static uint16_t enet_phy_read(uint8_t addr, uint8_t reg) {
  12603. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  12604. ENET->MMFR = (1 << 30) | (2 << 28) | (addr << 23) | (reg << 18) | (2 << 16);
  12605. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  12606. return ENET->MMFR & 0xffff;
  12607. }
  12608. static void enet_phy_write(uint8_t addr, uint8_t reg, uint16_t val) {
  12609. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  12610. ENET->MMFR =
  12611. (1 << 30) | (1 << 28) | (addr << 23) | (reg << 18) | (2 << 16) | val;
  12612. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  12613. }
  12614. static uint32_t enet_phy_id(uint8_t addr) {
  12615. uint16_t phy_id1 = enet_phy_read(addr, PHY_ID1);
  12616. uint16_t phy_id2 = enet_phy_read(addr, PHY_ID2);
  12617. return (uint32_t) phy_id1 << 16 | phy_id2;
  12618. }
  12619. // MDC clock is generated from IPS Bus clock (ipg_clk); as per 802.3,
  12620. // it must not exceed 2.5MHz
  12621. // The PHY receives the PLL6-generated 50MHz clock
  12622. static bool mg_tcpip_driver_imxrt_init(struct mg_tcpip_if *ifp) {
  12623. struct mg_tcpip_driver_imxrt_data *d =
  12624. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  12625. s_ifp = ifp;
  12626. // Init RX descriptors
  12627. for (int i = 0; i < ETH_DESC_CNT; i++) {
  12628. s_rxdesc[i].control = MG_BIT(15); // Own (E)
  12629. s_rxdesc[i].buffer = (uint32_t *) s_rxbuf[i]; // Point to data buffer
  12630. }
  12631. s_rxdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  12632. // Init TX descriptors
  12633. for (int i = 0; i < ETH_DESC_CNT; i++) {
  12634. // s_txdesc[i].control = MG_BIT(10); // Own (TC)
  12635. s_txdesc[i].buffer = (uint32_t *) s_txbuf[i];
  12636. }
  12637. s_txdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  12638. ENET->ECR = MG_BIT(0); // Software reset, disable
  12639. while ((ENET->ECR & MG_BIT(0))) (void) 0; // Wait until done
  12640. // Set MDC clock divider. If user told us the value, use it.
  12641. // TODO(): Otherwise, guess (currently assuming max freq)
  12642. int cr = (d == NULL || d->mdc_cr < 0) ? 24 : d->mdc_cr;
  12643. ENET->MSCR = (1 << 8) | ((cr & 0x3f) << 1); // HOLDTIME 2 clks
  12644. enet_phy_write(d->phy_addr, PHY_BCR, MG_BIT(15)); // Reset PHY
  12645. enet_phy_write(d->phy_addr, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  12646. // PHY: Enable 50 MHz external ref clock at XI (preserve defaults)
  12647. uint32_t id = enet_phy_id(d->phy_addr);
  12648. MG_INFO(("PHY ID: %#04x %#04x", (uint16_t) (id >> 16), (uint16_t) id));
  12649. // 2000 a140 - TI DP83825I
  12650. // 0007 c0fx - LAN8720
  12651. // 0022 1561 - KSZ8081RNB
  12652. if ((id & 0xffff0000) == 0x220000) { // KSZ8081RNB, like EVK-RTxxxx boards
  12653. enet_phy_write(d->phy_addr, 31,
  12654. MG_BIT(15) | MG_BIT(8) | MG_BIT(7)); // PC2R
  12655. } else if ((id & 0xffff0000) == 0x20000000) { // DP83825I, like Teensy4.1
  12656. enet_phy_write(d->phy_addr, 23, 0x81); // 50MHz clock input
  12657. enet_phy_write(d->phy_addr, 24, 0x280); // LED status, active high
  12658. } else { // Default to LAN8720
  12659. MG_INFO(("Defaulting to LAN8720 PHY...")); // TODO()
  12660. }
  12661. // Select RMII mode, 100M, keep CRC, set max rx length, disable loop
  12662. ENET->RCR = (1518 << 16) | MG_BIT(8) | MG_BIT(2);
  12663. // ENET->RCR |= MG_BIT(3); // Receive all
  12664. ENET->TCR = MG_BIT(2); // Full-duplex
  12665. ENET->RDSR = (uint32_t) (uintptr_t) s_rxdesc;
  12666. ENET->TDSR = (uint32_t) (uintptr_t) s_txdesc;
  12667. ENET->MRBR[0] = ETH_PKT_SIZE; // Same size for RX/TX buffers
  12668. // MAC address filtering (bytes in reversed order)
  12669. ENET->PAUR = ((uint32_t) ifp->mac[4] << 24U) | (uint32_t) ifp->mac[5] << 16U;
  12670. ENET->PALR = (uint32_t) (ifp->mac[0] << 24U) |
  12671. ((uint32_t) ifp->mac[1] << 16U) |
  12672. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  12673. ENET->ECR = MG_BIT(8) | MG_BIT(1); // Little-endian CPU, Enable
  12674. ENET->EIMR = MG_BIT(25); // Set interrupt mask
  12675. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  12676. ENET->TDAR = MG_BIT(24); // Transmit Descriptors have changed
  12677. // ENET->OPD = 0x10014;
  12678. return true;
  12679. }
  12680. // Transmit frame
  12681. static size_t mg_tcpip_driver_imxrt_tx(const void *buf, size_t len,
  12682. struct mg_tcpip_if *ifp) {
  12683. static int s_txno; // Current descriptor index
  12684. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  12685. ifp->nerr++;
  12686. MG_ERROR(("Frame too big, %ld", (long) len));
  12687. len = (size_t) -1; // fail
  12688. } else if ((s_txdesc[s_txno].control & MG_BIT(15))) {
  12689. MG_ERROR(("No descriptors available"));
  12690. len = 0; // retry later
  12691. } else {
  12692. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  12693. s_txdesc[s_txno].length = (uint16_t) len; // Set data len
  12694. // Table 37-34, R, L, TC (Ready, last, transmit CRC after frame
  12695. s_txdesc[s_txno].control |=
  12696. (uint16_t) (MG_BIT(15) | MG_BIT(11) | MG_BIT(10));
  12697. ENET->TDAR = MG_BIT(24); // Descriptor ring updated
  12698. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  12699. }
  12700. (void) ifp;
  12701. return len;
  12702. }
  12703. static bool mg_tcpip_driver_imxrt_up(struct mg_tcpip_if *ifp) {
  12704. struct mg_tcpip_driver_imxrt_data *d =
  12705. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  12706. uint32_t bsr = enet_phy_read(d->phy_addr, PHY_BSR);
  12707. bool up = bsr & MG_BIT(2) ? 1 : 0;
  12708. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  12709. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  12710. // if(link is slow or half) set flags otherwise
  12711. // reg = tmp
  12712. uint32_t tcr = ENET->TCR | MG_BIT(2); // Full-duplex
  12713. uint32_t rcr = ENET->RCR & ~MG_BIT(9); // 100M
  12714. uint32_t phy_id = enet_phy_id(d->phy_addr);
  12715. if ((phy_id & 0xffff0000) == 0x220000) { // KSZ8081RNB
  12716. uint16_t pc1r = enet_phy_read(d->phy_addr, 30); // Read PC1R
  12717. if ((pc1r & 3) == 1) rcr |= MG_BIT(9); // 10M
  12718. if ((pc1r & MG_BIT(2)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12719. } else if ((phy_id & 0xffff0000) == 0x20000000) { // DP83825I
  12720. uint16_t physts = enet_phy_read(d->phy_addr, 16); // Read PHYSTS
  12721. if (physts & MG_BIT(1)) rcr |= MG_BIT(9); // 10M
  12722. if ((physts & MG_BIT(2)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12723. } else { // Default to LAN8720
  12724. uint16_t scsr = enet_phy_read(d->phy_addr, 31); // Read CSCR
  12725. if ((scsr & MG_BIT(3)) == 0) rcr |= MG_BIT(9); // 10M
  12726. if ((scsr & MG_BIT(4)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12727. }
  12728. ENET->TCR = tcr; // IRQ handler does not fiddle with these registers
  12729. ENET->RCR = rcr;
  12730. MG_DEBUG(("Link is %uM %s-duplex", rcr & MG_BIT(9) ? 10 : 100,
  12731. tcr & MG_BIT(2) ? "full" : "half"));
  12732. }
  12733. return up;
  12734. }
  12735. void ENET_IRQHandler(void);
  12736. static uint32_t s_rxno;
  12737. void ENET_IRQHandler(void) {
  12738. ENET->EIR = MG_BIT(25); // Ack IRQ
  12739. // Frame received, loop
  12740. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  12741. uint32_t r = s_rxdesc[s_rxno].control;
  12742. if (r & MG_BIT(15)) break; // exit when done
  12743. // skip partial/errored frames (Table 37-32)
  12744. if ((r & MG_BIT(11)) &&
  12745. !(r & (MG_BIT(5) | MG_BIT(4) | MG_BIT(2) | MG_BIT(1) | MG_BIT(0)))) {
  12746. size_t len = s_rxdesc[s_rxno].length;
  12747. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  12748. }
  12749. s_rxdesc[s_rxno].control |= MG_BIT(15);
  12750. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  12751. }
  12752. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  12753. // If b24 == 0, descriptors were exhausted and probably frames were dropped
  12754. }
  12755. struct mg_tcpip_driver mg_tcpip_driver_imxrt = {mg_tcpip_driver_imxrt_init,
  12756. mg_tcpip_driver_imxrt_tx, NULL,
  12757. mg_tcpip_driver_imxrt_up};
  12758. #endif
  12759. #ifdef MG_ENABLE_LINES
  12760. #line 1 "src/drivers/same54.c"
  12761. #endif
  12762. #if defined(MG_ENABLE_DRIVER_SAME54) && MG_ENABLE_DRIVER_SAME54
  12763. #include <sam.h>
  12764. #define ETH_PKT_SIZE 1536 // Max frame size
  12765. #define ETH_DESC_CNT 4 // Descriptors count
  12766. #define ETH_DS 2 // Descriptor size (words)
  12767. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  12768. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  12769. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  12770. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  12771. static uint8_t s_txno; // Current TX descriptor
  12772. static uint8_t s_rxno; // Current RX descriptor
  12773. static struct mg_tcpip_if *s_ifp; // MIP interface
  12774. enum { PHY_ADDR = 0, PHY_BCR = 0, PHY_BSR = 1 };
  12775. #define PHY_BCR_DUPLEX_MODE_Msk MG_BIT(8)
  12776. #define PHY_BCR_SPEED_Msk MG_BIT(13)
  12777. #define PHY_BSR_LINK_STATUS_Msk MG_BIT(2)
  12778. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  12779. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk |
  12780. GMAC_MAN_OP(2) | // Setting the read operation
  12781. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  12782. GMAC_MAN_REGA(reg); // Setting the register
  12783. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)) (void) 0;
  12784. return GMAC_REGS->GMAC_MAN & GMAC_MAN_DATA_Msk; // Getting the read value
  12785. }
  12786. #if 0
  12787. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  12788. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk | GMAC_MAN_OP(1) | // Setting the write operation
  12789. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  12790. GMAC_MAN_REGA(reg) | GMAC_MAN_DATA(val); // Setting the register
  12791. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)); // Waiting until the write op is complete
  12792. }
  12793. #endif
  12794. int get_clock_rate(struct mg_tcpip_driver_same54_data *d) {
  12795. if (d && d->mdc_cr >= 0 && d->mdc_cr <= 5) {
  12796. return d->mdc_cr;
  12797. } else {
  12798. // get MCLK from GCLK_GENERATOR 0
  12799. uint32_t div = 512;
  12800. uint32_t mclk;
  12801. if (!(GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_DIVSEL_Msk)) {
  12802. div = ((GCLK_REGS->GCLK_GENCTRL[0] & 0x00FF0000) >> 16);
  12803. if (div == 0) div = 1;
  12804. }
  12805. switch (GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_SRC_Msk) {
  12806. case GCLK_GENCTRL_SRC_XOSC0_Val:
  12807. mclk = 32000000UL; /* 32MHz */
  12808. break;
  12809. case GCLK_GENCTRL_SRC_XOSC1_Val:
  12810. mclk = 32000000UL; /* 32MHz */
  12811. break;
  12812. case GCLK_GENCTRL_SRC_OSCULP32K_Val: mclk = 32000UL; break;
  12813. case GCLK_GENCTRL_SRC_XOSC32K_Val: mclk = 32000UL; break;
  12814. case GCLK_GENCTRL_SRC_DFLL_Val:
  12815. mclk = 48000000UL; /* 48MHz */
  12816. break;
  12817. case GCLK_GENCTRL_SRC_DPLL0_Val:
  12818. mclk = 200000000UL; /* 200MHz */
  12819. break;
  12820. case GCLK_GENCTRL_SRC_DPLL1_Val:
  12821. mclk = 200000000UL; /* 200MHz */
  12822. break;
  12823. default: mclk = 200000000UL; /* 200MHz */
  12824. }
  12825. mclk /= div;
  12826. uint8_t crs[] = {0, 1, 2, 3, 4, 5}; // GMAC->NCFGR::CLK values
  12827. uint8_t dividers[] = {8, 16, 32, 48, 64, 96}; // Respective CLK dividers
  12828. for (int i = 0; i < 6; i++) {
  12829. if (mclk / dividers[i] <= 2375000UL /* 2.5MHz - 5% */) {
  12830. return crs[i];
  12831. }
  12832. }
  12833. return 5;
  12834. }
  12835. }
  12836. static bool mg_tcpip_driver_same54_init(struct mg_tcpip_if *ifp) {
  12837. struct mg_tcpip_driver_same54_data *d =
  12838. (struct mg_tcpip_driver_same54_data *) ifp->driver_data;
  12839. s_ifp = ifp;
  12840. MCLK_REGS->MCLK_APBCMASK |= MCLK_APBCMASK_GMAC_Msk;
  12841. MCLK_REGS->MCLK_AHBMASK |= MCLK_AHBMASK_GMAC_Msk;
  12842. GMAC_REGS->GMAC_NCFGR = GMAC_NCFGR_CLK(get_clock_rate(d)); // Set MDC divider
  12843. GMAC_REGS->GMAC_NCR = 0; // Disable RX & TX
  12844. GMAC_REGS->GMAC_NCR |= GMAC_NCR_MPE_Msk; // Enable MDC & MDIO
  12845. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init TX descriptors
  12846. s_txdesc[i][0] = (uint32_t) s_txbuf[i]; // Point to data buffer
  12847. s_txdesc[i][1] = MG_BIT(31); // OWN bit
  12848. }
  12849. s_txdesc[ETH_DESC_CNT - 1][1] |= MG_BIT(30); // Last tx descriptor - wrap
  12850. GMAC_REGS->GMAC_DCFGR = GMAC_DCFGR_DRBS(0x18) // DMA recv buf 1536
  12851. | GMAC_DCFGR_RXBMS(GMAC_DCFGR_RXBMS_FULL_Val) |
  12852. GMAC_DCFGR_TXPBMS(1); // See #2487
  12853. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init RX descriptors
  12854. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i]; // Address of the data buffer
  12855. s_rxdesc[i][1] = 0; // Clear status
  12856. }
  12857. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(1); // Last rx descriptor - wrap
  12858. GMAC_REGS->GMAC_TBQB = (uint32_t) s_txdesc; // about the descriptor addresses
  12859. GMAC_REGS->GMAC_RBQB = (uint32_t) s_rxdesc; // Let the controller know
  12860. GMAC_REGS->SA[0].GMAC_SAB =
  12861. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  12862. GMAC_REGS->SA[0].GMAC_SAT = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  12863. GMAC_REGS->GMAC_UR &= ~GMAC_UR_MII_Msk; // Disable MII, use RMII
  12864. GMAC_REGS->GMAC_NCFGR |= GMAC_NCFGR_MAXFS_Msk | GMAC_NCFGR_MTIHEN_Msk |
  12865. GMAC_NCFGR_EFRHD_Msk | GMAC_NCFGR_CAF_Msk;
  12866. GMAC_REGS->GMAC_TSR = GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk |
  12867. GMAC_TSR_TXCOMP_Msk | GMAC_TSR_TFC_Msk |
  12868. GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  12869. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk;
  12870. GMAC_REGS->GMAC_RSR = GMAC_RSR_HNO_Msk | GMAC_RSR_RXOVR_Msk |
  12871. GMAC_RSR_REC_Msk | GMAC_RSR_BNA_Msk;
  12872. GMAC_REGS->GMAC_IDR = ~0U; // Disable interrupts, then enable required
  12873. GMAC_REGS->GMAC_IER = GMAC_IER_HRESP_Msk | GMAC_IER_ROVR_Msk |
  12874. GMAC_IER_TCOMP_Msk | GMAC_IER_TFC_Msk |
  12875. GMAC_IER_RLEX_Msk | GMAC_IER_TUR_Msk |
  12876. GMAC_IER_RXUBR_Msk | GMAC_IER_RCOMP_Msk;
  12877. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TXEN_Msk | GMAC_NCR_RXEN_Msk;
  12878. NVIC_EnableIRQ(GMAC_IRQn);
  12879. return true;
  12880. }
  12881. static size_t mg_tcpip_driver_same54_tx(const void *buf, size_t len,
  12882. struct mg_tcpip_if *ifp) {
  12883. if (len > sizeof(s_txbuf[s_txno])) {
  12884. MG_ERROR(("Frame too big, %ld", (long) len));
  12885. len = 0; // Frame is too big
  12886. } else if ((s_txdesc[s_txno][1] & MG_BIT(31)) == 0) {
  12887. ifp->nerr++;
  12888. MG_ERROR(("No free descriptors"));
  12889. len = 0; // All descriptors are busy, fail
  12890. } else {
  12891. uint32_t status = len | MG_BIT(15); // Frame length, last chunk
  12892. if (s_txno == ETH_DESC_CNT - 1) status |= MG_BIT(30); // wrap
  12893. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  12894. s_txdesc[s_txno][1] = status;
  12895. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  12896. }
  12897. __DSB(); // Ensure descriptors have been written
  12898. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TSTART_Msk; // Enable transmission
  12899. return len;
  12900. }
  12901. static bool mg_tcpip_driver_same54_up(struct mg_tcpip_if *ifp) {
  12902. uint16_t bsr = eth_read_phy(PHY_ADDR, PHY_BSR);
  12903. bool up = bsr & PHY_BSR_LINK_STATUS_Msk ? 1 : 0;
  12904. // If PHY is ready, update NCFGR accordingly
  12905. if (ifp->state == MG_TCPIP_STATE_DOWN && up) {
  12906. uint16_t bcr = eth_read_phy(PHY_ADDR, PHY_BCR);
  12907. bool fd = bcr & PHY_BCR_DUPLEX_MODE_Msk ? 1 : 0;
  12908. bool spd = bcr & PHY_BCR_SPEED_Msk ? 1 : 0;
  12909. GMAC_REGS->GMAC_NCFGR =
  12910. (GMAC_REGS->GMAC_NCFGR & ~(GMAC_NCFGR_SPD_Msk | PHY_BCR_SPEED_Msk)) |
  12911. GMAC_NCFGR_SPD(spd) | GMAC_NCFGR_FD(fd);
  12912. }
  12913. return up;
  12914. }
  12915. void GMAC_Handler(void);
  12916. void GMAC_Handler(void) {
  12917. uint32_t isr = GMAC_REGS->GMAC_ISR;
  12918. uint32_t rsr = GMAC_REGS->GMAC_RSR;
  12919. uint32_t tsr = GMAC_REGS->GMAC_TSR;
  12920. if (isr & GMAC_ISR_RCOMP_Msk) {
  12921. if (rsr & GMAC_ISR_RCOMP_Msk) {
  12922. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  12923. if ((s_rxdesc[s_rxno][0] & MG_BIT(0)) == 0) break;
  12924. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  12925. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  12926. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // Disown
  12927. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  12928. }
  12929. }
  12930. }
  12931. if ((tsr & (GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk | GMAC_TSR_TXCOMP_Msk |
  12932. GMAC_TSR_TFC_Msk | GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  12933. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk)) != 0) {
  12934. // MG_INFO((" --> %#x %#x", s_txdesc[s_txno][1], tsr));
  12935. if (!(s_txdesc[s_txno][1] & MG_BIT(31))) s_txdesc[s_txno][1] |= MG_BIT(31);
  12936. }
  12937. GMAC_REGS->GMAC_RSR = rsr;
  12938. GMAC_REGS->GMAC_TSR = tsr;
  12939. }
  12940. struct mg_tcpip_driver mg_tcpip_driver_same54 = {
  12941. mg_tcpip_driver_same54_init, mg_tcpip_driver_same54_tx, NULL,
  12942. mg_tcpip_driver_same54_up};
  12943. #endif
  12944. #ifdef MG_ENABLE_LINES
  12945. #line 1 "src/drivers/stm32f.c"
  12946. #endif
  12947. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
  12948. MG_ENABLE_DRIVER_STM32F
  12949. struct stm32f_eth {
  12950. volatile uint32_t MACCR, MACFFR, MACHTHR, MACHTLR, MACMIIAR, MACMIIDR, MACFCR,
  12951. MACVLANTR, RESERVED0[2], MACRWUFFR, MACPMTCSR, RESERVED1, MACDBGR, MACSR,
  12952. MACIMR, MACA0HR, MACA0LR, MACA1HR, MACA1LR, MACA2HR, MACA2LR, MACA3HR,
  12953. MACA3LR, RESERVED2[40], MMCCR, MMCRIR, MMCTIR, MMCRIMR, MMCTIMR,
  12954. RESERVED3[14], MMCTGFSCCR, MMCTGFMSCCR, RESERVED4[5], MMCTGFCR,
  12955. RESERVED5[10], MMCRFCECR, MMCRFAECR, RESERVED6[10], MMCRGUFCR,
  12956. RESERVED7[334], PTPTSCR, PTPSSIR, PTPTSHR, PTPTSLR, PTPTSHUR, PTPTSLUR,
  12957. PTPTSAR, PTPTTHR, PTPTTLR, RESERVED8, PTPTSSR, PTPPPSCR, RESERVED9[564],
  12958. DMABMR, DMATPDR, DMARPDR, DMARDLAR, DMATDLAR, DMASR, DMAOMR, DMAIER,
  12959. DMAMFBOCR, DMARSWTR, RESERVED10[8], DMACHTDR, DMACHRDR, DMACHTBAR,
  12960. DMACHRBAR;
  12961. };
  12962. #undef ETH
  12963. #define ETH ((struct stm32f_eth *) (uintptr_t) 0x40028000)
  12964. #define ETH_PKT_SIZE 1540 // Max frame size
  12965. #define ETH_DESC_CNT 4 // Descriptors count
  12966. #define ETH_DS 4 // Descriptor size (words)
  12967. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  12968. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  12969. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  12970. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  12971. static uint8_t s_txno; // Current TX descriptor
  12972. static uint8_t s_rxno; // Current RX descriptor
  12973. static struct mg_tcpip_if *s_ifp; // MIP interface
  12974. enum { PHY_BCR = 0, PHY_BSR = 1, PHY_ID1 = 2, PHY_ID2 = 3, PHY_CSCR = 31 };
  12975. static uint32_t eth_read_phy(uint8_t addr, uint8_t reg) {
  12976. ETH->MACMIIAR &= (7 << 2);
  12977. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  12978. ETH->MACMIIAR |= MG_BIT(0);
  12979. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  12980. return ETH->MACMIIDR;
  12981. }
  12982. static void eth_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  12983. ETH->MACMIIDR = val;
  12984. ETH->MACMIIAR &= (7 << 2);
  12985. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  12986. ETH->MACMIIAR |= MG_BIT(0);
  12987. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  12988. }
  12989. static uint32_t get_hclk(void) {
  12990. struct rcc {
  12991. volatile uint32_t CR, PLLCFGR, CFGR;
  12992. } *rcc = (struct rcc *) 0x40023800;
  12993. uint32_t clk = 0, hsi = 16000000 /* 16 MHz */, hse = 8000000 /* 8MHz */;
  12994. if (rcc->CFGR & (1 << 2)) {
  12995. clk = hse;
  12996. } else if (rcc->CFGR & (1 << 3)) {
  12997. uint32_t vco, m, n, p;
  12998. m = (rcc->PLLCFGR & (0x3f << 0)) >> 0;
  12999. n = (rcc->PLLCFGR & (0x1ff << 6)) >> 6;
  13000. p = (((rcc->PLLCFGR & (3 << 16)) >> 16) + 1) * 2;
  13001. clk = (rcc->PLLCFGR & (1 << 22)) ? hse : hsi;
  13002. vco = (uint32_t) ((uint64_t) clk * n / m);
  13003. clk = vco / p;
  13004. } else {
  13005. clk = hsi;
  13006. }
  13007. uint32_t hpre = (rcc->CFGR & (15 << 4)) >> 4;
  13008. if (hpre < 8) return clk;
  13009. uint8_t ahbptab[8] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  13010. return ((uint32_t) clk) >> ahbptab[hpre - 8];
  13011. }
  13012. // Guess CR from HCLK. MDC clock is generated from HCLK (AHB); as per 802.3,
  13013. // it must not exceed 2.5MHz As the AHB clock can be (and usually is) derived
  13014. // from the HSI (internal RC), and it can go above specs, the datasheets
  13015. // specify a range of frequencies and activate one of a series of dividers to
  13016. // keep the MDC clock safely below 2.5MHz. We guess a divider setting based on
  13017. // HCLK with a +5% drift. If the user uses a different clock from our
  13018. // defaults, needs to set the macros on top Valid for STM32F74xxx/75xxx
  13019. // (38.8.1) and STM32F42xxx/43xxx (33.8.1) (both 4.5% worst case drift)
  13020. static int guess_mdc_cr(void) {
  13021. uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMIIAR::CR values
  13022. uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  13023. uint32_t hclk = get_hclk(); // Guess system HCLK
  13024. int result = -1; // Invalid CR value
  13025. if (hclk < 25000000) {
  13026. MG_ERROR(("HCLK too low"));
  13027. } else {
  13028. for (int i = 0; i < 6; i++) {
  13029. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  13030. result = crs[i];
  13031. break;
  13032. }
  13033. }
  13034. if (result < 0) MG_ERROR(("HCLK too high"));
  13035. }
  13036. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  13037. return result;
  13038. }
  13039. static bool mg_tcpip_driver_stm32f_init(struct mg_tcpip_if *ifp) {
  13040. struct mg_tcpip_driver_stm32f_data *d =
  13041. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  13042. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  13043. s_ifp = ifp;
  13044. // Init RX descriptors
  13045. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13046. s_rxdesc[i][0] = MG_BIT(31); // Own
  13047. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  13048. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13049. s_rxdesc[i][3] =
  13050. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13051. }
  13052. // Init TX descriptors
  13053. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13054. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13055. s_txdesc[i][3] =
  13056. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13057. }
  13058. ETH->DMABMR |= MG_BIT(0); // Software reset
  13059. while ((ETH->DMABMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  13060. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13061. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13062. ETH->MACMIIAR = ((uint32_t) cr & 7) << 2;
  13063. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  13064. // hardware checksum. Therefore, descriptor size is 4, not 8
  13065. // ETH->DMABMR = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) |
  13066. // MG_BIT(25);
  13067. ETH->MACIMR = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  13068. ETH->MACFCR = MG_BIT(7); // Disable zero quarta pause
  13069. // ETH->MACFFR = MG_BIT(31); // Receive all
  13070. eth_write_phy(phy_addr, PHY_BCR, MG_BIT(15)); // Reset PHY
  13071. eth_write_phy(phy_addr, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  13072. ETH->DMARDLAR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  13073. ETH->DMATDLAR = (uint32_t) (uintptr_t) s_txdesc; // RX descriptors
  13074. ETH->DMAIER = MG_BIT(6) | MG_BIT(16); // RIE, NISE
  13075. ETH->MACCR =
  13076. MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  13077. ETH->DMAOMR =
  13078. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  13079. MG_DEBUG(("PHY ID: %#04hx %#04hx", eth_read_phy(phy_addr, PHY_ID1),
  13080. eth_read_phy(phy_addr, PHY_ID2)));
  13081. // MAC address filtering
  13082. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13083. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  13084. ((uint32_t) ifp->mac[2] << 16) |
  13085. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13086. return true;
  13087. }
  13088. static size_t mg_tcpip_driver_stm32f_tx(const void *buf, size_t len,
  13089. struct mg_tcpip_if *ifp) {
  13090. if (len > sizeof(s_txbuf[s_txno])) {
  13091. MG_ERROR(("Frame too big, %ld", (long) len));
  13092. len = 0; // Frame is too big
  13093. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  13094. ifp->nerr++;
  13095. MG_ERROR(("No free descriptors"));
  13096. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long) ETH->DMASR);
  13097. len = 0; // All descriptors are busy, fail
  13098. } else {
  13099. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13100. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  13101. s_txdesc[s_txno][0] = MG_BIT(20) | MG_BIT(28) | MG_BIT(29); // Chain,FS,LS
  13102. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13103. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13104. }
  13105. MG_DSB(); // ensure descriptors have been written
  13106. ETH->DMASR = MG_BIT(2) | MG_BIT(5); // Clear any prior TBUS/TUS
  13107. ETH->DMATPDR = 0; // and resume
  13108. return len;
  13109. }
  13110. static bool mg_tcpip_driver_stm32f_up(struct mg_tcpip_if *ifp) {
  13111. struct mg_tcpip_driver_stm32f_data *d =
  13112. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  13113. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  13114. uint32_t bsr = eth_read_phy(phy_addr, PHY_BSR);
  13115. bool up = bsr & MG_BIT(2) ? 1 : 0;
  13116. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13117. uint32_t scsr = eth_read_phy(phy_addr, PHY_CSCR);
  13118. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13119. // if(link is slow or half) set flags otherwise
  13120. // reg = tmp
  13121. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  13122. if ((scsr & MG_BIT(3)) == 0) maccr &= ~MG_BIT(14); // 10M
  13123. if ((scsr & MG_BIT(4)) == 0) maccr &= ~MG_BIT(11); // Half-duplex
  13124. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  13125. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  13126. maccr & MG_BIT(11) ? "full" : "half"));
  13127. }
  13128. return up;
  13129. }
  13130. #ifdef __riscv
  13131. __attribute__((interrupt())) // For RISCV CH32V307, which share the same MAC
  13132. #endif
  13133. void ETH_IRQHandler(void);
  13134. void ETH_IRQHandler(void) {
  13135. if (ETH->DMASR & MG_BIT(6)) { // Frame received, loop
  13136. ETH->DMASR = MG_BIT(16) | MG_BIT(6); // Clear flag
  13137. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13138. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  13139. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) ==
  13140. (MG_BIT(8) | MG_BIT(9))) &&
  13141. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  13142. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  13143. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  13144. // ETH->DMASR);
  13145. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13146. }
  13147. s_rxdesc[s_rxno][0] = MG_BIT(31);
  13148. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13149. }
  13150. }
  13151. // Cleanup flags
  13152. ETH->DMASR = MG_BIT(16) // NIS, normal interrupt summary
  13153. | MG_BIT(7); // Clear possible RBUS while processing
  13154. ETH->DMARPDR = 0; // and resume RX
  13155. }
  13156. struct mg_tcpip_driver mg_tcpip_driver_stm32f = {
  13157. mg_tcpip_driver_stm32f_init, mg_tcpip_driver_stm32f_tx, NULL,
  13158. mg_tcpip_driver_stm32f_up};
  13159. #endif
  13160. #ifdef MG_ENABLE_LINES
  13161. #line 1 "src/drivers/stm32h.c"
  13162. #endif
  13163. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32H) && \
  13164. MG_ENABLE_DRIVER_STM32H
  13165. struct stm32h_eth {
  13166. volatile uint32_t MACCR, MACECR, MACPFR, MACWTR, MACHT0R, MACHT1R,
  13167. RESERVED1[14], MACVTR, RESERVED2, MACVHTR, RESERVED3, MACVIR, MACIVIR,
  13168. RESERVED4[2], MACTFCR, RESERVED5[7], MACRFCR, RESERVED6[7], MACISR,
  13169. MACIER, MACRXTXSR, RESERVED7, MACPCSR, MACRWKPFR, RESERVED8[2], MACLCSR,
  13170. MACLTCR, MACLETR, MAC1USTCR, RESERVED9[12], MACVR, MACDR, RESERVED10,
  13171. MACHWF0R, MACHWF1R, MACHWF2R, RESERVED11[54], MACMDIOAR, MACMDIODR,
  13172. RESERVED12[2], MACARPAR, RESERVED13[59], MACA0HR, MACA0LR, MACA1HR,
  13173. MACA1LR, MACA2HR, MACA2LR, MACA3HR, MACA3LR, RESERVED14[248], MMCCR,
  13174. MMCRIR, MMCTIR, MMCRIMR, MMCTIMR, RESERVED15[14], MMCTSCGPR, MMCTMCGPR,
  13175. RESERVED16[5], MMCTPCGR, RESERVED17[10], MMCRCRCEPR, MMCRAEPR,
  13176. RESERVED18[10], MMCRUPGR, RESERVED19[9], MMCTLPIMSTR, MMCTLPITCR,
  13177. MMCRLPIMSTR, MMCRLPITCR, RESERVED20[65], MACL3L4C0R, MACL4A0R,
  13178. RESERVED21[2], MACL3A0R0R, MACL3A1R0R, MACL3A2R0R, MACL3A3R0R,
  13179. RESERVED22[4], MACL3L4C1R, MACL4A1R, RESERVED23[2], MACL3A0R1R,
  13180. MACL3A1R1R, MACL3A2R1R, MACL3A3R1R, RESERVED24[108], MACTSCR, MACSSIR,
  13181. MACSTSR, MACSTNR, MACSTSUR, MACSTNUR, MACTSAR, RESERVED25, MACTSSR,
  13182. RESERVED26[3], MACTTSSNR, MACTTSSSR, RESERVED27[2], MACACR, RESERVED28,
  13183. MACATSNR, MACATSSR, MACTSIACR, MACTSEACR, MACTSICNR, MACTSECNR,
  13184. RESERVED29[4], MACPPSCR, RESERVED30[3], MACPPSTTSR, MACPPSTTNR, MACPPSIR,
  13185. MACPPSWR, RESERVED31[12], MACPOCR, MACSPI0R, MACSPI1R, MACSPI2R, MACLMIR,
  13186. RESERVED32[11], MTLOMR, RESERVED33[7], MTLISR, RESERVED34[55], MTLTQOMR,
  13187. MTLTQUR, MTLTQDR, RESERVED35[8], MTLQICSR, MTLRQOMR, MTLRQMPOCR, MTLRQDR,
  13188. RESERVED36[177], DMAMR, DMASBMR, DMAISR, DMADSR, RESERVED37[60], DMACCR,
  13189. DMACTCR, DMACRCR, RESERVED38[2], DMACTDLAR, RESERVED39, DMACRDLAR,
  13190. DMACTDTPR, RESERVED40, DMACRDTPR, DMACTDRLR, DMACRDRLR, DMACIER,
  13191. DMACRIWTR, DMACSFCSR, RESERVED41, DMACCATDR, RESERVED42, DMACCARDR,
  13192. RESERVED43, DMACCATBR, RESERVED44, DMACCARBR, DMACSR, RESERVED45[2],
  13193. DMACMFCR;
  13194. };
  13195. #undef ETH
  13196. #define ETH \
  13197. ((struct stm32h_eth *) (uintptr_t) (0x40000000UL + 0x00020000UL + 0x8000UL))
  13198. #define ETH_PKT_SIZE 1540 // Max frame size
  13199. #define ETH_DESC_CNT 4 // Descriptors count
  13200. #define ETH_DS 4 // Descriptor size (words)
  13201. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  13202. static volatile uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  13203. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  13204. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  13205. static struct mg_tcpip_if *s_ifp; // MIP interface
  13206. enum {
  13207. PHY_ADDR = 0,
  13208. PHY_BCR = 0,
  13209. PHY_BSR = 1,
  13210. PHY_CSCR = 31
  13211. }; // PHY constants
  13212. static uint32_t eth_read_phy(uint8_t addr, uint8_t reg) {
  13213. ETH->MACMDIOAR &= (0xF << 8);
  13214. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 3 << 2;
  13215. ETH->MACMDIOAR |= MG_BIT(0);
  13216. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  13217. return ETH->MACMDIODR;
  13218. }
  13219. static void eth_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  13220. ETH->MACMDIODR = val;
  13221. ETH->MACMDIOAR &= (0xF << 8);
  13222. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 1 << 2;
  13223. ETH->MACMDIOAR |= MG_BIT(0);
  13224. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  13225. }
  13226. static uint32_t get_hclk(void) {
  13227. struct rcc {
  13228. volatile uint32_t CR, HSICFGR, CRRCR, CSICFGR, CFGR, RESERVED1, D1CFGR,
  13229. D2CFGR, D3CFGR, RESERVED2, PLLCKSELR, PLLCFGR, PLL1DIVR, PLL1FRACR,
  13230. PLL2DIVR, PLL2FRACR, PLL3DIVR, PLL3FRACR, RESERVED3, D1CCIPR, D2CCIP1R,
  13231. D2CCIP2R, D3CCIPR, RESERVED4, CIER, CIFR, CICR, RESERVED5, BDCR, CSR,
  13232. RESERVED6, AHB3RSTR, AHB1RSTR, AHB2RSTR, AHB4RSTR, APB3RSTR, APB1LRSTR,
  13233. APB1HRSTR, APB2RSTR, APB4RSTR, GCR, RESERVED8, D3AMR, RESERVED11[9],
  13234. RSR, AHB3ENR, AHB1ENR, AHB2ENR, AHB4ENR, APB3ENR, APB1LENR, APB1HENR,
  13235. APB2ENR, APB4ENR, RESERVED12, AHB3LPENR, AHB1LPENR, AHB2LPENR,
  13236. AHB4LPENR, APB3LPENR, APB1LLPENR, APB1HLPENR, APB2LPENR, APB4LPENR,
  13237. RESERVED13[4];
  13238. } *rcc = ((struct rcc *) (0x40000000 + 0x18020000 + 0x4400));
  13239. uint32_t clk = 0, hsi = 64000000 /* 64 MHz */, hse = 8000000 /* 8MHz */,
  13240. csi = 4000000 /* 4MHz */;
  13241. unsigned int sel = (rcc->CFGR & (7 << 3)) >> 3;
  13242. if (sel == 1) {
  13243. clk = csi;
  13244. } else if (sel == 2) {
  13245. clk = hse;
  13246. } else if (sel == 3) {
  13247. uint32_t vco, m, n, p;
  13248. unsigned int src = (rcc->PLLCKSELR & (3 << 0)) >> 0;
  13249. m = ((rcc->PLLCKSELR & (0x3F << 4)) >> 4);
  13250. n = ((rcc->PLL1DIVR & (0x1FF << 0)) >> 0) + 1 +
  13251. ((rcc->PLLCFGR & MG_BIT(0)) ? 1 : 0); // round-up in fractional mode
  13252. p = ((rcc->PLL1DIVR & (0x7F << 9)) >> 9) + 1;
  13253. if (src == 1) {
  13254. clk = csi;
  13255. } else if (src == 2) {
  13256. clk = hse;
  13257. } else {
  13258. clk = hsi;
  13259. clk >>= ((rcc->CR & 3) >> 3);
  13260. }
  13261. vco = (uint32_t) ((uint64_t) clk * n / m);
  13262. clk = vco / p;
  13263. } else {
  13264. clk = hsi;
  13265. clk >>= ((rcc->CR & 3) >> 3);
  13266. }
  13267. const uint8_t cptab[12] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  13268. uint32_t d1cpre = (rcc->D1CFGR & (0x0F << 8)) >> 8;
  13269. if (d1cpre >= 8) clk >>= cptab[d1cpre - 8];
  13270. MG_DEBUG(("D1 CLK: %u", clk));
  13271. uint32_t hpre = (rcc->D1CFGR & (0x0F << 0)) >> 0;
  13272. if (hpre < 8) return clk;
  13273. return ((uint32_t) clk) >> cptab[hpre - 8];
  13274. }
  13275. // Guess CR from AHB1 clock. MDC clock is generated from the ETH peripheral
  13276. // clock (AHB1); as per 802.3, it must not exceed 2. As the AHB clock can
  13277. // be derived from HSI or CSI (internal RC) clocks, and those can go above
  13278. // specs, the datasheets specify a range of frequencies and activate one of a
  13279. // series of dividers to keep the MDC clock safely below 2.5MHz. We guess a
  13280. // divider setting based on HCLK with some drift. If the user uses a different
  13281. // clock from our defaults, needs to set the macros on top. Valid for
  13282. // STM32H74xxx/75xxx (58.11.4)(4.5% worst case drift)(CSI clock has a 7.5 %
  13283. // worst case drift @ max temp)
  13284. static int guess_mdc_cr(void) {
  13285. const uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMDIOAR::CR values
  13286. const uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  13287. uint32_t hclk = get_hclk(); // Guess system HCLK
  13288. int result = -1; // Invalid CR value
  13289. for (int i = 0; i < 6; i++) {
  13290. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  13291. result = crs[i];
  13292. break;
  13293. }
  13294. }
  13295. if (result < 0) MG_ERROR(("HCLK too high"));
  13296. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  13297. return result;
  13298. }
  13299. static bool mg_tcpip_driver_stm32h_init(struct mg_tcpip_if *ifp) {
  13300. struct mg_tcpip_driver_stm32h_data *d =
  13301. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  13302. s_ifp = ifp;
  13303. // Init RX descriptors
  13304. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13305. s_rxdesc[i][0] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13306. s_rxdesc[i][3] = MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  13307. }
  13308. // Init TX descriptors
  13309. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13310. s_txdesc[i][0] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13311. }
  13312. ETH->DMAMR |= MG_BIT(0); // Software reset
  13313. while ((ETH->DMAMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  13314. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13315. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13316. ETH->MACMDIOAR = ((uint32_t) cr & 0xF) << 8;
  13317. // NOTE(scaprile): We do not use timing facilities so the DMA engine does not
  13318. // re-write buffer address
  13319. ETH->DMAMR = 0 << 16; // use interrupt mode 0 (58.8.1) (reset value)
  13320. ETH->DMASBMR |= MG_BIT(12); // AAL NOTE(scaprile): is this actually needed
  13321. ETH->MACIER = 0; // Do not enable additional irq sources (reset value)
  13322. ETH->MACTFCR = MG_BIT(7); // Disable zero-quanta pause
  13323. // ETH->MACPFR = MG_BIT(31); // Receive all
  13324. eth_write_phy(PHY_ADDR, PHY_BCR, MG_BIT(15)); // Reset PHY
  13325. eth_write_phy(PHY_ADDR, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  13326. ETH->DMACRDLAR =
  13327. (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors start address
  13328. ETH->DMACRDRLR = ETH_DESC_CNT - 1; // ring length
  13329. ETH->DMACRDTPR =
  13330. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT -
  13331. 1]; // last valid descriptor address
  13332. ETH->DMACTDLAR =
  13333. (uint32_t) (uintptr_t) s_txdesc; // TX descriptors start address
  13334. ETH->DMACTDRLR = ETH_DESC_CNT - 1; // ring length
  13335. ETH->DMACTDTPR =
  13336. (uint32_t) (uintptr_t) s_txdesc; // first available descriptor address
  13337. ETH->DMACCR = 0; // DSL = 0 (contiguous descriptor table) (reset value)
  13338. ETH->DMACIER = MG_BIT(6) | MG_BIT(15); // RIE, NIE
  13339. ETH->MACCR = MG_BIT(0) | MG_BIT(1) | MG_BIT(13) | MG_BIT(14) |
  13340. MG_BIT(15); // RE, TE, Duplex, Fast, Reserved
  13341. ETH->MTLTQOMR |= MG_BIT(1); // TSF
  13342. ETH->MTLRQOMR |= MG_BIT(5); // RSF
  13343. ETH->DMACTCR |= MG_BIT(0); // ST
  13344. ETH->DMACRCR |= MG_BIT(0); // SR
  13345. // MAC address filtering
  13346. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13347. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  13348. ((uint32_t) ifp->mac[2] << 16) |
  13349. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13350. return true;
  13351. }
  13352. static uint32_t s_txno;
  13353. static size_t mg_tcpip_driver_stm32h_tx(const void *buf, size_t len,
  13354. struct mg_tcpip_if *ifp) {
  13355. if (len > sizeof(s_txbuf[s_txno])) {
  13356. MG_ERROR(("Frame too big, %ld", (long) len));
  13357. len = 0; // Frame is too big
  13358. } else if ((s_txdesc[s_txno][3] & MG_BIT(31))) {
  13359. ifp->nerr++;
  13360. MG_ERROR(("No free descriptors: %u %08X %08X %08X", s_txno,
  13361. s_txdesc[s_txno][3], ETH->DMACSR, ETH->DMACTCR));
  13362. for (int i = 0; i < ETH_DESC_CNT; i++) MG_ERROR(("%08X", s_txdesc[i][3]));
  13363. len = 0; // All descriptors are busy, fail
  13364. } else {
  13365. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13366. s_txdesc[s_txno][2] = (uint32_t) len; // Set data len
  13367. s_txdesc[s_txno][3] = MG_BIT(28) | MG_BIT(29); // FD, LD
  13368. s_txdesc[s_txno][3] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13369. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13370. }
  13371. ETH->DMACSR |= MG_BIT(2) | MG_BIT(1); // Clear any prior TBU, TPS
  13372. ETH->DMACTDTPR = (uint32_t) (uintptr_t) &s_txdesc[s_txno]; // and resume
  13373. return len;
  13374. (void) ifp;
  13375. }
  13376. static bool mg_tcpip_driver_stm32h_up(struct mg_tcpip_if *ifp) {
  13377. uint32_t bsr = eth_read_phy(PHY_ADDR, PHY_BSR);
  13378. bool up = bsr & MG_BIT(2) ? 1 : 0;
  13379. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13380. uint32_t scsr = eth_read_phy(PHY_ADDR, PHY_CSCR);
  13381. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13382. // if(link is slow or half) set flags otherwise
  13383. // reg = tmp
  13384. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(13); // 100M, Full-duplex
  13385. if ((scsr & MG_BIT(3)) == 0) maccr &= ~MG_BIT(14); // 10M
  13386. if ((scsr & MG_BIT(4)) == 0) maccr &= ~MG_BIT(13); // Half-duplex
  13387. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  13388. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  13389. maccr & MG_BIT(13) ? "full" : "half"));
  13390. }
  13391. return up;
  13392. }
  13393. void ETH_IRQHandler(void);
  13394. static uint32_t s_rxno;
  13395. void ETH_IRQHandler(void) {
  13396. if (ETH->DMACSR & MG_BIT(6)) { // Frame received, loop
  13397. ETH->DMACSR = MG_BIT(15) | MG_BIT(6); // Clear flag
  13398. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13399. if (s_rxdesc[s_rxno][3] & MG_BIT(31)) break; // exit when done
  13400. if (((s_rxdesc[s_rxno][3] & (MG_BIT(28) | MG_BIT(29))) ==
  13401. (MG_BIT(28) | MG_BIT(29))) &&
  13402. !(s_rxdesc[s_rxno][3] & MG_BIT(15))) { // skip partial/errored frames
  13403. uint32_t len = s_rxdesc[s_rxno][3] & (MG_BIT(15) - 1);
  13404. // MG_DEBUG(("%lx %lu %lx %08lx", s_rxno, len, s_rxdesc[s_rxno][3],
  13405. // ETH->DMACSR));
  13406. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13407. }
  13408. s_rxdesc[s_rxno][3] =
  13409. MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  13410. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13411. }
  13412. }
  13413. ETH->DMACSR =
  13414. MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing
  13415. ETH->DMACRDTPR =
  13416. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT - 1]; // and resume RX
  13417. }
  13418. struct mg_tcpip_driver mg_tcpip_driver_stm32h = {
  13419. mg_tcpip_driver_stm32h_init, mg_tcpip_driver_stm32h_tx, NULL,
  13420. mg_tcpip_driver_stm32h_up};
  13421. #endif
  13422. #ifdef MG_ENABLE_LINES
  13423. #line 1 "src/drivers/tm4c.c"
  13424. #endif
  13425. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
  13426. struct tm4c_emac {
  13427. volatile uint32_t EMACCFG, EMACFRAMEFLTR, EMACHASHTBLH, EMACHASHTBLL,
  13428. EMACMIIADDR, EMACMIIDATA, EMACFLOWCTL, EMACVLANTG, RESERVED0, EMACSTATUS,
  13429. EMACRWUFF, EMACPMTCTLSTAT, RESERVED1[2], EMACRIS, EMACIM, EMACADDR0H,
  13430. EMACADDR0L, EMACADDR1H, EMACADDR1L, EMACADDR2H, EMACADDR2L, EMACADDR3H,
  13431. EMACADDR3L, RESERVED2[31], EMACWDOGTO, RESERVED3[8], EMACMMCCTRL,
  13432. EMACMMCRXRIS, EMACMMCTXRIS, EMACMMCRXIM, EMACMMCTXIM, RESERVED4,
  13433. EMACTXCNTGB, RESERVED5[12], EMACTXCNTSCOL, EMACTXCNTMCOL, RESERVED6[4],
  13434. EMACTXOCTCNTG, RESERVED7[6], EMACRXCNTGB, RESERVED8[4], EMACRXCNTCRCERR,
  13435. EMACRXCNTALGNERR, RESERVED9[10], EMACRXCNTGUNI, RESERVED10[239],
  13436. EMACVLNINCREP, EMACVLANHASH, RESERVED11[93], EMACTIMSTCTRL, EMACSUBSECINC,
  13437. EMACTIMSEC, EMACTIMNANO, EMACTIMSECU, EMACTIMNANOU, EMACTIMADD,
  13438. EMACTARGSEC, EMACTARGNANO, EMACHWORDSEC, EMACTIMSTAT, EMACPPSCTRL,
  13439. RESERVED12[12], EMACPPS0INTVL, EMACPPS0WIDTH, RESERVED13[294],
  13440. EMACDMABUSMOD, EMACTXPOLLD, EMACRXPOLLD, EMACRXDLADDR, EMACTXDLADDR,
  13441. EMACDMARIS, EMACDMAOPMODE, EMACDMAIM, EMACMFBOC, EMACRXINTWDT,
  13442. RESERVED14[8], EMACHOSTXDESC, EMACHOSRXDESC, EMACHOSTXBA, EMACHOSRXBA,
  13443. RESERVED15[218], EMACPP, EMACPC, EMACCC, RESERVED16, EMACEPHYRIS,
  13444. EMACEPHYIM, EMACEPHYIMSC;
  13445. };
  13446. #undef EMAC
  13447. #define EMAC ((struct tm4c_emac *) (uintptr_t) 0x400EC000)
  13448. #define ETH_PKT_SIZE 1540 // Max frame size
  13449. #define ETH_DESC_CNT 4 // Descriptors count
  13450. #define ETH_DS 4 // Descriptor size (words)
  13451. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  13452. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  13453. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  13454. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  13455. static struct mg_tcpip_if *s_ifp; // MIP interface
  13456. enum {
  13457. EPHY_ADDR = 0,
  13458. EPHYBMCR = 0,
  13459. EPHYBMSR = 1,
  13460. EPHYSTS = 16
  13461. }; // PHY constants
  13462. static inline void tm4cspin(volatile uint32_t count) {
  13463. while (count--) (void) 0;
  13464. }
  13465. static uint32_t emac_read_phy(uint8_t addr, uint8_t reg) {
  13466. EMAC->EMACMIIADDR &= (0xf << 2);
  13467. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  13468. EMAC->EMACMIIADDR |= MG_BIT(0);
  13469. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  13470. return EMAC->EMACMIIDATA;
  13471. }
  13472. static void emac_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  13473. EMAC->EMACMIIDATA = val;
  13474. EMAC->EMACMIIADDR &= (0xf << 2);
  13475. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  13476. EMAC->EMACMIIADDR |= MG_BIT(0);
  13477. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  13478. }
  13479. static uint32_t get_sysclk(void) {
  13480. struct sysctl {
  13481. volatile uint32_t DONTCARE0[44], RSCLKCFG, DONTCARE1[43], PLLFREQ0,
  13482. PLLFREQ1;
  13483. } *sysctl = (struct sysctl *) 0x400FE000;
  13484. uint32_t clk = 0, piosc = 16000000 /* 16 MHz */, mosc = 25000000 /* 25MHz */;
  13485. if (sysctl->RSCLKCFG & (1 << 28)) { // USEPLL
  13486. uint32_t fin, vco, mdiv, n, q, psysdiv;
  13487. uint32_t pllsrc = (sysctl->RSCLKCFG & (0xf << 24)) >> 24;
  13488. if (pllsrc == 0) {
  13489. clk = piosc;
  13490. } else if (pllsrc == 3) {
  13491. clk = mosc;
  13492. } else {
  13493. MG_ERROR(("Unsupported clock source"));
  13494. }
  13495. q = (sysctl->PLLFREQ1 & (0x1f << 8)) >> 8;
  13496. n = (sysctl->PLLFREQ1 & (0x1f << 0)) >> 0;
  13497. fin = clk / ((q + 1) * (n + 1));
  13498. mdiv = (sysctl->PLLFREQ0 & (0x3ff << 0)) >>
  13499. 0; // mint + (mfrac / 1024); MFRAC not supported
  13500. psysdiv = (sysctl->RSCLKCFG & (0x3f << 0)) >> 0;
  13501. vco = (uint32_t) ((uint64_t) fin * mdiv);
  13502. return vco / (psysdiv + 1);
  13503. }
  13504. uint32_t oscsrc = (sysctl->RSCLKCFG & (0xf << 20)) >> 20;
  13505. if (oscsrc == 0) {
  13506. clk = piosc;
  13507. } else if (oscsrc == 3) {
  13508. clk = mosc;
  13509. } else {
  13510. MG_ERROR(("Unsupported clock source"));
  13511. }
  13512. uint32_t osysdiv = (sysctl->RSCLKCFG & (0xf << 16)) >> 16;
  13513. return clk / (osysdiv + 1);
  13514. }
  13515. // Guess CR from SYSCLK. MDC clock is generated from SYSCLK (AHB); as per
  13516. // 802.3, it must not exceed 2.5MHz (also 20.4.2.6) As the AHB clock can be
  13517. // derived from the PIOSC (internal RC), and it can go above specs, the
  13518. // datasheets specify a range of frequencies and activate one of a series of
  13519. // dividers to keep the MDC clock safely below 2.5MHz. We guess a divider
  13520. // setting based on SYSCLK with a +5% drift. If the user uses a different clock
  13521. // from our defaults, needs to set the macros on top Valid for TM4C129x (20.7)
  13522. // (4.5% worst case drift)
  13523. // The PHY receives the main oscillator (MOSC) (20.3.1)
  13524. static int guess_mdc_cr(void) {
  13525. uint8_t crs[] = {2, 3, 0, 1}; // EMAC->MACMIIAR::CR values
  13526. uint8_t div[] = {16, 26, 42, 62}; // Respective HCLK dividers
  13527. uint32_t sysclk = get_sysclk(); // Guess system SYSCLK
  13528. int result = -1; // Invalid CR value
  13529. if (sysclk < 25000000) {
  13530. MG_ERROR(("SYSCLK too low"));
  13531. } else {
  13532. for (int i = 0; i < 4; i++) {
  13533. if (sysclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  13534. result = crs[i];
  13535. break;
  13536. }
  13537. }
  13538. if (result < 0) MG_ERROR(("SYSCLK too high"));
  13539. }
  13540. MG_DEBUG(("SYSCLK: %u, CR: %d", sysclk, result));
  13541. return result;
  13542. }
  13543. static bool mg_tcpip_driver_tm4c_init(struct mg_tcpip_if *ifp) {
  13544. struct mg_tcpip_driver_tm4c_data *d =
  13545. (struct mg_tcpip_driver_tm4c_data *) ifp->driver_data;
  13546. s_ifp = ifp;
  13547. // Init RX descriptors
  13548. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13549. s_rxdesc[i][0] = MG_BIT(31); // Own
  13550. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  13551. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13552. s_rxdesc[i][3] =
  13553. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13554. // MG_DEBUG(("%d %p", i, s_rxdesc[i]));
  13555. }
  13556. // Init TX descriptors
  13557. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13558. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13559. s_txdesc[i][3] =
  13560. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13561. }
  13562. EMAC->EMACDMABUSMOD |= MG_BIT(0); // Software reset
  13563. while ((EMAC->EMACDMABUSMOD & MG_BIT(0)) != 0) tm4cspin(1); // Wait until done
  13564. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13565. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13566. EMAC->EMACMIIADDR = ((uint32_t) cr & 0xf) << 2;
  13567. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  13568. // hardware checksum. Therefore, descriptor size is 4, not 8
  13569. // EMAC->EMACDMABUSMOD = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) | MG_BIT(25);
  13570. EMAC->EMACIM = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  13571. EMAC->EMACFLOWCTL = MG_BIT(7); // Disable zero-quanta pause
  13572. // EMAC->EMACFRAMEFLTR = MG_BIT(31); // Receive all
  13573. // EMAC->EMACPC defaults to internal PHY (EPHY) in MMI mode
  13574. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(15)); // Reset internal PHY (EPHY)
  13575. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(12)); // Set autonegotiation
  13576. EMAC->EMACRXDLADDR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  13577. EMAC->EMACTXDLADDR = (uint32_t) (uintptr_t) s_txdesc; // TX descriptors
  13578. EMAC->EMACDMAIM = MG_BIT(6) | MG_BIT(16); // RIE, NIE
  13579. EMAC->EMACCFG = MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  13580. EMAC->EMACDMAOPMODE =
  13581. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  13582. EMAC->EMACADDR0H = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13583. EMAC->EMACADDR0L = (uint32_t) (ifp->mac[3] << 24) |
  13584. ((uint32_t) ifp->mac[2] << 16) |
  13585. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13586. // NOTE(scaprile) There are 3 additional slots for filtering, disabled by
  13587. // default. This also applies to the STM32 driver (at least for F7)
  13588. return true;
  13589. }
  13590. static uint32_t s_txno;
  13591. static size_t mg_tcpip_driver_tm4c_tx(const void *buf, size_t len,
  13592. struct mg_tcpip_if *ifp) {
  13593. if (len > sizeof(s_txbuf[s_txno])) {
  13594. MG_ERROR(("Frame too big, %ld", (long) len));
  13595. len = 0; // fail
  13596. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  13597. ifp->nerr++;
  13598. MG_ERROR(("No descriptors available"));
  13599. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long)
  13600. // EMAC->EMACDMARIS);
  13601. len = 0; // fail
  13602. } else {
  13603. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13604. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  13605. s_txdesc[s_txno][0] =
  13606. MG_BIT(20) | MG_BIT(28) | MG_BIT(29) | MG_BIT(30); // Chain,FS,LS,IC
  13607. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13608. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13609. }
  13610. EMAC->EMACDMARIS = MG_BIT(2) | MG_BIT(5); // Clear any prior TU/UNF
  13611. EMAC->EMACTXPOLLD = 0; // and resume
  13612. return len;
  13613. (void) ifp;
  13614. }
  13615. static bool mg_tcpip_driver_tm4c_up(struct mg_tcpip_if *ifp) {
  13616. uint32_t bmsr = emac_read_phy(EPHY_ADDR, EPHYBMSR);
  13617. bool up = (bmsr & MG_BIT(2)) ? 1 : 0;
  13618. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13619. uint32_t sts = emac_read_phy(EPHY_ADDR, EPHYSTS);
  13620. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13621. // if(link is slow or half) set flags otherwise
  13622. // reg = tmp
  13623. uint32_t emaccfg = EMAC->EMACCFG | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  13624. if (sts & MG_BIT(1)) emaccfg &= ~MG_BIT(14); // 10M
  13625. if ((sts & MG_BIT(2)) == 0) emaccfg &= ~MG_BIT(11); // Half-duplex
  13626. EMAC->EMACCFG = emaccfg; // IRQ handler does not fiddle with this register
  13627. MG_DEBUG(("Link is %uM %s-duplex", emaccfg & MG_BIT(14) ? 100 : 10,
  13628. emaccfg & MG_BIT(11) ? "full" : "half"));
  13629. }
  13630. return up;
  13631. }
  13632. void EMAC0_IRQHandler(void);
  13633. static uint32_t s_rxno;
  13634. void EMAC0_IRQHandler(void) {
  13635. if (EMAC->EMACDMARIS & MG_BIT(6)) { // Frame received, loop
  13636. EMAC->EMACDMARIS = MG_BIT(16) | MG_BIT(6); // Clear flag
  13637. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13638. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  13639. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) == (MG_BIT(8) | MG_BIT(9))) &&
  13640. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  13641. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  13642. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  13643. // EMAC->EMACDMARIS);
  13644. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13645. }
  13646. s_rxdesc[s_rxno][0] = MG_BIT(31);
  13647. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13648. }
  13649. }
  13650. EMAC->EMACDMARIS = MG_BIT(7); // Clear possible RU while processing
  13651. EMAC->EMACRXPOLLD = 0; // and resume RX
  13652. }
  13653. struct mg_tcpip_driver mg_tcpip_driver_tm4c = {mg_tcpip_driver_tm4c_init,
  13654. mg_tcpip_driver_tm4c_tx, NULL,
  13655. mg_tcpip_driver_tm4c_up};
  13656. #endif
  13657. #ifdef MG_ENABLE_LINES
  13658. #line 1 "src/drivers/w5500.c"
  13659. #endif
  13660. #if MG_ENABLE_TCPIP
  13661. enum { W5500_CR = 0, W5500_S0 = 1, W5500_TX0 = 2, W5500_RX0 = 3 };
  13662. static void w5500_txn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr, bool wr,
  13663. void *buf, size_t len) {
  13664. uint8_t *p = (uint8_t *) buf;
  13665. uint8_t cmd[] = {(uint8_t) (addr >> 8), (uint8_t) (addr & 255),
  13666. (uint8_t) ((block << 3) | (wr ? 4 : 0))};
  13667. s->begin(s->spi);
  13668. for (size_t i = 0; i < sizeof(cmd); i++) s->txn(s->spi, cmd[i]);
  13669. for (size_t i = 0; i < len; i++) {
  13670. uint8_t r = s->txn(s->spi, p[i]);
  13671. if (!wr) p[i] = r;
  13672. }
  13673. s->end(s->spi);
  13674. }
  13675. // clang-format off
  13676. 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); }
  13677. 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); }
  13678. 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)); }
  13679. 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); }
  13680. 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; }
  13681. 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]); }
  13682. // clang-format on
  13683. static size_t w5500_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  13684. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13685. uint16_t r = 0, n = 0, len = (uint16_t) buflen, n2; // Read recv len
  13686. while ((n2 = w5500_r2(s, W5500_S0, 0x26)) > n) n = n2; // Until it is stable
  13687. // printf("RSR: %d\n", (int) n);
  13688. if (n > 0) {
  13689. uint16_t ptr = w5500_r2(s, W5500_S0, 0x28); // Get read pointer
  13690. n = w5500_r2(s, W5500_RX0, ptr); // Read frame length
  13691. if (n <= len + 2 && n > 1) {
  13692. r = (uint16_t) (n - 2);
  13693. w5500_rn(s, W5500_RX0, (uint16_t) (ptr + 2), buf, r);
  13694. }
  13695. w5500_w2(s, W5500_S0, 0x28, (uint16_t) (ptr + n)); // Advance read pointer
  13696. w5500_w1(s, W5500_S0, 1, 0x40); // Sock0 CR -> RECV
  13697. // printf(" RX_RD: tot=%u n=%u r=%u\n", n2, n, r);
  13698. }
  13699. return r;
  13700. }
  13701. static size_t w5500_tx(const void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  13702. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13703. uint16_t n = 0, len = (uint16_t) buflen;
  13704. while (n < len) n = w5500_r2(s, W5500_S0, 0x20); // Wait for space
  13705. uint16_t ptr = w5500_r2(s, W5500_S0, 0x24); // Get write pointer
  13706. w5500_wn(s, W5500_TX0, ptr, (void *) buf, len); // Write data
  13707. w5500_w2(s, W5500_S0, 0x24, (uint16_t) (ptr + len)); // Advance write pointer
  13708. w5500_w1(s, W5500_S0, 1, 0x20); // Sock0 CR -> SEND
  13709. for (int i = 0; i < 40; i++) {
  13710. uint8_t ir = w5500_r1(s, W5500_S0, 2); // Read S0 IR
  13711. if (ir == 0) continue;
  13712. // printf("IR %d, len=%d, free=%d, ptr %d\n", ir, (int) len, (int) n, ptr);
  13713. w5500_w1(s, W5500_S0, 2, ir); // Write S0 IR: clear it!
  13714. if (ir & 8) len = 0; // Timeout. Report error
  13715. if (ir & (16 | 8)) break; // Stop on SEND_OK or timeout
  13716. }
  13717. return len;
  13718. }
  13719. static bool w5500_init(struct mg_tcpip_if *ifp) {
  13720. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13721. s->end(s->spi);
  13722. w5500_w1(s, W5500_CR, 0, 0x80); // Reset chip: CR -> 0x80
  13723. w5500_w1(s, W5500_CR, 0x2e, 0); // CR PHYCFGR -> reset
  13724. w5500_w1(s, W5500_CR, 0x2e, 0xf8); // CR PHYCFGR -> set
  13725. // w5500_wn(s, W5500_CR, 9, s->mac, 6); // Set source MAC
  13726. w5500_w1(s, W5500_S0, 0x1e, 16); // Sock0 RX buf size
  13727. w5500_w1(s, W5500_S0, 0x1f, 16); // Sock0 TX buf size
  13728. w5500_w1(s, W5500_S0, 0, 4); // Sock0 MR -> MACRAW
  13729. w5500_w1(s, W5500_S0, 1, 1); // Sock0 CR -> OPEN
  13730. return w5500_r1(s, W5500_S0, 3) == 0x42; // Sock0 SR == MACRAW
  13731. }
  13732. static bool w5500_up(struct mg_tcpip_if *ifp) {
  13733. struct mg_tcpip_spi *spi = (struct mg_tcpip_spi *) ifp->driver_data;
  13734. uint8_t phycfgr = w5500_r1(spi, W5500_CR, 0x2e);
  13735. return phycfgr & 1; // Bit 0 of PHYCFGR is LNK (0 - down, 1 - up)
  13736. }
  13737. struct mg_tcpip_driver mg_tcpip_driver_w5500 = {w5500_init, w5500_tx, w5500_rx, w5500_up};
  13738. #endif