mongoose.c 515 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350
  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. if (c==NULL)
  2041. {
  2042. return;
  2043. }
  2044. // mg_printf(c, "HTTP/1.1 %d %s\r\n%sContent-Length: \r\n\r\n", code,
  2045. // mg_http_status_code_str(code), headers == NULL ? "" : headers);
  2046. mg_printf(c, "HTTP/1.1 %d %s\r\n"
  2047. "Content-Type: text/html\n"
  2048. "Content-Length: %d\n"
  2049. "Connection: Keep-Alive\n"
  2050. "Keep-Alive: timeout=30, max=396\n"
  2051. "X-Content-Type-0ptions: nosniff\n"
  2052. "X-Frame-0ptions:: SAMEORIGIN\n"
  2053. "X-Xss-Protection: 1: mode=block\n"
  2054. "Accept-Ranges: bytes\n"
  2055. "Vary: Accept-Encoding\n\n"
  2056. "%s\n", code, mg_http_status_code_str(code),strlen(fmt == NULL ? "" : fmt), fmt == NULL ? "" : fmt);
  2057. len = c->send.len;
  2058. va_start(ap, fmt == NULL ? "" : fmt);
  2059. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt == NULL ? "" : fmt, &ap);
  2060. va_end(ap);
  2061. /*if (c->send.len > 16) {
  2062. size_t n = mg_snprintf((char *) &c->send.buf[len - 15], 11, "%-10lu",
  2063. (unsigned long) (c->send.len - len));
  2064. c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space
  2065. }*/
  2066. c->is_resp = 0;
  2067. }
  2068. static void http_cb(struct mg_connection *, int, void *);
  2069. static void restore_http_cb(struct mg_connection *c) {
  2070. mg_fs_close((struct mg_fd *) c->pfn_data);
  2071. c->pfn_data = NULL;
  2072. c->pfn = http_cb;
  2073. c->is_resp = 0;
  2074. }
  2075. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
  2076. char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime) {
  2077. mg_snprintf(buf, len, "\"%lld.%lld\"", (int64_t) mtime, (int64_t) size);
  2078. return buf;
  2079. }
  2080. static void static_cb(struct mg_connection *c, int ev, void *ev_data) {
  2081. if (ev == MG_EV_WRITE || ev == MG_EV_POLL) {
  2082. struct mg_fd *fd = (struct mg_fd *) c->pfn_data;
  2083. // Read to send IO buffer directly, avoid extra on-stack buffer
  2084. size_t n, max = MG_IO_SIZE, space;
  2085. size_t *cl = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2086. sizeof(size_t) * sizeof(size_t)];
  2087. if (c->send.size < max) mg_iobuf_resize(&c->send, max);
  2088. if (c->send.len >= c->send.size) return; // Rate limit
  2089. if ((space = c->send.size - c->send.len) > *cl) space = *cl;
  2090. n = fd->fs->rd(fd->fd, c->send.buf + c->send.len, space);
  2091. c->send.len += n;
  2092. *cl -= n;
  2093. if (n == 0) restore_http_cb(c);
  2094. } else if (ev == MG_EV_CLOSE) {
  2095. restore_http_cb(c);
  2096. }
  2097. (void) ev_data;
  2098. }
  2099. // Known mime types. Keep it outside guess_content_type() function, since
  2100. // some environments don't like it defined there.
  2101. // clang-format off
  2102. static struct mg_str s_known_types[] = {
  2103. MG_C_STR("html"), MG_C_STR("text/html; charset=utf-8"),
  2104. MG_C_STR("htm"), MG_C_STR("text/html; charset=utf-8"),
  2105. MG_C_STR("css"), MG_C_STR("text/css; charset=utf-8"),
  2106. MG_C_STR("js"), MG_C_STR("text/javascript; charset=utf-8"),
  2107. MG_C_STR("gif"), MG_C_STR("image/gif"),
  2108. MG_C_STR("png"), MG_C_STR("image/png"),
  2109. MG_C_STR("jpg"), MG_C_STR("image/jpeg"),
  2110. MG_C_STR("jpeg"), MG_C_STR("image/jpeg"),
  2111. MG_C_STR("woff"), MG_C_STR("font/woff"),
  2112. MG_C_STR("ttf"), MG_C_STR("font/ttf"),
  2113. MG_C_STR("svg"), MG_C_STR("image/svg+xml"),
  2114. MG_C_STR("txt"), MG_C_STR("text/plain; charset=utf-8"),
  2115. MG_C_STR("avi"), MG_C_STR("video/x-msvideo"),
  2116. MG_C_STR("csv"), MG_C_STR("text/csv"),
  2117. MG_C_STR("doc"), MG_C_STR("application/msword"),
  2118. MG_C_STR("exe"), MG_C_STR("application/octet-stream"),
  2119. MG_C_STR("gz"), MG_C_STR("application/gzip"),
  2120. MG_C_STR("ico"), MG_C_STR("image/x-icon"),
  2121. MG_C_STR("json"), MG_C_STR("application/json"),
  2122. MG_C_STR("mov"), MG_C_STR("video/quicktime"),
  2123. MG_C_STR("mp3"), MG_C_STR("audio/mpeg"),
  2124. MG_C_STR("mp4"), MG_C_STR("video/mp4"),
  2125. MG_C_STR("mpeg"), MG_C_STR("video/mpeg"),
  2126. MG_C_STR("pdf"), MG_C_STR("application/pdf"),
  2127. MG_C_STR("shtml"), MG_C_STR("text/html; charset=utf-8"),
  2128. MG_C_STR("tgz"), MG_C_STR("application/tar-gz"),
  2129. MG_C_STR("wav"), MG_C_STR("audio/wav"),
  2130. MG_C_STR("webp"), MG_C_STR("image/webp"),
  2131. MG_C_STR("zip"), MG_C_STR("application/zip"),
  2132. MG_C_STR("3gp"), MG_C_STR("video/3gpp"),
  2133. {0, 0},
  2134. };
  2135. // clang-format on
  2136. static struct mg_str guess_content_type(struct mg_str path, const char *extra) {
  2137. struct mg_str k, v, s = mg_str(extra);
  2138. size_t i = 0;
  2139. // Shrink path to its extension only
  2140. while (i < path.len && path.ptr[path.len - i - 1] != '.') i++;
  2141. path.ptr += path.len - i;
  2142. path.len = i;
  2143. // Process user-provided mime type overrides, if any
  2144. while (mg_commalist(&s, &k, &v)) {
  2145. if (mg_strcmp(path, k) == 0) return v;
  2146. }
  2147. // Process built-in mime types
  2148. for (i = 0; s_known_types[i].ptr != NULL; i += 2) {
  2149. if (mg_strcmp(path, s_known_types[i]) == 0) return s_known_types[i + 1];
  2150. }
  2151. return mg_str("text/plain; charset=utf-8");
  2152. }
  2153. static int getrange(struct mg_str *s, size_t *a, size_t *b) {
  2154. size_t i, numparsed = 0;
  2155. for (i = 0; i + 6 < s->len; i++) {
  2156. struct mg_str k, v = mg_str_n(s->ptr + i + 6, s->len - i - 6);
  2157. if (memcmp(&s->ptr[i], "bytes=", 6) != 0) continue;
  2158. if (mg_split(&v, &k, NULL, '-')) {
  2159. if (mg_to_size_t(k, a)) numparsed++;
  2160. if (v.len > 0 && mg_to_size_t(v, b)) numparsed++;
  2161. } else {
  2162. if (mg_to_size_t(v, a)) numparsed++;
  2163. }
  2164. break;
  2165. }
  2166. return (int) numparsed;
  2167. }
  2168. void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
  2169. const char *path,
  2170. const struct mg_http_serve_opts *opts) {
  2171. char etag[64], tmp[MG_PATH_MAX];
  2172. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2173. struct mg_fd *fd = NULL;
  2174. size_t size = 0;
  2175. time_t mtime = 0;
  2176. struct mg_str *inm = NULL;
  2177. struct mg_str mime = guess_content_type(mg_str(path), opts->mime_types);
  2178. bool gzip = false;
  2179. if (path != NULL) {
  2180. // If a browser sends us "Accept-Encoding: gzip", try to open .gz first
  2181. struct mg_str *ae = mg_http_get_header(hm, "Accept-Encoding");
  2182. if (ae != NULL && mg_strstr(*ae, mg_str("gzip")) != NULL) {
  2183. mg_snprintf(tmp, sizeof(tmp), "%s.gz", path);
  2184. fd = mg_fs_open(fs, tmp, MG_FS_READ);
  2185. if (fd != NULL) gzip = true, path = tmp;
  2186. }
  2187. // No luck opening .gz? Open what we've told to open
  2188. if (fd == NULL) fd = mg_fs_open(fs, path, MG_FS_READ);
  2189. }
  2190. // Failed to open, and page404 is configured? Open it, then
  2191. if (fd == NULL && opts->page404 != NULL) {
  2192. fd = mg_fs_open(fs, opts->page404, MG_FS_READ);
  2193. mime = guess_content_type(mg_str(path), opts->mime_types);
  2194. path = opts->page404;
  2195. }
  2196. if (fd == NULL || fs->st(path, &size, &mtime) == 0) {
  2197. mg_http_reply(c, 404, opts->extra_headers, "Not found\n");
  2198. mg_fs_close(fd);
  2199. // NOTE: mg_http_etag() call should go first!
  2200. } else if (mg_http_etag(etag, sizeof(etag), size, mtime) != NULL &&
  2201. (inm = mg_http_get_header(hm, "If-None-Match")) != NULL &&
  2202. mg_vcasecmp(inm, etag) == 0) {
  2203. mg_fs_close(fd);
  2204. mg_http_reply(c, 304, opts->extra_headers, "");
  2205. } else {
  2206. int n, status = 200;
  2207. char range[100];
  2208. size_t r1 = 0, r2 = 0, cl = size;
  2209. // Handle Range header
  2210. struct mg_str *rh = mg_http_get_header(hm, "Range");
  2211. range[0] = '\0';
  2212. if (rh != NULL && (n = getrange(rh, &r1, &r2)) > 0) {
  2213. // If range is specified like "400-", set second limit to content len
  2214. if (n == 1) r2 = cl - 1;
  2215. if (r1 > r2 || r2 >= cl) {
  2216. status = 416;
  2217. cl = 0;
  2218. mg_snprintf(range, sizeof(range), "Content-Range: bytes */%lld\r\n",
  2219. (int64_t) size);
  2220. } else {
  2221. status = 206;
  2222. cl = r2 - r1 + 1;
  2223. mg_snprintf(range, sizeof(range),
  2224. "Content-Range: bytes %llu-%llu/%llu\r\n", (uint64_t) r1,
  2225. (uint64_t) (r1 + cl - 1), (uint64_t) size);
  2226. fs->sk(fd->fd, r1);
  2227. }
  2228. }
  2229. mg_printf(c,
  2230. "HTTP/1.1 %d %s\r\n"
  2231. "Content-Type: %.*s\r\n"
  2232. "Etag: %s\r\n"
  2233. "Content-Length: %llu\r\n"
  2234. "%s%s%s\r\n",
  2235. status, mg_http_status_code_str(status), (int) mime.len, mime.ptr,
  2236. etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
  2237. range, opts->extra_headers ? opts->extra_headers : "");
  2238. if (mg_vcasecmp(&hm->method, "HEAD") == 0) {
  2239. c->is_draining = 1;
  2240. c->is_resp = 0;
  2241. mg_fs_close(fd);
  2242. } else {
  2243. // Track to-be-sent content length at the end of c->data, aligned
  2244. size_t *clp = (size_t *) &c->data[(sizeof(c->data) - sizeof(size_t)) /
  2245. sizeof(size_t) * sizeof(size_t)];
  2246. c->pfn = static_cb;
  2247. c->pfn_data = fd;
  2248. *clp = cl;
  2249. }
  2250. }
  2251. }
  2252. struct printdirentrydata {
  2253. struct mg_connection *c;
  2254. struct mg_http_message *hm;
  2255. const struct mg_http_serve_opts *opts;
  2256. const char *dir;
  2257. };
  2258. #if MG_ENABLE_DIRLIST
  2259. static void printdirentry(const char *name, void *userdata) {
  2260. struct printdirentrydata *d = (struct printdirentrydata *) userdata;
  2261. struct mg_fs *fs = d->opts->fs == NULL ? &mg_fs_posix : d->opts->fs;
  2262. size_t size = 0;
  2263. time_t t = 0;
  2264. char path[MG_PATH_MAX], sz[40], mod[40];
  2265. int flags, n = 0;
  2266. // MG_DEBUG(("[%s] [%s]", d->dir, name));
  2267. if (mg_snprintf(path, sizeof(path), "%s%c%s", d->dir, '/', name) >
  2268. sizeof(path)) {
  2269. MG_ERROR(("%s truncated", name));
  2270. } else if ((flags = fs->st(path, &size, &t)) == 0) {
  2271. MG_ERROR(("%lu stat(%s): %d", d->c->id, path, errno));
  2272. } else {
  2273. const char *slash = flags & MG_FS_DIR ? "/" : "";
  2274. if (flags & MG_FS_DIR) {
  2275. mg_snprintf(sz, sizeof(sz), "%s", "[DIR]");
  2276. } else {
  2277. mg_snprintf(sz, sizeof(sz), "%lld", (uint64_t) size);
  2278. }
  2279. #if defined(MG_HTTP_DIRLIST_TIME_FMT)
  2280. {
  2281. char time_str[40];
  2282. struct tm *time_info = localtime(&t);
  2283. strftime(time_str, sizeof time_str, "%Y/%m/%d %H:%M:%S", time_info);
  2284. mg_snprintf(mod, sizeof(mod), "%s", time_str);
  2285. }
  2286. #else
  2287. mg_snprintf(mod, sizeof(mod), "%lu", (unsigned long) t);
  2288. #endif
  2289. n = (int) mg_url_encode(name, strlen(name), path, sizeof(path));
  2290. mg_printf(d->c,
  2291. " <tr><td><a href=\"%.*s%s\">%s%s</a></td>"
  2292. "<td name=%lu>%s</td><td name=%lld>%s</td></tr>\n",
  2293. n, path, slash, name, slash, (unsigned long) t, mod,
  2294. flags & MG_FS_DIR ? (int64_t) -1 : (int64_t) size, sz);
  2295. }
  2296. }
  2297. static void listdir(struct mg_connection *c, struct mg_http_message *hm,
  2298. const struct mg_http_serve_opts *opts, char *dir) {
  2299. const char *sort_js_code =
  2300. "<script>function srt(tb, sc, so, d) {"
  2301. "var tr = Array.prototype.slice.call(tb.rows, 0),"
  2302. "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
  2303. "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
  2304. "t1 = a.cells[2].getAttribute('name'), "
  2305. "t2 = b.cells[2].getAttribute('name'); "
  2306. "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
  2307. "n1 ? parseInt(n2) - parseInt(n1) : "
  2308. "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
  2309. const char *sort_js_code2 =
  2310. "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
  2311. "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
  2312. "};"
  2313. "window.onload = function() {"
  2314. "var tb = document.getElementById('tb');"
  2315. "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
  2316. "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
  2317. "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
  2318. "sc = c; ev.preventDefault();}};"
  2319. "srt(tb, sc, so, true);"
  2320. "}"
  2321. "</script>";
  2322. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2323. struct printdirentrydata d = {c, hm, opts, dir};
  2324. char tmp[10], buf[MG_PATH_MAX];
  2325. size_t off, n;
  2326. int len = mg_url_decode(hm->uri.ptr, hm->uri.len, buf, sizeof(buf), 0);
  2327. struct mg_str uri = len > 0 ? mg_str_n(buf, (size_t) len) : hm->uri;
  2328. mg_printf(c,
  2329. "HTTP/1.1 200 OK\r\n"
  2330. "Content-Type: text/html; charset=utf-8\r\n"
  2331. "%s"
  2332. "Content-Length: \r\n\r\n",
  2333. opts->extra_headers == NULL ? "" : opts->extra_headers);
  2334. off = c->send.len; // Start of body
  2335. mg_printf(c,
  2336. "<!DOCTYPE html><html><head><title>Index of %.*s</title>%s%s"
  2337. "<style>th,td {text-align: left; padding-right: 1em; "
  2338. "font-family: monospace; }</style></head>"
  2339. "<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>"
  2340. "<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
  2341. "<a href=\"#\" rel=\"1\">Modified</a></th>"
  2342. "<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
  2343. "<tr><td colspan=\"3\"><hr></td></tr>"
  2344. "</thead>"
  2345. "<tbody id=\"tb\">\n",
  2346. (int) uri.len, uri.ptr, sort_js_code, sort_js_code2, (int) uri.len,
  2347. uri.ptr);
  2348. mg_printf(c, "%s",
  2349. " <tr><td><a href=\"..\">..</a></td>"
  2350. "<td name=-1></td><td name=-1>[DIR]</td></tr>\n");
  2351. fs->ls(dir, printdirentry, &d);
  2352. mg_printf(c,
  2353. "</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
  2354. "</table><address>Mongoose v.%s</address></body></html>\n",
  2355. MG_VERSION);
  2356. n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
  2357. if (n > sizeof(tmp)) n = 0;
  2358. memcpy(c->send.buf + off - 12, tmp, n); // Set content length
  2359. c->is_resp = 0; // Mark response end
  2360. }
  2361. #endif
  2362. // Resolve requested file into `path` and return its fs->st() result
  2363. static int uri_to_path2(struct mg_connection *c, struct mg_http_message *hm,
  2364. struct mg_fs *fs, struct mg_str url, struct mg_str dir,
  2365. char *path, size_t path_size) {
  2366. int flags, tmp;
  2367. // Append URI to the root_dir, and sanitize it
  2368. size_t n = mg_snprintf(path, path_size, "%.*s", (int) dir.len, dir.ptr);
  2369. if (n + 2 >= path_size) {
  2370. mg_http_reply(c, 400, "", "Exceeded path size");
  2371. return -1;
  2372. }
  2373. path[path_size - 1] = '\0';
  2374. // Terminate root dir with slash
  2375. if (n > 0 && path[n - 1] != '/') path[n++] = '/', path[n] = '\0';
  2376. if (url.len < hm->uri.len) {
  2377. mg_url_decode(hm->uri.ptr + url.len, hm->uri.len - url.len, path + n,
  2378. path_size - n, 0);
  2379. }
  2380. path[path_size - 1] = '\0'; // Double-check
  2381. if (!mg_path_is_sane(path)) {
  2382. mg_http_reply(c, 400, "", "Invalid path");
  2383. return -1;
  2384. }
  2385. n = strlen(path);
  2386. while (n > 1 && path[n - 1] == '/') path[--n] = 0; // Trim trailing slashes
  2387. flags = mg_vcmp(&hm->uri, "/") == 0 ? MG_FS_DIR : fs->st(path, NULL, NULL);
  2388. MG_VERBOSE(("%lu %.*s -> %s %d", c->id, (int) hm->uri.len, hm->uri.ptr, path,
  2389. flags));
  2390. if (flags == 0) {
  2391. // Do nothing - let's caller decide
  2392. } else if ((flags & MG_FS_DIR) && hm->uri.len > 0 &&
  2393. hm->uri.ptr[hm->uri.len - 1] != '/') {
  2394. mg_printf(c,
  2395. "HTTP/1.1 301 Moved\r\n"
  2396. "Location: %.*s/\r\n"
  2397. "Content-Length: 0\r\n"
  2398. "\r\n",
  2399. (int) hm->uri.len, hm->uri.ptr);
  2400. c->is_resp = 0;
  2401. flags = -1;
  2402. } else if (flags & MG_FS_DIR) {
  2403. if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
  2404. (tmp = fs->st(path, NULL, NULL)) != 0) ||
  2405. (mg_snprintf(path + n, path_size - n, "/index.shtml") > 0 &&
  2406. (tmp = fs->st(path, NULL, NULL)) != 0))) {
  2407. flags = tmp;
  2408. } else if ((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX ".gz") >
  2409. 0 &&
  2410. (tmp = fs->st(path, NULL, NULL)) !=
  2411. 0)) { // check for gzipped index
  2412. flags = tmp;
  2413. path[n + 1 + strlen(MG_HTTP_INDEX)] =
  2414. '\0'; // Remove appended .gz in index file name
  2415. } else {
  2416. path[n] = '\0'; // Remove appended index file name
  2417. }
  2418. }
  2419. return flags;
  2420. }
  2421. static int uri_to_path(struct mg_connection *c, struct mg_http_message *hm,
  2422. const struct mg_http_serve_opts *opts, char *path,
  2423. size_t path_size) {
  2424. struct mg_fs *fs = opts->fs == NULL ? &mg_fs_posix : opts->fs;
  2425. struct mg_str k, v, s = mg_str(opts->root_dir), u = {0, 0}, p = {0, 0};
  2426. while (mg_commalist(&s, &k, &v)) {
  2427. if (v.len == 0) v = k, k = mg_str("/"), u = k, p = v;
  2428. if (hm->uri.len < k.len) continue;
  2429. if (mg_strcmp(k, mg_str_n(hm->uri.ptr, k.len)) != 0) continue;
  2430. u = k, p = v;
  2431. }
  2432. return uri_to_path2(c, hm, fs, u, p, path, path_size);
  2433. }
  2434. void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
  2435. const struct mg_http_serve_opts *opts) {
  2436. char path[MG_PATH_MAX];
  2437. const char *sp = opts->ssi_pattern;
  2438. int flags = uri_to_path(c, hm, opts, path, sizeof(path));
  2439. if (flags < 0) {
  2440. // Do nothing: the response has already been sent by uri_to_path()
  2441. } else if (flags & MG_FS_DIR) {
  2442. #if MG_ENABLE_DIRLIST
  2443. listdir(c, hm, opts, path);
  2444. #else
  2445. mg_http_reply(c, 403, "", "Forbidden\n");
  2446. #endif
  2447. } else if (flags && sp != NULL &&
  2448. mg_globmatch(sp, strlen(sp), path, strlen(path))) {
  2449. mg_http_serve_ssi(c, opts->root_dir, path);
  2450. } else {
  2451. mg_http_serve_file(c, hm, path, opts);
  2452. }
  2453. }
  2454. static bool mg_is_url_safe(int c) {
  2455. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') ||
  2456. (c >= 'A' && c <= 'Z') || c == '.' || c == '_' || c == '-' || c == '~';
  2457. }
  2458. size_t mg_url_encode(const char *s, size_t sl, char *buf, size_t len) {
  2459. size_t i, n = 0;
  2460. for (i = 0; i < sl; i++) {
  2461. int c = *(unsigned char *) &s[i];
  2462. if (n + 4 >= len) return 0;
  2463. if (mg_is_url_safe(c)) {
  2464. buf[n++] = s[i];
  2465. } else {
  2466. buf[n++] = '%';
  2467. mg_hex(&s[i], 1, &buf[n]);
  2468. n += 2;
  2469. }
  2470. }
  2471. if (len > 0 && n < len - 1) buf[n] = '\0'; // Null-terminate the destination
  2472. if (len > 0) buf[len - 1] = '\0'; // Always.
  2473. return n;
  2474. }
  2475. void mg_http_creds(struct mg_http_message *hm, char *user, size_t userlen,
  2476. char *pass, size_t passlen) {
  2477. struct mg_str *v = mg_http_get_header(hm, "Authorization");
  2478. user[0] = pass[0] = '\0';
  2479. if (v != NULL && v->len > 6 && memcmp(v->ptr, "Basic ", 6) == 0) {
  2480. char buf[256];
  2481. size_t n = mg_base64_decode(v->ptr + 6, v->len - 6, buf, sizeof(buf));
  2482. const char *p = (const char *) memchr(buf, ':', n > 0 ? n : 0);
  2483. if (p != NULL) {
  2484. mg_snprintf(user, userlen, "%.*s", p - buf, buf);
  2485. mg_snprintf(pass, passlen, "%.*s", n - (size_t) (p - buf) - 1, p + 1);
  2486. }
  2487. } else if (v != NULL && v->len > 7 && memcmp(v->ptr, "Bearer ", 7) == 0) {
  2488. mg_snprintf(pass, passlen, "%.*s", (int) v->len - 7, v->ptr + 7);
  2489. } else if ((v = mg_http_get_header(hm, "Cookie")) != NULL) {
  2490. struct mg_str t = mg_http_get_header_var(*v, mg_str_n("access_token", 12));
  2491. if (t.len > 0) mg_snprintf(pass, passlen, "%.*s", (int) t.len, t.ptr);
  2492. } else {
  2493. mg_http_get_var(&hm->query, "access_token", pass, passlen);
  2494. }
  2495. }
  2496. static struct mg_str stripquotes(struct mg_str s) {
  2497. return s.len > 1 && s.ptr[0] == '"' && s.ptr[s.len - 1] == '"'
  2498. ? mg_str_n(s.ptr + 1, s.len - 2)
  2499. : s;
  2500. }
  2501. struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v) {
  2502. size_t i;
  2503. for (i = 0; v.len > 0 && i + v.len + 2 < s.len; i++) {
  2504. if (s.ptr[i + v.len] == '=' && memcmp(&s.ptr[i], v.ptr, v.len) == 0) {
  2505. const char *p = &s.ptr[i + v.len + 1], *b = p, *x = &s.ptr[s.len];
  2506. int q = p < x && *p == '"' ? 1 : 0;
  2507. while (p < x &&
  2508. (q ? p == b || *p != '"' : *p != ';' && *p != ' ' && *p != ','))
  2509. p++;
  2510. // MG_INFO(("[%.*s] [%.*s] [%.*s]", (int) s.len, s.ptr, (int) v.len,
  2511. // v.ptr, (int) (p - b), b));
  2512. return stripquotes(mg_str_n(b, (size_t) (p - b + q)));
  2513. }
  2514. }
  2515. return mg_str_n(NULL, 0);
  2516. }
  2517. bool mg_http_match_uri(const struct mg_http_message *hm, const char *glob) {
  2518. return mg_match(hm->uri, mg_str(glob), NULL);
  2519. }
  2520. long mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
  2521. struct mg_fs *fs, const char *path, size_t max_size) {
  2522. char buf[20] = "0";
  2523. long res = 0, offset;
  2524. mg_http_get_var(&hm->query, "offset", buf, sizeof(buf));
  2525. offset = strtol(buf, NULL, 0);
  2526. if (hm->body.len == 0) {
  2527. mg_http_reply(c, 200, "", "%ld", res); // Nothing to write
  2528. } else {
  2529. struct mg_fd *fd;
  2530. size_t current_size = 0;
  2531. MG_DEBUG(("%s -> %d bytes @ %ld", path, (int) hm->body.len, offset));
  2532. if (offset == 0) fs->rm(path); // If offset if 0, truncate file
  2533. fs->st(path, &current_size, NULL);
  2534. if (offset < 0) {
  2535. mg_http_reply(c, 400, "", "offset required");
  2536. res = -1;
  2537. } else if (offset > 0 && current_size != (size_t) offset) {
  2538. mg_http_reply(c, 400, "", "%s: offset mismatch", path);
  2539. res = -2;
  2540. } else if ((size_t) offset + hm->body.len > max_size) {
  2541. mg_http_reply(c, 400, "", "%s: over max size of %lu", path,
  2542. (unsigned long) max_size);
  2543. res = -3;
  2544. } else if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
  2545. mg_http_reply(c, 400, "", "open(%s): %d", path, errno);
  2546. res = -4;
  2547. } else {
  2548. res = offset + (long) fs->wr(fd->fd, hm->body.ptr, hm->body.len);
  2549. mg_fs_close(fd);
  2550. mg_http_reply(c, 200, "", "%ld", res);
  2551. }
  2552. }
  2553. return res;
  2554. }
  2555. int mg_http_status(const struct mg_http_message *hm) {
  2556. return atoi(hm->uri.ptr);
  2557. }
  2558. static bool is_hex_digit(int c) {
  2559. return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') ||
  2560. (c >= 'A' && c <= 'F');
  2561. }
  2562. static int skip_chunk(const char *buf, int len, int *pl, int *dl) {
  2563. int i = 0, n = 0;
  2564. if (len < 3) return 0;
  2565. while (i < len && is_hex_digit(buf[i])) i++;
  2566. if (i > (int) sizeof(int) * 2) return -1; // Chunk length is too big
  2567. if (len < i + 1 || buf[i] != '\r' || buf[i + 1] != '\n') return -1; // Error
  2568. n = (int) mg_unhexn(buf, (size_t) i); // Decode chunk length
  2569. if (n < 0) return -1; // Error
  2570. if (n > len - i - 4) return 0; // Chunk not yet fully buffered
  2571. if (buf[i + n + 2] != '\r' || buf[i + n + 3] != '\n') return -1; // Error
  2572. *pl = i + 2, *dl = n;
  2573. return i + 2 + n + 2;
  2574. }
  2575. static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
  2576. if (ev == MG_EV_READ || ev == MG_EV_CLOSE) {
  2577. struct mg_http_message hm;
  2578. size_t ofs = 0; // Parsing offset
  2579. while (c->is_resp == 0 && ofs < c->recv.len) {
  2580. const char *buf = (char *) c->recv.buf + ofs;
  2581. int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
  2582. struct mg_str *te; // Transfer - encoding header
  2583. bool is_chunked = false;
  2584. if (n < 0) {
  2585. mg_error(c, "HTTP parse, %lu bytes", c->recv.len);
  2586. mg_hexdump(c->recv.buf, c->recv.len > 16 ? 16 : c->recv.len);
  2587. return;
  2588. }
  2589. if (n == 0) break; // Request is not buffered yet
  2590. if (ev == MG_EV_CLOSE) { // If client did not set Content-Length
  2591. hm.message.len = c->recv.len - ofs; // and closes now, deliver MSG
  2592. hm.body.len = hm.message.len - (size_t) (hm.body.ptr - hm.message.ptr);
  2593. }
  2594. if ((te = mg_http_get_header(&hm, "Transfer-Encoding")) != NULL) {
  2595. if (mg_vcasecmp(te, "chunked") == 0) {
  2596. is_chunked = true;
  2597. } else {
  2598. mg_error(c, "Invalid Transfer-Encoding"); // See #2460
  2599. return;
  2600. }
  2601. }
  2602. if (is_chunked) {
  2603. // For chunked data, strip off prefixes and suffixes from chunks
  2604. // and relocate them right after the headers, then report a message
  2605. char *s = (char *) c->recv.buf + ofs + n;
  2606. int o = 0, pl, dl, cl, len = (int) (c->recv.len - ofs - (size_t) n);
  2607. // Find zero-length chunk (the end of the body)
  2608. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0 && dl) o += cl;
  2609. if (cl == 0) break; // No zero-len chunk, buffer more data
  2610. if (cl < 0) {
  2611. mg_error(c, "Invalid chunk");
  2612. break;
  2613. }
  2614. // Zero chunk found. Second pass: strip + relocate
  2615. o = 0, hm.body.len = 0, hm.message.len = (size_t) n;
  2616. while ((cl = skip_chunk(s + o, len - o, &pl, &dl)) > 0) {
  2617. memmove(s + hm.body.len, s + o + pl, (size_t) dl);
  2618. o += cl, hm.body.len += (size_t) dl, hm.message.len += (size_t) dl;
  2619. if (dl == 0) break;
  2620. }
  2621. ofs += (size_t) (n + o);
  2622. } else { // Normal, non-chunked data
  2623. size_t len = c->recv.len - ofs - (size_t) n;
  2624. if (hm.body.len > len) break; // Buffer more data
  2625. ofs += (size_t) n + hm.body.len;
  2626. }
  2627. if (c->is_accepted) c->is_resp = 1; // Start generating response
  2628. mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp
  2629. }
  2630. if (ofs > 0) mg_iobuf_del(&c->recv, 0, ofs); // Delete processed data
  2631. }
  2632. (void) ev_data;
  2633. }
  2634. static void mg_hfn(struct mg_connection *c, int ev, void *ev_data) {
  2635. if (ev == MG_EV_HTTP_MSG) {
  2636. struct mg_http_message *hm = (struct mg_http_message *) ev_data;
  2637. if (mg_http_match_uri(hm, "/quit")) {
  2638. mg_http_reply(c, 200, "", "ok\n");
  2639. c->is_draining = 1;
  2640. c->data[0] = 'X';
  2641. } else if (mg_http_match_uri(hm, "/debug")) {
  2642. int level = (int) mg_json_get_long(hm->body, "$.level", MG_LL_DEBUG);
  2643. mg_log_set(level);
  2644. mg_http_reply(c, 200, "", "Debug level set to %d\n", level);
  2645. } else {
  2646. mg_http_reply(c, 200, "", "hi\n");
  2647. }
  2648. } else if (ev == MG_EV_CLOSE) {
  2649. if (c->data[0] == 'X') *(bool *) c->fn_data = true;
  2650. }
  2651. }
  2652. void mg_hello(const char *url) {
  2653. struct mg_mgr mgr;
  2654. bool done = false;
  2655. mg_mgr_init(&mgr);
  2656. if (mg_http_listen(&mgr, url, mg_hfn, &done) == NULL) done = true;
  2657. while (done == false) mg_mgr_poll(&mgr, 100);
  2658. mg_mgr_free(&mgr);
  2659. }
  2660. struct mg_connection *mg_http_connect(struct mg_mgr *mgr, const char *url,
  2661. mg_event_handler_t fn, void *fn_data) {
  2662. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  2663. if (c != NULL) c->pfn = http_cb;
  2664. return c;
  2665. }
  2666. struct mg_connection *mg_http_listen(struct mg_mgr *mgr, const char *url,
  2667. mg_event_handler_t fn, void *fn_data) {
  2668. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  2669. if (c != NULL) c->pfn = http_cb;
  2670. return c;
  2671. }
  2672. #ifdef MG_ENABLE_LINES
  2673. #line 1 "src/iobuf.c"
  2674. #endif
  2675. static size_t roundup(size_t size, size_t align) {
  2676. return align == 0 ? size : (size + align - 1) / align * align;
  2677. }
  2678. int mg_iobuf_resize(struct mg_iobuf *io, size_t new_size) {
  2679. int ok = 1;
  2680. new_size = roundup(new_size, io->align);
  2681. if (new_size == 0) {
  2682. mg_bzero(io->buf, io->size);
  2683. free(io->buf);
  2684. io->buf = NULL;
  2685. io->len = io->size = 0;
  2686. } else if (new_size != io->size) {
  2687. // NOTE(lsm): do not use realloc here. Use calloc/free only, to ease the
  2688. // porting to some obscure platforms like FreeRTOS
  2689. void *p = calloc(1, new_size);
  2690. if (p != NULL) {
  2691. size_t len = new_size < io->len ? new_size : io->len;
  2692. if (len > 0 && io->buf != NULL) memmove(p, io->buf, len);
  2693. mg_bzero(io->buf, io->size);
  2694. free(io->buf);
  2695. io->buf = (unsigned char *) p;
  2696. io->size = new_size;
  2697. } else {
  2698. ok = 0;
  2699. MG_ERROR(("%lld->%lld", (uint64_t) io->size, (uint64_t) new_size));
  2700. }
  2701. }
  2702. return ok;
  2703. }
  2704. int mg_iobuf_init(struct mg_iobuf *io, size_t size, size_t align) {
  2705. io->buf = NULL;
  2706. io->align = align;
  2707. io->size = io->len = 0;
  2708. return mg_iobuf_resize(io, size);
  2709. }
  2710. size_t mg_iobuf_add(struct mg_iobuf *io, size_t ofs, const void *buf,
  2711. size_t len) {
  2712. size_t new_size = roundup(io->len + len, io->align);
  2713. mg_iobuf_resize(io, new_size); // Attempt to resize
  2714. if (new_size != io->size) len = 0; // Resize failure, append nothing
  2715. if (ofs < io->len) memmove(io->buf + ofs + len, io->buf + ofs, io->len - ofs);
  2716. if (buf != NULL) memmove(io->buf + ofs, buf, len);
  2717. if (ofs > io->len) io->len += ofs - io->len;
  2718. io->len += len;
  2719. return len;
  2720. }
  2721. size_t mg_iobuf_del(struct mg_iobuf *io, size_t ofs, size_t len) {
  2722. if (ofs > io->len) ofs = io->len;
  2723. if (ofs + len > io->len) len = io->len - ofs;
  2724. if (io->buf) memmove(io->buf + ofs, io->buf + ofs + len, io->len - ofs - len);
  2725. if (io->buf) mg_bzero(io->buf + io->len - len, len);
  2726. io->len -= len;
  2727. return len;
  2728. }
  2729. void mg_iobuf_free(struct mg_iobuf *io) {
  2730. mg_iobuf_resize(io, 0);
  2731. }
  2732. #ifdef MG_ENABLE_LINES
  2733. #line 1 "src/json.c"
  2734. #endif
  2735. static const char *escapeseq(int esc) {
  2736. return esc ? "\b\f\n\r\t\\\"" : "bfnrt\\\"";
  2737. }
  2738. static char json_esc(int c, int esc) {
  2739. const char *p, *esc1 = escapeseq(esc), *esc2 = escapeseq(!esc);
  2740. for (p = esc1; *p != '\0'; p++) {
  2741. if (*p == c) return esc2[p - esc1];
  2742. }
  2743. return 0;
  2744. }
  2745. static int mg_pass_string(const char *s, int len) {
  2746. int i;
  2747. for (i = 0; i < len; i++) {
  2748. if (s[i] == '\\' && i + 1 < len && json_esc(s[i + 1], 1)) {
  2749. i++;
  2750. } else if (s[i] == '\0') {
  2751. return MG_JSON_INVALID;
  2752. } else if (s[i] == '"') {
  2753. return i;
  2754. }
  2755. }
  2756. return MG_JSON_INVALID;
  2757. }
  2758. static double mg_atod(const char *p, int len, int *numlen) {
  2759. double d = 0.0;
  2760. int i = 0, sign = 1;
  2761. // Sign
  2762. if (i < len && *p == '-') {
  2763. sign = -1, i++;
  2764. } else if (i < len && *p == '+') {
  2765. i++;
  2766. }
  2767. // Decimal
  2768. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  2769. d *= 10.0;
  2770. d += p[i] - '0';
  2771. }
  2772. d *= sign;
  2773. // Fractional
  2774. if (i < len && p[i] == '.') {
  2775. double frac = 0.0, base = 0.1;
  2776. i++;
  2777. for (; i < len && p[i] >= '0' && p[i] <= '9'; i++) {
  2778. frac += base * (p[i] - '0');
  2779. base /= 10.0;
  2780. }
  2781. d += frac * sign;
  2782. }
  2783. // Exponential
  2784. if (i < len && (p[i] == 'e' || p[i] == 'E')) {
  2785. int j, exp = 0, minus = 0;
  2786. i++;
  2787. if (i < len && p[i] == '-') minus = 1, i++;
  2788. if (i < len && p[i] == '+') i++;
  2789. while (i < len && p[i] >= '0' && p[i] <= '9' && exp < 308)
  2790. exp = exp * 10 + (p[i++] - '0');
  2791. if (minus) exp = -exp;
  2792. for (j = 0; j < exp; j++) d *= 10.0;
  2793. for (j = 0; j < -exp; j++) d /= 10.0;
  2794. }
  2795. if (numlen != NULL) *numlen = i;
  2796. return d;
  2797. }
  2798. // Iterate over object or array elements
  2799. size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key,
  2800. struct mg_str *val) {
  2801. if (ofs >= obj.len) {
  2802. ofs = 0; // Out of boundaries, stop scanning
  2803. } else if (obj.len < 2 || (*obj.ptr != '{' && *obj.ptr != '[')) {
  2804. ofs = 0; // Not an array or object, stop
  2805. } else {
  2806. struct mg_str sub = mg_str_n(obj.ptr + ofs, obj.len - ofs);
  2807. if (ofs == 0) ofs++, sub.ptr++, sub.len--;
  2808. if (*obj.ptr == '[') { // Iterate over an array
  2809. int n = 0, o = mg_json_get(sub, "$", &n);
  2810. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2811. ofs = 0; // Error parsing key, stop scanning
  2812. } else {
  2813. if (key) *key = mg_str_n(NULL, 0);
  2814. if (val) *val = mg_str_n(sub.ptr + o, (size_t) n);
  2815. ofs = (size_t) (&sub.ptr[o + n] - obj.ptr);
  2816. }
  2817. } else { // Iterate over an object
  2818. int n = 0, o = mg_json_get(sub, "$", &n);
  2819. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2820. ofs = 0; // Error parsing key, stop scanning
  2821. } else {
  2822. if (key) *key = mg_str_n(sub.ptr + o, (size_t) n);
  2823. sub.ptr += o + n, sub.len -= (size_t) (o + n);
  2824. while (sub.len > 0 && *sub.ptr != ':') sub.len--, sub.ptr++;
  2825. if (sub.len > 0 && *sub.ptr == ':') sub.len--, sub.ptr++;
  2826. n = 0, o = mg_json_get(sub, "$", &n);
  2827. if (n < 0 || o < 0 || (size_t) (o + n) > sub.len) {
  2828. ofs = 0; // Error parsing value, stop scanning
  2829. } else {
  2830. if (val) *val = mg_str_n(sub.ptr + o, (size_t) n);
  2831. ofs = (size_t) (&sub.ptr[o + n] - obj.ptr);
  2832. }
  2833. }
  2834. }
  2835. //MG_INFO(("SUB ofs %u %.*s", ofs, sub.len, sub.ptr));
  2836. while (ofs && ofs < obj.len &&
  2837. (obj.ptr[ofs] == ' ' || obj.ptr[ofs] == '\t' ||
  2838. obj.ptr[ofs] == '\n' || obj.ptr[ofs] == '\r')) {
  2839. ofs++;
  2840. }
  2841. if (ofs && ofs < obj.len && obj.ptr[ofs] == ',') ofs++;
  2842. if (ofs > obj.len) ofs = 0;
  2843. }
  2844. return ofs;
  2845. }
  2846. int mg_json_get(struct mg_str json, const char *path, int *toklen) {
  2847. const char *s = json.ptr;
  2848. int len = (int) json.len;
  2849. enum { S_VALUE, S_KEY, S_COLON, S_COMMA_OR_EOO } expecting = S_VALUE;
  2850. unsigned char nesting[MG_JSON_MAX_DEPTH];
  2851. int i = 0; // Current offset in `s`
  2852. int j = 0; // Offset in `s` we're looking for (return value)
  2853. int depth = 0; // Current depth (nesting level)
  2854. int ed = 0; // Expected depth
  2855. int pos = 1; // Current position in `path`
  2856. int ci = -1, ei = -1; // Current and expected index in array
  2857. if (toklen) *toklen = 0;
  2858. if (path[0] != '$') return MG_JSON_INVALID;
  2859. #define MG_CHECKRET(x) \
  2860. do { \
  2861. if (depth == ed && path[pos] == '\0' && ci == ei) { \
  2862. if (toklen) *toklen = i - j + 1; \
  2863. return j; \
  2864. } \
  2865. } while (0)
  2866. // In the ascii table, the distance between `[` and `]` is 2.
  2867. // Ditto for `{` and `}`. Hence +2 in the code below.
  2868. #define MG_EOO(x) \
  2869. do { \
  2870. if (depth == ed && ci != ei) return MG_JSON_NOT_FOUND; \
  2871. if (c != nesting[depth - 1] + 2) return MG_JSON_INVALID; \
  2872. depth--; \
  2873. MG_CHECKRET(x); \
  2874. } while (0)
  2875. for (i = 0; i < len; i++) {
  2876. unsigned char c = ((unsigned char *) s)[i];
  2877. if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue;
  2878. switch (expecting) {
  2879. case S_VALUE:
  2880. // p("V %s [%.*s] %d %d %d %d\n", path, pos, path, depth, ed, ci, ei);
  2881. if (depth == ed) j = i;
  2882. if (c == '{') {
  2883. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  2884. if (depth == ed && path[pos] == '.' && ci == ei) {
  2885. // If we start the object, reset array indices
  2886. ed++, pos++, ci = ei = -1;
  2887. }
  2888. nesting[depth++] = c;
  2889. expecting = S_KEY;
  2890. break;
  2891. } else if (c == '[') {
  2892. if (depth >= (int) sizeof(nesting)) return MG_JSON_TOO_DEEP;
  2893. if (depth == ed && path[pos] == '[' && ei == ci) {
  2894. ed++, pos++, ci = 0;
  2895. for (ei = 0; path[pos] != ']' && path[pos] != '\0'; pos++) {
  2896. ei *= 10;
  2897. ei += path[pos] - '0';
  2898. }
  2899. if (path[pos] != 0) pos++;
  2900. }
  2901. nesting[depth++] = c;
  2902. break;
  2903. } else if (c == ']' && depth > 0) { // Empty array
  2904. MG_EOO(']');
  2905. } else if (c == 't' && i + 3 < len && memcmp(&s[i], "true", 4) == 0) {
  2906. i += 3;
  2907. } else if (c == 'n' && i + 3 < len && memcmp(&s[i], "null", 4) == 0) {
  2908. i += 3;
  2909. } else if (c == 'f' && i + 4 < len && memcmp(&s[i], "false", 5) == 0) {
  2910. i += 4;
  2911. } else if (c == '-' || ((c >= '0' && c <= '9'))) {
  2912. int numlen = 0;
  2913. mg_atod(&s[i], len - i, &numlen);
  2914. i += numlen - 1;
  2915. } else if (c == '"') {
  2916. int n = mg_pass_string(&s[i + 1], len - i - 1);
  2917. if (n < 0) return n;
  2918. i += n + 1;
  2919. } else {
  2920. return MG_JSON_INVALID;
  2921. }
  2922. MG_CHECKRET('V');
  2923. if (depth == ed && ei >= 0) ci++;
  2924. expecting = S_COMMA_OR_EOO;
  2925. break;
  2926. case S_KEY:
  2927. if (c == '"') {
  2928. int n = mg_pass_string(&s[i + 1], len - i - 1);
  2929. if (n < 0) return n;
  2930. if (i + 1 + n >= len) return MG_JSON_NOT_FOUND;
  2931. if (depth < ed) return MG_JSON_NOT_FOUND;
  2932. if (depth == ed && path[pos - 1] != '.') return MG_JSON_NOT_FOUND;
  2933. // printf("K %s [%.*s] [%.*s] %d %d %d %d %d\n", path, pos, path, n,
  2934. // &s[i + 1], n, depth, ed, ci, ei);
  2935. // NOTE(cpq): in the check sequence below is important.
  2936. // strncmp() must go first: it fails fast if the remaining length
  2937. // of the path is smaller than `n`.
  2938. if (depth == ed && path[pos - 1] == '.' &&
  2939. strncmp(&s[i + 1], &path[pos], (size_t) n) == 0 &&
  2940. (path[pos + n] == '\0' || path[pos + n] == '.' ||
  2941. path[pos + n] == '[')) {
  2942. pos += n;
  2943. }
  2944. i += n + 1;
  2945. expecting = S_COLON;
  2946. } else if (c == '}') { // Empty object
  2947. MG_EOO('}');
  2948. expecting = S_COMMA_OR_EOO;
  2949. if (depth == ed && ei >= 0) ci++;
  2950. } else {
  2951. return MG_JSON_INVALID;
  2952. }
  2953. break;
  2954. case S_COLON:
  2955. if (c == ':') {
  2956. expecting = S_VALUE;
  2957. } else {
  2958. return MG_JSON_INVALID;
  2959. }
  2960. break;
  2961. case S_COMMA_OR_EOO:
  2962. if (depth <= 0) {
  2963. return MG_JSON_INVALID;
  2964. } else if (c == ',') {
  2965. expecting = (nesting[depth - 1] == '{') ? S_KEY : S_VALUE;
  2966. } else if (c == ']' || c == '}') {
  2967. if (depth == ed && c == '}' && path[pos - 1] == '.')
  2968. return MG_JSON_NOT_FOUND;
  2969. if (depth == ed && c == ']' && path[pos - 1] == ',')
  2970. return MG_JSON_NOT_FOUND;
  2971. MG_EOO('O');
  2972. if (depth == ed && ei >= 0) ci++;
  2973. } else {
  2974. return MG_JSON_INVALID;
  2975. }
  2976. break;
  2977. }
  2978. }
  2979. return MG_JSON_NOT_FOUND;
  2980. }
  2981. bool mg_json_get_num(struct mg_str json, const char *path, double *v) {
  2982. int n, toklen, found = 0;
  2983. if ((n = mg_json_get(json, path, &toklen)) >= 0 &&
  2984. (json.ptr[n] == '-' || (json.ptr[n] >= '0' && json.ptr[n] <= '9'))) {
  2985. if (v != NULL) *v = mg_atod(json.ptr + n, toklen, NULL);
  2986. found = 1;
  2987. }
  2988. return found;
  2989. }
  2990. bool mg_json_get_bool(struct mg_str json, const char *path, bool *v) {
  2991. int found = 0, off = mg_json_get(json, path, NULL);
  2992. if (off >= 0 && (json.ptr[off] == 't' || json.ptr[off] == 'f')) {
  2993. if (v != NULL) *v = json.ptr[off] == 't';
  2994. found = 1;
  2995. }
  2996. return found;
  2997. }
  2998. bool mg_json_unescape(struct mg_str s, char *to, size_t n) {
  2999. size_t i, j;
  3000. for (i = 0, j = 0; i < s.len && j < n; i++, j++) {
  3001. if (s.ptr[i] == '\\' && i + 5 < s.len && s.ptr[i + 1] == 'u') {
  3002. // \uXXXX escape. We could process a simple one-byte chars
  3003. // \u00xx from the ASCII range. More complex chars would require
  3004. // dragging in a UTF8 library, which is too much for us
  3005. if (s.ptr[i + 2] != '0' || s.ptr[i + 3] != '0') return false; // Give up
  3006. ((unsigned char *) to)[j] = (unsigned char) mg_unhexn(s.ptr + i + 4, 2);
  3007. i += 5;
  3008. } else if (s.ptr[i] == '\\' && i + 1 < s.len) {
  3009. char c = json_esc(s.ptr[i + 1], 0);
  3010. if (c == 0) return false;
  3011. to[j] = c;
  3012. i++;
  3013. } else {
  3014. to[j] = s.ptr[i];
  3015. }
  3016. }
  3017. if (j >= n) return false;
  3018. if (n > 0) to[j] = '\0';
  3019. return true;
  3020. }
  3021. char *mg_json_get_str(struct mg_str json, const char *path) {
  3022. char *result = NULL;
  3023. int len = 0, off = mg_json_get(json, path, &len);
  3024. if (off >= 0 && len > 1 && json.ptr[off] == '"') {
  3025. if ((result = (char *) calloc(1, (size_t) len)) != NULL &&
  3026. !mg_json_unescape(mg_str_n(json.ptr + off + 1, (size_t) (len - 2)),
  3027. result, (size_t) len)) {
  3028. free(result);
  3029. result = NULL;
  3030. }
  3031. }
  3032. return result;
  3033. }
  3034. char *mg_json_get_b64(struct mg_str json, const char *path, int *slen) {
  3035. char *result = NULL;
  3036. int len = 0, off = mg_json_get(json, path, &len);
  3037. if (off >= 0 && json.ptr[off] == '"' && len > 1 &&
  3038. (result = (char *) calloc(1, (size_t) len)) != NULL) {
  3039. size_t k = mg_base64_decode(json.ptr + off + 1, (size_t) (len - 2), result,
  3040. (size_t) len);
  3041. if (slen != NULL) *slen = (int) k;
  3042. }
  3043. return result;
  3044. }
  3045. char *mg_json_get_hex(struct mg_str json, const char *path, int *slen) {
  3046. char *result = NULL;
  3047. int len = 0, off = mg_json_get(json, path, &len);
  3048. if (off >= 0 && json.ptr[off] == '"' && len > 1 &&
  3049. (result = (char *) calloc(1, (size_t) len / 2)) != NULL) {
  3050. mg_unhex(json.ptr + off + 1, (size_t) (len - 2), (uint8_t *) result);
  3051. result[len / 2 - 1] = '\0';
  3052. if (slen != NULL) *slen = len / 2 - 1;
  3053. }
  3054. return result;
  3055. }
  3056. long mg_json_get_long(struct mg_str json, const char *path, long dflt) {
  3057. double dv;
  3058. long result = dflt;
  3059. if (mg_json_get_num(json, path, &dv)) result = (long) dv;
  3060. return result;
  3061. }
  3062. #ifdef MG_ENABLE_LINES
  3063. #line 1 "src/log.c"
  3064. #endif
  3065. int mg_log_level = MG_LL_INFO;
  3066. static mg_pfn_t s_log_func = mg_pfn_stdout;
  3067. static void *s_log_func_param = NULL;
  3068. void mg_log_set_fn(mg_pfn_t fn, void *param) {
  3069. s_log_func = fn;
  3070. s_log_func_param = param;
  3071. }
  3072. static void logc(unsigned char c) {
  3073. s_log_func((char) c, s_log_func_param);
  3074. }
  3075. static void logs(const char *buf, size_t len) {
  3076. size_t i;
  3077. for (i = 0; i < len; i++) logc(((unsigned char *) buf)[i]);
  3078. }
  3079. #if MG_ENABLE_CUSTOM_LOG
  3080. // Let user define their own mg_log_prefix() and mg_log()
  3081. #else
  3082. void mg_log_prefix(int level, const char *file, int line, const char *fname) {
  3083. const char *p = strrchr(file, '/');
  3084. char buf[41];
  3085. size_t n;
  3086. if (p == NULL) p = strrchr(file, '\\');
  3087. n = mg_snprintf(buf, sizeof(buf), "%-6llx %d %s:%d:%s", mg_millis(), level,
  3088. p == NULL ? file : p + 1, line, fname);
  3089. if (n > sizeof(buf) - 2) n = sizeof(buf) - 2;
  3090. while (n < sizeof(buf)) buf[n++] = ' ';
  3091. logs(buf, n - 1);
  3092. }
  3093. void mg_log(const char *fmt, ...) {
  3094. va_list ap;
  3095. va_start(ap, fmt);
  3096. mg_vxprintf(s_log_func, s_log_func_param, fmt, &ap);
  3097. va_end(ap);
  3098. logs("\r\n", 2);
  3099. }
  3100. #endif
  3101. static unsigned char nibble(unsigned c) {
  3102. return (unsigned char) (c < 10 ? c + '0' : c + 'W');
  3103. }
  3104. #define ISPRINT(x) ((x) >= ' ' && (x) <= '~')
  3105. void mg_hexdump(const void *buf, size_t len) {
  3106. const unsigned char *p = (const unsigned char *) buf;
  3107. unsigned char ascii[16], alen = 0;
  3108. size_t i;
  3109. for (i = 0; i < len; i++) {
  3110. if ((i % 16) == 0) {
  3111. // Print buffered ascii chars
  3112. if (i > 0) logs(" ", 2), logs((char *) ascii, 16), logc('\n'), alen = 0;
  3113. // Print hex address, then \t
  3114. logc(nibble((i >> 12) & 15)), logc(nibble((i >> 8) & 15)),
  3115. logc(nibble((i >> 4) & 15)), logc('0'), logs(" ", 3);
  3116. }
  3117. logc(nibble(p[i] >> 4)), logc(nibble(p[i] & 15)); // Two nibbles, e.g. c5
  3118. logc(' '); // Space after hex number
  3119. ascii[alen++] = ISPRINT(p[i]) ? p[i] : '.'; // Add to the ascii buf
  3120. }
  3121. while (alen < 16) logs(" ", 3), ascii[alen++] = ' ';
  3122. logs(" ", 2), logs((char *) ascii, 16), logc('\n');
  3123. }
  3124. #ifdef MG_ENABLE_LINES
  3125. #line 1 "src/md5.c"
  3126. #endif
  3127. // This code implements the MD5 message-digest algorithm.
  3128. // The algorithm is due to Ron Rivest. This code was
  3129. // written by Colin Plumb in 1993, no copyright is claimed.
  3130. // This code is in the public domain; do with it what you wish.
  3131. //
  3132. // Equivalent code is available from RSA Data Security, Inc.
  3133. // This code has been tested against that, and is equivalent,
  3134. // except that you don't need to include two pages of legalese
  3135. // with every copy.
  3136. //
  3137. // To compute the message digest of a chunk of bytes, declare an
  3138. // MD5Context structure, pass it to MD5Init, call MD5Update as
  3139. // needed on buffers full of bytes, and then call MD5Final, which
  3140. // will fill a supplied 16-byte array with the digest.
  3141. #if defined(MG_ENABLE_MD5) && MG_ENABLE_MD5
  3142. static void mg_byte_reverse(unsigned char *buf, unsigned longs) {
  3143. if (MG_BIG_ENDIAN) {
  3144. do {
  3145. uint32_t t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  3146. ((unsigned) buf[1] << 8 | buf[0]);
  3147. *(uint32_t *) buf = t;
  3148. buf += 4;
  3149. } while (--longs);
  3150. } else {
  3151. (void) buf, (void) longs; // Little endian. Do nothing
  3152. }
  3153. }
  3154. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  3155. #define F2(x, y, z) F1(z, x, y)
  3156. #define F3(x, y, z) (x ^ y ^ z)
  3157. #define F4(x, y, z) (y ^ (x | ~z))
  3158. #define MD5STEP(f, w, x, y, z, data, s) \
  3159. (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
  3160. /*
  3161. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  3162. * initialization constants.
  3163. */
  3164. void mg_md5_init(mg_md5_ctx *ctx) {
  3165. ctx->buf[0] = 0x67452301;
  3166. ctx->buf[1] = 0xefcdab89;
  3167. ctx->buf[2] = 0x98badcfe;
  3168. ctx->buf[3] = 0x10325476;
  3169. ctx->bits[0] = 0;
  3170. ctx->bits[1] = 0;
  3171. }
  3172. static void mg_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
  3173. uint32_t a, b, c, d;
  3174. a = buf[0];
  3175. b = buf[1];
  3176. c = buf[2];
  3177. d = buf[3];
  3178. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  3179. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  3180. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  3181. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  3182. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  3183. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  3184. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  3185. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  3186. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  3187. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  3188. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  3189. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  3190. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  3191. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  3192. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  3193. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  3194. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  3195. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  3196. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  3197. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  3198. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  3199. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  3200. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  3201. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  3202. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  3203. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  3204. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  3205. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  3206. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  3207. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  3208. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  3209. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  3210. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  3211. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  3212. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  3213. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  3214. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  3215. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  3216. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  3217. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  3218. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  3219. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  3220. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  3221. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  3222. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  3223. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  3224. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  3225. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  3226. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  3227. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  3228. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  3229. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  3230. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  3231. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  3232. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  3233. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  3234. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  3235. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  3236. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  3237. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  3238. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  3239. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  3240. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  3241. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  3242. buf[0] += a;
  3243. buf[1] += b;
  3244. buf[2] += c;
  3245. buf[3] += d;
  3246. }
  3247. void mg_md5_update(mg_md5_ctx *ctx, const unsigned char *buf, size_t len) {
  3248. uint32_t t;
  3249. t = ctx->bits[0];
  3250. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
  3251. ctx->bits[1] += (uint32_t) len >> 29;
  3252. t = (t >> 3) & 0x3f;
  3253. if (t) {
  3254. unsigned char *p = (unsigned char *) ctx->in + t;
  3255. t = 64 - t;
  3256. if (len < t) {
  3257. memcpy(p, buf, len);
  3258. return;
  3259. }
  3260. memcpy(p, buf, t);
  3261. mg_byte_reverse(ctx->in, 16);
  3262. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3263. buf += t;
  3264. len -= t;
  3265. }
  3266. while (len >= 64) {
  3267. memcpy(ctx->in, buf, 64);
  3268. mg_byte_reverse(ctx->in, 16);
  3269. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3270. buf += 64;
  3271. len -= 64;
  3272. }
  3273. memcpy(ctx->in, buf, len);
  3274. }
  3275. void mg_md5_final(mg_md5_ctx *ctx, unsigned char digest[16]) {
  3276. unsigned count;
  3277. unsigned char *p;
  3278. uint32_t *a;
  3279. count = (ctx->bits[0] >> 3) & 0x3F;
  3280. p = ctx->in + count;
  3281. *p++ = 0x80;
  3282. count = 64 - 1 - count;
  3283. if (count < 8) {
  3284. memset(p, 0, count);
  3285. mg_byte_reverse(ctx->in, 16);
  3286. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3287. memset(ctx->in, 0, 56);
  3288. } else {
  3289. memset(p, 0, count - 8);
  3290. }
  3291. mg_byte_reverse(ctx->in, 14);
  3292. a = (uint32_t *) ctx->in;
  3293. a[14] = ctx->bits[0];
  3294. a[15] = ctx->bits[1];
  3295. mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
  3296. mg_byte_reverse((unsigned char *) ctx->buf, 4);
  3297. memcpy(digest, ctx->buf, 16);
  3298. memset((char *) ctx, 0, sizeof(*ctx));
  3299. }
  3300. #endif
  3301. #ifdef MG_ENABLE_LINES
  3302. #line 1 "src/mqtt.c"
  3303. #endif
  3304. #define MQTT_CLEAN_SESSION 0x02
  3305. #define MQTT_HAS_WILL 0x04
  3306. #define MQTT_WILL_RETAIN 0x20
  3307. #define MQTT_HAS_PASSWORD 0x40
  3308. #define MQTT_HAS_USER_NAME 0x80
  3309. struct mg_mqtt_pmap {
  3310. uint8_t id;
  3311. uint8_t type;
  3312. };
  3313. static const struct mg_mqtt_pmap s_prop_map[] = {
  3314. {MQTT_PROP_PAYLOAD_FORMAT_INDICATOR, MQTT_PROP_TYPE_BYTE},
  3315. {MQTT_PROP_MESSAGE_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3316. {MQTT_PROP_CONTENT_TYPE, MQTT_PROP_TYPE_STRING},
  3317. {MQTT_PROP_RESPONSE_TOPIC, MQTT_PROP_TYPE_STRING},
  3318. {MQTT_PROP_CORRELATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3319. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER, MQTT_PROP_TYPE_VARIABLE_INT},
  3320. {MQTT_PROP_SESSION_EXPIRY_INTERVAL, MQTT_PROP_TYPE_INT},
  3321. {MQTT_PROP_ASSIGNED_CLIENT_IDENTIFIER, MQTT_PROP_TYPE_STRING},
  3322. {MQTT_PROP_SERVER_KEEP_ALIVE, MQTT_PROP_TYPE_SHORT},
  3323. {MQTT_PROP_AUTHENTICATION_METHOD, MQTT_PROP_TYPE_STRING},
  3324. {MQTT_PROP_AUTHENTICATION_DATA, MQTT_PROP_TYPE_BINARY_DATA},
  3325. {MQTT_PROP_REQUEST_PROBLEM_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3326. {MQTT_PROP_WILL_DELAY_INTERVAL, MQTT_PROP_TYPE_INT},
  3327. {MQTT_PROP_REQUEST_RESPONSE_INFORMATION, MQTT_PROP_TYPE_BYTE},
  3328. {MQTT_PROP_RESPONSE_INFORMATION, MQTT_PROP_TYPE_STRING},
  3329. {MQTT_PROP_SERVER_REFERENCE, MQTT_PROP_TYPE_STRING},
  3330. {MQTT_PROP_REASON_STRING, MQTT_PROP_TYPE_STRING},
  3331. {MQTT_PROP_RECEIVE_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3332. {MQTT_PROP_TOPIC_ALIAS_MAXIMUM, MQTT_PROP_TYPE_SHORT},
  3333. {MQTT_PROP_TOPIC_ALIAS, MQTT_PROP_TYPE_SHORT},
  3334. {MQTT_PROP_MAXIMUM_QOS, MQTT_PROP_TYPE_BYTE},
  3335. {MQTT_PROP_RETAIN_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3336. {MQTT_PROP_USER_PROPERTY, MQTT_PROP_TYPE_STRING_PAIR},
  3337. {MQTT_PROP_MAXIMUM_PACKET_SIZE, MQTT_PROP_TYPE_INT},
  3338. {MQTT_PROP_WILDCARD_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3339. {MQTT_PROP_SUBSCRIPTION_IDENTIFIER_AVAILABLE, MQTT_PROP_TYPE_BYTE},
  3340. {MQTT_PROP_SHARED_SUBSCRIPTION_AVAILABLE, MQTT_PROP_TYPE_BYTE}};
  3341. void mg_mqtt_send_header(struct mg_connection *c, uint8_t cmd, uint8_t flags,
  3342. uint32_t len) {
  3343. uint8_t buf[1 + sizeof(len)], *vlen = &buf[1];
  3344. buf[0] = (uint8_t) ((cmd << 4) | flags);
  3345. do {
  3346. *vlen = len % 0x80;
  3347. len /= 0x80;
  3348. if (len > 0) *vlen |= 0x80;
  3349. vlen++;
  3350. } while (len > 0 && vlen < &buf[sizeof(buf)]);
  3351. mg_send(c, buf, (size_t) (vlen - buf));
  3352. }
  3353. static void mg_send_u16(struct mg_connection *c, uint16_t value) {
  3354. mg_send(c, &value, sizeof(value));
  3355. }
  3356. static void mg_send_u32(struct mg_connection *c, uint32_t value) {
  3357. mg_send(c, &value, sizeof(value));
  3358. }
  3359. static uint8_t varint_size(size_t length) {
  3360. uint8_t bytes_needed = 0;
  3361. do {
  3362. bytes_needed++;
  3363. length /= 0x80;
  3364. } while (length > 0);
  3365. return bytes_needed;
  3366. }
  3367. static size_t encode_varint(uint8_t *buf, size_t value) {
  3368. size_t len = 0;
  3369. do {
  3370. uint8_t byte = (uint8_t) (value % 128);
  3371. value /= 128;
  3372. if (value > 0) byte |= 0x80;
  3373. buf[len++] = byte;
  3374. } while (value > 0);
  3375. return len;
  3376. }
  3377. static size_t decode_varint(const uint8_t *buf, size_t len, size_t *value) {
  3378. size_t multiplier = 1, offset;
  3379. *value = 0;
  3380. for (offset = 0; offset < 4 && offset < len; offset++) {
  3381. uint8_t encoded_byte = buf[offset];
  3382. *value += (encoded_byte & 0x7f) * multiplier;
  3383. multiplier *= 128;
  3384. if ((encoded_byte & 0x80) == 0) return offset + 1;
  3385. }
  3386. return 0;
  3387. }
  3388. static int mqtt_prop_type_by_id(uint8_t prop_id) {
  3389. size_t i, num_properties = sizeof(s_prop_map) / sizeof(s_prop_map[0]);
  3390. for (i = 0; i < num_properties; ++i) {
  3391. if (s_prop_map[i].id == prop_id) return s_prop_map[i].type;
  3392. }
  3393. return -1; // Property ID not found
  3394. }
  3395. // Returns the size of the properties section, without the
  3396. // size of the content's length
  3397. static size_t get_properties_length(struct mg_mqtt_prop *props, size_t count) {
  3398. size_t i, size = 0;
  3399. for (i = 0; i < count; i++) {
  3400. size++; // identifier
  3401. switch (mqtt_prop_type_by_id(props[i].id)) {
  3402. case MQTT_PROP_TYPE_STRING_PAIR:
  3403. size += (uint32_t) (props[i].val.len + props[i].key.len +
  3404. 2 * sizeof(uint16_t));
  3405. break;
  3406. case MQTT_PROP_TYPE_STRING:
  3407. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3408. break;
  3409. case MQTT_PROP_TYPE_BINARY_DATA:
  3410. size += (uint32_t) (props[i].val.len + sizeof(uint16_t));
  3411. break;
  3412. case MQTT_PROP_TYPE_VARIABLE_INT:
  3413. size += varint_size((uint32_t) props[i].iv);
  3414. break;
  3415. case MQTT_PROP_TYPE_INT:
  3416. size += (uint32_t) sizeof(uint32_t);
  3417. break;
  3418. case MQTT_PROP_TYPE_SHORT:
  3419. size += (uint32_t) sizeof(uint16_t);
  3420. break;
  3421. case MQTT_PROP_TYPE_BYTE:
  3422. size += (uint32_t) sizeof(uint8_t);
  3423. break;
  3424. default:
  3425. return size; // cannot parse further down
  3426. }
  3427. }
  3428. return size;
  3429. }
  3430. // returns the entire size of the properties section, including the
  3431. // size of the variable length of the content
  3432. static size_t get_props_size(struct mg_mqtt_prop *props, size_t count) {
  3433. size_t size = get_properties_length(props, count);
  3434. size += varint_size(size);
  3435. return size;
  3436. }
  3437. static void mg_send_mqtt_properties(struct mg_connection *c,
  3438. struct mg_mqtt_prop *props, size_t nprops) {
  3439. size_t total_size = get_properties_length(props, nprops);
  3440. uint8_t buf_v[4] = {0, 0, 0, 0};
  3441. uint8_t buf[4] = {0, 0, 0, 0};
  3442. size_t i, len = encode_varint(buf, total_size);
  3443. mg_send(c, buf, (size_t) len);
  3444. for (i = 0; i < nprops; i++) {
  3445. mg_send(c, &props[i].id, sizeof(props[i].id));
  3446. switch (mqtt_prop_type_by_id(props[i].id)) {
  3447. case MQTT_PROP_TYPE_STRING_PAIR:
  3448. mg_send_u16(c, mg_htons((uint16_t) props[i].key.len));
  3449. mg_send(c, props[i].key.ptr, props[i].key.len);
  3450. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3451. mg_send(c, props[i].val.ptr, props[i].val.len);
  3452. break;
  3453. case MQTT_PROP_TYPE_BYTE:
  3454. mg_send(c, &props[i].iv, sizeof(uint8_t));
  3455. break;
  3456. case MQTT_PROP_TYPE_SHORT:
  3457. mg_send_u16(c, mg_htons((uint16_t) props[i].iv));
  3458. break;
  3459. case MQTT_PROP_TYPE_INT:
  3460. mg_send_u32(c, mg_htonl((uint32_t) props[i].iv));
  3461. break;
  3462. case MQTT_PROP_TYPE_STRING:
  3463. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3464. mg_send(c, props[i].val.ptr, props[i].val.len);
  3465. break;
  3466. case MQTT_PROP_TYPE_BINARY_DATA:
  3467. mg_send_u16(c, mg_htons((uint16_t) props[i].val.len));
  3468. mg_send(c, props[i].val.ptr, props[i].val.len);
  3469. break;
  3470. case MQTT_PROP_TYPE_VARIABLE_INT:
  3471. len = encode_varint(buf_v, props[i].iv);
  3472. mg_send(c, buf_v, (size_t) len);
  3473. break;
  3474. }
  3475. }
  3476. }
  3477. size_t mg_mqtt_next_prop(struct mg_mqtt_message *msg, struct mg_mqtt_prop *prop,
  3478. size_t ofs) {
  3479. uint8_t *i = (uint8_t *) msg->dgram.ptr + msg->props_start + ofs;
  3480. uint8_t *end = (uint8_t *) msg->dgram.ptr + msg->dgram.len;
  3481. size_t new_pos = ofs, len;
  3482. prop->id = i[0];
  3483. if (ofs >= msg->dgram.len || ofs >= msg->props_start + msg->props_size)
  3484. return 0;
  3485. i++, new_pos++;
  3486. switch (mqtt_prop_type_by_id(prop->id)) {
  3487. case MQTT_PROP_TYPE_STRING_PAIR:
  3488. prop->key.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3489. prop->key.ptr = (char *) i + 2;
  3490. i += 2 + prop->key.len;
  3491. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3492. prop->val.ptr = (char *) i + 2;
  3493. new_pos += 2 * sizeof(uint16_t) + prop->val.len + prop->key.len;
  3494. break;
  3495. case MQTT_PROP_TYPE_BYTE:
  3496. prop->iv = (uint8_t) i[0];
  3497. new_pos++;
  3498. break;
  3499. case MQTT_PROP_TYPE_SHORT:
  3500. prop->iv = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3501. new_pos += sizeof(uint16_t);
  3502. break;
  3503. case MQTT_PROP_TYPE_INT:
  3504. prop->iv = ((uint32_t) i[0] << 24) | ((uint32_t) i[1] << 16) |
  3505. ((uint32_t) i[2] << 8) | i[3];
  3506. new_pos += sizeof(uint32_t);
  3507. break;
  3508. case MQTT_PROP_TYPE_STRING:
  3509. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3510. prop->val.ptr = (char *) i + 2;
  3511. new_pos += 2 + prop->val.len;
  3512. break;
  3513. case MQTT_PROP_TYPE_BINARY_DATA:
  3514. prop->val.len = (uint16_t) ((((uint16_t) i[0]) << 8) | i[1]);
  3515. prop->val.ptr = (char *) i + 2;
  3516. new_pos += 2 + prop->val.len;
  3517. break;
  3518. case MQTT_PROP_TYPE_VARIABLE_INT:
  3519. len = decode_varint(i, (size_t) (end - i), (size_t *) &prop->iv);
  3520. new_pos = (!len) ? 0 : new_pos + len;
  3521. break;
  3522. default:
  3523. new_pos = 0;
  3524. }
  3525. return new_pos;
  3526. }
  3527. void mg_mqtt_login(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3528. char rnd[10], client_id[21];
  3529. struct mg_str cid = opts->client_id;
  3530. size_t total_len = 7 + 1 + 2 + 2;
  3531. uint8_t hdr[8] = {0, 4, 'M', 'Q', 'T', 'T', opts->version, 0};
  3532. if (cid.len == 0) {
  3533. mg_random(rnd, sizeof(rnd));
  3534. mg_hex(rnd, sizeof(rnd), client_id);
  3535. client_id[sizeof(client_id) - 1] = '\0';
  3536. cid = mg_str(client_id);
  3537. }
  3538. if (hdr[6] == 0) hdr[6] = 4; // If version is not set, use 4 (3.1.1)
  3539. c->is_mqtt5 = hdr[6] == 5; // Set version 5 flag
  3540. hdr[7] = (uint8_t) ((opts->qos & 3) << 3); // Connection flags
  3541. if (opts->user.len > 0) {
  3542. total_len += 2 + (uint32_t) opts->user.len;
  3543. hdr[7] |= MQTT_HAS_USER_NAME;
  3544. }
  3545. if (opts->pass.len > 0) {
  3546. total_len += 2 + (uint32_t) opts->pass.len;
  3547. hdr[7] |= MQTT_HAS_PASSWORD;
  3548. }
  3549. if (opts->topic.len > 0 && opts->message.len > 0) {
  3550. total_len += 4 + (uint32_t) opts->topic.len + (uint32_t) opts->message.len;
  3551. hdr[7] |= MQTT_HAS_WILL;
  3552. }
  3553. if (opts->clean || cid.len == 0) hdr[7] |= MQTT_CLEAN_SESSION;
  3554. if (opts->retain) hdr[7] |= MQTT_WILL_RETAIN;
  3555. total_len += (uint32_t) cid.len;
  3556. if (c->is_mqtt5) {
  3557. total_len += get_props_size(opts->props, opts->num_props);
  3558. if (hdr[7] & MQTT_HAS_WILL)
  3559. total_len += get_props_size(opts->will_props, opts->num_will_props);
  3560. }
  3561. mg_mqtt_send_header(c, MQTT_CMD_CONNECT, 0, (uint32_t) total_len);
  3562. mg_send(c, hdr, sizeof(hdr));
  3563. // keepalive == 0 means "do not disconnect us!"
  3564. mg_send_u16(c, mg_htons((uint16_t) opts->keepalive));
  3565. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3566. mg_send_u16(c, mg_htons((uint16_t) cid.len));
  3567. mg_send(c, cid.ptr, cid.len);
  3568. if (hdr[7] & MQTT_HAS_WILL) {
  3569. if (c->is_mqtt5)
  3570. mg_send_mqtt_properties(c, opts->will_props, opts->num_will_props);
  3571. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3572. mg_send(c, opts->topic.ptr, opts->topic.len);
  3573. mg_send_u16(c, mg_htons((uint16_t) opts->message.len));
  3574. mg_send(c, opts->message.ptr, opts->message.len);
  3575. }
  3576. if (opts->user.len > 0) {
  3577. mg_send_u16(c, mg_htons((uint16_t) opts->user.len));
  3578. mg_send(c, opts->user.ptr, opts->user.len);
  3579. }
  3580. if (opts->pass.len > 0) {
  3581. mg_send_u16(c, mg_htons((uint16_t) opts->pass.len));
  3582. mg_send(c, opts->pass.ptr, opts->pass.len);
  3583. }
  3584. }
  3585. void mg_mqtt_pub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3586. uint8_t flags = (uint8_t) (((opts->qos & 3) << 1) | (opts->retain ? 1 : 0));
  3587. size_t len = 2 + opts->topic.len + opts->message.len;
  3588. MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) opts->topic.len,
  3589. (char *) opts->topic.ptr, (int) opts->message.len,
  3590. (char *) opts->message.ptr));
  3591. if (opts->qos > 0) len += 2;
  3592. if (c->is_mqtt5) len += get_props_size(opts->props, opts->num_props);
  3593. mg_mqtt_send_header(c, MQTT_CMD_PUBLISH, flags, (uint32_t) len);
  3594. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3595. mg_send(c, opts->topic.ptr, opts->topic.len);
  3596. if (opts->qos > 0) {
  3597. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  3598. mg_send_u16(c, mg_htons(c->mgr->mqtt_id));
  3599. }
  3600. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3601. if (opts->message.len > 0) mg_send(c, opts->message.ptr, opts->message.len);
  3602. }
  3603. void mg_mqtt_sub(struct mg_connection *c, const struct mg_mqtt_opts *opts) {
  3604. uint8_t qos_ = opts->qos & 3;
  3605. size_t plen = c->is_mqtt5 ? get_props_size(opts->props, opts->num_props) : 0;
  3606. size_t len = 2 + opts->topic.len + 2 + 1 + plen;
  3607. mg_mqtt_send_header(c, MQTT_CMD_SUBSCRIBE, 2, (uint32_t) len);
  3608. if (++c->mgr->mqtt_id == 0) ++c->mgr->mqtt_id;
  3609. mg_send_u16(c, mg_htons(c->mgr->mqtt_id));
  3610. if (c->is_mqtt5) mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3611. mg_send_u16(c, mg_htons((uint16_t) opts->topic.len));
  3612. mg_send(c, opts->topic.ptr, opts->topic.len);
  3613. mg_send(c, &qos_, sizeof(qos_));
  3614. }
  3615. int mg_mqtt_parse(const uint8_t *buf, size_t len, uint8_t version,
  3616. struct mg_mqtt_message *m) {
  3617. uint8_t lc = 0, *p, *end;
  3618. uint32_t n = 0, len_len = 0;
  3619. memset(m, 0, sizeof(*m));
  3620. m->dgram.ptr = (char *) buf;
  3621. if (len < 2) return MQTT_INCOMPLETE;
  3622. m->cmd = (uint8_t) (buf[0] >> 4);
  3623. m->qos = (buf[0] >> 1) & 3;
  3624. n = len_len = 0;
  3625. p = (uint8_t *) buf + 1;
  3626. while ((size_t) (p - buf) < len) {
  3627. lc = *((uint8_t *) p++);
  3628. n += (uint32_t) ((lc & 0x7f) << 7 * len_len);
  3629. len_len++;
  3630. if (!(lc & 0x80)) break;
  3631. if (len_len >= 4) return MQTT_MALFORMED;
  3632. }
  3633. end = p + n;
  3634. if ((lc & 0x80) || (end > buf + len)) return MQTT_INCOMPLETE;
  3635. m->dgram.len = (size_t) (end - buf);
  3636. switch (m->cmd) {
  3637. case MQTT_CMD_CONNACK:
  3638. if (end - p < 2) return MQTT_MALFORMED;
  3639. m->ack = p[1];
  3640. break;
  3641. case MQTT_CMD_PUBACK:
  3642. case MQTT_CMD_PUBREC:
  3643. case MQTT_CMD_PUBREL:
  3644. case MQTT_CMD_PUBCOMP:
  3645. case MQTT_CMD_SUBSCRIBE:
  3646. case MQTT_CMD_SUBACK:
  3647. case MQTT_CMD_UNSUBSCRIBE:
  3648. case MQTT_CMD_UNSUBACK:
  3649. if (p + 2 > end) return MQTT_MALFORMED;
  3650. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3651. p += 2;
  3652. break;
  3653. case MQTT_CMD_PUBLISH: {
  3654. if (p + 2 > end) return MQTT_MALFORMED;
  3655. m->topic.len = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3656. m->topic.ptr = (char *) p + 2;
  3657. p += 2 + m->topic.len;
  3658. if (p > end) return MQTT_MALFORMED;
  3659. if (m->qos > 0) {
  3660. if (p + 2 > end) return MQTT_MALFORMED;
  3661. m->id = (uint16_t) ((((uint16_t) p[0]) << 8) | p[1]);
  3662. p += 2;
  3663. }
  3664. if (p > end) return MQTT_MALFORMED;
  3665. if (version == 5 && p + 2 < end) {
  3666. len_len =
  3667. (uint32_t) decode_varint(p, (size_t) (end - p), &m->props_size);
  3668. if (!len_len) return MQTT_MALFORMED;
  3669. m->props_start = (size_t) (p + len_len - buf);
  3670. p += len_len + m->props_size;
  3671. }
  3672. if (p > end) return MQTT_MALFORMED;
  3673. m->data.ptr = (char *) p;
  3674. m->data.len = (size_t) (end - p);
  3675. break;
  3676. }
  3677. default:
  3678. break;
  3679. }
  3680. return MQTT_OK;
  3681. }
  3682. static void mqtt_cb(struct mg_connection *c, int ev, void *ev_data) {
  3683. if (ev == MG_EV_READ) {
  3684. for (;;) {
  3685. uint8_t version = c->is_mqtt5 ? 5 : 4;
  3686. struct mg_mqtt_message mm;
  3687. int rc = mg_mqtt_parse(c->recv.buf, c->recv.len, version, &mm);
  3688. if (rc == MQTT_MALFORMED) {
  3689. MG_ERROR(("%lu MQTT malformed message", c->id));
  3690. c->is_closing = 1;
  3691. break;
  3692. } else if (rc == MQTT_OK) {
  3693. MG_VERBOSE(("%lu MQTT CMD %d len %d [%.*s]", c->id, mm.cmd,
  3694. (int) mm.dgram.len, (int) mm.data.len, mm.data.ptr));
  3695. switch (mm.cmd) {
  3696. case MQTT_CMD_CONNACK:
  3697. mg_call(c, MG_EV_MQTT_OPEN, &mm.ack);
  3698. if (mm.ack == 0) {
  3699. MG_DEBUG(("%lu Connected", c->id));
  3700. } else {
  3701. MG_ERROR(("%lu MQTT auth failed, code %d", c->id, mm.ack));
  3702. c->is_closing = 1;
  3703. }
  3704. break;
  3705. case MQTT_CMD_PUBLISH: {
  3706. /*MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) mm.topic.len,
  3707. mm.topic.ptr, (int) mm.data.len, mm.data.ptr));*/
  3708. if (mm.qos > 0) {
  3709. uint16_t id = mg_ntohs(mm.id);
  3710. uint32_t remaining_len = sizeof(id);
  3711. if (c->is_mqtt5) remaining_len += 2; // 3.4.2
  3712. mg_mqtt_send_header(
  3713. c,
  3714. (uint8_t) (mm.qos == 2 ? MQTT_CMD_PUBREC : MQTT_CMD_PUBACK),
  3715. 0, remaining_len);
  3716. mg_send(c, &id, sizeof(id));
  3717. if (c->is_mqtt5) {
  3718. uint16_t zero = 0;
  3719. mg_send(c, &zero, sizeof(zero));
  3720. }
  3721. }
  3722. mg_call(c, MG_EV_MQTT_MSG, &mm); // let the app handle qos stuff
  3723. break;
  3724. }
  3725. case MQTT_CMD_PUBREC: { // MQTT5: 3.5.2-1 TODO(): variable header rc
  3726. uint16_t id = mg_ntohs(mm.id);
  3727. uint32_t remaining_len = sizeof(id); // MQTT5 3.6.2-1
  3728. mg_mqtt_send_header(c, MQTT_CMD_PUBREL, 2, remaining_len);
  3729. mg_send(c, &id, sizeof(id)); // MQTT5 3.6.1-1, flags = 2
  3730. break;
  3731. }
  3732. case MQTT_CMD_PUBREL: { // MQTT5: 3.6.2-1 TODO(): variable header rc
  3733. uint16_t id = mg_ntohs(mm.id);
  3734. uint32_t remaining_len = sizeof(id); // MQTT5 3.7.2-1
  3735. mg_mqtt_send_header(c, MQTT_CMD_PUBCOMP, 0, remaining_len);
  3736. mg_send(c, &id, sizeof(id));
  3737. break;
  3738. }
  3739. }
  3740. mg_call(c, MG_EV_MQTT_CMD, &mm);
  3741. mg_iobuf_del(&c->recv, 0, mm.dgram.len);
  3742. } else {
  3743. break;
  3744. }
  3745. }
  3746. }
  3747. (void) ev_data;
  3748. }
  3749. void mg_mqtt_ping(struct mg_connection *nc) {
  3750. mg_mqtt_send_header(nc, MQTT_CMD_PINGREQ, 0, 0);
  3751. }
  3752. void mg_mqtt_pong(struct mg_connection *nc) {
  3753. mg_mqtt_send_header(nc, MQTT_CMD_PINGRESP, 0, 0);
  3754. }
  3755. void mg_mqtt_disconnect(struct mg_connection *c,
  3756. const struct mg_mqtt_opts *opts) {
  3757. size_t len = 0;
  3758. if (c->is_mqtt5) len = 1 + get_props_size(opts->props, opts->num_props);
  3759. mg_mqtt_send_header(c, MQTT_CMD_DISCONNECT, 0, (uint32_t) len);
  3760. if (c->is_mqtt5) {
  3761. uint8_t zero = 0;
  3762. mg_send(c, &zero, sizeof(zero)); // reason code
  3763. mg_send_mqtt_properties(c, opts->props, opts->num_props);
  3764. }
  3765. }
  3766. struct mg_connection *mg_mqtt_connect(struct mg_mgr *mgr, const char *url,
  3767. const struct mg_mqtt_opts *opts,
  3768. mg_event_handler_t fn, void *fn_data) {
  3769. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  3770. if (c != NULL) {
  3771. struct mg_mqtt_opts empty;
  3772. memset(&empty, 0, sizeof(empty));
  3773. mg_mqtt_login(c, opts == NULL ? &empty : opts);
  3774. c->pfn = mqtt_cb;
  3775. }
  3776. return c;
  3777. }
  3778. struct mg_connection *mg_mqtt_listen(struct mg_mgr *mgr, const char *url,
  3779. mg_event_handler_t fn, void *fn_data) {
  3780. struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
  3781. if (c != NULL) c->pfn = mqtt_cb, c->pfn_data = mgr;
  3782. return c;
  3783. }
  3784. #ifdef MG_ENABLE_LINES
  3785. #line 1 "src/net.c"
  3786. #endif
  3787. size_t mg_vprintf(struct mg_connection *c, const char *fmt, va_list *ap) {
  3788. size_t old = c->send.len;
  3789. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  3790. return c->send.len - old;
  3791. }
  3792. size_t mg_printf(struct mg_connection *c, const char *fmt, ...) {
  3793. size_t len = 0;
  3794. va_list ap;
  3795. va_start(ap, fmt);
  3796. len = mg_vprintf(c, fmt, &ap);
  3797. va_end(ap);
  3798. return len;
  3799. }
  3800. static bool mg_atonl(struct mg_str str, struct mg_addr *addr) {
  3801. uint32_t localhost = mg_htonl(0x7f000001);
  3802. if (mg_vcasecmp(&str, "localhost") != 0) return false;
  3803. memcpy(addr->ip, &localhost, sizeof(uint32_t));
  3804. addr->is_ip6 = false;
  3805. return true;
  3806. }
  3807. static bool mg_atone(struct mg_str str, struct mg_addr *addr) {
  3808. if (str.len > 0) return false;
  3809. memset(addr->ip, 0, sizeof(addr->ip));
  3810. addr->is_ip6 = false;
  3811. return true;
  3812. }
  3813. static bool mg_aton4(struct mg_str str, struct mg_addr *addr) {
  3814. uint8_t data[4] = {0, 0, 0, 0};
  3815. size_t i, num_dots = 0;
  3816. for (i = 0; i < str.len; i++) {
  3817. if (str.ptr[i] >= '0' && str.ptr[i] <= '9') {
  3818. int octet = data[num_dots] * 10 + (str.ptr[i] - '0');
  3819. if (octet > 255) return false;
  3820. data[num_dots] = (uint8_t) octet;
  3821. } else if (str.ptr[i] == '.') {
  3822. if (num_dots >= 3 || i == 0 || str.ptr[i - 1] == '.') return false;
  3823. num_dots++;
  3824. } else {
  3825. return false;
  3826. }
  3827. }
  3828. if (num_dots != 3 || str.ptr[i - 1] == '.') return false;
  3829. memcpy(&addr->ip, data, sizeof(data));
  3830. addr->is_ip6 = false;
  3831. return true;
  3832. }
  3833. static bool mg_v4mapped(struct mg_str str, struct mg_addr *addr) {
  3834. int i;
  3835. uint32_t ipv4;
  3836. if (str.len < 14) return false;
  3837. if (str.ptr[0] != ':' || str.ptr[1] != ':' || str.ptr[6] != ':') return false;
  3838. for (i = 2; i < 6; i++) {
  3839. if (str.ptr[i] != 'f' && str.ptr[i] != 'F') return false;
  3840. }
  3841. // struct mg_str s = mg_str_n(&str.ptr[7], str.len - 7);
  3842. if (!mg_aton4(mg_str_n(&str.ptr[7], str.len - 7), addr)) return false;
  3843. memcpy(&ipv4, addr->ip, sizeof(ipv4));
  3844. memset(addr->ip, 0, sizeof(addr->ip));
  3845. addr->ip[10] = addr->ip[11] = 255;
  3846. memcpy(&addr->ip[12], &ipv4, 4);
  3847. addr->is_ip6 = true;
  3848. return true;
  3849. }
  3850. static bool mg_aton6(struct mg_str str, struct mg_addr *addr) {
  3851. size_t i, j = 0, n = 0, dc = 42;
  3852. addr->scope_id = 0;
  3853. if (str.len > 2 && str.ptr[0] == '[') str.ptr++, str.len -= 2;
  3854. if (mg_v4mapped(str, addr)) return true;
  3855. for (i = 0; i < str.len; i++) {
  3856. if ((str.ptr[i] >= '0' && str.ptr[i] <= '9') ||
  3857. (str.ptr[i] >= 'a' && str.ptr[i] <= 'f') ||
  3858. (str.ptr[i] >= 'A' && str.ptr[i] <= 'F')) {
  3859. unsigned long val;
  3860. if (i > j + 3) return false;
  3861. // MG_DEBUG(("%lu %lu [%.*s]", i, j, (int) (i - j + 1), &str.ptr[j]));
  3862. val = mg_unhexn(&str.ptr[j], i - j + 1);
  3863. addr->ip[n] = (uint8_t) ((val >> 8) & 255);
  3864. addr->ip[n + 1] = (uint8_t) (val & 255);
  3865. } else if (str.ptr[i] == ':') {
  3866. j = i + 1;
  3867. if (i > 0 && str.ptr[i - 1] == ':') {
  3868. dc = n; // Double colon
  3869. if (i > 1 && str.ptr[i - 2] == ':') return false;
  3870. } else if (i > 0) {
  3871. n += 2;
  3872. }
  3873. if (n > 14) return false;
  3874. addr->ip[n] = addr->ip[n + 1] = 0; // For trailing ::
  3875. } else if (str.ptr[i] == '%') { // Scope ID
  3876. for (i = i + 1; i < str.len; i++) {
  3877. if (str.ptr[i] < '0' || str.ptr[i] > '9') return false;
  3878. addr->scope_id = (uint8_t) (addr->scope_id * 10);
  3879. addr->scope_id = (uint8_t) (addr->scope_id + (str.ptr[i] - '0'));
  3880. }
  3881. } else {
  3882. return false;
  3883. }
  3884. }
  3885. if (n < 14 && dc == 42) return false;
  3886. if (n < 14) {
  3887. memmove(&addr->ip[dc + (14 - n)], &addr->ip[dc], n - dc + 2);
  3888. memset(&addr->ip[dc], 0, 14 - n);
  3889. }
  3890. addr->is_ip6 = true;
  3891. return true;
  3892. }
  3893. bool mg_aton(struct mg_str str, struct mg_addr *addr) {
  3894. // MG_INFO(("[%.*s]", (int) str.len, str.ptr));
  3895. return mg_atone(str, addr) || mg_atonl(str, addr) || mg_aton4(str, addr) ||
  3896. mg_aton6(str, addr);
  3897. }
  3898. struct mg_connection *mg_alloc_conn(struct mg_mgr *mgr) {
  3899. struct mg_connection *c =
  3900. (struct mg_connection *) calloc(1, sizeof(*c) + mgr->extraconnsize);
  3901. if (c != NULL) {
  3902. c->mgr = mgr;
  3903. c->send.align = c->recv.align = c->rtls.align = MG_IO_SIZE;
  3904. c->id = ++mgr->nextid;
  3905. MG_PROF_INIT(c);
  3906. }
  3907. return c;
  3908. }
  3909. void mg_close_conn(struct mg_connection *c) {
  3910. mg_resolve_cancel(c); // Close any pending DNS query
  3911. LIST_DELETE(struct mg_connection, &c->mgr->conns, c);
  3912. if (c == c->mgr->dns4.c) c->mgr->dns4.c = NULL;
  3913. if (c == c->mgr->dns6.c) c->mgr->dns6.c = NULL;
  3914. // Order of operations is important. `MG_EV_CLOSE` event must be fired
  3915. // before we deallocate received data, see #1331
  3916. mg_call(c, MG_EV_CLOSE, NULL);
  3917. MG_DEBUG(("%lu %ld closed", c->id, c->fd));
  3918. MG_PROF_DUMP(c);
  3919. MG_PROF_FREE(c);
  3920. mg_tls_free(c);
  3921. mg_iobuf_free(&c->recv);
  3922. mg_iobuf_free(&c->send);
  3923. mg_iobuf_free(&c->rtls);
  3924. mg_bzero((unsigned char *) c, sizeof(*c));
  3925. free(c);
  3926. }
  3927. struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url,
  3928. mg_event_handler_t fn, void *fn_data) {
  3929. struct mg_connection *c = NULL;
  3930. if (url == NULL || url[0] == '\0') {
  3931. MG_ERROR(("null url"));
  3932. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  3933. MG_ERROR(("OOM"));
  3934. } else {
  3935. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3936. c->is_udp = (strncmp(url, "udp:", 4) == 0);
  3937. c->fd = (void *) (size_t) MG_INVALID_SOCKET;
  3938. c->fn = fn;
  3939. c->is_client = true;
  3940. c->fn_data = fn_data;
  3941. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  3942. mg_call(c, MG_EV_OPEN, (void *) url);
  3943. mg_resolve(c, url);
  3944. }
  3945. return c;
  3946. }
  3947. struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url,
  3948. mg_event_handler_t fn, void *fn_data) {
  3949. struct mg_connection *c = NULL;
  3950. if ((c = mg_alloc_conn(mgr)) == NULL) {
  3951. MG_ERROR(("OOM %s", url));
  3952. } else if (!mg_open_listener(c, url)) {
  3953. MG_ERROR(("Failed: %s, errno %d", url, errno));
  3954. MG_PROF_FREE(c);
  3955. free(c);
  3956. c = NULL;
  3957. } else {
  3958. c->is_listening = 1;
  3959. c->is_udp = strncmp(url, "udp:", 4) == 0;
  3960. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3961. c->fn = fn;
  3962. c->fn_data = fn_data;
  3963. mg_call(c, MG_EV_OPEN, NULL);
  3964. if (mg_url_is_ssl(url)) c->is_tls = 1; // Accepted connection must
  3965. MG_DEBUG(("%lu %ld %s", c->id, c->fd, url));
  3966. }
  3967. return c;
  3968. }
  3969. struct mg_connection *mg_wrapfd(struct mg_mgr *mgr, int fd,
  3970. mg_event_handler_t fn, void *fn_data) {
  3971. struct mg_connection *c = mg_alloc_conn(mgr);
  3972. if (c != NULL) {
  3973. c->fd = (void *) (size_t) fd;
  3974. c->fn = fn;
  3975. c->fn_data = fn_data;
  3976. MG_EPOLL_ADD(c);
  3977. mg_call(c, MG_EV_OPEN, NULL);
  3978. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  3979. }
  3980. return c;
  3981. }
  3982. struct mg_timer *mg_timer_add(struct mg_mgr *mgr, uint64_t milliseconds,
  3983. unsigned flags, void (*fn)(void *), void *arg) {
  3984. struct mg_timer *t = (struct mg_timer *) calloc(1, sizeof(*t));
  3985. if (t != NULL) {
  3986. mg_timer_init(&mgr->timers, t, milliseconds, flags, fn, arg);
  3987. t->id = mgr->timerid++;
  3988. }
  3989. return t;
  3990. }
  3991. long mg_io_recv(struct mg_connection *c, void *buf, size_t len) {
  3992. if (c->rtls.len == 0) return MG_IO_WAIT;
  3993. if (len > c->rtls.len) len = c->rtls.len;
  3994. memcpy(buf, c->rtls.buf, len);
  3995. mg_iobuf_del(&c->rtls, 0, len);
  3996. return (long) len;
  3997. }
  3998. void mg_mgr_free(struct mg_mgr *mgr) {
  3999. struct mg_connection *c;
  4000. struct mg_timer *tmp, *t = mgr->timers;
  4001. while (t != NULL) tmp = t->next, free(t), t = tmp;
  4002. mgr->timers = NULL; // Important. Next call to poll won't touch timers
  4003. for (c = mgr->conns; c != NULL; c = c->next) c->is_closing = 1;
  4004. mg_mgr_poll(mgr, 0);
  4005. #if MG_ENABLE_FREERTOS_TCP
  4006. FreeRTOS_DeleteSocketSet(mgr->ss);
  4007. #endif
  4008. MG_DEBUG(("All connections closed"));
  4009. #if MG_ENABLE_EPOLL
  4010. if (mgr->epoll_fd >= 0) close(mgr->epoll_fd), mgr->epoll_fd = -1;
  4011. #endif
  4012. mg_tls_ctx_free(mgr);
  4013. }
  4014. bool mg_mgr_init(struct mg_mgr *mgr) {
  4015. memset(mgr, 0, sizeof(*mgr));
  4016. #if MG_ENABLE_EPOLL
  4017. if ((mgr->epoll_fd = epoll_create1(EPOLL_CLOEXEC)) < 0)
  4018. MG_ERROR(("epoll_create1 errno %d", errno));
  4019. #else
  4020. mgr->epoll_fd = -1;
  4021. #endif
  4022. #if MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  4023. // clang-format off
  4024. { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
  4025. // clang-format on
  4026. #elif MG_ENABLE_FREERTOS_TCP
  4027. mgr->ss = FreeRTOS_CreateSocketSet();
  4028. #elif defined(__unix) || defined(__unix__) || defined(__APPLE__)
  4029. // Ignore SIGPIPE signal, so if client cancels the request, it
  4030. // won't kill the whole process.
  4031. signal(SIGPIPE, SIG_IGN);
  4032. #endif
  4033. mgr->pipe = MG_INVALID_SOCKET;
  4034. mgr->dnstimeout = 3000;
  4035. mgr->dns4.url = "udp://8.8.8.8:53";
  4036. mgr->dns6.url = "udp://[2001:4860:4860::8888]:53";
  4037. mg_tls_ctx_init(mgr);
  4038. return true;
  4039. }
  4040. #ifdef MG_ENABLE_LINES
  4041. #line 1 "src/net_builtin.c"
  4042. #endif
  4043. #if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP
  4044. #define MG_EPHEMERAL_PORT_BASE 32768
  4045. #define PDIFF(a, b) ((size_t) (((char *) (b)) - ((char *) (a))))
  4046. #ifndef MIP_TCP_KEEPALIVE_MS
  4047. #define MIP_TCP_KEEPALIVE_MS 45000 // TCP keep-alive period, ms
  4048. #endif
  4049. #define MIP_TCP_ACK_MS 150 // Timeout for ACKing
  4050. #define MIP_TCP_ARP_MS 100 // Timeout for ARP response
  4051. #define MIP_TCP_SYN_MS 15000 // Timeout for connection establishment
  4052. #define MIP_TCP_FIN_MS 1000 // Timeout for closing connection
  4053. struct connstate {
  4054. uint32_t seq, ack; // TCP seq/ack counters
  4055. uint64_t timer; // TCP keep-alive / ACK timer
  4056. uint8_t mac[6]; // Peer MAC address
  4057. uint8_t ttype; // Timer type. 0: ack, 1: keep-alive
  4058. #define MIP_TTYPE_KEEPALIVE 0 // Connection is idle for long, send keepalive
  4059. #define MIP_TTYPE_ACK 1 // Peer sent us data, we have to ack it soon
  4060. #define MIP_TTYPE_ARP 2 // ARP resolve sent, waiting for response
  4061. #define MIP_TTYPE_SYN 3 // SYN sent, waiting for response
  4062. #define MIP_TTYPE_FIN 4 // FIN sent, waiting until terminating the connection
  4063. uint8_t tmiss; // Number of keep-alive misses
  4064. struct mg_iobuf raw; // For TLS only. Incoming raw data
  4065. };
  4066. #pragma pack(push, 1)
  4067. struct lcp {
  4068. uint8_t addr, ctrl, proto[2], code, id, len[2];
  4069. };
  4070. struct eth {
  4071. uint8_t dst[6]; // Destination MAC address
  4072. uint8_t src[6]; // Source MAC address
  4073. uint16_t type; // Ethernet type
  4074. };
  4075. struct ip {
  4076. uint8_t ver; // Version
  4077. uint8_t tos; // Unused
  4078. uint16_t len; // Length
  4079. uint16_t id; // Unused
  4080. uint16_t frag; // Fragmentation
  4081. #define IP_FRAG_OFFSET_MSK 0xFF1F
  4082. #define IP_MORE_FRAGS_MSK 0x20
  4083. uint8_t ttl; // Time to live
  4084. uint8_t proto; // Upper level protocol
  4085. uint16_t csum; // Checksum
  4086. uint32_t src; // Source IP
  4087. uint32_t dst; // Destination IP
  4088. };
  4089. struct ip6 {
  4090. uint8_t ver; // Version
  4091. uint8_t opts[3]; // Options
  4092. uint16_t len; // Length
  4093. uint8_t proto; // Upper level protocol
  4094. uint8_t ttl; // Time to live
  4095. uint8_t src[16]; // Source IP
  4096. uint8_t dst[16]; // Destination IP
  4097. };
  4098. struct icmp {
  4099. uint8_t type;
  4100. uint8_t code;
  4101. uint16_t csum;
  4102. };
  4103. struct arp {
  4104. uint16_t fmt; // Format of hardware address
  4105. uint16_t pro; // Format of protocol address
  4106. uint8_t hlen; // Length of hardware address
  4107. uint8_t plen; // Length of protocol address
  4108. uint16_t op; // Operation
  4109. uint8_t sha[6]; // Sender hardware address
  4110. uint32_t spa; // Sender protocol address
  4111. uint8_t tha[6]; // Target hardware address
  4112. uint32_t tpa; // Target protocol address
  4113. };
  4114. struct tcp {
  4115. uint16_t sport; // Source port
  4116. uint16_t dport; // Destination port
  4117. uint32_t seq; // Sequence number
  4118. uint32_t ack; // Acknowledgement number
  4119. uint8_t off; // Data offset
  4120. uint8_t flags; // TCP flags
  4121. #define TH_FIN 0x01
  4122. #define TH_SYN 0x02
  4123. #define TH_RST 0x04
  4124. #define TH_PUSH 0x08
  4125. #define TH_ACK 0x10
  4126. #define TH_URG 0x20
  4127. #define TH_ECE 0x40
  4128. #define TH_CWR 0x80
  4129. uint16_t win; // Window
  4130. uint16_t csum; // Checksum
  4131. uint16_t urp; // Urgent pointer
  4132. };
  4133. struct udp {
  4134. uint16_t sport; // Source port
  4135. uint16_t dport; // Destination port
  4136. uint16_t len; // UDP length
  4137. uint16_t csum; // UDP checksum
  4138. };
  4139. struct dhcp {
  4140. uint8_t op, htype, hlen, hops;
  4141. uint32_t xid;
  4142. uint16_t secs, flags;
  4143. uint32_t ciaddr, yiaddr, siaddr, giaddr;
  4144. uint8_t hwaddr[208];
  4145. uint32_t magic;
  4146. uint8_t options[32];
  4147. };
  4148. #pragma pack(pop)
  4149. struct pkt {
  4150. struct mg_str raw; // Raw packet data
  4151. struct mg_str pay; // Payload data
  4152. struct eth *eth;
  4153. struct llc *llc;
  4154. struct arp *arp;
  4155. struct ip *ip;
  4156. struct ip6 *ip6;
  4157. struct icmp *icmp;
  4158. struct tcp *tcp;
  4159. struct udp *udp;
  4160. struct dhcp *dhcp;
  4161. };
  4162. static void send_syn(struct mg_connection *c);
  4163. static void mkpay(struct pkt *pkt, void *p) {
  4164. pkt->pay =
  4165. mg_str_n((char *) p, (size_t) (&pkt->raw.ptr[pkt->raw.len] - (char *) p));
  4166. }
  4167. static uint32_t csumup(uint32_t sum, const void *buf, size_t len) {
  4168. const uint8_t *p = (const uint8_t *) buf;
  4169. for (size_t i = 0; i < len; i++) sum += i & 1 ? p[i] : (uint32_t) (p[i] << 8);
  4170. return sum;
  4171. }
  4172. static uint16_t csumfin(uint32_t sum) {
  4173. while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16);
  4174. return mg_htons(~sum & 0xffff);
  4175. }
  4176. static uint16_t ipcsum(const void *buf, size_t len) {
  4177. uint32_t sum = csumup(0, buf, len);
  4178. return csumfin(sum);
  4179. }
  4180. static void settmout(struct mg_connection *c, uint8_t type) {
  4181. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4182. struct connstate *s = (struct connstate *) (c + 1);
  4183. unsigned n = type == MIP_TTYPE_ACK ? MIP_TCP_ACK_MS
  4184. : type == MIP_TTYPE_ARP ? MIP_TCP_ARP_MS
  4185. : type == MIP_TTYPE_SYN ? MIP_TCP_SYN_MS
  4186. : type == MIP_TTYPE_FIN ? MIP_TCP_FIN_MS
  4187. : MIP_TCP_KEEPALIVE_MS;
  4188. s->timer = ifp->now + n;
  4189. s->ttype = type;
  4190. MG_VERBOSE(("%lu %d -> %llx", c->id, type, s->timer));
  4191. }
  4192. static size_t ether_output(struct mg_tcpip_if *ifp, size_t len) {
  4193. size_t n = ifp->driver->tx(ifp->tx.ptr, len, ifp);
  4194. if (n == len) ifp->nsent++;
  4195. return n;
  4196. }
  4197. static void arp_ask(struct mg_tcpip_if *ifp, uint32_t ip) {
  4198. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4199. struct arp *arp = (struct arp *) (eth + 1);
  4200. memset(eth->dst, 255, sizeof(eth->dst));
  4201. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4202. eth->type = mg_htons(0x806);
  4203. memset(arp, 0, sizeof(*arp));
  4204. arp->fmt = mg_htons(1), arp->pro = mg_htons(0x800), arp->hlen = 6,
  4205. arp->plen = 4;
  4206. arp->op = mg_htons(1), arp->tpa = ip, arp->spa = ifp->ip;
  4207. memcpy(arp->sha, ifp->mac, sizeof(arp->sha));
  4208. ether_output(ifp, PDIFF(eth, arp + 1));
  4209. }
  4210. static void onstatechange(struct mg_tcpip_if *ifp) {
  4211. if (ifp->state == MG_TCPIP_STATE_READY) {
  4212. MG_INFO(("READY, IP: %M", mg_print_ip4, &ifp->ip));
  4213. MG_INFO((" GW: %M", mg_print_ip4, &ifp->gw));
  4214. MG_INFO((" MAC: %M", mg_print_mac, &ifp->mac));
  4215. arp_ask(ifp, ifp->gw);
  4216. } else if (ifp->state == MG_TCPIP_STATE_UP) {
  4217. MG_ERROR(("Link up"));
  4218. srand((unsigned int) mg_millis());
  4219. } else if (ifp->state == MG_TCPIP_STATE_DOWN) {
  4220. MG_ERROR(("Link down"));
  4221. }
  4222. }
  4223. static struct ip *tx_ip(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4224. uint8_t proto, uint32_t ip_src, uint32_t ip_dst,
  4225. size_t plen) {
  4226. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4227. struct ip *ip = (struct ip *) (eth + 1);
  4228. memcpy(eth->dst, mac_dst, sizeof(eth->dst));
  4229. memcpy(eth->src, ifp->mac, sizeof(eth->src)); // Use our MAC
  4230. eth->type = mg_htons(0x800);
  4231. memset(ip, 0, sizeof(*ip));
  4232. ip->ver = 0x45; // Version 4, header length 5 words
  4233. ip->frag = 0x40; // Don't fragment
  4234. ip->len = mg_htons((uint16_t) (sizeof(*ip) + plen));
  4235. ip->ttl = 64;
  4236. ip->proto = proto;
  4237. ip->src = ip_src;
  4238. ip->dst = ip_dst;
  4239. ip->csum = ipcsum(ip, sizeof(*ip));
  4240. return ip;
  4241. }
  4242. static void tx_udp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4243. uint16_t sport, uint32_t ip_dst, uint16_t dport,
  4244. const void *buf, size_t len) {
  4245. struct ip *ip =
  4246. tx_ip(ifp, mac_dst, 17, ip_src, ip_dst, len + sizeof(struct udp));
  4247. struct udp *udp = (struct udp *) (ip + 1);
  4248. // MG_DEBUG(("UDP XX LEN %d %d", (int) len, (int) ifp->tx.len));
  4249. udp->sport = sport;
  4250. udp->dport = dport;
  4251. udp->len = mg_htons((uint16_t) (sizeof(*udp) + len));
  4252. udp->csum = 0;
  4253. uint32_t cs = csumup(0, udp, sizeof(*udp));
  4254. cs = csumup(cs, buf, len);
  4255. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4256. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4257. cs += (uint32_t) (ip->proto + sizeof(*udp) + len);
  4258. udp->csum = csumfin(cs);
  4259. memmove(udp + 1, buf, len);
  4260. // MG_DEBUG(("UDP LEN %d %d", (int) len, (int) ifp->frame_len));
  4261. ether_output(ifp, sizeof(struct eth) + sizeof(*ip) + sizeof(*udp) + len);
  4262. }
  4263. static void tx_dhcp(struct mg_tcpip_if *ifp, uint8_t *mac_dst, uint32_t ip_src,
  4264. uint32_t ip_dst, uint8_t *opts, size_t optslen,
  4265. bool ciaddr) {
  4266. // https://datatracker.ietf.org/doc/html/rfc2132#section-9.6
  4267. struct dhcp dhcp = {1, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4268. dhcp.magic = mg_htonl(0x63825363);
  4269. memcpy(&dhcp.hwaddr, ifp->mac, sizeof(ifp->mac));
  4270. memcpy(&dhcp.xid, ifp->mac + 2, sizeof(dhcp.xid));
  4271. memcpy(&dhcp.options, opts, optslen);
  4272. if (ciaddr) dhcp.ciaddr = ip_src;
  4273. tx_udp(ifp, mac_dst, ip_src, mg_htons(68), ip_dst, mg_htons(67), &dhcp,
  4274. sizeof(dhcp));
  4275. }
  4276. static const uint8_t broadcast[] = {255, 255, 255, 255, 255, 255};
  4277. // RFC-2131 #4.3.6, #4.4.1
  4278. static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
  4279. uint32_t ip_srv) {
  4280. uint8_t opts[] = {
  4281. 53, 1, 3, // Type: DHCP request
  4282. 55, 2, 1, 3, // GW and mask
  4283. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4284. 54, 4, 0, 0, 0, 0, // DHCP server ID
  4285. 50, 4, 0, 0, 0, 0, // Requested IP
  4286. 255 // End of options
  4287. };
  4288. memcpy(opts + 14, &ip_srv, sizeof(ip_srv));
  4289. memcpy(opts + 20, &ip_req, sizeof(ip_req));
  4290. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4291. MG_DEBUG(("DHCP req sent"));
  4292. }
  4293. // RFC-2131 #4.3.6, #4.4.5 (renewing: unicast, rebinding: bcast)
  4294. static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *mac_dst,
  4295. uint32_t ip_src, uint32_t ip_dst) {
  4296. uint8_t opts[] = {
  4297. 53, 1, 3, // Type: DHCP request
  4298. 255 // End of options
  4299. };
  4300. tx_dhcp(ifp, mac_dst, ip_src, ip_dst, opts, sizeof(opts), true);
  4301. MG_DEBUG(("DHCP req sent"));
  4302. }
  4303. static void tx_dhcp_discover(struct mg_tcpip_if *ifp) {
  4304. uint8_t opts[] = {
  4305. 53, 1, 1, // Type: DHCP discover
  4306. 55, 2, 1, 3, // Parameters: ip, mask
  4307. 255 // End of options
  4308. };
  4309. tx_dhcp(ifp, (uint8_t *) broadcast, 0, 0xffffffff, opts, sizeof(opts), false);
  4310. MG_DEBUG(("DHCP discover sent. Our MAC: %M", mg_print_mac, ifp->mac));
  4311. }
  4312. static struct mg_connection *getpeer(struct mg_mgr *mgr, struct pkt *pkt,
  4313. bool lsn) {
  4314. struct mg_connection *c = NULL;
  4315. for (c = mgr->conns; c != NULL; c = c->next) {
  4316. if (c->is_arplooking && pkt->arp &&
  4317. memcmp(&pkt->arp->spa, c->rem.ip, sizeof(pkt->arp->spa)) == 0)
  4318. break;
  4319. if (c->is_udp && pkt->udp && c->loc.port == pkt->udp->dport) break;
  4320. if (!c->is_udp && pkt->tcp && c->loc.port == pkt->tcp->dport &&
  4321. lsn == c->is_listening && (lsn || c->rem.port == pkt->tcp->sport))
  4322. break;
  4323. }
  4324. return c;
  4325. }
  4326. static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4327. if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) {
  4328. // ARP request. Make a response, then send
  4329. // MG_DEBUG(("ARP op %d %M: %M", mg_ntohs(pkt->arp->op), mg_print_ip4,
  4330. // &pkt->arp->spa, mg_print_ip4, &pkt->arp->tpa));
  4331. struct eth *eth = (struct eth *) ifp->tx.ptr;
  4332. struct arp *arp = (struct arp *) (eth + 1);
  4333. memcpy(eth->dst, pkt->eth->src, sizeof(eth->dst));
  4334. memcpy(eth->src, ifp->mac, sizeof(eth->src));
  4335. eth->type = mg_htons(0x806);
  4336. *arp = *pkt->arp;
  4337. arp->op = mg_htons(2);
  4338. memcpy(arp->tha, pkt->arp->sha, sizeof(pkt->arp->tha));
  4339. memcpy(arp->sha, ifp->mac, sizeof(pkt->arp->sha));
  4340. arp->tpa = pkt->arp->spa;
  4341. arp->spa = ifp->ip;
  4342. MG_DEBUG(("ARP: tell %M we're %M", mg_print_ip4, &arp->tpa, mg_print_mac,
  4343. &ifp->mac));
  4344. ether_output(ifp, PDIFF(eth, arp + 1));
  4345. } else if (pkt->arp->op == mg_htons(2)) {
  4346. if (memcmp(pkt->arp->tha, ifp->mac, sizeof(pkt->arp->tha)) != 0) return;
  4347. if (pkt->arp->spa == ifp->gw) {
  4348. // Got response for the GW ARP request. Set ifp->gwmac
  4349. memcpy(ifp->gwmac, pkt->arp->sha, sizeof(ifp->gwmac));
  4350. } else {
  4351. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4352. if (c != NULL && c->is_arplooking) {
  4353. struct connstate *s = (struct connstate *) (c + 1);
  4354. memcpy(s->mac, pkt->arp->sha, sizeof(s->mac));
  4355. MG_DEBUG(("%lu ARP resolved %M -> %M", c->id, mg_print_ip4, c->rem.ip,
  4356. mg_print_mac, s->mac));
  4357. c->is_arplooking = 0;
  4358. send_syn(c);
  4359. settmout(c, MIP_TTYPE_SYN);
  4360. }
  4361. }
  4362. }
  4363. }
  4364. static void rx_icmp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4365. // MG_DEBUG(("ICMP %d", (int) len));
  4366. if (pkt->icmp->type == 8 && pkt->ip != NULL && pkt->ip->dst == ifp->ip) {
  4367. size_t hlen = sizeof(struct eth) + sizeof(struct ip) + sizeof(struct icmp);
  4368. size_t space = ifp->tx.len - hlen, plen = pkt->pay.len;
  4369. if (plen > space) plen = space;
  4370. struct ip *ip = tx_ip(ifp, pkt->eth->src, 1, ifp->ip, pkt->ip->src,
  4371. sizeof(struct icmp) + plen);
  4372. struct icmp *icmp = (struct icmp *) (ip + 1);
  4373. memset(icmp, 0, sizeof(*icmp)); // Set csum to 0
  4374. memcpy(icmp + 1, pkt->pay.ptr, plen); // Copy RX payload to TX
  4375. icmp->csum = ipcsum(icmp, sizeof(*icmp) + plen);
  4376. ether_output(ifp, hlen + plen);
  4377. }
  4378. }
  4379. static void rx_dhcp_client(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4380. uint32_t ip = 0, gw = 0, mask = 0, lease = 0;
  4381. uint8_t msgtype = 0, state = ifp->state;
  4382. // perform size check first, then access fields
  4383. uint8_t *p = pkt->dhcp->options,
  4384. *end = (uint8_t *) &pkt->raw.ptr[pkt->raw.len];
  4385. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4386. if (memcmp(&pkt->dhcp->xid, ifp->mac + 2, sizeof(pkt->dhcp->xid))) return;
  4387. while (p + 1 < end && p[0] != 255) { // Parse options RFC-1533 #9
  4388. if (p[0] == 1 && p[1] == sizeof(ifp->mask) && p + 6 < end) { // Mask
  4389. memcpy(&mask, p + 2, sizeof(mask));
  4390. } else if (p[0] == 3 && p[1] == sizeof(ifp->gw) && p + 6 < end) { // GW
  4391. memcpy(&gw, p + 2, sizeof(gw));
  4392. ip = pkt->dhcp->yiaddr;
  4393. } else if (p[0] == 51 && p[1] == 4 && p + 6 < end) { // Lease
  4394. memcpy(&lease, p + 2, sizeof(lease));
  4395. lease = mg_ntohl(lease);
  4396. } else if (p[0] == 53 && p[1] == 1 && p + 6 < end) { // Msg Type
  4397. msgtype = p[2];
  4398. }
  4399. p += p[1] + 2;
  4400. }
  4401. // Process message type, RFC-1533 (9.4); RFC-2131 (3.1, 4)
  4402. if (msgtype == 6 && ifp->ip == ip) { // DHCPNACK, release IP
  4403. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0;
  4404. } else if (msgtype == 2 && ifp->state == MG_TCPIP_STATE_UP && ip && gw &&
  4405. lease) { // DHCPOFFER
  4406. tx_dhcp_request_sel(ifp, ip, pkt->dhcp->siaddr); // select IP, (4.4.1)
  4407. ifp->state = MG_TCPIP_STATE_REQ; // REQUESTING state
  4408. } else if (msgtype == 5) { // DHCPACK
  4409. if (ifp->state == MG_TCPIP_STATE_REQ && ip && gw && lease) { // got an IP
  4410. ifp->lease_expire = ifp->now + lease * 1000;
  4411. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4412. // assume DHCP server = router until ARP resolves
  4413. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4414. ifp->ip = ip, ifp->gw = gw, ifp->mask = mask;
  4415. ifp->state = MG_TCPIP_STATE_READY; // BOUND state
  4416. uint64_t rand;
  4417. mg_random(&rand, sizeof(rand));
  4418. srand((unsigned int) (rand + mg_millis()));
  4419. } else if (ifp->state == MG_TCPIP_STATE_READY && ifp->ip == ip) { // renew
  4420. ifp->lease_expire = ifp->now + lease * 1000;
  4421. MG_INFO(("Lease: %u sec (%lld)", lease, ifp->lease_expire / 1000));
  4422. } // TODO(): accept provided T1/T2 and store server IP for renewal (4.4)
  4423. }
  4424. if (ifp->state != state) onstatechange(ifp);
  4425. }
  4426. // Simple DHCP server that assigns a next IP address: ifp->ip + 1
  4427. static void rx_dhcp_server(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4428. uint8_t op = 0, *p = pkt->dhcp->options,
  4429. *end = (uint8_t *) &pkt->raw.ptr[pkt->raw.len];
  4430. if (end < (uint8_t *) (pkt->dhcp + 1)) return;
  4431. // struct dhcp *req = pkt->dhcp;
  4432. struct dhcp res = {2, 1, 6, 0, 0, 0, 0, 0, 0, 0, 0, {0}, 0, {0}};
  4433. res.yiaddr = ifp->ip;
  4434. ((uint8_t *) (&res.yiaddr))[3]++; // Offer our IP + 1
  4435. while (p + 1 < end && p[0] != 255) { // Parse options
  4436. if (p[0] == 53 && p[1] == 1 && p + 2 < end) { // Message type
  4437. op = p[2];
  4438. }
  4439. p += p[1] + 2;
  4440. }
  4441. if (op == 1 || op == 3) { // DHCP Discover or DHCP Request
  4442. uint8_t msg = op == 1 ? 2 : 5; // Message type: DHCP OFFER or DHCP ACK
  4443. uint8_t opts[] = {
  4444. 53, 1, msg, // Message type
  4445. 1, 4, 0, 0, 0, 0, // Subnet mask
  4446. 54, 4, 0, 0, 0, 0, // Server ID
  4447. 12, 3, 'm', 'i', 'p', // Host name: "mip"
  4448. 51, 4, 255, 255, 255, 255, // Lease time
  4449. 255 // End of options
  4450. };
  4451. memcpy(&res.hwaddr, pkt->dhcp->hwaddr, 6);
  4452. memcpy(opts + 5, &ifp->mask, sizeof(ifp->mask));
  4453. memcpy(opts + 11, &ifp->ip, sizeof(ifp->ip));
  4454. memcpy(&res.options, opts, sizeof(opts));
  4455. res.magic = pkt->dhcp->magic;
  4456. res.xid = pkt->dhcp->xid;
  4457. if (ifp->enable_get_gateway) {
  4458. ifp->gw = res.yiaddr;
  4459. memcpy(ifp->gwmac, pkt->eth->src, sizeof(ifp->gwmac));
  4460. }
  4461. tx_udp(ifp, pkt->eth->src, ifp->ip, mg_htons(67),
  4462. op == 1 ? ~0U : res.yiaddr, mg_htons(68), &res, sizeof(res));
  4463. }
  4464. }
  4465. static void rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4466. struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
  4467. if (c == NULL) {
  4468. // No UDP listener on this port. Should send ICMP, but keep silent.
  4469. } else {
  4470. c->rem.port = pkt->udp->sport;
  4471. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4472. struct connstate *s = (struct connstate *) (c + 1);
  4473. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4474. if (c->recv.len >= MG_MAX_RECV_SIZE) {
  4475. mg_error(c, "max_recv_buf_size reached");
  4476. } else if (c->recv.size - c->recv.len < pkt->pay.len &&
  4477. !mg_iobuf_resize(&c->recv, c->recv.len + pkt->pay.len)) {
  4478. mg_error(c, "oom");
  4479. } else {
  4480. memcpy(&c->recv.buf[c->recv.len], pkt->pay.ptr, pkt->pay.len);
  4481. c->recv.len += pkt->pay.len;
  4482. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4483. }
  4484. }
  4485. }
  4486. static size_t tx_tcp(struct mg_tcpip_if *ifp, uint8_t *dst_mac, uint32_t dst_ip,
  4487. uint8_t flags, uint16_t sport, uint16_t dport,
  4488. uint32_t seq, uint32_t ack, const void *buf, size_t len) {
  4489. struct ip *ip =
  4490. tx_ip(ifp, dst_mac, 6, ifp->ip, dst_ip, sizeof(struct tcp) + len);
  4491. struct tcp *tcp = (struct tcp *) (ip + 1);
  4492. memset(tcp, 0, sizeof(*tcp));
  4493. if (buf != NULL && len) memmove(tcp + 1, buf, len);
  4494. tcp->sport = sport;
  4495. tcp->dport = dport;
  4496. tcp->seq = seq;
  4497. tcp->ack = ack;
  4498. tcp->flags = flags;
  4499. tcp->win = mg_htons(8192);
  4500. tcp->off = (uint8_t) (sizeof(*tcp) / 4 << 4);
  4501. uint32_t cs = 0;
  4502. uint16_t n = (uint16_t) (sizeof(*tcp) + len);
  4503. uint8_t pseudo[] = {0, ip->proto, (uint8_t) (n >> 8), (uint8_t) (n & 255)};
  4504. cs = csumup(cs, tcp, n);
  4505. cs = csumup(cs, &ip->src, sizeof(ip->src));
  4506. cs = csumup(cs, &ip->dst, sizeof(ip->dst));
  4507. cs = csumup(cs, pseudo, sizeof(pseudo));
  4508. tcp->csum = csumfin(cs);
  4509. MG_VERBOSE(("TCP %M:%hu -> %M:%hu fl %x len %u", mg_print_ip4, &ip->src,
  4510. mg_ntohs(tcp->sport), mg_print_ip4, &ip->dst,
  4511. mg_ntohs(tcp->dport), tcp->flags, (int) len));
  4512. // mg_hexdump(ifp->tx.ptr, PDIFF(ifp->tx.ptr, tcp + 1) + len);
  4513. return ether_output(ifp, PDIFF(ifp->tx.ptr, tcp + 1) + len);
  4514. }
  4515. static size_t tx_tcp_pkt(struct mg_tcpip_if *ifp, struct pkt *pkt,
  4516. uint8_t flags, uint32_t seq, const void *buf,
  4517. size_t len) {
  4518. uint32_t delta = (pkt->tcp->flags & (TH_SYN | TH_FIN)) ? 1 : 0;
  4519. return tx_tcp(ifp, pkt->eth->src, pkt->ip->src, flags, pkt->tcp->dport,
  4520. pkt->tcp->sport, seq, mg_htonl(mg_ntohl(pkt->tcp->seq) + delta),
  4521. buf, len);
  4522. }
  4523. static struct mg_connection *accept_conn(struct mg_connection *lsn,
  4524. struct pkt *pkt) {
  4525. struct mg_connection *c = mg_alloc_conn(lsn->mgr);
  4526. if (c == NULL) {
  4527. MG_ERROR(("OOM"));
  4528. return NULL;
  4529. }
  4530. struct connstate *s = (struct connstate *) (c + 1);
  4531. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq);
  4532. memcpy(s->mac, pkt->eth->src, sizeof(s->mac));
  4533. settmout(c, MIP_TTYPE_KEEPALIVE);
  4534. memcpy(c->rem.ip, &pkt->ip->src, sizeof(uint32_t));
  4535. c->rem.port = pkt->tcp->sport;
  4536. MG_DEBUG(("%lu accepted %M", c->id, mg_print_ip_port, &c->rem));
  4537. LIST_ADD_HEAD(struct mg_connection, &lsn->mgr->conns, c);
  4538. c->is_accepted = 1;
  4539. c->is_hexdumping = lsn->is_hexdumping;
  4540. c->pfn = lsn->pfn;
  4541. c->loc = lsn->loc;
  4542. c->pfn_data = lsn->pfn_data;
  4543. c->fn = lsn->fn;
  4544. c->fn_data = lsn->fn_data;
  4545. mg_call(c, MG_EV_OPEN, NULL);
  4546. mg_call(c, MG_EV_ACCEPT, NULL);
  4547. return c;
  4548. }
  4549. static size_t trim_len(struct mg_connection *c, size_t len) {
  4550. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4551. size_t eth_h_len = 14, ip_max_h_len = 24, tcp_max_h_len = 60, udp_h_len = 8;
  4552. size_t max_headers_len =
  4553. eth_h_len + ip_max_h_len + (c->is_udp ? udp_h_len : tcp_max_h_len);
  4554. size_t min_mtu = c->is_udp ? 68 /* RFC-791 */ : max_headers_len - eth_h_len;
  4555. // If the frame exceeds the available buffer, trim the length
  4556. if (len + max_headers_len > ifp->tx.len) {
  4557. len = ifp->tx.len - max_headers_len;
  4558. }
  4559. // Ensure the MTU isn't lower than the minimum allowed value
  4560. if (ifp->mtu < min_mtu) {
  4561. MG_ERROR(("MTU is lower than minimum, capping to %lu", min_mtu));
  4562. ifp->mtu = (uint16_t) min_mtu;
  4563. }
  4564. // If the total packet size exceeds the MTU, trim the length
  4565. if (len + max_headers_len - eth_h_len > ifp->mtu) {
  4566. len = ifp->mtu - max_headers_len + eth_h_len;
  4567. if (c->is_udp) {
  4568. MG_ERROR(("UDP datagram exceeds MTU. Truncating it."));
  4569. }
  4570. }
  4571. return len;
  4572. }
  4573. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  4574. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4575. struct connstate *s = (struct connstate *) (c + 1);
  4576. uint32_t dst_ip = *(uint32_t *) c->rem.ip;
  4577. len = trim_len(c, len);
  4578. if (c->is_udp) {
  4579. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, dst_ip, c->rem.port, buf, len);
  4580. } else {
  4581. size_t sent =
  4582. tx_tcp(ifp, s->mac, dst_ip, TH_PUSH | TH_ACK, c->loc.port, c->rem.port,
  4583. mg_htonl(s->seq), mg_htonl(s->ack), buf, len);
  4584. if (sent == 0) {
  4585. return MG_IO_WAIT;
  4586. } else if (sent == (size_t) -1) {
  4587. return MG_IO_ERR;
  4588. } else {
  4589. s->seq += (uint32_t) len;
  4590. if (s->ttype == MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_KEEPALIVE);
  4591. }
  4592. }
  4593. return (long) len;
  4594. }
  4595. static void read_conn(struct mg_connection *c, struct pkt *pkt) {
  4596. struct connstate *s = (struct connstate *) (c + 1);
  4597. struct mg_iobuf *io = c->is_tls ? &c->rtls : &c->recv;
  4598. uint32_t seq = mg_ntohl(pkt->tcp->seq);
  4599. uint32_t rem_ip;
  4600. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4601. if (pkt->tcp->flags & TH_FIN) {
  4602. // If we initiated the closure, we reply with ACK upon receiving FIN
  4603. // If we didn't initiate it, we reply with FIN as part of the normal TCP
  4604. // closure process
  4605. uint8_t flags = TH_ACK;
  4606. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len + 1);
  4607. if (c->is_draining && s->ttype == MIP_TTYPE_FIN) {
  4608. if (s->seq == mg_htonl(pkt->tcp->ack)) { // Simultaneous closure ?
  4609. s->seq++; // Yes. Increment our SEQ
  4610. } else { // Otherwise,
  4611. s->seq = mg_htonl(pkt->tcp->ack); // Set to peer's ACK
  4612. }
  4613. } else {
  4614. flags |= TH_FIN;
  4615. c->is_draining = 1;
  4616. settmout(c, MIP_TTYPE_FIN);
  4617. }
  4618. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, flags,
  4619. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4620. } else if (pkt->pay.len == 0) {
  4621. // TODO(cpq): handle this peer's ACK
  4622. } else if (seq != s->ack) {
  4623. uint32_t ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  4624. if (s->ack == ack) {
  4625. MG_VERBOSE(("ignoring duplicate pkt"));
  4626. } else {
  4627. MG_VERBOSE(("SEQ != ACK: %x %x %x", seq, s->ack, ack));
  4628. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK,
  4629. c->loc.port, c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "",
  4630. 0);
  4631. }
  4632. } else if (io->size - io->len < pkt->pay.len &&
  4633. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  4634. mg_error(c, "oom");
  4635. } else {
  4636. // Copy TCP payload into the IO buffer. If the connection is plain text,
  4637. // we copy to c->recv. If the connection is TLS, this data is encrypted,
  4638. // therefore we copy that encrypted data to the c->rtls iobuffer instead,
  4639. // and then call mg_tls_recv() to decrypt it. NOTE: mg_tls_recv() will
  4640. // call back mg_io_recv() which grabs raw data from c->rtls
  4641. memcpy(&io->buf[io->len], pkt->pay.ptr, pkt->pay.len);
  4642. io->len += pkt->pay.len;
  4643. MG_VERBOSE(("%lu SEQ %x -> %x", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  4644. // Advance ACK counter
  4645. s->ack = (uint32_t) (mg_htonl(pkt->tcp->seq) + pkt->pay.len);
  4646. #if 0
  4647. // Send ACK immediately
  4648. uint32_t rem_ip;
  4649. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4650. MG_DEBUG((" imm ACK", c->id, mg_htonl(pkt->tcp->seq), s->ack));
  4651. tx_tcp((struct mg_tcpip_if *) c->mgr->priv, s->mac, rem_ip, TH_ACK, c->loc.port,
  4652. c->rem.port, mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4653. #else
  4654. // if not already running, setup a timer to send an ACK later
  4655. if (s->ttype != MIP_TTYPE_ACK) settmout(c, MIP_TTYPE_ACK);
  4656. #endif
  4657. if (c->is_tls && c->is_tls_hs) {
  4658. mg_tls_handshake(c);
  4659. } else if (c->is_tls) {
  4660. // TLS connection. Make room for decrypted data in c->recv
  4661. io = &c->recv;
  4662. if (io->size - io->len < pkt->pay.len &&
  4663. !mg_iobuf_resize(io, io->len + pkt->pay.len)) {
  4664. mg_error(c, "oom");
  4665. } else {
  4666. // Decrypt data directly into c->recv
  4667. long n = mg_tls_recv(c, &io->buf[io->len], io->size - io->len);
  4668. if (n == MG_IO_ERR) {
  4669. mg_error(c, "TLS recv error");
  4670. } else if (n > 0) {
  4671. // Decrypted successfully - trigger MG_EV_READ
  4672. io->len += (size_t) n;
  4673. mg_call(c, MG_EV_READ, &n);
  4674. }
  4675. }
  4676. } else {
  4677. // Plain text connection, data is already in c->recv, trigger
  4678. // MG_EV_READ
  4679. mg_call(c, MG_EV_READ, &pkt->pay.len);
  4680. }
  4681. }
  4682. }
  4683. static void rx_tcp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4684. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4685. struct connstate *s = c == NULL ? NULL : (struct connstate *) (c + 1);
  4686. #if 0
  4687. MG_INFO(("%lu %hhu %d", c ? c->id : 0, pkt->tcp->flags, (int) pkt->pay.len));
  4688. #endif
  4689. if (c != NULL && c->is_connecting && pkt->tcp->flags == (TH_SYN | TH_ACK)) {
  4690. s->seq = mg_ntohl(pkt->tcp->ack), s->ack = mg_ntohl(pkt->tcp->seq) + 1;
  4691. tx_tcp_pkt(ifp, pkt, TH_ACK, pkt->tcp->ack, NULL, 0);
  4692. c->is_connecting = 0; // Client connected
  4693. settmout(c, MIP_TTYPE_KEEPALIVE);
  4694. mg_call(c, MG_EV_CONNECT, NULL); // Let user know
  4695. } else if (c != NULL && c->is_connecting && pkt->tcp->flags != TH_ACK) {
  4696. // mg_hexdump(pkt->raw.ptr, pkt->raw.len);
  4697. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4698. } else if (c != NULL && pkt->tcp->flags & TH_RST) {
  4699. mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  4700. } else if (c != NULL) {
  4701. #if 0
  4702. MG_DEBUG(("%lu %d %M:%hu -> %M:%hu", c->id, (int) pkt->raw.len,
  4703. mg_print_ip4, &pkt->ip->src, mg_ntohs(pkt->tcp->sport),
  4704. mg_print_ip4, &pkt->ip->dst, mg_ntohs(pkt->tcp->dport)));
  4705. mg_hexdump(pkt->pay.ptr, pkt->pay.len);
  4706. #endif
  4707. s->tmiss = 0; // Reset missed keep-alive counter
  4708. if (s->ttype == MIP_TTYPE_KEEPALIVE) // Advance keep-alive timer
  4709. settmout(c,
  4710. MIP_TTYPE_KEEPALIVE); // unless a former ACK timeout is pending
  4711. read_conn(c, pkt); // Override timer with ACK timeout if needed
  4712. } else if ((c = getpeer(ifp->mgr, pkt, true)) == NULL) {
  4713. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4714. } else if (pkt->tcp->flags & TH_RST) {
  4715. if (c->is_accepted) mg_error(c, "peer RST"); // RFC-1122 4.2.2.13
  4716. // ignore RST if not connected
  4717. } else if (pkt->tcp->flags & TH_SYN) {
  4718. // Use peer's source port as ISN, in order to recognise the handshake
  4719. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(pkt->tcp->sport));
  4720. tx_tcp_pkt(ifp, pkt, TH_SYN | TH_ACK, isn, NULL, 0);
  4721. } else if (pkt->tcp->flags & TH_FIN) {
  4722. tx_tcp_pkt(ifp, pkt, TH_FIN | TH_ACK, pkt->tcp->ack, NULL, 0);
  4723. } else if (mg_htonl(pkt->tcp->ack) == mg_htons(pkt->tcp->sport) + 1U) {
  4724. accept_conn(c, pkt);
  4725. } else if (!c->is_accepted) { // no peer
  4726. tx_tcp_pkt(ifp, pkt, TH_RST | TH_ACK, pkt->tcp->ack, NULL, 0);
  4727. } else {
  4728. // MG_VERBOSE(("dropped silently.."));
  4729. }
  4730. }
  4731. static void rx_ip(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4732. if (pkt->ip->frag & IP_MORE_FRAGS_MSK || pkt->ip->frag & IP_FRAG_OFFSET_MSK) {
  4733. if (pkt->ip->proto == 17) pkt->udp = (struct udp *) (pkt->ip + 1);
  4734. if (pkt->ip->proto == 6) pkt->tcp = (struct tcp *) (pkt->ip + 1);
  4735. struct mg_connection *c = getpeer(ifp->mgr, pkt, false);
  4736. if (c) mg_error(c, "Received fragmented packet");
  4737. } else if (pkt->ip->proto == 1) {
  4738. pkt->icmp = (struct icmp *) (pkt->ip + 1);
  4739. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  4740. mkpay(pkt, pkt->icmp + 1);
  4741. rx_icmp(ifp, pkt);
  4742. } else if (pkt->ip->proto == 17) {
  4743. pkt->udp = (struct udp *) (pkt->ip + 1);
  4744. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  4745. mkpay(pkt, pkt->udp + 1);
  4746. MG_VERBOSE(("UDP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  4747. mg_ntohs(pkt->udp->sport), mg_print_ip4, &pkt->ip->dst,
  4748. mg_ntohs(pkt->udp->dport), (int) pkt->pay.len));
  4749. if (ifp->enable_dhcp_client && pkt->udp->dport == mg_htons(68)) {
  4750. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  4751. mkpay(pkt, pkt->dhcp + 1);
  4752. rx_dhcp_client(ifp, pkt);
  4753. } else if (ifp->enable_dhcp_server && pkt->udp->dport == mg_htons(67)) {
  4754. pkt->dhcp = (struct dhcp *) (pkt->udp + 1);
  4755. mkpay(pkt, pkt->dhcp + 1);
  4756. rx_dhcp_server(ifp, pkt);
  4757. } else {
  4758. rx_udp(ifp, pkt);
  4759. }
  4760. } else if (pkt->ip->proto == 6) {
  4761. pkt->tcp = (struct tcp *) (pkt->ip + 1);
  4762. if (pkt->pay.len < sizeof(*pkt->tcp)) return;
  4763. mkpay(pkt, pkt->tcp + 1);
  4764. uint16_t iplen = mg_ntohs(pkt->ip->len);
  4765. uint16_t off = (uint16_t) (sizeof(*pkt->ip) + ((pkt->tcp->off >> 4) * 4U));
  4766. if (iplen >= off) pkt->pay.len = (size_t) (iplen - off);
  4767. MG_VERBOSE(("TCP %M:%hu -> %M:%hu len %u", mg_print_ip4, &pkt->ip->src,
  4768. mg_ntohs(pkt->tcp->sport), mg_print_ip4, &pkt->ip->dst,
  4769. mg_ntohs(pkt->tcp->dport), (int) pkt->pay.len));
  4770. rx_tcp(ifp, pkt);
  4771. }
  4772. }
  4773. static void rx_ip6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
  4774. // MG_DEBUG(("IP %d", (int) len));
  4775. if (pkt->ip6->proto == 1 || pkt->ip6->proto == 58) {
  4776. pkt->icmp = (struct icmp *) (pkt->ip6 + 1);
  4777. if (pkt->pay.len < sizeof(*pkt->icmp)) return;
  4778. mkpay(pkt, pkt->icmp + 1);
  4779. rx_icmp(ifp, pkt);
  4780. } else if (pkt->ip6->proto == 17) {
  4781. pkt->udp = (struct udp *) (pkt->ip6 + 1);
  4782. if (pkt->pay.len < sizeof(*pkt->udp)) return;
  4783. // MG_DEBUG((" UDP %u %u -> %u", len, mg_htons(udp->sport),
  4784. // mg_htons(udp->dport)));
  4785. mkpay(pkt, pkt->udp + 1);
  4786. }
  4787. }
  4788. static void mg_tcpip_rx(struct mg_tcpip_if *ifp, void *buf, size_t len) {
  4789. struct pkt pkt;
  4790. memset(&pkt, 0, sizeof(pkt));
  4791. pkt.raw.ptr = (char *) buf;
  4792. pkt.raw.len = len;
  4793. pkt.eth = (struct eth *) buf;
  4794. // mg_hexdump(buf, len > 16 ? 16: len);
  4795. if (pkt.raw.len < sizeof(*pkt.eth)) return; // Truncated - runt?
  4796. if (ifp->enable_mac_check &&
  4797. memcmp(pkt.eth->dst, ifp->mac, sizeof(pkt.eth->dst)) != 0 &&
  4798. memcmp(pkt.eth->dst, broadcast, sizeof(pkt.eth->dst)) != 0)
  4799. return;
  4800. if (ifp->enable_crc32_check && len > 4) {
  4801. len -= 4; // TODO(scaprile): check on bigendian
  4802. uint32_t crc = mg_crc32(0, (const char *) buf, len);
  4803. if (memcmp((void *) ((size_t) buf + len), &crc, sizeof(crc))) return;
  4804. }
  4805. if (pkt.eth->type == mg_htons(0x806)) {
  4806. pkt.arp = (struct arp *) (pkt.eth + 1);
  4807. if (sizeof(*pkt.eth) + sizeof(*pkt.arp) > pkt.raw.len) return; // Truncated
  4808. rx_arp(ifp, &pkt);
  4809. } else if (pkt.eth->type == mg_htons(0x86dd)) {
  4810. pkt.ip6 = (struct ip6 *) (pkt.eth + 1);
  4811. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip6)) return; // Truncated
  4812. if ((pkt.ip6->ver >> 4) != 0x6) return; // Not IP
  4813. mkpay(&pkt, pkt.ip6 + 1);
  4814. rx_ip6(ifp, &pkt);
  4815. } else if (pkt.eth->type == mg_htons(0x800)) {
  4816. pkt.ip = (struct ip *) (pkt.eth + 1);
  4817. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  4818. // Truncate frame to what IP header tells us
  4819. if ((size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth) < pkt.raw.len) {
  4820. pkt.raw.len = (size_t) mg_ntohs(pkt.ip->len) + sizeof(struct eth);
  4821. }
  4822. if (pkt.raw.len < sizeof(*pkt.eth) + sizeof(*pkt.ip)) return; // Truncated
  4823. if ((pkt.ip->ver >> 4) != 4) return; // Not IP
  4824. mkpay(&pkt, pkt.ip + 1);
  4825. rx_ip(ifp, &pkt);
  4826. } else {
  4827. MG_DEBUG(("Unknown eth type %x", mg_htons(pkt.eth->type)));
  4828. if (mg_log_level >= MG_LL_VERBOSE) mg_hexdump(buf, len >= 32 ? 32 : len);
  4829. }
  4830. }
  4831. static void mg_tcpip_poll(struct mg_tcpip_if *ifp, uint64_t uptime_ms) {
  4832. if (ifp == NULL || ifp->driver == NULL) return;
  4833. bool expired_1000ms = mg_timer_expired(&ifp->timer_1000ms, 1000, uptime_ms);
  4834. ifp->now = uptime_ms;
  4835. // Handle physical interface up/down status
  4836. if (expired_1000ms && ifp->driver->up) {
  4837. bool up = ifp->driver->up(ifp);
  4838. bool current = ifp->state != MG_TCPIP_STATE_DOWN;
  4839. if (up != current) {
  4840. ifp->state = up == false ? MG_TCPIP_STATE_DOWN
  4841. : ifp->enable_dhcp_client ? MG_TCPIP_STATE_UP
  4842. : MG_TCPIP_STATE_READY;
  4843. if (!up && ifp->enable_dhcp_client) ifp->ip = 0;
  4844. onstatechange(ifp);
  4845. }
  4846. }
  4847. if (ifp->state == MG_TCPIP_STATE_DOWN) return;
  4848. // DHCP RFC-2131 (4.4)
  4849. if (ifp->state == MG_TCPIP_STATE_UP && expired_1000ms) {
  4850. tx_dhcp_discover(ifp); // INIT (4.4.1)
  4851. } else if (expired_1000ms && ifp->state == MG_TCPIP_STATE_READY &&
  4852. ifp->lease_expire > 0) { // BOUND / RENEWING / REBINDING
  4853. if (ifp->now >= ifp->lease_expire) {
  4854. ifp->state = MG_TCPIP_STATE_UP, ifp->ip = 0; // expired, release IP
  4855. onstatechange(ifp);
  4856. } else if (ifp->now + 30UL * 60UL * 1000UL > ifp->lease_expire &&
  4857. ((ifp->now / 1000) % 60) == 0) {
  4858. // hack: 30 min before deadline, try to rebind (4.3.6) every min
  4859. tx_dhcp_request_re(ifp, (uint8_t *) broadcast, ifp->ip, 0xffffffff);
  4860. } // TODO(): Handle T1 (RENEWING) and T2 (REBINDING) (4.4.5)
  4861. }
  4862. // Read data from the network
  4863. if (ifp->driver->rx != NULL) { // Polling driver. We must call it
  4864. size_t len =
  4865. ifp->driver->rx(ifp->recv_queue.buf, ifp->recv_queue.size, ifp);
  4866. if (len > 0) {
  4867. ifp->nrecv++;
  4868. mg_tcpip_rx(ifp, ifp->recv_queue.buf, len);
  4869. }
  4870. } else { // Interrupt-based driver. Fills recv queue itself
  4871. char *buf;
  4872. size_t len = mg_queue_next(&ifp->recv_queue, &buf);
  4873. if (len > 0) {
  4874. mg_tcpip_rx(ifp, buf, len);
  4875. mg_queue_del(&ifp->recv_queue, len);
  4876. }
  4877. }
  4878. // Process timeouts
  4879. for (struct mg_connection *c = ifp->mgr->conns; c != NULL; c = c->next) {
  4880. if (c->is_udp || c->is_listening || c->is_resolving) continue;
  4881. struct connstate *s = (struct connstate *) (c + 1);
  4882. uint32_t rem_ip;
  4883. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4884. if (uptime_ms > s->timer) {
  4885. if (s->ttype == MIP_TTYPE_ACK) {
  4886. MG_VERBOSE(("%lu ack %x %x", c->id, s->seq, s->ack));
  4887. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4888. mg_htonl(s->seq), mg_htonl(s->ack), "", 0);
  4889. } else if (s->ttype == MIP_TTYPE_ARP) {
  4890. mg_error(c, "ARP timeout");
  4891. } else if (s->ttype == MIP_TTYPE_SYN) {
  4892. mg_error(c, "Connection timeout");
  4893. } else if (s->ttype == MIP_TTYPE_FIN) {
  4894. c->is_closing = 1;
  4895. continue;
  4896. } else {
  4897. if (s->tmiss++ > 2) {
  4898. mg_error(c, "keepalive");
  4899. } else {
  4900. MG_VERBOSE(("%lu keepalive", c->id));
  4901. tx_tcp(ifp, s->mac, rem_ip, TH_ACK, c->loc.port, c->rem.port,
  4902. mg_htonl(s->seq - 1), mg_htonl(s->ack), "", 0);
  4903. }
  4904. }
  4905. settmout(c, MIP_TTYPE_KEEPALIVE);
  4906. }
  4907. }
  4908. }
  4909. // This function executes in interrupt context, thus it should copy data
  4910. // somewhere fast. Note that newlib's malloc is not thread safe, thus use
  4911. // our lock-free queue with preallocated buffer to copy data and return asap
  4912. void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) {
  4913. char *p;
  4914. if (mg_queue_book(&ifp->recv_queue, &p, len) >= len) {
  4915. memcpy(p, buf, len);
  4916. mg_queue_add(&ifp->recv_queue, len);
  4917. ifp->nrecv++;
  4918. } else {
  4919. ifp->ndrop++;
  4920. }
  4921. }
  4922. void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) {
  4923. // If MAC address is not set, make a random one
  4924. if (ifp->mac[0] == 0 && ifp->mac[1] == 0 && ifp->mac[2] == 0 &&
  4925. ifp->mac[3] == 0 && ifp->mac[4] == 0 && ifp->mac[5] == 0) {
  4926. ifp->mac[0] = 0x02; // Locally administered, unicast
  4927. mg_random(&ifp->mac[1], sizeof(ifp->mac) - 1);
  4928. MG_INFO(("MAC not set. Generated random: %M", mg_print_mac, ifp->mac));
  4929. }
  4930. if (ifp->driver->init && !ifp->driver->init(ifp)) {
  4931. MG_ERROR(("driver init failed"));
  4932. } else {
  4933. size_t framesize = 1540;
  4934. ifp->tx.ptr = (char *) calloc(1, framesize), ifp->tx.len = framesize;
  4935. if (ifp->recv_queue.size == 0)
  4936. ifp->recv_queue.size = ifp->driver->rx ? framesize : 8192;
  4937. ifp->recv_queue.buf = (char *) calloc(1, ifp->recv_queue.size);
  4938. ifp->timer_1000ms = mg_millis();
  4939. mgr->priv = ifp;
  4940. ifp->mgr = mgr;
  4941. ifp->mtu = MG_TCPIP_MTU_DEFAULT;
  4942. mgr->extraconnsize = sizeof(struct connstate);
  4943. if (ifp->ip == 0) ifp->enable_dhcp_client = true;
  4944. memset(ifp->gwmac, 255, sizeof(ifp->gwmac)); // Set to broadcast
  4945. mg_random(&ifp->eport, sizeof(ifp->eport)); // Random from 0 to 65535
  4946. ifp->eport |= MG_EPHEMERAL_PORT_BASE; // Random from
  4947. // MG_EPHEMERAL_PORT_BASE to 65535
  4948. if (ifp->tx.ptr == NULL || ifp->recv_queue.buf == NULL) MG_ERROR(("OOM"));
  4949. }
  4950. }
  4951. void mg_tcpip_free(struct mg_tcpip_if *ifp) {
  4952. free(ifp->recv_queue.buf);
  4953. free((char *) ifp->tx.ptr);
  4954. }
  4955. static void send_syn(struct mg_connection *c) {
  4956. struct connstate *s = (struct connstate *) (c + 1);
  4957. uint32_t isn = mg_htonl((uint32_t) mg_ntohs(c->loc.port));
  4958. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4959. uint32_t rem_ip;
  4960. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4961. tx_tcp(ifp, s->mac, rem_ip, TH_SYN, c->loc.port, c->rem.port, isn, 0, NULL,
  4962. 0);
  4963. }
  4964. void mg_connect_resolved(struct mg_connection *c) {
  4965. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  4966. uint32_t rem_ip;
  4967. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  4968. c->is_resolving = 0;
  4969. if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
  4970. memcpy(c->loc.ip, &ifp->ip, sizeof(uint32_t));
  4971. c->loc.port = mg_htons(ifp->eport++);
  4972. MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
  4973. &c->rem));
  4974. mg_call(c, MG_EV_RESOLVE, NULL);
  4975. if (c->is_udp && (rem_ip == 0xffffffff || rem_ip == (ifp->ip | ~ifp->mask))) {
  4976. struct connstate *s = (struct connstate *) (c + 1);
  4977. memset(s->mac, 0xFF, sizeof(s->mac)); // global or local broadcast
  4978. } else if (((rem_ip & ifp->mask) == (ifp->ip & ifp->mask))) {
  4979. // If we're in the same LAN, fire an ARP lookup.
  4980. MG_DEBUG(("%lu ARP lookup...", c->id));
  4981. arp_ask(ifp, rem_ip);
  4982. settmout(c, MIP_TTYPE_ARP);
  4983. c->is_arplooking = 1;
  4984. c->is_connecting = 1;
  4985. } else if ((*((uint8_t *) &rem_ip) & 0xE0) == 0xE0) {
  4986. struct connstate *s = (struct connstate *) (c + 1); // 224 to 239, E0 to EF
  4987. uint8_t mcastp[3] = {0x01, 0x00, 0x5E}; // multicast group
  4988. memcpy(s->mac, mcastp, 3);
  4989. memcpy(s->mac + 3, ((uint8_t *) &rem_ip) + 1, 3); // 23 LSb
  4990. s->mac[3] &= 0x7F;
  4991. } else {
  4992. struct connstate *s = (struct connstate *) (c + 1);
  4993. memcpy(s->mac, ifp->gwmac, sizeof(ifp->gwmac));
  4994. if (c->is_udp) {
  4995. mg_call(c, MG_EV_CONNECT, NULL);
  4996. } else {
  4997. send_syn(c);
  4998. settmout(c, MIP_TTYPE_SYN);
  4999. c->is_connecting = 1;
  5000. }
  5001. }
  5002. }
  5003. bool mg_open_listener(struct mg_connection *c, const char *url) {
  5004. c->loc.port = mg_htons(mg_url_port(url));
  5005. return true;
  5006. }
  5007. static void write_conn(struct mg_connection *c) {
  5008. long len = c->is_tls ? mg_tls_send(c, c->send.buf, c->send.len)
  5009. : mg_io_send(c, c->send.buf, c->send.len);
  5010. if (len == MG_IO_ERR) {
  5011. mg_error(c, "tx err");
  5012. } else if (len > 0) {
  5013. mg_iobuf_del(&c->send, 0, (size_t) len);
  5014. mg_call(c, MG_EV_WRITE, &len);
  5015. }
  5016. }
  5017. static void init_closure(struct mg_connection *c) {
  5018. struct connstate *s = (struct connstate *) (c + 1);
  5019. if (c->is_udp == false && c->is_listening == false &&
  5020. c->is_connecting == false) { // For TCP conns,
  5021. struct mg_tcpip_if *ifp =
  5022. (struct mg_tcpip_if *) c->mgr->priv; // send TCP FIN
  5023. uint32_t rem_ip;
  5024. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5025. tx_tcp(ifp, s->mac, rem_ip, TH_FIN | TH_ACK, c->loc.port, c->rem.port,
  5026. mg_htonl(s->seq), mg_htonl(s->ack), NULL, 0);
  5027. settmout(c, MIP_TTYPE_FIN);
  5028. }
  5029. }
  5030. static void close_conn(struct mg_connection *c) {
  5031. struct connstate *s = (struct connstate *) (c + 1);
  5032. mg_iobuf_free(&s->raw); // For TLS connections, release raw data
  5033. mg_close_conn(c);
  5034. }
  5035. static bool can_write(struct mg_connection *c) {
  5036. return c->is_connecting == 0 && c->is_resolving == 0 && c->send.len > 0 &&
  5037. c->is_tls_hs == 0 && c->is_arplooking == 0;
  5038. }
  5039. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  5040. struct mg_connection *c, *tmp;
  5041. uint64_t now = mg_millis();
  5042. mg_tcpip_poll((struct mg_tcpip_if *) mgr->priv, now);
  5043. mg_timer_poll(&mgr->timers, now);
  5044. for (c = mgr->conns; c != NULL; c = tmp) {
  5045. tmp = c->next;
  5046. struct connstate *s = (struct connstate *) (c + 1);
  5047. mg_call(c, MG_EV_POLL, &now);
  5048. MG_VERBOSE(("%lu .. %c%c%c%c%c", c->id, c->is_tls ? 'T' : 't',
  5049. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  5050. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  5051. if (can_write(c)) write_conn(c);
  5052. if (c->is_draining && c->send.len == 0 && s->ttype != MIP_TTYPE_FIN)
  5053. init_closure(c);
  5054. if (c->is_closing) close_conn(c);
  5055. }
  5056. (void) ms;
  5057. }
  5058. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  5059. struct mg_tcpip_if *ifp = (struct mg_tcpip_if *) c->mgr->priv;
  5060. bool res = false;
  5061. uint32_t rem_ip;
  5062. memcpy(&rem_ip, c->rem.ip, sizeof(uint32_t));
  5063. if (ifp->ip == 0 || ifp->state != MG_TCPIP_STATE_READY) {
  5064. mg_error(c, "net down");
  5065. } else if (c->is_udp) {
  5066. struct connstate *s = (struct connstate *) (c + 1);
  5067. len = trim_len(c, len); // Trimming length if necessary
  5068. tx_udp(ifp, s->mac, ifp->ip, c->loc.port, rem_ip, c->rem.port, buf, len);
  5069. res = true;
  5070. } else {
  5071. res = mg_iobuf_add(&c->send, c->send.len, buf, len);
  5072. }
  5073. return res;
  5074. }
  5075. #endif // MG_ENABLE_TCPIP
  5076. #ifdef MG_ENABLE_LINES
  5077. #line 1 "src/ota_dummy.c"
  5078. #endif
  5079. #if MG_OTA == MG_OTA_NONE
  5080. bool mg_ota_begin(size_t new_firmware_size) {
  5081. (void) new_firmware_size;
  5082. return true;
  5083. }
  5084. bool mg_ota_write(const void *buf, size_t len) {
  5085. (void) buf, (void) len;
  5086. return true;
  5087. }
  5088. bool mg_ota_end(void) {
  5089. return true;
  5090. }
  5091. bool mg_ota_commit(void) {
  5092. return true;
  5093. }
  5094. bool mg_ota_rollback(void) {
  5095. return true;
  5096. }
  5097. int mg_ota_status(int fw) {
  5098. (void) fw;
  5099. return 0;
  5100. }
  5101. uint32_t mg_ota_crc32(int fw) {
  5102. (void) fw;
  5103. return 0;
  5104. }
  5105. uint32_t mg_ota_timestamp(int fw) {
  5106. (void) fw;
  5107. return 0;
  5108. }
  5109. size_t mg_ota_size(int fw) {
  5110. (void) fw;
  5111. return 0;
  5112. }
  5113. MG_IRAM void mg_ota_boot(void) {
  5114. }
  5115. #endif
  5116. #ifdef MG_ENABLE_LINES
  5117. #line 1 "src/ota_flash.c"
  5118. #endif
  5119. // This OTA implementation uses the internal flash API outlined in device.h
  5120. // It splits flash into 2 equal partitions, and stores OTA status in the
  5121. // last sector of the partition.
  5122. #if MG_OTA == MG_OTA_FLASH
  5123. #define MG_OTADATA_KEY 0xb07afed0
  5124. static char *s_addr; // Current address to write to
  5125. static size_t s_size; // Firmware size to flash. In-progress indicator
  5126. static uint32_t s_crc32; // Firmware checksum
  5127. struct mg_otadata {
  5128. uint32_t crc32, size, timestamp, status;
  5129. };
  5130. bool mg_ota_begin(size_t new_firmware_size) {
  5131. bool ok = false;
  5132. if (s_size) {
  5133. MG_ERROR(("OTA already in progress. Call mg_ota_end()"));
  5134. } else {
  5135. size_t half = mg_flash_size() / 2, max = half - mg_flash_sector_size();
  5136. s_crc32 = 0;
  5137. s_addr = (char *) mg_flash_start() + half;
  5138. MG_DEBUG(("Firmware %lu bytes, max %lu", new_firmware_size, max));
  5139. if (new_firmware_size < max) {
  5140. ok = true;
  5141. s_size = new_firmware_size;
  5142. MG_INFO(("Starting OTA, firmware size %lu", s_size));
  5143. } else {
  5144. MG_ERROR(("Firmware %lu is too big to fit %lu", new_firmware_size, max));
  5145. }
  5146. }
  5147. return ok;
  5148. }
  5149. bool mg_ota_write(const void *buf, size_t len) {
  5150. bool ok = false;
  5151. if (s_size == 0) {
  5152. MG_ERROR(("OTA is not started, call mg_ota_begin()"));
  5153. } else {
  5154. size_t align = mg_flash_write_align();
  5155. size_t len_aligned_down = MG_ROUND_DOWN(len, align);
  5156. if (len_aligned_down) ok = mg_flash_write(s_addr, buf, len_aligned_down);
  5157. if (len_aligned_down < len) {
  5158. size_t left = len - len_aligned_down;
  5159. char tmp[align];
  5160. memset(tmp, 0xff, sizeof(tmp));
  5161. memcpy(tmp, (char *) buf + len_aligned_down, left);
  5162. ok = mg_flash_write(s_addr + len_aligned_down, tmp, sizeof(tmp));
  5163. }
  5164. s_crc32 = mg_crc32(s_crc32, (char *) buf, len); // Update CRC
  5165. MG_DEBUG(("%#x %p %lu -> %d", s_addr - len, buf, len, ok));
  5166. s_addr += len;
  5167. }
  5168. return ok;
  5169. }
  5170. MG_IRAM static uint32_t mg_fwkey(int fw) {
  5171. uint32_t key = MG_OTADATA_KEY + fw;
  5172. int bank = mg_flash_bank();
  5173. if (bank == 2 && fw == MG_FIRMWARE_PREVIOUS) key--;
  5174. if (bank == 2 && fw == MG_FIRMWARE_CURRENT) key++;
  5175. return key;
  5176. }
  5177. bool mg_ota_end(void) {
  5178. char *base = (char *) mg_flash_start() + mg_flash_size() / 2;
  5179. bool ok = false;
  5180. if (s_size) {
  5181. size_t size = s_addr - base;
  5182. uint32_t crc32 = mg_crc32(0, base, s_size);
  5183. if (size == s_size && crc32 == s_crc32) {
  5184. uint32_t now = (uint32_t) (mg_now() / 1000);
  5185. struct mg_otadata od = {crc32, size, now, MG_OTA_FIRST_BOOT};
  5186. uint32_t key = mg_fwkey(MG_FIRMWARE_PREVIOUS);
  5187. ok = mg_flash_save(NULL, key, &od, sizeof(od));
  5188. }
  5189. MG_DEBUG(("CRC: %x/%x, size: %lu/%lu, status: %s", s_crc32, crc32, s_size,
  5190. size, ok ? "ok" : "fail"));
  5191. s_size = 0;
  5192. if (ok) ok = mg_flash_swap_bank();
  5193. }
  5194. MG_INFO(("Finishing OTA: %s", ok ? "ok" : "fail"));
  5195. return ok;
  5196. }
  5197. MG_IRAM static struct mg_otadata mg_otadata(int fw) {
  5198. uint32_t key = mg_fwkey(fw);
  5199. struct mg_otadata od = {};
  5200. MG_INFO(("Loading %s OTA data", fw == MG_FIRMWARE_CURRENT ? "curr" : "prev"));
  5201. mg_flash_load(NULL, key, &od, sizeof(od));
  5202. // MG_DEBUG(("Loaded OTA data. fw %d, bank %d, key %p", fw, bank, key));
  5203. // mg_hexdump(&od, sizeof(od));
  5204. return od;
  5205. }
  5206. int mg_ota_status(int fw) {
  5207. struct mg_otadata od = mg_otadata(fw);
  5208. return od.status;
  5209. }
  5210. uint32_t mg_ota_crc32(int fw) {
  5211. struct mg_otadata od = mg_otadata(fw);
  5212. return od.crc32;
  5213. }
  5214. uint32_t mg_ota_timestamp(int fw) {
  5215. struct mg_otadata od = mg_otadata(fw);
  5216. return od.timestamp;
  5217. }
  5218. size_t mg_ota_size(int fw) {
  5219. struct mg_otadata od = mg_otadata(fw);
  5220. return od.size;
  5221. }
  5222. MG_IRAM bool mg_ota_commit(void) {
  5223. bool ok = true;
  5224. struct mg_otadata od = mg_otadata(MG_FIRMWARE_CURRENT);
  5225. if (od.status != MG_OTA_COMMITTED) {
  5226. od.status = MG_OTA_COMMITTED;
  5227. MG_INFO(("Committing current firmware, OD size %lu", sizeof(od)));
  5228. ok = mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &od, sizeof(od));
  5229. }
  5230. return ok;
  5231. }
  5232. bool mg_ota_rollback(void) {
  5233. MG_DEBUG(("Rolling firmware back"));
  5234. if (mg_flash_bank() == 0) {
  5235. // No dual bank support. Mark previous firmware as FIRST_BOOT
  5236. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5237. prev.status = MG_OTA_FIRST_BOOT;
  5238. return mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &prev,
  5239. sizeof(prev));
  5240. } else {
  5241. return mg_flash_swap_bank();
  5242. }
  5243. }
  5244. MG_IRAM void mg_ota_boot(void) {
  5245. MG_INFO(("Booting. Flash bank: %d", mg_flash_bank()));
  5246. struct mg_otadata curr = mg_otadata(MG_FIRMWARE_CURRENT);
  5247. struct mg_otadata prev = mg_otadata(MG_FIRMWARE_PREVIOUS);
  5248. if (curr.status == MG_OTA_FIRST_BOOT) {
  5249. if (prev.status == MG_OTA_UNAVAILABLE) {
  5250. MG_INFO(("Setting previous firmware state to committed"));
  5251. prev.status = MG_OTA_COMMITTED;
  5252. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_PREVIOUS), &prev, sizeof(prev));
  5253. }
  5254. curr.status = MG_OTA_UNCOMMITTED;
  5255. MG_INFO(("First boot, setting status to UNCOMMITTED"));
  5256. mg_flash_save(NULL, mg_fwkey(MG_FIRMWARE_CURRENT), &curr, sizeof(curr));
  5257. } else if (prev.status == MG_OTA_FIRST_BOOT && mg_flash_bank() == 0) {
  5258. // Swap paritions. Pray power does not disappear
  5259. size_t fs = mg_flash_size(), ss = mg_flash_sector_size();
  5260. char *partition1 = mg_flash_start();
  5261. char *partition2 = mg_flash_start() + fs / 2;
  5262. size_t ofs, max = fs / 2 - ss; // Set swap size to the whole partition
  5263. if (curr.status != MG_OTA_UNAVAILABLE &&
  5264. prev.status != MG_OTA_UNAVAILABLE) {
  5265. // We know exact sizes of both firmwares.
  5266. // Shrink swap size to the MAX(firmware1, firmware2)
  5267. size_t sz = curr.size > prev.size ? curr.size : prev.size;
  5268. if (sz > 0 && sz < max) max = sz;
  5269. }
  5270. // MG_OTA_FIRST_BOOT -> MG_OTA_UNCOMMITTED
  5271. prev.status = MG_OTA_UNCOMMITTED;
  5272. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_CURRENT, &prev,
  5273. sizeof(prev));
  5274. mg_flash_save(NULL, MG_OTADATA_KEY + MG_FIRMWARE_PREVIOUS, &curr,
  5275. sizeof(curr));
  5276. MG_INFO(("Swapping partitions, size %u (%u sectors)", max, max / ss));
  5277. MG_INFO(("Do NOT power off..."));
  5278. mg_log_level = MG_LL_NONE;
  5279. // We use the last sector of partition2 for OTA data/config storage
  5280. // Therefore we can use last sector of partition1 for swapping
  5281. char *tmpsector = partition1 + fs / 2 - ss; // Last sector of partition1
  5282. (void) tmpsector;
  5283. for (ofs = 0; ofs < max; ofs += ss) {
  5284. // mg_flash_erase(tmpsector);
  5285. mg_flash_write(tmpsector, partition1 + ofs, ss);
  5286. // mg_flash_erase(partition1 + ofs);
  5287. mg_flash_write(partition1 + ofs, partition2 + ofs, ss);
  5288. // mg_flash_erase(partition2 + ofs);
  5289. mg_flash_write(partition2 + ofs, tmpsector, ss);
  5290. }
  5291. mg_device_reset();
  5292. }
  5293. }
  5294. #endif
  5295. #ifdef MG_ENABLE_LINES
  5296. #line 1 "src/printf.c"
  5297. #endif
  5298. size_t mg_queue_vprintf(struct mg_queue *q, const char *fmt, va_list *ap) {
  5299. size_t len = mg_snprintf(NULL, 0, fmt, ap);
  5300. char *buf;
  5301. if (len == 0 || mg_queue_book(q, &buf, len + 1) < len + 1) {
  5302. len = 0; // Nah. Not enough space
  5303. } else {
  5304. len = mg_vsnprintf((char *) buf, len + 1, fmt, ap);
  5305. mg_queue_add(q, len);
  5306. }
  5307. return len;
  5308. }
  5309. size_t mg_queue_printf(struct mg_queue *q, const char *fmt, ...) {
  5310. va_list ap;
  5311. size_t len;
  5312. va_start(ap, fmt);
  5313. len = mg_queue_vprintf(q, fmt, &ap);
  5314. va_end(ap);
  5315. return len;
  5316. }
  5317. static void mg_pfn_iobuf_private(char ch, void *param, bool expand) {
  5318. struct mg_iobuf *io = (struct mg_iobuf *) param;
  5319. if (expand && io->len + 2 > io->size) mg_iobuf_resize(io, io->len + 2);
  5320. if (io->len + 2 <= io->size) {
  5321. io->buf[io->len++] = (uint8_t) ch;
  5322. io->buf[io->len] = 0;
  5323. } else if (io->len < io->size) {
  5324. io->buf[io->len++] = 0; // Guarantee to 0-terminate
  5325. }
  5326. }
  5327. static void mg_putchar_iobuf_static(char ch, void *param) {
  5328. mg_pfn_iobuf_private(ch, param, false);
  5329. }
  5330. void mg_pfn_iobuf(char ch, void *param) {
  5331. mg_pfn_iobuf_private(ch, param, true);
  5332. }
  5333. size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap) {
  5334. struct mg_iobuf io = {(uint8_t *) buf, len, 0, 0};
  5335. size_t n = mg_vxprintf(mg_putchar_iobuf_static, &io, fmt, ap);
  5336. if (n < len) buf[n] = '\0';
  5337. return n;
  5338. }
  5339. size_t mg_snprintf(char *buf, size_t len, const char *fmt, ...) {
  5340. va_list ap;
  5341. size_t n;
  5342. va_start(ap, fmt);
  5343. n = mg_vsnprintf(buf, len, fmt, &ap);
  5344. va_end(ap);
  5345. return n;
  5346. }
  5347. char *mg_vmprintf(const char *fmt, va_list *ap) {
  5348. struct mg_iobuf io = {0, 0, 0, 256};
  5349. mg_vxprintf(mg_pfn_iobuf, &io, fmt, ap);
  5350. return (char *) io.buf;
  5351. }
  5352. char *mg_mprintf(const char *fmt, ...) {
  5353. char *s;
  5354. va_list ap;
  5355. va_start(ap, fmt);
  5356. s = mg_vmprintf(fmt, &ap);
  5357. va_end(ap);
  5358. return s;
  5359. }
  5360. void mg_pfn_stdout(char c, void *param) {
  5361. putchar(c);
  5362. (void) param;
  5363. }
  5364. static size_t print_ip4(void (*out)(char, void *), void *arg, uint8_t *p) {
  5365. return mg_xprintf(out, arg, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  5366. }
  5367. static size_t print_ip6(void (*out)(char, void *), void *arg, uint16_t *p) {
  5368. return mg_xprintf(out, arg, "[%x:%x:%x:%x:%x:%x:%x:%x]", mg_ntohs(p[0]),
  5369. mg_ntohs(p[1]), mg_ntohs(p[2]), mg_ntohs(p[3]),
  5370. mg_ntohs(p[4]), mg_ntohs(p[5]), mg_ntohs(p[6]),
  5371. mg_ntohs(p[7]));
  5372. }
  5373. size_t mg_print_ip4(void (*out)(char, void *), void *arg, va_list *ap) {
  5374. uint8_t *p = va_arg(*ap, uint8_t *);
  5375. return print_ip4(out, arg, p);
  5376. }
  5377. size_t mg_print_ip6(void (*out)(char, void *), void *arg, va_list *ap) {
  5378. uint16_t *p = va_arg(*ap, uint16_t *);
  5379. return print_ip6(out, arg, p);
  5380. }
  5381. size_t mg_print_ip(void (*out)(char, void *), void *arg, va_list *ap) {
  5382. struct mg_addr *addr = va_arg(*ap, struct mg_addr *);
  5383. if (addr->is_ip6) return print_ip6(out, arg, (uint16_t *) addr->ip);
  5384. return print_ip4(out, arg, (uint8_t *) &addr->ip);
  5385. }
  5386. size_t mg_print_ip_port(void (*out)(char, void *), void *arg, va_list *ap) {
  5387. struct mg_addr *a = va_arg(*ap, struct mg_addr *);
  5388. return mg_xprintf(out, arg, "%M:%hu", mg_print_ip, a, mg_ntohs(a->port));
  5389. }
  5390. size_t mg_print_mac(void (*out)(char, void *), void *arg, va_list *ap) {
  5391. uint8_t *p = va_arg(*ap, uint8_t *);
  5392. return mg_xprintf(out, arg, "%02x:%02x:%02x:%02x:%02x:%02x", p[0], p[1], p[2],
  5393. p[3], p[4], p[5]);
  5394. }
  5395. static char mg_esc(int c, bool esc) {
  5396. const char *p, *esc1 = "\b\f\n\r\t\\\"", *esc2 = "bfnrt\\\"";
  5397. for (p = esc ? esc1 : esc2; *p != '\0'; p++) {
  5398. if (*p == c) return esc ? esc2[p - esc1] : esc1[p - esc2];
  5399. }
  5400. return 0;
  5401. }
  5402. static char mg_escape(int c) {
  5403. return mg_esc(c, true);
  5404. }
  5405. static size_t qcpy(void (*out)(char, void *), void *ptr, char *buf,
  5406. size_t len) {
  5407. size_t i = 0, extra = 0;
  5408. for (i = 0; i < len && buf[i] != '\0'; i++) {
  5409. char c = mg_escape(buf[i]);
  5410. if (c) {
  5411. out('\\', ptr), out(c, ptr), extra++;
  5412. } else {
  5413. out(buf[i], ptr);
  5414. }
  5415. }
  5416. return i + extra;
  5417. }
  5418. static size_t bcpy(void (*out)(char, void *), void *arg, uint8_t *buf,
  5419. size_t len) {
  5420. size_t i, j, n = 0;
  5421. const char *t =
  5422. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5423. for (i = 0; i < len; i += 3) {
  5424. uint8_t c1 = buf[i], c2 = i + 1 < len ? buf[i + 1] : 0,
  5425. c3 = i + 2 < len ? buf[i + 2] : 0;
  5426. char tmp[4] = {t[c1 >> 2], t[(c1 & 3) << 4 | (c2 >> 4)], '=', '='};
  5427. if (i + 1 < len) tmp[2] = t[(c2 & 15) << 2 | (c3 >> 6)];
  5428. if (i + 2 < len) tmp[3] = t[c3 & 63];
  5429. for (j = 0; j < sizeof(tmp) && tmp[j] != '\0'; j++) out(tmp[j], arg);
  5430. n += j;
  5431. }
  5432. return n;
  5433. }
  5434. size_t mg_print_hex(void (*out)(char, void *), void *arg, va_list *ap) {
  5435. size_t bl = (size_t) va_arg(*ap, int);
  5436. uint8_t *p = va_arg(*ap, uint8_t *);
  5437. const char *hex = "0123456789abcdef";
  5438. size_t j;
  5439. for (j = 0; j < bl; j++) {
  5440. out(hex[(p[j] >> 4) & 0x0F], arg);
  5441. out(hex[p[j] & 0x0F], arg);
  5442. }
  5443. return 2 * bl;
  5444. }
  5445. size_t mg_print_base64(void (*out)(char, void *), void *arg, va_list *ap) {
  5446. size_t len = (size_t) va_arg(*ap, int);
  5447. uint8_t *buf = va_arg(*ap, uint8_t *);
  5448. return bcpy(out, arg, buf, len);
  5449. }
  5450. size_t mg_print_esc(void (*out)(char, void *), void *arg, va_list *ap) {
  5451. size_t len = (size_t) va_arg(*ap, int);
  5452. char *p = va_arg(*ap, char *);
  5453. if (len == 0) len = p == NULL ? 0 : strlen(p);
  5454. return qcpy(out, arg, p, len);
  5455. }
  5456. #ifdef MG_ENABLE_LINES
  5457. #line 1 "src/queue.c"
  5458. #endif
  5459. #if (defined(__GNUC__) && (__GNUC__ > 4) || \
  5460. (defined(__GNUC_MINOR__) && __GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \
  5461. defined(__clang__)
  5462. #define MG_MEMORY_BARRIER() __sync_synchronize()
  5463. #elif defined(_MSC_VER) && _MSC_VER >= 1700
  5464. #define MG_MEMORY_BARRIER() MemoryBarrier()
  5465. #elif !defined(MG_MEMORY_BARRIER)
  5466. #define MG_MEMORY_BARRIER()
  5467. #endif
  5468. // Every message in a queue is prepended by a 32-bit message length (ML).
  5469. // If ML is 0, then it is the end, and reader must wrap to the beginning.
  5470. //
  5471. // Queue when q->tail <= q->head:
  5472. // |----- free -----| ML | message1 | ML | message2 | ----- free ------|
  5473. // ^ ^ ^ ^
  5474. // buf tail head len
  5475. //
  5476. // Queue when q->tail > q->head:
  5477. // | ML | message2 |----- free ------| ML | message1 | 0 |---- free ----|
  5478. // ^ ^ ^ ^
  5479. // buf head tail len
  5480. void mg_queue_init(struct mg_queue *q, char *buf, size_t size) {
  5481. q->size = size;
  5482. q->buf = buf;
  5483. q->head = q->tail = 0;
  5484. }
  5485. static size_t mg_queue_read_len(struct mg_queue *q) {
  5486. uint32_t n = 0;
  5487. MG_MEMORY_BARRIER();
  5488. memcpy(&n, q->buf + q->tail, sizeof(n));
  5489. assert(q->tail + n + sizeof(n) <= q->size);
  5490. return n;
  5491. }
  5492. static void mg_queue_write_len(struct mg_queue *q, size_t len) {
  5493. uint32_t n = (uint32_t) len;
  5494. memcpy(q->buf + q->head, &n, sizeof(n));
  5495. MG_MEMORY_BARRIER();
  5496. }
  5497. size_t mg_queue_book(struct mg_queue *q, char **buf, size_t len) {
  5498. size_t space = 0, hs = sizeof(uint32_t) * 2; // *2 is for the 0 marker
  5499. if (q->head >= q->tail && q->head + len + hs <= q->size) {
  5500. space = q->size - q->head - hs; // There is enough space
  5501. } else if (q->head >= q->tail && q->tail > hs) {
  5502. mg_queue_write_len(q, 0); // Not enough space ahead
  5503. q->head = 0; // Wrap head to the beginning
  5504. }
  5505. if (q->head + hs + len < q->tail) space = q->tail - q->head - hs;
  5506. if (buf != NULL) *buf = q->buf + q->head + sizeof(uint32_t);
  5507. return space;
  5508. }
  5509. size_t mg_queue_next(struct mg_queue *q, char **buf) {
  5510. size_t len = 0;
  5511. if (q->tail != q->head) {
  5512. len = mg_queue_read_len(q);
  5513. if (len == 0) { // Zero (head wrapped) ?
  5514. q->tail = 0; // Reset tail to the start
  5515. if (q->head > q->tail) len = mg_queue_read_len(q); // Read again
  5516. }
  5517. }
  5518. if (buf != NULL) *buf = q->buf + q->tail + sizeof(uint32_t);
  5519. assert(q->tail + len <= q->size);
  5520. return len;
  5521. }
  5522. void mg_queue_add(struct mg_queue *q, size_t len) {
  5523. assert(len > 0);
  5524. mg_queue_write_len(q, len);
  5525. assert(q->head + sizeof(uint32_t) * 2 + len <= q->size);
  5526. q->head += len + sizeof(uint32_t);
  5527. }
  5528. void mg_queue_del(struct mg_queue *q, size_t len) {
  5529. q->tail += len + sizeof(uint32_t);
  5530. assert(q->tail + sizeof(uint32_t) <= q->size);
  5531. }
  5532. #ifdef MG_ENABLE_LINES
  5533. #line 1 "src/rpc.c"
  5534. #endif
  5535. void mg_rpc_add(struct mg_rpc **head, struct mg_str method,
  5536. void (*fn)(struct mg_rpc_req *), void *fn_data) {
  5537. struct mg_rpc *rpc = (struct mg_rpc *) calloc(1, sizeof(*rpc));
  5538. if (rpc != NULL) {
  5539. rpc->method = mg_strdup(method), rpc->fn = fn, rpc->fn_data = fn_data;
  5540. rpc->next = *head, *head = rpc;
  5541. }
  5542. }
  5543. void mg_rpc_del(struct mg_rpc **head, void (*fn)(struct mg_rpc_req *)) {
  5544. struct mg_rpc *r;
  5545. while ((r = *head) != NULL) {
  5546. if (r->fn == fn || fn == NULL) {
  5547. *head = r->next;
  5548. free((void *) r->method.ptr);
  5549. free(r);
  5550. } else {
  5551. head = &(*head)->next;
  5552. }
  5553. }
  5554. }
  5555. static void mg_rpc_call(struct mg_rpc_req *r, struct mg_str method) {
  5556. struct mg_rpc *h = r->head == NULL ? NULL : *r->head;
  5557. while (h != NULL && !mg_match(method, h->method, NULL)) h = h->next;
  5558. if (h != NULL) {
  5559. r->rpc = h;
  5560. h->fn(r);
  5561. } else {
  5562. mg_rpc_err(r, -32601, "\"%.*s not found\"", (int) method.len, method.ptr);
  5563. }
  5564. }
  5565. void mg_rpc_process(struct mg_rpc_req *r) {
  5566. int len, off = mg_json_get(r->frame, "$.method", &len);
  5567. if (off > 0 && r->frame.ptr[off] == '"') {
  5568. struct mg_str method = mg_str_n(&r->frame.ptr[off + 1], (size_t) len - 2);
  5569. mg_rpc_call(r, method);
  5570. } else if ((off = mg_json_get(r->frame, "$.result", &len)) > 0 ||
  5571. (off = mg_json_get(r->frame, "$.error", &len)) > 0) {
  5572. mg_rpc_call(r, mg_str("")); // JSON response! call "" method handler
  5573. } else {
  5574. mg_rpc_err(r, -32700, "%m", mg_print_esc, (int) r->frame.len,
  5575. r->frame.ptr); // Invalid
  5576. }
  5577. }
  5578. void mg_rpc_vok(struct mg_rpc_req *r, const char *fmt, va_list *ap) {
  5579. int len, off = mg_json_get(r->frame, "$.id", &len);
  5580. if (off > 0) {
  5581. mg_xprintf(r->pfn, r->pfn_data, "{%m:%.*s,%m:", mg_print_esc, 0, "id", len,
  5582. &r->frame.ptr[off], mg_print_esc, 0, "result");
  5583. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  5584. mg_xprintf(r->pfn, r->pfn_data, "}");
  5585. }
  5586. }
  5587. void mg_rpc_ok(struct mg_rpc_req *r, const char *fmt, ...) {
  5588. va_list ap;
  5589. va_start(ap, fmt);
  5590. mg_rpc_vok(r, fmt, &ap);
  5591. va_end(ap);
  5592. }
  5593. void mg_rpc_verr(struct mg_rpc_req *r, int code, const char *fmt, va_list *ap) {
  5594. int len, off = mg_json_get(r->frame, "$.id", &len);
  5595. mg_xprintf(r->pfn, r->pfn_data, "{");
  5596. if (off > 0) {
  5597. mg_xprintf(r->pfn, r->pfn_data, "%m:%.*s,", mg_print_esc, 0, "id", len,
  5598. &r->frame.ptr[off]);
  5599. }
  5600. mg_xprintf(r->pfn, r->pfn_data, "%m:{%m:%d,%m:", mg_print_esc, 0, "error",
  5601. mg_print_esc, 0, "code", code, mg_print_esc, 0, "message");
  5602. mg_vxprintf(r->pfn, r->pfn_data, fmt == NULL ? "null" : fmt, ap);
  5603. mg_xprintf(r->pfn, r->pfn_data, "}}");
  5604. }
  5605. void mg_rpc_err(struct mg_rpc_req *r, int code, const char *fmt, ...) {
  5606. va_list ap;
  5607. va_start(ap, fmt);
  5608. mg_rpc_verr(r, code, fmt, &ap);
  5609. va_end(ap);
  5610. }
  5611. static size_t print_methods(mg_pfn_t pfn, void *pfn_data, va_list *ap) {
  5612. struct mg_rpc *h, **head = (struct mg_rpc **) va_arg(*ap, void **);
  5613. size_t len = 0;
  5614. for (h = *head; h != NULL; h = h->next) {
  5615. if (h->method.len == 0) continue; // Ignore response handler
  5616. len += mg_xprintf(pfn, pfn_data, "%s%m", h == *head ? "" : ",",
  5617. mg_print_esc, (int) h->method.len, h->method.ptr);
  5618. }
  5619. return len;
  5620. }
  5621. void mg_rpc_list(struct mg_rpc_req *r) {
  5622. mg_rpc_ok(r, "[%M]", print_methods, r->head);
  5623. }
  5624. #ifdef MG_ENABLE_LINES
  5625. #line 1 "src/sha1.c"
  5626. #endif
  5627. /* Copyright(c) By Steve Reid <steve@edmweb.com> */
  5628. /* 100% Public Domain */
  5629. union char64long16 {
  5630. unsigned char c[64];
  5631. uint32_t l[16];
  5632. };
  5633. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  5634. static uint32_t blk0(union char64long16 *block, int i) {
  5635. if (MG_BIG_ENDIAN) {
  5636. } else {
  5637. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  5638. (rol(block->l[i], 8) & 0x00FF00FF);
  5639. }
  5640. return block->l[i];
  5641. }
  5642. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  5643. #undef blk
  5644. #undef R0
  5645. #undef R1
  5646. #undef R2
  5647. #undef R3
  5648. #undef R4
  5649. #define blk(i) \
  5650. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  5651. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  5652. 1))
  5653. #define R0(v, w, x, y, z, i) \
  5654. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  5655. w = rol(w, 30);
  5656. #define R1(v, w, x, y, z, i) \
  5657. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  5658. w = rol(w, 30);
  5659. #define R2(v, w, x, y, z, i) \
  5660. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  5661. w = rol(w, 30);
  5662. #define R3(v, w, x, y, z, i) \
  5663. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  5664. w = rol(w, 30);
  5665. #define R4(v, w, x, y, z, i) \
  5666. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  5667. w = rol(w, 30);
  5668. static void mg_sha1_transform(uint32_t state[5],
  5669. const unsigned char *buffer) {
  5670. uint32_t a, b, c, d, e;
  5671. union char64long16 block[1];
  5672. memcpy(block, buffer, 64);
  5673. a = state[0];
  5674. b = state[1];
  5675. c = state[2];
  5676. d = state[3];
  5677. e = state[4];
  5678. R0(a, b, c, d, e, 0);
  5679. R0(e, a, b, c, d, 1);
  5680. R0(d, e, a, b, c, 2);
  5681. R0(c, d, e, a, b, 3);
  5682. R0(b, c, d, e, a, 4);
  5683. R0(a, b, c, d, e, 5);
  5684. R0(e, a, b, c, d, 6);
  5685. R0(d, e, a, b, c, 7);
  5686. R0(c, d, e, a, b, 8);
  5687. R0(b, c, d, e, a, 9);
  5688. R0(a, b, c, d, e, 10);
  5689. R0(e, a, b, c, d, 11);
  5690. R0(d, e, a, b, c, 12);
  5691. R0(c, d, e, a, b, 13);
  5692. R0(b, c, d, e, a, 14);
  5693. R0(a, b, c, d, e, 15);
  5694. R1(e, a, b, c, d, 16);
  5695. R1(d, e, a, b, c, 17);
  5696. R1(c, d, e, a, b, 18);
  5697. R1(b, c, d, e, a, 19);
  5698. R2(a, b, c, d, e, 20);
  5699. R2(e, a, b, c, d, 21);
  5700. R2(d, e, a, b, c, 22);
  5701. R2(c, d, e, a, b, 23);
  5702. R2(b, c, d, e, a, 24);
  5703. R2(a, b, c, d, e, 25);
  5704. R2(e, a, b, c, d, 26);
  5705. R2(d, e, a, b, c, 27);
  5706. R2(c, d, e, a, b, 28);
  5707. R2(b, c, d, e, a, 29);
  5708. R2(a, b, c, d, e, 30);
  5709. R2(e, a, b, c, d, 31);
  5710. R2(d, e, a, b, c, 32);
  5711. R2(c, d, e, a, b, 33);
  5712. R2(b, c, d, e, a, 34);
  5713. R2(a, b, c, d, e, 35);
  5714. R2(e, a, b, c, d, 36);
  5715. R2(d, e, a, b, c, 37);
  5716. R2(c, d, e, a, b, 38);
  5717. R2(b, c, d, e, a, 39);
  5718. R3(a, b, c, d, e, 40);
  5719. R3(e, a, b, c, d, 41);
  5720. R3(d, e, a, b, c, 42);
  5721. R3(c, d, e, a, b, 43);
  5722. R3(b, c, d, e, a, 44);
  5723. R3(a, b, c, d, e, 45);
  5724. R3(e, a, b, c, d, 46);
  5725. R3(d, e, a, b, c, 47);
  5726. R3(c, d, e, a, b, 48);
  5727. R3(b, c, d, e, a, 49);
  5728. R3(a, b, c, d, e, 50);
  5729. R3(e, a, b, c, d, 51);
  5730. R3(d, e, a, b, c, 52);
  5731. R3(c, d, e, a, b, 53);
  5732. R3(b, c, d, e, a, 54);
  5733. R3(a, b, c, d, e, 55);
  5734. R3(e, a, b, c, d, 56);
  5735. R3(d, e, a, b, c, 57);
  5736. R3(c, d, e, a, b, 58);
  5737. R3(b, c, d, e, a, 59);
  5738. R4(a, b, c, d, e, 60);
  5739. R4(e, a, b, c, d, 61);
  5740. R4(d, e, a, b, c, 62);
  5741. R4(c, d, e, a, b, 63);
  5742. R4(b, c, d, e, a, 64);
  5743. R4(a, b, c, d, e, 65);
  5744. R4(e, a, b, c, d, 66);
  5745. R4(d, e, a, b, c, 67);
  5746. R4(c, d, e, a, b, 68);
  5747. R4(b, c, d, e, a, 69);
  5748. R4(a, b, c, d, e, 70);
  5749. R4(e, a, b, c, d, 71);
  5750. R4(d, e, a, b, c, 72);
  5751. R4(c, d, e, a, b, 73);
  5752. R4(b, c, d, e, a, 74);
  5753. R4(a, b, c, d, e, 75);
  5754. R4(e, a, b, c, d, 76);
  5755. R4(d, e, a, b, c, 77);
  5756. R4(c, d, e, a, b, 78);
  5757. R4(b, c, d, e, a, 79);
  5758. state[0] += a;
  5759. state[1] += b;
  5760. state[2] += c;
  5761. state[3] += d;
  5762. state[4] += e;
  5763. /* Erase working structures. The order of operations is important,
  5764. * used to ensure that compiler doesn't optimize those out. */
  5765. memset(block, 0, sizeof(block));
  5766. a = b = c = d = e = 0;
  5767. (void) a;
  5768. (void) b;
  5769. (void) c;
  5770. (void) d;
  5771. (void) e;
  5772. }
  5773. void mg_sha1_init(mg_sha1_ctx *context) {
  5774. context->state[0] = 0x67452301;
  5775. context->state[1] = 0xEFCDAB89;
  5776. context->state[2] = 0x98BADCFE;
  5777. context->state[3] = 0x10325476;
  5778. context->state[4] = 0xC3D2E1F0;
  5779. context->count[0] = context->count[1] = 0;
  5780. }
  5781. void mg_sha1_update(mg_sha1_ctx *context, const unsigned char *data,
  5782. size_t len) {
  5783. size_t i, j;
  5784. j = context->count[0];
  5785. if ((context->count[0] += (uint32_t) len << 3) < j) context->count[1]++;
  5786. context->count[1] += (uint32_t) (len >> 29);
  5787. j = (j >> 3) & 63;
  5788. if ((j + len) > 63) {
  5789. memcpy(&context->buffer[j], data, (i = 64 - j));
  5790. mg_sha1_transform(context->state, context->buffer);
  5791. for (; i + 63 < len; i += 64) {
  5792. mg_sha1_transform(context->state, &data[i]);
  5793. }
  5794. j = 0;
  5795. } else
  5796. i = 0;
  5797. memcpy(&context->buffer[j], &data[i], len - i);
  5798. }
  5799. void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *context) {
  5800. unsigned i;
  5801. unsigned char finalcount[8], c;
  5802. for (i = 0; i < 8; i++) {
  5803. finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
  5804. ((3 - (i & 3)) * 8)) &
  5805. 255);
  5806. }
  5807. c = 0200;
  5808. mg_sha1_update(context, &c, 1);
  5809. while ((context->count[0] & 504) != 448) {
  5810. c = 0000;
  5811. mg_sha1_update(context, &c, 1);
  5812. }
  5813. mg_sha1_update(context, finalcount, 8);
  5814. for (i = 0; i < 20; i++) {
  5815. digest[i] =
  5816. (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
  5817. }
  5818. memset(context, '\0', sizeof(*context));
  5819. memset(&finalcount, '\0', sizeof(finalcount));
  5820. }
  5821. #ifdef MG_ENABLE_LINES
  5822. #line 1 "src/sha256.c"
  5823. #endif
  5824. #define ror(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
  5825. #define ch(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
  5826. #define maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
  5827. #define ep0(x) (ror(x, 2) ^ ror(x, 13) ^ ror(x, 22))
  5828. #define ep1(x) (ror(x, 6) ^ ror(x, 11) ^ ror(x, 25))
  5829. #define sig0(x) (ror(x, 7) ^ ror(x, 18) ^ ((x) >> 3))
  5830. #define sig1(x) (ror(x, 17) ^ ror(x, 19) ^ ((x) >> 10))
  5831. static const uint32_t mg_sha256_k[64] = {
  5832. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
  5833. 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  5834. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
  5835. 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  5836. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
  5837. 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  5838. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
  5839. 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  5840. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
  5841. 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  5842. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
  5843. void mg_sha256_init(mg_sha256_ctx *ctx) {
  5844. ctx->len = 0;
  5845. ctx->bits = 0;
  5846. ctx->state[0] = 0x6a09e667;
  5847. ctx->state[1] = 0xbb67ae85;
  5848. ctx->state[2] = 0x3c6ef372;
  5849. ctx->state[3] = 0xa54ff53a;
  5850. ctx->state[4] = 0x510e527f;
  5851. ctx->state[5] = 0x9b05688c;
  5852. ctx->state[6] = 0x1f83d9ab;
  5853. ctx->state[7] = 0x5be0cd19;
  5854. }
  5855. static void mg_sha256_chunk(mg_sha256_ctx *ctx) {
  5856. int i, j;
  5857. uint32_t a, b, c, d, e, f, g, h;
  5858. uint32_t m[64];
  5859. for (i = 0, j = 0; i < 16; ++i, j += 4)
  5860. m[i] = (uint32_t) ((ctx->buffer[j] << 24) | (ctx->buffer[j + 1] << 16) |
  5861. (ctx->buffer[j + 2] << 8) | (ctx->buffer[j + 3]));
  5862. for (; i < 64; ++i)
  5863. m[i] = sig1(m[i - 2]) + m[i - 7] + sig0(m[i - 15]) + m[i - 16];
  5864. a = ctx->state[0];
  5865. b = ctx->state[1];
  5866. c = ctx->state[2];
  5867. d = ctx->state[3];
  5868. e = ctx->state[4];
  5869. f = ctx->state[5];
  5870. g = ctx->state[6];
  5871. h = ctx->state[7];
  5872. for (i = 0; i < 64; ++i) {
  5873. uint32_t t1 = h + ep1(e) + ch(e, f, g) + mg_sha256_k[i] + m[i];
  5874. uint32_t t2 = ep0(a) + maj(a, b, c);
  5875. h = g;
  5876. g = f;
  5877. f = e;
  5878. e = d + t1;
  5879. d = c;
  5880. c = b;
  5881. b = a;
  5882. a = t1 + t2;
  5883. }
  5884. ctx->state[0] += a;
  5885. ctx->state[1] += b;
  5886. ctx->state[2] += c;
  5887. ctx->state[3] += d;
  5888. ctx->state[4] += e;
  5889. ctx->state[5] += f;
  5890. ctx->state[6] += g;
  5891. ctx->state[7] += h;
  5892. }
  5893. void mg_sha256_update(mg_sha256_ctx *ctx, const unsigned char *data,
  5894. size_t len) {
  5895. size_t i;
  5896. for (i = 0; i < len; i++) {
  5897. ctx->buffer[ctx->len] = data[i];
  5898. if ((++ctx->len) == 64) {
  5899. mg_sha256_chunk(ctx);
  5900. ctx->bits += 512;
  5901. ctx->len = 0;
  5902. }
  5903. }
  5904. }
  5905. // TODO: make final reusable (remove side effects)
  5906. void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *ctx) {
  5907. uint32_t i = ctx->len;
  5908. if (i < 56) {
  5909. ctx->buffer[i++] = 0x80;
  5910. while (i < 56) {
  5911. ctx->buffer[i++] = 0x00;
  5912. }
  5913. } else {
  5914. ctx->buffer[i++] = 0x80;
  5915. while (i < 64) {
  5916. ctx->buffer[i++] = 0x00;
  5917. }
  5918. mg_sha256_chunk(ctx);
  5919. memset(ctx->buffer, 0, 56);
  5920. }
  5921. ctx->bits += ctx->len * 8;
  5922. ctx->buffer[63] = (uint8_t) ((ctx->bits) & 0xff);
  5923. ctx->buffer[62] = (uint8_t) ((ctx->bits >> 8) & 0xff);
  5924. ctx->buffer[61] = (uint8_t) ((ctx->bits >> 16) & 0xff);
  5925. ctx->buffer[60] = (uint8_t) ((ctx->bits >> 24) & 0xff);
  5926. ctx->buffer[59] = (uint8_t) ((ctx->bits >> 32) & 0xff);
  5927. ctx->buffer[58] = (uint8_t) ((ctx->bits >> 40) & 0xff);
  5928. ctx->buffer[57] = (uint8_t) ((ctx->bits >> 48) & 0xff);
  5929. ctx->buffer[56] = (uint8_t) ((ctx->bits >> 56) & 0xff);
  5930. mg_sha256_chunk(ctx);
  5931. for (i = 0; i < 4; ++i) {
  5932. digest[i] = (ctx->state[0] >> (24 - i * 8)) & 0xff;
  5933. digest[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0xff;
  5934. digest[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0xff;
  5935. digest[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0xff;
  5936. digest[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0xff;
  5937. digest[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0xff;
  5938. digest[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0xff;
  5939. digest[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0xff;
  5940. }
  5941. }
  5942. void mg_hmac_sha256(uint8_t dst[32], uint8_t *key, size_t keysz, uint8_t *data,
  5943. size_t datasz) {
  5944. mg_sha256_ctx ctx;
  5945. uint8_t k[64] = {0};
  5946. uint8_t o_pad[64], i_pad[64];
  5947. unsigned int i;
  5948. memset(i_pad, 0x36, sizeof(i_pad));
  5949. memset(o_pad, 0x5c, sizeof(o_pad));
  5950. if (keysz < 64) {
  5951. memmove(k, key, keysz);
  5952. } else {
  5953. mg_sha256_init(&ctx);
  5954. mg_sha256_update(&ctx, key, keysz);
  5955. mg_sha256_final(k, &ctx);
  5956. }
  5957. for (i = 0; i < sizeof(k); i++) {
  5958. i_pad[i] ^= k[i];
  5959. o_pad[i] ^= k[i];
  5960. }
  5961. mg_sha256_init(&ctx);
  5962. mg_sha256_update(&ctx, i_pad, sizeof(i_pad));
  5963. mg_sha256_update(&ctx, data, datasz);
  5964. mg_sha256_final(dst, &ctx);
  5965. mg_sha256_init(&ctx);
  5966. mg_sha256_update(&ctx, o_pad, sizeof(o_pad));
  5967. mg_sha256_update(&ctx, dst, 32);
  5968. mg_sha256_final(dst, &ctx);
  5969. }
  5970. #ifdef MG_ENABLE_LINES
  5971. #line 1 "src/sntp.c"
  5972. #endif
  5973. #define SNTP_TIME_OFFSET 2208988800U // (1970 - 1900) in seconds
  5974. #define SNTP_MAX_FRAC 4294967295.0 // 2 ** 32 - 1
  5975. static int64_t gettimestamp(const uint32_t *data) {
  5976. uint32_t sec = mg_ntohl(data[0]), frac = mg_ntohl(data[1]);
  5977. if (sec) sec -= SNTP_TIME_OFFSET;
  5978. return ((int64_t) sec) * 1000 + (int64_t) (frac / SNTP_MAX_FRAC * 1000.0);
  5979. }
  5980. int64_t mg_sntp_parse(const unsigned char *buf, size_t len) {
  5981. int64_t res = -1;
  5982. int mode = len > 0 ? buf[0] & 7 : 0;
  5983. int version = len > 0 ? (buf[0] >> 3) & 7 : 0;
  5984. if (len < 48) {
  5985. MG_ERROR(("%s", "corrupt packet"));
  5986. } else if (mode != 4 && mode != 5) {
  5987. MG_ERROR(("%s", "not a server reply"));
  5988. } else if (buf[1] == 0) {
  5989. MG_ERROR(("%s", "server sent a kiss of death"));
  5990. } else if (version == 4 || version == 3) {
  5991. // int64_t ref = gettimestamp((uint32_t *) &buf[16]);
  5992. int64_t t0 = gettimestamp((uint32_t *) &buf[24]);
  5993. int64_t t1 = gettimestamp((uint32_t *) &buf[32]);
  5994. int64_t t2 = gettimestamp((uint32_t *) &buf[40]);
  5995. int64_t t3 = (int64_t) mg_millis();
  5996. int64_t delta = (t3 - t0) - (t2 - t1);
  5997. MG_VERBOSE(("%lld %lld %lld %lld delta:%lld", t0, t1, t2, t3, delta));
  5998. res = t2 + delta / 2;
  5999. } else {
  6000. MG_ERROR(("unexpected version: %d", version));
  6001. }
  6002. return res;
  6003. }
  6004. static void sntp_cb(struct mg_connection *c, int ev, void *ev_data) {
  6005. if (ev == MG_EV_READ) {
  6006. int64_t milliseconds = mg_sntp_parse(c->recv.buf, c->recv.len);
  6007. if (milliseconds > 0) {
  6008. MG_INFO(("%lu got time: %lld ms from epoch", c->id, milliseconds));
  6009. mg_call(c, MG_EV_SNTP_TIME, (uint64_t *) &milliseconds);
  6010. MG_VERBOSE(("%u.%u", (unsigned) (milliseconds / 1000),
  6011. (unsigned) (milliseconds % 1000)));
  6012. }
  6013. mg_iobuf_del(&c->recv, 0, c->recv.len); // Free receive buffer
  6014. } else if (ev == MG_EV_CONNECT) {
  6015. mg_sntp_request(c);
  6016. } else if (ev == MG_EV_CLOSE) {
  6017. }
  6018. (void) ev_data;
  6019. }
  6020. void mg_sntp_request(struct mg_connection *c) {
  6021. if (c->is_resolving) {
  6022. MG_ERROR(("%lu wait until resolved", c->id));
  6023. } else {
  6024. int64_t now = (int64_t) mg_millis(); // Use int64_t, for vc98
  6025. uint8_t buf[48] = {0};
  6026. uint32_t *t = (uint32_t *) &buf[40];
  6027. double frac = ((double) (now % 1000)) / 1000.0 * SNTP_MAX_FRAC;
  6028. buf[0] = (0 << 6) | (4 << 3) | 3;
  6029. t[0] = mg_htonl((uint32_t) (now / 1000) + SNTP_TIME_OFFSET);
  6030. t[1] = mg_htonl((uint32_t) frac);
  6031. mg_send(c, buf, sizeof(buf));
  6032. }
  6033. }
  6034. struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url,
  6035. mg_event_handler_t fn, void *fnd) {
  6036. struct mg_connection *c = NULL;
  6037. if (url == NULL) url = "udp://time.google.com:123";
  6038. if ((c = mg_connect(mgr, url, fn, fnd)) != NULL) c->pfn = sntp_cb;
  6039. return c;
  6040. }
  6041. #ifdef MG_ENABLE_LINES
  6042. #line 1 "src/sock.c"
  6043. #endif
  6044. #if MG_ENABLE_SOCKET
  6045. #ifndef closesocket
  6046. #define closesocket(x) close(x)
  6047. #endif
  6048. #define FD(c_) ((MG_SOCKET_TYPE) (size_t) (c_)->fd)
  6049. #define S2PTR(s_) ((void *) (size_t) (s_))
  6050. #ifndef MSG_NONBLOCKING
  6051. #define MSG_NONBLOCKING 0
  6052. #endif
  6053. #ifndef AF_INET6
  6054. #define AF_INET6 10
  6055. #endif
  6056. #ifndef MG_SOCK_ERR
  6057. #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? errno : 0)
  6058. #endif
  6059. #ifndef MG_SOCK_INTR
  6060. #define MG_SOCK_INTR(fd) (fd == MG_INVALID_SOCKET && MG_SOCK_ERR(-1) == EINTR)
  6061. #endif
  6062. #ifndef MG_SOCK_PENDING
  6063. #define MG_SOCK_PENDING(errcode) \
  6064. (((errcode) < 0) && (errno == EINPROGRESS || errno == EWOULDBLOCK))
  6065. #endif
  6066. #ifndef MG_SOCK_RESET
  6067. #define MG_SOCK_RESET(errcode) \
  6068. (((errcode) < 0) && (errno == EPIPE || errno == ECONNRESET))
  6069. #endif
  6070. union usa {
  6071. struct sockaddr sa;
  6072. struct sockaddr_in sin;
  6073. #if MG_ENABLE_IPV6
  6074. struct sockaddr_in6 sin6;
  6075. #endif
  6076. };
  6077. static socklen_t tousa(struct mg_addr *a, union usa *usa) {
  6078. socklen_t len = sizeof(usa->sin);
  6079. memset(usa, 0, sizeof(*usa));
  6080. usa->sin.sin_family = AF_INET;
  6081. usa->sin.sin_port = a->port;
  6082. memcpy(&usa->sin.sin_addr, a->ip, sizeof(uint32_t));
  6083. #if MG_ENABLE_IPV6
  6084. if (a->is_ip6) {
  6085. usa->sin.sin_family = AF_INET6;
  6086. usa->sin6.sin6_port = a->port;
  6087. usa->sin6.sin6_scope_id = a->scope_id;
  6088. memcpy(&usa->sin6.sin6_addr, a->ip, sizeof(a->ip));
  6089. len = sizeof(usa->sin6);
  6090. }
  6091. #endif
  6092. return len;
  6093. }
  6094. static void tomgaddr(union usa *usa, struct mg_addr *a, bool is_ip6) {
  6095. a->is_ip6 = is_ip6;
  6096. a->port = usa->sin.sin_port;
  6097. memcpy(&a->ip, &usa->sin.sin_addr, sizeof(uint32_t));
  6098. #if MG_ENABLE_IPV6
  6099. if (is_ip6) {
  6100. memcpy(a->ip, &usa->sin6.sin6_addr, sizeof(a->ip));
  6101. a->port = usa->sin6.sin6_port;
  6102. a->scope_id = (uint8_t) usa->sin6.sin6_scope_id;
  6103. }
  6104. #endif
  6105. }
  6106. static void setlocaddr(MG_SOCKET_TYPE fd, struct mg_addr *addr) {
  6107. union usa usa;
  6108. socklen_t n = sizeof(usa);
  6109. if (getsockname(fd, &usa.sa, &n) == 0) {
  6110. tomgaddr(&usa, addr, n != sizeof(usa.sin));
  6111. }
  6112. }
  6113. static void iolog(struct mg_connection *c, char *buf, long n, bool r) {
  6114. if (n == MG_IO_WAIT) {
  6115. // Do nothing
  6116. } else if (n <= 0) {
  6117. c->is_closing = 1; // Termination. Don't call mg_error(): #1529
  6118. } else if (n > 0) {
  6119. if (c->is_hexdumping) {
  6120. union usa usa;
  6121. socklen_t slen = sizeof(usa.sin);
  6122. if (getsockname(FD(c), &usa.sa, &slen) < 0) (void) 0; // Ignore result
  6123. MG_INFO(("\n-- %lu %M %s %M %ld", c->id, mg_print_ip_port, &c->loc,
  6124. r ? "<-" : "->", mg_print_ip_port, &c->rem, n));
  6125. mg_hexdump(buf, (size_t) n);
  6126. }
  6127. if (r) {
  6128. c->recv.len += (size_t) n;
  6129. mg_call(c, MG_EV_READ, &n);
  6130. } else {
  6131. mg_iobuf_del(&c->send, 0, (size_t) n);
  6132. // if (c->send.len == 0) mg_iobuf_resize(&c->send, 0);
  6133. if (c->send.len == 0) {
  6134. MG_EPOLL_MOD(c, 0);
  6135. }
  6136. mg_call(c, MG_EV_WRITE, &n);
  6137. }
  6138. }
  6139. }
  6140. long mg_io_send(struct mg_connection *c, const void *buf, size_t len) {
  6141. long n;
  6142. if (c->is_udp) {
  6143. union usa usa;
  6144. socklen_t slen = tousa(&c->rem, &usa);
  6145. n = sendto(FD(c), (char *) buf, len, 0, &usa.sa, slen);
  6146. if (n > 0) setlocaddr(FD(c), &c->loc);
  6147. } else {
  6148. n = send(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6149. }
  6150. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6151. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6152. if (n <= 0) return MG_IO_ERR;
  6153. return n;
  6154. }
  6155. bool mg_send(struct mg_connection *c, const void *buf, size_t len) {
  6156. if (c->is_udp) {
  6157. long n = mg_io_send(c, buf, len);
  6158. MG_DEBUG(("%lu %ld %d:%d %ld err %d", c->id, c->fd, (int) c->send.len,
  6159. (int) c->recv.len, n, MG_SOCK_ERR(n)));
  6160. iolog(c, (char *) buf, n, false);
  6161. return n > 0;
  6162. } else {
  6163. return mg_iobuf_add(&c->send, c->send.len, buf, len);
  6164. }
  6165. }
  6166. static void mg_set_non_blocking_mode(MG_SOCKET_TYPE fd) {
  6167. #if defined(MG_CUSTOM_NONBLOCK)
  6168. MG_CUSTOM_NONBLOCK(fd);
  6169. #elif MG_ARCH == MG_ARCH_WIN32 && MG_ENABLE_WINSOCK
  6170. unsigned long on = 1;
  6171. ioctlsocket(fd, FIONBIO, &on);
  6172. #elif MG_ENABLE_RL
  6173. unsigned long on = 1;
  6174. ioctlsocket(fd, FIONBIO, &on);
  6175. #elif MG_ENABLE_FREERTOS_TCP
  6176. const BaseType_t off = 0;
  6177. if (setsockopt(fd, 0, FREERTOS_SO_RCVTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6178. if (setsockopt(fd, 0, FREERTOS_SO_SNDTIMEO, &off, sizeof(off)) != 0) (void) 0;
  6179. #elif MG_ENABLE_LWIP
  6180. lwip_fcntl(fd, F_SETFL, O_NONBLOCK);
  6181. #elif MG_ARCH == MG_ARCH_AZURERTOS
  6182. fcntl(fd, F_SETFL, O_NONBLOCK);
  6183. #elif MG_ARCH == MG_ARCH_TIRTOS
  6184. int val = 0;
  6185. setsockopt(fd, SOL_SOCKET, SO_BLOCKING, &val, sizeof(val));
  6186. // SPRU524J section 3.3.3 page 63, SO_SNDLOWAT
  6187. int sz = sizeof(val);
  6188. getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &val, &sz);
  6189. val /= 2; // set send low-water mark at half send buffer size
  6190. setsockopt(fd, SOL_SOCKET, SO_SNDLOWAT, &val, sizeof(val));
  6191. #else
  6192. fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); // Non-blocking mode
  6193. fcntl(fd, F_SETFD, FD_CLOEXEC); // Set close-on-exec
  6194. #endif
  6195. }
  6196. bool mg_open_listener(struct mg_connection *c, const char *url) {
  6197. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6198. bool success = false;
  6199. c->loc.port = mg_htons(mg_url_port(url));
  6200. if (!mg_aton(mg_url_host(url), &c->loc)) {
  6201. MG_ERROR(("invalid listening URL: %s", url));
  6202. } else {
  6203. union usa usa;
  6204. socklen_t slen = tousa(&c->loc, &usa);
  6205. int rc, on = 1, af = c->loc.is_ip6 ? AF_INET6 : AF_INET;
  6206. int type = strncmp(url, "udp:", 4) == 0 ? SOCK_DGRAM : SOCK_STREAM;
  6207. int proto = type == SOCK_DGRAM ? IPPROTO_UDP : IPPROTO_TCP;
  6208. (void) on;
  6209. if ((fd = socket(af, type, proto)) == MG_INVALID_SOCKET) {
  6210. MG_ERROR(("socket: %d", MG_SOCK_ERR(-1)));
  6211. #if defined(SO_EXCLUSIVEADDRUSE)
  6212. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  6213. (char *) &on, sizeof(on))) != 0) {
  6214. // "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE"
  6215. MG_ERROR(("setsockopt(SO_EXCLUSIVEADDRUSE): %d %d", on, MG_SOCK_ERR(rc)));
  6216. #elif defined(SO_REUSEADDR) && (!defined(LWIP_SOCKET) || SO_REUSE)
  6217. } else if ((rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on,
  6218. sizeof(on))) != 0) {
  6219. // 1. SO_REUSEADDR semantics on UNIX and Windows is different. On
  6220. // Windows, SO_REUSEADDR allows to bind a socket to a port without error
  6221. // even if the port is already open by another program. This is not the
  6222. // behavior SO_REUSEADDR was designed for, and leads to hard-to-track
  6223. // failure scenarios.
  6224. //
  6225. // 2. For LWIP, SO_REUSEADDR should be explicitly enabled by defining
  6226. // SO_REUSE = 1 in lwipopts.h, otherwise the code below will compile but
  6227. // won't work! (setsockopt will return EINVAL)
  6228. MG_ERROR(("setsockopt(SO_REUSEADDR): %d", MG_SOCK_ERR(rc)));
  6229. #endif
  6230. #if MG_IPV6_V6ONLY
  6231. // Bind only to the V6 address, not V4 address on this port
  6232. } else if (c->loc.is_ip6 &&
  6233. (rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &on,
  6234. sizeof(on))) != 0) {
  6235. // See #2089. Allow to bind v4 and v6 sockets on the same port
  6236. MG_ERROR(("setsockopt(IPV6_V6ONLY): %d", MG_SOCK_ERR(rc)));
  6237. #endif
  6238. } else if ((rc = bind(fd, &usa.sa, slen)) != 0) {
  6239. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6240. } else if ((type == SOCK_STREAM &&
  6241. (rc = listen(fd, MG_SOCK_LISTEN_BACKLOG_SIZE)) != 0)) {
  6242. // NOTE(lsm): FreeRTOS uses backlog value as a connection limit
  6243. // In case port was set to 0, get the real port number
  6244. MG_ERROR(("listen: %d", MG_SOCK_ERR(rc)));
  6245. } else {
  6246. setlocaddr(fd, &c->loc);
  6247. mg_set_non_blocking_mode(fd);
  6248. c->fd = S2PTR(fd);
  6249. MG_EPOLL_ADD(c);
  6250. success = true;
  6251. }
  6252. }
  6253. if (success == false && fd != MG_INVALID_SOCKET) closesocket(fd);
  6254. return success;
  6255. }
  6256. static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
  6257. long n = 0;
  6258. if (c->is_udp) {
  6259. union usa usa;
  6260. socklen_t slen = tousa(&c->rem, &usa);
  6261. n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
  6262. if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
  6263. } else {
  6264. n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
  6265. }
  6266. if (MG_SOCK_PENDING(n)) return MG_IO_WAIT;
  6267. if (MG_SOCK_RESET(n)) return MG_IO_RESET;
  6268. if (n <= 0) return MG_IO_ERR;
  6269. return n;
  6270. }
  6271. static bool ioalloc(struct mg_connection *c, struct mg_iobuf *io) {
  6272. bool res = false;
  6273. if (io->len >= MG_MAX_RECV_SIZE) {
  6274. mg_error(c, "MG_MAX_RECV_SIZE");
  6275. } else if (io->size <= io->len &&
  6276. !mg_iobuf_resize(io, io->size + MG_IO_SIZE)) {
  6277. mg_error(c, "OOM");
  6278. } else {
  6279. res = true;
  6280. }
  6281. return res;
  6282. }
  6283. // NOTE(lsm): do only one iteration of reads, cause some systems
  6284. // (e.g. FreeRTOS stack) return 0 instead of -1/EWOULDBLOCK when no data
  6285. static void read_conn(struct mg_connection *c) {
  6286. if (ioalloc(c, &c->recv)) {
  6287. char *buf = (char *) &c->recv.buf[c->recv.len];
  6288. size_t len = c->recv.size - c->recv.len;
  6289. long n = -1;
  6290. if (c->is_tls) {
  6291. if (!ioalloc(c, &c->rtls)) return;
  6292. n = recv_raw(c, (char *) &c->rtls.buf[c->rtls.len],
  6293. c->rtls.size - c->rtls.len);
  6294. // MG_DEBUG(("%lu %ld", c->id, n));
  6295. if (n == MG_IO_ERR) {
  6296. c->is_closing = 1;
  6297. } else if (n > 0) {
  6298. c->rtls.len += (size_t) n;
  6299. if (c->is_tls_hs) mg_tls_handshake(c);
  6300. if (c->is_tls_hs) return;
  6301. n = mg_tls_recv(c, buf, len);
  6302. } else if (n == MG_IO_WAIT) {
  6303. n = mg_tls_recv(c, buf, len);
  6304. }
  6305. } else {
  6306. n = recv_raw(c, buf, len);
  6307. }
  6308. MG_DEBUG(("%lu %p snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6309. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6310. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6311. iolog(c, buf, n, true);
  6312. }
  6313. }
  6314. static void write_conn(struct mg_connection *c) {
  6315. #if MG_ARCH == MG_ARCH_UNIX
  6316. //pthread_mutex_lock(&WSlock);
  6317. #endif
  6318. char *buf = (char *) c->send.buf;
  6319. size_t len = c->send.len;
  6320. long n = c->is_tls ? mg_tls_send(c, buf, len) : mg_io_send(c, buf, len);
  6321. MG_DEBUG(("%lu %ld snd %ld/%ld rcv %ld/%ld n=%ld err=%d", c->id, c->fd,
  6322. (long) c->send.len, (long) c->send.size, (long) c->recv.len,
  6323. (long) c->recv.size, n, MG_SOCK_ERR(n)));
  6324. iolog(c, buf, n, false);
  6325. #if MG_ARCH == MG_ARCH_UNIX
  6326. //pthread_mutex_unlock(&WSlock);
  6327. #endif
  6328. }
  6329. static void close_conn(struct mg_connection *c) {
  6330. #if MG_ARCH == MG_ARCH_UNIX
  6331. //pthread_mutex_lock(&WSlock);
  6332. #endif
  6333. if (FD(c) != MG_INVALID_SOCKET) {
  6334. #if MG_ENABLE_EPOLL
  6335. epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_DEL, FD(c), NULL);
  6336. #endif
  6337. closesocket(FD(c));
  6338. #if MG_ENABLE_FREERTOS_TCP
  6339. FreeRTOS_FD_CLR(c->fd, c->mgr->ss, eSELECT_ALL);
  6340. #endif
  6341. }
  6342. mg_close_conn(c);
  6343. #if MG_ARCH == MG_ARCH_UNIX
  6344. //pthread_mutex_unlock(&WSlock);
  6345. #endif
  6346. }
  6347. static void connect_conn(struct mg_connection *c) {
  6348. union usa usa;
  6349. socklen_t n = sizeof(usa);
  6350. // Use getpeername() to test whether we have connected
  6351. if (getpeername(FD(c), &usa.sa, &n) == 0) {
  6352. c->is_connecting = 0;
  6353. mg_call(c, MG_EV_CONNECT, NULL);
  6354. MG_EPOLL_MOD(c, 0);
  6355. if (c->is_tls_hs) mg_tls_handshake(c);
  6356. } else {
  6357. mg_error(c, "socket error");
  6358. }
  6359. }
  6360. static void setsockopts(struct mg_connection *c) {
  6361. #if MG_ENABLE_FREERTOS_TCP || MG_ARCH == MG_ARCH_AZURERTOS || \
  6362. MG_ARCH == MG_ARCH_TIRTOS
  6363. (void) c;
  6364. #else
  6365. int on = 1;
  6366. #if !defined(SOL_TCP)
  6367. #define SOL_TCP IPPROTO_TCP
  6368. #endif
  6369. if (setsockopt(FD(c), SOL_TCP, TCP_NODELAY, (char *) &on, sizeof(on)) != 0)
  6370. (void) 0;
  6371. if (setsockopt(FD(c), SOL_SOCKET, SO_KEEPALIVE, (char *) &on, sizeof(on)) !=
  6372. 0)
  6373. (void) 0;
  6374. #endif
  6375. }
  6376. void mg_connect_resolved(struct mg_connection *c) {
  6377. int type = c->is_udp ? SOCK_DGRAM : SOCK_STREAM;
  6378. int rc, af = c->rem.is_ip6 ? AF_INET6 : AF_INET; // c->rem has resolved IP
  6379. c->fd = S2PTR(socket(af, type, 0)); // Create outbound socket
  6380. c->is_resolving = 0; // Clear resolving flag
  6381. if (FD(c) == MG_INVALID_SOCKET) {
  6382. mg_error(c, "socket(): %d", MG_SOCK_ERR(-1));
  6383. } else if (c->is_udp) {
  6384. MG_EPOLL_ADD(c);
  6385. #if MG_ARCH == MG_ARCH_TIRTOS
  6386. union usa usa; // TI-RTOS NDK requires binding to receive on UDP sockets
  6387. socklen_t slen = tousa(&c->loc, &usa);
  6388. if ((rc = bind(c->fd, &usa.sa, slen)) != 0)
  6389. MG_ERROR(("bind: %d", MG_SOCK_ERR(rc)));
  6390. #endif
  6391. mg_call(c, MG_EV_RESOLVE, NULL);
  6392. mg_call(c, MG_EV_CONNECT, NULL);
  6393. } else {
  6394. union usa usa;
  6395. socklen_t slen = tousa(&c->rem, &usa);
  6396. mg_set_non_blocking_mode(FD(c));
  6397. setsockopts(c);
  6398. MG_EPOLL_ADD(c);
  6399. mg_call(c, MG_EV_RESOLVE, NULL);
  6400. rc = connect(FD(c), &usa.sa, slen); // Attempt to connect
  6401. if (rc == 0) { // Success
  6402. mg_call(c, MG_EV_CONNECT, NULL); // Send MG_EV_CONNECT to the user
  6403. } else if (MG_SOCK_PENDING(rc)) { // Need to wait for TCP handshake
  6404. MG_DEBUG(("%lu %ld -> %M pend", c->id, c->fd, mg_print_ip_port, &c->rem));
  6405. c->is_connecting = 1;
  6406. } else {
  6407. mg_error(c, "connect: %d", MG_SOCK_ERR(rc));
  6408. }
  6409. }
  6410. }
  6411. static MG_SOCKET_TYPE raccept(MG_SOCKET_TYPE sock, union usa *usa,
  6412. socklen_t *len) {
  6413. MG_SOCKET_TYPE fd = MG_INVALID_SOCKET;
  6414. do {
  6415. memset(usa, 0, sizeof(*usa));
  6416. fd = accept(sock, &usa->sa, len);
  6417. } while (MG_SOCK_INTR(fd));
  6418. return fd;
  6419. }
  6420. static void accept_conn(struct mg_mgr *mgr, struct mg_connection *lsn) {
  6421. #if MG_ARCH == MG_ARCH_UNIX
  6422. //pthread_mutex_lock(&WSlock);
  6423. #endif
  6424. struct mg_connection *c = NULL;
  6425. union usa usa;
  6426. socklen_t sa_len = sizeof(usa);
  6427. MG_SOCKET_TYPE fd = raccept(FD(lsn), &usa, &sa_len);
  6428. if (fd == MG_INVALID_SOCKET) {
  6429. #if MG_ARCH == MG_ARCH_AZURERTOS || defined(__ECOS)
  6430. // AzureRTOS, in non-block socket mode can mark listening socket readable
  6431. // even it is not. See comment for 'select' func implementation in
  6432. // nx_bsd.c That's not an error, just should try later
  6433. if (errno != EAGAIN)
  6434. #endif
  6435. MG_ERROR(("%lu accept failed, errno %d", lsn->id, MG_SOCK_ERR(-1)));
  6436. #if (MG_ARCH != MG_ARCH_WIN32) && !MG_ENABLE_FREERTOS_TCP && \
  6437. (MG_ARCH != MG_ARCH_TIRTOS) && !MG_ENABLE_POLL && !MG_ENABLE_EPOLL
  6438. } else if ((long) fd >= FD_SETSIZE) {
  6439. MG_ERROR(("%ld > %ld", (long) fd, (long) FD_SETSIZE));
  6440. closesocket(fd);
  6441. #endif
  6442. } else if ((c = mg_alloc_conn(mgr)) == NULL) {
  6443. MG_ERROR(("%lu OOM", lsn->id));
  6444. closesocket(fd);
  6445. } else {
  6446. tomgaddr(&usa, &c->rem, sa_len != sizeof(usa.sin));
  6447. LIST_ADD_HEAD(struct mg_connection, &mgr->conns, c);
  6448. c->fd = S2PTR(fd);
  6449. MG_EPOLL_ADD(c);
  6450. mg_set_non_blocking_mode(FD(c));
  6451. setsockopts(c);
  6452. c->is_accepted = 1;
  6453. c->is_hexdumping = lsn->is_hexdumping;
  6454. c->loc = lsn->loc;
  6455. c->pfn = lsn->pfn;
  6456. c->pfn_data = lsn->pfn_data;
  6457. c->fn = lsn->fn;
  6458. c->fn_data = lsn->fn_data;
  6459. MG_DEBUG(("%lu %ld accepted %M -> %M", c->id, c->fd, mg_print_ip_port,
  6460. &c->rem, mg_print_ip_port, &c->loc));
  6461. mg_call(c, MG_EV_OPEN, NULL);
  6462. mg_call(c, MG_EV_ACCEPT, NULL);
  6463. }
  6464. #if MG_ARCH == MG_ARCH_UNIX
  6465. //pthread_mutex_unlock(&WSlock);
  6466. #endif
  6467. }
  6468. static bool can_read(const struct mg_connection *c) {
  6469. return c->is_full == false;
  6470. }
  6471. static bool can_write(const struct mg_connection *c) {
  6472. return c->is_connecting || (c->send.len > 0 && c->is_tls_hs == 0);
  6473. }
  6474. static bool skip_iotest(const struct mg_connection *c) {
  6475. return (c->is_closing || c->is_resolving || FD(c) == MG_INVALID_SOCKET) ||
  6476. (can_read(c) == false && can_write(c) == false);
  6477. }
  6478. static void mg_iotest(struct mg_mgr *mgr, int ms) {
  6479. #if MG_ENABLE_FREERTOS_TCP
  6480. struct mg_connection *c;
  6481. for (c = mgr->conns; c != NULL; c = c->next) {
  6482. c->is_readable = c->is_writable = 0;
  6483. if (skip_iotest(c)) continue;
  6484. if (can_read(c))
  6485. FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_READ | eSELECT_EXCEPT);
  6486. if (can_write(c)) FreeRTOS_FD_SET(c->fd, mgr->ss, eSELECT_WRITE);
  6487. if (c->is_closing) ms = 1;
  6488. }
  6489. FreeRTOS_select(mgr->ss, pdMS_TO_TICKS(ms));
  6490. for (c = mgr->conns; c != NULL; c = c->next) {
  6491. EventBits_t bits = FreeRTOS_FD_ISSET(c->fd, mgr->ss);
  6492. c->is_readable = bits & (eSELECT_READ | eSELECT_EXCEPT) ? 1U : 0;
  6493. c->is_writable = bits & eSELECT_WRITE ? 1U : 0;
  6494. if (c->fd != MG_INVALID_SOCKET)
  6495. FreeRTOS_FD_CLR(c->fd, mgr->ss,
  6496. eSELECT_READ | eSELECT_EXCEPT | eSELECT_WRITE);
  6497. }
  6498. #elif MG_ENABLE_EPOLL
  6499. size_t max = 1;
  6500. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6501. c->is_readable = c->is_writable = 0;
  6502. if (mg_tls_pending(c) > 0) ms = 1, c->is_readable = 1;
  6503. if (can_write(c)) MG_EPOLL_MOD(c, 1);
  6504. if (c->is_closing) ms = 1;
  6505. max++;
  6506. }
  6507. struct epoll_event *evs = (struct epoll_event *) alloca(max * sizeof(evs[0]));
  6508. int n = epoll_wait(mgr->epoll_fd, evs, (int) max, ms);
  6509. for (int i = 0; i < n; i++) {
  6510. struct mg_connection *c = (struct mg_connection *) evs[i].data.ptr;
  6511. if (evs[i].events & EPOLLERR) {
  6512. mg_error(c, "socket error");
  6513. } else if (c->is_readable == 0) {
  6514. bool rd = evs[i].events & (EPOLLIN | EPOLLHUP);
  6515. bool wr = evs[i].events & EPOLLOUT;
  6516. c->is_readable = can_read(c) && rd ? 1U : 0;
  6517. c->is_writable = can_write(c) && wr ? 1U : 0;
  6518. }
  6519. }
  6520. (void) skip_iotest;
  6521. #elif MG_ENABLE_POLL
  6522. nfds_t n = 0;
  6523. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) n++;
  6524. struct pollfd *fds = (struct pollfd *) alloca(n * sizeof(fds[0]));
  6525. memset(fds, 0, n * sizeof(fds[0]));
  6526. n = 0;
  6527. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6528. c->is_readable = c->is_writable = 0;
  6529. if (skip_iotest(c)) {
  6530. // Socket not valid, ignore
  6531. } else if (mg_tls_pending(c) > 0) {
  6532. ms = 1; // Don't wait if TLS is ready
  6533. } else {
  6534. fds[n].fd = FD(c);
  6535. if (can_read(c)) fds[n].events |= POLLIN;
  6536. if (can_write(c)) fds[n].events |= POLLOUT;
  6537. if (c->is_closing) ms = 1;
  6538. n++;
  6539. }
  6540. }
  6541. // MG_INFO(("poll n=%d ms=%d", (int) n, ms));
  6542. if (poll(fds, n, ms) < 0) {
  6543. #if MG_ARCH == MG_ARCH_WIN32
  6544. if (n == 0) Sleep(ms); // On Windows, poll fails if no sockets
  6545. #endif
  6546. memset(fds, 0, n * sizeof(fds[0]));
  6547. }
  6548. n = 0;
  6549. for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
  6550. if (skip_iotest(c)) {
  6551. // Socket not valid, ignore
  6552. } else if (mg_tls_pending(c) > 0) {
  6553. c->is_readable = 1;
  6554. } else {
  6555. if (fds[n].revents & POLLERR) {
  6556. mg_error(c, "socket error");
  6557. } else {
  6558. c->is_readable =
  6559. (unsigned) (fds[n].revents & (POLLIN | POLLHUP) ? 1 : 0);
  6560. c->is_writable = (unsigned) (fds[n].revents & POLLOUT ? 1 : 0);
  6561. }
  6562. n++;
  6563. }
  6564. }
  6565. #else
  6566. struct timeval tv = {ms / 1000, (ms % 1000) * 1000}, tv_zero = {0, 0}, *tvp;
  6567. struct mg_connection *c;
  6568. fd_set rset, wset, eset;
  6569. MG_SOCKET_TYPE maxfd = 0;
  6570. int rc;
  6571. FD_ZERO(&rset);
  6572. FD_ZERO(&wset);
  6573. FD_ZERO(&eset);
  6574. tvp = ms < 0 ? NULL : &tv;
  6575. for (c = mgr->conns; c != NULL; c = c->next) {
  6576. c->is_readable = c->is_writable = 0;
  6577. if (skip_iotest(c)) continue;
  6578. FD_SET(FD(c), &eset);
  6579. if (can_read(c)) FD_SET(FD(c), &rset);
  6580. if (can_write(c)) FD_SET(FD(c), &wset);
  6581. if (mg_tls_pending(c) > 0) tvp = &tv_zero;
  6582. if (FD(c) > maxfd) maxfd = FD(c);
  6583. if (c->is_closing) ms = 1;
  6584. }
  6585. if ((rc = select((int) maxfd + 1, &rset, &wset, &eset, tvp)) < 0) {
  6586. #if MG_ARCH == MG_ARCH_WIN32
  6587. if (maxfd == 0) Sleep(ms); // On Windows, select fails if no sockets
  6588. #else
  6589. MG_ERROR(("select: %d %d", rc, MG_SOCK_ERR(rc)));
  6590. #endif
  6591. FD_ZERO(&rset);
  6592. FD_ZERO(&wset);
  6593. FD_ZERO(&eset);
  6594. }
  6595. for (c = mgr->conns; c != NULL; c = c->next) {
  6596. if (FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &eset)) {
  6597. mg_error(c, "socket error");
  6598. } else {
  6599. c->is_readable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &rset);
  6600. c->is_writable = FD(c) != MG_INVALID_SOCKET && FD_ISSET(FD(c), &wset);
  6601. if (mg_tls_pending(c) > 0) c->is_readable = 1;
  6602. }
  6603. }
  6604. #endif
  6605. }
  6606. static bool mg_socketpair(MG_SOCKET_TYPE sp[2], union usa usa[2]) {
  6607. socklen_t n = sizeof(usa[0].sin);
  6608. bool success = false;
  6609. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6610. (void) memset(&usa[0], 0, sizeof(usa[0]));
  6611. usa[0].sin.sin_family = AF_INET;
  6612. *(uint32_t *) &usa->sin.sin_addr = mg_htonl(0x7f000001U); // 127.0.0.1
  6613. usa[1] = usa[0];
  6614. if ((sp[0] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  6615. (sp[1] = socket(AF_INET, SOCK_DGRAM, 0)) != MG_INVALID_SOCKET &&
  6616. bind(sp[0], &usa[0].sa, n) == 0 && //
  6617. bind(sp[1], &usa[1].sa, n) == 0 && //
  6618. getsockname(sp[0], &usa[0].sa, &n) == 0 && //
  6619. getsockname(sp[1], &usa[1].sa, &n) == 0 && //
  6620. connect(sp[0], &usa[1].sa, n) == 0 && //
  6621. connect(sp[1], &usa[0].sa, n) == 0) { //
  6622. success = true;
  6623. }
  6624. if (!success) {
  6625. if (sp[0] != MG_INVALID_SOCKET) closesocket(sp[0]);
  6626. if (sp[1] != MG_INVALID_SOCKET) closesocket(sp[1]);
  6627. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6628. }
  6629. return success;
  6630. }
  6631. // mg_wakeup() event handler
  6632. static void wufn(struct mg_connection *c, int ev, void *ev_data) {
  6633. if (ev == MG_EV_READ) {
  6634. unsigned long *id = (unsigned long *) c->recv.buf;
  6635. // MG_INFO(("Got data"));
  6636. // mg_hexdump(c->recv.buf, c->recv.len);
  6637. if (c->recv.len >= sizeof(*id)) {
  6638. struct mg_connection *t;
  6639. for (t = c->mgr->conns; t != NULL; t = t->next) {
  6640. if (t->id == *id) {
  6641. struct mg_str data = mg_str_n((char *) c->recv.buf + sizeof(*id),
  6642. c->recv.len - sizeof(*id));
  6643. mg_call(t, MG_EV_WAKEUP, &data);
  6644. }
  6645. }
  6646. }
  6647. c->recv.len = 0; // Consume received data
  6648. } else if (ev == MG_EV_CLOSE) {
  6649. closesocket(c->mgr->pipe); // When we're closing, close the other
  6650. c->mgr->pipe = MG_INVALID_SOCKET; // side of the socketpair, too
  6651. }
  6652. (void) ev_data;
  6653. }
  6654. bool mg_wakeup_init(struct mg_mgr *mgr) {
  6655. bool ok = false;
  6656. if (mgr->pipe == MG_INVALID_SOCKET) {
  6657. union usa usa[2];
  6658. MG_SOCKET_TYPE sp[2] = {MG_INVALID_SOCKET, MG_INVALID_SOCKET};
  6659. struct mg_connection *c = NULL;
  6660. if (!mg_socketpair(sp, usa)) {
  6661. MG_ERROR(("Cannot create socket pair"));
  6662. } else if ((c = mg_wrapfd(mgr, (int) sp[1], wufn, NULL)) == NULL) {
  6663. closesocket(sp[0]);
  6664. closesocket(sp[1]);
  6665. sp[0] = sp[1] = MG_INVALID_SOCKET;
  6666. } else {
  6667. tomgaddr(&usa[0], &c->rem, false);
  6668. MG_DEBUG(("%lu %p pipe %lu", c->id, c->fd, (unsigned long) sp[0]));
  6669. mgr->pipe = sp[0];
  6670. ok = true;
  6671. }
  6672. }
  6673. return ok;
  6674. }
  6675. bool mg_wakeup(struct mg_mgr *mgr, unsigned long conn_id, const void *buf,
  6676. size_t len) {
  6677. if (mgr->pipe != MG_INVALID_SOCKET && conn_id > 0) {
  6678. char *extended_buf = (char *) alloca(len + sizeof(conn_id));
  6679. memcpy(extended_buf, &conn_id, sizeof(conn_id));
  6680. memcpy(extended_buf + sizeof(conn_id), buf, len);
  6681. send(mgr->pipe, extended_buf, len + sizeof(conn_id), MSG_NONBLOCKING);
  6682. return true;
  6683. }
  6684. return false;
  6685. }
  6686. void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
  6687. struct mg_connection *c, *tmp;
  6688. uint64_t now;
  6689. mg_iotest(mgr, ms);
  6690. now = mg_millis();
  6691. mg_timer_poll(&mgr->timers, now);
  6692. for (c = mgr->conns; c != NULL; c = tmp) {
  6693. bool is_resp = c->is_resp;
  6694. tmp = c->next;
  6695. mg_call(c, MG_EV_POLL, &now);
  6696. if (is_resp && !c->is_resp) {
  6697. long n = 0;
  6698. mg_call(c, MG_EV_READ, &n);
  6699. }
  6700. MG_VERBOSE(("%lu %c%c %c%c%c%c%c", c->id, c->is_readable ? 'r' : '-',
  6701. c->is_writable ? 'w' : '-', c->is_tls ? 'T' : 't',
  6702. c->is_connecting ? 'C' : 'c', c->is_tls_hs ? 'H' : 'h',
  6703. c->is_resolving ? 'R' : 'r', c->is_closing ? 'C' : 'c'));
  6704. if (c->is_resolving || c->is_closing) {
  6705. // Do nothing
  6706. } else if (c->is_listening && c->is_udp == 0) {
  6707. if (c->is_readable) accept_conn(mgr, c);
  6708. } else if (c->is_connecting) {
  6709. if (c->is_readable || c->is_writable) connect_conn(c);
  6710. //} else if (c->is_tls_hs) {
  6711. // if ((c->is_readable || c->is_writable)) mg_tls_handshake(c);
  6712. } else {
  6713. if (c->is_readable) read_conn(c);
  6714. if (c->is_writable) write_conn(c);
  6715. }
  6716. if (c->is_draining && c->send.len == 0) c->is_closing = 1;
  6717. if (c->is_closing) close_conn(c);
  6718. }
  6719. }
  6720. #endif
  6721. #ifdef MG_ENABLE_LINES
  6722. #line 1 "src/ssi.c"
  6723. #endif
  6724. #ifndef MG_MAX_SSI_DEPTH
  6725. #define MG_MAX_SSI_DEPTH 5
  6726. #endif
  6727. #ifndef MG_SSI_BUFSIZ
  6728. #define MG_SSI_BUFSIZ 1024
  6729. #endif
  6730. #if MG_ENABLE_SSI
  6731. static char *mg_ssi(const char *path, const char *root, int depth) {
  6732. struct mg_iobuf b = {NULL, 0, 0, MG_IO_SIZE};
  6733. FILE *fp = fopen(path, "rb");
  6734. if (fp != NULL) {
  6735. char buf[MG_SSI_BUFSIZ], arg[sizeof(buf)];
  6736. int ch, intag = 0;
  6737. size_t len = 0;
  6738. buf[0] = arg[0] = '\0';
  6739. while ((ch = fgetc(fp)) != EOF) {
  6740. if (intag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
  6741. buf[len++] = (char) (ch & 0xff);
  6742. buf[len] = '\0';
  6743. if (sscanf(buf, "<!--#include file=\"%[^\"]", arg)) {
  6744. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10],
  6745. *p = (char *) path + strlen(path), *data;
  6746. while (p > path && p[-1] != MG_DIRSEP && p[-1] != '/') p--;
  6747. mg_snprintf(tmp, sizeof(tmp), "%.*s%s", (int) (p - path), path, arg);
  6748. if (depth < MG_MAX_SSI_DEPTH &&
  6749. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  6750. mg_iobuf_add(&b, b.len, data, strlen(data));
  6751. free(data);
  6752. } else {
  6753. MG_ERROR(("%s: file=%s error or too deep", path, arg));
  6754. }
  6755. } else if (sscanf(buf, "<!--#include virtual=\"%[^\"]", arg)) {
  6756. char tmp[MG_PATH_MAX + MG_SSI_BUFSIZ + 10], *data;
  6757. mg_snprintf(tmp, sizeof(tmp), "%s%s", root, arg);
  6758. if (depth < MG_MAX_SSI_DEPTH &&
  6759. (data = mg_ssi(tmp, root, depth + 1)) != NULL) {
  6760. mg_iobuf_add(&b, b.len, data, strlen(data));
  6761. free(data);
  6762. } else {
  6763. MG_ERROR(("%s: virtual=%s error or too deep", path, arg));
  6764. }
  6765. } else {
  6766. // Unknown SSI tag
  6767. MG_ERROR(("Unknown SSI tag: %.*s", (int) len, buf));
  6768. mg_iobuf_add(&b, b.len, buf, len);
  6769. }
  6770. intag = 0;
  6771. len = 0;
  6772. } else if (ch == '<') {
  6773. intag = 1;
  6774. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  6775. len = 0;
  6776. buf[len++] = (char) (ch & 0xff);
  6777. } else if (intag) {
  6778. if (len == 5 && strncmp(buf, "<!--#", 5) != 0) {
  6779. intag = 0;
  6780. } else if (len >= sizeof(buf) - 2) {
  6781. MG_ERROR(("%s: SSI tag is too large", path));
  6782. len = 0;
  6783. }
  6784. buf[len++] = (char) (ch & 0xff);
  6785. } else {
  6786. buf[len++] = (char) (ch & 0xff);
  6787. if (len >= sizeof(buf)) {
  6788. mg_iobuf_add(&b, b.len, buf, len);
  6789. len = 0;
  6790. }
  6791. }
  6792. }
  6793. if (len > 0) mg_iobuf_add(&b, b.len, buf, len);
  6794. if (b.len > 0) mg_iobuf_add(&b, b.len, "", 1); // nul-terminate
  6795. fclose(fp);
  6796. }
  6797. (void) depth;
  6798. (void) root;
  6799. return (char *) b.buf;
  6800. }
  6801. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  6802. const char *fullpath) {
  6803. const char *headers = "Content-Type: text/html; charset=utf-8\r\n";
  6804. char *data = mg_ssi(fullpath, root, 0);
  6805. mg_http_reply(c, 200, headers, "%s", data == NULL ? "" : data);
  6806. free(data);
  6807. }
  6808. #else
  6809. void mg_http_serve_ssi(struct mg_connection *c, const char *root,
  6810. const char *fullpath) {
  6811. mg_http_reply(c, 501, NULL, "SSI not enabled");
  6812. (void) root, (void) fullpath;
  6813. }
  6814. #endif
  6815. #ifdef MG_ENABLE_LINES
  6816. #line 1 "src/str.c"
  6817. #endif
  6818. struct mg_str mg_str_s(const char *s) {
  6819. struct mg_str str = {s, s == NULL ? 0 : strlen(s)};
  6820. return str;
  6821. }
  6822. struct mg_str mg_str_n(const char *s, size_t n) {
  6823. struct mg_str str = {s, n};
  6824. return str;
  6825. }
  6826. int mg_lower(const char *s) {
  6827. int c = *s;
  6828. if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
  6829. return c;
  6830. }
  6831. int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
  6832. int diff = 0;
  6833. if (len > 0) do {
  6834. diff = mg_lower(s1++) - mg_lower(s2++);
  6835. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  6836. return diff;
  6837. }
  6838. int mg_casecmp(const char *s1, const char *s2) {
  6839. return mg_ncasecmp(s1, s2, (size_t) ~0);
  6840. }
  6841. int mg_vcmp(const struct mg_str *s1, const char *s2) {
  6842. size_t n2 = strlen(s2), n1 = s1->len;
  6843. int r = strncmp(s1->ptr, s2, (n1 < n2) ? n1 : n2);
  6844. if (r == 0) return (int) (n1 - n2);
  6845. return r;
  6846. }
  6847. int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
  6848. size_t n2 = strlen(str2), n1 = str1->len;
  6849. int r = mg_ncasecmp(str1->ptr, str2, (n1 < n2) ? n1 : n2);
  6850. if (r == 0) return (int) (n1 - n2);
  6851. return r;
  6852. }
  6853. struct mg_str mg_strdup(const struct mg_str s) {
  6854. struct mg_str r = {NULL, 0};
  6855. if (s.len > 0 && s.ptr != NULL) {
  6856. char *sc = (char *) calloc(1, s.len + 1);
  6857. if (sc != NULL) {
  6858. memcpy(sc, s.ptr, s.len);
  6859. sc[s.len] = '\0';
  6860. r.ptr = sc;
  6861. r.len = s.len;
  6862. }
  6863. }
  6864. return r;
  6865. }
  6866. int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
  6867. size_t i = 0;
  6868. while (i < str1.len && i < str2.len) {
  6869. int c1 = str1.ptr[i];
  6870. int c2 = str2.ptr[i];
  6871. if (c1 < c2) return -1;
  6872. if (c1 > c2) return 1;
  6873. i++;
  6874. }
  6875. if (i < str1.len) return 1;
  6876. if (i < str2.len) return -1;
  6877. return 0;
  6878. }
  6879. const char *mg_strstr(const struct mg_str haystack,
  6880. const struct mg_str needle) {
  6881. size_t i;
  6882. if (needle.len > haystack.len) return NULL;
  6883. if (needle.len == 0) return haystack.ptr;
  6884. for (i = 0; i <= haystack.len - needle.len; i++) {
  6885. if (memcmp(haystack.ptr + i, needle.ptr, needle.len) == 0) {
  6886. return haystack.ptr + i;
  6887. }
  6888. }
  6889. return NULL;
  6890. }
  6891. static bool is_space(int c) {
  6892. return c == ' ' || c == '\r' || c == '\n' || c == '\t';
  6893. }
  6894. struct mg_str mg_strstrip(struct mg_str s) {
  6895. while (s.len > 0 && is_space((int) *s.ptr)) s.ptr++, s.len--;
  6896. while (s.len > 0 && is_space((int) *(s.ptr + s.len - 1))) s.len--;
  6897. return s;
  6898. }
  6899. bool mg_match(struct mg_str s, struct mg_str p, struct mg_str *caps) {
  6900. size_t i = 0, j = 0, ni = 0, nj = 0;
  6901. if (caps) caps->ptr = NULL, caps->len = 0;
  6902. while (i < p.len || j < s.len) {
  6903. if (i < p.len && j < s.len && (p.ptr[i] == '?' || s.ptr[j] == p.ptr[i])) {
  6904. if (caps == NULL) {
  6905. } else if (p.ptr[i] == '?') {
  6906. caps->ptr = &s.ptr[j], caps->len = 1; // Finalize `?` cap
  6907. caps++, caps->ptr = NULL, caps->len = 0; // Init next cap
  6908. } else if (caps->ptr != NULL && caps->len == 0) {
  6909. caps->len = (size_t) (&s.ptr[j] - caps->ptr); // Finalize current cap
  6910. caps++, caps->len = 0, caps->ptr = NULL; // Init next cap
  6911. }
  6912. i++, j++;
  6913. } else if (i < p.len && (p.ptr[i] == '*' || p.ptr[i] == '#')) {
  6914. if (caps && !caps->ptr) caps->len = 0, caps->ptr = &s.ptr[j]; // Init cap
  6915. ni = i++, nj = j + 1;
  6916. } else if (nj > 0 && nj <= s.len && (p.ptr[ni] == '#' || s.ptr[j] != '/')) {
  6917. i = ni, j = nj;
  6918. if (caps && caps->ptr == NULL && caps->len == 0) {
  6919. caps--, caps->len = 0; // Restart previous cap
  6920. }
  6921. } else {
  6922. return false;
  6923. }
  6924. }
  6925. if (caps && caps->ptr && caps->len == 0) {
  6926. caps->len = (size_t) (&s.ptr[j] - caps->ptr);
  6927. }
  6928. return true;
  6929. }
  6930. bool mg_globmatch(const char *s1, size_t n1, const char *s2, size_t n2) {
  6931. return mg_match(mg_str_n(s2, n2), mg_str_n(s1, n1), NULL);
  6932. }
  6933. static size_t mg_nce(const char *s, size_t n, size_t ofs, size_t *koff,
  6934. size_t *klen, size_t *voff, size_t *vlen, char delim) {
  6935. size_t kvlen, kl;
  6936. for (kvlen = 0; ofs + kvlen < n && s[ofs + kvlen] != delim;) kvlen++;
  6937. for (kl = 0; kl < kvlen && s[ofs + kl] != '=';) kl++;
  6938. if (koff != NULL) *koff = ofs;
  6939. if (klen != NULL) *klen = kl;
  6940. if (voff != NULL) *voff = kl < kvlen ? ofs + kl + 1 : 0;
  6941. if (vlen != NULL) *vlen = kl < kvlen ? kvlen - kl - 1 : 0;
  6942. ofs += kvlen + 1;
  6943. return ofs > n ? n : ofs;
  6944. }
  6945. bool mg_split(struct mg_str *s, struct mg_str *k, struct mg_str *v, char sep) {
  6946. size_t koff = 0, klen = 0, voff = 0, vlen = 0, off = 0;
  6947. if (s->ptr == NULL || s->len == 0) return 0;
  6948. off = mg_nce(s->ptr, s->len, 0, &koff, &klen, &voff, &vlen, sep);
  6949. if (k != NULL) *k = mg_str_n(s->ptr + koff, klen);
  6950. if (v != NULL) *v = mg_str_n(s->ptr + voff, vlen);
  6951. *s = mg_str_n(s->ptr + off, s->len - off);
  6952. return off > 0;
  6953. }
  6954. bool mg_commalist(struct mg_str *s, struct mg_str *k, struct mg_str *v) {
  6955. return mg_split(s, k, v, ',');
  6956. }
  6957. char *mg_hex(const void *buf, size_t len, char *to) {
  6958. const unsigned char *p = (const unsigned char *) buf;
  6959. const char *hex = "0123456789abcdef";
  6960. size_t i = 0;
  6961. for (; len--; p++) {
  6962. to[i++] = hex[p[0] >> 4];
  6963. to[i++] = hex[p[0] & 0x0f];
  6964. }
  6965. to[i] = '\0';
  6966. return to;
  6967. }
  6968. static unsigned char mg_unhex_nimble(unsigned char c) {
  6969. return (c >= '0' && c <= '9') ? (unsigned char) (c - '0')
  6970. : (c >= 'A' && c <= 'F') ? (unsigned char) (c - '7')
  6971. : (unsigned char) (c - 'W');
  6972. }
  6973. unsigned long mg_unhexn(const char *s, size_t len) {
  6974. unsigned long i = 0, v = 0;
  6975. for (i = 0; i < len; i++) v <<= 4, v |= mg_unhex_nimble(((uint8_t *) s)[i]);
  6976. return v;
  6977. }
  6978. void mg_unhex(const char *buf, size_t len, unsigned char *to) {
  6979. size_t i;
  6980. for (i = 0; i < len; i += 2) {
  6981. to[i >> 1] = (unsigned char) mg_unhexn(&buf[i], 2);
  6982. }
  6983. }
  6984. bool mg_path_is_sane(const char *path) {
  6985. const char *s = path;
  6986. for (; s[0] != '\0'; s++) {
  6987. if (s == path || s[0] == '/' || s[0] == '\\') { // Subdir?
  6988. if (s[1] == '.' && s[2] == '.') return false; // Starts with ..
  6989. }
  6990. }
  6991. return true;
  6992. }
  6993. #ifdef MG_ENABLE_LINES
  6994. #line 1 "src/timer.c"
  6995. #endif
  6996. #define MG_TIMER_CALLED 4
  6997. void mg_timer_init(struct mg_timer **head, struct mg_timer *t, uint64_t ms,
  6998. unsigned flags, void (*fn)(void *), void *arg) {
  6999. t->id = 0, t->period_ms = ms, t->expire = 0;
  7000. t->flags = flags, t->fn = fn, t->arg = arg, t->next = *head;
  7001. *head = t;
  7002. }
  7003. void mg_timer_free(struct mg_timer **head, struct mg_timer *t) {
  7004. while (*head && *head != t) head = &(*head)->next;
  7005. if (*head) *head = t->next;
  7006. }
  7007. // t: expiration time, prd: period, now: current time. Return true if expired
  7008. bool mg_timer_expired(uint64_t *t, uint64_t prd, uint64_t now) {
  7009. if (now + prd < *t) *t = 0; // Time wrapped? Reset timer
  7010. if (*t == 0) *t = now + prd; // Firt poll? Set expiration
  7011. if (*t > now) return false; // Not expired yet, return
  7012. *t = (now - *t) > prd ? now + prd : *t + prd; // Next expiration time
  7013. return true; // Expired, return true
  7014. }
  7015. void mg_timer_poll(struct mg_timer **head, uint64_t now_ms) {
  7016. struct mg_timer *t, *tmp;
  7017. for (t = *head; t != NULL; t = tmp) {
  7018. bool once = t->expire == 0 && (t->flags & MG_TIMER_RUN_NOW) &&
  7019. !(t->flags & MG_TIMER_CALLED); // Handle MG_TIMER_NOW only once
  7020. bool expired = mg_timer_expired(&t->expire, t->period_ms, now_ms);
  7021. tmp = t->next;
  7022. if (!once && !expired) continue;
  7023. if ((t->flags & MG_TIMER_REPEAT) || !(t->flags & MG_TIMER_CALLED)) {
  7024. t->fn(t->arg);
  7025. }
  7026. t->flags |= MG_TIMER_CALLED;
  7027. }
  7028. }
  7029. #ifdef MG_ENABLE_LINES
  7030. #line 1 "src/tls_aes128.c"
  7031. #endif
  7032. /******************************************************************************
  7033. *
  7034. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7035. *
  7036. * This is a simple and straightforward implementation of the AES Rijndael
  7037. * 128-bit block cipher designed by Vincent Rijmen and Joan Daemen. The focus
  7038. * of this work was correctness & accuracy. It is written in 'C' without any
  7039. * particular focus upon optimization or speed. It should be endian (memory
  7040. * byte order) neutral since the few places that care are handled explicitly.
  7041. *
  7042. * This implementation of Rijndael was created by Steven M. Gibson of GRC.com.
  7043. *
  7044. * It is intended for general purpose use, but was written in support of GRC's
  7045. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7046. *
  7047. * See: http://csrc.nist.gov/archive/aes/rijndael/wsdindex.html
  7048. *
  7049. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7050. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7051. *
  7052. *******************************************************************************/
  7053. #if MG_TLS == MG_TLS_BUILTIN
  7054. static int aes_tables_inited = 0; // run-once flag for performing key
  7055. // expasion table generation (see below)
  7056. /*
  7057. * The following static local tables must be filled-in before the first use of
  7058. * the GCM or AES ciphers. They are used for the AES key expansion/scheduling
  7059. * and once built are read-only and thread safe. The "gcm_initialize" function
  7060. * must be called once during system initialization to populate these arrays
  7061. * for subsequent use by the AES key scheduler. If they have not been built
  7062. * before attempted use, an error will be returned to the caller.
  7063. *
  7064. * NOTE: GCM Encryption/Decryption does NOT REQUIRE AES decryption. Since
  7065. * GCM uses AES in counter-mode, where the AES cipher output is XORed with
  7066. * the GCM input, we ONLY NEED AES encryption. Thus, to save space AES
  7067. * decryption is typically disabled by setting AES_DECRYPTION to 0 in aes.h.
  7068. */
  7069. // We always need our forward tables
  7070. static uchar FSb[256]; // Forward substitution box (FSb)
  7071. static uint32_t FT0[256]; // Forward key schedule assembly tables
  7072. static uint32_t FT1[256];
  7073. static uint32_t FT2[256];
  7074. static uint32_t FT3[256];
  7075. #if AES_DECRYPTION // We ONLY need reverse for decryption
  7076. static uchar RSb[256]; // Reverse substitution box (RSb)
  7077. static uint32_t RT0[256]; // Reverse key schedule assembly tables
  7078. static uint32_t RT1[256];
  7079. static uint32_t RT2[256];
  7080. static uint32_t RT3[256];
  7081. #endif /* AES_DECRYPTION */
  7082. static uint32_t RCON[10]; // AES round constants
  7083. /*
  7084. * Platform Endianness Neutralizing Load and Store Macro definitions
  7085. * AES wants platform-neutral Little Endian (LE) byte ordering
  7086. */
  7087. #define GET_UINT32_LE(n, b, i) \
  7088. { \
  7089. (n) = ((uint32_t) (b)[(i)]) | ((uint32_t) (b)[(i) + 1] << 8) | \
  7090. ((uint32_t) (b)[(i) + 2] << 16) | ((uint32_t) (b)[(i) + 3] << 24); \
  7091. }
  7092. #define PUT_UINT32_LE(n, b, i) \
  7093. { \
  7094. (b)[(i)] = (uchar) ((n)); \
  7095. (b)[(i) + 1] = (uchar) ((n) >> 8); \
  7096. (b)[(i) + 2] = (uchar) ((n) >> 16); \
  7097. (b)[(i) + 3] = (uchar) ((n) >> 24); \
  7098. }
  7099. /*
  7100. * AES forward and reverse encryption round processing macros
  7101. */
  7102. #define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7103. { \
  7104. X0 = *RK++ ^ FT0[(Y0) &0xFF] ^ FT1[(Y1 >> 8) & 0xFF] ^ \
  7105. FT2[(Y2 >> 16) & 0xFF] ^ FT3[(Y3 >> 24) & 0xFF]; \
  7106. \
  7107. X1 = *RK++ ^ FT0[(Y1) &0xFF] ^ FT1[(Y2 >> 8) & 0xFF] ^ \
  7108. FT2[(Y3 >> 16) & 0xFF] ^ FT3[(Y0 >> 24) & 0xFF]; \
  7109. \
  7110. X2 = *RK++ ^ FT0[(Y2) &0xFF] ^ FT1[(Y3 >> 8) & 0xFF] ^ \
  7111. FT2[(Y0 >> 16) & 0xFF] ^ FT3[(Y1 >> 24) & 0xFF]; \
  7112. \
  7113. X3 = *RK++ ^ FT0[(Y3) &0xFF] ^ FT1[(Y0 >> 8) & 0xFF] ^ \
  7114. FT2[(Y1 >> 16) & 0xFF] ^ FT3[(Y2 >> 24) & 0xFF]; \
  7115. }
  7116. #define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \
  7117. { \
  7118. X0 = *RK++ ^ RT0[(Y0) &0xFF] ^ RT1[(Y3 >> 8) & 0xFF] ^ \
  7119. RT2[(Y2 >> 16) & 0xFF] ^ RT3[(Y1 >> 24) & 0xFF]; \
  7120. \
  7121. X1 = *RK++ ^ RT0[(Y1) &0xFF] ^ RT1[(Y0 >> 8) & 0xFF] ^ \
  7122. RT2[(Y3 >> 16) & 0xFF] ^ RT3[(Y2 >> 24) & 0xFF]; \
  7123. \
  7124. X2 = *RK++ ^ RT0[(Y2) &0xFF] ^ RT1[(Y1 >> 8) & 0xFF] ^ \
  7125. RT2[(Y0 >> 16) & 0xFF] ^ RT3[(Y3 >> 24) & 0xFF]; \
  7126. \
  7127. X3 = *RK++ ^ RT0[(Y3) &0xFF] ^ RT1[(Y2 >> 8) & 0xFF] ^ \
  7128. RT2[(Y1 >> 16) & 0xFF] ^ RT3[(Y0 >> 24) & 0xFF]; \
  7129. }
  7130. /*
  7131. * These macros improve the readability of the key
  7132. * generation initialization code by collapsing
  7133. * repetitive common operations into logical pieces.
  7134. */
  7135. #define ROTL8(x) ((x << 8) & 0xFFFFFFFF) | (x >> 24)
  7136. #define XTIME(x) ((x << 1) ^ ((x & 0x80) ? 0x1B : 0x00))
  7137. #define MUL(x, y) ((x && y) ? pow[(log[x] + log[y]) % 255] : 0)
  7138. #define MIX(x, y) \
  7139. { \
  7140. y = ((y << 1) | (y >> 7)) & 0xFF; \
  7141. x ^= y; \
  7142. }
  7143. #define CPY128 \
  7144. { \
  7145. *RK++ = *SK++; \
  7146. *RK++ = *SK++; \
  7147. *RK++ = *SK++; \
  7148. *RK++ = *SK++; \
  7149. }
  7150. /******************************************************************************
  7151. *
  7152. * AES_INIT_KEYGEN_TABLES
  7153. *
  7154. * Fills the AES key expansion tables allocated above with their static
  7155. * data. This is not "per key" data, but static system-wide read-only
  7156. * table data. THIS FUNCTION IS NOT THREAD SAFE. It must be called once
  7157. * at system initialization to setup the tables for all subsequent use.
  7158. *
  7159. ******************************************************************************/
  7160. void aes_init_keygen_tables(void) {
  7161. int i, x, y, z; // general purpose iteration and computation locals
  7162. int pow[256];
  7163. int log[256];
  7164. if (aes_tables_inited) return;
  7165. // fill the 'pow' and 'log' tables over GF(2^8)
  7166. for (i = 0, x = 1; i < 256; i++) {
  7167. pow[i] = x;
  7168. log[x] = i;
  7169. x = (x ^ XTIME(x)) & 0xFF;
  7170. }
  7171. // compute the round constants
  7172. for (i = 0, x = 1; i < 10; i++) {
  7173. RCON[i] = (uint32_t) x;
  7174. x = XTIME(x) & 0xFF;
  7175. }
  7176. // fill the forward and reverse substitution boxes
  7177. FSb[0x00] = 0x63;
  7178. #if AES_DECRYPTION // whether AES decryption is supported
  7179. RSb[0x63] = 0x00;
  7180. #endif /* AES_DECRYPTION */
  7181. for (i = 1; i < 256; i++) {
  7182. x = y = pow[255 - log[i]];
  7183. MIX(x, y);
  7184. MIX(x, y);
  7185. MIX(x, y);
  7186. MIX(x, y);
  7187. FSb[i] = (uchar) (x ^= 0x63);
  7188. #if AES_DECRYPTION // whether AES decryption is supported
  7189. RSb[x] = (uchar) i;
  7190. #endif /* AES_DECRYPTION */
  7191. }
  7192. // generate the forward and reverse key expansion tables
  7193. for (i = 0; i < 256; i++) {
  7194. x = FSb[i];
  7195. y = XTIME(x) & 0xFF;
  7196. z = (y ^ x) & 0xFF;
  7197. FT0[i] = ((uint32_t) y) ^ ((uint32_t) x << 8) ^ ((uint32_t) x << 16) ^
  7198. ((uint32_t) z << 24);
  7199. FT1[i] = ROTL8(FT0[i]);
  7200. FT2[i] = ROTL8(FT1[i]);
  7201. FT3[i] = ROTL8(FT2[i]);
  7202. #if AES_DECRYPTION // whether AES decryption is supported
  7203. x = RSb[i];
  7204. RT0[i] = ((uint32_t) MUL(0x0E, x)) ^ ((uint32_t) MUL(0x09, x) << 8) ^
  7205. ((uint32_t) MUL(0x0D, x) << 16) ^ ((uint32_t) MUL(0x0B, x) << 24);
  7206. RT1[i] = ROTL8(RT0[i]);
  7207. RT2[i] = ROTL8(RT1[i]);
  7208. RT3[i] = ROTL8(RT2[i]);
  7209. #endif /* AES_DECRYPTION */
  7210. }
  7211. aes_tables_inited = 1; // flag that the tables have been generated
  7212. } // to permit subsequent use of the AES cipher
  7213. /******************************************************************************
  7214. *
  7215. * AES_SET_ENCRYPTION_KEY
  7216. *
  7217. * This is called by 'aes_setkey' when we're establishing a key for
  7218. * subsequent encryption. We give it a pointer to the encryption
  7219. * context, a pointer to the key, and the key's length in bytes.
  7220. * Valid lengths are: 16, 24 or 32 bytes (128, 192, 256 bits).
  7221. *
  7222. ******************************************************************************/
  7223. static int aes_set_encryption_key(aes_context *ctx, const uchar *key, uint keysize) {
  7224. uint i; // general purpose iteration local
  7225. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7226. for (i = 0; i < (keysize >> 2); i++) {
  7227. GET_UINT32_LE(RK[i], key, i << 2);
  7228. }
  7229. switch (ctx->rounds) {
  7230. case 10:
  7231. for (i = 0; i < 10; i++, RK += 4) {
  7232. RK[4] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[3] >> 8) & 0xFF]) ^
  7233. ((uint32_t) FSb[(RK[3] >> 16) & 0xFF] << 8) ^
  7234. ((uint32_t) FSb[(RK[3] >> 24) & 0xFF] << 16) ^
  7235. ((uint32_t) FSb[(RK[3]) & 0xFF] << 24);
  7236. RK[5] = RK[1] ^ RK[4];
  7237. RK[6] = RK[2] ^ RK[5];
  7238. RK[7] = RK[3] ^ RK[6];
  7239. }
  7240. break;
  7241. case 12:
  7242. for (i = 0; i < 8; i++, RK += 6) {
  7243. RK[6] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[5] >> 8) & 0xFF]) ^
  7244. ((uint32_t) FSb[(RK[5] >> 16) & 0xFF] << 8) ^
  7245. ((uint32_t) FSb[(RK[5] >> 24) & 0xFF] << 16) ^
  7246. ((uint32_t) FSb[(RK[5]) & 0xFF] << 24);
  7247. RK[7] = RK[1] ^ RK[6];
  7248. RK[8] = RK[2] ^ RK[7];
  7249. RK[9] = RK[3] ^ RK[8];
  7250. RK[10] = RK[4] ^ RK[9];
  7251. RK[11] = RK[5] ^ RK[10];
  7252. }
  7253. break;
  7254. case 14:
  7255. for (i = 0; i < 7; i++, RK += 8) {
  7256. RK[8] = RK[0] ^ RCON[i] ^ ((uint32_t) FSb[(RK[7] >> 8) & 0xFF]) ^
  7257. ((uint32_t) FSb[(RK[7] >> 16) & 0xFF] << 8) ^
  7258. ((uint32_t) FSb[(RK[7] >> 24) & 0xFF] << 16) ^
  7259. ((uint32_t) FSb[(RK[7]) & 0xFF] << 24);
  7260. RK[9] = RK[1] ^ RK[8];
  7261. RK[10] = RK[2] ^ RK[9];
  7262. RK[11] = RK[3] ^ RK[10];
  7263. RK[12] = RK[4] ^ ((uint32_t) FSb[(RK[11]) & 0xFF]) ^
  7264. ((uint32_t) FSb[(RK[11] >> 8) & 0xFF] << 8) ^
  7265. ((uint32_t) FSb[(RK[11] >> 16) & 0xFF] << 16) ^
  7266. ((uint32_t) FSb[(RK[11] >> 24) & 0xFF] << 24);
  7267. RK[13] = RK[5] ^ RK[12];
  7268. RK[14] = RK[6] ^ RK[13];
  7269. RK[15] = RK[7] ^ RK[14];
  7270. }
  7271. break;
  7272. default:
  7273. return -1;
  7274. }
  7275. return (0);
  7276. }
  7277. #if AES_DECRYPTION // whether AES decryption is supported
  7278. /******************************************************************************
  7279. *
  7280. * AES_SET_DECRYPTION_KEY
  7281. *
  7282. * This is called by 'aes_setkey' when we're establishing a
  7283. * key for subsequent decryption. We give it a pointer to
  7284. * the encryption context, a pointer to the key, and the key's
  7285. * length in bits. Valid lengths are: 128, 192, or 256 bits.
  7286. *
  7287. ******************************************************************************/
  7288. static int aes_set_decryption_key(aes_context *ctx, const uchar *key, uint keysize) {
  7289. int i, j;
  7290. aes_context cty; // a calling aes context for set_encryption_key
  7291. uint32_t *RK = ctx->rk; // initialize our RoundKey buffer pointer
  7292. uint32_t *SK;
  7293. int ret;
  7294. cty.rounds = ctx->rounds; // initialize our local aes context
  7295. cty.rk = cty.buf; // round count and key buf pointer
  7296. if ((ret = aes_set_encryption_key(&cty, key, keysize)) != 0) return (ret);
  7297. SK = cty.rk + cty.rounds * 4;
  7298. CPY128 // copy a 128-bit block from *SK to *RK
  7299. for (i = ctx->rounds - 1, SK -= 8; i > 0; i--, SK -= 8) {
  7300. for (j = 0; j < 4; j++, SK++) {
  7301. *RK++ = RT0[FSb[(*SK) & 0xFF]] ^ RT1[FSb[(*SK >> 8) & 0xFF]] ^
  7302. RT2[FSb[(*SK >> 16) & 0xFF]] ^ RT3[FSb[(*SK >> 24) & 0xFF]];
  7303. }
  7304. }
  7305. CPY128 // copy a 128-bit block from *SK to *RK
  7306. memset(&cty, 0, sizeof(aes_context)); // clear local aes context
  7307. return (0);
  7308. }
  7309. #endif /* AES_DECRYPTION */
  7310. /******************************************************************************
  7311. *
  7312. * AES_SETKEY
  7313. *
  7314. * Invoked to establish the key schedule for subsequent encryption/decryption
  7315. *
  7316. ******************************************************************************/
  7317. int aes_setkey(aes_context *ctx, // AES context provided by our caller
  7318. int mode, // ENCRYPT or DECRYPT flag
  7319. const uchar *key, // pointer to the key
  7320. uint keysize) // key length in bytes
  7321. {
  7322. // since table initialization is not thread safe, we could either add
  7323. // system-specific mutexes and init the AES key generation tables on
  7324. // demand, or ask the developer to simply call "gcm_initialize" once during
  7325. // application startup before threading begins. That's what we choose.
  7326. if (!aes_tables_inited) return (-1); // fail the call when not inited.
  7327. ctx->mode = mode; // capture the key type we're creating
  7328. ctx->rk = ctx->buf; // initialize our round key pointer
  7329. switch (keysize) // set the rounds count based upon the keysize
  7330. {
  7331. case 16:
  7332. ctx->rounds = 10;
  7333. break; // 16-byte, 128-bit key
  7334. case 24:
  7335. ctx->rounds = 12;
  7336. break; // 24-byte, 192-bit key
  7337. case 32:
  7338. ctx->rounds = 14;
  7339. break; // 32-byte, 256-bit key
  7340. default:
  7341. return (-1);
  7342. }
  7343. #if AES_DECRYPTION
  7344. if (mode == DECRYPT) // expand our key for encryption or decryption
  7345. return (aes_set_decryption_key(ctx, key, keysize));
  7346. else /* ENCRYPT */
  7347. #endif /* AES_DECRYPTION */
  7348. return (aes_set_encryption_key(ctx, key, keysize));
  7349. }
  7350. /******************************************************************************
  7351. *
  7352. * AES_CIPHER
  7353. *
  7354. * Perform AES encryption and decryption.
  7355. * The AES context will have been setup with the encryption mode
  7356. * and all keying information appropriate for the task.
  7357. *
  7358. ******************************************************************************/
  7359. int aes_cipher(aes_context *ctx, const uchar input[16], uchar output[16]) {
  7360. int i;
  7361. uint32_t *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3; // general purpose locals
  7362. RK = ctx->rk;
  7363. GET_UINT32_LE(X0, input, 0);
  7364. X0 ^= *RK++; // load our 128-bit
  7365. GET_UINT32_LE(X1, input, 4);
  7366. X1 ^= *RK++; // input buffer in a storage
  7367. GET_UINT32_LE(X2, input, 8);
  7368. X2 ^= *RK++; // memory endian-neutral way
  7369. GET_UINT32_LE(X3, input, 12);
  7370. X3 ^= *RK++;
  7371. #if AES_DECRYPTION // whether AES decryption is supported
  7372. if (ctx->mode == DECRYPT) {
  7373. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  7374. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7375. AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  7376. }
  7377. AES_RROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7378. X0 = *RK++ ^ ((uint32_t) RSb[(Y0) &0xFF]) ^
  7379. ((uint32_t) RSb[(Y3 >> 8) & 0xFF] << 8) ^
  7380. ((uint32_t) RSb[(Y2 >> 16) & 0xFF] << 16) ^
  7381. ((uint32_t) RSb[(Y1 >> 24) & 0xFF] << 24);
  7382. X1 = *RK++ ^ ((uint32_t) RSb[(Y1) &0xFF]) ^
  7383. ((uint32_t) RSb[(Y0 >> 8) & 0xFF] << 8) ^
  7384. ((uint32_t) RSb[(Y3 >> 16) & 0xFF] << 16) ^
  7385. ((uint32_t) RSb[(Y2 >> 24) & 0xFF] << 24);
  7386. X2 = *RK++ ^ ((uint32_t) RSb[(Y2) &0xFF]) ^
  7387. ((uint32_t) RSb[(Y1 >> 8) & 0xFF] << 8) ^
  7388. ((uint32_t) RSb[(Y0 >> 16) & 0xFF] << 16) ^
  7389. ((uint32_t) RSb[(Y3 >> 24) & 0xFF] << 24);
  7390. X3 = *RK++ ^ ((uint32_t) RSb[(Y3) &0xFF]) ^
  7391. ((uint32_t) RSb[(Y2 >> 8) & 0xFF] << 8) ^
  7392. ((uint32_t) RSb[(Y1 >> 16) & 0xFF] << 16) ^
  7393. ((uint32_t) RSb[(Y0 >> 24) & 0xFF] << 24);
  7394. } else /* ENCRYPT */
  7395. {
  7396. #endif /* AES_DECRYPTION */
  7397. for (i = (ctx->rounds >> 1) - 1; i > 0; i--) {
  7398. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7399. AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3);
  7400. }
  7401. AES_FROUND(Y0, Y1, Y2, Y3, X0, X1, X2, X3);
  7402. X0 = *RK++ ^ ((uint32_t) FSb[(Y0) &0xFF]) ^
  7403. ((uint32_t) FSb[(Y1 >> 8) & 0xFF] << 8) ^
  7404. ((uint32_t) FSb[(Y2 >> 16) & 0xFF] << 16) ^
  7405. ((uint32_t) FSb[(Y3 >> 24) & 0xFF] << 24);
  7406. X1 = *RK++ ^ ((uint32_t) FSb[(Y1) &0xFF]) ^
  7407. ((uint32_t) FSb[(Y2 >> 8) & 0xFF] << 8) ^
  7408. ((uint32_t) FSb[(Y3 >> 16) & 0xFF] << 16) ^
  7409. ((uint32_t) FSb[(Y0 >> 24) & 0xFF] << 24);
  7410. X2 = *RK++ ^ ((uint32_t) FSb[(Y2) &0xFF]) ^
  7411. ((uint32_t) FSb[(Y3 >> 8) & 0xFF] << 8) ^
  7412. ((uint32_t) FSb[(Y0 >> 16) & 0xFF] << 16) ^
  7413. ((uint32_t) FSb[(Y1 >> 24) & 0xFF] << 24);
  7414. X3 = *RK++ ^ ((uint32_t) FSb[(Y3) &0xFF]) ^
  7415. ((uint32_t) FSb[(Y0 >> 8) & 0xFF] << 8) ^
  7416. ((uint32_t) FSb[(Y1 >> 16) & 0xFF] << 16) ^
  7417. ((uint32_t) FSb[(Y2 >> 24) & 0xFF] << 24);
  7418. #if AES_DECRYPTION // whether AES decryption is supported
  7419. }
  7420. #endif /* AES_DECRYPTION */
  7421. PUT_UINT32_LE(X0, output, 0);
  7422. PUT_UINT32_LE(X1, output, 4);
  7423. PUT_UINT32_LE(X2, output, 8);
  7424. PUT_UINT32_LE(X3, output, 12);
  7425. return (0);
  7426. }
  7427. /* end of aes.c */
  7428. /******************************************************************************
  7429. *
  7430. * THIS SOURCE CODE IS HEREBY PLACED INTO THE PUBLIC DOMAIN FOR THE GOOD OF ALL
  7431. *
  7432. * This is a simple and straightforward implementation of AES-GCM authenticated
  7433. * encryption. The focus of this work was correctness & accuracy. It is written
  7434. * in straight 'C' without any particular focus upon optimization or speed. It
  7435. * should be endian (memory byte order) neutral since the few places that care
  7436. * are handled explicitly.
  7437. *
  7438. * This implementation of AES-GCM was created by Steven M. Gibson of GRC.com.
  7439. *
  7440. * It is intended for general purpose use, but was written in support of GRC's
  7441. * reference implementation of the SQRL (Secure Quick Reliable Login) client.
  7442. *
  7443. * See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  7444. * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/
  7445. * gcm/gcm-revised-spec.pdf
  7446. *
  7447. * NO COPYRIGHT IS CLAIMED IN THIS WORK, HOWEVER, NEITHER IS ANY WARRANTY MADE
  7448. * REGARDING ITS FITNESS FOR ANY PARTICULAR PURPOSE. USE IT AT YOUR OWN RISK.
  7449. *
  7450. *******************************************************************************/
  7451. /******************************************************************************
  7452. * ==== IMPLEMENTATION WARNING ====
  7453. *
  7454. * This code was developed for use within SQRL's fixed environmnent. Thus, it
  7455. * is somewhat less "general purpose" than it would be if it were designed as
  7456. * a general purpose AES-GCM library. Specifically, it bothers with almost NO
  7457. * error checking on parameter limits, buffer bounds, etc. It assumes that it
  7458. * is being invoked by its author or by someone who understands the values it
  7459. * expects to receive. Its behavior will be undefined otherwise.
  7460. *
  7461. * All functions that might fail are defined to return 'ints' to indicate a
  7462. * problem. Most do not do so now. But this allows for error propagation out
  7463. * of internal functions if robust error checking should ever be desired.
  7464. *
  7465. ******************************************************************************/
  7466. /* Calculating the "GHASH"
  7467. *
  7468. * There are many ways of calculating the so-called GHASH in software, each with
  7469. * a traditional size vs performance tradeoff. The GHASH (Galois field hash) is
  7470. * an intriguing construction which takes two 128-bit strings (also the cipher's
  7471. * block size and the fundamental operation size for the system) and hashes them
  7472. * into a third 128-bit result.
  7473. *
  7474. * Many implementation solutions have been worked out that use large precomputed
  7475. * table lookups in place of more time consuming bit fiddling, and this approach
  7476. * can be scaled easily upward or downward as needed to change the time/space
  7477. * tradeoff. It's been studied extensively and there's a solid body of theory
  7478. * and practice. For example, without using any lookup tables an implementation
  7479. * might obtain 119 cycles per byte throughput, whereas using a simple, though
  7480. * large, key-specific 64 kbyte 8-bit lookup table the performance jumps to 13
  7481. * cycles per byte.
  7482. *
  7483. * And Intel's processors have, since 2010, included an instruction which does
  7484. * the entire 128x128->128 bit job in just several 64x64->128 bit pieces.
  7485. *
  7486. * Since SQRL is interactive, and only processing a few 128-bit blocks, I've
  7487. * settled upon a relatively slower but appealing small-table compromise which
  7488. * folds a bunch of not only time consuming but also bit twiddling into a simple
  7489. * 16-entry table which is attributed to Victor Shoup's 1996 work while at
  7490. * Bellcore: "On Fast and Provably Secure MessageAuthentication Based on
  7491. * Universal Hashing." See: http://www.shoup.net/papers/macs.pdf
  7492. * See, also section 4.1 of the "gcm-revised-spec" cited above.
  7493. */
  7494. /*
  7495. * This 16-entry table of pre-computed constants is used by the
  7496. * GHASH multiplier to improve over a strictly table-free but
  7497. * significantly slower 128x128 bit multiple within GF(2^128).
  7498. */
  7499. static const uint64_t last4[16] = {
  7500. 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
  7501. 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0};
  7502. /*
  7503. * Platform Endianness Neutralizing Load and Store Macro definitions
  7504. * GCM wants platform-neutral Big Endian (BE) byte ordering
  7505. */
  7506. #define GET_UINT32_BE(n, b, i) \
  7507. { \
  7508. (n) = ((uint32_t) (b)[(i)] << 24) | ((uint32_t) (b)[(i) + 1] << 16) | \
  7509. ((uint32_t) (b)[(i) + 2] << 8) | ((uint32_t) (b)[(i) + 3]); \
  7510. }
  7511. #define PUT_UINT32_BE(n, b, i) \
  7512. { \
  7513. (b)[(i)] = (uchar) ((n) >> 24); \
  7514. (b)[(i) + 1] = (uchar) ((n) >> 16); \
  7515. (b)[(i) + 2] = (uchar) ((n) >> 8); \
  7516. (b)[(i) + 3] = (uchar) ((n)); \
  7517. }
  7518. /******************************************************************************
  7519. *
  7520. * GCM_INITIALIZE
  7521. *
  7522. * Must be called once to initialize the GCM library.
  7523. *
  7524. * At present, this only calls the AES keygen table generator, which expands
  7525. * the AES keying tables for use. This is NOT A THREAD-SAFE function, so it
  7526. * MUST be called during system initialization before a multi-threading
  7527. * environment is running.
  7528. *
  7529. ******************************************************************************/
  7530. int gcm_initialize(void) {
  7531. aes_init_keygen_tables();
  7532. return (0);
  7533. }
  7534. /******************************************************************************
  7535. *
  7536. * GCM_MULT
  7537. *
  7538. * Performs a GHASH operation on the 128-bit input vector 'x', setting
  7539. * the 128-bit output vector to 'x' times H using our precomputed tables.
  7540. * 'x' and 'output' are seen as elements of GCM's GF(2^128) Galois field.
  7541. *
  7542. ******************************************************************************/
  7543. static void gcm_mult(gcm_context *ctx, // pointer to established context
  7544. const uchar x[16], // pointer to 128-bit input vector
  7545. uchar output[16]) // pointer to 128-bit output vector
  7546. {
  7547. int i;
  7548. uchar lo, hi, rem;
  7549. uint64_t zh, zl;
  7550. lo = (uchar) (x[15] & 0x0f);
  7551. hi = (uchar) (x[15] >> 4);
  7552. zh = ctx->HH[lo];
  7553. zl = ctx->HL[lo];
  7554. for (i = 15; i >= 0; i--) {
  7555. lo = (uchar) (x[i] & 0x0f);
  7556. hi = (uchar) (x[i] >> 4);
  7557. if (i != 15) {
  7558. rem = (uchar) (zl & 0x0f);
  7559. zl = (zh << 60) | (zl >> 4);
  7560. zh = (zh >> 4);
  7561. zh ^= (uint64_t) last4[rem] << 48;
  7562. zh ^= ctx->HH[lo];
  7563. zl ^= ctx->HL[lo];
  7564. }
  7565. rem = (uchar) (zl & 0x0f);
  7566. zl = (zh << 60) | (zl >> 4);
  7567. zh = (zh >> 4);
  7568. zh ^= (uint64_t) last4[rem] << 48;
  7569. zh ^= ctx->HH[hi];
  7570. zl ^= ctx->HL[hi];
  7571. }
  7572. PUT_UINT32_BE(zh >> 32, output, 0);
  7573. PUT_UINT32_BE(zh, output, 4);
  7574. PUT_UINT32_BE(zl >> 32, output, 8);
  7575. PUT_UINT32_BE(zl, output, 12);
  7576. }
  7577. /******************************************************************************
  7578. *
  7579. * GCM_SETKEY
  7580. *
  7581. * This is called to set the AES-GCM key. It initializes the AES key
  7582. * and populates the gcm context's pre-calculated HTables.
  7583. *
  7584. ******************************************************************************/
  7585. int gcm_setkey(gcm_context *ctx, // pointer to caller-provided gcm context
  7586. const uchar *key, // pointer to the AES encryption key
  7587. const uint keysize) // size in bytes (must be 16, 24, 32 for
  7588. // 128, 192 or 256-bit keys respectively)
  7589. {
  7590. int ret, i, j;
  7591. uint64_t hi, lo;
  7592. uint64_t vl, vh;
  7593. unsigned char h[16];
  7594. memset(ctx, 0, sizeof(gcm_context)); // zero caller-provided GCM context
  7595. memset(h, 0, 16); // initialize the block to encrypt
  7596. // encrypt the null 128-bit block to generate a key-based value
  7597. // which is then used to initialize our GHASH lookup tables
  7598. if ((ret = aes_setkey(&ctx->aes_ctx, ENCRYPT, key, keysize)) != 0)
  7599. return (ret);
  7600. if ((ret = aes_cipher(&ctx->aes_ctx, h, h)) != 0) return (ret);
  7601. GET_UINT32_BE(hi, h, 0); // pack h as two 64-bit ints, big-endian
  7602. GET_UINT32_BE(lo, h, 4);
  7603. vh = (uint64_t) hi << 32 | lo;
  7604. GET_UINT32_BE(hi, h, 8);
  7605. GET_UINT32_BE(lo, h, 12);
  7606. vl = (uint64_t) hi << 32 | lo;
  7607. ctx->HL[8] = vl; // 8 = 1000 corresponds to 1 in GF(2^128)
  7608. ctx->HH[8] = vh;
  7609. ctx->HH[0] = 0; // 0 corresponds to 0 in GF(2^128)
  7610. ctx->HL[0] = 0;
  7611. for (i = 4; i > 0; i >>= 1) {
  7612. uint32_t T = (uint32_t) (vl & 1) * 0xe1000000U;
  7613. vl = (vh << 63) | (vl >> 1);
  7614. vh = (vh >> 1) ^ ((uint64_t) T << 32);
  7615. ctx->HL[i] = vl;
  7616. ctx->HH[i] = vh;
  7617. }
  7618. for (i = 2; i < 16; i <<= 1) {
  7619. uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
  7620. vh = *HiH;
  7621. vl = *HiL;
  7622. for (j = 1; j < i; j++) {
  7623. HiH[j] = vh ^ ctx->HH[j];
  7624. HiL[j] = vl ^ ctx->HL[j];
  7625. }
  7626. }
  7627. return (0);
  7628. }
  7629. /******************************************************************************
  7630. *
  7631. * GCM processing occurs four phases: SETKEY, START, UPDATE and FINISH.
  7632. *
  7633. * SETKEY:
  7634. *
  7635. * START: Sets the Encryption/Decryption mode.
  7636. * Accepts the initialization vector and additional data.
  7637. *
  7638. * UPDATE: Encrypts or decrypts the plaintext or ciphertext.
  7639. *
  7640. * FINISH: Performs a final GHASH to generate the authentication tag.
  7641. *
  7642. ******************************************************************************
  7643. *
  7644. * GCM_START
  7645. *
  7646. * Given a user-provided GCM context, this initializes it, sets the encryption
  7647. * mode, and preprocesses the initialization vector and additional AEAD data.
  7648. *
  7649. ******************************************************************************/
  7650. int gcm_start(gcm_context *ctx, // pointer to user-provided GCM context
  7651. int mode, // GCM_ENCRYPT or GCM_DECRYPT
  7652. const uchar *iv, // pointer to initialization vector
  7653. size_t iv_len, // IV length in bytes (should == 12)
  7654. const uchar *add, // ptr to additional AEAD data (NULL if none)
  7655. size_t add_len) // length of additional AEAD data (bytes)
  7656. {
  7657. int ret; // our error return if the AES encrypt fails
  7658. uchar work_buf[16]; // XOR source built from provided IV if len != 16
  7659. const uchar *p; // general purpose array pointer
  7660. size_t use_len; // byte count to process, up to 16 bytes
  7661. size_t i; // local loop iterator
  7662. // since the context might be reused under the same key
  7663. // we zero the working buffers for this next new process
  7664. memset(ctx->y, 0x00, sizeof(ctx->y));
  7665. memset(ctx->buf, 0x00, sizeof(ctx->buf));
  7666. ctx->len = 0;
  7667. ctx->add_len = 0;
  7668. ctx->mode = mode; // set the GCM encryption/decryption mode
  7669. ctx->aes_ctx.mode = ENCRYPT; // GCM *always* runs AES in ENCRYPTION mode
  7670. if (iv_len == 12) { // GCM natively uses a 12-byte, 96-bit IV
  7671. memcpy(ctx->y, iv, iv_len); // copy the IV to the top of the 'y' buff
  7672. ctx->y[15] = 1; // start "counting" from 1 (not 0)
  7673. } else // if we don't have a 12-byte IV, we GHASH whatever we've been given
  7674. {
  7675. memset(work_buf, 0x00, 16); // clear the working buffer
  7676. PUT_UINT32_BE(iv_len * 8, work_buf, 12); // place the IV into buffer
  7677. p = iv;
  7678. while (iv_len > 0) {
  7679. use_len = (iv_len < 16) ? iv_len : 16;
  7680. for (i = 0; i < use_len; i++) ctx->y[i] ^= p[i];
  7681. gcm_mult(ctx, ctx->y, ctx->y);
  7682. iv_len -= use_len;
  7683. p += use_len;
  7684. }
  7685. for (i = 0; i < 16; i++) ctx->y[i] ^= work_buf[i];
  7686. gcm_mult(ctx, ctx->y, ctx->y);
  7687. }
  7688. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ctx->base_ectr)) != 0)
  7689. return (ret);
  7690. ctx->add_len = add_len;
  7691. p = add;
  7692. while (add_len > 0) {
  7693. use_len = (add_len < 16) ? add_len : 16;
  7694. for (i = 0; i < use_len; i++) ctx->buf[i] ^= p[i];
  7695. gcm_mult(ctx, ctx->buf, ctx->buf);
  7696. add_len -= use_len;
  7697. p += use_len;
  7698. }
  7699. return (0);
  7700. }
  7701. /******************************************************************************
  7702. *
  7703. * GCM_UPDATE
  7704. *
  7705. * This is called once or more to process bulk plaintext or ciphertext data.
  7706. * We give this some number of bytes of input and it returns the same number
  7707. * of output bytes. If called multiple times (which is fine) all but the final
  7708. * invocation MUST be called with length mod 16 == 0. (Only the final call can
  7709. * have a partial block length of < 128 bits.)
  7710. *
  7711. ******************************************************************************/
  7712. int gcm_update(gcm_context *ctx, // pointer to user-provided GCM context
  7713. size_t length, // length, in bytes, of data to process
  7714. const uchar *input, // pointer to source data
  7715. uchar *output) // pointer to destination data
  7716. {
  7717. int ret; // our error return if the AES encrypt fails
  7718. uchar ectr[16]; // counter-mode cipher output for XORing
  7719. size_t use_len; // byte count to process, up to 16 bytes
  7720. size_t i; // local loop iterator
  7721. ctx->len += length; // bump the GCM context's running length count
  7722. while (length > 0) {
  7723. // clamp the length to process at 16 bytes
  7724. use_len = (length < 16) ? length : 16;
  7725. // increment the context's 128-bit IV||Counter 'y' vector
  7726. for (i = 16; i > 12; i--)
  7727. if (++ctx->y[i - 1] != 0) break;
  7728. // encrypt the context's 'y' vector under the established key
  7729. if ((ret = aes_cipher(&ctx->aes_ctx, ctx->y, ectr)) != 0) return (ret);
  7730. // encrypt or decrypt the input to the output
  7731. if (ctx->mode == ENCRYPT) {
  7732. for (i = 0; i < use_len; i++) {
  7733. // XOR the cipher's ouptut vector (ectr) with our input
  7734. output[i] = (uchar) (ectr[i] ^ input[i]);
  7735. // now we mix in our data into the authentication hash.
  7736. // if we're ENcrypting we XOR in the post-XOR (output)
  7737. // results, but if we're DEcrypting we XOR in the input
  7738. // data
  7739. ctx->buf[i] ^= output[i];
  7740. }
  7741. } else {
  7742. for (i = 0; i < use_len; i++) {
  7743. // but if we're DEcrypting we XOR in the input data first,
  7744. // i.e. before saving to ouput data, otherwise if the input
  7745. // and output buffer are the same (inplace decryption) we
  7746. // would not get the correct auth tag
  7747. ctx->buf[i] ^= input[i];
  7748. // XOR the cipher's ouptut vector (ectr) with our input
  7749. output[i] = (uchar) (ectr[i] ^ input[i]);
  7750. }
  7751. }
  7752. gcm_mult(ctx, ctx->buf, ctx->buf); // perform a GHASH operation
  7753. length -= use_len; // drop the remaining byte count to process
  7754. input += use_len; // bump our input pointer forward
  7755. output += use_len; // bump our output pointer forward
  7756. }
  7757. return (0);
  7758. }
  7759. /******************************************************************************
  7760. *
  7761. * GCM_FINISH
  7762. *
  7763. * This is called once after all calls to GCM_UPDATE to finalize the GCM.
  7764. * It performs the final GHASH to produce the resulting authentication TAG.
  7765. *
  7766. ******************************************************************************/
  7767. int gcm_finish(gcm_context *ctx, // pointer to user-provided GCM context
  7768. uchar *tag, // pointer to buffer which receives the tag
  7769. size_t tag_len) // length, in bytes, of the tag-receiving buf
  7770. {
  7771. uchar work_buf[16];
  7772. uint64_t orig_len = ctx->len * 8;
  7773. uint64_t orig_add_len = ctx->add_len * 8;
  7774. size_t i;
  7775. if (tag_len != 0) memcpy(tag, ctx->base_ectr, tag_len);
  7776. if (orig_len || orig_add_len) {
  7777. memset(work_buf, 0x00, 16);
  7778. PUT_UINT32_BE((orig_add_len >> 32), work_buf, 0);
  7779. PUT_UINT32_BE((orig_add_len), work_buf, 4);
  7780. PUT_UINT32_BE((orig_len >> 32), work_buf, 8);
  7781. PUT_UINT32_BE((orig_len), work_buf, 12);
  7782. for (i = 0; i < 16; i++) ctx->buf[i] ^= work_buf[i];
  7783. gcm_mult(ctx, ctx->buf, ctx->buf);
  7784. for (i = 0; i < tag_len; i++) tag[i] ^= ctx->buf[i];
  7785. }
  7786. return (0);
  7787. }
  7788. /******************************************************************************
  7789. *
  7790. * GCM_CRYPT_AND_TAG
  7791. *
  7792. * This either encrypts or decrypts the user-provided data and, either
  7793. * way, generates an authentication tag of the requested length. It must be
  7794. * called with a GCM context whose key has already been set with GCM_SETKEY.
  7795. *
  7796. * The user would typically call this explicitly to ENCRYPT a buffer of data
  7797. * and optional associated data, and produce its an authentication tag.
  7798. *
  7799. * To reverse the process the user would typically call the companion
  7800. * GCM_AUTH_DECRYPT function to decrypt data and verify a user-provided
  7801. * authentication tag. The GCM_AUTH_DECRYPT function calls this function
  7802. * to perform its decryption and tag generation, which it then compares.
  7803. *
  7804. ******************************************************************************/
  7805. int gcm_crypt_and_tag(
  7806. gcm_context *ctx, // gcm context with key already setup
  7807. int mode, // cipher direction: GCM_ENCRYPT or GCM_DECRYPT
  7808. const uchar *iv, // pointer to the 12-byte initialization vector
  7809. size_t iv_len, // byte length if the IV. should always be 12
  7810. const uchar *add, // pointer to the non-ciphered additional data
  7811. size_t add_len, // byte length of the additional AEAD data
  7812. const uchar *input, // pointer to the cipher data source
  7813. uchar *output, // pointer to the cipher data destination
  7814. size_t length, // byte length of the cipher data
  7815. uchar *tag, // pointer to the tag to be generated
  7816. size_t tag_len) // byte length of the tag to be generated
  7817. { /*
  7818. assuming that the caller has already invoked gcm_setkey to
  7819. prepare the gcm context with the keying material, we simply
  7820. invoke each of the three GCM sub-functions in turn...
  7821. */
  7822. gcm_start(ctx, mode, iv, iv_len, add, add_len);
  7823. gcm_update(ctx, length, input, output);
  7824. gcm_finish(ctx, tag, tag_len);
  7825. return (0);
  7826. }
  7827. /******************************************************************************
  7828. *
  7829. * GCM_AUTH_DECRYPT
  7830. *
  7831. * This DECRYPTS a user-provided data buffer with optional associated data.
  7832. * It then verifies a user-supplied authentication tag against the tag just
  7833. * re-created during decryption to verify that the data has not been altered.
  7834. *
  7835. * This function calls GCM_CRYPT_AND_TAG (above) to perform the decryption
  7836. * and authentication tag generation.
  7837. *
  7838. ******************************************************************************/
  7839. int gcm_auth_decrypt(
  7840. gcm_context *ctx, // gcm context with key already setup
  7841. const uchar *iv, // pointer to the 12-byte initialization vector
  7842. size_t iv_len, // byte length if the IV. should always be 12
  7843. const uchar *add, // pointer to the non-ciphered additional data
  7844. size_t add_len, // byte length of the additional AEAD data
  7845. const uchar *input, // pointer to the cipher data source
  7846. uchar *output, // pointer to the cipher data destination
  7847. size_t length, // byte length of the cipher data
  7848. const uchar *tag, // pointer to the tag to be authenticated
  7849. size_t tag_len) // byte length of the tag <= 16
  7850. {
  7851. uchar check_tag[16]; // the tag generated and returned by decryption
  7852. int diff; // an ORed flag to detect authentication errors
  7853. size_t i; // our local iterator
  7854. /*
  7855. we use GCM_DECRYPT_AND_TAG (above) to perform our decryption
  7856. (which is an identical XORing to reverse the previous one)
  7857. and also to re-generate the matching authentication tag
  7858. */
  7859. gcm_crypt_and_tag(ctx, DECRYPT, iv, iv_len, add, add_len, input, output,
  7860. length, check_tag, tag_len);
  7861. // now we verify the authentication tag in 'constant time'
  7862. for (diff = 0, i = 0; i < tag_len; i++) diff |= tag[i] ^ check_tag[i];
  7863. if (diff != 0) { // see whether any bits differed?
  7864. memset(output, 0, length); // if so... wipe the output data
  7865. return (GCM_AUTH_FAILURE); // return GCM_AUTH_FAILURE
  7866. }
  7867. return (0);
  7868. }
  7869. /******************************************************************************
  7870. *
  7871. * GCM_ZERO_CTX
  7872. *
  7873. * The GCM context contains both the GCM context and the AES context.
  7874. * This includes keying and key-related material which is security-
  7875. * sensitive, so it MUST be zeroed after use. This function does that.
  7876. *
  7877. ******************************************************************************/
  7878. void gcm_zero_ctx(gcm_context *ctx) {
  7879. // zero the context originally provided to us
  7880. memset(ctx, 0, sizeof(gcm_context));
  7881. }
  7882. //
  7883. // aes-gcm.c
  7884. // Pods
  7885. //
  7886. // Created by Markus Kosmal on 20/11/14.
  7887. //
  7888. //
  7889. int aes_gcm_encrypt(unsigned char *output, //
  7890. const unsigned char *input, size_t input_length,
  7891. const unsigned char *key, const size_t key_len,
  7892. const unsigned char *iv, const size_t iv_len,
  7893. unsigned char *aead, size_t aead_len, unsigned char *tag,
  7894. const size_t tag_len) {
  7895. int ret = 0; // our return value
  7896. gcm_context ctx; // includes the AES context structure
  7897. gcm_setkey(&ctx, key, (const uint) key_len);
  7898. ret = gcm_crypt_and_tag(&ctx, ENCRYPT, iv, iv_len, aead, aead_len, input, output,
  7899. input_length, tag, tag_len);
  7900. gcm_zero_ctx(&ctx);
  7901. return (ret);
  7902. }
  7903. int aes_gcm_decrypt(unsigned char *output, const unsigned char *input,
  7904. size_t input_length, const unsigned char *key,
  7905. const size_t key_len, const unsigned char *iv,
  7906. const size_t iv_len) {
  7907. int ret = 0; // our return value
  7908. gcm_context ctx; // includes the AES context structure
  7909. size_t tag_len = 0;
  7910. unsigned char *tag_buf = NULL;
  7911. gcm_setkey(&ctx, key, (const uint) key_len);
  7912. ret = gcm_crypt_and_tag(&ctx, DECRYPT, iv, iv_len, NULL, 0, input, output,
  7913. input_length, tag_buf, tag_len);
  7914. gcm_zero_ctx(&ctx);
  7915. return (ret);
  7916. }
  7917. #endif
  7918. // End of aes128 PD
  7919. #ifdef MG_ENABLE_LINES
  7920. #line 1 "src/tls_builtin.c"
  7921. #endif
  7922. #if MG_TLS == MG_TLS_BUILTIN
  7923. // handshake is re-entrant, so we need to keep track of its state
  7924. enum mg_tls_hs_state {
  7925. MG_TLS_HS_CLIENT_HELLO, // first, wait for ClientHello
  7926. MG_TLS_HS_SERVER_HELLO, // then, send all server handshake data at once
  7927. MG_TLS_HS_CLIENT_CHANGE_CIPHER, // finally wait for ClientChangeCipher
  7928. MG_TLS_HS_CLIENT_FINISH, // and ClientFinish (encrypted)
  7929. MG_TLS_HS_DONE, // finish handshake, start application data flow
  7930. };
  7931. // per-connection TLS data
  7932. struct tls_data {
  7933. enum mg_tls_hs_state state; // keep track of connection handshake progress
  7934. struct mg_iobuf send; // For the receive path, we're reusing c->rtls
  7935. mg_sha256_ctx sha256; // incremental SHA-256 hash for TLS handshake
  7936. uint32_t sseq; // server sequence number, used in encryption
  7937. uint32_t cseq; // client sequence number, used in decryption
  7938. uint8_t session_id[32]; // client session ID between the handshake states
  7939. uint8_t x25519_cli[32]; // client X25519 key between the handshake states
  7940. uint8_t x25519_sec[32]; // x25519 secret between the handshake states
  7941. struct mg_str server_cert_der; // server certificate in DER format
  7942. uint8_t server_key[32]; // server EC private key
  7943. // keys for AES encryption
  7944. uint8_t handshake_secret[32];
  7945. uint8_t server_write_key[16];
  7946. uint8_t server_write_iv[12];
  7947. uint8_t server_finished_key[32];
  7948. uint8_t client_write_key[16];
  7949. uint8_t client_write_iv[12];
  7950. uint8_t client_finished_key[32];
  7951. };
  7952. #define MG_LOAD_BE16(p) ((uint16_t) ((MG_U8P(p)[0] << 8U) | MG_U8P(p)[1]))
  7953. #define TLS_HDR_SIZE 5 // 1 byte type, 2 bytes version, 2 bytes len
  7954. // for derived tls keys we need SHA256([0]*32)
  7955. static uint8_t zeros[32] = {0};
  7956. static uint8_t zeros_sha256_digest[32] =
  7957. "\xe3\xb0\xc4\x42\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99\x6f\xb9\x24"
  7958. "\x27\xae\x41\xe4\x64\x9b\x93\x4c\xa4\x95\x99\x1b\x78\x52\xb8\x55";
  7959. #define X25519_BYTES 32
  7960. const uint8_t X25519_BASE_POINT[X25519_BYTES] = {9};
  7961. #define X25519_WBITS 32
  7962. typedef uint32_t limb_t;
  7963. typedef uint64_t dlimb_t;
  7964. typedef int64_t sdlimb_t;
  7965. #define LIMB(x) (uint32_t)(x##ull), (uint32_t) ((x##ull) >> 32)
  7966. #define NLIMBS (256 / X25519_WBITS)
  7967. typedef limb_t fe[NLIMBS];
  7968. static limb_t umaal(limb_t *carry, limb_t acc, limb_t mand, limb_t mier) {
  7969. dlimb_t tmp = (dlimb_t) mand * mier + acc + *carry;
  7970. *carry = (limb_t) (tmp >> X25519_WBITS);
  7971. return (limb_t) tmp;
  7972. }
  7973. // These functions are implemented in terms of umaal on ARM
  7974. static limb_t adc(limb_t *carry, limb_t acc, limb_t mand) {
  7975. dlimb_t total = (dlimb_t) *carry + acc + mand;
  7976. *carry = (limb_t) (total >> X25519_WBITS);
  7977. return (limb_t) total;
  7978. }
  7979. static limb_t adc0(limb_t *carry, limb_t acc) {
  7980. dlimb_t total = (dlimb_t) *carry + acc;
  7981. *carry = (limb_t) (total >> X25519_WBITS);
  7982. return (limb_t) total;
  7983. }
  7984. // - Precondition: carry is small.
  7985. // - Invariant: result of propagate is < 2^255 + 1 word
  7986. // - In particular, always less than 2p.
  7987. // - Also, output x >= min(x,19)
  7988. static void propagate(fe x, limb_t over) {
  7989. unsigned i;
  7990. limb_t carry;
  7991. over = x[NLIMBS - 1] >> (X25519_WBITS - 1) | over << 1;
  7992. x[NLIMBS - 1] &= ~((limb_t) 1 << (X25519_WBITS - 1));
  7993. carry = over * 19;
  7994. for (i = 0; i < NLIMBS; i++) {
  7995. x[i] = adc0(&carry, x[i]);
  7996. }
  7997. }
  7998. static void add(fe out, const fe a, const fe b) {
  7999. unsigned i;
  8000. limb_t carry = 0;
  8001. for (i = 0; i < NLIMBS; i++) {
  8002. out[i] = adc(&carry, a[i], b[i]);
  8003. }
  8004. propagate(out, carry);
  8005. }
  8006. static void sub(fe out, const fe a, const fe b) {
  8007. unsigned i;
  8008. sdlimb_t carry = -38;
  8009. for (i = 0; i < NLIMBS; i++) {
  8010. carry = carry + a[i] - b[i];
  8011. out[i] = (limb_t) carry;
  8012. carry >>= X25519_WBITS;
  8013. }
  8014. propagate(out, (limb_t) (1 + carry));
  8015. }
  8016. static void mul(fe out, const fe a, const fe b, unsigned nb) {
  8017. limb_t accum[2 * NLIMBS] = {0};
  8018. unsigned i, j;
  8019. limb_t carry2;
  8020. for (i = 0; i < nb; i++) {
  8021. limb_t mand = b[i];
  8022. carry2 = 0;
  8023. for (j = 0; j < NLIMBS; j++) {
  8024. accum[i + j] = umaal(&carry2, accum[i + j], mand, a[j]);
  8025. }
  8026. accum[i + j] = carry2;
  8027. }
  8028. carry2 = 0;
  8029. for (j = 0; j < NLIMBS; j++) {
  8030. out[j] = umaal(&carry2, accum[j], 38, accum[j + NLIMBS]);
  8031. }
  8032. propagate(out, carry2);
  8033. }
  8034. static void sqr(fe out, const fe a) {
  8035. mul(out, a, a, NLIMBS);
  8036. }
  8037. static void mul1(fe out, const fe a) {
  8038. mul(out, a, out, NLIMBS);
  8039. }
  8040. static void sqr1(fe a) {
  8041. mul1(a, a);
  8042. }
  8043. static void condswap(limb_t a[2 * NLIMBS], limb_t b[2 * NLIMBS],
  8044. limb_t doswap) {
  8045. unsigned i;
  8046. for (i = 0; i < 2 * NLIMBS; i++) {
  8047. limb_t xor = (a[i] ^ b[i]) & doswap;
  8048. a[i] ^= xor;
  8049. b[i] ^= xor;
  8050. }
  8051. }
  8052. // Canonicalize a field element x, reducing it to the least residue which is
  8053. // congruent to it mod 2^255-19
  8054. // - Precondition: x < 2^255 + 1 word
  8055. static limb_t canon(fe x) {
  8056. // First, add 19.
  8057. unsigned i;
  8058. limb_t carry0 = 19;
  8059. limb_t res;
  8060. sdlimb_t carry;
  8061. for (i = 0; i < NLIMBS; i++) {
  8062. x[i] = adc0(&carry0, x[i]);
  8063. }
  8064. propagate(x, carry0);
  8065. // Here, 19 <= x2 < 2^255
  8066. // - This is because we added 19, so before propagate it can't be less
  8067. // than 19. After propagate, it still can't be less than 19, because if
  8068. // propagate does anything it adds 19.
  8069. // - We know that the high bit must be clear, because either the input was ~
  8070. // 2^255 + one word + 19 (in which case it propagates to at most 2 words) or
  8071. // it was < 2^255. So now, if we subtract 19, we will get back to something in
  8072. // [0,2^255-19).
  8073. carry = -19;
  8074. res = 0;
  8075. for (i = 0; i < NLIMBS; i++) {
  8076. carry += x[i];
  8077. res |= x[i] = (limb_t) carry;
  8078. carry >>= X25519_WBITS;
  8079. }
  8080. return (limb_t) (((dlimb_t) res - 1) >> X25519_WBITS);
  8081. }
  8082. static const limb_t a24[1] = {121665};
  8083. static void ladder_part1(fe xs[5]) {
  8084. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  8085. add(t1, x2, z2); // t1 = A
  8086. sub(z2, x2, z2); // z2 = B
  8087. add(x2, x3, z3); // x2 = C
  8088. sub(z3, x3, z3); // z3 = D
  8089. mul1(z3, t1); // z3 = DA
  8090. mul1(x2, z2); // x3 = BC
  8091. add(x3, z3, x2); // x3 = DA+CB
  8092. sub(z3, z3, x2); // z3 = DA-CB
  8093. sqr1(t1); // t1 = AA
  8094. sqr1(z2); // z2 = BB
  8095. sub(x2, t1, z2); // x2 = E = AA-BB
  8096. mul(z2, x2, a24, sizeof(a24) / sizeof(a24[0])); // z2 = E*a24
  8097. add(z2, z2, t1); // z2 = E*a24 + AA
  8098. }
  8099. static void ladder_part2(fe xs[5], const fe x1) {
  8100. limb_t *x2 = xs[0], *z2 = xs[1], *x3 = xs[2], *z3 = xs[3], *t1 = xs[4];
  8101. sqr1(z3); // z3 = (DA-CB)^2
  8102. mul1(z3, x1); // z3 = x1 * (DA-CB)^2
  8103. sqr1(x3); // x3 = (DA+CB)^2
  8104. mul1(z2, x2); // z2 = AA*(E*a24+AA)
  8105. sub(x2, t1, x2); // x2 = BB again
  8106. mul1(x2, t1); // x2 = AA*BB
  8107. }
  8108. static void x25519_core(fe xs[5], const uint8_t scalar[X25519_BYTES],
  8109. const uint8_t *x1, int clamp) {
  8110. int i;
  8111. limb_t swap = 0;
  8112. limb_t *x2 = xs[0], *x3 = xs[2], *z3 = xs[3];
  8113. memset(xs, 0, 4 * sizeof(fe));
  8114. x2[0] = z3[0] = 1;
  8115. memcpy(x3, x1, sizeof(fe));
  8116. for (i = 255; i >= 0; i--) {
  8117. uint8_t bytei = scalar[i / 8];
  8118. limb_t doswap;
  8119. if (clamp) {
  8120. if (i / 8 == 0) {
  8121. bytei &= (uint8_t) ~7U;
  8122. } else if (i / 8 == X25519_BYTES - 1) {
  8123. bytei &= 0x7F;
  8124. bytei |= 0x40;
  8125. }
  8126. }
  8127. doswap = 0 - (limb_t) ((bytei >> (i % 8)) & 1);
  8128. condswap(x2, x3, swap ^ doswap);
  8129. swap = doswap;
  8130. ladder_part1(xs);
  8131. ladder_part2(xs, (const limb_t *) x1);
  8132. }
  8133. condswap(x2, x3, swap);
  8134. }
  8135. static int x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES],
  8136. const uint8_t x1[X25519_BYTES], int clamp) {
  8137. int i, ret;
  8138. fe xs[5];
  8139. limb_t *x2, *z2, *z3, *prev;
  8140. static const struct {
  8141. uint8_t a, c, n;
  8142. } steps[13] = {{2, 1, 1}, {2, 1, 1}, {4, 2, 3}, {2, 4, 6}, {3, 1, 1},
  8143. {3, 2, 12}, {4, 3, 25}, {2, 3, 25}, {2, 4, 50}, {3, 2, 125},
  8144. {3, 1, 2}, {3, 1, 2}, {3, 1, 1}};
  8145. x25519_core(xs, scalar, x1, clamp);
  8146. // Precomputed inversion chain
  8147. x2 = xs[0];
  8148. z2 = xs[1];
  8149. z3 = xs[3];
  8150. prev = z2;
  8151. for (i = 0; i < 13; i++) {
  8152. int j;
  8153. limb_t *a = xs[steps[i].a];
  8154. for (j = steps[i].n; j > 0; j--) {
  8155. sqr(a, prev);
  8156. prev = a;
  8157. }
  8158. mul1(a, xs[steps[i].c]);
  8159. }
  8160. // Here prev = z3
  8161. // x2 /= z2
  8162. mul((limb_t *) out, x2, z3, NLIMBS);
  8163. ret = (int) canon((limb_t *) out);
  8164. if (!clamp) ret = 0;
  8165. return ret;
  8166. }
  8167. // helper to hexdump buffers inline
  8168. static void mg_tls_hexdump(const char *msg, uint8_t *buf, size_t bufsz) {
  8169. char p[512];
  8170. MG_VERBOSE(("%s: %s", msg, mg_hex(buf, bufsz, p)));
  8171. }
  8172. // TLS1.3 secret derivation based on the key label
  8173. static void mg_tls_derive_secret(const char *label, uint8_t *key, size_t keysz,
  8174. uint8_t *data, size_t datasz, uint8_t *hash,
  8175. size_t hashsz) {
  8176. size_t labelsz = strlen(label);
  8177. uint8_t secret[32];
  8178. uint8_t packed[256] = {0, (uint8_t) hashsz, (uint8_t) labelsz};
  8179. // TODO: assert lengths of label, key, data and hash
  8180. memmove(packed + 3, label, labelsz);
  8181. packed[3 + labelsz] = (uint8_t) datasz;
  8182. memmove(packed + labelsz + 4, data, datasz);
  8183. packed[4 + labelsz + datasz] = 1;
  8184. mg_hmac_sha256(secret, key, keysz, packed, 5 + labelsz + datasz);
  8185. memmove(hash, secret, hashsz);
  8186. }
  8187. // Did we receive a full TLS message in the c->rtls buffer?
  8188. static bool mg_tls_got_msg(struct mg_connection *c) {
  8189. return c->rtls.len >= (size_t) TLS_HDR_SIZE &&
  8190. c->rtls.len >= (size_t) (TLS_HDR_SIZE + MG_LOAD_BE16(c->rtls.buf + 3));
  8191. }
  8192. // Remove a single TLS record from the recv buffer
  8193. static void mg_tls_drop_packet(struct mg_iobuf *rio) {
  8194. uint16_t n = MG_LOAD_BE16(rio->buf + 3) + TLS_HDR_SIZE;
  8195. mg_iobuf_del(rio, 0, n);
  8196. }
  8197. // read and parse ClientHello record
  8198. static int mg_tls_client_hello(struct mg_connection *c) {
  8199. struct tls_data *tls = c->tls;
  8200. struct mg_iobuf *rio = &c->rtls;
  8201. uint8_t session_id_len;
  8202. uint16_t j;
  8203. uint16_t cipher_suites_len;
  8204. uint16_t ext_len;
  8205. uint8_t *ext;
  8206. if (!mg_tls_got_msg(c)) {
  8207. return MG_IO_WAIT;
  8208. }
  8209. if (rio->buf[0] != 0x16 || rio->buf[5] != 0x01) {
  8210. mg_error(c, "not a hello packet");
  8211. return -1;
  8212. }
  8213. mg_sha256_update(&tls->sha256, rio->buf + 5, rio->len - 5);
  8214. session_id_len = rio->buf[43];
  8215. if (session_id_len == sizeof(tls->session_id)) {
  8216. memmove(tls->session_id, rio->buf + 44, session_id_len);
  8217. } else if (session_id_len != 0) {
  8218. MG_INFO(("bad session id len"));
  8219. }
  8220. cipher_suites_len = MG_LOAD_BE16(rio->buf + 44 + session_id_len);
  8221. ext_len = MG_LOAD_BE16(rio->buf + 48 + session_id_len + cipher_suites_len);
  8222. ext = rio->buf + 50 + session_id_len + cipher_suites_len;
  8223. for (j = 0; j < ext_len;) {
  8224. uint16_t k;
  8225. uint16_t key_exchange_len;
  8226. uint8_t *key_exchange;
  8227. uint16_t n = MG_LOAD_BE16(ext + j + 2);
  8228. if (ext[j] != 0x00 ||
  8229. ext[j + 1] != 0x33) { // not a key share extension, ignore
  8230. j += (uint16_t) (n + 4);
  8231. continue;
  8232. }
  8233. key_exchange_len = MG_LOAD_BE16(ext + j + 5);
  8234. key_exchange = ext + j + 6;
  8235. for (k = 0; k < key_exchange_len;) {
  8236. uint16_t m = MG_LOAD_BE16(key_exchange + k + 2);
  8237. if (m == 32 && key_exchange[k] == 0x00 && key_exchange[k + 1] == 0x1d) {
  8238. memmove(tls->x25519_cli, key_exchange + k + 4, m);
  8239. mg_tls_drop_packet(rio);
  8240. return 0;
  8241. }
  8242. k += (uint16_t) (m + 4);
  8243. }
  8244. j += (uint16_t) (n + 4);
  8245. }
  8246. mg_error(c, "bad client hello");
  8247. return -1;
  8248. }
  8249. // put ServerHello record into wio buffer
  8250. static void mg_tls_server_hello(struct mg_connection *c) {
  8251. struct tls_data *tls = c->tls;
  8252. struct mg_iobuf *wio = &tls->send;
  8253. uint8_t msg_server_hello[122] =
  8254. // server hello, tls 1.2
  8255. "\x02\x00\x00\x76\x03\x03"
  8256. // random (32 bytes)
  8257. "\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe"
  8258. "\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe\xfe"
  8259. // session ID length + session ID (32 bytes)
  8260. "\x20"
  8261. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
  8262. "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
  8263. #if defined(CHACHA20) && CHACHA20
  8264. // TLS_CHACHA20_POLY1305_SHA256 + no compression
  8265. "\x13\x03\x00"
  8266. #else
  8267. // TLS_AES_128_GCM_SHA256 + no compression
  8268. "\x13\x01\x00"
  8269. #endif
  8270. // extensions + keyshare
  8271. "\x00\x2e\x00\x33\x00\x24\x00\x1d\x00\x20"
  8272. // x25519 keyshare
  8273. "\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab"
  8274. "\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab\xab"
  8275. // supported versions (tls1.3 == 0x304)
  8276. "\x00\x2b\x00\x02\x03\x04";
  8277. // calculate keyshare
  8278. uint8_t x25519_pub[X25519_BYTES];
  8279. uint8_t x25519_prv[X25519_BYTES];
  8280. mg_random(x25519_prv, sizeof(x25519_prv));
  8281. x25519(x25519_pub, x25519_prv, X25519_BASE_POINT, 1);
  8282. x25519(tls->x25519_sec, x25519_prv, tls->x25519_cli, 1);
  8283. mg_tls_hexdump("x25519 sec", tls->x25519_sec, sizeof(tls->x25519_sec));
  8284. // fill in the gaps: session ID + keyshare
  8285. memmove(msg_server_hello + 39, tls->session_id, sizeof(tls->session_id));
  8286. memmove(msg_server_hello + 84, x25519_pub, sizeof(x25519_pub));
  8287. // server hello message
  8288. mg_iobuf_add(wio, wio->len, "\x16\x03\x03\x00\x7a", 5);
  8289. mg_iobuf_add(wio, wio->len, msg_server_hello, sizeof(msg_server_hello));
  8290. mg_sha256_update(&tls->sha256, msg_server_hello, sizeof(msg_server_hello));
  8291. // change cipher message
  8292. mg_iobuf_add(wio, wio->len, "\x14\x03\x03\x00\x01\x01", 6);
  8293. }
  8294. // at this point we have x25519 shared secret, we can generate a set of derived
  8295. // handshake encryption keys
  8296. static void mg_tls_generate_handshake_keys(struct mg_connection *c) {
  8297. struct tls_data *tls = c->tls;
  8298. mg_sha256_ctx sha256;
  8299. uint8_t early_secret[32];
  8300. uint8_t pre_extract_secret[32];
  8301. uint8_t hello_hash[32];
  8302. uint8_t server_hs_secret[32];
  8303. uint8_t client_hs_secret[32];
  8304. mg_hmac_sha256(early_secret, NULL, 0, zeros, sizeof(zeros));
  8305. mg_tls_derive_secret("tls13 derived", early_secret, 32, zeros_sha256_digest,
  8306. 32, pre_extract_secret, 32);
  8307. mg_hmac_sha256(tls->handshake_secret, pre_extract_secret,
  8308. sizeof(pre_extract_secret), tls->x25519_sec,
  8309. sizeof(tls->x25519_sec));
  8310. mg_tls_hexdump("hs secret", tls->handshake_secret, 32);
  8311. // mg_sha256_final is not idempotent, need to copy sha256 context to calculate
  8312. // the digest
  8313. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8314. mg_sha256_final(hello_hash, &sha256);
  8315. // derive keys needed for the rest of the handshake
  8316. mg_tls_derive_secret("tls13 s hs traffic", tls->handshake_secret, 32,
  8317. hello_hash, 32, server_hs_secret, 32);
  8318. mg_tls_derive_secret("tls13 key", server_hs_secret, 32, NULL, 0,
  8319. tls->server_write_key, 16);
  8320. mg_tls_derive_secret("tls13 iv", server_hs_secret, 32, NULL, 0,
  8321. tls->server_write_iv, 12);
  8322. mg_tls_derive_secret("tls13 finished", server_hs_secret, 32, NULL, 0,
  8323. tls->server_finished_key, 32);
  8324. mg_tls_hexdump("s hs traffic", server_hs_secret, 32);
  8325. mg_tls_derive_secret("tls13 c hs traffic", tls->handshake_secret, 32,
  8326. hello_hash, 32, client_hs_secret, 32);
  8327. mg_tls_derive_secret("tls13 key", client_hs_secret, 32, NULL, 0,
  8328. tls->client_write_key, 16);
  8329. mg_tls_derive_secret("tls13 iv", client_hs_secret, 32, NULL, 0,
  8330. tls->client_write_iv, 12);
  8331. mg_tls_derive_secret("tls13 finished", client_hs_secret, 32, NULL, 0,
  8332. tls->client_finished_key, 32);
  8333. }
  8334. // AES GCM encryption of the message + put encoded data into the write buffer
  8335. static void mg_tls_encrypt(struct mg_connection *c, const uint8_t *msg,
  8336. size_t msgsz, uint8_t msgtype) {
  8337. struct tls_data *tls = c->tls;
  8338. struct mg_iobuf *wio = &tls->send;
  8339. uint8_t *outmsg;
  8340. uint8_t *tag;
  8341. size_t encsz = msgsz + 16 + 1;
  8342. uint8_t hdr[5] = {0x17, 0x03, 0x03, (encsz >> 8) & 0xff, encsz & 0xff};
  8343. uint8_t associated_data[5] = {0x17, 0x03, 0x03, (encsz >> 8) & 0xff,
  8344. encsz & 0xff};
  8345. uint8_t nonce[12];
  8346. memmove(nonce, tls->server_write_iv, sizeof(tls->server_write_iv));
  8347. nonce[8] ^= (uint8_t) ((tls->sseq >> 24) & 255U);
  8348. nonce[9] ^= (uint8_t) ((tls->sseq >> 16) & 255U);
  8349. nonce[10] ^= (uint8_t) ((tls->sseq >> 8) & 255U);
  8350. nonce[11] ^= (uint8_t) ((tls->sseq) & 255U);
  8351. gcm_initialize();
  8352. mg_iobuf_add(wio, wio->len, hdr, sizeof(hdr));
  8353. mg_iobuf_resize(wio, wio->len + encsz);
  8354. outmsg = wio->buf + wio->len;
  8355. tag = wio->buf + wio->len + msgsz + 1;
  8356. memmove(outmsg, msg, msgsz);
  8357. outmsg[msgsz] = msgtype;
  8358. aes_gcm_encrypt(outmsg, outmsg, msgsz + 1, tls->server_write_key,
  8359. sizeof(tls->server_write_key), nonce, sizeof(nonce),
  8360. associated_data, sizeof(associated_data), tag, 16);
  8361. wio->len += encsz;
  8362. tls->sseq++;
  8363. }
  8364. // read an encrypted message, decrypt it into read buffer (AES GCM)
  8365. static int mg_tls_recv_decrypt(struct mg_connection *c, void *buf,
  8366. size_t bufsz) {
  8367. struct tls_data *tls = c->tls;
  8368. struct mg_iobuf *rio = &c->rtls;
  8369. // struct mg_iobuf *rio = &tls->recv;
  8370. uint16_t msgsz;
  8371. uint8_t *msg;
  8372. uint8_t nonce[12];
  8373. int r;
  8374. for (;;) {
  8375. if (!mg_tls_got_msg(c)) {
  8376. return MG_IO_WAIT;
  8377. }
  8378. if (rio->buf[0] == 0x17) {
  8379. break;
  8380. } else if (rio->buf[0] == 0x15) {
  8381. MG_INFO(("TLS ALERT packet received")); // TODO: drop packet?
  8382. } else {
  8383. mg_error(c, "unexpected packet");
  8384. return -1;
  8385. }
  8386. }
  8387. msgsz = MG_LOAD_BE16(rio->buf + 3);
  8388. msg = rio->buf + 5;
  8389. memmove(nonce, tls->client_write_iv, sizeof(tls->client_write_iv));
  8390. nonce[8] ^= (uint8_t) ((tls->cseq >> 24) & 255U);
  8391. nonce[9] ^= (uint8_t) ((tls->cseq >> 16) & 255U);
  8392. nonce[10] ^= (uint8_t) ((tls->cseq >> 8) & 255U);
  8393. nonce[11] ^= (uint8_t) ((tls->cseq) & 255U);
  8394. aes_gcm_decrypt(msg, msg, msgsz - 16, tls->client_write_key,
  8395. sizeof(tls->client_write_key), nonce, sizeof(nonce));
  8396. r = msgsz - 16 - 1;
  8397. if (msg[r] == 0x17) {
  8398. if (bufsz > 0) {
  8399. memmove(buf, msg, msgsz - 16);
  8400. }
  8401. } else {
  8402. r = 0;
  8403. }
  8404. tls->cseq++;
  8405. mg_tls_drop_packet(rio);
  8406. return r;
  8407. }
  8408. static void mg_tls_server_extensions(struct mg_connection *c) {
  8409. struct tls_data *tls = c->tls;
  8410. // server extensions
  8411. uint8_t ext[6] = {0x08, 0, 0, 2, 0, 0};
  8412. mg_sha256_update(&tls->sha256, ext, sizeof(ext));
  8413. mg_tls_encrypt(c, ext, sizeof(ext), 0x16);
  8414. }
  8415. static void mg_tls_server_cert(struct mg_connection *c) {
  8416. struct tls_data *tls = c->tls;
  8417. // server DER certificate (empty)
  8418. size_t n = tls->server_cert_der.len;
  8419. uint8_t *cert = calloc(1, 13 + n); // FIXME: free
  8420. cert[0] = 0x0b; // handshake header
  8421. cert[1] = (uint8_t) (((n + 9) >> 16) & 255U); // 3 bytes: payload length
  8422. cert[2] = (uint8_t) (((n + 9) >> 8) & 255U);
  8423. cert[3] = (uint8_t) ((n + 9) & 255U);
  8424. cert[4] = 0; // request context
  8425. cert[5] = (uint8_t) (((n + 5) >> 16) & 255U); // 3 bytes: cert (s) length
  8426. cert[6] = (uint8_t) (((n + 5) >> 8) & 255U);
  8427. cert[7] = (uint8_t) ((n + 5) & 255U);
  8428. cert[8] =
  8429. (uint8_t) (((n) >> 16) & 255U); // 3 bytes: first (and only) cert len
  8430. cert[9] = (uint8_t) (((n) >> 8) & 255U);
  8431. cert[10] = (uint8_t) (n & 255U);
  8432. // bytes 11+ are certificate in DER format
  8433. memmove(cert + 11, tls->server_cert_der.ptr, n);
  8434. cert[11 + n] = cert[12 + n] = 0; // certificate extensions (none)
  8435. mg_sha256_update(&tls->sha256, cert, 13 + n);
  8436. mg_tls_encrypt(c, cert, 13 + n, 0x16);
  8437. }
  8438. // type adapter between uECC hash context and our sha256 implementation
  8439. typedef struct SHA256_HashContext {
  8440. uECC_HashContext uECC;
  8441. mg_sha256_ctx ctx;
  8442. } SHA256_HashContext;
  8443. static void init_SHA256(const uECC_HashContext *base) {
  8444. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8445. mg_sha256_init(&c->ctx);
  8446. }
  8447. static void update_SHA256(const uECC_HashContext *base, const uint8_t *message,
  8448. unsigned message_size) {
  8449. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8450. mg_sha256_update(&c->ctx, message, message_size);
  8451. }
  8452. static void finish_SHA256(const uECC_HashContext *base, uint8_t *hash_result) {
  8453. SHA256_HashContext *c = (SHA256_HashContext *) base;
  8454. mg_sha256_final(hash_result, &c->ctx);
  8455. }
  8456. static void mg_tls_server_verify_ecdsa(struct mg_connection *c) {
  8457. struct tls_data *tls = c->tls;
  8458. // server certificate verify packet
  8459. uint8_t verify[82] = {0x0f, 0x00, 0x00, 0x00, 0x04, 0x03, 0x00, 0x00};
  8460. size_t sigsz, verifysz = 0;
  8461. uint8_t hash[32] = {0}, tmp[2 * 32 + 64] = {0};
  8462. struct SHA256_HashContext ctx = {
  8463. {&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp},
  8464. {{0}, 0, 0, {0}}};
  8465. int neg1, neg2;
  8466. uint8_t sig[64], sig_content[130] = {
  8467. " "
  8468. " "
  8469. "TLS 1.3, server CertificateVerify\0"};
  8470. mg_sha256_ctx sha256;
  8471. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8472. mg_sha256_final(sig_content + 98, &sha256);
  8473. mg_sha256_init(&sha256);
  8474. mg_sha256_update(&sha256, sig_content, sizeof(sig_content));
  8475. mg_sha256_final(hash, &sha256);
  8476. uECC_sign_deterministic(tls->server_key, hash, sizeof(hash), &ctx.uECC, sig,
  8477. uECC_secp256r1());
  8478. neg1 = !!(sig[0] & 0x80);
  8479. neg2 = !!(sig[32] & 0x80);
  8480. verify[8] = 0x30; // ASN.1 SEQUENCE
  8481. verify[9] = (uint8_t) (68 + neg1 + neg2);
  8482. verify[10] = 0x02; // ASN.1 INTEGER
  8483. verify[11] = (uint8_t) (32 + neg1);
  8484. memmove(verify + 12 + neg1, sig, 32);
  8485. verify[12 + 32 + neg1] = 0x02; // ASN.1 INTEGER
  8486. verify[13 + 32 + neg1] = (uint8_t) (32 + neg2);
  8487. memmove(verify + 14 + 32 + neg1 + neg2, sig + 32, 32);
  8488. sigsz = (size_t) (70 + neg1 + neg2);
  8489. verifysz = 8U + sigsz;
  8490. verify[3] = (uint8_t) (sigsz + 4);
  8491. verify[7] = (uint8_t) sigsz;
  8492. mg_tls_hexdump("verify", verify, verifysz);
  8493. mg_sha256_update(&tls->sha256, verify, verifysz);
  8494. mg_tls_encrypt(c, verify, verifysz, 0x16);
  8495. }
  8496. static void mg_tls_server_finish(struct mg_connection *c) {
  8497. struct tls_data *tls = c->tls;
  8498. struct mg_iobuf *wio = &tls->send;
  8499. mg_sha256_ctx sha256;
  8500. uint8_t hash[32];
  8501. uint8_t finish[36] = {0x14, 0, 0, 32};
  8502. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8503. mg_sha256_final(hash, &sha256);
  8504. mg_hmac_sha256(finish + 4, tls->server_finished_key, 32, hash, 32);
  8505. mg_tls_hexdump("hash", hash, sizeof(hash));
  8506. mg_tls_hexdump("key", tls->server_finished_key,
  8507. sizeof(tls->server_finished_key));
  8508. mg_tls_encrypt(c, finish, sizeof(finish), 0x16);
  8509. mg_io_send(c, wio->buf, wio->len);
  8510. wio->len = 0;
  8511. mg_sha256_update(&tls->sha256, finish, sizeof(finish));
  8512. }
  8513. static int mg_tls_client_change_cipher(struct mg_connection *c) {
  8514. // struct tls_data *tls = c->tls;
  8515. struct mg_iobuf *rio = &c->rtls;
  8516. for (;;) {
  8517. if (!mg_tls_got_msg(c)) {
  8518. return MG_IO_WAIT;
  8519. }
  8520. if (rio->buf[0] == 0x14) { // got a ChangeCipher record
  8521. break;
  8522. } else if (rio->buf[0] == 0x15) { // skip Alert records
  8523. MG_DEBUG(("TLS ALERT packet received"));
  8524. mg_tls_drop_packet(rio);
  8525. } else {
  8526. mg_error(c, "unexpected packet");
  8527. return MG_IO_ERR;
  8528. }
  8529. }
  8530. // consume ChangeCipher packet
  8531. mg_tls_drop_packet(rio);
  8532. return 0;
  8533. }
  8534. static int mg_tls_client_finish(struct mg_connection *c) {
  8535. uint8_t tmp[2048];
  8536. int n = mg_tls_recv_decrypt(c, tmp, sizeof(tmp));
  8537. if (n < 0) {
  8538. return -1;
  8539. }
  8540. // TODO: make sure it's a ClientFinish record
  8541. return 0;
  8542. }
  8543. static void mg_tls_generate_application_keys(struct mg_connection *c) {
  8544. struct tls_data *tls = c->tls;
  8545. uint8_t hash[32];
  8546. uint8_t premaster_secret[32];
  8547. uint8_t master_secret[32];
  8548. uint8_t server_secret[32];
  8549. uint8_t client_secret[32];
  8550. mg_sha256_ctx sha256;
  8551. memmove(&sha256, &tls->sha256, sizeof(mg_sha256_ctx));
  8552. mg_sha256_final(hash, &sha256);
  8553. mg_tls_derive_secret("tls13 derived", tls->handshake_secret, 32,
  8554. zeros_sha256_digest, 32, premaster_secret, 32);
  8555. mg_hmac_sha256(master_secret, premaster_secret, 32, zeros, 32);
  8556. mg_tls_derive_secret("tls13 s ap traffic", master_secret, 32, hash, 32,
  8557. server_secret, 32);
  8558. mg_tls_derive_secret("tls13 key", server_secret, 32, NULL, 0,
  8559. tls->server_write_key, 16);
  8560. mg_tls_derive_secret("tls13 iv", server_secret, 32, NULL, 0,
  8561. tls->server_write_iv, 12);
  8562. mg_tls_derive_secret("tls13 c ap traffic", master_secret, 32, hash, 32,
  8563. client_secret, 32);
  8564. mg_tls_derive_secret("tls13 key", client_secret, 32, NULL, 0,
  8565. tls->client_write_key, 16);
  8566. mg_tls_derive_secret("tls13 iv", client_secret, 32, NULL, 0,
  8567. tls->client_write_iv, 12);
  8568. tls->sseq = tls->cseq = 0;
  8569. }
  8570. void mg_tls_handshake(struct mg_connection *c) {
  8571. struct tls_data *tls = c->tls;
  8572. switch (tls->state) {
  8573. case MG_TLS_HS_CLIENT_HELLO:
  8574. if (mg_tls_client_hello(c) < 0) {
  8575. return;
  8576. }
  8577. tls->state = MG_TLS_HS_SERVER_HELLO;
  8578. // fallthrough
  8579. case MG_TLS_HS_SERVER_HELLO:
  8580. mg_tls_server_hello(c);
  8581. mg_tls_generate_handshake_keys(c);
  8582. mg_tls_server_extensions(c);
  8583. mg_tls_server_cert(c);
  8584. mg_tls_server_verify_ecdsa(c);
  8585. mg_tls_server_finish(c);
  8586. tls->state = MG_TLS_HS_CLIENT_CHANGE_CIPHER;
  8587. // fallthrough
  8588. case MG_TLS_HS_CLIENT_CHANGE_CIPHER:
  8589. if (mg_tls_client_change_cipher(c) < 0) {
  8590. return;
  8591. }
  8592. tls->state = MG_TLS_HS_CLIENT_FINISH;
  8593. // fallthrough
  8594. case MG_TLS_HS_CLIENT_FINISH:
  8595. if (mg_tls_client_finish(c) < 0) {
  8596. return;
  8597. }
  8598. mg_tls_generate_application_keys(c);
  8599. tls->state = MG_TLS_HS_DONE;
  8600. // fallthrough
  8601. case MG_TLS_HS_DONE: c->is_tls_hs = 0; return;
  8602. }
  8603. }
  8604. static int mg_parse_pem(const struct mg_str pem, const struct mg_str label,
  8605. struct mg_str *der) {
  8606. size_t n = 0, m = 0;
  8607. char *s;
  8608. const char *c;
  8609. struct mg_str caps[5];
  8610. if (!mg_match(pem, mg_str("#-----BEGIN #-----#-----END #-----#"), caps)) {
  8611. *der = mg_strdup(pem);
  8612. return 0;
  8613. }
  8614. if (mg_strcmp(caps[1], label) != 0 || mg_strcmp(caps[3], label) != 0) {
  8615. return -1; // bad label
  8616. }
  8617. if ((s = calloc(1, caps[2].len)) == NULL) {
  8618. return -1;
  8619. }
  8620. for (c = caps[2].ptr; c < caps[2].ptr + caps[2].len; c++) {
  8621. if (*c == ' ' || *c == '\n' || *c == '\r' || *c == '\t') {
  8622. continue;
  8623. }
  8624. s[n++] = *c;
  8625. }
  8626. m = mg_base64_decode(s, n, s, n);
  8627. if (m == 0) {
  8628. free(s);
  8629. return -1;
  8630. }
  8631. der->ptr = s;
  8632. der->len = m;
  8633. return 0;
  8634. }
  8635. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8636. struct mg_str key;
  8637. struct tls_data *tls = (struct tls_data *) calloc(1, sizeof(struct tls_data));
  8638. if (tls == NULL) {
  8639. mg_error(c, "tls oom");
  8640. return;
  8641. }
  8642. // parse PEM or DER EC key
  8643. if (opts->key.ptr == NULL ||
  8644. mg_parse_pem(opts->key, mg_str_s("EC PRIVATE KEY"), &key) < 0) {
  8645. MG_ERROR(("Failed to load EC private key"));
  8646. return;
  8647. }
  8648. if (key.len < 39) {
  8649. MG_ERROR(("EC private key too short"));
  8650. return;
  8651. }
  8652. // expect ASN.1 SEQUENCE=[INTEGER=1, BITSTRING of 32 bytes, ...]
  8653. // 30 nn 02 01 01 04 20 [key] ...
  8654. if (key.ptr[0] != 0x30 || (key.ptr[1] & 0x80) != 0) {
  8655. MG_ERROR(("EC private key: ASN.1 bad sequence"));
  8656. return;
  8657. }
  8658. if (memcmp(key.ptr + 2, "\x02\x01\x01\x04\x20", 5) != 0) {
  8659. MG_ERROR(("EC private key: ASN.1 bad data"));
  8660. }
  8661. memmove(tls->server_key, key.ptr + 7, 32);
  8662. free((void *) key.ptr);
  8663. // parse PEM or DER certificate
  8664. if (mg_parse_pem(opts->cert, mg_str_s("CERTIFICATE"), &tls->server_cert_der) <
  8665. 0) {
  8666. MG_ERROR(("Failed to load certificate"));
  8667. return;
  8668. }
  8669. // tls->send.align = tls->recv.align = MG_IO_SIZE;
  8670. tls->send.align = MG_IO_SIZE;
  8671. c->tls = tls;
  8672. c->is_tls = c->is_tls_hs = 1;
  8673. mg_sha256_init(&tls->sha256);
  8674. }
  8675. void mg_tls_free(struct mg_connection *c) {
  8676. struct tls_data *tls = c->tls;
  8677. if (tls != NULL) {
  8678. mg_iobuf_free(&tls->send);
  8679. free((void *) tls->server_cert_der.ptr);
  8680. }
  8681. free(c->tls);
  8682. c->tls = NULL;
  8683. }
  8684. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8685. struct tls_data *tls = c->tls;
  8686. long n = MG_IO_WAIT;
  8687. if (len > MG_IO_SIZE) len = MG_IO_SIZE;
  8688. mg_tls_encrypt(c, buf, len, 0x17);
  8689. while (tls->send.len > 0 &&
  8690. (n = mg_io_send(c, tls->send.buf, tls->send.len)) > 0) {
  8691. mg_iobuf_del(&tls->send, 0, (size_t) n);
  8692. }
  8693. if (n == MG_IO_ERR || n == MG_IO_WAIT) return n;
  8694. return (long) len;
  8695. }
  8696. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8697. return mg_tls_recv_decrypt(c, buf, len);
  8698. }
  8699. size_t mg_tls_pending(struct mg_connection *c) {
  8700. return mg_tls_got_msg(c) ? 1 : 0;
  8701. }
  8702. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8703. (void) mgr;
  8704. }
  8705. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8706. (void) mgr;
  8707. }
  8708. #endif
  8709. #ifdef MG_ENABLE_LINES
  8710. #line 1 "src/tls_dummy.c"
  8711. #endif
  8712. #if MG_TLS == MG_TLS_NONE
  8713. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8714. (void) opts;
  8715. mg_error(c, "TLS is not enabled");
  8716. }
  8717. void mg_tls_handshake(struct mg_connection *c) {
  8718. (void) c;
  8719. }
  8720. void mg_tls_free(struct mg_connection *c) {
  8721. (void) c;
  8722. }
  8723. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8724. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  8725. }
  8726. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8727. return c == NULL || buf == NULL || len == 0 ? 0 : -1;
  8728. }
  8729. size_t mg_tls_pending(struct mg_connection *c) {
  8730. (void) c;
  8731. return 0;
  8732. }
  8733. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8734. (void) mgr;
  8735. }
  8736. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8737. (void) mgr;
  8738. }
  8739. #endif
  8740. #ifdef MG_ENABLE_LINES
  8741. #line 1 "src/tls_mbed.c"
  8742. #endif
  8743. #if MG_TLS == MG_TLS_MBED
  8744. #if defined(MBEDTLS_VERSION_NUMBER) && MBEDTLS_VERSION_NUMBER >= 0x03000000
  8745. #define MG_MBEDTLS_RNG_GET , mg_mbed_rng, NULL
  8746. #else
  8747. #define MG_MBEDTLS_RNG_GET
  8748. #endif
  8749. static int mg_mbed_rng(void *ctx, unsigned char *buf, size_t len) {
  8750. mg_random(buf, len);
  8751. (void) ctx;
  8752. return 0;
  8753. }
  8754. static bool mg_load_cert(struct mg_str str, mbedtls_x509_crt *p) {
  8755. int rc;
  8756. if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true;
  8757. if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL
  8758. if ((rc = mbedtls_x509_crt_parse(p, (uint8_t *) str.ptr, str.len)) != 0) {
  8759. MG_ERROR(("cert err %#x", -rc));
  8760. return false;
  8761. }
  8762. return true;
  8763. }
  8764. static bool mg_load_key(struct mg_str str, mbedtls_pk_context *p) {
  8765. int rc;
  8766. if (str.ptr == NULL || str.ptr[0] == '\0' || str.ptr[0] == '*') return true;
  8767. if (str.ptr[0] == '-') str.len++; // PEM, include trailing NUL
  8768. if ((rc = mbedtls_pk_parse_key(p, (uint8_t *) str.ptr, str.len, NULL,
  8769. 0 MG_MBEDTLS_RNG_GET)) != 0) {
  8770. MG_ERROR(("key err %#x", -rc));
  8771. return false;
  8772. }
  8773. return true;
  8774. }
  8775. void mg_tls_free(struct mg_connection *c) {
  8776. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8777. if (tls != NULL) {
  8778. mbedtls_ssl_free(&tls->ssl);
  8779. mbedtls_pk_free(&tls->pk);
  8780. mbedtls_x509_crt_free(&tls->ca);
  8781. mbedtls_x509_crt_free(&tls->cert);
  8782. mbedtls_ssl_config_free(&tls->conf);
  8783. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8784. mbedtls_ssl_ticket_free(&tls->ticket);
  8785. #endif
  8786. free(tls);
  8787. c->tls = NULL;
  8788. }
  8789. }
  8790. static int mg_net_send(void *ctx, const unsigned char *buf, size_t len) {
  8791. long n = mg_io_send((struct mg_connection *) ctx, buf, len);
  8792. MG_VERBOSE(("%lu n=%ld e=%d", ((struct mg_connection *) ctx)->id, n, errno));
  8793. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  8794. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  8795. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_SEND_FAILED;
  8796. return (int) n;
  8797. }
  8798. static int mg_net_recv(void *ctx, unsigned char *buf, size_t len) {
  8799. long n = mg_io_recv((struct mg_connection *) ctx, buf, len);
  8800. MG_VERBOSE(("%lu n=%ld", ((struct mg_connection *) ctx)->id, n));
  8801. if (n == MG_IO_WAIT) return MBEDTLS_ERR_SSL_WANT_WRITE;
  8802. if (n == MG_IO_RESET) return MBEDTLS_ERR_NET_CONN_RESET;
  8803. if (n == MG_IO_ERR) return MBEDTLS_ERR_NET_RECV_FAILED;
  8804. return (int) n;
  8805. }
  8806. void mg_tls_handshake(struct mg_connection *c) {
  8807. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8808. int rc = mbedtls_ssl_handshake(&tls->ssl);
  8809. if (rc == 0) { // Success
  8810. MG_DEBUG(("%lu success", c->id));
  8811. c->is_tls_hs = 0;
  8812. mg_call(c, MG_EV_TLS_HS, NULL);
  8813. } else if (rc == MBEDTLS_ERR_SSL_WANT_READ ||
  8814. rc == MBEDTLS_ERR_SSL_WANT_WRITE) { // Still pending
  8815. MG_VERBOSE(("%lu pending, %d%d %d (-%#x)", c->id, c->is_connecting,
  8816. c->is_tls_hs, rc, -rc));
  8817. } else {
  8818. mg_error(c, "TLS handshake: -%#x", -rc); // Error
  8819. }
  8820. }
  8821. static void debug_cb(void *c, int lev, const char *s, int n, const char *s2) {
  8822. n = (int) strlen(s2) - 1;
  8823. MG_INFO(("%lu %d %.*s", ((struct mg_connection *) c)->id, lev, n, s2));
  8824. (void) s;
  8825. }
  8826. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  8827. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  8828. int rc = 0;
  8829. c->tls = tls;
  8830. if (c->tls == NULL) {
  8831. mg_error(c, "TLS OOM");
  8832. goto fail;
  8833. }
  8834. if (c->is_listening) goto fail;
  8835. MG_DEBUG(("%lu Setting TLS", c->id));
  8836. MG_PROF_ADD(c, "mbedtls_init_start");
  8837. mbedtls_ssl_init(&tls->ssl);
  8838. mbedtls_ssl_config_init(&tls->conf);
  8839. mbedtls_x509_crt_init(&tls->ca);
  8840. mbedtls_x509_crt_init(&tls->cert);
  8841. mbedtls_pk_init(&tls->pk);
  8842. mbedtls_ssl_conf_dbg(&tls->conf, debug_cb, c);
  8843. #if defined(MG_MBEDTLS_DEBUG_LEVEL)
  8844. mbedtls_debug_set_threshold(MG_MBEDTLS_DEBUG_LEVEL);
  8845. #endif
  8846. if ((rc = mbedtls_ssl_config_defaults(
  8847. &tls->conf,
  8848. c->is_client ? MBEDTLS_SSL_IS_CLIENT : MBEDTLS_SSL_IS_SERVER,
  8849. MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
  8850. mg_error(c, "tls defaults %#x", -rc);
  8851. goto fail;
  8852. }
  8853. mbedtls_ssl_conf_rng(&tls->conf, mg_mbed_rng, c);
  8854. if (opts->ca.len == 0 || mg_vcmp(&opts->ca, "*") == 0) {
  8855. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_NONE);
  8856. } else {
  8857. if (mg_load_cert(opts->ca, &tls->ca) == false) goto fail;
  8858. mbedtls_ssl_conf_ca_chain(&tls->conf, &tls->ca, NULL);
  8859. if (c->is_client && opts->name.ptr != NULL && opts->name.ptr[0] != '\0') {
  8860. char *host = mg_mprintf("%.*s", opts->name.len, opts->name.ptr);
  8861. mbedtls_ssl_set_hostname(&tls->ssl, host);
  8862. MG_DEBUG(("%lu hostname verification: %s", c->id, host));
  8863. free(host);
  8864. }
  8865. mbedtls_ssl_conf_authmode(&tls->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  8866. }
  8867. if (!mg_load_cert(opts->cert, &tls->cert)) goto fail;
  8868. if (!mg_load_key(opts->key, &tls->pk)) goto fail;
  8869. if (tls->cert.version &&
  8870. (rc = mbedtls_ssl_conf_own_cert(&tls->conf, &tls->cert, &tls->pk)) != 0) {
  8871. mg_error(c, "own cert %#x", -rc);
  8872. goto fail;
  8873. }
  8874. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8875. mbedtls_ssl_conf_session_tickets_cb(
  8876. &tls->conf, mbedtls_ssl_ticket_write, mbedtls_ssl_ticket_parse,
  8877. &((struct mg_tls_ctx *) c->mgr->tls_ctx)->tickets);
  8878. #endif
  8879. if ((rc = mbedtls_ssl_setup(&tls->ssl, &tls->conf)) != 0) {
  8880. mg_error(c, "setup err %#x", -rc);
  8881. goto fail;
  8882. }
  8883. c->is_tls = 1;
  8884. c->is_tls_hs = 1;
  8885. mbedtls_ssl_set_bio(&tls->ssl, c, mg_net_send, mg_net_recv, 0);
  8886. MG_PROF_ADD(c, "mbedtls_init_end");
  8887. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  8888. mg_tls_handshake(c);
  8889. }
  8890. return;
  8891. fail:
  8892. mg_tls_free(c);
  8893. }
  8894. size_t mg_tls_pending(struct mg_connection *c) {
  8895. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8896. return tls == NULL ? 0 : mbedtls_ssl_get_bytes_avail(&tls->ssl);
  8897. }
  8898. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  8899. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8900. long n = mbedtls_ssl_read(&tls->ssl, (unsigned char *) buf, len);
  8901. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  8902. return MG_IO_WAIT;
  8903. if (n <= 0) return MG_IO_ERR;
  8904. return n;
  8905. }
  8906. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  8907. struct mg_tls *tls = (struct mg_tls *) c->tls;
  8908. long n = mbedtls_ssl_write(&tls->ssl, (unsigned char *) buf, len);
  8909. if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE)
  8910. return MG_IO_WAIT;
  8911. if (n <= 0) return MG_IO_ERR;
  8912. return n;
  8913. }
  8914. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  8915. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) calloc(1, sizeof(*ctx));
  8916. if (ctx == NULL) {
  8917. MG_ERROR(("TLS context init OOM"));
  8918. } else {
  8919. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8920. int rc;
  8921. mbedtls_ssl_ticket_init(&ctx->tickets);
  8922. if ((rc = mbedtls_ssl_ticket_setup(&ctx->tickets, mg_mbed_rng, NULL,
  8923. MBEDTLS_CIPHER_AES_128_GCM, 86400)) !=
  8924. 0) {
  8925. MG_ERROR((" mbedtls_ssl_ticket_setup %#x", -rc));
  8926. }
  8927. #endif
  8928. mgr->tls_ctx = ctx;
  8929. }
  8930. }
  8931. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  8932. struct mg_tls_ctx *ctx = (struct mg_tls_ctx *) mgr->tls_ctx;
  8933. if (ctx != NULL) {
  8934. #ifdef MBEDTLS_SSL_SESSION_TICKETS
  8935. mbedtls_ssl_ticket_free(&ctx->tickets);
  8936. #endif
  8937. free(ctx);
  8938. mgr->tls_ctx = NULL;
  8939. }
  8940. }
  8941. #endif
  8942. #ifdef MG_ENABLE_LINES
  8943. #line 1 "src/tls_openssl.c"
  8944. #endif
  8945. #if MG_TLS == MG_TLS_OPENSSL
  8946. static int tls_err_cb(const char *s, size_t len, void *c) {
  8947. int n = (int) len - 1;
  8948. MG_ERROR(("%lu %.*s", ((struct mg_connection *) c)->id, n, s));
  8949. return 0; // undocumented
  8950. }
  8951. static int mg_tls_err(struct mg_connection *c, struct mg_tls *tls, int res) {
  8952. int err = SSL_get_error(tls->ssl, res);
  8953. // We've just fetched the last error from the queue.
  8954. // Now we need to clear the error queue. If we do not, then the following
  8955. // can happen (actually reported):
  8956. // - A new connection is accept()-ed with cert error (e.g. self-signed cert)
  8957. // - Since all accept()-ed connections share listener's context,
  8958. // - *ALL* SSL accepted connection report read error on the next poll cycle.
  8959. // Thus a single errored connection can close all the rest, unrelated ones.
  8960. // Clearing the error keeps the shared SSL_CTX in an OK state.
  8961. if (err != 0) ERR_print_errors_cb(tls_err_cb, c);
  8962. ERR_clear_error();
  8963. if (err == SSL_ERROR_WANT_READ) return 0;
  8964. if (err == SSL_ERROR_WANT_WRITE) return 0;
  8965. return err;
  8966. }
  8967. static STACK_OF(X509_INFO) * load_ca_certs(struct mg_str ca) {
  8968. BIO *bio = BIO_new_mem_buf(ca.ptr, (int) ca.len);
  8969. STACK_OF(X509_INFO) *certs =
  8970. bio ? PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL) : NULL;
  8971. if (bio) BIO_free(bio);
  8972. return certs;
  8973. }
  8974. static bool add_ca_certs(SSL_CTX *ctx, STACK_OF(X509_INFO) * certs) {
  8975. X509_STORE *cert_store = SSL_CTX_get_cert_store(ctx);
  8976. for (int i = 0; i < sk_X509_INFO_num(certs); i++) {
  8977. X509_INFO *cert_info = sk_X509_INFO_value(certs, i);
  8978. if (cert_info->x509 && !X509_STORE_add_cert(cert_store, cert_info->x509))
  8979. return false;
  8980. }
  8981. return true;
  8982. }
  8983. static EVP_PKEY *load_key(struct mg_str s) {
  8984. BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len);
  8985. EVP_PKEY *key = bio ? PEM_read_bio_PrivateKey(bio, NULL, 0, NULL) : NULL;
  8986. if (bio) BIO_free(bio);
  8987. return key;
  8988. }
  8989. static X509 *load_cert(struct mg_str s) {
  8990. BIO *bio = BIO_new_mem_buf(s.ptr, (int) (long) s.len);
  8991. X509 *cert = bio == NULL ? NULL
  8992. : s.ptr[0] == '-'
  8993. ? PEM_read_bio_X509(bio, NULL, NULL, NULL) // PEM
  8994. : d2i_X509_bio(bio, NULL); // DER
  8995. if (bio) BIO_free(bio);
  8996. return cert;
  8997. }
  8998. static long mg_bio_ctrl(BIO *b, int cmd, long larg, void *pargs) {
  8999. long ret = 0;
  9000. if (cmd == BIO_CTRL_PUSH) ret = 1;
  9001. if (cmd == BIO_CTRL_POP) ret = 1;
  9002. if (cmd == BIO_CTRL_FLUSH) ret = 1;
  9003. if (cmd == BIO_C_SET_NBIO) ret = 1;
  9004. // MG_DEBUG(("%d -> %ld", cmd, ret));
  9005. (void) b, (void) cmd, (void) larg, (void) pargs;
  9006. return ret;
  9007. }
  9008. static int mg_bio_read(BIO *bio, char *buf, int len) {
  9009. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  9010. long res = mg_io_recv(c, buf, (size_t) len);
  9011. // MG_DEBUG(("%p %d %ld", buf, len, res));
  9012. len = res > 0 ? (int) res : -1;
  9013. if (res == MG_IO_WAIT) BIO_set_retry_read(bio);
  9014. return len;
  9015. }
  9016. static int mg_bio_write(BIO *bio, const char *buf, int len) {
  9017. struct mg_connection *c = (struct mg_connection *) BIO_get_data(bio);
  9018. long res = mg_io_send(c, buf, (size_t) len);
  9019. // MG_DEBUG(("%p %d %ld", buf, len, res));
  9020. len = res > 0 ? (int) res : -1;
  9021. if (res == MG_IO_WAIT) BIO_set_retry_write(bio);
  9022. return len;
  9023. }
  9024. void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
  9025. struct mg_tls *tls = (struct mg_tls *) calloc(1, sizeof(*tls));
  9026. const char *id = "mongoose";
  9027. static unsigned char s_initialised = 0;
  9028. BIO *bio = NULL;
  9029. int rc;
  9030. if (tls == NULL) {
  9031. mg_error(c, "TLS OOM");
  9032. goto fail;
  9033. }
  9034. if (!s_initialised) {
  9035. SSL_library_init();
  9036. s_initialised++;
  9037. }
  9038. MG_DEBUG(("%lu Setting TLS", c->id));
  9039. tls->ctx = c->is_client ? SSL_CTX_new(SSLv23_client_method())
  9040. : SSL_CTX_new(SSLv23_server_method());
  9041. if ((tls->ssl = SSL_new(tls->ctx)) == NULL) {
  9042. mg_error(c, "SSL_new");
  9043. goto fail;
  9044. }
  9045. SSL_set_session_id_context(tls->ssl, (const uint8_t *) id,
  9046. (unsigned) strlen(id));
  9047. // Disable deprecated protocols
  9048. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv2);
  9049. SSL_set_options(tls->ssl, SSL_OP_NO_SSLv3);
  9050. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1);
  9051. SSL_set_options(tls->ssl, SSL_OP_NO_TLSv1_1);
  9052. #ifdef MG_ENABLE_OPENSSL_NO_COMPRESSION
  9053. SSL_set_options(tls->ssl, SSL_OP_NO_COMPRESSION);
  9054. #endif
  9055. #ifdef MG_ENABLE_OPENSSL_CIPHER_SERVER_PREFERENCE
  9056. SSL_set_options(tls->ssl, SSL_OP_CIPHER_SERVER_PREFERENCE);
  9057. #endif
  9058. if (opts->ca.ptr != NULL && opts->ca.ptr[0] != '\0') {
  9059. SSL_set_verify(tls->ssl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  9060. NULL);
  9061. STACK_OF(X509_INFO) *certs = load_ca_certs(opts->ca);
  9062. rc = add_ca_certs(tls->ctx, certs);
  9063. sk_X509_INFO_pop_free(certs, X509_INFO_free);
  9064. if (!rc) {
  9065. mg_error(c, "CA err");
  9066. goto fail;
  9067. }
  9068. }
  9069. if (opts->cert.ptr != NULL && opts->cert.ptr[0] != '\0') {
  9070. X509 *cert = load_cert(opts->cert);
  9071. rc = cert == NULL ? 0 : SSL_use_certificate(tls->ssl, cert);
  9072. X509_free(cert);
  9073. if (cert == NULL || rc != 1) {
  9074. mg_error(c, "CERT err %d", mg_tls_err(c, tls, rc));
  9075. goto fail;
  9076. }
  9077. }
  9078. if (opts->key.ptr != NULL && opts->key.ptr[0] != '\0') {
  9079. EVP_PKEY *key = load_key(opts->key);
  9080. rc = key == NULL ? 0 : SSL_use_PrivateKey(tls->ssl, key);
  9081. EVP_PKEY_free(key);
  9082. if (key == NULL || rc != 1) {
  9083. mg_error(c, "KEY err %d", mg_tls_err(c, tls, rc));
  9084. goto fail;
  9085. }
  9086. }
  9087. SSL_set_mode(tls->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  9088. #if OPENSSL_VERSION_NUMBER > 0x10002000L
  9089. (void) SSL_set_ecdh_auto(tls->ssl, 1);
  9090. #endif
  9091. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  9092. if (opts->name.len > 0) {
  9093. char *s = mg_mprintf("%.*s", (int) opts->name.len, opts->name.ptr);
  9094. SSL_set1_host(tls->ssl, s);
  9095. SSL_set_tlsext_host_name(tls->ssl, s);
  9096. free(s);
  9097. }
  9098. #endif
  9099. tls->bm = BIO_meth_new(BIO_get_new_index() | BIO_TYPE_SOURCE_SINK, "bio_mg");
  9100. BIO_meth_set_write(tls->bm, mg_bio_write);
  9101. BIO_meth_set_read(tls->bm, mg_bio_read);
  9102. BIO_meth_set_ctrl(tls->bm, mg_bio_ctrl);
  9103. bio = BIO_new(tls->bm);
  9104. BIO_set_data(bio, c);
  9105. SSL_set_bio(tls->ssl, bio, bio);
  9106. c->tls = tls;
  9107. c->is_tls = 1;
  9108. c->is_tls_hs = 1;
  9109. if (c->is_client && c->is_resolving == 0 && c->is_connecting == 0) {
  9110. mg_tls_handshake(c);
  9111. }
  9112. MG_DEBUG(("%lu SSL %s OK", c->id, c->is_accepted ? "accept" : "client"));
  9113. return;
  9114. fail:
  9115. free(tls);
  9116. }
  9117. void mg_tls_handshake(struct mg_connection *c) {
  9118. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9119. int rc = c->is_client ? SSL_connect(tls->ssl) : SSL_accept(tls->ssl);
  9120. if (rc == 1) {
  9121. MG_DEBUG(("%lu success", c->id));
  9122. c->is_tls_hs = 0;
  9123. mg_call(c, MG_EV_TLS_HS, NULL);
  9124. } else {
  9125. int code = mg_tls_err(c, tls, rc);
  9126. if (code != 0) mg_error(c, "tls hs: rc %d, err %d", rc, code);
  9127. }
  9128. }
  9129. void mg_tls_free(struct mg_connection *c) {
  9130. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9131. if (tls == NULL) return;
  9132. SSL_free(tls->ssl);
  9133. SSL_CTX_free(tls->ctx);
  9134. BIO_meth_free(tls->bm);
  9135. free(tls);
  9136. c->tls = NULL;
  9137. }
  9138. size_t mg_tls_pending(struct mg_connection *c) {
  9139. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9140. return tls == NULL ? 0 : (size_t) SSL_pending(tls->ssl);
  9141. }
  9142. long mg_tls_recv(struct mg_connection *c, void *buf, size_t len) {
  9143. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9144. int n = SSL_read(tls->ssl, buf, (int) len);
  9145. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  9146. if (n <= 0) return MG_IO_ERR;
  9147. return n;
  9148. }
  9149. long mg_tls_send(struct mg_connection *c, const void *buf, size_t len) {
  9150. struct mg_tls *tls = (struct mg_tls *) c->tls;
  9151. int n = SSL_write(tls->ssl, buf, (int) len);
  9152. if (n < 0 && mg_tls_err(c, tls, n) == 0) return MG_IO_WAIT;
  9153. if (n <= 0) return MG_IO_ERR;
  9154. return n;
  9155. }
  9156. void mg_tls_ctx_init(struct mg_mgr *mgr) {
  9157. (void) mgr;
  9158. }
  9159. void mg_tls_ctx_free(struct mg_mgr *mgr) {
  9160. (void) mgr;
  9161. }
  9162. #endif
  9163. #ifdef MG_ENABLE_LINES
  9164. #line 1 "src/tls_uecc.c"
  9165. #endif
  9166. /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  9167. #if MG_TLS == MG_TLS_BUILTIN
  9168. #ifndef uECC_RNG_MAX_TRIES
  9169. #define uECC_RNG_MAX_TRIES 64
  9170. #endif
  9171. #if uECC_ENABLE_VLI_API
  9172. #define uECC_VLI_API
  9173. #else
  9174. #define uECC_VLI_API static
  9175. #endif
  9176. #if (uECC_PLATFORM == uECC_avr) || (uECC_PLATFORM == uECC_arm) || \
  9177. (uECC_PLATFORM == uECC_arm_thumb) || (uECC_PLATFORM == uECC_arm_thumb2)
  9178. #define CONCATX(a, ...) a##__VA_ARGS__
  9179. #define CONCAT(a, ...) CONCATX(a, __VA_ARGS__)
  9180. #define STRX(a) #a
  9181. #define STR(a) STRX(a)
  9182. #define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__))))
  9183. #define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__))))
  9184. #define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__))))
  9185. #define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__))))
  9186. #define EVAL4(...) __VA_ARGS__
  9187. #define DEC_1 0
  9188. #define DEC_2 1
  9189. #define DEC_3 2
  9190. #define DEC_4 3
  9191. #define DEC_5 4
  9192. #define DEC_6 5
  9193. #define DEC_7 6
  9194. #define DEC_8 7
  9195. #define DEC_9 8
  9196. #define DEC_10 9
  9197. #define DEC_11 10
  9198. #define DEC_12 11
  9199. #define DEC_13 12
  9200. #define DEC_14 13
  9201. #define DEC_15 14
  9202. #define DEC_16 15
  9203. #define DEC_17 16
  9204. #define DEC_18 17
  9205. #define DEC_19 18
  9206. #define DEC_20 19
  9207. #define DEC_21 20
  9208. #define DEC_22 21
  9209. #define DEC_23 22
  9210. #define DEC_24 23
  9211. #define DEC_25 24
  9212. #define DEC_26 25
  9213. #define DEC_27 26
  9214. #define DEC_28 27
  9215. #define DEC_29 28
  9216. #define DEC_30 29
  9217. #define DEC_31 30
  9218. #define DEC_32 31
  9219. #define DEC(N) CONCAT(DEC_, N)
  9220. #define SECOND_ARG(_, val, ...) val
  9221. #define SOME_CHECK_0 ~, 0
  9222. #define GET_SECOND_ARG(...) SECOND_ARG(__VA_ARGS__, SOME, )
  9223. #define SOME_OR_0(N) GET_SECOND_ARG(CONCAT(SOME_CHECK_, N))
  9224. #define EMPTY(...)
  9225. #define DEFER(...) __VA_ARGS__ EMPTY()
  9226. #define REPEAT_NAME_0() REPEAT_0
  9227. #define REPEAT_NAME_SOME() REPEAT_SOME
  9228. #define REPEAT_0(...)
  9229. #define REPEAT_SOME(N, stuff) \
  9230. DEFER(CONCAT(REPEAT_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), stuff) stuff
  9231. #define REPEAT(N, stuff) EVAL(REPEAT_SOME(N, stuff))
  9232. #define REPEATM_NAME_0() REPEATM_0
  9233. #define REPEATM_NAME_SOME() REPEATM_SOME
  9234. #define REPEATM_0(...)
  9235. #define REPEATM_SOME(N, macro) \
  9236. macro(N) DEFER(CONCAT(REPEATM_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), macro)
  9237. #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro))
  9238. #endif
  9239. //
  9240. #if (uECC_WORD_SIZE == 1)
  9241. #if uECC_SUPPORTS_secp160r1
  9242. #define uECC_MAX_WORDS 21 /* Due to the size of curve_n. */
  9243. #endif
  9244. #if uECC_SUPPORTS_secp192r1
  9245. #undef uECC_MAX_WORDS
  9246. #define uECC_MAX_WORDS 24
  9247. #endif
  9248. #if uECC_SUPPORTS_secp224r1
  9249. #undef uECC_MAX_WORDS
  9250. #define uECC_MAX_WORDS 28
  9251. #endif
  9252. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9253. #undef uECC_MAX_WORDS
  9254. #define uECC_MAX_WORDS 32
  9255. #endif
  9256. #elif (uECC_WORD_SIZE == 4)
  9257. #if uECC_SUPPORTS_secp160r1
  9258. #define uECC_MAX_WORDS 6 /* Due to the size of curve_n. */
  9259. #endif
  9260. #if uECC_SUPPORTS_secp192r1
  9261. #undef uECC_MAX_WORDS
  9262. #define uECC_MAX_WORDS 6
  9263. #endif
  9264. #if uECC_SUPPORTS_secp224r1
  9265. #undef uECC_MAX_WORDS
  9266. #define uECC_MAX_WORDS 7
  9267. #endif
  9268. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9269. #undef uECC_MAX_WORDS
  9270. #define uECC_MAX_WORDS 8
  9271. #endif
  9272. #elif (uECC_WORD_SIZE == 8)
  9273. #if uECC_SUPPORTS_secp160r1
  9274. #define uECC_MAX_WORDS 3
  9275. #endif
  9276. #if uECC_SUPPORTS_secp192r1
  9277. #undef uECC_MAX_WORDS
  9278. #define uECC_MAX_WORDS 3
  9279. #endif
  9280. #if uECC_SUPPORTS_secp224r1
  9281. #undef uECC_MAX_WORDS
  9282. #define uECC_MAX_WORDS 4
  9283. #endif
  9284. #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1)
  9285. #undef uECC_MAX_WORDS
  9286. #define uECC_MAX_WORDS 4
  9287. #endif
  9288. #endif /* uECC_WORD_SIZE */
  9289. #define BITS_TO_WORDS(num_bits) \
  9290. ((wordcount_t) ((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / \
  9291. (uECC_WORD_SIZE * 8)))
  9292. #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8)
  9293. struct uECC_Curve_t {
  9294. wordcount_t num_words;
  9295. wordcount_t num_bytes;
  9296. bitcount_t num_n_bits;
  9297. uECC_word_t p[uECC_MAX_WORDS];
  9298. uECC_word_t n[uECC_MAX_WORDS];
  9299. uECC_word_t G[uECC_MAX_WORDS * 2];
  9300. uECC_word_t b[uECC_MAX_WORDS];
  9301. void (*double_jacobian)(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *Z1,
  9302. uECC_Curve curve);
  9303. #if uECC_SUPPORT_COMPRESSED_POINT
  9304. void (*mod_sqrt)(uECC_word_t *a, uECC_Curve curve);
  9305. #endif
  9306. void (*x_side)(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve);
  9307. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9308. void (*mmod_fast)(uECC_word_t *result, uECC_word_t *product);
  9309. #endif
  9310. };
  9311. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  9312. static void bcopy(uint8_t *dst, const uint8_t *src, unsigned num_bytes) {
  9313. while (0 != num_bytes) {
  9314. num_bytes--;
  9315. dst[num_bytes] = src[num_bytes];
  9316. }
  9317. }
  9318. #endif
  9319. static cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
  9320. const uECC_word_t *right,
  9321. wordcount_t num_words);
  9322. #if (uECC_PLATFORM == uECC_arm || uECC_PLATFORM == uECC_arm_thumb || \
  9323. uECC_PLATFORM == uECC_arm_thumb2)
  9324. #endif
  9325. #if (uECC_PLATFORM == uECC_avr)
  9326. #endif
  9327. #ifndef asm_clear
  9328. #define asm_clear 0
  9329. #endif
  9330. #ifndef asm_set
  9331. #define asm_set 0
  9332. #endif
  9333. #ifndef asm_add
  9334. #define asm_add 0
  9335. #endif
  9336. #ifndef asm_sub
  9337. #define asm_sub 0
  9338. #endif
  9339. #ifndef asm_mult
  9340. #define asm_mult 0
  9341. #endif
  9342. #ifndef asm_rshift1
  9343. #define asm_rshift1 0
  9344. #endif
  9345. #ifndef asm_mmod_fast_secp256r1
  9346. #define asm_mmod_fast_secp256r1 0
  9347. #endif
  9348. #if defined(default_RNG_defined) && default_RNG_defined
  9349. static uECC_RNG_Function g_rng_function = &default_RNG;
  9350. #else
  9351. static uECC_RNG_Function g_rng_function = 0;
  9352. #endif
  9353. void uECC_set_rng(uECC_RNG_Function rng_function) {
  9354. g_rng_function = rng_function;
  9355. }
  9356. uECC_RNG_Function uECC_get_rng(void) {
  9357. return g_rng_function;
  9358. }
  9359. int uECC_curve_private_key_size(uECC_Curve curve) {
  9360. return BITS_TO_BYTES(curve->num_n_bits);
  9361. }
  9362. int uECC_curve_public_key_size(uECC_Curve curve) {
  9363. return 2 * curve->num_bytes;
  9364. }
  9365. #if !asm_clear
  9366. uECC_VLI_API void uECC_vli_clear(uECC_word_t *vli, wordcount_t num_words) {
  9367. wordcount_t i;
  9368. for (i = 0; i < num_words; ++i) {
  9369. vli[i] = 0;
  9370. }
  9371. }
  9372. #endif /* !asm_clear */
  9373. /* Constant-time comparison to zero - secure way to compare long integers */
  9374. /* Returns 1 if vli == 0, 0 otherwise. */
  9375. uECC_VLI_API uECC_word_t uECC_vli_isZero(const uECC_word_t *vli,
  9376. wordcount_t num_words) {
  9377. uECC_word_t bits = 0;
  9378. wordcount_t i;
  9379. for (i = 0; i < num_words; ++i) {
  9380. bits |= vli[i];
  9381. }
  9382. return (bits == 0);
  9383. }
  9384. /* Returns nonzero if bit 'bit' of vli is set. */
  9385. uECC_VLI_API uECC_word_t uECC_vli_testBit(const uECC_word_t *vli,
  9386. bitcount_t bit) {
  9387. return (vli[bit >> uECC_WORD_BITS_SHIFT] &
  9388. ((uECC_word_t) 1 << (bit & uECC_WORD_BITS_MASK)));
  9389. }
  9390. /* Counts the number of words in vli. */
  9391. static wordcount_t vli_numDigits(const uECC_word_t *vli,
  9392. const wordcount_t max_words) {
  9393. wordcount_t i;
  9394. /* Search from the end until we find a non-zero digit.
  9395. We do it in reverse because we expect that most digits will be nonzero. */
  9396. for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) {
  9397. }
  9398. return (i + 1);
  9399. }
  9400. /* Counts the number of bits required to represent vli. */
  9401. uECC_VLI_API bitcount_t uECC_vli_numBits(const uECC_word_t *vli,
  9402. const wordcount_t max_words) {
  9403. uECC_word_t i;
  9404. uECC_word_t digit;
  9405. wordcount_t num_digits = vli_numDigits(vli, max_words);
  9406. if (num_digits == 0) {
  9407. return 0;
  9408. }
  9409. digit = vli[num_digits - 1];
  9410. for (i = 0; digit; ++i) {
  9411. digit >>= 1;
  9412. }
  9413. return (((bitcount_t) ((num_digits - 1) << uECC_WORD_BITS_SHIFT)) +
  9414. (bitcount_t) i);
  9415. }
  9416. /* Sets dest = src. */
  9417. #if !asm_set
  9418. uECC_VLI_API void uECC_vli_set(uECC_word_t *dest, const uECC_word_t *src,
  9419. wordcount_t num_words) {
  9420. wordcount_t i;
  9421. for (i = 0; i < num_words; ++i) {
  9422. dest[i] = src[i];
  9423. }
  9424. }
  9425. #endif /* !asm_set */
  9426. /* Returns sign of left - right. */
  9427. static cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t *left,
  9428. const uECC_word_t *right,
  9429. wordcount_t num_words) {
  9430. wordcount_t i;
  9431. for (i = num_words - 1; i >= 0; --i) {
  9432. if (left[i] > right[i]) {
  9433. return 1;
  9434. } else if (left[i] < right[i]) {
  9435. return -1;
  9436. }
  9437. }
  9438. return 0;
  9439. }
  9440. /* Constant-time comparison function - secure way to compare long integers */
  9441. /* Returns one if left == right, zero otherwise. */
  9442. uECC_VLI_API uECC_word_t uECC_vli_equal(const uECC_word_t *left,
  9443. const uECC_word_t *right,
  9444. wordcount_t num_words) {
  9445. uECC_word_t diff = 0;
  9446. wordcount_t i;
  9447. for (i = num_words - 1; i >= 0; --i) {
  9448. diff |= (left[i] ^ right[i]);
  9449. }
  9450. return (diff == 0);
  9451. }
  9452. uECC_VLI_API uECC_word_t uECC_vli_sub(uECC_word_t *result,
  9453. const uECC_word_t *left,
  9454. const uECC_word_t *right,
  9455. wordcount_t num_words);
  9456. /* Returns sign of left - right, in constant time. */
  9457. uECC_VLI_API cmpresult_t uECC_vli_cmp(const uECC_word_t *left,
  9458. const uECC_word_t *right,
  9459. wordcount_t num_words) {
  9460. uECC_word_t tmp[uECC_MAX_WORDS];
  9461. uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words);
  9462. uECC_word_t equal = uECC_vli_isZero(tmp, num_words);
  9463. return (cmpresult_t) (!equal - 2 * neg);
  9464. }
  9465. /* Computes vli = vli >> 1. */
  9466. #if !asm_rshift1
  9467. uECC_VLI_API void uECC_vli_rshift1(uECC_word_t *vli, wordcount_t num_words) {
  9468. uECC_word_t *end = vli;
  9469. uECC_word_t carry = 0;
  9470. vli += num_words;
  9471. while (vli-- > end) {
  9472. uECC_word_t temp = *vli;
  9473. *vli = (temp >> 1) | carry;
  9474. carry = temp << (uECC_WORD_BITS - 1);
  9475. }
  9476. }
  9477. #endif /* !asm_rshift1 */
  9478. /* Computes result = left + right, returning carry. Can modify in place. */
  9479. #if !asm_add
  9480. uECC_VLI_API uECC_word_t uECC_vli_add(uECC_word_t *result,
  9481. const uECC_word_t *left,
  9482. const uECC_word_t *right,
  9483. wordcount_t num_words) {
  9484. uECC_word_t carry = 0;
  9485. wordcount_t i;
  9486. for (i = 0; i < num_words; ++i) {
  9487. uECC_word_t sum = left[i] + right[i] + carry;
  9488. if (sum != left[i]) {
  9489. carry = (sum < left[i]);
  9490. }
  9491. result[i] = sum;
  9492. }
  9493. return carry;
  9494. }
  9495. #endif /* !asm_add */
  9496. /* Computes result = left - right, returning borrow. Can modify in place. */
  9497. #if !asm_sub
  9498. uECC_VLI_API uECC_word_t uECC_vli_sub(uECC_word_t *result,
  9499. const uECC_word_t *left,
  9500. const uECC_word_t *right,
  9501. wordcount_t num_words) {
  9502. uECC_word_t borrow = 0;
  9503. wordcount_t i;
  9504. for (i = 0; i < num_words; ++i) {
  9505. uECC_word_t diff = left[i] - right[i] - borrow;
  9506. if (diff != left[i]) {
  9507. borrow = (diff > left[i]);
  9508. }
  9509. result[i] = diff;
  9510. }
  9511. return borrow;
  9512. }
  9513. #endif /* !asm_sub */
  9514. #if !asm_mult || (uECC_SQUARE_FUNC && !asm_square) || \
  9515. (uECC_SUPPORTS_secp256k1 && (uECC_OPTIMIZATION_LEVEL > 0) && \
  9516. ((uECC_WORD_SIZE == 1) || (uECC_WORD_SIZE == 8)))
  9517. static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
  9518. uECC_word_t *r1, uECC_word_t *r2) {
  9519. #if uECC_WORD_SIZE == 8
  9520. uint64_t a0 = a & 0xffffffff;
  9521. uint64_t a1 = a >> 32;
  9522. uint64_t b0 = b & 0xffffffff;
  9523. uint64_t b1 = b >> 32;
  9524. uint64_t i0 = a0 * b0;
  9525. uint64_t i1 = a0 * b1;
  9526. uint64_t i2 = a1 * b0;
  9527. uint64_t i3 = a1 * b1;
  9528. uint64_t p0, p1;
  9529. i2 += (i0 >> 32);
  9530. i2 += i1;
  9531. if (i2 < i1) { /* overflow */
  9532. i3 += 0x100000000;
  9533. }
  9534. p0 = (i0 & 0xffffffff) | (i2 << 32);
  9535. p1 = i3 + (i2 >> 32);
  9536. *r0 += p0;
  9537. *r1 += (p1 + (*r0 < p0));
  9538. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  9539. #else
  9540. uECC_dword_t p = (uECC_dword_t) a * b;
  9541. uECC_dword_t r01 = ((uECC_dword_t) (*r1) << uECC_WORD_BITS) | *r0;
  9542. r01 += p;
  9543. *r2 += (r01 < p);
  9544. *r1 = (uECC_word_t) (r01 >> uECC_WORD_BITS);
  9545. *r0 = (uECC_word_t) r01;
  9546. #endif
  9547. }
  9548. #endif /* muladd needed */
  9549. #if !asm_mult
  9550. uECC_VLI_API void uECC_vli_mult(uECC_word_t *result, const uECC_word_t *left,
  9551. const uECC_word_t *right,
  9552. wordcount_t num_words) {
  9553. uECC_word_t r0 = 0;
  9554. uECC_word_t r1 = 0;
  9555. uECC_word_t r2 = 0;
  9556. wordcount_t i, k;
  9557. /* Compute each digit of result in sequence, maintaining the carries. */
  9558. for (k = 0; k < num_words; ++k) {
  9559. for (i = 0; i <= k; ++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. for (k = num_words; k < num_words * 2 - 1; ++k) {
  9568. for (i = (wordcount_t) ((k + 1) - num_words); i < num_words; ++i) {
  9569. muladd(left[i], right[k - i], &r0, &r1, &r2);
  9570. }
  9571. result[k] = r0;
  9572. r0 = r1;
  9573. r1 = r2;
  9574. r2 = 0;
  9575. }
  9576. result[num_words * 2 - 1] = r0;
  9577. }
  9578. #endif /* !asm_mult */
  9579. #if uECC_SQUARE_FUNC
  9580. #if !asm_square
  9581. static void mul2add(uECC_word_t a, uECC_word_t b, uECC_word_t *r0,
  9582. uECC_word_t *r1, uECC_word_t *r2) {
  9583. #if uECC_WORD_SIZE == 8
  9584. uint64_t a0 = a & 0xffffffffull;
  9585. uint64_t a1 = a >> 32;
  9586. uint64_t b0 = b & 0xffffffffull;
  9587. uint64_t b1 = b >> 32;
  9588. uint64_t i0 = a0 * b0;
  9589. uint64_t i1 = a0 * b1;
  9590. uint64_t i2 = a1 * b0;
  9591. uint64_t i3 = a1 * b1;
  9592. uint64_t p0, p1;
  9593. i2 += (i0 >> 32);
  9594. i2 += i1;
  9595. if (i2 < i1) { /* overflow */
  9596. i3 += 0x100000000ull;
  9597. }
  9598. p0 = (i0 & 0xffffffffull) | (i2 << 32);
  9599. p1 = i3 + (i2 >> 32);
  9600. *r2 += (p1 >> 63);
  9601. p1 = (p1 << 1) | (p0 >> 63);
  9602. p0 <<= 1;
  9603. *r0 += p0;
  9604. *r1 += (p1 + (*r0 < p0));
  9605. *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0));
  9606. #else
  9607. uECC_dword_t p = (uECC_dword_t) a * b;
  9608. uECC_dword_t r01 = ((uECC_dword_t) (*r1) << uECC_WORD_BITS) | *r0;
  9609. *r2 += (p >> (uECC_WORD_BITS * 2 - 1));
  9610. p *= 2;
  9611. r01 += p;
  9612. *r2 += (r01 < p);
  9613. *r1 = r01 >> uECC_WORD_BITS;
  9614. *r0 = (uECC_word_t) r01;
  9615. #endif
  9616. }
  9617. uECC_VLI_API void uECC_vli_square(uECC_word_t *result, const uECC_word_t *left,
  9618. wordcount_t num_words) {
  9619. uECC_word_t r0 = 0;
  9620. uECC_word_t r1 = 0;
  9621. uECC_word_t r2 = 0;
  9622. wordcount_t i, k;
  9623. for (k = 0; k < num_words * 2 - 1; ++k) {
  9624. uECC_word_t min = (k < num_words ? 0 : (k + 1) - num_words);
  9625. for (i = min; i <= k && i <= k - i; ++i) {
  9626. if (i < k - i) {
  9627. mul2add(left[i], left[k - i], &r0, &r1, &r2);
  9628. } else {
  9629. muladd(left[i], left[k - i], &r0, &r1, &r2);
  9630. }
  9631. }
  9632. result[k] = r0;
  9633. r0 = r1;
  9634. r1 = r2;
  9635. r2 = 0;
  9636. }
  9637. result[num_words * 2 - 1] = r0;
  9638. }
  9639. #endif /* !asm_square */
  9640. #else /* uECC_SQUARE_FUNC */
  9641. #if uECC_ENABLE_VLI_API
  9642. uECC_VLI_API void uECC_vli_square(uECC_word_t *result, const uECC_word_t *left,
  9643. wordcount_t num_words) {
  9644. uECC_vli_mult(result, left, left, num_words);
  9645. }
  9646. #endif /* uECC_ENABLE_VLI_API */
  9647. #endif /* uECC_SQUARE_FUNC */
  9648. /* Computes result = (left + right) % mod.
  9649. Assumes that left < mod and right < mod, and that result does not overlap
  9650. mod. */
  9651. uECC_VLI_API void uECC_vli_modAdd(uECC_word_t *result, const uECC_word_t *left,
  9652. const uECC_word_t *right,
  9653. const uECC_word_t *mod,
  9654. wordcount_t num_words) {
  9655. uECC_word_t carry = uECC_vli_add(result, left, right, num_words);
  9656. if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {
  9657. /* result > mod (result = mod + remainder), so subtract mod to get
  9658. * remainder. */
  9659. uECC_vli_sub(result, result, mod, num_words);
  9660. }
  9661. }
  9662. /* Computes result = (left - right) % mod.
  9663. Assumes that left < mod and right < mod, and that result does not overlap
  9664. mod. */
  9665. uECC_VLI_API void uECC_vli_modSub(uECC_word_t *result, const uECC_word_t *left,
  9666. const uECC_word_t *right,
  9667. const uECC_word_t *mod,
  9668. wordcount_t num_words) {
  9669. uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);
  9670. if (l_borrow) {
  9671. /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,
  9672. we can get the correct result from result + mod (with overflow). */
  9673. uECC_vli_add(result, result, mod, num_words);
  9674. }
  9675. }
  9676. /* Computes result = product % mod, where product is 2N words long. */
  9677. /* Currently only designed to work for curve_p or curve_n. */
  9678. uECC_VLI_API void uECC_vli_mmod(uECC_word_t *result, uECC_word_t *product,
  9679. const uECC_word_t *mod, wordcount_t num_words) {
  9680. uECC_word_t mod_multiple[2 * uECC_MAX_WORDS];
  9681. uECC_word_t tmp[2 * uECC_MAX_WORDS];
  9682. uECC_word_t *v[2] = {tmp, product};
  9683. uECC_word_t index;
  9684. /* Shift mod so its highest set bit is at the maximum position. */
  9685. bitcount_t shift = (bitcount_t) (
  9686. (num_words * 2 * uECC_WORD_BITS) - uECC_vli_numBits(mod, num_words));
  9687. wordcount_t word_shift = (wordcount_t) (shift / uECC_WORD_BITS);
  9688. wordcount_t bit_shift = (wordcount_t) (shift % uECC_WORD_BITS);
  9689. uECC_word_t carry = 0;
  9690. uECC_vli_clear(mod_multiple, word_shift);
  9691. if (bit_shift > 0) {
  9692. for (index = 0; index < (uECC_word_t) num_words; ++index) {
  9693. mod_multiple[(uECC_word_t) word_shift + index] =
  9694. (uECC_word_t) (mod[index] << bit_shift) | carry;
  9695. carry = mod[index] >> (uECC_WORD_BITS - bit_shift);
  9696. }
  9697. } else {
  9698. uECC_vli_set(mod_multiple + word_shift, mod, num_words);
  9699. }
  9700. for (index = 1; shift >= 0; --shift) {
  9701. uECC_word_t borrow = 0;
  9702. wordcount_t i;
  9703. for (i = 0; i < num_words * 2; ++i) {
  9704. uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow;
  9705. if (diff != v[index][i]) {
  9706. borrow = (diff > v[index][i]);
  9707. }
  9708. v[1 - index][i] = diff;
  9709. }
  9710. index = !(index ^ borrow); /* Swap the index if there was no borrow */
  9711. uECC_vli_rshift1(mod_multiple, num_words);
  9712. mod_multiple[num_words - 1] |= mod_multiple[num_words]
  9713. << (uECC_WORD_BITS - 1);
  9714. uECC_vli_rshift1(mod_multiple + num_words, num_words);
  9715. }
  9716. uECC_vli_set(result, v[index], num_words);
  9717. }
  9718. /* Computes result = (left * right) % mod. */
  9719. uECC_VLI_API void uECC_vli_modMult(uECC_word_t *result, const uECC_word_t *left,
  9720. const uECC_word_t *right,
  9721. const uECC_word_t *mod,
  9722. wordcount_t num_words) {
  9723. uECC_word_t product[2 * uECC_MAX_WORDS];
  9724. uECC_vli_mult(product, left, right, num_words);
  9725. uECC_vli_mmod(result, product, mod, num_words);
  9726. }
  9727. uECC_VLI_API void uECC_vli_modMult_fast(uECC_word_t *result,
  9728. const uECC_word_t *left,
  9729. const uECC_word_t *right,
  9730. uECC_Curve curve) {
  9731. uECC_word_t product[2 * uECC_MAX_WORDS];
  9732. uECC_vli_mult(product, left, right, curve->num_words);
  9733. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9734. curve->mmod_fast(result, product);
  9735. #else
  9736. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  9737. #endif
  9738. }
  9739. #if uECC_SQUARE_FUNC
  9740. #if uECC_ENABLE_VLI_API
  9741. /* Computes result = left^2 % mod. */
  9742. uECC_VLI_API void uECC_vli_modSquare(uECC_word_t *result,
  9743. const uECC_word_t *left,
  9744. const uECC_word_t *mod,
  9745. wordcount_t num_words) {
  9746. uECC_word_t product[2 * uECC_MAX_WORDS];
  9747. uECC_vli_square(product, left, num_words);
  9748. uECC_vli_mmod(result, product, mod, num_words);
  9749. }
  9750. #endif /* uECC_ENABLE_VLI_API */
  9751. uECC_VLI_API void uECC_vli_modSquare_fast(uECC_word_t *result,
  9752. const uECC_word_t *left,
  9753. uECC_Curve curve) {
  9754. uECC_word_t product[2 * uECC_MAX_WORDS];
  9755. uECC_vli_square(product, left, curve->num_words);
  9756. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9757. curve->mmod_fast(result, product);
  9758. #else
  9759. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  9760. #endif
  9761. }
  9762. #else /* uECC_SQUARE_FUNC */
  9763. #if uECC_ENABLE_VLI_API
  9764. uECC_VLI_API void uECC_vli_modSquare(uECC_word_t *result,
  9765. const uECC_word_t *left,
  9766. const uECC_word_t *mod,
  9767. wordcount_t num_words) {
  9768. uECC_vli_modMult(result, left, left, mod, num_words);
  9769. }
  9770. #endif /* uECC_ENABLE_VLI_API */
  9771. uECC_VLI_API void uECC_vli_modSquare_fast(uECC_word_t *result,
  9772. const uECC_word_t *left,
  9773. uECC_Curve curve) {
  9774. uECC_vli_modMult_fast(result, left, left, curve);
  9775. }
  9776. #endif /* uECC_SQUARE_FUNC */
  9777. #define EVEN(vli) (!(vli[0] & 1))
  9778. static void vli_modInv_update(uECC_word_t *uv, const uECC_word_t *mod,
  9779. wordcount_t num_words) {
  9780. uECC_word_t carry = 0;
  9781. if (!EVEN(uv)) {
  9782. carry = uECC_vli_add(uv, uv, mod, num_words);
  9783. }
  9784. uECC_vli_rshift1(uv, num_words);
  9785. if (carry) {
  9786. uv[num_words - 1] |= HIGH_BIT_SET;
  9787. }
  9788. }
  9789. /* Computes result = (1 / input) % mod. All VLIs are the same size.
  9790. See "From Euclid's GCD to Montgomery Multiplication to the Great Divide" */
  9791. uECC_VLI_API void uECC_vli_modInv(uECC_word_t *result, const uECC_word_t *input,
  9792. const uECC_word_t *mod,
  9793. wordcount_t num_words) {
  9794. uECC_word_t a[uECC_MAX_WORDS], b[uECC_MAX_WORDS], u[uECC_MAX_WORDS],
  9795. v[uECC_MAX_WORDS];
  9796. cmpresult_t cmpResult;
  9797. if (uECC_vli_isZero(input, num_words)) {
  9798. uECC_vli_clear(result, num_words);
  9799. return;
  9800. }
  9801. uECC_vli_set(a, input, num_words);
  9802. uECC_vli_set(b, mod, num_words);
  9803. uECC_vli_clear(u, num_words);
  9804. u[0] = 1;
  9805. uECC_vli_clear(v, num_words);
  9806. while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {
  9807. if (EVEN(a)) {
  9808. uECC_vli_rshift1(a, num_words);
  9809. vli_modInv_update(u, mod, num_words);
  9810. } else if (EVEN(b)) {
  9811. uECC_vli_rshift1(b, num_words);
  9812. vli_modInv_update(v, mod, num_words);
  9813. } else if (cmpResult > 0) {
  9814. uECC_vli_sub(a, a, b, num_words);
  9815. uECC_vli_rshift1(a, num_words);
  9816. if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {
  9817. uECC_vli_add(u, u, mod, num_words);
  9818. }
  9819. uECC_vli_sub(u, u, v, num_words);
  9820. vli_modInv_update(u, mod, num_words);
  9821. } else {
  9822. uECC_vli_sub(b, b, a, num_words);
  9823. uECC_vli_rshift1(b, num_words);
  9824. if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {
  9825. uECC_vli_add(v, v, mod, num_words);
  9826. }
  9827. uECC_vli_sub(v, v, u, num_words);
  9828. vli_modInv_update(v, mod, num_words);
  9829. }
  9830. }
  9831. uECC_vli_set(result, u, num_words);
  9832. }
  9833. /* ------ Point operations ------ */
  9834. /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  9835. #ifndef _UECC_CURVE_SPECIFIC_H_
  9836. #define _UECC_CURVE_SPECIFIC_H_
  9837. #define num_bytes_secp160r1 20
  9838. #define num_bytes_secp192r1 24
  9839. #define num_bytes_secp224r1 28
  9840. #define num_bytes_secp256r1 32
  9841. #define num_bytes_secp256k1 32
  9842. #if (uECC_WORD_SIZE == 1)
  9843. #define num_words_secp160r1 20
  9844. #define num_words_secp192r1 24
  9845. #define num_words_secp224r1 28
  9846. #define num_words_secp256r1 32
  9847. #define num_words_secp256k1 32
  9848. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) \
  9849. 0x##a, 0x##b, 0x##c, 0x##d, 0x##e, 0x##f, 0x##g, 0x##h
  9850. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##a, 0x##b, 0x##c, 0x##d
  9851. #elif (uECC_WORD_SIZE == 4)
  9852. #define num_words_secp160r1 5
  9853. #define num_words_secp192r1 6
  9854. #define num_words_secp224r1 7
  9855. #define num_words_secp256r1 8
  9856. #define num_words_secp256k1 8
  9857. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e
  9858. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a
  9859. #elif (uECC_WORD_SIZE == 8)
  9860. #define num_words_secp160r1 3
  9861. #define num_words_secp192r1 3
  9862. #define num_words_secp224r1 4
  9863. #define num_words_secp256r1 4
  9864. #define num_words_secp256k1 4
  9865. #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##h##g##f##e##d##c##b##a##U
  9866. #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a##U
  9867. #endif /* uECC_WORD_SIZE */
  9868. #if uECC_SUPPORTS_secp160r1 || uECC_SUPPORTS_secp192r1 || \
  9869. uECC_SUPPORTS_secp224r1 || uECC_SUPPORTS_secp256r1
  9870. static void double_jacobian_default(uECC_word_t *X1, uECC_word_t *Y1,
  9871. uECC_word_t *Z1, uECC_Curve curve) {
  9872. /* t1 = X, t2 = Y, t3 = Z */
  9873. uECC_word_t t4[uECC_MAX_WORDS];
  9874. uECC_word_t t5[uECC_MAX_WORDS];
  9875. wordcount_t num_words = curve->num_words;
  9876. if (uECC_vli_isZero(Z1, num_words)) {
  9877. return;
  9878. }
  9879. uECC_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */
  9880. uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */
  9881. uECC_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */
  9882. uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */
  9883. uECC_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */
  9884. uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */
  9885. uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */
  9886. uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */
  9887. uECC_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */
  9888. uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */
  9889. uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */
  9890. if (uECC_vli_testBit(X1, 0)) {
  9891. uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words);
  9892. uECC_vli_rshift1(X1, num_words);
  9893. X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1);
  9894. } else {
  9895. uECC_vli_rshift1(X1, num_words);
  9896. }
  9897. /* t1 = 3/2*(x1^2 - z1^4) = B */
  9898. uECC_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */
  9899. uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */
  9900. uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */
  9901. uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */
  9902. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */
  9903. uECC_vli_modSub(t4, X1, t4, curve->p,
  9904. num_words); /* t4 = B * (A - x3) - y1^4 = y3 */
  9905. uECC_vli_set(X1, Z1, num_words);
  9906. uECC_vli_set(Z1, Y1, num_words);
  9907. uECC_vli_set(Y1, t4, num_words);
  9908. }
  9909. /* Computes result = x^3 + ax + b. result must not overlap x. */
  9910. static void x_side_default(uECC_word_t *result, const uECC_word_t *x,
  9911. uECC_Curve curve) {
  9912. uECC_word_t _3[uECC_MAX_WORDS] = {3}; /* -a = 3 */
  9913. wordcount_t num_words = curve->num_words;
  9914. uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  9915. uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */
  9916. uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */
  9917. uECC_vli_modAdd(result, result, curve->b, curve->p,
  9918. num_words); /* r = x^3 - 3x + b */
  9919. }
  9920. #endif /* uECC_SUPPORTS_secp... */
  9921. #if uECC_SUPPORT_COMPRESSED_POINT
  9922. #if uECC_SUPPORTS_secp160r1 || uECC_SUPPORTS_secp192r1 || \
  9923. uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1
  9924. /* Compute a = sqrt(a) (mod curve_p). */
  9925. static void mod_sqrt_default(uECC_word_t *a, uECC_Curve curve) {
  9926. bitcount_t i;
  9927. uECC_word_t p1[uECC_MAX_WORDS] = {1};
  9928. uECC_word_t l_result[uECC_MAX_WORDS] = {1};
  9929. wordcount_t num_words = curve->num_words;
  9930. /* When curve->p == 3 (mod 4), we can compute
  9931. sqrt(a) = a^((curve->p + 1) / 4) (mod curve->p). */
  9932. uECC_vli_add(p1, curve->p, p1, num_words); /* p1 = curve_p + 1 */
  9933. for (i = uECC_vli_numBits(p1, num_words) - 1; i > 1; --i) {
  9934. uECC_vli_modSquare_fast(l_result, l_result, curve);
  9935. if (uECC_vli_testBit(p1, i)) {
  9936. uECC_vli_modMult_fast(l_result, l_result, a, curve);
  9937. }
  9938. }
  9939. uECC_vli_set(a, l_result, num_words);
  9940. }
  9941. #endif /* uECC_SUPPORTS_secp... */
  9942. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  9943. #if uECC_SUPPORTS_secp160r1
  9944. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9945. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product);
  9946. #endif
  9947. static const struct uECC_Curve_t curve_secp160r1 = {
  9948. num_words_secp160r1,
  9949. num_bytes_secp160r1,
  9950. 161, /* num_n_bits */
  9951. {BYTES_TO_WORDS_8(FF, FF, FF, 7F, FF, FF, FF, FF),
  9952. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  9953. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  9954. {BYTES_TO_WORDS_8(57, 22, 75, CA, D3, AE, 27, F9),
  9955. BYTES_TO_WORDS_8(C8, F4, 01, 00, 00, 00, 00, 00),
  9956. BYTES_TO_WORDS_8(00, 00, 00, 00, 01, 00, 00, 00)},
  9957. {BYTES_TO_WORDS_8(82, FC, CB, 13, B9, 8B, C3, 68),
  9958. BYTES_TO_WORDS_8(89, 69, 64, 46, 28, 73, F5, 8E),
  9959. BYTES_TO_WORDS_4(68, B5, 96, 4A),
  9960. BYTES_TO_WORDS_8(32, FB, C5, 7A, 37, 51, 23, 04),
  9961. BYTES_TO_WORDS_8(12, C9, DC, 59, 7D, 94, 68, 31),
  9962. BYTES_TO_WORDS_4(55, 28, A6, 23)},
  9963. {BYTES_TO_WORDS_8(45, FA, 65, C5, AD, D4, D4, 81),
  9964. BYTES_TO_WORDS_8(9F, F8, AC, 65, 8B, 7A, BD, 54),
  9965. BYTES_TO_WORDS_4(FC, BE, 97, 1C)},
  9966. &double_jacobian_default,
  9967. #if uECC_SUPPORT_COMPRESSED_POINT
  9968. &mod_sqrt_default,
  9969. #endif
  9970. &x_side_default,
  9971. #if (uECC_OPTIMIZATION_LEVEL > 0)
  9972. &vli_mmod_fast_secp160r1
  9973. #endif
  9974. };
  9975. uECC_Curve uECC_secp160r1(void) {
  9976. return &curve_secp160r1;
  9977. }
  9978. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1)
  9979. /* Computes result = product % curve_p
  9980. see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
  9981. Note that this only works if log2(omega) < log2(p) / 2 */
  9982. static void omega_mult_secp160r1(uECC_word_t *result, const uECC_word_t *right);
  9983. #if uECC_WORD_SIZE == 8
  9984. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product) {
  9985. uECC_word_t tmp[2 * num_words_secp160r1];
  9986. uECC_word_t copy;
  9987. uECC_vli_clear(tmp, num_words_secp160r1);
  9988. uECC_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  9989. omega_mult_secp160r1(tmp,
  9990. product + num_words_secp160r1 - 1); /* (Rq, q) = q * c */
  9991. product[num_words_secp160r1 - 1] &= 0xffffffff;
  9992. copy = tmp[num_words_secp160r1 - 1];
  9993. tmp[num_words_secp160r1 - 1] &= 0xffffffff;
  9994. uECC_vli_add(result, product, tmp, num_words_secp160r1); /* (C, r) = r + q */
  9995. uECC_vli_clear(product, num_words_secp160r1);
  9996. tmp[num_words_secp160r1 - 1] = copy;
  9997. omega_mult_secp160r1(product, tmp + num_words_secp160r1 - 1); /* Rq*c */
  9998. uECC_vli_add(result, result, product,
  9999. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  10000. while (uECC_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) >
  10001. 0) {
  10002. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  10003. }
  10004. }
  10005. static void omega_mult_secp160r1(uint64_t *result, const uint64_t *right) {
  10006. uint32_t carry;
  10007. unsigned i;
  10008. /* Multiply by (2^31 + 1). */
  10009. carry = 0;
  10010. for (i = 0; i < num_words_secp160r1; ++i) {
  10011. uint64_t tmp = (right[i] >> 32) | (right[i + 1] << 32);
  10012. result[i] = (tmp << 31) + tmp + carry;
  10013. carry = (tmp >> 33) + (result[i] < tmp || (carry && result[i] == tmp));
  10014. }
  10015. result[i] = carry;
  10016. }
  10017. #else
  10018. static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product) {
  10019. uECC_word_t tmp[2 * num_words_secp160r1];
  10020. uECC_word_t carry;
  10021. uECC_vli_clear(tmp, num_words_secp160r1);
  10022. uECC_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1);
  10023. omega_mult_secp160r1(tmp,
  10024. product + num_words_secp160r1); /* (Rq, q) = q * c */
  10025. carry = uECC_vli_add(result, product, tmp,
  10026. num_words_secp160r1); /* (C, r) = r + q */
  10027. uECC_vli_clear(product, num_words_secp160r1);
  10028. omega_mult_secp160r1(product, tmp + num_words_secp160r1); /* Rq*c */
  10029. carry += uECC_vli_add(result, result, product,
  10030. num_words_secp160r1); /* (C1, r) = r + Rq*c */
  10031. while (carry > 0) {
  10032. --carry;
  10033. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  10034. }
  10035. if (uECC_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) > 0) {
  10036. uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1);
  10037. }
  10038. }
  10039. #endif
  10040. #if uECC_WORD_SIZE == 1
  10041. static void omega_mult_secp160r1(uint8_t *result, const uint8_t *right) {
  10042. uint8_t carry;
  10043. uint8_t i;
  10044. /* Multiply by (2^31 + 1). */
  10045. uECC_vli_set(result + 4, right, num_words_secp160r1); /* 2^32 */
  10046. uECC_vli_rshift1(result + 4, num_words_secp160r1); /* 2^31 */
  10047. result[3] = right[0] << 7; /* get last bit from shift */
  10048. carry =
  10049. uECC_vli_add(result, result, right, num_words_secp160r1); /* 2^31 + 1 */
  10050. for (i = num_words_secp160r1; carry; ++i) {
  10051. uint16_t sum = (uint16_t) result[i] + carry;
  10052. result[i] = (uint8_t) sum;
  10053. carry = sum >> 8;
  10054. }
  10055. }
  10056. #elif uECC_WORD_SIZE == 4
  10057. static void omega_mult_secp160r1(uint32_t *result, const uint32_t *right) {
  10058. uint32_t carry;
  10059. unsigned i;
  10060. /* Multiply by (2^31 + 1). */
  10061. uECC_vli_set(result + 1, right, num_words_secp160r1); /* 2^32 */
  10062. uECC_vli_rshift1(result + 1, num_words_secp160r1); /* 2^31 */
  10063. result[0] = right[0] << 31; /* get last bit from shift */
  10064. carry =
  10065. uECC_vli_add(result, result, right, num_words_secp160r1); /* 2^31 + 1 */
  10066. for (i = num_words_secp160r1; carry; ++i) {
  10067. uint64_t sum = (uint64_t) result[i] + carry;
  10068. result[i] = (uint32_t) sum;
  10069. carry = sum >> 32;
  10070. }
  10071. }
  10072. #endif /* uECC_WORD_SIZE */
  10073. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) */
  10074. #endif /* uECC_SUPPORTS_secp160r1 */
  10075. #if uECC_SUPPORTS_secp192r1
  10076. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10077. static void vli_mmod_fast_secp192r1(uECC_word_t *result, uECC_word_t *product);
  10078. #endif
  10079. static const struct uECC_Curve_t curve_secp192r1 = {
  10080. num_words_secp192r1,
  10081. num_bytes_secp192r1,
  10082. 192, /* num_n_bits */
  10083. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10084. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  10085. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  10086. {BYTES_TO_WORDS_8(31, 28, D2, B4, B1, C9, 6B, 14),
  10087. BYTES_TO_WORDS_8(36, F8, DE, 99, FF, FF, FF, FF),
  10088. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  10089. {BYTES_TO_WORDS_8(12, 10, FF, 82, FD, 0A, FF, F4),
  10090. BYTES_TO_WORDS_8(00, 88, A1, 43, EB, 20, BF, 7C),
  10091. BYTES_TO_WORDS_8(F6, 90, 30, B0, 0E, A8, 8D, 18),
  10092. BYTES_TO_WORDS_8(11, 48, 79, 1E, A1, 77, F9, 73),
  10093. BYTES_TO_WORDS_8(D5, CD, 24, 6B, ED, 11, 10, 63),
  10094. BYTES_TO_WORDS_8(78, DA, C8, FF, 95, 2B, 19, 07)},
  10095. {BYTES_TO_WORDS_8(B1, B9, 46, C1, EC, DE, B8, FE),
  10096. BYTES_TO_WORDS_8(49, 30, 24, 72, AB, E9, A7, 0F),
  10097. BYTES_TO_WORDS_8(E7, 80, 9C, E5, 19, 05, 21, 64)},
  10098. &double_jacobian_default,
  10099. #if uECC_SUPPORT_COMPRESSED_POINT
  10100. &mod_sqrt_default,
  10101. #endif
  10102. &x_side_default,
  10103. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10104. &vli_mmod_fast_secp192r1
  10105. #endif
  10106. };
  10107. uECC_Curve uECC_secp192r1(void) {
  10108. return &curve_secp192r1;
  10109. }
  10110. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10111. /* Computes result = product % curve_p.
  10112. See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf
  10113. */
  10114. #if uECC_WORD_SIZE == 1
  10115. static void vli_mmod_fast_secp192r1(uint8_t *result, uint8_t *product) {
  10116. uint8_t tmp[num_words_secp192r1];
  10117. uint8_t carry;
  10118. uECC_vli_set(result, product, num_words_secp192r1);
  10119. uECC_vli_set(tmp, &product[24], num_words_secp192r1);
  10120. carry = uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10121. tmp[0] = tmp[1] = tmp[2] = tmp[3] = tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10122. tmp[8] = product[24];
  10123. tmp[9] = product[25];
  10124. tmp[10] = product[26];
  10125. tmp[11] = product[27];
  10126. tmp[12] = product[28];
  10127. tmp[13] = product[29];
  10128. tmp[14] = product[30];
  10129. tmp[15] = product[31];
  10130. tmp[16] = product[32];
  10131. tmp[17] = product[33];
  10132. tmp[18] = product[34];
  10133. tmp[19] = product[35];
  10134. tmp[20] = product[36];
  10135. tmp[21] = product[37];
  10136. tmp[22] = product[38];
  10137. tmp[23] = product[39];
  10138. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10139. tmp[0] = tmp[8] = product[40];
  10140. tmp[1] = tmp[9] = product[41];
  10141. tmp[2] = tmp[10] = product[42];
  10142. tmp[3] = tmp[11] = product[43];
  10143. tmp[4] = tmp[12] = product[44];
  10144. tmp[5] = tmp[13] = product[45];
  10145. tmp[6] = tmp[14] = product[46];
  10146. tmp[7] = tmp[15] = product[47];
  10147. tmp[16] = tmp[17] = tmp[18] = tmp[19] = tmp[20] = tmp[21] = tmp[22] =
  10148. tmp[23] = 0;
  10149. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10150. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10151. num_words_secp192r1) != 1) {
  10152. carry -=
  10153. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10154. }
  10155. }
  10156. #elif uECC_WORD_SIZE == 4
  10157. static void vli_mmod_fast_secp192r1(uint32_t *result, uint32_t *product) {
  10158. uint32_t tmp[num_words_secp192r1];
  10159. int carry;
  10160. uECC_vli_set(result, product, num_words_secp192r1);
  10161. uECC_vli_set(tmp, &product[6], num_words_secp192r1);
  10162. carry = uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10163. tmp[0] = tmp[1] = 0;
  10164. tmp[2] = product[6];
  10165. tmp[3] = product[7];
  10166. tmp[4] = product[8];
  10167. tmp[5] = product[9];
  10168. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10169. tmp[0] = tmp[2] = product[10];
  10170. tmp[1] = tmp[3] = product[11];
  10171. tmp[4] = tmp[5] = 0;
  10172. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10173. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10174. num_words_secp192r1) != 1) {
  10175. carry -=
  10176. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10177. }
  10178. }
  10179. #else
  10180. static void vli_mmod_fast_secp192r1(uint64_t *result, uint64_t *product) {
  10181. uint64_t tmp[num_words_secp192r1];
  10182. int carry;
  10183. uECC_vli_set(result, product, num_words_secp192r1);
  10184. uECC_vli_set(tmp, &product[3], num_words_secp192r1);
  10185. carry = (int) uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10186. tmp[0] = 0;
  10187. tmp[1] = product[3];
  10188. tmp[2] = product[4];
  10189. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10190. tmp[0] = tmp[1] = product[5];
  10191. tmp[2] = 0;
  10192. carry += uECC_vli_add(result, result, tmp, num_words_secp192r1);
  10193. while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result,
  10194. num_words_secp192r1) != 1) {
  10195. carry -=
  10196. uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1);
  10197. }
  10198. }
  10199. #endif /* uECC_WORD_SIZE */
  10200. #endif /* (uECC_OPTIMIZATION_LEVEL > 0) */
  10201. #endif /* uECC_SUPPORTS_secp192r1 */
  10202. #if uECC_SUPPORTS_secp224r1
  10203. #if uECC_SUPPORT_COMPRESSED_POINT
  10204. static void mod_sqrt_secp224r1(uECC_word_t *a, uECC_Curve curve);
  10205. #endif
  10206. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10207. static void vli_mmod_fast_secp224r1(uECC_word_t *result, uECC_word_t *product);
  10208. #endif
  10209. static const struct uECC_Curve_t curve_secp224r1 = {
  10210. num_words_secp224r1,
  10211. num_bytes_secp224r1,
  10212. 224, /* num_n_bits */
  10213. {BYTES_TO_WORDS_8(01, 00, 00, 00, 00, 00, 00, 00),
  10214. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF),
  10215. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10216. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  10217. {BYTES_TO_WORDS_8(3D, 2A, 5C, 5C, 45, 29, DD, 13),
  10218. BYTES_TO_WORDS_8(3E, F0, B8, E0, A2, 16, FF, FF),
  10219. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10220. BYTES_TO_WORDS_4(FF, FF, FF, FF)},
  10221. {BYTES_TO_WORDS_8(21, 1D, 5C, 11, D6, 80, 32, 34),
  10222. BYTES_TO_WORDS_8(22, 11, C2, 56, D3, C1, 03, 4A),
  10223. BYTES_TO_WORDS_8(B9, 90, 13, 32, 7F, BF, B4, 6B),
  10224. BYTES_TO_WORDS_4(BD, 0C, 0E, B7),
  10225. BYTES_TO_WORDS_8(34, 7E, 00, 85, 99, 81, D5, 44),
  10226. BYTES_TO_WORDS_8(64, 47, 07, 5A, A0, 75, 43, CD),
  10227. BYTES_TO_WORDS_8(E6, DF, 22, 4C, FB, 23, F7, B5),
  10228. BYTES_TO_WORDS_4(88, 63, 37, BD)},
  10229. {BYTES_TO_WORDS_8(B4, FF, 55, 23, 43, 39, 0B, 27),
  10230. BYTES_TO_WORDS_8(BA, D8, BF, D7, B7, B0, 44, 50),
  10231. BYTES_TO_WORDS_8(56, 32, 41, F5, AB, B3, 04, 0C),
  10232. BYTES_TO_WORDS_4(85, 0A, 05, B4)},
  10233. &double_jacobian_default,
  10234. #if uECC_SUPPORT_COMPRESSED_POINT
  10235. &mod_sqrt_secp224r1,
  10236. #endif
  10237. &x_side_default,
  10238. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10239. &vli_mmod_fast_secp224r1
  10240. #endif
  10241. };
  10242. uECC_Curve uECC_secp224r1(void) {
  10243. return &curve_secp224r1;
  10244. }
  10245. #if uECC_SUPPORT_COMPRESSED_POINT
  10246. /* Routine 3.2.4 RS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10247. static void mod_sqrt_secp224r1_rs(uECC_word_t *d1, uECC_word_t *e1,
  10248. uECC_word_t *f1, const uECC_word_t *d0,
  10249. const uECC_word_t *e0,
  10250. const uECC_word_t *f0) {
  10251. uECC_word_t t[num_words_secp224r1];
  10252. uECC_vli_modSquare_fast(t, d0, &curve_secp224r1); /* t <-- d0 ^ 2 */
  10253. uECC_vli_modMult_fast(e1, d0, e0, &curve_secp224r1); /* e1 <-- d0 * e0 */
  10254. uECC_vli_modAdd(d1, t, f0, curve_secp224r1.p,
  10255. num_words_secp224r1); /* d1 <-- t + f0 */
  10256. uECC_vli_modAdd(e1, e1, e1, curve_secp224r1.p,
  10257. num_words_secp224r1); /* e1 <-- e1 + e1 */
  10258. uECC_vli_modMult_fast(f1, t, f0, &curve_secp224r1); /* f1 <-- t * f0 */
  10259. uECC_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  10260. num_words_secp224r1); /* f1 <-- f1 + f1 */
  10261. uECC_vli_modAdd(f1, f1, f1, curve_secp224r1.p,
  10262. num_words_secp224r1); /* f1 <-- f1 + f1 */
  10263. }
  10264. /* Routine 3.2.5 RSS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10265. static void mod_sqrt_secp224r1_rss(uECC_word_t *d1, uECC_word_t *e1,
  10266. uECC_word_t *f1, const uECC_word_t *d0,
  10267. const uECC_word_t *e0, const uECC_word_t *f0,
  10268. const bitcount_t j) {
  10269. bitcount_t i;
  10270. uECC_vli_set(d1, d0, num_words_secp224r1); /* d1 <-- d0 */
  10271. uECC_vli_set(e1, e0, num_words_secp224r1); /* e1 <-- e0 */
  10272. uECC_vli_set(f1, f0, num_words_secp224r1); /* f1 <-- f0 */
  10273. for (i = 1; i <= j; i++) {
  10274. mod_sqrt_secp224r1_rs(d1, e1, f1, d1, e1, f1); /* RS (d1,e1,f1,d1,e1,f1) */
  10275. }
  10276. }
  10277. /* Routine 3.2.6 RM; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10278. static void mod_sqrt_secp224r1_rm(uECC_word_t *d2, uECC_word_t *e2,
  10279. uECC_word_t *f2, const uECC_word_t *c,
  10280. const uECC_word_t *d0, const uECC_word_t *e0,
  10281. const uECC_word_t *d1,
  10282. const uECC_word_t *e1) {
  10283. uECC_word_t t1[num_words_secp224r1];
  10284. uECC_word_t t2[num_words_secp224r1];
  10285. uECC_vli_modMult_fast(t1, e0, e1, &curve_secp224r1); /* t1 <-- e0 * e1 */
  10286. uECC_vli_modMult_fast(t1, t1, c, &curve_secp224r1); /* t1 <-- t1 * c */
  10287. /* t1 <-- p - t1 */
  10288. uECC_vli_modSub(t1, curve_secp224r1.p, t1, curve_secp224r1.p,
  10289. num_words_secp224r1);
  10290. uECC_vli_modMult_fast(t2, d0, d1, &curve_secp224r1); /* t2 <-- d0 * d1 */
  10291. uECC_vli_modAdd(t2, t2, t1, curve_secp224r1.p,
  10292. num_words_secp224r1); /* t2 <-- t2 + t1 */
  10293. uECC_vli_modMult_fast(t1, d0, e1, &curve_secp224r1); /* t1 <-- d0 * e1 */
  10294. uECC_vli_modMult_fast(e2, d1, e0, &curve_secp224r1); /* e2 <-- d1 * e0 */
  10295. uECC_vli_modAdd(e2, e2, t1, curve_secp224r1.p,
  10296. num_words_secp224r1); /* e2 <-- e2 + t1 */
  10297. uECC_vli_modSquare_fast(f2, e2, &curve_secp224r1); /* f2 <-- e2^2 */
  10298. uECC_vli_modMult_fast(f2, f2, c, &curve_secp224r1); /* f2 <-- f2 * c */
  10299. /* f2 <-- p - f2 */
  10300. uECC_vli_modSub(f2, curve_secp224r1.p, f2, curve_secp224r1.p,
  10301. num_words_secp224r1);
  10302. uECC_vli_set(d2, t2, num_words_secp224r1); /* d2 <-- t2 */
  10303. }
  10304. /* Routine 3.2.7 RP; from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10305. static void mod_sqrt_secp224r1_rp(uECC_word_t *d1, uECC_word_t *e1,
  10306. uECC_word_t *f1, const uECC_word_t *c,
  10307. const uECC_word_t *r) {
  10308. wordcount_t i;
  10309. wordcount_t pow2i = 1;
  10310. uECC_word_t d0[num_words_secp224r1];
  10311. uECC_word_t e0[num_words_secp224r1] = {1}; /* e0 <-- 1 */
  10312. uECC_word_t f0[num_words_secp224r1];
  10313. uECC_vli_set(d0, r, num_words_secp224r1); /* d0 <-- r */
  10314. /* f0 <-- p - c */
  10315. uECC_vli_modSub(f0, curve_secp224r1.p, c, curve_secp224r1.p,
  10316. num_words_secp224r1);
  10317. for (i = 0; i <= 6; i++) {
  10318. mod_sqrt_secp224r1_rss(d1, e1, f1, d0, e0, f0,
  10319. pow2i); /* RSS (d1,e1,f1,d0,e0,f0,2^i) */
  10320. mod_sqrt_secp224r1_rm(d1, e1, f1, c, d1, e1, d0,
  10321. e0); /* RM (d1,e1,f1,c,d1,e1,d0,e0) */
  10322. uECC_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  10323. uECC_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  10324. uECC_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  10325. pow2i *= 2;
  10326. }
  10327. }
  10328. /* Compute a = sqrt(a) (mod curve_p). */
  10329. /* Routine 3.2.8 mp_mod_sqrt_224; from
  10330. * http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10331. static void mod_sqrt_secp224r1(uECC_word_t *a, uECC_Curve curve) {
  10332. (void) curve;
  10333. bitcount_t i;
  10334. uECC_word_t e1[num_words_secp224r1];
  10335. uECC_word_t f1[num_words_secp224r1];
  10336. uECC_word_t d0[num_words_secp224r1];
  10337. uECC_word_t e0[num_words_secp224r1];
  10338. uECC_word_t f0[num_words_secp224r1];
  10339. uECC_word_t d1[num_words_secp224r1];
  10340. /* s = a; using constant instead of random value */
  10341. mod_sqrt_secp224r1_rp(d0, e0, f0, a, a); /* RP (d0, e0, f0, c, s) */
  10342. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  10343. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  10344. for (i = 1; i <= 95; i++) {
  10345. uECC_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */
  10346. uECC_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */
  10347. uECC_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */
  10348. mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0,
  10349. f0); /* RS (d1, e1, f1, d0, e0, f0) */
  10350. if (uECC_vli_isZero(d1, num_words_secp224r1)) { /* if d1 == 0 */
  10351. break;
  10352. }
  10353. }
  10354. uECC_vli_modInv(f1, e0, curve_secp224r1.p,
  10355. num_words_secp224r1); /* f1 <-- 1 / e0 */
  10356. uECC_vli_modMult_fast(a, d0, f1, &curve_secp224r1); /* a <-- d0 / e0 */
  10357. }
  10358. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  10359. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10360. /* Computes result = product % curve_p
  10361. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10362. #if uECC_WORD_SIZE == 1
  10363. static void vli_mmod_fast_secp224r1(uint8_t *result, uint8_t *product) {
  10364. uint8_t tmp[num_words_secp224r1];
  10365. int8_t carry;
  10366. /* t */
  10367. uECC_vli_set(result, product, num_words_secp224r1);
  10368. /* s1 */
  10369. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  10370. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10371. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10372. tmp[12] = product[28];
  10373. tmp[13] = product[29];
  10374. tmp[14] = product[30];
  10375. tmp[15] = product[31];
  10376. tmp[16] = product[32];
  10377. tmp[17] = product[33];
  10378. tmp[18] = product[34];
  10379. tmp[19] = product[35];
  10380. tmp[20] = product[36];
  10381. tmp[21] = product[37];
  10382. tmp[22] = product[38];
  10383. tmp[23] = product[39];
  10384. tmp[24] = product[40];
  10385. tmp[25] = product[41];
  10386. tmp[26] = product[42];
  10387. tmp[27] = product[43];
  10388. carry = uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10389. /* s2 */
  10390. tmp[12] = product[44];
  10391. tmp[13] = product[45];
  10392. tmp[14] = product[46];
  10393. tmp[15] = product[47];
  10394. tmp[16] = product[48];
  10395. tmp[17] = product[49];
  10396. tmp[18] = product[50];
  10397. tmp[19] = product[51];
  10398. tmp[20] = product[52];
  10399. tmp[21] = product[53];
  10400. tmp[22] = product[54];
  10401. tmp[23] = product[55];
  10402. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10403. carry += uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10404. /* d1 */
  10405. tmp[0] = product[28];
  10406. tmp[1] = product[29];
  10407. tmp[2] = product[30];
  10408. tmp[3] = product[31];
  10409. tmp[4] = product[32];
  10410. tmp[5] = product[33];
  10411. tmp[6] = product[34];
  10412. tmp[7] = product[35];
  10413. tmp[8] = product[36];
  10414. tmp[9] = product[37];
  10415. tmp[10] = product[38];
  10416. tmp[11] = product[39];
  10417. tmp[12] = product[40];
  10418. tmp[13] = product[41];
  10419. tmp[14] = product[42];
  10420. tmp[15] = product[43];
  10421. tmp[16] = product[44];
  10422. tmp[17] = product[45];
  10423. tmp[18] = product[46];
  10424. tmp[19] = product[47];
  10425. tmp[20] = product[48];
  10426. tmp[21] = product[49];
  10427. tmp[22] = product[50];
  10428. tmp[23] = product[51];
  10429. tmp[24] = product[52];
  10430. tmp[25] = product[53];
  10431. tmp[26] = product[54];
  10432. tmp[27] = product[55];
  10433. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10434. /* d2 */
  10435. tmp[0] = product[44];
  10436. tmp[1] = product[45];
  10437. tmp[2] = product[46];
  10438. tmp[3] = product[47];
  10439. tmp[4] = product[48];
  10440. tmp[5] = product[49];
  10441. tmp[6] = product[50];
  10442. tmp[7] = product[51];
  10443. tmp[8] = product[52];
  10444. tmp[9] = product[53];
  10445. tmp[10] = product[54];
  10446. tmp[11] = product[55];
  10447. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10448. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10449. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10450. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10451. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10452. if (carry < 0) {
  10453. do {
  10454. carry +=
  10455. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10456. } while (carry < 0);
  10457. } else {
  10458. while (carry || uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10459. num_words_secp224r1) != 1) {
  10460. carry -=
  10461. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10462. }
  10463. }
  10464. }
  10465. #elif uECC_WORD_SIZE == 4
  10466. static void vli_mmod_fast_secp224r1(uint32_t *result, uint32_t *product) {
  10467. uint32_t tmp[num_words_secp224r1];
  10468. int carry;
  10469. /* t */
  10470. uECC_vli_set(result, product, num_words_secp224r1);
  10471. /* s1 */
  10472. tmp[0] = tmp[1] = tmp[2] = 0;
  10473. tmp[3] = product[7];
  10474. tmp[4] = product[8];
  10475. tmp[5] = product[9];
  10476. tmp[6] = product[10];
  10477. carry = uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10478. /* s2 */
  10479. tmp[3] = product[11];
  10480. tmp[4] = product[12];
  10481. tmp[5] = product[13];
  10482. tmp[6] = 0;
  10483. carry += uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10484. /* d1 */
  10485. tmp[0] = product[7];
  10486. tmp[1] = product[8];
  10487. tmp[2] = product[9];
  10488. tmp[3] = product[10];
  10489. tmp[4] = product[11];
  10490. tmp[5] = product[12];
  10491. tmp[6] = product[13];
  10492. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10493. /* d2 */
  10494. tmp[0] = product[11];
  10495. tmp[1] = product[12];
  10496. tmp[2] = product[13];
  10497. tmp[3] = tmp[4] = tmp[5] = tmp[6] = 0;
  10498. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10499. if (carry < 0) {
  10500. do {
  10501. carry +=
  10502. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10503. } while (carry < 0);
  10504. } else {
  10505. while (carry || uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10506. num_words_secp224r1) != 1) {
  10507. carry -=
  10508. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10509. }
  10510. }
  10511. }
  10512. #else
  10513. static void vli_mmod_fast_secp224r1(uint64_t *result, uint64_t *product) {
  10514. uint64_t tmp[num_words_secp224r1];
  10515. int carry = 0;
  10516. /* t */
  10517. uECC_vli_set(result, product, num_words_secp224r1);
  10518. result[num_words_secp224r1 - 1] &= 0xffffffff;
  10519. /* s1 */
  10520. tmp[0] = 0;
  10521. tmp[1] = product[3] & 0xffffffff00000000ull;
  10522. tmp[2] = product[4];
  10523. tmp[3] = product[5] & 0xffffffff;
  10524. uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10525. /* s2 */
  10526. tmp[1] = product[5] & 0xffffffff00000000ull;
  10527. tmp[2] = product[6];
  10528. tmp[3] = 0;
  10529. uECC_vli_add(result, result, tmp, num_words_secp224r1);
  10530. /* d1 */
  10531. tmp[0] = (product[3] >> 32) | (product[4] << 32);
  10532. tmp[1] = (product[4] >> 32) | (product[5] << 32);
  10533. tmp[2] = (product[5] >> 32) | (product[6] << 32);
  10534. tmp[3] = product[6] >> 32;
  10535. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10536. /* d2 */
  10537. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  10538. tmp[1] = product[6] >> 32;
  10539. tmp[2] = tmp[3] = 0;
  10540. carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1);
  10541. if (carry < 0) {
  10542. do {
  10543. carry +=
  10544. uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1);
  10545. } while (carry < 0);
  10546. } else {
  10547. while (uECC_vli_cmp_unsafe(curve_secp224r1.p, result,
  10548. num_words_secp224r1) != 1) {
  10549. uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1);
  10550. }
  10551. }
  10552. }
  10553. #endif /* uECC_WORD_SIZE */
  10554. #endif /* (uECC_OPTIMIZATION_LEVEL > 0) */
  10555. #endif /* uECC_SUPPORTS_secp224r1 */
  10556. #if uECC_SUPPORTS_secp256r1
  10557. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10558. static void vli_mmod_fast_secp256r1(uECC_word_t *result, uECC_word_t *product);
  10559. #endif
  10560. static const struct uECC_Curve_t curve_secp256r1 = {
  10561. num_words_secp256r1,
  10562. num_bytes_secp256r1,
  10563. 256, /* num_n_bits */
  10564. {BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10565. BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00),
  10566. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  10567. BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF)},
  10568. {BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3),
  10569. BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC),
  10570. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  10571. BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF)},
  10572. {BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4),
  10573. BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77),
  10574. BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8),
  10575. BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B),
  10576. BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB),
  10577. BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B),
  10578. BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E),
  10579. BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F)},
  10580. {BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B),
  10581. BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65),
  10582. BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3),
  10583. BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A)},
  10584. &double_jacobian_default,
  10585. #if uECC_SUPPORT_COMPRESSED_POINT
  10586. &mod_sqrt_default,
  10587. #endif
  10588. &x_side_default,
  10589. #if (uECC_OPTIMIZATION_LEVEL > 0)
  10590. &vli_mmod_fast_secp256r1
  10591. #endif
  10592. };
  10593. uECC_Curve uECC_secp256r1(void) {
  10594. return &curve_secp256r1;
  10595. }
  10596. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1)
  10597. /* Computes result = product % curve_p
  10598. from http://www.nsa.gov/ia/_files/nist-routines.pdf */
  10599. #if uECC_WORD_SIZE == 1
  10600. static void vli_mmod_fast_secp256r1(uint8_t *result, uint8_t *product) {
  10601. uint8_t tmp[num_words_secp256r1];
  10602. int8_t carry;
  10603. /* t */
  10604. uECC_vli_set(result, product, num_words_secp256r1);
  10605. /* s1 */
  10606. tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0;
  10607. tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0;
  10608. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10609. tmp[12] = product[44];
  10610. tmp[13] = product[45];
  10611. tmp[14] = product[46];
  10612. tmp[15] = product[47];
  10613. tmp[16] = product[48];
  10614. tmp[17] = product[49];
  10615. tmp[18] = product[50];
  10616. tmp[19] = product[51];
  10617. tmp[20] = product[52];
  10618. tmp[21] = product[53];
  10619. tmp[22] = product[54];
  10620. tmp[23] = product[55];
  10621. tmp[24] = product[56];
  10622. tmp[25] = product[57];
  10623. tmp[26] = product[58];
  10624. tmp[27] = product[59];
  10625. tmp[28] = product[60];
  10626. tmp[29] = product[61];
  10627. tmp[30] = product[62];
  10628. tmp[31] = product[63];
  10629. carry = uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10630. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10631. /* s2 */
  10632. tmp[12] = product[48];
  10633. tmp[13] = product[49];
  10634. tmp[14] = product[50];
  10635. tmp[15] = product[51];
  10636. tmp[16] = product[52];
  10637. tmp[17] = product[53];
  10638. tmp[18] = product[54];
  10639. tmp[19] = product[55];
  10640. tmp[20] = product[56];
  10641. tmp[21] = product[57];
  10642. tmp[22] = product[58];
  10643. tmp[23] = product[59];
  10644. tmp[24] = product[60];
  10645. tmp[25] = product[61];
  10646. tmp[26] = product[62];
  10647. tmp[27] = product[63];
  10648. tmp[28] = tmp[29] = tmp[30] = tmp[31] = 0;
  10649. carry += uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10650. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10651. /* s3 */
  10652. tmp[0] = product[32];
  10653. tmp[1] = product[33];
  10654. tmp[2] = product[34];
  10655. tmp[3] = product[35];
  10656. tmp[4] = product[36];
  10657. tmp[5] = product[37];
  10658. tmp[6] = product[38];
  10659. tmp[7] = product[39];
  10660. tmp[8] = product[40];
  10661. tmp[9] = product[41];
  10662. tmp[10] = product[42];
  10663. tmp[11] = product[43];
  10664. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10665. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10666. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10667. tmp[24] = product[56];
  10668. tmp[25] = product[57];
  10669. tmp[26] = product[58];
  10670. tmp[27] = product[59];
  10671. tmp[28] = product[60];
  10672. tmp[29] = product[61];
  10673. tmp[30] = product[62];
  10674. tmp[31] = product[63];
  10675. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10676. /* s4 */
  10677. tmp[0] = product[36];
  10678. tmp[1] = product[37];
  10679. tmp[2] = product[38];
  10680. tmp[3] = product[39];
  10681. tmp[4] = product[40];
  10682. tmp[5] = product[41];
  10683. tmp[6] = product[42];
  10684. tmp[7] = product[43];
  10685. tmp[8] = product[44];
  10686. tmp[9] = product[45];
  10687. tmp[10] = product[46];
  10688. tmp[11] = product[47];
  10689. tmp[12] = product[52];
  10690. tmp[13] = product[53];
  10691. tmp[14] = product[54];
  10692. tmp[15] = product[55];
  10693. tmp[16] = product[56];
  10694. tmp[17] = product[57];
  10695. tmp[18] = product[58];
  10696. tmp[19] = product[59];
  10697. tmp[20] = product[60];
  10698. tmp[21] = product[61];
  10699. tmp[22] = product[62];
  10700. tmp[23] = product[63];
  10701. tmp[24] = product[52];
  10702. tmp[25] = product[53];
  10703. tmp[26] = product[54];
  10704. tmp[27] = product[55];
  10705. tmp[28] = product[32];
  10706. tmp[29] = product[33];
  10707. tmp[30] = product[34];
  10708. tmp[31] = product[35];
  10709. carry += uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10710. /* d1 */
  10711. tmp[0] = product[44];
  10712. tmp[1] = product[45];
  10713. tmp[2] = product[46];
  10714. tmp[3] = product[47];
  10715. tmp[4] = product[48];
  10716. tmp[5] = product[49];
  10717. tmp[6] = product[50];
  10718. tmp[7] = product[51];
  10719. tmp[8] = product[52];
  10720. tmp[9] = product[53];
  10721. tmp[10] = product[54];
  10722. tmp[11] = product[55];
  10723. tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0;
  10724. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10725. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10726. tmp[24] = product[32];
  10727. tmp[25] = product[33];
  10728. tmp[26] = product[34];
  10729. tmp[27] = product[35];
  10730. tmp[28] = product[40];
  10731. tmp[29] = product[41];
  10732. tmp[30] = product[42];
  10733. tmp[31] = product[43];
  10734. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10735. /* d2 */
  10736. tmp[0] = product[48];
  10737. tmp[1] = product[49];
  10738. tmp[2] = product[50];
  10739. tmp[3] = product[51];
  10740. tmp[4] = product[52];
  10741. tmp[5] = product[53];
  10742. tmp[6] = product[54];
  10743. tmp[7] = product[55];
  10744. tmp[8] = product[56];
  10745. tmp[9] = product[57];
  10746. tmp[10] = product[58];
  10747. tmp[11] = product[59];
  10748. tmp[12] = product[60];
  10749. tmp[13] = product[61];
  10750. tmp[14] = product[62];
  10751. tmp[15] = product[63];
  10752. tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0;
  10753. tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0;
  10754. tmp[24] = product[36];
  10755. tmp[25] = product[37];
  10756. tmp[26] = product[38];
  10757. tmp[27] = product[39];
  10758. tmp[28] = product[44];
  10759. tmp[29] = product[45];
  10760. tmp[30] = product[46];
  10761. tmp[31] = product[47];
  10762. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10763. /* d3 */
  10764. tmp[0] = product[52];
  10765. tmp[1] = product[53];
  10766. tmp[2] = product[54];
  10767. tmp[3] = product[55];
  10768. tmp[4] = product[56];
  10769. tmp[5] = product[57];
  10770. tmp[6] = product[58];
  10771. tmp[7] = product[59];
  10772. tmp[8] = product[60];
  10773. tmp[9] = product[61];
  10774. tmp[10] = product[62];
  10775. tmp[11] = product[63];
  10776. tmp[12] = product[32];
  10777. tmp[13] = product[33];
  10778. tmp[14] = product[34];
  10779. tmp[15] = product[35];
  10780. tmp[16] = product[36];
  10781. tmp[17] = product[37];
  10782. tmp[18] = product[38];
  10783. tmp[19] = product[39];
  10784. tmp[20] = product[40];
  10785. tmp[21] = product[41];
  10786. tmp[22] = product[42];
  10787. tmp[23] = product[43];
  10788. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10789. tmp[28] = product[48];
  10790. tmp[29] = product[49];
  10791. tmp[30] = product[50];
  10792. tmp[31] = product[51];
  10793. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10794. /* d4 */
  10795. tmp[0] = product[56];
  10796. tmp[1] = product[57];
  10797. tmp[2] = product[58];
  10798. tmp[3] = product[59];
  10799. tmp[4] = product[60];
  10800. tmp[5] = product[61];
  10801. tmp[6] = product[62];
  10802. tmp[7] = product[63];
  10803. tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0;
  10804. tmp[12] = product[36];
  10805. tmp[13] = product[37];
  10806. tmp[14] = product[38];
  10807. tmp[15] = product[39];
  10808. tmp[16] = product[40];
  10809. tmp[17] = product[41];
  10810. tmp[18] = product[42];
  10811. tmp[19] = product[43];
  10812. tmp[20] = product[44];
  10813. tmp[21] = product[45];
  10814. tmp[22] = product[46];
  10815. tmp[23] = product[47];
  10816. tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0;
  10817. tmp[28] = product[52];
  10818. tmp[29] = product[53];
  10819. tmp[30] = product[54];
  10820. tmp[31] = product[55];
  10821. carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10822. if (carry < 0) {
  10823. do {
  10824. carry +=
  10825. uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10826. } while (carry < 0);
  10827. } else {
  10828. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10829. num_words_secp256r1) != 1) {
  10830. carry -=
  10831. uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10832. }
  10833. }
  10834. }
  10835. #elif uECC_WORD_SIZE == 4
  10836. static void vli_mmod_fast_secp256r1(uint32_t *result, uint32_t *product) {
  10837. uint32_t tmp[num_words_secp256r1];
  10838. int carry;
  10839. /* t */
  10840. uECC_vli_set(result, product, num_words_secp256r1);
  10841. /* s1 */
  10842. tmp[0] = tmp[1] = tmp[2] = 0;
  10843. tmp[3] = product[11];
  10844. tmp[4] = product[12];
  10845. tmp[5] = product[13];
  10846. tmp[6] = product[14];
  10847. tmp[7] = product[15];
  10848. carry = (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10849. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10850. /* s2 */
  10851. tmp[3] = product[12];
  10852. tmp[4] = product[13];
  10853. tmp[5] = product[14];
  10854. tmp[6] = product[15];
  10855. tmp[7] = 0;
  10856. carry += (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10857. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10858. /* s3 */
  10859. tmp[0] = product[8];
  10860. tmp[1] = product[9];
  10861. tmp[2] = product[10];
  10862. tmp[3] = tmp[4] = tmp[5] = 0;
  10863. tmp[6] = product[14];
  10864. tmp[7] = product[15];
  10865. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10866. /* s4 */
  10867. tmp[0] = product[9];
  10868. tmp[1] = product[10];
  10869. tmp[2] = product[11];
  10870. tmp[3] = product[13];
  10871. tmp[4] = product[14];
  10872. tmp[5] = product[15];
  10873. tmp[6] = product[13];
  10874. tmp[7] = product[8];
  10875. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10876. /* d1 */
  10877. tmp[0] = product[11];
  10878. tmp[1] = product[12];
  10879. tmp[2] = product[13];
  10880. tmp[3] = tmp[4] = tmp[5] = 0;
  10881. tmp[6] = product[8];
  10882. tmp[7] = product[10];
  10883. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10884. /* d2 */
  10885. tmp[0] = product[12];
  10886. tmp[1] = product[13];
  10887. tmp[2] = product[14];
  10888. tmp[3] = product[15];
  10889. tmp[4] = tmp[5] = 0;
  10890. tmp[6] = product[9];
  10891. tmp[7] = product[11];
  10892. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10893. /* d3 */
  10894. tmp[0] = product[13];
  10895. tmp[1] = product[14];
  10896. tmp[2] = product[15];
  10897. tmp[3] = product[8];
  10898. tmp[4] = product[9];
  10899. tmp[5] = product[10];
  10900. tmp[6] = 0;
  10901. tmp[7] = product[12];
  10902. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10903. /* d4 */
  10904. tmp[0] = product[14];
  10905. tmp[1] = product[15];
  10906. tmp[2] = 0;
  10907. tmp[3] = product[9];
  10908. tmp[4] = product[10];
  10909. tmp[5] = product[11];
  10910. tmp[6] = 0;
  10911. tmp[7] = product[13];
  10912. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10913. if (carry < 0) {
  10914. do {
  10915. carry +=
  10916. (int) uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10917. } while (carry < 0);
  10918. } else {
  10919. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10920. num_words_secp256r1) != 1) {
  10921. carry -=
  10922. (int) uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10923. }
  10924. }
  10925. }
  10926. #else
  10927. static void vli_mmod_fast_secp256r1(uint64_t *result, uint64_t *product) {
  10928. uint64_t tmp[num_words_secp256r1];
  10929. int carry;
  10930. /* t */
  10931. uECC_vli_set(result, product, num_words_secp256r1);
  10932. /* s1 */
  10933. tmp[0] = 0;
  10934. tmp[1] = product[5] & 0xffffffff00000000U;
  10935. tmp[2] = product[6];
  10936. tmp[3] = product[7];
  10937. carry = (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10938. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10939. /* s2 */
  10940. tmp[1] = product[6] << 32;
  10941. tmp[2] = (product[6] >> 32) | (product[7] << 32);
  10942. tmp[3] = product[7] >> 32;
  10943. carry += (int) uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1);
  10944. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10945. /* s3 */
  10946. tmp[0] = product[4];
  10947. tmp[1] = product[5] & 0xffffffff;
  10948. tmp[2] = 0;
  10949. tmp[3] = product[7];
  10950. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10951. /* s4 */
  10952. tmp[0] = (product[4] >> 32) | (product[5] << 32);
  10953. tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000U);
  10954. tmp[2] = product[7];
  10955. tmp[3] = (product[6] >> 32) | (product[4] << 32);
  10956. carry += (int) uECC_vli_add(result, result, tmp, num_words_secp256r1);
  10957. /* d1 */
  10958. tmp[0] = (product[5] >> 32) | (product[6] << 32);
  10959. tmp[1] = (product[6] >> 32);
  10960. tmp[2] = 0;
  10961. tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32);
  10962. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10963. /* d2 */
  10964. tmp[0] = product[6];
  10965. tmp[1] = product[7];
  10966. tmp[2] = 0;
  10967. tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000);
  10968. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10969. /* d3 */
  10970. tmp[0] = (product[6] >> 32) | (product[7] << 32);
  10971. tmp[1] = (product[7] >> 32) | (product[4] << 32);
  10972. tmp[2] = (product[4] >> 32) | (product[5] << 32);
  10973. tmp[3] = (product[6] << 32);
  10974. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10975. /* d4 */
  10976. tmp[0] = product[7];
  10977. tmp[1] = product[4] & 0xffffffff00000000U;
  10978. tmp[2] = product[5];
  10979. tmp[3] = product[6] & 0xffffffff00000000U;
  10980. carry -= (int) uECC_vli_sub(result, result, tmp, num_words_secp256r1);
  10981. if (carry < 0) {
  10982. do {
  10983. carry +=
  10984. (int) uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1);
  10985. } while (carry < 0);
  10986. } else {
  10987. while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result,
  10988. num_words_secp256r1) != 1) {
  10989. carry -=
  10990. (int) uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1);
  10991. }
  10992. }
  10993. }
  10994. #endif /* uECC_WORD_SIZE */
  10995. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) */
  10996. #endif /* uECC_SUPPORTS_secp256r1 */
  10997. #if uECC_SUPPORTS_secp256k1
  10998. static void double_jacobian_secp256k1(uECC_word_t *X1, uECC_word_t *Y1,
  10999. uECC_word_t *Z1, uECC_Curve curve);
  11000. static void x_side_secp256k1(uECC_word_t *result, const uECC_word_t *x,
  11001. uECC_Curve curve);
  11002. #if (uECC_OPTIMIZATION_LEVEL > 0)
  11003. static void vli_mmod_fast_secp256k1(uECC_word_t *result, uECC_word_t *product);
  11004. #endif
  11005. static const struct uECC_Curve_t curve_secp256k1 = {
  11006. num_words_secp256k1,
  11007. num_bytes_secp256k1,
  11008. 256, /* num_n_bits */
  11009. {BYTES_TO_WORDS_8(2F, FC, FF, FF, FE, FF, FF, FF),
  11010. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11011. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF),
  11012. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11013. {BYTES_TO_WORDS_8(41, 41, 36, D0, 8C, 5E, D2, BF),
  11014. BYTES_TO_WORDS_8(3B, A0, 48, AF, E6, DC, AE, BA),
  11015. BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF),
  11016. BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF)},
  11017. {BYTES_TO_WORDS_8(98, 17, F8, 16, 5B, 81, F2, 59),
  11018. BYTES_TO_WORDS_8(D9, 28, CE, 2D, DB, FC, 9B, 02),
  11019. BYTES_TO_WORDS_8(07, 0B, 87, CE, 95, 62, A0, 55),
  11020. BYTES_TO_WORDS_8(AC, BB, DC, F9, 7E, 66, BE, 79),
  11021. BYTES_TO_WORDS_8(B8, D4, 10, FB, 8F, D0, 47, 9C),
  11022. BYTES_TO_WORDS_8(19, 54, 85, A6, 48, B4, 17, FD),
  11023. BYTES_TO_WORDS_8(A8, 08, 11, 0E, FC, FB, A4, 5D),
  11024. BYTES_TO_WORDS_8(65, C4, A3, 26, 77, DA, 3A, 48)},
  11025. {BYTES_TO_WORDS_8(07, 00, 00, 00, 00, 00, 00, 00),
  11026. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  11027. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00),
  11028. BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00)},
  11029. &double_jacobian_secp256k1,
  11030. #if uECC_SUPPORT_COMPRESSED_POINT
  11031. &mod_sqrt_default,
  11032. #endif
  11033. &x_side_secp256k1,
  11034. #if (uECC_OPTIMIZATION_LEVEL > 0)
  11035. &vli_mmod_fast_secp256k1
  11036. #endif
  11037. };
  11038. uECC_Curve uECC_secp256k1(void) {
  11039. return &curve_secp256k1;
  11040. }
  11041. /* Double in place */
  11042. static void double_jacobian_secp256k1(uECC_word_t *X1, uECC_word_t *Y1,
  11043. uECC_word_t *Z1, uECC_Curve curve) {
  11044. /* t1 = X, t2 = Y, t3 = Z */
  11045. uECC_word_t t4[num_words_secp256k1];
  11046. uECC_word_t t5[num_words_secp256k1];
  11047. if (uECC_vli_isZero(Z1, num_words_secp256k1)) {
  11048. return;
  11049. }
  11050. uECC_vli_modSquare_fast(t5, Y1, curve); /* t5 = y1^2 */
  11051. uECC_vli_modMult_fast(t4, X1, t5, curve); /* t4 = x1*y1^2 = A */
  11052. uECC_vli_modSquare_fast(X1, X1, curve); /* t1 = x1^2 */
  11053. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = y1^4 */
  11054. uECC_vli_modMult_fast(Z1, Y1, Z1, curve); /* t3 = y1*z1 = z3 */
  11055. uECC_vli_modAdd(Y1, X1, X1, curve->p, num_words_secp256k1); /* t2 = 2*x1^2 */
  11056. uECC_vli_modAdd(Y1, Y1, X1, curve->p, num_words_secp256k1); /* t2 = 3*x1^2 */
  11057. if (uECC_vli_testBit(Y1, 0)) {
  11058. uECC_word_t carry = uECC_vli_add(Y1, Y1, curve->p, num_words_secp256k1);
  11059. uECC_vli_rshift1(Y1, num_words_secp256k1);
  11060. Y1[num_words_secp256k1 - 1] |= carry << (uECC_WORD_BITS - 1);
  11061. } else {
  11062. uECC_vli_rshift1(Y1, num_words_secp256k1);
  11063. }
  11064. /* t2 = 3/2*(x1^2) = B */
  11065. uECC_vli_modSquare_fast(X1, Y1, curve); /* t1 = B^2 */
  11066. uECC_vli_modSub(X1, X1, t4, curve->p, num_words_secp256k1); /* t1 = B^2 - A */
  11067. uECC_vli_modSub(X1, X1, t4, curve->p,
  11068. num_words_secp256k1); /* t1 = B^2 - 2A = x3 */
  11069. uECC_vli_modSub(t4, t4, X1, curve->p, num_words_secp256k1); /* t4 = A - x3 */
  11070. uECC_vli_modMult_fast(Y1, Y1, t4, curve); /* t2 = B * (A - x3) */
  11071. uECC_vli_modSub(Y1, Y1, t5, curve->p,
  11072. num_words_secp256k1); /* t2 = B * (A - x3) - y1^4 = y3 */
  11073. }
  11074. /* Computes result = x^3 + b. result must not overlap x. */
  11075. static void x_side_secp256k1(uECC_word_t *result, const uECC_word_t *x,
  11076. uECC_Curve curve) {
  11077. uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */
  11078. uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 */
  11079. uECC_vli_modAdd(result, result, curve->b, curve->p,
  11080. num_words_secp256k1); /* r = x^3 + b */
  11081. }
  11082. #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256k1)
  11083. static void omega_mult_secp256k1(uECC_word_t *result, const uECC_word_t *right);
  11084. static void vli_mmod_fast_secp256k1(uECC_word_t *result, uECC_word_t *product) {
  11085. uECC_word_t tmp[2 * num_words_secp256k1];
  11086. uECC_word_t carry;
  11087. uECC_vli_clear(tmp, num_words_secp256k1);
  11088. uECC_vli_clear(tmp + num_words_secp256k1, num_words_secp256k1);
  11089. omega_mult_secp256k1(tmp,
  11090. product + num_words_secp256k1); /* (Rq, q) = q * c */
  11091. carry = uECC_vli_add(result, product, tmp,
  11092. num_words_secp256k1); /* (C, r) = r + q */
  11093. uECC_vli_clear(product, num_words_secp256k1);
  11094. omega_mult_secp256k1(product, tmp + num_words_secp256k1); /* Rq*c */
  11095. carry += uECC_vli_add(result, result, product,
  11096. num_words_secp256k1); /* (C1, r) = r + Rq*c */
  11097. while (carry > 0) {
  11098. --carry;
  11099. uECC_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  11100. }
  11101. if (uECC_vli_cmp_unsafe(result, curve_secp256k1.p, num_words_secp256k1) > 0) {
  11102. uECC_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1);
  11103. }
  11104. }
  11105. #if uECC_WORD_SIZE == 1
  11106. static void omega_mult_secp256k1(uint8_t *result, const uint8_t *right) {
  11107. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11108. uECC_word_t r0 = 0;
  11109. uECC_word_t r1 = 0;
  11110. uECC_word_t r2 = 0;
  11111. wordcount_t k;
  11112. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11113. muladd(0xD1, right[0], &r0, &r1, &r2);
  11114. result[0] = r0;
  11115. r0 = r1;
  11116. r1 = r2;
  11117. /* r2 is still 0 */
  11118. for (k = 1; k < num_words_secp256k1; ++k) {
  11119. muladd(0x03, right[k - 1], &r0, &r1, &r2);
  11120. muladd(0xD1, right[k], &r0, &r1, &r2);
  11121. result[k] = r0;
  11122. r0 = r1;
  11123. r1 = r2;
  11124. r2 = 0;
  11125. }
  11126. muladd(0x03, right[num_words_secp256k1 - 1], &r0, &r1, &r2);
  11127. result[num_words_secp256k1] = r0;
  11128. result[num_words_secp256k1 + 1] = r1;
  11129. /* add the 2^32 multiple */
  11130. result[4 + num_words_secp256k1] =
  11131. uECC_vli_add(result + 4, result + 4, right, num_words_secp256k1);
  11132. }
  11133. #elif uECC_WORD_SIZE == 4
  11134. static void omega_mult_secp256k1(uint32_t *result, const uint32_t *right) {
  11135. /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11136. uint32_t carry = 0;
  11137. wordcount_t k;
  11138. for (k = 0; k < num_words_secp256k1; ++k) {
  11139. uint64_t p = (uint64_t) 0x3D1 * right[k] + carry;
  11140. result[k] = (uint32_t) p;
  11141. carry = p >> 32;
  11142. }
  11143. result[num_words_secp256k1] = carry;
  11144. /* add the 2^32 multiple */
  11145. result[1 + num_words_secp256k1] =
  11146. uECC_vli_add(result + 1, result + 1, right, num_words_secp256k1);
  11147. }
  11148. #else
  11149. static void omega_mult_secp256k1(uint64_t *result, const uint64_t *right) {
  11150. uECC_word_t r0 = 0;
  11151. uECC_word_t r1 = 0;
  11152. uECC_word_t r2 = 0;
  11153. wordcount_t k;
  11154. /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
  11155. for (k = 0; k < num_words_secp256k1; ++k) {
  11156. muladd(0x1000003D1ull, right[k], &r0, &r1, &r2);
  11157. result[k] = r0;
  11158. r0 = r1;
  11159. r1 = r2;
  11160. r2 = 0;
  11161. }
  11162. result[num_words_secp256k1] = r0;
  11163. }
  11164. #endif /* uECC_WORD_SIZE */
  11165. #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && && !asm_mmod_fast_secp256k1) */
  11166. #endif /* uECC_SUPPORTS_secp256k1 */
  11167. #endif /* _UECC_CURVE_SPECIFIC_H_ */
  11168. /* Returns 1 if 'point' is the point at infinity, 0 otherwise. */
  11169. #define EccPoint_isZero(point, curve) \
  11170. uECC_vli_isZero((point), (wordcount_t) ((curve)->num_words * 2))
  11171. /* Point multiplication algorithm using Montgomery's ladder with co-Z
  11172. coordinates. From http://eprint.iacr.org/2011/338.pdf
  11173. */
  11174. /* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
  11175. static void apply_z(uECC_word_t *X1, uECC_word_t *Y1,
  11176. const uECC_word_t *const Z, uECC_Curve curve) {
  11177. uECC_word_t t1[uECC_MAX_WORDS];
  11178. uECC_vli_modSquare_fast(t1, Z, curve); /* z^2 */
  11179. uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */
  11180. uECC_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */
  11181. uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */
  11182. }
  11183. /* P = (x1, y1) => 2P, (x2, y2) => P' */
  11184. static void XYcZ_initial_double(uECC_word_t *X1, uECC_word_t *Y1,
  11185. uECC_word_t *X2, uECC_word_t *Y2,
  11186. const uECC_word_t *const initial_Z,
  11187. uECC_Curve curve) {
  11188. uECC_word_t z[uECC_MAX_WORDS];
  11189. wordcount_t num_words = curve->num_words;
  11190. if (initial_Z) {
  11191. uECC_vli_set(z, initial_Z, num_words);
  11192. } else {
  11193. uECC_vli_clear(z, num_words);
  11194. z[0] = 1;
  11195. }
  11196. uECC_vli_set(X2, X1, num_words);
  11197. uECC_vli_set(Y2, Y1, num_words);
  11198. apply_z(X1, Y1, z, curve);
  11199. curve->double_jacobian(X1, Y1, z, curve);
  11200. apply_z(X2, Y2, z, curve);
  11201. }
  11202. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  11203. Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
  11204. or P => P', Q => P + Q
  11205. */
  11206. static void XYcZ_add(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2,
  11207. uECC_word_t *Y2, uECC_Curve curve) {
  11208. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  11209. uECC_word_t t5[uECC_MAX_WORDS] = {0};
  11210. wordcount_t num_words = curve->num_words;
  11211. uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  11212. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  11213. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  11214. uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  11215. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  11216. uECC_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */
  11217. uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */
  11218. uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */
  11219. uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */
  11220. uECC_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */
  11221. uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */
  11222. uECC_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */
  11223. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */
  11224. uECC_vli_set(X2, t5, num_words);
  11225. }
  11226. /* Input P = (x1, y1, Z), Q = (x2, y2, Z)
  11227. Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
  11228. or P => P - Q, Q => P + Q
  11229. */
  11230. static void XYcZ_addC(uECC_word_t *X1, uECC_word_t *Y1, uECC_word_t *X2,
  11231. uECC_word_t *Y2, uECC_Curve curve) {
  11232. /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
  11233. uECC_word_t t5[uECC_MAX_WORDS] = {0};
  11234. uECC_word_t t6[uECC_MAX_WORDS];
  11235. uECC_word_t t7[uECC_MAX_WORDS];
  11236. wordcount_t num_words = curve->num_words;
  11237. uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */
  11238. uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */
  11239. uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */
  11240. uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */
  11241. uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */
  11242. uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */
  11243. uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */
  11244. uECC_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */
  11245. uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */
  11246. uECC_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */
  11247. uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */
  11248. uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */
  11249. uECC_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */
  11250. uECC_vli_modSub(Y2, Y2, Y1, curve->p,
  11251. num_words); /* t4 = (y2 - y1)*(B - x3) - E = y3 */
  11252. uECC_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */
  11253. uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */
  11254. uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */
  11255. uECC_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */
  11256. uECC_vli_modSub(Y1, t6, Y1, curve->p,
  11257. num_words); /* t2 = (y2+y1)*(x3' - B) - E = y3' */
  11258. uECC_vli_set(X1, t7, num_words);
  11259. }
  11260. /* result may overlap point. */
  11261. static void EccPoint_mult(uECC_word_t *result, const uECC_word_t *point,
  11262. const uECC_word_t *scalar,
  11263. const uECC_word_t *initial_Z, bitcount_t num_bits,
  11264. uECC_Curve curve) {
  11265. /* R0 and R1 */
  11266. uECC_word_t Rx[2][uECC_MAX_WORDS];
  11267. uECC_word_t Ry[2][uECC_MAX_WORDS];
  11268. uECC_word_t z[uECC_MAX_WORDS];
  11269. bitcount_t i;
  11270. uECC_word_t nb;
  11271. wordcount_t num_words = curve->num_words;
  11272. uECC_vli_set(Rx[1], point, num_words);
  11273. uECC_vli_set(Ry[1], point + num_words, num_words);
  11274. XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve);
  11275. for (i = num_bits - 2; i > 0; --i) {
  11276. nb = !uECC_vli_testBit(scalar, i);
  11277. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  11278. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  11279. }
  11280. nb = !uECC_vli_testBit(scalar, 0);
  11281. XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve);
  11282. /* Find final 1/Z value. */
  11283. uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */
  11284. uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */
  11285. uECC_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */
  11286. uECC_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0)) */
  11287. /* yP / (xP * Yb * (X1 - X0)) */
  11288. uECC_vli_modMult_fast(z, z, point + num_words, curve);
  11289. uECC_vli_modMult_fast(z, z, Rx[1 - nb],
  11290. curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */
  11291. /* End 1/Z calculation */
  11292. XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve);
  11293. apply_z(Rx[0], Ry[0], z, curve);
  11294. uECC_vli_set(result, Rx[0], num_words);
  11295. uECC_vli_set(result + num_words, Ry[0], num_words);
  11296. }
  11297. static uECC_word_t regularize_k(const uECC_word_t *const k, uECC_word_t *k0,
  11298. uECC_word_t *k1, uECC_Curve curve) {
  11299. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11300. bitcount_t num_n_bits = curve->num_n_bits;
  11301. uECC_word_t carry =
  11302. uECC_vli_add(k0, k, curve->n, num_n_words) ||
  11303. (num_n_bits < ((bitcount_t) num_n_words * uECC_WORD_SIZE * 8) &&
  11304. uECC_vli_testBit(k0, num_n_bits));
  11305. uECC_vli_add(k1, k0, curve->n, num_n_words);
  11306. return carry;
  11307. }
  11308. /* Generates a random integer in the range 0 < random < top.
  11309. Both random and top have num_words words. */
  11310. uECC_VLI_API int uECC_generate_random_int(uECC_word_t *random,
  11311. const uECC_word_t *top,
  11312. wordcount_t num_words) {
  11313. uECC_word_t mask = (uECC_word_t) -1;
  11314. uECC_word_t tries;
  11315. bitcount_t num_bits = uECC_vli_numBits(top, num_words);
  11316. if (!g_rng_function) {
  11317. return 0;
  11318. }
  11319. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11320. if (!g_rng_function((uint8_t *) random,
  11321. (unsigned int) (num_words * uECC_WORD_SIZE))) {
  11322. return 0;
  11323. }
  11324. random[num_words - 1] &=
  11325. mask >> ((bitcount_t) (num_words * uECC_WORD_SIZE * 8 - num_bits));
  11326. if (!uECC_vli_isZero(random, num_words) &&
  11327. uECC_vli_cmp(top, random, num_words) == 1) {
  11328. return 1;
  11329. }
  11330. }
  11331. return 0;
  11332. }
  11333. static uECC_word_t EccPoint_compute_public_key(uECC_word_t *result,
  11334. uECC_word_t *private_key,
  11335. uECC_Curve curve) {
  11336. uECC_word_t tmp1[uECC_MAX_WORDS];
  11337. uECC_word_t tmp2[uECC_MAX_WORDS];
  11338. uECC_word_t *p2[2] = {tmp1, tmp2};
  11339. uECC_word_t *initial_Z = 0;
  11340. uECC_word_t carry;
  11341. /* Regularize the bitcount for the private key so that attackers cannot use a
  11342. side channel attack to learn the number of leading zeros. */
  11343. carry = regularize_k(private_key, tmp1, tmp2, curve);
  11344. /* If an RNG function was specified, try to get a random initial Z value to
  11345. improve protection against side-channel attacks. */
  11346. if (g_rng_function) {
  11347. if (!uECC_generate_random_int(p2[carry], curve->p, curve->num_words)) {
  11348. return 0;
  11349. }
  11350. initial_Z = p2[carry];
  11351. }
  11352. EccPoint_mult(result, curve->G, p2[!carry], initial_Z,
  11353. (bitcount_t) (curve->num_n_bits + 1), curve);
  11354. if (EccPoint_isZero(result, curve)) {
  11355. return 0;
  11356. }
  11357. return 1;
  11358. }
  11359. #if uECC_WORD_SIZE == 1
  11360. uECC_VLI_API void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  11361. const uint8_t *native) {
  11362. wordcount_t i;
  11363. for (i = 0; i < num_bytes; ++i) {
  11364. bytes[i] = native[(num_bytes - 1) - i];
  11365. }
  11366. }
  11367. uECC_VLI_API void uECC_vli_bytesToNative(uint8_t *native, const uint8_t *bytes,
  11368. int num_bytes) {
  11369. uECC_vli_nativeToBytes(native, num_bytes, bytes);
  11370. }
  11371. #else
  11372. uECC_VLI_API void uECC_vli_nativeToBytes(uint8_t *bytes, int num_bytes,
  11373. const uECC_word_t *native) {
  11374. int i;
  11375. for (i = 0; i < num_bytes; ++i) {
  11376. unsigned b = (unsigned) (num_bytes - 1 - i);
  11377. bytes[i] =
  11378. (uint8_t) (native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE)));
  11379. }
  11380. }
  11381. uECC_VLI_API void uECC_vli_bytesToNative(uECC_word_t *native,
  11382. const uint8_t *bytes, int num_bytes) {
  11383. int i;
  11384. uECC_vli_clear(native, (wordcount_t) ((num_bytes + (uECC_WORD_SIZE - 1)) /
  11385. uECC_WORD_SIZE));
  11386. for (i = 0; i < num_bytes; ++i) {
  11387. unsigned b = (unsigned) (num_bytes - 1 - i);
  11388. native[b / uECC_WORD_SIZE] |= (uECC_word_t) bytes[i]
  11389. << (8 * (b % uECC_WORD_SIZE));
  11390. }
  11391. }
  11392. #endif /* uECC_WORD_SIZE */
  11393. int uECC_make_key(uint8_t *public_key, uint8_t *private_key, uECC_Curve curve) {
  11394. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11395. uECC_word_t *_private = (uECC_word_t *) private_key;
  11396. uECC_word_t *_public = (uECC_word_t *) public_key;
  11397. #else
  11398. uECC_word_t _private[uECC_MAX_WORDS];
  11399. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11400. #endif
  11401. uECC_word_t tries;
  11402. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11403. if (!uECC_generate_random_int(_private, curve->n,
  11404. BITS_TO_WORDS(curve->num_n_bits))) {
  11405. return 0;
  11406. }
  11407. if (EccPoint_compute_public_key(_public, _private, curve)) {
  11408. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11409. uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits),
  11410. _private);
  11411. uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  11412. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  11413. _public + curve->num_words);
  11414. #endif
  11415. return 1;
  11416. }
  11417. }
  11418. return 0;
  11419. }
  11420. int uECC_shared_secret(const uint8_t *public_key, const uint8_t *private_key,
  11421. uint8_t *secret, uECC_Curve curve) {
  11422. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11423. uECC_word_t _private[uECC_MAX_WORDS];
  11424. uECC_word_t tmp[uECC_MAX_WORDS];
  11425. uECC_word_t *p2[2] = {_private, tmp};
  11426. uECC_word_t *initial_Z = 0;
  11427. uECC_word_t carry;
  11428. wordcount_t num_words = curve->num_words;
  11429. wordcount_t num_bytes = curve->num_bytes;
  11430. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11431. bcopy((uint8_t *) _private, private_key, num_bytes);
  11432. bcopy((uint8_t *) _public, public_key, num_bytes * 2);
  11433. #else
  11434. uECC_vli_bytesToNative(_private, private_key,
  11435. BITS_TO_BYTES(curve->num_n_bits));
  11436. uECC_vli_bytesToNative(_public, public_key, num_bytes);
  11437. uECC_vli_bytesToNative(_public + num_words, public_key + num_bytes,
  11438. num_bytes);
  11439. #endif
  11440. /* Regularize the bitcount for the private key so that attackers cannot use a
  11441. side channel attack to learn the number of leading zeros. */
  11442. carry = regularize_k(_private, _private, tmp, curve);
  11443. /* If an RNG function was specified, try to get a random initial Z value to
  11444. improve protection against side-channel attacks. */
  11445. if (g_rng_function) {
  11446. if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) {
  11447. return 0;
  11448. }
  11449. initial_Z = p2[carry];
  11450. }
  11451. EccPoint_mult(_public, _public, p2[!carry], initial_Z,
  11452. (bitcount_t) (curve->num_n_bits + 1), curve);
  11453. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11454. bcopy((uint8_t *) secret, (uint8_t *) _public, num_bytes);
  11455. #else
  11456. uECC_vli_nativeToBytes(secret, num_bytes, _public);
  11457. #endif
  11458. return !EccPoint_isZero(_public, curve);
  11459. }
  11460. #if uECC_SUPPORT_COMPRESSED_POINT
  11461. void uECC_compress(const uint8_t *public_key, uint8_t *compressed,
  11462. uECC_Curve curve) {
  11463. wordcount_t i;
  11464. for (i = 0; i < curve->num_bytes; ++i) {
  11465. compressed[i + 1] = public_key[i];
  11466. }
  11467. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11468. compressed[0] = 2 + (public_key[curve->num_bytes] & 0x01);
  11469. #else
  11470. compressed[0] = 2 + (public_key[curve->num_bytes * 2 - 1] & 0x01);
  11471. #endif
  11472. }
  11473. void uECC_decompress(const uint8_t *compressed, uint8_t *public_key,
  11474. uECC_Curve curve) {
  11475. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11476. uECC_word_t *point = (uECC_word_t *) public_key;
  11477. #else
  11478. uECC_word_t point[uECC_MAX_WORDS * 2];
  11479. #endif
  11480. uECC_word_t *y = point + curve->num_words;
  11481. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11482. bcopy(public_key, compressed + 1, curve->num_bytes);
  11483. #else
  11484. uECC_vli_bytesToNative(point, compressed + 1, curve->num_bytes);
  11485. #endif
  11486. curve->x_side(y, point, curve);
  11487. curve->mod_sqrt(y, curve);
  11488. if ((uint8_t) (y[0] & 0x01) != (compressed[0] & 0x01)) {
  11489. uECC_vli_sub(y, curve->p, y, curve->num_words);
  11490. }
  11491. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11492. uECC_vli_nativeToBytes(public_key, curve->num_bytes, point);
  11493. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, y);
  11494. #endif
  11495. }
  11496. #endif /* uECC_SUPPORT_COMPRESSED_POINT */
  11497. uECC_VLI_API int uECC_valid_point(const uECC_word_t *point, uECC_Curve curve) {
  11498. uECC_word_t tmp1[uECC_MAX_WORDS];
  11499. uECC_word_t tmp2[uECC_MAX_WORDS];
  11500. wordcount_t num_words = curve->num_words;
  11501. /* The point at infinity is invalid. */
  11502. if (EccPoint_isZero(point, curve)) {
  11503. return 0;
  11504. }
  11505. /* x and y must be smaller than p. */
  11506. if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 ||
  11507. uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) {
  11508. return 0;
  11509. }
  11510. uECC_vli_modSquare_fast(tmp1, point + num_words, curve);
  11511. curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */
  11512. /* Make sure that y^2 == x^3 + ax + b */
  11513. return (int) (uECC_vli_equal(tmp1, tmp2, num_words));
  11514. }
  11515. int uECC_valid_public_key(const uint8_t *public_key, uECC_Curve curve) {
  11516. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11517. uECC_word_t *_public = (uECC_word_t *) public_key;
  11518. #else
  11519. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11520. #endif
  11521. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11522. uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
  11523. uECC_vli_bytesToNative(_public + curve->num_words,
  11524. public_key + curve->num_bytes, curve->num_bytes);
  11525. #endif
  11526. return uECC_valid_point(_public, curve);
  11527. }
  11528. int uECC_compute_public_key(const uint8_t *private_key, uint8_t *public_key,
  11529. uECC_Curve curve) {
  11530. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11531. uECC_word_t *_private = (uECC_word_t *) private_key;
  11532. uECC_word_t *_public = (uECC_word_t *) public_key;
  11533. #else
  11534. uECC_word_t _private[uECC_MAX_WORDS];
  11535. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11536. #endif
  11537. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11538. uECC_vli_bytesToNative(_private, private_key,
  11539. BITS_TO_BYTES(curve->num_n_bits));
  11540. #endif
  11541. /* Make sure the private key is in the range [1, n-1]. */
  11542. if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) {
  11543. return 0;
  11544. }
  11545. if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) {
  11546. return 0;
  11547. }
  11548. /* Compute public key. */
  11549. if (!EccPoint_compute_public_key(_public, _private, curve)) {
  11550. return 0;
  11551. }
  11552. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11553. uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public);
  11554. uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes,
  11555. _public + curve->num_words);
  11556. #endif
  11557. return 1;
  11558. }
  11559. /* -------- ECDSA code -------- */
  11560. static void bits2int(uECC_word_t *native, const uint8_t *bits,
  11561. unsigned bits_size, uECC_Curve curve) {
  11562. unsigned num_n_bytes = (unsigned) BITS_TO_BYTES(curve->num_n_bits);
  11563. unsigned num_n_words = (unsigned) BITS_TO_WORDS(curve->num_n_bits);
  11564. int shift;
  11565. uECC_word_t carry;
  11566. uECC_word_t *ptr;
  11567. if (bits_size > num_n_bytes) {
  11568. bits_size = num_n_bytes;
  11569. }
  11570. uECC_vli_clear(native, (wordcount_t) num_n_words);
  11571. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11572. bcopy((uint8_t *) native, bits, bits_size);
  11573. #else
  11574. uECC_vli_bytesToNative(native, bits, (int) bits_size);
  11575. #endif
  11576. if (bits_size * 8 <= (unsigned) curve->num_n_bits) {
  11577. return;
  11578. }
  11579. shift = (int) bits_size * 8 - curve->num_n_bits;
  11580. carry = 0;
  11581. ptr = native + num_n_words;
  11582. while (ptr-- > native) {
  11583. uECC_word_t temp = *ptr;
  11584. *ptr = (temp >> shift) | carry;
  11585. carry = temp << (uECC_WORD_BITS - shift);
  11586. }
  11587. /* Reduce mod curve_n */
  11588. if (uECC_vli_cmp_unsafe(curve->n, native, (wordcount_t) num_n_words) != 1) {
  11589. uECC_vli_sub(native, native, curve->n, (wordcount_t) num_n_words);
  11590. }
  11591. }
  11592. static int uECC_sign_with_k_internal(const uint8_t *private_key,
  11593. const uint8_t *message_hash,
  11594. unsigned hash_size, uECC_word_t *k,
  11595. uint8_t *signature, uECC_Curve curve) {
  11596. uECC_word_t tmp[uECC_MAX_WORDS];
  11597. uECC_word_t s[uECC_MAX_WORDS];
  11598. uECC_word_t *k2[2] = {tmp, s};
  11599. uECC_word_t *initial_Z = 0;
  11600. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11601. uECC_word_t *p = (uECC_word_t *) signature;
  11602. #else
  11603. uECC_word_t p[uECC_MAX_WORDS * 2];
  11604. #endif
  11605. uECC_word_t carry;
  11606. wordcount_t num_words = curve->num_words;
  11607. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11608. bitcount_t num_n_bits = curve->num_n_bits;
  11609. /* Make sure 0 < k < curve_n */
  11610. if (uECC_vli_isZero(k, num_words) ||
  11611. uECC_vli_cmp(curve->n, k, num_n_words) != 1) {
  11612. return 0;
  11613. }
  11614. carry = regularize_k(k, tmp, s, curve);
  11615. /* If an RNG function was specified, try to get a random initial Z value to
  11616. improve protection against side-channel attacks. */
  11617. if (g_rng_function) {
  11618. if (!uECC_generate_random_int(k2[carry], curve->p, num_words)) {
  11619. return 0;
  11620. }
  11621. initial_Z = k2[carry];
  11622. }
  11623. EccPoint_mult(p, curve->G, k2[!carry], initial_Z,
  11624. (bitcount_t) (num_n_bits + 1), curve);
  11625. if (uECC_vli_isZero(p, num_words)) {
  11626. return 0;
  11627. }
  11628. /* If an RNG function was specified, get a random number
  11629. to prevent side channel analysis of k. */
  11630. if (!g_rng_function) {
  11631. uECC_vli_clear(tmp, num_n_words);
  11632. tmp[0] = 1;
  11633. } else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) {
  11634. return 0;
  11635. }
  11636. /* Prevent side channel analysis of uECC_vli_modInv() to determine
  11637. bits of k / the private key by premultiplying by a random number */
  11638. uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */
  11639. uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */
  11640. uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */
  11641. #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0
  11642. uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */
  11643. #endif
  11644. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11645. bcopy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits));
  11646. #else
  11647. uECC_vli_bytesToNative(tmp, private_key,
  11648. BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */
  11649. #endif
  11650. s[num_n_words - 1] = 0;
  11651. uECC_vli_set(s, p, num_words);
  11652. uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */
  11653. bits2int(tmp, message_hash, hash_size, curve);
  11654. uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */
  11655. uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */
  11656. if (uECC_vli_numBits(s, num_n_words) > (bitcount_t) curve->num_bytes * 8) {
  11657. return 0;
  11658. }
  11659. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11660. bcopy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s,
  11661. curve->num_bytes);
  11662. #else
  11663. uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s);
  11664. #endif
  11665. return 1;
  11666. }
  11667. #if 0
  11668. /* For testing - sign with an explicitly specified k value */
  11669. int uECC_sign_with_k(const uint8_t *private_key, const uint8_t *message_hash,
  11670. unsigned hash_size, const uint8_t *k, uint8_t *signature,
  11671. uECC_Curve curve) {
  11672. uECC_word_t k2[uECC_MAX_WORDS];
  11673. bits2int(k2, k, (unsigned) BITS_TO_BYTES(curve->num_n_bits), curve);
  11674. return uECC_sign_with_k_internal(private_key, message_hash, hash_size, k2,
  11675. signature, curve);
  11676. }
  11677. #endif
  11678. int uECC_sign(const uint8_t *private_key, const uint8_t *message_hash,
  11679. unsigned hash_size, uint8_t *signature, uECC_Curve curve) {
  11680. uECC_word_t k[uECC_MAX_WORDS];
  11681. uECC_word_t tries;
  11682. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11683. if (!uECC_generate_random_int(k, curve->n,
  11684. BITS_TO_WORDS(curve->num_n_bits))) {
  11685. return 0;
  11686. }
  11687. if (uECC_sign_with_k_internal(private_key, message_hash, hash_size, k,
  11688. signature, curve)) {
  11689. return 1;
  11690. }
  11691. }
  11692. return 0;
  11693. }
  11694. /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always
  11695. the same size as the hash result size. */
  11696. static void HMAC_init(const uECC_HashContext *hash_context, const uint8_t *K) {
  11697. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  11698. unsigned i;
  11699. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x36;
  11700. for (; i < hash_context->block_size; ++i) pad[i] = 0x36;
  11701. hash_context->init_hash(hash_context);
  11702. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  11703. }
  11704. static void HMAC_update(const uECC_HashContext *hash_context,
  11705. const uint8_t *message, unsigned message_size) {
  11706. hash_context->update_hash(hash_context, message, message_size);
  11707. }
  11708. static void HMAC_finish(const uECC_HashContext *hash_context, const uint8_t *K,
  11709. uint8_t *result) {
  11710. uint8_t *pad = hash_context->tmp + 2 * hash_context->result_size;
  11711. unsigned i;
  11712. for (i = 0; i < hash_context->result_size; ++i) pad[i] = K[i] ^ 0x5c;
  11713. for (; i < hash_context->block_size; ++i) pad[i] = 0x5c;
  11714. hash_context->finish_hash(hash_context, result);
  11715. hash_context->init_hash(hash_context);
  11716. hash_context->update_hash(hash_context, pad, hash_context->block_size);
  11717. hash_context->update_hash(hash_context, result, hash_context->result_size);
  11718. hash_context->finish_hash(hash_context, result);
  11719. }
  11720. /* V = HMAC_K(V) */
  11721. static void update_V(const uECC_HashContext *hash_context, uint8_t *K,
  11722. uint8_t *V) {
  11723. HMAC_init(hash_context, K);
  11724. HMAC_update(hash_context, V, hash_context->result_size);
  11725. HMAC_finish(hash_context, K, V);
  11726. }
  11727. /* Deterministic signing, similar to RFC 6979. Differences are:
  11728. * We just use H(m) directly rather than bits2octets(H(m))
  11729. (it is not reduced modulo curve_n).
  11730. * We generate a value for k (aka T) directly rather than converting
  11731. endianness.
  11732. Layout of hash_context->tmp: <K> | <V> | (1 byte overlapped 0x00 or 0x01) /
  11733. <HMAC pad> */
  11734. int uECC_sign_deterministic(const uint8_t *private_key,
  11735. const uint8_t *message_hash, unsigned hash_size,
  11736. const uECC_HashContext *hash_context,
  11737. uint8_t *signature, uECC_Curve curve) {
  11738. uint8_t *K = hash_context->tmp;
  11739. uint8_t *V = K + hash_context->result_size;
  11740. wordcount_t num_bytes = curve->num_bytes;
  11741. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11742. bitcount_t num_n_bits = curve->num_n_bits;
  11743. uECC_word_t tries;
  11744. unsigned i;
  11745. for (i = 0; i < hash_context->result_size; ++i) {
  11746. V[i] = 0x01;
  11747. K[i] = 0;
  11748. }
  11749. /* K = HMAC_K(V || 0x00 || int2octets(x) || h(m)) */
  11750. HMAC_init(hash_context, K);
  11751. V[hash_context->result_size] = 0x00;
  11752. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11753. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  11754. HMAC_update(hash_context, message_hash, hash_size);
  11755. HMAC_finish(hash_context, K, K);
  11756. update_V(hash_context, K, V);
  11757. /* K = HMAC_K(V || 0x01 || int2octets(x) || h(m)) */
  11758. HMAC_init(hash_context, K);
  11759. V[hash_context->result_size] = 0x01;
  11760. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11761. HMAC_update(hash_context, private_key, (unsigned int) num_bytes);
  11762. HMAC_update(hash_context, message_hash, hash_size);
  11763. HMAC_finish(hash_context, K, K);
  11764. update_V(hash_context, K, V);
  11765. for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) {
  11766. uECC_word_t T[uECC_MAX_WORDS];
  11767. uint8_t *T_ptr = (uint8_t *) T;
  11768. wordcount_t T_bytes = 0;
  11769. for (;;) {
  11770. update_V(hash_context, K, V);
  11771. for (i = 0; i < hash_context->result_size; ++i) {
  11772. T_ptr[T_bytes++] = V[i];
  11773. if (T_bytes >= num_n_words * uECC_WORD_SIZE) {
  11774. goto filled;
  11775. }
  11776. }
  11777. }
  11778. filled:
  11779. if ((bitcount_t) num_n_words * uECC_WORD_SIZE * 8 > num_n_bits) {
  11780. uECC_word_t mask = (uECC_word_t) -1;
  11781. T[num_n_words - 1] &=
  11782. mask >>
  11783. ((bitcount_t) (num_n_words * uECC_WORD_SIZE * 8 - num_n_bits));
  11784. }
  11785. if (uECC_sign_with_k_internal(private_key, message_hash, hash_size, T,
  11786. signature, curve)) {
  11787. return 1;
  11788. }
  11789. /* K = HMAC_K(V || 0x00) */
  11790. HMAC_init(hash_context, K);
  11791. V[hash_context->result_size] = 0x00;
  11792. HMAC_update(hash_context, V, hash_context->result_size + 1);
  11793. HMAC_finish(hash_context, K, K);
  11794. update_V(hash_context, K, V);
  11795. }
  11796. return 0;
  11797. }
  11798. static bitcount_t smax(bitcount_t a, bitcount_t b) {
  11799. return (a > b ? a : b);
  11800. }
  11801. int uECC_verify(const uint8_t *public_key, const uint8_t *message_hash,
  11802. unsigned hash_size, const uint8_t *signature,
  11803. uECC_Curve curve) {
  11804. uECC_word_t u1[uECC_MAX_WORDS], u2[uECC_MAX_WORDS];
  11805. uECC_word_t z[uECC_MAX_WORDS];
  11806. uECC_word_t sum[uECC_MAX_WORDS * 2];
  11807. uECC_word_t rx[uECC_MAX_WORDS];
  11808. uECC_word_t ry[uECC_MAX_WORDS];
  11809. uECC_word_t tx[uECC_MAX_WORDS];
  11810. uECC_word_t ty[uECC_MAX_WORDS];
  11811. uECC_word_t tz[uECC_MAX_WORDS];
  11812. const uECC_word_t *points[4];
  11813. const uECC_word_t *point;
  11814. bitcount_t num_bits;
  11815. bitcount_t i;
  11816. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11817. uECC_word_t *_public = (uECC_word_t *) public_key;
  11818. #else
  11819. uECC_word_t _public[uECC_MAX_WORDS * 2];
  11820. #endif
  11821. uECC_word_t r[uECC_MAX_WORDS], s[uECC_MAX_WORDS];
  11822. wordcount_t num_words = curve->num_words;
  11823. wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits);
  11824. rx[num_n_words - 1] = 0;
  11825. r[num_n_words - 1] = 0;
  11826. s[num_n_words - 1] = 0;
  11827. #if uECC_VLI_NATIVE_LITTLE_ENDIAN
  11828. bcopy((uint8_t *) r, signature, curve->num_bytes);
  11829. bcopy((uint8_t *) s, signature + curve->num_bytes, curve->num_bytes);
  11830. #else
  11831. uECC_vli_bytesToNative(_public, public_key, curve->num_bytes);
  11832. uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes,
  11833. curve->num_bytes);
  11834. uECC_vli_bytesToNative(r, signature, curve->num_bytes);
  11835. uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes);
  11836. #endif
  11837. /* r, s must not be 0. */
  11838. if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) {
  11839. return 0;
  11840. }
  11841. /* r, s must be < n. */
  11842. if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 ||
  11843. uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) {
  11844. return 0;
  11845. }
  11846. /* Calculate u1 and u2. */
  11847. uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */
  11848. u1[num_n_words - 1] = 0;
  11849. bits2int(u1, message_hash, hash_size, curve);
  11850. uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */
  11851. uECC_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */
  11852. /* Calculate sum = G + Q. */
  11853. uECC_vli_set(sum, _public, num_words);
  11854. uECC_vli_set(sum + num_words, _public + num_words, num_words);
  11855. uECC_vli_set(tx, curve->G, num_words);
  11856. uECC_vli_set(ty, curve->G + num_words, num_words);
  11857. uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */
  11858. XYcZ_add(tx, ty, sum, sum + num_words, curve);
  11859. uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */
  11860. apply_z(sum, sum + num_words, z, curve);
  11861. /* Use Shamir's trick to calculate u1*G + u2*Q */
  11862. points[0] = 0;
  11863. points[1] = curve->G;
  11864. points[2] = _public;
  11865. points[3] = sum;
  11866. num_bits = smax(uECC_vli_numBits(u1, num_n_words),
  11867. uECC_vli_numBits(u2, num_n_words));
  11868. point = points[(!!uECC_vli_testBit(u1, (bitcount_t) (num_bits - 1))) |
  11869. ((!!uECC_vli_testBit(u2, (bitcount_t) (num_bits - 1))) << 1)];
  11870. uECC_vli_set(rx, point, num_words);
  11871. uECC_vli_set(ry, point + num_words, num_words);
  11872. uECC_vli_clear(z, num_words);
  11873. z[0] = 1;
  11874. for (i = num_bits - 2; i >= 0; --i) {
  11875. uECC_word_t index;
  11876. curve->double_jacobian(rx, ry, z, curve);
  11877. index = (!!uECC_vli_testBit(u1, i)) |
  11878. (uECC_word_t) ((!!uECC_vli_testBit(u2, i)) << 1);
  11879. point = points[index];
  11880. if (point) {
  11881. uECC_vli_set(tx, point, num_words);
  11882. uECC_vli_set(ty, point + num_words, num_words);
  11883. apply_z(tx, ty, z, curve);
  11884. uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */
  11885. XYcZ_add(tx, ty, rx, ry, curve);
  11886. uECC_vli_modMult_fast(z, z, tz, curve);
  11887. }
  11888. }
  11889. uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */
  11890. apply_z(rx, ry, z, curve);
  11891. /* v = x1 (mod n) */
  11892. if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) {
  11893. uECC_vli_sub(rx, rx, curve->n, num_n_words);
  11894. }
  11895. /* Accept only if v == r. */
  11896. return (int) (uECC_vli_equal(rx, r, num_words));
  11897. }
  11898. #if uECC_ENABLE_VLI_API
  11899. unsigned uECC_curve_num_words(uECC_Curve curve) {
  11900. return curve->num_words;
  11901. }
  11902. unsigned uECC_curve_num_bytes(uECC_Curve curve) {
  11903. return curve->num_bytes;
  11904. }
  11905. unsigned uECC_curve_num_bits(uECC_Curve curve) {
  11906. return curve->num_bytes * 8;
  11907. }
  11908. unsigned uECC_curve_num_n_words(uECC_Curve curve) {
  11909. return BITS_TO_WORDS(curve->num_n_bits);
  11910. }
  11911. unsigned uECC_curve_num_n_bytes(uECC_Curve curve) {
  11912. return BITS_TO_BYTES(curve->num_n_bits);
  11913. }
  11914. unsigned uECC_curve_num_n_bits(uECC_Curve curve) {
  11915. return curve->num_n_bits;
  11916. }
  11917. const uECC_word_t *uECC_curve_p(uECC_Curve curve) {
  11918. return curve->p;
  11919. }
  11920. const uECC_word_t *uECC_curve_n(uECC_Curve curve) {
  11921. return curve->n;
  11922. }
  11923. const uECC_word_t *uECC_curve_G(uECC_Curve curve) {
  11924. return curve->G;
  11925. }
  11926. const uECC_word_t *uECC_curve_b(uECC_Curve curve) {
  11927. return curve->b;
  11928. }
  11929. #if uECC_SUPPORT_COMPRESSED_POINT
  11930. void uECC_vli_mod_sqrt(uECC_word_t *a, uECC_Curve curve) {
  11931. curve->mod_sqrt(a, curve);
  11932. }
  11933. #endif
  11934. void uECC_vli_mmod_fast(uECC_word_t *result, uECC_word_t *product,
  11935. uECC_Curve curve) {
  11936. #if (uECC_OPTIMIZATION_LEVEL > 0)
  11937. curve->mmod_fast(result, product);
  11938. #else
  11939. uECC_vli_mmod(result, product, curve->p, curve->num_words);
  11940. #endif
  11941. }
  11942. void uECC_point_mult(uECC_word_t *result, const uECC_word_t *point,
  11943. const uECC_word_t *scalar, uECC_Curve curve) {
  11944. uECC_word_t tmp1[uECC_MAX_WORDS];
  11945. uECC_word_t tmp2[uECC_MAX_WORDS];
  11946. uECC_word_t *p2[2] = {tmp1, tmp2};
  11947. uECC_word_t carry = regularize_k(scalar, tmp1, tmp2, curve);
  11948. EccPoint_mult(result, point, p2[!carry], 0, curve->num_n_bits + 1, curve);
  11949. }
  11950. #endif /* uECC_ENABLE_VLI_API */
  11951. #endif // MG_TLS_BUILTIN
  11952. // End of uecc BSD-2
  11953. #ifdef MG_ENABLE_LINES
  11954. #line 1 "src/url.c"
  11955. #endif
  11956. struct url {
  11957. size_t key, user, pass, host, port, uri, end;
  11958. };
  11959. int mg_url_is_ssl(const char *url) {
  11960. return strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0 ||
  11961. strncmp(url, "mqtts:", 6) == 0 || strncmp(url, "ssl:", 4) == 0 ||
  11962. strncmp(url, "tls:", 4) == 0 || strncmp(url, "tcps:", 5) == 0;
  11963. }
  11964. static struct url urlparse(const char *url) {
  11965. size_t i;
  11966. struct url u;
  11967. memset(&u, 0, sizeof(u));
  11968. for (i = 0; url[i] != '\0'; i++) {
  11969. if (url[i] == '/' && i > 0 && u.host == 0 && url[i - 1] == '/') {
  11970. u.host = i + 1;
  11971. u.port = 0;
  11972. } else if (url[i] == ']') {
  11973. u.port = 0; // IPv6 URLs, like http://[::1]/bar
  11974. } else if (url[i] == ':' && u.port == 0 && u.uri == 0) {
  11975. u.port = i + 1;
  11976. } else if (url[i] == '@' && u.user == 0 && u.pass == 0 && u.uri == 0) {
  11977. u.user = u.host;
  11978. u.pass = u.port;
  11979. u.host = i + 1;
  11980. u.port = 0;
  11981. } else if (url[i] == '/' && u.host && u.uri == 0) {
  11982. u.uri = i;
  11983. }
  11984. }
  11985. u.end = i;
  11986. #if 0
  11987. printf("[%s] %d %d %d %d %d\n", url, u.user, u.pass, u.host, u.port, u.uri);
  11988. #endif
  11989. return u;
  11990. }
  11991. struct mg_str mg_url_host(const char *url) {
  11992. struct url u = urlparse(url);
  11993. size_t n = u.port ? u.port - u.host - 1
  11994. : u.uri ? u.uri - u.host
  11995. : u.end - u.host;
  11996. struct mg_str s = mg_str_n(url + u.host, n);
  11997. return s;
  11998. }
  11999. const char *mg_url_uri(const char *url) {
  12000. struct url u = urlparse(url);
  12001. return u.uri ? url + u.uri : "/";
  12002. }
  12003. unsigned short mg_url_port(const char *url) {
  12004. struct url u = urlparse(url);
  12005. unsigned short port = 0;
  12006. if (strncmp(url, "http:", 5) == 0 || strncmp(url, "ws:", 3) == 0) port = 80;
  12007. if (strncmp(url, "wss:", 4) == 0 || strncmp(url, "https:", 6) == 0)
  12008. port = 443;
  12009. if (strncmp(url, "mqtt:", 5) == 0) port = 1883;
  12010. if (strncmp(url, "mqtts:", 6) == 0) port = 8883;
  12011. if (u.port) port = (unsigned short) atoi(url + u.port);
  12012. return port;
  12013. }
  12014. struct mg_str mg_url_user(const char *url) {
  12015. struct url u = urlparse(url);
  12016. struct mg_str s = mg_str("");
  12017. if (u.user && (u.pass || u.host)) {
  12018. size_t n = u.pass ? u.pass - u.user - 1 : u.host - u.user - 1;
  12019. s = mg_str_n(url + u.user, n);
  12020. }
  12021. return s;
  12022. }
  12023. struct mg_str mg_url_pass(const char *url) {
  12024. struct url u = urlparse(url);
  12025. struct mg_str s = mg_str_n("", 0UL);
  12026. if (u.pass && u.host) {
  12027. size_t n = u.host - u.pass - 1;
  12028. s = mg_str_n(url + u.pass, n);
  12029. }
  12030. return s;
  12031. }
  12032. #ifdef MG_ENABLE_LINES
  12033. #line 1 "src/util.c"
  12034. #endif
  12035. // Not using memset for zeroing memory, cause it can be dropped by compiler
  12036. // See https://github.com/cesanta/mongoose/pull/1265
  12037. void mg_bzero(volatile unsigned char *buf, size_t len) {
  12038. if (buf != NULL) {
  12039. while (len--) *buf++ = 0;
  12040. }
  12041. }
  12042. #if MG_ENABLE_CUSTOM_RANDOM
  12043. #else
  12044. void mg_random(void *buf, size_t len) {
  12045. bool done = false;
  12046. unsigned char *p = (unsigned char *) buf;
  12047. #if MG_ARCH == MG_ARCH_ESP32
  12048. while (len--) *p++ = (unsigned char) (esp_random() & 255);
  12049. done = true;
  12050. #elif MG_ARCH == MG_ARCH_WIN32
  12051. #elif MG_ARCH == MG_ARCH_UNIX
  12052. FILE *fp = fopen("/dev/urandom", "rb");
  12053. if (fp != NULL) {
  12054. if (fread(buf, 1, len, fp) == len) done = true;
  12055. fclose(fp);
  12056. }
  12057. #endif
  12058. // If everything above did not work, fallback to a pseudo random generator
  12059. while (!done && len--) *p++ = (unsigned char) (rand() & 255);
  12060. }
  12061. #endif
  12062. char *mg_random_str(char *buf, size_t len) {
  12063. size_t i;
  12064. mg_random(buf, len);
  12065. for (i = 0; i < len; i++) {
  12066. uint8_t c = ((uint8_t *) buf)[i] % 62U;
  12067. buf[i] = i == len - 1 ? (char) '\0' // 0-terminate last byte
  12068. : c < 26 ? (char) ('a' + c) // lowercase
  12069. : c < 52 ? (char) ('A' + c - 26) // uppercase
  12070. : (char) ('0' + c - 52); // numeric
  12071. }
  12072. return buf;
  12073. }
  12074. uint32_t mg_ntohl(uint32_t net) {
  12075. uint8_t data[4] = {0, 0, 0, 0};
  12076. memcpy(&data, &net, sizeof(data));
  12077. return (((uint32_t) data[3]) << 0) | (((uint32_t) data[2]) << 8) |
  12078. (((uint32_t) data[1]) << 16) | (((uint32_t) data[0]) << 24);
  12079. }
  12080. uint16_t mg_ntohs(uint16_t net) {
  12081. uint8_t data[2] = {0, 0};
  12082. memcpy(&data, &net, sizeof(data));
  12083. return (uint16_t) ((uint16_t) data[1] | (((uint16_t) data[0]) << 8));
  12084. }
  12085. uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len) {
  12086. static const uint32_t crclut[16] = {
  12087. // table for polynomial 0xEDB88320 (reflected)
  12088. 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
  12089. 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
  12090. 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
  12091. crc = ~crc;
  12092. while (len--) {
  12093. uint8_t byte = *(uint8_t *) buf++;
  12094. crc = crclut[(crc ^ byte) & 0x0F] ^ (crc >> 4);
  12095. crc = crclut[(crc ^ (byte >> 4)) & 0x0F] ^ (crc >> 4);
  12096. }
  12097. return ~crc;
  12098. }
  12099. static int isbyte(int n) {
  12100. return n >= 0 && n <= 255;
  12101. }
  12102. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  12103. int n, a, b, c, d, slash = 32, len = 0;
  12104. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  12105. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  12106. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  12107. slash < 33) {
  12108. len = n;
  12109. *net = ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) |
  12110. (uint32_t) d;
  12111. *mask = slash ? (uint32_t) (0xffffffffU << (32 - slash)) : (uint32_t) 0;
  12112. }
  12113. return len;
  12114. }
  12115. int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip) {
  12116. struct mg_str k, v;
  12117. int allowed = acl.len == 0 ? '+' : '-'; // If any ACL is set, deny by default
  12118. uint32_t remote_ip4;
  12119. if (remote_ip->is_ip6) {
  12120. return -1; // TODO(): handle IPv6 ACL and addresses
  12121. } else { // IPv4
  12122. memcpy((void *) &remote_ip4, remote_ip->ip, sizeof(remote_ip4));
  12123. while (mg_commalist(&acl, &k, &v)) {
  12124. uint32_t net, mask;
  12125. if (k.ptr[0] != '+' && k.ptr[0] != '-') return -1;
  12126. if (parse_net(&k.ptr[1], &net, &mask) == 0) return -2;
  12127. if ((mg_ntohl(remote_ip4) & mask) == net) allowed = k.ptr[0];
  12128. }
  12129. }
  12130. return allowed == '+';
  12131. }
  12132. #if MG_ENABLE_CUSTOM_MILLIS
  12133. #else
  12134. uint64_t mg_millis(void) {
  12135. #if MG_ARCH == MG_ARCH_WIN32
  12136. return GetTickCount();
  12137. #elif MG_ARCH == MG_ARCH_RP2040
  12138. return time_us_64() / 1000;
  12139. #elif MG_ARCH == MG_ARCH_ESP8266 || MG_ARCH == MG_ARCH_ESP32 || \
  12140. MG_ARCH == MG_ARCH_FREERTOS
  12141. return xTaskGetTickCount() * portTICK_PERIOD_MS;
  12142. #elif MG_ARCH == MG_ARCH_AZURERTOS
  12143. return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND);
  12144. #elif MG_ARCH == MG_ARCH_TIRTOS
  12145. return (uint64_t) Clock_getTicks();
  12146. #elif MG_ARCH == MG_ARCH_ZEPHYR
  12147. return (uint64_t) k_uptime_get();
  12148. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
  12149. return (uint64_t) rt_time_get();
  12150. #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
  12151. return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq());
  12152. #elif MG_ARCH == MG_ARCH_RTTHREAD
  12153. return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND);
  12154. #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
  12155. // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
  12156. // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
  12157. return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000;
  12158. #elif MG_ARCH == MG_ARCH_UNIX
  12159. struct timespec ts = {0, 0};
  12160. // See #1615 - prefer monotonic clock
  12161. #if defined(CLOCK_MONOTONIC_RAW)
  12162. // Raw hardware-based time that is not subject to NTP adjustment
  12163. clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  12164. #elif defined(CLOCK_MONOTONIC)
  12165. // Affected by the incremental adjustments performed by adjtime and NTP
  12166. clock_gettime(CLOCK_MONOTONIC, &ts);
  12167. #else
  12168. // Affected by discontinuous jumps in the system time and by the incremental
  12169. // adjustments performed by adjtime and NTP
  12170. clock_gettime(CLOCK_REALTIME, &ts);
  12171. #endif
  12172. return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000);
  12173. #elif defined(ARDUINO)
  12174. return (uint64_t) millis();
  12175. #else
  12176. return (uint64_t) (time(NULL) * 1000);
  12177. #endif
  12178. }
  12179. #endif
  12180. #ifdef MG_ENABLE_LINES
  12181. #line 1 "src/ws.c"
  12182. #endif
  12183. struct ws_msg {
  12184. uint8_t flags;
  12185. size_t header_len;
  12186. size_t data_len;
  12187. };
  12188. size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
  12189. va_list *ap) {
  12190. size_t len = c->send.len;
  12191. size_t n = mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  12192. mg_ws_wrap(c, c->send.len - len, op);
  12193. return n;
  12194. }
  12195. size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...) {
  12196. size_t len = 0;
  12197. va_list ap;
  12198. va_start(ap, fmt);
  12199. len = mg_ws_vprintf(c, op, fmt, &ap);
  12200. va_end(ap);
  12201. return len;
  12202. }
  12203. static void ws_handshake(struct mg_connection *c, const struct mg_str *wskey,
  12204. const struct mg_str *wsproto, const char *fmt,
  12205. va_list *ap) {
  12206. const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  12207. unsigned char sha[20], b64_sha[30];
  12208. mg_sha1_ctx sha_ctx;
  12209. mg_sha1_init(&sha_ctx);
  12210. mg_sha1_update(&sha_ctx, (unsigned char *) wskey->ptr, wskey->len);
  12211. mg_sha1_update(&sha_ctx, (unsigned char *) magic, 36);
  12212. mg_sha1_final(sha, &sha_ctx);
  12213. mg_base64_encode(sha, sizeof(sha), (char *) b64_sha, sizeof(b64_sha));
  12214. mg_xprintf(mg_pfn_iobuf, &c->send,
  12215. "HTTP/1.1 101 Switching Protocols\r\n"
  12216. "Upgrade: websocket\r\n"
  12217. "Connection: Upgrade\r\n"
  12218. "Sec-WebSocket-Accept: %s\r\n",
  12219. b64_sha);
  12220. if (fmt != NULL) mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, ap);
  12221. if (wsproto != NULL) {
  12222. mg_printf(c, "Sec-WebSocket-Protocol: %.*s\r\n", (int) wsproto->len,
  12223. wsproto->ptr);
  12224. }
  12225. mg_send(c, "\r\n", 2);
  12226. }
  12227. static uint32_t be32(const uint8_t *p) {
  12228. return (((uint32_t) p[3]) << 0) | (((uint32_t) p[2]) << 8) |
  12229. (((uint32_t) p[1]) << 16) | (((uint32_t) p[0]) << 24);
  12230. }
  12231. static size_t ws_process(uint8_t *buf, size_t len, struct ws_msg *msg) {
  12232. size_t i, n = 0, mask_len = 0;
  12233. memset(msg, 0, sizeof(*msg));
  12234. if (len >= 2) {
  12235. n = buf[1] & 0x7f; // Frame length
  12236. mask_len = buf[1] & 128 ? 4 : 0; // last bit is a mask bit
  12237. msg->flags = buf[0];
  12238. if (n < 126 && len >= mask_len) {
  12239. msg->data_len = n;
  12240. msg->header_len = 2 + mask_len;
  12241. } else if (n == 126 && len >= 4 + mask_len) {
  12242. msg->header_len = 4 + mask_len;
  12243. msg->data_len = (((size_t) buf[2]) << 8) | buf[3];
  12244. } else if (len >= 10 + mask_len) {
  12245. msg->header_len = 10 + mask_len;
  12246. msg->data_len =
  12247. (size_t) (((uint64_t) be32(buf + 2) << 32) + be32(buf + 6));
  12248. }
  12249. }
  12250. // Sanity check, and integer overflow protection for the boundary check below
  12251. // data_len should not be larger than 1 Gb
  12252. if (msg->data_len > 1024 * 1024 * 1024) return 0;
  12253. if (msg->header_len + msg->data_len > len) return 0;
  12254. if (mask_len > 0) {
  12255. uint8_t *p = buf + msg->header_len, *m = p - mask_len;
  12256. for (i = 0; i < msg->data_len; i++) p[i] ^= m[i & 3];
  12257. }
  12258. return msg->header_len + msg->data_len;
  12259. }
  12260. static size_t mkhdr(size_t len, int op, bool is_client, uint8_t *buf) {
  12261. size_t n = 0;
  12262. buf[0] = (uint8_t) (op | 128);
  12263. if (len < 126) {
  12264. buf[1] = (unsigned char) len;
  12265. n = 2;
  12266. } else if (len < 65536) {
  12267. uint16_t tmp = mg_htons((uint16_t) len);
  12268. buf[1] = 126;
  12269. memcpy(&buf[2], &tmp, sizeof(tmp));
  12270. n = 4;
  12271. } else {
  12272. uint32_t tmp;
  12273. buf[1] = 127;
  12274. tmp = mg_htonl((uint32_t) (((uint64_t) len) >> 32));
  12275. memcpy(&buf[2], &tmp, sizeof(tmp));
  12276. tmp = mg_htonl((uint32_t) (len & 0xffffffffU));
  12277. memcpy(&buf[6], &tmp, sizeof(tmp));
  12278. n = 10;
  12279. }
  12280. if (is_client) {
  12281. buf[1] |= 1 << 7; // Set masking flag
  12282. mg_random(&buf[n], 4);
  12283. n += 4;
  12284. }
  12285. return n;
  12286. }
  12287. static void mg_ws_mask(struct mg_connection *c, size_t len) {
  12288. if (c->is_client && c->send.buf != NULL) {
  12289. size_t i;
  12290. uint8_t *p = c->send.buf + c->send.len - len, *mask = p - 4;
  12291. for (i = 0; i < len; i++) p[i] ^= mask[i & 3];
  12292. }
  12293. }
  12294. size_t mg_ws_send(struct mg_connection *c, const void *buf, size_t len,
  12295. int op) {
  12296. #if MG_ARCH == MG_ARCH_UNIX
  12297. // pthread_mutex_lock(&WSlock);
  12298. #endif
  12299. if (c==NULL || c->send.buf== NULL)
  12300. {
  12301. #if MG_ARCH == MG_ARCH_UNIX
  12302. // pthread_mutex_unlock(&WSlock);
  12303. #endif
  12304. return 0;
  12305. }
  12306. uint8_t header[14];
  12307. size_t header_len = mkhdr(len, op, c->is_client, header);
  12308. //printf("WS out: %d [%.*s]", (int) len, (int) len, buf);
  12309. mg_send(c, header, header_len);
  12310. MG_VERBOSE(("WS out: %d [%.*s]", (int) len, (int) len, buf));
  12311. mg_send(c, buf, len);
  12312. mg_ws_mask(c, len);
  12313. #if MG_ARCH == MG_ARCH_UNIX
  12314. // pthread_mutex_unlock(&WSlock);
  12315. #endif
  12316. return header_len + len;
  12317. }
  12318. static bool mg_ws_client_handshake(struct mg_connection *c) {
  12319. int n = mg_http_get_request_len(c->recv.buf, c->recv.len);
  12320. if (n < 0) {
  12321. mg_error(c, "not http"); // Some just, not an HTTP request
  12322. } else if (n > 0) {
  12323. if (n < 15 || memcmp(c->recv.buf + 9, "101", 3) != 0) {
  12324. mg_error(c, "ws handshake error");
  12325. } else {
  12326. struct mg_http_message hm;
  12327. if (mg_http_parse((char *) c->recv.buf, c->recv.len, &hm)) {
  12328. c->is_websocket = 1;
  12329. mg_call(c, MG_EV_WS_OPEN, &hm);
  12330. } else {
  12331. mg_error(c, "ws handshake error");
  12332. }
  12333. }
  12334. mg_iobuf_del(&c->recv, 0, (size_t) n);
  12335. } else {
  12336. return true; // Request is not yet received, quit event handler
  12337. }
  12338. return false; // Continue event handler
  12339. }
  12340. static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
  12341. struct ws_msg msg;
  12342. size_t ofs = (size_t) c->pfn_data;
  12343. // assert(ofs < c->recv.len);
  12344. if (ev == MG_EV_READ) {
  12345. if (c->is_client && !c->is_websocket && mg_ws_client_handshake(c)) return;
  12346. while (ws_process(c->recv.buf + ofs, c->recv.len - ofs, &msg) > 0) {
  12347. char *s = (char *) c->recv.buf + ofs + msg.header_len;
  12348. struct mg_ws_message m = {{s, msg.data_len}, msg.flags};
  12349. size_t len = msg.header_len + msg.data_len;
  12350. uint8_t final = msg.flags & 128, op = msg.flags & 15;
  12351. // MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
  12352. // (int) m.data.len, (int) m.data.len, m.data.ptr));
  12353. switch (op) {
  12354. case WEBSOCKET_OP_CONTINUE:
  12355. mg_call(c, MG_EV_WS_CTL, &m);
  12356. break;
  12357. case WEBSOCKET_OP_PING:
  12358. MG_DEBUG(("%s", "WS PONG"));
  12359. mg_ws_send(c, s, msg.data_len, WEBSOCKET_OP_PONG);
  12360. mg_call(c, MG_EV_WS_CTL, &m);
  12361. break;
  12362. case WEBSOCKET_OP_PONG:
  12363. mg_call(c, MG_EV_WS_CTL, &m);
  12364. break;
  12365. case WEBSOCKET_OP_TEXT:
  12366. case WEBSOCKET_OP_BINARY:
  12367. if (final) mg_call(c, MG_EV_WS_MSG, &m);
  12368. break;
  12369. case WEBSOCKET_OP_CLOSE:
  12370. MG_DEBUG(("%lu WS CLOSE", c->id));
  12371. mg_call(c, MG_EV_WS_CTL, &m);
  12372. // Echo the payload of the received CLOSE message back to the sender
  12373. mg_ws_send(c, m.data.ptr, m.data.len, WEBSOCKET_OP_CLOSE);
  12374. c->is_draining = 1;
  12375. break;
  12376. default:
  12377. // Per RFC6455, close conn when an unknown op is recvd
  12378. mg_error(c, "unknown WS op %d", op);
  12379. break;
  12380. }
  12381. // Handle fragmented frames: strip header, keep in c->recv
  12382. if (final == 0 || op == 0) {
  12383. if (op) ofs++, len--, msg.header_len--; // First frame
  12384. mg_iobuf_del(&c->recv, ofs, msg.header_len); // Strip header
  12385. len -= msg.header_len;
  12386. ofs += len;
  12387. c->pfn_data = (void *) ofs;
  12388. // MG_INFO(("FRAG %d [%.*s]", (int) ofs, (int) ofs, c->recv.buf));
  12389. }
  12390. // Remove non-fragmented frame
  12391. if (final && op) mg_iobuf_del(&c->recv, ofs, len);
  12392. // Last chunk of the fragmented frame
  12393. if (final && !op) {
  12394. m.flags = c->recv.buf[0];
  12395. m.data = mg_str_n((char *) &c->recv.buf[1], (size_t) (ofs - 1));
  12396. mg_call(c, MG_EV_WS_MSG, &m);
  12397. mg_iobuf_del(&c->recv, 0, ofs);
  12398. ofs = 0;
  12399. c->pfn_data = NULL;
  12400. }
  12401. }
  12402. }
  12403. (void) ev_data;
  12404. }
  12405. struct mg_connection *mg_ws_connect(struct mg_mgr *mgr, const char *url,
  12406. mg_event_handler_t fn, void *fn_data,
  12407. const char *fmt, ...) {
  12408. struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
  12409. if (c != NULL) {
  12410. char nonce[16], key[30];
  12411. struct mg_str host = mg_url_host(url);
  12412. mg_random(nonce, sizeof(nonce));
  12413. mg_base64_encode((unsigned char *) nonce, sizeof(nonce), key, sizeof(key));
  12414. mg_xprintf(mg_pfn_iobuf, &c->send,
  12415. "GET %s HTTP/1.1\r\n"
  12416. "Upgrade: websocket\r\n"
  12417. "Host: %.*s\r\n"
  12418. "Connection: Upgrade\r\n"
  12419. "Sec-WebSocket-Version: 13\r\n"
  12420. "Sec-WebSocket-Key: %s\r\n",
  12421. mg_url_uri(url), (int) host.len, host.ptr, key);
  12422. if (fmt != NULL) {
  12423. va_list ap;
  12424. va_start(ap, fmt);
  12425. mg_vxprintf(mg_pfn_iobuf, &c->send, fmt, &ap);
  12426. va_end(ap);
  12427. }
  12428. mg_xprintf(mg_pfn_iobuf, &c->send, "\r\n");
  12429. c->pfn = mg_ws_cb;
  12430. c->pfn_data = NULL;
  12431. }
  12432. return c;
  12433. }
  12434. void mg_ws_upgrade(struct mg_connection *c, struct mg_http_message *hm,
  12435. const char *fmt, ...) {
  12436. struct mg_str *wskey = mg_http_get_header(hm, "Sec-WebSocket-Key");
  12437. c->pfn = mg_ws_cb;
  12438. c->pfn_data = NULL;
  12439. if (wskey == NULL) {
  12440. mg_http_reply(c, 426, "", "WS upgrade expected\n");
  12441. c->is_draining = 1;
  12442. } else {
  12443. struct mg_str *wsproto = mg_http_get_header(hm, "Sec-WebSocket-Protocol");
  12444. va_list ap;
  12445. va_start(ap, fmt);
  12446. ws_handshake(c, wskey, wsproto, fmt, &ap);
  12447. va_end(ap);
  12448. c->is_websocket = 1;
  12449. c->is_resp = 0;
  12450. mg_call(c, MG_EV_WS_OPEN, hm);
  12451. }
  12452. }
  12453. size_t mg_ws_wrap(struct mg_connection *c, size_t len, int op) {
  12454. uint8_t header[14], *p;
  12455. size_t header_len = mkhdr(len, op, c->is_client, header);
  12456. // NOTE: order of operations is important!
  12457. mg_iobuf_add(&c->send, c->send.len, NULL, header_len);
  12458. p = &c->send.buf[c->send.len - len]; // p points to data
  12459. memmove(p, p - header_len, len); // Shift data
  12460. memcpy(p - header_len, header, header_len); // Prepend header
  12461. mg_ws_mask(c, len); // Mask data
  12462. return c->send.len;
  12463. }
  12464. #ifdef MG_ENABLE_LINES
  12465. #line 1 "src/drivers/cmsis.c"
  12466. #endif
  12467. // https://arm-software.github.io/CMSIS_5/Driver/html/index.html
  12468. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
  12469. extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0;
  12470. extern ARM_DRIVER_ETH_PHY Driver_ETH_PHY0;
  12471. static struct mg_tcpip_if *s_ifp;
  12472. static void mac_cb(uint32_t);
  12473. static bool cmsis_init(struct mg_tcpip_if *);
  12474. static bool cmsis_up(struct mg_tcpip_if *);
  12475. static size_t cmsis_tx(const void *, size_t, struct mg_tcpip_if *);
  12476. static size_t cmsis_rx(void *, size_t, struct mg_tcpip_if *);
  12477. struct mg_tcpip_driver mg_tcpip_driver_cmsis = {cmsis_init, cmsis_tx, NULL,
  12478. cmsis_up};
  12479. static bool cmsis_init(struct mg_tcpip_if *ifp) {
  12480. ARM_ETH_MAC_ADDR addr;
  12481. s_ifp = ifp;
  12482. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12483. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  12484. ARM_ETH_MAC_CAPABILITIES cap = mac->GetCapabilities();
  12485. if (mac->Initialize(mac_cb) != ARM_DRIVER_OK) return false;
  12486. if (phy->Initialize(mac->PHY_Read, mac->PHY_Write) != ARM_DRIVER_OK)
  12487. return false;
  12488. if (cap.event_rx_frame == 0) // polled mode driver
  12489. mg_tcpip_driver_cmsis.rx = cmsis_rx;
  12490. mac->PowerControl(ARM_POWER_FULL);
  12491. if (cap.mac_address) { // driver provides MAC address
  12492. mac->GetMacAddress(&addr);
  12493. memcpy(ifp->mac, &addr, sizeof(ifp->mac));
  12494. } else { // we provide MAC address
  12495. memcpy(&addr, ifp->mac, sizeof(addr));
  12496. mac->SetMacAddress(&addr);
  12497. }
  12498. phy->PowerControl(ARM_POWER_FULL);
  12499. phy->SetInterface(cap.media_interface);
  12500. phy->SetMode(ARM_ETH_PHY_AUTO_NEGOTIATE);
  12501. return true;
  12502. }
  12503. static size_t cmsis_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
  12504. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12505. if (mac->SendFrame(buf, (uint32_t) len, 0) != ARM_DRIVER_OK) {
  12506. ifp->nerr++;
  12507. return 0;
  12508. }
  12509. ifp->nsent++;
  12510. return len;
  12511. }
  12512. static bool cmsis_up(struct mg_tcpip_if *ifp) {
  12513. ARM_DRIVER_ETH_PHY *phy = &Driver_ETH_PHY0;
  12514. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12515. bool up = (phy->GetLinkState() == ARM_ETH_LINK_UP) ? 1 : 0; // link state
  12516. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // just went up
  12517. ARM_ETH_LINK_INFO st = phy->GetLinkInfo();
  12518. mac->Control(ARM_ETH_MAC_CONFIGURE,
  12519. (st.speed << ARM_ETH_MAC_SPEED_Pos) |
  12520. (st.duplex << ARM_ETH_MAC_DUPLEX_Pos) |
  12521. ARM_ETH_MAC_ADDRESS_BROADCAST);
  12522. MG_DEBUG(("Link is %uM %s-duplex",
  12523. (st.speed == 2) ? 1000
  12524. : st.speed ? 100
  12525. : 10,
  12526. st.duplex ? "full" : "half"));
  12527. mac->Control(ARM_ETH_MAC_CONTROL_TX, 1);
  12528. mac->Control(ARM_ETH_MAC_CONTROL_RX, 1);
  12529. } else if ((ifp->state != MG_TCPIP_STATE_DOWN) && !up) { // just went down
  12530. mac->Control(ARM_ETH_MAC_FLUSH,
  12531. ARM_ETH_MAC_FLUSH_TX | ARM_ETH_MAC_FLUSH_RX);
  12532. mac->Control(ARM_ETH_MAC_CONTROL_TX, 0);
  12533. mac->Control(ARM_ETH_MAC_CONTROL_RX, 0);
  12534. }
  12535. return up;
  12536. }
  12537. static void mac_cb(uint32_t ev) {
  12538. if ((ev & ARM_ETH_MAC_EVENT_RX_FRAME) == 0) return;
  12539. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12540. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  12541. if (len >= 60 && len <= 1518) { // proper frame
  12542. char *p;
  12543. if (mg_queue_book(&s_ifp->recv_queue, &p, len) >= len) { // have room
  12544. if ((len = mac->ReadFrame((uint8_t *) p, len)) > 0) { // copy succeeds
  12545. mg_queue_add(&s_ifp->recv_queue, len);
  12546. s_ifp->nrecv++;
  12547. }
  12548. return;
  12549. }
  12550. s_ifp->ndrop++;
  12551. }
  12552. mac->ReadFrame(NULL, 0); // otherwise, discard
  12553. }
  12554. static size_t cmsis_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  12555. ARM_DRIVER_ETH_MAC *mac = &Driver_ETH_MAC0;
  12556. uint32_t len = mac->GetRxFrameSize(); // CRC already stripped
  12557. if (len >= 60 && len <= 1518 &&
  12558. ((len = mac->ReadFrame(buf, (uint32_t) buflen)) > 0))
  12559. return len;
  12560. if (len > 0) mac->ReadFrame(NULL, 0); // discard bad frames
  12561. (void) ifp;
  12562. return 0;
  12563. }
  12564. #endif
  12565. #ifdef MG_ENABLE_LINES
  12566. #line 1 "src/drivers/imxrt.c"
  12567. #endif
  12568. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_IMXRT) && MG_ENABLE_DRIVER_IMXRT
  12569. struct imxrt_enet {
  12570. volatile uint32_t RESERVED0, EIR, EIMR, RESERVED1, RDAR, TDAR, RESERVED2[3],
  12571. ECR, RESERVED3[6], MMFR, MSCR, RESERVED4[7], MIBC, RESERVED5[7], RCR,
  12572. RESERVED6[15], TCR, RESERVED7[7], PALR, PAUR, OPD, TXIC0, TXIC1, TXIC2,
  12573. RESERVED8, RXIC0, RXIC1, RXIC2, RESERVED9[3], IAUR, IALR, GAUR, GALR,
  12574. RESERVED10[7], TFWR, RESERVED11[14], RDSR, TDSR, MRBR[2], RSFL, RSEM,
  12575. RAEM, RAFL, TSEM, TAEM, TAFL, TIPG, FTRL, RESERVED12[3], TACC, RACC,
  12576. RESERVED13[15], RMON_T_PACKETS, RMON_T_BC_PKT, RMON_T_MC_PKT,
  12577. RMON_T_CRC_ALIGN, RMON_T_UNDERSIZE, RMON_T_OVERSIZE, RMON_T_FRAG,
  12578. RMON_T_JAB, RMON_T_COL, RMON_T_P64, RMON_T_P65TO127, RMON_T_P128TO255,
  12579. RMON_T_P256TO511, RMON_T_P512TO1023, RMON_T_P1024TO2048, RMON_T_GTE2048,
  12580. RMON_T_OCTETS, IEEE_T_DROP, IEEE_T_FRAME_OK, IEEE_T_1COL, IEEE_T_MCOL,
  12581. IEEE_T_DEF, IEEE_T_LCOL, IEEE_T_EXCOL, IEEE_T_MACERR, IEEE_T_CSERR,
  12582. IEEE_T_SQE, IEEE_T_FDXFC, IEEE_T_OCTETS_OK, RESERVED14[3], RMON_R_PACKETS,
  12583. RMON_R_BC_PKT, RMON_R_MC_PKT, RMON_R_CRC_ALIGN, RMON_R_UNDERSIZE,
  12584. RMON_R_OVERSIZE, RMON_R_FRAG, RMON_R_JAB, RESERVED15, RMON_R_P64,
  12585. RMON_R_P65TO127, RMON_R_P128TO255, RMON_R_P256TO511, RMON_R_P512TO1023,
  12586. RMON_R_P1024TO2047, RMON_R_GTE2048, RMON_R_OCTETS, IEEE_R_DROP,
  12587. IEEE_R_FRAME_OK, IEEE_R_CRC, IEEE_R_ALIGN, IEEE_R_MACERR, IEEE_R_FDXFC,
  12588. IEEE_R_OCTETS_OK, RESERVED16[71], ATCR, ATVR, ATOFF, ATPER, ATCOR, ATINC,
  12589. ATSTMP, RESERVED17[122], TGSR, TCSR0, TCCR0, TCSR1, TCCR1, TCSR2, TCCR2,
  12590. TCSR3;
  12591. };
  12592. #undef ENET
  12593. #define ENET ((struct imxrt_enet *) (uintptr_t) 0x402D8000U)
  12594. #define ETH_PKT_SIZE 1536 // Max frame size, 64-bit aligned
  12595. #define ETH_DESC_CNT 4 // Descriptors count
  12596. struct enet_desc {
  12597. uint16_t length; // Data length
  12598. uint16_t control; // Control and status
  12599. uint32_t *buffer; // Data ptr
  12600. };
  12601. // TODO(): handle these in a portable compiler-independent CMSIS-friendly way
  12602. #define MG_64BIT_ALIGNED __attribute__((aligned((64U))))
  12603. // Descriptors: in non-cached area (TODO(scaprile)), 64-bit aligned
  12604. // Buffers: 64-bit aligned
  12605. static volatile struct enet_desc s_rxdesc[ETH_DESC_CNT] MG_64BIT_ALIGNED;
  12606. static volatile struct enet_desc s_txdesc[ETH_DESC_CNT] MG_64BIT_ALIGNED;
  12607. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BIT_ALIGNED;
  12608. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] MG_64BIT_ALIGNED;
  12609. static struct mg_tcpip_if *s_ifp; // MIP interface
  12610. enum { PHY_BCR = 0, PHY_BSR = 1, PHY_ID1 = 2, PHY_ID2 = 3 };
  12611. static uint16_t enet_phy_read(uint8_t addr, uint8_t reg) {
  12612. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  12613. ENET->MMFR = (1 << 30) | (2 << 28) | (addr << 23) | (reg << 18) | (2 << 16);
  12614. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  12615. return ENET->MMFR & 0xffff;
  12616. }
  12617. static void enet_phy_write(uint8_t addr, uint8_t reg, uint16_t val) {
  12618. ENET->EIR |= MG_BIT(23); // MII interrupt clear
  12619. ENET->MMFR =
  12620. (1 << 30) | (1 << 28) | (addr << 23) | (reg << 18) | (2 << 16) | val;
  12621. while ((ENET->EIR & MG_BIT(23)) == 0) (void) 0;
  12622. }
  12623. static uint32_t enet_phy_id(uint8_t addr) {
  12624. uint16_t phy_id1 = enet_phy_read(addr, PHY_ID1);
  12625. uint16_t phy_id2 = enet_phy_read(addr, PHY_ID2);
  12626. return (uint32_t) phy_id1 << 16 | phy_id2;
  12627. }
  12628. // MDC clock is generated from IPS Bus clock (ipg_clk); as per 802.3,
  12629. // it must not exceed 2.5MHz
  12630. // The PHY receives the PLL6-generated 50MHz clock
  12631. static bool mg_tcpip_driver_imxrt_init(struct mg_tcpip_if *ifp) {
  12632. struct mg_tcpip_driver_imxrt_data *d =
  12633. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  12634. s_ifp = ifp;
  12635. // Init RX descriptors
  12636. for (int i = 0; i < ETH_DESC_CNT; i++) {
  12637. s_rxdesc[i].control = MG_BIT(15); // Own (E)
  12638. s_rxdesc[i].buffer = (uint32_t *) s_rxbuf[i]; // Point to data buffer
  12639. }
  12640. s_rxdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  12641. // Init TX descriptors
  12642. for (int i = 0; i < ETH_DESC_CNT; i++) {
  12643. // s_txdesc[i].control = MG_BIT(10); // Own (TC)
  12644. s_txdesc[i].buffer = (uint32_t *) s_txbuf[i];
  12645. }
  12646. s_txdesc[ETH_DESC_CNT - 1].control |= MG_BIT(13); // Wrap last descriptor
  12647. ENET->ECR = MG_BIT(0); // Software reset, disable
  12648. while ((ENET->ECR & MG_BIT(0))) (void) 0; // Wait until done
  12649. // Set MDC clock divider. If user told us the value, use it.
  12650. // TODO(): Otherwise, guess (currently assuming max freq)
  12651. int cr = (d == NULL || d->mdc_cr < 0) ? 24 : d->mdc_cr;
  12652. ENET->MSCR = (1 << 8) | ((cr & 0x3f) << 1); // HOLDTIME 2 clks
  12653. enet_phy_write(d->phy_addr, PHY_BCR, MG_BIT(15)); // Reset PHY
  12654. enet_phy_write(d->phy_addr, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  12655. // PHY: Enable 50 MHz external ref clock at XI (preserve defaults)
  12656. uint32_t id = enet_phy_id(d->phy_addr);
  12657. MG_INFO(("PHY ID: %#04x %#04x", (uint16_t) (id >> 16), (uint16_t) id));
  12658. // 2000 a140 - TI DP83825I
  12659. // 0007 c0fx - LAN8720
  12660. // 0022 1561 - KSZ8081RNB
  12661. if ((id & 0xffff0000) == 0x220000) { // KSZ8081RNB, like EVK-RTxxxx boards
  12662. enet_phy_write(d->phy_addr, 31,
  12663. MG_BIT(15) | MG_BIT(8) | MG_BIT(7)); // PC2R
  12664. } else if ((id & 0xffff0000) == 0x20000000) { // DP83825I, like Teensy4.1
  12665. enet_phy_write(d->phy_addr, 23, 0x81); // 50MHz clock input
  12666. enet_phy_write(d->phy_addr, 24, 0x280); // LED status, active high
  12667. } else { // Default to LAN8720
  12668. MG_INFO(("Defaulting to LAN8720 PHY...")); // TODO()
  12669. }
  12670. // Select RMII mode, 100M, keep CRC, set max rx length, disable loop
  12671. ENET->RCR = (1518 << 16) | MG_BIT(8) | MG_BIT(2);
  12672. // ENET->RCR |= MG_BIT(3); // Receive all
  12673. ENET->TCR = MG_BIT(2); // Full-duplex
  12674. ENET->RDSR = (uint32_t) (uintptr_t) s_rxdesc;
  12675. ENET->TDSR = (uint32_t) (uintptr_t) s_txdesc;
  12676. ENET->MRBR[0] = ETH_PKT_SIZE; // Same size for RX/TX buffers
  12677. // MAC address filtering (bytes in reversed order)
  12678. ENET->PAUR = ((uint32_t) ifp->mac[4] << 24U) | (uint32_t) ifp->mac[5] << 16U;
  12679. ENET->PALR = (uint32_t) (ifp->mac[0] << 24U) |
  12680. ((uint32_t) ifp->mac[1] << 16U) |
  12681. ((uint32_t) ifp->mac[2] << 8U) | ifp->mac[3];
  12682. ENET->ECR = MG_BIT(8) | MG_BIT(1); // Little-endian CPU, Enable
  12683. ENET->EIMR = MG_BIT(25); // Set interrupt mask
  12684. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  12685. ENET->TDAR = MG_BIT(24); // Transmit Descriptors have changed
  12686. // ENET->OPD = 0x10014;
  12687. return true;
  12688. }
  12689. // Transmit frame
  12690. static size_t mg_tcpip_driver_imxrt_tx(const void *buf, size_t len,
  12691. struct mg_tcpip_if *ifp) {
  12692. static int s_txno; // Current descriptor index
  12693. if (len > sizeof(s_txbuf[ETH_DESC_CNT])) {
  12694. ifp->nerr++;
  12695. MG_ERROR(("Frame too big, %ld", (long) len));
  12696. len = (size_t) -1; // fail
  12697. } else if ((s_txdesc[s_txno].control & MG_BIT(15))) {
  12698. MG_ERROR(("No descriptors available"));
  12699. len = 0; // retry later
  12700. } else {
  12701. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  12702. s_txdesc[s_txno].length = (uint16_t) len; // Set data len
  12703. // Table 37-34, R, L, TC (Ready, last, transmit CRC after frame
  12704. s_txdesc[s_txno].control |=
  12705. (uint16_t) (MG_BIT(15) | MG_BIT(11) | MG_BIT(10));
  12706. ENET->TDAR = MG_BIT(24); // Descriptor ring updated
  12707. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  12708. }
  12709. (void) ifp;
  12710. return len;
  12711. }
  12712. static bool mg_tcpip_driver_imxrt_up(struct mg_tcpip_if *ifp) {
  12713. struct mg_tcpip_driver_imxrt_data *d =
  12714. (struct mg_tcpip_driver_imxrt_data *) ifp->driver_data;
  12715. uint32_t bsr = enet_phy_read(d->phy_addr, PHY_BSR);
  12716. bool up = bsr & MG_BIT(2) ? 1 : 0;
  12717. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  12718. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  12719. // if(link is slow or half) set flags otherwise
  12720. // reg = tmp
  12721. uint32_t tcr = ENET->TCR | MG_BIT(2); // Full-duplex
  12722. uint32_t rcr = ENET->RCR & ~MG_BIT(9); // 100M
  12723. uint32_t phy_id = enet_phy_id(d->phy_addr);
  12724. if ((phy_id & 0xffff0000) == 0x220000) { // KSZ8081RNB
  12725. uint16_t pc1r = enet_phy_read(d->phy_addr, 30); // Read PC1R
  12726. if ((pc1r & 3) == 1) rcr |= MG_BIT(9); // 10M
  12727. if ((pc1r & MG_BIT(2)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12728. } else if ((phy_id & 0xffff0000) == 0x20000000) { // DP83825I
  12729. uint16_t physts = enet_phy_read(d->phy_addr, 16); // Read PHYSTS
  12730. if (physts & MG_BIT(1)) rcr |= MG_BIT(9); // 10M
  12731. if ((physts & MG_BIT(2)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12732. } else { // Default to LAN8720
  12733. uint16_t scsr = enet_phy_read(d->phy_addr, 31); // Read CSCR
  12734. if ((scsr & MG_BIT(3)) == 0) rcr |= MG_BIT(9); // 10M
  12735. if ((scsr & MG_BIT(4)) == 0) tcr &= ~MG_BIT(2); // Half-duplex
  12736. }
  12737. ENET->TCR = tcr; // IRQ handler does not fiddle with these registers
  12738. ENET->RCR = rcr;
  12739. MG_DEBUG(("Link is %uM %s-duplex", rcr & MG_BIT(9) ? 10 : 100,
  12740. tcr & MG_BIT(2) ? "full" : "half"));
  12741. }
  12742. return up;
  12743. }
  12744. void ENET_IRQHandler(void);
  12745. static uint32_t s_rxno;
  12746. void ENET_IRQHandler(void) {
  12747. ENET->EIR = MG_BIT(25); // Ack IRQ
  12748. // Frame received, loop
  12749. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  12750. uint32_t r = s_rxdesc[s_rxno].control;
  12751. if (r & MG_BIT(15)) break; // exit when done
  12752. // skip partial/errored frames (Table 37-32)
  12753. if ((r & MG_BIT(11)) &&
  12754. !(r & (MG_BIT(5) | MG_BIT(4) | MG_BIT(2) | MG_BIT(1) | MG_BIT(0)))) {
  12755. size_t len = s_rxdesc[s_rxno].length;
  12756. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  12757. }
  12758. s_rxdesc[s_rxno].control |= MG_BIT(15);
  12759. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  12760. }
  12761. ENET->RDAR = MG_BIT(24); // Receive Descriptors have changed
  12762. // If b24 == 0, descriptors were exhausted and probably frames were dropped
  12763. }
  12764. struct mg_tcpip_driver mg_tcpip_driver_imxrt = {mg_tcpip_driver_imxrt_init,
  12765. mg_tcpip_driver_imxrt_tx, NULL,
  12766. mg_tcpip_driver_imxrt_up};
  12767. #endif
  12768. #ifdef MG_ENABLE_LINES
  12769. #line 1 "src/drivers/same54.c"
  12770. #endif
  12771. #if defined(MG_ENABLE_DRIVER_SAME54) && MG_ENABLE_DRIVER_SAME54
  12772. #include <sam.h>
  12773. #define ETH_PKT_SIZE 1536 // Max frame size
  12774. #define ETH_DESC_CNT 4 // Descriptors count
  12775. #define ETH_DS 2 // Descriptor size (words)
  12776. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  12777. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE];
  12778. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  12779. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  12780. static uint8_t s_txno; // Current TX descriptor
  12781. static uint8_t s_rxno; // Current RX descriptor
  12782. static struct mg_tcpip_if *s_ifp; // MIP interface
  12783. enum { PHY_ADDR = 0, PHY_BCR = 0, PHY_BSR = 1 };
  12784. #define PHY_BCR_DUPLEX_MODE_Msk MG_BIT(8)
  12785. #define PHY_BCR_SPEED_Msk MG_BIT(13)
  12786. #define PHY_BSR_LINK_STATUS_Msk MG_BIT(2)
  12787. static uint16_t eth_read_phy(uint8_t addr, uint8_t reg) {
  12788. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk |
  12789. GMAC_MAN_OP(2) | // Setting the read operation
  12790. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  12791. GMAC_MAN_REGA(reg); // Setting the register
  12792. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)) (void) 0;
  12793. return GMAC_REGS->GMAC_MAN & GMAC_MAN_DATA_Msk; // Getting the read value
  12794. }
  12795. #if 0
  12796. static void eth_write_phy(uint8_t addr, uint8_t reg, uint16_t val) {
  12797. GMAC_REGS->GMAC_MAN = GMAC_MAN_CLTTO_Msk | GMAC_MAN_OP(1) | // Setting the write operation
  12798. GMAC_MAN_WTN(2) | GMAC_MAN_PHYA(addr) | // PHY address
  12799. GMAC_MAN_REGA(reg) | GMAC_MAN_DATA(val); // Setting the register
  12800. while (!(GMAC_REGS->GMAC_NSR & GMAC_NSR_IDLE_Msk)); // Waiting until the write op is complete
  12801. }
  12802. #endif
  12803. int get_clock_rate(struct mg_tcpip_driver_same54_data *d) {
  12804. if (d && d->mdc_cr >= 0 && d->mdc_cr <= 5) {
  12805. return d->mdc_cr;
  12806. } else {
  12807. // get MCLK from GCLK_GENERATOR 0
  12808. uint32_t div = 512;
  12809. uint32_t mclk;
  12810. if (!(GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_DIVSEL_Msk)) {
  12811. div = ((GCLK_REGS->GCLK_GENCTRL[0] & 0x00FF0000) >> 16);
  12812. if (div == 0) div = 1;
  12813. }
  12814. switch (GCLK_REGS->GCLK_GENCTRL[0] & GCLK_GENCTRL_SRC_Msk) {
  12815. case GCLK_GENCTRL_SRC_XOSC0_Val:
  12816. mclk = 32000000UL; /* 32MHz */
  12817. break;
  12818. case GCLK_GENCTRL_SRC_XOSC1_Val:
  12819. mclk = 32000000UL; /* 32MHz */
  12820. break;
  12821. case GCLK_GENCTRL_SRC_OSCULP32K_Val: mclk = 32000UL; break;
  12822. case GCLK_GENCTRL_SRC_XOSC32K_Val: mclk = 32000UL; break;
  12823. case GCLK_GENCTRL_SRC_DFLL_Val:
  12824. mclk = 48000000UL; /* 48MHz */
  12825. break;
  12826. case GCLK_GENCTRL_SRC_DPLL0_Val:
  12827. mclk = 200000000UL; /* 200MHz */
  12828. break;
  12829. case GCLK_GENCTRL_SRC_DPLL1_Val:
  12830. mclk = 200000000UL; /* 200MHz */
  12831. break;
  12832. default: mclk = 200000000UL; /* 200MHz */
  12833. }
  12834. mclk /= div;
  12835. uint8_t crs[] = {0, 1, 2, 3, 4, 5}; // GMAC->NCFGR::CLK values
  12836. uint8_t dividers[] = {8, 16, 32, 48, 64, 96}; // Respective CLK dividers
  12837. for (int i = 0; i < 6; i++) {
  12838. if (mclk / dividers[i] <= 2375000UL /* 2.5MHz - 5% */) {
  12839. return crs[i];
  12840. }
  12841. }
  12842. return 5;
  12843. }
  12844. }
  12845. static bool mg_tcpip_driver_same54_init(struct mg_tcpip_if *ifp) {
  12846. struct mg_tcpip_driver_same54_data *d =
  12847. (struct mg_tcpip_driver_same54_data *) ifp->driver_data;
  12848. s_ifp = ifp;
  12849. MCLK_REGS->MCLK_APBCMASK |= MCLK_APBCMASK_GMAC_Msk;
  12850. MCLK_REGS->MCLK_AHBMASK |= MCLK_AHBMASK_GMAC_Msk;
  12851. GMAC_REGS->GMAC_NCFGR = GMAC_NCFGR_CLK(get_clock_rate(d)); // Set MDC divider
  12852. GMAC_REGS->GMAC_NCR = 0; // Disable RX & TX
  12853. GMAC_REGS->GMAC_NCR |= GMAC_NCR_MPE_Msk; // Enable MDC & MDIO
  12854. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init TX descriptors
  12855. s_txdesc[i][0] = (uint32_t) s_txbuf[i]; // Point to data buffer
  12856. s_txdesc[i][1] = MG_BIT(31); // OWN bit
  12857. }
  12858. s_txdesc[ETH_DESC_CNT - 1][1] |= MG_BIT(30); // Last tx descriptor - wrap
  12859. GMAC_REGS->GMAC_DCFGR = GMAC_DCFGR_DRBS(0x18) // DMA recv buf 1536
  12860. | GMAC_DCFGR_RXBMS(GMAC_DCFGR_RXBMS_FULL_Val) |
  12861. GMAC_DCFGR_TXPBMS(1); // See #2487
  12862. for (int i = 0; i < ETH_DESC_CNT; i++) { // Init RX descriptors
  12863. s_rxdesc[i][0] = (uint32_t) s_rxbuf[i]; // Address of the data buffer
  12864. s_rxdesc[i][1] = 0; // Clear status
  12865. }
  12866. s_rxdesc[ETH_DESC_CNT - 1][0] |= MG_BIT(1); // Last rx descriptor - wrap
  12867. GMAC_REGS->GMAC_TBQB = (uint32_t) s_txdesc; // about the descriptor addresses
  12868. GMAC_REGS->GMAC_RBQB = (uint32_t) s_rxdesc; // Let the controller know
  12869. GMAC_REGS->SA[0].GMAC_SAB =
  12870. MG_U32(ifp->mac[3], ifp->mac[2], ifp->mac[1], ifp->mac[0]);
  12871. GMAC_REGS->SA[0].GMAC_SAT = MG_U32(0, 0, ifp->mac[5], ifp->mac[4]);
  12872. GMAC_REGS->GMAC_UR &= ~GMAC_UR_MII_Msk; // Disable MII, use RMII
  12873. GMAC_REGS->GMAC_NCFGR |= GMAC_NCFGR_MAXFS_Msk | GMAC_NCFGR_MTIHEN_Msk |
  12874. GMAC_NCFGR_EFRHD_Msk | GMAC_NCFGR_CAF_Msk;
  12875. GMAC_REGS->GMAC_TSR = GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk |
  12876. GMAC_TSR_TXCOMP_Msk | GMAC_TSR_TFC_Msk |
  12877. GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  12878. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk;
  12879. GMAC_REGS->GMAC_RSR = GMAC_RSR_HNO_Msk | GMAC_RSR_RXOVR_Msk |
  12880. GMAC_RSR_REC_Msk | GMAC_RSR_BNA_Msk;
  12881. GMAC_REGS->GMAC_IDR = ~0U; // Disable interrupts, then enable required
  12882. GMAC_REGS->GMAC_IER = GMAC_IER_HRESP_Msk | GMAC_IER_ROVR_Msk |
  12883. GMAC_IER_TCOMP_Msk | GMAC_IER_TFC_Msk |
  12884. GMAC_IER_RLEX_Msk | GMAC_IER_TUR_Msk |
  12885. GMAC_IER_RXUBR_Msk | GMAC_IER_RCOMP_Msk;
  12886. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TXEN_Msk | GMAC_NCR_RXEN_Msk;
  12887. NVIC_EnableIRQ(GMAC_IRQn);
  12888. return true;
  12889. }
  12890. static size_t mg_tcpip_driver_same54_tx(const void *buf, size_t len,
  12891. struct mg_tcpip_if *ifp) {
  12892. if (len > sizeof(s_txbuf[s_txno])) {
  12893. MG_ERROR(("Frame too big, %ld", (long) len));
  12894. len = 0; // Frame is too big
  12895. } else if ((s_txdesc[s_txno][1] & MG_BIT(31)) == 0) {
  12896. ifp->nerr++;
  12897. MG_ERROR(("No free descriptors"));
  12898. len = 0; // All descriptors are busy, fail
  12899. } else {
  12900. uint32_t status = len | MG_BIT(15); // Frame length, last chunk
  12901. if (s_txno == ETH_DESC_CNT - 1) status |= MG_BIT(30); // wrap
  12902. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  12903. s_txdesc[s_txno][1] = status;
  12904. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  12905. }
  12906. __DSB(); // Ensure descriptors have been written
  12907. GMAC_REGS->GMAC_NCR |= GMAC_NCR_TSTART_Msk; // Enable transmission
  12908. return len;
  12909. }
  12910. static bool mg_tcpip_driver_same54_up(struct mg_tcpip_if *ifp) {
  12911. uint16_t bsr = eth_read_phy(PHY_ADDR, PHY_BSR);
  12912. bool up = bsr & PHY_BSR_LINK_STATUS_Msk ? 1 : 0;
  12913. // If PHY is ready, update NCFGR accordingly
  12914. if (ifp->state == MG_TCPIP_STATE_DOWN && up) {
  12915. uint16_t bcr = eth_read_phy(PHY_ADDR, PHY_BCR);
  12916. bool fd = bcr & PHY_BCR_DUPLEX_MODE_Msk ? 1 : 0;
  12917. bool spd = bcr & PHY_BCR_SPEED_Msk ? 1 : 0;
  12918. GMAC_REGS->GMAC_NCFGR =
  12919. (GMAC_REGS->GMAC_NCFGR & ~(GMAC_NCFGR_SPD_Msk | PHY_BCR_SPEED_Msk)) |
  12920. GMAC_NCFGR_SPD(spd) | GMAC_NCFGR_FD(fd);
  12921. }
  12922. return up;
  12923. }
  12924. void GMAC_Handler(void);
  12925. void GMAC_Handler(void) {
  12926. uint32_t isr = GMAC_REGS->GMAC_ISR;
  12927. uint32_t rsr = GMAC_REGS->GMAC_RSR;
  12928. uint32_t tsr = GMAC_REGS->GMAC_TSR;
  12929. if (isr & GMAC_ISR_RCOMP_Msk) {
  12930. if (rsr & GMAC_ISR_RCOMP_Msk) {
  12931. for (uint8_t i = 0; i < ETH_DESC_CNT; i++) {
  12932. if ((s_rxdesc[s_rxno][0] & MG_BIT(0)) == 0) break;
  12933. size_t len = s_rxdesc[s_rxno][1] & (MG_BIT(13) - 1);
  12934. mg_tcpip_qwrite(s_rxbuf[s_rxno], len, s_ifp);
  12935. s_rxdesc[s_rxno][0] &= ~MG_BIT(0); // Disown
  12936. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  12937. }
  12938. }
  12939. }
  12940. if ((tsr & (GMAC_TSR_HRESP_Msk | GMAC_TSR_UND_Msk | GMAC_TSR_TXCOMP_Msk |
  12941. GMAC_TSR_TFC_Msk | GMAC_TSR_TXGO_Msk | GMAC_TSR_RLE_Msk |
  12942. GMAC_TSR_COL_Msk | GMAC_TSR_UBR_Msk)) != 0) {
  12943. // MG_INFO((" --> %#x %#x", s_txdesc[s_txno][1], tsr));
  12944. if (!(s_txdesc[s_txno][1] & MG_BIT(31))) s_txdesc[s_txno][1] |= MG_BIT(31);
  12945. }
  12946. GMAC_REGS->GMAC_RSR = rsr;
  12947. GMAC_REGS->GMAC_TSR = tsr;
  12948. }
  12949. struct mg_tcpip_driver mg_tcpip_driver_same54 = {
  12950. mg_tcpip_driver_same54_init, mg_tcpip_driver_same54_tx, NULL,
  12951. mg_tcpip_driver_same54_up};
  12952. #endif
  12953. #ifdef MG_ENABLE_LINES
  12954. #line 1 "src/drivers/stm32f.c"
  12955. #endif
  12956. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
  12957. MG_ENABLE_DRIVER_STM32F
  12958. struct stm32f_eth {
  12959. volatile uint32_t MACCR, MACFFR, MACHTHR, MACHTLR, MACMIIAR, MACMIIDR, MACFCR,
  12960. MACVLANTR, RESERVED0[2], MACRWUFFR, MACPMTCSR, RESERVED1, MACDBGR, MACSR,
  12961. MACIMR, MACA0HR, MACA0LR, MACA1HR, MACA1LR, MACA2HR, MACA2LR, MACA3HR,
  12962. MACA3LR, RESERVED2[40], MMCCR, MMCRIR, MMCTIR, MMCRIMR, MMCTIMR,
  12963. RESERVED3[14], MMCTGFSCCR, MMCTGFMSCCR, RESERVED4[5], MMCTGFCR,
  12964. RESERVED5[10], MMCRFCECR, MMCRFAECR, RESERVED6[10], MMCRGUFCR,
  12965. RESERVED7[334], PTPTSCR, PTPSSIR, PTPTSHR, PTPTSLR, PTPTSHUR, PTPTSLUR,
  12966. PTPTSAR, PTPTTHR, PTPTTLR, RESERVED8, PTPTSSR, PTPPPSCR, RESERVED9[564],
  12967. DMABMR, DMATPDR, DMARPDR, DMARDLAR, DMATDLAR, DMASR, DMAOMR, DMAIER,
  12968. DMAMFBOCR, DMARSWTR, RESERVED10[8], DMACHTDR, DMACHRDR, DMACHTBAR,
  12969. DMACHRBAR;
  12970. };
  12971. #undef ETH
  12972. #define ETH ((struct stm32f_eth *) (uintptr_t) 0x40028000)
  12973. #define ETH_PKT_SIZE 1540 // Max frame size
  12974. #define ETH_DESC_CNT 4 // Descriptors count
  12975. #define ETH_DS 4 // Descriptor size (words)
  12976. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  12977. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  12978. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  12979. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  12980. static uint8_t s_txno; // Current TX descriptor
  12981. static uint8_t s_rxno; // Current RX descriptor
  12982. static struct mg_tcpip_if *s_ifp; // MIP interface
  12983. enum { PHY_BCR = 0, PHY_BSR = 1, PHY_ID1 = 2, PHY_ID2 = 3, PHY_CSCR = 31 };
  12984. static uint32_t eth_read_phy(uint8_t addr, uint8_t reg) {
  12985. ETH->MACMIIAR &= (7 << 2);
  12986. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  12987. ETH->MACMIIAR |= MG_BIT(0);
  12988. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  12989. return ETH->MACMIIDR;
  12990. }
  12991. static void eth_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  12992. ETH->MACMIIDR = val;
  12993. ETH->MACMIIAR &= (7 << 2);
  12994. ETH->MACMIIAR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  12995. ETH->MACMIIAR |= MG_BIT(0);
  12996. while (ETH->MACMIIAR & MG_BIT(0)) (void) 0;
  12997. }
  12998. static uint32_t get_hclk(void) {
  12999. struct rcc {
  13000. volatile uint32_t CR, PLLCFGR, CFGR;
  13001. } *rcc = (struct rcc *) 0x40023800;
  13002. uint32_t clk = 0, hsi = 16000000 /* 16 MHz */, hse = 8000000 /* 8MHz */;
  13003. if (rcc->CFGR & (1 << 2)) {
  13004. clk = hse;
  13005. } else if (rcc->CFGR & (1 << 3)) {
  13006. uint32_t vco, m, n, p;
  13007. m = (rcc->PLLCFGR & (0x3f << 0)) >> 0;
  13008. n = (rcc->PLLCFGR & (0x1ff << 6)) >> 6;
  13009. p = (((rcc->PLLCFGR & (3 << 16)) >> 16) + 1) * 2;
  13010. clk = (rcc->PLLCFGR & (1 << 22)) ? hse : hsi;
  13011. vco = (uint32_t) ((uint64_t) clk * n / m);
  13012. clk = vco / p;
  13013. } else {
  13014. clk = hsi;
  13015. }
  13016. uint32_t hpre = (rcc->CFGR & (15 << 4)) >> 4;
  13017. if (hpre < 8) return clk;
  13018. uint8_t ahbptab[8] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  13019. return ((uint32_t) clk) >> ahbptab[hpre - 8];
  13020. }
  13021. // Guess CR from HCLK. MDC clock is generated from HCLK (AHB); as per 802.3,
  13022. // it must not exceed 2.5MHz As the AHB clock can be (and usually is) derived
  13023. // from the HSI (internal RC), and it can go above specs, the datasheets
  13024. // specify a range of frequencies and activate one of a series of dividers to
  13025. // keep the MDC clock safely below 2.5MHz. We guess a divider setting based on
  13026. // HCLK with a +5% drift. If the user uses a different clock from our
  13027. // defaults, needs to set the macros on top Valid for STM32F74xxx/75xxx
  13028. // (38.8.1) and STM32F42xxx/43xxx (33.8.1) (both 4.5% worst case drift)
  13029. static int guess_mdc_cr(void) {
  13030. uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMIIAR::CR values
  13031. uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  13032. uint32_t hclk = get_hclk(); // Guess system HCLK
  13033. int result = -1; // Invalid CR value
  13034. if (hclk < 25000000) {
  13035. MG_ERROR(("HCLK too low"));
  13036. } else {
  13037. for (int i = 0; i < 6; i++) {
  13038. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  13039. result = crs[i];
  13040. break;
  13041. }
  13042. }
  13043. if (result < 0) MG_ERROR(("HCLK too high"));
  13044. }
  13045. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  13046. return result;
  13047. }
  13048. static bool mg_tcpip_driver_stm32f_init(struct mg_tcpip_if *ifp) {
  13049. struct mg_tcpip_driver_stm32f_data *d =
  13050. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  13051. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  13052. s_ifp = ifp;
  13053. // Init RX descriptors
  13054. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13055. s_rxdesc[i][0] = MG_BIT(31); // Own
  13056. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  13057. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13058. s_rxdesc[i][3] =
  13059. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13060. }
  13061. // Init TX descriptors
  13062. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13063. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13064. s_txdesc[i][3] =
  13065. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13066. }
  13067. ETH->DMABMR |= MG_BIT(0); // Software reset
  13068. while ((ETH->DMABMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  13069. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13070. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13071. ETH->MACMIIAR = ((uint32_t) cr & 7) << 2;
  13072. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  13073. // hardware checksum. Therefore, descriptor size is 4, not 8
  13074. // ETH->DMABMR = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) |
  13075. // MG_BIT(25);
  13076. ETH->MACIMR = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  13077. ETH->MACFCR = MG_BIT(7); // Disable zero quarta pause
  13078. // ETH->MACFFR = MG_BIT(31); // Receive all
  13079. eth_write_phy(phy_addr, PHY_BCR, MG_BIT(15)); // Reset PHY
  13080. eth_write_phy(phy_addr, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  13081. ETH->DMARDLAR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  13082. ETH->DMATDLAR = (uint32_t) (uintptr_t) s_txdesc; // RX descriptors
  13083. ETH->DMAIER = MG_BIT(6) | MG_BIT(16); // RIE, NISE
  13084. ETH->MACCR =
  13085. MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  13086. ETH->DMAOMR =
  13087. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  13088. MG_DEBUG(("PHY ID: %#04hx %#04hx", eth_read_phy(phy_addr, PHY_ID1),
  13089. eth_read_phy(phy_addr, PHY_ID2)));
  13090. // MAC address filtering
  13091. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13092. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  13093. ((uint32_t) ifp->mac[2] << 16) |
  13094. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13095. return true;
  13096. }
  13097. static size_t mg_tcpip_driver_stm32f_tx(const void *buf, size_t len,
  13098. struct mg_tcpip_if *ifp) {
  13099. if (len > sizeof(s_txbuf[s_txno])) {
  13100. MG_ERROR(("Frame too big, %ld", (long) len));
  13101. len = 0; // Frame is too big
  13102. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  13103. ifp->nerr++;
  13104. MG_ERROR(("No free descriptors"));
  13105. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long) ETH->DMASR);
  13106. len = 0; // All descriptors are busy, fail
  13107. } else {
  13108. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13109. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  13110. s_txdesc[s_txno][0] = MG_BIT(20) | MG_BIT(28) | MG_BIT(29); // Chain,FS,LS
  13111. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13112. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13113. }
  13114. MG_DSB(); // ensure descriptors have been written
  13115. ETH->DMASR = MG_BIT(2) | MG_BIT(5); // Clear any prior TBUS/TUS
  13116. ETH->DMATPDR = 0; // and resume
  13117. return len;
  13118. }
  13119. static bool mg_tcpip_driver_stm32f_up(struct mg_tcpip_if *ifp) {
  13120. struct mg_tcpip_driver_stm32f_data *d =
  13121. (struct mg_tcpip_driver_stm32f_data *) ifp->driver_data;
  13122. uint8_t phy_addr = d == NULL ? 0 : d->phy_addr;
  13123. uint32_t bsr = eth_read_phy(phy_addr, PHY_BSR);
  13124. bool up = bsr & MG_BIT(2) ? 1 : 0;
  13125. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13126. uint32_t scsr = eth_read_phy(phy_addr, PHY_CSCR);
  13127. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13128. // if(link is slow or half) set flags otherwise
  13129. // reg = tmp
  13130. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  13131. if ((scsr & MG_BIT(3)) == 0) maccr &= ~MG_BIT(14); // 10M
  13132. if ((scsr & MG_BIT(4)) == 0) maccr &= ~MG_BIT(11); // Half-duplex
  13133. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  13134. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  13135. maccr & MG_BIT(11) ? "full" : "half"));
  13136. }
  13137. return up;
  13138. }
  13139. #ifdef __riscv
  13140. __attribute__((interrupt())) // For RISCV CH32V307, which share the same MAC
  13141. #endif
  13142. void ETH_IRQHandler(void);
  13143. void ETH_IRQHandler(void) {
  13144. if (ETH->DMASR & MG_BIT(6)) { // Frame received, loop
  13145. ETH->DMASR = MG_BIT(16) | MG_BIT(6); // Clear flag
  13146. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13147. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  13148. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) ==
  13149. (MG_BIT(8) | MG_BIT(9))) &&
  13150. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  13151. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  13152. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  13153. // ETH->DMASR);
  13154. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13155. }
  13156. s_rxdesc[s_rxno][0] = MG_BIT(31);
  13157. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13158. }
  13159. }
  13160. // Cleanup flags
  13161. ETH->DMASR = MG_BIT(16) // NIS, normal interrupt summary
  13162. | MG_BIT(7); // Clear possible RBUS while processing
  13163. ETH->DMARPDR = 0; // and resume RX
  13164. }
  13165. struct mg_tcpip_driver mg_tcpip_driver_stm32f = {
  13166. mg_tcpip_driver_stm32f_init, mg_tcpip_driver_stm32f_tx, NULL,
  13167. mg_tcpip_driver_stm32f_up};
  13168. #endif
  13169. #ifdef MG_ENABLE_LINES
  13170. #line 1 "src/drivers/stm32h.c"
  13171. #endif
  13172. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32H) && \
  13173. MG_ENABLE_DRIVER_STM32H
  13174. struct stm32h_eth {
  13175. volatile uint32_t MACCR, MACECR, MACPFR, MACWTR, MACHT0R, MACHT1R,
  13176. RESERVED1[14], MACVTR, RESERVED2, MACVHTR, RESERVED3, MACVIR, MACIVIR,
  13177. RESERVED4[2], MACTFCR, RESERVED5[7], MACRFCR, RESERVED6[7], MACISR,
  13178. MACIER, MACRXTXSR, RESERVED7, MACPCSR, MACRWKPFR, RESERVED8[2], MACLCSR,
  13179. MACLTCR, MACLETR, MAC1USTCR, RESERVED9[12], MACVR, MACDR, RESERVED10,
  13180. MACHWF0R, MACHWF1R, MACHWF2R, RESERVED11[54], MACMDIOAR, MACMDIODR,
  13181. RESERVED12[2], MACARPAR, RESERVED13[59], MACA0HR, MACA0LR, MACA1HR,
  13182. MACA1LR, MACA2HR, MACA2LR, MACA3HR, MACA3LR, RESERVED14[248], MMCCR,
  13183. MMCRIR, MMCTIR, MMCRIMR, MMCTIMR, RESERVED15[14], MMCTSCGPR, MMCTMCGPR,
  13184. RESERVED16[5], MMCTPCGR, RESERVED17[10], MMCRCRCEPR, MMCRAEPR,
  13185. RESERVED18[10], MMCRUPGR, RESERVED19[9], MMCTLPIMSTR, MMCTLPITCR,
  13186. MMCRLPIMSTR, MMCRLPITCR, RESERVED20[65], MACL3L4C0R, MACL4A0R,
  13187. RESERVED21[2], MACL3A0R0R, MACL3A1R0R, MACL3A2R0R, MACL3A3R0R,
  13188. RESERVED22[4], MACL3L4C1R, MACL4A1R, RESERVED23[2], MACL3A0R1R,
  13189. MACL3A1R1R, MACL3A2R1R, MACL3A3R1R, RESERVED24[108], MACTSCR, MACSSIR,
  13190. MACSTSR, MACSTNR, MACSTSUR, MACSTNUR, MACTSAR, RESERVED25, MACTSSR,
  13191. RESERVED26[3], MACTTSSNR, MACTTSSSR, RESERVED27[2], MACACR, RESERVED28,
  13192. MACATSNR, MACATSSR, MACTSIACR, MACTSEACR, MACTSICNR, MACTSECNR,
  13193. RESERVED29[4], MACPPSCR, RESERVED30[3], MACPPSTTSR, MACPPSTTNR, MACPPSIR,
  13194. MACPPSWR, RESERVED31[12], MACPOCR, MACSPI0R, MACSPI1R, MACSPI2R, MACLMIR,
  13195. RESERVED32[11], MTLOMR, RESERVED33[7], MTLISR, RESERVED34[55], MTLTQOMR,
  13196. MTLTQUR, MTLTQDR, RESERVED35[8], MTLQICSR, MTLRQOMR, MTLRQMPOCR, MTLRQDR,
  13197. RESERVED36[177], DMAMR, DMASBMR, DMAISR, DMADSR, RESERVED37[60], DMACCR,
  13198. DMACTCR, DMACRCR, RESERVED38[2], DMACTDLAR, RESERVED39, DMACRDLAR,
  13199. DMACTDTPR, RESERVED40, DMACRDTPR, DMACTDRLR, DMACRDRLR, DMACIER,
  13200. DMACRIWTR, DMACSFCSR, RESERVED41, DMACCATDR, RESERVED42, DMACCARDR,
  13201. RESERVED43, DMACCATBR, RESERVED44, DMACCARBR, DMACSR, RESERVED45[2],
  13202. DMACMFCR;
  13203. };
  13204. #undef ETH
  13205. #define ETH \
  13206. ((struct stm32h_eth *) (uintptr_t) (0x40000000UL + 0x00020000UL + 0x8000UL))
  13207. #define ETH_PKT_SIZE 1540 // Max frame size
  13208. #define ETH_DESC_CNT 4 // Descriptors count
  13209. #define ETH_DS 4 // Descriptor size (words)
  13210. static volatile uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  13211. static volatile uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  13212. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  13213. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  13214. static struct mg_tcpip_if *s_ifp; // MIP interface
  13215. enum {
  13216. PHY_ADDR = 0,
  13217. PHY_BCR = 0,
  13218. PHY_BSR = 1,
  13219. PHY_CSCR = 31
  13220. }; // PHY constants
  13221. static uint32_t eth_read_phy(uint8_t addr, uint8_t reg) {
  13222. ETH->MACMDIOAR &= (0xF << 8);
  13223. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 3 << 2;
  13224. ETH->MACMDIOAR |= MG_BIT(0);
  13225. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  13226. return ETH->MACMDIODR;
  13227. }
  13228. static void eth_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  13229. ETH->MACMDIODR = val;
  13230. ETH->MACMDIOAR &= (0xF << 8);
  13231. ETH->MACMDIOAR |= ((uint32_t) addr << 21) | ((uint32_t) reg << 16) | 1 << 2;
  13232. ETH->MACMDIOAR |= MG_BIT(0);
  13233. while (ETH->MACMDIOAR & MG_BIT(0)) (void) 0;
  13234. }
  13235. static uint32_t get_hclk(void) {
  13236. struct rcc {
  13237. volatile uint32_t CR, HSICFGR, CRRCR, CSICFGR, CFGR, RESERVED1, D1CFGR,
  13238. D2CFGR, D3CFGR, RESERVED2, PLLCKSELR, PLLCFGR, PLL1DIVR, PLL1FRACR,
  13239. PLL2DIVR, PLL2FRACR, PLL3DIVR, PLL3FRACR, RESERVED3, D1CCIPR, D2CCIP1R,
  13240. D2CCIP2R, D3CCIPR, RESERVED4, CIER, CIFR, CICR, RESERVED5, BDCR, CSR,
  13241. RESERVED6, AHB3RSTR, AHB1RSTR, AHB2RSTR, AHB4RSTR, APB3RSTR, APB1LRSTR,
  13242. APB1HRSTR, APB2RSTR, APB4RSTR, GCR, RESERVED8, D3AMR, RESERVED11[9],
  13243. RSR, AHB3ENR, AHB1ENR, AHB2ENR, AHB4ENR, APB3ENR, APB1LENR, APB1HENR,
  13244. APB2ENR, APB4ENR, RESERVED12, AHB3LPENR, AHB1LPENR, AHB2LPENR,
  13245. AHB4LPENR, APB3LPENR, APB1LLPENR, APB1HLPENR, APB2LPENR, APB4LPENR,
  13246. RESERVED13[4];
  13247. } *rcc = ((struct rcc *) (0x40000000 + 0x18020000 + 0x4400));
  13248. uint32_t clk = 0, hsi = 64000000 /* 64 MHz */, hse = 8000000 /* 8MHz */,
  13249. csi = 4000000 /* 4MHz */;
  13250. unsigned int sel = (rcc->CFGR & (7 << 3)) >> 3;
  13251. if (sel == 1) {
  13252. clk = csi;
  13253. } else if (sel == 2) {
  13254. clk = hse;
  13255. } else if (sel == 3) {
  13256. uint32_t vco, m, n, p;
  13257. unsigned int src = (rcc->PLLCKSELR & (3 << 0)) >> 0;
  13258. m = ((rcc->PLLCKSELR & (0x3F << 4)) >> 4);
  13259. n = ((rcc->PLL1DIVR & (0x1FF << 0)) >> 0) + 1 +
  13260. ((rcc->PLLCFGR & MG_BIT(0)) ? 1 : 0); // round-up in fractional mode
  13261. p = ((rcc->PLL1DIVR & (0x7F << 9)) >> 9) + 1;
  13262. if (src == 1) {
  13263. clk = csi;
  13264. } else if (src == 2) {
  13265. clk = hse;
  13266. } else {
  13267. clk = hsi;
  13268. clk >>= ((rcc->CR & 3) >> 3);
  13269. }
  13270. vco = (uint32_t) ((uint64_t) clk * n / m);
  13271. clk = vco / p;
  13272. } else {
  13273. clk = hsi;
  13274. clk >>= ((rcc->CR & 3) >> 3);
  13275. }
  13276. const uint8_t cptab[12] = {1, 2, 3, 4, 6, 7, 8, 9}; // log2(div)
  13277. uint32_t d1cpre = (rcc->D1CFGR & (0x0F << 8)) >> 8;
  13278. if (d1cpre >= 8) clk >>= cptab[d1cpre - 8];
  13279. MG_DEBUG(("D1 CLK: %u", clk));
  13280. uint32_t hpre = (rcc->D1CFGR & (0x0F << 0)) >> 0;
  13281. if (hpre < 8) return clk;
  13282. return ((uint32_t) clk) >> cptab[hpre - 8];
  13283. }
  13284. // Guess CR from AHB1 clock. MDC clock is generated from the ETH peripheral
  13285. // clock (AHB1); as per 802.3, it must not exceed 2. As the AHB clock can
  13286. // be derived from HSI or CSI (internal RC) clocks, and those can go above
  13287. // specs, the datasheets specify a range of frequencies and activate one of a
  13288. // series of dividers to keep the MDC clock safely below 2.5MHz. We guess a
  13289. // divider setting based on HCLK with some drift. If the user uses a different
  13290. // clock from our defaults, needs to set the macros on top. Valid for
  13291. // STM32H74xxx/75xxx (58.11.4)(4.5% worst case drift)(CSI clock has a 7.5 %
  13292. // worst case drift @ max temp)
  13293. static int guess_mdc_cr(void) {
  13294. const uint8_t crs[] = {2, 3, 0, 1, 4, 5}; // ETH->MACMDIOAR::CR values
  13295. const uint8_t div[] = {16, 26, 42, 62, 102, 124}; // Respective HCLK dividers
  13296. uint32_t hclk = get_hclk(); // Guess system HCLK
  13297. int result = -1; // Invalid CR value
  13298. for (int i = 0; i < 6; i++) {
  13299. if (hclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  13300. result = crs[i];
  13301. break;
  13302. }
  13303. }
  13304. if (result < 0) MG_ERROR(("HCLK too high"));
  13305. MG_DEBUG(("HCLK: %u, CR: %d", hclk, result));
  13306. return result;
  13307. }
  13308. static bool mg_tcpip_driver_stm32h_init(struct mg_tcpip_if *ifp) {
  13309. struct mg_tcpip_driver_stm32h_data *d =
  13310. (struct mg_tcpip_driver_stm32h_data *) ifp->driver_data;
  13311. s_ifp = ifp;
  13312. // Init RX descriptors
  13313. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13314. s_rxdesc[i][0] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13315. s_rxdesc[i][3] = MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  13316. }
  13317. // Init TX descriptors
  13318. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13319. s_txdesc[i][0] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13320. }
  13321. ETH->DMAMR |= MG_BIT(0); // Software reset
  13322. while ((ETH->DMAMR & MG_BIT(0)) != 0) (void) 0; // Wait until done
  13323. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13324. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13325. ETH->MACMDIOAR = ((uint32_t) cr & 0xF) << 8;
  13326. // NOTE(scaprile): We do not use timing facilities so the DMA engine does not
  13327. // re-write buffer address
  13328. ETH->DMAMR = 0 << 16; // use interrupt mode 0 (58.8.1) (reset value)
  13329. ETH->DMASBMR |= MG_BIT(12); // AAL NOTE(scaprile): is this actually needed
  13330. ETH->MACIER = 0; // Do not enable additional irq sources (reset value)
  13331. ETH->MACTFCR = MG_BIT(7); // Disable zero-quanta pause
  13332. // ETH->MACPFR = MG_BIT(31); // Receive all
  13333. eth_write_phy(PHY_ADDR, PHY_BCR, MG_BIT(15)); // Reset PHY
  13334. eth_write_phy(PHY_ADDR, PHY_BCR, MG_BIT(12)); // Set autonegotiation
  13335. ETH->DMACRDLAR =
  13336. (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors start address
  13337. ETH->DMACRDRLR = ETH_DESC_CNT - 1; // ring length
  13338. ETH->DMACRDTPR =
  13339. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT -
  13340. 1]; // last valid descriptor address
  13341. ETH->DMACTDLAR =
  13342. (uint32_t) (uintptr_t) s_txdesc; // TX descriptors start address
  13343. ETH->DMACTDRLR = ETH_DESC_CNT - 1; // ring length
  13344. ETH->DMACTDTPR =
  13345. (uint32_t) (uintptr_t) s_txdesc; // first available descriptor address
  13346. ETH->DMACCR = 0; // DSL = 0 (contiguous descriptor table) (reset value)
  13347. ETH->DMACIER = MG_BIT(6) | MG_BIT(15); // RIE, NIE
  13348. ETH->MACCR = MG_BIT(0) | MG_BIT(1) | MG_BIT(13) | MG_BIT(14) |
  13349. MG_BIT(15); // RE, TE, Duplex, Fast, Reserved
  13350. ETH->MTLTQOMR |= MG_BIT(1); // TSF
  13351. ETH->MTLRQOMR |= MG_BIT(5); // RSF
  13352. ETH->DMACTCR |= MG_BIT(0); // ST
  13353. ETH->DMACRCR |= MG_BIT(0); // SR
  13354. // MAC address filtering
  13355. ETH->MACA0HR = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13356. ETH->MACA0LR = (uint32_t) (ifp->mac[3] << 24) |
  13357. ((uint32_t) ifp->mac[2] << 16) |
  13358. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13359. return true;
  13360. }
  13361. static uint32_t s_txno;
  13362. static size_t mg_tcpip_driver_stm32h_tx(const void *buf, size_t len,
  13363. struct mg_tcpip_if *ifp) {
  13364. if (len > sizeof(s_txbuf[s_txno])) {
  13365. MG_ERROR(("Frame too big, %ld", (long) len));
  13366. len = 0; // Frame is too big
  13367. } else if ((s_txdesc[s_txno][3] & MG_BIT(31))) {
  13368. ifp->nerr++;
  13369. MG_ERROR(("No free descriptors: %u %08X %08X %08X", s_txno,
  13370. s_txdesc[s_txno][3], ETH->DMACSR, ETH->DMACTCR));
  13371. for (int i = 0; i < ETH_DESC_CNT; i++) MG_ERROR(("%08X", s_txdesc[i][3]));
  13372. len = 0; // All descriptors are busy, fail
  13373. } else {
  13374. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13375. s_txdesc[s_txno][2] = (uint32_t) len; // Set data len
  13376. s_txdesc[s_txno][3] = MG_BIT(28) | MG_BIT(29); // FD, LD
  13377. s_txdesc[s_txno][3] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13378. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13379. }
  13380. ETH->DMACSR |= MG_BIT(2) | MG_BIT(1); // Clear any prior TBU, TPS
  13381. ETH->DMACTDTPR = (uint32_t) (uintptr_t) &s_txdesc[s_txno]; // and resume
  13382. return len;
  13383. (void) ifp;
  13384. }
  13385. static bool mg_tcpip_driver_stm32h_up(struct mg_tcpip_if *ifp) {
  13386. uint32_t bsr = eth_read_phy(PHY_ADDR, PHY_BSR);
  13387. bool up = bsr & MG_BIT(2) ? 1 : 0;
  13388. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13389. uint32_t scsr = eth_read_phy(PHY_ADDR, PHY_CSCR);
  13390. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13391. // if(link is slow or half) set flags otherwise
  13392. // reg = tmp
  13393. uint32_t maccr = ETH->MACCR | MG_BIT(14) | MG_BIT(13); // 100M, Full-duplex
  13394. if ((scsr & MG_BIT(3)) == 0) maccr &= ~MG_BIT(14); // 10M
  13395. if ((scsr & MG_BIT(4)) == 0) maccr &= ~MG_BIT(13); // Half-duplex
  13396. ETH->MACCR = maccr; // IRQ handler does not fiddle with this register
  13397. MG_DEBUG(("Link is %uM %s-duplex", maccr & MG_BIT(14) ? 100 : 10,
  13398. maccr & MG_BIT(13) ? "full" : "half"));
  13399. }
  13400. return up;
  13401. }
  13402. void ETH_IRQHandler(void);
  13403. static uint32_t s_rxno;
  13404. void ETH_IRQHandler(void) {
  13405. if (ETH->DMACSR & MG_BIT(6)) { // Frame received, loop
  13406. ETH->DMACSR = MG_BIT(15) | MG_BIT(6); // Clear flag
  13407. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13408. if (s_rxdesc[s_rxno][3] & MG_BIT(31)) break; // exit when done
  13409. if (((s_rxdesc[s_rxno][3] & (MG_BIT(28) | MG_BIT(29))) ==
  13410. (MG_BIT(28) | MG_BIT(29))) &&
  13411. !(s_rxdesc[s_rxno][3] & MG_BIT(15))) { // skip partial/errored frames
  13412. uint32_t len = s_rxdesc[s_rxno][3] & (MG_BIT(15) - 1);
  13413. // MG_DEBUG(("%lx %lu %lx %08lx", s_rxno, len, s_rxdesc[s_rxno][3],
  13414. // ETH->DMACSR));
  13415. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13416. }
  13417. s_rxdesc[s_rxno][3] =
  13418. MG_BIT(31) | MG_BIT(30) | MG_BIT(24); // OWN, IOC, BUF1V
  13419. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13420. }
  13421. }
  13422. ETH->DMACSR =
  13423. MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing
  13424. ETH->DMACRDTPR =
  13425. (uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT - 1]; // and resume RX
  13426. }
  13427. struct mg_tcpip_driver mg_tcpip_driver_stm32h = {
  13428. mg_tcpip_driver_stm32h_init, mg_tcpip_driver_stm32h_tx, NULL,
  13429. mg_tcpip_driver_stm32h_up};
  13430. #endif
  13431. #ifdef MG_ENABLE_LINES
  13432. #line 1 "src/drivers/tm4c.c"
  13433. #endif
  13434. #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
  13435. struct tm4c_emac {
  13436. volatile uint32_t EMACCFG, EMACFRAMEFLTR, EMACHASHTBLH, EMACHASHTBLL,
  13437. EMACMIIADDR, EMACMIIDATA, EMACFLOWCTL, EMACVLANTG, RESERVED0, EMACSTATUS,
  13438. EMACRWUFF, EMACPMTCTLSTAT, RESERVED1[2], EMACRIS, EMACIM, EMACADDR0H,
  13439. EMACADDR0L, EMACADDR1H, EMACADDR1L, EMACADDR2H, EMACADDR2L, EMACADDR3H,
  13440. EMACADDR3L, RESERVED2[31], EMACWDOGTO, RESERVED3[8], EMACMMCCTRL,
  13441. EMACMMCRXRIS, EMACMMCTXRIS, EMACMMCRXIM, EMACMMCTXIM, RESERVED4,
  13442. EMACTXCNTGB, RESERVED5[12], EMACTXCNTSCOL, EMACTXCNTMCOL, RESERVED6[4],
  13443. EMACTXOCTCNTG, RESERVED7[6], EMACRXCNTGB, RESERVED8[4], EMACRXCNTCRCERR,
  13444. EMACRXCNTALGNERR, RESERVED9[10], EMACRXCNTGUNI, RESERVED10[239],
  13445. EMACVLNINCREP, EMACVLANHASH, RESERVED11[93], EMACTIMSTCTRL, EMACSUBSECINC,
  13446. EMACTIMSEC, EMACTIMNANO, EMACTIMSECU, EMACTIMNANOU, EMACTIMADD,
  13447. EMACTARGSEC, EMACTARGNANO, EMACHWORDSEC, EMACTIMSTAT, EMACPPSCTRL,
  13448. RESERVED12[12], EMACPPS0INTVL, EMACPPS0WIDTH, RESERVED13[294],
  13449. EMACDMABUSMOD, EMACTXPOLLD, EMACRXPOLLD, EMACRXDLADDR, EMACTXDLADDR,
  13450. EMACDMARIS, EMACDMAOPMODE, EMACDMAIM, EMACMFBOC, EMACRXINTWDT,
  13451. RESERVED14[8], EMACHOSTXDESC, EMACHOSRXDESC, EMACHOSTXBA, EMACHOSRXBA,
  13452. RESERVED15[218], EMACPP, EMACPC, EMACCC, RESERVED16, EMACEPHYRIS,
  13453. EMACEPHYIM, EMACEPHYIMSC;
  13454. };
  13455. #undef EMAC
  13456. #define EMAC ((struct tm4c_emac *) (uintptr_t) 0x400EC000)
  13457. #define ETH_PKT_SIZE 1540 // Max frame size
  13458. #define ETH_DESC_CNT 4 // Descriptors count
  13459. #define ETH_DS 4 // Descriptor size (words)
  13460. static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS]; // RX descriptors
  13461. static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS]; // TX descriptors
  13462. static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // RX ethernet buffers
  13463. static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE]; // TX ethernet buffers
  13464. static struct mg_tcpip_if *s_ifp; // MIP interface
  13465. enum {
  13466. EPHY_ADDR = 0,
  13467. EPHYBMCR = 0,
  13468. EPHYBMSR = 1,
  13469. EPHYSTS = 16
  13470. }; // PHY constants
  13471. static inline void tm4cspin(volatile uint32_t count) {
  13472. while (count--) (void) 0;
  13473. }
  13474. static uint32_t emac_read_phy(uint8_t addr, uint8_t reg) {
  13475. EMAC->EMACMIIADDR &= (0xf << 2);
  13476. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6);
  13477. EMAC->EMACMIIADDR |= MG_BIT(0);
  13478. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  13479. return EMAC->EMACMIIDATA;
  13480. }
  13481. static void emac_write_phy(uint8_t addr, uint8_t reg, uint32_t val) {
  13482. EMAC->EMACMIIDATA = val;
  13483. EMAC->EMACMIIADDR &= (0xf << 2);
  13484. EMAC->EMACMIIADDR |= ((uint32_t) addr << 11) | ((uint32_t) reg << 6) | MG_BIT(1);
  13485. EMAC->EMACMIIADDR |= MG_BIT(0);
  13486. while (EMAC->EMACMIIADDR & MG_BIT(0)) tm4cspin(1);
  13487. }
  13488. static uint32_t get_sysclk(void) {
  13489. struct sysctl {
  13490. volatile uint32_t DONTCARE0[44], RSCLKCFG, DONTCARE1[43], PLLFREQ0,
  13491. PLLFREQ1;
  13492. } *sysctl = (struct sysctl *) 0x400FE000;
  13493. uint32_t clk = 0, piosc = 16000000 /* 16 MHz */, mosc = 25000000 /* 25MHz */;
  13494. if (sysctl->RSCLKCFG & (1 << 28)) { // USEPLL
  13495. uint32_t fin, vco, mdiv, n, q, psysdiv;
  13496. uint32_t pllsrc = (sysctl->RSCLKCFG & (0xf << 24)) >> 24;
  13497. if (pllsrc == 0) {
  13498. clk = piosc;
  13499. } else if (pllsrc == 3) {
  13500. clk = mosc;
  13501. } else {
  13502. MG_ERROR(("Unsupported clock source"));
  13503. }
  13504. q = (sysctl->PLLFREQ1 & (0x1f << 8)) >> 8;
  13505. n = (sysctl->PLLFREQ1 & (0x1f << 0)) >> 0;
  13506. fin = clk / ((q + 1) * (n + 1));
  13507. mdiv = (sysctl->PLLFREQ0 & (0x3ff << 0)) >>
  13508. 0; // mint + (mfrac / 1024); MFRAC not supported
  13509. psysdiv = (sysctl->RSCLKCFG & (0x3f << 0)) >> 0;
  13510. vco = (uint32_t) ((uint64_t) fin * mdiv);
  13511. return vco / (psysdiv + 1);
  13512. }
  13513. uint32_t oscsrc = (sysctl->RSCLKCFG & (0xf << 20)) >> 20;
  13514. if (oscsrc == 0) {
  13515. clk = piosc;
  13516. } else if (oscsrc == 3) {
  13517. clk = mosc;
  13518. } else {
  13519. MG_ERROR(("Unsupported clock source"));
  13520. }
  13521. uint32_t osysdiv = (sysctl->RSCLKCFG & (0xf << 16)) >> 16;
  13522. return clk / (osysdiv + 1);
  13523. }
  13524. // Guess CR from SYSCLK. MDC clock is generated from SYSCLK (AHB); as per
  13525. // 802.3, it must not exceed 2.5MHz (also 20.4.2.6) As the AHB clock can be
  13526. // derived from the PIOSC (internal RC), and it can go above specs, the
  13527. // datasheets specify a range of frequencies and activate one of a series of
  13528. // dividers to keep the MDC clock safely below 2.5MHz. We guess a divider
  13529. // setting based on SYSCLK with a +5% drift. If the user uses a different clock
  13530. // from our defaults, needs to set the macros on top Valid for TM4C129x (20.7)
  13531. // (4.5% worst case drift)
  13532. // The PHY receives the main oscillator (MOSC) (20.3.1)
  13533. static int guess_mdc_cr(void) {
  13534. uint8_t crs[] = {2, 3, 0, 1}; // EMAC->MACMIIAR::CR values
  13535. uint8_t div[] = {16, 26, 42, 62}; // Respective HCLK dividers
  13536. uint32_t sysclk = get_sysclk(); // Guess system SYSCLK
  13537. int result = -1; // Invalid CR value
  13538. if (sysclk < 25000000) {
  13539. MG_ERROR(("SYSCLK too low"));
  13540. } else {
  13541. for (int i = 0; i < 4; i++) {
  13542. if (sysclk / div[i] <= 2375000UL /* 2.5MHz - 5% */) {
  13543. result = crs[i];
  13544. break;
  13545. }
  13546. }
  13547. if (result < 0) MG_ERROR(("SYSCLK too high"));
  13548. }
  13549. MG_DEBUG(("SYSCLK: %u, CR: %d", sysclk, result));
  13550. return result;
  13551. }
  13552. static bool mg_tcpip_driver_tm4c_init(struct mg_tcpip_if *ifp) {
  13553. struct mg_tcpip_driver_tm4c_data *d =
  13554. (struct mg_tcpip_driver_tm4c_data *) ifp->driver_data;
  13555. s_ifp = ifp;
  13556. // Init RX descriptors
  13557. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13558. s_rxdesc[i][0] = MG_BIT(31); // Own
  13559. s_rxdesc[i][1] = sizeof(s_rxbuf[i]) | MG_BIT(14); // 2nd address chained
  13560. s_rxdesc[i][2] = (uint32_t) (uintptr_t) s_rxbuf[i]; // Point to data buffer
  13561. s_rxdesc[i][3] =
  13562. (uint32_t) (uintptr_t) s_rxdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13563. // MG_DEBUG(("%d %p", i, s_rxdesc[i]));
  13564. }
  13565. // Init TX descriptors
  13566. for (int i = 0; i < ETH_DESC_CNT; i++) {
  13567. s_txdesc[i][2] = (uint32_t) (uintptr_t) s_txbuf[i]; // Buf pointer
  13568. s_txdesc[i][3] =
  13569. (uint32_t) (uintptr_t) s_txdesc[(i + 1) % ETH_DESC_CNT]; // Chain
  13570. }
  13571. EMAC->EMACDMABUSMOD |= MG_BIT(0); // Software reset
  13572. while ((EMAC->EMACDMABUSMOD & MG_BIT(0)) != 0) tm4cspin(1); // Wait until done
  13573. // Set MDC clock divider. If user told us the value, use it. Otherwise, guess
  13574. int cr = (d == NULL || d->mdc_cr < 0) ? guess_mdc_cr() : d->mdc_cr;
  13575. EMAC->EMACMIIADDR = ((uint32_t) cr & 0xf) << 2;
  13576. // NOTE(cpq): we do not use extended descriptor bit 7, and do not use
  13577. // hardware checksum. Therefore, descriptor size is 4, not 8
  13578. // EMAC->EMACDMABUSMOD = MG_BIT(13) | MG_BIT(16) | MG_BIT(22) | MG_BIT(23) | MG_BIT(25);
  13579. EMAC->EMACIM = MG_BIT(3) | MG_BIT(9); // Mask timestamp & PMT IT
  13580. EMAC->EMACFLOWCTL = MG_BIT(7); // Disable zero-quanta pause
  13581. // EMAC->EMACFRAMEFLTR = MG_BIT(31); // Receive all
  13582. // EMAC->EMACPC defaults to internal PHY (EPHY) in MMI mode
  13583. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(15)); // Reset internal PHY (EPHY)
  13584. emac_write_phy(EPHY_ADDR, EPHYBMCR, MG_BIT(12)); // Set autonegotiation
  13585. EMAC->EMACRXDLADDR = (uint32_t) (uintptr_t) s_rxdesc; // RX descriptors
  13586. EMAC->EMACTXDLADDR = (uint32_t) (uintptr_t) s_txdesc; // TX descriptors
  13587. EMAC->EMACDMAIM = MG_BIT(6) | MG_BIT(16); // RIE, NIE
  13588. EMAC->EMACCFG = MG_BIT(2) | MG_BIT(3) | MG_BIT(11) | MG_BIT(14); // RE, TE, Duplex, Fast
  13589. EMAC->EMACDMAOPMODE =
  13590. MG_BIT(1) | MG_BIT(13) | MG_BIT(21) | MG_BIT(25); // SR, ST, TSF, RSF
  13591. EMAC->EMACADDR0H = ((uint32_t) ifp->mac[5] << 8U) | ifp->mac[4];
  13592. EMAC->EMACADDR0L = (uint32_t) (ifp->mac[3] << 24) |
  13593. ((uint32_t) ifp->mac[2] << 16) |
  13594. ((uint32_t) ifp->mac[1] << 8) | ifp->mac[0];
  13595. // NOTE(scaprile) There are 3 additional slots for filtering, disabled by
  13596. // default. This also applies to the STM32 driver (at least for F7)
  13597. return true;
  13598. }
  13599. static uint32_t s_txno;
  13600. static size_t mg_tcpip_driver_tm4c_tx(const void *buf, size_t len,
  13601. struct mg_tcpip_if *ifp) {
  13602. if (len > sizeof(s_txbuf[s_txno])) {
  13603. MG_ERROR(("Frame too big, %ld", (long) len));
  13604. len = 0; // fail
  13605. } else if ((s_txdesc[s_txno][0] & MG_BIT(31))) {
  13606. ifp->nerr++;
  13607. MG_ERROR(("No descriptors available"));
  13608. // printf("D0 %lx SR %lx\n", (long) s_txdesc[0][0], (long)
  13609. // EMAC->EMACDMARIS);
  13610. len = 0; // fail
  13611. } else {
  13612. memcpy(s_txbuf[s_txno], buf, len); // Copy data
  13613. s_txdesc[s_txno][1] = (uint32_t) len; // Set data len
  13614. s_txdesc[s_txno][0] =
  13615. MG_BIT(20) | MG_BIT(28) | MG_BIT(29) | MG_BIT(30); // Chain,FS,LS,IC
  13616. s_txdesc[s_txno][0] |= MG_BIT(31); // Set OWN bit - let DMA take over
  13617. if (++s_txno >= ETH_DESC_CNT) s_txno = 0;
  13618. }
  13619. EMAC->EMACDMARIS = MG_BIT(2) | MG_BIT(5); // Clear any prior TU/UNF
  13620. EMAC->EMACTXPOLLD = 0; // and resume
  13621. return len;
  13622. (void) ifp;
  13623. }
  13624. static bool mg_tcpip_driver_tm4c_up(struct mg_tcpip_if *ifp) {
  13625. uint32_t bmsr = emac_read_phy(EPHY_ADDR, EPHYBMSR);
  13626. bool up = (bmsr & MG_BIT(2)) ? 1 : 0;
  13627. if ((ifp->state == MG_TCPIP_STATE_DOWN) && up) { // link state just went up
  13628. uint32_t sts = emac_read_phy(EPHY_ADDR, EPHYSTS);
  13629. // tmp = reg with flags set to the most likely situation: 100M full-duplex
  13630. // if(link is slow or half) set flags otherwise
  13631. // reg = tmp
  13632. uint32_t emaccfg = EMAC->EMACCFG | MG_BIT(14) | MG_BIT(11); // 100M, Full-duplex
  13633. if (sts & MG_BIT(1)) emaccfg &= ~MG_BIT(14); // 10M
  13634. if ((sts & MG_BIT(2)) == 0) emaccfg &= ~MG_BIT(11); // Half-duplex
  13635. EMAC->EMACCFG = emaccfg; // IRQ handler does not fiddle with this register
  13636. MG_DEBUG(("Link is %uM %s-duplex", emaccfg & MG_BIT(14) ? 100 : 10,
  13637. emaccfg & MG_BIT(11) ? "full" : "half"));
  13638. }
  13639. return up;
  13640. }
  13641. void EMAC0_IRQHandler(void);
  13642. static uint32_t s_rxno;
  13643. void EMAC0_IRQHandler(void) {
  13644. if (EMAC->EMACDMARIS & MG_BIT(6)) { // Frame received, loop
  13645. EMAC->EMACDMARIS = MG_BIT(16) | MG_BIT(6); // Clear flag
  13646. for (uint32_t i = 0; i < 10; i++) { // read as they arrive but not forever
  13647. if (s_rxdesc[s_rxno][0] & MG_BIT(31)) break; // exit when done
  13648. if (((s_rxdesc[s_rxno][0] & (MG_BIT(8) | MG_BIT(9))) == (MG_BIT(8) | MG_BIT(9))) &&
  13649. !(s_rxdesc[s_rxno][0] & MG_BIT(15))) { // skip partial/errored frames
  13650. uint32_t len = ((s_rxdesc[s_rxno][0] >> 16) & (MG_BIT(14) - 1));
  13651. // printf("%lx %lu %lx %.8lx\n", s_rxno, len, s_rxdesc[s_rxno][0],
  13652. // EMAC->EMACDMARIS);
  13653. mg_tcpip_qwrite(s_rxbuf[s_rxno], len > 4 ? len - 4 : len, s_ifp);
  13654. }
  13655. s_rxdesc[s_rxno][0] = MG_BIT(31);
  13656. if (++s_rxno >= ETH_DESC_CNT) s_rxno = 0;
  13657. }
  13658. }
  13659. EMAC->EMACDMARIS = MG_BIT(7); // Clear possible RU while processing
  13660. EMAC->EMACRXPOLLD = 0; // and resume RX
  13661. }
  13662. struct mg_tcpip_driver mg_tcpip_driver_tm4c = {mg_tcpip_driver_tm4c_init,
  13663. mg_tcpip_driver_tm4c_tx, NULL,
  13664. mg_tcpip_driver_tm4c_up};
  13665. #endif
  13666. #ifdef MG_ENABLE_LINES
  13667. #line 1 "src/drivers/w5500.c"
  13668. #endif
  13669. #if MG_ENABLE_TCPIP
  13670. enum { W5500_CR = 0, W5500_S0 = 1, W5500_TX0 = 2, W5500_RX0 = 3 };
  13671. static void w5500_txn(struct mg_tcpip_spi *s, uint8_t block, uint16_t addr, bool wr,
  13672. void *buf, size_t len) {
  13673. uint8_t *p = (uint8_t *) buf;
  13674. uint8_t cmd[] = {(uint8_t) (addr >> 8), (uint8_t) (addr & 255),
  13675. (uint8_t) ((block << 3) | (wr ? 4 : 0))};
  13676. s->begin(s->spi);
  13677. for (size_t i = 0; i < sizeof(cmd); i++) s->txn(s->spi, cmd[i]);
  13678. for (size_t i = 0; i < len; i++) {
  13679. uint8_t r = s->txn(s->spi, p[i]);
  13680. if (!wr) p[i] = r;
  13681. }
  13682. s->end(s->spi);
  13683. }
  13684. // clang-format off
  13685. 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); }
  13686. 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); }
  13687. 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)); }
  13688. 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); }
  13689. 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; }
  13690. 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]); }
  13691. // clang-format on
  13692. static size_t w5500_rx(void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  13693. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13694. uint16_t r = 0, n = 0, len = (uint16_t) buflen, n2; // Read recv len
  13695. while ((n2 = w5500_r2(s, W5500_S0, 0x26)) > n) n = n2; // Until it is stable
  13696. // printf("RSR: %d\n", (int) n);
  13697. if (n > 0) {
  13698. uint16_t ptr = w5500_r2(s, W5500_S0, 0x28); // Get read pointer
  13699. n = w5500_r2(s, W5500_RX0, ptr); // Read frame length
  13700. if (n <= len + 2 && n > 1) {
  13701. r = (uint16_t) (n - 2);
  13702. w5500_rn(s, W5500_RX0, (uint16_t) (ptr + 2), buf, r);
  13703. }
  13704. w5500_w2(s, W5500_S0, 0x28, (uint16_t) (ptr + n)); // Advance read pointer
  13705. w5500_w1(s, W5500_S0, 1, 0x40); // Sock0 CR -> RECV
  13706. // printf(" RX_RD: tot=%u n=%u r=%u\n", n2, n, r);
  13707. }
  13708. return r;
  13709. }
  13710. static size_t w5500_tx(const void *buf, size_t buflen, struct mg_tcpip_if *ifp) {
  13711. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13712. uint16_t n = 0, len = (uint16_t) buflen;
  13713. while (n < len) n = w5500_r2(s, W5500_S0, 0x20); // Wait for space
  13714. uint16_t ptr = w5500_r2(s, W5500_S0, 0x24); // Get write pointer
  13715. w5500_wn(s, W5500_TX0, ptr, (void *) buf, len); // Write data
  13716. w5500_w2(s, W5500_S0, 0x24, (uint16_t) (ptr + len)); // Advance write pointer
  13717. w5500_w1(s, W5500_S0, 1, 0x20); // Sock0 CR -> SEND
  13718. for (int i = 0; i < 40; i++) {
  13719. uint8_t ir = w5500_r1(s, W5500_S0, 2); // Read S0 IR
  13720. if (ir == 0) continue;
  13721. // printf("IR %d, len=%d, free=%d, ptr %d\n", ir, (int) len, (int) n, ptr);
  13722. w5500_w1(s, W5500_S0, 2, ir); // Write S0 IR: clear it!
  13723. if (ir & 8) len = 0; // Timeout. Report error
  13724. if (ir & (16 | 8)) break; // Stop on SEND_OK or timeout
  13725. }
  13726. return len;
  13727. }
  13728. static bool w5500_init(struct mg_tcpip_if *ifp) {
  13729. struct mg_tcpip_spi *s = (struct mg_tcpip_spi *) ifp->driver_data;
  13730. s->end(s->spi);
  13731. w5500_w1(s, W5500_CR, 0, 0x80); // Reset chip: CR -> 0x80
  13732. w5500_w1(s, W5500_CR, 0x2e, 0); // CR PHYCFGR -> reset
  13733. w5500_w1(s, W5500_CR, 0x2e, 0xf8); // CR PHYCFGR -> set
  13734. // w5500_wn(s, W5500_CR, 9, s->mac, 6); // Set source MAC
  13735. w5500_w1(s, W5500_S0, 0x1e, 16); // Sock0 RX buf size
  13736. w5500_w1(s, W5500_S0, 0x1f, 16); // Sock0 TX buf size
  13737. w5500_w1(s, W5500_S0, 0, 4); // Sock0 MR -> MACRAW
  13738. w5500_w1(s, W5500_S0, 1, 1); // Sock0 CR -> OPEN
  13739. return w5500_r1(s, W5500_S0, 3) == 0x42; // Sock0 SR == MACRAW
  13740. }
  13741. static bool w5500_up(struct mg_tcpip_if *ifp) {
  13742. struct mg_tcpip_spi *spi = (struct mg_tcpip_spi *) ifp->driver_data;
  13743. uint8_t phycfgr = w5500_r1(spi, W5500_CR, 0x2e);
  13744. return phycfgr & 1; // Bit 0 of PHYCFGR is LNK (0 - down, 1 - up)
  13745. }
  13746. struct mg_tcpip_driver mg_tcpip_driver_w5500 = {w5500_init, w5500_tx, w5500_rx, w5500_up};
  13747. #endif