Node-Red configuration
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

index.js 178KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225
  1. // Copyright 2013 Stephen Vickers <stephen.vickers.sv@gmail.com>
  2. var ber = require ("asn1-ber").Ber;
  3. var smartbuffer = require ("smart-buffer");
  4. var dgram = require ("dgram");
  5. var net = require ("net");
  6. var events = require ("events");
  7. var util = require ("util");
  8. var crypto = require ("crypto");
  9. var mibparser = require ("./lib/mib");
  10. var DEBUG = false;
  11. var MIN_SIGNED_INT32 = -2147483648;
  12. var MAX_SIGNED_INT32 = 2147483647;
  13. var MIN_UNSIGNED_INT32 = 0;
  14. var MAX_UNSIGNED_INT32 = 4294967295;
  15. function debug (line) {
  16. if ( DEBUG ) {
  17. console.debug (line);
  18. }
  19. }
  20. /*****************************************************************************
  21. ** Constants
  22. **/
  23. function _expandConstantObject (object) {
  24. var keys = [];
  25. for (var key in object)
  26. keys.push (key);
  27. for (var i = 0; i < keys.length; i++)
  28. object[object[keys[i]]] = parseInt (keys[i]);
  29. }
  30. var ErrorStatus = {
  31. 0: "NoError",
  32. 1: "TooBig",
  33. 2: "NoSuchName",
  34. 3: "BadValue",
  35. 4: "ReadOnly",
  36. 5: "GeneralError",
  37. 6: "NoAccess",
  38. 7: "WrongType",
  39. 8: "WrongLength",
  40. 9: "WrongEncoding",
  41. 10: "WrongValue",
  42. 11: "NoCreation",
  43. 12: "InconsistentValue",
  44. 13: "ResourceUnavailable",
  45. 14: "CommitFailed",
  46. 15: "UndoFailed",
  47. 16: "AuthorizationError",
  48. 17: "NotWritable",
  49. 18: "InconsistentName"
  50. };
  51. _expandConstantObject (ErrorStatus);
  52. var ObjectType = {
  53. 1: "Boolean",
  54. 2: "Integer",
  55. 3: "BitString",
  56. 4: "OctetString",
  57. 5: "Null",
  58. 6: "OID",
  59. 64: "IpAddress",
  60. 65: "Counter",
  61. 66: "Gauge",
  62. 67: "TimeTicks",
  63. 68: "Opaque",
  64. 70: "Counter64",
  65. 128: "NoSuchObject",
  66. 129: "NoSuchInstance",
  67. 130: "EndOfMibView"
  68. };
  69. _expandConstantObject (ObjectType);
  70. // ASN.1
  71. ObjectType.INTEGER = ObjectType.Integer;
  72. ObjectType["OCTET STRING"] = ObjectType.OctetString;
  73. ObjectType["OBJECT IDENTIFIER"] = ObjectType.OID;
  74. // SNMPv2-SMI
  75. ObjectType.Integer32 = ObjectType.Integer;
  76. ObjectType.Counter32 = ObjectType.Counter;
  77. ObjectType.Gauge32 = ObjectType.Gauge;
  78. ObjectType.Unsigned32 = ObjectType.Gauge32;
  79. // SNMPv2-TC
  80. ObjectType.AutonomousType = ObjectType["OBJECT IDENTIFIER"];
  81. ObjectType.DateAndTime = ObjectType["OCTET STRING"];
  82. ObjectType.DisplayString = ObjectType["OCTET STRING"];
  83. ObjectType.InstancePointer = ObjectType["OBJECT IDENTIFIER"];
  84. ObjectType.MacAddress = ObjectType["OCTET STRING"];
  85. ObjectType.PhysAddress = ObjectType["OCTET STRING"];
  86. ObjectType.RowPointer = ObjectType["OBJECT IDENTIFIER"];
  87. ObjectType.RowStatus = ObjectType.INTEGER;
  88. ObjectType.StorageType = ObjectType.INTEGER;
  89. ObjectType.TestAndIncr = ObjectType.INTEGER;
  90. ObjectType.TimeStamp = ObjectType.TimeTicks;
  91. ObjectType.TruthValue = ObjectType.INTEGER;
  92. ObjectType.TAddress = ObjectType["OCTET STRING"];
  93. ObjectType.TDomain = ObjectType["OBJECT IDENTIFIER"];
  94. ObjectType.VariablePointer = ObjectType["OBJECT IDENTIFIER"];
  95. var PduType = {
  96. 160: "GetRequest",
  97. 161: "GetNextRequest",
  98. 162: "GetResponse",
  99. 163: "SetRequest",
  100. 164: "Trap",
  101. 165: "GetBulkRequest",
  102. 166: "InformRequest",
  103. 167: "TrapV2",
  104. 168: "Report"
  105. };
  106. _expandConstantObject (PduType);
  107. var TrapType = {
  108. 0: "ColdStart",
  109. 1: "WarmStart",
  110. 2: "LinkDown",
  111. 3: "LinkUp",
  112. 4: "AuthenticationFailure",
  113. 5: "EgpNeighborLoss",
  114. 6: "EnterpriseSpecific"
  115. };
  116. _expandConstantObject (TrapType);
  117. var SecurityLevel = {
  118. 1: "noAuthNoPriv",
  119. 2: "authNoPriv",
  120. 3: "authPriv"
  121. };
  122. _expandConstantObject (SecurityLevel);
  123. var AuthProtocols = {
  124. "1": "none",
  125. "2": "md5",
  126. "3": "sha",
  127. "4": "sha224",
  128. "5": "sha256",
  129. "6": "sha384",
  130. "7": "sha512"
  131. };
  132. _expandConstantObject (AuthProtocols);
  133. var PrivProtocols = {
  134. "1": "none",
  135. "2": "des",
  136. "4": "aes",
  137. "6": "aes256b",
  138. "8": "aes256r"
  139. };
  140. _expandConstantObject (PrivProtocols);
  141. var UsmStatsBase = "1.3.6.1.6.3.15.1.1";
  142. var UsmStats = {
  143. "1": "Unsupported Security Level",
  144. "2": "Not In Time Window",
  145. "3": "Unknown User Name",
  146. "4": "Unknown Engine ID",
  147. "5": "Wrong Digest (incorrect password, community or key)",
  148. "6": "Decryption Error"
  149. };
  150. _expandConstantObject (UsmStats);
  151. var MibProviderType = {
  152. "1": "Scalar",
  153. "2": "Table"
  154. };
  155. _expandConstantObject (MibProviderType);
  156. var Version1 = 0;
  157. var Version2c = 1;
  158. var Version3 = 3;
  159. var Version = {
  160. "1": Version1,
  161. "2c": Version2c,
  162. "3": Version3
  163. };
  164. var AgentXPduType = {
  165. 1: "Open",
  166. 2: "Close",
  167. 3: "Register",
  168. 4: "Unregister",
  169. 5: "Get",
  170. 6: "GetNext",
  171. 7: "GetBulk",
  172. 8: "TestSet",
  173. 9: "CommitSet",
  174. 10: "UndoSet",
  175. 11: "CleanupSet",
  176. 12: "Notify",
  177. 13: "Ping",
  178. 14: "IndexAllocate",
  179. 15: "IndexDeallocate",
  180. 16: "AddAgentCaps",
  181. 17: "RemoveAgentCaps",
  182. 18: "Response"
  183. };
  184. _expandConstantObject (AgentXPduType);
  185. var AccessControlModelType = {
  186. 0: "None",
  187. 1: "Simple"
  188. };
  189. _expandConstantObject (AccessControlModelType);
  190. var AccessLevel = {
  191. 0: "None",
  192. 1: "ReadOnly",
  193. 2: "ReadWrite"
  194. };
  195. _expandConstantObject (AccessLevel);
  196. // SMIv2 MAX-ACCESS values
  197. var MaxAccess = {
  198. 0: "not-accessible",
  199. 1: "accessible-for-notify",
  200. 2: "read-only",
  201. 3: "read-write",
  202. 4: "read-create"
  203. };
  204. _expandConstantObject (MaxAccess);
  205. // SMIv1 ACCESS value mapping to SMIv2 MAX-ACCESS
  206. var AccessToMaxAccess = {
  207. "not-accessible": "not-accessible",
  208. "read-only": "read-only",
  209. "read-write": "read-write",
  210. "write-only": "read-write"
  211. };
  212. var RowStatus = {
  213. // status values
  214. 1: "active",
  215. 2: "notInService",
  216. 3: "notReady",
  217. // actions
  218. 4: "createAndGo",
  219. 5: "createAndWait",
  220. 6: "destroy"
  221. };
  222. _expandConstantObject (RowStatus);
  223. var ResponseInvalidCode = {
  224. 1: "EIp4AddressSize",
  225. 2: "EUnknownObjectType",
  226. 3: "EUnknownPduType",
  227. 4: "ECouldNotDecrypt",
  228. 5: "EAuthFailure",
  229. 6: "EReqResOidNoMatch",
  230. // 7: "ENonRepeaterCountMismatch", // no longer used
  231. 8: "EOutOfOrder",
  232. 9: "EVersionNoMatch",
  233. 10: "ECommunityNoMatch",
  234. 11: "EUnexpectedReport",
  235. 12: "EResponseNotHandled",
  236. 13: "EUnexpectedResponse"
  237. };
  238. _expandConstantObject (ResponseInvalidCode);
  239. /*****************************************************************************
  240. ** Exception class definitions
  241. **/
  242. function ResponseInvalidError (message, code, info) {
  243. this.name = "ResponseInvalidError";
  244. this.message = message;
  245. this.code = code;
  246. this.info = info;
  247. Error.captureStackTrace(this, ResponseInvalidError);
  248. }
  249. util.inherits (ResponseInvalidError, Error);
  250. function RequestInvalidError (message) {
  251. this.name = "RequestInvalidError";
  252. this.message = message;
  253. Error.captureStackTrace(this, RequestInvalidError);
  254. }
  255. util.inherits (RequestInvalidError, Error);
  256. function RequestFailedError (message, status) {
  257. this.name = "RequestFailedError";
  258. this.message = message;
  259. this.status = status;
  260. Error.captureStackTrace(this, RequestFailedError);
  261. }
  262. util.inherits (RequestFailedError, Error);
  263. function RequestTimedOutError (message) {
  264. this.name = "RequestTimedOutError";
  265. this.message = message;
  266. Error.captureStackTrace(this, RequestTimedOutError);
  267. }
  268. util.inherits (RequestTimedOutError, Error);
  269. /*****************************************************************************
  270. ** OID and varbind helper functions
  271. **/
  272. function isVarbindError (varbind) {
  273. return !!(varbind.type == ObjectType.NoSuchObject
  274. || varbind.type == ObjectType.NoSuchInstance
  275. || varbind.type == ObjectType.EndOfMibView);
  276. }
  277. function varbindError (varbind) {
  278. return (ObjectType[varbind.type] || "NotAnError") + ": " + varbind.oid;
  279. }
  280. function oidFollowsOid (oidString, nextString) {
  281. var oid = {str: oidString, len: oidString.length, idx: 0};
  282. var next = {str: nextString, len: nextString.length, idx: 0};
  283. var dotCharCode = ".".charCodeAt (0);
  284. function getNumber (item) {
  285. var n = 0;
  286. if (item.idx >= item.len)
  287. return null;
  288. while (item.idx < item.len) {
  289. var charCode = item.str.charCodeAt (item.idx++);
  290. if (charCode == dotCharCode)
  291. return n;
  292. n = (n ? (n * 10) : n) + (charCode - 48);
  293. }
  294. return n;
  295. }
  296. while (1) {
  297. var oidNumber = getNumber (oid);
  298. var nextNumber = getNumber (next);
  299. if (oidNumber !== null) {
  300. if (nextNumber !== null) {
  301. if (nextNumber > oidNumber) {
  302. return true;
  303. } else if (nextNumber < oidNumber) {
  304. return false;
  305. }
  306. } else {
  307. return true;
  308. }
  309. } else {
  310. return true;
  311. }
  312. }
  313. }
  314. function oidInSubtree (oidString, nextString) {
  315. var oid = oidString.split (".");
  316. var next = nextString.split (".");
  317. if (oid.length > next.length)
  318. return false;
  319. for (var i = 0; i < oid.length; i++) {
  320. if (next[i] != oid[i])
  321. return false;
  322. }
  323. return true;
  324. }
  325. function readInt32 (buffer) {
  326. var parsedInt = buffer.readInt ();
  327. if ( ! Number.isInteger(parsedInt) ) {
  328. throw new TypeError('Value read as integer ' + parsedInt + ' is not an integer');
  329. }
  330. if ( parsedInt < MIN_SIGNED_INT32 || parsedInt > MAX_SIGNED_INT32 ) {
  331. throw new RangeError('Read integer ' + parsedInt + ' is outside the signed 32-bit range');
  332. }
  333. return parsedInt;
  334. }
  335. function readUint32 (buffer) {
  336. var parsedInt = buffer.readInt ();
  337. if ( ! Number.isInteger(parsedInt) ) {
  338. throw new TypeError('Value read as integer ' + parsedInt + ' is not an integer');
  339. }
  340. if ( parsedInt < MIN_UNSIGNED_INT32 || parsedInt > MAX_UNSIGNED_INT32 ) {
  341. throw new RangeError('Read integer ' + parsedInt + ' is outside the unsigned 32-bit range');
  342. }
  343. return parsedInt;
  344. }
  345. function readUint64 (buffer) {
  346. var value = buffer.readString (ObjectType.Counter64, true);
  347. return value;
  348. }
  349. function readIpAddress (buffer) {
  350. var bytes = buffer.readString (ObjectType.IpAddress, true);
  351. if (bytes.length != 4)
  352. throw new ResponseInvalidError ("Length '" + bytes.length
  353. + "' of IP address '" + bytes.toString ("hex")
  354. + "' is not 4", ResponseInvalidCode.EIp4AddressSize);
  355. var value = bytes[0] + "." + bytes[1] + "." + bytes[2] + "." + bytes[3];
  356. return value;
  357. }
  358. function readVarbindValue (buffer, type) {
  359. var value;
  360. if (type == ObjectType.Boolean) {
  361. value = buffer.readBoolean ();
  362. } else if (type == ObjectType.Integer) {
  363. value = readInt32 (buffer);
  364. } else if (type == ObjectType.BitString) {
  365. value = buffer.readBitString();
  366. } else if (type == ObjectType.OctetString) {
  367. value = buffer.readString (null, true);
  368. } else if (type == ObjectType.Null) {
  369. buffer.readByte ();
  370. buffer.readByte ();
  371. value = null;
  372. } else if (type == ObjectType.OID) {
  373. value = buffer.readOID ();
  374. } else if (type == ObjectType.IpAddress) {
  375. value = readIpAddress (buffer);
  376. } else if (type == ObjectType.Counter) {
  377. value = readUint32 (buffer);
  378. } else if (type == ObjectType.Gauge) {
  379. value = readUint32 (buffer);
  380. } else if (type == ObjectType.TimeTicks) {
  381. value = readUint32 (buffer);
  382. } else if (type == ObjectType.Opaque) {
  383. value = buffer.readString (ObjectType.Opaque, true);
  384. } else if (type == ObjectType.Counter64) {
  385. value = readUint64 (buffer);
  386. } else if (type == ObjectType.NoSuchObject) {
  387. buffer.readByte ();
  388. buffer.readByte ();
  389. value = null;
  390. } else if (type == ObjectType.NoSuchInstance) {
  391. buffer.readByte ();
  392. buffer.readByte ();
  393. value = null;
  394. } else if (type == ObjectType.EndOfMibView) {
  395. buffer.readByte ();
  396. buffer.readByte ();
  397. value = null;
  398. } else {
  399. throw new ResponseInvalidError ("Unknown type '" + type
  400. + "' in response", ResponseInvalidCode.EUnknownObjectType);
  401. }
  402. return value;
  403. }
  404. function readVarbinds (buffer, varbinds) {
  405. buffer.readSequence ();
  406. while (1) {
  407. buffer.readSequence ();
  408. if ( buffer.peek () != ObjectType.OID )
  409. break;
  410. var oid = buffer.readOID ();
  411. var type = buffer.peek ();
  412. if (type == null)
  413. break;
  414. var value = readVarbindValue (buffer, type);
  415. varbinds.push ({
  416. oid: oid,
  417. type: type,
  418. value: value
  419. });
  420. }
  421. }
  422. function writeInt32 (buffer, type, value) {
  423. if ( ! Number.isInteger(value) ) {
  424. throw new TypeError('Value to write as integer ' + value + ' is not an integer');
  425. }
  426. if ( value < MIN_SIGNED_INT32 || value > MAX_SIGNED_INT32 ) {
  427. throw new RangeError('Integer to write ' + value + ' is outside the signed 32-bit range');
  428. }
  429. buffer.writeInt(value, type);
  430. }
  431. function writeUint32 (buffer, type, value) {
  432. if ( ! Number.isInteger(value) ) {
  433. throw new TypeError('Value to write as integer ' + value + ' is not an integer');
  434. }
  435. if ( value < MIN_UNSIGNED_INT32 || value > MAX_UNSIGNED_INT32 ) {
  436. throw new RangeError('Integer to write ' + value + ' is outside the unsigned 32-bit range');
  437. }
  438. buffer.writeInt(value, type);
  439. }
  440. function writeUint64 (buffer, value) {
  441. buffer.writeBuffer (value, ObjectType.Counter64);
  442. }
  443. function writeVarbinds (buffer, varbinds) {
  444. buffer.startSequence ();
  445. for (var i = 0; i < varbinds.length; i++) {
  446. buffer.startSequence ();
  447. buffer.writeOID (varbinds[i].oid);
  448. if (varbinds[i].type && varbinds[i].hasOwnProperty("value")) {
  449. var type = varbinds[i].type;
  450. var value = varbinds[i].value;
  451. switch ( type ) {
  452. case ObjectType.Boolean:
  453. buffer.writeBoolean (value ? true : false);
  454. break;
  455. case ObjectType.Integer: // also Integer32
  456. writeInt32 (buffer, ObjectType.Integer, value);
  457. break;
  458. case ObjectType.OctetString:
  459. if (typeof value == "string")
  460. buffer.writeString (value);
  461. else
  462. buffer.writeBuffer (value, ObjectType.OctetString);
  463. break;
  464. case ObjectType.Null:
  465. buffer.writeNull ();
  466. break;
  467. case ObjectType.OID:
  468. buffer.writeOID (value);
  469. break;
  470. case ObjectType.IpAddress:
  471. var bytes = value.split (".");
  472. if (bytes.length != 4)
  473. throw new RequestInvalidError ("Invalid IP address '"
  474. + value + "'");
  475. buffer.writeBuffer (Buffer.from (bytes), 64);
  476. break;
  477. case ObjectType.Counter: // also Counter32
  478. writeUint32 (buffer, ObjectType.Counter, value);
  479. break;
  480. case ObjectType.Gauge: // also Gauge32 & Unsigned32
  481. writeUint32 (buffer, ObjectType.Gauge, value);
  482. break;
  483. case ObjectType.TimeTicks:
  484. writeUint32 (buffer, ObjectType.TimeTicks, value);
  485. break;
  486. case ObjectType.Opaque:
  487. buffer.writeBuffer (value, ObjectType.Opaque);
  488. break;
  489. case ObjectType.Counter64:
  490. writeUint64 (buffer, value);
  491. break;
  492. case ObjectType.NoSuchObject:
  493. case ObjectType.NoSuchInstance:
  494. case ObjectType.EndOfMibView:
  495. buffer.writeByte (type);
  496. buffer.writeByte (0);
  497. break;
  498. default:
  499. throw new RequestInvalidError ("Unknown type '" + type
  500. + "' in request");
  501. }
  502. } else {
  503. buffer.writeNull ();
  504. }
  505. buffer.endSequence ();
  506. }
  507. buffer.endSequence ();
  508. }
  509. /*****************************************************************************
  510. ** PDU class definitions
  511. **/
  512. var SimplePdu = function () {
  513. };
  514. SimplePdu.prototype.toBuffer = function (buffer) {
  515. buffer.startSequence (this.type);
  516. writeInt32 (buffer, ObjectType.Integer, this.id);
  517. writeInt32 (buffer, ObjectType.Integer,
  518. (this.type == PduType.GetBulkRequest)
  519. ? (this.options.nonRepeaters || 0)
  520. : 0);
  521. writeInt32 (buffer, ObjectType.Integer,
  522. (this.type == PduType.GetBulkRequest)
  523. ? (this.options.maxRepetitions || 0)
  524. : 0);
  525. writeVarbinds (buffer, this.varbinds);
  526. buffer.endSequence ();
  527. };
  528. SimplePdu.prototype.initializeFromVariables = function (id, varbinds, options) {
  529. this.id = id;
  530. this.varbinds = varbinds;
  531. this.options = options || {};
  532. this.contextName = (options && options.context) ? options.context : "";
  533. };
  534. SimplePdu.prototype.initializeFromBuffer = function (reader) {
  535. this.type = reader.peek ();
  536. reader.readSequence ();
  537. this.id = readInt32 (reader);
  538. this.nonRepeaters = readInt32 (reader);
  539. this.maxRepetitions = readInt32 (reader);
  540. this.varbinds = [];
  541. readVarbinds (reader, this.varbinds);
  542. };
  543. SimplePdu.prototype.getResponsePduForRequest = function () {
  544. var responsePdu = GetResponsePdu.createFromVariables(this.id, [], {});
  545. if ( this.contextEngineID ) {
  546. responsePdu.contextEngineID = this.contextEngineID;
  547. responsePdu.contextName = this.contextName;
  548. }
  549. return responsePdu;
  550. };
  551. SimplePdu.createFromVariables = function (pduClass, id, varbinds, options) {
  552. var pdu = new pduClass (id, varbinds, options);
  553. pdu.id = id;
  554. pdu.varbinds = varbinds;
  555. pdu.options = options || {};
  556. pdu.contextName = (options && options.context) ? options.context : "";
  557. return pdu;
  558. };
  559. var GetBulkRequestPdu = function () {
  560. this.type = PduType.GetBulkRequest;
  561. GetBulkRequestPdu.super_.apply (this, arguments);
  562. };
  563. util.inherits (GetBulkRequestPdu, SimplePdu);
  564. GetBulkRequestPdu.createFromBuffer = function (reader) {
  565. var pdu = new GetBulkRequestPdu ();
  566. pdu.initializeFromBuffer (reader);
  567. return pdu;
  568. };
  569. var GetNextRequestPdu = function () {
  570. this.type = PduType.GetNextRequest;
  571. GetNextRequestPdu.super_.apply (this, arguments);
  572. };
  573. util.inherits (GetNextRequestPdu, SimplePdu);
  574. GetNextRequestPdu.createFromBuffer = function (reader) {
  575. var pdu = new GetNextRequestPdu ();
  576. pdu.initializeFromBuffer (reader);
  577. return pdu;
  578. };
  579. var GetRequestPdu = function () {
  580. this.type = PduType.GetRequest;
  581. GetRequestPdu.super_.apply (this, arguments);
  582. };
  583. util.inherits (GetRequestPdu, SimplePdu);
  584. GetRequestPdu.createFromBuffer = function (reader) {
  585. var pdu = new GetRequestPdu();
  586. pdu.initializeFromBuffer (reader);
  587. return pdu;
  588. };
  589. GetRequestPdu.createFromVariables = function (id, varbinds, options) {
  590. var pdu = new GetRequestPdu();
  591. pdu.initializeFromVariables (id, varbinds, options);
  592. return pdu;
  593. };
  594. var InformRequestPdu = function () {
  595. this.type = PduType.InformRequest;
  596. InformRequestPdu.super_.apply (this, arguments);
  597. };
  598. util.inherits (InformRequestPdu, SimplePdu);
  599. InformRequestPdu.createFromBuffer = function (reader) {
  600. var pdu = new InformRequestPdu();
  601. pdu.initializeFromBuffer (reader);
  602. return pdu;
  603. };
  604. var SetRequestPdu = function () {
  605. this.type = PduType.SetRequest;
  606. SetRequestPdu.super_.apply (this, arguments);
  607. };
  608. util.inherits (SetRequestPdu, SimplePdu);
  609. SetRequestPdu.createFromBuffer = function (reader) {
  610. var pdu = new SetRequestPdu ();
  611. pdu.initializeFromBuffer (reader);
  612. return pdu;
  613. };
  614. var TrapPdu = function () {
  615. this.type = PduType.Trap;
  616. };
  617. TrapPdu.prototype.toBuffer = function (buffer) {
  618. buffer.startSequence (this.type);
  619. buffer.writeOID (this.enterprise);
  620. buffer.writeBuffer (Buffer.from (this.agentAddr.split (".")),
  621. ObjectType.IpAddress);
  622. writeInt32 (buffer, ObjectType.Integer, this.generic);
  623. writeInt32 (buffer, ObjectType.Integer, this.specific);
  624. writeUint32 (buffer, ObjectType.TimeTicks,
  625. this.upTime || Math.floor (process.uptime () * 100));
  626. writeVarbinds (buffer, this.varbinds);
  627. buffer.endSequence ();
  628. };
  629. TrapPdu.createFromBuffer = function (reader) {
  630. var pdu = new TrapPdu();
  631. reader.readSequence ();
  632. pdu.enterprise = reader.readOID ();
  633. pdu.agentAddr = readIpAddress (reader);
  634. pdu.generic = readInt32 (reader);
  635. pdu.specific = readInt32 (reader);
  636. pdu.upTime = readUint32 (reader);
  637. pdu.varbinds = [];
  638. readVarbinds (reader, pdu.varbinds);
  639. return pdu;
  640. };
  641. TrapPdu.createFromVariables = function (typeOrOid, varbinds, options) {
  642. var pdu = new TrapPdu ();
  643. pdu.agentAddr = options.agentAddr || "127.0.0.1";
  644. pdu.upTime = options.upTime;
  645. if (typeof typeOrOid == "string") {
  646. pdu.generic = TrapType.EnterpriseSpecific;
  647. pdu.specific = parseInt (typeOrOid.match (/\.(\d+)$/)[1]);
  648. pdu.enterprise = typeOrOid.replace (/\.(\d+)$/, "");
  649. } else {
  650. pdu.generic = typeOrOid;
  651. pdu.specific = 0;
  652. pdu.enterprise = "1.3.6.1.4.1";
  653. }
  654. pdu.varbinds = varbinds;
  655. return pdu;
  656. };
  657. var TrapV2Pdu = function () {
  658. this.type = PduType.TrapV2;
  659. TrapV2Pdu.super_.apply (this, arguments);
  660. };
  661. util.inherits (TrapV2Pdu, SimplePdu);
  662. TrapV2Pdu.createFromBuffer = function (reader) {
  663. var pdu = new TrapV2Pdu();
  664. pdu.initializeFromBuffer (reader);
  665. return pdu;
  666. };
  667. TrapV2Pdu.createFromVariables = function (id, varbinds, options) {
  668. var pdu = new TrapV2Pdu();
  669. pdu.initializeFromVariables (id, varbinds, options);
  670. return pdu;
  671. };
  672. var SimpleResponsePdu = function() {
  673. };
  674. SimpleResponsePdu.prototype.toBuffer = function (writer) {
  675. writer.startSequence (this.type);
  676. writeInt32 (writer, ObjectType.Integer, this.id);
  677. writeInt32 (writer, ObjectType.Integer, this.errorStatus || 0);
  678. writeInt32 (writer, ObjectType.Integer, this.errorIndex || 0);
  679. writeVarbinds (writer, this.varbinds);
  680. writer.endSequence ();
  681. };
  682. SimpleResponsePdu.prototype.initializeFromBuffer = function (reader) {
  683. reader.readSequence (this.type);
  684. this.id = readInt32 (reader);
  685. this.errorStatus = readInt32 (reader);
  686. this.errorIndex = readInt32 (reader);
  687. this.varbinds = [];
  688. readVarbinds (reader, this.varbinds);
  689. };
  690. SimpleResponsePdu.prototype.initializeFromVariables = function (id, varbinds, options) {
  691. this.id = id;
  692. this.varbinds = varbinds;
  693. this.options = options || {};
  694. };
  695. var GetResponsePdu = function () {
  696. this.type = PduType.GetResponse;
  697. GetResponsePdu.super_.apply (this, arguments);
  698. };
  699. util.inherits (GetResponsePdu, SimpleResponsePdu);
  700. GetResponsePdu.createFromBuffer = function (reader) {
  701. var pdu = new GetResponsePdu ();
  702. pdu.initializeFromBuffer (reader);
  703. return pdu;
  704. };
  705. GetResponsePdu.createFromVariables = function (id, varbinds, options) {
  706. var pdu = new GetResponsePdu();
  707. pdu.initializeFromVariables (id, varbinds, options);
  708. return pdu;
  709. };
  710. var ReportPdu = function () {
  711. this.type = PduType.Report;
  712. ReportPdu.super_.apply (this, arguments);
  713. };
  714. util.inherits (ReportPdu, SimpleResponsePdu);
  715. ReportPdu.createFromBuffer = function (reader) {
  716. var pdu = new ReportPdu ();
  717. pdu.initializeFromBuffer (reader);
  718. return pdu;
  719. };
  720. ReportPdu.createFromVariables = function (id, varbinds, options) {
  721. var pdu = new ReportPdu();
  722. pdu.initializeFromVariables (id, varbinds, options);
  723. return pdu;
  724. };
  725. var readPdu = function (reader, scoped) {
  726. var pdu;
  727. var contextEngineID;
  728. var contextName;
  729. if ( scoped ) {
  730. reader = new ber.Reader (reader.readString (ber.Sequence | ber.Constructor, true));
  731. contextEngineID = reader.readString (ber.OctetString, true);
  732. contextName = reader.readString ();
  733. }
  734. var type = reader.peek ();
  735. if (type == PduType.GetResponse) {
  736. pdu = GetResponsePdu.createFromBuffer (reader);
  737. } else if (type == PduType.Report ) {
  738. pdu = ReportPdu.createFromBuffer (reader);
  739. } else if (type == PduType.Trap ) {
  740. pdu = TrapPdu.createFromBuffer (reader);
  741. } else if (type == PduType.TrapV2 ) {
  742. pdu = TrapV2Pdu.createFromBuffer (reader);
  743. } else if (type == PduType.InformRequest ) {
  744. pdu = InformRequestPdu.createFromBuffer (reader);
  745. } else if (type == PduType.GetRequest ) {
  746. pdu = GetRequestPdu.createFromBuffer (reader);
  747. } else if (type == PduType.SetRequest ) {
  748. pdu = SetRequestPdu.createFromBuffer (reader);
  749. } else if (type == PduType.GetNextRequest ) {
  750. pdu = GetNextRequestPdu.createFromBuffer (reader);
  751. } else if (type == PduType.GetBulkRequest ) {
  752. pdu = GetBulkRequestPdu.createFromBuffer (reader);
  753. } else {
  754. throw new ResponseInvalidError ("Unknown PDU type '" + type
  755. + "' in response", ResponseInvalidCode.EUnknownPduType);
  756. }
  757. if ( scoped ) {
  758. pdu.contextEngineID = contextEngineID;
  759. pdu.contextName = contextName;
  760. }
  761. pdu.scoped = scoped;
  762. return pdu;
  763. };
  764. var createDiscoveryPdu = function (context) {
  765. return GetRequestPdu.createFromVariables(_generateId(), [], {context: context});
  766. };
  767. var Authentication = {};
  768. Authentication.HMAC_BUFFER_SIZE = 1024*1024;
  769. Authentication.algorithms = {};
  770. Authentication.algorithms[AuthProtocols.md5] = {
  771. KEY_LENGTH: 16,
  772. AUTHENTICATION_CODE_LENGTH: 12,
  773. CRYPTO_ALGORITHM: 'md5'
  774. };
  775. Authentication.algorithms[AuthProtocols.sha] = {
  776. KEY_LENGTH: 20,
  777. AUTHENTICATION_CODE_LENGTH: 12,
  778. CRYPTO_ALGORITHM: 'sha1'
  779. };
  780. Authentication.algorithms[AuthProtocols.sha224] = {
  781. KEY_LENGTH: 28,
  782. AUTHENTICATION_CODE_LENGTH: 16,
  783. CRYPTO_ALGORITHM: 'sha224'
  784. };
  785. Authentication.algorithms[AuthProtocols.sha256] = {
  786. KEY_LENGTH: 32,
  787. AUTHENTICATION_CODE_LENGTH: 24,
  788. CRYPTO_ALGORITHM: 'sha256'
  789. };
  790. Authentication.algorithms[AuthProtocols.sha384] = {
  791. KEY_LENGTH: 48,
  792. AUTHENTICATION_CODE_LENGTH: 32,
  793. CRYPTO_ALGORITHM: 'sha384'
  794. };
  795. Authentication.algorithms[AuthProtocols.sha512] = {
  796. KEY_LENGTH: 64,
  797. AUTHENTICATION_CODE_LENGTH: 48,
  798. CRYPTO_ALGORITHM: 'sha512'
  799. };
  800. Authentication.authToKeyCache = {};
  801. Authentication.computeCacheKey = function (authProtocol, authPasswordString, engineID) {
  802. var engineIDString = engineID.toString('base64');
  803. return authProtocol + authPasswordString + engineIDString;
  804. };
  805. // Adapted from RFC3414 Appendix A.2.1. Password to Key Sample Code for MD5
  806. Authentication.passwordToKey = function (authProtocol, authPasswordString, engineID) {
  807. var hashAlgorithm;
  808. var firstDigest;
  809. var finalDigest;
  810. var buf;
  811. var cryptoAlgorithm = Authentication.algorithms[authProtocol].CRYPTO_ALGORITHM;
  812. var cacheKey = Authentication.computeCacheKey(authProtocol, authPasswordString, engineID);
  813. if (Authentication.authToKeyCache[cacheKey] !== undefined) {
  814. return Authentication.authToKeyCache[cacheKey];
  815. }
  816. buf = Buffer.alloc (Authentication.HMAC_BUFFER_SIZE, authPasswordString);
  817. hashAlgorithm = crypto.createHash(cryptoAlgorithm);
  818. hashAlgorithm.update(buf);
  819. firstDigest = hashAlgorithm.digest();
  820. // debug ("First digest: " + firstDigest.toString('hex'));
  821. hashAlgorithm = crypto.createHash(cryptoAlgorithm);
  822. hashAlgorithm.update(firstDigest);
  823. hashAlgorithm.update(engineID);
  824. hashAlgorithm.update(firstDigest);
  825. finalDigest = hashAlgorithm.digest();
  826. // debug ("Localized key: " + finalDigest.toString('hex'));
  827. Authentication.authToKeyCache[cacheKey] = finalDigest;
  828. return finalDigest;
  829. };
  830. Authentication.getParametersLength = function (authProtocol) {
  831. return Authentication.algorithms[authProtocol].AUTHENTICATION_CODE_LENGTH;
  832. };
  833. Authentication.writeParameters = function (messageBuffer, authProtocol, authPassword, engineID, digestInMessage) {
  834. var digestToAdd;
  835. digestToAdd = Authentication.calculateDigest (messageBuffer, authProtocol, authPassword, engineID);
  836. digestToAdd.copy (digestInMessage);
  837. // debug ("Added Auth Parameters: " + digestToAdd.toString('hex'));
  838. };
  839. Authentication.isAuthentic = function (messageBuffer, authProtocol, authPassword, engineID, digestInMessage) {
  840. var savedDigest;
  841. var calculatedDigest;
  842. if (digestInMessage.length !== Authentication.algorithms[authProtocol].AUTHENTICATION_CODE_LENGTH)
  843. return false;
  844. // save original authenticationParameters field in message
  845. savedDigest = Buffer.from (digestInMessage);
  846. // clear the authenticationParameters field in message
  847. digestInMessage.fill (0);
  848. calculatedDigest = Authentication.calculateDigest (messageBuffer, authProtocol, authPassword, engineID);
  849. // replace previously cleared authenticationParameters field in message
  850. savedDigest.copy (digestInMessage);
  851. // debug ("Digest in message: " + digestInMessage.toString('hex'));
  852. // debug ("Calculated digest: " + calculatedDigest.toString('hex'));
  853. return calculatedDigest.equals (digestInMessage);
  854. };
  855. Authentication.calculateDigest = function (messageBuffer, authProtocol, authPassword, engineID) {
  856. var authKey = Authentication.passwordToKey (authProtocol, authPassword, engineID);
  857. var cryptoAlgorithm = Authentication.algorithms[authProtocol].CRYPTO_ALGORITHM;
  858. var hmacAlgorithm = crypto.createHmac (cryptoAlgorithm, authKey);
  859. hmacAlgorithm.update (messageBuffer);
  860. var digest = hmacAlgorithm.digest ();
  861. return digest.subarray (0, Authentication.algorithms[authProtocol].AUTHENTICATION_CODE_LENGTH);
  862. };
  863. var Encryption = {};
  864. Encryption.encryptPdu = function (privProtocol, scopedPdu, privPassword, authProtocol, engine) {
  865. var encryptFunction = Encryption.algorithms[privProtocol].encryptPdu;
  866. return encryptFunction (scopedPdu, privProtocol, privPassword, authProtocol, engine);
  867. };
  868. Encryption.decryptPdu = function (privProtocol, encryptedPdu, privParameters, privPassword, authProtocol, engine) {
  869. var decryptFunction = Encryption.algorithms[privProtocol].decryptPdu;
  870. return decryptFunction (encryptedPdu, privProtocol, privParameters, privPassword, authProtocol, engine);
  871. };
  872. Encryption.debugEncrypt = function (encryptionKey, iv, plainPdu, encryptedPdu) {
  873. debug ("Key: " + encryptionKey.toString ('hex'));
  874. debug ("IV: " + iv.toString ('hex'));
  875. debug ("Plain: " + plainPdu.toString ('hex'));
  876. debug ("Encrypted: " + encryptedPdu.toString ('hex'));
  877. };
  878. Encryption.debugDecrypt = function (decryptionKey, iv, encryptedPdu, plainPdu) {
  879. debug ("Key: " + decryptionKey.toString ('hex'));
  880. debug ("IV: " + iv.toString ('hex'));
  881. debug ("Encrypted: " + encryptedPdu.toString ('hex'));
  882. debug ("Plain: " + plainPdu.toString ('hex'));
  883. };
  884. Encryption.generateLocalizedKey = function (algorithm, authProtocol, privPassword, engineID) {
  885. var privLocalizedKey;
  886. var encryptionKey;
  887. privLocalizedKey = Authentication.passwordToKey (authProtocol, privPassword, engineID);
  888. encryptionKey = Buffer.alloc (algorithm.KEY_LENGTH);
  889. privLocalizedKey.copy (encryptionKey, 0, 0, algorithm.KEY_LENGTH);
  890. return encryptionKey;
  891. };
  892. Encryption.generateLocalizedKeyBlumenthal = function (algorithm, authProtocol, privPassword, engineID) {
  893. let authKeyLength;
  894. let privLocalizedKey;
  895. let encryptionKey;
  896. let rounds;
  897. let hashInput;
  898. let nextHash;
  899. let hashAlgorithm;
  900. authKeyLength = Authentication.algorithms[authProtocol].KEY_LENGTH;
  901. rounds = Math.ceil (algorithm.KEY_LENGTH / authKeyLength );
  902. encryptionKey = Buffer.alloc (algorithm.KEY_LENGTH);
  903. privLocalizedKey = Authentication.passwordToKey (authProtocol, privPassword, engineID);
  904. nextHash = privLocalizedKey;
  905. for ( let round = 0 ; round < rounds ; round++ ) {
  906. nextHash.copy (encryptionKey, round * authKeyLength, 0, authKeyLength);
  907. if ( round < rounds - 1 ) {
  908. hashAlgorithm = crypto.createHash (Authentication.algorithms[authProtocol].CRYPTO_ALGORITHM);
  909. hashInput = Buffer.alloc ( (round + 1) * authKeyLength);
  910. encryptionKey.copy (hashInput, round * authKeyLength, 0, (round + 1) * authKeyLength);
  911. hashAlgorithm.update (hashInput);
  912. nextHash = hashAlgorithm.digest ();
  913. }
  914. }
  915. return encryptionKey;
  916. };
  917. Encryption.generateLocalizedKeyReeder = function (algorithm, authProtocol, privPassword, engineID) {
  918. let authKeyLength;
  919. let privLocalizedKey;
  920. let encryptionKey;
  921. let rounds;
  922. let nextPasswordInput;
  923. authKeyLength = Authentication.algorithms[authProtocol].KEY_LENGTH;
  924. rounds = Math.ceil (algorithm.KEY_LENGTH / authKeyLength );
  925. encryptionKey = Buffer.alloc (algorithm.KEY_LENGTH);
  926. nextPasswordInput = privPassword;
  927. for ( let round = 0 ; round < rounds ; round++ ) {
  928. privLocalizedKey = Authentication.passwordToKey (authProtocol, nextPasswordInput, engineID);
  929. privLocalizedKey.copy (encryptionKey, round * authKeyLength, 0, authKeyLength);
  930. nextPasswordInput = privLocalizedKey;
  931. }
  932. return encryptionKey;
  933. };
  934. Encryption.encryptPduDes = function (scopedPdu, privProtocol, privPassword, authProtocol, engine) {
  935. var des = Encryption.algorithms[PrivProtocols.des];
  936. var privLocalizedKey;
  937. var encryptionKey;
  938. var preIv;
  939. var salt;
  940. var iv;
  941. var i;
  942. var paddedScopedPduLength;
  943. var paddedScopedPdu;
  944. var encryptedPdu;
  945. var cipher;
  946. encryptionKey = Encryption.generateLocalizedKey (des, authProtocol, privPassword, engine.engineID);
  947. privLocalizedKey = Authentication.passwordToKey (authProtocol, privPassword, engine.engineID);
  948. encryptionKey = Buffer.alloc (des.KEY_LENGTH);
  949. privLocalizedKey.copy (encryptionKey, 0, 0, des.KEY_LENGTH);
  950. preIv = Buffer.alloc (des.BLOCK_LENGTH);
  951. privLocalizedKey.copy (preIv, 0, des.KEY_LENGTH, des.KEY_LENGTH + des.BLOCK_LENGTH);
  952. salt = Buffer.alloc (des.BLOCK_LENGTH);
  953. // set local SNMP engine boots part of salt to 1, as we have no persistent engine state
  954. salt.fill ('00000001', 0, 4, 'hex');
  955. // set local integer part of salt to random
  956. salt.fill (crypto.randomBytes (4), 4, 8);
  957. iv = Buffer.alloc (des.BLOCK_LENGTH);
  958. for (i = 0; i < iv.length; i++) {
  959. iv[i] = preIv[i] ^ salt[i];
  960. }
  961. if (scopedPdu.length % des.BLOCK_LENGTH == 0) {
  962. paddedScopedPdu = scopedPdu;
  963. } else {
  964. paddedScopedPduLength = des.BLOCK_LENGTH * (Math.floor (scopedPdu.length / des.BLOCK_LENGTH) + 1);
  965. paddedScopedPdu = Buffer.alloc (paddedScopedPduLength);
  966. scopedPdu.copy (paddedScopedPdu, 0, 0, scopedPdu.length);
  967. }
  968. cipher = crypto.createCipheriv (des.CRYPTO_ALGORITHM, encryptionKey, iv);
  969. encryptedPdu = cipher.update (paddedScopedPdu);
  970. encryptedPdu = Buffer.concat ([encryptedPdu, cipher.final()]);
  971. // Encryption.debugEncrypt (encryptionKey, iv, paddedScopedPdu, encryptedPdu);
  972. return {
  973. encryptedPdu: encryptedPdu,
  974. msgPrivacyParameters: salt
  975. };
  976. };
  977. Encryption.decryptPduDes = function (encryptedPdu, privProtocol, privParameters, privPassword, authProtocol, engine) {
  978. var des = Encryption.algorithms[PrivProtocols.des];
  979. var privLocalizedKey;
  980. var decryptionKey;
  981. var preIv;
  982. var salt;
  983. var iv;
  984. var i;
  985. var decryptedPdu;
  986. var decipher;
  987. privLocalizedKey = Authentication.passwordToKey (authProtocol, privPassword, engine.engineID);
  988. decryptionKey = Buffer.alloc (des.KEY_LENGTH);
  989. privLocalizedKey.copy (decryptionKey, 0, 0, des.KEY_LENGTH);
  990. preIv = Buffer.alloc (des.BLOCK_LENGTH);
  991. privLocalizedKey.copy (preIv, 0, des.KEY_LENGTH, des.KEY_LENGTH + des.BLOCK_LENGTH);
  992. salt = privParameters;
  993. iv = Buffer.alloc (des.BLOCK_LENGTH);
  994. for (i = 0; i < iv.length; i++) {
  995. iv[i] = preIv[i] ^ salt[i];
  996. }
  997. decipher = crypto.createDecipheriv (des.CRYPTO_ALGORITHM, decryptionKey, iv);
  998. decipher.setAutoPadding(false);
  999. decryptedPdu = decipher.update (encryptedPdu);
  1000. decryptedPdu = Buffer.concat ([decryptedPdu, decipher.final()]);
  1001. // Encryption.debugDecrypt (decryptionKey, iv, encryptedPdu, decryptedPdu);
  1002. return decryptedPdu;
  1003. };
  1004. Encryption.generateIvAes = function (aes, engineBoots, engineTime, salt) {
  1005. var iv;
  1006. var engineBootsBuffer;
  1007. var engineTimeBuffer;
  1008. // iv = engineBoots(4) | engineTime(4) | salt(8)
  1009. iv = Buffer.alloc (aes.BLOCK_LENGTH);
  1010. engineBootsBuffer = Buffer.alloc (4);
  1011. engineBootsBuffer.writeUInt32BE (engineBoots);
  1012. engineTimeBuffer = Buffer.alloc (4);
  1013. engineTimeBuffer.writeUInt32BE (engineTime);
  1014. engineBootsBuffer.copy (iv, 0, 0, 4);
  1015. engineTimeBuffer.copy (iv, 4, 0, 4);
  1016. salt.copy (iv, 8, 0, 8);
  1017. return iv;
  1018. };
  1019. Encryption.encryptPduAes = function (scopedPdu, privProtocol, privPassword, authProtocol, engine) {
  1020. var aes = Encryption.algorithms[privProtocol];
  1021. var localizationAlgorithm = aes.localizationAlgorithm;
  1022. var encryptionKey;
  1023. var salt;
  1024. var iv;
  1025. var cipher;
  1026. var encryptedPdu;
  1027. encryptionKey = localizationAlgorithm (aes, authProtocol, privPassword, engine.engineID);
  1028. salt = Buffer.alloc (8).fill (crypto.randomBytes (8), 0, 8);
  1029. iv = Encryption.generateIvAes (aes, engine.engineBoots, engine.engineTime, salt);
  1030. cipher = crypto.createCipheriv (aes.CRYPTO_ALGORITHM, encryptionKey, iv);
  1031. encryptedPdu = cipher.update (scopedPdu);
  1032. encryptedPdu = Buffer.concat ([encryptedPdu, cipher.final()]);
  1033. // Encryption.debugEncrypt (encryptionKey, iv, scopedPdu, encryptedPdu);
  1034. return {
  1035. encryptedPdu: encryptedPdu,
  1036. msgPrivacyParameters: salt
  1037. };
  1038. };
  1039. Encryption.decryptPduAes = function (encryptedPdu, privProtocol, privParameters, privPassword, authProtocol, engine) {
  1040. var aes = Encryption.algorithms[privProtocol];
  1041. var localizationAlgorithm = aes.localizationAlgorithm;
  1042. var decryptionKey;
  1043. var iv;
  1044. var decipher;
  1045. var decryptedPdu;
  1046. decryptionKey = localizationAlgorithm (aes, authProtocol, privPassword, engine.engineID);
  1047. iv = Encryption.generateIvAes (aes, engine.engineBoots, engine.engineTime, privParameters);
  1048. decipher = crypto.createDecipheriv (aes.CRYPTO_ALGORITHM, decryptionKey, iv);
  1049. decryptedPdu = decipher.update (encryptedPdu);
  1050. decryptedPdu = Buffer.concat ([decryptedPdu, decipher.final()]);
  1051. // Encryption.debugDecrypt (decryptionKey, iv, encryptedPdu, decryptedPdu);
  1052. return decryptedPdu;
  1053. };
  1054. Encryption.algorithms = {};
  1055. Encryption.algorithms[PrivProtocols.des] = {
  1056. CRYPTO_ALGORITHM: 'des-cbc',
  1057. KEY_LENGTH: 8,
  1058. BLOCK_LENGTH: 8,
  1059. encryptPdu: Encryption.encryptPduDes,
  1060. decryptPdu: Encryption.decryptPduDes,
  1061. localizationAlgorithm: Encryption.generateLocalizedKey
  1062. };
  1063. Encryption.algorithms[PrivProtocols.aes] = {
  1064. CRYPTO_ALGORITHM: 'aes-128-cfb',
  1065. KEY_LENGTH: 16,
  1066. BLOCK_LENGTH: 16,
  1067. encryptPdu: Encryption.encryptPduAes,
  1068. decryptPdu: Encryption.decryptPduAes,
  1069. localizationAlgorithm: Encryption.generateLocalizedKey
  1070. };
  1071. Encryption.algorithms[PrivProtocols.aes256b] = {
  1072. CRYPTO_ALGORITHM: 'aes-256-cfb',
  1073. KEY_LENGTH: 32,
  1074. BLOCK_LENGTH: 16,
  1075. encryptPdu: Encryption.encryptPduAes,
  1076. decryptPdu: Encryption.decryptPduAes,
  1077. localizationAlgorithm: Encryption.generateLocalizedKeyBlumenthal
  1078. };
  1079. Encryption.algorithms[PrivProtocols.aes256r] = {
  1080. CRYPTO_ALGORITHM: 'aes-256-cfb',
  1081. KEY_LENGTH: 32,
  1082. BLOCK_LENGTH: 16,
  1083. encryptPdu: Encryption.encryptPduAes,
  1084. decryptPdu: Encryption.decryptPduAes,
  1085. localizationAlgorithm: Encryption.generateLocalizedKeyReeder
  1086. };
  1087. /*****************************************************************************
  1088. ** Message class definition
  1089. **/
  1090. var Message = function () {
  1091. };
  1092. Message.prototype.getReqId = function () {
  1093. return this.version == Version3 ? this.msgGlobalData.msgID : this.pdu.id;
  1094. };
  1095. Message.prototype.toBuffer = function () {
  1096. if ( this.version == Version3 ) {
  1097. return this.toBufferV3();
  1098. } else {
  1099. return this.toBufferCommunity();
  1100. }
  1101. };
  1102. Message.prototype.toBufferCommunity = function () {
  1103. if (this.buffer)
  1104. return this.buffer;
  1105. var writer = new ber.Writer ();
  1106. writer.startSequence ();
  1107. writeInt32 (writer, ObjectType.Integer, this.version);
  1108. writer.writeString (this.community);
  1109. this.pdu.toBuffer (writer);
  1110. writer.endSequence ();
  1111. this.buffer = writer.buffer;
  1112. return this.buffer;
  1113. };
  1114. Message.prototype.toBufferV3 = function () {
  1115. var encryptionResult;
  1116. if (this.buffer)
  1117. return this.buffer;
  1118. // ScopedPDU
  1119. var scopedPduWriter = new ber.Writer ();
  1120. scopedPduWriter.startSequence ();
  1121. var contextEngineID = this.pdu.contextEngineID ? this.pdu.contextEngineID : this.msgSecurityParameters.msgAuthoritativeEngineID;
  1122. if ( contextEngineID.length == 0 ) {
  1123. scopedPduWriter.writeString ("");
  1124. } else {
  1125. scopedPduWriter.writeBuffer (contextEngineID, ber.OctetString);
  1126. }
  1127. scopedPduWriter.writeString (this.pdu.contextName);
  1128. this.pdu.toBuffer (scopedPduWriter);
  1129. scopedPduWriter.endSequence ();
  1130. if ( this.hasPrivacy() ) {
  1131. var authoritativeEngine = {
  1132. engineID: this.msgSecurityParameters.msgAuthoritativeEngineID,
  1133. engineBoots: this.msgSecurityParameters.msgAuthoritativeEngineBoots,
  1134. engineTime: this.msgSecurityParameters.msgAuthoritativeEngineTime,
  1135. };
  1136. encryptionResult = Encryption.encryptPdu (this.user.privProtocol, scopedPduWriter.buffer,
  1137. this.user.privKey, this.user.authProtocol, authoritativeEngine);
  1138. }
  1139. var writer = new ber.Writer ();
  1140. writer.startSequence ();
  1141. writeInt32 (writer, ObjectType.Integer, this.version);
  1142. // HeaderData
  1143. writer.startSequence ();
  1144. writeInt32 (writer, ObjectType.Integer, this.msgGlobalData.msgID);
  1145. writeInt32 (writer, ObjectType.Integer, this.msgGlobalData.msgMaxSize);
  1146. writer.writeByte (ber.OctetString);
  1147. writer.writeByte (1);
  1148. writer.writeByte (this.msgGlobalData.msgFlags);
  1149. writeInt32 (writer, ObjectType.Integer, this.msgGlobalData.msgSecurityModel);
  1150. writer.endSequence ();
  1151. // msgSecurityParameters
  1152. writer.startSequence (ber.OctetString);
  1153. writer.startSequence ();
  1154. //writer.writeString (this.msgSecurityParameters.msgAuthoritativeEngineID);
  1155. // writing a zero-length buffer fails - should fix asn1-ber for this condition
  1156. if ( this.msgSecurityParameters.msgAuthoritativeEngineID.length == 0 ) {
  1157. writer.writeString ("");
  1158. } else {
  1159. writer.writeBuffer (this.msgSecurityParameters.msgAuthoritativeEngineID, ber.OctetString);
  1160. }
  1161. writeInt32 (writer, ObjectType.Integer, this.msgSecurityParameters.msgAuthoritativeEngineBoots);
  1162. writeInt32 (writer, ObjectType.Integer, this.msgSecurityParameters.msgAuthoritativeEngineTime);
  1163. writer.writeString (this.msgSecurityParameters.msgUserName);
  1164. var msgAuthenticationParameters = '';
  1165. if ( this.hasAuthentication() ) {
  1166. var authParametersLength = Authentication.getParametersLength (this.user.authProtocol);
  1167. msgAuthenticationParameters = Buffer.alloc (authParametersLength);
  1168. writer.writeBuffer (msgAuthenticationParameters, ber.OctetString);
  1169. } else {
  1170. writer.writeString ("");
  1171. }
  1172. var msgAuthenticationParametersOffset = writer._offset - msgAuthenticationParameters.length;
  1173. if ( this.hasPrivacy() ) {
  1174. writer.writeBuffer (encryptionResult.msgPrivacyParameters, ber.OctetString);
  1175. } else {
  1176. writer.writeString ("");
  1177. }
  1178. msgAuthenticationParametersOffset -= writer._offset;
  1179. writer.endSequence ();
  1180. writer.endSequence ();
  1181. msgAuthenticationParametersOffset += writer._offset;
  1182. if ( this.hasPrivacy() ) {
  1183. writer.writeBuffer (encryptionResult.encryptedPdu, ber.OctetString);
  1184. } else {
  1185. writer.writeBuffer (scopedPduWriter.buffer);
  1186. }
  1187. msgAuthenticationParametersOffset -= writer._offset;
  1188. writer.endSequence ();
  1189. msgAuthenticationParametersOffset += writer._offset;
  1190. this.buffer = writer.buffer;
  1191. if ( this.hasAuthentication() ) {
  1192. msgAuthenticationParameters = this.buffer.subarray (msgAuthenticationParametersOffset,
  1193. msgAuthenticationParametersOffset + msgAuthenticationParameters.length);
  1194. Authentication.writeParameters (this.buffer, this.user.authProtocol, this.user.authKey,
  1195. this.msgSecurityParameters.msgAuthoritativeEngineID, msgAuthenticationParameters);
  1196. }
  1197. return this.buffer;
  1198. };
  1199. Message.prototype.processIncomingSecurity = function (user, responseCb) {
  1200. if ( this.hasPrivacy() ) {
  1201. if ( ! this.decryptPdu(user, responseCb) ) {
  1202. return false;
  1203. }
  1204. }
  1205. if ( this.hasAuthentication() && ! this.isAuthenticationDisabled() ) {
  1206. return this.checkAuthentication(user, responseCb);
  1207. } else {
  1208. return true;
  1209. }
  1210. };
  1211. Message.prototype.decryptPdu = function (user, responseCb) {
  1212. var decryptedPdu;
  1213. var decryptedPduReader;
  1214. try {
  1215. var authoratitiveEngine = {
  1216. engineID: this.msgSecurityParameters.msgAuthoritativeEngineID,
  1217. engineBoots: this.msgSecurityParameters.msgAuthoritativeEngineBoots,
  1218. engineTime: this.msgSecurityParameters.msgAuthoritativeEngineTime
  1219. };
  1220. decryptedPdu = Encryption.decryptPdu(user.privProtocol, this.encryptedPdu,
  1221. this.msgSecurityParameters.msgPrivacyParameters, user.privKey, user.authProtocol,
  1222. authoratitiveEngine);
  1223. decryptedPduReader = new ber.Reader (decryptedPdu);
  1224. this.pdu = readPdu(decryptedPduReader, true);
  1225. return true;
  1226. } catch (error) {
  1227. responseCb (new ResponseInvalidError ("Failed to decrypt PDU: " + error,
  1228. ResponseInvalidCode.ECouldNotDecrypt));
  1229. return false;
  1230. }
  1231. };
  1232. Message.prototype.checkAuthentication = function (user, responseCb) {
  1233. if ( Authentication.isAuthentic(this.buffer, user.authProtocol, user.authKey,
  1234. this.msgSecurityParameters.msgAuthoritativeEngineID, this.msgSecurityParameters.msgAuthenticationParameters) ) {
  1235. return true;
  1236. } else {
  1237. responseCb (new ResponseInvalidError ("Authentication digest "
  1238. + this.msgSecurityParameters.msgAuthenticationParameters.toString ('hex')
  1239. + " received in message does not match digest "
  1240. + Authentication.calculateDigest (this.buffer, user.authProtocol, user.authKey,
  1241. this.msgSecurityParameters.msgAuthoritativeEngineID).toString ('hex')
  1242. + " calculated for message", ResponseInvalidCode.EAuthFailure, { user }));
  1243. return false;
  1244. }
  1245. };
  1246. Message.prototype.setMsgFlags = function (bitPosition, flag) {
  1247. if ( this.msgGlobalData && this.msgGlobalData !== undefined && this.msgGlobalData !== null ) {
  1248. if ( flag ) {
  1249. this.msgGlobalData.msgFlags = this.msgGlobalData.msgFlags | ( 2 ** bitPosition );
  1250. } else {
  1251. this.msgGlobalData.msgFlags = this.msgGlobalData.msgFlags & ( 255 - 2 ** bitPosition );
  1252. }
  1253. }
  1254. };
  1255. Message.prototype.hasAuthentication = function () {
  1256. return this.msgGlobalData && this.msgGlobalData.msgFlags && this.msgGlobalData.msgFlags & 1;
  1257. };
  1258. Message.prototype.setAuthentication = function (flag) {
  1259. this.setMsgFlags (0, flag);
  1260. };
  1261. Message.prototype.hasPrivacy = function () {
  1262. return this.msgGlobalData && this.msgGlobalData.msgFlags && this.msgGlobalData.msgFlags & 2;
  1263. };
  1264. Message.prototype.setPrivacy = function (flag) {
  1265. this.setMsgFlags (1, flag);
  1266. };
  1267. Message.prototype.isReportable = function () {
  1268. return this.msgGlobalData && this.msgGlobalData.msgFlags && this.msgGlobalData.msgFlags & 4;
  1269. };
  1270. Message.prototype.setReportable = function (flag) {
  1271. this.setMsgFlags (2, flag);
  1272. };
  1273. Message.prototype.isAuthenticationDisabled = function () {
  1274. return this.disableAuthentication;
  1275. };
  1276. Message.prototype.hasAuthoritativeEngineID = function () {
  1277. return this.msgSecurityParameters && this.msgSecurityParameters.msgAuthoritativeEngineID &&
  1278. this.msgSecurityParameters.msgAuthoritativeEngineID != "";
  1279. };
  1280. Message.prototype.createReportResponseMessage = function (engine, context) {
  1281. var user = {
  1282. name: "",
  1283. level: SecurityLevel.noAuthNoPriv
  1284. };
  1285. var responseSecurityParameters = {
  1286. msgAuthoritativeEngineID: engine.engineID,
  1287. msgAuthoritativeEngineBoots: engine.engineBoots,
  1288. msgAuthoritativeEngineTime: engine.engineTime,
  1289. msgUserName: user.name,
  1290. msgAuthenticationParameters: "",
  1291. msgPrivacyParameters: ""
  1292. };
  1293. var reportPdu = ReportPdu.createFromVariables (this.pdu.id, [], {});
  1294. reportPdu.contextName = context;
  1295. var responseMessage = Message.createRequestV3 (user, responseSecurityParameters, reportPdu);
  1296. responseMessage.msgGlobalData.msgID = this.msgGlobalData.msgID;
  1297. return responseMessage;
  1298. };
  1299. Message.prototype.createResponseForRequest = function (responsePdu) {
  1300. if ( this.version == Version3 ) {
  1301. return this.createV3ResponseFromRequest(responsePdu);
  1302. } else {
  1303. return this.createCommunityResponseFromRequest(responsePdu);
  1304. }
  1305. };
  1306. Message.prototype.createCommunityResponseFromRequest = function (responsePdu) {
  1307. return Message.createCommunity(this.version, this.community, responsePdu);
  1308. };
  1309. Message.prototype.createV3ResponseFromRequest = function (responsePdu) {
  1310. var responseUser = {
  1311. name: this.user.name,
  1312. level: this.user.level,
  1313. authProtocol: this.user.authProtocol,
  1314. authKey: this.user.authKey,
  1315. privProtocol: this.user.privProtocol,
  1316. privKey: this.user.privKey
  1317. };
  1318. var responseSecurityParameters = {
  1319. msgAuthoritativeEngineID: this.msgSecurityParameters.msgAuthoritativeEngineID,
  1320. msgAuthoritativeEngineBoots: this.msgSecurityParameters.msgAuthoritativeEngineBoots,
  1321. msgAuthoritativeEngineTime: this.msgSecurityParameters.msgAuthoritativeEngineTime,
  1322. msgUserName: this.msgSecurityParameters.msgUserName,
  1323. msgAuthenticationParameters: "",
  1324. msgPrivacyParameters: ""
  1325. };
  1326. var responseGlobalData = {
  1327. msgID: this.msgGlobalData.msgID,
  1328. msgMaxSize: 65507,
  1329. msgFlags: this.msgGlobalData.msgFlags & (255 - 4),
  1330. msgSecurityModel: 3
  1331. };
  1332. return Message.createV3 (responseUser, responseGlobalData, responseSecurityParameters, responsePdu);
  1333. };
  1334. Message.createCommunity = function (version, community, pdu) {
  1335. var message = new Message ();
  1336. message.version = version;
  1337. message.community = community;
  1338. message.pdu = pdu;
  1339. return message;
  1340. };
  1341. Message.createRequestV3 = function (user, msgSecurityParameters, pdu) {
  1342. var authFlag = user.level == SecurityLevel.authNoPriv || user.level == SecurityLevel.authPriv ? 1 : 0;
  1343. var privFlag = user.level == SecurityLevel.authPriv ? 1 : 0;
  1344. var reportableFlag = ( pdu.type == PduType.GetResponse || pdu.type == PduType.TrapV2 ) ? 0 : 1;
  1345. var msgGlobalData = {
  1346. msgID: _generateId(), // random ID
  1347. msgMaxSize: 65507,
  1348. msgFlags: reportableFlag * 4 | privFlag * 2 | authFlag * 1,
  1349. msgSecurityModel: 3
  1350. };
  1351. return Message.createV3 (user, msgGlobalData, msgSecurityParameters, pdu);
  1352. };
  1353. Message.createV3 = function (user, msgGlobalData, msgSecurityParameters, pdu) {
  1354. var message = new Message ();
  1355. message.version = 3;
  1356. message.user = user;
  1357. message.msgGlobalData = msgGlobalData;
  1358. message.msgSecurityParameters = {
  1359. msgAuthoritativeEngineID: msgSecurityParameters.msgAuthoritativeEngineID || Buffer.from(""),
  1360. msgAuthoritativeEngineBoots: msgSecurityParameters.msgAuthoritativeEngineBoots || 0,
  1361. msgAuthoritativeEngineTime: msgSecurityParameters.msgAuthoritativeEngineTime || 0,
  1362. msgUserName: user.name || "",
  1363. msgAuthenticationParameters: "",
  1364. msgPrivacyParameters: ""
  1365. };
  1366. message.pdu = pdu;
  1367. return message;
  1368. };
  1369. Message.createDiscoveryV3 = function (pdu) {
  1370. var msgSecurityParameters = {
  1371. msgAuthoritativeEngineID: Buffer.from(""),
  1372. msgAuthoritativeEngineBoots: 0,
  1373. msgAuthoritativeEngineTime: 0
  1374. };
  1375. var emptyUser = {
  1376. name: "",
  1377. level: SecurityLevel.noAuthNoPriv
  1378. };
  1379. return Message.createRequestV3 (emptyUser, msgSecurityParameters, pdu);
  1380. };
  1381. Message.createFromBuffer = function (buffer, user) {
  1382. var reader = new ber.Reader (buffer);
  1383. var message = new Message();
  1384. reader.readSequence ();
  1385. message.version = readInt32 (reader);
  1386. if (message.version != 3) {
  1387. message.community = reader.readString ();
  1388. message.pdu = readPdu(reader, false);
  1389. } else {
  1390. // HeaderData
  1391. message.msgGlobalData = {};
  1392. reader.readSequence ();
  1393. message.msgGlobalData.msgID = readInt32 (reader);
  1394. message.msgGlobalData.msgMaxSize = readInt32 (reader);
  1395. message.msgGlobalData.msgFlags = reader.readString (ber.OctetString, true)[0];
  1396. message.msgGlobalData.msgSecurityModel = readInt32 (reader);
  1397. // msgSecurityParameters
  1398. message.msgSecurityParameters = {};
  1399. var msgSecurityParametersReader = new ber.Reader (reader.readString (ber.OctetString, true));
  1400. msgSecurityParametersReader.readSequence ();
  1401. message.msgSecurityParameters.msgAuthoritativeEngineID = msgSecurityParametersReader.readString (ber.OctetString, true);
  1402. message.msgSecurityParameters.msgAuthoritativeEngineBoots = readInt32 (msgSecurityParametersReader);
  1403. message.msgSecurityParameters.msgAuthoritativeEngineTime = readInt32 (msgSecurityParametersReader);
  1404. message.msgSecurityParameters.msgUserName = msgSecurityParametersReader.readString ();
  1405. message.msgSecurityParameters.msgAuthenticationParameters = msgSecurityParametersReader.readString (ber.OctetString, true);
  1406. message.msgSecurityParameters.msgPrivacyParameters = Buffer.from(msgSecurityParametersReader.readString (ber.OctetString, true));
  1407. if ( message.hasPrivacy() ) {
  1408. message.encryptedPdu = reader.readString (ber.OctetString, true);
  1409. message.pdu = null;
  1410. } else {
  1411. message.pdu = readPdu(reader, true);
  1412. }
  1413. }
  1414. message.buffer = buffer;
  1415. return message;
  1416. };
  1417. var Req = function (session, message, feedCb, responseCb, options) {
  1418. this.message = message;
  1419. this.responseCb = responseCb;
  1420. this.retries = session.retries;
  1421. this.timeout = session.timeout;
  1422. // Add timeout backoff
  1423. this.backoff = session.backoff;
  1424. this.onResponse = session.onSimpleGetResponse;
  1425. this.feedCb = feedCb;
  1426. this.port = (options && options.port) ? options.port : session.port;
  1427. this.context = session.context;
  1428. };
  1429. Req.prototype.getId = function() {
  1430. return this.message.getReqId ();
  1431. };
  1432. /*****************************************************************************
  1433. ** Session class definition
  1434. **/
  1435. var Session = function (target, authenticator, options) {
  1436. this.target = target || "127.0.0.1";
  1437. options = options || {};
  1438. this.version = options.version
  1439. ? options.version
  1440. : Version1;
  1441. if ( this.version == Version3 ) {
  1442. this.user = authenticator;
  1443. } else {
  1444. this.community = authenticator || "public";
  1445. }
  1446. this.transport = options.transport
  1447. ? options.transport
  1448. : "udp4";
  1449. this.port = options.port
  1450. ? options.port
  1451. : 161;
  1452. this.trapPort = options.trapPort
  1453. ? options.trapPort
  1454. : 162;
  1455. this.retries = (options.retries || options.retries == 0)
  1456. ? options.retries
  1457. : 1;
  1458. this.timeout = options.timeout
  1459. ? options.timeout
  1460. : 5000;
  1461. this.backoff = options.backoff >= 1.0
  1462. ? options.backoff
  1463. : 1.0;
  1464. this.sourceAddress = options.sourceAddress
  1465. ? options.sourceAddress
  1466. : undefined;
  1467. this.sourcePort = options.sourcePort
  1468. ? parseInt(options.sourcePort)
  1469. : undefined;
  1470. this.idBitsSize = options.idBitsSize
  1471. ? parseInt(options.idBitsSize)
  1472. : 32;
  1473. this.context = options.context
  1474. ? options.context
  1475. : "";
  1476. this.backwardsGetNexts = (typeof options.backwardsGetNexts !== 'undefined')
  1477. ? options.backwardsGetNexts
  1478. : true;
  1479. this.reportOidMismatchErrors = (typeof options.reportOidMismatchErrors !== 'undefined')
  1480. ? options.reportOidMismatchErrors
  1481. : false;
  1482. DEBUG = options.debug;
  1483. this.engine = new Engine (options.engineID);
  1484. this.reqs = {};
  1485. this.reqCount = 0;
  1486. this.dgram = dgram.createSocket (this.transport);
  1487. this.dgram.unref();
  1488. var me = this;
  1489. this.dgram.on ("message", me.onMsg.bind (me));
  1490. this.dgram.on ("close", me.onClose.bind (me));
  1491. this.dgram.on ("error", me.onError.bind (me));
  1492. if (this.sourceAddress || this.sourcePort)
  1493. this.dgram.bind (this.sourcePort, this.sourceAddress);
  1494. };
  1495. util.inherits (Session, events.EventEmitter);
  1496. Session.prototype.close = function () {
  1497. this.dgram.close ();
  1498. return this;
  1499. };
  1500. Session.prototype.cancelRequests = function (error) {
  1501. var id;
  1502. for (id in this.reqs) {
  1503. var req = this.reqs[id];
  1504. this.unregisterRequest (req.getId ());
  1505. req.responseCb (error);
  1506. }
  1507. };
  1508. function _generateId (bitSize) {
  1509. if (bitSize === 16) {
  1510. return Math.floor(Math.random() * 10000) % 65535;
  1511. }
  1512. return Math.floor(Math.random() * 100000000) % 4294967295;
  1513. }
  1514. Session.prototype.get = function (oids, responseCb) {
  1515. var reportOidMismatchErrors = this.reportOidMismatchErrors;
  1516. function feedCb (req, message) {
  1517. var pdu = message.pdu;
  1518. var varbinds = [];
  1519. if (req.message.pdu.varbinds.length != pdu.varbinds.length) {
  1520. req.responseCb (new ResponseInvalidError ("Requested OIDs do not "
  1521. + "match response OIDs", ResponseInvalidCode.EReqResOidNoMatch));
  1522. } else {
  1523. for (var i = 0; i < req.message.pdu.varbinds.length; i++) {
  1524. if ( reportOidMismatchErrors && req.message.pdu.varbinds[i].oid != pdu.varbinds[i].oid ) {
  1525. req.responseCb (new ResponseInvalidError ("OID '"
  1526. + req.message.pdu.varbinds[i].oid
  1527. + "' in request at position '" + i + "' does not "
  1528. + "match OID '" + pdu.varbinds[i].oid + "' in response "
  1529. + "at position '" + i + "'", ResponseInvalidCode.EReqResOidNoMatch));
  1530. return;
  1531. } else {
  1532. varbinds.push (pdu.varbinds[i]);
  1533. }
  1534. }
  1535. req.responseCb (null, varbinds);
  1536. }
  1537. }
  1538. var pduVarbinds = [];
  1539. for (var i = 0; i < oids.length; i++) {
  1540. var varbind = {
  1541. oid: oids[i]
  1542. };
  1543. pduVarbinds.push (varbind);
  1544. }
  1545. this.simpleGet (GetRequestPdu, feedCb, pduVarbinds, responseCb);
  1546. return this;
  1547. };
  1548. Session.prototype.getBulk = function () {
  1549. var oids, nonRepeaters, maxRepetitions, responseCb;
  1550. var reportOidMismatchErrors = this.reportOidMismatchErrors;
  1551. var backwardsGetNexts = this.backwardsGetNexts;
  1552. if (arguments.length >= 4) {
  1553. oids = arguments[0];
  1554. nonRepeaters = arguments[1];
  1555. maxRepetitions = arguments[2];
  1556. responseCb = arguments[3];
  1557. } else if (arguments.length >= 3) {
  1558. oids = arguments[0];
  1559. nonRepeaters = arguments[1];
  1560. maxRepetitions = 10;
  1561. responseCb = arguments[2];
  1562. } else {
  1563. oids = arguments[0];
  1564. nonRepeaters = 0;
  1565. maxRepetitions = 10;
  1566. responseCb = arguments[1];
  1567. }
  1568. function feedCb (req, message) {
  1569. var pdu = message.pdu;
  1570. var reqVarbinds = req.message.pdu.varbinds;
  1571. var varbinds = [];
  1572. var i = 0;
  1573. for ( ; i < reqVarbinds.length && i < pdu.varbinds.length; i++) {
  1574. if (isVarbindError (pdu.varbinds[i])) {
  1575. if ( reportOidMismatchErrors && reqVarbinds[i].oid != pdu.varbinds[i].oid ) {
  1576. req.responseCb (new ResponseInvalidError ("OID '" + reqVarbinds[i].oid
  1577. + "' in request at position '" + i + "' does not "
  1578. + "match OID '" + pdu.varbinds[i].oid + "' in response "
  1579. + "at position '" + i + "'", ResponseInvalidCode.EReqResOidNoMatch));
  1580. return;
  1581. }
  1582. } else {
  1583. if ( ! backwardsGetNexts && ! oidFollowsOid (reqVarbinds[i].oid, pdu.varbinds[i].oid)) {
  1584. req.responseCb (new ResponseInvalidError ("OID '" + reqVarbinds[i].oid
  1585. + "' in request at positiion '" + i + "' does not "
  1586. + "precede OID '" + pdu.varbinds[i].oid + "' in response "
  1587. + "at position '" + i + "'", ResponseInvalidCode.EOutOfOrder));
  1588. return;
  1589. }
  1590. }
  1591. if (i < nonRepeaters)
  1592. varbinds.push (pdu.varbinds[i]);
  1593. else
  1594. varbinds.push ([pdu.varbinds[i]]);
  1595. }
  1596. var repeaters = reqVarbinds.length - nonRepeaters;
  1597. for ( ; i < pdu.varbinds.length; i++) {
  1598. var reqIndex = (i - nonRepeaters) % repeaters + nonRepeaters;
  1599. var prevIndex = i - repeaters;
  1600. var prevOid = pdu.varbinds[prevIndex].oid;
  1601. if (isVarbindError (pdu.varbinds[i])) {
  1602. if ( reportOidMismatchErrors && prevOid != pdu.varbinds[i].oid ) {
  1603. req.responseCb (new ResponseInvalidError ("OID '" + prevOid
  1604. + "' in response at position '" + prevIndex + "' does not "
  1605. + "match OID '" + pdu.varbinds[i].oid + "' in response "
  1606. + "at position '" + i + "'", ResponseInvalidCode.EReqResOidNoMatch));
  1607. return;
  1608. }
  1609. } else {
  1610. if ( ! backwardsGetNexts && ! oidFollowsOid (prevOid, pdu.varbinds[i].oid)) {
  1611. req.responseCb (new ResponseInvalidError ("OID '" + prevOid
  1612. + "' in response at positiion '" + prevIndex + "' does not "
  1613. + "precede OID '" + pdu.varbinds[i].oid + "' in response "
  1614. + "at position '" + i + "'", ResponseInvalidCode.EOutOfOrder));
  1615. return;
  1616. }
  1617. }
  1618. varbinds[reqIndex].push (pdu.varbinds[i]);
  1619. }
  1620. req.responseCb (null, varbinds);
  1621. }
  1622. var pduVarbinds = [];
  1623. for (var i = 0; i < oids.length; i++) {
  1624. var varbind = {
  1625. oid: oids[i]
  1626. };
  1627. pduVarbinds.push (varbind);
  1628. }
  1629. var options = {
  1630. nonRepeaters: nonRepeaters,
  1631. maxRepetitions: maxRepetitions
  1632. };
  1633. this.simpleGet (GetBulkRequestPdu, feedCb, pduVarbinds, responseCb,
  1634. options);
  1635. return this;
  1636. };
  1637. Session.prototype.getNext = function (oids, responseCb) {
  1638. var backwardsGetNexts = this.backwardsGetNexts;
  1639. function feedCb (req, message) {
  1640. var pdu = message.pdu;
  1641. var varbinds = [];
  1642. if (req.message.pdu.varbinds.length != pdu.varbinds.length) {
  1643. req.responseCb (new ResponseInvalidError ("Requested OIDs do not "
  1644. + "match response OIDs", ResponseInvalidCode.EReqResOidNoMatch));
  1645. } else {
  1646. for (var i = 0; i < req.message.pdu.varbinds.length; i++) {
  1647. if (isVarbindError (pdu.varbinds[i])) {
  1648. varbinds.push (pdu.varbinds[i]);
  1649. } else if ( ! backwardsGetNexts && ! oidFollowsOid (req.message.pdu.varbinds[i].oid,
  1650. pdu.varbinds[i].oid)) {
  1651. req.responseCb (new ResponseInvalidError ("OID '"
  1652. + req.message.pdu.varbinds[i].oid + "' in request at "
  1653. + "positiion '" + i + "' does not precede "
  1654. + "OID '" + pdu.varbinds[i].oid + "' in response "
  1655. + "at position '" + i + "'", ResponseInvalidCode.OutOfOrder));
  1656. return;
  1657. } else {
  1658. varbinds.push (pdu.varbinds[i]);
  1659. }
  1660. }
  1661. req.responseCb (null, varbinds);
  1662. }
  1663. }
  1664. var pduVarbinds = [];
  1665. for (var i = 0; i < oids.length; i++) {
  1666. var varbind = {
  1667. oid: oids[i]
  1668. };
  1669. pduVarbinds.push (varbind);
  1670. }
  1671. this.simpleGet (GetNextRequestPdu, feedCb, pduVarbinds, responseCb);
  1672. return this;
  1673. };
  1674. Session.prototype.inform = function () {
  1675. var typeOrOid = arguments[0];
  1676. var varbinds, options = {}, responseCb;
  1677. /**
  1678. ** Support the following signatures:
  1679. **
  1680. ** typeOrOid, varbinds, options, callback
  1681. ** typeOrOid, varbinds, callback
  1682. ** typeOrOid, options, callback
  1683. ** typeOrOid, callback
  1684. **/
  1685. if (arguments.length >= 4) {
  1686. varbinds = arguments[1];
  1687. options = arguments[2];
  1688. responseCb = arguments[3];
  1689. } else if (arguments.length >= 3) {
  1690. if (arguments[1].constructor != Array) {
  1691. varbinds = [];
  1692. options = arguments[1];
  1693. responseCb = arguments[2];
  1694. } else {
  1695. varbinds = arguments[1];
  1696. responseCb = arguments[2];
  1697. }
  1698. } else {
  1699. varbinds = [];
  1700. responseCb = arguments[1];
  1701. }
  1702. if ( this.version == Version1 ) {
  1703. responseCb (new RequestInvalidError ("Inform not allowed for SNMPv1"));
  1704. return;
  1705. }
  1706. function feedCb (req, message) {
  1707. var pdu = message.pdu;
  1708. var varbinds = [];
  1709. if (req.message.pdu.varbinds.length != pdu.varbinds.length) {
  1710. req.responseCb (new ResponseInvalidError ("Inform OIDs do not "
  1711. + "match response OIDs", ResponseInvalidCode.EReqResOidNoMatch));
  1712. } else {
  1713. for (var i = 0; i < req.message.pdu.varbinds.length; i++) {
  1714. if (req.message.pdu.varbinds[i].oid != pdu.varbinds[i].oid) {
  1715. req.responseCb (new ResponseInvalidError ("OID '"
  1716. + req.message.pdu.varbinds[i].oid
  1717. + "' in inform at positiion '" + i + "' does not "
  1718. + "match OID '" + pdu.varbinds[i].oid + "' in response "
  1719. + "at position '" + i + "'", ResponseInvalidCode.EReqResOidNoMatch));
  1720. return;
  1721. } else {
  1722. varbinds.push (pdu.varbinds[i]);
  1723. }
  1724. }
  1725. req.responseCb (null, varbinds);
  1726. }
  1727. }
  1728. if (typeof typeOrOid != "string")
  1729. typeOrOid = "1.3.6.1.6.3.1.1.5." + (typeOrOid + 1);
  1730. var pduVarbinds = [
  1731. {
  1732. oid: "1.3.6.1.2.1.1.3.0",
  1733. type: ObjectType.TimeTicks,
  1734. value: options.upTime || Math.floor (process.uptime () * 100)
  1735. },
  1736. {
  1737. oid: "1.3.6.1.6.3.1.1.4.1.0",
  1738. type: ObjectType.OID,
  1739. value: typeOrOid
  1740. }
  1741. ];
  1742. for (var i = 0; i < varbinds.length; i++) {
  1743. var varbind = {
  1744. oid: varbinds[i].oid,
  1745. type: varbinds[i].type,
  1746. value: varbinds[i].value
  1747. };
  1748. pduVarbinds.push (varbind);
  1749. }
  1750. options.port = this.trapPort;
  1751. this.simpleGet (InformRequestPdu, feedCb, pduVarbinds, responseCb, options);
  1752. return this;
  1753. };
  1754. Session.prototype.onClose = function () {
  1755. this.cancelRequests (new Error ("Socket forcibly closed"));
  1756. this.emit ("close");
  1757. };
  1758. Session.prototype.onError = function (error) {
  1759. this.emit (error);
  1760. };
  1761. Session.prototype.onMsg = function (buffer) {
  1762. try {
  1763. var message = Message.createFromBuffer (buffer);
  1764. } catch (error) {
  1765. this.emit("error", error);
  1766. return;
  1767. }
  1768. var req = this.unregisterRequest (message.getReqId ());
  1769. if ( ! req )
  1770. return;
  1771. if ( ! message.processIncomingSecurity (this.user, req.responseCb) )
  1772. return;
  1773. if (message.version != req.message.version) {
  1774. req.responseCb (new ResponseInvalidError ("Version in request '"
  1775. + req.message.version + "' does not match version in "
  1776. + "response '" + message.version + "'", ResponseInvalidCode.EVersionNoMatch));
  1777. } else if (message.community != req.message.community) {
  1778. req.responseCb (new ResponseInvalidError ("Community '"
  1779. + req.message.community + "' in request does not match "
  1780. + "community '" + message.community + "' in response", ResponseInvalidCode.ECommunityNoMatch));
  1781. } else if (message.pdu.type == PduType.Report) {
  1782. this.msgSecurityParameters = {
  1783. msgAuthoritativeEngineID: message.msgSecurityParameters.msgAuthoritativeEngineID,
  1784. msgAuthoritativeEngineBoots: message.msgSecurityParameters.msgAuthoritativeEngineBoots,
  1785. msgAuthoritativeEngineTime: message.msgSecurityParameters.msgAuthoritativeEngineTime
  1786. };
  1787. if ( this.proxy ) {
  1788. this.msgSecurityParameters.msgUserName = this.proxy.user.name;
  1789. this.msgSecurityParameters.msgAuthenticationParameters = "";
  1790. this.msgSecurityParameters.msgPrivacyParameters = "";
  1791. } else {
  1792. if ( ! req.originalPdu || ! req.allowReport ) {
  1793. if (Array.isArray(message.pdu.varbinds) && message.pdu.varbinds[0] && message.pdu.varbinds[0].oid.indexOf(UsmStatsBase) === 0) {
  1794. this.userSecurityModelError (req, message.pdu.varbinds[0].oid);
  1795. return;
  1796. }
  1797. req.responseCb (new ResponseInvalidError ("Unexpected Report PDU", ResponseInvalidCode.EUnexpectedReport) );
  1798. return;
  1799. }
  1800. req.originalPdu.contextName = this.context;
  1801. var timeSyncNeeded = ! message.msgSecurityParameters.msgAuthoritativeEngineBoots && ! message.msgSecurityParameters.msgAuthoritativeEngineTime;
  1802. this.sendV3Req (req.originalPdu, req.feedCb, req.responseCb, req.options, req.port, timeSyncNeeded);
  1803. }
  1804. } else if ( this.proxy ) {
  1805. this.onProxyResponse (req, message);
  1806. } else if (message.pdu.type == PduType.GetResponse) {
  1807. req.onResponse (req, message);
  1808. } else {
  1809. req.responseCb (new ResponseInvalidError ("Unknown PDU type '"
  1810. + message.pdu.type + "' in response", ResponseInvalidCode.EUnknownPduType));
  1811. }
  1812. };
  1813. Session.prototype.onSimpleGetResponse = function (req, message) {
  1814. var pdu = message.pdu;
  1815. if (pdu.errorStatus > 0) {
  1816. var statusString = ErrorStatus[pdu.errorStatus]
  1817. || ErrorStatus.GeneralError;
  1818. var statusCode = ErrorStatus[statusString]
  1819. || ErrorStatus[ErrorStatus.GeneralError];
  1820. if (pdu.errorIndex <= 0 || pdu.errorIndex > pdu.varbinds.length) {
  1821. req.responseCb (new RequestFailedError (statusString, statusCode));
  1822. } else {
  1823. var oid = pdu.varbinds[pdu.errorIndex - 1].oid;
  1824. var error = new RequestFailedError (statusString + ": " + oid,
  1825. statusCode);
  1826. req.responseCb (error);
  1827. }
  1828. } else {
  1829. req.feedCb (req, message);
  1830. }
  1831. };
  1832. Session.prototype.registerRequest = function (req) {
  1833. if (! this.reqs[req.getId ()]) {
  1834. this.reqs[req.getId ()] = req;
  1835. if (this.reqCount <= 0)
  1836. this.dgram.ref();
  1837. this.reqCount++;
  1838. }
  1839. var me = this;
  1840. req.timer = setTimeout (function () {
  1841. if (req.retries-- > 0) {
  1842. me.send (req);
  1843. } else {
  1844. me.unregisterRequest (req.getId ());
  1845. req.responseCb (new RequestTimedOutError (
  1846. "Request timed out"));
  1847. }
  1848. }, req.timeout);
  1849. // Apply timeout backoff
  1850. if (req.backoff && req.backoff >= 1)
  1851. req.timeout *= req.backoff;
  1852. };
  1853. Session.prototype.send = function (req, noWait) {
  1854. try {
  1855. var me = this;
  1856. var buffer = req.message.toBuffer ();
  1857. this.dgram.send (buffer, 0, buffer.length, req.port, this.target,
  1858. function (error, bytes) {
  1859. if (error) {
  1860. req.responseCb (error);
  1861. } else {
  1862. if (noWait) {
  1863. req.responseCb (null);
  1864. } else {
  1865. me.registerRequest (req);
  1866. }
  1867. }
  1868. });
  1869. } catch (error) {
  1870. req.responseCb (error);
  1871. }
  1872. return this;
  1873. };
  1874. Session.prototype.set = function (varbinds, responseCb) {
  1875. var reportOidMismatchErrors = this.reportOidMismatchErrors;
  1876. function feedCb (req, message) {
  1877. var pdu = message.pdu;
  1878. var varbinds = [];
  1879. if (req.message.pdu.varbinds.length != pdu.varbinds.length) {
  1880. req.responseCb (new ResponseInvalidError ("Requested OIDs do not "
  1881. + "match response OIDs", ResponseInvalidCode.EReqResOidNoMatch));
  1882. } else {
  1883. for (var i = 0; i < req.message.pdu.varbinds.length; i++) {
  1884. if ( reportOidMismatchErrors && req.message.pdu.varbinds[i].oid != pdu.varbinds[i].oid ) {
  1885. req.responseCb (new ResponseInvalidError ("OID '"
  1886. + req.message.pdu.varbinds[i].oid
  1887. + "' in request at position '" + i + "' does not "
  1888. + "match OID '" + pdu.varbinds[i].oid + "' in response "
  1889. + "at position '" + i + "'", ResponseInvalidCode.EReqResOidNoMatch));
  1890. return;
  1891. } else {
  1892. varbinds.push (pdu.varbinds[i]);
  1893. }
  1894. }
  1895. req.responseCb (null, varbinds);
  1896. }
  1897. }
  1898. var pduVarbinds = [];
  1899. for (var i = 0; i < varbinds.length; i++) {
  1900. var varbind = {
  1901. oid: varbinds[i].oid,
  1902. type: varbinds[i].type,
  1903. value: varbinds[i].value
  1904. };
  1905. pduVarbinds.push (varbind);
  1906. }
  1907. this.simpleGet (SetRequestPdu, feedCb, pduVarbinds, responseCb);
  1908. return this;
  1909. };
  1910. Session.prototype.simpleGet = function (pduClass, feedCb, varbinds,
  1911. responseCb, options) {
  1912. var id = _generateId (this.idBitsSize);
  1913. options = Object.assign({}, options, { context: this.context });
  1914. var pdu = SimplePdu.createFromVariables (pduClass, id, varbinds, options);
  1915. var message;
  1916. var req;
  1917. if ( this.version == Version3 ) {
  1918. if ( this.msgSecurityParameters ) {
  1919. this.sendV3Req (pdu, feedCb, responseCb, options, this.port, true);
  1920. } else {
  1921. this.sendV3Discovery (pdu, feedCb, responseCb, options);
  1922. }
  1923. } else {
  1924. message = Message.createCommunity (this.version, this.community, pdu);
  1925. req = new Req (this, message, feedCb, responseCb, options);
  1926. this.send (req);
  1927. }
  1928. };
  1929. function subtreeCb (req, varbinds) {
  1930. var done = 0;
  1931. for (var i = varbinds.length; i > 0; i--) {
  1932. if (! oidInSubtree (req.baseOid, varbinds[i - 1].oid)) {
  1933. done = 1;
  1934. varbinds.pop ();
  1935. }
  1936. }
  1937. if (varbinds.length > 0)
  1938. req.feedCb (varbinds);
  1939. if (done)
  1940. return true;
  1941. }
  1942. Session.prototype.subtree = function () {
  1943. var me = this;
  1944. var oid = arguments[0];
  1945. var maxRepetitions, feedCb, doneCb;
  1946. if (arguments.length < 4) {
  1947. maxRepetitions = 20;
  1948. feedCb = arguments[1];
  1949. doneCb = arguments[2];
  1950. } else {
  1951. maxRepetitions = arguments[1];
  1952. feedCb = arguments[2];
  1953. doneCb = arguments[3];
  1954. }
  1955. var req = {
  1956. feedCb: feedCb,
  1957. doneCb: doneCb,
  1958. maxRepetitions: maxRepetitions,
  1959. baseOid: oid
  1960. };
  1961. this.walk (oid, maxRepetitions, subtreeCb.bind (me, req), doneCb);
  1962. return this;
  1963. };
  1964. function tableColumnsResponseCb (req, error) {
  1965. if (error) {
  1966. req.responseCb (error);
  1967. } else if (req.error) {
  1968. req.responseCb (req.error);
  1969. } else {
  1970. if (req.columns.length > 0) {
  1971. var column = req.columns.pop ();
  1972. var me = this;
  1973. this.subtree (req.rowOid + column, req.maxRepetitions,
  1974. tableColumnsFeedCb.bind (me, req),
  1975. tableColumnsResponseCb.bind (me, req));
  1976. } else {
  1977. req.responseCb (null, req.table);
  1978. }
  1979. }
  1980. }
  1981. function tableColumnsFeedCb (req, varbinds) {
  1982. for (var i = 0; i < varbinds.length; i++) {
  1983. if (isVarbindError (varbinds[i])) {
  1984. req.error = new RequestFailedError (varbindError (varbinds[i]));
  1985. return true;
  1986. }
  1987. var oid = varbinds[i].oid.replace (req.rowOid, "");
  1988. if (oid && oid != varbinds[i].oid) {
  1989. var match = oid.match (/^(\d+)\.(.+)$/);
  1990. if (match && match[1] > 0) {
  1991. if (! req.table[match[2]])
  1992. req.table[match[2]] = {};
  1993. req.table[match[2]][match[1]] = varbinds[i].value;
  1994. }
  1995. }
  1996. }
  1997. }
  1998. Session.prototype.tableColumns = function () {
  1999. var me = this;
  2000. var oid = arguments[0];
  2001. var columns = arguments[1];
  2002. var maxRepetitions, responseCb;
  2003. if (arguments.length < 4) {
  2004. responseCb = arguments[2];
  2005. maxRepetitions = 20;
  2006. } else {
  2007. maxRepetitions = arguments[2];
  2008. responseCb = arguments[3];
  2009. }
  2010. var req = {
  2011. responseCb: responseCb,
  2012. maxRepetitions: maxRepetitions,
  2013. baseOid: oid,
  2014. rowOid: oid + ".1.",
  2015. columns: columns.slice(0),
  2016. table: {}
  2017. };
  2018. if (req.columns.length > 0) {
  2019. var column = req.columns.pop ();
  2020. this.subtree (req.rowOid + column, maxRepetitions,
  2021. tableColumnsFeedCb.bind (me, req),
  2022. tableColumnsResponseCb.bind (me, req));
  2023. }
  2024. return this;
  2025. };
  2026. function tableResponseCb (req, error) {
  2027. if (error)
  2028. req.responseCb (error);
  2029. else if (req.error)
  2030. req.responseCb (req.error);
  2031. else
  2032. req.responseCb (null, req.table);
  2033. }
  2034. function tableFeedCb (req, varbinds) {
  2035. for (var i = 0; i < varbinds.length; i++) {
  2036. if (isVarbindError (varbinds[i])) {
  2037. req.error = new RequestFailedError (varbindError (varbinds[i]));
  2038. return true;
  2039. }
  2040. var oid = varbinds[i].oid.replace (req.rowOid, "");
  2041. if (oid && oid != varbinds[i].oid) {
  2042. var match = oid.match (/^(\d+)\.(.+)$/);
  2043. if (match && match[1] > 0) {
  2044. if (! req.table[match[2]])
  2045. req.table[match[2]] = {};
  2046. req.table[match[2]][match[1]] = varbinds[i].value;
  2047. }
  2048. }
  2049. }
  2050. }
  2051. Session.prototype.table = function () {
  2052. var me = this;
  2053. var oid = arguments[0];
  2054. var maxRepetitions, responseCb;
  2055. if (arguments.length < 3) {
  2056. responseCb = arguments[1];
  2057. maxRepetitions = 20;
  2058. } else {
  2059. maxRepetitions = arguments[1];
  2060. responseCb = arguments[2];
  2061. }
  2062. var req = {
  2063. responseCb: responseCb,
  2064. maxRepetitions: maxRepetitions,
  2065. baseOid: oid,
  2066. rowOid: oid + ".1.",
  2067. table: {}
  2068. };
  2069. this.subtree (oid, maxRepetitions, tableFeedCb.bind (me, req),
  2070. tableResponseCb.bind (me, req));
  2071. return this;
  2072. };
  2073. Session.prototype.trap = function () {
  2074. var req = {};
  2075. var typeOrOid = arguments[0];
  2076. var varbinds, options = {}, responseCb;
  2077. var message;
  2078. /**
  2079. ** Support the following signatures:
  2080. **
  2081. ** typeOrOid, varbinds, options, callback
  2082. ** typeOrOid, varbinds, agentAddr, callback
  2083. ** typeOrOid, varbinds, callback
  2084. ** typeOrOid, agentAddr, callback
  2085. ** typeOrOid, options, callback
  2086. ** typeOrOid, callback
  2087. **/
  2088. if (arguments.length >= 4) {
  2089. varbinds = arguments[1];
  2090. if (typeof arguments[2] == "string") {
  2091. options.agentAddr = arguments[2];
  2092. } else if (arguments[2].constructor != Array) {
  2093. options = arguments[2];
  2094. }
  2095. responseCb = arguments[3];
  2096. } else if (arguments.length >= 3) {
  2097. if (typeof arguments[1] == "string") {
  2098. varbinds = [];
  2099. options.agentAddr = arguments[1];
  2100. } else if (arguments[1].constructor != Array) {
  2101. varbinds = [];
  2102. options = arguments[1];
  2103. } else {
  2104. varbinds = arguments[1];
  2105. options.agentAddr = null;
  2106. }
  2107. responseCb = arguments[2];
  2108. } else {
  2109. varbinds = [];
  2110. responseCb = arguments[1];
  2111. }
  2112. var pdu, pduVarbinds = [];
  2113. for (var i = 0; i < varbinds.length; i++) {
  2114. var varbind = {
  2115. oid: varbinds[i].oid,
  2116. type: varbinds[i].type,
  2117. value: varbinds[i].value
  2118. };
  2119. pduVarbinds.push (varbind);
  2120. }
  2121. var id = _generateId (this.idBitsSize);
  2122. if (this.version == Version2c || this.version == Version3 ) {
  2123. if (typeof typeOrOid != "string")
  2124. typeOrOid = "1.3.6.1.6.3.1.1.5." + (typeOrOid + 1);
  2125. pduVarbinds.unshift (
  2126. {
  2127. oid: "1.3.6.1.2.1.1.3.0",
  2128. type: ObjectType.TimeTicks,
  2129. value: options.upTime || Math.floor (process.uptime () * 100)
  2130. },
  2131. {
  2132. oid: "1.3.6.1.6.3.1.1.4.1.0",
  2133. type: ObjectType.OID,
  2134. value: typeOrOid
  2135. }
  2136. );
  2137. pdu = TrapV2Pdu.createFromVariables (id, pduVarbinds, options);
  2138. } else {
  2139. pdu = TrapPdu.createFromVariables (typeOrOid, pduVarbinds, options);
  2140. }
  2141. if ( this.version == Version3 ) {
  2142. var msgSecurityParameters = {
  2143. msgAuthoritativeEngineID: this.engine.engineID,
  2144. msgAuthoritativeEngineBoots: 0,
  2145. msgAuthoritativeEngineTime: 0
  2146. };
  2147. message = Message.createRequestV3 (this.user, msgSecurityParameters, pdu);
  2148. } else {
  2149. message = Message.createCommunity (this.version, this.community, pdu);
  2150. }
  2151. req = {
  2152. id: id,
  2153. message: message,
  2154. responseCb: responseCb,
  2155. port: this.trapPort
  2156. };
  2157. this.send (req, true);
  2158. return this;
  2159. };
  2160. Session.prototype.unregisterRequest = function (id) {
  2161. var req = this.reqs[id];
  2162. if (req) {
  2163. delete this.reqs[id];
  2164. clearTimeout (req.timer);
  2165. delete req.timer;
  2166. this.reqCount--;
  2167. if (this.reqCount <= 0)
  2168. this.dgram.unref();
  2169. return req;
  2170. } else {
  2171. return null;
  2172. }
  2173. };
  2174. function walkCb (req, error, varbinds) {
  2175. var done = 0;
  2176. var oid;
  2177. if (error) {
  2178. if (error instanceof RequestFailedError) {
  2179. if (error.status != ErrorStatus.NoSuchName) {
  2180. req.doneCb (error);
  2181. return;
  2182. } else {
  2183. // signal the version 1 walk code below that it should stop
  2184. done = 1;
  2185. }
  2186. } else {
  2187. req.doneCb (error);
  2188. return;
  2189. }
  2190. }
  2191. if ( ! varbinds || ! varbinds.length ) {
  2192. req.doneCb(null);
  2193. return;
  2194. }
  2195. if (this.version == Version2c || this.version == Version3) {
  2196. for (var i = varbinds[0].length; i > 0; i--) {
  2197. if (varbinds[0][i - 1].type == ObjectType.EndOfMibView) {
  2198. varbinds[0].pop ();
  2199. done = 1;
  2200. }
  2201. }
  2202. if (req.feedCb (varbinds[0]))
  2203. done = 1;
  2204. if (! done)
  2205. oid = varbinds[0][varbinds[0].length - 1].oid;
  2206. } else {
  2207. if (! done) {
  2208. if (req.feedCb (varbinds)) {
  2209. done = 1;
  2210. } else {
  2211. oid = varbinds[0].oid;
  2212. }
  2213. }
  2214. }
  2215. if (done)
  2216. req.doneCb (null);
  2217. else
  2218. this.walk (oid, req.maxRepetitions, req.feedCb, req.doneCb,
  2219. req.baseOid);
  2220. }
  2221. Session.prototype.walk = function () {
  2222. var me = this;
  2223. var oid = arguments[0];
  2224. var maxRepetitions, feedCb, doneCb;
  2225. if (arguments.length < 4) {
  2226. maxRepetitions = 20;
  2227. feedCb = arguments[1];
  2228. doneCb = arguments[2];
  2229. } else {
  2230. maxRepetitions = arguments[1];
  2231. feedCb = arguments[2];
  2232. doneCb = arguments[3];
  2233. }
  2234. var req = {
  2235. maxRepetitions: maxRepetitions,
  2236. feedCb: feedCb,
  2237. doneCb: doneCb
  2238. };
  2239. if (this.version == Version2c || this.version == Version3)
  2240. this.getBulk ([oid], 0, maxRepetitions,
  2241. walkCb.bind (me, req));
  2242. else
  2243. this.getNext ([oid], walkCb.bind (me, req));
  2244. return this;
  2245. };
  2246. Session.prototype.sendV3Req = function (pdu, feedCb, responseCb, options, port, allowReport) {
  2247. var message = Message.createRequestV3 (this.user, this.msgSecurityParameters, pdu);
  2248. var reqOptions = options || {};
  2249. var req = new Req (this, message, feedCb, responseCb, reqOptions);
  2250. req.port = port;
  2251. req.originalPdu = pdu;
  2252. req.allowReport = allowReport;
  2253. this.send (req);
  2254. };
  2255. Session.prototype.sendV3Discovery = function (originalPdu, feedCb, responseCb, options) {
  2256. var discoveryPdu = createDiscoveryPdu(this.context);
  2257. var discoveryMessage = Message.createDiscoveryV3 (discoveryPdu);
  2258. var discoveryReq = new Req (this, discoveryMessage, feedCb, responseCb, options);
  2259. discoveryReq.originalPdu = originalPdu;
  2260. discoveryReq.allowReport = true;
  2261. this.send (discoveryReq);
  2262. };
  2263. Session.prototype.userSecurityModelError = function (req, oid) {
  2264. var oidSuffix = oid.replace (UsmStatsBase + '.', '').replace (/\.0$/, '');
  2265. var errorType = UsmStats[oidSuffix] || "Unexpected Report PDU";
  2266. req.responseCb (new ResponseInvalidError (errorType, ResponseInvalidCode.EAuthFailure) );
  2267. };
  2268. Session.prototype.onProxyResponse = function (req, message) {
  2269. if ( message.version != Version3 ) {
  2270. this.callback (new RequestFailedError ("Only SNMP version 3 contexts are supported"));
  2271. return;
  2272. }
  2273. message.pdu.contextName = this.proxy.context;
  2274. message.user = req.proxiedUser;
  2275. message.setAuthentication ( ! (req.proxiedUser.level == SecurityLevel.noAuthNoPriv));
  2276. message.setPrivacy (req.proxiedUser.level == SecurityLevel.authPriv);
  2277. message.msgSecurityParameters = {
  2278. msgAuthoritativeEngineID: req.proxiedEngine.engineID,
  2279. msgAuthoritativeEngineBoots: req.proxiedEngine.engineBoots,
  2280. msgAuthoritativeEngineTime: req.proxiedEngine.engineTime,
  2281. msgUserName: req.proxiedUser.name,
  2282. msgAuthenticationParameters: "",
  2283. msgPrivacyParameters: ""
  2284. };
  2285. message.buffer = null;
  2286. message.pdu.contextEngineID = message.msgSecurityParameters.msgAuthoritativeEngineID;
  2287. message.pdu.contextName = this.proxy.context;
  2288. message.pdu.id = req.proxiedPduId;
  2289. this.proxy.listener.send (message, req.proxiedRinfo);
  2290. };
  2291. Session.create = function (target, community, options) {
  2292. // Ensure that options may be optional
  2293. var version = (options && options.version) ? options.version : Version1;
  2294. if (version != Version1 && version != Version2c) {
  2295. throw new ResponseInvalidError ("SNMP community session requested but version '" + options.version + "' specified in options not valid",
  2296. ResponseInvalidCode.EVersionNoMatch);
  2297. } else {
  2298. if (!options)
  2299. options = {};
  2300. options.version = version;
  2301. return new Session (target, community, options);
  2302. }
  2303. };
  2304. Session.createV3 = function (target, user, options) {
  2305. // Ensure that options may be optional
  2306. if ( options && options.version && options.version != Version3 ) {
  2307. throw new ResponseInvalidError ("SNMPv3 session requested but version '" + options.version + "' specified in options",
  2308. ResponseInvalidCode.EVersionNoMatch);
  2309. } else {
  2310. if (!options)
  2311. options = {};
  2312. options.version = Version3;
  2313. }
  2314. return new Session (target, user, options);
  2315. };
  2316. var Engine = function (engineID, engineBoots, engineTime) {
  2317. if ( engineID ) {
  2318. if ( ! (engineID instanceof Buffer) ) {
  2319. engineID = engineID.replace('0x', '');
  2320. this.engineID = Buffer.from((engineID.toString().length % 2 == 1 ? '0' : '') + engineID.toString(), 'hex');
  2321. } else {
  2322. this.engineID = engineID;
  2323. }
  2324. } else {
  2325. this.generateEngineID ();
  2326. }
  2327. this.engineBoots = 0;
  2328. this.engineTime = 10;
  2329. };
  2330. Engine.prototype.generateEngineID = function() {
  2331. // generate a 17-byte engine ID in the following format:
  2332. // 0x80 | 0x00B983 (enterprise OID) | 0x80 (enterprise-specific format) | 12 bytes of random
  2333. this.engineID = Buffer.alloc (17);
  2334. this.engineID.fill ('8000B98380', 'hex', 0, 5);
  2335. this.engineID.fill (crypto.randomBytes (12), 5, 17, 'hex');
  2336. };
  2337. var Listener = function (options, receiver) {
  2338. this.receiver = receiver;
  2339. this.callback = receiver.onMsg;
  2340. this.family = options.transport || 'udp4';
  2341. this.port = options.port || 161;
  2342. this.address = options.address;
  2343. this.disableAuthorization = options.disableAuthorization || false;
  2344. };
  2345. Listener.prototype.startListening = function () {
  2346. var me = this;
  2347. this.dgram = dgram.createSocket (this.family);
  2348. this.dgram.on ("error", me.receiver.callback);
  2349. this.dgram.bind (this.port, this.address);
  2350. this.dgram.on ("message", me.callback.bind (me.receiver));
  2351. };
  2352. Listener.prototype.send = function (message, rinfo) {
  2353. // var me = this;
  2354. var buffer = message.toBuffer ();
  2355. this.dgram.send (buffer, 0, buffer.length, rinfo.port, rinfo.address,
  2356. function (error, bytes) {
  2357. if (error) {
  2358. // me.callback (error);
  2359. console.error ("Error sending: " + error.message);
  2360. } else {
  2361. // debug ("Listener sent response message");
  2362. }
  2363. });
  2364. };
  2365. Listener.formatCallbackData = function (pdu, rinfo) {
  2366. if ( pdu.contextEngineID ) {
  2367. pdu.contextEngineID = pdu.contextEngineID.toString('hex');
  2368. }
  2369. delete pdu.nonRepeaters;
  2370. delete pdu.maxRepetitions;
  2371. return {
  2372. pdu: pdu,
  2373. rinfo: rinfo
  2374. };
  2375. };
  2376. Listener.processIncoming = function (buffer, authorizer, callback) {
  2377. var message = Message.createFromBuffer (buffer);
  2378. var community;
  2379. // Authorization
  2380. if ( message.version == Version3 ) {
  2381. message.user = authorizer.users.filter( localUser => localUser.name ==
  2382. message.msgSecurityParameters.msgUserName )[0];
  2383. message.disableAuthentication = authorizer.disableAuthorization;
  2384. if ( ! message.user ) {
  2385. if ( message.msgSecurityParameters.msgUserName != "" && ! authorizer.disableAuthorization ) {
  2386. callback (new RequestFailedError ("Local user not found for message with user " +
  2387. message.msgSecurityParameters.msgUserName));
  2388. return;
  2389. } else if ( message.hasAuthentication () ) {
  2390. callback (new RequestFailedError ("Local user not found and message requires authentication with user " +
  2391. message.msgSecurityParameters.msgUserName));
  2392. return;
  2393. } else {
  2394. message.user = {
  2395. name: "",
  2396. level: SecurityLevel.noAuthNoPriv
  2397. };
  2398. }
  2399. }
  2400. if ( (message.user.level == SecurityLevel.authNoPriv || message.user.level == SecurityLevel.authPriv) && ! message.hasAuthentication() ) {
  2401. callback (new RequestFailedError ("Local user " + message.msgSecurityParameters.msgUserName +
  2402. " requires authentication but message does not provide it"));
  2403. return;
  2404. }
  2405. if ( message.user.level == SecurityLevel.authPriv && ! message.hasPrivacy() ) {
  2406. callback (new RequestFailedError ("Local user " + message.msgSecurityParameters.msgUserName +
  2407. " requires privacy but message does not provide it"));
  2408. return;
  2409. }
  2410. if ( ! message.processIncomingSecurity (message.user, callback) ) {
  2411. return;
  2412. }
  2413. } else {
  2414. community = authorizer.communities.filter( localCommunity => localCommunity == message.community )[0];
  2415. if ( ! community && ! authorizer.disableAuthorization ) {
  2416. callback (new RequestFailedError ("Local community not found for message with community " + message.community));
  2417. return;
  2418. }
  2419. }
  2420. return message;
  2421. };
  2422. Listener.prototype.close = function () {
  2423. if ( this.dgram ) {
  2424. this.dgram.close ();
  2425. }
  2426. };
  2427. var Authorizer = function (options) {
  2428. this.communities = [];
  2429. this.users = [];
  2430. this.disableAuthorization = options.disableAuthorization;
  2431. this.accessControlModelType = options.accessControlModelType || AccessControlModelType.None;
  2432. if ( this.accessControlModelType == AccessControlModelType.None ) {
  2433. this.accessControlModel = null;
  2434. } else if ( this.accessControlModelType == AccessControlModelType.Simple ) {
  2435. this.accessControlModel = new SimpleAccessControlModel ();
  2436. }
  2437. };
  2438. Authorizer.prototype.addCommunity = function (community) {
  2439. if ( this.getCommunity (community) ) {
  2440. return;
  2441. } else {
  2442. this.communities.push (community);
  2443. if ( this.accessControlModelType == AccessControlModelType.Simple ) {
  2444. this.accessControlModel.setCommunityAccess (community, AccessLevel.ReadOnly);
  2445. }
  2446. }
  2447. };
  2448. Authorizer.prototype.getCommunity = function (community) {
  2449. return this.communities.filter( localCommunity => localCommunity == community )[0] || null;
  2450. };
  2451. Authorizer.prototype.getCommunities = function () {
  2452. return this.communities;
  2453. };
  2454. Authorizer.prototype.deleteCommunity = function (community) {
  2455. var index = this.communities.indexOf(community);
  2456. if ( index > -1 ) {
  2457. this.communities.splice(index, 1);
  2458. }
  2459. };
  2460. Authorizer.prototype.addUser = function (user) {
  2461. if ( this.getUser (user.name) ) {
  2462. this.deleteUser (user.name);
  2463. }
  2464. this.users.push (user);
  2465. if ( this.accessControlModelType == AccessControlModelType.Simple ) {
  2466. this.accessControlModel.setUserAccess (user.name, AccessLevel.ReadOnly);
  2467. }
  2468. };
  2469. Authorizer.prototype.getUser = function (userName) {
  2470. return this.users.filter( localUser => localUser.name == userName )[0] || null;
  2471. };
  2472. Authorizer.prototype.getUsers = function () {
  2473. return this.users;
  2474. };
  2475. Authorizer.prototype.deleteUser = function (userName) {
  2476. var index = this.users.findIndex(localUser => localUser.name == userName );
  2477. if ( index > -1 ) {
  2478. this.users.splice(index, 1);
  2479. }
  2480. };
  2481. Authorizer.prototype.getAccessControlModelType = function () {
  2482. return this.accessControlModelType;
  2483. };
  2484. Authorizer.prototype.getAccessControlModel = function () {
  2485. return this.accessControlModel;
  2486. };
  2487. Authorizer.prototype.isAccessAllowed = function (securityModel, securityName, pduType) {
  2488. if ( this.accessControlModel ) {
  2489. return this.accessControlModel.isAccessAllowed (securityModel, securityName, pduType);
  2490. } else {
  2491. return true;
  2492. }
  2493. };
  2494. var SimpleAccessControlModel = function () {
  2495. this.communitiesAccess = [];
  2496. this.usersAccess = [];
  2497. };
  2498. SimpleAccessControlModel.prototype.getCommunityAccess = function (community) {
  2499. return this.communitiesAccess.find (entry => entry.community == community );
  2500. };
  2501. SimpleAccessControlModel.prototype.getCommunityAccessLevel = function (community) {
  2502. var communityAccessEntry = this.getCommunityAccess (community);
  2503. return communityAccessEntry ? communityAccessEntry.level : AccessLevel.None;
  2504. };
  2505. SimpleAccessControlModel.prototype.getCommunitiesAccess = function () {
  2506. return this.communitiesAccess;
  2507. };
  2508. SimpleAccessControlModel.prototype.setCommunityAccess = function (community, accessLevel) {
  2509. let accessEntry = this.getCommunityAccess (community);
  2510. if ( accessEntry ) {
  2511. accessEntry.level = accessLevel;
  2512. } else {
  2513. this.communitiesAccess.push ({
  2514. community: community,
  2515. level: accessLevel
  2516. });
  2517. this.communitiesAccess.sort ((a, b) => (a.community > b.community) ? 1 : -1);
  2518. }
  2519. };
  2520. SimpleAccessControlModel.prototype.removeCommunityAccess = function (community) {
  2521. this.communitiesAccess.splice ( this.communitiesAccess.findIndex (entry => entry.community == community), 1);
  2522. };
  2523. SimpleAccessControlModel.prototype.getUserAccess = function (userName) {
  2524. return this.usersAccess.find (entry => entry.userName == userName );
  2525. };
  2526. SimpleAccessControlModel.prototype.getUserAccessLevel = function (user) {
  2527. var userAccessEntry = this.getUserAccess (user);
  2528. return userAccessEntry ? userAccessEntry.level : AccessLevel.None;
  2529. };
  2530. SimpleAccessControlModel.prototype.getUsersAccess = function () {
  2531. return this.usersAccess;
  2532. };
  2533. SimpleAccessControlModel.prototype.setUserAccess = function (userName, accessLevel) {
  2534. let accessEntry = this.getUserAccess (userName);
  2535. if ( accessEntry ) {
  2536. accessEntry.level = accessLevel;
  2537. } else {
  2538. this.usersAccess.push ({
  2539. userName: userName,
  2540. level: accessLevel
  2541. });
  2542. this.usersAccess.sort ((a, b) => (a.userName > b.userName) ? 1 : -1);
  2543. }
  2544. };
  2545. SimpleAccessControlModel.prototype.removeUserAccess = function (userName) {
  2546. this.usersAccess.splice ( this.usersAccess.findIndex (entry => entry.userName == userName), 1);
  2547. };
  2548. SimpleAccessControlModel.prototype.isAccessAllowed = function (securityModel, securityName, pduType) {
  2549. var accessLevelConfigured;
  2550. var accessLevelRequired;
  2551. switch ( securityModel ) {
  2552. case Version1:
  2553. case Version2c:
  2554. accessLevelConfigured = this.getCommunityAccessLevel (securityName);
  2555. break;
  2556. case Version3:
  2557. accessLevelConfigured = this.getUserAccessLevel (securityName);
  2558. break;
  2559. }
  2560. switch ( pduType ) {
  2561. case PduType.SetRequest:
  2562. accessLevelRequired = AccessLevel.ReadWrite;
  2563. break;
  2564. case PduType.GetRequest:
  2565. case PduType.GetNextRequest:
  2566. case PduType.GetBulkRequest:
  2567. accessLevelRequired = AccessLevel.ReadOnly;
  2568. break;
  2569. default:
  2570. accessLevelRequired = AccessLevel.None;
  2571. break;
  2572. }
  2573. switch ( accessLevelRequired ) {
  2574. case AccessLevel.ReadWrite:
  2575. return accessLevelConfigured == AccessLevel.ReadWrite;
  2576. case AccessLevel.ReadOnly:
  2577. return accessLevelConfigured == AccessLevel.ReadWrite || accessLevelConfigured == AccessLevel.ReadOnly;
  2578. case AccessLevel.None:
  2579. return true;
  2580. default:
  2581. return false;
  2582. }
  2583. };
  2584. /*****************************************************************************
  2585. ** Receiver class definition
  2586. **/
  2587. var Receiver = function (options, callback) {
  2588. DEBUG = options.debug;
  2589. this.listener = new Listener (options, this);
  2590. this.authorizer = new Authorizer (options);
  2591. this.engine = new Engine (options.engineID);
  2592. this.engineBoots = 0;
  2593. this.engineTime = 10;
  2594. this.disableAuthorization = false;
  2595. this.callback = callback;
  2596. this.family = options.transport || 'udp4';
  2597. this.port = options.port || 162;
  2598. options.port = this.port;
  2599. this.disableAuthorization = options.disableAuthorization || false;
  2600. this.includeAuthentication = options.includeAuthentication || false;
  2601. this.context = (options && options.context) ? options.context : "";
  2602. this.listener = new Listener (options, this);
  2603. };
  2604. Receiver.prototype.getAuthorizer = function () {
  2605. return this.authorizer;
  2606. };
  2607. Receiver.prototype.onMsg = function (buffer, rinfo) {
  2608. var message = Listener.processIncoming (buffer, this.authorizer, this.callback);
  2609. var reportMessage;
  2610. if ( ! message ) {
  2611. return;
  2612. }
  2613. // The only GetRequest PDUs supported are those used for SNMPv3 discovery
  2614. if ( message.pdu.type == PduType.GetRequest ) {
  2615. if ( message.version != Version3 ) {
  2616. this.callback (new RequestInvalidError ("Only SNMPv3 discovery GetRequests are supported"));
  2617. return;
  2618. } else if ( message.hasAuthentication() ) {
  2619. this.callback (new RequestInvalidError ("Only discovery (noAuthNoPriv) GetRequests are supported but this message has authentication"));
  2620. return;
  2621. } else if ( ! message.isReportable () ) {
  2622. this.callback (new RequestInvalidError ("Only discovery GetRequests are supported and this message does not have the reportable flag set"));
  2623. return;
  2624. }
  2625. reportMessage = message.createReportResponseMessage (this.engine, this.context);
  2626. this.listener.send (reportMessage, rinfo);
  2627. return;
  2628. }
  2629. // Inform/trap processing
  2630. // debug (JSON.stringify (message.pdu, null, 2));
  2631. if ( message.pdu.type == PduType.Trap || message.pdu.type == PduType.TrapV2 ) {
  2632. this.callback (null, this.formatCallbackData (message, rinfo) );
  2633. } else if ( message.pdu.type == PduType.InformRequest ) {
  2634. message.pdu.type = PduType.GetResponse;
  2635. message.buffer = null;
  2636. message.setReportable (false);
  2637. this.listener.send (message, rinfo);
  2638. message.pdu.type = PduType.InformRequest;
  2639. this.callback (null, this.formatCallbackData (message, rinfo) );
  2640. } else {
  2641. this.callback (new RequestInvalidError ("Unexpected PDU type " + message.pdu.type + " (" + PduType[message.pdu.type] + ")"));
  2642. }
  2643. };
  2644. Receiver.prototype.formatCallbackData = function (message, rinfo) {
  2645. if ( message.pdu.contextEngineID ) {
  2646. message.pdu.contextEngineID = message.pdu.contextEngineID.toString('hex');
  2647. }
  2648. delete message.pdu.nonRepeaters;
  2649. delete message.pdu.maxRepetitions;
  2650. const formattedData = {
  2651. pdu: message.pdu,
  2652. rinfo: rinfo
  2653. };
  2654. if (this.includeAuthentication) {
  2655. if (message.community) {
  2656. formattedData.pdu.community = message.community;
  2657. } else if (message.user) {
  2658. formattedData.pdu.user = message.user.name;
  2659. }
  2660. }
  2661. return formattedData;
  2662. };
  2663. Receiver.prototype.close = function() {
  2664. this.listener.close ();
  2665. };
  2666. Receiver.create = function (options, callback) {
  2667. var receiver = new Receiver (options, callback);
  2668. receiver.listener.startListening ();
  2669. return receiver;
  2670. };
  2671. var ModuleStore = function () {
  2672. this.parser = mibparser ();
  2673. };
  2674. ModuleStore.prototype.getSyntaxTypes = function () {
  2675. var syntaxTypes = {};
  2676. Object.assign (syntaxTypes, ObjectType);
  2677. var entryArray;
  2678. for ( var mibModule of Object.values (this.parser.Modules) ) {
  2679. entryArray = Object.values (mibModule);
  2680. for ( var mibEntry of entryArray ) {
  2681. if ( mibEntry.MACRO == "TEXTUAL-CONVENTION" ) {
  2682. if ( mibEntry.SYNTAX && ! syntaxTypes[mibEntry.ObjectName] ) {
  2683. if ( typeof mibEntry.SYNTAX == "object" ) {
  2684. syntaxTypes[mibEntry.ObjectName] = syntaxTypes.Integer;
  2685. } else {
  2686. syntaxTypes[mibEntry.ObjectName] = syntaxTypes[mibEntry.SYNTAX];
  2687. }
  2688. }
  2689. }
  2690. }
  2691. }
  2692. return syntaxTypes;
  2693. };
  2694. ModuleStore.prototype.loadFromFile = function (fileName) {
  2695. this.parser.Import (fileName);
  2696. this.parser.Serialize ();
  2697. };
  2698. ModuleStore.prototype.getModule = function (moduleName) {
  2699. return this.parser.Modules[moduleName];
  2700. };
  2701. ModuleStore.prototype.getModules = function (includeBase) {
  2702. var modules = {};
  2703. for ( var moduleName of Object.keys(this.parser.Modules) ) {
  2704. if ( includeBase || ModuleStore.BASE_MODULES.indexOf (moduleName) == -1 ) {
  2705. modules[moduleName] = this.parser.Modules[moduleName];
  2706. }
  2707. }
  2708. return modules;
  2709. };
  2710. ModuleStore.prototype.getModuleNames = function (includeBase) {
  2711. var modules = [];
  2712. for ( var moduleName of Object.keys(this.parser.Modules) ) {
  2713. if ( includeBase || ModuleStore.BASE_MODULES.indexOf (moduleName) == -1 ) {
  2714. modules.push (moduleName);
  2715. }
  2716. }
  2717. return modules;
  2718. };
  2719. ModuleStore.prototype.getProvidersForModule = function (moduleName) {
  2720. var mibModule = this.parser.Modules[moduleName];
  2721. var scalars = [];
  2722. var tables = [];
  2723. var mibEntry;
  2724. var syntaxTypes;
  2725. var entryArray;
  2726. var currentTableProvider;
  2727. var parentOid;
  2728. var constraintsResults;
  2729. var constraints;
  2730. if ( ! mibModule ) {
  2731. throw new ReferenceError ("MIB module " + moduleName + " not loaded");
  2732. }
  2733. syntaxTypes = this.getSyntaxTypes ();
  2734. entryArray = Object.values (mibModule);
  2735. for ( var i = 0; i < entryArray.length ; i++ ) {
  2736. mibEntry = entryArray[i];
  2737. var syntax = mibEntry.SYNTAX;
  2738. var access = mibEntry["ACCESS"];
  2739. var maxAccess = (typeof mibEntry["MAX-ACCESS"] != "undefined" ? mibEntry["MAX-ACCESS"] : (access ? AccessToMaxAccess[access] : "not-accessible"));
  2740. var defVal = mibEntry["DEFVAL"];
  2741. if ( syntax ) {
  2742. constraintsResults = ModuleStore.getConstraintsFromSyntax (syntax);
  2743. syntax = constraintsResults.syntax;
  2744. constraints = constraintsResults.constraints;
  2745. if ( syntax.startsWith ("SEQUENCE OF") ) {
  2746. // start of table
  2747. currentTableProvider = {
  2748. tableName: mibEntry.ObjectName,
  2749. type: MibProviderType.Table,
  2750. //oid: mibEntry.OID,
  2751. tableColumns: [],
  2752. tableIndex: [1] // default - assume first column is index
  2753. };
  2754. currentTableProvider.maxAccess = MaxAccess[maxAccess];
  2755. // read table to completion
  2756. while ( currentTableProvider || i >= entryArray.length ) {
  2757. i++;
  2758. mibEntry = entryArray[i];
  2759. if ( ! mibEntry ) {
  2760. tables.push (currentTableProvider);
  2761. currentTableProvider = null;
  2762. i--;
  2763. break;
  2764. }
  2765. syntax = mibEntry.SYNTAX;
  2766. access = mibEntry["ACCESS"];
  2767. maxAccess = (typeof mibEntry["MAX-ACCESS"] != "undefined" ? mibEntry["MAX-ACCESS"] : (access ? AccessToMaxAccess[access] : "not-accessible"));
  2768. defVal = mibEntry["DEFVAL"];
  2769. constraintsResults = ModuleStore.getConstraintsFromSyntax (syntax);
  2770. syntax = constraintsResults.syntax;
  2771. constraints = constraintsResults.constraints;
  2772. if ( mibEntry.MACRO == "SEQUENCE" ) {
  2773. // table entry sequence - ignore
  2774. } else if ( ! mibEntry["OBJECT IDENTIFIER"] ) {
  2775. // unexpected
  2776. } else {
  2777. parentOid = mibEntry["OBJECT IDENTIFIER"].split (" ")[0];
  2778. if ( parentOid == currentTableProvider.tableName ) {
  2779. // table entry
  2780. currentTableProvider.name = mibEntry.ObjectName;
  2781. currentTableProvider.oid = mibEntry.OID;
  2782. if ( mibEntry.INDEX ) {
  2783. currentTableProvider.tableIndex = [];
  2784. for ( var indexEntry of mibEntry.INDEX ) {
  2785. indexEntry = indexEntry.trim ();
  2786. if ( indexEntry.includes(" ") ) {
  2787. if ( indexEntry.split(" ")[0] == "IMPLIED" ) {
  2788. currentTableProvider.tableIndex.push ({
  2789. columnName: indexEntry.split(" ")[1],
  2790. implied: true
  2791. });
  2792. } else {
  2793. // unknown condition - guess that last token is name
  2794. currentTableProvider.tableIndex.push ({
  2795. columnName: indexEntry.split(" ").slice(-1)[0],
  2796. });
  2797. }
  2798. } else {
  2799. currentTableProvider.tableIndex.push ({
  2800. columnName: indexEntry
  2801. });
  2802. }
  2803. }
  2804. }
  2805. if ( mibEntry.AUGMENTS ) {
  2806. currentTableProvider.tableAugments = mibEntry.AUGMENTS[0].trim();
  2807. currentTableProvider.tableIndex = null;
  2808. }
  2809. } else if ( parentOid == currentTableProvider.name ) {
  2810. // table column
  2811. var columnDefinition = {
  2812. number: parseInt (mibEntry["OBJECT IDENTIFIER"].split (" ")[1]),
  2813. name: mibEntry.ObjectName,
  2814. type: syntaxTypes[syntax],
  2815. maxAccess: MaxAccess[maxAccess]
  2816. };
  2817. if ( constraints ) {
  2818. columnDefinition.constraints = constraints;
  2819. }
  2820. if (defVal) {
  2821. columnDefinition.defVal = defVal;
  2822. }
  2823. // If this column has syntax RowStatus and
  2824. // the MIB module imports RowStatus from
  2825. // SNMPv2-TC, mark this column as the
  2826. // rowStatus column so we can act on it.
  2827. // (See lib/mibs/SNMPv2-TC.mib#L186.)
  2828. if ( syntax == "RowStatus" &&
  2829. "IMPORTS" in mibModule &&
  2830. Array.isArray(mibModule.IMPORTS["SNMPv2-TC"]) &&
  2831. mibModule.IMPORTS["SNMPv2-TC"].includes("RowStatus") ) {
  2832. // Mark this column as being rowStatus
  2833. columnDefinition.rowStatus = true;
  2834. }
  2835. currentTableProvider.tableColumns.push (columnDefinition);
  2836. } else {
  2837. // table finished
  2838. tables.push (currentTableProvider);
  2839. // console.log ("Table: " + currentTableProvider.name);
  2840. currentTableProvider = null;
  2841. i--;
  2842. }
  2843. }
  2844. }
  2845. } else if ( mibEntry.MACRO == "OBJECT-TYPE" ) {
  2846. // OBJECT-TYPE entries not in a table are scalars
  2847. var scalarDefinition = {
  2848. name: mibEntry.ObjectName,
  2849. type: MibProviderType.Scalar,
  2850. oid: mibEntry.OID,
  2851. scalarType: syntaxTypes[syntax],
  2852. maxAccess: MaxAccess[maxAccess]
  2853. };
  2854. if (defVal) {
  2855. scalarDefinition.defVal = defVal;
  2856. }
  2857. if ( constraints ) {
  2858. scalarDefinition.constraints = constraints;
  2859. }
  2860. scalars.push (scalarDefinition);
  2861. // console.log ("Scalar: " + mibEntry.ObjectName);
  2862. }
  2863. }
  2864. }
  2865. return scalars.concat (tables);
  2866. };
  2867. ModuleStore.prototype.loadBaseModules = function () {
  2868. for ( var mibModule of ModuleStore.BASE_MODULES ) {
  2869. this.parser.Import (__dirname + "/lib/mibs/" + mibModule + ".mib");
  2870. }
  2871. this.parser.Serialize ();
  2872. };
  2873. ModuleStore.getConstraintsFromSyntax = function (syntax) {
  2874. let constraints;
  2875. // detect INTEGER ranges, OCTET STRING sizes, and INTEGER enumerations
  2876. if ( typeof syntax == "object" ) {
  2877. let firstSyntaxKey = syntax[Object.keys(syntax)[0]];
  2878. if ( firstSyntaxKey.ranges ) {
  2879. constraints = {
  2880. ranges: firstSyntaxKey.ranges
  2881. };
  2882. syntax = Object.keys(syntax)[0];
  2883. } else if ( firstSyntaxKey.sizes ) {
  2884. constraints = {
  2885. size: firstSyntaxKey.sizes
  2886. };
  2887. syntax = Object.keys(syntax)[0];
  2888. } else {
  2889. constraints = {
  2890. enumeration: syntax.INTEGER
  2891. };
  2892. syntax = "INTEGER";
  2893. }
  2894. } else {
  2895. constraints = null;
  2896. }
  2897. return {
  2898. constraints: constraints,
  2899. syntax: syntax
  2900. };
  2901. };
  2902. ModuleStore.create = function () {
  2903. var store = new ModuleStore ();
  2904. store.loadBaseModules ();
  2905. return store;
  2906. };
  2907. ModuleStore.BASE_MODULES = [
  2908. "RFC1155-SMI",
  2909. "RFC1158-MIB",
  2910. "RFC-1212",
  2911. "RFC1213-MIB",
  2912. "SNMPv2-SMI",
  2913. "SNMPv2-CONF",
  2914. "SNMPv2-TC",
  2915. "SNMPv2-MIB"
  2916. ];
  2917. var MibNode = function(address, parent) {
  2918. this.address = address;
  2919. this.oid = this.address.join('.');
  2920. this.parent = parent;
  2921. this.children = {};
  2922. };
  2923. MibNode.prototype.child = function (index) {
  2924. return this.children[index];
  2925. };
  2926. MibNode.prototype.listChildren = function (lowest) {
  2927. var sorted = [];
  2928. lowest = lowest || 0;
  2929. this.children.forEach (function (c, i) {
  2930. if (i >= lowest)
  2931. sorted.push (i);
  2932. });
  2933. sorted.sort (function (a, b) {
  2934. return (a - b);
  2935. });
  2936. return sorted;
  2937. };
  2938. MibNode.prototype.findChildImmediatelyBefore = function (index) {
  2939. var sortedChildrenKeys = Object.keys(this.children).sort(function (a, b) {
  2940. return (a - b);
  2941. });
  2942. if ( sortedChildrenKeys.length === 0 ) {
  2943. return null;
  2944. }
  2945. for ( var i = 0; i < sortedChildrenKeys.length; i++ ) {
  2946. if ( index < sortedChildrenKeys[i] ) {
  2947. if ( i === 0 ) {
  2948. return null;
  2949. } else {
  2950. return this.children[sortedChildrenKeys[i - 1]];
  2951. }
  2952. }
  2953. }
  2954. return this.children[sortedChildrenKeys[sortedChildrenKeys.length - 1]];
  2955. };
  2956. MibNode.prototype.isDescendant = function (address) {
  2957. return MibNode.oidIsDescended(this.address, address);
  2958. };
  2959. MibNode.prototype.isAncestor = function (address) {
  2960. return MibNode.oidIsDescended (address, this.address);
  2961. };
  2962. MibNode.prototype.getAncestorProvider = function () {
  2963. if ( this.provider ) {
  2964. return this;
  2965. } else if ( ! this.parent ) {
  2966. return null;
  2967. } else {
  2968. return this.parent.getAncestorProvider ();
  2969. }
  2970. };
  2971. MibNode.prototype.getTableColumnFromInstanceNode = function () {
  2972. if ( this.parent && this.parent.provider ) {
  2973. return this.address[this.address.length - 1];
  2974. } else if ( ! this.parent ) {
  2975. return null;
  2976. } else {
  2977. return this.parent.getTableColumnFromInstanceNode ();
  2978. }
  2979. };
  2980. MibNode.prototype.getConstraintsFromProvider = function () {
  2981. var providerNode = this.getAncestorProvider ();
  2982. if ( ! providerNode ) {
  2983. return null;
  2984. }
  2985. var provider = providerNode.provider;
  2986. if ( provider.type == MibProviderType.Scalar ) {
  2987. return provider.constraints;
  2988. } else if ( provider.type == MibProviderType.Table ) {
  2989. var columnNumber = this.getTableColumnFromInstanceNode ();
  2990. if ( ! columnNumber ) {
  2991. return null;
  2992. }
  2993. var columnDefinition = provider.tableColumns.filter (column => column.number == columnNumber)[0];
  2994. return columnDefinition ? columnDefinition.constraints : null;
  2995. } else {
  2996. return null;
  2997. }
  2998. };
  2999. MibNode.prototype.setValue = function (newValue) {
  3000. var len;
  3001. var min;
  3002. var max;
  3003. var range;
  3004. var found = false;
  3005. var constraints = this.getConstraintsFromProvider ();
  3006. if ( ! constraints ) {
  3007. this.value = newValue;
  3008. return true;
  3009. }
  3010. if ( constraints.enumeration ) {
  3011. if ( ! constraints.enumeration[newValue] ) {
  3012. return false;
  3013. }
  3014. } else if ( constraints.ranges ) {
  3015. for ( range of constraints.ranges ) {
  3016. min = "min" in range ? range.min : Number.MIN_SAFE_INTEGER;
  3017. max = "max" in range ? range.max : Number.MAX_SAFE_INTEGER;
  3018. if ( newValue >= min && newValue <= max ) {
  3019. found = true;
  3020. break;
  3021. }
  3022. }
  3023. if ( ! found ) {
  3024. return false;
  3025. }
  3026. } else if ( constraints.sizes ) {
  3027. // if size is constrained, value must have a length property
  3028. if ( ! ( "length" in newValue ) ) {
  3029. return false;
  3030. }
  3031. len = newValue.length;
  3032. for ( range of constraints.sizes ) {
  3033. min = "min" in range ? range.min : Number.MIN_SAFE_INTEGER;
  3034. max = "max" in range ? range.max : Number.MAX_SAFE_INTEGER;
  3035. if ( len >= min && len <= max ) {
  3036. found = true;
  3037. break;
  3038. }
  3039. }
  3040. if ( ! found ) {
  3041. return false;
  3042. }
  3043. }
  3044. this.value = newValue;
  3045. return true;
  3046. };
  3047. MibNode.prototype.getInstanceNodeForTableRow = function () {
  3048. var childCount = Object.keys (this.children).length;
  3049. if ( childCount == 0 ) {
  3050. if ( this.value != null ) {
  3051. return this;
  3052. } else {
  3053. return null;
  3054. }
  3055. } else if ( childCount == 1 ) {
  3056. return this.children[0].getInstanceNodeForTableRow();
  3057. } else if ( childCount > 1 ) {
  3058. return null;
  3059. }
  3060. };
  3061. MibNode.prototype.getInstanceNodeForTableRowIndex = function (index) {
  3062. var childCount = Object.keys (this.children).length;
  3063. var remainingIndex;
  3064. if ( childCount == 0 ) {
  3065. if ( this.value != null ) {
  3066. return this;
  3067. } else {
  3068. // not found
  3069. return null;
  3070. }
  3071. } else {
  3072. if ( index.length == 0 ) {
  3073. return this.getInstanceNodeForTableRow();
  3074. } else {
  3075. var nextChildIndexPart = index[0];
  3076. if ( nextChildIndexPart == null ) {
  3077. return null;
  3078. }
  3079. remainingIndex = index.slice(1);
  3080. if ( this.children[nextChildIndexPart] ) {
  3081. return this.children[nextChildIndexPart].getInstanceNodeForTableRowIndex(remainingIndex);
  3082. } else {
  3083. return null;
  3084. }
  3085. }
  3086. }
  3087. };
  3088. MibNode.prototype.getInstanceNodesForColumn = function () {
  3089. var columnNode = this;
  3090. var instanceNode = this;
  3091. var instanceNodes = [];
  3092. while (instanceNode && ( instanceNode == columnNode || columnNode.isAncestor (instanceNode.address) ) ) {
  3093. instanceNode = instanceNode.getNextInstanceNode ();
  3094. if ( instanceNode && columnNode.isAncestor (instanceNode.address) ) {
  3095. instanceNodes.push (instanceNode);
  3096. }
  3097. }
  3098. return instanceNodes;
  3099. };
  3100. MibNode.prototype.getNextInstanceNode = function () {
  3101. var siblingIndex;
  3102. var childrenAddresses;
  3103. var node = this;
  3104. if ( this.value != null ) {
  3105. // Need upwards traversal first
  3106. node = this;
  3107. while ( node ) {
  3108. siblingIndex = node.address.slice(-1)[0];
  3109. node = node.parent;
  3110. if ( ! node ) {
  3111. // end of MIB
  3112. return null;
  3113. } else {
  3114. childrenAddresses = Object.keys (node.children).sort ( (a, b) => a - b);
  3115. var siblingPosition = childrenAddresses.indexOf(siblingIndex.toString());
  3116. if ( siblingPosition + 1 < childrenAddresses.length ) {
  3117. node = node.children[childrenAddresses[siblingPosition + 1]];
  3118. break;
  3119. }
  3120. }
  3121. }
  3122. }
  3123. // Descent
  3124. while ( node ) {
  3125. if ( node.value != null ) {
  3126. return node;
  3127. }
  3128. childrenAddresses = Object.keys (node.children).sort ( (a, b) => a - b);
  3129. node = node.children[childrenAddresses[0]];
  3130. if ( ! node ) {
  3131. // unexpected
  3132. return null;
  3133. }
  3134. }
  3135. };
  3136. MibNode.prototype.delete = function () {
  3137. if ( Object.keys (this.children) > 0 ) {
  3138. throw new Error ("Cannot delete non-leaf MIB node");
  3139. }
  3140. var addressLastPart = this.address.slice(-1)[0];
  3141. delete this.parent.children[addressLastPart];
  3142. this.parent = null;
  3143. };
  3144. MibNode.prototype.pruneUpwards = function () {
  3145. if ( ! this.parent ) {
  3146. return;
  3147. }
  3148. if ( Object.keys (this.children).length == 0 ) {
  3149. var lastAddressPart = this.address.splice(-1)[0].toString();
  3150. delete this.parent.children[lastAddressPart];
  3151. this.parent.pruneUpwards();
  3152. this.parent = null;
  3153. }
  3154. };
  3155. MibNode.prototype.dump = function (options) {
  3156. var valueString;
  3157. if ( ( ! options.leavesOnly || options.showProviders ) && this.provider ) {
  3158. console.log (this.oid + " [" + MibProviderType[this.provider.type] + ": " + this.provider.name + "]");
  3159. } else if ( ( ! options.leavesOnly ) || Object.keys (this.children).length == 0 ) {
  3160. if ( this.value != null ) {
  3161. valueString = " = ";
  3162. valueString += options.showTypes ? ObjectType[this.valueType] + ": " : "";
  3163. valueString += options.showValues ? this.value : "";
  3164. } else {
  3165. valueString = "";
  3166. }
  3167. console.log (this.oid + valueString);
  3168. }
  3169. for ( var node of Object.keys (this.children).sort ((a, b) => a - b)) {
  3170. this.children[node].dump (options);
  3171. }
  3172. };
  3173. MibNode.oidIsDescended = function (oid, ancestor) {
  3174. var ancestorAddress = Mib.convertOidToAddress(ancestor);
  3175. var address = Mib.convertOidToAddress(oid);
  3176. var isAncestor = true;
  3177. if (address.length <= ancestorAddress.length) {
  3178. return false;
  3179. }
  3180. ancestorAddress.forEach (function (o, i) {
  3181. if (address[i] !== ancestorAddress[i]) {
  3182. isAncestor = false;
  3183. }
  3184. });
  3185. return isAncestor;
  3186. };
  3187. var Mib = function () {
  3188. var providersByOid;
  3189. this.root = new MibNode ([], null);
  3190. this.providerNodes = {};
  3191. // this.providers will be modified throughout this code.
  3192. // Keep this.providersByOid in sync with it
  3193. providersByOid = this.providersByOid = {};
  3194. this.providers = new Proxy({}, {
  3195. set: function (target, key, value) {
  3196. target[key] = value;
  3197. providersByOid[value.oid] = value;
  3198. },
  3199. deleteProperty: function (target, key) {
  3200. delete providersByOid[target[key].oid];
  3201. delete target[key];
  3202. }
  3203. });
  3204. };
  3205. Mib.prototype.addNodesForOid = function (oidString) {
  3206. var address = Mib.convertOidToAddress (oidString);
  3207. return this.addNodesForAddress (address);
  3208. };
  3209. Mib.prototype.addNodesForAddress = function (address) {
  3210. var node;
  3211. var i;
  3212. node = this.root;
  3213. for (i = 0; i < address.length; i++) {
  3214. if ( ! node.children.hasOwnProperty (address[i]) ) {
  3215. node.children[address[i]] = new MibNode (address.slice(0, i + 1), node);
  3216. }
  3217. node = node.children[address[i]];
  3218. }
  3219. return node;
  3220. };
  3221. Mib.prototype.lookup = function (oid) {
  3222. var address;
  3223. address = Mib.convertOidToAddress (oid);
  3224. return this.lookupAddress(address);
  3225. };
  3226. Mib.prototype.lookupAddress = function (address) {
  3227. var i;
  3228. var node;
  3229. node = this.root;
  3230. for (i = 0; i < address.length; i++) {
  3231. if ( ! node.children.hasOwnProperty (address[i])) {
  3232. return null;
  3233. }
  3234. node = node.children[address[i]];
  3235. }
  3236. return node;
  3237. };
  3238. Mib.prototype.getTreeNode = function (oid) {
  3239. var address = Mib.convertOidToAddress (oid);
  3240. var node;
  3241. node = this.lookupAddress (address);
  3242. // OID already on tree
  3243. if ( node ) {
  3244. return node;
  3245. }
  3246. while ( address.length > 0 ) {
  3247. var last = address.pop ();
  3248. var parent = this.lookupAddress (address);
  3249. if ( parent ) {
  3250. node = parent.findChildImmediatelyBefore (last);
  3251. if ( !node )
  3252. return parent;
  3253. while ( true ) {
  3254. // Find the last descendant
  3255. var childrenAddresses = Object.keys (node.children).sort ( (a, b) => a - b);
  3256. if ( childrenAddresses.length == 0 )
  3257. return node;
  3258. node = node.children[childrenAddresses[childrenAddresses.length - 1]];
  3259. }
  3260. }
  3261. }
  3262. return this.root;
  3263. };
  3264. Mib.prototype.getProviderNodeForInstance = function (instanceNode) {
  3265. if ( instanceNode.provider ) {
  3266. // throw new ReferenceError ("Instance node has provider which should never happen");
  3267. return null;
  3268. }
  3269. return instanceNode.getAncestorProvider ();
  3270. };
  3271. Mib.prototype.addProviderToNode = function (provider) {
  3272. var node = this.addNodesForOid (provider.oid);
  3273. node.provider = provider;
  3274. if ( provider.type == MibProviderType.Table ) {
  3275. if ( ! provider.tableIndex ) {
  3276. provider.tableIndex = [1];
  3277. }
  3278. }
  3279. this.providerNodes[provider.name] = node;
  3280. return node;
  3281. };
  3282. Mib.prototype.getColumnFromProvider = function (provider, indexEntry) {
  3283. var column = null;
  3284. if ( indexEntry.columnName ) {
  3285. column = provider.tableColumns.filter (column => column.name == indexEntry.columnName )[0];
  3286. } else if ( indexEntry.columnNumber !== undefined && indexEntry.columnNumber !== null ) {
  3287. column = provider.tableColumns.filter (column => column.number == indexEntry.columnNumber )[0];
  3288. }
  3289. return column;
  3290. };
  3291. Mib.prototype.populateIndexEntryFromColumn = function (localProvider, indexEntry, i) {
  3292. var column = null;
  3293. var tableProviders;
  3294. if ( ! indexEntry.columnName && ! indexEntry.columnNumber ) {
  3295. throw new Error ("Index entry " + i + ": does not have either a columnName or columnNumber");
  3296. }
  3297. if ( indexEntry.foreign ) {
  3298. // Explicit foreign table is first to search
  3299. column = this.getColumnFromProvider (this.providers[indexEntry.foreign], indexEntry);
  3300. } else {
  3301. // If foreign table isn't given, search the local table next
  3302. column = this.getColumnFromProvider (localProvider, indexEntry);
  3303. if ( ! column ) {
  3304. // as a last resort, try to find the column in a foreign table
  3305. tableProviders = Object.values(this.providers).
  3306. filter ( prov => prov.type == MibProviderType.Table );
  3307. for ( var provider of tableProviders ) {
  3308. column = this.getColumnFromProvider (provider, indexEntry);
  3309. if ( column ) {
  3310. indexEntry.foreign = provider.name;
  3311. break;
  3312. }
  3313. }
  3314. }
  3315. }
  3316. if ( ! column ) {
  3317. throw new Error ("Could not find column for index entry with column " + indexEntry.columnName);
  3318. }
  3319. if ( indexEntry.columnName && indexEntry.columnName != column.name ) {
  3320. throw new Error ("Index entry " + i + ": Calculated column name " + column.name +
  3321. "does not match supplied column name " + indexEntry.columnName);
  3322. }
  3323. if ( indexEntry.columnNumber && indexEntry.columnNumber != column.number ) {
  3324. throw new Error ("Index entry " + i + ": Calculated column number " + column.number +
  3325. " does not match supplied column number " + indexEntry.columnNumber);
  3326. }
  3327. if ( ! indexEntry.columnName ) {
  3328. indexEntry.columnName = column.name;
  3329. }
  3330. if ( ! indexEntry.columnNumber ) {
  3331. indexEntry.columnNumber = column.number;
  3332. }
  3333. indexEntry.type = column.type;
  3334. };
  3335. Mib.prototype.registerProvider = function (provider) {
  3336. this.providers[provider.name] = provider;
  3337. if ( provider.type == MibProviderType.Table ) {
  3338. if ( provider.tableAugments ) {
  3339. if ( provider.tableAugments == provider.name ) {
  3340. throw new Error ("Table " + provider.name + " cannot augment itself");
  3341. }
  3342. var augmentProvider = this.providers[provider.tableAugments];
  3343. if ( ! augmentProvider ) {
  3344. throw new Error ("Cannot find base table " + provider.tableAugments + " to augment");
  3345. }
  3346. provider.tableIndex = JSON.parse(JSON.stringify(augmentProvider.tableIndex));
  3347. provider.tableIndex.map (index => index.foreign = augmentProvider.name);
  3348. } else {
  3349. if ( ! provider.tableIndex ) {
  3350. provider.tableIndex = [1]; // default to first column index
  3351. }
  3352. for ( var i = 0 ; i < provider.tableIndex.length ; i++ ) {
  3353. var indexEntry = provider.tableIndex[i];
  3354. if ( typeof indexEntry == 'number' ) {
  3355. provider.tableIndex[i] = {
  3356. columnNumber: indexEntry
  3357. };
  3358. } else if ( typeof indexEntry == 'string' ) {
  3359. provider.tableIndex[i] = {
  3360. columnName: indexEntry
  3361. };
  3362. }
  3363. indexEntry = provider.tableIndex[i];
  3364. this.populateIndexEntryFromColumn (provider, indexEntry, i);
  3365. }
  3366. }
  3367. }
  3368. };
  3369. Mib.prototype.setScalarDefaultValue = function (name, value) {
  3370. let provider = this.getProvider(name);
  3371. provider.defVal = value;
  3372. };
  3373. Mib.prototype.setTableRowDefaultValues = function (name, values) {
  3374. let provider = this.getProvider(name);
  3375. let tc = provider.tableColumns;
  3376. // We must be given an array of exactly the right number of columns
  3377. if (values.length != tc.length) {
  3378. throw new Error(`Incorrect values length: got ${values.length}; expected ${tc.length}`);
  3379. }
  3380. // Add defVal to each table column.
  3381. tc.forEach((entry, i) => {
  3382. if (typeof values[i] != "undefined") {
  3383. entry.defVal = values[i];
  3384. }
  3385. });
  3386. };
  3387. Mib.prototype.setScalarRanges = function (name, ranges ) {
  3388. let provider = this.getProvider(name);
  3389. provider.constraints = { ranges };
  3390. };
  3391. Mib.prototype.setTableColumnRanges = function(name, column, ranges ) {
  3392. let provider = this.getProvider(name);
  3393. let tc = provider.tableColumns;
  3394. tc[column].constraints = { ranges };
  3395. };
  3396. Mib.prototype.setScalarSizes = function (name, sizes ) {
  3397. let provider = this.getProvider(name);
  3398. provider.constraints = { sizes };
  3399. };
  3400. Mib.prototype.setTableColumnSizes = function(name, column, sizes ) {
  3401. let provider = this.getProvider(name);
  3402. let tc = provider.tableColumns;
  3403. tc[column].constraints = { sizes };
  3404. };
  3405. Mib.prototype.registerProviders = function (providers) {
  3406. for ( var provider of providers ) {
  3407. this.registerProvider (provider);
  3408. }
  3409. };
  3410. Mib.prototype.unregisterProvider = function (name) {
  3411. var providerNode = this.providerNodes[name];
  3412. if ( providerNode ) {
  3413. var providerNodeParent = providerNode.parent;
  3414. providerNode.delete();
  3415. providerNodeParent.pruneUpwards();
  3416. delete this.providerNodes[name];
  3417. }
  3418. delete this.providers[name];
  3419. };
  3420. Mib.prototype.getProvider = function (name) {
  3421. return this.providers[name];
  3422. };
  3423. Mib.prototype.getProviders = function () {
  3424. return this.providers;
  3425. };
  3426. Mib.prototype.dumpProviders = function () {
  3427. var extraInfo;
  3428. for ( var provider of Object.values(this.providers) ) {
  3429. extraInfo = provider.type == MibProviderType.Scalar ? ObjectType[provider.scalarType] : "Columns = " + provider.tableColumns.length;
  3430. console.log(MibProviderType[provider.type] + ": " + provider.name + " (" + provider.oid + "): " + extraInfo);
  3431. }
  3432. };
  3433. Mib.prototype.getScalarValue = function (scalarName) {
  3434. var providerNode = this.providerNodes[scalarName];
  3435. if ( ! providerNode || ! providerNode.provider || providerNode.provider.type != MibProviderType.Scalar ) {
  3436. throw new ReferenceError ("Failed to get node for registered MIB provider " + scalarName);
  3437. }
  3438. var instanceAddress = providerNode.address.concat ([0]);
  3439. if ( ! this.lookup (instanceAddress) ) {
  3440. throw new Error ("Failed created instance node for registered MIB provider " + scalarName);
  3441. }
  3442. var instanceNode = this.lookup (instanceAddress);
  3443. return instanceNode.value;
  3444. };
  3445. Mib.prototype.setScalarValue = function (scalarName, newValue) {
  3446. var providerNode;
  3447. var instanceNode;
  3448. var provider;
  3449. if ( ! this.providers[scalarName] ) {
  3450. throw new ReferenceError ("Provider " + scalarName + " not registered with this MIB");
  3451. }
  3452. providerNode = this.providerNodes[scalarName];
  3453. if ( ! providerNode ) {
  3454. providerNode = this.addProviderToNode (this.providers[scalarName]);
  3455. }
  3456. provider = providerNode.provider;
  3457. if ( ! providerNode || ! provider || provider.type != MibProviderType.Scalar ) {
  3458. throw new ReferenceError ("Could not find MIB node for registered provider " + scalarName);
  3459. }
  3460. var instanceAddress = providerNode.address.concat ([0]);
  3461. instanceNode = this.lookup (instanceAddress);
  3462. if ( ! instanceNode ) {
  3463. this.addNodesForAddress (instanceAddress);
  3464. instanceNode = this.lookup (instanceAddress);
  3465. instanceNode.valueType = provider.scalarType;
  3466. }
  3467. instanceNode.value = newValue;
  3468. // return instanceNode.setValue (newValue);
  3469. };
  3470. Mib.prototype.getProviderNodeForTable = function (table) {
  3471. var providerNode;
  3472. var provider;
  3473. providerNode = this.providerNodes[table];
  3474. if ( ! providerNode ) {
  3475. throw new ReferenceError ("No MIB provider registered for " + table);
  3476. }
  3477. provider = providerNode.provider;
  3478. if ( ! providerNode ) {
  3479. throw new ReferenceError ("No MIB provider definition for registered provider " + table);
  3480. }
  3481. if ( provider.type != MibProviderType.Table ) {
  3482. throw new TypeError ("Registered MIB provider " + table +
  3483. " is not of the correct type (is type " + MibProviderType[provider.type] + ")");
  3484. }
  3485. return providerNode;
  3486. };
  3487. Mib.prototype.getOidAddressFromValue = function (value, indexPart) {
  3488. var oidComponents;
  3489. switch ( indexPart.type ) {
  3490. case ObjectType.OID:
  3491. oidComponents = value.split (".");
  3492. break;
  3493. case ObjectType.OctetString:
  3494. if ( value instanceof Buffer ) {
  3495. // Buffer
  3496. oidComponents = Array.prototype.slice.call (value);
  3497. } else {
  3498. // string
  3499. oidComponents = [...value].map (c => c.charCodeAt());
  3500. }
  3501. break;
  3502. case ObjectType.IpAddress:
  3503. return value.split (".");
  3504. default:
  3505. return [value];
  3506. }
  3507. if ( ! indexPart.implied && ! indexPart.length ) {
  3508. oidComponents.unshift (oidComponents.length);
  3509. }
  3510. return oidComponents;
  3511. };
  3512. /* What is this empty function here for?
  3513. Mib.prototype.getValueFromOidAddress = function (oid, indexPart) {
  3514. };
  3515. */
  3516. Mib.prototype.getTableRowInstanceFromRow = function (provider, row) {
  3517. var rowIndex = [];
  3518. var foreignColumnParts;
  3519. var localColumnParts;
  3520. var localColumnPosition;
  3521. var oidArrayForValue;
  3522. // foreign columns are first in row
  3523. foreignColumnParts = provider.tableIndex.filter ( indexPart => indexPart.foreign );
  3524. for ( var i = 0; i < foreignColumnParts.length ; i++ ) {
  3525. //rowIndex.push (row[i]);
  3526. oidArrayForValue = this.getOidAddressFromValue (row[i], foreignColumnParts[i]);
  3527. rowIndex = rowIndex.concat (oidArrayForValue);
  3528. }
  3529. // then local columns
  3530. localColumnParts = provider.tableIndex.filter ( indexPart => ! indexPart.foreign );
  3531. for ( var localColumnPart of localColumnParts ) {
  3532. localColumnPosition = provider.tableColumns.findIndex (column => column.number == localColumnPart.columnNumber);
  3533. oidArrayForValue = this.getOidAddressFromValue (row[foreignColumnParts.length + localColumnPosition], localColumnPart);
  3534. rowIndex = rowIndex.concat (oidArrayForValue);
  3535. }
  3536. return rowIndex;
  3537. };
  3538. Mib.getRowIndexFromOid = function (oid, index) {
  3539. var addressRemaining = oid.split (".");
  3540. var length = 0;
  3541. var values = [];
  3542. var value;
  3543. for ( var indexPart of index ) {
  3544. switch ( indexPart.type ) {
  3545. case ObjectType.OID:
  3546. if ( indexPart.implied ) {
  3547. length = addressRemaining.length;
  3548. } else {
  3549. length = addressRemaining.shift ();
  3550. }
  3551. value = addressRemaining.splice (0, length);
  3552. values.push (value.join ("."));
  3553. break;
  3554. case ObjectType.IpAddress:
  3555. length = 4;
  3556. value = addressRemaining.splice (0, length);
  3557. values.push (value.join ("."));
  3558. break;
  3559. case ObjectType.OctetString:
  3560. if ( indexPart.implied ) {
  3561. length = addressRemaining.length;
  3562. } else {
  3563. length = addressRemaining.shift ();
  3564. }
  3565. value = addressRemaining.splice (0, length);
  3566. value = value.map (c => String.fromCharCode(c)).join ("");
  3567. values.push (value);
  3568. break;
  3569. default:
  3570. values.push (parseInt (addressRemaining.shift ()) );
  3571. }
  3572. }
  3573. return values;
  3574. };
  3575. Mib.prototype.getTableRowInstanceFromRowIndex = function (provider, rowIndex) {
  3576. var rowIndexOid = [];
  3577. var indexPart;
  3578. var keyPart;
  3579. for ( var i = 0; i < provider.tableIndex.length ; i++ ) {
  3580. indexPart = provider.tableIndex[i];
  3581. keyPart = rowIndex[i];
  3582. rowIndexOid = rowIndexOid.concat (this.getOidAddressFromValue (keyPart, indexPart));
  3583. }
  3584. return rowIndexOid;
  3585. };
  3586. Mib.prototype.addTableRow = function (table, row) {
  3587. var providerNode;
  3588. var provider;
  3589. var instance = [];
  3590. var instanceAddress;
  3591. var instanceNode;
  3592. var rowValueOffset;
  3593. if ( this.providers[table] && ! this.providerNodes[table] ) {
  3594. this.addProviderToNode (this.providers[table]);
  3595. }
  3596. providerNode = this.getProviderNodeForTable (table);
  3597. provider = providerNode.provider;
  3598. rowValueOffset = provider.tableIndex.filter ( indexPart => indexPart.foreign ).length;
  3599. instance = this.getTableRowInstanceFromRow (provider, row);
  3600. for ( var i = 0; i < provider.tableColumns.length ; i++ ) {
  3601. var column = provider.tableColumns[i];
  3602. var isColumnIndex = provider.tableIndex.some ( indexPart => indexPart.columnNumber == column.number );
  3603. // prevent not-accessible and accessible-for-notify index entries from being added as columns in the row
  3604. if ( ! isColumnIndex || ! (column.maxAccess === MaxAccess['not-accessible'] || column.maxAccess === MaxAccess['accessible-for-notify']) ) {
  3605. instanceAddress = providerNode.address.concat (column.number).concat (instance);
  3606. this.addNodesForAddress (instanceAddress);
  3607. instanceNode = this.lookup (instanceAddress);
  3608. instanceNode.valueType = column.type;
  3609. instanceNode.value = row[rowValueOffset + i];
  3610. }
  3611. }
  3612. };
  3613. Mib.prototype.getTableColumnDefinitions = function (table) {
  3614. var providerNode;
  3615. var provider;
  3616. providerNode = this.getProviderNodeForTable (table);
  3617. provider = providerNode.provider;
  3618. return provider.tableColumns;
  3619. };
  3620. Mib.prototype.getTableColumnCells = function (table, columnNumber, includeInstances) {
  3621. var provider = this.providers[table];
  3622. var providerIndex = provider.tableIndex;
  3623. var providerNode = this.getProviderNodeForTable (table);
  3624. var columnNode = providerNode.children[columnNumber];
  3625. if ( ! columnNode ) {
  3626. return null;
  3627. }
  3628. var instanceNodes = columnNode.getInstanceNodesForColumn ();
  3629. var instanceOid;
  3630. var indexValues = [];
  3631. var columnValues = [];
  3632. for ( var instanceNode of instanceNodes ) {
  3633. instanceOid = Mib.getSubOidFromBaseOid (instanceNode.oid, columnNode.oid);
  3634. indexValues.push (Mib.getRowIndexFromOid (instanceOid, providerIndex));
  3635. columnValues.push (instanceNode.value);
  3636. }
  3637. if ( includeInstances ) {
  3638. return [ indexValues, columnValues ];
  3639. } else {
  3640. return columnValues;
  3641. }
  3642. };
  3643. Mib.prototype.getTableRowCells = function (table, rowIndex) {
  3644. var provider;
  3645. var providerNode;
  3646. var columnNode;
  3647. var instanceAddress;
  3648. var instanceNode;
  3649. var row = [];
  3650. var rowFound = false;
  3651. provider = this.providers[table];
  3652. providerNode = this.getProviderNodeForTable (table);
  3653. instanceAddress = this.getTableRowInstanceFromRowIndex (provider, rowIndex);
  3654. for ( var columnNumber of Object.keys (providerNode.children) ) {
  3655. columnNode = providerNode.children[columnNumber];
  3656. if ( columnNode ) {
  3657. instanceNode = columnNode.getInstanceNodeForTableRowIndex (instanceAddress);
  3658. if ( instanceNode ) {
  3659. row.push (instanceNode.value);
  3660. rowFound = true;
  3661. } else {
  3662. row.push (null);
  3663. }
  3664. } else {
  3665. row.push (null);
  3666. }
  3667. }
  3668. if ( rowFound ) {
  3669. return row;
  3670. } else {
  3671. return null;
  3672. }
  3673. };
  3674. Mib.prototype.getTableCells = function (table, byRows, includeInstances) {
  3675. var providerNode;
  3676. var column;
  3677. var data = [];
  3678. providerNode = this.getProviderNodeForTable (table);
  3679. for ( var columnNumber of Object.keys (providerNode.children) ) {
  3680. column = this.getTableColumnCells (table, columnNumber, includeInstances);
  3681. if ( includeInstances ) {
  3682. data.push (...column);
  3683. includeInstances = false;
  3684. } else {
  3685. data.push (column);
  3686. }
  3687. }
  3688. if ( byRows ) {
  3689. return Object.keys (data[0]).map (function (c) {
  3690. return data.map (function (r) { return r[c]; });
  3691. });
  3692. } else {
  3693. return data;
  3694. }
  3695. };
  3696. Mib.prototype.getTableSingleCell = function (table, columnNumber, rowIndex) {
  3697. var provider;
  3698. var providerNode;
  3699. var instanceAddress;
  3700. var columnNode;
  3701. var instanceNode;
  3702. provider = this.providers[table];
  3703. providerNode = this.getProviderNodeForTable (table);
  3704. instanceAddress = this.getTableRowInstanceFromRowIndex (provider, rowIndex);
  3705. columnNode = providerNode.children[columnNumber];
  3706. instanceNode = columnNode.getInstanceNodeForTableRowIndex (instanceAddress);
  3707. return instanceNode.value;
  3708. };
  3709. Mib.prototype.setTableSingleCell = function (table, columnNumber, rowIndex, value) {
  3710. var provider;
  3711. var providerNode;
  3712. var columnNode;
  3713. var instanceNode;
  3714. var instanceAddress;
  3715. provider = this.providers[table];
  3716. providerNode = this.getProviderNodeForTable (table);
  3717. instanceAddress = this.getTableRowInstanceFromRowIndex (provider, rowIndex);
  3718. columnNode = providerNode.children[columnNumber];
  3719. instanceNode = columnNode.getInstanceNodeForTableRowIndex (instanceAddress);
  3720. instanceNode.value = value;
  3721. // return instanceNode.setValue (value);
  3722. };
  3723. Mib.prototype.deleteTableRow = function (table, rowIndex) {
  3724. var provider;
  3725. var providerNode;
  3726. var instanceAddress;
  3727. var columnNode;
  3728. var instanceNode;
  3729. var instanceParentNode;
  3730. provider = this.providers[table];
  3731. providerNode = this.getProviderNodeForTable (table);
  3732. instanceAddress = this.getTableRowInstanceFromRowIndex (provider, rowIndex);
  3733. for ( var columnNumber of Object.keys (providerNode.children) ) {
  3734. columnNode = providerNode.children[columnNumber];
  3735. instanceNode = columnNode.getInstanceNodeForTableRowIndex (instanceAddress);
  3736. if ( instanceNode ) {
  3737. instanceParentNode = instanceNode.parent;
  3738. instanceNode.delete();
  3739. instanceParentNode.pruneUpwards();
  3740. } else {
  3741. throw new ReferenceError ("Cannot find row for index " + rowIndex + " at registered provider " + table);
  3742. }
  3743. }
  3744. if ( Object.keys (this.providerNodes[table].children).length === 0 ) {
  3745. delete this.providerNodes[table];
  3746. }
  3747. return true;
  3748. };
  3749. Mib.prototype.dump = function (options) {
  3750. if ( ! options ) {
  3751. options = {};
  3752. }
  3753. var completedOptions = {
  3754. leavesOnly: options.leavesOnly === undefined ? true : options.leavesOnly,
  3755. showProviders: options.showProviders === undefined ? true : options.showProviders,
  3756. showValues: options.showValues === undefined ? true : options.showValues,
  3757. showTypes: options.showTypes === undefined ? true : options.showTypes
  3758. };
  3759. this.root.dump (completedOptions);
  3760. };
  3761. Mib.convertOidToAddress = function (oid) {
  3762. var address;
  3763. var oidArray;
  3764. var i;
  3765. if (typeof (oid) === 'object' && util.isArray(oid)) {
  3766. address = oid;
  3767. } else if (typeof (oid) === 'string') {
  3768. address = oid.split('.');
  3769. } else {
  3770. throw new TypeError('oid (string or array) is required');
  3771. }
  3772. if (address.length < 1)
  3773. throw new RangeError('object identifier is too short');
  3774. oidArray = [];
  3775. for (i = 0; i < address.length; i++) {
  3776. var n;
  3777. if (address[i] === '')
  3778. continue;
  3779. if (address[i] === true || address[i] === false) {
  3780. throw new TypeError('object identifier component ' +
  3781. address[i] + ' is malformed');
  3782. }
  3783. n = Number(address[i]);
  3784. if (isNaN(n)) {
  3785. throw new TypeError('object identifier component ' +
  3786. address[i] + ' is malformed');
  3787. }
  3788. if (n % 1 !== 0) {
  3789. throw new TypeError('object identifier component ' +
  3790. address[i] + ' is not an integer');
  3791. }
  3792. if (i === 0 && n > 2) {
  3793. throw new RangeError('object identifier does not ' +
  3794. 'begin with 0, 1, or 2');
  3795. }
  3796. if (i === 1 && n > 39) {
  3797. throw new RangeError('object identifier second ' +
  3798. 'component ' + n + ' exceeds encoding limit of 39');
  3799. }
  3800. if (n < 0) {
  3801. throw new RangeError('object identifier component ' +
  3802. address[i] + ' is negative');
  3803. }
  3804. if (n > MAX_SIGNED_INT32) {
  3805. throw new RangeError('object identifier component ' +
  3806. address[i] + ' is too large');
  3807. }
  3808. oidArray.push(n);
  3809. }
  3810. return oidArray;
  3811. };
  3812. Mib.getSubOidFromBaseOid = function (oid, base) {
  3813. return oid.substring (base.length + 1);
  3814. };
  3815. Mib.create = function () {
  3816. return new Mib ();
  3817. };
  3818. var MibRequest = function (requestDefinition) {
  3819. this.operation = requestDefinition.operation;
  3820. this.address = Mib.convertOidToAddress (requestDefinition.oid);
  3821. this.oid = this.address.join ('.');
  3822. this.providerNode = requestDefinition.providerNode;
  3823. this.instanceNode = requestDefinition.instanceNode;
  3824. };
  3825. MibRequest.prototype.isScalar = function () {
  3826. return this.providerNode && this.providerNode.provider &&
  3827. this.providerNode.provider.type == MibProviderType.Scalar;
  3828. };
  3829. MibRequest.prototype.isTabular = function () {
  3830. return this.providerNode && this.providerNode.provider &&
  3831. this.providerNode.provider.type == MibProviderType.Table;
  3832. };
  3833. var Agent = function (options, callback, mib) {
  3834. DEBUG = options.debug;
  3835. this.listener = new Listener (options, this);
  3836. this.engine = new Engine (options.engineID);
  3837. this.authorizer = new Authorizer (options);
  3838. this.callback = callback || function () {};
  3839. this.mib = mib || new Mib ();
  3840. this.context = "";
  3841. this.forwarder = new Forwarder (this.listener, this.callback);
  3842. };
  3843. Agent.prototype.getMib = function () {
  3844. return this.mib;
  3845. };
  3846. Agent.prototype.setMib = function (mib) {
  3847. this.mib = mib;
  3848. };
  3849. Agent.prototype.getAuthorizer = function () {
  3850. return this.authorizer;
  3851. };
  3852. Agent.prototype.registerProvider = function (provider) {
  3853. this.mib.registerProvider (provider);
  3854. };
  3855. Agent.prototype.registerProviders = function (providers) {
  3856. this.mib.registerProviders (providers);
  3857. };
  3858. Agent.prototype.unregisterProvider = function (name) {
  3859. this.mib.unregisterProvider (name);
  3860. };
  3861. Agent.prototype.getProvider = function (name) {
  3862. return this.mib.getProvider (name);
  3863. };
  3864. Agent.prototype.getProviders = function () {
  3865. return this.mib.getProviders ();
  3866. };
  3867. Agent.prototype.scalarReadCreateHandlerInternal = function (createRequest) {
  3868. let provider = createRequest.provider;
  3869. // If there's a default value specified...
  3870. if ( provider && typeof provider.defVal != "undefined" ) {
  3871. // ... then use it
  3872. return provider.defVal;
  3873. }
  3874. // We don't have enough information to auto-create the scalar
  3875. return undefined;
  3876. };
  3877. Agent.prototype.tableRowStatusHandlerInternal = function (createRequest) {
  3878. let provider = createRequest.provider;
  3879. let action = createRequest.action;
  3880. let row = createRequest.row;
  3881. let values = [];
  3882. let missingDefVal = false;
  3883. let rowIndexValues = Array.isArray( row ) ? row.slice(0) : [ row ];
  3884. const tc = provider.tableColumns;
  3885. tc.forEach(
  3886. (columnInfo) => {
  3887. let entries;
  3888. // Index columns get successive values from the rowIndexValues array.
  3889. // RowStatus columns get either "active" or "notInService" values.
  3890. // Every other column requires a defVal.
  3891. entries = provider.tableIndex.filter( entry => columnInfo.number === entry.columnNumber );
  3892. if (entries.length > 0 ) {
  3893. // It's an index column. Use the next index value
  3894. values.push(rowIndexValues.shift());
  3895. } else if ( columnInfo.rowStatus ) {
  3896. // It's the RowStatus column. Retain the action value for now; replaced later
  3897. values.push( RowStatus[action] );
  3898. } else if ( "defVal" in columnInfo ) {
  3899. // Neither index nor RowStatus column, so use the default value
  3900. values.push( columnInfo.defVal );
  3901. } else {
  3902. // Default value was required but not found
  3903. console.log("No defVal defined for column:", columnInfo);
  3904. missingDefVal = true;
  3905. values.push( undefined ); // just for debugging; never gets returned
  3906. }
  3907. }
  3908. );
  3909. // If a default value was missing, we can't auto-create the table row.
  3910. // Otherwise, we're good to go: give 'em the column values.
  3911. return missingDefVal ? undefined : values;
  3912. };
  3913. Agent.prototype.onMsg = function (buffer, rinfo) {
  3914. var message = Listener.processIncoming (buffer, this.authorizer, this.callback);
  3915. var reportMessage;
  3916. if ( ! message ) {
  3917. return;
  3918. }
  3919. // SNMPv3 discovery
  3920. if ( message.version == Version3 && message.pdu.type == PduType.GetRequest &&
  3921. ! message.hasAuthoritativeEngineID() && message.isReportable () ) {
  3922. reportMessage = message.createReportResponseMessage (this.engine, this.context);
  3923. this.listener.send (reportMessage, rinfo);
  3924. return;
  3925. }
  3926. // Request processing
  3927. // debug (JSON.stringify (message.pdu, null, 2));
  3928. if ( message.pdu.contextName && message.pdu.contextName != "" ) {
  3929. this.onProxyRequest (message, rinfo);
  3930. } else if ( message.pdu.type == PduType.GetRequest ) {
  3931. this.getRequest (message, rinfo);
  3932. } else if ( message.pdu.type == PduType.SetRequest ) {
  3933. this.setRequest (message, rinfo);
  3934. } else if ( message.pdu.type == PduType.GetNextRequest ) {
  3935. this.getNextRequest (message, rinfo);
  3936. } else if ( message.pdu.type == PduType.GetBulkRequest ) {
  3937. this.getBulkRequest (message, rinfo);
  3938. } else {
  3939. this.callback (new RequestInvalidError ("Unexpected PDU type " +
  3940. message.pdu.type + " (" + PduType[message.pdu.type] + ")"));
  3941. }
  3942. };
  3943. Agent.prototype.castSetValue = function ( type, value ) {
  3944. switch (type) {
  3945. case ObjectType.Boolean:
  3946. return !! value;
  3947. case ObjectType.Integer:
  3948. if ( typeof value != "number" && typeof value != "string" ) {
  3949. throw new Error("Invalid Integer", value);
  3950. }
  3951. return typeof value == "number" ? value : parseInt(value, 10);
  3952. case ObjectType.OctetString:
  3953. if ( value instanceof Buffer) {
  3954. return value.toString();
  3955. } else if ( typeof value != "string" ) {
  3956. throw new Error("Invalid OctetString", value);
  3957. } else {
  3958. return value;
  3959. }
  3960. case ObjectType.OID:
  3961. if ( typeof value != "string" || ! value.match(/[0-9]+\([.][0-9]+\)+/) ) {
  3962. throw new Error("Invalid OID", value);
  3963. }
  3964. return value;
  3965. case ObjectType.Counter:
  3966. case ObjectType.Counter64:
  3967. // Counters should be initialized to 0 (RFC2578, end of section 7.9)
  3968. // We'll do so.
  3969. return 0;
  3970. case ObjectType.IpAddress:
  3971. // A 32-bit internet address represented as OCTET STRING of length 4
  3972. if ( typeof value != "string" || value.length != 4 ) {
  3973. throw new Error("Invalid IpAddress", value);
  3974. }
  3975. return value;
  3976. default :
  3977. // Assume the caller knows what he's doing
  3978. return value;
  3979. }
  3980. };
  3981. Agent.prototype.tryCreateInstance = function (varbind, requestType) {
  3982. var row;
  3983. var column;
  3984. var value;
  3985. var subOid;
  3986. var subAddr;
  3987. var address;
  3988. var fullAddress;
  3989. var rowStatusColumn;
  3990. var provider;
  3991. var providersByOid = this.mib.providersByOid;
  3992. var oid = varbind.oid;
  3993. var createRequest;
  3994. // Look for the provider.
  3995. fullAddress = Mib.convertOidToAddress (oid);
  3996. for ( address = fullAddress.slice(0) ; address.length > 0; address.pop() ) {
  3997. subOid = address.join("."); // create an oid from the current address
  3998. // Does this oid have a provider?
  3999. provider = providersByOid[subOid];
  4000. if (provider) {
  4001. // Yup. Figure out what to do with it.
  4002. // console.log(`FOUND MATCH TO ${oid}:\n`, providersByOid[subOid]);
  4003. //
  4004. // Scalar
  4005. //
  4006. if ( provider.type === MibProviderType.Scalar ) {
  4007. // Does this provider support "read-create"?
  4008. if ( provider.maxAccess != MaxAccess["read-create"] ) {
  4009. // Nope. Nothing we can do to help 'em.
  4010. return undefined;
  4011. }
  4012. // See if the provider says not to auto-create this scalar
  4013. if ( provider.createHandler === null ) {
  4014. return undefined;
  4015. }
  4016. // Call the provider-provided handler if available, or the default one if not
  4017. createRequest = {
  4018. provider: provider
  4019. };
  4020. value = ( provider.createHandler || this.scalarReadCreateHandlerInternal ) ( createRequest );
  4021. if ( typeof value == "undefined" ) {
  4022. // Handler said do not create instance
  4023. return undefined;
  4024. }
  4025. // Ensure the value is of the correct type, and save it
  4026. value = this.castSetValue ( provider.scalarType, value );
  4027. this.mib.setScalarValue ( provider.name, value );
  4028. // Now there should be an instanceNode available.
  4029. return {
  4030. instanceNode: this.mib.lookup (oid),
  4031. providerType: MibProviderType.Scalar
  4032. };
  4033. }
  4034. //
  4035. // Table
  4036. //
  4037. // This is where we would support "read-create" of table
  4038. // columns. RFC2578 section 7.1.12.1, however, implies
  4039. // that rows should be created only via use of the
  4040. // RowStatus column. We'll therefore avoid creating rows
  4041. // based solely on any other column's "read-create"
  4042. // max-access value.
  4043. //
  4044. // RowStatus setter (actions)
  4045. //
  4046. subOid = Mib.getSubOidFromBaseOid (oid, provider.oid);
  4047. subAddr = subOid.split(".");
  4048. column = parseInt(subAddr.shift(), 10);
  4049. row = Mib.getRowIndexFromOid(subAddr.join("."), provider.tableIndex);
  4050. rowStatusColumn = provider.tableColumns.reduce( (acc, current) => current.rowStatus ? current.number : acc, null );
  4051. if ( requestType === PduType.SetRequest &&
  4052. typeof rowStatusColumn == "number" &&
  4053. column === rowStatusColumn ) {
  4054. if ( (varbind.value === RowStatus["createAndGo"] || varbind.value === RowStatus["createAndWait"]) &&
  4055. provider.createHandler !== null ) {
  4056. // The create handler will return an array
  4057. // containing all table column values for the
  4058. // table row to be added.
  4059. createRequest = {
  4060. provider: provider,
  4061. action: RowStatus[varbind.value],
  4062. row: row
  4063. };
  4064. value = ( provider.createHandler || this.tableRowStatusHandlerInternal )( createRequest );
  4065. if ( typeof value == "undefined") {
  4066. // Handler said do not create instance
  4067. return undefined;
  4068. }
  4069. if (! Array.isArray( value ) ) {
  4070. throw new Error("createHandler must return an array or undefined; got", value);
  4071. }
  4072. if ( value.length != provider.tableColumns.length ) {
  4073. throw new Error("createHandler's returned array must contain a value for for each column" );
  4074. }
  4075. // Map each column's value to the appropriate type
  4076. value = value.map( (v, i) => this.castSetValue ( provider.tableColumns[i].type, v ) );
  4077. // Add the table row
  4078. this.mib.addTableRow ( provider.name, value );
  4079. // Now there should be an instanceNode available.
  4080. return {
  4081. instanceNode: this.mib.lookup (oid),
  4082. providerType: MibProviderType.Table,
  4083. action: RowStatus[varbind.value],
  4084. rowIndex: row,
  4085. row: value
  4086. };
  4087. }
  4088. }
  4089. return undefined;
  4090. }
  4091. }
  4092. // console.log(`NO MATCH TO ${oid}`);
  4093. return undefined;
  4094. };
  4095. Agent.prototype.isAllowed = function (pduType, provider, instanceNode) {
  4096. var column;
  4097. var maxAccess;
  4098. var columnEntry;
  4099. if (provider.type === MibProviderType.Scalar) {
  4100. // It's a scalar. We'll use the provider's maxAccess
  4101. maxAccess = provider.maxAccess;
  4102. } else {
  4103. // It's a table column. Use that column's maxAccess.
  4104. column = instanceNode.getTableColumnFromInstanceNode();
  4105. // In the typical case, we could use (column - 1) to index
  4106. // into tableColumns to get to the correct entry. There is no
  4107. // guarantee, however, that column numbers in the OID are
  4108. // necessarily consecutive; theoretically some could be
  4109. // missing. We'll therefore play it safe and search for the
  4110. // specified column entry.
  4111. columnEntry = provider.tableColumns.find(entry => entry.number === column);
  4112. maxAccess = columnEntry ? columnEntry.maxAccess || MaxAccess['not-accessible'] : MaxAccess['not-accessible'];
  4113. }
  4114. switch ( PduType[pduType] ) {
  4115. case "SetRequest":
  4116. // SetRequest requires at least read-write access
  4117. return maxAccess >= MaxAccess["read-write"];
  4118. case "GetRequest":
  4119. case "GetNextRequest":
  4120. case "GetBulkRequest":
  4121. // GetRequests require at least read-only access
  4122. return maxAccess >= MaxAccess["read-only"];
  4123. default:
  4124. // Disallow other pdu types
  4125. return false;
  4126. }
  4127. };
  4128. Agent.prototype.request = function (requestMessage, rinfo) {
  4129. var me = this;
  4130. var varbindsCompleted = 0;
  4131. var requestPdu = requestMessage.pdu;
  4132. var varbindsLength = requestPdu.varbinds.length;
  4133. var responsePdu = requestPdu.getResponsePduForRequest ();
  4134. var mibRequests = [];
  4135. var handlers = [];
  4136. var createResult = [];
  4137. var oldValues = [];
  4138. var securityName = requestMessage.version == Version3 ? requestMessage.user.name : requestMessage.community;
  4139. for ( let i = 0; i < requestPdu.varbinds.length; i++ ) {
  4140. let instanceNode = this.mib.lookup (requestPdu.varbinds[i].oid);
  4141. let providerNode;
  4142. let rowStatusColumn;
  4143. let getIcsHandler;
  4144. // If we didn't find an instance node, see if we can
  4145. // automatically create it, either because it has
  4146. // "read-create" MAX-ACCESS, or because it's a RowStatus SET
  4147. // indicating create.
  4148. if ( ! instanceNode ) {
  4149. createResult[i] = this.tryCreateInstance(requestPdu.varbinds[i], requestPdu.type);
  4150. if ( createResult[i] ) {
  4151. instanceNode = createResult[i].instanceNode;
  4152. }
  4153. }
  4154. // workaround re-write of OIDs less than 4 digits due to asn1-ber length limitation
  4155. if ( requestPdu.varbinds[i].oid.split('.').length < 4 ) {
  4156. requestPdu.varbinds[i].oid = "1.3.6.1";
  4157. }
  4158. if ( ! instanceNode ) {
  4159. mibRequests[i] = new MibRequest ({
  4160. operation: requestPdu.type,
  4161. oid: requestPdu.varbinds[i].oid
  4162. });
  4163. handlers[i] = function getNsoHandler (mibRequestForNso) {
  4164. mibRequestForNso.done ({
  4165. errorStatus: ErrorStatus.NoError,
  4166. type: ObjectType.NoSuchObject,
  4167. value: null
  4168. });
  4169. };
  4170. } else {
  4171. providerNode = this.mib.getProviderNodeForInstance (instanceNode);
  4172. if ( ! providerNode || instanceNode.value === undefined ) {
  4173. mibRequests[i] = new MibRequest ({
  4174. operation: requestPdu.type,
  4175. oid: requestPdu.varbinds[i].oid
  4176. });
  4177. handlers[i] = function getNsiHandler (mibRequestForNsi) {
  4178. mibRequestForNsi.done ({
  4179. errorStatus: ErrorStatus.NoError,
  4180. type: ObjectType.NoSuchInstance,
  4181. value: null
  4182. });
  4183. };
  4184. } else if ( ! this.isAllowed(requestPdu.type, providerNode.provider, instanceNode ) ) {
  4185. // requested access not allowed (by MAX-ACCESS)
  4186. mibRequests[i] = new MibRequest ({
  4187. operation: requestPdu.type,
  4188. oid: requestPdu.varbinds[i].oid
  4189. });
  4190. handlers[i] = function getRanaHandler (mibRequestForRana) {
  4191. mibRequestForRana.done ({
  4192. errorStatus: ErrorStatus.NoAccess,
  4193. type: ObjectType.Null,
  4194. value: null
  4195. });
  4196. };
  4197. } else if ( this.authorizer.getAccessControlModelType () == AccessControlModelType.Simple &&
  4198. ! this.authorizer.getAccessControlModel ().isAccessAllowed (requestMessage.version, securityName, requestMessage.pdu.type) ) {
  4199. // Access control check
  4200. mibRequests[i] = new MibRequest ({
  4201. operation: requestPdu.type,
  4202. oid: requestPdu.varbinds[i].oid
  4203. });
  4204. handlers[i] = function getAccessDeniedHandler (mibRequestForAccessDenied) {
  4205. mibRequestForAccessDenied.done ({
  4206. errorStatus: ErrorStatus.NoAccess,
  4207. type: ObjectType.Null,
  4208. value: null
  4209. });
  4210. };
  4211. } else if ( requestPdu.type === PduType.SetRequest &&
  4212. providerNode.provider.type == MibProviderType.Table &&
  4213. typeof (rowStatusColumn = providerNode.provider.tableColumns.reduce(
  4214. (acc, current) => current.rowStatus ? current.number : acc, null )) == "number" &&
  4215. instanceNode.getTableColumnFromInstanceNode() === rowStatusColumn) {
  4216. getIcsHandler = function (mibRequestForIcs) {
  4217. mibRequestForIcs.done ({
  4218. errorStatus: ErrorStatus.InconsistentValue,
  4219. type: ObjectType.Null,
  4220. value: null
  4221. });
  4222. };
  4223. requestPdu.varbinds[i].requestValue = this.castSetValue (requestPdu.varbinds[i].type, requestPdu.varbinds[i].value);
  4224. switch ( requestPdu.varbinds[i].value ) {
  4225. case RowStatus["active"]:
  4226. case RowStatus["notInService"]:
  4227. // Setting either of these states, when the
  4228. // row already exists, is fine
  4229. break;
  4230. case RowStatus["destroy"]:
  4231. // This case is handled later
  4232. break;
  4233. case RowStatus["createAndGo"]:
  4234. // Valid if this was a new row creation, but now set to active
  4235. if ( instanceNode.value === RowStatus["createAndGo"] ) {
  4236. requestPdu.varbinds[i].value = RowStatus["active"];
  4237. } else {
  4238. // Row already existed
  4239. mibRequests[i] = new MibRequest ({
  4240. operation: requestPdu.type,
  4241. oid: requestPdu.varbinds[i].oid
  4242. });
  4243. handlers[i] = getIcsHandler;
  4244. }
  4245. break;
  4246. case RowStatus["createAndWait"]:
  4247. // Valid if this was a new row creation, but now set to notInService
  4248. if ( instanceNode.value === RowStatus["createAndWait"] ) {
  4249. requestPdu.varbinds[i].value = RowStatus["notInService"];
  4250. } else {
  4251. // Row already existed
  4252. mibRequests[i] = new MibRequest ({
  4253. operation: requestPdu.type,
  4254. oid: requestPdu.varbinds[i].oid
  4255. });
  4256. handlers[i] = getIcsHandler;
  4257. }
  4258. break;
  4259. case RowStatus["notReady"]:
  4260. default:
  4261. // It's not ever legal to set the RowStatus to
  4262. // any value but the six that are defined, and
  4263. // it's not legal to change the state to
  4264. // "notReady".
  4265. //
  4266. // The row already exists, as determined by
  4267. // the fact that we have an instanceNode, so
  4268. // we can not apply a create action to the
  4269. // RowStatus column, as dictated RFC-2579.
  4270. // (See the summary state table on Page 8
  4271. // (inconsistent value)
  4272. mibRequests[i] = new MibRequest ({
  4273. operation: requestPdu.type,
  4274. oid: requestPdu.varbinds[i].oid
  4275. });
  4276. handlers[i] = getIcsHandler;
  4277. break;
  4278. }
  4279. }
  4280. if ( requestPdu.type === PduType.SetRequest && ! createResult[i] ) {
  4281. oldValues[i] = instanceNode.value;
  4282. }
  4283. if ( ! handlers[i] ) {
  4284. mibRequests[i] = new MibRequest ({
  4285. operation: requestPdu.type,
  4286. providerNode: providerNode,
  4287. instanceNode: instanceNode,
  4288. oid: requestPdu.varbinds[i].oid
  4289. });
  4290. if ( requestPdu.type == PduType.SetRequest ) {
  4291. mibRequests[i].setType = requestPdu.varbinds[i].type;
  4292. mibRequests[i].setValue = requestPdu.varbinds[i].requestValue || requestPdu.varbinds[i].value;
  4293. }
  4294. handlers[i] = providerNode.provider.handler;
  4295. }
  4296. }
  4297. (function (savedIndex) {
  4298. let responseVarbind;
  4299. mibRequests[savedIndex].done = function (error) {
  4300. let rowIndex = null;
  4301. let row = null;
  4302. let deleted = false;
  4303. let column = -1;
  4304. responseVarbind = {
  4305. oid: mibRequests[savedIndex].oid
  4306. };
  4307. if ( error ) {
  4308. if ( (typeof responsePdu.errorStatus == "undefined" || responsePdu.errorStatus == ErrorStatus.NoError) && error.errorStatus != ErrorStatus.NoError ) {
  4309. responsePdu.errorStatus = error.errorStatus;
  4310. responsePdu.errorIndex = savedIndex + 1;
  4311. }
  4312. responseVarbind.type = error.type || ObjectType.Null;
  4313. responseVarbind.value = error.value || null;
  4314. //responseVarbind.errorStatus: error.errorStatus
  4315. if ( error.errorStatus != ErrorStatus.NoError ) {
  4316. responseVarbind.errorStatus = error.errorStatus;
  4317. }
  4318. } else {
  4319. let provider = providerNode ? providerNode.provider : null;
  4320. let providerName = provider ? provider.name : null;
  4321. let subOid;
  4322. let subAddr;
  4323. if ( providerNode && providerNode.provider && providerNode.provider.type == MibProviderType.Table ) {
  4324. column = instanceNode.getTableColumnFromInstanceNode();
  4325. subOid = Mib.getSubOidFromBaseOid (instanceNode.oid, provider.oid);
  4326. subAddr = subOid.split(".");
  4327. subAddr.shift(); // shift off the column number, leaving the row index values
  4328. rowIndex = Mib.getRowIndexFromOid( subAddr.join("."), provider.tableIndex );
  4329. row = me.mib.getTableRowCells ( providerName, rowIndex );
  4330. }
  4331. if ( requestPdu.type == PduType.SetRequest ) {
  4332. // Is this a RowStatus column with a value of 6 (delete)?
  4333. let rowStatusColumn = provider.type == MibProviderType.Table
  4334. ? provider.tableColumns.reduce( (acc, current) => current.rowStatus ? current.number : acc, null )
  4335. : null;
  4336. if ( requestPdu.varbinds[savedIndex].value === RowStatus["destroy"] &&
  4337. typeof rowStatusColumn == "number" &&
  4338. column === rowStatusColumn ) {
  4339. // Yup. Do the deletion.
  4340. me.mib.deleteTableRow ( providerName, rowIndex );
  4341. deleted = true;
  4342. // This is going to return the prior state of the RowStatus column,
  4343. // i.e., either "active" or "notInService". That feels wrong, but there
  4344. // is no value we can set it to to indicate just-deleted. One would
  4345. // think we could set it to "notReady", but that is explicitly defined
  4346. // in RFC-2579 as "the conceptual row exists in the agent", which is
  4347. // no longer the case now that we've deleted the row. We're not allowed
  4348. // to ever return "destroy" as a status, so that doesn't give us an
  4349. // option either.
  4350. } else {
  4351. // No special handling required. Just save the new value.
  4352. let setResult = mibRequests[savedIndex].instanceNode.setValue (me.castSetValue (
  4353. requestPdu.varbinds[savedIndex].type,
  4354. requestPdu.varbinds[savedIndex].value
  4355. ));
  4356. if ( ! setResult ) {
  4357. if ( typeof responsePdu.errorStatus == "undefined" || responsePdu.errorStatus == ErrorStatus.NoError ) {
  4358. responsePdu.errorStatus = ErrorStatus.WrongValue;
  4359. responsePdu.errorIndex = savedIndex + 1;
  4360. }
  4361. responseVarbind.errorStatus = ErrorStatus.WrongValue;
  4362. }
  4363. }
  4364. }
  4365. if ( ( requestPdu.type == PduType.GetNextRequest || requestPdu.type == PduType.GetBulkRequest ) &&
  4366. requestPdu.varbinds[savedIndex].type == ObjectType.EndOfMibView ) {
  4367. responseVarbind.type = ObjectType.EndOfMibView;
  4368. } else {
  4369. responseVarbind.type = mibRequests[savedIndex].instanceNode.valueType;
  4370. }
  4371. responseVarbind.value = mibRequests[savedIndex].instanceNode.value;
  4372. }
  4373. if ( providerNode && providerNode.provider && providerNode.provider.name ) {
  4374. responseVarbind.providerName = providerNode.provider.name;
  4375. }
  4376. if ( requestPdu.type == PduType.GetNextRequest || requestPdu.type == PduType.GetNextRequest ) {
  4377. responseVarbind.previousOid = requestPdu.varbinds[savedIndex].previousOid;
  4378. }
  4379. if ( requestPdu.type == PduType.SetRequest ) {
  4380. if ( oldValues[savedIndex] !== undefined ) {
  4381. responseVarbind.oldValue = oldValues[savedIndex];
  4382. }
  4383. responseVarbind.requestType = requestPdu.varbinds[savedIndex].type;
  4384. if ( requestPdu.varbinds[savedIndex].requestValue ) {
  4385. responseVarbind.requestValue = me.castSetValue (requestPdu.varbinds[savedIndex].type, requestPdu.varbinds[savedIndex].requestValue);
  4386. } else {
  4387. responseVarbind.requestValue = me.castSetValue (requestPdu.varbinds[savedIndex].type, requestPdu.varbinds[savedIndex].value);
  4388. }
  4389. }
  4390. if ( createResult[savedIndex] ) {
  4391. responseVarbind.autoCreated = true;
  4392. } else if ( deleted ) {
  4393. responseVarbind.deleted = true;
  4394. }
  4395. if ( providerNode && providerNode.provider.type == MibProviderType.Table ) {
  4396. responseVarbind.column = column;
  4397. responseVarbind.columnPosition = providerNode.provider.tableColumns.findIndex(tc => tc.number == column);
  4398. responseVarbind.rowIndex = rowIndex;
  4399. if ( ! deleted && rowIndex ) {
  4400. row = me.mib.getTableRowCells ( providerNode.provider.name, rowIndex );
  4401. }
  4402. responseVarbind.row = row;
  4403. }
  4404. me.setSingleVarbind (responsePdu, savedIndex, responseVarbind);
  4405. if ( ++varbindsCompleted == varbindsLength) {
  4406. me.sendResponse.call (me, rinfo, requestMessage, responsePdu);
  4407. }
  4408. };
  4409. })(i);
  4410. if ( handlers[i] ) {
  4411. handlers[i] (mibRequests[i]);
  4412. } else {
  4413. mibRequests[i].done ();
  4414. }
  4415. }
  4416. };
  4417. Agent.prototype.getRequest = function (requestMessage, rinfo) {
  4418. this.request (requestMessage, rinfo);
  4419. };
  4420. Agent.prototype.setRequest = function (requestMessage, rinfo) {
  4421. this.request (requestMessage, rinfo);
  4422. };
  4423. Agent.prototype.addGetNextVarbind = function (targetVarbinds, startOid) {
  4424. var startNode;
  4425. var getNextNode;
  4426. try {
  4427. startNode = this.mib.lookup (startOid);
  4428. } catch ( error ) {
  4429. startOid = '1.3.6.1';
  4430. startNode = this.mib.lookup (startOid);
  4431. }
  4432. if ( ! startNode ) {
  4433. // Off-tree start specified
  4434. startNode = this.mib.getTreeNode (startOid);
  4435. }
  4436. getNextNode = startNode.getNextInstanceNode();
  4437. if ( ! getNextNode ) {
  4438. // End of MIB
  4439. targetVarbinds.push ({
  4440. previousOid: startOid,
  4441. oid: startOid,
  4442. type: ObjectType.EndOfMibView,
  4443. value: null
  4444. });
  4445. } else {
  4446. // Normal response
  4447. targetVarbinds.push ({
  4448. previousOid: startOid,
  4449. oid: getNextNode.oid,
  4450. type: getNextNode.valueType,
  4451. value: getNextNode.value
  4452. });
  4453. }
  4454. return getNextNode;
  4455. };
  4456. Agent.prototype.getNextRequest = function (requestMessage, rinfo) {
  4457. var requestPdu = requestMessage.pdu;
  4458. var varbindsLength = requestPdu.varbinds.length;
  4459. var getNextVarbinds = [];
  4460. for (var i = 0 ; i < varbindsLength ; i++ ) {
  4461. this.addGetNextVarbind (getNextVarbinds, requestPdu.varbinds[i].oid);
  4462. }
  4463. requestMessage.pdu.varbinds = getNextVarbinds;
  4464. this.request (requestMessage, rinfo);
  4465. };
  4466. Agent.prototype.getBulkRequest = function (requestMessage, rinfo) {
  4467. var requestPdu = requestMessage.pdu;
  4468. var requestVarbinds = requestPdu.varbinds;
  4469. var getBulkVarbinds = [];
  4470. var startOid = [];
  4471. var getNextNode;
  4472. var endOfMib = false;
  4473. for (var n = 0 ; n < Math.min (requestPdu.nonRepeaters, requestVarbinds.length) ; n++ ) {
  4474. this.addGetNextVarbind (getBulkVarbinds, requestVarbinds[n].oid);
  4475. }
  4476. if ( requestPdu.nonRepeaters < requestVarbinds.length ) {
  4477. for (var v = requestPdu.nonRepeaters ; v < requestVarbinds.length ; v++ ) {
  4478. startOid.push (requestVarbinds[v].oid);
  4479. }
  4480. while ( getBulkVarbinds.length < requestPdu.maxRepetitions && ! endOfMib ) {
  4481. for (var w = requestPdu.nonRepeaters ; w < requestVarbinds.length ; w++ ) {
  4482. if (getBulkVarbinds.length < requestPdu.maxRepetitions ) {
  4483. getNextNode = this.addGetNextVarbind (getBulkVarbinds, startOid[w - requestPdu.nonRepeaters]);
  4484. if ( getNextNode ) {
  4485. startOid[w - requestPdu.nonRepeaters] = getNextNode.oid;
  4486. if ( getNextNode.type == ObjectType.EndOfMibView ) {
  4487. endOfMib = true;
  4488. }
  4489. }
  4490. }
  4491. }
  4492. }
  4493. }
  4494. requestMessage.pdu.varbinds = getBulkVarbinds;
  4495. this.request (requestMessage, rinfo);
  4496. };
  4497. Agent.prototype.setSingleVarbind = function (responsePdu, index, responseVarbind) {
  4498. responsePdu.varbinds[index] = responseVarbind;
  4499. };
  4500. Agent.prototype.sendResponse = function (rinfo, requestMessage, responsePdu) {
  4501. var responseMessage = requestMessage.createResponseForRequest (responsePdu);
  4502. this.listener.send (responseMessage, rinfo);
  4503. this.callback (null, Listener.formatCallbackData (responseMessage.pdu, rinfo) );
  4504. };
  4505. Agent.prototype.onProxyRequest = function (message, rinfo) {
  4506. var contextName = message.pdu.contextName;
  4507. var proxy;
  4508. var proxiedPduId;
  4509. var proxiedUser;
  4510. if ( message.version != Version3 ) {
  4511. this.callback (new RequestFailedError ("Only SNMP version 3 contexts are supported"));
  4512. return;
  4513. }
  4514. proxy = this.forwarder.getProxy (contextName);
  4515. if ( ! proxy ) {
  4516. this.callback (new RequestFailedError ("No proxy found for message received with context " + contextName));
  4517. return;
  4518. }
  4519. if ( ! proxy.session.msgSecurityParameters ) {
  4520. // Discovery required - but chaining not implemented from here yet
  4521. proxy.session.sendV3Discovery (null, null, this.callback, {});
  4522. } else {
  4523. message.msgSecurityParameters = proxy.session.msgSecurityParameters;
  4524. message.setAuthentication ( ! (proxy.user.level == SecurityLevel.noAuthNoPriv));
  4525. message.setPrivacy (proxy.user.level == SecurityLevel.authPriv);
  4526. proxiedUser = message.user;
  4527. message.user = proxy.user;
  4528. message.buffer = null;
  4529. message.pdu.contextEngineID = proxy.session.msgSecurityParameters.msgAuthoritativeEngineID;
  4530. message.pdu.contextName = "";
  4531. proxiedPduId = message.pdu.id;
  4532. message.pdu.id = _generateId ();
  4533. var req = new Req (proxy.session, message, null, this.callback, {}, true);
  4534. req.port = proxy.port;
  4535. req.proxiedRinfo = rinfo;
  4536. req.proxiedPduId = proxiedPduId;
  4537. req.proxiedUser = proxiedUser;
  4538. req.proxiedEngine = this.engine;
  4539. proxy.session.send (req);
  4540. }
  4541. };
  4542. Agent.prototype.getForwarder = function () {
  4543. return this.forwarder;
  4544. };
  4545. Agent.prototype.close = function() {
  4546. this.listener.close ();
  4547. };
  4548. Agent.create = function (options, callback, mib) {
  4549. var agent = new Agent (options, callback, mib);
  4550. agent.listener.startListening ();
  4551. return agent;
  4552. };
  4553. var Forwarder = function (listener, callback) {
  4554. this.proxies = {};
  4555. this.listener = listener;
  4556. this.callback = callback;
  4557. };
  4558. Forwarder.prototype.addProxy = function (proxy) {
  4559. var options = {
  4560. version: Version3,
  4561. port: proxy.port,
  4562. transport: proxy.transport
  4563. };
  4564. proxy.session = Session.createV3 (proxy.target, proxy.user, options);
  4565. proxy.session.proxy = proxy;
  4566. proxy.session.proxy.listener = this.listener;
  4567. this.proxies[proxy.context] = proxy;
  4568. proxy.session.sendV3Discovery (null, null, this.callback);
  4569. };
  4570. Forwarder.prototype.deleteProxy = function (proxyName) {
  4571. var proxy = this.proxies[proxyName];
  4572. if ( proxy && proxy.session ) {
  4573. proxy.session.close ();
  4574. }
  4575. delete this.proxies[proxyName];
  4576. };
  4577. Forwarder.prototype.getProxy = function (proxyName) {
  4578. return this.proxies[proxyName];
  4579. };
  4580. Forwarder.prototype.getProxies = function () {
  4581. return this.proxies;
  4582. };
  4583. Forwarder.prototype.dumpProxies = function () {
  4584. var dump = {};
  4585. for ( var proxy of Object.values (this.proxies) ) {
  4586. dump[proxy.context] = {
  4587. context: proxy.context,
  4588. target: proxy.target,
  4589. user: proxy.user,
  4590. port: proxy.port
  4591. };
  4592. }
  4593. console.log (JSON.stringify (dump, null, 2));
  4594. };
  4595. var AgentXPdu = function () {
  4596. };
  4597. AgentXPdu.prototype.toBuffer = function () {
  4598. var buffer = new smartbuffer.SmartBuffer();
  4599. this.writeHeader (buffer);
  4600. switch ( this.pduType ) {
  4601. case AgentXPduType.Open:
  4602. buffer.writeUInt32BE (this.timeout);
  4603. AgentXPdu.writeOid (buffer, this.oid);
  4604. AgentXPdu.writeOctetString (buffer, this.descr);
  4605. break;
  4606. case AgentXPduType.Close:
  4607. buffer.writeUInt8 (5); // reasonShutdown == 5
  4608. buffer.writeUInt8 (0); // 3 x reserved bytes
  4609. buffer.writeUInt8 (0);
  4610. buffer.writeUInt8 (0);
  4611. break;
  4612. case AgentXPduType.Register:
  4613. buffer.writeUInt8 (this.timeout);
  4614. buffer.writeUInt8 (this.priority);
  4615. buffer.writeUInt8 (this.rangeSubid);
  4616. buffer.writeUInt8 (0);
  4617. AgentXPdu.writeOid (buffer, this.oid);
  4618. break;
  4619. case AgentXPduType.Unregister:
  4620. buffer.writeUInt8 (0); // reserved
  4621. buffer.writeUInt8 (this.priority);
  4622. buffer.writeUInt8 (this.rangeSubid);
  4623. buffer.writeUInt8 (0); // reserved
  4624. AgentXPdu.writeOid (buffer, this.oid);
  4625. break;
  4626. case AgentXPduType.AddAgentCaps:
  4627. AgentXPdu.writeOid (buffer, this.oid);
  4628. AgentXPdu.writeOctetString (buffer, this.descr);
  4629. break;
  4630. case AgentXPduType.RemoveAgentCaps:
  4631. AgentXPdu.writeOid (buffer, this.oid);
  4632. break;
  4633. case AgentXPduType.Notify:
  4634. AgentXPdu.writeVarbinds (buffer, this.varbinds);
  4635. break;
  4636. case AgentXPduType.Ping:
  4637. break;
  4638. case AgentXPduType.Response:
  4639. buffer.writeUInt32BE (this.sysUpTime);
  4640. buffer.writeUInt16BE (this.error);
  4641. buffer.writeUInt16BE (this.index);
  4642. AgentXPdu.writeVarbinds (buffer, this.varbinds);
  4643. break;
  4644. default:
  4645. // unknown PDU type - should never happen as we control these
  4646. }
  4647. buffer.writeUInt32BE (buffer.length - 20, 16);
  4648. return buffer.toBuffer ();
  4649. };
  4650. AgentXPdu.prototype.writeHeader = function (buffer) {
  4651. this.flags = this.flags | 0x10; // set NETWORK_BYTE_ORDER
  4652. buffer.writeUInt8 (1); // h.version = 1
  4653. buffer.writeUInt8 (this.pduType);
  4654. buffer.writeUInt8 (this.flags);
  4655. buffer.writeUInt8 (0); // reserved byte
  4656. buffer.writeUInt32BE (this.sessionID);
  4657. buffer.writeUInt32BE (this.transactionID);
  4658. buffer.writeUInt32BE (this.packetID);
  4659. buffer.writeUInt32BE (0);
  4660. return buffer;
  4661. };
  4662. AgentXPdu.prototype.readHeader = function (buffer) {
  4663. this.version = buffer.readUInt8 ();
  4664. this.pduType = buffer.readUInt8 ();
  4665. this.flags = buffer.readUInt8 ();
  4666. buffer.readUInt8 (); // reserved byte
  4667. this.sessionID = buffer.readUInt32BE ();
  4668. this.transactionID = buffer.readUInt32BE ();
  4669. this.packetID = buffer.readUInt32BE ();
  4670. this.payloadLength = buffer.readUInt32BE ();
  4671. };
  4672. AgentXPdu.createFromVariables = function (vars) {
  4673. var pdu = new AgentXPdu ();
  4674. pdu.flags = vars.flags ? vars.flags | 0x10 : 0x10; // set NETWORK_BYTE_ORDER to big endian
  4675. pdu.pduType = vars.pduType || AgentXPduType.Open;
  4676. pdu.sessionID = vars.sessionID || 0;
  4677. pdu.transactionID = vars.transactionID || 0;
  4678. pdu.packetID = vars.packetID || ++AgentXPdu.packetID;
  4679. switch ( pdu.pduType ) {
  4680. case AgentXPduType.Open:
  4681. pdu.timeout = vars.timeout || 0;
  4682. pdu.oid = vars.oid || null;
  4683. pdu.descr = vars.descr || null;
  4684. break;
  4685. case AgentXPduType.Close:
  4686. break;
  4687. case AgentXPduType.Register:
  4688. pdu.timeout = vars.timeout || 0;
  4689. pdu.oid = vars.oid || null;
  4690. pdu.priority = vars.priority || 127;
  4691. pdu.rangeSubid = vars.rangeSubid || 0;
  4692. break;
  4693. case AgentXPduType.Unregister:
  4694. pdu.oid = vars.oid || null;
  4695. pdu.priority = vars.priority || 127;
  4696. pdu.rangeSubid = vars.rangeSubid || 0;
  4697. break;
  4698. case AgentXPduType.AddAgentCaps:
  4699. pdu.oid = vars.oid;
  4700. pdu.descr = vars.descr;
  4701. break;
  4702. case AgentXPduType.RemoveAgentCaps:
  4703. pdu.oid = vars.oid;
  4704. break;
  4705. case AgentXPduType.Notify:
  4706. pdu.varbinds = vars.varbinds;
  4707. break;
  4708. case AgentXPduType.Ping:
  4709. break;
  4710. case AgentXPduType.Response:
  4711. pdu.sysUpTime = vars.sysUpTime || 0;
  4712. pdu.error = vars.error || 0;
  4713. pdu.index = vars.index || 0;
  4714. pdu.varbinds = vars.varbinds || null;
  4715. break;
  4716. default:
  4717. // unsupported PDU type - should never happen as we control these
  4718. throw new RequestInvalidError ("Unknown PDU type '" + pdu.pduType
  4719. + "' in created PDU");
  4720. }
  4721. return pdu;
  4722. };
  4723. AgentXPdu.createFromBuffer = function (socketBuffer) {
  4724. var pdu = new AgentXPdu ();
  4725. var buffer = smartbuffer.SmartBuffer.fromBuffer (socketBuffer);
  4726. pdu.readHeader (buffer);
  4727. switch ( pdu.pduType ) {
  4728. case AgentXPduType.Response:
  4729. pdu.sysUpTime = buffer.readUInt32BE ();
  4730. pdu.error = buffer.readUInt16BE ();
  4731. pdu.index = buffer.readUInt16BE ();
  4732. break;
  4733. case AgentXPduType.Get:
  4734. case AgentXPduType.GetNext:
  4735. pdu.searchRangeList = AgentXPdu.readSearchRangeList (buffer, pdu.payloadLength);
  4736. break;
  4737. case AgentXPduType.GetBulk:
  4738. pdu.nonRepeaters = buffer.readUInt16BE ();
  4739. pdu.maxRepetitions = buffer.readUInt16BE ();
  4740. pdu.searchRangeList = AgentXPdu.readSearchRangeList (buffer, pdu.payloadLength - 4);
  4741. break;
  4742. case AgentXPduType.TestSet:
  4743. pdu.varbinds = AgentXPdu.readVarbinds (buffer, pdu.payloadLength);
  4744. break;
  4745. case AgentXPduType.CommitSet:
  4746. case AgentXPduType.UndoSet:
  4747. case AgentXPduType.CleanupSet:
  4748. break;
  4749. default:
  4750. // Unknown PDU type - shouldn't happen as master agents shouldn't send administrative PDUs
  4751. throw new RequestInvalidError ("Unknown PDU type '" + pdu.pduType
  4752. + "' in request");
  4753. }
  4754. return pdu;
  4755. };
  4756. AgentXPdu.writeOid = function (buffer, oid, include = 0) {
  4757. var prefix;
  4758. if ( oid ) {
  4759. var address = oid.split ('.').map ( Number );
  4760. if ( address.length >= 5 && address.slice (0, 4).join('.') == '1.3.6.1' ) {
  4761. prefix = address[4];
  4762. address = address.slice(5);
  4763. } else {
  4764. prefix = 0;
  4765. }
  4766. buffer.writeUInt8 (address.length);
  4767. buffer.writeUInt8 (prefix);
  4768. buffer.writeUInt8 (include);
  4769. buffer.writeUInt8 (0); // reserved
  4770. for ( let addressPart of address ) {
  4771. buffer.writeUInt32BE (addressPart);
  4772. }
  4773. } else {
  4774. buffer.writeUInt32BE (0); // row of zeros for null OID
  4775. }
  4776. };
  4777. AgentXPdu.writeOctetString = function (buffer, octetString) {
  4778. buffer.writeUInt32BE (octetString.length);
  4779. buffer.writeString (octetString);
  4780. var paddingOctets = ( 4 - octetString.length % 4 ) % 4;
  4781. for ( let i = 0; i < paddingOctets ; i++ ) {
  4782. buffer.writeUInt8 (0);
  4783. }
  4784. };
  4785. AgentXPdu.writeVarBind = function (buffer, varbind) {
  4786. buffer.writeUInt16BE (varbind.type);
  4787. buffer.writeUInt16BE (0); // reserved
  4788. AgentXPdu.writeOid (buffer, varbind.oid);
  4789. if (varbind.type && varbind.oid) {
  4790. switch (varbind.type) {
  4791. case ObjectType.Integer: // also Integer32
  4792. case ObjectType.Counter: // also Counter32
  4793. case ObjectType.Gauge: // also Gauge32 & Unsigned32
  4794. case ObjectType.TimeTicks:
  4795. buffer.writeUInt32BE (varbind.value);
  4796. break;
  4797. case ObjectType.OctetString:
  4798. case ObjectType.Opaque:
  4799. AgentXPdu.writeOctetString (buffer, varbind.value);
  4800. break;
  4801. case ObjectType.OID:
  4802. AgentXPdu.writeOid (buffer, varbind.value);
  4803. break;
  4804. case ObjectType.IpAddress:
  4805. var bytes = varbind.value.split (".");
  4806. if (bytes.length != 4)
  4807. throw new RequestInvalidError ("Invalid IP address '"
  4808. + varbind.value + "'");
  4809. buffer.writeOctetString (buffer, Buffer.from (bytes));
  4810. break;
  4811. case ObjectType.Counter64:
  4812. buffer.writeUint64 (varbind.value);
  4813. break;
  4814. case ObjectType.Null:
  4815. case ObjectType.EndOfMibView:
  4816. case ObjectType.NoSuchObject:
  4817. case ObjectType.NoSuchInstance:
  4818. break;
  4819. default:
  4820. // Unknown data type - should never happen as the above covers all types in RFC 2741 Section 5.4
  4821. throw new RequestInvalidError ("Unknown type '" + varbind.type
  4822. + "' in request");
  4823. }
  4824. }
  4825. };
  4826. AgentXPdu.writeVarbinds = function (buffer, varbinds) {
  4827. if ( varbinds ) {
  4828. for ( var i = 0; i < varbinds.length ; i++ ) {
  4829. var varbind = varbinds[i];
  4830. AgentXPdu.writeVarBind(buffer, varbind);
  4831. }
  4832. }
  4833. };
  4834. AgentXPdu.readOid = function (buffer) {
  4835. var subidLength = buffer.readUInt8 ();
  4836. var prefix = buffer.readUInt8 ();
  4837. var include = buffer.readUInt8 ();
  4838. buffer.readUInt8 (); // reserved
  4839. // Null OID check
  4840. if ( subidLength == 0 && prefix == 0 && include == 0) {
  4841. return null;
  4842. }
  4843. var address = [];
  4844. if ( prefix == 0 ) {
  4845. address = [];
  4846. } else {
  4847. address = [1, 3, 6, 1, prefix];
  4848. }
  4849. for ( let i = 0; i < subidLength; i++ ) {
  4850. address.push (buffer.readUInt32BE ());
  4851. }
  4852. var oid = address.join ('.');
  4853. return oid;
  4854. };
  4855. AgentXPdu.readSearchRange = function (buffer) {
  4856. return {
  4857. start: AgentXPdu.readOid (buffer),
  4858. end: AgentXPdu.readOid (buffer)
  4859. };
  4860. };
  4861. AgentXPdu.readSearchRangeList = function (buffer, payloadLength) {
  4862. var bytesLeft = payloadLength;
  4863. var bufferPosition = (buffer.readOffset + 1);
  4864. var searchRangeList = [];
  4865. while (bytesLeft > 0) {
  4866. searchRangeList.push (AgentXPdu.readSearchRange (buffer));
  4867. bytesLeft -= (buffer.readOffset + 1) - bufferPosition;
  4868. bufferPosition = buffer.readOffset + 1;
  4869. }
  4870. return searchRangeList;
  4871. };
  4872. AgentXPdu.readOctetString = function (buffer) {
  4873. var octetStringLength = buffer.readUInt32BE ();
  4874. var paddingOctets = ( 4 - octetStringLength % 4 ) % 4;
  4875. var octetString = buffer.readString (octetStringLength);
  4876. buffer.readString (paddingOctets);
  4877. return octetString;
  4878. };
  4879. AgentXPdu.readVarbind = function (buffer) {
  4880. var vtype = buffer.readUInt16BE ();
  4881. buffer.readUInt16BE (); // reserved
  4882. var oid = AgentXPdu.readOid (buffer);
  4883. var value;
  4884. switch (vtype) {
  4885. case ObjectType.Integer:
  4886. case ObjectType.Counter:
  4887. case ObjectType.Gauge:
  4888. case ObjectType.TimeTicks:
  4889. value = buffer.readUInt32BE ();
  4890. break;
  4891. case ObjectType.OctetString:
  4892. case ObjectType.IpAddress:
  4893. case ObjectType.Opaque:
  4894. value = AgentXPdu.readOctetString (buffer);
  4895. break;
  4896. case ObjectType.OID:
  4897. value = AgentXPdu.readOid (buffer);
  4898. break;
  4899. case ObjectType.Counter64:
  4900. value = readUint64 (buffer);
  4901. break;
  4902. case ObjectType.Null:
  4903. case ObjectType.NoSuchObject:
  4904. case ObjectType.NoSuchInstance:
  4905. case ObjectType.EndOfMibView:
  4906. value = null;
  4907. break;
  4908. default:
  4909. // Unknown data type - should never happen as the above covers all types in RFC 2741 Section 5.4
  4910. throw new RequestInvalidError ("Unknown type '" + vtype
  4911. + "' in varbind");
  4912. }
  4913. return {
  4914. type: vtype,
  4915. oid: oid,
  4916. value: value
  4917. };
  4918. };
  4919. AgentXPdu.readVarbinds = function (buffer, payloadLength) {
  4920. var bytesLeft = payloadLength;
  4921. var bufferPosition = (buffer.readOffset + 1);
  4922. var varbindList = [];
  4923. while (bytesLeft > 0) {
  4924. varbindList.push (AgentXPdu.readVarbind (buffer));
  4925. bytesLeft -= (buffer.readOffset + 1) - bufferPosition;
  4926. bufferPosition = buffer.readOffset + 1;
  4927. }
  4928. return varbindList;
  4929. };
  4930. AgentXPdu.packetID = 1;
  4931. var Subagent = function (options) {
  4932. DEBUG = options.debug;
  4933. this.mib = new Mib ();
  4934. this.master = options.master || 'localhost';
  4935. this.masterPort = options.masterPort || 705;
  4936. this.timeout = options.timeout || 0;
  4937. this.descr = options.description || "Node net-snmp AgentX sub-agent";
  4938. this.sessionID = 0;
  4939. this.transactionID = 0;
  4940. this.packetID = _generateId();
  4941. this.requestPdus = {};
  4942. this.setTransactions = {};
  4943. };
  4944. Subagent.prototype.getMib = function () {
  4945. return this.mib;
  4946. };
  4947. Subagent.prototype.connectSocket = function () {
  4948. var me = this;
  4949. this.socket = new net.Socket ();
  4950. this.socket.connect (this.masterPort, this.master, function () {
  4951. debug ("Connected to '" + me.master + "' on port " + me.masterPort);
  4952. });
  4953. this.socket.on ("data", me.onMsg.bind (me));
  4954. this.socket.on ("error", function (error) {
  4955. console.error (error);
  4956. });
  4957. };
  4958. Subagent.prototype.open = function (callback) {
  4959. var pdu = AgentXPdu.createFromVariables ({
  4960. pduType: AgentXPduType.Open,
  4961. timeout: this.timeout,
  4962. oid: this.oid,
  4963. descr: this.descr
  4964. });
  4965. this.sendPdu (pdu, callback);
  4966. };
  4967. Subagent.prototype.close = function (callback) {
  4968. var pdu = AgentXPdu.createFromVariables ({
  4969. pduType: AgentXPduType.Close,
  4970. sessionID: this.sessionID
  4971. });
  4972. this.sendPdu (pdu, callback);
  4973. };
  4974. Subagent.prototype.registerProvider = function (provider, callback) {
  4975. var pdu = AgentXPdu.createFromVariables ({
  4976. pduType: AgentXPduType.Register,
  4977. sessionID: this.sessionID,
  4978. rangeSubid: 0,
  4979. timeout: 5,
  4980. priority: 127,
  4981. oid: provider.oid
  4982. });
  4983. this.mib.registerProvider (provider);
  4984. this.sendPdu (pdu, callback);
  4985. };
  4986. Subagent.prototype.unregisterProvider = function (name, callback) {
  4987. var provider = this.getProvider (name);
  4988. var pdu = AgentXPdu.createFromVariables ({
  4989. pduType: AgentXPduType.Unregister,
  4990. sessionID: this.sessionID,
  4991. rangeSubid: 0,
  4992. priority: 127,
  4993. oid: provider.oid
  4994. });
  4995. this.mib.unregisterProvider (name);
  4996. this.sendPdu (pdu, callback);
  4997. };
  4998. Subagent.prototype.registerProviders = function (providers, callback) {
  4999. for (var provider of providers) {
  5000. this.registerProvider (provider, callback);
  5001. }
  5002. };
  5003. Subagent.prototype.getProvider = function (name) {
  5004. return this.mib.getProvider (name);
  5005. };
  5006. Subagent.prototype.getProviders = function () {
  5007. return this.mib.getProviders ();
  5008. };
  5009. Subagent.prototype.addAgentCaps = function (oid, descr, callback) {
  5010. var pdu = AgentXPdu.createFromVariables ({
  5011. pduType: AgentXPduType.AddAgentCaps,
  5012. sessionID: this.sessionID,
  5013. oid: oid,
  5014. descr: descr
  5015. });
  5016. this.sendPdu (pdu, callback);
  5017. };
  5018. Subagent.prototype.removeAgentCaps = function (oid, callback) {
  5019. var pdu = AgentXPdu.createFromVariables ({
  5020. pduType: AgentXPduType.RemoveAgentCaps,
  5021. sessionID: this.sessionID,
  5022. oid: oid
  5023. });
  5024. this.sendPdu (pdu, callback);
  5025. };
  5026. Subagent.prototype.notify = function (typeOrOid, varbinds, callback) {
  5027. varbinds = varbinds || [];
  5028. if (typeof typeOrOid != "string") {
  5029. typeOrOid = "1.3.6.1.6.3.1.1.5." + (typeOrOid + 1);
  5030. }
  5031. var pduVarbinds = [
  5032. {
  5033. oid: "1.3.6.1.2.1.1.3.0",
  5034. type: ObjectType.TimeTicks,
  5035. value: Math.floor (process.uptime () * 100)
  5036. },
  5037. {
  5038. oid: "1.3.6.1.6.3.1.1.4.1.0",
  5039. type: ObjectType.OID,
  5040. value: typeOrOid
  5041. }
  5042. ];
  5043. pduVarbinds = pduVarbinds.concat (varbinds);
  5044. var pdu = AgentXPdu.createFromVariables ({
  5045. pduType: AgentXPduType.Notify,
  5046. sessionID: this.sessionID,
  5047. varbinds: pduVarbinds
  5048. });
  5049. this.sendPdu (pdu, callback);
  5050. };
  5051. Subagent.prototype.ping = function (callback) {
  5052. var pdu = AgentXPdu.createFromVariables ({
  5053. pduType: AgentXPduType.Ping,
  5054. sessionID: this.sessionID
  5055. });
  5056. this.sendPdu (pdu, callback);
  5057. };
  5058. Subagent.prototype.sendPdu = function (pdu, callback) {
  5059. debug ("Sending AgentX " + AgentXPduType[pdu.pduType] + " PDU");
  5060. debug (pdu);
  5061. var buffer = pdu.toBuffer ();
  5062. this.socket.write (buffer);
  5063. if ( pdu.pduType != AgentXPduType.Response && ! this.requestPdus[pdu.packetID] ) {
  5064. pdu.callback = callback;
  5065. this.requestPdus[pdu.packetID] = pdu;
  5066. }
  5067. // Possible timeout / retry mechanism?
  5068. // var me = this;
  5069. // pdu.timer = setTimeout (function () {
  5070. // if (pdu.retries-- > 0) {
  5071. // this.sendPdu (pdu);
  5072. // } else {
  5073. // delete me.requestPdus[pdu.packetID];
  5074. // me.callback (new RequestTimedOutError (
  5075. // "Request timed out"));
  5076. // }
  5077. // }, this.timeout);
  5078. };
  5079. Subagent.prototype.onMsg = function (buffer, rinfo) {
  5080. var pdu = AgentXPdu.createFromBuffer (buffer);
  5081. debug ("Received AgentX " + AgentXPduType[pdu.pduType] + " PDU");
  5082. debug (pdu);
  5083. switch (pdu.pduType) {
  5084. case AgentXPduType.Response:
  5085. this.response (pdu);
  5086. break;
  5087. case AgentXPduType.Get:
  5088. this.getRequest (pdu);
  5089. break;
  5090. case AgentXPduType.GetNext:
  5091. this.getNextRequest (pdu);
  5092. break;
  5093. case AgentXPduType.GetBulk:
  5094. this.getBulkRequest (pdu);
  5095. break;
  5096. case AgentXPduType.TestSet:
  5097. this.testSet (pdu);
  5098. break;
  5099. case AgentXPduType.CommitSet:
  5100. this.commitSet (pdu);
  5101. break;
  5102. case AgentXPduType.UndoSet:
  5103. this.undoSet (pdu);
  5104. break;
  5105. case AgentXPduType.CleanupSet:
  5106. this.cleanupSet (pdu);
  5107. break;
  5108. default:
  5109. // Unknown PDU type - shouldn't happen as master agents shouldn't send administrative PDUs
  5110. throw new RequestInvalidError ("Unknown PDU type '" + pdu.pduType
  5111. + "' in request");
  5112. }
  5113. };
  5114. Subagent.prototype.response = function (pdu) {
  5115. var requestPdu = this.requestPdus[pdu.packetID];
  5116. if (requestPdu) {
  5117. delete this.requestPdus[pdu.packetID];
  5118. // clearTimeout (pdu.timer);
  5119. // delete pdu.timer;
  5120. switch (requestPdu.pduType) {
  5121. case AgentXPduType.Open:
  5122. this.sessionID = pdu.sessionID;
  5123. break;
  5124. case AgentXPduType.Close:
  5125. this.socket.end();
  5126. break;
  5127. case AgentXPduType.Register:
  5128. case AgentXPduType.Unregister:
  5129. case AgentXPduType.AddAgentCaps:
  5130. case AgentXPduType.RemoveAgentCaps:
  5131. case AgentXPduType.Notify:
  5132. case AgentXPduType.Ping:
  5133. break;
  5134. default:
  5135. // Response PDU for request type not handled
  5136. throw new ResponseInvalidError ("Response PDU for type '" + requestPdu.pduType + "' not handled",
  5137. ResponseInvalidCode.EResponseNotHandled);
  5138. }
  5139. if (requestPdu.callback) {
  5140. requestPdu.callback(null, pdu);
  5141. }
  5142. } else {
  5143. // unexpected Response PDU - has no matching request
  5144. throw new ResponseInvalidError ("Unexpected Response PDU with packetID " + pdu.packetID,
  5145. ResponseInvalidCode.EUnexpectedResponse);
  5146. }
  5147. };
  5148. Subagent.prototype.request = function (pdu, requestVarbinds) {
  5149. var me = this;
  5150. var varbindsCompleted = 0;
  5151. var varbindsLength = requestVarbinds.length;
  5152. var responseVarbinds = [];
  5153. for ( var i = 0; i < requestVarbinds.length; i++ ) {
  5154. var requestVarbind = requestVarbinds[i];
  5155. var instanceNode = this.mib.lookup (requestVarbind.oid);
  5156. var providerNode;
  5157. var mibRequest;
  5158. var handler;
  5159. var responseVarbindType;
  5160. if ( ! instanceNode ) {
  5161. mibRequest = new MibRequest ({
  5162. operation: pdu.pduType,
  5163. oid: requestVarbind.oid
  5164. });
  5165. handler = function getNsoHandler (mibRequestForNso) {
  5166. mibRequestForNso.done ({
  5167. errorStatus: ErrorStatus.NoError,
  5168. errorIndex: 0,
  5169. type: ObjectType.NoSuchObject,
  5170. value: null
  5171. });
  5172. };
  5173. } else {
  5174. providerNode = this.mib.getProviderNodeForInstance (instanceNode);
  5175. if ( ! providerNode ) {
  5176. mibRequest = new MibRequest ({
  5177. operation: pdu.pduType,
  5178. oid: requestVarbind.oid
  5179. });
  5180. handler = function getNsiHandler (mibRequestForNsi) {
  5181. mibRequestForNsi.done ({
  5182. errorStatus: ErrorStatus.NoError,
  5183. errorIndex: 0,
  5184. type: ObjectType.NoSuchInstance,
  5185. value: null
  5186. });
  5187. };
  5188. } else {
  5189. mibRequest = new MibRequest ({
  5190. operation: pdu.pduType,
  5191. providerNode: providerNode,
  5192. instanceNode: instanceNode,
  5193. oid: requestVarbind.oid
  5194. });
  5195. if ( pdu.pduType == AgentXPduType.TestSet ) {
  5196. mibRequest.setType = requestVarbind.type;
  5197. mibRequest.setValue = requestVarbind.value;
  5198. }
  5199. handler = providerNode.provider.handler;
  5200. }
  5201. }
  5202. (function (savedIndex) {
  5203. var responseVarbind;
  5204. mibRequest.done = function (error) {
  5205. if ( error ) {
  5206. responseVarbind = {
  5207. oid: mibRequest.oid,
  5208. type: error.type || ObjectType.Null,
  5209. value: error.value || null
  5210. };
  5211. } else {
  5212. if ( pdu.pduType == AgentXPduType.TestSet ) {
  5213. // more tests?
  5214. } else if ( pdu.pduType == AgentXPduType.CommitSet ) {
  5215. me.setTransactions[pdu.transactionID].originalValue = mibRequest.instanceNode.value;
  5216. mibRequest.instanceNode.value = requestVarbind.value;
  5217. } else if ( pdu.pduType == AgentXPduType.UndoSet ) {
  5218. mibRequest.instanceNode.value = me.setTransactions[pdu.transactionID].originalValue;
  5219. }
  5220. if ( ( pdu.pduType == AgentXPduType.GetNext || pdu.pduType == AgentXPduType.GetBulk ) &&
  5221. requestVarbind.type == ObjectType.EndOfMibView ) {
  5222. responseVarbindType = ObjectType.EndOfMibView;
  5223. } else {
  5224. responseVarbindType = mibRequest.instanceNode.valueType;
  5225. }
  5226. responseVarbind = {
  5227. oid: mibRequest.oid,
  5228. type: responseVarbindType,
  5229. value: mibRequest.instanceNode.value
  5230. };
  5231. }
  5232. responseVarbinds[savedIndex] = responseVarbind;
  5233. if ( ++varbindsCompleted == varbindsLength) {
  5234. if ( pdu.pduType == AgentXPduType.TestSet || pdu.pduType == AgentXPduType.CommitSet
  5235. || pdu.pduType == AgentXPduType.UndoSet) {
  5236. me.sendSetResponse.call (me, pdu);
  5237. } else {
  5238. me.sendGetResponse.call (me, pdu, responseVarbinds);
  5239. }
  5240. }
  5241. };
  5242. })(i);
  5243. if ( handler ) {
  5244. handler (mibRequest);
  5245. } else {
  5246. mibRequest.done ();
  5247. }
  5248. }
  5249. };
  5250. Subagent.prototype.addGetNextVarbind = function (targetVarbinds, startOid) {
  5251. var startNode;
  5252. var getNextNode;
  5253. try {
  5254. startNode = this.mib.lookup (startOid);
  5255. } catch ( error ) {
  5256. startOid = '1.3.6.1';
  5257. startNode = this.mib.lookup (startOid);
  5258. }
  5259. if ( ! startNode ) {
  5260. // Off-tree start specified
  5261. startNode = this.mib.getTreeNode (startOid);
  5262. }
  5263. getNextNode = startNode.getNextInstanceNode();
  5264. if ( ! getNextNode ) {
  5265. // End of MIB
  5266. targetVarbinds.push ({
  5267. oid: startOid,
  5268. type: ObjectType.EndOfMibView,
  5269. value: null
  5270. });
  5271. } else {
  5272. // Normal response
  5273. targetVarbinds.push ({
  5274. oid: getNextNode.oid,
  5275. type: getNextNode.valueType,
  5276. value: getNextNode.value
  5277. });
  5278. }
  5279. return getNextNode;
  5280. };
  5281. Subagent.prototype.getRequest = function (pdu) {
  5282. var requestVarbinds = [];
  5283. for ( var i = 0; i < pdu.searchRangeList.length; i++ ) {
  5284. requestVarbinds.push ({
  5285. oid: pdu.searchRangeList[i].start,
  5286. value: null,
  5287. type: null
  5288. });
  5289. }
  5290. this.request (pdu, requestVarbinds);
  5291. };
  5292. Subagent.prototype.getNextRequest = function (pdu) {
  5293. var getNextVarbinds = [];
  5294. for (var i = 0 ; i < pdu.searchRangeList.length ; i++ ) {
  5295. this.addGetNextVarbind (getNextVarbinds, pdu.searchRangeList[i].start);
  5296. }
  5297. this.request (pdu, getNextVarbinds);
  5298. };
  5299. Subagent.prototype.getBulkRequest = function (pdu) {
  5300. var getBulkVarbinds = [];
  5301. var startOid = [];
  5302. var getNextNode;
  5303. var endOfMib = false;
  5304. for (var n = 0 ; n < pdu.nonRepeaters ; n++ ) {
  5305. this.addGetNextVarbind (getBulkVarbinds, pdu.searchRangeList[n].start);
  5306. }
  5307. for (var v = pdu.nonRepeaters ; v < pdu.searchRangeList.length ; v++ ) {
  5308. startOid.push (pdu.searchRangeList[v].oid);
  5309. }
  5310. while ( getBulkVarbinds.length < pdu.maxRepetitions && ! endOfMib ) {
  5311. for (var w = pdu.nonRepeaters ; w < pdu.searchRangeList.length ; w++ ) {
  5312. if (getBulkVarbinds.length < pdu.maxRepetitions ) {
  5313. getNextNode = this.addGetNextVarbind (getBulkVarbinds, startOid[w - pdu.nonRepeaters]);
  5314. if ( getNextNode ) {
  5315. startOid[w - pdu.nonRepeaters] = getNextNode.oid;
  5316. if ( getNextNode.type == ObjectType.EndOfMibView ) {
  5317. endOfMib = true;
  5318. }
  5319. }
  5320. }
  5321. }
  5322. }
  5323. this.request (pdu, getBulkVarbinds);
  5324. };
  5325. Subagent.prototype.sendGetResponse = function (requestPdu, varbinds) {
  5326. var pdu = AgentXPdu.createFromVariables ({
  5327. pduType: AgentXPduType.Response,
  5328. sessionID: requestPdu.sessionID,
  5329. transactionID: requestPdu.transactionID,
  5330. packetID: requestPdu.packetID,
  5331. sysUpTime: 0,
  5332. error: 0,
  5333. index: 0,
  5334. varbinds: varbinds
  5335. });
  5336. this.sendPdu (pdu, null);
  5337. };
  5338. Subagent.prototype.sendSetResponse = function (setPdu) {
  5339. var responsePdu = AgentXPdu.createFromVariables ({
  5340. pduType: AgentXPduType.Response,
  5341. sessionID: setPdu.sessionID,
  5342. transactionID: setPdu.transactionID,
  5343. packetID: setPdu.packetID,
  5344. sysUpTime: 0,
  5345. error: 0,
  5346. index: 0,
  5347. });
  5348. this.sendPdu (responsePdu, null);
  5349. };
  5350. Subagent.prototype.testSet = function (setPdu) {
  5351. this.setTransactions[setPdu.transactionID] = setPdu;
  5352. this.request (setPdu, setPdu.varbinds);
  5353. };
  5354. Subagent.prototype.commitSet = function (setPdu) {
  5355. if ( this.setTransactions[setPdu.transactionID] ) {
  5356. this.request (setPdu, this.setTransactions[setPdu.transactionID].varbinds);
  5357. } else {
  5358. throw new RequestInvalidError ("Unexpected CommitSet PDU with transactionID " + setPdu.transactionID);
  5359. }
  5360. };
  5361. Subagent.prototype.undoSet = function (setPdu) {
  5362. if ( this.setTransactions[setPdu.transactionID] ) {
  5363. this.request (setPdu, this.setTransactions[setPdu.transactionID].varbinds);
  5364. } else {
  5365. throw new RequestInvalidError ("Unexpected UndoSet PDU with transactionID " + setPdu.transactionID);
  5366. }
  5367. };
  5368. Subagent.prototype.cleanupSet = function (setPdu) {
  5369. if ( this.setTransactions[setPdu.transactionID] ) {
  5370. delete this.setTransactions[setPdu.transactionID];
  5371. } else {
  5372. throw new RequestInvalidError ("Unexpected CleanupSet PDU with transactionID " + setPdu.transactionID);
  5373. }
  5374. };
  5375. Subagent.create = function (options) {
  5376. var subagent = new Subagent (options);
  5377. subagent.connectSocket ();
  5378. return subagent;
  5379. };
  5380. /*****************************************************************************
  5381. ** Exports
  5382. **/
  5383. exports.Session = Session;
  5384. exports.createSession = Session.create;
  5385. exports.createV3Session = Session.createV3;
  5386. exports.createReceiver = Receiver.create;
  5387. exports.createAgent = Agent.create;
  5388. exports.createModuleStore = ModuleStore.create;
  5389. exports.createSubagent = Subagent.create;
  5390. exports.createMib = Mib.create;
  5391. exports.isVarbindError = isVarbindError;
  5392. exports.varbindError = varbindError;
  5393. exports.Version1 = Version1;
  5394. exports.Version2c = Version2c;
  5395. exports.Version3 = Version3;
  5396. exports.Version = Version;
  5397. exports.ErrorStatus = ErrorStatus;
  5398. exports.TrapType = TrapType;
  5399. exports.ObjectType = ObjectType;
  5400. exports.PduType = PduType;
  5401. exports.AgentXPduType = AgentXPduType;
  5402. exports.MibProviderType = MibProviderType;
  5403. exports.SecurityLevel = SecurityLevel;
  5404. exports.AuthProtocols = AuthProtocols;
  5405. exports.PrivProtocols = PrivProtocols;
  5406. exports.AccessControlModelType = AccessControlModelType;
  5407. exports.AccessLevel = AccessLevel;
  5408. exports.MaxAccess = MaxAccess;
  5409. exports.RowStatus = RowStatus;
  5410. exports.ResponseInvalidCode = ResponseInvalidCode;
  5411. exports.ResponseInvalidError = ResponseInvalidError;
  5412. exports.RequestInvalidError = RequestInvalidError;
  5413. exports.RequestFailedError = RequestFailedError;
  5414. exports.RequestTimedOutError = RequestTimedOutError;
  5415. /**
  5416. ** Added for testing
  5417. **/
  5418. exports.ObjectParser = {
  5419. readInt32: readInt32,
  5420. readUint32: readUint32,
  5421. readVarbindValue: readVarbindValue
  5422. };
  5423. exports.Authentication = Authentication;
  5424. exports.Encryption = Encryption;