-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsnmp.lua
1971 lines (1825 loc) · 60.8 KB
/
snmp.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
------------------------------------------------------------------------------
--
-- snmp.lua : SNMP primitives
--
------------------------------------------------------------------------------
local snmp = require "snmp.core"
local mib = snmp.mib
-- Lua version compatibility
local unpack = unpack or table.unpack
if string.find(_VERSION, "5.1") then
module("snmp", package.seeall)
else
_ENV = setmetatable(snmp, {
__index = _G
})
end
------------------------------------------------------------------------------
-- Default Exception Handler
------------------------------------------------------------------------------
try = newtry()
------------------------------------------------------------------------------
-- MIB definitions
------------------------------------------------------------------------------
mib.NOACCESS = 0
mib.READONLY = 1
mib.READWRITE = 2
mib.WRITEONLY = 3
mib.READCREATE = 4
------------------------------------------------------------------------------
-- Init Mibs and SNMP client
------------------------------------------------------------------------------
if (LUA_SNMP_MIBS == nil or LUA_SNMP_MIBS) then
mib.init()
end
------------------------------------------------------------------------------
-- Reverse
------------------------------------------------------------------------------
function mib.renums(oid)
local t, err = mib.enums(oid)
if not t then return nil, err end
local rv = {}
for k, v in ipairs(t) do
rv[v] = k
end
return rv
end
------------------------------------------------------------------------------
-- Assemble list of net-snmp config files
------------------------------------------------------------------------------
local function configfiles()
local dirlist = {
"/etc/snmp/",
"/usr/lib/snmp/",
"/usr/share/snmp/",
os.getenv("HOME").."/.snmp/"
}
local filelist = {
"snmp.conf",
"snmp.local.conf",
-- "snmpapp.conf"
}
local t = {}
local confpath = os.getenv("SNMPCONFPATH")
if confpath then
for dir in string.gmatch(confpath, "[^:]+") do
table.insert(t, dir .. "/snmp.conf")
table.insert(t, dir .. "/snmp.local.conf")
table.insert(t, dir .. "/snmpapp.conf")
end
else
for _, dir in ipairs(dirlist) do
for _, file in ipairs(filelist) do
table.insert(t, dir .. file)
end
end
end
return t
end
------------------------------------------------------------------------------
-- Gather SNMP configuration
------------------------------------------------------------------------------
local function read_config()
local config = {}
for _, fname in ipairs(configfiles()) do
local f = io.open(fname, "r")
if f then
for line in f:lines() do
tok, val = string.gsub(line, "^%s*(#*)%s*(%w+)%s+([^%s#]*)",
function(comment1, tok, val)
if comment1 ~= "#" then
-- Uncomment to see which token read from which file.
-- print(string.format("config-read: %s = %s from %s",
-- tok, val, fname))
config[tok] = val
end
end)
end
f:close()
end
end
return config
end
config = read_config()
local tokens = {
"pathStrap",
"trapdPort"
}
------------------------------------------------------------------------------
-- A metatable for variable bindings.
------------------------------------------------------------------------------
__vbindmetatable = {
__tostring = sprint_variable,
__eq = function(vb1, vb2) return vb1.value == vb2.value end,
__le = function(vb1, vb2) return vb1.value <= vb2.value end,
__lt = function(vb1, vb2) return vb1.value < vb2.value end,
__concat = function(vb1, vb2)
local vb = {}
if vb1.oid and vb2.oid then return {vb1, vb2} end
if not vb1.oid then
for _, v in ipairs(vb1) do table.insert(vb, v) end
if vb2.oid then
table.insert(vb, vb2)
else
for _, v in ipairs(vb2) do table.insert(vb, v) end
end
else
table.insert(vb, vb1)
for _, v in ipairs(vb2) do table.insert(vb, v) end
end
return vb
end
}
------------------------------------------------------------------------------
-- Init general things and config tokens
------------------------------------------------------------------------------
assert(not init(tokens, function(token, line)
end))
------------------------------------------------------------------------------
-- Init Traps handler.
-- 1. LUASNMP_STRAPS is set: use straps
-- 2. LUASNMP_TRAPDPORT is set: use LUASNMP_TRAPDPORT
-- 3. trapdPort in snmp.conf is set: use configuration value
-- 4. Use port 6000
------------------------------------------------------------------------------
local trapdport = tonumber(os.getenv("LUASNMP_TRAPDPORT") or
config.trapdPort) or 6000
if trapdport then
inittrap(trapdport)
end
------------------------------------------------------------------------------
-- Session configuration parameters
------------------------------------------------------------------------------
SNMPv1 = 0
SNMPv2C = 1
SNMPv2c = 1
SNMPv2u = 2
SNMPv3 = 3
local NOAUTH = 1
local AUTHNOPRIV = 2
local AUTHPRIV = 3
local seclevels = {
["noAuthNoPriv"] = NOAUTH,
["authNoPriv"] = AUTHNOPRIV,
["authPriv"] = AUTHPRIV
}
local secmodels = {
["SNMPv1"] = 1,
["SNMPv2c"] = 2,
["USM"] = 3
}
------------------------------------------------------------------------------
-- SNMPv3 transform OIDs
-- Giving them here explicitly avoids the necessity to load the MIBs.
------------------------------------------------------------------------------
usmProtocol = {
NoAuth = "1.3.6.1.6.3.10.1.1.1",
HMACMD5Auth = "1.3.6.1.6.3.10.1.1.2",
HMACSHA1Auth = "1.3.6.1.6.3.10.1.1.3",
NoPriv = "1.3.6.1.6.3.10.1.2.1",
DESPriv = "1.3.6.1.6.3.10.1.2.2",
AESPriv = "1.3.6.1.6.3.10.1.2.4"
}
keyOid = {
auth = "1.3.6.1.6.3.15.1.2.2.1.6",
ownAuth = "1.3.6.1.6.3.15.1.2.2.1.7",
priv = "1.3.6.1.6.3.15.1.2.2.1.9",
ownPriv = "1.3.6.1.6.3.15.1.2.2.1.10"
}
usmOid = {
userStatus = "1.3.6.1.6.3.15.1.2.2.1.13",
userSecurityName = "1.3.6.1.6.3.15.1.2.2.1.3",
userCloneFrom = "1.3.6.1.6.3.15.1.2.2.1.4"
}
vacmOid = {
groupName = "1.3.6.1.6.3.16.1.2.1.3",
sec2GroupStorageType = "1.3.6.1.6.3.16.1.2.1.4",
sec2GroupStatus = "1.3.6.1.6.3.16.1.2.1.5",
accessContextMatch = "1.3.6.1.6.3.16.1.4.1.4",
accessReadViewName = "1.3.6.1.6.3.16.1.4.1.5",
accessWriteViewName = "1.3.6.1.6.3.16.1.4.1.6",
accessNotifyViewName = "1.3.6.1.6.3.16.1.4.1.7",
accessStorageType = "1.3.6.1.6.3.16.1.4.1.8",
accessStatus = "1.3.6.1.6.3.16.1.4.1.9",
viewTreeFamilyMask = "1.3.6.1.6.3.16.1.5.2.1.3",
viewTreeFamilyType = "1.3.6.1.6.3.16.1.5.2.1.4",
viewTreeFamilyStorageType = "1.3.6.1.6.3.16.1.5.2.1.5",
viewTreeFamilyStatus = "1.3.6.1.6.3.16.1.5.2.1.6"
}
rowStatus = {
active = 1,
notInService = 2,
notReady = 3,
createAndGo = 4,
createAndWait = 5,
destroy = 6,
}
------------------------------------------------------------------------------
-- Error Codes
------------------------------------------------------------------------------
NOERROR = 0
TOOBIG = 1
NOSUCHNAME = 2
BADVALUE = 3
READONLY = 4
GENERR = 5
NOACCESS = 6
WRONGTYPE = 7
WRONGLENGTH = 8
WRONGENCODING = 9
WRONGVALUE = 10
NOCREATION = 11
INCONSISTENTVALUE = 12
RESOURCEUNAVAILABLE = 13
COMMITFAILED = 14
UNDOFAILED = 15
AUTHORIZATIONERROR = 16
NOTWRITABLE = 17
INCONSISTENTNAME = 18
BADVERSION = 101
BADCOMMUNITY = 102
BADTIME = 103
BADRETRIES = 104
BADPEER = 105
BADPORT = 106
BADCALLBACK = 107
BADTRAP = 108
BADINFO = 109
INVINFO = 110
BADPRINTVAR = 111
BADPRINTVAL = 112
BADUSER = 113
BADSECLEVEL = 114
BADPASSPHRASE = 115
BADPRIVPASSPHRASE = 116
BADENGBOOTS = 117
BADENGTIME = 118
BADINCL = 119
BADSESSION = 120
BADTYPE = 121
BADNAME = NOSUCHNAME
BADNR = 123
BADMR = 124
INVINFOREQ = 125
BADTRAPOID = 126
TIMEOUT = 190
INTERR = 191
BADARG = 192
BADOID = 193
BADENGPROBE = 194
BADSECMODEL = 195
BADSECNAME = 196
BADGROUPNAME = 197
------------------------------------------------------------------------------
-- Error Messages
------------------------------------------------------------------------------
errtb={}
errtb[0] = "snmp: no error"
errtb[1] = "snmp: too big"
errtb[2] = "snmp: no such name"
errtb[3] = "snmp: bad value"
errtb[4] = "snmp: read only"
errtb[5] = "snmp: generic error"
errtb[6] = "snmp: no access"
errtb[7] = "snmp: wrong type"
errtb[8] = "snmp: wrong length"
errtb[9] = "snmp: wrong encoding"
errtb[10] = "snmp: wrong value"
errtb[11] = "snmp: no creation"
errtb[12] = "snmp: inconsistent value"
errtb[13] = "snmp: resource unavailable"
errtb[14] = "snmp: commit failed"
errtb[15] = "snmp: undo failed"
errtb[16] = "snmp: authorization error"
errtb[17] = "snmp: not writable"
errtb[18] = "snmp: inconsistent name"
local cnf_err = "snmp: invalid session configuration "
errtb[101] = cnf_err.."(version)"
errtb[102] = cnf_err.."(community)"
errtb[103] = cnf_err.."(timeout)"
errtb[104] = cnf_err.."(retries)"
errtb[105] = cnf_err.."(peer address)"
errtb[106] = cnf_err.."(port)"
errtb[107] = cnf_err.."(callback)"
errtb[108] = cnf_err.."(trap)"
errtb[109] = cnf_err.."(inform)"
local opt_err = "snmp: invalid configuration for SNMPv1 session "
errtb[110] = opt_err.."(inform)"
errtb[111] = cnf_err.."(sprintvar)"
errtb[112] = cnf_err.."(sprintval)"
errtb[113] = cnf_err.."(user)"
errtb[114] = cnf_err.."(securityLevel)"
errtb[115] = cnf_err.."(authPassphrase, password)"
errtb[116] = cnf_err.."(privPassphrase, password)"
errtb[117] = cnf_err.."(engineBoots)"
errtb[118] = cnf_err.."(engineTime)"
errtb[119] = opt_err.."(includeroot)"
errtb[120] = "snmp: invalid session"
errtb[121] = "snmp: invalid variable type"
errtb[122] = "snmp: invalid variable name"
errtb[123] = "snmp: invalid argument (non-repeaters)"
errtb[124] = "snmp: invalid argument (max-repetitions)"
errtb[125] = "snmp: invalid operation for SNMPv1 session (inform)"
errtb[126] = "snmp: invalid argument (trap OID)"
errtb[190] = "snmp: no response (timeout)"
errtb[191] = "snmp: internal failure"
errtb[192] = "snmp: bad argument"
errtb[193] = "snmp: oid not increasing"
errtb[194] = "snmp: engineID probe failed"
errtb[195] = "snmp: bad security model"
errtb[196] = "snmp: bad security name"
errtb[197] = "snmp: bad group name"
------------------------------------------------------------------------------
-- Returns nil + error message in case of errors.
-- @param errnum number - Error number.
-- @param message string - function's message to append.
-- @return nil, "errormsg (MESSAGE)"
------------------------------------------------------------------------------
local function FAIL(err, message)
local rmsg
if type(err) == "number" then
rmsg = errtb[err]
elseif type(err) == "string" then
rmsg = err
end
if message then
rmsg = rmsg .. " (" .. message ..")"
end
return nil, rmsg
end
------------------------------------------------------------------------------
-- Request Types
------------------------------------------------------------------------------
GET_REQ = 1
GETNEXT_REQ = 2
SET_REQ = 3
BULK_REQ = 5
INFO_REQ = 6
------------------------------------------------------------------------------
-- Mib type codes
------------------------------------------------------------------------------
NOSUCHOBJECT = 128
NOSUCHINSTANCE = 129
ENDOFMIBVIEW = 130
TYPE_OTHER = 0
TYPE_OBJID = 1
TYPE_OCTETSTR = 2
TYPE_INTEGER = 3
TYPE_NETADDR = 4
TYPE_IPADDR = 5
TYPE_COUNTER = 6
TYPE_GAUGE = 7
TYPE_TIMETICKS = 8
TYPE_OPAQUE = 9
TYPE_NULL = 10
TYPE_COUNTER64 = 11
TYPE_BITSTRING = 12
TYPE_NSAPADDRESS = 13
TYPE_UINTEGER = 14
TYPE_UNSIGNED32 = 15
TYPE_INTEGER32 = 16
TYPE_SIMPLE_LAST = 16
TYPE_TRAPTYPE = 20
TYPE_NOTIFTYPE = 21
TYPE_OBJGROUP = 22
TYPE_NOTIFGROUP = 23
TYPE_MODID = 24
TYPE_AGENTCAP = 25
TYPE_MODCOMP = 26
TYPE_FLOAT = 120
TPYE_DOUBLE = 121
TYPE_INTEGER64 = 122
TYPE_UNSIGNED64 = 123
------------------------------------------------------------------------------
-- Mib type names
------------------------------------------------------------------------------
typetb = {
"OBJECT IDENTIFIER",
"OCTET STRING",
"INTEGER",
"NetworkAddress",
"IpAddress",
"Counter",
"Gauge32",
"TimeTicks",
"Opaque",
"NULL",
"Counter64",
"BIT STRING",
"NsapAddress",
"UInteger",
"UInteger32",
"Integer32",
"",
"",
"",
"TRAP-TYPE",
"NOTIFICATION-TYPE",
"OBJECT-GROUP",
"NOTIFICATION-GROUP",
"MODULE-IDENTITY",
"AGENT-CAPABILITIES",
"MODULE-COMPLIANCE"
}
typetb[0] = "OTHER"
typetb[120] = "Opaque: Float"
typetb[121] = "Opaque: Double"
typetb[122] = "Opaque: Integer64"
typetb[123] = "Opaque: Unsigned64"
typetb[128] = "NO SUCH OBJECT"
typetb[129] = "NO SUCH INSTANCE"
typetb[130] = "END OF MIB VIEW"
------------------------------------------------------------------------------
--
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Return comprimated varlist result.
-- @param vl table - Varlist.
-- @param err string - error or nil.
-- @param errindex number - index of failure varbind in varlist.
-- @return varlist or nil + errormessage on failure.
------------------------------------------------------------------------------
local function retvarlist(vl, err, errindex)
if err then
if errindex then
return FAIL(err, "in index " .. tostring(errindex))
else
return FAIL(err)
end
else
return vl
end
end
------------------------------------------------------------------------------
-- Print an object value
-- @param vb Variable binding or value.
-- @return formatted string for printing.
------------------------------------------------------------------------------
function sprintval2(vb)
if type(vb) ~= "table" then
if vb then
return tostring(vb)
else
return "<NULL>"
end
end
local value = vb.value
if not value then
return "<NULL>"
end
local type = vb.type
if type == TYPE_TIMETICKS then
local days,hours,minutes,seconds,deci,ticks
if (value.days) then days = value.days else days = 0 end
if (value.hours) then hours = value.hours else hours = 0 end
if (value.minutes) then minutes = value.minutes else minutes = 0 end
if (value.seconds) then seconds = value.seconds else seconds = 0 end
if (value.deciseconds) then deci= value.deciseconds else deci= 0 end
if (value.ticks) then ticks= value.ticks else ticks= 0 end
return string.format("%dd %d:%d:%d.%d (%d)",days,hours,minutes,seconds,deci,ticks)
elseif (type == TYPE_INTEGER) or (type == TYPE_UINTEGER) then
local enums = mib.enums(vb.oid)
if enums and enums[value] then
return enums[value].."("..value..")"
end
elseif (type == TYPE_OBJID) then
local name = mib.name(value)
if name ~= value then
return name.." ("..value..")"
else
return value
end
end
return tostring(value)
end
------------------------------------------------------------------------------
-- Print an object variable.
-- @param vb table - Variable binding.
-- @return Formatted string for printing.
------------------------------------------------------------------------------
function sprintvar2(vb)
if type(vb) ~= "table" then
return "<Invalid varbind>"
end
local name = mib.name(vb.oid) ---> aceitar ja' receber nome pronto?
if not name then
name = ""
end
return string.format("%s (%s) = %s",name,sprint_type(vb.type),sprintval2(vb))
end
------------------------------------------------------------------------------
-- Print an object type.
-- @param t Variable binding or type code.
-- @return Formatted string for printing.
------------------------------------------------------------------------------
function sprint_type(t)
local tCode
if type(t) == "table" then
tCode = tonumber(t.type or mib.type(t.oid))
elseif type(t) == "number" then
tCode = tonumber(t)
elseif type(t) == "string" then
tCode = mib.type(t)
end
if tCode and typetb[tCode] then
return typetb[tCode]
else
return "<Invalid type>"
end
end
-- For convenience.
mib.typename = sprint_type
------------------------------------------------------------------------------
-- Print an error.
-- @param err Error code.
-- @return Formatted string for printing.
------------------------------------------------------------------------------
function sprint_error(err)
local str = errtb[err]
if str then
return str
else
return "UNKNOWN ERROR"
end
end
------------------------------------------------------------------------------
-- Check an OID.
-- Does not check whether OID is in the tree.
-- @param oid string - OID string representation.
-- @return OID string, if o.k. Nil otherwise.
------------------------------------------------------------------------------
local function isoid(oid)
if type(oid) ~= "string" then return FAIL(BADARG) end
if string.find(string.gsub(oid,"%.%d%d*",""),"^%d%d*$") then
return oid
else
return FAIL("snmp: not an OID")
end
end
------------------------------------------------------------------------------
-- Eval length of an OID.
-- Does not check whether OID is in the tree.
-- @param oid string - OID string representation.
-- @return OID string, if o.k. Nil otherwise.
------------------------------------------------------------------------------
local function oidlen(oid)
local oid, err = isoid(oid)
if not oid then return FAIL("snmp: not an OID") end
local n = 0
string.gsub(oid, "%.", function(v)
n = n + 1
end)
return n + 1
end
------------------------------------------------------------------------------
-- Eval a base OID of certain length.
-- Does not check whether OID is in the tree.
-- @param oid string - OID string representation.
-- @param len number - Length of base OID.
-- @return Base OID string, if o.k. nil otherwise.
------------------------------------------------------------------------------
local function oidbase(oid, len)
local err
local len = len or oidlen(oid)
oid, err = isoid(oid)
if not oid then return nil, err end
local rv = ""
for d, p in string.gmatch(oid,"(%d+)(%.*)") do
rv = rv .. d
len = len - 1
if len == 0 then
return rv
else
rv = rv .. (p or "")
end
end
print("###", oid, rv)
return rv
end
------------------------------------------------------------------------------
-- Translate an OID into a table.
-- Does not check whether OID is in the tree.
-- @param oid string - OID string representation or name.
-- @return Table presentation of an OID: {1,2,17,2,3}.
------------------------------------------------------------------------------
local function oidtotable(oid)
local err
oid, err = isoid(oid)
if not oid then return nil, err end
local t = {}
string.gsub(oid, "(%d+)%.*", function(d) table.insert(t, tonumber(d)) end)
return t, #t
end
------------------------------------------------------------------------------
-- Compare two OIDs.
-- Does not check whether OID is in the tree.
-- @param oid1 string - OID string 1 or name 1.
-- @param oid2 string - OID string 2 or name 2.
-- @return 1 if oid1 > oid2, 0 if oid1 == oid2, -1 if oid1 < oid2.
------------------------------------------------------------------------------
local function oidcompare(oid1, oid2)
if not isoid(oid1) then return FAIL(BADARG, "oid1") end
if not isoid(oid2) then return FAIL(BADARG, "oid2") end
local t1,n1 = oidtotable(oid1)
local t2,n2 = oidtotable(oid2)
local n = n1
if n2 < n1 then
n = n2
end
for i = 1,n do
if t1[i] > t2[i] then
return 1
elseif t1[i] < t2[i] then
return -1
end
end
if n1 < n2 then return -1 end
if n2 < n1 then return 1 end
return 0
end
------------------------------------------------------------------------------
-- Returns the index of a varbind based on a superordinated OID.
-- @param vb table - Variable name (text or OID).
-- @param tname string - Super-ordinated OID
-- @return Index as string.
------------------------------------------------------------------------------
local function oidindex(oid, base)
if not isoid(oid) then return FAIL(BADARG, "oid") end
if not isoid(base) then return FAIL(BADARG, "base") end
local s, n = string.gsub(oid, "^"..base.."%.(.+)","%1")
if n > 0 then return s else return "" end
end
------------------------------------------------------------------------------
-- Load a MIB file.
-- Search in all directories given by MIBDIRS.
-- @param fname string File name.
------------------------------------------------------------------------------
local function load(fname)
if string.sub(fname, 1, 1) == "/" then
local tree, err = mib._load(fname)
if tree then return tree end
else
local configdirs = string.gsub(config.mibdirs or "", "(%+*)(.+)", "%2")
local mibdirs = ".:" .. (os.getenv("LUASNMP_MIBDIRS") or os.getenv("MIBDIRS") or configdirs)
for dir in string.gmatch(mibdirs, "[^:;]+") do
for _,ext in ipairs{".txt","",".mib"} do
local fn = dir.."/"..fname..ext
local f = io.open(fn,"r")
if f then
f:close()
local tree, err = mib._load(fn)
if tree then return tree end
end
end
end
end
return nil, "mib: cannot add mib"
end
mib.isoid = isoid
mib.oidlen = oidlen
mib.oidbase = oidbase
mib.oidtotable = oidtotable
mib.oidcompare = oidcompare
mib.oidindex = oidindex
mib.load = load
-- Some other names for sprints.
sprintval = sprint_value
sprinttype = sprint_type
sprintvar = sprint_variable
sprinterr = sprint_error
---------------------------------------------------------------------------
-- Walk the MIB tree
-- @param sess table - Session.
-- @param var table or string - Root object.
-- @return Varbind list with values.
---------------------------------------------------------------------------
function walk(sess, var)
local oid
local running = true
local t = {}
local root, vb, err
-- if not sess then return nil, errtb[BADSESSION] end
if not sess then return FAIL(BADSESSION) end
local var = var or "mib-2"
if type(var) == "table" then
oid = mib.oid(var.oid)
elseif type(var) == "string" then
oid = mib.oid(var)
else
return FAIL(BADARG, "var")
end
if not oid then return nil, errtb[BADOID] end
root = {oid = oid}
if sess.includeroot then
vb, err = sess:get(root)
if err then return nil, err end
table.insert(t,vb)
end
local rootlen = oidlen(root.oid)
local vb = root
local rootoid = root.oid
local last = rootoid
while running do
vb, err = sess:getnext(vb)
if not vb then return nil, err end
if err then
if err == NOSUCHNAME or string.find(err, "no such name") then
running = false
return t, nil
else
return t, err
end
end
local oid = vb.oid
if oidlen(oid) < rootlen or
vb.type == ENDOFMIBVIEW or
not string.find(oid, rootoid) then
running = false
else
if oidcompare(last, oid) >= 0 then
return nil, errtb[BADOID]
end
last = oid
table.insert(t, vb)
end
end
if not err and #t == 0 then
vb, err = sess:get(root)
if err then return t, err end
table.insert(t, vb)
end
return t
end
---------------------------------------------------------------------------
-- Retrieve sorted list of keys of a table
---------------------------------------------------------------------------
function getkeys(t)
local rv = {}
for k,v in pairs(t) do
table.insert(rv, k)
end
table.sort(rv)
return rv
end
---------------------------------------------------------------------------
-- Sorted iteration over a list of keys in table.
---------------------------------------------------------------------------
assert(not _G.spairs, "Symbol 'spairs' already defined")
function _G.spairs(t)
local keys = getkeys(t)
local i = 0
table.sort(keys)
return function()
i = i + 1
return keys[i], t[keys[i]]
end
end
---------------------------------------------------------------------------
-- Convert formatted time value to varbind.
-- @param s string - Formatted string.
-- @return Varbind.
---------------------------------------------------------------------------
function uptimeS2V(s)
local ticks = nil
if type(s) ~= "string" then return FAIL(BADARG) end
string.gsub(s, "(%d+):(%d+):(%d+):(%d+)%.(%d+)$",
function(d, h, m, s, ds)
ticks = {
days = tonumber(d) or 0,
hours = tonumber(h) or 0,
minutes = tonumber(m) or 0,
seconds = tonumber(s) or 0,
deciseconds = tonumber(ds) or 0
}
ticks.ticks = ticks.deciseconds +
ticks.seconds * 100 +
ticks.minutes * 60 * 100 +
ticks.hours * 60 * 60 * 100 +
ticks.days * 24 * 60 * 60 * 100
end)
return ticks
end
---------------------------------------------------------------------------
-- Convert uptime varbind to string.
-- @param vb table - Varbinding containing sysUpTime.
-- @return Formatted string.
---------------------------------------------------------------------------
function uptimeV2S(vb)
if type(vb) ~= "table" then return FAIL(BADARG) end
return string.format("%d:%d:%d:%d.%d",
vb.days, vb.hours, vb.minutes,
vb.seconds, vb.deciseconds)
end
---------------------------------------------------------------------------
-- A generic trap handler.
-- Only activated if a user supplied trap callback function has
-- been provided. It also calls the user callback function.
-- NOTE: The scanner of the trap message requires the following log formats
-- settings in snmptrapfmt.conf to work properly:
-- SUBST=\#\ \
-- NODEFMT=ip
-- VARFMT="#[%s] %n (%t) : %v"
-- LOGFMT="$x#$A#$e#$G#$S#$T$*"
-- @param session table - Session that captures the trap.
-- @param msg string - Message from snmptrapd.
-- See snmptrapd.conf manual page for content.
-- @return none.
---------------------------------------------------------------------------
function __trap(session, msg)
local host, src, vbs, sip, dip, sport, dport, uptimeName, uptimeVal, vbs, ip, port
-- debugging: uncomment if desired
--print(string.format(" session.name=%s", session.name))
--print(string.format(" generic_trap(): msg = %q", msg))
--print(string.format(" netsnmp version: %s", snmp.getversion()))
--print(string.format(" snmp._SYSTEM: %s", snmp._SYSTEM))
-- The message may ne different for Cygwin and Linux.
-- We keep the differentiation even if not really required.
if snmp._SYSTEM == "Cygwin" and snmp.getversion() > "5.3" then
string.gsub(msg,
"^%s*([%w%.]+)%s+(%w+):%s*%[[%d%.]+%]%-%>%[([%d%.]+)%]:(%d+)%s+([^%s]+)%s+([^%s]+)%s+(.*)",
function(...)
host, proto, ip, port, uptimeName, uptimeVal, vbs = select(1, ...)
end)
-- debugging:
-- print(string.format(" host=%q, proto=%q, ip=%q, port=%q, uptimeName=%q, uptimeVal=%q, vbs=%q",
-- host, proto, ip, port, uptimeName, uptimeVal, vbs))
elseif snmp.getversion() > "5.5" then
string.gsub(msg,
-- Example msg:
-- " localhost UDP: [127.0.0.1]->[127.0.0.1]:-6577 \
-- iso.3.6.1.2.1.1.3.0 0:2:11:01.53 iso.3.6.1.6.3.1.1.4.1.0 ccitt.0 iso.3.6.1.2.1.1.5.0 \"hello\""
"^%s*([%w%.]+)%s+(%w+):%s*%[([%d%.]+)%]:([%d]+)%-%>%[([%d%.]+)%]:([%-%d]+)%s+([^%s]+)%s+([^%s]+)%s+(.*)",
function(...)
host, proto, sip, sport, dip, dport, uptimeName, uptimeVal, vbs = select(1, ...)
ip = sip
port = sport
-- debugging:
-- print("dissected msg:", host, proto, sip, sport, dip, dport, uptimeName, uptimeVal, vbs)
end)
-- debugging: uncomment if desired
-- print(string.format(" host=%q, proto=%q, ip=%q, port=%q, uptimeName=%q, uptimeVal=%q, vbs=%q",
-- host, proto, ip, port, uptimeName, uptimeVal, vbs))
else
string.gsub(msg, "([%w%.]+)%s+([%d%.]+)%s+([^%s]+)%s+([^%s]+)%s+(.*)",
function(...)
local arg = {select(1, ...)}
host = arg[1]
src = arg[2]
uptimeName = arg[3]
uptimeVal = uptimeS2V(arg[4])
vbs = arg[5]
end)
end
if dip == session.peer_ip or true then
-- Convert variable bindings
local vlist
if string.find(snmp.getversion(), "5.4") then
vlist = {{oid = uptimeName, type = mib.type("sysUpTime"), value = uptimeVal}}
elseif string.find(snmp.getversion(), "5.3") then
-- Note: we don't get a reasonable type value for sysUpTimeInstance in net-snmp 5.3
vlist = {{oid=uptimeName, type=mib.type("sysUpTime"), value = uptimeVal}}
else
vlist = {{oid=uptimeName, type=mib.type(uptimeName), value = uptimeVal}}
end
string.gsub(vbs, "([^%s]+)%s+([^%s]+)%s*",
function(name, val)
local oid = name
local typ = mib.type(name)
local value = mib.oid(val) or uptimeS2V(val) or val
table.insert(vlist, {oid=oid, type=typ, value=value})
end)
-- debugging:
-- table.foreach(vlist, function(k,v) table.foreach(v, print) end)
session.usertrap(vlist, ip, port, host, session)
end
end
---------------------------------------------------------------------------
-- Create a new variable binding.
-- @param name string - Name or OID of variable.
-- @param value any - Value of variable.
-- @param type number (opt) - Type of the object.
-- @return Variable binding with metamethods set.
---------------------------------------------------------------------------
function newvar(name, value, typ, session)
local oid = mib.oid(name) or name
local vb = {oid = oid, type = typ or mib.type(oid), value = value}
if session then vb[".session"] = session end
setmetatable(vb, __vbindmetatable)
return vb
end
---------------------------------------------------------------------------
-- Print a hexstring (key) in the form 0x1234etc.
-- @param key string - Hexstring (may contain embedded zeros).
-- @param len number - Length of the (sub)string to evaluate.
-- @return String containing a readable presentation of the hexstring.
---------------------------------------------------------------------------
function sprintkeyx(key, len)
local s = "0x"
local slen = string.len(key)
local len = len or slen
if len > slen then len = slen end
for i = 1, len do
s = s..string.format("%02X", string.byte(key, i))
end
return s
end
---------------------------------------------------------------------------
-- Print a hexstring (key) in the OID form 1.2.3.4.
-- @param key string - Hexstring (may contain embedded zeros).
-- @param len number - Length of the (sub)string to evaluate.
-- @return String containing an OID presentation of the input string.
---------------------------------------------------------------------------
function sprintkeyd(key, len)
local s = ""
local slen = string.len(key)
local len = len or slen
if len > slen then len = slen end
for i = 1, len do
s = s..string.format("%d", string.byte(key,i))